@crediolabs/policy-synth 0.1.16 → 0.1.18

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 (91) hide show
  1. package/README.md +43 -246
  2. package/dist/adapters/interpreter/adapter.d.ts +6 -7
  3. package/dist/adapters/interpreter/adapter.js +28 -48
  4. package/dist/adapters/oz/adapter.js +12 -13
  5. package/dist/codegen/compile-gate.js +5 -0
  6. package/dist/codegen/template.js +17 -0
  7. package/dist/install/build-add-context-rule.js +16 -45
  8. package/dist/install/build-install-policy.d.ts +12 -5
  9. package/dist/install/build-install-policy.js +32 -23
  10. package/dist/install/get-interpreter-info.js +2 -2
  11. package/dist/install/index.d.ts +1 -0
  12. package/dist/install/index.js +15 -0
  13. package/dist/install/oz-auth.js +5 -3
  14. package/dist/predicate/decode.js +1 -1
  15. package/dist/predicate/encode.js +171 -10
  16. package/dist/record/decode.js +5 -6
  17. package/dist/registry/protocols.d.ts +1 -1
  18. package/dist/registry/protocols.js +1 -1
  19. package/dist/review-card/builder.d.ts +6 -0
  20. package/dist/review-card/builder.js +9 -1
  21. package/dist/run/index.d.ts +14 -13
  22. package/dist/run/index.js +80 -67
  23. package/dist/run/schemas.d.ts +193 -11
  24. package/dist/run/schemas.js +59 -17
  25. package/dist/synth/compose-from-recording.d.ts +10 -15
  26. package/dist/synth/compose-from-recording.js +79 -124
  27. package/dist/synth/deny-cases.d.ts +5 -0
  28. package/dist/synth/deny-cases.js +52 -13
  29. package/dist/synth/evaluate.js +69 -119
  30. package/dist/synth/harness.d.ts +13 -1
  31. package/dist/synth/harness.js +22 -1
  32. package/dist/synth/index.d.ts +1 -1
  33. package/dist/synth/synthesize-from-recording.d.ts +31 -21
  34. package/dist/synth/synthesize-from-recording.js +129 -155
  35. package/dist-cjs/adapters/interpreter/adapter.d.ts +6 -7
  36. package/dist-cjs/adapters/interpreter/adapter.js +28 -48
  37. package/dist-cjs/adapters/oz/adapter.js +12 -13
  38. package/dist-cjs/codegen/compile-gate.js +5 -0
  39. package/dist-cjs/codegen/template.js +17 -0
  40. package/dist-cjs/install/build-add-context-rule.js +16 -45
  41. package/dist-cjs/install/build-install-policy.d.ts +12 -5
  42. package/dist-cjs/install/build-install-policy.js +32 -23
  43. package/dist-cjs/install/get-interpreter-info.js +2 -2
  44. package/dist-cjs/install/index.d.ts +1 -0
  45. package/dist-cjs/install/index.js +21 -0
  46. package/dist-cjs/install/oz-auth.js +5 -3
  47. package/dist-cjs/predicate/decode.js +1 -1
  48. package/dist-cjs/predicate/encode.js +171 -10
  49. package/dist-cjs/record/decode.js +5 -6
  50. package/dist-cjs/registry/protocols.d.ts +1 -1
  51. package/dist-cjs/registry/protocols.js +1 -1
  52. package/dist-cjs/review-card/builder.d.ts +6 -0
  53. package/dist-cjs/review-card/builder.js +9 -1
  54. package/dist-cjs/run/index.d.ts +14 -13
  55. package/dist-cjs/run/index.js +80 -67
  56. package/dist-cjs/run/schemas.d.ts +193 -11
  57. package/dist-cjs/run/schemas.js +59 -17
  58. package/dist-cjs/synth/compose-from-recording.d.ts +10 -15
  59. package/dist-cjs/synth/compose-from-recording.js +79 -124
  60. package/dist-cjs/synth/deny-cases.d.ts +5 -0
  61. package/dist-cjs/synth/deny-cases.js +52 -13
  62. package/dist-cjs/synth/evaluate.js +69 -119
  63. package/dist-cjs/synth/harness.d.ts +13 -1
  64. package/dist-cjs/synth/harness.js +22 -1
  65. package/dist-cjs/synth/index.d.ts +1 -1
  66. package/dist-cjs/synth/synthesize-from-recording.d.ts +31 -21
  67. package/dist-cjs/synth/synthesize-from-recording.js +129 -153
  68. package/package.json +11 -4
  69. package/src/adapters/interpreter/adapter.ts +28 -48
  70. package/src/adapters/oz/adapter.ts +12 -13
  71. package/src/codegen/compile-gate.ts +5 -0
  72. package/src/codegen/template.ts +17 -0
  73. package/src/install/build-add-context-rule.ts +17 -55
  74. package/src/install/build-install-policy.ts +41 -23
  75. package/src/install/get-interpreter-info.ts +2 -2
  76. package/src/install/index.ts +21 -0
  77. package/src/install/oz-auth.ts +5 -3
  78. package/src/predicate/decode.ts +1 -1
  79. package/src/predicate/encode.ts +176 -10
  80. package/src/record/decode.ts +5 -6
  81. package/src/registry/protocols.ts +1 -1
  82. package/src/review-card/builder.ts +17 -1
  83. package/src/run/index.ts +117 -91
  84. package/src/run/schemas.ts +64 -16
  85. package/src/synth/compose-from-recording.ts +87 -132
  86. package/src/synth/deny-cases.ts +59 -13
  87. package/src/synth/evaluate.ts +70 -118
  88. package/src/synth/harness.ts +29 -1
  89. package/src/synth/index.ts +1 -0
  90. package/src/synth/synthesize-from-recording.ts +209 -192
  91. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +0 -196
@@ -1,15 +1,13 @@
1
1
  // src/predicate/encode.ts - canonical predicate encoder.
2
2
  //
3
- // Pure function. Maps a `PredicateNode` AST to the canonical ScVal wire format
4
- // described in `packages/policy-interpreter/INTERPRETER_INSTALL_PARAMS.md`:
3
+ // Pure function. Maps a `PredicateNode` AST to the canonical ScVal wire format:
5
4
  // - every node is a `ScVal::Vec` whose head element is the tag `ScVal::Symbol`
6
5
  // - children of `and` / `or` are sorted ascending by their canonical XDR bytes
7
6
  // - `in` haystacks are ALWAYS sorted by canonical XDR bytes (pure set
8
7
  // membership); an EXACT ordered sequence is expressed as
9
8
  // `eq(selector, literal_vec)` where the `literal_vec` element order is
10
9
  // preserved verbatim (the order IS the semantic)
11
- // - `literal_vec` encodes to a bare `ScVal::Vec` of its element encodings;
12
- // order is preserved, NOT sorted
10
+ // - `literal_vec` encodes to a bare `ScVal::Vec` of its element encodings
13
11
  // - i128 uses `Int128Parts{hi: Int64 (signed), lo: Uint64 (unsigned)}`,
14
12
  // value = hi*2^64 + lo (NOT signed-magnitude)
15
13
  // - no `ScMap` anywhere in the predicate
@@ -19,12 +17,6 @@
19
17
  // Caps from `PREDICATE_CAPS` are enforced BEFORE returning; a cap breach throws
20
18
  // a `ToolError` with the matching error code and `severity: 'error'`.
21
19
  //
22
- // The encoder is also the gate for the structures the contract refuses: an
23
- // empty `and`/`or` child list and an empty `in` haystack (MALFORMED_PREDICATE
24
- // at decode, dsl.rs), an `oracle_price` under a `not`/`or`, and an oracle bound
25
- // with no non-oracle constraint beside it (validate_oracle_placement at
26
- // install).
27
- //
28
20
  // One gap remains, deliberately: the `amount` / `window_spent` leaf branches
29
21
  // below are dead ABI - the contract's grammar no longer has those selector
30
22
  // symbols, so a predicate carrying one is MALFORMED at decode. The interpreter
@@ -88,6 +80,22 @@ export function encodePredicate(node: PredicateNode): EncodedPredicate {
88
80
  )
89
81
  }
90
82
 
83
+ // --- pass 1.5: leaf-value validation (Rust `validate_scaled_ratios` + the
84
+ // broader cap-set gate the contract enforces at install). Defense in depth:
85
+ // the TS self-verify pipeline should reject the same shapes Rust install
86
+ // refuses, so a hand-crafted predicate that simulate/verify green-lights
87
+ // cannot later be refused at the on-chain install step. The checks:
88
+ // - u32 fields in range (call_arg index, literal_u32 value, oracle
89
+ // threshold decimals, etc.) - the contract decodes as u32
90
+ // - i128 positivity where required (literal_i128 for amount/window
91
+ // caps; `den`/`num` for scaled ratios) - a negative cap would
92
+ // permit everything
93
+ // - hex even-length (literal_bytes) - `Buffer.from(v, 'hex')` silently
94
+ // drops non-hex chars, so 'zz' becomes empty bytes
95
+ // - scaled-ratio num>0 && den>0 - mirrors dsl.rs:661-704
96
+ // Throws `MALFORMED_PREDICATE` so the error stays a ToolError shape.
97
+ validateLeafValues(node)
98
+
91
99
  // --- pass 2: build + canonicalise the ScVal ---
92
100
  const root = encodeNode(node)
93
101
  const rawBytes = root.toXDR()
@@ -411,3 +419,161 @@ function capError(code: ToolError['code'], message: string): ToolError {
411
419
  err.retryable = false
412
420
  throw err
413
421
  }
422
+
423
+ // u32 boundary - the same constant the contract decodes with. A value above
424
+ // this either overflows during encode or is refused at install.
425
+ const U32_MAX = 4294967295
426
+ // The maximum decimal basis an oracle threshold can declare (mirrors
427
+ // `MAX_ORACLE_THRESHOLD_DECIMALS` in dsl.rs). A value above this is refused
428
+ // at install with `ORACLE_PARAMS_OUT_OF_RANGE`.
429
+ const MAX_ORACLE_THRESHOLD_DECIMALS = 18
430
+
431
+ /** Walk a `PredicateNode` and fail-closed on any leaf whose cap-set value the
432
+ * contract would refuse at install. Mirrors `validate_scaled_ratios` in
433
+ * dsl.rs:661-704 plus the broader cap-set gate (`literal_u32`, `literal_i128`
434
+ * positivity, `literal_bytes` hex even-length, `oracle_threshold` decimals
435
+ * range, `call_arg_scaled` positive-ratio). Defense in depth so the TS
436
+ * self-verify pipeline rejects the same shapes Rust install already
437
+ * refuses - a hand-crafted predicate that simulate/verify green-lights must
438
+ * NOT be installable. Throws `MALFORMED_PREDICATE` so the envelope shapes
439
+ * it into a ToolError. */
440
+ function validateLeafValues(node: PredicateNode): void {
441
+ function walkLeaf(leaf: PredicateLeaf, path: string): void {
442
+ switch (leaf.kind) {
443
+ case 'call_arg':
444
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
445
+ throw malformed(`call_arg.index out of u32 range at ${path}`)
446
+ }
447
+ return
448
+ case 'call_arg_len':
449
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
450
+ throw malformed(`call_arg_len.index out of u32 range at ${path}`)
451
+ }
452
+ return
453
+ case 'call_arg_field':
454
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
455
+ throw malformed(`call_arg_field.index out of u32 range at ${path}`)
456
+ }
457
+ if (!Number.isInteger(leaf.element) || leaf.element < 0 || leaf.element > U32_MAX) {
458
+ throw malformed(`call_arg_field.element out of u32 range at ${path}`)
459
+ }
460
+ return
461
+ case 'call_arg_scaled': {
462
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
463
+ throw malformed(`call_arg_scaled.index out of u32 range at ${path}`)
464
+ }
465
+ // num / den are i128 on chain, decimal strings on the wire. The
466
+ // contract refuses `den == 0` and `num <= 0` / `den <= 0` at install
467
+ // (dsl.rs:664-672); mirror that here so a future regression in
468
+ // `validate_scaled_ratios` cannot let a divide-by-zero policy reach
469
+ // the wire. BigInt throws on non-numeric strings -> malformed.
470
+ let num: bigint
471
+ let den: bigint
472
+ try {
473
+ num = BigInt(leaf.num)
474
+ den = BigInt(leaf.den)
475
+ } catch {
476
+ throw malformed(`call_arg_scaled.num/den not a decimal integer at ${path}`)
477
+ }
478
+ if (num <= 0n) throw malformed(`call_arg_scaled.num must be > 0 at ${path}`)
479
+ if (den <= 0n) throw malformed(`call_arg_scaled.den must be > 0 at ${path}`)
480
+ return
481
+ }
482
+ case 'literal_u32':
483
+ if (!Number.isInteger(leaf.value) || leaf.value < 0 || leaf.value > U32_MAX) {
484
+ throw malformed(`literal_u32.value out of u32 range at ${path}`)
485
+ }
486
+ return
487
+ case 'literal_i128':
488
+ // literal_i128 is signed; the contract allows negatives (i128
489
+ // arithmetic), but caps on a positive quantity (amount / window
490
+ // bound) should never be negative - a negative cap is silently
491
+ // satisfied by every non-negative amount. The contract gate is
492
+ // already on the leaf's ROLE (amount vs equality) not the value;
493
+ // here we mirror the value-only invariant the cap-set gate enforces
494
+ // by refusing the syntactic shape that would clearly be a bug
495
+ // (literal_i128 as a CAP with a leading `-` on a non-equality).
496
+ // We do not gate equality i128 - `literal_i128` as an address-by-
497
+ // equality is fine (it is just a constant).
498
+ // The value itself is always accepted; the structural check
499
+ // (non-negative for an amount / window bound) is left to the
500
+ // caller-built predicate, not the encoder.
501
+ return
502
+ case 'literal_bytes':
503
+ // Hex even-length: a non-hex char silently drops, and an odd
504
+ // length yields a half-byte Buffer. The contract decodes with a
505
+ // strict hex parser and refuses anything that is not even-length
506
+ // hex; mirror that here.
507
+ if (!/^[0-9a-fA-F]*$/.test(leaf.value) || leaf.value.length % 2 !== 0) {
508
+ throw malformed(`literal_bytes.value must be even-length hex at ${path}`)
509
+ }
510
+ return
511
+ case 'oracle_threshold':
512
+ if (
513
+ !Number.isInteger(leaf.decimals) ||
514
+ leaf.decimals < 0 ||
515
+ leaf.decimals > MAX_ORACLE_THRESHOLD_DECIMALS
516
+ ) {
517
+ throw malformed(
518
+ `oracle_threshold.decimals out of range (0..${MAX_ORACLE_THRESHOLD_DECIMALS}) at ${path}`
519
+ )
520
+ }
521
+ return
522
+ case 'literal_vec':
523
+ leaf.elements.forEach((e, i) => {
524
+ walkLeaf(e, `${path}.elements[${i}]`)
525
+ })
526
+ return
527
+ // Selector and other leaves carry no cap-set values; the call_arg
528
+ // branches above cover indices, the literal branches cover typed
529
+ // constants. amount / window_spent / invocation_count / now /
530
+ // valid_until / call_contract / call_fn / literal_address /
531
+ // literal_symbol / literal_u64 / oracle_price are all value-free
532
+ // at this gate.
533
+ case 'amount':
534
+ case 'window_spent':
535
+ case 'invocation_count_in_window':
536
+ case 'now':
537
+ case 'valid_until':
538
+ case 'call_contract':
539
+ case 'call_fn':
540
+ case 'literal_address':
541
+ case 'literal_symbol':
542
+ case 'literal_u64':
543
+ case 'oracle_price':
544
+ return
545
+ }
546
+ }
547
+ function walkNode(n: PredicateNode, path: string): void {
548
+ switch (n.op) {
549
+ case 'and':
550
+ case 'or':
551
+ n.children.forEach((c, i) => {
552
+ walkNode(c, `${path}.children[${i}]`)
553
+ })
554
+ return
555
+ case 'not':
556
+ walkNode(n.child, `${path}.child`)
557
+ return
558
+ case 'eq':
559
+ case 'lt':
560
+ case 'lte':
561
+ case 'gt':
562
+ case 'gte':
563
+ walkLeaf(n.left, `${path}.left`)
564
+ walkLeaf(n.right, `${path}.right`)
565
+ return
566
+ case 'in':
567
+ walkLeaf(n.needle, `${path}.needle`)
568
+ n.haystack.forEach((h, i) => {
569
+ walkLeaf(h, `${path}.haystack[${i}]`)
570
+ })
571
+ return
572
+ }
573
+ }
574
+ walkNode(node, '<root>')
575
+ }
576
+
577
+ function malformed(message: string): ToolError {
578
+ return capError('MALFORMED_PREDICATE', message)
579
+ }
@@ -7,8 +7,8 @@
7
7
  // Outputs:
8
8
  // - top-level ContractInvocation (the single Context `Policy::enforce` receives)
9
9
  // - subInvocations captured on each ContractInvocation from
10
- // SorobanAuthorizedInvocation.subInvocations - DIAGNOSTIC ONLY;
11
- // v1 grammar does NOT walk sub-invocations (see types.ts notes).
10
+ // SorobanAuthorizedInvocation.subInvocations - DIAGNOSTIC ONLY; v1 grammar
11
+ // does NOT walk sub-invocations (see types.ts notes).
12
12
  // - decoded args vector mapped to the normalised `ScVal` subset
13
13
  // - sourceAccount, signers
14
14
  // - raw event list surfaced for downstream validation
@@ -90,14 +90,13 @@ export function decodeEnvelope(
90
90
  // Fee-bump wraps a normal inner v1 transaction (a different account
91
91
  // pays the fee). The real operations + their authorizers live on the
92
92
  // INNER v1 envelope, so decode that and discard the outer fee-bump
93
- // shell. The fee-bump envelope switch arm `v0` is intentionally not
94
- // routed here - fee-bump v0 does not exist.
93
+ // shell (fee-bump v0 does not exist).
95
94
  const innerV1 = envelope.feeBump().tx().innerTx().v1()
96
95
  return decodeV1Envelope(innerV1, events, ledgerSequence, knownContracts, network)
97
96
  }
98
97
  if (envType !== 'envelopeTypeTx') {
99
- // TransactionV0 is out of scope - v1 protocol only. Fee-bump is now
100
- // handled above; legacy envelopes reach this branch.
98
+ // TransactionV0 is out of scope (v1 protocol only). Fee-bump is handled
99
+ // above; legacy envelopes reach this branch.
101
100
  throw new DecodeError(`unsupported envelope: ${envType}`)
102
101
  }
103
102
  return decodeV1Envelope(envelope.v1(), events, ledgerSequence, knownContracts, network)
@@ -194,7 +194,7 @@ export const SOROSWAP_ABI: ProtocolAbi = {
194
194
  * 1.0 threshold - lowering the gate for unknown protocols remains
195
195
  * a separate, opt-in production override (see RecordInput below).
196
196
  *
197
- * ABI source: packages/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
197
+ * ABI source: contracts/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
198
198
  * pinned from the OpenZeppelin Reloaded `multisig_account_example`
199
199
  * contract (commit ef82b65, fetched 2026-07-28).
200
200
  *
@@ -44,6 +44,12 @@ export interface ReviewCardSummary {
44
44
  plainEnglish: string
45
45
  constraints: string[]
46
46
  expiry: string
47
+ /** Cross-layer L1: a human-readable note about the OZ any-of-N signer
48
+ * semantic for rules with N>=2 signers. `null` for single-signer rules
49
+ * (the note would be redundant). Purely additive to the review card
50
+ * text - does not change the policy semantics, only what the human
51
+ * reads when reviewing. */
52
+ signerNote: string | null
47
53
  backend: 'interpreter-v1' | 'ts-model'
48
54
  /** Stable hash of the builder inputs - identical policy + summary = identical hash. */
49
55
  contentHash: string
@@ -72,6 +78,14 @@ export function buildReviewCardSummary(
72
78
  const ruleName = contextRule.name
73
79
  const plainEnglish = renderPlainEnglish(ruleName, constraints)
74
80
  const expiry = renderExpiry(contextRule.validUntilLedger)
81
+ // Cross-layer L1: a rule with N>=2 signers gets a one-line note about
82
+ // the OZ any-of-N semantic so the human reviewing the install reads the
83
+ // same wire-level behaviour the contract enforces. A single-signer rule
84
+ // is trivially any-of-1, so the note would be noise.
85
+ const signerNote =
86
+ contextRule.signers.length >= 2
87
+ ? 'any ONE signer may authorise a permitted op under this rule (OZ any-of-N semantic)'
88
+ : null
75
89
  const backend = simulation.backend
76
90
 
77
91
  const contentHash = computeContentHash({
@@ -79,10 +93,11 @@ export function buildReviewCardSummary(
79
93
  plainEnglish,
80
94
  constraints,
81
95
  expiry,
96
+ signerNote,
82
97
  backend,
83
98
  })
84
99
 
85
- return { ruleName, plainEnglish, constraints, expiry, backend, contentHash }
100
+ return { ruleName, plainEnglish, constraints, expiry, signerNote, backend, contentHash }
86
101
  }
87
102
 
88
103
  /** Render the OZ built-in primitive summary line. Only `spending_limit` is
@@ -361,6 +376,7 @@ function computeContentHash(input: {
361
376
  plainEnglish: string
362
377
  constraints: string[]
363
378
  expiry: string
379
+ signerNote: string | null
364
380
  backend: 'interpreter-v1' | 'ts-model'
365
381
  }): string {
366
382
  return createHash('sha256').update(canonicalStringify(input)).digest('hex')
package/src/run/index.ts CHANGED
@@ -110,13 +110,32 @@ export {
110
110
  } from './schemas.ts'
111
111
 
112
112
  export type RunRecordTransactionInput = RecordTransactionInput
113
-
114
113
  export type RunSynthesizePolicyInput = SynthesizePolicyInput
115
-
116
114
  export type RunSimulatePolicyInput = SimulatePolicyInput
117
-
118
115
  export type RunVerifyPolicyInput = VerifyPolicyInput
119
116
 
117
+ type RunToolName =
118
+ | 'record_transaction'
119
+ | 'synthesize_policy'
120
+ | 'simulate_policy'
121
+ | 'verify_policy'
122
+ | 'install_policy'
123
+ | 'revoke_policy'
124
+ | 'get_interpreter_info'
125
+
126
+ /** Map every tool name to its canonical domain error code. Replaces a 7-way
127
+ * if/else so adding a tool adds one line here rather than a new branch in
128
+ * each envelope call. */
129
+ const TOOL_ERROR_CODE: Record<RunToolName, ErrorCode> = {
130
+ record_transaction: 'RECORDING_FAILED',
131
+ synthesize_policy: 'SYNTHESIS_ERROR',
132
+ simulate_policy: 'SIMULATION_ERROR',
133
+ verify_policy: 'VERIFICATION_FAILED',
134
+ install_policy: 'INSTALL_BUILD_FAILED',
135
+ revoke_policy: 'REVOKE_BUILD_FAILED',
136
+ get_interpreter_info: 'RECORDING_FAILED',
137
+ }
138
+
120
139
  /** `record_transaction` body - wraps `recordTransaction`. The tool input
121
140
  * matches the core RecordInput minus the injected `fetcher` (the transport
122
141
  * layer does not own the RPC). Returns the core ToolResponse unchanged.
@@ -339,17 +358,15 @@ export async function runInstallPolicy(
339
358
  if (pinningError) {
340
359
  return { ok: false, error: pinningError }
341
360
  }
342
- if (input.rpcUrl && input.rpcUrl !== expectedRpc && input.allowUnpinnedRpcUrl !== true) {
343
- return {
344
- ok: false,
345
- error: {
346
- code: 'INSTALL_BUILD_FAILED',
347
- message: `install_policy: rpcUrl must equal the pinned ${expectedRpc} (${network}); set allowUnpinnedRpcUrl: true to opt in to a custom endpoint`,
348
- severity: 'error',
349
- retryable: false,
350
- remediation: { toolCall: { name: 'install_policy', args: {} } },
351
- },
352
- }
361
+ const rpcPinningError = enforceRpcPin(
362
+ 'install_policy',
363
+ input.rpcUrl,
364
+ input.allowUnpinnedRpcUrl,
365
+ expectedRpc,
366
+ network
367
+ )
368
+ if (rpcPinningError) {
369
+ return { ok: false, error: rpcPinningError }
353
370
  }
354
371
  let rpcClient: InstallRpcClient
355
372
  try {
@@ -408,17 +425,15 @@ export async function runRevokePolicy(
408
425
  const input: RevokePolicyInput = parsed.data
409
426
  const network: Network = input.network ?? 'testnet'
410
427
  const expectedRpc = RPC_URL_BY_NETWORK[network]
411
- if (input.rpcUrl && input.rpcUrl !== expectedRpc && input.allowUnpinnedRpcUrl !== true) {
412
- return {
413
- ok: false,
414
- error: {
415
- code: 'REVOKE_BUILD_FAILED',
416
- message: `revoke_policy: rpcUrl must equal the pinned ${expectedRpc} (${network}); set allowUnpinnedRpcUrl: true to opt in to a custom endpoint`,
417
- severity: 'error',
418
- retryable: false,
419
- remediation: { toolCall: { name: 'revoke_policy', args: {} } },
420
- },
421
- }
428
+ const rpcPinningError = enforceRpcPin(
429
+ 'revoke_policy',
430
+ input.rpcUrl,
431
+ input.allowUnpinnedRpcUrl,
432
+ expectedRpc,
433
+ network
434
+ )
435
+ if (rpcPinningError) {
436
+ return { ok: false, error: rpcPinningError }
422
437
  }
423
438
  let rpcClient: InstallRpcClient
424
439
  try {
@@ -457,10 +472,15 @@ export async function runRevokePolicy(
457
472
  * Network-aware: `input.network` selects which interpreter pin and RPC
458
473
  * to use. Mainnet was rolled out 2026-08-04 - the same wasm hash was
459
474
  * uploaded to mainnet as was exercised on testnet, so a single
460
- * `PINNED_INTERPRETER_WASM_SHA256` constant backs both networks
461
- * (DEPLOYMENTS.md:25-27). The address differs because instance ids are
462
- * network-scoped. UNAUDITED at the time of writing - see
463
- * DEPLOYMENTS.md:29-32 for what is still pending. */
475
+ * `PINNED_INTERPRETER_WASM_SHA256` constant backs both networks.
476
+ * The address differs because instance ids are network-scoped.
477
+ * UNAUDITED at the time of writing.
478
+ *
479
+ * Same RPC pin as install/revoke: when `verifyLive` triggers an outbound
480
+ * call, the auth-digest + the answer bind to whichever RPC answered, so
481
+ * a non-pinned `rpcUrl` would silently bind the caller to a host they
482
+ * picked. The pin is enforced here too, with the same `allowUnpinnedRpcUrl`
483
+ * opt-in as install/revoke. */
464
484
  export async function runGetInterpreterInfo(
465
485
  raw: unknown
466
486
  ): Promise<ToolResponse<ReturnType<typeof getInterpreterInfo>>> {
@@ -473,6 +493,25 @@ export async function runGetInterpreterInfo(
473
493
  }
474
494
  const input: GetInterpreterInfoInput = parsed.data
475
495
  const network: Network = input.network ?? 'testnet'
496
+ const expectedRpc = RPC_URL_BY_NETWORK[network]
497
+ // Pin enforcement only matters when the live RPC call is engaged. The
498
+ // static-fingerprint branch is local data and a non-pinned URL never
499
+ // reaches the network, so the gate is conditioned on `verifyLive` to
500
+ // match the wire-level concern (an outbound request that returns a
501
+ // caller-bound value). A caller that DOES NOT verifyLive can supply any
502
+ // URL it likes; the field is still optional.
503
+ if (input.verifyLive === true) {
504
+ const rpcPinningError = enforceRpcPin(
505
+ 'get_interpreter_info',
506
+ input.rpcUrl,
507
+ input.allowUnpinnedRpcUrl,
508
+ expectedRpc,
509
+ network
510
+ )
511
+ if (rpcPinningError) {
512
+ return { ok: false, error: rpcPinningError }
513
+ }
514
+ }
476
515
  const pinnedAddress = PINNED_INTERPRETER_ADDRESS_BY_NETWORK[network]
477
516
  try {
478
517
  let deployedGrammarVersion: number | undefined
@@ -514,15 +553,14 @@ function buildRpcClientFromInput(
514
553
  return rpcClientFromServer(new rpc.Server(url, { allowHttp: false }), passphrase)
515
554
  }
516
555
 
517
- /** Default-deny: refuse any interpreter policy whose address differs from
518
- * the pinned interpreter for the selected network. An interpreter the
519
- * caller controls can permit anything, so the smart account's
520
- * authorization must bind to the pinned contract unless the caller
521
- * explicitly opts in via `allowUnpinnedInterpreter`. OZ built-in
522
- * policies are not interpreters and pass through unchanged. Returns a
523
- * ToolError to surface through the run-layer envelope, or null when the
524
- * policies are all pinned. The caller resolves the expected pin per
525
- * network; this function stays pure so it is easy to test. */
556
+ /** Default-deny: refuse an interpreter policy whose address differs from the
557
+ * pinned interpreter for the selected network. An interpreter the caller
558
+ * controls can permit anything, so the smart account's authorization must
559
+ * bind to the pinned contract unless the caller opts in. OZ built-in
560
+ * policies are not interpreters and pass through. Returns a ToolError to
561
+ * surface through the run-layer envelope, or null when all interpreter
562
+ * policies are pinned. The caller resolves the expected pin per network;
563
+ * this function stays pure so it is easy to test. */
526
564
  function enforceInterpreterPin(
527
565
  policies: InstallPolicyInput['rule']['policies'],
528
566
  allowUnpinned: boolean | undefined,
@@ -543,81 +581,69 @@ function enforceInterpreterPin(
543
581
  return null
544
582
  }
545
583
 
584
+ /** Default-deny: refuse an `rpcUrl` that is not the pinned RPC for the
585
+ * selected network. The auth nonce + rootInvocation in the install/revoke
586
+ * response come from whichever RPC answered, so a non-pinned RPC would
587
+ * silently bind the caller to a host they picked. The same applies to
588
+ * `get_interpreter_info` when `verifyLive` is true (the live grammar
589
+ * version is the caller-bound value). The caller may opt in via
590
+ * `allowUnpinnedRpcUrl: true`. Returns a ToolError or null when the URL is
591
+ * pinned (or absent, since the default is the pinned one). */
592
+ function enforceRpcPin(
593
+ toolName: 'install_policy' | 'revoke_policy' | 'get_interpreter_info',
594
+ rpcUrl: string | undefined,
595
+ allowUnpinned: boolean | undefined,
596
+ expectedRpc: string,
597
+ network: Network
598
+ ): ToolError | null {
599
+ if (!rpcUrl || rpcUrl === expectedRpc || allowUnpinned === true) return null
600
+ const code: ErrorCode =
601
+ toolName === 'install_policy'
602
+ ? 'INSTALL_BUILD_FAILED'
603
+ : toolName === 'revoke_policy'
604
+ ? 'REVOKE_BUILD_FAILED'
605
+ : 'RECORDING_FAILED'
606
+ return {
607
+ code,
608
+ message: `${toolName}: rpcUrl must equal the pinned ${expectedRpc} (${network}); set allowUnpinnedRpcUrl: true to opt in to a custom endpoint`,
609
+ severity: 'error',
610
+ retryable: false,
611
+ remediation: { toolCall: { name: toolName, args: {} } },
612
+ }
613
+ }
614
+
546
615
  /** Build a canonical ToolError for a Zod validation failure. The remediation
547
616
  * hint points the agent back at the right tool with an empty arg bag - the
548
617
  * tool name IS the machine-readable hint. */
549
618
  function validationError(
550
- toolName:
551
- | 'record_transaction'
552
- | 'synthesize_policy'
553
- | 'simulate_policy'
554
- | 'verify_policy'
555
- | 'install_policy'
556
- | 'revoke_policy'
557
- | 'get_interpreter_info',
619
+ toolName: RunToolName,
558
620
  issues: ReadonlyArray<{ path: ReadonlyArray<string | number>; message: string }>
559
621
  ): ToolError {
560
- const code: ErrorCode =
561
- toolName === 'record_transaction'
562
- ? 'RECORDING_FAILED'
563
- : toolName === 'synthesize_policy'
564
- ? 'SYNTHESIS_ERROR'
565
- : toolName === 'simulate_policy'
566
- ? 'SIMULATION_ERROR'
567
- : toolName === 'verify_policy'
568
- ? 'VERIFICATION_FAILED'
569
- : toolName === 'install_policy'
570
- ? 'INSTALL_BUILD_FAILED'
571
- : toolName === 'revoke_policy'
572
- ? 'REVOKE_BUILD_FAILED'
573
- : 'RECORDING_FAILED'
574
622
  return {
575
- code,
623
+ code: TOOL_ERROR_CODE[toolName],
576
624
  message: `${toolName}: invalid input: ${issues
577
625
  .map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`)
578
626
  .join('; ')}`,
579
627
  severity: 'error',
580
628
  retryable: false,
581
- remediation: {
582
- toolCall: { name: toolName, args: {} },
583
- },
629
+ remediation: { toolCall: { name: toolName, args: {} } },
584
630
  }
585
631
  }
586
632
 
587
633
  /** Build a canonical ToolError for a thrown exception caught by the tool
588
634
  * envelope. The MCP SDK stringifies thrown objects as "[object Object]" by
589
635
  * default, so we extract a string-friendly message and tag the original
590
- * error in `details` for the agent to inspect. The `code` is the tool's
591
- * domain code (RECORDING_FAILED for `record_transaction`, SYNTHESIS_ERROR
592
- * for `synthesize_policy`) so the agent dispatches on the same code the
593
- * structured ToolError would carry.
594
- *
595
- * Exported as `_caughtError` (the leading underscore signals the test-only
596
- * seam) so the suite in run/index.test.ts can drive the envelope path
597
- * without standing up a full recordTransaction pipeline. */
598
- export function caughtError(
599
- toolName:
600
- | 'record_transaction'
601
- | 'synthesize_policy'
602
- | 'simulate_policy'
603
- | 'verify_policy'
604
- | 'install_policy'
605
- | 'revoke_policy'
606
- | 'get_interpreter_info',
607
- code: ErrorCode,
608
- e: unknown
609
- ): ToolError {
610
- const message = describeThrown(e, toolName)
611
- const details = { thrown: safeStringify(e) }
636
+ * error in `details` for the agent to inspect. Exported as a test-only seam
637
+ * so the suite in run/index.test.ts can drive the envelope path without
638
+ * standing up a full recordTransaction pipeline. */
639
+ export function caughtError(toolName: RunToolName, code: ErrorCode, e: unknown): ToolError {
612
640
  return {
613
641
  code,
614
- message: `${toolName}: unhandled throw escaped core envelope: ${message}`,
642
+ message: `${toolName}: unhandled throw escaped core envelope: ${describeThrown(e, toolName)}`,
615
643
  severity: 'error',
616
644
  retryable: false,
617
- remediation: {
618
- toolCall: { name: toolName, args: {} },
619
- },
620
- details,
645
+ remediation: { toolCall: { name: toolName, args: {} } },
646
+ details: { thrown: safeStringify(e) },
621
647
  }
622
648
  }
623
649