@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.
package/src/gates.ts CHANGED
@@ -1,366 +1,366 @@
1
- import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
2
- import type { HttpClient } from "./http.js";
3
- import type {
4
- CreateGateInput,
5
- ExecutionReceipt,
6
- GateAgentRef,
7
- GateData,
8
- GateDecision,
9
- RecordExecutionInput,
10
- } from "./types.js";
11
-
12
- /**
13
- * Ask before you act.
14
- *
15
- * The other primitives in this package are an agent asking a person to look at
16
- * work it has already done. This one asks first, and the answer comes from
17
- * policy the developer does not own — which is the point: what needs a human is
18
- * an organisation's decision, not a line in the agent's code.
19
- *
20
- * ```ts
21
- * const decision = await deliverd.gate({
22
- * action: "finance.refund",
23
- * externalId: `refund:${order.id}`,
24
- * input: { customer_id: order.customerId, amount: 1240, currency: "GBP" },
25
- * });
26
- * if (!decision.allowed) return;
27
- * await stripe.refunds.create(decision.input);
28
- * ```
29
- *
30
- * **Use `decision.input`, not your own object.** It is what the action's schema
31
- * validated and what an approver actually saw. Passing the original is right
32
- * until the day somebody edits a value before approving, and then it is a
33
- * silent bug that spends an approval for £1200 on a refund of £1240.
34
- *
35
- * **Scoped permissions.** Name what the act is about and where it lands, and an
36
- * approval covers exactly that — the version you asked about, the destination
37
- * you named — then report what you did:
38
- *
39
- * ```ts
40
- * const gate = await deliverd.gates.check({
41
- * actionId: "report.publish",
42
- * externalId: `weekly-portfolio:${week}`,
43
- * input: { title: "Weekly Portfolio Report" },
44
- * classification: "confidential",
45
- * destination: { type: "workspace", id: "executive" },
46
- * artifact: { reportId, versionId },
47
- * });
48
- * await gate.wait();
49
- * if (gate.canExecute) {
50
- * await publish(report);
51
- * await gate.recordExecution({ artifactSha256: gate.scope.artifact?.sha256 ?? undefined });
52
- * }
53
- * ```
54
- *
55
- * `canExecute` is your organisation's authorisation, nothing more: the platform
56
- * your agent runs on may still require its user's confirmation, or refuse.
57
- */
58
-
59
- /** How long between polls while waiting on a person. */
60
- const POLL_SCHEDULE = [250, 750, 2_000, 4_000, 8_000, 15_000, 30_000] as const;
61
-
62
- export interface GateWaitOptions {
63
- /** Give up after this many milliseconds. Without one, waits indefinitely. */
64
- timeout?: number;
65
- signal?: AbortSignal;
66
- /** Called on every poll, for a progress line. */
67
- onPoll?: (gate: GateData) => void;
68
- pollIntervals?: readonly number[];
69
- }
70
-
71
- export interface GateOptions extends GateWaitOptions {
72
- /** The registered action: `finance.refund`. */
73
- action: string;
74
- input: Record<string, unknown>;
75
- externalId: string;
76
- environment?: string;
77
- reason?: string;
78
- flowId?: string;
79
- /**
80
- * Whether to block when policy sends it to a person. Default true.
81
- *
82
- * False returns the pending decision immediately, which is what you want
83
- * inside a request handler that must not hold a connection open for an hour.
84
- * `deliverd.gates.create()` is the same thing said more plainly.
85
- */
86
- wait?: boolean;
87
- }
88
-
89
- /**
90
- * A decision, and what you can do with it.
91
- *
92
- * The data is a snapshot; `wait()` and `refresh()` replace it in place, so a
93
- * handle held across a wait reads the settled decision rather than the pending
94
- * one you created.
95
- */
96
- export class Gate {
97
- constructor(
98
- private readonly http: HttpClient,
99
- private data: GateData
100
- ) {}
101
-
102
- get id(): string { return this.data.id; }
103
- get status(): GateData["status"] { return this.data.status; }
104
- /**
105
- * The one to branch on. True when a rule permitted it **or** a person agreed
106
- * to it; false for denied, rejected, expired, cancelled and while pending.
107
- * An expiry is not permission — nobody said yes.
108
- */
109
- get allowed(): boolean { return this.data.allowed; }
110
- /** Still waiting on a person. */
111
- get pending(): boolean { return this.data.status === "pending"; }
112
- /** Refused by a rule, as against rejected by a person. */
113
- get denied(): boolean { return this.data.status === "denied"; }
114
- /** What to execute with: the input as the action's schema validated it. */
115
- get input(): Record<string, unknown> { return this.data.input; }
116
- /** Why, in the words of whoever wrote the rule. */
117
- get reason(): string | null { return this.data.reason; }
118
- /** The rule that decided, by name. Null when nothing matched it. */
119
- get rule(): string | null { return this.data.rule; }
120
- /** Where a person decides, when one was asked. */
121
- get approvalUrl(): string | null { return this.data.approvalUrl; }
122
- get approvalId(): string | null { return this.data.approvalId; }
123
- /** True when this call read back a decision already made under your id. */
124
- get reused(): boolean { return this.data.reused; }
125
- /**
126
- * Whether you may act on it **now**: authorised, inside its window, with a
127
- * use left, not revoked. Branch on this rather than `allowed`, which says it
128
- * was authorised at some point. The organisation's authorisation only.
129
- */
130
- get canExecute(): boolean { return this.data.canExecute; }
131
- /** What policy said: ALLOW, APPROVAL_REQUIRED, REVIEW_REQUIRED or DENY. */
132
- get decision(): GateData["decision"] { return this.data.decision; }
133
- /** Why it cannot be executed, when it cannot. */
134
- get blockedBecause(): string | null { return this.data.blockedBecause; }
135
- /** What the permission covers: destination, artifact and its hash, classification. */
136
- get scope(): GateData["scope"] { return this.data.scope; }
137
- /** How long it lasts and how many uses are left. */
138
- get authorisation(): GateData["authorisation"] { return this.data.authorisation; }
139
- /** A person sent it back. Revise and ask again with `supersedesGateId: gate.id`. */
140
- get changesRequested(): boolean { return this.data.status === "changes_requested"; }
141
-
142
- /**
143
- * Report what you did with the permission. Spends a use. A different
144
- * artifact hash is refused as `approval_invalidated`; a different
145
- * destination as `destination_mismatch`.
146
- */
147
- async recordExecution(input: RecordExecutionInput = {}, signal?: AbortSignal): Promise<ExecutionReceipt> {
148
- const { receipt, gate } = await recordExecution(this.http, this.data.id, input, signal);
149
- this.data = gate;
150
- return receipt;
151
- }
152
-
153
- /** Withdraw it: the request if a person has not answered, the permission if unused. */
154
- async cancel(note?: string, agent?: GateAgentRef, signal?: AbortSignal): Promise<this> {
155
- this.data = await this.http.request<GateData>({
156
- method: "POST",
157
- path: `/gates/${this.data.id}/cancel`,
158
- body: { note, agent },
159
- signal,
160
- });
161
- return this;
162
- }
163
-
164
- /** Everything the API returned, if you want a field the getters do not name. */
165
- toJSON(): GateData { return this.data; }
166
-
167
- /** The answer, flattened — what `gate()` hands back. */
168
- toDecision(): GateDecision {
169
- return {
170
- allowed: this.data.allowed,
171
- status: this.data.status,
172
- reason: this.data.reason,
173
- rule: this.data.rule,
174
- input: this.data.input,
175
- changes: this.data.changes ?? [],
176
- id: this.data.id,
177
- approvalUrl: this.data.approvalUrl,
178
- gate: this,
179
- };
180
- }
181
-
182
- async refresh(signal?: AbortSignal): Promise<this> {
183
- this.data = await this.http.request<GateData>({
184
- method: "GET",
185
- path: `/gates/${this.data.id}`,
186
- signal,
187
- });
188
- return this;
189
- }
190
-
191
- /**
192
- * Block until a person decides, then return.
193
- *
194
- * Resolves on every settled state — it does not throw on a refusal, because
195
- * a no is an answer and `if (gate.allowed)` is the line that should follow.
196
- * It throws only when the wait itself failed: a timeout, an abort, or the
197
- * API being unreachable.
198
- *
199
- * Returns immediately when policy already settled it, which is the common
200
- * case: most gated calls are allowed or denied by a rule and never reach a
201
- * person at all.
202
- */
203
- async wait(options: GateWaitOptions = {}): Promise<this> {
204
- const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
205
- let poll = 0;
206
-
207
- if (!this.pending) return this;
208
-
209
- for (;;) {
210
- if (options.signal?.aborted) {
211
- throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
212
- cause: options.signal.reason,
213
- });
214
- }
215
- if (deadline !== undefined && Date.now() >= deadline) {
216
- throw new DeliverdTimeoutError(
217
- `Nobody decided the ${this.data.rule ? `"${this.data.rule}" ` : ""}gate on ` +
218
- // The action id, not an input field that happened to be called `action`.
219
- `"${this.data.actionId || this.id}" within the timeout. ` +
220
- (this.data.approvalUrl
221
- ? `It is still open at ${this.data.approvalUrl}.`
222
- : "It is still open.")
223
- );
224
- }
225
-
226
- const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
227
- const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
228
- await sleep(Math.max(0, remaining), options.signal);
229
-
230
- await this.refresh(options.signal);
231
- options.onPoll?.(this.data);
232
-
233
- if (!this.pending) return this;
234
- }
235
- }
236
- }
237
-
238
- /** ±25% jitter, so a fleet of agents does not poll in lockstep. */
239
- function pollDelay(attempt: number, schedule: readonly number[]): number {
240
- const base = schedule[Math.min(attempt, schedule.length - 1)] ?? 30_000;
241
- return Math.round(base * (0.75 + Math.random() * 0.5));
242
- }
243
-
244
- function sleep(ms: number, signal?: AbortSignal): Promise<void> {
245
- return new Promise((resolve, reject) => {
246
- if (signal?.aborted) {
247
- return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
248
- }
249
- const timer = setTimeout(() => {
250
- signal?.removeEventListener("abort", onAbort);
251
- resolve();
252
- }, ms);
253
- const onAbort = () => {
254
- clearTimeout(timer);
255
- reject(new DeliverdError(0, "aborted", "The wait was aborted."));
256
- };
257
- signal?.addEventListener("abort", onAbort, { once: true });
258
- });
259
- }
260
-
261
- async function recordExecution(
262
- http: HttpClient,
263
- id: string,
264
- input: RecordExecutionInput,
265
- signal?: AbortSignal
266
- ): Promise<{ receipt: ExecutionReceipt; gate: GateData }> {
267
- return http.request<{ receipt: ExecutionReceipt; gate: GateData }>({
268
- method: "POST",
269
- path: `/gates/${id}/execution`,
270
- body: { phase: "completed", ...input },
271
- signal,
272
- });
273
- }
274
-
275
- export class Gates {
276
- constructor(private readonly http: HttpClient) {}
277
-
278
- /**
279
- * Ask whether you may act, and return at once — the same call as `create`,
280
- * named for what it does. Policy answers; `canExecute` is the field to branch
281
- * on, now or after `wait()`.
282
- */
283
- async check(input: CreateGateInput, signal?: AbortSignal): Promise<Gate> {
284
- return this.create(input, signal);
285
- }
286
-
287
- /** Report what you did with a gate's permission. See `Gate.recordExecution`. */
288
- async recordExecution(
289
- id: string,
290
- input: RecordExecutionInput = {},
291
- signal?: AbortSignal
292
- ): Promise<{ receipt: ExecutionReceipt; gate: Gate }> {
293
- const { receipt, gate } = await recordExecution(this.http, id, input, signal);
294
- return { receipt, gate: new Gate(this.http, gate) };
295
- }
296
-
297
- /** Withdraw a request, or an unused permission. */
298
- async cancel(id: string, note?: string, agent?: GateAgentRef, signal?: AbortSignal): Promise<Gate> {
299
- const data = await this.http.request<GateData>({
300
- method: "POST",
301
- path: `/gates/${id}/cancel`,
302
- body: { note, agent },
303
- signal,
304
- });
305
- return new Gate(this.http, data);
306
- }
307
-
308
- /**
309
- * Have Deliverd make the staged report version the gate authorised live.
310
- * The receipt is `verified`: Deliverd carried it out.
311
- */
312
- async release(
313
- id: string,
314
- agent?: GateAgentRef,
315
- signal?: AbortSignal
316
- ): Promise<{ receipt: ExecutionReceipt; gate: Gate; url: string }> {
317
- const released = await this.http.request<{ receipt: ExecutionReceipt; gate: GateData; url: string }>({
318
- method: "POST",
319
- path: `/gates/${id}/release`,
320
- body: { agent },
321
- signal,
322
- });
323
- return { ...released, gate: new Gate(this.http, released.gate) };
324
- }
325
-
326
- /** The gate's evidence pack, as JSON. */
327
- async evidence(id: string, signal?: AbortSignal): Promise<Record<string, unknown>> {
328
- return this.http.request<Record<string, unknown>>({ method: "GET", path: `/gates/${id}/evidence`, signal });
329
- }
330
-
331
- /**
332
- * Raise a decision and return straight away, even if it went to a person.
333
- *
334
- * The non-blocking half of `gate()`. Use it when the work resumes on a
335
- * webhook or a later poll rather than inside this call.
336
- */
337
- async create(input: CreateGateInput, signal?: AbortSignal): Promise<Gate> {
338
- const data = await this.http.request<GateData>({
339
- method: "POST",
340
- path: "/gates",
341
- body: input,
342
- /*
343
- * The caller's own id, as the HTTP idempotency key too.
344
- *
345
- * The server enforces reuse against `gate_requests.external_id`, so this
346
- * is belt and braces rather than the mechanism — but it means a retry
347
- * inside the transport layer and a retry by the caller's own code are the
348
- * same key, instead of one guarding the request and the other the
349
- * decision.
350
- */
351
- idempotencyKey: input.externalId,
352
- signal,
353
- });
354
- return new Gate(this.http, data);
355
- }
356
-
357
- /** One decision by its id. */
358
- async get(id: string, signal?: AbortSignal): Promise<Gate> {
359
- const data = await this.http.request<GateData>({
360
- method: "GET",
361
- path: `/gates/${id}`,
362
- signal,
363
- });
364
- return new Gate(this.http, data);
365
- }
366
- }
1
+ import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
2
+ import type { HttpClient } from "./http.js";
3
+ import type {
4
+ CreateGateInput,
5
+ ExecutionReceipt,
6
+ GateAgentRef,
7
+ GateData,
8
+ GateDecision,
9
+ RecordExecutionInput,
10
+ } from "./types.js";
11
+
12
+ /**
13
+ * Ask before you act.
14
+ *
15
+ * The other primitives in this package are an agent asking a person to look at
16
+ * work it has already done. This one asks first, and the answer comes from
17
+ * policy the developer does not own — which is the point: what needs a human is
18
+ * an organisation's decision, not a line in the agent's code.
19
+ *
20
+ * ```ts
21
+ * const decision = await deliverd.gate({
22
+ * action: "finance.refund",
23
+ * externalId: `refund:${order.id}`,
24
+ * input: { customer_id: order.customerId, amount: 1240, currency: "GBP" },
25
+ * });
26
+ * if (!decision.allowed) return;
27
+ * await stripe.refunds.create(decision.input);
28
+ * ```
29
+ *
30
+ * **Use `decision.input`, not your own object.** It is what the action's schema
31
+ * validated and what an approver actually saw. Passing the original is right
32
+ * until the day somebody edits a value before approving, and then it is a
33
+ * silent bug that spends an approval for £1200 on a refund of £1240.
34
+ *
35
+ * **Scoped permissions.** Name what the act is about and where it lands, and an
36
+ * approval covers exactly that — the version you asked about, the destination
37
+ * you named — then report what you did:
38
+ *
39
+ * ```ts
40
+ * const gate = await deliverd.gates.check({
41
+ * actionId: "report.publish",
42
+ * externalId: `weekly-portfolio:${week}`,
43
+ * input: { title: "Weekly Portfolio Report" },
44
+ * classification: "confidential",
45
+ * destination: { type: "workspace", id: "executive" },
46
+ * artifact: { reportId, versionId },
47
+ * });
48
+ * await gate.wait();
49
+ * if (gate.canExecute) {
50
+ * await publish(report);
51
+ * await gate.recordExecution({ artifactSha256: gate.scope.artifact?.sha256 ?? undefined });
52
+ * }
53
+ * ```
54
+ *
55
+ * `canExecute` is your organisation's authorisation, nothing more: the platform
56
+ * your agent runs on may still require its user's confirmation, or refuse.
57
+ */
58
+
59
+ /** How long between polls while waiting on a person. */
60
+ const POLL_SCHEDULE = [250, 750, 2_000, 4_000, 8_000, 15_000, 30_000] as const;
61
+
62
+ export interface GateWaitOptions {
63
+ /** Give up after this many milliseconds. Without one, waits indefinitely. */
64
+ timeout?: number;
65
+ signal?: AbortSignal;
66
+ /** Called on every poll, for a progress line. */
67
+ onPoll?: (gate: GateData) => void;
68
+ pollIntervals?: readonly number[];
69
+ }
70
+
71
+ export interface GateOptions extends GateWaitOptions {
72
+ /** The registered action: `finance.refund`. */
73
+ action: string;
74
+ input: Record<string, unknown>;
75
+ externalId: string;
76
+ environment?: string;
77
+ reason?: string;
78
+ flowId?: string;
79
+ /**
80
+ * Whether to block when policy sends it to a person. Default true.
81
+ *
82
+ * False returns the pending decision immediately, which is what you want
83
+ * inside a request handler that must not hold a connection open for an hour.
84
+ * `deliverd.gates.create()` is the same thing said more plainly.
85
+ */
86
+ wait?: boolean;
87
+ }
88
+
89
+ /**
90
+ * A decision, and what you can do with it.
91
+ *
92
+ * The data is a snapshot; `wait()` and `refresh()` replace it in place, so a
93
+ * handle held across a wait reads the settled decision rather than the pending
94
+ * one you created.
95
+ */
96
+ export class Gate {
97
+ constructor(
98
+ private readonly http: HttpClient,
99
+ private data: GateData
100
+ ) {}
101
+
102
+ get id(): string { return this.data.id; }
103
+ get status(): GateData["status"] { return this.data.status; }
104
+ /**
105
+ * The one to branch on. True when a rule permitted it **or** a person agreed
106
+ * to it; false for denied, rejected, expired, cancelled and while pending.
107
+ * An expiry is not permission — nobody said yes.
108
+ */
109
+ get allowed(): boolean { return this.data.allowed; }
110
+ /** Still waiting on a person. */
111
+ get pending(): boolean { return this.data.status === "pending"; }
112
+ /** Refused by a rule, as against rejected by a person. */
113
+ get denied(): boolean { return this.data.status === "denied"; }
114
+ /** What to execute with: the input as the action's schema validated it. */
115
+ get input(): Record<string, unknown> { return this.data.input; }
116
+ /** Why, in the words of whoever wrote the rule. */
117
+ get reason(): string | null { return this.data.reason; }
118
+ /** The rule that decided, by name. Null when nothing matched it. */
119
+ get rule(): string | null { return this.data.rule; }
120
+ /** Where a person decides, when one was asked. */
121
+ get approvalUrl(): string | null { return this.data.approvalUrl; }
122
+ get approvalId(): string | null { return this.data.approvalId; }
123
+ /** True when this call read back a decision already made under your id. */
124
+ get reused(): boolean { return this.data.reused; }
125
+ /**
126
+ * Whether you may act on it **now**: authorised, inside its window, with a
127
+ * use left, not revoked. Branch on this rather than `allowed`, which says it
128
+ * was authorised at some point. The organisation's authorisation only.
129
+ */
130
+ get canExecute(): boolean { return this.data.canExecute; }
131
+ /** What policy said: ALLOW, APPROVAL_REQUIRED, REVIEW_REQUIRED or DENY. */
132
+ get decision(): GateData["decision"] { return this.data.decision; }
133
+ /** Why it cannot be executed, when it cannot. */
134
+ get blockedBecause(): string | null { return this.data.blockedBecause; }
135
+ /** What the permission covers: destination, artifact and its hash, classification. */
136
+ get scope(): GateData["scope"] { return this.data.scope; }
137
+ /** How long it lasts and how many uses are left. */
138
+ get authorisation(): GateData["authorisation"] { return this.data.authorisation; }
139
+ /** A person sent it back. Revise and ask again with `supersedesGateId: gate.id`. */
140
+ get changesRequested(): boolean { return this.data.status === "changes_requested"; }
141
+
142
+ /**
143
+ * Report what you did with the permission. Spends a use. A different
144
+ * artifact hash is refused as `approval_invalidated`; a different
145
+ * destination as `destination_mismatch`.
146
+ */
147
+ async recordExecution(input: RecordExecutionInput = {}, signal?: AbortSignal): Promise<ExecutionReceipt> {
148
+ const { receipt, gate } = await recordExecution(this.http, this.data.id, input, signal);
149
+ this.data = gate;
150
+ return receipt;
151
+ }
152
+
153
+ /** Withdraw it: the request if a person has not answered, the permission if unused. */
154
+ async cancel(note?: string, agent?: GateAgentRef, signal?: AbortSignal): Promise<this> {
155
+ this.data = await this.http.request<GateData>({
156
+ method: "POST",
157
+ path: `/gates/${this.data.id}/cancel`,
158
+ body: { note, agent },
159
+ signal,
160
+ });
161
+ return this;
162
+ }
163
+
164
+ /** Everything the API returned, if you want a field the getters do not name. */
165
+ toJSON(): GateData { return this.data; }
166
+
167
+ /** The answer, flattened — what `gate()` hands back. */
168
+ toDecision(): GateDecision {
169
+ return {
170
+ allowed: this.data.allowed,
171
+ status: this.data.status,
172
+ reason: this.data.reason,
173
+ rule: this.data.rule,
174
+ input: this.data.input,
175
+ changes: this.data.changes ?? [],
176
+ id: this.data.id,
177
+ approvalUrl: this.data.approvalUrl,
178
+ gate: this,
179
+ };
180
+ }
181
+
182
+ async refresh(signal?: AbortSignal): Promise<this> {
183
+ this.data = await this.http.request<GateData>({
184
+ method: "GET",
185
+ path: `/gates/${this.data.id}`,
186
+ signal,
187
+ });
188
+ return this;
189
+ }
190
+
191
+ /**
192
+ * Block until a person decides, then return.
193
+ *
194
+ * Resolves on every settled state — it does not throw on a refusal, because
195
+ * a no is an answer and `if (gate.allowed)` is the line that should follow.
196
+ * It throws only when the wait itself failed: a timeout, an abort, or the
197
+ * API being unreachable.
198
+ *
199
+ * Returns immediately when policy already settled it, which is the common
200
+ * case: most gated calls are allowed or denied by a rule and never reach a
201
+ * person at all.
202
+ */
203
+ async wait(options: GateWaitOptions = {}): Promise<this> {
204
+ const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
205
+ let poll = 0;
206
+
207
+ if (!this.pending) return this;
208
+
209
+ for (;;) {
210
+ if (options.signal?.aborted) {
211
+ throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
212
+ cause: options.signal.reason,
213
+ });
214
+ }
215
+ if (deadline !== undefined && Date.now() >= deadline) {
216
+ throw new DeliverdTimeoutError(
217
+ `Nobody decided the ${this.data.rule ? `"${this.data.rule}" ` : ""}gate on ` +
218
+ // The action id, not an input field that happened to be called `action`.
219
+ `"${this.data.actionId || this.id}" within the timeout. ` +
220
+ (this.data.approvalUrl
221
+ ? `It is still open at ${this.data.approvalUrl}.`
222
+ : "It is still open.")
223
+ );
224
+ }
225
+
226
+ const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
227
+ const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
228
+ await sleep(Math.max(0, remaining), options.signal);
229
+
230
+ await this.refresh(options.signal);
231
+ options.onPoll?.(this.data);
232
+
233
+ if (!this.pending) return this;
234
+ }
235
+ }
236
+ }
237
+
238
+ /** ±25% jitter, so a fleet of agents does not poll in lockstep. */
239
+ function pollDelay(attempt: number, schedule: readonly number[]): number {
240
+ const base = schedule[Math.min(attempt, schedule.length - 1)] ?? 30_000;
241
+ return Math.round(base * (0.75 + Math.random() * 0.5));
242
+ }
243
+
244
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
245
+ return new Promise((resolve, reject) => {
246
+ if (signal?.aborted) {
247
+ return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
248
+ }
249
+ const timer = setTimeout(() => {
250
+ signal?.removeEventListener("abort", onAbort);
251
+ resolve();
252
+ }, ms);
253
+ const onAbort = () => {
254
+ clearTimeout(timer);
255
+ reject(new DeliverdError(0, "aborted", "The wait was aborted."));
256
+ };
257
+ signal?.addEventListener("abort", onAbort, { once: true });
258
+ });
259
+ }
260
+
261
+ async function recordExecution(
262
+ http: HttpClient,
263
+ id: string,
264
+ input: RecordExecutionInput,
265
+ signal?: AbortSignal
266
+ ): Promise<{ receipt: ExecutionReceipt; gate: GateData }> {
267
+ return http.request<{ receipt: ExecutionReceipt; gate: GateData }>({
268
+ method: "POST",
269
+ path: `/gates/${id}/execution`,
270
+ body: { phase: "completed", ...input },
271
+ signal,
272
+ });
273
+ }
274
+
275
+ export class Gates {
276
+ constructor(private readonly http: HttpClient) {}
277
+
278
+ /**
279
+ * Ask whether you may act, and return at once — the same call as `create`,
280
+ * named for what it does. Policy answers; `canExecute` is the field to branch
281
+ * on, now or after `wait()`.
282
+ */
283
+ async check(input: CreateGateInput, signal?: AbortSignal): Promise<Gate> {
284
+ return this.create(input, signal);
285
+ }
286
+
287
+ /** Report what you did with a gate's permission. See `Gate.recordExecution`. */
288
+ async recordExecution(
289
+ id: string,
290
+ input: RecordExecutionInput = {},
291
+ signal?: AbortSignal
292
+ ): Promise<{ receipt: ExecutionReceipt; gate: Gate }> {
293
+ const { receipt, gate } = await recordExecution(this.http, id, input, signal);
294
+ return { receipt, gate: new Gate(this.http, gate) };
295
+ }
296
+
297
+ /** Withdraw a request, or an unused permission. */
298
+ async cancel(id: string, note?: string, agent?: GateAgentRef, signal?: AbortSignal): Promise<Gate> {
299
+ const data = await this.http.request<GateData>({
300
+ method: "POST",
301
+ path: `/gates/${id}/cancel`,
302
+ body: { note, agent },
303
+ signal,
304
+ });
305
+ return new Gate(this.http, data);
306
+ }
307
+
308
+ /**
309
+ * Have Deliverd make the staged report version the gate authorised live.
310
+ * The receipt is `verified`: Deliverd carried it out.
311
+ */
312
+ async release(
313
+ id: string,
314
+ agent?: GateAgentRef,
315
+ signal?: AbortSignal
316
+ ): Promise<{ receipt: ExecutionReceipt; gate: Gate; url: string }> {
317
+ const released = await this.http.request<{ receipt: ExecutionReceipt; gate: GateData; url: string }>({
318
+ method: "POST",
319
+ path: `/gates/${id}/release`,
320
+ body: { agent },
321
+ signal,
322
+ });
323
+ return { ...released, gate: new Gate(this.http, released.gate) };
324
+ }
325
+
326
+ /** The gate's evidence pack, as JSON. */
327
+ async evidence(id: string, signal?: AbortSignal): Promise<Record<string, unknown>> {
328
+ return this.http.request<Record<string, unknown>>({ method: "GET", path: `/gates/${id}/evidence`, signal });
329
+ }
330
+
331
+ /**
332
+ * Raise a decision and return straight away, even if it went to a person.
333
+ *
334
+ * The non-blocking half of `gate()`. Use it when the work resumes on a
335
+ * webhook or a later poll rather than inside this call.
336
+ */
337
+ async create(input: CreateGateInput, signal?: AbortSignal): Promise<Gate> {
338
+ const data = await this.http.request<GateData>({
339
+ method: "POST",
340
+ path: "/gates",
341
+ body: input,
342
+ /*
343
+ * The caller's own id, as the HTTP idempotency key too.
344
+ *
345
+ * The server enforces reuse against `gate_requests.external_id`, so this
346
+ * is belt and braces rather than the mechanism — but it means a retry
347
+ * inside the transport layer and a retry by the caller's own code are the
348
+ * same key, instead of one guarding the request and the other the
349
+ * decision.
350
+ */
351
+ idempotencyKey: input.externalId,
352
+ signal,
353
+ });
354
+ return new Gate(this.http, data);
355
+ }
356
+
357
+ /** One decision by its id. */
358
+ async get(id: string, signal?: AbortSignal): Promise<Gate> {
359
+ const data = await this.http.request<GateData>({
360
+ method: "GET",
361
+ path: `/gates/${id}`,
362
+ signal,
363
+ });
364
+ return new Gate(this.http, data);
365
+ }
366
+ }