@kya-os/mcp-i-runtime 1.3.1 → 1.3.3

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 (122) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/auth/handshake.d.ts +23 -43
  3. package/dist/auth/handshake.d.ts.map +1 -1
  4. package/dist/auth/handshake.js +51 -82
  5. package/dist/auth/handshake.js.map +1 -1
  6. package/dist/auth/index.d.ts +1 -1
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js.map +1 -1
  9. package/dist/auth/resume-token.d.ts +52 -0
  10. package/dist/auth/resume-token.d.ts.map +1 -0
  11. package/dist/auth/resume-token.js +89 -0
  12. package/dist/auth/resume-token.js.map +1 -0
  13. package/dist/auth/types.d.ts +15 -0
  14. package/dist/auth/types.d.ts.map +1 -1
  15. package/dist/index.d.ts +7 -3
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +25 -3
  18. package/dist/index.js.map +1 -1
  19. package/dist/proof/companion.d.ts +25 -0
  20. package/dist/proof/companion.d.ts.map +1 -0
  21. package/dist/proof/companion.js +14 -0
  22. package/dist/proof/companion.js.map +1 -0
  23. package/dist/proof/generator.d.ts +22 -9
  24. package/dist/proof/generator.d.ts.map +1 -1
  25. package/dist/proof/generator.js +20 -27
  26. package/dist/proof/generator.js.map +1 -1
  27. package/dist/proof/index.d.ts +2 -1
  28. package/dist/proof/index.d.ts.map +1 -1
  29. package/dist/proof/index.js +3 -1
  30. package/dist/proof/index.js.map +1 -1
  31. package/dist/runtime/audit.d.ts.map +1 -1
  32. package/dist/runtime/audit.js +78 -18
  33. package/dist/runtime/audit.js.map +1 -1
  34. package/dist/runtime/base.d.ts +6 -1
  35. package/dist/runtime/base.d.ts.map +1 -1
  36. package/dist/runtime/base.js +65 -17
  37. package/dist/runtime/base.js.map +1 -1
  38. package/dist/runtime/dif-core.d.ts +8 -0
  39. package/dist/runtime/dif-core.d.ts.map +1 -1
  40. package/dist/runtime/dif-core.js +10 -0
  41. package/dist/runtime/dif-core.js.map +1 -1
  42. package/dist/services/access-control.service.d.ts.map +1 -1
  43. package/dist/services/access-control.service.js +12 -5
  44. package/dist/services/access-control.service.js.map +1 -1
  45. package/dist/services/claims-first-guard.d.ts +33 -0
  46. package/dist/services/claims-first-guard.d.ts.map +1 -0
  47. package/dist/services/claims-first-guard.js +77 -0
  48. package/dist/services/claims-first-guard.js.map +1 -0
  49. package/dist/services/holder-keys.d.ts +95 -0
  50. package/dist/services/holder-keys.d.ts.map +1 -0
  51. package/dist/services/holder-keys.js +281 -0
  52. package/dist/services/holder-keys.js.map +1 -0
  53. package/dist/services/holder-read-slots.d.ts +42 -0
  54. package/dist/services/holder-read-slots.d.ts.map +1 -0
  55. package/dist/services/holder-read-slots.js +82 -0
  56. package/dist/services/holder-read-slots.js.map +1 -0
  57. package/dist/services/proof-verifier.d.ts +13 -35
  58. package/dist/services/proof-verifier.d.ts.map +1 -1
  59. package/dist/services/proof-verifier.js +16 -74
  60. package/dist/services/proof-verifier.js.map +1 -1
  61. package/dist/services/request-holder.d.ts +78 -0
  62. package/dist/services/request-holder.d.ts.map +1 -0
  63. package/dist/services/request-holder.js +81 -0
  64. package/dist/services/request-holder.js.map +1 -0
  65. package/dist/services/tool-context-builder.d.ts.map +1 -1
  66. package/dist/services/tool-context-builder.js +16 -4
  67. package/dist/services/tool-context-builder.js.map +1 -1
  68. package/dist/services/tool-protection.service.d.ts +7 -0
  69. package/dist/services/tool-protection.service.d.ts.map +1 -1
  70. package/dist/services/tool-protection.service.js +34 -15
  71. package/dist/services/tool-protection.service.js.map +1 -1
  72. package/dist/types/tool-protection.d.ts +94 -0
  73. package/dist/types/tool-protection.d.ts.map +1 -1
  74. package/dist/types/tool-protection.js +113 -1
  75. package/dist/types/tool-protection.js.map +1 -1
  76. package/eslint.config.js +20 -0
  77. package/package.json +8 -2
  78. package/src/__tests__/runtime/amount-limit-enforcement.test.ts +269 -0
  79. package/src/__tests__/runtime/amount-limit-result.test.ts +61 -0
  80. package/src/__tests__/runtime/audit-contracts-compat.test.ts +20 -5
  81. package/src/__tests__/runtime/audit.test.ts +363 -53
  82. package/src/__tests__/runtime/process-tool-call-security.test.ts +97 -13
  83. package/src/__tests__/runtime/provider-selection.test.ts +4 -6
  84. package/src/__tests__/runtime/route-interception.test.ts +215 -214
  85. package/src/__tests__/runtime/tool-protection-enforcement.test.ts +89 -6
  86. package/src/__tests__/services/tool-protection-amount.test.ts +107 -0
  87. package/src/__tests__/services/tool-protection-failsafe.test.ts +71 -4
  88. package/src/__tests__/utils/tool-protection-runtime.ts +3 -0
  89. package/src/auth/__tests__/verify-or-hints-presented.test.ts +155 -0
  90. package/src/auth/handshake.ts +80 -125
  91. package/src/auth/index.ts +1 -0
  92. package/src/auth/resume-token.ts +134 -0
  93. package/src/auth/types.ts +20 -2
  94. package/src/index.ts +40 -1
  95. package/src/proof/__tests__/proof-generator.test.ts +80 -13
  96. package/src/proof/companion.ts +35 -0
  97. package/src/proof/generator.ts +51 -33
  98. package/src/proof/index.ts +3 -0
  99. package/src/runtime/__tests__/ext-apps-consent.test.ts +87 -2
  100. package/src/runtime/audit.ts +170 -65
  101. package/src/runtime/base.ts +95 -31
  102. package/src/runtime/dif-core.ts +16 -0
  103. package/src/services/__tests__/access-control.service.test.ts +44 -0
  104. package/src/services/__tests__/claims-first-guard.test.ts +93 -0
  105. package/src/services/__tests__/holder-fixtures.ts +135 -0
  106. package/src/services/__tests__/holder-keys.test.ts +257 -0
  107. package/src/services/__tests__/holder-read-slots.test.ts +117 -0
  108. package/src/services/__tests__/holder-reads.test.ts +284 -0
  109. package/src/services/__tests__/proof-verifier.test.ts +286 -195
  110. package/src/services/__tests__/request-holder.test.ts +210 -0
  111. package/src/services/__tests__/tool-context-builder-authtype.test.ts +79 -0
  112. package/src/services/__tests__/tool-context-builder.test.ts +4 -7
  113. package/src/services/__tests__/tool-protection-served-revision.test.ts +102 -0
  114. package/src/services/access-control.service.ts +11 -5
  115. package/src/services/claims-first-guard.ts +89 -0
  116. package/src/services/holder-keys.ts +379 -0
  117. package/src/services/holder-read-slots.ts +85 -0
  118. package/src/services/proof-verifier.ts +18 -79
  119. package/src/services/request-holder.ts +146 -0
  120. package/src/services/tool-context-builder.ts +19 -4
  121. package/src/services/tool-protection.service.ts +62 -19
  122. package/src/types/tool-protection.ts +161 -0
@@ -6,10 +6,16 @@ import type {
6
6
  AuthorizationEvidence,
7
7
  PartyRef,
8
8
  } from "@kya-os/mcp/audit" with { "resolution-mode": "import" };
9
- // Type-only on purpose: package.json accepts contracts releases that predate
10
- // the denial code list, so the known codes come from this package instead.
11
- import type { DelegationDenialCode } from "@kya-os/contracts/config";
9
+ // The denial code is type-only on purpose: package.json accepts contracts
10
+ // releases that predate the denial code list, so the known codes come from
11
+ // this package instead. The refusal marker reader shipped in contracts 1.13.0,
12
+ // so every contracts release package.json accepts has it.
13
+ import {
14
+ readToolRefusal,
15
+ type DelegationDenialCode,
16
+ } from "@kya-os/contracts/config";
12
17
  import { DEFAULT_DENIAL_MESSAGES } from "./delegation-denial.js";
18
+ import { AmountLimitError } from "../types/tool-protection.js";
13
19
 
14
20
  const encoder = new TextEncoder();
15
21
  const MAX_REFERENCE_LENGTH = 256;
@@ -37,7 +43,7 @@ export interface RuntimeAuditAssurance {
37
43
  * remains AAP-0. Legacy diagnostic logging is deliberately not consulted.
38
44
  */
39
45
  export function resolveRuntimeAuditAssurance(
40
- config: RuntimeAuditConfig | undefined,
46
+ config: RuntimeAuditConfig | undefined
41
47
  ): RuntimeAuditAssurance {
42
48
  if (config === undefined) return { enabled: false, profile: "AAP-0" };
43
49
  const capabilities = config.trail.capabilities;
@@ -73,7 +79,13 @@ export interface RuntimeConsentAuditInput {
73
79
  }
74
80
 
75
81
  export interface RuntimeDelegationAuditInput {
76
- phase: "issued" | "verified" | "rejected" | "revoked" | "cascade_revoked" | "outbound_attached";
82
+ phase:
83
+ | "issued"
84
+ | "verified"
85
+ | "rejected"
86
+ | "revoked"
87
+ | "cascade_revoked"
88
+ | "outbound_attached";
77
89
  outcome: "succeeded" | "failed" | "denied";
78
90
  sessionId: string;
79
91
  delegationRef: string;
@@ -98,9 +110,9 @@ export interface RuntimeAuditCallContext {
98
110
  }
99
111
 
100
112
  export interface RuntimeAuditContextFactory {
101
- create(input: RuntimeAuditToolInput):
102
- | RuntimeAuditCallContext
103
- | Promise<RuntimeAuditCallContext>;
113
+ create(
114
+ input: RuntimeAuditToolInput
115
+ ): RuntimeAuditCallContext | Promise<RuntimeAuditCallContext>;
104
116
  }
105
117
 
106
118
  /**
@@ -128,7 +140,10 @@ export interface HmacRuntimeAuditContextOptions {
128
140
  randomUUID?: () => string;
129
141
  }
130
142
 
131
- function optionalString(record: Record<string, unknown> | undefined, key: string): string | undefined {
143
+ function optionalString(
144
+ record: Record<string, unknown> | undefined,
145
+ key: string
146
+ ): string | undefined {
132
147
  const value = record?.[key];
133
148
  if (typeof value !== "string") return undefined;
134
149
  const trimmed = value.trim();
@@ -158,32 +173,38 @@ function bytesToHex(bytes: Uint8Array): string {
158
173
  * before emission, so transport/session capabilities never enter the journal.
159
174
  */
160
175
  export function createHmacRuntimeAuditContextFactory(
161
- options: HmacRuntimeAuditContextOptions,
176
+ options: HmacRuntimeAuditContextOptions
162
177
  ): RuntimeAuditContextFactory {
163
178
  if (options.keyId.trim().length === 0) {
164
179
  throw new TypeError("Audit reference keyId must be non-empty");
165
180
  }
166
- const secret = typeof options.secret === "string"
167
- ? encoder.encode(options.secret)
168
- : new Uint8Array(options.secret);
181
+ const secret =
182
+ typeof options.secret === "string"
183
+ ? encoder.encode(options.secret)
184
+ : new Uint8Array(options.secret);
169
185
  if (secret.byteLength < 32) {
170
- throw new TypeError("Audit reference secret must contain at least 32 bytes");
186
+ throw new TypeError(
187
+ "Audit reference secret must contain at least 32 bytes"
188
+ );
171
189
  }
172
190
  const randomUUID = options.randomUUID ?? (() => crypto.randomUUID());
173
191
  let keyPromise: ReturnType<typeof crypto.subtle.importKey> | undefined;
174
192
 
175
- const commitment = async (domain: string, value: string): Promise<`sha256:${string}`> => {
193
+ const commitment = async (
194
+ domain: string,
195
+ value: string
196
+ ): Promise<`sha256:${string}`> => {
176
197
  keyPromise ??= crypto.subtle.importKey(
177
198
  "raw",
178
199
  secret,
179
200
  { name: "HMAC", hash: "SHA-256" },
180
201
  false,
181
- ["sign"],
202
+ ["sign"]
182
203
  );
183
204
  const signature = await crypto.subtle.sign(
184
205
  "HMAC",
185
206
  await keyPromise,
186
- encoder.encode(`${domain}\0${value}`),
207
+ encoder.encode(`${domain}\0${value}`)
187
208
  );
188
209
  return `sha256:${bytesToHex(new Uint8Array(signature))}`;
189
210
  };
@@ -194,25 +215,38 @@ export function createHmacRuntimeAuditContextFactory(
194
215
  return {
195
216
  async create(input): Promise<RuntimeAuditCallContext> {
196
217
  const session = input.session;
197
- const rawInvocation = optionalString(session, "auditInvocationId") ?? randomUUID();
198
- const rawCorrelation = optionalString(session, "auditCorrelationId") ?? rawInvocation;
218
+ const rawInvocation =
219
+ optionalString(session, "auditInvocationId") ?? randomUUID();
220
+ const rawCorrelation =
221
+ optionalString(session, "auditCorrelationId") ?? rawInvocation;
199
222
  const rawCausation = optionalString(session, "auditCausationId");
200
223
  const sessionId = optionalString(session, "id");
201
- const actorDid = optionalString(session, "clientDid") ?? optionalString(session, "userDid");
202
-
203
- const [invocationId, correlationId, causationId, sessionCommitment] = await Promise.all([
204
- opaqueId("invocation", rawInvocation),
205
- opaqueId("correlation", rawCorrelation),
206
- rawCausation === undefined ? undefined : opaqueId("causation", rawCausation),
207
- sessionId === undefined
208
- ? undefined
209
- : commitment("org.kya-os.audit.session-ref.v1", sessionId),
210
- ]);
224
+ // A holder proved by request admission outranks clientDid, which the
225
+ // caller asserts, and userDid. agentDid is never read: it can fall back
226
+ // to the server's own DID and would attribute the call to the server.
227
+ const actorDid =
228
+ optionalString(session, "verifiedInvokerDid") ??
229
+ optionalString(session, "clientDid") ??
230
+ optionalString(session, "userDid");
231
+
232
+ const [invocationId, correlationId, causationId, sessionCommitment] =
233
+ await Promise.all([
234
+ opaqueId("invocation", rawInvocation),
235
+ opaqueId("correlation", rawCorrelation),
236
+ rawCausation === undefined
237
+ ? undefined
238
+ : opaqueId("causation", rawCausation),
239
+ sessionId === undefined
240
+ ? undefined
241
+ : commitment("org.kya-os.audit.session-ref.v1", sessionId),
242
+ ]);
211
243
 
212
244
  return {
213
245
  invocationId: bounded(invocationId),
214
246
  correlationId: bounded(correlationId),
215
- ...(causationId === undefined ? {} : { causationId: bounded(causationId) }),
247
+ ...(causationId === undefined
248
+ ? {}
249
+ : { causationId: bounded(causationId) }),
216
250
  ...(sessionCommitment === undefined
217
251
  ? {}
218
252
  : {
@@ -232,7 +266,11 @@ export function createHmacRuntimeAuditContextFactory(
232
266
  };
233
267
  }
234
268
 
235
- export type RuntimeToolTerminalPhase = "completed" | "failed" | "denied" | "challenged";
269
+ export type RuntimeToolTerminalPhase =
270
+ | "completed"
271
+ | "failed"
272
+ | "denied"
273
+ | "challenged";
236
274
 
237
275
  export interface RuntimeToolTerminal {
238
276
  phase: RuntimeToolTerminalPhase;
@@ -247,7 +285,7 @@ export class RuntimeToolAuditInvocation {
247
285
  constructor(
248
286
  private readonly config: RuntimeAuditConfig,
249
287
  private readonly toolName: string,
250
- readonly context: RuntimeAuditCallContext,
288
+ readonly context: RuntimeAuditCallContext
251
289
  ) {}
252
290
 
253
291
  async started(): Promise<AuditEmitResult> {
@@ -257,7 +295,9 @@ export class RuntimeToolAuditInvocation {
257
295
  ...this.eventContext(),
258
296
  action: {
259
297
  category: "tool.call",
260
- ...(this.config.includeToolNames ? { name: bounded(this.toolName) } : {}),
298
+ ...(this.config.includeToolNames
299
+ ? { name: bounded(this.toolName) }
300
+ : {}),
261
301
  },
262
302
  outcome: "unknown",
263
303
  evidence: [],
@@ -274,7 +314,9 @@ export class RuntimeToolAuditInvocation {
274
314
 
275
315
  async terminal(value: RuntimeToolTerminal): Promise<AuditEmitResult> {
276
316
  if (this.terminalRecorded) {
277
- throw new Error(`Terminal audit event already recorded for ${this.context.invocationId}`);
317
+ throw new Error(
318
+ `Terminal audit event already recorded for ${this.context.invocationId}`
319
+ );
278
320
  }
279
321
  this.terminalRecorded = true;
280
322
  return this.config.trail.record({
@@ -283,7 +325,9 @@ export class RuntimeToolAuditInvocation {
283
325
  ...this.eventContext(),
284
326
  action: {
285
327
  category: "tool.call",
286
- ...(this.config.includeToolNames ? { name: bounded(this.toolName) } : {}),
328
+ ...(this.config.includeToolNames
329
+ ? { name: bounded(this.toolName) }
330
+ : {}),
287
331
  },
288
332
  outcome: value.outcome,
289
333
  ...(value.reasonCode === undefined
@@ -300,21 +344,33 @@ export class RuntimeToolAuditInvocation {
300
344
  }
301
345
 
302
346
  results(terminal?: AuditEmitResult): readonly AuditEmitResult[] {
303
- if (this.startedResult === undefined) return terminal === undefined ? [] : [terminal];
304
- return terminal === undefined ? [this.startedResult] : [this.startedResult, terminal];
347
+ if (this.startedResult === undefined)
348
+ return terminal === undefined ? [] : [terminal];
349
+ return terminal === undefined
350
+ ? [this.startedResult]
351
+ : [this.startedResult, terminal];
305
352
  }
306
353
 
307
354
  private eventContext(): Pick<
308
355
  AuditTrailEventInput,
309
- "correlationId" | "causationId" | "session" | "actor" | "responsibleParty" | "authorization"
356
+ | "correlationId"
357
+ | "causationId"
358
+ | "session"
359
+ | "actor"
360
+ | "responsibleParty"
361
+ | "authorization"
310
362
  > {
311
363
  return {
312
364
  correlationId: bounded(this.context.correlationId),
313
365
  ...(this.context.causationId === undefined
314
366
  ? {}
315
367
  : { causationId: bounded(this.context.causationId) }),
316
- ...(this.context.session === undefined ? {} : { session: this.context.session }),
317
- ...(this.context.actor === undefined ? {} : { actor: this.context.actor }),
368
+ ...(this.context.session === undefined
369
+ ? {}
370
+ : { session: this.context.session }),
371
+ ...(this.context.actor === undefined
372
+ ? {}
373
+ : { actor: this.context.actor }),
318
374
  ...(this.context.responsibleParty === undefined
319
375
  ? {}
320
376
  : { responsibleParty: this.context.responsibleParty }),
@@ -327,7 +383,7 @@ export class RuntimeToolAuditInvocation {
327
383
 
328
384
  export async function beginRuntimeToolAudit(
329
385
  config: RuntimeAuditConfig,
330
- input: RuntimeAuditToolInput,
386
+ input: RuntimeAuditToolInput
331
387
  ): Promise<RuntimeToolAuditInvocation> {
332
388
  if (config.sourceId.trim().length === 0) {
333
389
  throw new TypeError("Audit sourceId must be non-empty");
@@ -335,13 +391,13 @@ export async function beginRuntimeToolAudit(
335
391
  const trailSourceId = config.trail.configuration?.sourceId;
336
392
  if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
337
393
  throw new TypeError(
338
- `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
394
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`
339
395
  );
340
396
  }
341
397
  const invocation = new RuntimeToolAuditInvocation(
342
398
  config,
343
399
  input.toolName,
344
- await config.context.create(input),
400
+ await config.context.create(input)
345
401
  );
346
402
  await invocation.started();
347
403
  return invocation;
@@ -355,7 +411,7 @@ export async function beginRuntimeToolAudit(
355
411
  */
356
412
  export async function recordRuntimeConsentAudit(
357
413
  config: RuntimeAuditConfig,
358
- input: RuntimeConsentAuditInput,
414
+ input: RuntimeConsentAuditInput
359
415
  ): Promise<AuditEmitResult> {
360
416
  if (config.sourceId.trim().length === 0) {
361
417
  throw new TypeError("Audit sourceId must be non-empty");
@@ -363,7 +419,7 @@ export async function recordRuntimeConsentAudit(
363
419
  const trailSourceId = config.trail.configuration?.sourceId;
364
420
  if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
365
421
  throw new TypeError(
366
- `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
422
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`
367
423
  );
368
424
  }
369
425
 
@@ -423,7 +479,7 @@ export async function recordRuntimeConsentAudit(
423
479
  /** Record a privacy-minimal delegation lifecycle event on the canonical trail. */
424
480
  export async function recordRuntimeDelegationAudit(
425
481
  config: RuntimeAuditConfig,
426
- input: RuntimeDelegationAuditInput,
482
+ input: RuntimeDelegationAuditInput
427
483
  ): Promise<AuditEmitResult> {
428
484
  if (config.sourceId.trim().length === 0) {
429
485
  throw new TypeError("Audit sourceId must be non-empty");
@@ -431,7 +487,7 @@ export async function recordRuntimeDelegationAudit(
431
487
  const trailSourceId = config.trail.configuration?.sourceId;
432
488
  if (trailSourceId !== undefined && trailSourceId !== config.sourceId) {
433
489
  throw new TypeError(
434
- `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`,
490
+ `Audit sourceId mismatch: runtime expects ${config.sourceId} but trail uses ${trailSourceId}`
435
491
  );
436
492
  }
437
493
  const context = await config.context.create({
@@ -498,7 +554,9 @@ interface RuntimeAuditEventReference {
498
554
  };
499
555
  }
500
556
 
501
- function auditEventReference(result: AuditEmitResult): RuntimeAuditEventReference {
557
+ function auditEventReference(
558
+ result: AuditEmitResult
559
+ ): RuntimeAuditEventReference {
502
560
  return {
503
561
  eventId: result.event.eventId,
504
562
  eventType: result.event.eventType,
@@ -525,11 +583,13 @@ export function attachRuntimeAuditMetadata<T>(
525
583
  sourceId: string,
526
584
  invocationId: string,
527
585
  auditResults: readonly AuditEmitResult[],
528
- requiredDeliveryError = false,
586
+ requiredDeliveryError = false
529
587
  ): T {
530
588
  if (!isRecord(result) || Array.isArray(result)) {
531
589
  if (requiredDeliveryError) {
532
- throw new Error("Required terminal audit delivery failed after tool execution");
590
+ throw new Error(
591
+ "Required terminal audit delivery failed after tool execution"
592
+ );
533
593
  }
534
594
  return result;
535
595
  }
@@ -540,16 +600,22 @@ export function attachRuntimeAuditMetadata<T>(
540
600
  const existingAudit = isRecord(existingMeta[RUNTIME_AUDIT_META_KEY])
541
601
  ? existingMeta[RUNTIME_AUDIT_META_KEY]
542
602
  : {};
543
- const degraded = requiredDeliveryError || auditResults.some((item) => item.status === "failed");
603
+ const degraded =
604
+ requiredDeliveryError ||
605
+ auditResults.some((item) => item.status === "failed");
544
606
  mutableResult["_meta"] = {
545
607
  ...existingMeta,
546
608
  [RUNTIME_AUDIT_META_KEY]: {
547
609
  ...existingAudit,
548
- status: degraded ? "degraded" : auditResults.at(-1)?.status ?? "unknown",
610
+ status: degraded
611
+ ? "degraded"
612
+ : (auditResults.at(-1)?.status ?? "unknown"),
549
613
  sourceId,
550
614
  invocationId,
551
615
  events: auditResults.map(auditEventReference),
552
- ...(requiredDeliveryError ? { reason: "AUDIT_TERMINAL_DELIVERY_FAILED" } : {}),
616
+ ...(requiredDeliveryError
617
+ ? { reason: "AUDIT_TERMINAL_DELIVERY_FAILED" }
618
+ : {}),
553
619
  },
554
620
  };
555
621
  if (requiredDeliveryError) mutableResult["isError"] = true;
@@ -574,23 +640,41 @@ export function terminalForToolResult(result: unknown): RuntimeToolTerminal {
574
640
  reasonCode: "AUTHORIZATION_REQUIRED",
575
641
  };
576
642
  }
577
- if (result.isError !== true) return { phase: "completed", outcome: "succeeded" };
643
+ // A tool's policy refusal (over a spend cap, a product out of scope) is a
644
+ // denial with the tool's own code, not a tool error. Read before isError,
645
+ // as Checkpoint and the activity telemetry do, so all three agree.
646
+ const refusal = readToolRefusal(result);
647
+ if (refusal) {
648
+ return { phase: "denied", outcome: "denied", reasonCode: refusal.code };
649
+ }
650
+ if (result.isError !== true)
651
+ return { phase: "completed", outcome: "succeeded" };
578
652
  const metadata = isRecord(result._meta) ? result._meta : undefined;
579
- const errorType = typeof metadata?.errorType === "string" ? metadata.errorType : undefined;
580
- if (errorType === "authorization_required" || errorType === "oauth_required" ||
581
- isRecord(metadata?.needs_authorization)) {
653
+ const errorType =
654
+ typeof metadata?.errorType === "string" ? metadata.errorType : undefined;
655
+ if (
656
+ errorType === "authorization_required" ||
657
+ errorType === "oauth_required" ||
658
+ isRecord(metadata?.needs_authorization)
659
+ ) {
582
660
  return {
583
661
  phase: "challenged",
584
662
  outcome: "challenged",
585
663
  reasonCode: "AUTHORIZATION_REQUIRED",
586
664
  };
587
665
  }
588
- return { phase: "failed", outcome: "failed", reasonCode: "HANDLER_ERROR_RESULT" };
666
+ return {
667
+ phase: "failed",
668
+ outcome: "failed",
669
+ reasonCode: "HANDLER_ERROR_RESULT",
670
+ };
589
671
  }
590
672
 
591
673
  // Read by shape, like the name checks below, because the error may come from
592
674
  // another copy of this package. Only a known code counts as a denial.
593
- function delegationDenialCode(error: unknown): DelegationDenialCode | undefined {
675
+ function delegationDenialCode(
676
+ error: unknown
677
+ ): DelegationDenialCode | undefined {
594
678
  if (!isRecord(error) || !isRecord(error.denial)) return undefined;
595
679
  const code = error.denial.code;
596
680
  // Own keys only, so an inherited name such as "constructor" never matches.
@@ -600,20 +684,41 @@ function delegationDenialCode(error: unknown): DelegationDenialCode | undefined
600
684
  : undefined;
601
685
  }
602
686
 
687
+ const STATEFUL_DENIAL_CODES: ReadonlySet<DelegationDenialCode> = new Set([
688
+ "budget_exceeded",
689
+ "policy_denied",
690
+ ]);
691
+
603
692
  export function terminalForToolError(error: unknown): RuntimeToolTerminal {
693
+ if (error instanceof AmountLimitError) {
694
+ return {
695
+ phase: "denied",
696
+ outcome: "denied",
697
+ reasonCode: error.code.toUpperCase(),
698
+ };
699
+ }
604
700
  const name = error instanceof Error ? error.name : "UnknownError";
605
701
  const denialCode =
606
- name === "DelegationRequiredError" ? delegationDenialCode(error) : undefined;
702
+ name === "DelegationRequiredError"
703
+ ? delegationDenialCode(error)
704
+ : undefined;
607
705
  if (denialCode !== undefined) {
608
- // The verifier refused a presented grant: a denial, not a request for consent.
706
+ // A stateful policy refusal (a spent budget, an origin or IP rule) is a
707
+ // denial: a new grant would not change the answer. Any other verifier
708
+ // refusal of a presented grant (revoked, expired, another holder, too
709
+ // little scope) is a challenge: a new grant could fix it.
710
+ const stateful = STATEFUL_DENIAL_CODES.has(denialCode);
609
711
  return {
610
- phase: "denied",
611
- outcome: "denied",
712
+ phase: stateful ? "denied" : "challenged",
713
+ outcome: stateful ? "denied" : "challenged",
612
714
  reasonCode: denialCode.toUpperCase(),
613
715
  };
614
716
  }
615
- if (name === "DelegationRequiredError" || name === "OAuthRequiredError" ||
616
- name === "AuthRequiredError") {
717
+ if (
718
+ name === "DelegationRequiredError" ||
719
+ name === "OAuthRequiredError" ||
720
+ name === "AuthRequiredError"
721
+ ) {
617
722
  return {
618
723
  phase: "challenged",
619
724
  outcome: "challenged",