@deliverd/sdk 0.10.0 → 0.11.1

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.
@@ -1,112 +1,112 @@
1
- import { askAboutCall, type ToolApprovalOptions } from "./shared.js";
2
-
3
- /**
4
- * The OpenAI Agents SDK: a person resolves the run's approval interruptions,
5
- * through Deliverd.
6
- *
7
- * Mark the tools that need a person with `needsApproval: true` as usual; a run
8
- * then stops with `result.interruptions`. Instead of building your own prompt:
9
- *
10
- * ```ts
11
- * import { Agent, run } from "@openai/agents";
12
- * import { Deliverd } from "@deliverd/sdk";
13
- * import { runWithDeliverdApprovals } from "@deliverd/sdk/adapters";
14
- *
15
- * const result = await runWithDeliverdApprovals(
16
- * (input) => run(agent, input),
17
- * "Refund order 1042",
18
- * { deliverd: new Deliverd(), approvers: ["finance"] }
19
- * );
20
- * ```
21
- *
22
- * Each interruption becomes a request in Deliverd; approved ones are
23
- * `state.approve(item)`, declined ones `state.reject(item, { message })` with
24
- * the person's reason, and the run resumes from its state until nothing is
25
- * waiting. `resolveInterruptions` does one round, for a loop you own.
26
- *
27
- * Shapes follow `RunToolApprovalItem`, `RunState.approve` / `reject` and
28
- * `RunResult.interruptions` in `@openai/agents-core`'s type definitions.
29
- */
30
-
31
- /** The part of a `RunToolApprovalItem` this adapter reads. */
32
- export interface OpenAiApprovalItem {
33
- name?: string;
34
- arguments?: string;
35
- rawItem?: { callId?: string; id?: string; name?: string };
36
- }
37
-
38
- /** The part of a run result this adapter reads and resolves. */
39
- export interface OpenAiInterruptedResult<Item extends OpenAiApprovalItem = OpenAiApprovalItem, State = unknown> {
40
- interruptions: Item[];
41
- state: State & {
42
- approve(item: Item, options?: { alwaysApprove?: boolean }): void;
43
- reject(item: Item, options?: { alwaysReject?: boolean; message?: string }): void;
44
- };
45
- }
46
-
47
- /** Ask about every interruption in a result, and record each answer on its state. */
48
- export async function resolveInterruptions<Item extends OpenAiApprovalItem>(
49
- result: OpenAiInterruptedResult<Item>,
50
- options: ToolApprovalOptions
51
- ): Promise<{ approved: number; rejected: number }> {
52
- let approved = 0;
53
- let rejected = 0;
54
- for (const item of result.interruptions) {
55
- const toolName = item.name ?? item.rawItem?.name ?? "a tool";
56
- const input = parseArguments(item.arguments);
57
- if (options.when && !(await options.when(toolName, input))) {
58
- result.state.approve(item);
59
- approved += 1;
60
- continue;
61
- }
62
- const callId = item.rawItem?.callId ?? item.rawItem?.id ?? `${toolName}:${item.arguments ?? ""}`;
63
- const outcome = await askAboutCall(toolName, input, `openai-agents:${callId}`, options);
64
- if (outcome.allowed) {
65
- result.state.approve(item);
66
- approved += 1;
67
- } else {
68
- result.state.reject(item, { message: outcome.reason });
69
- rejected += 1;
70
- }
71
- }
72
- return { approved, rejected };
73
- }
74
-
75
- /**
76
- * Run until nothing is waiting on a person.
77
- *
78
- * `runOnce` is your call to the SDK's `run(agent, input)`; it is called
79
- * first with `input`, then with the result's state after each round of
80
- * decisions. A cap on rounds stops an agent that keeps asking from waiting
81
- * forever.
82
- */
83
- export async function runWithDeliverdApprovals<
84
- Result extends OpenAiInterruptedResult<Item>,
85
- Item extends OpenAiApprovalItem = OpenAiApprovalItem,
86
- Input = unknown,
87
- >(
88
- runOnce: (input: Input | Result["state"]) => Promise<Result>,
89
- input: Input,
90
- options: ToolApprovalOptions & { maxRounds?: number }
91
- ): Promise<Result> {
92
- let result = await runOnce(input);
93
- for (let round = 0; result.interruptions.length > 0; round++) {
94
- if (round >= (options.maxRounds ?? 10)) {
95
- throw new Error(
96
- `The run was still waiting for approval after ${options.maxRounds ?? 10} rounds; stopping rather than asking forever.`
97
- );
98
- }
99
- await resolveInterruptions(result, options);
100
- result = await runOnce(result.state);
101
- }
102
- return result;
103
- }
104
-
105
- function parseArguments(raw: string | undefined): unknown {
106
- if (!raw) return {};
107
- try {
108
- return JSON.parse(raw);
109
- } catch {
110
- return raw;
111
- }
112
- }
1
+ import { askAboutCall, type ToolApprovalOptions } from "./shared.js";
2
+
3
+ /**
4
+ * The OpenAI Agents SDK: a person resolves the run's approval interruptions,
5
+ * through Deliverd.
6
+ *
7
+ * Mark the tools that need a person with `needsApproval: true` as usual; a run
8
+ * then stops with `result.interruptions`. Instead of building your own prompt:
9
+ *
10
+ * ```ts
11
+ * import { Agent, run } from "@openai/agents";
12
+ * import { Deliverd } from "@deliverd/sdk";
13
+ * import { runWithDeliverdApprovals } from "@deliverd/sdk/adapters";
14
+ *
15
+ * const result = await runWithDeliverdApprovals(
16
+ * (input) => run(agent, input),
17
+ * "Refund order 1042",
18
+ * { deliverd: new Deliverd(), approvers: ["finance"] }
19
+ * );
20
+ * ```
21
+ *
22
+ * Each interruption becomes a request in Deliverd; approved ones are
23
+ * `state.approve(item)`, declined ones `state.reject(item, { message })` with
24
+ * the person's reason, and the run resumes from its state until nothing is
25
+ * waiting. `resolveInterruptions` does one round, for a loop you own.
26
+ *
27
+ * Shapes follow `RunToolApprovalItem`, `RunState.approve` / `reject` and
28
+ * `RunResult.interruptions` in `@openai/agents-core`'s type definitions.
29
+ */
30
+
31
+ /** The part of a `RunToolApprovalItem` this adapter reads. */
32
+ export interface OpenAiApprovalItem {
33
+ name?: string;
34
+ arguments?: string;
35
+ rawItem?: { callId?: string; id?: string; name?: string };
36
+ }
37
+
38
+ /** The part of a run result this adapter reads and resolves. */
39
+ export interface OpenAiInterruptedResult<Item extends OpenAiApprovalItem = OpenAiApprovalItem, State = unknown> {
40
+ interruptions: Item[];
41
+ state: State & {
42
+ approve(item: Item, options?: { alwaysApprove?: boolean }): void;
43
+ reject(item: Item, options?: { alwaysReject?: boolean; message?: string }): void;
44
+ };
45
+ }
46
+
47
+ /** Ask about every interruption in a result, and record each answer on its state. */
48
+ export async function resolveInterruptions<Item extends OpenAiApprovalItem>(
49
+ result: OpenAiInterruptedResult<Item>,
50
+ options: ToolApprovalOptions
51
+ ): Promise<{ approved: number; rejected: number }> {
52
+ let approved = 0;
53
+ let rejected = 0;
54
+ for (const item of result.interruptions) {
55
+ const toolName = item.name ?? item.rawItem?.name ?? "a tool";
56
+ const input = parseArguments(item.arguments);
57
+ if (options.when && !(await options.when(toolName, input))) {
58
+ result.state.approve(item);
59
+ approved += 1;
60
+ continue;
61
+ }
62
+ const callId = item.rawItem?.callId ?? item.rawItem?.id ?? `${toolName}:${item.arguments ?? ""}`;
63
+ const outcome = await askAboutCall(toolName, input, `openai-agents:${callId}`, options);
64
+ if (outcome.allowed) {
65
+ result.state.approve(item);
66
+ approved += 1;
67
+ } else {
68
+ result.state.reject(item, { message: outcome.reason });
69
+ rejected += 1;
70
+ }
71
+ }
72
+ return { approved, rejected };
73
+ }
74
+
75
+ /**
76
+ * Run until nothing is waiting on a person.
77
+ *
78
+ * `runOnce` is your call to the SDK's `run(agent, input)`; it is called
79
+ * first with `input`, then with the result's state after each round of
80
+ * decisions. A cap on rounds stops an agent that keeps asking from waiting
81
+ * forever.
82
+ */
83
+ export async function runWithDeliverdApprovals<
84
+ Result extends OpenAiInterruptedResult<Item>,
85
+ Item extends OpenAiApprovalItem = OpenAiApprovalItem,
86
+ Input = unknown,
87
+ >(
88
+ runOnce: (input: Input | Result["state"]) => Promise<Result>,
89
+ input: Input,
90
+ options: ToolApprovalOptions & { maxRounds?: number }
91
+ ): Promise<Result> {
92
+ let result = await runOnce(input);
93
+ for (let round = 0; result.interruptions.length > 0; round++) {
94
+ if (round >= (options.maxRounds ?? 10)) {
95
+ throw new Error(
96
+ `The run was still waiting for approval after ${options.maxRounds ?? 10} rounds; stopping rather than asking forever.`
97
+ );
98
+ }
99
+ await resolveInterruptions(result, options);
100
+ result = await runOnce(result.state);
101
+ }
102
+ return result;
103
+ }
104
+
105
+ function parseArguments(raw: string | undefined): unknown {
106
+ if (!raw) return {};
107
+ try {
108
+ return JSON.parse(raw);
109
+ } catch {
110
+ return raw;
111
+ }
112
+ }
@@ -1,179 +1,179 @@
1
- import { DeliverdTimeoutError } from "../errors.js";
2
- import type { Duration } from "../duration.js";
3
- import type { ApprovalFactor, ApprovalRisk, Decision, FieldChange } from "../types.js";
4
-
5
- /**
6
- * What the framework adapters share: how a tool call becomes a request, and
7
- * what the answer becomes.
8
- *
9
- * The adapters are written against each framework's own hook — the Claude
10
- * Agent SDK's `canUseTool`, the AI SDK's `toolApproval`, the OpenAI Agents
11
- * SDK's interruptions, LangGraph's `interrupt` — by shape rather than by
12
- * import, so `@deliverd/sdk` keeps its promise of no dependencies. Each
13
- * shape was taken from that framework's published type definitions and is
14
- * checked against them in this package's tests.
15
- */
16
-
17
- /** Anything with Deliverd's `approve()`: the client, or a test double. */
18
- export interface Approver {
19
- approve(options: {
20
- title: string;
21
- description?: string;
22
- risk?: ApprovalRisk;
23
- factors?: ApprovalFactor[];
24
- approvers?: string[];
25
- externalId?: string;
26
- flowId?: string;
27
- metadata?: Record<string, unknown>;
28
- callbackUrl?: string;
29
- input?: Record<string, unknown>;
30
- editableFields?: string[];
31
- expiresIn?: Duration;
32
- timeout?: Duration;
33
- signal?: AbortSignal;
34
- }): Promise<Decision>;
35
- }
36
-
37
- /** What a person is shown about one tool call. */
38
- export interface CallDescription {
39
- title: string;
40
- description?: string;
41
- risk?: ApprovalRisk;
42
- factors?: ApprovalFactor[];
43
- }
44
-
45
- export interface ToolApprovalOptions {
46
- /** The client: `new Deliverd()`. */
47
- deliverd: Approver;
48
- /**
49
- * Which calls need a person. Every call when omitted — so name the few
50
- * that matter: `when: (tool) => ["send_email", "refund"].includes(tool)`.
51
- */
52
- when?: (toolName: string, input: unknown) => boolean | Promise<boolean>;
53
- /** Who may decide: people, teams, groups. The organisation's admins when omitted. */
54
- approvers?: string[];
55
- /** What the approver reads. A readable default is built from the tool and its input. */
56
- describe?: (toolName: string, input: unknown) => CallDescription;
57
- /** How long the request stays open. Default one hour: an agent is waiting. */
58
- expiresIn?: Duration;
59
- /** Give up waiting after this and refuse the call. Defaults to the request's own expiry. */
60
- timeout?: Duration;
61
- /** The flow this run belongs to, so every call it asked about is on one timeline. */
62
- flowId?: string;
63
- metadata?: Record<string, unknown>;
64
- }
65
-
66
- /**
67
- * The tool input as the approver sees it: its arguments, shown field by field
68
- * on the approval page, when it is a plain object of a sensible size. Larger
69
- * or odd-shaped input is still in the description, just not structured.
70
- */
71
- const INPUT_MAX = 8000;
72
- export function structuredInput(input: unknown): Record<string, unknown> | undefined {
73
- if (typeof input !== "object" || input === null || Array.isArray(input)) return undefined;
74
- try {
75
- return JSON.stringify(input).length <= INPUT_MAX ? (input as Record<string, unknown>) : undefined;
76
- } catch {
77
- return undefined;
78
- }
79
- }
80
-
81
- export const DEFAULT_TOOL_EXPIRY: Duration = "1h";
82
- const INPUT_PREVIEW_MAX = 3000;
83
-
84
- /** A plain account of a call, for when the caller did not write one. */
85
- export function defaultDescription(toolName: string, input: unknown): CallDescription {
86
- let rendered: string;
87
- try {
88
- rendered = typeof input === "string" ? input : JSON.stringify(input, null, 2);
89
- } catch {
90
- rendered = String(input);
91
- }
92
- if (rendered && rendered.length > INPUT_PREVIEW_MAX) rendered = `${rendered.slice(0, INPUT_PREVIEW_MAX - 1)}…`;
93
- return {
94
- title: `Allow the agent to run ${toolName}`,
95
- description: rendered ? `With this input:\n\n${rendered}` : undefined,
96
- risk: "medium",
97
- };
98
- }
99
-
100
- /** The answer an adapter hands back to its framework. */
101
- export type CallOutcome =
102
- | {
103
- allowed: true;
104
- decidedBy: string | null;
105
- note: string | null;
106
- /** What to run with: the approver's correction, when they made one. */
107
- input: Record<string, unknown> | null;
108
- changes: FieldChange[];
109
- }
110
- | { allowed: false; reason: string };
111
-
112
- /**
113
- * Ask about one call and wait.
114
- *
115
- * `externalId` makes the ask idempotent: a framework that retries a step, or
116
- * a process that restarts mid-wait, finds the request it already made instead
117
- * of filing a second one (`approve()` reuses by `externalId`).
118
- *
119
- * A refusal, an expiry and a wait that ran out are all "not allowed", each
120
- * with a sentence the model can read and act on — never a thrown error, which
121
- * most frameworks would turn into a crashed run rather than a declined call.
122
- */
123
- export async function askAboutCall(
124
- toolName: string,
125
- input: unknown,
126
- externalId: string,
127
- options: ToolApprovalOptions,
128
- signal?: AbortSignal,
129
- /** Fields a person may correct. Only for a framework that can run a corrected call. */
130
- editableFields?: string[]
131
- ): Promise<CallOutcome> {
132
- const described = (options.describe ?? defaultDescription)(toolName, input);
133
- const structured = structuredInput(input);
134
- let decision: Decision;
135
- try {
136
- decision = await options.deliverd.approve({
137
- ...described,
138
- approvers: options.approvers,
139
- externalId,
140
- flowId: options.flowId,
141
- metadata: { ...options.metadata, tool: toolName },
142
- ...(structured ? { input: structured } : {}),
143
- ...(structured && editableFields?.length
144
- ? { editableFields: editableFields.filter((field) => field in structured) }
145
- : {}),
146
- expiresIn: options.expiresIn ?? DEFAULT_TOOL_EXPIRY,
147
- timeout: options.timeout,
148
- signal,
149
- });
150
- } catch (err) {
151
- if (err instanceof DeliverdTimeoutError) {
152
- return { allowed: false, reason: `Nobody decided whether to run ${toolName} in time, so it was not run.` };
153
- }
154
- throw err;
155
- }
156
- if (decision.approved) {
157
- return {
158
- allowed: true,
159
- decidedBy: decision.decidedBy,
160
- note: decision.note,
161
- input: decision.input ?? null,
162
- changes: decision.changes ?? [],
163
- };
164
- }
165
- return { allowed: false, reason: refusalReason(toolName, decision) };
166
- }
167
-
168
- export function refusalReason(toolName: string, decision: Pick<Decision, "status" | "note" | "decidedBy">): string {
169
- const who = decision.decidedBy ? ` by ${decision.decidedBy}` : "";
170
- const why = decision.note ? ` Their reason: ${decision.note}` : "";
171
- switch (decision.status) {
172
- case "rejected":
173
- return `A person declined running ${toolName}${who}.${why} Do not retry it; change course or ask how to proceed.`;
174
- case "expired":
175
- return `Nobody decided whether to run ${toolName} before the request expired, so it was not run.`;
176
- default:
177
- return `The request to run ${toolName} was withdrawn, so it was not run.`;
178
- }
179
- }
1
+ import { DeliverdTimeoutError } from "../errors.js";
2
+ import type { Duration } from "../duration.js";
3
+ import type { ApprovalFactor, ApprovalRisk, Decision, FieldChange } from "../types.js";
4
+
5
+ /**
6
+ * What the framework adapters share: how a tool call becomes a request, and
7
+ * what the answer becomes.
8
+ *
9
+ * The adapters are written against each framework's own hook — the Claude
10
+ * Agent SDK's `canUseTool`, the AI SDK's `toolApproval`, the OpenAI Agents
11
+ * SDK's interruptions, LangGraph's `interrupt` — by shape rather than by
12
+ * import, so `@deliverd/sdk` keeps its promise of no dependencies. Each
13
+ * shape was taken from that framework's published type definitions and is
14
+ * checked against them in this package's tests.
15
+ */
16
+
17
+ /** Anything with Deliverd's `approve()`: the client, or a test double. */
18
+ export interface Approver {
19
+ approve(options: {
20
+ title: string;
21
+ description?: string;
22
+ risk?: ApprovalRisk;
23
+ factors?: ApprovalFactor[];
24
+ approvers?: string[];
25
+ externalId?: string;
26
+ flowId?: string;
27
+ metadata?: Record<string, unknown>;
28
+ callbackUrl?: string;
29
+ input?: Record<string, unknown>;
30
+ editableFields?: string[];
31
+ expiresIn?: Duration;
32
+ timeout?: Duration;
33
+ signal?: AbortSignal;
34
+ }): Promise<Decision>;
35
+ }
36
+
37
+ /** What a person is shown about one tool call. */
38
+ export interface CallDescription {
39
+ title: string;
40
+ description?: string;
41
+ risk?: ApprovalRisk;
42
+ factors?: ApprovalFactor[];
43
+ }
44
+
45
+ export interface ToolApprovalOptions {
46
+ /** The client: `new Deliverd()`. */
47
+ deliverd: Approver;
48
+ /**
49
+ * Which calls need a person. Every call when omitted — so name the few
50
+ * that matter: `when: (tool) => ["send_email", "refund"].includes(tool)`.
51
+ */
52
+ when?: (toolName: string, input: unknown) => boolean | Promise<boolean>;
53
+ /** Who may decide: people, teams, groups. The organisation's admins when omitted. */
54
+ approvers?: string[];
55
+ /** What the approver reads. A readable default is built from the tool and its input. */
56
+ describe?: (toolName: string, input: unknown) => CallDescription;
57
+ /** How long the request stays open. Default one hour: an agent is waiting. */
58
+ expiresIn?: Duration;
59
+ /** Give up waiting after this and refuse the call. Defaults to the request's own expiry. */
60
+ timeout?: Duration;
61
+ /** The flow this run belongs to, so every call it asked about is on one timeline. */
62
+ flowId?: string;
63
+ metadata?: Record<string, unknown>;
64
+ }
65
+
66
+ /**
67
+ * The tool input as the approver sees it: its arguments, shown field by field
68
+ * on the approval page, when it is a plain object of a sensible size. Larger
69
+ * or odd-shaped input is still in the description, just not structured.
70
+ */
71
+ const INPUT_MAX = 8000;
72
+ export function structuredInput(input: unknown): Record<string, unknown> | undefined {
73
+ if (typeof input !== "object" || input === null || Array.isArray(input)) return undefined;
74
+ try {
75
+ return JSON.stringify(input).length <= INPUT_MAX ? (input as Record<string, unknown>) : undefined;
76
+ } catch {
77
+ return undefined;
78
+ }
79
+ }
80
+
81
+ export const DEFAULT_TOOL_EXPIRY: Duration = "1h";
82
+ const INPUT_PREVIEW_MAX = 3000;
83
+
84
+ /** A plain account of a call, for when the caller did not write one. */
85
+ export function defaultDescription(toolName: string, input: unknown): CallDescription {
86
+ let rendered: string;
87
+ try {
88
+ rendered = typeof input === "string" ? input : JSON.stringify(input, null, 2);
89
+ } catch {
90
+ rendered = String(input);
91
+ }
92
+ if (rendered && rendered.length > INPUT_PREVIEW_MAX) rendered = `${rendered.slice(0, INPUT_PREVIEW_MAX - 1)}…`;
93
+ return {
94
+ title: `Allow the agent to run ${toolName}`,
95
+ description: rendered ? `With this input:\n\n${rendered}` : undefined,
96
+ risk: "medium",
97
+ };
98
+ }
99
+
100
+ /** The answer an adapter hands back to its framework. */
101
+ export type CallOutcome =
102
+ | {
103
+ allowed: true;
104
+ decidedBy: string | null;
105
+ note: string | null;
106
+ /** What to run with: the approver's correction, when they made one. */
107
+ input: Record<string, unknown> | null;
108
+ changes: FieldChange[];
109
+ }
110
+ | { allowed: false; reason: string };
111
+
112
+ /**
113
+ * Ask about one call and wait.
114
+ *
115
+ * `externalId` makes the ask idempotent: a framework that retries a step, or
116
+ * a process that restarts mid-wait, finds the request it already made instead
117
+ * of filing a second one (`approve()` reuses by `externalId`).
118
+ *
119
+ * A refusal, an expiry and a wait that ran out are all "not allowed", each
120
+ * with a sentence the model can read and act on — never a thrown error, which
121
+ * most frameworks would turn into a crashed run rather than a declined call.
122
+ */
123
+ export async function askAboutCall(
124
+ toolName: string,
125
+ input: unknown,
126
+ externalId: string,
127
+ options: ToolApprovalOptions,
128
+ signal?: AbortSignal,
129
+ /** Fields a person may correct. Only for a framework that can run a corrected call. */
130
+ editableFields?: string[]
131
+ ): Promise<CallOutcome> {
132
+ const described = (options.describe ?? defaultDescription)(toolName, input);
133
+ const structured = structuredInput(input);
134
+ let decision: Decision;
135
+ try {
136
+ decision = await options.deliverd.approve({
137
+ ...described,
138
+ approvers: options.approvers,
139
+ externalId,
140
+ flowId: options.flowId,
141
+ metadata: { ...options.metadata, tool: toolName },
142
+ ...(structured ? { input: structured } : {}),
143
+ ...(structured && editableFields?.length
144
+ ? { editableFields: editableFields.filter((field) => field in structured) }
145
+ : {}),
146
+ expiresIn: options.expiresIn ?? DEFAULT_TOOL_EXPIRY,
147
+ timeout: options.timeout,
148
+ signal,
149
+ });
150
+ } catch (err) {
151
+ if (err instanceof DeliverdTimeoutError) {
152
+ return { allowed: false, reason: `Nobody decided whether to run ${toolName} in time, so it was not run.` };
153
+ }
154
+ throw err;
155
+ }
156
+ if (decision.approved) {
157
+ return {
158
+ allowed: true,
159
+ decidedBy: decision.decidedBy,
160
+ note: decision.note,
161
+ input: decision.input ?? null,
162
+ changes: decision.changes ?? [],
163
+ };
164
+ }
165
+ return { allowed: false, reason: refusalReason(toolName, decision) };
166
+ }
167
+
168
+ export function refusalReason(toolName: string, decision: Pick<Decision, "status" | "note" | "decidedBy">): string {
169
+ const who = decision.decidedBy ? ` by ${decision.decidedBy}` : "";
170
+ const why = decision.note ? ` Their reason: ${decision.note}` : "";
171
+ switch (decision.status) {
172
+ case "rejected":
173
+ return `A person declined running ${toolName}${who}.${why} Do not retry it; change course or ask how to proceed.`;
174
+ case "expired":
175
+ return `Nobody decided whether to run ${toolName} before the request expired, so it was not run.`;
176
+ default:
177
+ return `The request to run ${toolName} was withdrawn, so it was not run.`;
178
+ }
179
+ }