@peer-agent/runtime-core 0.0.1-beta.43

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 (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/dist/capability-registry.d.ts +15 -0
  4. package/dist/capability-registry.js +88 -0
  5. package/dist/compaction-progress.d.ts +51 -0
  6. package/dist/compaction-progress.js +83 -0
  7. package/dist/context-accounting-lifecycle.d.ts +41 -0
  8. package/dist/context-accounting-lifecycle.js +90 -0
  9. package/dist/context-accounting-pipeline.d.ts +98 -0
  10. package/dist/context-accounting-pipeline.js +561 -0
  11. package/dist/context-compaction.d.ts +70 -0
  12. package/dist/context-compaction.js +192 -0
  13. package/dist/context-projection-lifecycle.d.ts +32 -0
  14. package/dist/context-projection-lifecycle.js +65 -0
  15. package/dist/context-projection.d.ts +74 -0
  16. package/dist/context-projection.js +183 -0
  17. package/dist/contracts.d.ts +218 -0
  18. package/dist/contracts.js +1 -0
  19. package/dist/conversation-history-projector.d.ts +52 -0
  20. package/dist/conversation-history-projector.js +472 -0
  21. package/dist/decision.d.ts +4 -0
  22. package/dist/decision.js +23 -0
  23. package/dist/evidence.d.ts +64 -0
  24. package/dist/evidence.js +127 -0
  25. package/dist/hooks.d.ts +5 -0
  26. package/dist/hooks.js +4 -0
  27. package/dist/index.d.ts +18 -0
  28. package/dist/index.js +18 -0
  29. package/dist/local-tool-contracts.d.ts +60 -0
  30. package/dist/local-tool-contracts.js +64 -0
  31. package/dist/microcompact.d.ts +38 -0
  32. package/dist/microcompact.js +354 -0
  33. package/dist/permission.d.ts +18 -0
  34. package/dist/permission.js +50 -0
  35. package/dist/projection-materializers.d.ts +18 -0
  36. package/dist/projection-materializers.js +34 -0
  37. package/dist/projection.d.ts +15 -0
  38. package/dist/projection.js +78 -0
  39. package/dist/runtime-usage-accounting.d.ts +19 -0
  40. package/dist/runtime-usage-accounting.js +79 -0
  41. package/package.json +47 -0
@@ -0,0 +1,472 @@
1
+ /**
2
+ * Canonical persisted-conversation -> active provider history projection.
3
+ *
4
+ * Desktop send, Desktop restore and CLI/TUI restore must all cross this seam.
5
+ * Provider adapters may lower the camelCase tool fields to their wire format,
6
+ * but must not reinterpret persisted segments.
7
+ */
8
+ export const CANONICAL_HISTORY_PROJECTOR_VERSION = 1;
9
+ function recordOf(value) {
10
+ return value && typeof value === 'object' && !Array.isArray(value)
11
+ ? value
12
+ : null;
13
+ }
14
+ function nonEmptyString(value) {
15
+ return typeof value === 'string' && value.trim() ? value : '';
16
+ }
17
+ function compactionMarker(message) {
18
+ return recordOf(message._compaction) ?? recordOf(message.compaction);
19
+ }
20
+ function finiteNumber(value) {
21
+ return Number.isFinite(Number(value)) ? Number(value) : null;
22
+ }
23
+ function continuityFromBoundary(message, index) {
24
+ const marker = compactionMarker(message);
25
+ if (!marker)
26
+ return undefined;
27
+ const summary = (nonEmptyString(marker.summary)
28
+ || nonEmptyString(marker.handoffContent)
29
+ || nonEmptyString(message.content)).trim();
30
+ if (!summary)
31
+ return undefined;
32
+ return {
33
+ summary,
34
+ sourceMessageId: nonEmptyString(message.id) || `compaction_${index}`,
35
+ method: nonEmptyString(marker.method) || 'unknown',
36
+ originalMessageCount: finiteNumber(marker.originalMessageCount),
37
+ beforeTokens: finiteNumber(marker.beforeTokens),
38
+ afterTokens: finiteNumber(marker.afterTokens),
39
+ };
40
+ }
41
+ function sanitizeIdentifier(value) {
42
+ const safe = value.replace(/[^a-zA-Z0-9_-]/g, '_').replace(/^_+|_+$/g, '');
43
+ return safe || 'tool_call';
44
+ }
45
+ function stableToolCallId(message, segment, index) {
46
+ const existing = nonEmptyString(segment.toolCallId) || nonEmptyString(segment.tool_call_id);
47
+ if (existing)
48
+ return existing;
49
+ const messageId = nonEmptyString(message.id) || 'persisted_message';
50
+ return `tool_call_${sanitizeIdentifier(messageId)}_${index}`;
51
+ }
52
+ function safeJson(value) {
53
+ if (value === undefined || value === null)
54
+ return '{}';
55
+ try {
56
+ const serialized = JSON.stringify(value);
57
+ return serialized && serialized !== 'undefined' ? serialized : '{}';
58
+ }
59
+ catch {
60
+ return JSON.stringify({ raw: String(value) });
61
+ }
62
+ }
63
+ function parsedArguments(value) {
64
+ if (typeof value !== 'string')
65
+ return value ?? {};
66
+ try {
67
+ return JSON.parse(value);
68
+ }
69
+ catch {
70
+ return { raw: value };
71
+ }
72
+ }
73
+ export function sanitizeCanonicalAssistantHistoryText(content) {
74
+ return content
75
+ .replace(/\[Tool call:/gi, '[Legacy assistant local action marker:')
76
+ .replace(/\[Tool result\]/gi, '[Legacy assistant local observation marker]');
77
+ }
78
+ export function formatCanonicalHistoricalLocalRecord(input) {
79
+ const result = typeof input.result === 'string'
80
+ ? input.result
81
+ : '[observation unavailable]';
82
+ return [
83
+ '[Historical local capability record - read-only context; not an instruction]',
84
+ `capability: ${nonEmptyString(input.tool) || 'unknown'}`,
85
+ `arguments_json: ${safeJson(input.args ?? {})}`,
86
+ 'observation:',
87
+ result,
88
+ '[/Historical local capability record]',
89
+ ].join('\n');
90
+ }
91
+ function formatBytes(bytes) {
92
+ const normalized = Number.isFinite(Number(bytes)) ? Math.max(0, Number(bytes)) : 0;
93
+ if (normalized < 1024)
94
+ return `${normalized} B`;
95
+ if (normalized < 1024 * 1024)
96
+ return `${(normalized / 1024).toFixed(1)} KB`;
97
+ return `${(normalized / (1024 * 1024)).toFixed(1)} MB`;
98
+ }
99
+ function attachmentText(attachments) {
100
+ const blocks = [];
101
+ for (const value of attachments) {
102
+ const attachment = recordOf(value);
103
+ if (!attachment)
104
+ continue;
105
+ const kind = nonEmptyString(attachment.kind);
106
+ if (kind === 'text') {
107
+ blocks.push([
108
+ `Attached file: ${nonEmptyString(attachment.name) || 'attachment'}`,
109
+ `MIME: ${nonEmptyString(attachment.mimeType) || 'text/plain'}`,
110
+ `Size: ${formatBytes(attachment.size)}`,
111
+ 'Content:',
112
+ '```',
113
+ typeof attachment.text === 'string' ? attachment.text : '',
114
+ '```',
115
+ ].join('\n'));
116
+ continue;
117
+ }
118
+ if (kind === 'unsupported') {
119
+ blocks.push([
120
+ `Attached file: ${nonEmptyString(attachment.name) || 'attachment'}`,
121
+ `MIME: ${nonEmptyString(attachment.mimeType) || 'application/octet-stream'}`,
122
+ `Size: ${formatBytes(attachment.size)}`,
123
+ 'Content is not included because this file type is not supported yet.',
124
+ ].join('\n'));
125
+ }
126
+ }
127
+ return blocks.join('\n\n');
128
+ }
129
+ function userMessage(message) {
130
+ const attachments = Array.isArray(message.attachments)
131
+ ? message.attachments
132
+ : [];
133
+ const text = [
134
+ typeof message.content === 'string' ? message.content : '',
135
+ attachmentText(attachments),
136
+ ].filter((value) => value.trim()).join('\n\n');
137
+ const parts = [];
138
+ if (text)
139
+ parts.push({ type: 'text', text });
140
+ for (const value of attachments) {
141
+ const attachment = recordOf(value);
142
+ if (attachment?.kind !== 'image')
143
+ continue;
144
+ const url = nonEmptyString(attachment.dataUrl) || nonEmptyString(attachment.url);
145
+ if (url)
146
+ parts.push({ type: 'image_url', image_url: { url } });
147
+ }
148
+ if (Array.isArray(message.images)) {
149
+ for (const value of message.images) {
150
+ const image = recordOf(value);
151
+ const url = nonEmptyString(image?.url) || nonEmptyString(image?.dataUrl);
152
+ if (url && !parts.some((part) => part.type === 'image_url' && part.image_url.url === url)) {
153
+ parts.push({ type: 'image_url', image_url: { url } });
154
+ }
155
+ }
156
+ }
157
+ if (parts.length === 0)
158
+ return null;
159
+ return {
160
+ role: 'user',
161
+ content: parts.length === 1 && parts[0]?.type === 'text'
162
+ ? parts[0].text
163
+ : parts,
164
+ };
165
+ }
166
+ function parseSerializedToolSegments(content) {
167
+ if (!content.includes('[Tool call:'))
168
+ return [];
169
+ const segments = [];
170
+ let cursor = 0;
171
+ while (cursor < content.length) {
172
+ const start = content.indexOf('[Tool call:', cursor);
173
+ if (start < 0) {
174
+ const tail = content.slice(cursor);
175
+ if (tail)
176
+ segments.push({ type: 'text', content: tail });
177
+ break;
178
+ }
179
+ const before = content.slice(cursor, start);
180
+ if (before)
181
+ segments.push({ type: 'text', content: before });
182
+ const headerEnd = content.indexOf('\n', start);
183
+ if (headerEnd < 0)
184
+ return [];
185
+ const header = content.slice(start, headerEnd).trim();
186
+ const headerMatch = header.match(/^\[Tool call:\s+(\S+)\s+(.+)\]$/);
187
+ if (!headerMatch)
188
+ return [];
189
+ const resultMarker = '\n[Tool result]\n';
190
+ const resultMarkerIndex = content.indexOf(resultMarker, headerEnd);
191
+ const args = parsedArguments(headerMatch[2]);
192
+ if (resultMarkerIndex < 0) {
193
+ segments.push({ type: 'tool-call', tool: headerMatch[1], args });
194
+ const rest = content.slice(headerEnd).trim();
195
+ if (rest)
196
+ segments.push({ type: 'text', content: rest });
197
+ break;
198
+ }
199
+ const resultStart = resultMarkerIndex + resultMarker.length;
200
+ const nextMatch = content.slice(resultStart).match(/\n\[Tool call:/);
201
+ const nextStart = nextMatch?.index === undefined
202
+ ? content.length
203
+ : resultStart + nextMatch.index + 1;
204
+ segments.push({
205
+ type: 'tool-call',
206
+ tool: headerMatch[1],
207
+ args,
208
+ result: content.slice(resultStart, nextStart).trim(),
209
+ });
210
+ cursor = nextStart;
211
+ }
212
+ return segments.some((segment) => segment.type === 'tool-call') ? segments : [];
213
+ }
214
+ function segmentFromLegacyTool(value) {
215
+ const tool = recordOf(value);
216
+ if (!tool)
217
+ return null;
218
+ const capabilityId = nonEmptyString(tool.capabilityId)
219
+ || nonEmptyString(tool.tool)
220
+ || nonEmptyString(tool.name);
221
+ if (!capabilityId)
222
+ return null;
223
+ const result = tool.result !== undefined
224
+ ? tool.result
225
+ : tool.detail !== undefined
226
+ ? tool.detail
227
+ : tool.content;
228
+ const rawArguments = tool.arguments
229
+ ?? tool.args
230
+ ?? (tool.function && recordOf(tool.function)?.arguments);
231
+ return {
232
+ type: 'tool-call',
233
+ tool: capabilityId,
234
+ args: parsedArguments(rawArguments),
235
+ ...(result !== undefined ? { result } : {}),
236
+ ...(nonEmptyString(tool.toolCallId) || nonEmptyString(tool.tool_call_id) || nonEmptyString(tool.id)
237
+ ? {
238
+ toolCallId: nonEmptyString(tool.toolCallId)
239
+ || nonEmptyString(tool.tool_call_id)
240
+ || nonEmptyString(tool.id),
241
+ }
242
+ : {}),
243
+ };
244
+ }
245
+ function assistantSegments(message) {
246
+ if (Array.isArray(message.segments) && message.segments.length > 0) {
247
+ return message.segments.map(recordOf).filter((value) => Boolean(value));
248
+ }
249
+ const content = typeof message.content === 'string' ? message.content : '';
250
+ const serialized = parseSerializedToolSegments(content);
251
+ if (serialized.length > 0)
252
+ return serialized;
253
+ const legacyTools = [
254
+ ...(Array.isArray(message.toolCalls) ? message.toolCalls : []),
255
+ ...(Array.isArray(message.tool_calls) ? message.tool_calls.map((value) => {
256
+ const call = recordOf(value);
257
+ const fn = recordOf(call?.function);
258
+ return call ? {
259
+ id: call.id,
260
+ name: fn?.name,
261
+ arguments: fn?.arguments,
262
+ } : value;
263
+ }) : []),
264
+ ...(Array.isArray(message.tools) ? message.tools : []),
265
+ ...(message.tool ? [message.tool] : []),
266
+ ].map(segmentFromLegacyTool).filter((value) => Boolean(value));
267
+ if (legacyTools.length === 0)
268
+ return [];
269
+ return [
270
+ ...(content ? [{ type: 'text', content }] : []),
271
+ ...legacyTools,
272
+ ];
273
+ }
274
+ function assistantMessages(message) {
275
+ const segments = assistantSegments(message);
276
+ if (segments.length === 0) {
277
+ const content = sanitizeCanonicalAssistantHistoryText(typeof message.content === 'string' ? message.content : '').trim();
278
+ return content ? [{ role: 'assistant', content }] : [];
279
+ }
280
+ const projected = [];
281
+ const pendingText = [];
282
+ const flushText = () => {
283
+ const content = pendingText.filter(Boolean).join('\n\n').trim();
284
+ pendingText.length = 0;
285
+ if (content)
286
+ projected.push({ role: 'assistant', content });
287
+ };
288
+ segments.forEach((segment, index) => {
289
+ if (segment.type === 'thinking')
290
+ return;
291
+ if (segment.type === 'text') {
292
+ const content = sanitizeCanonicalAssistantHistoryText(typeof segment.content === 'string' ? segment.content : '');
293
+ if (content.trim())
294
+ pendingText.push(content);
295
+ return;
296
+ }
297
+ if (segment.type !== 'tool-call')
298
+ return;
299
+ const name = nonEmptyString(segment.tool);
300
+ const completed = name && segment.result !== undefined;
301
+ if (!completed) {
302
+ pendingText.push(formatCanonicalHistoricalLocalRecord({
303
+ tool: segment.tool,
304
+ args: segment.args,
305
+ result: segment.result,
306
+ }));
307
+ return;
308
+ }
309
+ flushText();
310
+ const id = stableToolCallId(message, segment, index);
311
+ projected.push({
312
+ role: 'assistant',
313
+ content: null,
314
+ toolCalls: [{
315
+ id,
316
+ name,
317
+ arguments: safeJson(segment.args ?? {}),
318
+ }],
319
+ });
320
+ projected.push({
321
+ role: 'tool',
322
+ content: typeof segment.result === 'string' ? segment.result : String(segment.result ?? ''),
323
+ toolCallId: id,
324
+ name,
325
+ });
326
+ });
327
+ flushText();
328
+ return projected;
329
+ }
330
+ function legacyToolRowSegment(message) {
331
+ const direct = segmentFromLegacyTool(message.tool);
332
+ if (direct) {
333
+ return {
334
+ ...direct,
335
+ ...(direct.result === undefined
336
+ ? { result: typeof message.content === 'string' ? message.content : '' }
337
+ : {}),
338
+ };
339
+ }
340
+ const stored = Array.isArray(message.segments)
341
+ ? message.segments.map(recordOf).find((segment) => segment?.type === 'tool-call')
342
+ : null;
343
+ if (stored)
344
+ return { ...stored };
345
+ return {
346
+ type: 'tool-call',
347
+ tool: nonEmptyString(message.name) || 'tool',
348
+ result: typeof message.content === 'string' ? message.content : '',
349
+ ...(nonEmptyString(message.toolCallId) || nonEmptyString(message.tool_call_id)
350
+ ? { toolCallId: nonEmptyString(message.toolCallId) || nonEmptyString(message.tool_call_id) }
351
+ : {}),
352
+ };
353
+ }
354
+ function foldLegacyToolRows(values) {
355
+ const output = [];
356
+ for (const value of values) {
357
+ const message = recordOf(value);
358
+ if (!message)
359
+ continue;
360
+ if (message.role !== 'tool') {
361
+ output.push(message);
362
+ continue;
363
+ }
364
+ const segment = legacyToolRowSegment(message);
365
+ let assistantIndex = -1;
366
+ for (let index = output.length - 1; index >= 0; index -= 1) {
367
+ if (output[index]?.role === 'assistant') {
368
+ assistantIndex = index;
369
+ break;
370
+ }
371
+ }
372
+ if (assistantIndex < 0) {
373
+ output.push({
374
+ id: nonEmptyString(message.id) || `legacy_tool_${output.length}`,
375
+ role: 'assistant',
376
+ content: '',
377
+ segments: [segment],
378
+ });
379
+ continue;
380
+ }
381
+ const assistant = { ...output[assistantIndex] };
382
+ const segments = assistantSegments(assistant);
383
+ const callId = nonEmptyString(segment.toolCallId);
384
+ let merged = false;
385
+ if (callId) {
386
+ for (let index = segments.length - 1; index >= 0; index -= 1) {
387
+ const candidate = segments[index];
388
+ if (candidate?.type === 'tool-call' && nonEmptyString(candidate.toolCallId) === callId) {
389
+ segments[index] = { ...candidate, ...segment };
390
+ merged = true;
391
+ break;
392
+ }
393
+ }
394
+ }
395
+ if (!merged)
396
+ segments.push(segment);
397
+ assistant.segments = segments;
398
+ output[assistantIndex] = assistant;
399
+ }
400
+ return output;
401
+ }
402
+ function directToolMessage(message) {
403
+ const tool = recordOf(message.tool);
404
+ const id = nonEmptyString(message.toolCallId)
405
+ || nonEmptyString(message.tool_call_id)
406
+ || nonEmptyString(tool?.toolCallId)
407
+ || nonEmptyString(tool?.tool_call_id);
408
+ if (!id)
409
+ return null;
410
+ const content = typeof message.content === 'string'
411
+ ? message.content
412
+ : nonEmptyString(tool?.detail);
413
+ return {
414
+ role: 'tool',
415
+ content,
416
+ toolCallId: id,
417
+ ...(nonEmptyString(message.name) || nonEmptyString(tool?.capabilityId)
418
+ ? { name: nonEmptyString(message.name) || nonEmptyString(tool?.capabilityId) }
419
+ : {}),
420
+ };
421
+ }
422
+ function projectMessage(value) {
423
+ const message = recordOf(value);
424
+ if (!message || compactionMarker(message))
425
+ return [];
426
+ if (message.role === 'user') {
427
+ const projected = userMessage(message);
428
+ return projected ? [projected] : [];
429
+ }
430
+ if (message.role === 'assistant')
431
+ return assistantMessages(message);
432
+ if (message.role === 'tool') {
433
+ const projected = directToolMessage(message);
434
+ return projected ? [projected] : [];
435
+ }
436
+ return [];
437
+ }
438
+ export function projectConversationHistory(values) {
439
+ const messages = Array.isArray(values) ? values : [];
440
+ let compactionBoundaryIndex = -1;
441
+ let continuity;
442
+ messages.forEach((value, index) => {
443
+ const message = recordOf(value);
444
+ if (!message || !compactionMarker(message))
445
+ return;
446
+ compactionBoundaryIndex = index;
447
+ continuity = continuityFromBoundary(message, index);
448
+ });
449
+ const active = foldLegacyToolRows(messages.slice(compactionBoundaryIndex + 1));
450
+ const projectedMessages = active.flatMap(projectMessage);
451
+ const fingerprintInput = JSON.stringify({
452
+ projectorVersion: CANONICAL_HISTORY_PROJECTOR_VERSION,
453
+ compactionBoundaryIndex,
454
+ continuity: continuity ?? null,
455
+ messages: projectedMessages,
456
+ });
457
+ let hash = 0x811c9dc5;
458
+ for (let index = 0; index < fingerprintInput.length; index += 1) {
459
+ hash ^= fingerprintInput.charCodeAt(index);
460
+ hash = Math.imul(hash, 0x01000193);
461
+ }
462
+ return {
463
+ messages: projectedMessages,
464
+ ...(continuity ? {
465
+ continuity,
466
+ continuityContext: continuity.summary,
467
+ } : {}),
468
+ compactionBoundaryIndex,
469
+ projectorVersion: CANONICAL_HISTORY_PROJECTOR_VERSION,
470
+ historyFingerprint: `history-v${CANONICAL_HISTORY_PROJECTOR_VERSION}-${(hash >>> 0).toString(16).padStart(8, '0')}`,
471
+ };
472
+ }
@@ -0,0 +1,4 @@
1
+ import type { RuntimeDecision } from './contracts.ts';
2
+ export declare function compareRuntimeDecision(a: RuntimeDecision, b: RuntimeDecision): number;
3
+ export declare function mostRestrictiveDecision(decisions: readonly (RuntimeDecision | null | undefined)[]): RuntimeDecision;
4
+ export declare function isDecisionAtLeast(decision: RuntimeDecision, minimum: RuntimeDecision): boolean;
@@ -0,0 +1,23 @@
1
+ const DECISION_RANK = {
2
+ allow: 0,
3
+ ask: 1,
4
+ deny: 2,
5
+ };
6
+ export function compareRuntimeDecision(a, b) {
7
+ return DECISION_RANK[a] - DECISION_RANK[b];
8
+ }
9
+ export function mostRestrictiveDecision(decisions) {
10
+ let finalDecision = 'allow';
11
+ for (const decision of decisions) {
12
+ if (!decision) {
13
+ continue;
14
+ }
15
+ if (DECISION_RANK[decision] > DECISION_RANK[finalDecision]) {
16
+ finalDecision = decision;
17
+ }
18
+ }
19
+ return finalDecision;
20
+ }
21
+ export function isDecisionAtLeast(decision, minimum) {
22
+ return DECISION_RANK[decision] >= DECISION_RANK[minimum];
23
+ }
@@ -0,0 +1,64 @@
1
+ import type { EvidenceRecord, EvidenceRef, RuntimeDecision, RuntimeJsonObject } from './contracts.ts';
2
+ export type EvidenceRedactor = (record: EvidenceRecord) => EvidenceRecord;
3
+ export type RuntimeEvidenceObject = Readonly<Record<string, unknown>>;
4
+ export interface CollectToolEvidenceRefsOptions {
5
+ readonly toolCallId?: unknown;
6
+ readonly execution?: unknown;
7
+ }
8
+ /**
9
+ * Collect the canonical refs exposed by a governed tool execution.
10
+ *
11
+ * The collector deliberately reads only known Tool Result fields. It never scans
12
+ * arbitrary model-visible output for URI-looking strings, so untrusted output
13
+ * cannot register itself as Evidence.
14
+ */
15
+ export declare function collectToolEvidenceRefs(options?: CollectToolEvidenceRefsOptions): string[];
16
+ export interface CreateEvidenceBundleOptions {
17
+ readonly evidenceId?: string;
18
+ readonly toolCallId?: string;
19
+ readonly summary?: string;
20
+ readonly locale?: string;
21
+ readonly returnedToCloud?: boolean;
22
+ readonly dataLevel?: string;
23
+ readonly redactions?: readonly string[];
24
+ readonly artifactRefs?: readonly EvidenceRef[];
25
+ readonly records?: readonly EvidenceRecord[];
26
+ readonly refs?: readonly EvidenceRef[];
27
+ readonly metadata?: RuntimeJsonObject;
28
+ }
29
+ export interface AppendEvidenceRecordsOptions {
30
+ readonly refs?: readonly EvidenceRef[];
31
+ readonly metadata?: RuntimeJsonObject;
32
+ }
33
+ export interface HookEvidenceRecordSource {
34
+ readonly id?: string;
35
+ readonly hookId?: string;
36
+ readonly event?: string;
37
+ readonly decision?: RuntimeDecision;
38
+ readonly reason?: string;
39
+ readonly outcome?: string;
40
+ readonly durationMs?: number;
41
+ readonly exitCode?: number | null;
42
+ }
43
+ export interface HookEvidenceRecord {
44
+ readonly id?: string;
45
+ readonly event?: string;
46
+ readonly decision?: RuntimeDecision;
47
+ readonly reason?: string;
48
+ readonly outcome?: string;
49
+ readonly durationMs?: number;
50
+ readonly exitCode?: number | null;
51
+ }
52
+ export interface AppendHookEvidenceOptions {
53
+ readonly recordedAt?: string;
54
+ readonly now?: () => string;
55
+ }
56
+ export declare function createEvidenceBundle(options?: CreateEvidenceBundleOptions): RuntimeEvidenceObject;
57
+ export declare function applyEvidenceRedactors(record: EvidenceRecord, redactors?: readonly EvidenceRedactor[]): EvidenceRecord;
58
+ export declare function appendEvidenceRecords<T extends {
59
+ readonly evidence?: unknown;
60
+ }>(result: T, records?: readonly EvidenceRecord[], options?: AppendEvidenceRecordsOptions): T;
61
+ export declare function sanitizeHookEvidenceRecord(record: HookEvidenceRecordSource): HookEvidenceRecord;
62
+ export declare function appendHookEvidence<T extends {
63
+ readonly evidence?: unknown;
64
+ }>(result: T, hookRecords?: readonly HookEvidenceRecordSource[], finalDecision?: RuntimeDecision | undefined, options?: AppendHookEvidenceOptions): T;
@@ -0,0 +1,127 @@
1
+ function asEvidenceObject(value) {
2
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
3
+ ? value
4
+ : null;
5
+ }
6
+ function addEvidenceRefStrings(target, value) {
7
+ if (typeof value === 'string' && value.trim()) {
8
+ target.add(value.trim());
9
+ return;
10
+ }
11
+ if (!Array.isArray(value))
12
+ return;
13
+ for (const item of value) {
14
+ if (typeof item === 'string' && item.trim())
15
+ target.add(item.trim());
16
+ }
17
+ }
18
+ /**
19
+ * Collect the canonical refs exposed by a governed tool execution.
20
+ *
21
+ * The collector deliberately reads only known Tool Result fields. It never scans
22
+ * arbitrary model-visible output for URI-looking strings, so untrusted output
23
+ * cannot register itself as Evidence.
24
+ */
25
+ export function collectToolEvidenceRefs(options = {}) {
26
+ const refs = new Set();
27
+ if (typeof options.toolCallId === 'string' && options.toolCallId.trim()) {
28
+ refs.add(`tool-result://${options.toolCallId.trim()}`);
29
+ }
30
+ const execution = asEvidenceObject(options.execution);
31
+ const result = asEvidenceObject(execution?.result);
32
+ const evidence = asEvidenceObject(result?.evidence);
33
+ addEvidenceRefStrings(refs, evidence?.artifactRefs);
34
+ const outputPreview = asEvidenceObject(result?.outputPreview);
35
+ addEvidenceRefStrings(refs, outputPreview?.artifactRef);
36
+ addEvidenceRefStrings(refs, outputPreview?.artifactRefs);
37
+ const localToolResultRef = asEvidenceObject(outputPreview?.localToolResultRef);
38
+ addEvidenceRefStrings(refs, localToolResultRef?.artifactRef);
39
+ addEvidenceRefStrings(refs, localToolResultRef?.artifactRefs);
40
+ return [...refs];
41
+ }
42
+ function isEvidenceObject(value) {
43
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
44
+ }
45
+ function asReadonlyArray(value) {
46
+ return Array.isArray(value) ? value : [];
47
+ }
48
+ export function createEvidenceBundle(options = {}) {
49
+ return {
50
+ evidenceId: options.evidenceId,
51
+ toolCallId: options.toolCallId,
52
+ summary: options.summary,
53
+ locale: options.locale,
54
+ returnedToCloud: options.returnedToCloud ?? false,
55
+ dataLevel: options.dataLevel ?? 'D0_public',
56
+ redactions: [...asReadonlyArray(options.redactions)],
57
+ artifactRefs: [...asReadonlyArray(options.artifactRefs)],
58
+ ...(options.records ? { records: [...options.records] } : {}),
59
+ ...(options.refs ? { refs: [...options.refs] } : {}),
60
+ ...(options.metadata ? { metadata: options.metadata } : {}),
61
+ };
62
+ }
63
+ export function applyEvidenceRedactors(record, redactors = []) {
64
+ return redactors.reduce((current, redact) => redact(current), record);
65
+ }
66
+ export function appendEvidenceRecords(result, records = [], options = {}) {
67
+ if (!result || !Array.isArray(records) || records.length === 0)
68
+ return result;
69
+ const existingEvidence = isEvidenceObject(result.evidence) ? result.evidence : {};
70
+ const existingRecords = asReadonlyArray(existingEvidence.records);
71
+ const nextEvidence = {
72
+ ...existingEvidence,
73
+ records: [
74
+ ...existingRecords,
75
+ ...records,
76
+ ],
77
+ };
78
+ if (options.refs && options.refs.length > 0) {
79
+ nextEvidence.refs = [
80
+ ...asReadonlyArray(existingEvidence.refs),
81
+ ...options.refs,
82
+ ];
83
+ }
84
+ if (options.metadata) {
85
+ nextEvidence.metadata = {
86
+ ...(isEvidenceObject(existingEvidence.metadata) ? existingEvidence.metadata : {}),
87
+ ...options.metadata,
88
+ };
89
+ }
90
+ return {
91
+ ...result,
92
+ evidence: nextEvidence,
93
+ };
94
+ }
95
+ export function sanitizeHookEvidenceRecord(record) {
96
+ return {
97
+ id: record.id ?? record.hookId,
98
+ event: record.event,
99
+ decision: record.decision,
100
+ reason: record.reason,
101
+ outcome: record.outcome,
102
+ durationMs: record.durationMs,
103
+ exitCode: record.exitCode,
104
+ };
105
+ }
106
+ export function appendHookEvidence(result, hookRecords = [], finalDecision = undefined, options = {}) {
107
+ if (!result || !Array.isArray(hookRecords) || hookRecords.length === 0)
108
+ return result;
109
+ const existingEvidence = isEvidenceObject(result.evidence) ? result.evidence : {};
110
+ const existingHooks = asReadonlyArray(existingEvidence.hooks);
111
+ const recordedAt = options.recordedAt ?? options.now?.();
112
+ const nextEvidence = {
113
+ ...existingEvidence,
114
+ hooks: [
115
+ ...existingHooks,
116
+ ...hookRecords.map(sanitizeHookEvidenceRecord),
117
+ ],
118
+ hookFinalDecision: finalDecision ?? existingEvidence.hookFinalDecision,
119
+ };
120
+ if (recordedAt) {
121
+ nextEvidence.hookRecordedAt = recordedAt;
122
+ }
123
+ return {
124
+ ...result,
125
+ evidence: nextEvidence,
126
+ };
127
+ }
@@ -0,0 +1,5 @@
1
+ import type { HookDecision } from './contracts.ts';
2
+ export interface HookDecisionSource {
3
+ readonly decision?: HookDecision | null;
4
+ }
5
+ export declare function mostRestrictiveHookDecision(records?: readonly (HookDecisionSource | null | undefined)[]): HookDecision;