@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,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
+ }