@kya-os/mcp-i-runtime 1.1.0 → 1.2.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 (51) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/config.d.ts +5 -7
  3. package/dist/config.d.ts.map +1 -1
  4. package/dist/config.js +4 -6
  5. package/dist/config.js.map +1 -1
  6. package/dist/index.d.ts +2 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +13 -2
  9. package/dist/index.js.map +1 -1
  10. package/dist/runtime/audit-logger.d.ts +6 -28
  11. package/dist/runtime/audit-logger.d.ts.map +1 -1
  12. package/dist/runtime/audit-logger.js +5 -3
  13. package/dist/runtime/audit-logger.js.map +1 -1
  14. package/dist/runtime/audit.d.ts +132 -0
  15. package/dist/runtime/audit.d.ts.map +1 -0
  16. package/dist/runtime/audit.js +424 -0
  17. package/dist/runtime/audit.js.map +1 -0
  18. package/dist/runtime/base.d.ts +9 -48
  19. package/dist/runtime/base.d.ts.map +1 -1
  20. package/dist/runtime/base.js +109 -89
  21. package/dist/runtime/base.js.map +1 -1
  22. package/dist/services/oauth-config.service.d.ts.map +1 -1
  23. package/dist/services/oauth-config.service.js +29 -0
  24. package/dist/services/oauth-config.service.js.map +1 -1
  25. package/package.json +7 -3
  26. package/src/__tests__/config/provider-runtime-config.test.ts +2 -9
  27. package/src/__tests__/config.test.ts +12 -11
  28. package/src/__tests__/integration/full-flow.test.ts +0 -5
  29. package/src/__tests__/integration.test.ts +2 -6
  30. package/src/__tests__/runtime/audit.test.ts +327 -0
  31. package/src/__tests__/runtime/base-extensions.test.ts +0 -46
  32. package/src/__tests__/runtime/base.test.ts +71 -102
  33. package/src/__tests__/runtime/delegation-flow.test.ts +0 -4
  34. package/src/__tests__/runtime/process-tool-call-security.test.ts +5 -11
  35. package/src/__tests__/runtime/proof-client-did.test.ts +0 -4
  36. package/src/__tests__/runtime/provider-selection.test.ts +0 -2
  37. package/src/__tests__/runtime/route-interception.test.ts +7 -4
  38. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +23 -31
  39. package/src/__tests__/services/tool-protection-merged-config.test.ts +0 -40
  40. package/src/config/__tests__/merged-config.spec.ts +0 -26
  41. package/src/config.ts +9 -10
  42. package/src/index.ts +23 -2
  43. package/src/runtime/__tests__/audit-logger-compat.test.ts +15 -0
  44. package/src/runtime/audit-logger.ts +6 -29
  45. package/src/runtime/audit.ts +598 -0
  46. package/src/runtime/base.ts +154 -99
  47. package/src/services/__tests__/oauth-config.service.test.ts +66 -0
  48. package/src/services/__tests__/proof-verifier.integration.test.ts +1 -1
  49. package/src/services/__tests__/proof-verifier.test.ts +6 -3
  50. package/src/services/oauth-config.service.ts +44 -1
  51. package/src/__tests__/runtime/audit-logger.test.ts +0 -154
@@ -0,0 +1,598 @@
1
+ import type {
2
+ AuditAssuranceProfile,
3
+ AuditCapabilities,
4
+ AuditEmitResult,
5
+ AuditTrailEventInput,
6
+ AuthorizationEvidence,
7
+ PartyRef,
8
+ } from "@kya-os/mcp/audit" with { "resolution-mode": "import" };
9
+
10
+ const encoder = new TextEncoder();
11
+ const MAX_REFERENCE_LENGTH = 256;
12
+
13
+ export interface RuntimeAuditTrailPort {
14
+ /** Present on AuditTrailService and recommended for remote trail adapters. */
15
+ readonly configuration?: { readonly sourceId?: string };
16
+ /** Mechanically derived by the configured recorder/producer, never a user label. */
17
+ readonly auditProfile?: AuditAssuranceProfile;
18
+ /** Full mechanics used to substantiate an assurance profile when available. */
19
+ readonly capabilities?: AuditCapabilities;
20
+ record(input: AuditTrailEventInput): Promise<AuditEmitResult>;
21
+ }
22
+
23
+ export interface RuntimeAuditAssurance {
24
+ enabled: boolean;
25
+ profile: AuditAssuranceProfile;
26
+ capabilities?: AuditCapabilities;
27
+ }
28
+
29
+ /**
30
+ * Resolve the assurance the active canonical trail can substantiate.
31
+ *
32
+ * A configured trail without a complete capabilities report is observable but
33
+ * remains AAP-0. Legacy diagnostic logging is deliberately not consulted.
34
+ */
35
+ export function resolveRuntimeAuditAssurance(
36
+ config: RuntimeAuditConfig | undefined,
37
+ ): RuntimeAuditAssurance {
38
+ if (config === undefined) return { enabled: false, profile: "AAP-0" };
39
+ const capabilities = config.trail.capabilities;
40
+ if (capabilities === undefined) return { enabled: true, profile: "AAP-0" };
41
+ return {
42
+ enabled: true,
43
+ profile: capabilities.profile,
44
+ capabilities,
45
+ };
46
+ }
47
+
48
+ export interface RuntimeAuditToolInput {
49
+ toolName: string;
50
+ args: unknown;
51
+ session?: Record<string, unknown>;
52
+ }
53
+
54
+ export interface RuntimeConsentAuditInput {
55
+ phase:
56
+ | "requested"
57
+ | "approved"
58
+ | "denied"
59
+ | "credential_required"
60
+ | "credential_verified"
61
+ | "credential_failed";
62
+ outcome: "succeeded" | "failed" | "denied" | "challenged";
63
+ sessionId: string;
64
+ userDid?: string;
65
+ consentRef?: string;
66
+ reasonCode?: string;
67
+ correlationId?: string;
68
+ causationId?: string;
69
+ }
70
+
71
+ export interface RuntimeDelegationAuditInput {
72
+ phase: "issued" | "verified" | "rejected" | "revoked" | "cascade_revoked" | "outbound_attached";
73
+ outcome: "succeeded" | "failed" | "denied";
74
+ sessionId: string;
75
+ delegationRef: string;
76
+ userDid?: string;
77
+ parentRef?: string;
78
+ reasonCode?: string;
79
+ correlationId?: string;
80
+ causationId?: string;
81
+ }
82
+
83
+ export interface RuntimeAuditCallContext {
84
+ /** Stable for the logical invocation and safe to expose in the audit stream. */
85
+ invocationId: string;
86
+ /** Stable across the events that belong to the same logical operation. */
87
+ correlationId: string;
88
+ causationId?: string;
89
+ session?: { ref: PartyRef };
90
+ actor?: PartyRef;
91
+ responsibleParty?: PartyRef;
92
+ authorization?: AuthorizationEvidence;
93
+ attempt?: string;
94
+ }
95
+
96
+ export interface RuntimeAuditContextFactory {
97
+ create(input: RuntimeAuditToolInput):
98
+ | RuntimeAuditCallContext
99
+ | Promise<RuntimeAuditCallContext>;
100
+ }
101
+
102
+ /**
103
+ * Canonical KYA-OS audit configuration for the product runtime.
104
+ *
105
+ * The trail owns delivery and assurance semantics. In particular, a required
106
+ * trail throws when intent cannot be recorded, while a best-effort trail
107
+ * returns a failed result. Diagnostic output is never promoted to an assurance
108
+ * claim.
109
+ */
110
+ export interface RuntimeAuditConfig {
111
+ trail: RuntimeAuditTrailPort;
112
+ context: RuntimeAuditContextFactory;
113
+ /** Stable deployment/source label. The configured AuditTrailService remains authoritative. */
114
+ sourceId: string;
115
+ /** Tool names are omitted by default to preserve the core adapter's privacy posture. */
116
+ includeToolNames?: boolean;
117
+ }
118
+
119
+ export interface HmacRuntimeAuditContextOptions {
120
+ /** Deployment-scoped secret. It is never included in an event. */
121
+ secret: string | Uint8Array;
122
+ /** Identifier for secret rotation and verifier-side correlation policy. */
123
+ keyId: string;
124
+ randomUUID?: () => string;
125
+ }
126
+
127
+ function optionalString(record: Record<string, unknown> | undefined, key: string): string | undefined {
128
+ const value = record?.[key];
129
+ if (typeof value !== "string") return undefined;
130
+ const trimmed = value.trim();
131
+ return trimmed.length === 0 ? undefined : trimmed;
132
+ }
133
+
134
+ function bounded(value: string): string {
135
+ return value.slice(0, MAX_REFERENCE_LENGTH);
136
+ }
137
+
138
+ function eventIdFor(invocationId: string, phase: string): string {
139
+ const suffix = `:${phase}`;
140
+ return `${invocationId.slice(0, MAX_REFERENCE_LENGTH - suffix.length)}${suffix}`;
141
+ }
142
+
143
+ function bytesToHex(bytes: Uint8Array): string {
144
+ let result = "";
145
+ for (const byte of bytes) result += byte.toString(16).padStart(2, "0");
146
+ return result;
147
+ }
148
+
149
+ /**
150
+ * Build privacy-safe, deterministic references with HMAC-SHA-256.
151
+ *
152
+ * Callers may pass `auditInvocationId`, `auditCorrelationId`, and
153
+ * `auditCausationId` in the request-scoped session object. They are committed
154
+ * before emission, so transport/session capabilities never enter the journal.
155
+ */
156
+ export function createHmacRuntimeAuditContextFactory(
157
+ options: HmacRuntimeAuditContextOptions,
158
+ ): RuntimeAuditContextFactory {
159
+ if (options.keyId.trim().length === 0) {
160
+ throw new TypeError("Audit reference keyId must be non-empty");
161
+ }
162
+ const secret = typeof options.secret === "string"
163
+ ? encoder.encode(options.secret)
164
+ : new Uint8Array(options.secret);
165
+ if (secret.byteLength < 32) {
166
+ throw new TypeError("Audit reference secret must contain at least 32 bytes");
167
+ }
168
+ const randomUUID = options.randomUUID ?? (() => crypto.randomUUID());
169
+ let keyPromise: ReturnType<typeof crypto.subtle.importKey> | undefined;
170
+
171
+ const commitment = async (domain: string, value: string): Promise<`sha256:${string}`> => {
172
+ keyPromise ??= crypto.subtle.importKey(
173
+ "raw",
174
+ secret,
175
+ { name: "HMAC", hash: "SHA-256" },
176
+ false,
177
+ ["sign"],
178
+ );
179
+ const signature = await crypto.subtle.sign(
180
+ "HMAC",
181
+ await keyPromise,
182
+ encoder.encode(`${domain}\0${value}`),
183
+ );
184
+ return `sha256:${bytesToHex(new Uint8Array(signature))}`;
185
+ };
186
+
187
+ const opaqueId = async (domain: string, value: string): Promise<string> =>
188
+ `${domain}:${(await commitment(`org.kya-os.audit.${domain}.v1`, value)).slice("sha256:".length)}`;
189
+
190
+ return {
191
+ async create(input): Promise<RuntimeAuditCallContext> {
192
+ const session = input.session;
193
+ const rawInvocation = optionalString(session, "auditInvocationId") ?? randomUUID();
194
+ const rawCorrelation = optionalString(session, "auditCorrelationId") ?? rawInvocation;
195
+ const rawCausation = optionalString(session, "auditCausationId");
196
+ const sessionId = optionalString(session, "id");
197
+ const actorDid = optionalString(session, "clientDid") ?? optionalString(session, "userDid");
198
+
199
+ const [invocationId, correlationId, causationId, sessionCommitment] = await Promise.all([
200
+ opaqueId("invocation", rawInvocation),
201
+ opaqueId("correlation", rawCorrelation),
202
+ rawCausation === undefined ? undefined : opaqueId("causation", rawCausation),
203
+ sessionId === undefined
204
+ ? undefined
205
+ : commitment("org.kya-os.audit.session-ref.v1", sessionId),
206
+ ]);
207
+
208
+ return {
209
+ invocationId: bounded(invocationId),
210
+ correlationId: bounded(correlationId),
211
+ ...(causationId === undefined ? {} : { causationId: bounded(causationId) }),
212
+ ...(sessionCommitment === undefined
213
+ ? {}
214
+ : {
215
+ session: {
216
+ ref: {
217
+ kind: "keyed_commitment",
218
+ value: sessionCommitment,
219
+ keyId: bounded(options.keyId),
220
+ },
221
+ },
222
+ }),
223
+ ...(actorDid?.startsWith("did:")
224
+ ? { actor: { kind: "public_did" as const, did: actorDid } }
225
+ : {}),
226
+ };
227
+ },
228
+ };
229
+ }
230
+
231
+ export type RuntimeToolTerminalPhase = "completed" | "failed" | "denied" | "challenged";
232
+
233
+ export interface RuntimeToolTerminal {
234
+ phase: RuntimeToolTerminalPhase;
235
+ outcome: "succeeded" | "failed" | "denied" | "challenged";
236
+ reasonCode?: string;
237
+ }
238
+
239
+ export class RuntimeToolAuditInvocation {
240
+ private terminalRecorded = false;
241
+ private startedResult?: AuditEmitResult;
242
+
243
+ constructor(
244
+ private readonly config: RuntimeAuditConfig,
245
+ private readonly toolName: string,
246
+ readonly context: RuntimeAuditCallContext,
247
+ ) {}
248
+
249
+ async started(): Promise<AuditEmitResult> {
250
+ const result = await this.config.trail.record({
251
+ eventId: eventIdFor(this.context.invocationId, "started"),
252
+ eventType: "tool.call.started",
253
+ ...this.eventContext(),
254
+ action: {
255
+ category: "tool.call",
256
+ ...(this.config.includeToolNames ? { name: bounded(this.toolName) } : {}),
257
+ },
258
+ outcome: "unknown",
259
+ evidence: [],
260
+ details: {
261
+ family: "tool",
262
+ phase: "started",
263
+ attempt: this.context.attempt ?? "1",
264
+ idempotencyRef: bounded(this.context.invocationId),
265
+ },
266
+ });
267
+ this.startedResult = result;
268
+ return result;
269
+ }
270
+
271
+ async terminal(value: RuntimeToolTerminal): Promise<AuditEmitResult> {
272
+ if (this.terminalRecorded) {
273
+ throw new Error(`Terminal audit event already recorded for ${this.context.invocationId}`);
274
+ }
275
+ this.terminalRecorded = true;
276
+ return this.config.trail.record({
277
+ eventId: eventIdFor(this.context.invocationId, value.phase),
278
+ eventType: `tool.call.${value.phase}`,
279
+ ...this.eventContext(),
280
+ action: {
281
+ category: "tool.call",
282
+ ...(this.config.includeToolNames ? { name: bounded(this.toolName) } : {}),
283
+ },
284
+ outcome: value.outcome,
285
+ ...(value.reasonCode === undefined
286
+ ? {}
287
+ : { reason: { code: bounded(value.reasonCode) } }),
288
+ evidence: [],
289
+ details: {
290
+ family: "tool",
291
+ phase: value.phase,
292
+ attempt: this.context.attempt ?? "1",
293
+ idempotencyRef: bounded(this.context.invocationId),
294
+ },
295
+ });
296
+ }
297
+
298
+ results(terminal?: AuditEmitResult): readonly AuditEmitResult[] {
299
+ if (this.startedResult === undefined) return terminal === undefined ? [] : [terminal];
300
+ return terminal === undefined ? [this.startedResult] : [this.startedResult, terminal];
301
+ }
302
+
303
+ private eventContext(): Pick<
304
+ AuditTrailEventInput,
305
+ "correlationId" | "causationId" | "session" | "actor" | "responsibleParty" | "authorization"
306
+ > {
307
+ return {
308
+ correlationId: bounded(this.context.correlationId),
309
+ ...(this.context.causationId === undefined
310
+ ? {}
311
+ : { causationId: bounded(this.context.causationId) }),
312
+ ...(this.context.session === undefined ? {} : { session: this.context.session }),
313
+ ...(this.context.actor === undefined ? {} : { actor: this.context.actor }),
314
+ ...(this.context.responsibleParty === undefined
315
+ ? {}
316
+ : { responsibleParty: this.context.responsibleParty }),
317
+ ...(this.context.authorization === undefined
318
+ ? {}
319
+ : { authorization: this.context.authorization }),
320
+ };
321
+ }
322
+ }
323
+
324
+ export async function beginRuntimeToolAudit(
325
+ config: RuntimeAuditConfig,
326
+ input: RuntimeAuditToolInput,
327
+ ): Promise<RuntimeToolAuditInvocation> {
328
+ if (config.sourceId.trim().length === 0) {
329
+ throw new TypeError("Audit sourceId must be non-empty");
330
+ }
331
+ const trailSourceId = config.trail.configuration?.sourceId;
332
+ if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
333
+ throw new TypeError(
334
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
335
+ );
336
+ }
337
+ const invocation = new RuntimeToolAuditInvocation(
338
+ config,
339
+ input.toolName,
340
+ await config.context.create(input),
341
+ );
342
+ await invocation.started();
343
+ return invocation;
344
+ }
345
+
346
+ /**
347
+ * Record a privacy-minimal consent or credential lifecycle event through the
348
+ * canonical trail. Proof submission remains an independent concern: this
349
+ * function never generates or transports a proof and never copies consent
350
+ * request payloads into the event.
351
+ */
352
+ export async function recordRuntimeConsentAudit(
353
+ config: RuntimeAuditConfig,
354
+ input: RuntimeConsentAuditInput,
355
+ ): Promise<AuditEmitResult> {
356
+ if (config.sourceId.trim().length === 0) {
357
+ throw new TypeError("Audit sourceId must be non-empty");
358
+ }
359
+ const trailSourceId = config.trail.configuration?.sourceId;
360
+ if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
361
+ throw new TypeError(
362
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
363
+ );
364
+ }
365
+
366
+ const context = await config.context.create({
367
+ toolName: input.phase.startsWith("credential_")
368
+ ? `credential.${input.phase.slice("credential_".length)}`
369
+ : `consent.${input.phase}`,
370
+ args: {},
371
+ session: {
372
+ id: input.sessionId,
373
+ ...(input.userDid === undefined ? {} : { userDid: input.userDid }),
374
+ ...(input.correlationId === undefined
375
+ ? {}
376
+ : { auditCorrelationId: input.correlationId }),
377
+ ...(input.causationId === undefined
378
+ ? {}
379
+ : { auditCausationId: input.causationId }),
380
+ },
381
+ });
382
+ const eventTypes = {
383
+ requested: "consent.requested",
384
+ approved: "consent.approved",
385
+ denied: "consent.denied",
386
+ credential_required: "credential.required",
387
+ credential_verified: "credential.verified",
388
+ credential_failed: "credential.failed",
389
+ } as const;
390
+
391
+ return config.trail.record({
392
+ eventId: eventIdFor(context.invocationId, input.phase),
393
+ eventType: eventTypes[input.phase],
394
+ correlationId: bounded(context.correlationId),
395
+ ...(context.causationId === undefined
396
+ ? {}
397
+ : { causationId: bounded(context.causationId) }),
398
+ ...(context.session === undefined ? {} : { session: context.session }),
399
+ ...(context.actor === undefined ? {} : { actor: context.actor }),
400
+ ...(context.responsibleParty === undefined
401
+ ? {}
402
+ : { responsibleParty: context.responsibleParty }),
403
+ action: { category: "consent" },
404
+ outcome: input.outcome,
405
+ ...(input.reasonCode === undefined
406
+ ? {}
407
+ : { reason: { code: bounded(input.reasonCode) } }),
408
+ evidence: [],
409
+ details: {
410
+ family: "consent",
411
+ phase: input.phase,
412
+ ...(input.consentRef === undefined
413
+ ? {}
414
+ : { consentRef: bounded(input.consentRef) }),
415
+ },
416
+ });
417
+ }
418
+
419
+ /** Record a privacy-minimal delegation lifecycle event on the canonical trail. */
420
+ export async function recordRuntimeDelegationAudit(
421
+ config: RuntimeAuditConfig,
422
+ input: RuntimeDelegationAuditInput,
423
+ ): Promise<AuditEmitResult> {
424
+ if (config.sourceId.trim().length === 0) {
425
+ throw new TypeError("Audit sourceId must be non-empty");
426
+ }
427
+ const trailSourceId = config.trail.configuration?.sourceId;
428
+ if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
429
+ throw new TypeError(
430
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
431
+ );
432
+ }
433
+ const context = await config.context.create({
434
+ toolName: `delegation.${input.phase}`,
435
+ args: {},
436
+ session: {
437
+ id: input.sessionId,
438
+ ...(input.userDid === undefined ? {} : { userDid: input.userDid }),
439
+ ...(input.correlationId === undefined
440
+ ? {}
441
+ : { auditCorrelationId: input.correlationId }),
442
+ ...(input.causationId === undefined
443
+ ? {}
444
+ : { auditCausationId: input.causationId }),
445
+ },
446
+ });
447
+ const eventTypes = {
448
+ issued: "delegation.issued",
449
+ verified: "delegation.verified",
450
+ rejected: "delegation.rejected",
451
+ revoked: "delegation.revoked",
452
+ cascade_revoked: "delegation.cascade_revoked",
453
+ outbound_attached: "delegation.outbound_attached",
454
+ } as const;
455
+
456
+ return config.trail.record({
457
+ eventId: eventIdFor(context.invocationId, input.phase),
458
+ eventType: eventTypes[input.phase],
459
+ correlationId: bounded(context.correlationId),
460
+ ...(context.causationId === undefined
461
+ ? {}
462
+ : { causationId: bounded(context.causationId) }),
463
+ ...(context.session === undefined ? {} : { session: context.session }),
464
+ ...(context.actor === undefined ? {} : { actor: context.actor }),
465
+ action: { category: "delegation" },
466
+ outcome: input.outcome,
467
+ ...(input.reasonCode === undefined
468
+ ? {}
469
+ : { reason: { code: bounded(input.reasonCode) } }),
470
+ evidence: [],
471
+ details: {
472
+ family: "delegation",
473
+ phase: input.phase,
474
+ delegationRef: bounded(input.delegationRef),
475
+ ...(input.parentRef === undefined
476
+ ? {}
477
+ : { parentRef: bounded(input.parentRef) }),
478
+ },
479
+ });
480
+ }
481
+
482
+ export const RUNTIME_AUDIT_META_KEY = "org.kya-os/audit" as const;
483
+
484
+ interface RuntimeAuditEventReference {
485
+ eventId: string;
486
+ eventType: string;
487
+ status: AuditEmitResult["status"];
488
+ sourceSequence?: string;
489
+ receipt?: {
490
+ ledgerId: string;
491
+ ledgerEpochId: string;
492
+ sequence: string;
493
+ entryDigest: string;
494
+ };
495
+ }
496
+
497
+ function auditEventReference(result: AuditEmitResult): RuntimeAuditEventReference {
498
+ return {
499
+ eventId: result.event.eventId,
500
+ eventType: result.event.eventType,
501
+ status: result.status,
502
+ ...(result.event.source.sourceSequence === undefined
503
+ ? {}
504
+ : { sourceSequence: result.event.source.sourceSequence }),
505
+ ...(result.status !== "recorded"
506
+ ? {}
507
+ : {
508
+ receipt: {
509
+ ledgerId: result.entry.core.ledgerId,
510
+ ledgerEpochId: result.entry.core.ledgerEpochId,
511
+ sequence: result.entry.core.sequence,
512
+ entryDigest: result.entry.entryDigest,
513
+ },
514
+ }),
515
+ };
516
+ }
517
+
518
+ /** Merge audit delivery references into `_meta` without replacing proof or foreign metadata. */
519
+ export function attachRuntimeAuditMetadata<T>(
520
+ result: T,
521
+ sourceId: string,
522
+ invocationId: string,
523
+ auditResults: readonly AuditEmitResult[],
524
+ requiredDeliveryError = false,
525
+ ): T {
526
+ if (!isRecord(result) || Array.isArray(result)) {
527
+ if (requiredDeliveryError) {
528
+ throw new Error("Required terminal audit delivery failed after tool execution");
529
+ }
530
+ return result;
531
+ }
532
+ const mutableResult = result as Record<string, unknown>;
533
+ const existingMeta = isRecord(mutableResult["_meta"])
534
+ ? mutableResult["_meta"]
535
+ : {};
536
+ const existingAudit = isRecord(existingMeta[RUNTIME_AUDIT_META_KEY])
537
+ ? existingMeta[RUNTIME_AUDIT_META_KEY]
538
+ : {};
539
+ const degraded = requiredDeliveryError || auditResults.some((item) => item.status === "failed");
540
+ mutableResult["_meta"] = {
541
+ ...existingMeta,
542
+ [RUNTIME_AUDIT_META_KEY]: {
543
+ ...existingAudit,
544
+ status: degraded ? "degraded" : auditResults.at(-1)?.status ?? "unknown",
545
+ sourceId,
546
+ invocationId,
547
+ events: auditResults.map(auditEventReference),
548
+ ...(requiredDeliveryError ? { reason: "AUDIT_TERMINAL_DELIVERY_FAILED" } : {}),
549
+ },
550
+ };
551
+ if (requiredDeliveryError) mutableResult["isError"] = true;
552
+ return result;
553
+ }
554
+
555
+ function isRecord(value: unknown): value is Record<string, unknown> {
556
+ return typeof value === "object" && value !== null;
557
+ }
558
+
559
+ export function terminalForToolResult(result: unknown): RuntimeToolTerminal {
560
+ if (!isRecord(result)) {
561
+ return { phase: "completed", outcome: "succeeded" };
562
+ }
563
+ const structuredContent = isRecord(result.structuredContent)
564
+ ? result.structuredContent
565
+ : undefined;
566
+ if (structuredContent?.type === "consent_required") {
567
+ return {
568
+ phase: "challenged",
569
+ outcome: "challenged",
570
+ reasonCode: "AUTHORIZATION_REQUIRED",
571
+ };
572
+ }
573
+ if (result.isError !== true) return { phase: "completed", outcome: "succeeded" };
574
+ const metadata = isRecord(result._meta) ? result._meta : undefined;
575
+ const errorType = typeof metadata?.errorType === "string" ? metadata.errorType : undefined;
576
+ if (errorType === "authorization_required" || errorType === "oauth_required" ||
577
+ isRecord(metadata?.needs_authorization)) {
578
+ return {
579
+ phase: "challenged",
580
+ outcome: "challenged",
581
+ reasonCode: "AUTHORIZATION_REQUIRED",
582
+ };
583
+ }
584
+ return { phase: "failed", outcome: "failed", reasonCode: "HANDLER_ERROR_RESULT" };
585
+ }
586
+
587
+ export function terminalForToolError(error: unknown): RuntimeToolTerminal {
588
+ const name = error instanceof Error ? error.name : "UnknownError";
589
+ if (name === "DelegationRequiredError" || name === "OAuthRequiredError" ||
590
+ name === "AuthRequiredError") {
591
+ return {
592
+ phase: "challenged",
593
+ outcome: "challenged",
594
+ reasonCode: "AUTHORIZATION_REQUIRED",
595
+ };
596
+ }
597
+ return { phase: "failed", outcome: "failed", reasonCode: "HANDLER_THROWN" };
598
+ }