@deliverd/sdk 0.11.1 → 0.12.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.
@@ -1,202 +1,202 @@
1
- import { durationMs, type Duration } from "../duration.js";
2
- import type { ApprovalFactor, ApprovalRisk, CallbackEnvelope, FieldChange } from "../types.js";
3
-
4
- /**
5
- * LangGraph: pause a graph on a person's decision, and wake it with a
6
- * callback instead of a process waiting on it.
7
- *
8
- * Inside a node, instead of blocking on `deliverd.approve()`:
9
- *
10
- * ```ts
11
- * import { interrupt } from "@langchain/langgraph";
12
- * import { approveInGraph } from "@deliverd/sdk/adapters";
13
- *
14
- * async function refund(state, config) {
15
- * const decision = await approveInGraph(deliverd, {
16
- * interrupt,
17
- * threadId: config.configurable.thread_id,
18
- * step: "refund",
19
- * title: `Refund £${state.amount} to ${state.customer}`,
20
- * approvers: ["finance"],
21
- * callbackUrl: "https://agent.example.com/hooks/deliverd",
22
- * });
23
- * if (!decision.approved) return { refunded: false, reason: decision.note };
24
- * …
25
- * }
26
- * ```
27
- *
28
- * And where the callback lands:
29
- *
30
- * ```ts
31
- * import { Command } from "@langchain/langgraph";
32
- * import { resumeFromCallback } from "@deliverd/sdk/adapters";
33
- *
34
- * const envelope = deliverd.webhooks.constructCallback(secret, rawBody, signature);
35
- * const resume = resumeFromCallback(envelope);
36
- * if (resume) await graph.invoke(new Command({ resume: resume.value }), { configurable: { thread_id: resume.threadId } });
37
- * ```
38
- *
39
- * **Why it is safe to re-run.** LangGraph resumes a node from its first line.
40
- * The request is keyed by `externalId` (`langgraph:<thread>:<step>`), so the
41
- * second run finds the request the first one made rather than filing another,
42
- * sees it settled, and returns without interrupting again. A resume that
43
- * arrives early — before anyone decided — re-reads the request, finds it
44
- * still pending and returns `approved: false, status: "pending"`: the
45
- * decision is always Deliverd's record, never the resume value, so a stray
46
- * resume can never approve anything.
47
- *
48
- * `interrupt` is passed in rather than imported, so this package keeps no
49
- * dependency on LangGraph. Its signature follows `interrupt` in
50
- * `@langchain/langgraph`'s type definitions.
51
- */
52
-
53
- /** The parts of the Deliverd client this adapter uses. */
54
- export interface GraphApprover {
55
- approvals: {
56
- findByExternalId(externalId: string): Promise<GraphApprovalRecord | null>;
57
- create(input: {
58
- title: string;
59
- description?: string;
60
- risk?: ApprovalRisk;
61
- factors?: ApprovalFactor[];
62
- approvers?: string[];
63
- externalId: string;
64
- expiresAt?: string;
65
- callbackUrl?: string;
66
- metadata?: Record<string, unknown>;
67
- flowId?: string;
68
- input?: Record<string, unknown>;
69
- editableFields?: string[];
70
- }): Promise<GraphApprovalRecord & { callbackSecret: string | null }>;
71
- };
72
- }
73
-
74
- /** The request as this adapter reads it back. */
75
- export interface GraphApprovalRecord {
76
- id: string;
77
- status: string;
78
- url: string;
79
- note: string | null;
80
- decidedBy: string | null;
81
- approvedInput?: Record<string, unknown> | null;
82
- changes?: FieldChange[];
83
- }
84
-
85
- export interface GraphDecision {
86
- approved: boolean;
87
- status: string;
88
- note: string | null;
89
- decidedBy: string | null;
90
- approvalId: string;
91
- url: string;
92
- /**
93
- * What to run with, when an `input` was sent and approved: with the
94
- * approver's corrections. Null otherwise.
95
- */
96
- input: Record<string, unknown> | null;
97
- changes: FieldChange[];
98
- }
99
-
100
- /** What the graph is paused on, as `interrupt` receives it. */
101
- export interface DeliverdInterruptValue {
102
- deliverd: { approvalId: string; url: string };
103
- }
104
-
105
- /**
106
- * Every graph request's `externalId` starts with this; the thread and step
107
- * follow, and are what a callback is matched back to (callbacks carry the
108
- * `externalId`, which is set by this adapter and nothing else).
109
- */
110
- const PREFIX = "langgraph:";
111
-
112
- export async function approveInGraph(
113
- deliverd: GraphApprover,
114
- options: {
115
- /** `interrupt` from `@langchain/langgraph`. */
116
- interrupt: (value: DeliverdInterruptValue) => unknown;
117
- /** The graph's thread: `config.configurable.thread_id`. */
118
- threadId: string;
119
- /** A name for this point in the graph, unique within the thread. No colons. */
120
- step: string;
121
- title: string;
122
- description?: string;
123
- risk?: ApprovalRisk;
124
- factors?: ApprovalFactor[];
125
- approvers?: string[];
126
- /** Where Deliverd POSTs the decision; pair with `resumeFromCallback`. */
127
- callbackUrl?: string;
128
- /** How long the request stays open. Default a day. */
129
- expiresIn?: Duration;
130
- flowId?: string;
131
- /** The arguments the node will run with, shown to the approver. */
132
- input?: Record<string, unknown>;
133
- /** Fields of `input` the approver may correct; the decision's `input` has them. */
134
- editableFields?: string[];
135
- /** Called once, when the request is first made, with the secret its callback is signed with. */
136
- onCreated?: (created: { approvalId: string; url: string; callbackSecret: string | null }) => void | Promise<void>;
137
- }
138
- ): Promise<GraphDecision> {
139
- if (options.step.includes(":")) {
140
- throw new Error(`step must not contain ":" (got "${options.step}"): it is how the thread is found again.`);
141
- }
142
- const externalId = `${PREFIX}${options.threadId}:${options.step}`;
143
- let approval = await deliverd.approvals.findByExternalId(externalId);
144
- if (!approval) {
145
- const created = await deliverd.approvals.create({
146
- title: options.title,
147
- description: options.description,
148
- risk: options.risk,
149
- factors: options.factors,
150
- approvers: options.approvers,
151
- externalId,
152
- expiresAt: new Date(Date.now() + durationMs(options.expiresIn ?? "24h")).toISOString(),
153
- callbackUrl: options.callbackUrl,
154
- metadata: { langgraph: { threadId: options.threadId, step: options.step } },
155
- flowId: options.flowId,
156
- input: options.input,
157
- editableFields: options.editableFields,
158
- });
159
- await options.onCreated?.({ approvalId: created.id, url: created.url, callbackSecret: created.callbackSecret });
160
- approval = created;
161
- }
162
-
163
- if (approval.status === "pending") {
164
- // Pauses the graph on the first run. It returns only when the graph is
165
- // resumed, and what it returns is not trusted: the request is re-read.
166
- options.interrupt({ deliverd: { approvalId: approval.id, url: approval.url } });
167
- approval = (await deliverd.approvals.findByExternalId(externalId)) ?? approval;
168
- }
169
-
170
- return {
171
- approved: approval.status === "approved",
172
- status: approval.status,
173
- note: approval.note,
174
- decidedBy: approval.decidedBy,
175
- approvalId: approval.id,
176
- url: approval.url,
177
- input: approval.status === "approved" ? (approval.approvedInput ?? options.input ?? null) : null,
178
- changes: approval.changes ?? [],
179
- };
180
- }
181
-
182
- /**
183
- * The thread to resume and the value to resume it with, from a verified
184
- * callback. Null for a callback that is not about a graph's approval, and
185
- * for a question — the graph stays paused until the request settles.
186
- */
187
- export function resumeFromCallback(
188
- envelope: CallbackEnvelope
189
- ): { threadId: string; step: string; value: { approvalId: string; status: string } } | null {
190
- if (envelope.requestType !== "approval" || envelope.event === "approval.question") return null;
191
- const externalId = envelope.data.externalId;
192
- if (typeof externalId !== "string" || !externalId.startsWith(PREFIX)) return null;
193
- const rest = externalId.slice(PREFIX.length);
194
- const cut = rest.lastIndexOf(":");
195
- if (cut <= 0 || cut === rest.length - 1) return null;
196
- return {
197
- threadId: rest.slice(0, cut),
198
- step: rest.slice(cut + 1),
199
- value: { approvalId: envelope.requestId, status: String(envelope.data.status ?? envelope.event.split(".")[1]) },
200
- };
201
- }
202
-
1
+ import { durationMs, type Duration } from "../duration.js";
2
+ import type { ApprovalFactor, ApprovalRisk, CallbackEnvelope, FieldChange } from "../types.js";
3
+
4
+ /**
5
+ * LangGraph: pause a graph on a person's decision, and wake it with a
6
+ * callback instead of a process waiting on it.
7
+ *
8
+ * Inside a node, instead of blocking on `deliverd.approve()`:
9
+ *
10
+ * ```ts
11
+ * import { interrupt } from "@langchain/langgraph";
12
+ * import { approveInGraph } from "@deliverd/sdk/adapters";
13
+ *
14
+ * async function refund(state, config) {
15
+ * const decision = await approveInGraph(deliverd, {
16
+ * interrupt,
17
+ * threadId: config.configurable.thread_id,
18
+ * step: "refund",
19
+ * title: `Refund £${state.amount} to ${state.customer}`,
20
+ * approvers: ["finance"],
21
+ * callbackUrl: "https://agent.example.com/hooks/deliverd",
22
+ * });
23
+ * if (!decision.approved) return { refunded: false, reason: decision.note };
24
+ * …
25
+ * }
26
+ * ```
27
+ *
28
+ * And where the callback lands:
29
+ *
30
+ * ```ts
31
+ * import { Command } from "@langchain/langgraph";
32
+ * import { resumeFromCallback } from "@deliverd/sdk/adapters";
33
+ *
34
+ * const envelope = deliverd.webhooks.constructCallback(secret, rawBody, signature);
35
+ * const resume = resumeFromCallback(envelope);
36
+ * if (resume) await graph.invoke(new Command({ resume: resume.value }), { configurable: { thread_id: resume.threadId } });
37
+ * ```
38
+ *
39
+ * **Why it is safe to re-run.** LangGraph resumes a node from its first line.
40
+ * The request is keyed by `externalId` (`langgraph:<thread>:<step>`), so the
41
+ * second run finds the request the first one made rather than filing another,
42
+ * sees it settled, and returns without interrupting again. A resume that
43
+ * arrives early — before anyone decided — re-reads the request, finds it
44
+ * still pending and returns `approved: false, status: "pending"`: the
45
+ * decision is always Deliverd's record, never the resume value, so a stray
46
+ * resume can never approve anything.
47
+ *
48
+ * `interrupt` is passed in rather than imported, so this package keeps no
49
+ * dependency on LangGraph. Its signature follows `interrupt` in
50
+ * `@langchain/langgraph`'s type definitions.
51
+ */
52
+
53
+ /** The parts of the Deliverd client this adapter uses. */
54
+ export interface GraphApprover {
55
+ approvals: {
56
+ findByExternalId(externalId: string): Promise<GraphApprovalRecord | null>;
57
+ create(input: {
58
+ title: string;
59
+ description?: string;
60
+ risk?: ApprovalRisk;
61
+ factors?: ApprovalFactor[];
62
+ approvers?: string[];
63
+ externalId: string;
64
+ expiresAt?: string;
65
+ callbackUrl?: string;
66
+ metadata?: Record<string, unknown>;
67
+ flowId?: string;
68
+ input?: Record<string, unknown>;
69
+ editableFields?: string[];
70
+ }): Promise<GraphApprovalRecord & { callbackSecret: string | null }>;
71
+ };
72
+ }
73
+
74
+ /** The request as this adapter reads it back. */
75
+ export interface GraphApprovalRecord {
76
+ id: string;
77
+ status: string;
78
+ url: string;
79
+ note: string | null;
80
+ decidedBy: string | null;
81
+ approvedInput?: Record<string, unknown> | null;
82
+ changes?: FieldChange[];
83
+ }
84
+
85
+ export interface GraphDecision {
86
+ approved: boolean;
87
+ status: string;
88
+ note: string | null;
89
+ decidedBy: string | null;
90
+ approvalId: string;
91
+ url: string;
92
+ /**
93
+ * What to run with, when an `input` was sent and approved: with the
94
+ * approver's corrections. Null otherwise.
95
+ */
96
+ input: Record<string, unknown> | null;
97
+ changes: FieldChange[];
98
+ }
99
+
100
+ /** What the graph is paused on, as `interrupt` receives it. */
101
+ export interface DeliverdInterruptValue {
102
+ deliverd: { approvalId: string; url: string };
103
+ }
104
+
105
+ /**
106
+ * Every graph request's `externalId` starts with this; the thread and step
107
+ * follow, and are what a callback is matched back to (callbacks carry the
108
+ * `externalId`, which is set by this adapter and nothing else).
109
+ */
110
+ const PREFIX = "langgraph:";
111
+
112
+ export async function approveInGraph(
113
+ deliverd: GraphApprover,
114
+ options: {
115
+ /** `interrupt` from `@langchain/langgraph`. */
116
+ interrupt: (value: DeliverdInterruptValue) => unknown;
117
+ /** The graph's thread: `config.configurable.thread_id`. */
118
+ threadId: string;
119
+ /** A name for this point in the graph, unique within the thread. No colons. */
120
+ step: string;
121
+ title: string;
122
+ description?: string;
123
+ risk?: ApprovalRisk;
124
+ factors?: ApprovalFactor[];
125
+ approvers?: string[];
126
+ /** Where Deliverd POSTs the decision; pair with `resumeFromCallback`. */
127
+ callbackUrl?: string;
128
+ /** How long the request stays open. Default a day. */
129
+ expiresIn?: Duration;
130
+ flowId?: string;
131
+ /** The arguments the node will run with, shown to the approver. */
132
+ input?: Record<string, unknown>;
133
+ /** Fields of `input` the approver may correct; the decision's `input` has them. */
134
+ editableFields?: string[];
135
+ /** Called once, when the request is first made, with the secret its callback is signed with. */
136
+ onCreated?: (created: { approvalId: string; url: string; callbackSecret: string | null }) => void | Promise<void>;
137
+ }
138
+ ): Promise<GraphDecision> {
139
+ if (options.step.includes(":")) {
140
+ throw new Error(`step must not contain ":" (got "${options.step}"): it is how the thread is found again.`);
141
+ }
142
+ const externalId = `${PREFIX}${options.threadId}:${options.step}`;
143
+ let approval = await deliverd.approvals.findByExternalId(externalId);
144
+ if (!approval) {
145
+ const created = await deliverd.approvals.create({
146
+ title: options.title,
147
+ description: options.description,
148
+ risk: options.risk,
149
+ factors: options.factors,
150
+ approvers: options.approvers,
151
+ externalId,
152
+ expiresAt: new Date(Date.now() + durationMs(options.expiresIn ?? "24h")).toISOString(),
153
+ callbackUrl: options.callbackUrl,
154
+ metadata: { langgraph: { threadId: options.threadId, step: options.step } },
155
+ flowId: options.flowId,
156
+ input: options.input,
157
+ editableFields: options.editableFields,
158
+ });
159
+ await options.onCreated?.({ approvalId: created.id, url: created.url, callbackSecret: created.callbackSecret });
160
+ approval = created;
161
+ }
162
+
163
+ if (approval.status === "pending") {
164
+ // Pauses the graph on the first run. It returns only when the graph is
165
+ // resumed, and what it returns is not trusted: the request is re-read.
166
+ options.interrupt({ deliverd: { approvalId: approval.id, url: approval.url } });
167
+ approval = (await deliverd.approvals.findByExternalId(externalId)) ?? approval;
168
+ }
169
+
170
+ return {
171
+ approved: approval.status === "approved",
172
+ status: approval.status,
173
+ note: approval.note,
174
+ decidedBy: approval.decidedBy,
175
+ approvalId: approval.id,
176
+ url: approval.url,
177
+ input: approval.status === "approved" ? (approval.approvedInput ?? options.input ?? null) : null,
178
+ changes: approval.changes ?? [],
179
+ };
180
+ }
181
+
182
+ /**
183
+ * The thread to resume and the value to resume it with, from a verified
184
+ * callback. Null for a callback that is not about a graph's approval, and
185
+ * for a question — the graph stays paused until the request settles.
186
+ */
187
+ export function resumeFromCallback(
188
+ envelope: CallbackEnvelope
189
+ ): { threadId: string; step: string; value: { approvalId: string; status: string } } | null {
190
+ if (envelope.requestType !== "approval" || envelope.event === "approval.question") return null;
191
+ const externalId = envelope.data.externalId;
192
+ if (typeof externalId !== "string" || !externalId.startsWith(PREFIX)) return null;
193
+ const rest = externalId.slice(PREFIX.length);
194
+ const cut = rest.lastIndexOf(":");
195
+ if (cut <= 0 || cut === rest.length - 1) return null;
196
+ return {
197
+ threadId: rest.slice(0, cut),
198
+ step: rest.slice(cut + 1),
199
+ value: { approvalId: envelope.requestId, status: String(envelope.data.status ?? envelope.event.split(".")[1]) },
200
+ };
201
+ }
202
+
@@ -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
+ }