@deliverd/sdk 0.8.2 → 0.10.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.
Files changed (60) hide show
  1. package/README.md +92 -0
  2. package/dist/adapters/ai-sdk.d.ts +48 -0
  3. package/dist/adapters/ai-sdk.d.ts.map +1 -0
  4. package/dist/adapters/ai-sdk.js +12 -0
  5. package/dist/adapters/claude-agent-sdk.d.ts +55 -0
  6. package/dist/adapters/claude-agent-sdk.d.ts.map +1 -0
  7. package/dist/adapters/claude-agent-sdk.js +24 -0
  8. package/dist/adapters/index.d.ts +19 -0
  9. package/dist/adapters/index.d.ts.map +1 -0
  10. package/dist/adapters/index.js +13 -0
  11. package/dist/adapters/langgraph.d.ts +145 -0
  12. package/dist/adapters/langgraph.d.ts.map +1 -0
  13. package/dist/adapters/langgraph.js +69 -0
  14. package/dist/adapters/openai-agents.d.ts +68 -0
  15. package/dist/adapters/openai-agents.d.ts.map +1 -0
  16. package/dist/adapters/openai-agents.js +55 -0
  17. package/dist/adapters/shared.d.ts +91 -0
  18. package/dist/adapters/shared.d.ts.map +1 -0
  19. package/dist/adapters/shared.js +98 -0
  20. package/dist/approvals.d.ts +15 -1
  21. package/dist/approvals.d.ts.map +1 -1
  22. package/dist/approvals.js +19 -1
  23. package/dist/collections.d.ts +8 -0
  24. package/dist/collections.d.ts.map +1 -1
  25. package/dist/collections.js +11 -1
  26. package/dist/dev.d.ts +6 -0
  27. package/dist/dev.d.ts.map +1 -1
  28. package/dist/dev.js +13 -0
  29. package/dist/gates.d.ts.map +1 -1
  30. package/dist/gates.js +1 -0
  31. package/dist/index.d.ts +1 -1
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +1 -1
  34. package/dist/released.d.ts +1 -1
  35. package/dist/released.d.ts.map +1 -1
  36. package/dist/released.js +910 -0
  37. package/dist/reviews.d.ts +8 -0
  38. package/dist/reviews.d.ts.map +1 -1
  39. package/dist/reviews.js +11 -1
  40. package/dist/types.d.ts +93 -1
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/webhooks.d.ts +15 -1
  43. package/dist/webhooks.d.ts.map +1 -1
  44. package/dist/webhooks.js +13 -0
  45. package/package.json +5 -1
  46. package/src/adapters/ai-sdk.ts +59 -0
  47. package/src/adapters/claude-agent-sdk.ts +90 -0
  48. package/src/adapters/index.ts +23 -0
  49. package/src/adapters/langgraph.ts +202 -0
  50. package/src/adapters/openai-agents.ts +112 -0
  51. package/src/adapters/shared.ts +179 -0
  52. package/src/approvals.ts +21 -1
  53. package/src/collections.ts +12 -1
  54. package/src/dev.ts +21 -0
  55. package/src/gates.ts +1 -0
  56. package/src/index.ts +1 -0
  57. package/src/released.ts +910 -0
  58. package/src/reviews.ts +12 -1
  59. package/src/types.ts +96 -1
  60. package/src/webhooks.ts +20 -1
@@ -0,0 +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
+
@@ -0,0 +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
+ }
@@ -0,0 +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
+ }
package/src/approvals.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  ApprovalQuestion,
8
8
  CreateApprovalInput,
9
9
  Decision,
10
+ FieldChange,
10
11
  ListApprovalsInput,
11
12
  } from "./types.js";
12
13
 
@@ -81,6 +82,15 @@ export class Approval {
81
82
  private data: ApprovalData
82
83
  ) {}
83
84
 
85
+ /**
86
+ * The secret this request's callbacks are signed with, when you gave a
87
+ * `callbackUrl`. Only on the handle `create()` returned — the API hands it
88
+ * over once and never again — so keep it with whatever will receive the
89
+ * callback, and check each one with
90
+ * `deliverd.webhooks.constructCallback(callbackSecret, rawBody, signature)`.
91
+ */
92
+ callbackSecret: string | null = null;
93
+
84
94
  get id(): string { return this.data.id; }
85
95
  get status(): ApprovalData["status"] { return this.data.status; }
86
96
  /** The page the approver decides on. Put it in your own UI or logs. */
@@ -92,6 +102,12 @@ export class Approval {
92
102
  get decidedBy(): string | null { return this.data.decidedBy; }
93
103
  get decidedById(): string | null { return this.data.decidedById; }
94
104
  get decidedAt(): string | null { return this.data.decidedAt; }
105
+ /** What you proposed to run with. */
106
+ get input(): Record<string, unknown> | null { return this.data.input ?? null; }
107
+ /** What to run with once approved, with any corrections. Null until then. */
108
+ get approvedInput(): Record<string, unknown> | null { return this.data.approvedInput ?? null; }
109
+ /** What the approver changed. */
110
+ get changes(): FieldChange[] { return this.data.changes ?? []; }
95
111
  get questions(): ApprovalQuestion[] { return this.data.questions; }
96
112
  /** Questions the approver is still waiting on you to answer. */
97
113
  get openQuestions(): ApprovalQuestion[] { return this.data.questions.filter((q) => !q.answer); }
@@ -124,6 +140,8 @@ export class Approval {
124
140
  decidedAt: this.data.decidedAt,
125
141
  id: this.data.id,
126
142
  url: this.data.url,
143
+ input: this.data.status === "approved" ? (this.data.approvedInput ?? this.data.input) : null,
144
+ changes: this.data.changes ?? [],
127
145
  approval: this,
128
146
  } as Decision;
129
147
  }
@@ -249,7 +267,9 @@ export class Approvals {
249
267
  body: input,
250
268
  signal,
251
269
  });
252
- return new Approval(this.http, data);
270
+ const created = new Approval(this.http, data);
271
+ created.callbackSecret = (data as ApprovalData & { callbackSecret?: string }).callbackSecret ?? null;
272
+ return created;
253
273
  }
254
274
 
255
275
  async get(id: string, signal?: AbortSignal): Promise<Approval> {
@@ -43,6 +43,15 @@ export class Collection {
43
43
  private data: CollectionData
44
44
  ) {}
45
45
 
46
+ /**
47
+ * The secret this request's callbacks are signed with, when you gave a
48
+ * `callbackUrl`. Only on the handle `create()` returned — the API hands it
49
+ * over once and never again — so keep it with whatever will receive the
50
+ * callback, and check each one with
51
+ * `deliverd.webhooks.constructCallback(callbackSecret, rawBody, signature)`.
52
+ */
53
+ callbackSecret: string | null = null;
54
+
46
55
  get id(): string { return this.data.id; }
47
56
  get status(): CollectionData["status"] { return this.data.status; }
48
57
  /** The page the people you asked will fill in. */
@@ -176,7 +185,9 @@ export class Collections {
176
185
  body: input,
177
186
  signal,
178
187
  });
179
- return new Collection(this.http, data);
188
+ const created = new Collection(this.http, data);
189
+ created.callbackSecret = (data as CollectionData & { callbackSecret?: string }).callbackSecret ?? null;
190
+ return created;
180
191
  }
181
192
 
182
193
  async get(id: string, signal?: AbortSignal): Promise<Collection> {
package/src/dev.ts CHANGED
@@ -51,6 +51,12 @@ export interface DevelopmentOptions {
51
51
  delay?: number;
52
52
  /** What they say. Defaults suit the outcome. */
53
53
  note?: string;
54
+ /**
55
+ * Corrections the imaginary approver makes when approving a request that
56
+ * sent an `input`, so the approve-with-changes path can be run offline.
57
+ * Only fields you named in `editableFields` are applied, as in production.
58
+ */
59
+ edits?: Record<string, unknown>;
54
60
  /** What they ask, when the outcome is `question`. */
55
61
  question?: string;
56
62
  /** Print what the approver would have seen. Default true. */
@@ -110,6 +116,11 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
110
116
  reportId: (body.reportId as string | undefined) ?? null,
111
117
  externalId: (body.externalId as string | undefined) ?? null,
112
118
  metadata: (body.metadata as Record<string, unknown>) ?? {},
119
+ input: (body.input as Record<string, unknown> | undefined) ?? null,
120
+ editableFields: (body.editableFields as string[] | undefined) ?? [],
121
+ approvedInput: null,
122
+ changes: [],
123
+ concerns: [],
113
124
  requestedBy: "You (development mode)",
114
125
  approvers: (body.approvers as string[] | undefined) ?? [],
115
126
  /*
@@ -274,6 +285,8 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
274
285
  status: byRule ? "denied" : "pending",
275
286
  allowed: false,
276
287
  input: (body.input as Record<string, unknown>) ?? {},
288
+ changes: [],
289
+ concerns: [],
277
290
  basis: byRule ? "policy" : "human",
278
291
  reason: byRule
279
292
  ? "Development mode refused it. A real rule would say which one and why."
@@ -575,6 +588,14 @@ function settle(stored: Stored): void {
575
588
  stored.data.note =
576
589
  stored.options.note ??
577
590
  (stored.data.status === "rejected" ? "Not yet — development mode says no." : null);
591
+ if (stored.data.status === "approved" && stored.data.input) {
592
+ const proposed = stored.data.input;
593
+ const edits = Object.entries(stored.options.edits ?? {}).filter(
594
+ ([field, value]) => stored.data.editableFields.includes(field) && !Object.is(proposed[field], value)
595
+ );
596
+ stored.data.approvedInput = { ...proposed, ...Object.fromEntries(edits) };
597
+ stored.data.changes = edits.map(([field, to]) => ({ field, from: proposed[field] ?? null, to }));
598
+ }
578
599
  }
579
600
 
580
601
  /**
package/src/gates.ts CHANGED
@@ -105,6 +105,7 @@ export class Gate {
105
105
  reason: this.data.reason,
106
106
  rule: this.data.rule,
107
107
  input: this.data.input,
108
+ changes: this.data.changes ?? [],
108
109
  id: this.data.id,
109
110
  approvalUrl: this.data.approvalUrl,
110
111
  gate: this,
package/src/index.ts CHANGED
@@ -28,6 +28,7 @@ export { Review, Reviews, type ReviewWaitOptions } from "./reviews.js";
28
28
  export { Collection, Collections, type CollectWaitOptions } from "./collections.js";
29
29
  export { Flow, Flows, type FlowPrimitives } from "./flows.js";
30
30
  export {
31
+ constructCallback,
31
32
  constructEvent,
32
33
  DELIVERY_HEADER,
33
34
  EVENT_HEADER,