@deliverd/sdk 0.34.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/README.md +16 -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/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +1492 -0
- package/package.json +1 -1
- package/src/adapters/claude-managed-agents.ts +293 -0
- package/src/adapters/index.ts +13 -0
- package/src/released.ts +1493 -0
package/package.json
CHANGED
|
@@ -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
|
+
}
|
package/src/adapters/index.ts
CHANGED
|
@@ -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";
|