@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.
- package/LICENSE +21 -21
- package/README.md +654 -654
- package/dist/dev.d.ts.map +1 -1
- package/dist/dev.js +82 -0
- package/dist/gates.d.ts +49 -1
- package/dist/gates.d.ts.map +1 -1
- package/dist/gates.js +110 -3
- package/dist/messages.d.ts.map +1 -1
- package/dist/messages.js +48 -0
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +1067 -0
- package/dist/types.d.ts +162 -9
- package/dist/types.d.ts.map +1 -1
- package/package.json +59 -59
- package/src/adapters/ai-sdk.ts +59 -59
- package/src/adapters/claude-agent-sdk.ts +90 -90
- package/src/adapters/index.ts +23 -23
- package/src/adapters/langgraph.ts +202 -202
- package/src/adapters/openai-agents.ts +112 -112
- package/src/adapters/shared.ts +179 -179
- package/src/approvals.ts +342 -342
- package/src/collections.ts +247 -247
- package/src/dev.ts +868 -782
- package/src/duration.ts +21 -21
- package/src/errors.ts +62 -62
- package/src/flows.ts +222 -222
- package/src/gates.ts +366 -231
- package/src/http.ts +217 -217
- package/src/index.ts +444 -444
- package/src/messages.ts +209 -161
- package/src/paging.ts +64 -64
- package/src/released.ts +4049 -2982
- package/src/reports.ts +490 -490
- package/src/reviews.ts +236 -236
- package/src/types.ts +1107 -933
- package/src/webhooks.ts +117 -117
|
@@ -1,90 +1,90 @@
|
|
|
1
|
-
import { askAboutCall, type ToolApprovalOptions } from "./shared.js";
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* The Claude Agent SDK: a person approves tool calls, through Deliverd.
|
|
5
|
-
*
|
|
6
|
-
* ```ts
|
|
7
|
-
* import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
8
|
-
* import { Deliverd } from "@deliverd/sdk";
|
|
9
|
-
* import { deliverdCanUseTool } from "@deliverd/sdk/adapters";
|
|
10
|
-
*
|
|
11
|
-
* const deliverd = new Deliverd();
|
|
12
|
-
* for await (const message of query({
|
|
13
|
-
* prompt: "Tidy the release notes and publish them",
|
|
14
|
-
* options: {
|
|
15
|
-
* canUseTool: deliverdCanUseTool({
|
|
16
|
-
* deliverd,
|
|
17
|
-
* approvers: ["release-managers"],
|
|
18
|
-
* when: (tool) => tool === "Bash" || tool.startsWith("mcp__"),
|
|
19
|
-
* }),
|
|
20
|
-
* },
|
|
21
|
-
* })) { … }
|
|
22
|
-
* ```
|
|
23
|
-
*
|
|
24
|
-
* A call that needs no person is allowed with its input unchanged. One that
|
|
25
|
-
* does waits for the decision, from the page, the email link, Slack or Teams:
|
|
26
|
-
* allowed, it runs; declined, the model is told why and told not to retry.
|
|
27
|
-
* The run's abort signal cancels the wait.
|
|
28
|
-
*
|
|
29
|
-
* Shapes follow `CanUseTool` and `PermissionResult` in
|
|
30
|
-
* `@anthropic-ai/claude-agent-sdk`'s `sdk.d.ts`.
|
|
31
|
-
*/
|
|
32
|
-
|
|
33
|
-
/** The options `canUseTool` receives that this adapter reads. */
|
|
34
|
-
export interface ClaudeCanUseToolContext {
|
|
35
|
-
signal: AbortSignal;
|
|
36
|
-
/** The tool call's id, which keeps a retried call from asking twice. */
|
|
37
|
-
toolUseID?: string;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export type ClaudePermissionResult =
|
|
41
|
-
| { behavior: "allow"; updatedInput: Record<string, unknown> }
|
|
42
|
-
| { behavior: "deny"; message: string };
|
|
43
|
-
|
|
44
|
-
export type ClaudeCanUseTool = (
|
|
45
|
-
toolName: string,
|
|
46
|
-
input: Record<string, unknown>,
|
|
47
|
-
context: ClaudeCanUseToolContext
|
|
48
|
-
) => Promise<ClaudePermissionResult>;
|
|
49
|
-
|
|
50
|
-
export interface ClaudeToolApprovalOptions extends ToolApprovalOptions {
|
|
51
|
-
/**
|
|
52
|
-
* Fields of a tool's input the approver may correct before approving, per
|
|
53
|
-
* tool: `editable: (tool) => tool === "refund" ? ["amount"] : []`. The call
|
|
54
|
-
* then runs with what they approved — the Agent SDK's `updatedInput` —
|
|
55
|
-
* rather than with what the model proposed.
|
|
56
|
-
*/
|
|
57
|
-
editable?: (toolName: string, input: Record<string, unknown>) => string[];
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function deliverdCanUseTool(options: ClaudeToolApprovalOptions): ClaudeCanUseTool {
|
|
61
|
-
return async (toolName, input, context) => {
|
|
62
|
-
if (options.when && !(await options.when(toolName, input))) {
|
|
63
|
-
return { behavior: "allow", updatedInput: input };
|
|
64
|
-
}
|
|
65
|
-
const id = context.toolUseID ?? `${toolName}:${stableHash(input)}`;
|
|
66
|
-
const outcome = await askAboutCall(
|
|
67
|
-
toolName,
|
|
68
|
-
input,
|
|
69
|
-
`claude-agent-sdk:${id}`,
|
|
70
|
-
options,
|
|
71
|
-
context.signal,
|
|
72
|
-
options.editable?.(toolName, input)
|
|
73
|
-
);
|
|
74
|
-
// What was approved runs, which is the proposal unless a person corrected it.
|
|
75
|
-
return outcome.allowed
|
|
76
|
-
? { behavior: "allow", updatedInput: outcome.input ?? input }
|
|
77
|
-
: { behavior: "deny", message: outcome.reason };
|
|
78
|
-
};
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/** A short, stable fingerprint of an input, for when no call id is given. */
|
|
82
|
-
function stableHash(value: unknown): string {
|
|
83
|
-
const text = JSON.stringify(value) ?? "";
|
|
84
|
-
let h = 0x811c9dc5;
|
|
85
|
-
for (let i = 0; i < text.length; i++) {
|
|
86
|
-
h ^= text.charCodeAt(i);
|
|
87
|
-
h = Math.imul(h, 0x01000193);
|
|
88
|
-
}
|
|
89
|
-
return (h >>> 0).toString(16);
|
|
90
|
-
}
|
|
1
|
+
import { askAboutCall, type ToolApprovalOptions } from "./shared.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The Claude Agent SDK: a person approves tool calls, through Deliverd.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
8
|
+
* import { Deliverd } from "@deliverd/sdk";
|
|
9
|
+
* import { deliverdCanUseTool } from "@deliverd/sdk/adapters";
|
|
10
|
+
*
|
|
11
|
+
* const deliverd = new Deliverd();
|
|
12
|
+
* for await (const message of query({
|
|
13
|
+
* prompt: "Tidy the release notes and publish them",
|
|
14
|
+
* options: {
|
|
15
|
+
* canUseTool: deliverdCanUseTool({
|
|
16
|
+
* deliverd,
|
|
17
|
+
* approvers: ["release-managers"],
|
|
18
|
+
* when: (tool) => tool === "Bash" || tool.startsWith("mcp__"),
|
|
19
|
+
* }),
|
|
20
|
+
* },
|
|
21
|
+
* })) { … }
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* A call that needs no person is allowed with its input unchanged. One that
|
|
25
|
+
* does waits for the decision, from the page, the email link, Slack or Teams:
|
|
26
|
+
* allowed, it runs; declined, the model is told why and told not to retry.
|
|
27
|
+
* The run's abort signal cancels the wait.
|
|
28
|
+
*
|
|
29
|
+
* Shapes follow `CanUseTool` and `PermissionResult` in
|
|
30
|
+
* `@anthropic-ai/claude-agent-sdk`'s `sdk.d.ts`.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
/** The options `canUseTool` receives that this adapter reads. */
|
|
34
|
+
export interface ClaudeCanUseToolContext {
|
|
35
|
+
signal: AbortSignal;
|
|
36
|
+
/** The tool call's id, which keeps a retried call from asking twice. */
|
|
37
|
+
toolUseID?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export type ClaudePermissionResult =
|
|
41
|
+
| { behavior: "allow"; updatedInput: Record<string, unknown> }
|
|
42
|
+
| { behavior: "deny"; message: string };
|
|
43
|
+
|
|
44
|
+
export type ClaudeCanUseTool = (
|
|
45
|
+
toolName: string,
|
|
46
|
+
input: Record<string, unknown>,
|
|
47
|
+
context: ClaudeCanUseToolContext
|
|
48
|
+
) => Promise<ClaudePermissionResult>;
|
|
49
|
+
|
|
50
|
+
export interface ClaudeToolApprovalOptions extends ToolApprovalOptions {
|
|
51
|
+
/**
|
|
52
|
+
* Fields of a tool's input the approver may correct before approving, per
|
|
53
|
+
* tool: `editable: (tool) => tool === "refund" ? ["amount"] : []`. The call
|
|
54
|
+
* then runs with what they approved — the Agent SDK's `updatedInput` —
|
|
55
|
+
* rather than with what the model proposed.
|
|
56
|
+
*/
|
|
57
|
+
editable?: (toolName: string, input: Record<string, unknown>) => string[];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function deliverdCanUseTool(options: ClaudeToolApprovalOptions): ClaudeCanUseTool {
|
|
61
|
+
return async (toolName, input, context) => {
|
|
62
|
+
if (options.when && !(await options.when(toolName, input))) {
|
|
63
|
+
return { behavior: "allow", updatedInput: input };
|
|
64
|
+
}
|
|
65
|
+
const id = context.toolUseID ?? `${toolName}:${stableHash(input)}`;
|
|
66
|
+
const outcome = await askAboutCall(
|
|
67
|
+
toolName,
|
|
68
|
+
input,
|
|
69
|
+
`claude-agent-sdk:${id}`,
|
|
70
|
+
options,
|
|
71
|
+
context.signal,
|
|
72
|
+
options.editable?.(toolName, input)
|
|
73
|
+
);
|
|
74
|
+
// What was approved runs, which is the proposal unless a person corrected it.
|
|
75
|
+
return outcome.allowed
|
|
76
|
+
? { behavior: "allow", updatedInput: outcome.input ?? input }
|
|
77
|
+
: { behavior: "deny", message: outcome.reason };
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** A short, stable fingerprint of an input, for when no call id is given. */
|
|
82
|
+
function stableHash(value: unknown): string {
|
|
83
|
+
const text = JSON.stringify(value) ?? "";
|
|
84
|
+
let h = 0x811c9dc5;
|
|
85
|
+
for (let i = 0; i < text.length; i++) {
|
|
86
|
+
h ^= text.charCodeAt(i);
|
|
87
|
+
h = Math.imul(h, 0x01000193);
|
|
88
|
+
}
|
|
89
|
+
return (h >>> 0).toString(16);
|
|
90
|
+
}
|
package/src/adapters/index.ts
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Deliverd inside the agent frameworks people already use: a person approves
|
|
3
|
-
* a tool call from their inbox, Slack or Teams, and the agent carries on.
|
|
4
|
-
*
|
|
5
|
-
* `@deliverd/sdk/adapters`, separate from the main entry so none of it is
|
|
6
|
-
* loaded unless it is used. No dependencies: each adapter matches its
|
|
7
|
-
* framework's hook by shape.
|
|
8
|
-
*/
|
|
9
|
-
export { deliverdCanUseTool } from "./claude-agent-sdk.js";
|
|
10
|
-
export type {
|
|
11
|
-
ClaudeCanUseTool,
|
|
12
|
-
ClaudeCanUseToolContext,
|
|
13
|
-
ClaudePermissionResult,
|
|
14
|
-
ClaudeToolApprovalOptions,
|
|
15
|
-
} from "./claude-agent-sdk.js";
|
|
16
|
-
export { deliverdToolApproval } from "./ai-sdk.js";
|
|
17
|
-
export type { AiSdkApprovalCall, AiSdkApprovalStatus } from "./ai-sdk.js";
|
|
18
|
-
export { resolveInterruptions, runWithDeliverdApprovals } from "./openai-agents.js";
|
|
19
|
-
export type { OpenAiApprovalItem, OpenAiInterruptedResult } from "./openai-agents.js";
|
|
20
|
-
export { approveInGraph, resumeFromCallback } from "./langgraph.js";
|
|
21
|
-
export type { DeliverdInterruptValue, GraphApprovalRecord, GraphApprover, GraphDecision } from "./langgraph.js";
|
|
22
|
-
export { defaultDescription, DEFAULT_TOOL_EXPIRY } from "./shared.js";
|
|
23
|
-
export type { Approver, CallDescription, CallOutcome, ToolApprovalOptions } from "./shared.js";
|
|
1
|
+
/**
|
|
2
|
+
* Deliverd inside the agent frameworks people already use: a person approves
|
|
3
|
+
* a tool call from their inbox, Slack or Teams, and the agent carries on.
|
|
4
|
+
*
|
|
5
|
+
* `@deliverd/sdk/adapters`, separate from the main entry so none of it is
|
|
6
|
+
* loaded unless it is used. No dependencies: each adapter matches its
|
|
7
|
+
* framework's hook by shape.
|
|
8
|
+
*/
|
|
9
|
+
export { deliverdCanUseTool } from "./claude-agent-sdk.js";
|
|
10
|
+
export type {
|
|
11
|
+
ClaudeCanUseTool,
|
|
12
|
+
ClaudeCanUseToolContext,
|
|
13
|
+
ClaudePermissionResult,
|
|
14
|
+
ClaudeToolApprovalOptions,
|
|
15
|
+
} from "./claude-agent-sdk.js";
|
|
16
|
+
export { deliverdToolApproval } from "./ai-sdk.js";
|
|
17
|
+
export type { AiSdkApprovalCall, AiSdkApprovalStatus } from "./ai-sdk.js";
|
|
18
|
+
export { resolveInterruptions, runWithDeliverdApprovals } from "./openai-agents.js";
|
|
19
|
+
export type { OpenAiApprovalItem, OpenAiInterruptedResult } from "./openai-agents.js";
|
|
20
|
+
export { approveInGraph, resumeFromCallback } from "./langgraph.js";
|
|
21
|
+
export type { DeliverdInterruptValue, GraphApprovalRecord, GraphApprover, GraphDecision } from "./langgraph.js";
|
|
22
|
+
export { defaultDescription, DEFAULT_TOOL_EXPIRY } from "./shared.js";
|
|
23
|
+
export type { Approver, CallDescription, CallOutcome, ToolApprovalOptions } from "./shared.js";
|
|
@@ -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
|
+
|