@deliverd/sdk 0.33.0 → 0.34.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/README.md +21 -0
- package/dist/adapters/index.d.ts +2 -0
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +1 -0
- package/dist/adapters/ui-sdk.d.ts +116 -0
- package/dist/adapters/ui-sdk.d.ts.map +1 -0
- package/dist/adapters/ui-sdk.js +164 -0
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +1483 -0
- package/package.json +1 -1
- package/src/adapters/index.ts +2 -0
- package/src/adapters/ui-sdk.ts +263 -0
- package/src/released.ts +1484 -0
package/package.json
CHANGED
package/src/adapters/index.ts
CHANGED
|
@@ -30,5 +30,7 @@ export type {
|
|
|
30
30
|
MuseToolMessage,
|
|
31
31
|
MuseToolRunner,
|
|
32
32
|
} from "./muse-spark.js";
|
|
33
|
+
export { deliverdAllow, describeStep, uiSdkApprovalRoute, UI_SDK_DEFAULT_TIMEOUT } from "./ui-sdk.js";
|
|
34
|
+
export type { DeliverdAllowOptions, UiSdkApprovalAnswer, UiSdkApprovalRouteOptions, UiSdkStep } from "./ui-sdk.js";
|
|
33
35
|
export { defaultDescription, DEFAULT_TOOL_EXPIRY } from "./shared.js";
|
|
34
36
|
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
|
+
}
|