@verax-ai/proxy 0.6.1 → 0.8.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/dist/approvals.d.ts +30 -1
- package/dist/approvals.js +71 -14
- package/dist/control-sync.js +7 -1
- package/dist/data-classes.d.ts +36 -0
- package/dist/data-classes.js +412 -0
- package/dist/explain.js +128 -16
- package/dist/index.d.ts +4 -3
- package/dist/index.js +3 -2
- package/dist/inputs.d.ts +4 -0
- package/dist/inputs.js +41 -0
- package/dist/ledger-manifest.d.ts +2 -0
- package/dist/ledger-manifest.js +1 -0
- package/dist/ledger.d.ts +2 -0
- package/dist/ledger.js +4 -0
- package/dist/policy.d.ts +12 -2
- package/dist/policy.js +208 -7
- package/dist/process-halt.d.ts +9 -0
- package/dist/process-halt.js +68 -0
- package/dist/proxy.js +215 -47
- package/dist/reconcile.d.ts +10 -1
- package/dist/reconcile.js +89 -14
- package/dist/result-classes.d.ts +35 -0
- package/dist/result-classes.js +485 -0
- package/dist/types.d.ts +64 -7
- package/dist/types.js +6 -1
- package/dist/verify-ledger.d.ts +7 -0
- package/dist/verify-ledger.js +180 -17
- package/package.json +3 -2
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { maskField } from "@conarium-ai/mask";
|
|
2
|
+
import type { DecisionKind } from "@cedulon/core";
|
|
3
|
+
import type { DecisionInputs, Policy, Principal, ToolResult } from "./types.ts";
|
|
4
|
+
export type ResultRecordWriter = (opts: {
|
|
5
|
+
decision: DecisionKind;
|
|
6
|
+
reasonCode: string;
|
|
7
|
+
ref: string;
|
|
8
|
+
requestHash: string;
|
|
9
|
+
inputs: DecisionInputs;
|
|
10
|
+
effectHash: string | null;
|
|
11
|
+
subject: string;
|
|
12
|
+
timestampMs: number;
|
|
13
|
+
}) => Promise<void>;
|
|
14
|
+
export type ResultMasker = typeof maskField;
|
|
15
|
+
export type ResultGateDeps = {
|
|
16
|
+
policy: Policy;
|
|
17
|
+
nonce: () => string;
|
|
18
|
+
now: () => number;
|
|
19
|
+
writeRecord: ResultRecordWriter;
|
|
20
|
+
/** Defaults to Conarium's `maskField`. */
|
|
21
|
+
masker?: ResultMasker;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Mask a tool throw the same way as a text block. The `:threw` row is already
|
|
25
|
+
* written over the original payload. Returns a new object so a string, a
|
|
26
|
+
* frozen Error, a stack that was already read, or a stuck cause cannot
|
|
27
|
+
* carry the raw text out. A throw inside this gate becomes
|
|
28
|
+
* `withheld:result-class-error:<ref>`, never the original. The error comes
|
|
29
|
+
* back wrapped, so awaiting the gate cannot adopt a thenable error. Call it
|
|
30
|
+
* only when the policy sets `resultClasses`.
|
|
31
|
+
*/
|
|
32
|
+
export declare function gateThrownError(err: unknown, tool: string, callRef: string, resultHash: string, principal: Principal, deps: ResultGateDeps): Promise<{
|
|
33
|
+
error: unknown;
|
|
34
|
+
}>;
|
|
35
|
+
export declare function gateResultClasses(result: ToolResult, tool: string, callRef: string, resultHash: string, principal: Principal, deps: ResultGateDeps): Promise<ToolResult>;
|
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { maskField } from "@conarium-ai/mask";
|
|
6
|
+
import { DEFAULT_SCAN_CHAR_CAP, detectorsFor, SPAN_CLASSES } from "./data-classes.js";
|
|
7
|
+
import { sha256Canonical } from "./hash.js";
|
|
8
|
+
import { terminalText } from "./policy.js";
|
|
9
|
+
import { isMediaContent, isTextContent } from "./types.js";
|
|
10
|
+
/** Text results and error text use Conarium's text pipeline. */
|
|
11
|
+
const TEXT_MASK_PIPELINE = "text";
|
|
12
|
+
/** Transcripts use its speech pipeline (split digit runs, spoken addresses); its harsher rules would over-mask plain text. */
|
|
13
|
+
const TRANSCRIPT_MASK_PIPELINE = "speech";
|
|
14
|
+
function principalOf(principal) {
|
|
15
|
+
return {
|
|
16
|
+
brain: principal.brain,
|
|
17
|
+
scopes: [...principal.scopes].sort(),
|
|
18
|
+
...(principal.iss ? { iss: principal.iss } : {}),
|
|
19
|
+
...(principal.tenant ? { tenant: principal.tenant } : {}),
|
|
20
|
+
...(principal.org ? { org: principal.org } : {}),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function choicesFor(policy, tool) {
|
|
24
|
+
if (!policy.resultClasses)
|
|
25
|
+
return {};
|
|
26
|
+
return { ...policy.resultClasses.document, ...(policy.resultClasses.byTool[tool] ?? {}) };
|
|
27
|
+
}
|
|
28
|
+
function restrictsChoices(choices) {
|
|
29
|
+
return Object.values(choices).some((choice) => choice === "mask" || choice === "block");
|
|
30
|
+
}
|
|
31
|
+
function addCounts(into, add) {
|
|
32
|
+
if (!add)
|
|
33
|
+
return;
|
|
34
|
+
for (const [key, n] of Object.entries(add)) {
|
|
35
|
+
if (typeof n !== "number" || n <= 0)
|
|
36
|
+
continue;
|
|
37
|
+
into[key] = (into[key] ?? 0) + n;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function compactCounts(counts) {
|
|
41
|
+
const out = {};
|
|
42
|
+
for (const [key, n] of Object.entries(counts)) {
|
|
43
|
+
if (n > 0)
|
|
44
|
+
out[key] = n;
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
function firstBlocked(classes, choices) {
|
|
49
|
+
for (const cls of SPAN_CLASSES) {
|
|
50
|
+
if ((classes[cls] ?? 0) > 0 && choices[cls] === "block")
|
|
51
|
+
return cls;
|
|
52
|
+
}
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
function firstBlockChoice(choices) {
|
|
56
|
+
for (const cls of SPAN_CLASSES) {
|
|
57
|
+
if (choices[cls] === "block")
|
|
58
|
+
return cls;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
function blockedOrUnscanned(classes, masked, choices) {
|
|
63
|
+
return firstBlocked(classes, choices) ?? ((masked.whole ?? 0) > 0 ? firstBlockChoice(choices) : undefined);
|
|
64
|
+
}
|
|
65
|
+
function splitTextForScan(text, cap) {
|
|
66
|
+
if (text.length <= cap)
|
|
67
|
+
return [text];
|
|
68
|
+
const lines = text.split("\n");
|
|
69
|
+
const pieces = [];
|
|
70
|
+
let buf = "";
|
|
71
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
72
|
+
const chunk = i < lines.length - 1 ? `${lines[i]}\n` : lines[i];
|
|
73
|
+
if (buf.length === 0) {
|
|
74
|
+
buf = chunk;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (buf.length + chunk.length <= cap) {
|
|
78
|
+
buf += chunk;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
pieces.push(buf);
|
|
82
|
+
buf = chunk;
|
|
83
|
+
}
|
|
84
|
+
if (buf.length > 0)
|
|
85
|
+
pieces.push(buf);
|
|
86
|
+
return pieces;
|
|
87
|
+
}
|
|
88
|
+
function scanText(text, only, cap, masker, pipeline, detectors) {
|
|
89
|
+
const pieces = splitTextForScan(text, cap);
|
|
90
|
+
const classes = {};
|
|
91
|
+
const masked = {};
|
|
92
|
+
const out = [];
|
|
93
|
+
for (const piece of pieces) {
|
|
94
|
+
const { body, suffix } = dropScanBreak(piece);
|
|
95
|
+
const result = masker(body, {
|
|
96
|
+
pipeline,
|
|
97
|
+
only,
|
|
98
|
+
scanCharCap: cap,
|
|
99
|
+
...(detectors ? { detectors } : {}),
|
|
100
|
+
});
|
|
101
|
+
out.push(`${result.text}${suffix}`);
|
|
102
|
+
addCounts(classes, result.classes);
|
|
103
|
+
addCounts(masked, result.masked);
|
|
104
|
+
}
|
|
105
|
+
return { text: out.join(""), classes, masked };
|
|
106
|
+
}
|
|
107
|
+
/** A trailing `\r\n` or `\n` is not part of the line; put back exactly that suffix. */
|
|
108
|
+
function dropScanBreak(piece) {
|
|
109
|
+
if (piece.endsWith("\r\n"))
|
|
110
|
+
return { body: piece.slice(0, -2), suffix: "\r\n" };
|
|
111
|
+
if (piece.endsWith("\n"))
|
|
112
|
+
return { body: piece.slice(0, -1), suffix: "\n" };
|
|
113
|
+
return { body: piece, suffix: "" };
|
|
114
|
+
}
|
|
115
|
+
function audioExt(mimeType) {
|
|
116
|
+
const mime = mimeType.toLowerCase().split(";")[0].trim();
|
|
117
|
+
if (mime === "audio/mpeg" || mime === "audio/mp3")
|
|
118
|
+
return ".mp3";
|
|
119
|
+
if (mime === "audio/wav" || mime === "audio/wave" || mime === "audio/x-wav")
|
|
120
|
+
return ".wav";
|
|
121
|
+
if (mime === "audio/ogg")
|
|
122
|
+
return ".ogg";
|
|
123
|
+
if (mime === "audio/webm")
|
|
124
|
+
return ".webm";
|
|
125
|
+
if (mime === "audio/mp4")
|
|
126
|
+
return ".m4a";
|
|
127
|
+
return ".bin";
|
|
128
|
+
}
|
|
129
|
+
function mediaChoice(kind, media) {
|
|
130
|
+
if (kind === "audio")
|
|
131
|
+
return media?.audio ?? "withhold";
|
|
132
|
+
return media?.image ?? "withhold";
|
|
133
|
+
}
|
|
134
|
+
function stopTranscriberTree(child) {
|
|
135
|
+
if (process.platform !== "win32" && child.pid !== undefined) {
|
|
136
|
+
try {
|
|
137
|
+
process.kill(-child.pid, "SIGKILL");
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
// The pid was not a group leader, or the group was already gone.
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
child.kill("SIGKILL");
|
|
145
|
+
}
|
|
146
|
+
function runTranscriber(command, file, timeoutMs, cap) {
|
|
147
|
+
const args = command.slice(1).map((arg) => (arg.includes("{file}") ? arg.replace("{file}", file) : arg));
|
|
148
|
+
return new Promise((resolve) => {
|
|
149
|
+
let settled = false;
|
|
150
|
+
const finish = (text) => {
|
|
151
|
+
if (settled)
|
|
152
|
+
return;
|
|
153
|
+
settled = true;
|
|
154
|
+
clearTimeout(timer);
|
|
155
|
+
resolve(text);
|
|
156
|
+
};
|
|
157
|
+
let child;
|
|
158
|
+
try {
|
|
159
|
+
child = spawn(command[0], args, {
|
|
160
|
+
shell: false,
|
|
161
|
+
windowsHide: true,
|
|
162
|
+
// POSIX: a new group so a timeout can SIGKILL the launcher and what it
|
|
163
|
+
// started. Do not detach on Windows: that takes the child out of
|
|
164
|
+
// node's job object, which is what stops the tree there.
|
|
165
|
+
...(process.platform === "win32" ? {} : { detached: true }),
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
finish(null);
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
let out = "";
|
|
173
|
+
let over = false;
|
|
174
|
+
let timedOut = false;
|
|
175
|
+
const abandon = () => {
|
|
176
|
+
child.stdout?.destroy();
|
|
177
|
+
child.stderr?.destroy();
|
|
178
|
+
};
|
|
179
|
+
child.stdout?.setEncoding("utf8");
|
|
180
|
+
child.stdout?.on("data", (chunk) => {
|
|
181
|
+
if (settled || over)
|
|
182
|
+
return;
|
|
183
|
+
out += chunk;
|
|
184
|
+
if (out.length > cap) {
|
|
185
|
+
over = true;
|
|
186
|
+
stopTranscriberTree(child);
|
|
187
|
+
abandon();
|
|
188
|
+
finish(null);
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
child.on("error", () => finish(null));
|
|
192
|
+
child.on("close", (code, signal) => {
|
|
193
|
+
if (over || timedOut || signal) {
|
|
194
|
+
finish(null);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
if (code !== 0) {
|
|
198
|
+
finish(null);
|
|
199
|
+
return;
|
|
200
|
+
}
|
|
201
|
+
const text = out.trim();
|
|
202
|
+
if (text === "" || out.length > cap) {
|
|
203
|
+
finish(null);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
finish(text);
|
|
207
|
+
});
|
|
208
|
+
const timer = setTimeout(() => {
|
|
209
|
+
timedOut = true;
|
|
210
|
+
stopTranscriberTree(child);
|
|
211
|
+
abandon();
|
|
212
|
+
finish(null);
|
|
213
|
+
}, timeoutMs);
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
async function transcribeBlock(data, mimeType, media, cap) {
|
|
217
|
+
const transcriber = media.transcriber;
|
|
218
|
+
if (!transcriber)
|
|
219
|
+
return null;
|
|
220
|
+
const dir = mkdtempSync(join(tmpdir(), "verax-stt-"));
|
|
221
|
+
try {
|
|
222
|
+
if (process.platform !== "win32")
|
|
223
|
+
chmodSync(dir, 0o700);
|
|
224
|
+
const file = join(dir, `audio${audioExt(mimeType)}`);
|
|
225
|
+
writeFileSync(file, Buffer.from(data, "base64"), { mode: 0o600 });
|
|
226
|
+
return await runTranscriber(transcriber.command, file, transcriber.timeoutMs, cap);
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
finally {
|
|
232
|
+
try {
|
|
233
|
+
rmSync(dir, { recursive: true, force: true, maxRetries: 5 });
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
process.stderr.write(`verax-proxy: temporary audio not removed: ${terminalText(dir)}\n`);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function withheldError(callRef) {
|
|
241
|
+
return {
|
|
242
|
+
content: [{ type: "text", text: `result-unrecorded:${callRef}` }],
|
|
243
|
+
isError: true,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function blockError(cls, callRef) {
|
|
247
|
+
return {
|
|
248
|
+
content: [{ type: "text", text: `withheld:result-class-block:${cls}:${callRef}` }],
|
|
249
|
+
isError: true,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
function classError(callRef) {
|
|
253
|
+
return {
|
|
254
|
+
content: [{ type: "text", text: `withheld:result-class-error:${callRef}` }],
|
|
255
|
+
isError: true,
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
const CLASS_NAME = /^[A-Za-z_$][\w$]{0,63}$/;
|
|
259
|
+
/**
|
|
260
|
+
* A new object: the original's prototype (or Error), the masked message, a
|
|
261
|
+
* one-line stack, and `prefix`/`tool` when both are strings. Nothing else
|
|
262
|
+
* is copied — those fields can hold the raw text. The name is the class's,
|
|
263
|
+
* from code, not the error's own `name`, which a tool can set to anything.
|
|
264
|
+
*/
|
|
265
|
+
function leaveError(original, message) {
|
|
266
|
+
try {
|
|
267
|
+
const isErr = original instanceof Error;
|
|
268
|
+
const proto = isErr ? Object.getPrototypeOf(original) : Error.prototype;
|
|
269
|
+
const className = proto?.constructor?.name;
|
|
270
|
+
const name = typeof className === "string" && CLASS_NAME.test(className) ? className : "Error";
|
|
271
|
+
const out = Object.create(proto);
|
|
272
|
+
Object.defineProperty(out, "name", { configurable: true, writable: true, value: name });
|
|
273
|
+
Object.defineProperty(out, "message", { configurable: true, writable: true, value: message });
|
|
274
|
+
Object.defineProperty(out, "stack", { configurable: true, writable: true, value: `${name}: ${message}` });
|
|
275
|
+
if (isErr) {
|
|
276
|
+
const prefix = original.prefix;
|
|
277
|
+
const tool = original.tool;
|
|
278
|
+
if (typeof prefix === "string" && typeof tool === "string") {
|
|
279
|
+
out.prefix = prefix;
|
|
280
|
+
out.tool = tool;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
return out;
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
const fallback = new Error(message);
|
|
287
|
+
fallback.stack = `Error: ${message}`;
|
|
288
|
+
return fallback;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Mask a tool throw the same way as a text block. The `:threw` row is already
|
|
293
|
+
* written over the original payload. Returns a new object so a string, a
|
|
294
|
+
* frozen Error, a stack that was already read, or a stuck cause cannot
|
|
295
|
+
* carry the raw text out. A throw inside this gate becomes
|
|
296
|
+
* `withheld:result-class-error:<ref>`, never the original. The error comes
|
|
297
|
+
* back wrapped, so awaiting the gate cannot adopt a thenable error. Call it
|
|
298
|
+
* only when the policy sets `resultClasses`.
|
|
299
|
+
*/
|
|
300
|
+
export async function gateThrownError(err, tool, callRef, resultHash, principal, deps) {
|
|
301
|
+
const { policy } = deps;
|
|
302
|
+
if (!policy.resultClasses)
|
|
303
|
+
return { error: err };
|
|
304
|
+
try {
|
|
305
|
+
const choices = choicesFor(policy, tool);
|
|
306
|
+
if (!restrictsChoices(choices))
|
|
307
|
+
return { error: err };
|
|
308
|
+
const only = SPAN_CLASSES.filter((cls) => choices[cls] === "mask");
|
|
309
|
+
const cap = policy.scanCharCap ?? policy.dataClasses?.scanCharCap ?? DEFAULT_SCAN_CHAR_CAP;
|
|
310
|
+
const masker = deps.masker ?? maskField;
|
|
311
|
+
const original = err instanceof Error ? `${err.message}` : String(err);
|
|
312
|
+
let leaving = original;
|
|
313
|
+
let decision = "allow";
|
|
314
|
+
let reasonCode = "result-classes";
|
|
315
|
+
const masked = {};
|
|
316
|
+
let scanFailed = false;
|
|
317
|
+
try {
|
|
318
|
+
const scanned = scanText(original, only, cap, masker, TEXT_MASK_PIPELINE, detectorsFor(choices));
|
|
319
|
+
addCounts(masked, scanned.masked);
|
|
320
|
+
const blocked = blockedOrUnscanned(scanned.classes, scanned.masked, choices);
|
|
321
|
+
if (blocked) {
|
|
322
|
+
leaving = `withheld:result-class-block:${blocked}:${callRef}`;
|
|
323
|
+
decision = "deny";
|
|
324
|
+
reasonCode = `result-class-block:${blocked}`;
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
leaving = scanned.text;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
scanFailed = true;
|
|
332
|
+
leaving = `withheld:result-class-error:${callRef}`;
|
|
333
|
+
decision = "deny";
|
|
334
|
+
reasonCode = "result-class-error";
|
|
335
|
+
}
|
|
336
|
+
const next = leaveError(err, leaving);
|
|
337
|
+
if (leaving === original && !scanFailed)
|
|
338
|
+
return { error: next };
|
|
339
|
+
try {
|
|
340
|
+
await deps.writeRecord({
|
|
341
|
+
decision,
|
|
342
|
+
reasonCode,
|
|
343
|
+
ref: deps.nonce(),
|
|
344
|
+
requestHash: resultHash,
|
|
345
|
+
inputs: {
|
|
346
|
+
principal: principalOf(principal),
|
|
347
|
+
inputs: [],
|
|
348
|
+
resultOf: callRef,
|
|
349
|
+
resultClasses: {
|
|
350
|
+
masked: compactCounts(masked),
|
|
351
|
+
transcribed: 0,
|
|
352
|
+
withheld: {},
|
|
353
|
+
returnedHash: sha256Canonical({ error: leaving }),
|
|
354
|
+
},
|
|
355
|
+
},
|
|
356
|
+
effectHash: decision === "deny" ? null : resultHash,
|
|
357
|
+
subject: tool,
|
|
358
|
+
timestampMs: deps.now(),
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
catch {
|
|
362
|
+
return { error: leaveError(err, `result-unrecorded:${callRef}`) };
|
|
363
|
+
}
|
|
364
|
+
return { error: next };
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
return { error: leaveError(err, `withheld:result-class-error:${callRef}`) };
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
export async function gateResultClasses(result, tool, callRef, resultHash, principal, deps) {
|
|
371
|
+
const { policy } = deps;
|
|
372
|
+
if (!policy.resultClasses && !policy.media)
|
|
373
|
+
return result;
|
|
374
|
+
const choices = choicesFor(policy, tool);
|
|
375
|
+
const scanTextResults = restrictsChoices(choices);
|
|
376
|
+
const only = SPAN_CLASSES.filter((cls) => choices[cls] === "mask");
|
|
377
|
+
const cap = policy.scanCharCap ?? policy.dataClasses?.scanCharCap ?? DEFAULT_SCAN_CHAR_CAP;
|
|
378
|
+
const masker = deps.masker ?? maskField;
|
|
379
|
+
const classCounts = {};
|
|
380
|
+
const masked = {};
|
|
381
|
+
const withheld = {};
|
|
382
|
+
let transcribed = 0;
|
|
383
|
+
let changed = false;
|
|
384
|
+
let scanFailed = false;
|
|
385
|
+
const content = [];
|
|
386
|
+
for (const block of result.content) {
|
|
387
|
+
if (isTextContent(block)) {
|
|
388
|
+
if (!policy.resultClasses || !scanTextResults) {
|
|
389
|
+
content.push(block);
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
let scanned;
|
|
393
|
+
try {
|
|
394
|
+
scanned = scanText(block.text, only, cap, masker, TEXT_MASK_PIPELINE, detectorsFor(choices));
|
|
395
|
+
}
|
|
396
|
+
catch {
|
|
397
|
+
scanFailed = true;
|
|
398
|
+
break;
|
|
399
|
+
}
|
|
400
|
+
addCounts(classCounts, scanned.classes);
|
|
401
|
+
addCounts(masked, scanned.masked);
|
|
402
|
+
if (scanned.text !== block.text)
|
|
403
|
+
changed = true;
|
|
404
|
+
content.push({ type: "text", text: scanned.text });
|
|
405
|
+
continue;
|
|
406
|
+
}
|
|
407
|
+
if (!isMediaContent(block))
|
|
408
|
+
continue;
|
|
409
|
+
const choice = mediaChoice(block.type, policy.media);
|
|
410
|
+
if (choice === "allow") {
|
|
411
|
+
content.push(block);
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (block.type === "image" || choice === "withhold") {
|
|
415
|
+
changed = true;
|
|
416
|
+
withheld[block.type] = (withheld[block.type] ?? 0) + 1;
|
|
417
|
+
content.push({ type: "text", text: `[${block.type} withheld]` });
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
const transcript = await transcribeBlock(block.data, block.mimeType, policy.media, cap);
|
|
421
|
+
changed = true;
|
|
422
|
+
if (transcript === null) {
|
|
423
|
+
withheld.audio = (withheld.audio ?? 0) + 1;
|
|
424
|
+
content.push({ type: "text", text: "[audio withheld: transcriber-failed]" });
|
|
425
|
+
continue;
|
|
426
|
+
}
|
|
427
|
+
transcribed += 1;
|
|
428
|
+
if (!policy.resultClasses || !scanTextResults) {
|
|
429
|
+
content.push({ type: "text", text: `[audio transcript] ${transcript}` });
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
let scanned;
|
|
433
|
+
try {
|
|
434
|
+
scanned = scanText(transcript, only, cap, masker, TRANSCRIPT_MASK_PIPELINE, detectorsFor(choices));
|
|
435
|
+
}
|
|
436
|
+
catch {
|
|
437
|
+
scanFailed = true;
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
addCounts(classCounts, scanned.classes);
|
|
441
|
+
addCounts(masked, scanned.masked);
|
|
442
|
+
content.push({ type: "text", text: `[audio transcript] ${scanned.text}` });
|
|
443
|
+
}
|
|
444
|
+
const blocked = scanFailed ? undefined : blockedOrUnscanned(classCounts, masked, choices);
|
|
445
|
+
const gated = scanFailed
|
|
446
|
+
? classError(callRef)
|
|
447
|
+
: blocked
|
|
448
|
+
? blockError(blocked, callRef)
|
|
449
|
+
: { content, isError: result.isError };
|
|
450
|
+
if (!scanFailed && !blocked && !changed)
|
|
451
|
+
return result;
|
|
452
|
+
const recordInputs = {
|
|
453
|
+
principal: principalOf(principal),
|
|
454
|
+
inputs: [],
|
|
455
|
+
resultOf: callRef,
|
|
456
|
+
resultClasses: {
|
|
457
|
+
masked: compactCounts(masked),
|
|
458
|
+
transcribed,
|
|
459
|
+
withheld: compactCounts(withheld),
|
|
460
|
+
returnedHash: sha256Canonical(gated),
|
|
461
|
+
},
|
|
462
|
+
};
|
|
463
|
+
try {
|
|
464
|
+
await deps.writeRecord({
|
|
465
|
+
decision: scanFailed || blocked ? "deny" : "allow",
|
|
466
|
+
reasonCode: scanFailed
|
|
467
|
+
? "result-class-error"
|
|
468
|
+
: blocked
|
|
469
|
+
? `result-class-block:${blocked}`
|
|
470
|
+
: "result-classes",
|
|
471
|
+
ref: deps.nonce(),
|
|
472
|
+
requestHash: resultHash,
|
|
473
|
+
inputs: recordInputs,
|
|
474
|
+
// Cedulon refuses an allow with a null effectHash (`allow-requires-effect-hash`).
|
|
475
|
+
// The hash is the same resultHash the effect row already stored.
|
|
476
|
+
effectHash: scanFailed || blocked ? null : resultHash,
|
|
477
|
+
subject: tool,
|
|
478
|
+
timestampMs: deps.now(),
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
catch {
|
|
482
|
+
return withheldError(callRef);
|
|
483
|
+
}
|
|
484
|
+
return gated;
|
|
485
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -16,12 +16,22 @@ export type ToolCall = {
|
|
|
16
16
|
name: string;
|
|
17
17
|
arguments: Record<string, unknown>;
|
|
18
18
|
};
|
|
19
|
-
|
|
19
|
+
export type TextContent = {
|
|
20
|
+
type: "text";
|
|
21
|
+
text: string;
|
|
22
|
+
};
|
|
23
|
+
export type MediaContent = {
|
|
24
|
+
type: "image" | "audio";
|
|
25
|
+
data: string;
|
|
26
|
+
mimeType: string;
|
|
27
|
+
text?: undefined;
|
|
28
|
+
};
|
|
29
|
+
export type ResultContent = TextContent | MediaContent;
|
|
30
|
+
export declare function isTextContent(block: ResultContent): block is TextContent;
|
|
31
|
+
export declare function isMediaContent(block: ResultContent): block is MediaContent;
|
|
32
|
+
/** Same shape as `@cedulon/mcp-guard`, plus image and audio blocks as MCP tools return them. claimedHash is a side field; it does not enter the ledger or audit. */
|
|
20
33
|
export type ToolResult = {
|
|
21
|
-
content:
|
|
22
|
-
type: "text";
|
|
23
|
-
text: string;
|
|
24
|
-
}[];
|
|
34
|
+
content: ResultContent[];
|
|
25
35
|
isError: boolean;
|
|
26
36
|
claimedHash?: string;
|
|
27
37
|
/** Adapter-verified downstream extract. Side field: excluded from resultHash and the agent response. */
|
|
@@ -40,6 +50,31 @@ export type PolicyLimits = {
|
|
|
40
50
|
dailyMax?: number;
|
|
41
51
|
diskFreeBytes: number;
|
|
42
52
|
};
|
|
53
|
+
export type DataClassChoice = "allow" | "mask" | "local" | "block";
|
|
54
|
+
export type ResultClassChoice = "allow" | "mask" | "block";
|
|
55
|
+
/** Present on a loaded version 2 policy; version 1 leaves the gate off. */
|
|
56
|
+
export type DataClassConfig = {
|
|
57
|
+
document: Readonly<Record<string, DataClassChoice>>;
|
|
58
|
+
byTool: Readonly<Record<string, Readonly<Record<string, DataClassChoice>>>>;
|
|
59
|
+
localTools: readonly string[];
|
|
60
|
+
blockedFileTypes: readonly string[];
|
|
61
|
+
scanCharCap?: number;
|
|
62
|
+
};
|
|
63
|
+
export type ResultClassConfig = {
|
|
64
|
+
document: Readonly<Record<string, ResultClassChoice>>;
|
|
65
|
+
byTool: Readonly<Record<string, Readonly<Record<string, ResultClassChoice>>>>;
|
|
66
|
+
};
|
|
67
|
+
export type AudioChoice = "allow" | "transcribe" | "withhold";
|
|
68
|
+
export type ImageChoice = "allow" | "withhold";
|
|
69
|
+
export type TranscriberConfig = {
|
|
70
|
+
command: readonly string[];
|
|
71
|
+
timeoutMs: number;
|
|
72
|
+
};
|
|
73
|
+
export type MediaConfig = {
|
|
74
|
+
audio?: AudioChoice;
|
|
75
|
+
image?: ImageChoice;
|
|
76
|
+
transcriber?: TranscriberConfig;
|
|
77
|
+
};
|
|
43
78
|
export type Policy = {
|
|
44
79
|
hash: string;
|
|
45
80
|
approvalTtlMs: number;
|
|
@@ -59,6 +94,11 @@ export type Policy = {
|
|
|
59
94
|
dayOffsetMinutes?: number;
|
|
60
95
|
};
|
|
61
96
|
} | null;
|
|
97
|
+
dataClasses?: DataClassConfig;
|
|
98
|
+
resultClasses?: ResultClassConfig;
|
|
99
|
+
media?: MediaConfig;
|
|
100
|
+
/** Document `scanCharCap`. Results read it even when no `dataClasses` key is set. */
|
|
101
|
+
scanCharCap?: number;
|
|
62
102
|
};
|
|
63
103
|
export type WitnessClass = "self" | "same-org" | "third-party" | "regulated";
|
|
64
104
|
export type EffectAttestation = {
|
|
@@ -119,7 +159,7 @@ export type DecisionInputRow = {
|
|
|
119
159
|
export type ControlInput = {
|
|
120
160
|
action: "halt" | "resume";
|
|
121
161
|
by: string;
|
|
122
|
-
via: "cli" | "http" | "file";
|
|
162
|
+
via: "cli" | "http" | "file" | "integrity";
|
|
123
163
|
atMs: number;
|
|
124
164
|
line: number;
|
|
125
165
|
lineHash: string;
|
|
@@ -205,6 +245,20 @@ export type DecisionInputs = {
|
|
|
205
245
|
control?: ControlInput;
|
|
206
246
|
revoke?: RevokeInput;
|
|
207
247
|
operatorRemoval?: OperatorRemovalInput;
|
|
248
|
+
/** Counts and the hash of what was forwarded. Never a value or a masked text. */
|
|
249
|
+
dataClasses?: {
|
|
250
|
+
masked: Record<string, number>;
|
|
251
|
+
forwardedHash: string;
|
|
252
|
+
};
|
|
253
|
+
/** Ref of the call whose result this record is about. */
|
|
254
|
+
resultOf?: string;
|
|
255
|
+
/** Counts and the hash of what the agent received. Never a value or transcript text. */
|
|
256
|
+
resultClasses?: {
|
|
257
|
+
masked: Record<string, number>;
|
|
258
|
+
transcribed: number;
|
|
259
|
+
withheld: Record<string, number>;
|
|
260
|
+
returnedHash: string;
|
|
261
|
+
};
|
|
208
262
|
};
|
|
209
263
|
/** How an operator's approval reached the ledger: a person at `verax approve`, a non-interactive `--from-script` run, or the body's `/api/approve`. */
|
|
210
264
|
export type ApprovalChannel = "cli" | "cli-script" | "http";
|
|
@@ -224,7 +278,10 @@ export type ProxyDeps = {
|
|
|
224
278
|
ledger: Ledger;
|
|
225
279
|
now: () => number;
|
|
226
280
|
nonce: () => string;
|
|
227
|
-
inner: (call: ToolCall, principal: Principal, ref?: string
|
|
281
|
+
inner: (call: ToolCall, principal: Principal, ref?: string, bound?: ReadonlyArray<{
|
|
282
|
+
id: string;
|
|
283
|
+
versionHash: string;
|
|
284
|
+
}>) => Promise<ToolResult>;
|
|
228
285
|
inputsLog?: InputsLog;
|
|
229
286
|
resolveInput?: (id: string, principal?: Principal) => Promise<ResolvedInput | null>;
|
|
230
287
|
/** True when the call names another tenant's memory id or decision ref. */
|
package/dist/types.js
CHANGED
package/dist/verify-ledger.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SignedDecisionRecord } from "@cedulon/core";
|
|
1
2
|
export type VerifyTrust = {
|
|
2
3
|
/** `pinned`: the caller supplied the key. `in-ledger`: read from the records. */
|
|
3
4
|
source: "pinned" | "in-ledger" | "none";
|
|
@@ -112,6 +113,12 @@ export type VerifyOptions = {
|
|
|
112
113
|
};
|
|
113
114
|
/** The core's default clock-skew allowance, which decision profile 6.1 applies unchanged. */
|
|
114
115
|
export declare const DEFAULT_BOUNDARY_ALLOWANCE_MS = 300000;
|
|
116
|
+
export type ResultRecordMeta = {
|
|
117
|
+
resultOf: string;
|
|
118
|
+
resultClasses: unknown;
|
|
119
|
+
};
|
|
120
|
+
/** The same checks verifyLedger applies to a result record. */
|
|
121
|
+
export declare function resultRecordIsMismatch(rec: SignedDecisionRecord, meta: ResultRecordMeta, resultHashByRef: ReadonlyMap<string, string>, effectClassByRef: ReadonlyMap<string, string>, namedCount: number): boolean;
|
|
115
122
|
/**
|
|
116
123
|
* How long after its window ends a checkpoint may be unanchored. The witness
|
|
117
124
|
* signs when the body asks, after the window closes, and registers after it
|