Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Let webhook owners edit a webhook's task in place (#2212)

Joshua Franced9599386bf31
diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.ts
index d4bfe9a1b..4d24e836e 100644
--- a/src/api/agent-api-catalog.ts
+++ b/src/api/agent-api-catalog.ts
@@ -551,7 +551,7 @@ const FAMILIES: AgentApiFamily[] = [
match: (m, p) =>
(p === "/v1/webhooks" && (m === "POST" || m === "GET")) ||
(m === "GET" && /^\/v1\/webhooks\/[^/]+\/events$/.test(p)) ||
- (m === "POST" && /^\/v1\/webhooks\/[^/]+\/(disable|enable)$/.test(p)),
+ (m === "POST" && /^\/v1\/webhooks\/[^/]+\/(disable|enable|update)$/.test(p)),
when: () => false,
routes: [
{
@@ -562,6 +562,11 @@ const FAMILIES: AgentApiFamily[] = [
{ method: "GET", path: "/v1/webhooks", summary: "list your webhooks" },
{ method: "GET", path: "/v1/webhooks/:id/events", summary: "recent webhook payloads and sessions" },
{ method: "POST", path: "/v1/webhooks/:id/disable", summary: "disable a webhook" },
+ {
+ method: "POST",
+ path: "/v1/webhooks/:id/update",
+ summary: "update a webhook task in place (URL and secret unchanged)",
+ },
{ method: "POST", path: "/v1/webhooks/:id/enable", summary: "re-enable a webhook" },
],
},
diff --git a/src/api/app-messaging.ts b/src/api/app-messaging.ts
index aa1d4c86c..60aa7ef11 100644
--- a/src/api/app-messaging.ts
+++ b/src/api/app-messaging.ts
@@ -82,6 +82,7 @@ export function createMessagingMethods(
| "listWebhooks"
| "listWebhookEvents"
| "setWebhookEnabled"
+ | "updateWebhook"
| "setWebhookRecipientConsent"
| "pendingDeliveries"
| "enqueueDelivery"
@@ -328,6 +329,9 @@ export function createMessagingMethods(
setWebhookEnabled(id, enabled) {
return deps.webhooks.setEnabled(id, enabled);
},
+ updateWebhook(id, patch) {
+ return deps.webhooks.update(id, patch);
+ },
setWebhookRecipientConsent(id, recipientConsent) {
return deps.webhooks.setRecipientConsent(id, recipientConsent);
},
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index bff15b8d0..7da2db8fe 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -459,6 +459,7 @@ export interface App {
listWebhookEvents(id: string, viewer: string): Promise<Array<WebhookEvent & { sessionId?: string }>>;
listWebhooks(): Promise<Webhook[]>;
setWebhookEnabled(id: string, enabled: boolean): Promise<void>;
+ updateWebhook(id: string, patch: { action: string }): Promise<Webhook | null>;
setWebhookRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
pendingDeliveries(type: string, claimMs?: number): Promise<Delivery[]>;
enqueueDelivery(input: {
diff --git a/src/api/control-service.ts b/src/api/control-service.ts
index 28a36a4a7..28fdcfce6 100644
--- a/src/api/control-service.ts
+++ b/src/api/control-service.ts
@@ -170,6 +170,11 @@ export interface ControlService {
id: string,
claims: CapabilityClaims,
): Promise<ControlOk<Record<never, never>> | ControlErr<"not_found" | "forbidden">>;
+ updateWebhook(
+ id: string,
+ patch: { action: string },
+ claims: CapabilityClaims,
+ ): Promise<ControlOk<{ webhook: Webhook }> | ControlErr<"not_found" | "forbidden" | "bad_request">>;
readSoul(claims: CapabilityClaims): { effectiveSoul: string; soul: string | null; soulVersion: number };
writeSoul(
content: string,
@@ -197,6 +202,21 @@ export async function canAdministerCron(
return app.managesScope(actorId, cron.ownerScopeId);
}
+export async function editWebhookTask(
+ app: App,
+ id: string,
+ action: string,
+ principalId: string,
+): Promise<ControlOk<{ webhook: Webhook }> | ControlErr<"not_found" | "forbidden" | "bad_request">> {
+ if (!action.trim()) return { ok: false, code: "bad_request", message: "task cannot be empty" };
+ const webhook = await app.getWebhook(id);
+ if (!webhook) return { ok: false, code: "not_found", message: `no webhook ${id}` };
+ if (!(await canAdministerWebhook(app, webhook, principalId)))
+ return { ok: false, code: "forbidden", message: "not your webhook" };
+ const updated = await app.updateWebhook(id, { action });
+ return updated ? { ok: true, webhook: updated } : { ok: false, code: "not_found", message: `no webhook ${id}` };
+}
+
export async function canAdministerWebhook(
app: Pick<App, "membershipControlsScope" | "managesScope" | "samePerson">,
webhook: Pick<Webhook, "ownerScopeId" | "owner">,
@@ -888,6 +908,12 @@ export function createControlService(app: App, scheduler?: Scheduler, admin?: Ad
return { ok: true };
},
+ async updateWebhook(id, patch, capability) {
+ if (capability.triggered || !livePersonCapability(capability))
+ return { ok: false, code: "forbidden", message: "editing a webhook requires a live turn started by its owner" };
+ return editWebhookTask(app, id, patch.action, capability.actorId);
+ },
+
readSoul(capability) {
const { effectiveSoul, soul, soulVersion } = app.getSoul(capability.scopeId);
return { effectiveSoul, soul, soulVersion };
diff --git a/src/api/routes/webhooks.ts b/src/api/routes/webhooks.ts
index bfc20beb3..0bc95eb53 100644
--- a/src/api/routes/webhooks.ts
+++ b/src/api/routes/webhooks.ts
@@ -2,7 +2,7 @@ import type { Webhook } from "../../types.ts";
import { WEBHOOK_SCHEMES } from "../../webhooks/verifiers.ts";
import type { CreateWebhookInput } from "../../webhooks/webhook-store.ts";
import { errMessage } from "../../util/errors.ts";
-import { canAdministerWebhook } from "../control-service.ts";
+import { canAdministerWebhook, editWebhookTask } from "../control-service.ts";
import { PayloadTooLargeError, readRawBody, sendJson } from "../http.ts";
import { isObj } from "./shared.ts";
import type { ApiCtx, BaseCtx, Route } from "./route.ts";
@@ -81,6 +81,7 @@ async function incomingWebhook(ctx: BaseCtx): Promise<void> {
const WEBHOOK_ERROR_STATUS: Record<string, number> = {
bad_request: 400,
forbidden: 403,
+ not_found: 404,
unknown_destination: 400,
webhook_create_failed: 400,
};
@@ -172,6 +173,18 @@ async function setWebhookEnabled(ctx: ApiCtx, enabled: boolean): Promise<void> {
return sendJson(res, 200, { ok: true });
}
+async function updateWebhook(ctx: ApiCtx): Promise<void> {
+ const { res, app, deps, params, capability, actor, url, body } = ctx;
+ const action = isObj(body) && typeof body.action === "string" ? body.action : "";
+ const principalId = actor?.p ?? url.searchParams.get("principalId");
+ if (!capability && !principalId) return sendJson(res, 404, { error: "not_found" });
+ const r = capability
+ ? await deps.control.updateWebhook(params.id!, { action }, capability)
+ : await editWebhookTask(app, params.id!, action, principalId!);
+ if (!r.ok) return sendJson(res, WEBHOOK_ERROR_STATUS[r.code] ?? 400, { error: r.code, message: r.message });
+ return sendJson(res, 200, { webhook: redactWebhook(r.webhook), url: inboundUrl(deps.publicUrl, r.webhook.id) });
+}
+
const disableWebhook = (ctx: ApiCtx): Promise<void> => setWebhookEnabled(ctx, false);
const enableWebhook = (ctx: ApiCtx): Promise<void> => setWebhookEnabled(ctx, true);
@@ -183,6 +196,7 @@ export const webhookRoutes: ReadonlyArray<Route<ApiCtx>> = [
{ method: "POST", path: "/v1/webhooks", auth: "either", handle: createWebhook },
{ method: "GET", path: "/v1/webhooks", auth: "either", handle: listWebhooks },
{ method: "GET", path: "/v1/webhooks/:id/events", auth: "either", handle: listWebhookEvents },
+ { method: "POST", path: "/v1/webhooks/:id/update", auth: "either", handle: updateWebhook },
{ method: "POST", path: "/v1/webhooks/:id/disable", auth: "either", handle: disableWebhook },
{ method: "POST", path: "/v1/webhooks/:id/enable", auth: "either", handle: enableWebhook },
];
diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.ts
index e89ced18b..85105476f 100644
--- a/src/api/user-scoped-routes.ts
+++ b/src/api/user-scoped-routes.ts
@@ -106,6 +106,7 @@ const USER_SCOPED: Rule[] = [
pat("POST", "/v1/connectors/token", { in: "body", name: "principalId" }),
pat("POST", "/v1/connectors/oauth/revoke", { in: "body", name: "principalId" }),
pat("POST", "/v1/webhooks/:id/disable", { in: "query", name: "principalId" }),
+ pat("POST", "/v1/webhooks/:id/update", { in: "query", name: "principalId" }),
pat("POST", "/v1/deployments/:id/display-name"),
pat("POST", "/v1/deployments/:id/name"),
pat("POST", "/v1/deployments/:id/archive"),
diff --git a/src/harness/agent-tools.ts b/src/harness/agent-tools.ts
index d5c3a9ca8..c951738e8 100644
--- a/src/harness/agent-tools.ts
+++ b/src/harness/agent-tools.ts
@@ -2782,14 +2782,21 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
"relay BOTH to the user verbatim — the `url` is already the full public inbound URL (hand it over as-is) " +
"and the `secret` — so they can point GitHub/Stripe/etc. at it. Until they do, it never fires.\n" +
"action=list pages through your webhooks (secrets elided, task text flattened and capped at 2000 chars, " +
- "25 per page — a footer line names the offset for the next page when there's more); action=disable pauses one by id.",
+ "25 per page — a footer line names the offset for the next page when there's more); action=update replaces one's task in place " +
+ "(same URL and secret, used from the next event; live owner turns only); action=disable pauses one by id.",
parameters: Type.Object({
- action: Type.Union([Type.Literal("create"), Type.Literal("list"), Type.Literal("disable")], {
- description: "create an inbound webhook, list yours, or disable one by id.",
- }),
- id: Type.Optional(Type.String({ description: "disable only: the webhook id." })),
+ action: Type.Union(
+ [Type.Literal("create"), Type.Literal("list"), Type.Literal("update"), Type.Literal("disable")],
+ {
+ description:
+ "create an inbound webhook, list yours, update one's task in place by id (URL and secret unchanged), or disable one by id.",
+ },
+ ),
+ id: Type.Optional(Type.String({ description: "update and disable: the webhook id." })),
task: Type.Optional(
- Type.String({ description: "create only: what to do on each event (the payload is appended automatically)." }),
+ Type.String({
+ description: "create and update: what to do on each event (the payload is appended automatically).",
+ }),
),
verification: Type.Optional(
Type.Object(
@@ -2894,6 +2901,26 @@ export function createAgentTools(ref: ToolContextRef, opts?: AgentToolsOptions):
return recordResult(callId, { tool: "webhook", error: r.code }, text(`[error] ${r.message}`), true);
return recordResult(callId, { tool: "webhook", id, enabled: false }, text(`Disabled webhook ${id}.`));
}
+ case "update": {
+ const id = typeof params.id === "string" && params.id ? params.id : null;
+ const task = typeof params.task === "string" ? params.task : "";
+ if (!id)
+ return recordResult(
+ callId,
+ { tool: "webhook", error: "id required" },
+ text("[error] webhook update requires `id` and the new `task`."),
+ true,
+ );
+ const r = await tc.webhookUpdate(id, task);
+ if (isUnavailable(r)) return unavailable(callId, "webhook");
+ if (!r.ok)
+ return recordResult(callId, { tool: "webhook", error: r.code }, text(`[error] ${r.message}`), true);
+ return recordResult(
+ callId,
+ { tool: "webhook", id, updated: true },
+ text(`Updated webhook ${id}. The next delivery uses the new task; URL and secret are unchanged.`),
+ );
+ }
}
},
});
diff --git a/src/tools/primitives.ts b/src/tools/primitives.ts
index 3c57aab6b..11e282585 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -318,6 +318,12 @@ export interface ToolContext extends SurfaceToolDeps {
webhookDisable(
id: string,
): Promise<ControlOk<Record<never, never>> | ControlErr<"not_found" | "forbidden"> | ControlUnavailable>;
+ webhookUpdate(
+ id: string,
+ action: string,
+ ): Promise<
+ ControlOk<{ webhook: Webhook }> | ControlErr<"not_found" | "forbidden" | "bad_request"> | ControlUnavailable
+ >;
soulRead(): { effectiveSoul: string; soul: string | null; soulVersion: number } | ControlUnavailable;
soulWrite(
content: string,
@@ -1405,6 +1411,11 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
(c, cl) => c.disableWebhook(id, cl),
(r) => r.ok,
),
+ webhookUpdate: (id, action) =>
+ controlOp(
+ (c, cl) => c.updateWebhook(id, { action }, cl),
+ (r) => r.ok,
+ ),
soulRead() {
if (!deps.control || !deps.controlClaims) return CONTROL_UNAVAILABLE;
return deps.control.readSoul(deps.controlClaims);
diff --git a/src/webhooks/webhook-store.ts b/src/webhooks/webhook-store.ts
index d5ab0338f..af1376fca 100644
--- a/src/webhooks/webhook-store.ts
+++ b/src/webhooks/webhook-store.ts
@@ -35,6 +35,7 @@ export interface WebhookStore {
get(id: string): Promise<Webhook | null>;
list(): Promise<Webhook[]>;
setEnabled(id: string, enabled: boolean): Promise<void>;
+ update(id: string, patch: { action: string }): Promise<Webhook | null>;
setRecipientConsent(id: string, recipientConsent: RecipientConsent): Promise<void>;
recordFire(id: string, info: { at: number; deliveryId?: string; error?: string }): Promise<void>;
}
@@ -102,6 +103,9 @@ export function createWebhookStore(
setEnabled(id, enabled) {
return setTriggerEnabled(backing, id, enabled);
},
+ update(id, patch) {
+ return backing.merge(id, { action: patch.action });
+ },
setRecipientConsent(id, recipientConsent) {
return setTriggerRecipientConsent(backing, id, recipientConsent);
},
diff --git a/test/agent-tools.test.ts b/test/agent-tools.test.ts
index c0d145460..975ee7f09 100644
--- a/test/agent-tools.test.ts
+++ b/test/agent-tools.test.ts
@@ -280,6 +280,9 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["execute
},
];
},
+ async webhookUpdate() {
+ return { ok: false as const, code: "not_found" as const, message: "x" };
+ },
async webhookDisable() {
return { ok: true };
},
diff --git a/test/webhook-edit.test.ts b/test/webhook-edit.test.ts
new file mode 100644
index 000000000..18e641e0b
--- /dev/null
+++ b/test/webhook-edit.test.ts
@@ -0,0 +1,19 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createWebhookStore } from "../src/webhooks/webhook-store.ts";
+test("editing a webhook's action keeps its id (URL) and secret", async () => {
+ const store = createWebhookStore();
+ const wh = await store.create({
+ owner: "u:a",
+ createdBy: "u:a",
+ ownerScopeId: "personal:a",
+ action: "old task",
+ verification: { scheme: "hmac-sha256", secret: "s3cret" },
+ });
+ const out = await store.update(wh.id, { action: "new task" });
+ assert.equal(out?.id, wh.id);
+ assert.equal(out?.action, "new task");
+ assert.equal(out?.verification.secret, "s3cret");
+ assert.equal((await store.get(wh.id))?.action, "new task");
+ assert.equal(await store.update("nope", { action: "x" }), null);
+});
diff --git a/test/webhook-receiver.test.ts b/test/webhook-receiver.test.ts
index 5840f9039..3c2d41944 100644
--- a/test/webhook-receiver.test.ts
+++ b/test/webhook-receiver.test.ts
@@ -395,3 +395,19 @@ test("webhook fire accounting failures remain contained when recording the failu
assert.equal(calls.length, 2);
assert.equal((await webhooks.get(wh.id))?.lastError, undefined);
});
+
+test("an edited task applies to the next delivery at the same URL and secret", async () => {
+ const { webhooks, calls, receiver } = harness();
+ const wh = await webhooks.create({
+ ownerScopeId: scopeId("personal", "U1"),
+ owner: "U1",
+ createdBy: "U1",
+ action: "old orders",
+ verification: { scheme: "github", secret: SECRET },
+ });
+ await webhooks.update(wh.id, { action: "new orders" });
+ assert.deepEqual(await receiver.deliver(wh.id, githubReq(JSON.stringify({ n: 1 }), "d-edit")), { status: 202 });
+ await flush();
+ assert.match(calls[0]?.text ?? "", /new orders/);
+ assert.doesNotMatch(calls[0]?.text ?? "", /old orders/);
+});