@deliverd/sdk 0.25.1 → 0.27.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/README.md +104 -0
- package/dist/adapters/index.d.ts +4 -0
- package/dist/adapters/index.d.ts.map +1 -1
- package/dist/adapters/index.js +2 -0
- package/dist/adapters/mastra.d.ts +81 -0
- package/dist/adapters/mastra.d.ts.map +1 -0
- package/dist/adapters/mastra.js +54 -0
- package/dist/adapters/muse-spark.d.ts +79 -0
- package/dist/adapters/muse-spark.d.ts.map +1 -0
- package/dist/adapters/muse-spark.js +59 -0
- package/dist/adapters/shared.d.ts +2 -1
- package/dist/adapters/shared.d.ts.map +1 -1
- package/dist/data-screen.d.ts +233 -0
- package/dist/data-screen.d.ts.map +1 -0
- package/dist/data-screen.js +395 -0
- package/dist/decision-token.d.ts +102 -0
- package/dist/decision-token.d.ts.map +1 -0
- package/dist/decision-token.js +139 -0
- package/dist/dev.d.ts.map +1 -1
- package/dist/dev.js +57 -2
- package/dist/gates.d.ts +2 -0
- package/dist/gates.d.ts.map +1 -1
- package/dist/gates.js +3 -0
- package/dist/governance.d.ts +94 -0
- package/dist/governance.d.ts.map +1 -0
- package/dist/governance.js +166 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +35 -0
- package/dist/messages.d.ts.map +1 -1
- package/dist/messages.js +4 -0
- package/dist/released.d.ts +1 -1
- package/dist/released.d.ts.map +1 -1
- package/dist/released.js +3803 -0
- package/dist/screen.d.ts +85 -0
- package/dist/screen.d.ts.map +1 -0
- package/dist/screen.js +69 -0
- package/dist/tasks.d.ts +38 -1
- package/dist/tasks.d.ts.map +1 -1
- package/dist/tasks.js +67 -0
- package/dist/types.d.ts +656 -4
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/adapters/index.ts +11 -0
- package/src/adapters/mastra.ts +118 -0
- package/src/adapters/muse-spark.ts +147 -0
- package/src/adapters/shared.ts +2 -1
- package/src/data-screen.ts +536 -0
- package/src/decision-token.ts +184 -0
- package/src/dev.ts +63 -2
- package/src/gates.ts +3 -0
- package/src/governance.ts +204 -0
- package/src/index.ts +60 -0
- package/src/messages.ts +4 -0
- package/src/released.ts +3804 -0
- package/src/screen.ts +144 -0
- package/src/tasks.ts +88 -0
- package/src/types.ts +646 -4
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { createHash, createPublicKey, verify, type KeyObject } from "node:crypto";
|
|
2
|
+
import { DeliverdError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Checking a decision token where the action happens.
|
|
6
|
+
*
|
|
7
|
+
* A gate that may be acted on carries `decisionToken`: the yes, signed with
|
|
8
|
+
* the deployment's Ed25519 evidence key. Hand it to the service that performs
|
|
9
|
+
* the action — the one that issues the refund or merges the change — and that
|
|
10
|
+
* service checks it against what it is about to do before it does it:
|
|
11
|
+
*
|
|
12
|
+
* ```ts
|
|
13
|
+
* const check = await deliverd.decisionTokens.verify(req.headers["deliverd-decision"], {
|
|
14
|
+
* action: "finance.refund",
|
|
15
|
+
* input: { customer_id, amount, currency },
|
|
16
|
+
* });
|
|
17
|
+
* if (!check.ok) return res.status(403).send(check.reason);
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* It fails when the token was not signed by your Deliverd, has expired, is for
|
|
21
|
+
* another action, or was agreed for a different input: a refund of £1240
|
|
22
|
+
* against a yes for £1200 is refused. It needs no API key and makes no call
|
|
23
|
+
* beyond fetching the public key once.
|
|
24
|
+
*
|
|
25
|
+
* What it does not check is how many times the yes has been used. Record the
|
|
26
|
+
* execution against the gate (`gate.recordExecution`) to spend the use; the
|
|
27
|
+
* server refuses a second.
|
|
28
|
+
*
|
|
29
|
+
* Kept byte-for-byte with the server's `lib/governance/decision-token.ts`;
|
|
30
|
+
* `decision-token.test.ts` on the server signs there and verifies here.
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
export const DECISION_TOKEN_PREFIX = "dlv_dt1";
|
|
34
|
+
export const DECISION_TOKEN_CONTEXT = "deliverd-decision-token:v1:";
|
|
35
|
+
/** Where a deployment publishes the key that signs its tokens and evidence packs. */
|
|
36
|
+
export const EVIDENCE_KEY_PATH = "/.well-known/deliverd-evidence-key";
|
|
37
|
+
|
|
38
|
+
export interface DecisionTokenClaims {
|
|
39
|
+
v: 1;
|
|
40
|
+
kid: string;
|
|
41
|
+
iss: string;
|
|
42
|
+
org: string;
|
|
43
|
+
gate: string;
|
|
44
|
+
action: string;
|
|
45
|
+
/** Hex SHA-256 of the approved input in canonical JSON. */
|
|
46
|
+
input: string;
|
|
47
|
+
dest: { type: string; id: string } | null;
|
|
48
|
+
artifact: string | null;
|
|
49
|
+
iat: number;
|
|
50
|
+
exp: number;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface DecisionTokenExpectation {
|
|
54
|
+
/** The action you are about to perform. */
|
|
55
|
+
action: string;
|
|
56
|
+
/** The input you are about to perform it with. */
|
|
57
|
+
input: unknown;
|
|
58
|
+
/** Where it lands, when the gate named a destination. */
|
|
59
|
+
destination?: { type: string; id: string } | null;
|
|
60
|
+
/** The SHA-256 of what you are sending, when the gate named an artifact. */
|
|
61
|
+
artifactSha256?: string | null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type DecisionTokenFailure =
|
|
65
|
+
| "missing"
|
|
66
|
+
| "malformed"
|
|
67
|
+
| "bad_signature"
|
|
68
|
+
| "wrong_issuer"
|
|
69
|
+
| "expired"
|
|
70
|
+
| "wrong_action"
|
|
71
|
+
| "input_mismatch"
|
|
72
|
+
| "destination_mismatch"
|
|
73
|
+
| "artifact_mismatch";
|
|
74
|
+
|
|
75
|
+
export type DecisionTokenResult =
|
|
76
|
+
| { ok: true; claims: DecisionTokenClaims }
|
|
77
|
+
| { ok: false; reason: DecisionTokenFailure };
|
|
78
|
+
|
|
79
|
+
/** Keys sorted at every depth, undefined dropped: the server's `canonicalJson`. */
|
|
80
|
+
export function canonicalJson(value: unknown): string {
|
|
81
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value ?? null);
|
|
82
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
83
|
+
const entries = Object.entries(value as Record<string, unknown>)
|
|
84
|
+
.filter(([, v]) => v !== undefined)
|
|
85
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
86
|
+
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function decisionInputHash(input: unknown): string {
|
|
90
|
+
return createHash("sha256").update(canonicalJson(input ?? {}), "utf8").digest("hex");
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The server's `sameDestination`: addresses and domains ignore case, ids do not. */
|
|
94
|
+
function sameDestination(a: { type: string; id: string }, b: { type: string; id: string }): boolean {
|
|
95
|
+
if (a.type !== b.type) return false;
|
|
96
|
+
const fold = a.type === "email" || a.type === "domain";
|
|
97
|
+
return fold ? a.id.trim().toLowerCase() === b.id.trim().toLowerCase() : a.id.trim() === b.id.trim();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Verify with a key you already hold: a PEM string or a `KeyObject`. `issuer`
|
|
102
|
+
* is the origin of the deployment you trust, such as `https://deliverd.dev`.
|
|
103
|
+
*/
|
|
104
|
+
export function verifyDecisionToken(
|
|
105
|
+
token: string | null | undefined,
|
|
106
|
+
expected: DecisionTokenExpectation,
|
|
107
|
+
key: { publicKey: string | KeyObject; issuer: string; now?: Date; skewSeconds?: number }
|
|
108
|
+
): DecisionTokenResult {
|
|
109
|
+
if (!token) return { ok: false, reason: "missing" };
|
|
110
|
+
const parts = token.split(".");
|
|
111
|
+
if (parts.length !== 3 || parts[0] !== DECISION_TOKEN_PREFIX) return { ok: false, reason: "malformed" };
|
|
112
|
+
let claims: DecisionTokenClaims;
|
|
113
|
+
try {
|
|
114
|
+
claims = JSON.parse(Buffer.from(parts[1]!, "base64url").toString("utf8")) as DecisionTokenClaims;
|
|
115
|
+
} catch {
|
|
116
|
+
return { ok: false, reason: "malformed" };
|
|
117
|
+
}
|
|
118
|
+
if (claims?.v !== 1) return { ok: false, reason: "malformed" };
|
|
119
|
+
let good = false;
|
|
120
|
+
try {
|
|
121
|
+
const publicKey = typeof key.publicKey === "string" ? createPublicKey(key.publicKey) : key.publicKey;
|
|
122
|
+
good = verify(
|
|
123
|
+
null,
|
|
124
|
+
Buffer.from(DECISION_TOKEN_CONTEXT + parts[1], "utf8"),
|
|
125
|
+
publicKey,
|
|
126
|
+
Buffer.from(parts[2]!, "base64url")
|
|
127
|
+
);
|
|
128
|
+
} catch {
|
|
129
|
+
good = false;
|
|
130
|
+
}
|
|
131
|
+
if (!good) return { ok: false, reason: "bad_signature" };
|
|
132
|
+
if (claims.iss !== key.issuer.replace(/\/+$/, "")) return { ok: false, reason: "wrong_issuer" };
|
|
133
|
+
const now = Math.floor((key.now ?? new Date()).getTime() / 1000);
|
|
134
|
+
if (claims.exp + (key.skewSeconds ?? 30) <= now) return { ok: false, reason: "expired" };
|
|
135
|
+
if (claims.action !== expected.action) return { ok: false, reason: "wrong_action" };
|
|
136
|
+
if (claims.input !== decisionInputHash(expected.input)) return { ok: false, reason: "input_mismatch" };
|
|
137
|
+
if (claims.dest) {
|
|
138
|
+
const d = expected.destination;
|
|
139
|
+
if (!d || !sameDestination(d, claims.dest)) return { ok: false, reason: "destination_mismatch" };
|
|
140
|
+
}
|
|
141
|
+
if (claims.artifact && expected.artifactSha256 !== claims.artifact) return { ok: false, reason: "artifact_mismatch" };
|
|
142
|
+
return { ok: true, claims };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* `deliverd.decisionTokens`: verification against the deployment this client
|
|
147
|
+
* talks to. The key comes from that deployment's own well-known address and
|
|
148
|
+
* the issuer must be that deployment, never whatever the token names, so a
|
|
149
|
+
* token signed by somebody else's Deliverd does not pass.
|
|
150
|
+
*/
|
|
151
|
+
export class DecisionTokens {
|
|
152
|
+
private key: Promise<KeyObject> | null = null;
|
|
153
|
+
|
|
154
|
+
constructor(
|
|
155
|
+
private readonly baseUrl: string,
|
|
156
|
+
private readonly doFetch: typeof globalThis.fetch = globalThis.fetch
|
|
157
|
+
) {}
|
|
158
|
+
|
|
159
|
+
async verify(
|
|
160
|
+
token: string | null | undefined,
|
|
161
|
+
expected: DecisionTokenExpectation,
|
|
162
|
+
options: { now?: Date; skewSeconds?: number } = {}
|
|
163
|
+
): Promise<DecisionTokenResult> {
|
|
164
|
+
if (!token) return { ok: false, reason: "missing" };
|
|
165
|
+
const publicKey = await this.publicKey();
|
|
166
|
+
return verifyDecisionToken(token, expected, { publicKey, issuer: new URL(this.baseUrl).origin, ...options });
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private publicKey(): Promise<KeyObject> {
|
|
170
|
+
this.key ??= (async () => {
|
|
171
|
+
const res = await this.doFetch(`${this.baseUrl.replace(/\/+$/, "")}${EVIDENCE_KEY_PATH}`);
|
|
172
|
+
if (!res.ok) {
|
|
173
|
+
throw new DeliverdError(res.status, "no_signing_key", "This deployment does not publish a signing key.");
|
|
174
|
+
}
|
|
175
|
+
const body = (await res.json()) as { publicKey?: string };
|
|
176
|
+
if (!body.publicKey) throw new DeliverdError(0, "no_signing_key", "The signing key response had no public key.");
|
|
177
|
+
return createPublicKey(body.publicKey);
|
|
178
|
+
})().catch((err) => {
|
|
179
|
+
this.key = null;
|
|
180
|
+
throw err;
|
|
181
|
+
});
|
|
182
|
+
return this.key;
|
|
183
|
+
}
|
|
184
|
+
}
|
package/src/dev.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
ApprovalData,
|
|
3
3
|
CollectionData,
|
|
4
|
+
DeclaredAgent,
|
|
4
5
|
EvidencePack,
|
|
5
6
|
FlowData,
|
|
6
7
|
GateData,
|
|
@@ -11,6 +12,7 @@ import type {
|
|
|
11
12
|
TaskNode,
|
|
12
13
|
TaskState,
|
|
13
14
|
} from "./types.js";
|
|
15
|
+
import { assessCounts, DEFAULT_SCREEN_POLICY, describeCounts, type ScreenCounts } from "./data-screen.js";
|
|
14
16
|
|
|
15
17
|
/**
|
|
16
18
|
* Development mode: the whole loop, on your machine, with nobody in it.
|
|
@@ -95,7 +97,7 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
|
|
|
95
97
|
const flowStore = new Map<string, FlowData>();
|
|
96
98
|
const tasks = developmentTasks(options);
|
|
97
99
|
|
|
98
|
-
|
|
100
|
+
const handle = (async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
|
|
99
101
|
const url = new URL(String(input));
|
|
100
102
|
const path = url.pathname.replace(/^\/api\/v1/, "");
|
|
101
103
|
const method = (init?.method ?? "GET").toUpperCase();
|
|
@@ -128,6 +130,7 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
|
|
|
128
130
|
changes: [],
|
|
129
131
|
concerns: [],
|
|
130
132
|
requestedBy: "You (development mode)",
|
|
133
|
+
...declaredOf(body),
|
|
131
134
|
approvers: (body.approvers as string[] | undefined) ?? [],
|
|
132
135
|
/*
|
|
133
136
|
* One, always. A standing rule could raise it on a real organisation,
|
|
@@ -221,6 +224,7 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
|
|
|
221
224
|
externalId: (body.externalId as string | undefined) ?? null,
|
|
222
225
|
metadata: (body.metadata as Record<string, unknown>) ?? {},
|
|
223
226
|
requestedBy: "You (development mode)",
|
|
227
|
+
...declaredOf(body),
|
|
224
228
|
requiredApprovals: (body.requiredApprovals as number | undefined) ?? 1,
|
|
225
229
|
reviewers,
|
|
226
230
|
verdicts: [],
|
|
@@ -482,6 +486,7 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
|
|
|
482
486
|
externalId: (body.externalId as string | undefined) ?? null,
|
|
483
487
|
metadata: (body.metadata as Record<string, unknown>) ?? {},
|
|
484
488
|
requestedBy: "You (development mode)",
|
|
489
|
+
...declaredOf(body),
|
|
485
490
|
requiredResponses: (body.requiredResponses as number | undefined) ?? (asked.length || 1),
|
|
486
491
|
questions,
|
|
487
492
|
responses: asked.map((who) => ({
|
|
@@ -658,6 +663,47 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
|
|
|
658
663
|
return json({ tasks: tasks.list(url.searchParams), nextCursor: null });
|
|
659
664
|
}
|
|
660
665
|
|
|
666
|
+
/*
|
|
667
|
+
* Screening with no organisation behind it: no register record and no
|
|
668
|
+
* policy, so the defaults decide — internal data and no personal data
|
|
669
|
+
* approved — and an `ask` files an ordinary development approval, which
|
|
670
|
+
* the imaginary approver decides like any other.
|
|
671
|
+
*/
|
|
672
|
+
if (method === "POST" && path === "/screen") {
|
|
673
|
+
const counts = (body.counts ?? {}) as ScreenCounts;
|
|
674
|
+
const termClassification = body.termClassification === "restricted" ? "restricted" : "confidential";
|
|
675
|
+
const assessment = assessCounts(counts, null, DEFAULT_SCREEN_POLICY, termClassification);
|
|
676
|
+
let approval: { id: string; url: string; status: string } | null = null;
|
|
677
|
+
if (assessment.verdict === "ask" && body.ask !== false) {
|
|
678
|
+
const created = (await (
|
|
679
|
+
await handle(`${url.origin}/api/v1/approvals`, {
|
|
680
|
+
method: "POST",
|
|
681
|
+
body: JSON.stringify({
|
|
682
|
+
title: `Send ${describeCounts(counts)} to an AI model?`,
|
|
683
|
+
description: assessment.reasons.join("\n"),
|
|
684
|
+
risk: assessment.classification === "restricted" ? "high" : "medium",
|
|
685
|
+
externalId: body.externalId,
|
|
686
|
+
}),
|
|
687
|
+
})
|
|
688
|
+
).json()) as ApprovalData;
|
|
689
|
+
approval = { id: created.id, url: created.url, status: created.status };
|
|
690
|
+
}
|
|
691
|
+
return json({
|
|
692
|
+
verdict: assessment.verdict,
|
|
693
|
+
allowed: assessment.verdict === "allow" || assessment.verdict === "redact",
|
|
694
|
+
classification: assessment.classification,
|
|
695
|
+
personalData: assessment.personalData,
|
|
696
|
+
categories: assessment.categories,
|
|
697
|
+
counts,
|
|
698
|
+
offending: assessment.offending,
|
|
699
|
+
reasons: assessment.reasons,
|
|
700
|
+
target: null,
|
|
701
|
+
findings: null,
|
|
702
|
+
redactedText: null,
|
|
703
|
+
approval,
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
|
|
661
707
|
const taskMatch = /^\/tasks\/([^/]+)(?:\/(context|graph|side-tasks|findings|complete|apply|reopen|cancel|links))?$/.exec(path);
|
|
662
708
|
if (taskMatch) {
|
|
663
709
|
const [status, payload] = tasks.act(method, taskMatch[1]!, taskMatch[2] ?? null, body);
|
|
@@ -668,12 +714,27 @@ export function developmentFetch(options: DevelopmentOptions = {}): typeof globa
|
|
|
668
714
|
{
|
|
669
715
|
error: {
|
|
670
716
|
code: "not_in_development_mode",
|
|
671
|
-
message: `Development mode simulates approvals, reviews, collections, flows and
|
|
717
|
+
message: `Development mode simulates approvals, reviews, collections, flows, tasks and screening only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
|
|
672
718
|
},
|
|
673
719
|
},
|
|
674
720
|
501
|
|
675
721
|
);
|
|
676
722
|
}) as typeof globalThis.fetch;
|
|
723
|
+
return handle;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* The agent and model a request declared, as the API echoes them: what was
|
|
728
|
+
* sent, every field present, null when nothing was. Development mode stores
|
|
729
|
+
* nothing, so this is the whole of it.
|
|
730
|
+
*/
|
|
731
|
+
function declaredOf(body: Record<string, unknown>): { agent: DeclaredAgent | null; model: string | null } {
|
|
732
|
+
const a = body.agent as { name?: string; provider?: string; externalId?: string } | undefined;
|
|
733
|
+
const agent =
|
|
734
|
+
a && (a.name || a.provider || a.externalId)
|
|
735
|
+
? { name: a.name ?? null, provider: a.provider ?? null, externalId: a.externalId ?? null }
|
|
736
|
+
: null;
|
|
737
|
+
return { agent, model: typeof body.model === "string" && body.model ? body.model : null };
|
|
677
738
|
}
|
|
678
739
|
|
|
679
740
|
function resolveOutcome(
|
package/src/gates.ts
CHANGED
|
@@ -136,6 +136,8 @@ export class Gate {
|
|
|
136
136
|
get scope(): GateData["scope"] { return this.data.scope; }
|
|
137
137
|
/** How long it lasts and how many uses are left. */
|
|
138
138
|
get authorisation(): GateData["authorisation"] { return this.data.authorisation; }
|
|
139
|
+
/** The signed yes to hand the code that performs the action. Null unless `canExecute`. */
|
|
140
|
+
get decisionToken(): string | null { return this.data.decisionToken ?? null; }
|
|
139
141
|
/** A person sent it back. Revise and ask again with `supersedesGateId: gate.id`. */
|
|
140
142
|
get changesRequested(): boolean { return this.data.status === "changes_requested"; }
|
|
141
143
|
|
|
@@ -175,6 +177,7 @@ export class Gate {
|
|
|
175
177
|
changes: this.data.changes ?? [],
|
|
176
178
|
id: this.data.id,
|
|
177
179
|
approvalUrl: this.data.approvalUrl,
|
|
180
|
+
decisionToken: this.data.decisionToken ?? null,
|
|
178
181
|
gate: this,
|
|
179
182
|
};
|
|
180
183
|
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import type { HttpClient } from "./http.js";
|
|
2
|
+
import { listOrCollect, type PageOf } from "./paging.js";
|
|
3
|
+
import type {
|
|
4
|
+
AiIncident,
|
|
5
|
+
AiIncidentDetail,
|
|
6
|
+
AiSystem,
|
|
7
|
+
AiSystemDetail,
|
|
8
|
+
AuthorityDecision,
|
|
9
|
+
CheckAuthorityInput,
|
|
10
|
+
CreateCustomFrameworkInput,
|
|
11
|
+
CustomFramework,
|
|
12
|
+
DraftedIncidentReport,
|
|
13
|
+
DraftIncidentReportInput,
|
|
14
|
+
FrameworkCatalogue,
|
|
15
|
+
FrameworkMapping,
|
|
16
|
+
FrameworkMappingInput,
|
|
17
|
+
GovernanceSummary,
|
|
18
|
+
GovernanceSummaryInput,
|
|
19
|
+
IctRegister,
|
|
20
|
+
ListIncidentsInput,
|
|
21
|
+
ModelChangeInput,
|
|
22
|
+
ModelChangeResult,
|
|
23
|
+
RegisterAiSystemInput,
|
|
24
|
+
ReportIncidentInput,
|
|
25
|
+
UpdateAiSystemInput,
|
|
26
|
+
} from "./types.js";
|
|
27
|
+
|
|
28
|
+
const enc = encodeURIComponent;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The organisation's register of AI systems. A governed task names one by
|
|
32
|
+
* `aiSystemId` instead of describing it again, and a change of model is
|
|
33
|
+
* recorded here so every task using it is reassessed.
|
|
34
|
+
*/
|
|
35
|
+
export class AiSystems {
|
|
36
|
+
constructor(private readonly http: HttpClient) {}
|
|
37
|
+
|
|
38
|
+
/** The register, active and retired, or only one of them. */
|
|
39
|
+
async list(input: { status?: AiSystem["status"] } = {}, signal?: AbortSignal): Promise<AiSystem[]> {
|
|
40
|
+
const { aiSystems } = await this.http.request<{ aiSystems: AiSystem[] }>({
|
|
41
|
+
method: "GET",
|
|
42
|
+
path: "/ai-systems",
|
|
43
|
+
query: { status: input.status },
|
|
44
|
+
signal,
|
|
45
|
+
});
|
|
46
|
+
return aiSystems;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** One system, and the governed tasks that name it. */
|
|
50
|
+
get(id: string, signal?: AbortSignal): Promise<AiSystemDetail> {
|
|
51
|
+
return this.http.request<AiSystemDetail>({ method: "GET", path: `/ai-systems/${enc(id)}`, signal });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Add a system to the register. Digests of its prompt and guardrails, never the text. */
|
|
55
|
+
register(input: RegisterAiSystemInput, signal?: AbortSignal): Promise<AiSystem> {
|
|
56
|
+
return this.http.request<AiSystem>({ method: "POST", path: "/ai-systems", body: input, signal });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Change a system's record. An agent may raise its risk but not lower it, and may not retire it. */
|
|
60
|
+
update(id: string, input: UpdateAiSystemInput, signal?: AbortSignal): Promise<AiSystem> {
|
|
61
|
+
return this.http.request<AiSystem>({ method: "PATCH", path: `/ai-systems/${enc(id)}`, body: input, signal });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Record a new provider, model, version, prompt or guardrails (Enterprise).
|
|
66
|
+
* Every governed task using the system is reassessed, and evidence of the
|
|
67
|
+
* old release stops counting.
|
|
68
|
+
*/
|
|
69
|
+
recordModelChange(id: string, input: ModelChangeInput, signal?: AbortSignal): Promise<ModelChangeResult> {
|
|
70
|
+
return this.http.request<ModelChangeResult>({
|
|
71
|
+
method: "POST",
|
|
72
|
+
path: `/ai-systems/${enc(id)}/model-change`,
|
|
73
|
+
body: input,
|
|
74
|
+
signal,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* AI incidents, and the DORA reports on the major ones. A high or critical
|
|
81
|
+
* incident closes its task's governance gate until a person resolves it in
|
|
82
|
+
* Deliverd; classifying it, and submitting a report, are a person's too.
|
|
83
|
+
*/
|
|
84
|
+
export class Incidents {
|
|
85
|
+
constructor(private readonly http: HttpClient) {}
|
|
86
|
+
|
|
87
|
+
/** Report an incident against a governed task, an AI system, or both. */
|
|
88
|
+
report(input: ReportIncidentInput, signal?: AbortSignal): Promise<AiIncident> {
|
|
89
|
+
return this.http.request<AiIncident>({ method: "POST", path: "/governance/incidents", body: input, signal });
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** One incident: its DORA classification, its reports and their sign-off, and which report is due next. */
|
|
93
|
+
get(id: string, signal?: AbortSignal): Promise<AiIncidentDetail> {
|
|
94
|
+
return this.http.request<AiIncidentDetail>({ method: "GET", path: `/governance/incidents/${enc(id)}`, signal });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Newest first. With no `limit` this is every incident; with a `limit` it is
|
|
99
|
+
* one page of that size, and `listPage` hands back the cursor to continue from.
|
|
100
|
+
*/
|
|
101
|
+
async list(input: ListIncidentsInput = {}, signal?: AbortSignal): Promise<AiIncident[]> {
|
|
102
|
+
return listOrCollect(input, (q) => this.listPage({ ...input, ...q }, signal));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** One page, and the cursor to continue from — null when it is the end. */
|
|
106
|
+
listPage(input: ListIncidentsInput = {}, signal?: AbortSignal): Promise<PageOf<AiIncident>> {
|
|
107
|
+
return this.http.request<PageOf<AiIncident>>({
|
|
108
|
+
method: "GET",
|
|
109
|
+
path: "/governance/incidents",
|
|
110
|
+
query: { status: input.status, aiSystemId: input.aiSystemId, limit: input.limit, cursor: input.cursor },
|
|
111
|
+
signal,
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Draft a DORA report on a major incident and put it to a person to sign
|
|
117
|
+
* off. Reports follow in order: initial, intermediate, final. Needs
|
|
118
|
+
* `approvals:write` as well as `tasks:write`.
|
|
119
|
+
*/
|
|
120
|
+
draftReport(id: string, input: DraftIncidentReportInput, signal?: AbortSignal): Promise<DraftedIncidentReport> {
|
|
121
|
+
return this.http.request<DraftedIncidentReport>({
|
|
122
|
+
method: "POST",
|
|
123
|
+
path: `/governance/incidents/${enc(id)}/reports`,
|
|
124
|
+
body: input,
|
|
125
|
+
signal,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Compliance Mode across the organisation (Business and Enterprise): the AI
|
|
132
|
+
* system register, incidents, what an agent may do, the frameworks and the
|
|
133
|
+
* ICT register. A governed task's own governance is on `deliverd.tasks`.
|
|
134
|
+
*
|
|
135
|
+
* ```ts
|
|
136
|
+
* const { mode } = await deliverd.governance.checkAuthority({ action: "send" });
|
|
137
|
+
* if (mode === "denied") return;
|
|
138
|
+
* ```
|
|
139
|
+
*
|
|
140
|
+
* Every answer records governance and certifies nothing.
|
|
141
|
+
*/
|
|
142
|
+
export class AiGovernance {
|
|
143
|
+
readonly aiSystems: AiSystems;
|
|
144
|
+
readonly incidents: Incidents;
|
|
145
|
+
|
|
146
|
+
constructor(private readonly http: HttpClient) {
|
|
147
|
+
this.aiSystems = new AiSystems(http);
|
|
148
|
+
this.incidents = new Incidents(http);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* May this agent take this kind of action: on its own (`allowed`), only
|
|
153
|
+
* with a person's approval (`approval`), or not at all (`denied`)? By the
|
|
154
|
+
* organisation's policy and the agent's own, which can only be stricter
|
|
155
|
+
* (Enterprise). Reads; records nothing.
|
|
156
|
+
*/
|
|
157
|
+
checkAuthority(input: CheckAuthorityInput, signal?: AbortSignal): Promise<AuthorityDecision> {
|
|
158
|
+
return this.http.request<AuthorityDecision>({
|
|
159
|
+
method: "POST",
|
|
160
|
+
path: "/governance/authority/evaluate",
|
|
161
|
+
body: input,
|
|
162
|
+
signal,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The frameworks the organisation can see: the built-in packs and its own, and which are applied. */
|
|
167
|
+
frameworks(signal?: AbortSignal): Promise<FrameworkCatalogue> {
|
|
168
|
+
return this.http.request<FrameworkCatalogue>({ method: "GET", path: "/governance/frameworks", signal });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* How framework requirements map onto the common controls and, with
|
|
173
|
+
* `taskId`, how far that task's controls cover each one. A mapping, never
|
|
174
|
+
* a compliance verdict.
|
|
175
|
+
*/
|
|
176
|
+
frameworkMapping(input: FrameworkMappingInput = {}, signal?: AbortSignal): Promise<FrameworkMapping> {
|
|
177
|
+
return this.http.request<FrameworkMapping>({
|
|
178
|
+
method: "GET",
|
|
179
|
+
path: "/governance/frameworks/mapping",
|
|
180
|
+
query: { taskId: input.taskId, framework: input.framework },
|
|
181
|
+
signal,
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Draft the organisation's own framework (Enterprise). It adds nothing until a person publishes and applies it. */
|
|
186
|
+
createCustomFramework(input: CreateCustomFrameworkInput, signal?: AbortSignal): Promise<CustomFramework> {
|
|
187
|
+
return this.http.request<CustomFramework>({ method: "POST", path: "/governance/frameworks", body: input, signal });
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The ICT third-party register: providers, contracts, the AI systems under each, gaps and concentration. */
|
|
191
|
+
ictRegister(signal?: AbortSignal): Promise<IctRegister> {
|
|
192
|
+
return this.http.request<IctRegister>({ method: "GET", path: "/governance/ict-register", signal });
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The organisation's AI governance in counts, optionally narrowed. Never a compliance percentage. */
|
|
196
|
+
summary(input: GovernanceSummaryInput = {}, signal?: AbortSignal): Promise<GovernanceSummary> {
|
|
197
|
+
return this.http.request<GovernanceSummary>({
|
|
198
|
+
method: "GET",
|
|
199
|
+
path: "/governance/summary",
|
|
200
|
+
query: { ...input },
|
|
201
|
+
signal,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -6,8 +6,11 @@ import { Reviews, type ReviewWaitOptions } from "./reviews.js";
|
|
|
6
6
|
import { Collections, type CollectWaitOptions } from "./collections.js";
|
|
7
7
|
import { Flows } from "./flows.js";
|
|
8
8
|
import { Tasks } from "./tasks.js";
|
|
9
|
+
import { AiGovernance } from "./governance.js";
|
|
9
10
|
import { Webhooks } from "./webhooks.js";
|
|
11
|
+
import { DecisionTokens } from "./decision-token.js";
|
|
10
12
|
import { WebhookEndpoints } from "./webhook-endpoints.js";
|
|
13
|
+
import { screen, Screened, type ScreenOptions } from "./screen.js";
|
|
11
14
|
import { developmentFetch, type DevelopmentOptions } from "./dev.js";
|
|
12
15
|
import { durationMs, type Duration } from "./duration.js";
|
|
13
16
|
import { DeliverdError } from "./errors.js";
|
|
@@ -30,7 +33,35 @@ export { Review, Reviews, type ReviewWaitOptions } from "./reviews.js";
|
|
|
30
33
|
export { Collection, Collections, type CollectWaitOptions } from "./collections.js";
|
|
31
34
|
export { Flow, Flows, type FlowPrimitives } from "./flows.js";
|
|
32
35
|
export { Task, Tasks } from "./tasks.js";
|
|
36
|
+
export { AiGovernance, AiSystems, Incidents } from "./governance.js";
|
|
33
37
|
export { WebhookEndpoints } from "./webhook-endpoints.js";
|
|
38
|
+
export {
|
|
39
|
+
canonicalJson,
|
|
40
|
+
DECISION_TOKEN_CONTEXT,
|
|
41
|
+
DECISION_TOKEN_PREFIX,
|
|
42
|
+
decisionInputHash,
|
|
43
|
+
DecisionTokens,
|
|
44
|
+
EVIDENCE_KEY_PATH,
|
|
45
|
+
verifyDecisionToken,
|
|
46
|
+
type DecisionTokenClaims,
|
|
47
|
+
type DecisionTokenExpectation,
|
|
48
|
+
type DecisionTokenFailure,
|
|
49
|
+
type DecisionTokenResult,
|
|
50
|
+
} from "./decision-token.js";
|
|
51
|
+
export { Screened, type ScreenOptions } from "./screen.js";
|
|
52
|
+
export {
|
|
53
|
+
DATA_KINDS,
|
|
54
|
+
redact,
|
|
55
|
+
restore,
|
|
56
|
+
screenText,
|
|
57
|
+
summarise,
|
|
58
|
+
type DataKind,
|
|
59
|
+
type DetectedSpan,
|
|
60
|
+
type Redaction,
|
|
61
|
+
type ScreenFinding,
|
|
62
|
+
type ScreenTerm,
|
|
63
|
+
type SpanDetector,
|
|
64
|
+
} from "./data-screen.js";
|
|
34
65
|
export {
|
|
35
66
|
constructCallback,
|
|
36
67
|
constructEvent,
|
|
@@ -148,11 +179,15 @@ export class Deliverd {
|
|
|
148
179
|
readonly collections: Collections;
|
|
149
180
|
readonly flows: Flows;
|
|
150
181
|
readonly tasks: Tasks;
|
|
182
|
+
/** Compliance Mode across the organisation: AI systems, incidents, authority, frameworks, the ICT register. */
|
|
183
|
+
readonly governance: AiGovernance;
|
|
151
184
|
readonly reports: Reports;
|
|
152
185
|
readonly comments: Comments;
|
|
153
186
|
readonly schedules: Schedules;
|
|
154
187
|
readonly webhooks: Webhooks;
|
|
155
188
|
readonly webhookEndpoints: WebhookEndpoints;
|
|
189
|
+
/** Check a gate's signed yes where the action happens, before it happens. */
|
|
190
|
+
readonly decisionTokens: DecisionTokens;
|
|
156
191
|
readonly http: HttpClient;
|
|
157
192
|
/** Whether an imaginary approver is deciding these. */
|
|
158
193
|
readonly development: boolean;
|
|
@@ -181,11 +216,13 @@ export class Deliverd {
|
|
|
181
216
|
*/
|
|
182
217
|
this.flows = new Flows(this.http, this);
|
|
183
218
|
this.tasks = new Tasks(this.http);
|
|
219
|
+
this.governance = new AiGovernance(this.http);
|
|
184
220
|
this.reports = new Reports(this.http);
|
|
185
221
|
this.comments = new Comments(this.http);
|
|
186
222
|
this.schedules = new Schedules(this.http);
|
|
187
223
|
this.webhooks = new Webhooks();
|
|
188
224
|
this.webhookEndpoints = new WebhookEndpoints(this.http);
|
|
225
|
+
this.decisionTokens = new DecisionTokens(this.http.baseUrl, options.fetch);
|
|
189
226
|
}
|
|
190
227
|
|
|
191
228
|
/**
|
|
@@ -421,6 +458,29 @@ export class Deliverd {
|
|
|
421
458
|
}
|
|
422
459
|
|
|
423
460
|
/** Publish HTML to a secure URL. The sixth primitive, one call in. */
|
|
461
|
+
/**
|
|
462
|
+
* Check text before it goes to an AI model, and wait if a person has to decide.
|
|
463
|
+
*
|
|
464
|
+
* The detectors run here, so the text never leaves your machine: Deliverd is
|
|
465
|
+
* told only what was found, by kind, and answers from what your AI register
|
|
466
|
+
* approves that model to receive.
|
|
467
|
+
*
|
|
468
|
+
* ```ts
|
|
469
|
+
* const screened = await deliverd.screen(prompt, { aiSystemId: CLAIMS_MODEL });
|
|
470
|
+
* if (!screened.allowed) return screened.reasons;
|
|
471
|
+
* const answer = await model.generate(screened.text!);
|
|
472
|
+
* return screened.restore(answer);
|
|
473
|
+
* ```
|
|
474
|
+
*
|
|
475
|
+
* `allow` sends it as it is; `redact` gives you `screened.text` with the
|
|
476
|
+
* findings replaced by placeholders, and `restore()` puts them back in the
|
|
477
|
+
* answer; `ask` puts it to a person and waits; `deny` sends nothing. A net,
|
|
478
|
+
* not a guarantee: names in particular are not reliably found.
|
|
479
|
+
*/
|
|
480
|
+
screen(text: string, options: ScreenOptions = {}): Promise<Screened> {
|
|
481
|
+
return screen(this.http, this.approvals, text, options, this.development);
|
|
482
|
+
}
|
|
483
|
+
|
|
424
484
|
publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult> {
|
|
425
485
|
return this.reports.publish(input, signal);
|
|
426
486
|
}
|
package/src/messages.ts
CHANGED
|
@@ -181,6 +181,10 @@ export const EXPLANATIONS: Record<string, Explanation> = {
|
|
|
181
181
|
message: "That permission was withdrawn after it was given.",
|
|
182
182
|
hint: "Do not act. Read the gate for who revoked it and why, and ask again if the work still needs doing.",
|
|
183
183
|
},
|
|
184
|
+
agents_stopped: {
|
|
185
|
+
message: "A person has stopped every agent in this organisation.",
|
|
186
|
+
hint: "Do not act, and do not retry. Tell the user; nothing proceeds until somebody resumes the agents.",
|
|
187
|
+
},
|
|
184
188
|
gate_cancelled: {
|
|
185
189
|
message: "That request was withdrawn.",
|
|
186
190
|
hint: "Ask again if the work still needs doing.",
|