@deliverd/sdk 0.1.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/LICENSE +21 -0
- package/README.md +282 -0
- package/dist/approvals.d.ts +133 -0
- package/dist/approvals.d.ts.map +1 -0
- package/dist/approvals.js +228 -0
- package/dist/dev.d.ts +46 -0
- package/dist/dev.d.ts.map +1 -0
- package/dist/dev.js +147 -0
- package/dist/duration.d.ts +10 -0
- package/dist/duration.d.ts.map +1 -0
- package/dist/duration.js +10 -0
- package/dist/errors.d.ts +44 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +58 -0
- package/dist/http.d.ts +45 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +135 -0
- package/dist/index.d.ts +103 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +144 -0
- package/dist/messages.d.ts +24 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +70 -0
- package/dist/reports.d.ts +76 -0
- package/dist/reports.d.ts.map +1 -0
- package/dist/reports.js +168 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +11 -0
- package/dist/webhooks.d.ts +49 -0
- package/dist/webhooks.d.ts.map +1 -0
- package/dist/webhooks.js +77 -0
- package/package.json +55 -0
- package/src/approvals.ts +286 -0
- package/src/dev.ts +213 -0
- package/src/duration.ts +21 -0
- package/src/errors.ts +62 -0
- package/src/http.ts +185 -0
- package/src/index.ts +212 -0
- package/src/messages.ts +78 -0
- package/src/reports.ts +217 -0
- package/src/types.ts +213 -0
- package/src/webhooks.ts +98 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Deliverd
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
# @deliverd/sdk
|
|
2
|
+
|
|
3
|
+
You build the action. Deliverd handles the human.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @deliverd/sdk
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { deliverd } from "@deliverd/sdk";
|
|
11
|
+
|
|
12
|
+
const decision = await deliverd.approve({ title: "Deploy to production" });
|
|
13
|
+
|
|
14
|
+
if (decision.approved) await deploy();
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
That is the integration. What it stands in for: an approval page, the emails
|
|
18
|
+
and the reminders, identity and single sign-on, who is allowed to decide, a
|
|
19
|
+
table to keep it in, an audit trail, and the dashboard somebody uses to do it.
|
|
20
|
+
None of that is yours to build.
|
|
21
|
+
|
|
22
|
+
Your approver gets an email and a notification, opens a page that works on a
|
|
23
|
+
phone, and approves, rejects with a reason, or asks your agent a question.
|
|
24
|
+
Every step is on the record.
|
|
25
|
+
|
|
26
|
+
## Before you have an account
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
import { Deliverd } from "@deliverd/sdk";
|
|
30
|
+
|
|
31
|
+
const deliverd = new Deliverd({ mode: "development" });
|
|
32
|
+
const decision = await deliverd.approve({ title: "Deploy to production" });
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
No key, no network, nobody interrupted. It prints what the approver would have
|
|
36
|
+
seen and answers instantly:
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
┌─ Deliverd · development mode ─────────────────────────
|
|
40
|
+
│ Refund £1,240 to Acme
|
|
41
|
+
│ Duplicate charge on invoice 4821.
|
|
42
|
+
│ Risk: high
|
|
43
|
+
│ ✓ Within the refund limit
|
|
44
|
+
│ To: finance@example.com
|
|
45
|
+
│
|
|
46
|
+
│ Simulating: approved
|
|
47
|
+
└───────────────────────────────────────────────────────
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
All four things that can happen are one word away, including the one people
|
|
51
|
+
forget to write:
|
|
52
|
+
|
|
53
|
+
```ts
|
|
54
|
+
new Deliverd({ mode: "development", development: { outcome: "rejected" } });
|
|
55
|
+
new Deliverd({ mode: "development", development: { outcome: "timeout" } });
|
|
56
|
+
new Deliverd({ mode: "development", development: { outcome: "question" } });
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Or flip a whole test suite from the command line with
|
|
60
|
+
`DELIVERD_DEV_OUTCOME=rejected`. Development mode swaps out the network and
|
|
61
|
+
nothing else, so the code it exercises is the code that will run in
|
|
62
|
+
production — the same retries, the same errors, the same waiting.
|
|
63
|
+
|
|
64
|
+
## Configuration
|
|
65
|
+
|
|
66
|
+
There is none. `new Deliverd()` reads `DELIVERD_API_KEY`, and
|
|
67
|
+
`import { deliverd }` does not even need that line. Everything below has a
|
|
68
|
+
default that works:
|
|
69
|
+
|
|
70
|
+
| | Default |
|
|
71
|
+
|---|---|
|
|
72
|
+
| Who decides | Your organisation's owners and admins, unless you name `approvers` |
|
|
73
|
+
| Expiry | 24 hours, so a wait always ends |
|
|
74
|
+
| Notifications | Email and in-app, to whoever has to decide |
|
|
75
|
+
| Retries | Transient failures and rate limits, honouring `Retry-After` |
|
|
76
|
+
| Audit | On. Every request, question and decision, with the actor |
|
|
77
|
+
| Correlation id | Generated per request and sent with it |
|
|
78
|
+
| Webhook signing | Already signed; verify with `constructEvent` |
|
|
79
|
+
|
|
80
|
+
## Progressive depth
|
|
81
|
+
|
|
82
|
+
Level one is the five lines above. Level two adds context, which is what the
|
|
83
|
+
approver reads before deciding:
|
|
84
|
+
|
|
85
|
+
```ts
|
|
86
|
+
await deliverd.approve({
|
|
87
|
+
title: "Deploy release 4.2 to production",
|
|
88
|
+
description: "142 commits since 4.1. All checks green.",
|
|
89
|
+
risk: "high",
|
|
90
|
+
factors: [
|
|
91
|
+
{ label: "All checks green", status: "ok" },
|
|
92
|
+
{ label: "Touches the payments path", status: "warning", detail: "3 files under /billing" },
|
|
93
|
+
],
|
|
94
|
+
links: [{ label: "The diff", url: "https://github.com/…/compare/4.1...4.2" }],
|
|
95
|
+
approvers: ["dave@example.com"],
|
|
96
|
+
expiresIn: "4h",
|
|
97
|
+
externalId: "deploy_4842",
|
|
98
|
+
});
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`externalId` is your own reference. Pass one and a restarted agent reuses the
|
|
102
|
+
request it already made rather than asking a second time.
|
|
103
|
+
|
|
104
|
+
## Answering the approver
|
|
105
|
+
|
|
106
|
+
## Answering the approver
|
|
107
|
+
|
|
108
|
+
The thing that makes this more than a pause button: a person can ask your
|
|
109
|
+
agent a question from the approval page, and your agent can answer it without
|
|
110
|
+
anyone leaving what they are doing.
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
await approval.wait({
|
|
114
|
+
onQuestion: async (question) => {
|
|
115
|
+
// Return a string and it is posted as the answer; return null to leave
|
|
116
|
+
// it for a person.
|
|
117
|
+
return await agent.ask(question.question);
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Without a handler the question simply sits there — which is correct, because
|
|
123
|
+
the approver is waiting on an answer and nothing should move until they get
|
|
124
|
+
one or decide anyway.
|
|
125
|
+
|
|
126
|
+
## Waiting
|
|
127
|
+
|
|
128
|
+
`wait()` polls, backing off from two seconds to a minute with jitter, so a
|
|
129
|
+
hundred agents started by the same cron do not arrive together. It resolves
|
|
130
|
+
when the request settles, **including on a rejection** — a refusal is an
|
|
131
|
+
answer, and `if (approval.approved)` is the line that should follow.
|
|
132
|
+
|
|
133
|
+
It throws only when the wait itself failed:
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
try {
|
|
137
|
+
await approval.wait({ timeout: 30 * 60_000 });
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if (err instanceof DeliverdTimeoutError) {
|
|
140
|
+
// Nobody decided in time. The request is still open at approval.url.
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Give every request an `expiresAt` or every wait a `timeout`. A request with
|
|
146
|
+
neither can be waited on for ever, which is what `await` means.
|
|
147
|
+
|
|
148
|
+
`wait()` also takes an `AbortSignal`, and `onPoll` for a progress line.
|
|
149
|
+
|
|
150
|
+
## The primitives
|
|
151
|
+
|
|
152
|
+
```ts
|
|
153
|
+
await deliverd.approve({ title }); // ask, and wait for the answer
|
|
154
|
+
await deliverd.confirm({ title }); // a yes or no on something small → boolean
|
|
155
|
+
await deliverd.publish({ title, content }); // get the work to the people who need it
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
`review()` and `collect()` — a human reading an artifact and giving a verdict,
|
|
159
|
+
and a human filling in what your agent is missing — are the next two, and they
|
|
160
|
+
are **not in this package yet**, because the API behind them is not built yet.
|
|
161
|
+
They are stages three and four of
|
|
162
|
+
[the plan](https://github.com/davidpreid/deliverd/blob/main/docs/control-layer.md).
|
|
163
|
+
Shipping them now as methods that throw would put a lie in your autocomplete,
|
|
164
|
+
which is worse than their absence.
|
|
165
|
+
|
|
166
|
+
Under `approve()` is the full surface, when you want it:
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
await deliverd.approvals.create(input); // ask without waiting
|
|
170
|
+
await deliverd.approvals.get(id);
|
|
171
|
+
await deliverd.approvals.list({ status: "pending" });
|
|
172
|
+
await deliverd.approvals.findByExternalId("deploy_4842");
|
|
173
|
+
await approval.wait({ onQuestion });
|
|
174
|
+
await approval.answer(questionId, "…");
|
|
175
|
+
await approval.cancel(); // withdraw; the row stays
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Two rules the API enforces and the SDK cannot talk you out of: **an agent
|
|
179
|
+
never decides** — the decision takes a person's session, and there is no
|
|
180
|
+
endpoint for it — and **nobody approves their own request**. Approvers must be
|
|
181
|
+
members of your organisation, named by email or user id; an address that is
|
|
182
|
+
not a member is refused when you create the request, rather than notified into
|
|
183
|
+
nothing.
|
|
184
|
+
|
|
185
|
+
## Publishing
|
|
186
|
+
|
|
187
|
+
The other half of Deliverd: get what your agent wrote to the people who need
|
|
188
|
+
it, at an address that does not change.
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
const { report } = await deliverd.reports.publish({
|
|
192
|
+
title: "Q3 board pack",
|
|
193
|
+
content: html,
|
|
194
|
+
audience: "the Finance team",
|
|
195
|
+
});
|
|
196
|
+
console.log(report.url);
|
|
197
|
+
|
|
198
|
+
await deliverd.reports.update(report.id, { content: revised, changeSummary: "…" });
|
|
199
|
+
await deliverd.reports.share(report.id, "sarah@client.example");
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
A publishing policy can hold a version for a person's approval, so check
|
|
203
|
+
`result.status`: `published`, `updated` or `pending_approval`. When it is
|
|
204
|
+
held, `result.approval` names the request and nothing is live until somebody
|
|
205
|
+
says so.
|
|
206
|
+
|
|
207
|
+
Also on `reports`: `get`, `list`, `rename`, `archive`, `rollback`, `versions`,
|
|
208
|
+
`analytics`, `putData`, `listData`, `revisionBrief`.
|
|
209
|
+
|
|
210
|
+
And reader feedback:
|
|
211
|
+
|
|
212
|
+
```ts
|
|
213
|
+
const threads = await deliverd.comments.list(reportId);
|
|
214
|
+
await deliverd.comments.resolve(threadId, { note: "Fixed in v4." });
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Webhooks
|
|
218
|
+
|
|
219
|
+
Rather than polling, take the decision as it happens. Verify first — a
|
|
220
|
+
receiver that skips this accepts anything anyone posts at the URL.
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import { constructEvent } from "@deliverd/sdk";
|
|
224
|
+
|
|
225
|
+
app.post("/webhooks/deliverd", express.raw({ type: "application/json" }), (req, res) => {
|
|
226
|
+
const event = constructEvent(
|
|
227
|
+
process.env.DELIVERD_WEBHOOK_SECRET!,
|
|
228
|
+
req.body.toString("utf8"), // the raw body, not a re-encoded object
|
|
229
|
+
req.header("deliverd-signature")
|
|
230
|
+
);
|
|
231
|
+
|
|
232
|
+
if (event.event === "approval.approved") {
|
|
233
|
+
// event.data.approvalId, .externalId, .decidedBy, .note
|
|
234
|
+
}
|
|
235
|
+
res.sendStatus(200);
|
|
236
|
+
});
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
`constructEvent` throws if the signature does not verify; `verifySignature`
|
|
240
|
+
returns a boolean if you would rather branch. The scheme is Stripe's — a
|
|
241
|
+
timestamp and an HMAC in one header, the timestamp inside the signed material,
|
|
242
|
+
five minutes of tolerance — so anything you have written before will work too.
|
|
243
|
+
|
|
244
|
+
## Errors
|
|
245
|
+
|
|
246
|
+
An error is part of the interface, so it says what happened and the one thing
|
|
247
|
+
to do next:
|
|
248
|
+
|
|
249
|
+
```
|
|
250
|
+
No approver could be found for this request.
|
|
251
|
+
Everyone in `approvers` must be an active member of your organisation, named
|
|
252
|
+
by email or user id. Invite them first, or leave `approvers` out and your
|
|
253
|
+
owners and admins decide.
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Every failure is a `DeliverdError` with the API's `code`, the HTTP `status`,
|
|
257
|
+
the `hint` as its own property, and `isAuth`, `isNotFound`, `isRateLimit` and
|
|
258
|
+
`isConflict` for the cases worth branching on. Rate limits and 5xx are retried
|
|
259
|
+
for you; a 4xx is not, because it will be just as wrong a second later.
|
|
260
|
+
|
|
261
|
+
## Options
|
|
262
|
+
|
|
263
|
+
```ts
|
|
264
|
+
new Deliverd({
|
|
265
|
+
apiKey: process.env.DELIVERD_API_KEY, // default: DELIVERD_API_KEY
|
|
266
|
+
baseUrl: "https://deliverd.dev", // default: DELIVERD_BASE_URL
|
|
267
|
+
mode: "live", // default: DELIVERD_MODE
|
|
268
|
+
maxRetries: 3,
|
|
269
|
+
timeout: 30_000, // per request, not per wait
|
|
270
|
+
});
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Zero dependencies. Node 20 or later.
|
|
274
|
+
|
|
275
|
+
## Also
|
|
276
|
+
|
|
277
|
+
- The API reference: <https://deliverd.dev/docs/api>
|
|
278
|
+
- MCP, if your agent speaks it rather than TypeScript:
|
|
279
|
+
<https://deliverd.dev/connect>
|
|
280
|
+
- The CLI, for a terminal or a CI job: `npm install -g deliverd`
|
|
281
|
+
|
|
282
|
+
MIT.
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import type { HttpClient } from "./http.js";
|
|
2
|
+
import type { ApprovalData, ApprovalQuestion, CreateApprovalInput, Decision, ListApprovalsInput } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Ask a person before you act.
|
|
5
|
+
*
|
|
6
|
+
* The point of this module is one line — `await approval.wait()` — and
|
|
7
|
+
* everything in it exists to make that line safe to write in a real agent:
|
|
8
|
+
* polling that backs off instead of hammering, a question from the approver
|
|
9
|
+
* answered without leaving the wait, and an end that is guaranteed by the
|
|
10
|
+
* request's own expiry rather than by hope.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* How often to ask, as the wait gets longer. Milliseconds.
|
|
14
|
+
*
|
|
15
|
+
* The first one is deliberately quick. Most approvals take minutes, but the
|
|
16
|
+
* ones that take two seconds are the ones somebody is watching — a demo, a
|
|
17
|
+
* deploy with the approver stood next to you — and a client whose first look
|
|
18
|
+
* is two seconds away makes an instant decision feel like a slow one. One
|
|
19
|
+
* cheap early request buys that, and against a limit of 120 a minute it costs
|
|
20
|
+
* nothing. After a few polls the schedule is somebody's afternoon, not a
|
|
21
|
+
* progress bar.
|
|
22
|
+
*/
|
|
23
|
+
export declare const POLL_SCHEDULE: readonly [250, 750, 2000, 4000, 8000, 15000, 30000];
|
|
24
|
+
/** Development mode: the approver is imaginary and instant, so keep up. */
|
|
25
|
+
export declare const FAST_POLL_SCHEDULE: readonly [10, 25, 50, 100];
|
|
26
|
+
export interface WaitOptions {
|
|
27
|
+
/**
|
|
28
|
+
* Called when the approver asks the requester something. Return the answer
|
|
29
|
+
* and the wait posts it and carries on; return `null` to leave it for a
|
|
30
|
+
* person. Without this a question simply sits there — the approver is
|
|
31
|
+
* waiting on you, and nothing will move until it is answered or they decide
|
|
32
|
+
* anyway.
|
|
33
|
+
*/
|
|
34
|
+
onQuestion?: (question: ApprovalQuestion, approval: ApprovalData) => Promise<string | null> | string | null;
|
|
35
|
+
/** Called after every poll, for a progress line in a CLI. */
|
|
36
|
+
onPoll?: (approval: ApprovalData) => void;
|
|
37
|
+
/**
|
|
38
|
+
* Give up after this many milliseconds and throw `DeliverdTimeoutError`.
|
|
39
|
+
* Omitted, the wait ends when the request does — which, for a request with
|
|
40
|
+
* no `expiresAt`, may be never. Set one or the other.
|
|
41
|
+
*/
|
|
42
|
+
timeout?: number;
|
|
43
|
+
signal?: AbortSignal;
|
|
44
|
+
/**
|
|
45
|
+
* How long between polls, as the wait lengthens. Rarely worth changing —
|
|
46
|
+
* development mode uses it to keep up with an approver who is instant.
|
|
47
|
+
*/
|
|
48
|
+
pollIntervals?: readonly number[];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A request, and what you can do with it.
|
|
52
|
+
*
|
|
53
|
+
* The data is a snapshot; `wait()` and `refresh()` replace it in place, so a
|
|
54
|
+
* handle held across a wait reads the settled request rather than the one you
|
|
55
|
+
* created.
|
|
56
|
+
*/
|
|
57
|
+
export declare class Approval {
|
|
58
|
+
private readonly http;
|
|
59
|
+
private data;
|
|
60
|
+
constructor(http: HttpClient, data: ApprovalData);
|
|
61
|
+
get id(): string;
|
|
62
|
+
get status(): ApprovalData["status"];
|
|
63
|
+
/** The page the approver decides on. Put it in your own UI or logs. */
|
|
64
|
+
get url(): string;
|
|
65
|
+
get title(): string;
|
|
66
|
+
/** Their reason, when they gave one. */
|
|
67
|
+
get note(): string | null;
|
|
68
|
+
get decidedBy(): string | null;
|
|
69
|
+
get decidedAt(): string | null;
|
|
70
|
+
get questions(): ApprovalQuestion[];
|
|
71
|
+
/** Questions the approver is still waiting on you to answer. */
|
|
72
|
+
get openQuestions(): ApprovalQuestion[];
|
|
73
|
+
/** The one to branch on. False for rejected, expired and cancelled alike. */
|
|
74
|
+
get approved(): boolean;
|
|
75
|
+
get rejected(): boolean;
|
|
76
|
+
get expired(): boolean;
|
|
77
|
+
get cancelled(): boolean;
|
|
78
|
+
get pending(): boolean;
|
|
79
|
+
/** Everything the API returned, if you want a field the getters do not name. */
|
|
80
|
+
toJSON(): ApprovalData;
|
|
81
|
+
/**
|
|
82
|
+
* The answer, flattened — what `approve()` hands back.
|
|
83
|
+
*
|
|
84
|
+
* `approved` is a boolean so `if (decision.approved)` reads as the sentence
|
|
85
|
+
* it is; `status` is the narrowing union for a switch. Both, because people
|
|
86
|
+
* write both and neither should be the wrong one.
|
|
87
|
+
*/
|
|
88
|
+
toDecision(): Decision;
|
|
89
|
+
refresh(signal?: AbortSignal): Promise<this>;
|
|
90
|
+
/** Answer a question the approver asked. Only the requester may. */
|
|
91
|
+
answer(questionId: string, answer: string, signal?: AbortSignal): Promise<this>;
|
|
92
|
+
/** Withdraw it. The row stays as evidence of what was asked and dropped. */
|
|
93
|
+
cancel(signal?: AbortSignal): Promise<this>;
|
|
94
|
+
/**
|
|
95
|
+
* Block until a person decides, then return.
|
|
96
|
+
*
|
|
97
|
+
* Resolves on approved, rejected, expired and cancelled — it does not throw
|
|
98
|
+
* on a no, because a refusal is an answer and `if (approval.approved)` is
|
|
99
|
+
* the line that should follow. It throws only when the wait itself failed:
|
|
100
|
+
* a timeout, an abort, or the API being unreachable.
|
|
101
|
+
*/
|
|
102
|
+
wait(options?: WaitOptions): Promise<this>;
|
|
103
|
+
}
|
|
104
|
+
export declare class Approvals {
|
|
105
|
+
private readonly http;
|
|
106
|
+
constructor(http: HttpClient);
|
|
107
|
+
/**
|
|
108
|
+
* Ask. Returns as soon as the request is filed — the approvers are being
|
|
109
|
+
* told while this resolves — so call `wait()` next, or keep the id and poll
|
|
110
|
+
* later.
|
|
111
|
+
*/
|
|
112
|
+
create(input: CreateApprovalInput, signal?: AbortSignal): Promise<Approval>;
|
|
113
|
+
get(id: string, signal?: AbortSignal): Promise<Approval>;
|
|
114
|
+
list(input?: ListApprovalsInput, signal?: AbortSignal): Promise<Approval[]>;
|
|
115
|
+
/**
|
|
116
|
+
* Ask and wait, for the common case where there is nothing to do in
|
|
117
|
+
* between. `const { approved } = await deliverd.approvals.request({…})`.
|
|
118
|
+
*/
|
|
119
|
+
request(input: CreateApprovalInput, options?: WaitOptions): Promise<Approval>;
|
|
120
|
+
/**
|
|
121
|
+
* The same request as before, when there was one.
|
|
122
|
+
*
|
|
123
|
+
* Best effort, and worth being exact about what that means: it looks for a
|
|
124
|
+
* request with this `externalId` and returns it rather than filing a second.
|
|
125
|
+
* That makes an agent safe to restart — a crash between "asked" and
|
|
126
|
+
* "recorded that I asked" does not produce two notifications for one
|
|
127
|
+
* decision. Two *concurrent* calls can still both find nothing and both
|
|
128
|
+
* create; real idempotency needs a key the server enforces, and that is
|
|
129
|
+
* server work, not something a client can promise.
|
|
130
|
+
*/
|
|
131
|
+
findByExternalId(externalId: string, signal?: AbortSignal): Promise<Approval | null>;
|
|
132
|
+
}
|
|
133
|
+
//# sourceMappingURL=approvals.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"approvals.d.ts","sourceRoot":"","sources":["../src/approvals.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,KAAK,EACV,YAAY,EACZ,gBAAgB,EAChB,mBAAmB,EACnB,QAAQ,EACR,kBAAkB,EACnB,MAAM,YAAY,CAAC;AAEpB;;;;;;;;GAQG;AAEH;;;;;;;;;;GAUG;AACH,eAAO,MAAM,aAAa,qDAA2D,CAAC;AAGtF,2EAA2E;AAC3E,eAAO,MAAM,kBAAkB,4BAA6B,CAAC;AAQ7D,MAAM,WAAW,WAAW;IAC1B;;;;;;OAMG;IACH,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,gBAAgB,EAAE,QAAQ,EAAE,YAAY,KAAK,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,MAAM,GAAG,IAAI,CAAC;IAC5G,6DAA6D;IAC7D,MAAM,CAAC,EAAE,CAAC,QAAQ,EAAE,YAAY,KAAK,IAAI,CAAC;IAC1C;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;;OAGG;IACH,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC;AAED;;;;;;GAMG;AACH,qBAAa,QAAQ;IAEjB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,IAAI;gBADK,IAAI,EAAE,UAAU,EACzB,IAAI,EAAE,YAAY;IAG5B,IAAI,EAAE,IAAI,MAAM,CAAyB;IACzC,IAAI,MAAM,IAAI,YAAY,CAAC,QAAQ,CAAC,CAA6B;IACjE,uEAAuE;IACvE,IAAI,GAAG,IAAI,MAAM,CAA0B;IAC3C,IAAI,KAAK,IAAI,MAAM,CAA4B;IAC/C,wCAAwC;IACxC,IAAI,IAAI,IAAI,MAAM,GAAG,IAAI,CAA2B;IACpD,IAAI,SAAS,IAAI,MAAM,GAAG,IAAI,CAAgC;IAC9D,IAAI,SAAS,IAAI,MAAM,GAAG,IAAI,CAAgC;IAC9D,IAAI,SAAS,IAAI,gBAAgB,EAAE,CAAgC;IACnE,gEAAgE;IAChE,IAAI,aAAa,IAAI,gBAAgB,EAAE,CAAyD;IAEhG,6EAA6E;IAC7E,IAAI,QAAQ,IAAI,OAAO,CAA4C;IACnE,IAAI,QAAQ,IAAI,OAAO,CAA4C;IACnE,IAAI,OAAO,IAAI,OAAO,CAA2C;IACjE,IAAI,SAAS,IAAI,OAAO,CAA6C;IACrE,IAAI,OAAO,IAAI,OAAO,CAA2C;IAEjE,gFAAgF;IAChF,MAAM,IAAI,YAAY;IAEtB;;;;;;OAMG;IACH,UAAU,IAAI,QAAQ;IAchB,OAAO,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IASlD,oEAAoE;IAC9D,MAAM,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAUrF,4EAA4E;IACtE,MAAM,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IASjD;;;;;;;OAOG;IACG,IAAI,CAAC,OAAO,GAAE,WAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;CAsCrD;AAmBD,qBAAa,SAAS;IACR,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,EAAE,UAAU;IAE7C;;;;OAIG;IACG,MAAM,CAAC,KAAK,EAAE,mBAAmB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC;IAU3E,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,CAAC;IASxD,IAAI,CAAC,KAAK,GAAE,kBAAuB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,EAAE,CAAC;IAUrF;;;OAGG;IACG,OAAO,CACX,KAAK,EAAE,mBAAmB,EAC1B,OAAO,GAAE,WAAgB,GACxB,OAAO,CAAC,QAAQ,CAAC;IAKpB;;;;;;;;;;OAUG;IACG,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC;CAI3F"}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
|
|
2
|
+
/**
|
|
3
|
+
* Ask a person before you act.
|
|
4
|
+
*
|
|
5
|
+
* The point of this module is one line — `await approval.wait()` — and
|
|
6
|
+
* everything in it exists to make that line safe to write in a real agent:
|
|
7
|
+
* polling that backs off instead of hammering, a question from the approver
|
|
8
|
+
* answered without leaving the wait, and an end that is guaranteed by the
|
|
9
|
+
* request's own expiry rather than by hope.
|
|
10
|
+
*/
|
|
11
|
+
/**
|
|
12
|
+
* How often to ask, as the wait gets longer. Milliseconds.
|
|
13
|
+
*
|
|
14
|
+
* The first one is deliberately quick. Most approvals take minutes, but the
|
|
15
|
+
* ones that take two seconds are the ones somebody is watching — a demo, a
|
|
16
|
+
* deploy with the approver stood next to you — and a client whose first look
|
|
17
|
+
* is two seconds away makes an instant decision feel like a slow one. One
|
|
18
|
+
* cheap early request buys that, and against a limit of 120 a minute it costs
|
|
19
|
+
* nothing. After a few polls the schedule is somebody's afternoon, not a
|
|
20
|
+
* progress bar.
|
|
21
|
+
*/
|
|
22
|
+
export const POLL_SCHEDULE = [250, 750, 2_000, 4_000, 8_000, 15_000, 30_000];
|
|
23
|
+
const POLL_CEILING = 60_000;
|
|
24
|
+
/** Development mode: the approver is imaginary and instant, so keep up. */
|
|
25
|
+
export const FAST_POLL_SCHEDULE = [10, 25, 50, 100];
|
|
26
|
+
function pollDelay(poll, schedule) {
|
|
27
|
+
const base = schedule[Math.min(poll, schedule.length - 1)] ?? POLL_CEILING;
|
|
28
|
+
// Jitter, so a hundred agents started by the same cron do not arrive together.
|
|
29
|
+
return base * 0.75 + Math.random() * base * 0.5;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A request, and what you can do with it.
|
|
33
|
+
*
|
|
34
|
+
* The data is a snapshot; `wait()` and `refresh()` replace it in place, so a
|
|
35
|
+
* handle held across a wait reads the settled request rather than the one you
|
|
36
|
+
* created.
|
|
37
|
+
*/
|
|
38
|
+
export class Approval {
|
|
39
|
+
http;
|
|
40
|
+
data;
|
|
41
|
+
constructor(http, data) {
|
|
42
|
+
this.http = http;
|
|
43
|
+
this.data = data;
|
|
44
|
+
}
|
|
45
|
+
get id() { return this.data.id; }
|
|
46
|
+
get status() { return this.data.status; }
|
|
47
|
+
/** The page the approver decides on. Put it in your own UI or logs. */
|
|
48
|
+
get url() { return this.data.url; }
|
|
49
|
+
get title() { return this.data.title; }
|
|
50
|
+
/** Their reason, when they gave one. */
|
|
51
|
+
get note() { return this.data.note; }
|
|
52
|
+
get decidedBy() { return this.data.decidedBy; }
|
|
53
|
+
get decidedAt() { return this.data.decidedAt; }
|
|
54
|
+
get questions() { return this.data.questions; }
|
|
55
|
+
/** Questions the approver is still waiting on you to answer. */
|
|
56
|
+
get openQuestions() { return this.data.questions.filter((q) => !q.answer); }
|
|
57
|
+
/** The one to branch on. False for rejected, expired and cancelled alike. */
|
|
58
|
+
get approved() { return this.data.status === "approved"; }
|
|
59
|
+
get rejected() { return this.data.status === "rejected"; }
|
|
60
|
+
get expired() { return this.data.status === "expired"; }
|
|
61
|
+
get cancelled() { return this.data.status === "cancelled"; }
|
|
62
|
+
get pending() { return this.data.status === "pending"; }
|
|
63
|
+
/** Everything the API returned, if you want a field the getters do not name. */
|
|
64
|
+
toJSON() { return this.data; }
|
|
65
|
+
/**
|
|
66
|
+
* The answer, flattened — what `approve()` hands back.
|
|
67
|
+
*
|
|
68
|
+
* `approved` is a boolean so `if (decision.approved)` reads as the sentence
|
|
69
|
+
* it is; `status` is the narrowing union for a switch. Both, because people
|
|
70
|
+
* write both and neither should be the wrong one.
|
|
71
|
+
*/
|
|
72
|
+
toDecision() {
|
|
73
|
+
const status = this.data.status === "pending" ? "expired" : this.data.status;
|
|
74
|
+
return {
|
|
75
|
+
approved: this.data.status === "approved",
|
|
76
|
+
status,
|
|
77
|
+
note: this.data.note,
|
|
78
|
+
decidedBy: this.data.decidedBy,
|
|
79
|
+
decidedAt: this.data.decidedAt,
|
|
80
|
+
id: this.data.id,
|
|
81
|
+
url: this.data.url,
|
|
82
|
+
approval: this,
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
async refresh(signal) {
|
|
86
|
+
this.data = await this.http.request({
|
|
87
|
+
method: "GET",
|
|
88
|
+
path: `/approvals/${this.data.id}`,
|
|
89
|
+
signal,
|
|
90
|
+
});
|
|
91
|
+
return this;
|
|
92
|
+
}
|
|
93
|
+
/** Answer a question the approver asked. Only the requester may. */
|
|
94
|
+
async answer(questionId, answer, signal) {
|
|
95
|
+
this.data = await this.http.request({
|
|
96
|
+
method: "POST",
|
|
97
|
+
path: `/approvals/${this.data.id}/answers`,
|
|
98
|
+
body: { questionId, answer },
|
|
99
|
+
signal,
|
|
100
|
+
});
|
|
101
|
+
return this;
|
|
102
|
+
}
|
|
103
|
+
/** Withdraw it. The row stays as evidence of what was asked and dropped. */
|
|
104
|
+
async cancel(signal) {
|
|
105
|
+
this.data = await this.http.request({
|
|
106
|
+
method: "POST",
|
|
107
|
+
path: `/approvals/${this.data.id}/cancel`,
|
|
108
|
+
signal,
|
|
109
|
+
});
|
|
110
|
+
return this;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Block until a person decides, then return.
|
|
114
|
+
*
|
|
115
|
+
* Resolves on approved, rejected, expired and cancelled — it does not throw
|
|
116
|
+
* on a no, because a refusal is an answer and `if (approval.approved)` is
|
|
117
|
+
* the line that should follow. It throws only when the wait itself failed:
|
|
118
|
+
* a timeout, an abort, or the API being unreachable.
|
|
119
|
+
*/
|
|
120
|
+
async wait(options = {}) {
|
|
121
|
+
const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
|
|
122
|
+
let poll = 0;
|
|
123
|
+
// Already settled, or answered between create and wait.
|
|
124
|
+
if (!this.pending)
|
|
125
|
+
return this;
|
|
126
|
+
for (;;) {
|
|
127
|
+
if (options.signal?.aborted) {
|
|
128
|
+
throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
|
|
129
|
+
cause: options.signal.reason,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
if (deadline !== undefined && Date.now() >= deadline) {
|
|
133
|
+
throw new DeliverdTimeoutError(`Nobody decided "${this.data.title}" within the timeout. It is still open at ${this.data.url}.`);
|
|
134
|
+
}
|
|
135
|
+
const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
|
|
136
|
+
const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
|
|
137
|
+
await wait(Math.max(0, remaining), options.signal);
|
|
138
|
+
await this.refresh(options.signal);
|
|
139
|
+
options.onPoll?.(this.data);
|
|
140
|
+
if (options.onQuestion) {
|
|
141
|
+
for (const question of this.openQuestions) {
|
|
142
|
+
const answer = await options.onQuestion(question, this.data);
|
|
143
|
+
if (typeof answer === "string" && answer.trim()) {
|
|
144
|
+
await this.answer(question.id, answer, options.signal);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!this.pending)
|
|
149
|
+
return this;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function wait(ms, signal) {
|
|
154
|
+
return new Promise((resolve, reject) => {
|
|
155
|
+
if (signal?.aborted) {
|
|
156
|
+
return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
157
|
+
}
|
|
158
|
+
const timer = setTimeout(() => {
|
|
159
|
+
signal?.removeEventListener("abort", onAbort);
|
|
160
|
+
resolve();
|
|
161
|
+
}, ms);
|
|
162
|
+
const onAbort = () => {
|
|
163
|
+
clearTimeout(timer);
|
|
164
|
+
reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
165
|
+
};
|
|
166
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
export class Approvals {
|
|
170
|
+
http;
|
|
171
|
+
constructor(http) {
|
|
172
|
+
this.http = http;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Ask. Returns as soon as the request is filed — the approvers are being
|
|
176
|
+
* told while this resolves — so call `wait()` next, or keep the id and poll
|
|
177
|
+
* later.
|
|
178
|
+
*/
|
|
179
|
+
async create(input, signal) {
|
|
180
|
+
const data = await this.http.request({
|
|
181
|
+
method: "POST",
|
|
182
|
+
path: "/approvals",
|
|
183
|
+
body: input,
|
|
184
|
+
signal,
|
|
185
|
+
});
|
|
186
|
+
return new Approval(this.http, data);
|
|
187
|
+
}
|
|
188
|
+
async get(id, signal) {
|
|
189
|
+
const data = await this.http.request({
|
|
190
|
+
method: "GET",
|
|
191
|
+
path: `/approvals/${id}`,
|
|
192
|
+
signal,
|
|
193
|
+
});
|
|
194
|
+
return new Approval(this.http, data);
|
|
195
|
+
}
|
|
196
|
+
async list(input = {}, signal) {
|
|
197
|
+
const { approvals } = await this.http.request({
|
|
198
|
+
method: "GET",
|
|
199
|
+
path: "/approvals",
|
|
200
|
+
query: { status: input.status, externalId: input.externalId, limit: input.limit },
|
|
201
|
+
signal,
|
|
202
|
+
});
|
|
203
|
+
return approvals.map((a) => new Approval(this.http, a));
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Ask and wait, for the common case where there is nothing to do in
|
|
207
|
+
* between. `const { approved } = await deliverd.approvals.request({…})`.
|
|
208
|
+
*/
|
|
209
|
+
async request(input, options = {}) {
|
|
210
|
+
const approval = await this.create(input, options.signal);
|
|
211
|
+
return approval.wait(options);
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* The same request as before, when there was one.
|
|
215
|
+
*
|
|
216
|
+
* Best effort, and worth being exact about what that means: it looks for a
|
|
217
|
+
* request with this `externalId` and returns it rather than filing a second.
|
|
218
|
+
* That makes an agent safe to restart — a crash between "asked" and
|
|
219
|
+
* "recorded that I asked" does not produce two notifications for one
|
|
220
|
+
* decision. Two *concurrent* calls can still both find nothing and both
|
|
221
|
+
* create; real idempotency needs a key the server enforces, and that is
|
|
222
|
+
* server work, not something a client can promise.
|
|
223
|
+
*/
|
|
224
|
+
async findByExternalId(externalId, signal) {
|
|
225
|
+
const found = await this.list({ externalId, limit: 1 }, signal);
|
|
226
|
+
return found[0] ?? null;
|
|
227
|
+
}
|
|
228
|
+
}
|