@deliverd/sdk 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deliverd/sdk",
3
- "version": "0.33.0",
3
+ "version": "0.35.0",
4
4
  "description": "Add human approval to any AI agent. Ask a person, wait for the answer, act on it. Start free at deliverd.dev.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -0,0 +1,293 @@
1
+ import { DeliverdTimeoutError } from "../errors.js";
2
+ import { durationMs, type Duration } from "../duration.js";
3
+ import type { FieldChange } from "../types.js";
4
+ import { DEFAULT_TOOL_EXPIRY, defaultDescription, refusalReason, structuredInput, type ToolApprovalOptions } from "./shared.js";
5
+
6
+ /**
7
+ * Claude Managed Agents, hosted by Anthropic or self-hosted: a person answers
8
+ * the tool calls a permission policy holds for confirmation.
9
+ *
10
+ * Give the agent a toolset with `permission_policy: { type: "always_ask" }`
11
+ * (MCP toolsets ask by default) and the session pauses on each such call with
12
+ * `session.status_idle`, `stop_reason.type: "requires_action"`. These answer
13
+ * the pause with a person's decision, as `user.tool_confirmation` events:
14
+ *
15
+ * ```ts
16
+ * import Anthropic from "@anthropic-ai/sdk";
17
+ * import { Deliverd } from "@deliverd/sdk";
18
+ * import { watchManagedAgentSessions } from "@deliverd/sdk/adapters";
19
+ *
20
+ * // Self-hosted: ANTHROPIC_BASE_URL is your server, ANTHROPIC_API_KEY its key.
21
+ * const client = new Anthropic();
22
+ * await watchManagedAgentSessions(client, {
23
+ * deliverd: new Deliverd(),
24
+ * approvers: ["platform-team"],
25
+ * });
26
+ * ```
27
+ *
28
+ * A self-hosted server sends no webhooks, so something has to look. The
29
+ * watcher polls for idle sessions and answers the ones waiting on a
30
+ * confirmation; `followManagedAgentSession` follows one session's stream; and
31
+ * `answerManagedAgentConfirmations` does one pass over one session, for a loop
32
+ * you own. Each call is one request in Deliverd keyed by its event id
33
+ * (`managed-agents:<id>`), so a second pass finds the request it already made
34
+ * rather than asking twice.
35
+ *
36
+ * - **Approved**, the call runs.
37
+ * - **Declined**, it does not, and the person's reason reaches the model as
38
+ * the `deny_message`.
39
+ * - **Approved only with changes**, it is declined: a confirmation is a yes or
40
+ * a no and cannot carry corrected input. The model is told the approved
41
+ * values, so it can call again with them.
42
+ * - **Undecided** before `timeout`, nothing is sent. The session waits
43
+ * indefinitely, so a later pass picks the same request up.
44
+ *
45
+ * Only calls the server marked `evaluated_permission: "ask"` are answered.
46
+ * A call `auto` already ran or denied, a worker-run tool on a self-hosted
47
+ * environment and a custom tool (your own code, where `deliverd.approve()`
48
+ * belongs) are left alone.
49
+ *
50
+ * Shapes follow `client.beta.sessions` in `@anthropic-ai/sdk` 1.8 (beta
51
+ * header `managed-agents-2026-04-01`), which self-hosted servers serve too.
52
+ * Nothing is imported from it.
53
+ */
54
+
55
+ /** The events this reads. Every other event passes through untouched. */
56
+ export interface ManagedAgentsEvent {
57
+ id: string;
58
+ type: string;
59
+ /** `agent.tool_use` and `agent.mcp_tool_use`: the tool. */
60
+ name?: string;
61
+ input?: Record<string, unknown>;
62
+ /** `agent.mcp_tool_use`: the server that offers the tool. */
63
+ mcp_server_name?: string;
64
+ /** `"ask"` on a call that is waiting for a confirmation. */
65
+ evaluated_permission?: string;
66
+ /** `session.status_idle`: why it stopped. */
67
+ stop_reason?: { type: string; event_ids?: string[] } | null;
68
+ }
69
+
70
+ /** What a stream carries: the events above, and `event_start` / `event_delta` frames with no id. */
71
+ export type ManagedAgentsStreamEvent = Omit<ManagedAgentsEvent, "id"> & { id?: string };
72
+
73
+ export interface ManagedAgentsToolConfirmation {
74
+ type: "user.tool_confirmation";
75
+ tool_use_id: string;
76
+ result: "allow" | "deny";
77
+ deny_message?: string;
78
+ }
79
+
80
+ /** The part of `new Anthropic()` these use. */
81
+ export interface ManagedAgentsClient {
82
+ beta: {
83
+ sessions: {
84
+ list(params?: { statuses?: Array<"rescheduling" | "running" | "idle" | "terminated">; agent_id?: string }): AsyncIterable<{
85
+ id: string;
86
+ }>;
87
+ events: {
88
+ list(sessionId: string, params?: { order?: "asc" | "desc"; types?: Array<"session.status_idle" | "agent.tool_use" | "agent.mcp_tool_use"> }): AsyncIterable<ManagedAgentsEvent>;
89
+ send(sessionId: string, params: { events: ManagedAgentsToolConfirmation[] }): PromiseLike<unknown>;
90
+ stream(sessionId: string): PromiseLike<AsyncIterable<ManagedAgentsStreamEvent>>;
91
+ };
92
+ };
93
+ };
94
+ }
95
+
96
+ export interface ManagedAgentsApprovalOptions extends ToolApprovalOptions {
97
+ /**
98
+ * Stop waiting on a person after this and leave the call for a later pass.
99
+ * The session waits indefinitely, so nothing is refused for being slow.
100
+ */
101
+ timeout?: Duration;
102
+ /** Cancels the wait. */
103
+ signal?: AbortSignal;
104
+ }
105
+
106
+ /** What one pass over a session came to. */
107
+ export interface ManagedAgentsResolution {
108
+ /** The confirmations sent, in the order the calls were asked about. */
109
+ sent: ManagedAgentsToolConfirmation[];
110
+ /** Event ids nobody decided before `timeout`. Still open in Deliverd and in the session. */
111
+ pending: string[];
112
+ /** Why each declined call was declined, by event id. */
113
+ reasons: Record<string, string>;
114
+ }
115
+
116
+ const PREFIX = "managed-agents:";
117
+ const TOOL_USE: Array<"agent.tool_use" | "agent.mcp_tool_use"> = ["agent.tool_use", "agent.mcp_tool_use"];
118
+
119
+ /** The event ids the session is blocked on, from its latest idle event; none when it is not. */
120
+ async function blockingIds(client: ManagedAgentsClient, sessionId: string): Promise<string[]> {
121
+ for await (const event of client.beta.sessions.events.list(sessionId, { order: "desc", types: ["session.status_idle"] })) {
122
+ return event.stop_reason?.type === "requires_action" ? [...(event.stop_reason.event_ids ?? [])] : [];
123
+ }
124
+ return [];
125
+ }
126
+
127
+ /** The tool-use events behind those ids, newest first, stopping once all are found. */
128
+ async function toolUses(client: ManagedAgentsClient, sessionId: string, ids: string[]): Promise<ManagedAgentsEvent[]> {
129
+ const wanted = new Set(ids);
130
+ const found = new Map<string, ManagedAgentsEvent>();
131
+ for await (const event of client.beta.sessions.events.list(sessionId, { order: "desc", types: TOOL_USE })) {
132
+ if (wanted.has(event.id)) found.set(event.id, event);
133
+ if (found.size === wanted.size) break;
134
+ }
135
+ return ids.flatMap((id) => (found.has(id) ? [found.get(id)!] : []));
136
+ }
137
+
138
+ function changedReason(tool: string, changes: FieldChange[]): string {
139
+ const parts = changes.map((c) => `${c.field} from ${JSON.stringify(c.from)} to ${JSON.stringify(c.to)}`);
140
+ return `A person approved ${tool} only with changes: ${parts.join("; ")}. It was not run as proposed. If it is still needed, call it again with those values.`;
141
+ }
142
+
143
+ function toolLabel(event: ManagedAgentsEvent): string {
144
+ const name = event.name ?? "a tool";
145
+ return event.mcp_server_name ? `${name} on ${event.mcp_server_name}` : name;
146
+ }
147
+
148
+ type Answer = { kind: "allow" } | { kind: "deny"; reason: string } | { kind: "pending" };
149
+
150
+ async function decideCall(event: ManagedAgentsEvent, sessionId: string, options: ManagedAgentsApprovalOptions): Promise<Answer> {
151
+ const tool = event.name ?? "a tool";
152
+ const input = event.input ?? {};
153
+ if (options.when && !(await options.when(tool, input))) return { kind: "allow" };
154
+ const described = (options.describe ?? defaultDescription)(toolLabel(event), input);
155
+ const structured = structuredInput(input);
156
+ try {
157
+ const decision = await options.deliverd.approve({
158
+ ...described,
159
+ approvers: options.approvers,
160
+ externalId: PREFIX + event.id,
161
+ flowId: options.flowId,
162
+ metadata: {
163
+ ...options.metadata,
164
+ tool,
165
+ session: sessionId,
166
+ ...(event.mcp_server_name ? { mcp_server: event.mcp_server_name } : {}),
167
+ },
168
+ ...(structured ? { input: structured } : {}),
169
+ expiresIn: options.expiresIn ?? DEFAULT_TOOL_EXPIRY,
170
+ timeout: options.timeout,
171
+ signal: options.signal,
172
+ });
173
+ if (decision.approved) {
174
+ return decision.changes?.length ? { kind: "deny", reason: changedReason(tool, decision.changes) } : { kind: "allow" };
175
+ }
176
+ return { kind: "deny", reason: refusalReason(tool, decision) };
177
+ } catch (err) {
178
+ if (err instanceof DeliverdTimeoutError) return { kind: "pending" };
179
+ throw err;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * One pass over one session: if it is waiting on confirmations, ask a person
185
+ * about each and send the answers that came back.
186
+ */
187
+ export async function answerManagedAgentConfirmations(
188
+ client: ManagedAgentsClient,
189
+ sessionId: string,
190
+ options: ManagedAgentsApprovalOptions,
191
+ /** The ids from a `requires_action` you already hold, to skip looking them up. */
192
+ eventIds?: string[]
193
+ ): Promise<ManagedAgentsResolution> {
194
+ const resolution: ManagedAgentsResolution = { sent: [], pending: [], reasons: {} };
195
+ const ids = eventIds ?? (await blockingIds(client, sessionId));
196
+ if (ids.length === 0) return resolution;
197
+ const calls = (await toolUses(client, sessionId, ids)).filter((e) => e.evaluated_permission === "ask");
198
+ const answers = await Promise.all(calls.map((event) => decideCall(event, sessionId, options)));
199
+ calls.forEach((event, i) => {
200
+ const answer = answers[i]!;
201
+ if (answer.kind === "pending") {
202
+ resolution.pending.push(event.id);
203
+ } else if (answer.kind === "allow") {
204
+ resolution.sent.push({ type: "user.tool_confirmation", tool_use_id: event.id, result: "allow" });
205
+ } else {
206
+ resolution.reasons[event.id] = answer.reason;
207
+ resolution.sent.push({ type: "user.tool_confirmation", tool_use_id: event.id, result: "deny", deny_message: answer.reason });
208
+ }
209
+ });
210
+ if (resolution.sent.length > 0) await client.beta.sessions.events.send(sessionId, { events: resolution.sent });
211
+ return resolution;
212
+ }
213
+
214
+ /**
215
+ * Follow one session's stream, answering each confirmation it pauses on,
216
+ * until its turn ends, it stops for another reason, or it terminates.
217
+ * Open it before you send the message that starts the turn: a stream carries
218
+ * only what happens after it opens.
219
+ */
220
+ export async function followManagedAgentSession(
221
+ client: ManagedAgentsClient,
222
+ sessionId: string,
223
+ options: ManagedAgentsApprovalOptions & {
224
+ /** Every event, for printing the agent's messages as they arrive. */
225
+ onEvent?: (event: ManagedAgentsStreamEvent) => void;
226
+ }
227
+ ): Promise<void> {
228
+ const stream = await client.beta.sessions.events.stream(sessionId);
229
+ for await (const event of stream) {
230
+ options.onEvent?.(event);
231
+ if (event.type === "session.status_terminated") return;
232
+ if (event.type !== "session.status_idle") continue;
233
+ if (event.stop_reason?.type !== "requires_action") return;
234
+ await answerManagedAgentConfirmations(client, sessionId, options, event.stop_reason.event_ids ?? []);
235
+ }
236
+ }
237
+
238
+ /**
239
+ * Keep answering, for every idle session the key can see (or one agent's,
240
+ * with `agentId`), until `signal` aborts. For a self-hosted server, which
241
+ * sends no webhooks; it works the same against Anthropic's API.
242
+ *
243
+ * Each pass waits on a person for at most `timeout` per call (default ten
244
+ * seconds), so one slow decision does not hold up another session. An
245
+ * undecided call is picked up again next pass, from the same request.
246
+ */
247
+ export async function watchManagedAgentSessions(
248
+ client: ManagedAgentsClient,
249
+ options: ManagedAgentsApprovalOptions & {
250
+ agentId?: string;
251
+ /** Time between passes. Default five seconds. */
252
+ interval?: Duration;
253
+ /** A session that could not be answered this pass; the watcher carries on. */
254
+ onError?: (error: unknown, sessionId: string) => void;
255
+ }
256
+ ): Promise<void> {
257
+ const interval = options.interval === undefined ? 5_000 : durationMs(options.interval);
258
+ const perPass: ManagedAgentsApprovalOptions = { ...options, timeout: options.timeout ?? "10s" };
259
+ while (!options.signal?.aborted) {
260
+ const idle: string[] = [];
261
+ for await (const session of client.beta.sessions.list({
262
+ statuses: ["idle"],
263
+ ...(options.agentId ? { agent_id: options.agentId } : {}),
264
+ })) {
265
+ idle.push(session.id);
266
+ }
267
+ await Promise.all(
268
+ idle.map(async (id) => {
269
+ try {
270
+ await answerManagedAgentConfirmations(client, id, perPass);
271
+ } catch (err) {
272
+ if (options.signal?.aborted) return;
273
+ if (options.onError) options.onError(err, id);
274
+ else throw err;
275
+ }
276
+ })
277
+ );
278
+ await sleep(interval, options.signal);
279
+ }
280
+ }
281
+
282
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
283
+ return new Promise((resolve) => {
284
+ if (signal?.aborted) return resolve();
285
+ const timer = setTimeout(done, ms);
286
+ function done() {
287
+ clearTimeout(timer);
288
+ signal?.removeEventListener("abort", done);
289
+ resolve();
290
+ }
291
+ signal?.addEventListener("abort", done, { once: true });
292
+ });
293
+ }
@@ -13,6 +13,19 @@ export type {
13
13
  ClaudePermissionResult,
14
14
  ClaudeToolApprovalOptions,
15
15
  } from "./claude-agent-sdk.js";
16
+ export {
17
+ answerManagedAgentConfirmations,
18
+ followManagedAgentSession,
19
+ watchManagedAgentSessions,
20
+ } from "./claude-managed-agents.js";
21
+ export type {
22
+ ManagedAgentsApprovalOptions,
23
+ ManagedAgentsClient,
24
+ ManagedAgentsEvent,
25
+ ManagedAgentsResolution,
26
+ ManagedAgentsStreamEvent,
27
+ ManagedAgentsToolConfirmation,
28
+ } from "./claude-managed-agents.js";
16
29
  export { deliverdToolApproval } from "./ai-sdk.js";
17
30
  export type { AiSdkApprovalCall, AiSdkApprovalStatus } from "./ai-sdk.js";
18
31
  export { resolveInterruptions, runWithDeliverdApprovals } from "./openai-agents.js";
@@ -30,5 +43,7 @@ export type {
30
43
  MuseToolMessage,
31
44
  MuseToolRunner,
32
45
  } from "./muse-spark.js";
46
+ export { deliverdAllow, describeStep, uiSdkApprovalRoute, UI_SDK_DEFAULT_TIMEOUT } from "./ui-sdk.js";
47
+ export type { DeliverdAllowOptions, UiSdkApprovalAnswer, UiSdkApprovalRouteOptions, UiSdkStep } from "./ui-sdk.js";
33
48
  export { defaultDescription, DEFAULT_TOOL_EXPIRY } from "./shared.js";
34
49
  export type { Approver, CallDescription, CallOutcome, ToolApprovalOptions } from "./shared.js";
@@ -0,0 +1,263 @@
1
+ import type { Duration } from "../duration.js";
2
+ import { askAboutCall, type CallDescription, type ToolApprovalOptions } from "./shared.js";
3
+
4
+ /**
5
+ * Vercel's UI SDK (`@ui-sdk/*`): a person approves what an agent does in your
6
+ * interface, through Deliverd.
7
+ *
8
+ * UI SDK's agent bridge lets an agent press buttons and fill fields in an app
9
+ * built with its components. Controls marked `data-agent-confirm="…"` wait for
10
+ * the bridge's `allow` hook. These two functions make that hook a Deliverd
11
+ * approval: the browser half asks your server, and your server, which holds the
12
+ * agent key, asks Deliverd and waits for the person.
13
+ *
14
+ * In the browser, where the bridge is created:
15
+ *
16
+ * ```ts
17
+ * import { createAgent } from "@ui-sdk/react/agent";
18
+ * import { deliverdAllow } from "@deliverd/sdk/adapters";
19
+ *
20
+ * const agent = createAgent({
21
+ * allow: deliverdAllow({ endpoint: "/api/deliverd/ui-approval" }),
22
+ * timeout: 15 * 60_000,
23
+ * });
24
+ * ```
25
+ *
26
+ * On the server, as a fetch-style route (Next.js `app/api/deliverd/ui-approval/route.ts`):
27
+ *
28
+ * ```ts
29
+ * import { Deliverd } from "@deliverd/sdk";
30
+ * import { uiSdkApprovalRoute } from "@deliverd/sdk/adapters";
31
+ *
32
+ * export const maxDuration = 800;
33
+ * export const POST = uiSdkApprovalRoute({ deliverd: new Deliverd(), approvers: ["ops"], timeout: "13m" });
34
+ * ```
35
+ *
36
+ * The browser never sees the agent key, and the agent never sees the answer
37
+ * until a person gives it. Each ask is its own request: an approval is for
38
+ * that one step, then, and is never reused for a later one. A wait that runs
39
+ * out is a no, and the request expires with it, so nobody approves a step the
40
+ * agent has stopped waiting for.
41
+ *
42
+ * Shapes follow `AgentAction` and `createAgent`'s `allow` option in
43
+ * `@ui-sdk/core`'s agent docs (0.1.0-beta.1).
44
+ */
45
+
46
+ /** The step UI SDK hands to `allow`: its `AgentAction`. */
47
+ export interface UiSdkStep {
48
+ ref: string;
49
+ component: string;
50
+ label?: string;
51
+ action: string;
52
+ args?: unknown[];
53
+ /** The sentence from a `data-agent-confirm` mark on the target, when it has one. */
54
+ confirm?: string;
55
+ }
56
+
57
+ /** What the server route answers. */
58
+ export type UiSdkApprovalAnswer = { allowed: true; decidedBy: string | null } | { allowed: false; reason: string };
59
+
60
+ export interface DeliverdAllowOptions {
61
+ /** Your server route that calls `uiSdkApprovalRoute`. */
62
+ endpoint: string;
63
+ /**
64
+ * Which steps go to a person. Default: those on a `data-agent-confirm`
65
+ * mark. Steps outside it are allowed without asking.
66
+ */
67
+ when?: (step: UiSdkStep) => boolean;
68
+ /** Headers for the call to your route, such as a CSRF token. */
69
+ headers?: Record<string, string> | (() => Record<string, string>);
70
+ /** Told each answer, so the page can show a person's reason. */
71
+ onAnswer?: (answer: UiSdkApprovalAnswer, step: UiSdkStep) => void;
72
+ fetch?: typeof globalThis.fetch;
73
+ }
74
+
75
+ /**
76
+ * UI SDK's `allow` hook, answered by a person through Deliverd.
77
+ *
78
+ * Anything other than a clear yes from your route is a no: a network failure,
79
+ * an error status, an answer it cannot read. UI SDK then tells the agent the
80
+ * person said no, and the control is not touched.
81
+ */
82
+ export function deliverdAllow(
83
+ options: DeliverdAllowOptions
84
+ ): (step: UiSdkStep, context?: { signal?: AbortSignal }) => Promise<boolean> {
85
+ const needsPerson = options.when ?? ((step: UiSdkStep) => Boolean(step.confirm));
86
+ return async (step, context) => {
87
+ if (!needsPerson(step)) return true;
88
+ const doFetch = options.fetch ?? globalThis.fetch;
89
+ const headers = typeof options.headers === "function" ? options.headers() : options.headers;
90
+ let answer: UiSdkApprovalAnswer;
91
+ try {
92
+ const response = await doFetch(options.endpoint, {
93
+ method: "POST",
94
+ headers: { "content-type": "application/json", ...headers },
95
+ body: JSON.stringify({ step: pickStep(step), nonce: nonce() }),
96
+ signal: context?.signal,
97
+ });
98
+ const body = (await response.json().catch(() => null)) as Partial<UiSdkApprovalAnswer> | null;
99
+ answer =
100
+ response.ok && body?.allowed === true
101
+ ? { allowed: true, decidedBy: typeof body.decidedBy === "string" ? body.decidedBy : null }
102
+ : {
103
+ allowed: false,
104
+ reason:
105
+ body && body.allowed === false && typeof body.reason === "string"
106
+ ? body.reason
107
+ : `The approval route answered ${response.status}, so the step was not run.`,
108
+ };
109
+ } catch {
110
+ if (context?.signal?.aborted) return false;
111
+ answer = { allowed: false, reason: "The approval route could not be reached, so the step was not run." };
112
+ }
113
+ options.onAnswer?.(answer, step);
114
+ return answer.allowed;
115
+ };
116
+ }
117
+
118
+ export interface UiSdkApprovalRouteOptions extends Omit<ToolApprovalOptions, "when" | "describe"> {
119
+ /**
120
+ * Which steps go to a person, decided on the server. Default: those on a
121
+ * `data-agent-confirm` mark. A step outside it is refused, not allowed:
122
+ * the browser only sends steps it wants a person for, so anything else
123
+ * arriving here was not sent by `deliverdAllow`.
124
+ */
125
+ when?: (step: UiSdkStep, request: Request) => boolean | Promise<boolean>;
126
+ /** What the approver reads. Built from the mark's sentence, the control and its values when omitted. */
127
+ describe?: (step: UiSdkStep) => CallDescription;
128
+ /**
129
+ * How long to wait for the person. Default four minutes, inside UI SDK's
130
+ * own five-minute wait and a typical function limit. Raise all three together.
131
+ */
132
+ timeout?: Duration;
133
+ /** How long the request stays open. Default: the same as `timeout`. */
134
+ expiresIn?: Duration;
135
+ }
136
+
137
+ export const UI_SDK_DEFAULT_TIMEOUT: Duration = "4m";
138
+
139
+ /**
140
+ * The server half: a fetch-style `POST` handler (Next.js route handlers, Hono,
141
+ * Remix, Workers) that asks Deliverd about one UI SDK step and waits.
142
+ *
143
+ * Set `timeout` below both your platform's function limit and the bridge's
144
+ * own `timeout`, or the function is cut off before it can answer. The
145
+ * request's abort signal cancels the wait when the page stops asking.
146
+ */
147
+ export function uiSdkApprovalRoute(options: UiSdkApprovalRouteOptions): (request: Request) => Promise<Response> {
148
+ const needsPerson = options.when ?? ((step: UiSdkStep) => Boolean(step.confirm));
149
+ const describe = options.describe ?? describeStep;
150
+ const timeout = options.timeout ?? UI_SDK_DEFAULT_TIMEOUT;
151
+ return async (request) => {
152
+ if (request.method !== "POST") return json({ allowed: false, reason: "Use POST." }, 405);
153
+ let raw: unknown;
154
+ try {
155
+ const text = await request.text();
156
+ if (text.length > BODY_MAX) return json({ allowed: false, reason: "The step is too large to ask about." }, 413);
157
+ raw = JSON.parse(text);
158
+ } catch {
159
+ return json({ allowed: false, reason: "The step could not be read." }, 400);
160
+ }
161
+ const parsed = readBody(raw);
162
+ if (!parsed) return json({ allowed: false, reason: "The step could not be read." }, 400);
163
+ const { step, nonce: id } = parsed;
164
+ if (!(await needsPerson(step, request))) {
165
+ return json({ allowed: false, reason: "This step is not one this route asks a person about." }, 403);
166
+ }
167
+ const name = stepName(step);
168
+ const outcome = await askAboutCall(
169
+ name,
170
+ { component: step.component, ref: step.ref, action: step.action, args: step.args ?? [] },
171
+ `ui-sdk:${await sha256(canonical({ step, id }))}`,
172
+ {
173
+ ...options,
174
+ when: undefined,
175
+ describe: () => describe(step),
176
+ timeout,
177
+ expiresIn: options.expiresIn ?? timeout,
178
+ metadata: { ...options.metadata, source: "ui-sdk" },
179
+ },
180
+ request.signal
181
+ );
182
+ return json(
183
+ outcome.allowed ? { allowed: true, decidedBy: outcome.decidedBy } : { allowed: false, reason: outcome.reason },
184
+ 200
185
+ );
186
+ };
187
+ }
188
+
189
+ /** What an approver reads about a step, when the app did not write it. */
190
+ export function describeStep(step: UiSdkStep): CallDescription {
191
+ const target = step.label ? `"${step.label}"` : `the ${step.component}`;
192
+ const verb = step.action === "press" ? "press" : step.action === "setValue" ? "set" : step.action;
193
+ const values = (step.args ?? []).map((arg) => (typeof arg === "string" ? arg : JSON.stringify(arg))).join(", ");
194
+ const lines = [
195
+ step.confirm ? `The app says this: ${step.confirm}` : undefined,
196
+ `An agent wants to ${verb} ${target}${values ? ` (${truncate(values, 500)})` : ""} in the app.`,
197
+ ].filter(Boolean);
198
+ return {
199
+ title: truncate(step.confirm ?? `Let the agent ${verb} ${target}`, 200),
200
+ description: lines.join("\n\n"),
201
+ risk: step.confirm ? "high" : "medium",
202
+ };
203
+ }
204
+
205
+ const BODY_MAX = 16_000;
206
+
207
+ function stepName(step: UiSdkStep): string {
208
+ return step.label ? `${step.action} "${step.label}"` : `${step.action} ${step.component}`;
209
+ }
210
+
211
+ /** Only the fields `AgentAction` documents, so nothing else on the object leaves the page. */
212
+ function pickStep(step: UiSdkStep): UiSdkStep {
213
+ return {
214
+ ref: step.ref,
215
+ component: step.component,
216
+ ...(step.label !== undefined ? { label: step.label } : {}),
217
+ action: step.action,
218
+ args: step.args ?? [],
219
+ ...(step.confirm !== undefined ? { confirm: step.confirm } : {}),
220
+ };
221
+ }
222
+
223
+ function readBody(raw: unknown): { step: UiSdkStep; nonce: string } | null {
224
+ if (typeof raw !== "object" || raw === null) return null;
225
+ const { step, nonce: id } = raw as { step?: unknown; nonce?: unknown };
226
+ if (typeof id !== "string" || id.length === 0 || id.length > 100) return null;
227
+ if (typeof step !== "object" || step === null) return null;
228
+ const s = step as Record<string, unknown>;
229
+ const str = (v: unknown) => typeof v === "string" && v.length <= 1000;
230
+ if (!str(s.ref) || !str(s.component) || !str(s.action)) return null;
231
+ if (s.label !== undefined && !str(s.label)) return null;
232
+ if (s.confirm !== undefined && !str(s.confirm)) return null;
233
+ if (s.args !== undefined && !Array.isArray(s.args)) return null;
234
+ return { step: pickStep(s as unknown as UiSdkStep), nonce: id };
235
+ }
236
+
237
+ function json(body: UiSdkApprovalAnswer | { allowed: false; reason: string }, status: number): Response {
238
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
239
+ }
240
+
241
+ function truncate(text: string, max: number): string {
242
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
243
+ }
244
+
245
+ function nonce(): string {
246
+ const c = globalThis.crypto;
247
+ if (c?.randomUUID) return c.randomUUID();
248
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
249
+ }
250
+
251
+ function canonical(value: unknown): string {
252
+ if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
253
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
254
+ const entries = Object.entries(value as Record<string, unknown>)
255
+ .filter(([, v]) => v !== undefined)
256
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
257
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
258
+ }
259
+
260
+ async function sha256(text: string): Promise<string> {
261
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
262
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
263
+ }