@deliverd/sdk 0.25.1 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +65 -0
  2. package/dist/adapters/index.d.ts +4 -0
  3. package/dist/adapters/index.d.ts.map +1 -1
  4. package/dist/adapters/index.js +2 -0
  5. package/dist/adapters/mastra.d.ts +81 -0
  6. package/dist/adapters/mastra.d.ts.map +1 -0
  7. package/dist/adapters/mastra.js +54 -0
  8. package/dist/adapters/muse-spark.d.ts +79 -0
  9. package/dist/adapters/muse-spark.d.ts.map +1 -0
  10. package/dist/adapters/muse-spark.js +59 -0
  11. package/dist/adapters/shared.d.ts +2 -1
  12. package/dist/adapters/shared.d.ts.map +1 -1
  13. package/dist/data-screen.d.ts +233 -0
  14. package/dist/data-screen.d.ts.map +1 -0
  15. package/dist/data-screen.js +389 -0
  16. package/dist/dev.d.ts.map +1 -1
  17. package/dist/dev.js +42 -2
  18. package/dist/governance.d.ts +94 -0
  19. package/dist/governance.d.ts.map +1 -0
  20. package/dist/governance.js +166 -0
  21. package/dist/index.d.ts +27 -0
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +30 -0
  24. package/dist/released.d.ts +1 -1
  25. package/dist/released.d.ts.map +1 -1
  26. package/dist/released.js +1265 -0
  27. package/dist/screen.d.ts +85 -0
  28. package/dist/screen.d.ts.map +1 -0
  29. package/dist/screen.js +69 -0
  30. package/dist/tasks.d.ts +38 -1
  31. package/dist/tasks.d.ts.map +1 -1
  32. package/dist/tasks.js +67 -0
  33. package/dist/types.d.ts +589 -3
  34. package/dist/types.d.ts.map +1 -1
  35. package/package.json +2 -2
  36. package/src/adapters/index.ts +11 -0
  37. package/src/adapters/mastra.ts +118 -0
  38. package/src/adapters/muse-spark.ts +147 -0
  39. package/src/adapters/shared.ts +2 -1
  40. package/src/data-screen.ts +533 -0
  41. package/src/dev.ts +45 -2
  42. package/src/governance.ts +204 -0
  43. package/src/index.ts +43 -0
  44. package/src/released.ts +1265 -0
  45. package/src/screen.ts +144 -0
  46. package/src/tasks.ts +88 -0
  47. package/src/types.ts +577 -3
@@ -0,0 +1,389 @@
1
+ /**
2
+ * Screening what an agent is about to send to an AI model.
3
+ *
4
+ * Before a prompt, a document or a retrieved record goes to a model, this
5
+ * finds the personal data, secrets and confidential terms in it, says how
6
+ * sensitive the whole is, and decides — against what the organisation has
7
+ * approved that model to receive — whether it may go as it is, go with the
8
+ * findings replaced by placeholders, go only once a person agrees, or not go.
9
+ *
10
+ * Three lines are held throughout:
11
+ *
12
+ * - **The text need not leave the caller.** Everything here is pure and has no
13
+ * imports, so the SDKs run the same detectors where the agent runs and send
14
+ * Deliverd only counts: "two email addresses, one IBAN". This file is copied
15
+ * verbatim into `packages/sdk/src/data-screen.ts` and into the open-source
16
+ * `packages/screen/src/data-screen.ts`, and a test fails when they differ.
17
+ * - **A finding never carries its value off the machine.** `ScreenFinding` has
18
+ * offsets into the caller's own text; `summarise` keeps only counts.
19
+ * - **Detection is a net, not a guarantee.** Patterns find structured
20
+ * identifiers well and names hardly at all; a name is personal data and
21
+ * nothing here claims to have found every one. Pseudonymised text is still
22
+ * personal data in law. What this buys is fewer identifiers sent, a record of
23
+ * what was, and a person asked when it matters — never a certificate that a
24
+ * prompt is clean.
25
+ */
26
+ /** Ordered: the stricter of two classifications is the later one. */
27
+ export const SCREEN_CLASSIFICATIONS = ["public", "internal", "confidential", "restricted"];
28
+ export const SCREEN_CATEGORIES = ["personal", "financial", "special", "secret", "confidential"];
29
+ export const SCREEN_VERDICTS = ["allow", "redact", "ask", "deny"];
30
+ export const DATA_KINDS = {
31
+ email: { label: "Email address", category: "personal", placeholder: "EMAIL", redactable: true },
32
+ phone: { label: "Phone number", category: "personal", placeholder: "PHONE", redactable: true },
33
+ iban: { label: "IBAN", category: "financial", placeholder: "IBAN", redactable: true },
34
+ payment_card: { label: "Payment card number", category: "financial", placeholder: "CARD", redactable: true },
35
+ uk_national_insurance: { label: "UK National Insurance number", category: "personal", placeholder: "NINO", redactable: true },
36
+ ie_pps: { label: "Irish PPS number", category: "personal", placeholder: "PPS", redactable: true },
37
+ us_ssn: { label: "US Social Security number", category: "personal", placeholder: "SSN", redactable: true },
38
+ ip_address: { label: "IP address", category: "personal", placeholder: "IP", redactable: true },
39
+ date_of_birth: { label: "Date of birth", category: "personal", placeholder: "DOB", redactable: true },
40
+ /** Never found by a pattern here: only by a model detector the caller plugs in (`spans`). */
41
+ person_name: { label: "Person's name", category: "personal", placeholder: "NAME", redactable: true },
42
+ special_category: { label: "Special-category data", category: "special", placeholder: "SPECIAL", redactable: false },
43
+ secret: { label: "Secret or credential", category: "secret", placeholder: "SECRET", redactable: true },
44
+ term: { label: "Confidential term", category: "confidential", placeholder: "TERM", redactable: true },
45
+ };
46
+ export const DATA_KIND_KEYS = Object.keys(DATA_KINDS);
47
+ const CATEGORY_CLASSIFICATION = {
48
+ personal: "confidential",
49
+ financial: "confidential",
50
+ confidential: "confidential",
51
+ special: "restricted",
52
+ secret: "restricted",
53
+ };
54
+ /** Categories that are personal data, for a target approved for none. */
55
+ const PERSONAL_CATEGORIES = new Set(["personal", "financial", "special"]);
56
+ const digitsOf = (s) => s.replace(/\D/g, "");
57
+ function luhn(digits) {
58
+ let sum = 0;
59
+ let double = false;
60
+ for (let i = digits.length - 1; i >= 0; i--) {
61
+ let d = digits.charCodeAt(i) - 48;
62
+ if (double) {
63
+ d *= 2;
64
+ if (d > 9)
65
+ d -= 9;
66
+ }
67
+ sum += d;
68
+ double = !double;
69
+ }
70
+ return sum % 10 === 0;
71
+ }
72
+ function ibanValid(raw) {
73
+ const iban = raw.replace(/\s/g, "").toUpperCase();
74
+ if (iban.length < 15 || iban.length > 34)
75
+ return false;
76
+ const moved = iban.slice(4) + iban.slice(0, 4);
77
+ let remainder = 0;
78
+ for (const ch of moved) {
79
+ const code = ch.charCodeAt(0);
80
+ const value = code >= 65 && code <= 90 ? String(code - 55) : ch;
81
+ for (const digit of value)
82
+ remainder = (remainder * 10 + (digit.charCodeAt(0) - 48)) % 97;
83
+ }
84
+ return remainder === 1;
85
+ }
86
+ /** The PPS check character: weights 8 to 2 on the digits, 9 on a second letter, mod 23, 0 is W. */
87
+ function ppsValid(raw) {
88
+ const m = /^(\d{7})([A-W])([A-IW]?)$/.exec(raw.toUpperCase());
89
+ if (!m)
90
+ return false;
91
+ let sum = 0;
92
+ for (let i = 0; i < 7; i++)
93
+ sum += (m[1].charCodeAt(i) - 48) * (8 - i);
94
+ if (m[3])
95
+ sum += (m[3] === "W" ? 0 : m[3].charCodeAt(0) - 64) * 9;
96
+ const r = sum % 23;
97
+ return m[2] === (r === 0 ? "W" : String.fromCharCode(64 + r));
98
+ }
99
+ function ipv4Valid(raw) {
100
+ const parts = raw.split(".").map(Number);
101
+ if (parts.length !== 4 || parts.some((p) => p > 255))
102
+ return false;
103
+ // Loopback and the unspecified address identify nobody.
104
+ return parts[0] !== 127 && parts[0] !== 0;
105
+ }
106
+ /**
107
+ * Credential patterns. The same set the publish scanner blocks a report for,
108
+ * because a key that must not be published must not be sent to a model either.
109
+ */
110
+ const SECRET_PATTERNS = [
111
+ /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,
112
+ /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/g,
113
+ /\bgh[pousr]_[A-Za-z0-9]{36,255}\b/g,
114
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/g,
115
+ /\b[sr]k_(?:live|test)_[A-Za-z0-9]{20,}\b/g,
116
+ /\bsk-ant-[A-Za-z0-9_-]{24,}\b/g,
117
+ /\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\b/g,
118
+ /\bAIza[0-9A-Za-z_-]{35}\b/g,
119
+ /\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,
120
+ /\b(?:password|passwd|secret_key|api_key|apikey|auth_token)\s*[:=]\s*["'][^"']{8,}["']/gi,
121
+ /\b(?:dlv|dlvk)_[A-Za-z0-9]{24,}\b/g,
122
+ ];
123
+ /**
124
+ * Words that say a passage is about special-category data (GDPR Article 9,
125
+ * and criminal-offence data under Article 10). A keyword is a weak signal, so
126
+ * it is never redacted away: it sends the passage to a person when the target
127
+ * is not approved for restricted personal data.
128
+ */
129
+ const SPECIAL_PATTERN = /\b(?:diagnos(?:is|ed|es)|medical (?:record|history|condition)s?|mental health|prescri(?:bed|ption)s?|HIV|pregnan(?:t|cy)|disabilit(?:y|ies)|sexual orientation|religious belief|ethnic origin|racial origin|trade union member(?:ship)?|biometric|genetic data|criminal (?:record|conviction|offence)s?)\b/gi;
130
+ const DETECTORS = [
131
+ ...SECRET_PATTERNS.map((pattern) => ({ kind: "secret", pattern })),
132
+ { kind: "iban", pattern: /\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,4})?\b/g, valid: ibanValid },
133
+ {
134
+ kind: "payment_card",
135
+ pattern: /\b[2-6]\d{3}(?:[ -]?\d{4}){2}[ -]?\d{1,7}\b/g,
136
+ valid: (m) => {
137
+ const d = digitsOf(m);
138
+ return d.length >= 13 && d.length <= 19 && luhn(d);
139
+ },
140
+ },
141
+ { kind: "us_ssn", pattern: /\b(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}\b/g },
142
+ {
143
+ kind: "uk_national_insurance",
144
+ pattern: /\b(?!BG|GB|NK|KN|TN|NT|ZZ)[A-CEGHJ-PR-TW-Z][A-CEGHJ-NPR-TW-Z] ?\d{2} ?\d{2} ?\d{2} ?[A-D]\b/g,
145
+ },
146
+ { kind: "ie_pps", pattern: /\b\d{7}[A-W][A-IW]?\b/g, valid: ppsValid },
147
+ { kind: "email", pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}\b/g },
148
+ {
149
+ kind: "date_of_birth",
150
+ pattern: /\b(?:date of birth|d\.?o\.?b\.?|born(?: on)?)\s*[:\-]?\s*(\d{1,2}[\/.\-]\d{1,2}[\/.\-]\d{2,4}|\d{4}-\d{2}-\d{2}|\d{1,2} (?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[a-z]* \d{4})/gi,
151
+ group: 1,
152
+ },
153
+ {
154
+ kind: "phone",
155
+ // An international number, or a national one starting with 0: a bare run
156
+ // of digits is far more often an amount, an id or a date.
157
+ pattern: /(?<![\w+])(?:\+\d{1,3}[ .-]?(?:\(0\)[ .-]?)?|\(?0)\d{1,4}\)?(?:[ .-]?\d{2,4}){2,4}(?![\w])/g,
158
+ valid: (m) => {
159
+ const d = digitsOf(m);
160
+ return d.length >= 9 && d.length <= 15;
161
+ },
162
+ },
163
+ { kind: "ip_address", pattern: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g, valid: ipv4Valid },
164
+ { kind: "special_category", pattern: SPECIAL_PATTERN },
165
+ ];
166
+ /** Earlier wins an overlap: a card number is not also a phone number. */
167
+ const PRIORITY = Object.fromEntries(["secret", "iban", "payment_card", "us_ssn", "uk_national_insurance", "ie_pps", "email", "date_of_birth", "phone", "ip_address", "term", "person_name", "special_category"].map((k, i) => [k, i]));
168
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
169
+ /** Terms past this are ignored, so a pasted list cannot make every screen slow. */
170
+ export const MAX_SCREEN_TERMS = 500;
171
+ /**
172
+ * Find what is in a text. Overlapping matches keep the stronger kind, so each
173
+ * character belongs to at most one finding. `spans` are another detector's
174
+ * findings, held to the same rules; one outside the text or of no known kind
175
+ * is dropped.
176
+ */
177
+ export function screenText(text, terms = [], spans = []) {
178
+ const raw = [];
179
+ const add = (kind, start, end, label, classification) => {
180
+ const spec = DATA_KINDS[kind];
181
+ raw.push({
182
+ kind,
183
+ category: spec.category,
184
+ classification: classification ?? CATEGORY_CLASSIFICATION[spec.category],
185
+ start,
186
+ end,
187
+ label: label ?? spec.label,
188
+ redactable: spec.redactable,
189
+ });
190
+ };
191
+ for (const d of DETECTORS) {
192
+ d.pattern.lastIndex = 0;
193
+ for (const m of text.matchAll(d.pattern)) {
194
+ const value = d.group ? m[d.group] : m[0];
195
+ if (!value || (d.valid && !d.valid(value)))
196
+ continue;
197
+ const start = d.group ? m.index + m[0].lastIndexOf(value) : m.index;
198
+ add(d.kind, start, start + value.length);
199
+ }
200
+ }
201
+ for (const t of terms.slice(0, MAX_SCREEN_TERMS)) {
202
+ const term = t.term.trim();
203
+ if (term.length < 2)
204
+ continue;
205
+ const pattern = new RegExp(`(?<![\\p{L}\\p{N}])${escapeRegExp(term)}(?![\\p{L}\\p{N}])`, "giu");
206
+ for (const m of text.matchAll(pattern)) {
207
+ add("term", m.index, m.index + m[0].length, t.label?.trim() || DATA_KINDS.term.label, t.classification ?? "confidential");
208
+ }
209
+ }
210
+ for (const s of spans) {
211
+ if (!Object.hasOwn(DATA_KINDS, s.kind) || s.kind === "term")
212
+ continue;
213
+ if (!Number.isInteger(s.start) || !Number.isInteger(s.end) || s.start < 0 || s.end > text.length || s.end <= s.start)
214
+ continue;
215
+ add(s.kind, s.start, s.end);
216
+ }
217
+ raw.sort((a, b) => PRIORITY[a.kind] - PRIORITY[b.kind] || b.end - b.start - (a.end - a.start) || a.start - b.start);
218
+ const kept = [];
219
+ for (const f of raw) {
220
+ if (kept.some((k) => f.start < k.end && k.start < f.end))
221
+ continue;
222
+ kept.push(f);
223
+ }
224
+ return kept.sort((a, b) => a.start - b.start);
225
+ }
226
+ /** Counts only: what goes over the wire when the text stays where it is. */
227
+ export function summarise(findings) {
228
+ const counts = {};
229
+ for (const f of findings)
230
+ counts[f.kind] = (counts[f.kind] ?? 0) + 1;
231
+ return counts;
232
+ }
233
+ const placeholderWord = (f) => f.kind === "term" && f.label !== DATA_KINDS.term.label
234
+ ? f.label.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_|_$/g, "").slice(0, 24) || "TERM"
235
+ : DATA_KINDS[f.kind].placeholder;
236
+ /**
237
+ * Replace each redactable finding with a placeholder. The same value gets the
238
+ * same placeholder throughout, so a model can still tell that two mentions are
239
+ * one person, and `restore` can put the values back in its answer.
240
+ */
241
+ export function redact(text, findings) {
242
+ const replacements = {};
243
+ const byValue = new Map();
244
+ const counters = new Map();
245
+ let out = "";
246
+ let at = 0;
247
+ for (const f of [...findings].sort((a, b) => a.start - b.start)) {
248
+ if (!f.redactable || f.start < at)
249
+ continue;
250
+ const value = text.slice(f.start, f.end);
251
+ const key = `${f.kind}\u0000${value.toLowerCase()}`;
252
+ let placeholder = byValue.get(key);
253
+ if (!placeholder) {
254
+ const word = placeholderWord(f);
255
+ const n = (counters.get(word) ?? 0) + 1;
256
+ counters.set(word, n);
257
+ placeholder = `[${word}_${n}]`;
258
+ byValue.set(key, placeholder);
259
+ replacements[placeholder] = value;
260
+ }
261
+ out += text.slice(at, f.start) + placeholder;
262
+ at = f.end;
263
+ }
264
+ return { text: out + text.slice(at), replacements };
265
+ }
266
+ /** Put the original values back into text a model wrote using the placeholders. */
267
+ export function restore(text, replacements) {
268
+ const keys = Object.keys(replacements).sort((a, b) => b.length - a.length);
269
+ if (keys.length === 0)
270
+ return text;
271
+ const pattern = new RegExp(keys.map(escapeRegExp).join("|"), "g");
272
+ return text.replace(pattern, (p) => replacements[p] ?? p);
273
+ }
274
+ export const DEFAULT_SCREEN_POLICY = {
275
+ secrets: "deny",
276
+ beyondApproval: "redact",
277
+ notRedactable: "ask",
278
+ unregistered: { approvedClassification: "internal", personalData: false },
279
+ };
280
+ const rank = (c) => SCREEN_CLASSIFICATIONS.indexOf(c);
281
+ const VERDICT_RANK = { allow: 0, redact: 1, ask: 2, deny: 3 };
282
+ const stricter = (a, b) => (VERDICT_RANK[b] > VERDICT_RANK[a] ? b : a);
283
+ /** Reads a stored or sent policy, keeping a default for anything missing or unknown. */
284
+ export function readScreenPolicy(raw) {
285
+ const p = (raw && typeof raw === "object" ? raw : {});
286
+ const actions = ["redact", "ask", "deny"];
287
+ const pick = (v, allowed, fallback) => typeof v === "string" && allowed.includes(v) ? v : fallback;
288
+ const u = (p.unregistered && typeof p.unregistered === "object" ? p.unregistered : {});
289
+ return {
290
+ secrets: pick(p.secrets, actions, DEFAULT_SCREEN_POLICY.secrets),
291
+ beyondApproval: pick(p.beyondApproval, actions, DEFAULT_SCREEN_POLICY.beyondApproval),
292
+ notRedactable: pick(p.notRedactable, ["ask", "deny"], DEFAULT_SCREEN_POLICY.notRedactable),
293
+ unregistered: {
294
+ approvedClassification: pick(u.approvedClassification, SCREEN_CLASSIFICATIONS, DEFAULT_SCREEN_POLICY.unregistered.approvedClassification),
295
+ personalData: typeof u.personalData === "boolean" ? u.personalData : DEFAULT_SCREEN_POLICY.unregistered.personalData,
296
+ },
297
+ };
298
+ }
299
+ const plural = (n, label) => `${n} ${label.toLowerCase()}${n === 1 ? "" : "s"}`;
300
+ /** "2 email addresses and 1 IBAN", for a reason or an approval's title. */
301
+ export function describeCounts(counts) {
302
+ const parts = DATA_KIND_KEYS.filter((k) => (counts[k] ?? 0) > 0).map((k) => {
303
+ const n = counts[k];
304
+ const label = DATA_KINDS[k].label;
305
+ if (k === "email")
306
+ return `${n} email address${n === 1 ? "" : "es"}`;
307
+ if (k === "special_category")
308
+ return `${n} mention${n === 1 ? "" : "s"} of special-category data`;
309
+ if (k === "secret")
310
+ return `${n} secret${n === 1 ? "" : "s"} or credential${n === 1 ? "" : "s"}`;
311
+ if (k === "term")
312
+ return plural(n, "confidential term");
313
+ if (k === "person_name")
314
+ return `${n} ${n === 1 ? "person's name" : "people's names"}`;
315
+ return /^[A-Z]{2,}/.test(label) ? `${n} ${label}${n === 1 ? "" : "s"}` : plural(n, label);
316
+ });
317
+ if (parts.length <= 1)
318
+ return parts[0] ?? "nothing";
319
+ return `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}`;
320
+ }
321
+ /**
322
+ * Decide from counts alone, so the same answer comes back whether the text was
323
+ * screened here or on the caller's machine.
324
+ *
325
+ * `termClassification` is the strictest classification among the terms found,
326
+ * which counts cannot carry; restricted when a caller says so.
327
+ */
328
+ export function assessCounts(counts, target, policy = DEFAULT_SCREEN_POLICY, termClassification = "confidential") {
329
+ const present = DATA_KIND_KEYS.filter((k) => (counts[k] ?? 0) > 0);
330
+ const categories = SCREEN_CATEGORIES.filter((c) => present.some((k) => DATA_KINDS[k].category === c));
331
+ const classOf = (k) => (k === "term" ? termClassification : CATEGORY_CLASSIFICATION[DATA_KINDS[k].category]);
332
+ const classification = present.reduce((acc, k) => (rank(classOf(k)) > rank(acc) ? classOf(k) : acc), "public");
333
+ const personalData = categories.some((c) => PERSONAL_CATEGORIES.has(c));
334
+ const reasons = [];
335
+ const offending = [];
336
+ let verdict = "allow";
337
+ if (target && !target.active) {
338
+ return {
339
+ verdict: "deny",
340
+ classification,
341
+ personalData,
342
+ categories,
343
+ offending: present,
344
+ reasons: [`${target.name} is not an active system in the AI register, so nothing should be sent to it.`],
345
+ };
346
+ }
347
+ if (present.length === 0)
348
+ return { verdict, classification, personalData, categories, offending, reasons };
349
+ const name = target?.name ?? "an AI system that is not in the register";
350
+ const approved = target ? target.approvedClassification ?? policy.unregistered.approvedClassification : policy.unregistered.approvedClassification;
351
+ const personalApproved = target ? target.personalData : policy.unregistered.personalData;
352
+ const secrets = counts.secret ?? 0;
353
+ if (secrets > 0) {
354
+ verdict = stricter(verdict, policy.secrets);
355
+ offending.push("secret");
356
+ reasons.push(`It contains ${describeCounts({ secret: secrets })}, which should never be sent to a model.`);
357
+ }
358
+ for (const k of present) {
359
+ if (k === "secret")
360
+ continue;
361
+ const tooSensitive = rank(classOf(k)) > rank(approved);
362
+ const personalNotApproved = DATA_KINDS[k].category !== "confidential" && !personalApproved;
363
+ if (!tooSensitive && !personalNotApproved)
364
+ continue;
365
+ const action = DATA_KINDS[k].redactable ? policy.beyondApproval : policy.notRedactable;
366
+ verdict = stricter(verdict, action);
367
+ offending.push(k);
368
+ const why = personalNotApproved
369
+ ? "which is not approved to receive personal data"
370
+ : `which is approved for ${approved} data at most`;
371
+ reasons.push(`It contains ${describeCounts({ [k]: counts[k] })}, and goes to ${name}, ${why}.`);
372
+ }
373
+ return { verdict, classification, personalData, categories, offending, reasons };
374
+ }
375
+ /**
376
+ * The text with the findings behind a verdict replaced: only those, so data
377
+ * the target is approved for still reaches it. What a person asked is shown,
378
+ * and what a `redact` verdict sends. Null for a deny, which sends nothing.
379
+ */
380
+ export function redactFor(text, findings, assessment) {
381
+ if (assessment.verdict === "deny")
382
+ return null;
383
+ const offending = new Set(assessment.offending);
384
+ return redact(text, findings.filter((f) => offending.has(f.kind)));
385
+ }
386
+ /** The strictest classification among the terms found, for `assessCounts`. */
387
+ export function termClassificationOf(findings) {
388
+ return findings.some((f) => f.kind === "term" && f.classification === "restricted") ? "restricted" : "confidential";
389
+ }
package/dist/dev.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EAWb,MAAM,YAAY,CAAC;AAEpB;;;;;;;;;;;;;;;;;;GAkBG;AAEH;;;;;;;;;;GAUG;AACH,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,UAAU,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAE7F,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,OAAO,CAAC,EAAE,kBAAkB,GAAG,CAAC,CAAC,OAAO,EAAE,YAAY,KAAK,kBAAkB,CAAC,CAAC;IAC/E,+DAA+D;IAC/D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAcD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,UAAU,CAAC,KAAK,CA2kB1F"}
1
+ {"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EAWb,MAAM,YAAY,CAAC;AAGpB;;;;;;;;;;;;;;;;;;GAkBG;AAEH;;;;;;;;;;GAUG;AACH,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,UAAU,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAAC;AAE7F,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,OAAO,CAAC,EAAE,kBAAkB,GAAG,CAAC,CAAC,OAAO,EAAE,YAAY,KAAK,kBAAkB,CAAC,CAAC;IAC/E,+DAA+D;IAC/D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAcD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,UAAU,CAAC,KAAK,CAqnB1F"}
package/dist/dev.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { assessCounts, DEFAULT_SCREEN_POLICY, describeCounts } from "./data-screen.js";
1
2
  const DEFAULT_QUESTION = "Has this been through staging?";
2
3
  let counter = 0;
3
4
  /**
@@ -14,7 +15,7 @@ export function developmentFetch(options = {}) {
14
15
  const collectionStore = new Map();
15
16
  const flowStore = new Map();
16
17
  const tasks = developmentTasks(options);
17
- return (async (input, init) => {
18
+ const handle = (async (input, init) => {
18
19
  const url = new URL(String(input));
19
20
  const path = url.pathname.replace(/^\/api\/v1/, "");
20
21
  const method = (init?.method ?? "GET").toUpperCase();
@@ -540,6 +541,44 @@ export function developmentFetch(options = {}) {
540
541
  if (method === "GET" && path === "/tasks") {
541
542
  return json({ tasks: tasks.list(url.searchParams), nextCursor: null });
542
543
  }
544
+ /*
545
+ * Screening with no organisation behind it: no register record and no
546
+ * policy, so the defaults decide — internal data and no personal data
547
+ * approved — and an `ask` files an ordinary development approval, which
548
+ * the imaginary approver decides like any other.
549
+ */
550
+ if (method === "POST" && path === "/screen") {
551
+ const counts = (body.counts ?? {});
552
+ const termClassification = body.termClassification === "restricted" ? "restricted" : "confidential";
553
+ const assessment = assessCounts(counts, null, DEFAULT_SCREEN_POLICY, termClassification);
554
+ let approval = null;
555
+ if (assessment.verdict === "ask" && body.ask !== false) {
556
+ const created = (await (await handle(`${url.origin}/api/v1/approvals`, {
557
+ method: "POST",
558
+ body: JSON.stringify({
559
+ title: `Send ${describeCounts(counts)} to an AI model?`,
560
+ description: assessment.reasons.join("\n"),
561
+ risk: assessment.classification === "restricted" ? "high" : "medium",
562
+ externalId: body.externalId,
563
+ }),
564
+ })).json());
565
+ approval = { id: created.id, url: created.url, status: created.status };
566
+ }
567
+ return json({
568
+ verdict: assessment.verdict,
569
+ allowed: assessment.verdict === "allow" || assessment.verdict === "redact",
570
+ classification: assessment.classification,
571
+ personalData: assessment.personalData,
572
+ categories: assessment.categories,
573
+ counts,
574
+ offending: assessment.offending,
575
+ reasons: assessment.reasons,
576
+ target: null,
577
+ findings: null,
578
+ redactedText: null,
579
+ approval,
580
+ });
581
+ }
543
582
  const taskMatch = /^\/tasks\/([^/]+)(?:\/(context|graph|side-tasks|findings|complete|apply|reopen|cancel|links))?$/.exec(path);
544
583
  if (taskMatch) {
545
584
  const [status, payload] = tasks.act(method, taskMatch[1], taskMatch[2] ?? null, body);
@@ -548,10 +587,11 @@ export function developmentFetch(options = {}) {
548
587
  return json({
549
588
  error: {
550
589
  code: "not_in_development_mode",
551
- message: `Development mode simulates approvals, reviews, collections, flows and tasks only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
590
+ 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.`,
552
591
  },
553
592
  }, 501);
554
593
  });
594
+ return handle;
555
595
  }
556
596
  function resolveOutcome(outcome, body) {
557
597
  const fromEnv = process.env.DELIVERD_DEV_OUTCOME;
@@ -0,0 +1,94 @@
1
+ import type { HttpClient } from "./http.js";
2
+ import { type PageOf } from "./paging.js";
3
+ import type { AiIncident, AiIncidentDetail, AiSystem, AiSystemDetail, AuthorityDecision, CheckAuthorityInput, CreateCustomFrameworkInput, CustomFramework, DraftedIncidentReport, DraftIncidentReportInput, FrameworkCatalogue, FrameworkMapping, FrameworkMappingInput, GovernanceSummary, GovernanceSummaryInput, IctRegister, ListIncidentsInput, ModelChangeInput, ModelChangeResult, RegisterAiSystemInput, ReportIncidentInput, UpdateAiSystemInput } from "./types.js";
4
+ /**
5
+ * The organisation's register of AI systems. A governed task names one by
6
+ * `aiSystemId` instead of describing it again, and a change of model is
7
+ * recorded here so every task using it is reassessed.
8
+ */
9
+ export declare class AiSystems {
10
+ private readonly http;
11
+ constructor(http: HttpClient);
12
+ /** The register, active and retired, or only one of them. */
13
+ list(input?: {
14
+ status?: AiSystem["status"];
15
+ }, signal?: AbortSignal): Promise<AiSystem[]>;
16
+ /** One system, and the governed tasks that name it. */
17
+ get(id: string, signal?: AbortSignal): Promise<AiSystemDetail>;
18
+ /** Add a system to the register. Digests of its prompt and guardrails, never the text. */
19
+ register(input: RegisterAiSystemInput, signal?: AbortSignal): Promise<AiSystem>;
20
+ /** Change a system's record. An agent may raise its risk but not lower it, and may not retire it. */
21
+ update(id: string, input: UpdateAiSystemInput, signal?: AbortSignal): Promise<AiSystem>;
22
+ /**
23
+ * Record a new provider, model, version, prompt or guardrails (Enterprise).
24
+ * Every governed task using the system is reassessed, and evidence of the
25
+ * old release stops counting.
26
+ */
27
+ recordModelChange(id: string, input: ModelChangeInput, signal?: AbortSignal): Promise<ModelChangeResult>;
28
+ }
29
+ /**
30
+ * AI incidents, and the DORA reports on the major ones. A high or critical
31
+ * incident closes its task's governance gate until a person resolves it in
32
+ * Deliverd; classifying it, and submitting a report, are a person's too.
33
+ */
34
+ export declare class Incidents {
35
+ private readonly http;
36
+ constructor(http: HttpClient);
37
+ /** Report an incident against a governed task, an AI system, or both. */
38
+ report(input: ReportIncidentInput, signal?: AbortSignal): Promise<AiIncident>;
39
+ /** One incident: its DORA classification, its reports and their sign-off, and which report is due next. */
40
+ get(id: string, signal?: AbortSignal): Promise<AiIncidentDetail>;
41
+ /**
42
+ * Newest first. With no `limit` this is every incident; with a `limit` it is
43
+ * one page of that size, and `listPage` hands back the cursor to continue from.
44
+ */
45
+ list(input?: ListIncidentsInput, signal?: AbortSignal): Promise<AiIncident[]>;
46
+ /** One page, and the cursor to continue from — null when it is the end. */
47
+ listPage(input?: ListIncidentsInput, signal?: AbortSignal): Promise<PageOf<AiIncident>>;
48
+ /**
49
+ * Draft a DORA report on a major incident and put it to a person to sign
50
+ * off. Reports follow in order: initial, intermediate, final. Needs
51
+ * `approvals:write` as well as `tasks:write`.
52
+ */
53
+ draftReport(id: string, input: DraftIncidentReportInput, signal?: AbortSignal): Promise<DraftedIncidentReport>;
54
+ }
55
+ /**
56
+ * Compliance Mode across the organisation (Business and Enterprise): the AI
57
+ * system register, incidents, what an agent may do, the frameworks and the
58
+ * ICT register. A governed task's own governance is on `deliverd.tasks`.
59
+ *
60
+ * ```ts
61
+ * const { mode } = await deliverd.governance.checkAuthority({ action: "send" });
62
+ * if (mode === "denied") return;
63
+ * ```
64
+ *
65
+ * Every answer records governance and certifies nothing.
66
+ */
67
+ export declare class AiGovernance {
68
+ private readonly http;
69
+ readonly aiSystems: AiSystems;
70
+ readonly incidents: Incidents;
71
+ constructor(http: HttpClient);
72
+ /**
73
+ * May this agent take this kind of action: on its own (`allowed`), only
74
+ * with a person's approval (`approval`), or not at all (`denied`)? By the
75
+ * organisation's policy and the agent's own, which can only be stricter
76
+ * (Enterprise). Reads; records nothing.
77
+ */
78
+ checkAuthority(input: CheckAuthorityInput, signal?: AbortSignal): Promise<AuthorityDecision>;
79
+ /** The frameworks the organisation can see: the built-in packs and its own, and which are applied. */
80
+ frameworks(signal?: AbortSignal): Promise<FrameworkCatalogue>;
81
+ /**
82
+ * How framework requirements map onto the common controls and, with
83
+ * `taskId`, how far that task's controls cover each one. A mapping, never
84
+ * a compliance verdict.
85
+ */
86
+ frameworkMapping(input?: FrameworkMappingInput, signal?: AbortSignal): Promise<FrameworkMapping>;
87
+ /** Draft the organisation's own framework (Enterprise). It adds nothing until a person publishes and applies it. */
88
+ createCustomFramework(input: CreateCustomFrameworkInput, signal?: AbortSignal): Promise<CustomFramework>;
89
+ /** The ICT third-party register: providers, contracts, the AI systems under each, gaps and concentration. */
90
+ ictRegister(signal?: AbortSignal): Promise<IctRegister>;
91
+ /** The organisation's AI governance in counts, optionally narrowed. Never a compliance percentage. */
92
+ summary(input?: GovernanceSummaryInput, signal?: AbortSignal): Promise<GovernanceSummary>;
93
+ }
94
+ //# sourceMappingURL=governance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"governance.d.ts","sourceRoot":"","sources":["../src/governance.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,EAAiB,KAAK,MAAM,EAAE,MAAM,aAAa,CAAC;AACzD,OAAO,KAAK,EACV,UAAU,EACV,gBAAgB,EAChB,QAAQ,EACR,cAAc,EACd,iBAAiB,EACjB,mBAAmB,EACnB,0BAA0B,EAC1B,eAAe,EACf,qBAAqB,EACrB,wBAAwB,EACxB,kBAAkB,EAClB,gBAAgB,EAChB,qBAAqB,EACrB,iBAAiB,EACjB,sBAAsB,EACtB,WAAW,EACX,kBAAkB,EA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