@deliverd/sdk 0.34.0 → 0.36.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 +34 -0
- package/dist/adapters/claude-managed-agents.d.ts +152 -0
- package/dist/adapters/claude-managed-agents.d.ts.map +1 -0
- package/dist/adapters/claude-managed-agents.js +165 -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/elements.d.ts +96 -0
- package/dist/elements.d.ts.map +1 -0
- package/dist/elements.js +94 -0
- package/dist/react.d.ts +40 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +73 -0
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +2996 -0
- package/package.json +19 -1
- package/src/adapters/claude-managed-agents.ts +293 -0
- package/src/adapters/index.ts +13 -0
- package/src/elements.ts +160 -0
- package/src/react.ts +104 -0
- package/src/released.ts +2998 -0
package/README.md
CHANGED
|
@@ -808,6 +808,24 @@ done.status; // "complete"
|
|
|
808
808
|
done.decision; // "approved"
|
|
809
809
|
```
|
|
810
810
|
|
|
811
|
+
In React, mount it with one component from `@deliverd/sdk/react` (React 18 or
|
|
812
|
+
later; `react` is an optional peer dependency):
|
|
813
|
+
|
|
814
|
+
```tsx
|
|
815
|
+
import { DeliverdDecision } from "@deliverd/sdk/react";
|
|
816
|
+
|
|
817
|
+
<DeliverdDecision
|
|
818
|
+
clientSecret={clientSecret} // embedded.clientSecret, handed down from your server
|
|
819
|
+
onDecided={(event) => confirmOnServer(event.sessionId)}
|
|
820
|
+
/>;
|
|
821
|
+
|
|
822
|
+
// No account yet? The demo request: sample data, nothing recorded.
|
|
823
|
+
<DeliverdDecision demo onDecided={(event) => console.log(event.decision)} />;
|
|
824
|
+
```
|
|
825
|
+
|
|
826
|
+
Elsewhere, `loadElements()` from `@deliverd/sdk/elements` loads the script once
|
|
827
|
+
and resolves to the same `mountDecision`.
|
|
828
|
+
|
|
811
829
|
`deliverd.approvals.list({ approver: "sarah@acme.com", status: "pending" })` is
|
|
812
830
|
her inbox, to show in your own UI. `deliverd.decisionSessions.expire(id)` ends a
|
|
813
831
|
session early.
|
|
@@ -826,6 +844,22 @@ import { deliverdCanUseTool } from "@deliverd/sdk/adapters";
|
|
|
826
844
|
query({ prompt, options: { canUseTool: deliverdCanUseTool({ deliverd, when: (tool) => tool === "Bash" }) } });
|
|
827
845
|
```
|
|
828
846
|
|
|
847
|
+
**Claude Managed Agents** (hosted, or self-hosted on your own servers) — give the
|
|
848
|
+
toolset `permission_policy: always_ask` (MCP toolsets ask by default), then
|
|
849
|
+
answer the sessions that pause for confirmation:
|
|
850
|
+
|
|
851
|
+
```ts
|
|
852
|
+
import { watchManagedAgentSessions } from "@deliverd/sdk/adapters";
|
|
853
|
+
|
|
854
|
+
// Self-hosted: ANTHROPIC_BASE_URL is your server, ANTHROPIC_API_KEY its API key.
|
|
855
|
+
await watchManagedAgentSessions(new Anthropic(), { deliverd, approvers: ["platform-team"] });
|
|
856
|
+
```
|
|
857
|
+
|
|
858
|
+
Each held call is asked about once and answered with `user.tool_confirmation`;
|
|
859
|
+
a no carries the person's reason as the `deny_message`. A self-hosted server
|
|
860
|
+
sends no webhooks, so the watcher polls; `followManagedAgentSession(client,
|
|
861
|
+
sessionId, { deliverd })` follows one session's stream instead.
|
|
862
|
+
|
|
829
863
|
**Vercel AI SDK**
|
|
830
864
|
|
|
831
865
|
```ts
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { type Duration } from "../duration.js";
|
|
2
|
+
import { type ToolApprovalOptions } from "./shared.js";
|
|
3
|
+
/**
|
|
4
|
+
* Claude Managed Agents, hosted by Anthropic or self-hosted: a person answers
|
|
5
|
+
* the tool calls a permission policy holds for confirmation.
|
|
6
|
+
*
|
|
7
|
+
* Give the agent a toolset with `permission_policy: { type: "always_ask" }`
|
|
8
|
+
* (MCP toolsets ask by default) and the session pauses on each such call with
|
|
9
|
+
* `session.status_idle`, `stop_reason.type: "requires_action"`. These answer
|
|
10
|
+
* the pause with a person's decision, as `user.tool_confirmation` events:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* import Anthropic from "@anthropic-ai/sdk";
|
|
14
|
+
* import { Deliverd } from "@deliverd/sdk";
|
|
15
|
+
* import { watchManagedAgentSessions } from "@deliverd/sdk/adapters";
|
|
16
|
+
*
|
|
17
|
+
* // Self-hosted: ANTHROPIC_BASE_URL is your server, ANTHROPIC_API_KEY its key.
|
|
18
|
+
* const client = new Anthropic();
|
|
19
|
+
* await watchManagedAgentSessions(client, {
|
|
20
|
+
* deliverd: new Deliverd(),
|
|
21
|
+
* approvers: ["platform-team"],
|
|
22
|
+
* });
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* A self-hosted server sends no webhooks, so something has to look. The
|
|
26
|
+
* watcher polls for idle sessions and answers the ones waiting on a
|
|
27
|
+
* confirmation; `followManagedAgentSession` follows one session's stream; and
|
|
28
|
+
* `answerManagedAgentConfirmations` does one pass over one session, for a loop
|
|
29
|
+
* you own. Each call is one request in Deliverd keyed by its event id
|
|
30
|
+
* (`managed-agents:<id>`), so a second pass finds the request it already made
|
|
31
|
+
* rather than asking twice.
|
|
32
|
+
*
|
|
33
|
+
* - **Approved**, the call runs.
|
|
34
|
+
* - **Declined**, it does not, and the person's reason reaches the model as
|
|
35
|
+
* the `deny_message`.
|
|
36
|
+
* - **Approved only with changes**, it is declined: a confirmation is a yes or
|
|
37
|
+
* a no and cannot carry corrected input. The model is told the approved
|
|
38
|
+
* values, so it can call again with them.
|
|
39
|
+
* - **Undecided** before `timeout`, nothing is sent. The session waits
|
|
40
|
+
* indefinitely, so a later pass picks the same request up.
|
|
41
|
+
*
|
|
42
|
+
* Only calls the server marked `evaluated_permission: "ask"` are answered.
|
|
43
|
+
* A call `auto` already ran or denied, a worker-run tool on a self-hosted
|
|
44
|
+
* environment and a custom tool (your own code, where `deliverd.approve()`
|
|
45
|
+
* belongs) are left alone.
|
|
46
|
+
*
|
|
47
|
+
* Shapes follow `client.beta.sessions` in `@anthropic-ai/sdk` 1.8 (beta
|
|
48
|
+
* header `managed-agents-2026-04-01`), which self-hosted servers serve too.
|
|
49
|
+
* Nothing is imported from it.
|
|
50
|
+
*/
|
|
51
|
+
/** The events this reads. Every other event passes through untouched. */
|
|
52
|
+
export interface ManagedAgentsEvent {
|
|
53
|
+
id: string;
|
|
54
|
+
type: string;
|
|
55
|
+
/** `agent.tool_use` and `agent.mcp_tool_use`: the tool. */
|
|
56
|
+
name?: string;
|
|
57
|
+
input?: Record<string, unknown>;
|
|
58
|
+
/** `agent.mcp_tool_use`: the server that offers the tool. */
|
|
59
|
+
mcp_server_name?: string;
|
|
60
|
+
/** `"ask"` on a call that is waiting for a confirmation. */
|
|
61
|
+
evaluated_permission?: string;
|
|
62
|
+
/** `session.status_idle`: why it stopped. */
|
|
63
|
+
stop_reason?: {
|
|
64
|
+
type: string;
|
|
65
|
+
event_ids?: string[];
|
|
66
|
+
} | null;
|
|
67
|
+
}
|
|
68
|
+
/** What a stream carries: the events above, and `event_start` / `event_delta` frames with no id. */
|
|
69
|
+
export type ManagedAgentsStreamEvent = Omit<ManagedAgentsEvent, "id"> & {
|
|
70
|
+
id?: string;
|
|
71
|
+
};
|
|
72
|
+
export interface ManagedAgentsToolConfirmation {
|
|
73
|
+
type: "user.tool_confirmation";
|
|
74
|
+
tool_use_id: string;
|
|
75
|
+
result: "allow" | "deny";
|
|
76
|
+
deny_message?: string;
|
|
77
|
+
}
|
|
78
|
+
/** The part of `new Anthropic()` these use. */
|
|
79
|
+
export interface ManagedAgentsClient {
|
|
80
|
+
beta: {
|
|
81
|
+
sessions: {
|
|
82
|
+
list(params?: {
|
|
83
|
+
statuses?: Array<"rescheduling" | "running" | "idle" | "terminated">;
|
|
84
|
+
agent_id?: string;
|
|
85
|
+
}): AsyncIterable<{
|
|
86
|
+
id: string;
|
|
87
|
+
}>;
|
|
88
|
+
events: {
|
|
89
|
+
list(sessionId: string, params?: {
|
|
90
|
+
order?: "asc" | "desc";
|
|
91
|
+
types?: Array<"session.status_idle" | "agent.tool_use" | "agent.mcp_tool_use">;
|
|
92
|
+
}): AsyncIterable<ManagedAgentsEvent>;
|
|
93
|
+
send(sessionId: string, params: {
|
|
94
|
+
events: ManagedAgentsToolConfirmation[];
|
|
95
|
+
}): PromiseLike<unknown>;
|
|
96
|
+
stream(sessionId: string): PromiseLike<AsyncIterable<ManagedAgentsStreamEvent>>;
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
export interface ManagedAgentsApprovalOptions extends ToolApprovalOptions {
|
|
102
|
+
/**
|
|
103
|
+
* Stop waiting on a person after this and leave the call for a later pass.
|
|
104
|
+
* The session waits indefinitely, so nothing is refused for being slow.
|
|
105
|
+
*/
|
|
106
|
+
timeout?: Duration;
|
|
107
|
+
/** Cancels the wait. */
|
|
108
|
+
signal?: AbortSignal;
|
|
109
|
+
}
|
|
110
|
+
/** What one pass over a session came to. */
|
|
111
|
+
export interface ManagedAgentsResolution {
|
|
112
|
+
/** The confirmations sent, in the order the calls were asked about. */
|
|
113
|
+
sent: ManagedAgentsToolConfirmation[];
|
|
114
|
+
/** Event ids nobody decided before `timeout`. Still open in Deliverd and in the session. */
|
|
115
|
+
pending: string[];
|
|
116
|
+
/** Why each declined call was declined, by event id. */
|
|
117
|
+
reasons: Record<string, string>;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* One pass over one session: if it is waiting on confirmations, ask a person
|
|
121
|
+
* about each and send the answers that came back.
|
|
122
|
+
*/
|
|
123
|
+
export declare function answerManagedAgentConfirmations(client: ManagedAgentsClient, sessionId: string, options: ManagedAgentsApprovalOptions,
|
|
124
|
+
/** The ids from a `requires_action` you already hold, to skip looking them up. */
|
|
125
|
+
eventIds?: string[]): Promise<ManagedAgentsResolution>;
|
|
126
|
+
/**
|
|
127
|
+
* Follow one session's stream, answering each confirmation it pauses on,
|
|
128
|
+
* until its turn ends, it stops for another reason, or it terminates.
|
|
129
|
+
* Open it before you send the message that starts the turn: a stream carries
|
|
130
|
+
* only what happens after it opens.
|
|
131
|
+
*/
|
|
132
|
+
export declare function followManagedAgentSession(client: ManagedAgentsClient, sessionId: string, options: ManagedAgentsApprovalOptions & {
|
|
133
|
+
/** Every event, for printing the agent's messages as they arrive. */
|
|
134
|
+
onEvent?: (event: ManagedAgentsStreamEvent) => void;
|
|
135
|
+
}): Promise<void>;
|
|
136
|
+
/**
|
|
137
|
+
* Keep answering, for every idle session the key can see (or one agent's,
|
|
138
|
+
* with `agentId`), until `signal` aborts. For a self-hosted server, which
|
|
139
|
+
* sends no webhooks; it works the same against Anthropic's API.
|
|
140
|
+
*
|
|
141
|
+
* Each pass waits on a person for at most `timeout` per call (default ten
|
|
142
|
+
* seconds), so one slow decision does not hold up another session. An
|
|
143
|
+
* undecided call is picked up again next pass, from the same request.
|
|
144
|
+
*/
|
|
145
|
+
export declare function watchManagedAgentSessions(client: ManagedAgentsClient, options: ManagedAgentsApprovalOptions & {
|
|
146
|
+
agentId?: string;
|
|
147
|
+
/** Time between passes. Default five seconds. */
|
|
148
|
+
interval?: Duration;
|
|
149
|
+
/** A session that could not be answered this pass; the watcher carries on. */
|
|
150
|
+
onError?: (error: unknown, sessionId: string) => void;
|
|
151
|
+
}): Promise<void>;
|
|
152
|
+
//# sourceMappingURL=claude-managed-agents.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude-managed-agents.d.ts","sourceRoot":"","sources":["../../src/adapters/claude-managed-agents.ts"],"names":[],"mappings":"AACA,OAAO,EAAc,KAAK,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE3D,OAAO,EAA2E,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEhI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+CG;AAEH,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G;AACH,wBAAsB,yBAAyB,CAC7C,MAAM,EAAE,mBAAmB,EAC3B,OAAO,EAAE,4BAA4B,GAAG;IACtC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,iDAAiD;IACjD,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,8EAA8E;IAC9E,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;CACvD,GACA,OAAO,CAAC,IAAI,CAAC,CAwBf"}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { DeliverdTimeoutError } from "../errors.js";
|
|
2
|
+
import { durationMs } from "../duration.js";
|
|
3
|
+
import { DEFAULT_TOOL_EXPIRY, defaultDescription, refusalReason, structuredInput } from "./shared.js";
|
|
4
|
+
const PREFIX = "managed-agents:";
|
|
5
|
+
const TOOL_USE = ["agent.tool_use", "agent.mcp_tool_use"];
|
|
6
|
+
/** The event ids the session is blocked on, from its latest idle event; none when it is not. */
|
|
7
|
+
async function blockingIds(client, sessionId) {
|
|
8
|
+
for await (const event of client.beta.sessions.events.list(sessionId, { order: "desc", types: ["session.status_idle"] })) {
|
|
9
|
+
return event.stop_reason?.type === "requires_action" ? [...(event.stop_reason.event_ids ?? [])] : [];
|
|
10
|
+
}
|
|
11
|
+
return [];
|
|
12
|
+
}
|
|
13
|
+
/** The tool-use events behind those ids, newest first, stopping once all are found. */
|
|
14
|
+
async function toolUses(client, sessionId, ids) {
|
|
15
|
+
const wanted = new Set(ids);
|
|
16
|
+
const found = new Map();
|
|
17
|
+
for await (const event of client.beta.sessions.events.list(sessionId, { order: "desc", types: TOOL_USE })) {
|
|
18
|
+
if (wanted.has(event.id))
|
|
19
|
+
found.set(event.id, event);
|
|
20
|
+
if (found.size === wanted.size)
|
|
21
|
+
break;
|
|
22
|
+
}
|
|
23
|
+
return ids.flatMap((id) => (found.has(id) ? [found.get(id)] : []));
|
|
24
|
+
}
|
|
25
|
+
function changedReason(tool, changes) {
|
|
26
|
+
const parts = changes.map((c) => `${c.field} from ${JSON.stringify(c.from)} to ${JSON.stringify(c.to)}`);
|
|
27
|
+
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.`;
|
|
28
|
+
}
|
|
29
|
+
function toolLabel(event) {
|
|
30
|
+
const name = event.name ?? "a tool";
|
|
31
|
+
return event.mcp_server_name ? `${name} on ${event.mcp_server_name}` : name;
|
|
32
|
+
}
|
|
33
|
+
async function decideCall(event, sessionId, options) {
|
|
34
|
+
const tool = event.name ?? "a tool";
|
|
35
|
+
const input = event.input ?? {};
|
|
36
|
+
if (options.when && !(await options.when(tool, input)))
|
|
37
|
+
return { kind: "allow" };
|
|
38
|
+
const described = (options.describe ?? defaultDescription)(toolLabel(event), input);
|
|
39
|
+
const structured = structuredInput(input);
|
|
40
|
+
try {
|
|
41
|
+
const decision = await options.deliverd.approve({
|
|
42
|
+
...described,
|
|
43
|
+
approvers: options.approvers,
|
|
44
|
+
externalId: PREFIX + event.id,
|
|
45
|
+
flowId: options.flowId,
|
|
46
|
+
metadata: {
|
|
47
|
+
...options.metadata,
|
|
48
|
+
tool,
|
|
49
|
+
session: sessionId,
|
|
50
|
+
...(event.mcp_server_name ? { mcp_server: event.mcp_server_name } : {}),
|
|
51
|
+
},
|
|
52
|
+
...(structured ? { input: structured } : {}),
|
|
53
|
+
expiresIn: options.expiresIn ?? DEFAULT_TOOL_EXPIRY,
|
|
54
|
+
timeout: options.timeout,
|
|
55
|
+
signal: options.signal,
|
|
56
|
+
});
|
|
57
|
+
if (decision.approved) {
|
|
58
|
+
return decision.changes?.length ? { kind: "deny", reason: changedReason(tool, decision.changes) } : { kind: "allow" };
|
|
59
|
+
}
|
|
60
|
+
return { kind: "deny", reason: refusalReason(tool, decision) };
|
|
61
|
+
}
|
|
62
|
+
catch (err) {
|
|
63
|
+
if (err instanceof DeliverdTimeoutError)
|
|
64
|
+
return { kind: "pending" };
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* One pass over one session: if it is waiting on confirmations, ask a person
|
|
70
|
+
* about each and send the answers that came back.
|
|
71
|
+
*/
|
|
72
|
+
export async function answerManagedAgentConfirmations(client, sessionId, options,
|
|
73
|
+
/** The ids from a `requires_action` you already hold, to skip looking them up. */
|
|
74
|
+
eventIds) {
|
|
75
|
+
const resolution = { sent: [], pending: [], reasons: {} };
|
|
76
|
+
const ids = eventIds ?? (await blockingIds(client, sessionId));
|
|
77
|
+
if (ids.length === 0)
|
|
78
|
+
return resolution;
|
|
79
|
+
const calls = (await toolUses(client, sessionId, ids)).filter((e) => e.evaluated_permission === "ask");
|
|
80
|
+
const answers = await Promise.all(calls.map((event) => decideCall(event, sessionId, options)));
|
|
81
|
+
calls.forEach((event, i) => {
|
|
82
|
+
const answer = answers[i];
|
|
83
|
+
if (answer.kind === "pending") {
|
|
84
|
+
resolution.pending.push(event.id);
|
|
85
|
+
}
|
|
86
|
+
else if (answer.kind === "allow") {
|
|
87
|
+
resolution.sent.push({ type: "user.tool_confirmation", tool_use_id: event.id, result: "allow" });
|
|
88
|
+
}
|
|
89
|
+
else {
|
|
90
|
+
resolution.reasons[event.id] = answer.reason;
|
|
91
|
+
resolution.sent.push({ type: "user.tool_confirmation", tool_use_id: event.id, result: "deny", deny_message: answer.reason });
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
if (resolution.sent.length > 0)
|
|
95
|
+
await client.beta.sessions.events.send(sessionId, { events: resolution.sent });
|
|
96
|
+
return resolution;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Follow one session's stream, answering each confirmation it pauses on,
|
|
100
|
+
* until its turn ends, it stops for another reason, or it terminates.
|
|
101
|
+
* Open it before you send the message that starts the turn: a stream carries
|
|
102
|
+
* only what happens after it opens.
|
|
103
|
+
*/
|
|
104
|
+
export async function followManagedAgentSession(client, sessionId, options) {
|
|
105
|
+
const stream = await client.beta.sessions.events.stream(sessionId);
|
|
106
|
+
for await (const event of stream) {
|
|
107
|
+
options.onEvent?.(event);
|
|
108
|
+
if (event.type === "session.status_terminated")
|
|
109
|
+
return;
|
|
110
|
+
if (event.type !== "session.status_idle")
|
|
111
|
+
continue;
|
|
112
|
+
if (event.stop_reason?.type !== "requires_action")
|
|
113
|
+
return;
|
|
114
|
+
await answerManagedAgentConfirmations(client, sessionId, options, event.stop_reason.event_ids ?? []);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Keep answering, for every idle session the key can see (or one agent's,
|
|
119
|
+
* with `agentId`), until `signal` aborts. For a self-hosted server, which
|
|
120
|
+
* sends no webhooks; it works the same against Anthropic's API.
|
|
121
|
+
*
|
|
122
|
+
* Each pass waits on a person for at most `timeout` per call (default ten
|
|
123
|
+
* seconds), so one slow decision does not hold up another session. An
|
|
124
|
+
* undecided call is picked up again next pass, from the same request.
|
|
125
|
+
*/
|
|
126
|
+
export async function watchManagedAgentSessions(client, options) {
|
|
127
|
+
const interval = options.interval === undefined ? 5_000 : durationMs(options.interval);
|
|
128
|
+
const perPass = { ...options, timeout: options.timeout ?? "10s" };
|
|
129
|
+
while (!options.signal?.aborted) {
|
|
130
|
+
const idle = [];
|
|
131
|
+
for await (const session of client.beta.sessions.list({
|
|
132
|
+
statuses: ["idle"],
|
|
133
|
+
...(options.agentId ? { agent_id: options.agentId } : {}),
|
|
134
|
+
})) {
|
|
135
|
+
idle.push(session.id);
|
|
136
|
+
}
|
|
137
|
+
await Promise.all(idle.map(async (id) => {
|
|
138
|
+
try {
|
|
139
|
+
await answerManagedAgentConfirmations(client, id, perPass);
|
|
140
|
+
}
|
|
141
|
+
catch (err) {
|
|
142
|
+
if (options.signal?.aborted)
|
|
143
|
+
return;
|
|
144
|
+
if (options.onError)
|
|
145
|
+
options.onError(err, id);
|
|
146
|
+
else
|
|
147
|
+
throw err;
|
|
148
|
+
}
|
|
149
|
+
}));
|
|
150
|
+
await sleep(interval, options.signal);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function sleep(ms, signal) {
|
|
154
|
+
return new Promise((resolve) => {
|
|
155
|
+
if (signal?.aborted)
|
|
156
|
+
return resolve();
|
|
157
|
+
const timer = setTimeout(done, ms);
|
|
158
|
+
function done() {
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
signal?.removeEventListener("abort", done);
|
|
161
|
+
resolve();
|
|
162
|
+
}
|
|
163
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
164
|
+
});
|
|
165
|
+
}
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
*/
|
|
9
9
|
export { deliverdCanUseTool } from "./claude-agent-sdk.js";
|
|
10
10
|
export type { ClaudeCanUseTool, ClaudeCanUseToolContext, ClaudePermissionResult, ClaudeToolApprovalOptions, } from "./claude-agent-sdk.js";
|
|
11
|
+
export { answerManagedAgentConfirmations, followManagedAgentSession, watchManagedAgentSessions, } from "./claude-managed-agents.js";
|
|
12
|
+
export type { ManagedAgentsApprovalOptions, ManagedAgentsClient, ManagedAgentsEvent, ManagedAgentsResolution, ManagedAgentsStreamEvent, ManagedAgentsToolConfirmation, } from "./claude-managed-agents.js";
|
|
11
13
|
export { deliverdToolApproval } from "./ai-sdk.js";
|
|
12
14
|
export type { AiSdkApprovalCall, AiSdkApprovalStatus } from "./ai-sdk.js";
|
|
13
15
|
export { resolveInterruptions, runWithDeliverdApprovals } from "./openai-agents.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/adapters/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,YAAY,EACV,gBAAgB,EAChB,uBAAuB,EACvB,sBAAsB,EACtB,yBAAyB,GAC1B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,oBAAoB,EAAE,M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CAAC;AACtE,YAAY,EAAE,QAAQ,EAAE,eAAe,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC"}
|
package/dist/adapters/index.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* framework's hook by shape.
|
|
8
8
|
*/
|
|
9
9
|
export { deliverdCanUseTool } from "./claude-agent-sdk.js";
|
|
10
|
+
export { answerManagedAgentConfirmations, followManagedAgentSession, watchManagedAgentSessions, } from "./claude-managed-agents.js";
|
|
10
11
|
export { deliverdToolApproval } from "./ai-sdk.js";
|
|
11
12
|
export { resolveInterruptions, runWithDeliverdApprovals } from "./openai-agents.js";
|
|
12
13
|
export { approveInGraph, resumeFromCallback } from "./langgraph.js";
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deliverd Elements from a bundler: load the script, mount a decision.
|
|
3
|
+
*
|
|
4
|
+
* `https://deliverd.dev/elements/v1.js` is the element. This module does not
|
|
5
|
+
* reimplement it; it loads it, once, and hands back the same `mountDecision`
|
|
6
|
+
* a `<script>` tag would. Keeping one copy is the point: the frame, the
|
|
7
|
+
* origin checks on its messages and the sizing all live in that script, so a
|
|
8
|
+
* fix there reaches every page without anybody upgrading a package.
|
|
9
|
+
*
|
|
10
|
+
* Browser only. On a server there is no page to put a frame in, so
|
|
11
|
+
* `loadElements()` rejects there rather than pretending.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { loadElements } from "@deliverd/sdk/elements";
|
|
15
|
+
*
|
|
16
|
+
* const elements = await loadElements();
|
|
17
|
+
* const decision = elements.mountDecision("#decision", {
|
|
18
|
+
* clientSecret, // from your server: approvals.createSession(id, { mode: "embedded", origin })
|
|
19
|
+
* onDecided(event) {
|
|
20
|
+
* // Tell your server, which reads decisionSessions.get(event.sessionId) before acting.
|
|
21
|
+
* },
|
|
22
|
+
* });
|
|
23
|
+
* // later: decision.unmount();
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
/** Where Elements is served from, unless you say otherwise. */
|
|
27
|
+
export declare const ELEMENTS_ORIGIN = "https://deliverd.dev";
|
|
28
|
+
/** The path of the script on that origin. Versioned: v1 keeps working. */
|
|
29
|
+
export declare const ELEMENTS_PATH = "/elements/v1.js";
|
|
30
|
+
/** What every event hands your handler. */
|
|
31
|
+
export interface DecisionEvent {
|
|
32
|
+
type: "ready" | "verified" | "decided" | "expired";
|
|
33
|
+
sessionId: string;
|
|
34
|
+
approvalId: string;
|
|
35
|
+
/** Set on `decided`: what the approver chose. */
|
|
36
|
+
decision: "approved" | "rejected" | "changes_requested" | null;
|
|
37
|
+
/** Set on `decided`: the request's own status, which other approvers may still be part of. */
|
|
38
|
+
approvalStatus: string | null;
|
|
39
|
+
}
|
|
40
|
+
export interface MountDecisionOptions {
|
|
41
|
+
/**
|
|
42
|
+
* The session's `clientSecret`, from `approvals.createSession(id, { mode: "embedded", origin })`
|
|
43
|
+
* on your server. Required unless `demo` is set.
|
|
44
|
+
*/
|
|
45
|
+
clientSecret?: string;
|
|
46
|
+
/**
|
|
47
|
+
* Show the demo request instead of a real one: sample data, a code shown on
|
|
48
|
+
* screen, and nothing recorded. Needs no account and frames on any site, so
|
|
49
|
+
* you can see the element and its events before writing server code.
|
|
50
|
+
*/
|
|
51
|
+
demo?: boolean;
|
|
52
|
+
/** The frame's accessible title. "Decision" when omitted. */
|
|
53
|
+
title?: string;
|
|
54
|
+
/** The frame's height before it reports its own, in pixels. 320 when omitted. */
|
|
55
|
+
minHeight?: number;
|
|
56
|
+
/** Set `false` to size the frame yourself instead of letting it fit its content. */
|
|
57
|
+
autoResize?: boolean;
|
|
58
|
+
onReady?: (event: DecisionEvent) => void;
|
|
59
|
+
onVerified?: (event: DecisionEvent) => void;
|
|
60
|
+
/** The browser's word only: confirm with `decisionSessions.get(id)` from your server before acting. */
|
|
61
|
+
onDecided?: (event: DecisionEvent) => void;
|
|
62
|
+
onExpired?: (event: DecisionEvent) => void;
|
|
63
|
+
}
|
|
64
|
+
export interface MountedDecision {
|
|
65
|
+
frame: HTMLIFrameElement;
|
|
66
|
+
unmount(): void;
|
|
67
|
+
}
|
|
68
|
+
/** What the script puts on `window.Deliverd`. */
|
|
69
|
+
export interface DeliverdElements {
|
|
70
|
+
mountDecision(target: string | Element, options: MountDecisionOptions): MountedDecision;
|
|
71
|
+
elementsVersion: number;
|
|
72
|
+
}
|
|
73
|
+
export interface LoadElementsOptions {
|
|
74
|
+
/**
|
|
75
|
+
* Another Deliverd origin, such as your own self-hosted deployment. Must be
|
|
76
|
+
* the origin the session was made on: the frame only talks to the script
|
|
77
|
+
* that came from its own origin.
|
|
78
|
+
*/
|
|
79
|
+
origin?: string;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Loads Elements into the page once, and resolves to its API.
|
|
83
|
+
*
|
|
84
|
+
* Safe to call as often as you like: a second call, from anywhere, waits on
|
|
85
|
+
* the same script rather than adding another. If the page already loaded the
|
|
86
|
+
* script with a `<script>` tag, that one is used.
|
|
87
|
+
*/
|
|
88
|
+
export declare function loadElements(options?: LoadElementsOptions): Promise<DeliverdElements>;
|
|
89
|
+
/**
|
|
90
|
+
* Loads Elements and mounts a decision into `host`, unless `cancelled()` says
|
|
91
|
+
* the caller went away first. Resolves to the mounted decision, or `null`
|
|
92
|
+
* when it was cancelled. What the React component does in an effect, kept
|
|
93
|
+
* here so it can be used, and tested, without React.
|
|
94
|
+
*/
|
|
95
|
+
export declare function mountWhenLoaded(host: Element, options: MountDecisionOptions, load: () => Promise<DeliverdElements>, cancelled: () => boolean): Promise<MountedDecision | null>;
|
|
96
|
+
//# sourceMappingURL=elements.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"elements.d.ts","sourceRoot":"","sources":["../src/elements.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,+DAA+D;AAC/D,eAAO,MAAM,eAAe,yBAAyB,CAAC;AAEtD,0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;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAWD;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,OAAO,GAAE,mBAAwB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAmCzF;AAED;;;;;GAKG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,oBAAoB,EAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,gBAAgB,CAAC,EACrC,SAAS,EAAE,MAAM,OAAO,GACvB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAOjC"}
|
package/dist/elements.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deliverd Elements from a bundler: load the script, mount a decision.
|
|
3
|
+
*
|
|
4
|
+
* `https://deliverd.dev/elements/v1.js` is the element. This module does not
|
|
5
|
+
* reimplement it; it loads it, once, and hands back the same `mountDecision`
|
|
6
|
+
* a `<script>` tag would. Keeping one copy is the point: the frame, the
|
|
7
|
+
* origin checks on its messages and the sizing all live in that script, so a
|
|
8
|
+
* fix there reaches every page without anybody upgrading a package.
|
|
9
|
+
*
|
|
10
|
+
* Browser only. On a server there is no page to put a frame in, so
|
|
11
|
+
* `loadElements()` rejects there rather than pretending.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { loadElements } from "@deliverd/sdk/elements";
|
|
15
|
+
*
|
|
16
|
+
* const elements = await loadElements();
|
|
17
|
+
* const decision = elements.mountDecision("#decision", {
|
|
18
|
+
* clientSecret, // from your server: approvals.createSession(id, { mode: "embedded", origin })
|
|
19
|
+
* onDecided(event) {
|
|
20
|
+
* // Tell your server, which reads decisionSessions.get(event.sessionId) before acting.
|
|
21
|
+
* },
|
|
22
|
+
* });
|
|
23
|
+
* // later: decision.unmount();
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
/** Where Elements is served from, unless you say otherwise. */
|
|
27
|
+
export const ELEMENTS_ORIGIN = "https://deliverd.dev";
|
|
28
|
+
/** The path of the script on that origin. Versioned: v1 keeps working. */
|
|
29
|
+
export const ELEMENTS_PATH = "/elements/v1.js";
|
|
30
|
+
const loading = new Map();
|
|
31
|
+
function ready(w) {
|
|
32
|
+
const api = w.Deliverd;
|
|
33
|
+
return api && typeof api.mountDecision === "function" ? api : null;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Loads Elements into the page once, and resolves to its API.
|
|
37
|
+
*
|
|
38
|
+
* Safe to call as often as you like: a second call, from anywhere, waits on
|
|
39
|
+
* the same script rather than adding another. If the page already loaded the
|
|
40
|
+
* script with a `<script>` tag, that one is used.
|
|
41
|
+
*/
|
|
42
|
+
export function loadElements(options = {}) {
|
|
43
|
+
if (typeof window === "undefined" || typeof document === "undefined") {
|
|
44
|
+
return Promise.reject(new Error("Deliverd Elements runs in a browser. Call loadElements() from client code."));
|
|
45
|
+
}
|
|
46
|
+
const origin = new URL(options.origin ?? ELEMENTS_ORIGIN).origin;
|
|
47
|
+
const w = window;
|
|
48
|
+
const existing = ready(w);
|
|
49
|
+
if (existing)
|
|
50
|
+
return Promise.resolve(existing);
|
|
51
|
+
const cached = loading.get(origin);
|
|
52
|
+
if (cached)
|
|
53
|
+
return cached;
|
|
54
|
+
const src = origin + ELEMENTS_PATH;
|
|
55
|
+
const promise = new Promise((resolve, reject) => {
|
|
56
|
+
const fail = (message) => {
|
|
57
|
+
loading.delete(origin);
|
|
58
|
+
reject(new Error(message));
|
|
59
|
+
};
|
|
60
|
+
const done = () => {
|
|
61
|
+
const api = ready(w);
|
|
62
|
+
if (api)
|
|
63
|
+
resolve(api);
|
|
64
|
+
else
|
|
65
|
+
fail(`Deliverd Elements loaded from ${src} but did not start.`);
|
|
66
|
+
};
|
|
67
|
+
let script = document.querySelector(`script[src="${src}"]`);
|
|
68
|
+
if (!script) {
|
|
69
|
+
script = document.createElement("script");
|
|
70
|
+
script.src = src;
|
|
71
|
+
script.async = true;
|
|
72
|
+
document.head.appendChild(script);
|
|
73
|
+
}
|
|
74
|
+
script.addEventListener("load", done, { once: true });
|
|
75
|
+
script.addEventListener("error", () => fail(`Could not load Deliverd Elements from ${src}.`), { once: true });
|
|
76
|
+
});
|
|
77
|
+
loading.set(origin, promise);
|
|
78
|
+
return promise;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Loads Elements and mounts a decision into `host`, unless `cancelled()` says
|
|
82
|
+
* the caller went away first. Resolves to the mounted decision, or `null`
|
|
83
|
+
* when it was cancelled. What the React component does in an effect, kept
|
|
84
|
+
* here so it can be used, and tested, without React.
|
|
85
|
+
*/
|
|
86
|
+
export async function mountWhenLoaded(host, options, load, cancelled) {
|
|
87
|
+
if (!options.demo && !options.clientSecret) {
|
|
88
|
+
throw new Error("Deliverd: pass clientSecret (from an embedded session), or demo: true.");
|
|
89
|
+
}
|
|
90
|
+
const elements = await load();
|
|
91
|
+
if (cancelled())
|
|
92
|
+
return null;
|
|
93
|
+
return elements.mountDecision(host, options);
|
|
94
|
+
}
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `<DeliverdDecision>`: a decision session in a React page.
|
|
3
|
+
*
|
|
4
|
+
* A thin wrapper over Deliverd Elements (`@deliverd/sdk/elements`): it loads
|
|
5
|
+
* the script once, mounts the frame into a `<div>` it renders, passes your
|
|
6
|
+
* handlers through, and unmounts the frame when the component goes away or
|
|
7
|
+
* the secret changes. The frame is still served from Deliverd's origin, so
|
|
8
|
+
* your page cannot read it or press its buttons, and the approver still
|
|
9
|
+
* proves who they are before deciding.
|
|
10
|
+
*
|
|
11
|
+
* ```tsx
|
|
12
|
+
* import { DeliverdDecision } from "@deliverd/sdk/react";
|
|
13
|
+
*
|
|
14
|
+
* <DeliverdDecision
|
|
15
|
+
* clientSecret={clientSecret} // from your server
|
|
16
|
+
* onDecided={(event) => confirmOnServer(event.sessionId)}
|
|
17
|
+
* />
|
|
18
|
+
*
|
|
19
|
+
* // No account yet? See it with sample data, nothing recorded:
|
|
20
|
+
* <DeliverdDecision demo onDecided={(event) => console.log(event)} />
|
|
21
|
+
* ```
|
|
22
|
+
*
|
|
23
|
+
* React 18 or later. Written without JSX so the package needs no build step
|
|
24
|
+
* of its own for it; `react` is an optional peer dependency, needed only if
|
|
25
|
+
* you import this entry.
|
|
26
|
+
*/
|
|
27
|
+
import { type CSSProperties, type ReactElement } from "react";
|
|
28
|
+
import { type MountDecisionOptions } from "./elements.js";
|
|
29
|
+
export type { DecisionEvent } from "./elements.js";
|
|
30
|
+
export interface DeliverdDecisionProps extends Pick<MountDecisionOptions, "clientSecret" | "demo" | "title" | "minHeight" | "autoResize" | "onReady" | "onVerified" | "onDecided" | "onExpired"> {
|
|
31
|
+
/** Another Deliverd origin, such as a self-hosted deployment. https://deliverd.dev when omitted. */
|
|
32
|
+
origin?: string;
|
|
33
|
+
/** Called when the script cannot load or the options are refused. Thrown to the console otherwise. */
|
|
34
|
+
onError?: (error: Error) => void;
|
|
35
|
+
className?: string;
|
|
36
|
+
style?: CSSProperties;
|
|
37
|
+
id?: string;
|
|
38
|
+
}
|
|
39
|
+
export declare function DeliverdDecision(props: DeliverdDecisionProps): ReactElement;
|
|
40
|
+
//# sourceMappingURL=react.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"react.d.ts","sourceRoot":"","sources":["../src/react.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,EAAoC,KAAK,aAAa,EAAE,KAAK,YAAY,EAAE,MAAM,OAAO,CAAC;AAChG,OAAO,EAIL,KAAK,oBAAoB,EAE1B,MAAM,eAAe,CAAC;AAEvB,YAAY,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAEnD,MAAM,WAAW,qBACf,SAAQ,IAAI,CACV,oBAAoB,EACpB,cAAc,GAAG,MAAM,GAAG,OAAO,GAAG,WAAW,GAAG,YAAY,GAAG,SAAS,GAAG,YAAY,GAAG,WAAW,GAAG,WAAW,CACtH;IACD,oGAAoG;IACpG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,sGAAsG;IACtG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,EAAE,CAAC,EAAE,MAAM,CAAC;CACb;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,qBAAqB,GAAG,YAAY,CAiD3E"}
|