tenjin-cli 0.1.0-alpha.27 → 0.1.0-alpha.29

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 (148) hide show
  1. package/README.md +18 -26
  2. package/dist/alive-3J3CHOQP.js +21 -0
  3. package/dist/{chunk-XVYATBKD.js → chunk-25GGN553.js} +897 -522
  4. package/dist/chunk-25GGN553.js.map +1 -0
  5. package/dist/{chunk-B2L53TMK.js → chunk-2SNUOHAT.js} +28 -23
  6. package/dist/chunk-2SNUOHAT.js.map +1 -0
  7. package/dist/{chunk-5NEHH2E5.js → chunk-3FY5HG7R.js} +86 -19
  8. package/dist/chunk-3FY5HG7R.js.map +1 -0
  9. package/dist/{chunk-YQOQ6XEI.js → chunk-4FYMDRD3.js} +51 -41
  10. package/dist/chunk-4FYMDRD3.js.map +1 -0
  11. package/dist/chunk-6W5GYG3W.js +128 -0
  12. package/dist/chunk-6W5GYG3W.js.map +1 -0
  13. package/dist/{chunk-G4AM2SOL.js → chunk-AMEUXNJT.js} +4 -8
  14. package/dist/{chunk-G4AM2SOL.js.map → chunk-AMEUXNJT.js.map} +1 -1
  15. package/dist/chunk-EWLU46J6.js +100 -0
  16. package/dist/chunk-EWLU46J6.js.map +1 -0
  17. package/dist/chunk-LRCJ2IZ5.js +115 -0
  18. package/dist/{chunk-HC3QEZKT.js.map → chunk-LRCJ2IZ5.js.map} +1 -1
  19. package/dist/{chunk-X7I343ZY.js → chunk-LX5OT4TQ.js} +3 -3
  20. package/dist/{chunk-X7I343ZY.js.map → chunk-LX5OT4TQ.js.map} +1 -1
  21. package/dist/{chunk-DATCR7AU.js → chunk-MG3G644T.js} +5 -7
  22. package/dist/{chunk-DATCR7AU.js.map → chunk-MG3G644T.js.map} +1 -1
  23. package/dist/{chunk-BOAI23CX.js → chunk-MOG7PB3A.js} +21 -15
  24. package/dist/chunk-MOG7PB3A.js.map +1 -0
  25. package/dist/{chunk-GU4GGKYP.js → chunk-MRUPDSUM.js} +14 -59
  26. package/dist/chunk-MRUPDSUM.js.map +1 -0
  27. package/dist/{chunk-AWKQSKUL.js → chunk-OOSRB3OF.js} +2 -2
  28. package/dist/{chunk-PZ5N6BAL.js → chunk-ORWL5BSN.js} +5 -4
  29. package/dist/chunk-ORWL5BSN.js.map +1 -0
  30. package/dist/chunk-P4LVLFO4.js +29 -0
  31. package/dist/chunk-P4LVLFO4.js.map +1 -0
  32. package/dist/{chunk-VXIBZ6W5.js → chunk-QTGUDCIR.js} +5 -5
  33. package/dist/{chunk-YKM2ZTA2.js → chunk-R4AO7GC2.js} +462 -105
  34. package/dist/chunk-R4AO7GC2.js.map +1 -0
  35. package/dist/{chunk-OHZYNZSD.js → chunk-RJEPZMYY.js} +12 -8
  36. package/dist/chunk-RJEPZMYY.js.map +1 -0
  37. package/dist/chunk-SBL4THYT.js +2074 -0
  38. package/dist/chunk-SBL4THYT.js.map +1 -0
  39. package/dist/{chunk-VNNXAYJE.js → chunk-SFEQGENI.js} +2 -2
  40. package/dist/{chunk-K6AXXYCG.js → chunk-SJLTEINJ.js} +10 -2
  41. package/dist/{chunk-K6AXXYCG.js.map → chunk-SJLTEINJ.js.map} +1 -1
  42. package/dist/{chunk-5FGO6TYT.js → chunk-TROZ6HL4.js} +3 -5
  43. package/dist/{chunk-5FGO6TYT.js.map → chunk-TROZ6HL4.js.map} +1 -1
  44. package/dist/{chunk-SKQQOEWH.js → chunk-USOLCBKC.js} +6 -8
  45. package/dist/{chunk-SKQQOEWH.js.map → chunk-USOLCBKC.js.map} +1 -1
  46. package/dist/{chunk-64SE3QC5.js → chunk-VKQXVCZR.js} +54 -5
  47. package/dist/chunk-VKQXVCZR.js.map +1 -0
  48. package/dist/{chunk-VIOUZW7Z.js → chunk-VVAHFCX2.js} +209 -37
  49. package/dist/chunk-VVAHFCX2.js.map +1 -0
  50. package/dist/{chunk-4L7KMA7P.js → chunk-WM7TJEBP.js} +8 -10
  51. package/dist/{chunk-4L7KMA7P.js.map → chunk-WM7TJEBP.js.map} +1 -1
  52. package/dist/{chunk-2TYQD22Q.js → chunk-XDYKZRLN.js} +23 -16
  53. package/dist/chunk-XDYKZRLN.js.map +1 -0
  54. package/dist/{chunk-LAIZ2AQA.js → chunk-XJQ6CH7X.js} +3 -2
  55. package/dist/{chunk-O7CUHHYU.js → chunk-ZQNGTLOC.js} +8 -10
  56. package/dist/{chunk-O7CUHHYU.js.map → chunk-ZQNGTLOC.js.map} +1 -1
  57. package/dist/{cli-6JNIPZQ6.js → cli-JPTDHGRX.js} +58 -52
  58. package/dist/{cli-6JNIPZQ6.js.map → cli-JPTDHGRX.js.map} +1 -1
  59. package/dist/{config-G75YT6NC.js → config-YYKDH2TH.js} +12 -15
  60. package/dist/{doctor-3GMDOW4Y.js → doctor-SSTXGCHX.js} +298 -269
  61. package/dist/doctor-SSTXGCHX.js.map +1 -0
  62. package/dist/{fund-3IPR5YRJ.js → fund-QWVWRVDK.js} +95 -43
  63. package/dist/{fund-3IPR5YRJ.js.map → fund-QWVWRVDK.js.map} +1 -1
  64. package/dist/hook-command-VWJXRT7H.js +31 -0
  65. package/dist/hosts/claude/.claude-plugin/marketplace.json +19 -0
  66. package/dist/hosts/claude/tenjin/.claude-plugin/plugin.json +14 -0
  67. package/dist/hosts/claude/tenjin/.mcp.json +12 -0
  68. package/dist/hosts/claude/tenjin/hooks/hooks.json +221 -0
  69. package/dist/index.js +13 -4
  70. package/dist/index.js.map +1 -1
  71. package/dist/install-2GXXD4DK.js +51 -0
  72. package/dist/{install-identity-PM4AGFFX.js → install-identity-FK3YF227.js} +7 -9
  73. package/dist/{install-wallet-6756NOB5.js → install-wallet-TC22U52X.js} +21 -17
  74. package/dist/{install-wallet-6756NOB5.js.map → install-wallet-TC22U52X.js.map} +1 -1
  75. package/dist/{mcp-33FAAZ7F.js → mcp-42H2F4NY.js} +2128 -372
  76. package/dist/mcp-42H2F4NY.js.map +1 -0
  77. package/dist/package-6DJA3Y2O.js +37 -0
  78. package/dist/{paths-MUXHUOCM.js → paths-POPTXJO6.js} +6 -2
  79. package/dist/{pay-XOYR4PCH.js → pay-LSDJBIAZ.js} +20 -18
  80. package/dist/payments-SPECLBRQ.js +105 -0
  81. package/dist/payments-SPECLBRQ.js.map +1 -0
  82. package/dist/{send-CVGNOQW3.js → send-MHAOLPK3.js} +13 -17
  83. package/dist/{send-CVGNOQW3.js.map → send-MHAOLPK3.js.map} +1 -1
  84. package/dist/status-O2RWLPS5.js +114 -0
  85. package/dist/status-O2RWLPS5.js.map +1 -0
  86. package/dist/{status-line-3IQKGRUH.js → status-line-45TVCRM3.js} +7 -9
  87. package/dist/{status-line-3IQKGRUH.js.map → status-line-45TVCRM3.js.map} +1 -1
  88. package/dist/uninstall-VOK2Z5M4.js +146 -0
  89. package/dist/uninstall-VOK2Z5M4.js.map +1 -0
  90. package/dist/update-FGP3HNLD.js +33 -0
  91. package/dist/update-FGP3HNLD.js.map +1 -0
  92. package/dist/{wallet-B3FVHNTS.js → wallet-DA7OFNEW.js} +18 -14
  93. package/dist/wallet-DA7OFNEW.js.map +1 -0
  94. package/docs/agent-permissions.md +35 -22
  95. package/docs/safety-model.md +3 -1
  96. package/package.json +2 -2
  97. package/dist/chunk-2TYQD22Q.js.map +0 -1
  98. package/dist/chunk-5NEHH2E5.js.map +0 -1
  99. package/dist/chunk-64SE3QC5.js.map +0 -1
  100. package/dist/chunk-6ZSGER3A.js +0 -52
  101. package/dist/chunk-6ZSGER3A.js.map +0 -1
  102. package/dist/chunk-B2L53TMK.js.map +0 -1
  103. package/dist/chunk-BOAI23CX.js.map +0 -1
  104. package/dist/chunk-DSNXKUXI.js +0 -172
  105. package/dist/chunk-DSNXKUXI.js.map +0 -1
  106. package/dist/chunk-GU4GGKYP.js.map +0 -1
  107. package/dist/chunk-H2L33M7F.js +0 -944
  108. package/dist/chunk-H2L33M7F.js.map +0 -1
  109. package/dist/chunk-HC3QEZKT.js +0 -87
  110. package/dist/chunk-JLEF5WHM.js +0 -132
  111. package/dist/chunk-JLEF5WHM.js.map +0 -1
  112. package/dist/chunk-MAQUL5BD.js +0 -99
  113. package/dist/chunk-MAQUL5BD.js.map +0 -1
  114. package/dist/chunk-OHZYNZSD.js.map +0 -1
  115. package/dist/chunk-PY7MQUKP.js +0 -755
  116. package/dist/chunk-PY7MQUKP.js.map +0 -1
  117. package/dist/chunk-PZ5N6BAL.js.map +0 -1
  118. package/dist/chunk-TGLKKLQG.js +0 -11
  119. package/dist/chunk-TGLKKLQG.js.map +0 -1
  120. package/dist/chunk-VIOUZW7Z.js.map +0 -1
  121. package/dist/chunk-XVYATBKD.js.map +0 -1
  122. package/dist/chunk-YKM2ZTA2.js.map +0 -1
  123. package/dist/chunk-YQOQ6XEI.js.map +0 -1
  124. package/dist/doctor-3GMDOW4Y.js.map +0 -1
  125. package/dist/hook-command-ZXX4FT4N.js +0 -32
  126. package/dist/install-6OROTYHZ.js +0 -72
  127. package/dist/mcp-33FAAZ7F.js.map +0 -1
  128. package/dist/payments-UTQDBO7H.js +0 -48
  129. package/dist/payments-UTQDBO7H.js.map +0 -1
  130. package/dist/status-NACN4DGX.js +0 -72
  131. package/dist/status-NACN4DGX.js.map +0 -1
  132. package/dist/status-line-wiring-QXBOOY2T.js +0 -31
  133. package/dist/uninstall-NYFKSYW4.js +0 -175
  134. package/dist/uninstall-NYFKSYW4.js.map +0 -1
  135. package/dist/update-RJDA5ZY3.js +0 -442
  136. package/dist/update-RJDA5ZY3.js.map +0 -1
  137. /package/dist/{config-G75YT6NC.js.map → alive-3J3CHOQP.js.map} +0 -0
  138. /package/dist/{chunk-AWKQSKUL.js.map → chunk-OOSRB3OF.js.map} +0 -0
  139. /package/dist/{chunk-VXIBZ6W5.js.map → chunk-QTGUDCIR.js.map} +0 -0
  140. /package/dist/{chunk-VNNXAYJE.js.map → chunk-SFEQGENI.js.map} +0 -0
  141. /package/dist/{chunk-LAIZ2AQA.js.map → chunk-XJQ6CH7X.js.map} +0 -0
  142. /package/dist/{hook-command-ZXX4FT4N.js.map → config-YYKDH2TH.js.map} +0 -0
  143. /package/dist/{install-6OROTYHZ.js.map → hook-command-VWJXRT7H.js.map} +0 -0
  144. /package/dist/{install-identity-PM4AGFFX.js.map → install-2GXXD4DK.js.map} +0 -0
  145. /package/dist/{paths-MUXHUOCM.js.map → install-identity-FK3YF227.js.map} +0 -0
  146. /package/dist/{pay-XOYR4PCH.js.map → package-6DJA3Y2O.js.map} +0 -0
  147. /package/dist/{status-line-wiring-QXBOOY2T.js.map → paths-POPTXJO6.js.map} +0 -0
  148. /package/dist/{wallet-B3FVHNTS.js.map → pay-LSDJBIAZ.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/paths.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/**\n * Where the CLI keeps its config and wallet. Defaults to ~/.tenjin, overridable\n * via TENJIN_DATA_DIR (CI, ephemeral agents, and every test — which point it at\n * a temp dir so the real home is never touched).\n */\nexport function dataDir(env: NodeJS.ProcessEnv = process.env): string {\n const override = env.TENJIN_DATA_DIR;\n // Absolute, always: the daemon compares this string against its own\n // `data_dir` and is spawned with it as `cwd`, so a relative override must\n // mean the same directory from every process.\n if (override !== undefined && override.length > 0) return resolve(override);\n return defaultDataDir();\n}\n\n/**\n * The data dir a run with no override resolves. Split out of {@link dataDir} so\n * a caller holding a home directory can ask whether some other profile IS the\n * default one, without a second copy of the `.tenjin` literal.\n */\nexport function defaultDataDir(home: string = homedir()): string {\n return join(home, '.tenjin');\n}\n\nexport function configPath(dir: string = dataDir()): string {\n return join(dir, 'config.json');\n}\n\nexport function walletPath(dir: string = dataDir()): string {\n return join(dir, 'wallet.json');\n}\n\n/**\n * The anonymous install id sent to Tenjin as `X-Tenjin-Install` (lib/install-identity).\n * Under the data dir so it survives upgrades and reinstalls of the CLI itself.\n */\nexport function installIdPath(dir: string = dataDir()): string {\n return join(dir, 'install-id');\n}\n\n/**\n * Where the delegated P-256 session key + its wallet-signed SIWX delegation are\n * cached (B3, D35). A short-lived (≤24h) hot key: lower stakes than wallet.json,\n * but still written 0600 and address-bound so a wallet change invalidates it.\n */\nexport function sessionPath(dir: string = dataDir()): string {\n return join(dir, 'session.json');\n}\n\n/**\n * Where the client-side rolling spend ledger lives (lib/wallet/spend.ts).\n *\n * Its own file, NOT session.json: the two schemas are incompatible and both\n * readers treat a parse failure as \"absent\", so a shared path meant each writer\n * silently destroyed the other's file — a session key wiped the spend window, and\n * the next spend wiped the session key.\n */\nexport function spendLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'spend.json');\n}\n\n/**\n * The wallet's last USDC balance read (lib/usdc-balance). A pure cache, a\n * minute long: an unreadable file is simply read again from the chain.\n */\nexport function balanceCachePath(dir: string = dataDir()): string {\n return join(dir, 'balance.json');\n}\n\n/**\n * Where the once-a-day \"a newer tenjin-cli exists\" check caches the registry\n * answer. A pure cache: nothing here is authoritative, so an unreadable file is\n * simply re-fetched.\n */\nexport function updateCheckPath(dir: string = dataDir()): string {\n return join(dir, 'update-check.json');\n}\n\n/**\n * Where `install` writes the standalone harness hook scripts. Under the data dir\n * rather than the harness's own config directory: the scripts are ours, a harness\n * only ever holds the path to them, and one location serves every harness.\n */\nexport function hooksDir(dir: string = dataDir()): string {\n return join(dir, 'hooks');\n}\n\n/**\n * How the marketplace has been answering the dispatch hook lately, so a run of\n * failures stops the arm instead of paying the fetch budget per subagent through\n * an outage. Hook-written, unlocked, and cheap to lose, since a missing file\n * reads as \"healthy\". Its own file because two hooks writing one unlocked file\n * would erase each other.\n */\nexport function hookHealthPath(dir: string = dataDir()): string {\n return join(dir, 'hook-health.json');\n}\n\n/**\n * Where the LEGACY (pre-per-wallet) Windows DPAPI passphrase blob lives. The\n * file holds a DPAPI CurrentUser ciphertext, not the passphrase in plaintext.\n * New writes go to the per-wallet path below; this one is only read as a\n * migration fallback and removed after a verified per-wallet copy exists.\n */\nexport function passphraseBlobPath(dir: string = dataDir()): string {\n return join(dir, 'passphrase.dpapi');\n}\n\n/**\n * The per-wallet Windows DPAPI passphrase blob: one file per wallet address\n * (lowercase), so creating a new wallet never clobbers an old wallet's blob.\n * Only ever written on win32; other platforms use their own OS store.\n */\nexport function passphraseBlobPathFor(account: string, dir: string = dataDir()): string {\n return join(dir, `passphrase.${account}.dpapi`);\n}\n\n/**\n * Where `wallet create --replace` parks the outgoing wallet's keystore, keyed by\n * its lowercase address so successive replaces can never collide. Together with\n * the wallet's per-address passphrase entry in the OS store, this file keeps the\n * replaced wallet's funds recoverable; it is never read by the active-wallet\n * path.\n */\nexport function archivedWalletPath(account: string, dir: string = dataDir()): string {\n return join(dir, `wallet.${account}.json.bak`);\n}\n\n/**\n * The loop daemon's own state, all under the data dir (tenjin-notes\n * loop-redesign/02-redesign.md §4, §10).\n */\nexport function loopDbPath(dir: string = dataDir()): string {\n return join(dir, 'loop.db');\n}\n\n/** 32 random bytes, hex, 0600. Minted by `tenjin daemon start`, rotated only by\n * reinstall, NEVER deleted by the daemon: every transport reads it, and an idle\n * exit that removed it would strand them all. */\nexport function daemonTokenPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.token');\n}\n\n/** `{ pid, port, started_at, data_dir }`, advisory: written after the bind,\n * removed at exit only by the process whose pid it names. Liveness is\n * `GET /health`, never this file alone. */\nexport function daemonPidPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.pid');\n}\n\n/** Where a detached daemon's stdout and stderr go, and where the shim writes its\n * one `daemon-down` line when it cannot reach one. */\nexport function daemonLogPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.log');\n}\n\n/** An empty file whose mtime is the last spawn attempt; the shim's backoff. */\nexport function daemonSpawnPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.spawn');\n}\n\n/** The single-file daemon bundle `tenjin daemon start` copies from `dist`. */\nexport function daemonBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-daemon.mjs');\n}\n\n/** The ensure-and-forward shim the two `command` hook entries run. */\nexport function shimBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-shim.mjs');\n}\n\n/** Tenjin's own vitest reporter, copied beside the bundles. NOT A HOOK ENTRY\n * and never spawned: a repo's own `vitest.config.ts` imports it by this\n * absolute path, which is why `doctor` can hint at it verbatim. */\nexport const VITEST_REPORTER_FILE = 'tenjin-vitest-reporter.mjs';\n\nexport function vitestReporterPath(dir: string = dataDir()): string {\n return join(hooksDir(dir), VITEST_REPORTER_FILE);\n}\n\n/**\n * Where a router lookup that bought a file (a sound, an image) saves it. The\n * bytes cannot ride in the tool result, so the result names this file instead.\n */\nexport function downloadsDir(dir: string = dataDir()): string {\n return join(dir, 'downloads');\n}\n\n/**\n * One JSON line per paid router call: what was bought, from whom, for how much,\n * the settlement it carried and the files it saved. The user's own record; only\n * reconcile reads it back (`tenjin payments reconcile`, and the `request` tool's\n * pass beside each lookup), to settle what was left unknown.\n */\nexport function paidLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'paid', 'ledger.jsonl');\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAOvB,SAAS,QAAQ,MAAyB,QAAQ,KAAa;AACpE,QAAM,WAAW,IAAI;AAIrB,MAAI,aAAa,UAAa,SAAS,SAAS,EAAG,QAAO,QAAQ,QAAQ;AAC1E,SAAO,eAAe;AACxB;AAOO,SAAS,eAAe,OAAe,QAAQ,GAAW;AAC/D,SAAO,KAAK,MAAM,SAAS;AAC7B;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;AAMO,SAAS,cAAc,MAAc,QAAQ,GAAW;AAC7D,SAAO,KAAK,KAAK,YAAY;AAC/B;AAOO,SAAS,YAAY,MAAc,QAAQ,GAAW;AAC3D,SAAO,KAAK,KAAK,cAAc;AACjC;AAUO,SAAS,gBAAgB,MAAc,QAAQ,GAAW;AA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W;AAClE,SAAO,KAAK,SAAS,GAAG,GAAG,oBAAoB;AACjD;AAMO,SAAS,aAAa,MAAc,QAAQ,GAAW;AAC5D,SAAO,KAAK,KAAK,WAAW;AAC9B;AAQO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,KAAK,QAAQ,cAAc;AACzC;","names":[]}
1
+ {"version":3,"sources":["../src/lib/paths.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/**\n * Where the CLI keeps its config and wallet. Defaults to ~/.tenjin, overridable\n * via TENJIN_DATA_DIR (CI, ephemeral agents, and every test — which point it at\n * a temp dir so the real home is never touched).\n */\nexport function dataDir(env: NodeJS.ProcessEnv = process.env): string {\n const override = env.TENJIN_DATA_DIR;\n // Absolute, always: the daemon compares this string against its own\n // `data_dir` and is spawned with it as `cwd`, so a relative override must\n // mean the same directory from every process.\n if (override !== undefined && override.length > 0) return resolve(override);\n return defaultDataDir();\n}\n\n/**\n * The data dir a run with no override resolves. Split out of {@link dataDir} so\n * a caller holding a home directory can ask whether some other profile IS the\n * default one, without a second copy of the `.tenjin` literal.\n */\nexport function defaultDataDir(home: string = homedir()): string {\n return join(home, '.tenjin');\n}\n\nexport function configPath(dir: string = dataDir()): string {\n return join(dir, 'config.json');\n}\n\nexport function walletPath(dir: string = dataDir()): string {\n return join(dir, 'wallet.json');\n}\n\n/**\n * The anonymous install id sent to Tenjin as `X-Tenjin-Install` (lib/install-identity).\n * Under the data dir so it survives upgrades and reinstalls of the CLI itself.\n */\nexport function installIdPath(dir: string = dataDir()): string {\n return join(dir, 'install-id');\n}\n\n/**\n * Where the delegated P-256 session key + its wallet-signed SIWX delegation are\n * cached (B3, D35). A short-lived (≤24h) hot key: lower stakes than wallet.json,\n * but still written 0600 and address-bound so a wallet change invalidates it.\n */\nexport function sessionPath(dir: string = dataDir()): string {\n return join(dir, 'session.json');\n}\n\n/**\n * Where the client-side rolling spend ledger lives (lib/wallet/spend.ts).\n *\n * Its own file, NOT session.json: the two schemas are incompatible and both\n * readers treat a parse failure as \"absent\", so a shared path meant each writer\n * silently destroyed the other's file — a session key wiped the spend window, and\n * the next spend wiped the session key.\n */\nexport function spendLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'spend.json');\n}\n\n/**\n * The wallet's last USDC balance read (lib/usdc-balance). A pure cache, a\n * minute long: an unreadable file is simply read again from the chain.\n */\nexport function balanceCachePath(dir: string = dataDir()): string {\n return join(dir, 'balance.json');\n}\n\n/**\n * Where the once-a-day \"a newer tenjin-cli exists\" check caches the registry\n * answer. A pure cache: nothing here is authoritative, so an unreadable file is\n * simply re-fetched.\n */\nexport function updateCheckPath(dir: string = dataDir()): string {\n return join(dir, 'update-check.json');\n}\n\n/**\n * Where `install` writes the standalone harness hook scripts. Under the data dir\n * rather than the harness's own config directory: the scripts are ours, a harness\n * only ever holds the path to them, and one location serves every harness.\n */\nexport function hooksDir(dir: string = dataDir()): string {\n return join(dir, 'hooks');\n}\n\n/**\n * How the marketplace has been answering the dispatch hook lately, so a run of\n * failures stops the arm instead of paying the fetch budget per subagent through\n * an outage. Hook-written, unlocked, and cheap to lose, since a missing file\n * reads as \"healthy\". Its own file because two hooks writing one unlocked file\n * would erase each other.\n */\nexport function hookHealthPath(dir: string = dataDir()): string {\n return join(dir, 'hook-health.json');\n}\n\n/**\n * Where the LEGACY (pre-per-wallet) Windows DPAPI passphrase blob lives. The\n * file holds a DPAPI CurrentUser ciphertext, not the passphrase in plaintext.\n * New writes go to the per-wallet path below; this one is only read as a\n * migration fallback and removed after a verified per-wallet copy exists.\n */\nexport function passphraseBlobPath(dir: string = dataDir()): string {\n return join(dir, 'passphrase.dpapi');\n}\n\n/**\n * The per-wallet Windows DPAPI passphrase blob: one file per wallet address\n * (lowercase), so creating a new wallet never clobbers an old wallet's blob.\n * Only ever written on win32; other platforms use their own OS store.\n */\nexport function passphraseBlobPathFor(account: string, dir: string = dataDir()): string {\n return join(dir, `passphrase.${account}.dpapi`);\n}\n\n/**\n * Where `wallet create --replace` parks the outgoing wallet's keystore, keyed by\n * its lowercase address so successive replaces can never collide. Together with\n * the wallet's per-address passphrase entry in the OS store, this file keeps the\n * replaced wallet's funds recoverable; it is never read by the active-wallet\n * path.\n */\nexport function archivedWalletPath(account: string, dir: string = dataDir()): string {\n return join(dir, `wallet.${account}.json.bak`);\n}\n\n/**\n * The loop daemon's own state, all under the data dir (tenjin-notes\n * loop-redesign/02-redesign.md §4, §10).\n */\nexport function loopDbPath(dir: string = dataDir()): string {\n return join(dir, 'loop.db');\n}\n\n/** 32 random bytes, hex, 0600. Minted by `tenjin daemon start`, rotated only by\n * reinstall, NEVER deleted by the daemon: every transport reads it, and an idle\n * exit that removed it would strand them all. */\nexport function daemonTokenPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.token');\n}\n\n/** `{ pid, port, started_at, data_dir }`, advisory: written after the bind,\n * removed at exit only by the process whose pid it names. Liveness is\n * `GET /health`, never this file alone. */\nexport function daemonPidPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.pid');\n}\n\n/** Where a detached daemon's stdout and stderr go, and where the shim writes its\n * one `daemon-down` line when it cannot reach one. */\nexport function daemonLogPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.log');\n}\n\n/** An empty file whose mtime is the last spawn attempt; the shim's backoff. */\nexport function daemonSpawnPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.spawn');\n}\n\n/** The single-file daemon bundle `tenjin daemon start` copies from `dist`. */\nexport function daemonBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-daemon.mjs');\n}\n\n/** The ensure-and-forward shim the two `command` hook entries run. */\nexport function shimBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-shim.mjs');\n}\n\n/** Tenjin's own vitest reporter, copied beside the bundles. NOT A HOOK ENTRY\n * and never spawned: a repo's own `vitest.config.ts` imports it by this\n * absolute path, which is why `doctor` can hint at it verbatim. */\nexport const VITEST_REPORTER_FILE = 'tenjin-vitest-reporter.mjs';\n\nexport function vitestReporterPath(dir: string = dataDir()): string {\n return join(hooksDir(dir), VITEST_REPORTER_FILE);\n}\n\n/**\n * Where a router lookup that bought a file (a sound, an image) saves it. The\n * bytes cannot ride in the tool result, so the result names this file instead.\n */\nexport function downloadsDir(dir: string = dataDir()): string {\n return join(dir, 'downloads');\n}\n\n/**\n * One JSON line per paid router call: what was bought, from whom, for how much,\n * the settlement it carried and the files it saved. The user's own record; only\n * reconcile reads it back (`tenjin payments reconcile`, and the `request` tool's\n * pass beside each lookup), to settle what was left unknown.\n */\nexport function paidLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'paid', 'ledger.jsonl');\n}\n\n/**\n * One file per take of a paid router call whose seller was still working when\n * the call ended: where to poll, until when, and what it saved. `request({job})`\n * resumes from it in any later process.\n */\nexport function jobsDir(dir: string = dataDir()): string {\n return join(dir, 'jobs');\n}\n\n/**\n * One file per quote: a router call over the automatic limits, kept with its\n * exact plan until the user approves it, it runs once, or it expires.\n */\nexport function quotesDir(dir: string = dataDir()): string {\n return join(dir, 'quotes');\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAOvB,SAAS,QAAQ,MAAyB,QAAQ,KAAa;AACpE,QAAM,WAAW,IAAI;AAIrB,MAAI,aAAa,UAAa,SAAS,SAAS,EAAG,QAAO,QAAQ,QAAQ;AAC1E,SAAO,eAAe;AACxB;AAOO,SAAS,eAAe,OAAe,QAAQ,GAAW;AAC/D,SAAO,KAAK,MAAM,SAAS;AAC7B;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;AAEO,SAAS,WAAW,MAAc,QAAQ,GAAW;AAC1D,SAAO,KAAK,KAAK,aAAa;AAChC;AAMO,SAAS,cAAc,MAAc,QAAQ,GAAW;AAC7D,SAAO,KAAK,KAAK,YAAY;AAC/B;AAOO,SAAS,YAAY,MAAc,QAAQ,GAAW;AAC3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iBAAiB;AAC9C;AAKO,IAAM,uBAAuB;AAE7B,SAAS,mBAAmB,MAAc,QAAQ,GAAW;AAClE,SAAO,KAAK,SAAS,GAAG,GAAG,oBAAoB;AACjD;AAMO,SAAS,aAAa,MAAc,QAAQ,GAAW;AAC5D,SAAO,KAAK,KAAK,WAAW;AAC9B;AAQO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,KAAK,QAAQ,cAAc;AACzC;AAOO,SAAS,QAAQ,MAAc,QAAQ,GAAW;AACvD,SAAO,KAAK,KAAK,MAAM;AACzB;AAMO,SAAS,UAAU,MAAc,QAAQ,GAAW;AACzD,SAAO,KAAK,KAAK,QAAQ;AAC3B;","names":[]}
@@ -1,10 +1,8 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
+ CliError,
3
4
  external_exports
4
- } from "./chunk-VIOUZW7Z.js";
5
- import {
6
- CliError
7
- } from "./chunk-JLEF5WHM.js";
5
+ } from "./chunk-VVAHFCX2.js";
8
6
 
9
7
  // src/lib/output.ts
10
8
  import { WriteStream } from "node:tty";
@@ -236,4 +234,4 @@ export {
236
234
  style,
237
235
  paint
238
236
  };
239
- //# sourceMappingURL=chunk-5FGO6TYT.js.map
237
+ //# sourceMappingURL=chunk-TROZ6HL4.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/output.ts","../src/schemas.ts"],"sourcesContent":["import { WriteStream } from 'node:tty';\nimport { styleText } from 'node:util';\nimport { CliError } from './errors';\nimport type { StdinInput } from './stdin';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { UpdateAvailable } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY facts. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` describes stdout; the separate `--json` flag (passed to the emit\n * functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output. `stdin` is\n * optional for compatibility with command-core contexts that never read it;\n * defaultIo supplies the real stream, and only the CLI forwards that capability\n * to commands that accept Markdown on stdin.\n */\nexport interface Io {\n stdin?: StdinInput;\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n /**\n * \"A newer tenjin-cli exists\", from the daily check's cache. Rides the\n * envelope so the AGENT running the command learns it; the human at a TTY\n * gets the dim stderr line instead, and neither path fetches anything.\n */\n updateAvailable?: UpdateAvailable | null;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(\n command: string,\n data: unknown,\n updateAvailable?: UpdateAvailable | null,\n): SuccessEnvelope {\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: true,\n data,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\nexport function buildFailureEnvelope(\n command: string,\n err: CliError,\n updateAvailable?: UpdateAvailable | null,\n): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: false,\n error,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them\n // an interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees\n // the count but not WHICH lines tripped. Every other shape is machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Every escape sequence a terminal writes: CSI (colour, cursor), OSC — which\n * covers the OSC-8 hyperlinks pnpm wraps package names in, terminated by BEL\n * or ST — charset selection, and a stray ESC with a single final byte.\n *\n * ONE COPY, because the other reader is the failure lane: `stripAnsi`\n * (`hooks/text.ts`) takes colour off a runner's output before the arm scans it\n * for a diagnostic, and a pattern that misses OSC-8 leaves `]8;;https://…`\n * sitting in front of the very line the start-anchored markers must match.\n * That reader CANNOT call {@link sanitizeForTerminal}: this is only its first\n * clause, and the second strips `\\n`, which would flatten the output it is\n * about to split into lines.\n *\n * Safe to share despite the `g` flag: both callers use it through\n * `String.replace`, which starts at 0 and resets `lastIndex`. Do not `test()`\n * or `exec()` it.\n */\nexport const ANSI_ESCAPE_RE =\n // eslint-disable-next-line no-control-regex\n /\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g;\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n .replace(ANSI_ESCAPE_RE, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n *\n * A finding the SERVER gate contributed carries a `source`, and the marker is\n * printed because it is the difference between \"fix your file\" and \"the\n * marketplace refused this\": the detector may be one this release predates, so\n * the line has to stand on the server's own words rather than on recognition.\n * The tier rides the same line, for the payloads that mix block and warn.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt, source, severity } = f as {\n check?: unknown;\n line?: unknown;\n excerpt?: unknown;\n source?: unknown;\n severity?: unknown;\n };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n const from = source === 'server' ? ' [server]' : source === 'both' ? ' [local+server]' : '';\n // THE TIER IS PRINTED because one payload can mix them: a `scan_blocked`\n // envelope ships the block finding alongside the warns the same pass found,\n // and without the tier nothing on the page says which one is the refusal.\n // An open string, sanitized like the rest: the server owns its own tier names.\n const tier = typeof severity === 'string' && severity.length > 0 ? `${severity}, ` : '';\n // The detector id is sanitized too: on a server finding it is a name this\n // release may never have seen, so it is untrusted text like the excerpt.\n rendered.push(\n paint(\n io,\n 'dim',\n ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`,\n ),\n );\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\nexport type StyleFormat = Parameters<typeof styleText>[0];\n\n/**\n * Does `stream` take ANSI color? Node's own rule (`shouldColorize`): FORCE_COLOR\n * wins when set, otherwise a TTY whose color depth is above 2 (which reads\n * NO_COLOR, NODE_DISABLE_COLORS and TERM). Decided here because styleText only\n * checks the stream from Node 22.13 and colors unconditionally before it.\n */\nexport function colorCapable(stream: unknown, env: NodeJS.ProcessEnv = process.env): boolean {\n const force = env.FORCE_COLOR;\n if (force !== undefined) return ['', '1', 'true', '2', '3'].includes(force);\n return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;\n}\n\n/** `text` in `format` when `stream` takes color, else plain. */\nexport function style(format: StyleFormat, text: string, stream: unknown = process.stdout): string {\n return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;\n}\n\n/** Color a human line for stdout. A test or redirected sink is no TTY, so it comes out plain. */\nexport function paint(io: Io, format: StyleFormat, text: string): string {\n return style(format, text, io.stdout);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit\n // 4). Its own code rather than PUBLISH_FAILED because the two say opposite\n // things about what is now live, and an agent reporting the outcome to a user\n // must not read \"the piece is still up\" as \"the piece went up\".\n 'DELETE_FAILED',\n // `tenjin update`: the npm install it spawned exited nonzero or never started.\n // Exit 1, not the post-decision class: nothing is half-written that the\n // operator must reconcile, and the old build keeps running.\n 'UPDATE_FAILED',\n // `tenjin pay` Bazaar lane: the live 402 does not match what a configured\n // registry publicly advertises for this resource (understood-but-refused, 3);\n // nothing was signed and nothing was spent.\n 'REGISTRY_MISMATCH',\n // The seller's 402 challenge exceeds this process's response-header limit, so\n // its terms could never be read (understood-but-refused, 3). Nothing was\n // signed and nothing was sent; a retry changes nothing without an operator\n // raising `--max-http-header-size` on the process that runs the CLI.\n 'CHALLENGE_TOO_LARGE',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\n/**\n * \"A newer tenjin-cli exists\", carried on the envelope so an AGENT learns it.\n *\n * The daily check's other surface is one dim stderr line, which only a human at\n * a terminal ever sees; on the machines that run this CLI most, nobody does.\n * This field is how the agent driving the command finds out it can run\n * `tenjin update` itself. Read from the check's cache, never fetched here: the\n * envelope must not wait on a network call it did not need.\n */\nexport const UpdateAvailableSchema = z.object({\n current: z.string(),\n latest: z.string(),\n});\nexport type UpdateAvailable = z.infer<typeof UpdateAvailableSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n /** Present only when a newer version is known and update.mode is not `off`. */\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;;;ACMnB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA,EAGA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA;AA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';\nimport { styleText } from 'node:util';\nimport { CliError } from './errors';\nimport type { StdinInput } from './stdin';\nimport { SCHEMA_VERSION } from '../schemas';\nimport type { UpdateAvailable } from '../schemas';\nimport type { FailureEnvelope, OutputError, SuccessEnvelope } from '../schemas';\n\n/**\n * Injected streams + TTY facts. Every command receives one via CommandContext,\n * so tests drive the CLI in-process with memory buffers and no child process.\n * `isTTY` describes stdout; the separate `--json` flag (passed to the emit\n * functions) is what suppresses human rendering — the two are ANDed, never\n * conflated, so `--json` on a TTY still yields pure machine output. `stdin` is\n * optional for compatibility with command-core contexts that never read it;\n * defaultIo supplies the real stream, and only the CLI forwards that capability\n * to commands that accept Markdown on stdin.\n */\nexport interface Io {\n stdin?: StdinInput;\n stdout: NodeJS.WritableStream;\n stderr: NodeJS.WritableStream;\n isTTY: boolean;\n}\n\nexport function defaultIo(): Io {\n return {\n stdin: { stream: process.stdin, isTTY: Boolean(process.stdin.isTTY) },\n stdout: process.stdout,\n stderr: process.stderr,\n isTTY: Boolean(process.stdout.isTTY),\n };\n}\n\nexport interface EmitOptions {\n /** The global --json flag. When true, the JSON envelope is emitted even at a TTY. */\n json?: boolean;\n /**\n * \"A newer tenjin-cli exists\", from the daily check's cache. Rides the\n * envelope so the AGENT running the command learns it; the human at a TTY\n * gets the dim stderr line instead, and neither path fetches anything.\n */\n updateAvailable?: UpdateAvailable | null;\n}\n\n/**\n * The two pure envelope builders, shared by the CLI's emit functions and the MCP\n * adapter so both surfaces produce the identical wire object by construction. They\n * hold no I/O and no --json branching: they turn a (command, data) or a normalized\n * CliError into the exact object that goes to stdout / structuredContent.\n */\nexport function buildSuccessEnvelope(\n command: string,\n data: unknown,\n updateAvailable?: UpdateAvailable | null,\n): SuccessEnvelope {\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: true,\n data,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\nexport function buildFailureEnvelope(\n command: string,\n err: CliError,\n updateAvailable?: UpdateAvailable | null,\n): FailureEnvelope {\n const error: OutputError = {\n code: err.code,\n message: err.message,\n ...(err.fix !== undefined ? { fix: err.fix } : {}),\n ...(err.details !== undefined ? { details: err.details } : {}),\n };\n return {\n schemaVersion: SCHEMA_VERSION,\n command,\n ok: false,\n error,\n ...(updateAvailable != null ? { updateAvailable: updateAvailable } : {}),\n };\n}\n\n/**\n * Output contract (human-first): at a TTY without `--json`, print ONLY the human\n * rendering to stdout, no JSON envelope. With `--json`, or when stdout is not a\n * TTY (a pipe, an agent), print exactly one JSON envelope to stdout and nothing\n * else. Exit codes are identical on both paths; only the stdout shape differs.\n */\nexport function emitSuccess(\n io: Io,\n command: string,\n data: unknown,\n humanLines: string[] = [],\n opts: EmitOptions = {},\n): void {\n if (humanMode(io, opts)) {\n writeLines(io.stdout, humanLines);\n return;\n }\n writeJson(io.stdout, buildSuccessEnvelope(command, data, opts.updateAvailable));\n}\n\n/**\n * The failure half of the same contract: at a TTY without `--json`, a red error\n * line plus a `fix` line to stdout and no envelope; otherwise exactly one failure\n * envelope to stdout. Accepts a CliError or any thrown value (non-CliError\n * normalizes to INTERNAL). Returns the normalized CliError so the caller reads its\n * `exitCode`.\n */\nexport function emitFailure(\n io: Io,\n command: string,\n err: unknown,\n opts: EmitOptions = {},\n): CliError {\n const cliErr = normalizeError(err);\n if (humanMode(io, opts)) {\n // Error messages can embed server-sourced text (api error passthrough) and\n // never carry intentional ANSI, so sanitize before painting.\n const lines = [paint(io, 'red', `error: ${sanitizeForTerminal(cliErr.message)}`)];\n if (cliErr.fix !== undefined) {\n lines.push(paint(io, 'dim', `fix: ${sanitizeForTerminal(cliErr.fix)}`));\n }\n // Scan findings are the one detail shape a human needs inline: without them\n // an interactive publish hitting NEEDS_CONFIRMATION / PUBLISH_BLOCKED sees\n // the count but not WHICH lines tripped. Every other shape is machine-only.\n lines.push(...findingLines(io, cliErr.details));\n writeLines(io.stdout, lines);\n return cliErr;\n }\n writeJson(io.stdout, buildFailureEnvelope(command, cliErr, opts.updateAvailable));\n return cliErr;\n}\n\n/**\n * One dim advisory line on stderr, human mode only. This is for facts that belong\n * to NO command's result — an unreadable spend ledger, a newer release on npm —\n * so they can never join the envelope on stdout or reach a machine consumer at\n * all. Sanitized here rather than by each caller: what these lines quote (a\n * registry version string, a parse error) is not the command's own prose.\n */\nexport function emitNotice(io: Io, text: string, opts: EmitOptions = {}): void {\n if (!humanMode(io, opts)) return;\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * The same dim stderr line, delivered whatever the surface is: no TTY gate and no\n * `--json` gate. Only for an advisory a piped or agent-driven run must not miss,\n * which today is two things: a WRITE to the operator's own files, and `fund`'s\n * checkout link, which expires long before the stdout envelope that also carries\n * it is written. Anything a piped run can simply do without belongs in\n * {@link emitNotice} instead. stdout is untouched either way, so the exactly-one\n * JSON object contract is unaffected.\n */\nexport function emitWriteNotice(io: Io, text: string): void {\n io.stderr.write(`${paint(io, 'dim', sanitizeForTerminal(text))}\\n`);\n}\n\n/**\n * Every escape sequence a terminal writes: CSI (colour, cursor), OSC — which\n * covers the OSC-8 hyperlinks pnpm wraps package names in, terminated by BEL\n * or ST — charset selection, and a stray ESC with a single final byte.\n *\n * ONE COPY, because the other reader is the failure lane: `stripAnsi`\n * (`hooks/text.ts`) takes colour off a runner's output before the arm scans it\n * for a diagnostic, and a pattern that misses OSC-8 leaves `]8;;https://…`\n * sitting in front of the very line the start-anchored markers must match.\n * That reader CANNOT call {@link sanitizeForTerminal}: this is only its first\n * clause, and the second strips `\\n`, which would flatten the output it is\n * about to split into lines.\n *\n * Safe to share despite the `g` flag: both callers use it through\n * `String.replace`, which starts at 0 and resets `lastIndex`. Do not `test()`\n * or `exec()` it.\n */\nexport const ANSI_ESCAPE_RE =\n // eslint-disable-next-line no-control-regex\n /\\x1b(?:\\[[0-9;?]*[ -/]*[@-~]|\\][^\\x07\\x1b]*(?:\\x07|\\x1b\\\\)|[@-Z\\\\-_])/g;\n\n/**\n * Strip ANSI escape sequences, C0/C1 control characters, Unicode bidirectional\n * formatting, and invisible tag/BOM characters from a string headed for a\n * terminal. Commands apply this to every SERVER-sourced string (titles,\n * handles) they put into human lines or the buy confirm prompt; without it a\n * malicious deployment could use cursor-movement escapes to overwrite the very\n * price a human is being asked to confirm, a right-to-left override to reorder\n * that same line on screen into one that reads as a different price, or tag\n * characters to carry a payload that draws as nothing at all. It is not\n * applied to whole human lines here because trusted callers (doctor) paint\n * their own ANSI colors. JSON stdout is untouched: JSON.stringify escapes C0\n * controls itself, but the bidi and tag/BOM sets ride through it raw, and that\n * is deliberate rather than covered — the envelope is machine-read data whose\n * bytes must be what the server said, and a consumer reading codepoints is not\n * deceived by rendering order the way a human reading a drawn line is.\n */\nexport function sanitizeForTerminal(text: string): string {\n return (\n text\n // CSI/OSC/charset escape sequences first, then any stray ESC and the rest\n // of C0 (except \\t) plus DEL and the C1 range.\n .replace(ANSI_ESCAPE_RE, '')\n // eslint-disable-next-line no-control-regex\n .replace(/[\\x00-\\x08\\x0a-\\x1f\\x7f-\\x9f]/g, '')\n // The UAX#9 directional formatting set: the marks (LRM/RLM/ALM), the\n // embeddings and overrides (U+202A-U+202E), and the isolates\n // (U+2066-U+2069). Removed, not escaped, so what a human reads is the\n // order the bytes are in. Deliberately this set and NOT all of category\n // Cf: U+200D (ZWJ) joins legitimate emoji sequences, and dropping it\n // would corrupt honest titles to defend against dishonest ones.\n .replace(/[\\u061c\\u200e\\u200f\\u202a-\\u202e\\u2066-\\u2069]/g, '')\n // The Unicode tag block (U+E0000-U+E007F) and the BOM/ZWNBSP, neither of\n // which has a legitimate mid-title use. Tag characters render as nothing\n // at all, so a payload spelled in them is invisible in the line a human\n // is reading and in the line they would paste back to report it.\n //\n // The three RGI subdivision flags are the exception and survive\n // byte-identical: they are ordinary title content. The whitelist is those\n // three sequences and NOT \"any well-formed tag sequence\", because a\n // non-RGI sequence draws as a bare black flag with the payload hidden\n // behind it, which is the exact channel this closes.\n //\n // Kept for the same reason as ZWJ above: U+200B (ZWSP) hints line breaks\n // in CJK and U+200C (ZWNJ) is orthographically required in Persian, so\n // stripping them would corrupt honest titles to defend against dishonest\n // ones.\n .replace(\n /(\\u{1F3F4}\\u{E0067}\\u{E0062}(?:\\u{E0065}\\u{E006E}\\u{E0067}|\\u{E0073}\\u{E0063}\\u{E0074}|\\u{E0077}\\u{E006C}\\u{E0073})\\u{E007F})|[\\u{E0000}-\\u{E007F}\\u{FEFF}]/gu,\n (_match, rgiFlag: string | undefined) => rgiFlag ?? '',\n )\n );\n}\n\n/**\n * The same strip, for text that ships to OTHER PEOPLE rather than to this\n * terminal: a post's title, its public excerpt, and every free-text field of the\n * answer card a buyer reads before paying.\n *\n * The threat is the same one {@link sanitizeForTerminal} closes, one hop further\n * out. None of this text is necessarily typed by the person publishing: a card\n * question can be prefilled from a stored search, and every field can arrive over\n * MCP from an agent that read them off a fetched page. `trim()` removes neither a\n * CSI sequence nor a right-to-left override, so without this a payload rides into\n * the marketplace and renders in every future reader's terminal.\n *\n * Newlines and tabs fold to a single space FIRST, because these are all\n * single-line display fields and a bare strip would join the words on either side\n * of a line break into one. NOT for the post BODY: that is the author's document,\n * markdown and all, and rewriting it is not this function's business.\n */\nexport function sanitizeWireText(text: string): string {\n return sanitizeForTerminal(text.replace(/[\\r\\n\\t]+/g, ' ')).trim();\n}\n\n/** CliError passes through; every other thrown value becomes an INTERNAL CliError. */\nexport function normalizeError(err: unknown): CliError {\n if (err instanceof CliError) return err;\n if (err instanceof Error) return new CliError('INTERNAL', err.message, { cause: err });\n return new CliError('INTERNAL', 'Unexpected error', { details: err });\n}\n\n/** True in human-first mode: a TTY without --json. Otherwise the JSON envelope wins. */\nfunction humanMode(io: Io, opts: EmitOptions): boolean {\n return io.isTTY && opts.json !== true;\n}\n\n/**\n * Render `details.findings` (the scan-finding projection publish attaches to\n * NEEDS_CONFIRMATION / PUBLISH_BLOCKED) as one dim line per finding:\n * ` <check> (line N): <excerpt>`. The excerpt is already masked for secret\n * findings at the source; sanitize it anyway since it can echo file content.\n * Returns [] for any other details shape, so no other error leaks a detail dump.\n *\n * A finding the SERVER gate contributed carries a `source`, and the marker is\n * printed because it is the difference between \"fix your file\" and \"the\n * marketplace refused this\": the detector may be one this release predates, so\n * the line has to stand on the server's own words rather than on recognition.\n * The tier rides the same line, for the payloads that mix block and warn.\n */\nfunction findingLines(io: Io, details: unknown): string[] {\n if (typeof details !== 'object' || details === null || !('findings' in details)) return [];\n const { findings } = details as { findings: unknown };\n if (!Array.isArray(findings) || findings.length === 0) return [];\n const rendered: string[] = [];\n for (const f of findings) {\n if (typeof f !== 'object' || f === null) continue;\n const { check, line, excerpt, source, severity } = f as {\n check?: unknown;\n line?: unknown;\n excerpt?: unknown;\n source?: unknown;\n severity?: unknown;\n };\n if (typeof check !== 'string' || typeof line !== 'number' || typeof excerpt !== 'string') {\n continue;\n }\n const from = source === 'server' ? ' [server]' : source === 'both' ? ' [local+server]' : '';\n // THE TIER IS PRINTED because one payload can mix them: a `scan_blocked`\n // envelope ships the block finding alongside the warns the same pass found,\n // and without the tier nothing on the page says which one is the refusal.\n // An open string, sanitized like the rest: the server owns its own tier names.\n const tier = typeof severity === 'string' && severity.length > 0 ? `${severity}, ` : '';\n // The detector id is sanitized too: on a server finding it is a name this\n // release may never have seen, so it is untrusted text like the excerpt.\n rendered.push(\n paint(\n io,\n 'dim',\n ` ${sanitizeForTerminal(check)}${from} (${sanitizeForTerminal(tier)}line ${line}): ${sanitizeForTerminal(excerpt)}`,\n ),\n );\n }\n return rendered;\n}\n\nfunction writeJson(stream: NodeJS.WritableStream, value: unknown): void {\n stream.write(`${JSON.stringify(value, null, 2)}\\n`);\n}\n\nfunction writeLines(stream: NodeJS.WritableStream, lines: string[]): void {\n if (lines.length > 0) stream.write(`${lines.join('\\n')}\\n`);\n}\n\nexport type StyleFormat = Parameters<typeof styleText>[0];\n\n/**\n * Does `stream` take ANSI color? Node's own rule (`shouldColorize`): FORCE_COLOR\n * wins when set, otherwise a TTY whose color depth is above 2 (which reads\n * NO_COLOR, NODE_DISABLE_COLORS and TERM). Decided here because styleText only\n * checks the stream from Node 22.13 and colors unconditionally before it.\n */\nexport function colorCapable(stream: unknown, env: NodeJS.ProcessEnv = process.env): boolean {\n const force = env.FORCE_COLOR;\n if (force !== undefined) return ['', '1', 'true', '2', '3'].includes(force);\n return stream instanceof WriteStream && stream.isTTY && stream.getColorDepth(env) > 2;\n}\n\n/** `text` in `format` when `stream` takes color, else plain. */\nexport function style(format: StyleFormat, text: string, stream: unknown = process.stdout): string {\n return colorCapable(stream) ? styleText(format, text, { validateStream: false }) : text;\n}\n\n/** Color a human line for stdout. A test or redirected sink is no TTY, so it comes out plain. */\nexport function paint(io: Io, format: StyleFormat, text: string): string {\n return style(format, text, io.stdout);\n}\n","import { z } from 'zod';\n\n/**\n * Bumped only on a breaking change to any stdout envelope shape. Agents pin on\n * this: a consumer that sees an unexpected value should refuse to parse rather\n * than guess. Every envelope carries it, success or failure.\n */\nexport const SCHEMA_VERSION = 1;\n\n/**\n * The closed set of machine error codes. `error.code` in a failure envelope is\n * always one of these; agents branch on it, humans read `message`/`fix`. The\n * exit-code mapping lives in lib/errors.ts (this enum is the single source of\n * the code names both sides agree on).\n */\nexport const ErrorCodeSchema = z.enum([\n 'NODE_UNSUPPORTED',\n 'USAGE',\n 'CONFIG_INVALID',\n 'WALLET_EXISTS',\n 'WALLET_MISSING',\n 'WALLET_INVALID_KEY',\n 'PROVIDER_ERROR',\n 'RPC_ERROR',\n 'API_UNREACHABLE',\n 'CONTRACT_MISMATCH',\n 'REFUSED',\n 'NETWORK_ERROR',\n 'INTERNAL',\n 'NOT_IMPLEMENTED',\n // B2 (search/inspect/buy/outcome): a policy refusal (exit 3) has its own code\n // so an agent can distinguish a spend-cap block from a generic REFUSED; a\n // payment that failed after approval (exit 4) is PAYMENT_FAILED; the read\n // route's own coded failures (402 preview parse, 409 gate) surface as these.\n 'POLICY_REFUSED',\n 'PAYMENT_FAILED',\n 'RESOURCE_NOT_FOUND',\n 'SEARCH_NOT_FOUND',\n // A 429 from the anonymous search/outcome/read limits; error.details carries\n // retryAfterSeconds so a looping agent can back off instead of hammering.\n 'RATE_LIMITED',\n // B3 (publish): a publish that needs the human's yes (exit 3) — soft scan\n // findings, or `review` mode always. NEEDS_CONFIRMATION clears with --yes;\n // PUBLISH_BLOCKED is a hard-block finding (a live secret) that no mode or --yes\n // ever clears. PUBLISH_FAILED (exit 4) is a write that failed AFTER approval,\n // mirroring PAYMENT_FAILED's post-decision failure class.\n 'NEEDS_CONFIRMATION',\n 'PUBLISH_BLOCKED',\n 'PUBLISH_FAILED',\n // A send that reverted or produced no receipt AFTER the human approved it and\n // it was broadcast (exit 4), same post-decision class as PAYMENT_FAILED.\n 'SEND_FAILED',\n // `tenjin delete`: the soft-delete failed AFTER the human confirmed it (exit\n // 4). Its own code rather than PUBLISH_FAILED because the two say opposite\n // things about what is now live, and an agent reporting the outcome to a user\n // must not read \"the piece is still up\" as \"the piece went up\".\n 'DELETE_FAILED',\n // `tenjin update`: the npm install it spawned exited nonzero or never started.\n // Exit 1, not the post-decision class: nothing is half-written that the\n // operator must reconcile, and the old build keeps running.\n 'UPDATE_FAILED',\n // `tenjin pay` Bazaar lane: the live 402 does not match what a configured\n // registry publicly advertises for this resource (understood-but-refused, 3);\n // nothing was signed and nothing was spent.\n 'REGISTRY_MISMATCH',\n // The seller's 402 challenge exceeds this process's response-header limit, so\n // its terms could never be read (understood-but-refused, 3). Nothing was\n // signed and nothing was sent; a retry changes nothing without an operator\n // raising `--max-http-header-size` on the process that runs the CLI.\n 'CHALLENGE_TOO_LARGE',\n]);\nexport type ErrorCode = z.infer<typeof ErrorCodeSchema>;\n\n/**\n * All money in machine output is dual-form: `atomic` is the 6-decimal USDC base\n * unit as a decimal string (never a JS number — precision), `usd` is the same\n * value formatted as decimal dollars. Emit both so agents compute on `atomic`\n * and humans read `usd` without either side re-deriving the other.\n */\nexport const MoneySchema = z.object({\n atomic: z.string(),\n usd: z.string(),\n});\nexport type Money = z.infer<typeof MoneySchema>;\n\nexport const OutputErrorSchema = z.object({\n code: ErrorCodeSchema,\n message: z.string(),\n fix: z.string().optional(),\n details: z.unknown().optional(),\n});\nexport type OutputError = z.infer<typeof OutputErrorSchema>;\n\n/**\n * \"A newer tenjin-cli exists\", carried on the envelope so an AGENT learns it.\n *\n * The daily check's other surface is one dim stderr line, which only a human at\n * a terminal ever sees; on the machines that run this CLI most, nobody does.\n * This field is how the agent driving the command finds out it can run\n * `tenjin update` itself. Read from the check's cache, never fetched here: the\n * envelope must not wait on a network call it did not need.\n */\nexport const UpdateAvailableSchema = z.object({\n current: z.string(),\n latest: z.string(),\n});\nexport type UpdateAvailable = z.infer<typeof UpdateAvailableSchema>;\n\nexport const SuccessEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(true),\n data: z.unknown(),\n /** Present only when a newer version is known and update.mode is not `off`. */\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type SuccessEnvelope = z.infer<typeof SuccessEnvelopeSchema>;\n\nexport const FailureEnvelopeSchema = z.object({\n schemaVersion: z.literal(SCHEMA_VERSION),\n command: z.string(),\n ok: z.literal(false),\n error: OutputErrorSchema,\n updateAvailable: UpdateAvailableSchema.optional(),\n});\nexport type FailureEnvelope = z.infer<typeof FailureEnvelopeSchema>;\n\n/** The one thing every invocation prints to stdout, discriminated on `ok`. */\nexport const OutputEnvelopeSchema = z.discriminatedUnion('ok', [\n SuccessEnvelopeSchema,\n FailureEnvelopeSchema,\n]);\nexport type OutputEnvelope = z.infer<typeof OutputEnvelopeSchema>;\n"],"mappings":";;;;;;;AAAA,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;;;ACMnB,IAAM,iBAAiB;AAQvB,IAAM,kBAAkB,iBAAE,KAAK;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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S,MAAM,QAAqB,MAAc,SAAkB,QAAQ,QAAgB;AACjG,SAAO,aAAa,MAAM,IAAI,UAAU,QAAQ,MAAM,EAAE,gBAAgB,MAAM,CAAC,IAAI;AACrF;AAGO,SAAS,MAAM,IAAQ,QAAqB,MAAsB;AACvE,SAAO,MAAM,QAAQ,MAAM,GAAG,MAAM;AACtC;","names":[]}
@@ -1,24 +1,22 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  setTenjinIdentity
4
- } from "./chunk-OHZYNZSD.js";
4
+ } from "./chunk-RJEPZMYY.js";
5
5
  import {
6
6
  hasCode
7
7
  } from "./chunk-2I4QTOLB.js";
8
8
  import {
9
9
  isTeamModeConfig
10
- } from "./chunk-G4AM2SOL.js";
10
+ } from "./chunk-AMEUXNJT.js";
11
11
  import {
12
12
  knownDeploymentOrigins,
13
13
  loadRawConfig,
14
- resolveSettings
15
- } from "./chunk-VIOUZW7Z.js";
16
- import {
14
+ resolveSettings,
17
15
  writeFileAtomicExclusive
18
- } from "./chunk-JLEF5WHM.js";
16
+ } from "./chunk-VVAHFCX2.js";
19
17
  import {
20
18
  installIdPath
21
- } from "./chunk-K6AXXYCG.js";
19
+ } from "./chunk-SJLTEINJ.js";
22
20
 
23
21
  // src/lib/install-identity.ts
24
22
  import { randomUUID } from "node:crypto";
@@ -109,4 +107,4 @@ export {
109
107
  enableCliIdentity,
110
108
  enableDaemonIdentity
111
109
  };
112
- //# sourceMappingURL=chunk-SKQQOEWH.js.map
110
+ //# sourceMappingURL=chunk-USOLCBKC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/install-identity.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { writeFileAtomicExclusive } from './atomic-json';\nimport { loadRawConfig, resolveSettings } from './config';\nimport { hasCode } from './errno';\nimport { setTenjinIdentity, type TenjinIdentity } from './http';\nimport { installIdPath } from './paths';\nimport { knownDeploymentOrigins } from './production-origin';\nimport { isTeamModeConfig } from './settings';\n\n/**\n * The install id the transport attaches to Tenjin-bound requests (see\n * `TenjinIdentity` in lib/http), and the rule for which origins are Tenjin's.\n *\n * Nothing here may fail a request: every read that goes wrong is an absent\n * header. There is no opt-out for alpha; the id is random, anonymous, and not a\n * credential.\n */\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction parseInstallId(raw: string): string | undefined {\n const id = raw.trim();\n return UUID_RE.test(id) ? id : undefined;\n}\n\n/**\n * This data dir's install id, minted on first need. Created no-clobber, so two\n * processes racing on a first run agree on the winner's id rather than each\n * keeping its own. A file that exists but does not hold a UUID is left alone and\n * sends nothing: overwriting it would be a new id for the same install.\n */\nexport async function readOrCreateInstallId(dir: string): Promise<string | undefined> {\n const path = installIdPath(dir);\n try {\n return parseInstallId(await readFile(path, 'utf8'));\n } catch (err) {\n if (!hasCode(err, 'ENOENT')) return undefined;\n }\n const id = randomUUID();\n try {\n await writeFileAtomicExclusive(path, `${id}\\n`, { mode: 0o600, dirMode: 0o700 });\n return id;\n } catch (err) {\n if (!hasCode(err, 'EEXIST')) return undefined;\n }\n try {\n return parseInstallId(await readFile(path, 'utf8'));\n } catch {\n return undefined;\n }\n}\n\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The origins that get the header: Tenjin's own deployments and the base URL\n * this run is pointed at, overrides included (a local dev server is Tenjin too).\n * Not `publicShelfUrl`: its default is already one of Tenjin's deployments, and\n * a custom one may be a host Tenjin does not run.\n *\n * NOT a team shelf. In team mode `baseUrl` is the team's own deployment, which\n * Tenjin does not operate, so on a team machine the base URL is left out unless\n * it is one of Tenjin's own origins anyway. `isTeamModeConfig` reads the file,\n * so a `--base-url` on one run cannot switch that exclusion off.\n */\nexport function tenjinOrigins(s: { baseUrl: string; teamMode: boolean }): string[] {\n const origins = new Set(knownDeploymentOrigins());\n const baseOrigin = tryOrigin(s.baseUrl);\n if (baseOrigin !== undefined && !s.teamMode) origins.add(baseOrigin);\n return [...origins];\n}\n\n/** An identity for one data dir. The install id is read once per process. */\nexport function identityFor(\n dir: string,\n origins: () => Promise<readonly string[]>,\n): TenjinIdentity {\n let install: Promise<string | undefined> | undefined;\n return {\n origins,\n installId: () => (install ??= readOrCreateInstallId(dir)),\n };\n}\n\n/**\n * The run's `--base-url`, recorded by the CLI once it has parsed the global\n * flags. The origins are resolved on the first request, which comes after that.\n */\nlet baseUrlFlag: string | undefined;\n\nexport function noteBaseUrlFlag(flag: string | undefined): void {\n baseUrlFlag = flag;\n}\n\n/**\n * Turn the header on for this CLI process. Called from the entry only, never\n * from `main`, so in-process tests of the command tree never mint an id.\n */\nexport function enableCliIdentity(dir: string, env: NodeJS.ProcessEnv = process.env): void {\n let origins: Promise<readonly string[]> | undefined;\n setTenjinIdentity(\n identityFor(dir, () => {\n origins ??= (async () => {\n const config = await loadRawConfig(dir);\n const s = resolveSettings({ config, flags: { baseUrl: baseUrlFlag }, env });\n return tenjinOrigins({\n baseUrl: s.baseUrl.value,\n teamMode: isTeamModeConfig(config),\n });\n })();\n return origins;\n }),\n );\n}\n\n/**\n * Turn the header on for the loop daemon. No flag or env layer, like the rest\n * of the daemon's config, and re-read per request because the daemon reloads\n * config.json when it changes.\n */\nexport function enableDaemonIdentity(\n dir: string,\n config: () => { baseUrl: string; publicShelfUrl: string; shelfBypassSecret: string },\n): void {\n setTenjinIdentity(\n identityFor(dir, async () => {\n const c = config();\n return tenjinOrigins({\n baseUrl: c.baseUrl,\n teamMode: isTeamModeConfig(c),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AAkBzB,IAAM,UAAU;AAEhB,SAAS,eAAe,KAAiC;AACvD,QAAM,KAAK,IAAI,KAAK;AAC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C,cAAM,IAAI,gBAAgB,EAAE,QAAQ,OAAO,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;AAC1E,eAAO,cAAc;AAAA,UACnB,SAAS,EAAE,QAAQ;AAAA,UACnB,UAAU,iBAAiB,MAAM;AAAA,QACnC,CAAC;AAAA,MACH,GAAG;AACH,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;AAOO,SAAS,qBACd,KACA,QACM;AACN;AAAA,IACE,YAAY,KAAK,YAAY;AAC3B,YAAM,IAAI,OAAO;AACjB,aAAO,cAAc;AAAA,QACnB,SAAS,EAAE;AAAA,QACX,UAAU,iBAAiB,CAAC;AAAA,MAC9B,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/lib/install-identity.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { readFile } from 'node:fs/promises';\nimport { writeFileAtomicExclusive } from './atomic-json';\nimport { loadRawConfig, resolveSettings } from './config';\nimport { hasCode } from './errno';\nimport { setTenjinIdentity, type TenjinIdentity } from './http';\nimport { installIdPath } from './paths';\nimport { knownDeploymentOrigins } from './production-origin';\nimport { isTeamModeConfig } from './settings';\n\n/**\n * The install id the transport attaches to Tenjin-bound requests (see\n * `TenjinIdentity` in lib/http), and the rule for which origins are Tenjin's.\n *\n * Nothing here may fail a request: every read that goes wrong is an absent\n * header. There is no opt-out for alpha; the id is random, anonymous, and not a\n * credential.\n */\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nfunction parseInstallId(raw: string): string | undefined {\n const id = raw.trim();\n return UUID_RE.test(id) ? id : undefined;\n}\n\n/**\n * This data dir's install id, minted on first need. Created no-clobber, so two\n * processes racing on a first run agree on the winner's id rather than each\n * keeping its own. A file that exists but does not hold a UUID is left alone and\n * sends nothing: overwriting it would be a new id for the same install.\n */\nexport async function readOrCreateInstallId(dir: string): Promise<string | undefined> {\n const path = installIdPath(dir);\n try {\n return parseInstallId(await readFile(path, 'utf8'));\n } catch (err) {\n if (!hasCode(err, 'ENOENT')) return undefined;\n }\n const id = randomUUID();\n try {\n await writeFileAtomicExclusive(path, `${id}\\n`, { mode: 0o600, dirMode: 0o700 });\n return id;\n } catch (err) {\n if (!hasCode(err, 'EEXIST')) return undefined;\n }\n try {\n return parseInstallId(await readFile(path, 'utf8'));\n } catch {\n return undefined;\n }\n}\n\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The origins that get the header: Tenjin's own deployments and the base URL\n * this run is pointed at, overrides included (a local dev server is Tenjin too).\n * Not `publicShelfUrl`: its default is already one of Tenjin's deployments, and\n * a custom one may be a host Tenjin does not run.\n *\n * NOT a team shelf. In team mode `baseUrl` is the team's own deployment, which\n * Tenjin does not operate, so on a team machine the base URL is left out unless\n * it is one of Tenjin's own origins anyway. `isTeamModeConfig` reads the file,\n * so a `--base-url` on one run cannot switch that exclusion off.\n */\nexport function tenjinOrigins(s: { baseUrl: string; teamMode: boolean }): string[] {\n const origins = new Set(knownDeploymentOrigins());\n const baseOrigin = tryOrigin(s.baseUrl);\n if (baseOrigin !== undefined && !s.teamMode) origins.add(baseOrigin);\n return [...origins];\n}\n\n/** An identity for one data dir. The install id is read once per process. */\nexport function identityFor(\n dir: string,\n origins: () => Promise<readonly string[]>,\n): TenjinIdentity {\n let install: Promise<string | undefined> | undefined;\n return {\n origins,\n installId: () => (install ??= readOrCreateInstallId(dir)),\n };\n}\n\n/**\n * The run's `--base-url`, recorded by the CLI once it has parsed the global\n * flags. The origins are resolved on the first request, which comes after that.\n */\nlet baseUrlFlag: string | undefined;\n\nexport function noteBaseUrlFlag(flag: string | undefined): void {\n baseUrlFlag = flag;\n}\n\n/**\n * Turn the header on for this CLI process. Called from the entry only, never\n * from `main`, so in-process tests of the command tree never mint an id.\n */\nexport function enableCliIdentity(dir: string, env: NodeJS.ProcessEnv = process.env): void {\n let origins: Promise<readonly string[]> | undefined;\n setTenjinIdentity(\n identityFor(dir, () => {\n origins ??= (async () => {\n const config = await loadRawConfig(dir);\n const s = resolveSettings({ config, flags: { baseUrl: baseUrlFlag }, env });\n return tenjinOrigins({\n baseUrl: s.baseUrl.value,\n teamMode: isTeamModeConfig(config),\n });\n })();\n return origins;\n }),\n );\n}\n\n/**\n * Turn the header on for the loop daemon. No flag or env layer, like the rest\n * of the daemon's config, and re-read per request because the daemon reloads\n * config.json when it changes.\n */\nexport function enableDaemonIdentity(\n dir: string,\n config: () => { baseUrl: string; publicShelfUrl: string; shelfBypassSecret: string },\n): void {\n setTenjinIdentity(\n identityFor(dir, async () => {\n const c = config();\n return tenjinOrigins({\n baseUrl: c.baseUrl,\n teamMode: isTeamModeConfig(c),\n });\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AAkBzB,IAAM,UAAU;AAEhB,SAAS,eAAe,KAAiC;AACvD,QAAM,KAAK,IAAI,KAAK;AACpB,SAAO,QAAQ,KAAK,EAAE,IAAI,KAAK;AACjC;AAQA,eAAsB,sBAAsB,KAA0C;AACpF,QAAM,OAAO,cAAc,GAAG;AAC9B,MAAI;AACF,WAAO,eAAe,MAAM,SAAS,MAAM,MAAM,CAAC;AAAA,EACpD,SAAS,KAAK;AACZ,QAAI,CAAC,QAAQ,KAAK,QAAQ,EAAG,QAAO;AAAA,EACtC;AACA,QAAM,KAAK,WAAW;AACtB,MAAI;AACF,UAAM,yBAAyB,MAAM,GAAG,EAAE;AAAA,GAAM,EAAE,MAAM,KAAO,SAAS,IAAM,CAAC;AAC/E,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,CAAC,QAAQ,KAAK,QAAQ,EAAG,QAAO;AAAA,EACtC;AACA,MAAI;AACF,WAAO,eAAe,MAAM,SAAS,MAAM,MAAM,CAAC;AAAA,EACpD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,UAAU,KAAiC;AAClD,MAAI;AACF,WAAO,IAAI,IAAI,GAAG,EAAE;AAAA,EACtB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAaO,SAAS,cAAc,GAAqD;AACjF,QAAM,UAAU,IAAI,IAAI,uBAAuB,CAAC;AAChD,QAAM,aAAa,UAAU,EAAE,OAAO;AACtC,MAAI,eAAe,UAAa,CAAC,EAAE,SAAU,SAAQ,IAAI,UAAU;AACnE,SAAO,CAAC,GAAG,OAAO;AACpB;AAGO,SAAS,YACd,KACA,SACgB;AAChB,MAAI;AACJ,SAAO;AAAA,IACL;AAAA,IACA,WAAW,MAAO,YAAY,sBAAsB,GAAG;AAAA,EACzD;AACF;AAMA,IAAI;AAEG,SAAS,gBAAgB,MAAgC;AAC9D,gBAAc;AAChB;AAMO,SAAS,kBAAkB,KAAa,MAAyB,QAAQ,KAAW;AACzF,MAAI;AACJ;AAAA,IACE,YAAY,KAAK,MAAM;AACrB,mBAAa,YAAY;AACvB,cAAM,SAAS,MAAM,cAAc,GAAG;AACtC,cAAM,IAAI,gBAAgB,EAAE,QAAQ,OAAO,EAAE,SAAS,YAAY,GAAG,IAAI,CAAC;AAC1E,eAAO,cAAc;AAAA,UACnB,SAAS,EAAE,QAAQ;AAAA,UACnB,UAAU,iBAAiB,MAAM;AAAA,QACnC,CAAC;AAAA,MACH,GAAG;AACH,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AACF;AAOO,SAAS,qBACd,KACA,QACM;AACN;AAAA,IACE,YAAY,KAAK,YAAY;AAC3B,YAAM,IAAI,OAAO;AACjB,aAAO,cAAc;AAAA,QACnB,SAAS,EAAE;AAAA,QACX,UAAU,iBAAiB,CAAC;AAAA,MAC9B,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACF;","names":[]}
@@ -2,10 +2,10 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  fetchFailureToCliError,
4
4
  httpRequest
5
- } from "./chunk-OHZYNZSD.js";
5
+ } from "./chunk-RJEPZMYY.js";
6
6
  import {
7
7
  external_exports
8
- } from "./chunk-VIOUZW7Z.js";
8
+ } from "./chunk-VVAHFCX2.js";
9
9
 
10
10
  // src/router/decision.ts
11
11
  var ROUTER_PATH = "/api/x402-router";
@@ -74,9 +74,52 @@ var DiscoveredCandidateSchema = external_exports.strictObject({
74
74
  schema: external_exports.record(external_exports.string(), external_exports.unknown())
75
75
  })
76
76
  });
77
+ var JobField = external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);
78
+ var JobFieldStateSchema = external_exports.strictObject({
79
+ field: JobField,
80
+ values: external_exports.array(external_exports.string().min(1).max(64)).min(1).max(8)
81
+ });
82
+ var POLL_REFERENCE = /^\$(input|result)\.([A-Za-z_][A-Za-z0-9_]{0,63})$/;
83
+ var JobSchema = external_exports.strictObject({
84
+ pollUrl: external_exports.union([
85
+ external_exports.strictObject({
86
+ field: JobField.optional(),
87
+ header: external_exports.string().regex(/^[A-Za-z0-9-]{1,64}$/).optional()
88
+ }).refine((at) => at.field !== void 0 || at.header !== void 0, "a field or a header"),
89
+ external_exports.strictObject({ fixed: external_exports.string().min(1).max(2048) })
90
+ ]),
91
+ /** Sent once like a poll after the result is saved, never after a save
92
+ * that failed: it frees the seller's copy (AiSpace's `/complete`). Its
93
+ * answer is ignored. */
94
+ completeUrl: external_exports.strictObject({ fixed: external_exports.string().min(1).max(2048) }).optional(),
95
+ pollMethod: external_exports.enum(["GET", "POST"]),
96
+ pollBody: external_exports.record(JobField, external_exports.unknown()).refine(
97
+ (body) => Object.values(body).every(
98
+ (value) => typeof value !== "string" || !value.startsWith("$") || POLL_REFERENCE.test(value)
99
+ ),
100
+ "a $ value is $input.<field> or $result.<field>"
101
+ ).optional(),
102
+ running: external_exports.union([
103
+ external_exports.strictObject({ httpStatus: external_exports.array(external_exports.number().int().min(200).max(299)).min(1).max(8) }),
104
+ JobFieldStateSchema
105
+ ]),
106
+ failed: JobFieldStateSchema.optional(),
107
+ everyS: external_exports.number().int().min(1).max(30),
108
+ maxWaitS: external_exports.number().int().min(1).max(600),
109
+ keepH: external_exports.number().int().min(1).max(48),
110
+ always: external_exports.literal(true).optional()
111
+ }).refine((job) => !job.pollBody || job.pollMethod === "POST", "only a POST poll has a body");
77
112
  var ToolSpecSchema = external_exports.strictObject({
78
113
  capabilityId: external_exports.string().min(1).max(200),
79
114
  provider: external_exports.string().min(1).max(120),
115
+ /** The input field that takes a pending search's query or fetch's URL. */
116
+ holds: external_exports.strictObject({
117
+ WebSearch: external_exports.string().min(1).max(64).optional(),
118
+ WebFetch: external_exports.string().min(1).max(64).optional()
119
+ }).optional(),
120
+ /** What a paid result is. `media` means its files (bytes, links or inline
121
+ * base64) are saved locally; absent on a Bazaar spec. */
122
+ output: external_exports.enum(["json", "text", "media"]).optional(),
80
123
  description: external_exports.string().min(1).max(500),
81
124
  priceAtomic: external_exports.string().regex(/^\d+$/),
82
125
  priceVaries: external_exports.boolean(),
@@ -98,7 +141,11 @@ var ToolSpecSchema = external_exports.strictObject({
98
141
  resultSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
99
142
  /** The fields the result promises (type, properties, items, required). The
100
143
  * agent is handed only these; the whole body is saved to a file. */
101
- outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional()
144
+ outputSchema: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
145
+ /** How a call answered before its result is ready is finished. */
146
+ job: JobSchema.optional(),
147
+ /** A media service that runs several takes of one call: `count` up to `max`. */
148
+ takes: external_exports.strictObject({ max: external_exports.number().int().min(2).max(5) }).optional()
102
149
  });
103
150
  var OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });
104
151
  var SpecsSchema = external_exports.array(OfferSpecSchema).min(1).max(8).optional();
@@ -204,7 +251,7 @@ function envelope(decision) {
204
251
  }
205
252
  var HookResponseSchema = envelope(HookDecisionSchema);
206
253
  var ToolResponseSchema = envelope(ToolDecisionSchema);
207
- var CLIENT_ACCEPTS = ["discovered", "spec", "choices"];
254
+ var CLIENT_ACCEPTS = ["catalog", "spec", "jobs"];
208
255
  var BAZAAR_ACCEPT = "bazaar";
209
256
  function acceptsFor(bazaar) {
210
257
  return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];
@@ -352,6 +399,8 @@ function isUnreachable(failure) {
352
399
 
353
400
  export {
354
401
  ROUTER_PATH,
402
+ POLL_REFERENCE,
403
+ JobSchema,
355
404
  OfferSpecSchema,
356
405
  ChoicesSchema,
357
406
  ALL_CHOICES,
@@ -364,4 +413,4 @@ export {
364
413
  reportSpecOutcome,
365
414
  isUnreachable
366
415
  };
367
- //# sourceMappingURL=chunk-64SE3QC5.js.map
416
+ //# sourceMappingURL=chunk-VKQXVCZR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { FetchJsonFailure, HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE DECISION PER LOOKUP. On the free path it costs\n * nothing. Inside `tenjin mcp`, while the server answers its paid path, the\n * same body goes to that path through the stock x402 client\n * ({@link DecisionRoute}, `routing-payer.ts`); a call that path cannot take\n * falls back to the free path. The rest of this note describes the free path,\n * which is unchanged.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * The bounded packet travels with the hook request and the backend keeps it\n * against the decision id until that id expires. What this client keeps is\n * each offer's spec, by its id (`specs.ts`).\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\n/**\n * STRUCTURE, NEVER WORDING. A hint lands in the model's context verbatim, so\n * its shape is checked the way the id's alphabet is: one line, no control\n * characters, and it has to be the call it claims to be, naming the id this\n * same answer carries. A hint that fails any of these is a protocol error and\n * the turn falls back to the generic line; nothing here rewrites a word of a\n * hint that passes. Both offering arms, `execute` and `discovered`, hold it.\n */\nfunction checkHint(decision: { id: string; hint: string }, ctx: z.RefinementCtx): void {\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n}\n\n/**\n * A PAY-PER-CALL SERVICE NOBODY CURATED. When a Tenjin list service does the\n * task the gate picked, or no task fits and a listed x402 service could do the\n * step, the server names that one service: who sells it, where, for how much,\n * and the input it takes. A Tenjin list service arrives here under its catalog\n * id, because this build sends `catalog`. The candidate is the seller's own\n * listing, so every field is data for the host to judge, never an instruction;\n * the host builds the `input` and the tool call pays through the same `runPay`\n * path and caps as a curated lookup.\n */\nconst DiscoveredCandidateSchema = z.strictObject({\n source: z.string().min(1).max(64),\n provider: z.string().min(1).max(120),\n url: z.string().min(1).max(2_048),\n method: z.enum(['GET', 'POST']),\n description: z.string().max(500),\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n network: z.string().min(1).max(64),\n payTo: z.string().min(1).max(200),\n input: z.strictObject({\n location: z.enum(['body', 'query']),\n schema: z.record(z.string(), z.unknown()),\n }),\n});\n\n/** A field name a job reads from an answer or writes into a poll body. */\nconst JobField = z.string().regex(/^[A-Za-z_][A-Za-z0-9_]{0,63}$/);\n\n/** A body field whose value names a state: Treza's `status: \"running\"`. */\nconst JobFieldStateSchema = z.strictObject({\n field: JobField,\n values: z.array(z.string().min(1).max(64)).min(1).max(8),\n});\n\n/** A poll body value naming a field of the call's input or of the submit's\n * answer; any other value is sent as written. */\nexport const POLL_REFERENCE = /^\\$(input|result)\\.([A-Za-z_][A-Za-z0-9_]{0,63})$/;\n\n/**\n * HOW A CALL WHOSE SELLER ANSWERS BEFORE THE RESULT IS READY IS FINISHED, sent\n * on a spec only because this build asks for it (`accepts: [\"jobs\"]`): where\n * the status is (a field or header of the submit's answer, or one fixed URL),\n * how a poll is sent, what says it is still running or failed, how often and\n * how long to poll, and how many hours the job can be resumed. `always`: the\n * seller never answers inline. A poll is never signed: the take's one payment\n * is its submit. Every field is the server's: the poll and complete URLs are\n * still checked here against the submit's host (`jobs.ts`).\n */\nexport const JobSchema = z\n .strictObject({\n pollUrl: z.union([\n z\n .strictObject({\n field: JobField.optional(),\n header: z\n .string()\n .regex(/^[A-Za-z0-9-]{1,64}$/)\n .optional(),\n })\n .refine((at) => at.field !== undefined || at.header !== undefined, 'a field or a header'),\n z.strictObject({ fixed: z.string().min(1).max(2_048) }),\n ]),\n /** Sent once like a poll after the result is saved, never after a save\n * that failed: it frees the seller's copy (AiSpace's `/complete`). Its\n * answer is ignored. */\n completeUrl: z.strictObject({ fixed: z.string().min(1).max(2_048) }).optional(),\n pollMethod: z.enum(['GET', 'POST']),\n pollBody: z\n .record(JobField, z.unknown())\n .refine(\n (body) =>\n Object.values(body).every(\n (value) =>\n typeof value !== 'string' || !value.startsWith('$') || POLL_REFERENCE.test(value),\n ),\n 'a $ value is $input.<field> or $result.<field>',\n )\n .optional(),\n running: z.union([\n z.strictObject({ httpStatus: z.array(z.number().int().min(200).max(299)).min(1).max(8) }),\n JobFieldStateSchema,\n ]),\n failed: JobFieldStateSchema.optional(),\n everyS: z.number().int().min(1).max(30),\n maxWaitS: z.number().int().min(1).max(600),\n keepH: z.number().int().min(1).max(48),\n always: z.literal(true).optional(),\n })\n .refine((job) => !job.pollBody || job.pollMethod === 'POST', 'only a POST poll has a body');\nexport type Job = z.infer<typeof JobSchema>;\n\n/**\n * A REQUEST SPEC: the offered service's real contract, sent beside the line only\n * because this build asks for it (`accepts: [\"spec\"]`). The hook stores it by\n * the offer's id; `request({id})` shows it and `request({id, input})` fills its\n * request and pays the provider directly, with no second decision. Every field\n * is the server's, and so is checked like the rest of the answer: the payee and\n * price still meet the live 402 and the spend policy in `runPay`.\n */\nexport const ToolSpecSchema = z.strictObject({\n capabilityId: z.string().min(1).max(200),\n provider: z.string().min(1).max(120),\n /** The input field that takes a pending search's query or fetch's URL. */\n holds: z\n .strictObject({\n WebSearch: z.string().min(1).max(64).optional(),\n WebFetch: z.string().min(1).max(64).optional(),\n })\n .optional(),\n /** What a paid result is. `media` means its files (bytes, links or inline\n * base64) are saved locally; absent on a Bazaar spec. */\n output: z.enum(['json', 'text', 'media']).optional(),\n description: z.string().min(1).max(500),\n priceAtomic: z.string().regex(/^\\d+$/),\n priceVaries: z.boolean(),\n maxAmountAtomic: z.string().regex(/^\\d+$/),\n payTo: z.string().min(1).max(200),\n network: z.string().min(1).max(64),\n asset: z.string().min(1).max(200),\n request: z.strictObject({\n method: z.enum(['GET', 'POST']),\n url: z.string().min(1).max(2_048),\n fields: z.record(z.string(), z.enum(['path', 'query', 'body'])),\n location: z.enum(['query', 'body']),\n }),\n input: z.record(z.string(), z.unknown()),\n pinned: z.record(z.string(), z.unknown()),\n example: z.record(z.string(), z.unknown()).optional(),\n returns: z.string().min(1).max(200).optional(),\n returnsExample: z.unknown().optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n /** The fields the result promises (type, properties, items, required). The\n * agent is handed only these; the whole body is saved to a file. */\n outputSchema: z.record(z.string(), z.unknown()).optional(),\n /** How a call answered before its result is ready is finished. */\n job: JobSchema.optional(),\n /** A media service that runs several takes of one call: `count` up to `max`. */\n takes: z.strictObject({ max: z.number().int().min(2).max(5) }).optional(),\n});\nexport type ToolSpec = z.infer<typeof ToolSpecSchema>;\n\nexport const OfferSpecSchema = ToolSpecSchema.extend({ id: IdSchema });\nexport type OfferSpec = z.infer<typeof OfferSpecSchema>;\n\n/** One spec per service the line names: the offer, any other service it\n * lists, and each option of a choice set. */\nconst SpecsSchema = z.array(OfferSpecSchema).min(1).max(8).optional();\n\n/** Words this client shows the model itself, in its own line: one plain line. */\nconst PlainLine = (max: number) =>\n z\n .string()\n .min(1)\n .max(max)\n .refine((text) => !/[\\p{Cc}\\p{Cf}]/u.test(text), 'one plain line');\n\n/**\n * SERVICES THE USER PICKS BETWEEN, OR RUNS ALL OF. Sent only beside a\n * discovered offer, to a build that lists `catalog` in `accepts`. Each option\n * is a real offer: its own id, its own spec in `specs`, and its own one\n * payment, so `request({id, choice})` runs exactly the spec\n * `request({id: option.id})` would. `all` runs every option side by side, one\n * payment each. The set is the server's data: changing it is a deploy there,\n * not a release here. `input` names the open fields the options share, the\n * only ones an `all` call may carry.\n */\nexport const ChoicesSchema = z.strictObject({\n group: PlainLine(64),\n default: PlainLine(64),\n input: z.array(PlainLine(64)).min(1).max(16),\n options: z\n .array(\n z.strictObject({\n key: PlainLine(64),\n label: PlainLine(120),\n strength: PlainLine(300),\n id: IdSchema,\n }),\n )\n .min(2)\n .max(4),\n all: z.strictObject({ totalAtomic: z.string().regex(/^\\d+$/) }),\n});\nexport type Choices = z.infer<typeof ChoicesSchema>;\n\n/** The word that runs every option, so no option may take it as its key. */\nexport const ALL_CHOICES = 'all';\n\n/**\n * A CHOICE NAMES ONLY WHAT THIS ANSWER CARRIES: each key and id once, `all`\n * free for the whole set, a spec for every option, and the default option is\n * the offer this answer's id already names. A set that breaks any of these is\n * a protocol error, and the turn falls back like any unreadable answer.\n */\nfunction checkChoices(\n decision: { id: string; specs?: { id: string }[] | undefined; choices?: Choices | undefined },\n ctx: z.RefinementCtx,\n): void {\n const { choices } = decision;\n if (choices === undefined) return;\n const issue = (message: string) => ctx.addIssue({ code: 'custom', path: ['choices'], message });\n const keys = choices.options.map((option) => option.key);\n const ids = choices.options.map((option) => option.id);\n if (new Set(keys).size !== keys.length) issue('each choice key is named once');\n if (new Set(ids).size !== ids.length) issue('each choice id is named once');\n if (keys.includes(ALL_CHOICES)) issue(`\"${ALL_CHOICES}\" runs every choice, so it is no key`);\n const specIds = new Set((decision.specs ?? []).map((spec) => spec.id));\n if (ids.some((id) => !specIds.has(id))) issue('every choice carries its spec');\n const fallback = choices.options.find((option) => option.key === choices.default);\n if (fallback === undefined) issue('the default is one of the choices');\n else if (fallback.id !== decision.id) issue(\"the default choice is this answer's own offer\");\n}\n\n/** The same answer on both calls: the hook's offer, and the tool's answer\n * when a query with no id found a service nobody curated. */\nconst DiscoveredSchema = z\n .strictObject({\n action: z.literal('discovered'),\n id: IdSchema,\n candidate: DiscoveredCandidateSchema,\n /** THE LINE, FINISHED, as on `execute`: it carries the seller's\n * description and the input it takes. */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n choices: ChoicesSchema.optional(),\n })\n .superRefine(checkHint)\n .superRefine(checkChoices);\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift. The same\n * bound as a discovered line's.\n */\n hint: z.string().min(1).max(2_000),\n specs: SpecsSchema,\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n /**\n * A query with no id, answered with the spec of the service the server\n * picked under a fresh `id`: kept like a hook's, and never run in the same\n * call. `hint` is the line, with the skeleton of the next call:\n * `request({id, input: {...}})` with the required fields. `input` is what a\n * router from before the binder's removal still sends on a bound pick: it\n * is accepted so that answer parses, and never read, so it never runs.\n */\n z\n .strictObject({\n action: z.literal('spec'),\n id: IdSchema,\n spec: ToolSpecSchema,\n hint: z.string().min(1).max(2_000),\n input: z.record(z.string(), z.unknown()).optional(),\n })\n .superRefine(checkHint),\n DiscoveredSchema,\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * What this client can act on beyond the curated answers, sent on both calls.\n * `catalog` takes Tenjin's reviewed list of third-party services as\n * `discovered` offers under their catalog ids, with each spec's `holds` and\n * `output`, and `choices`, a set of options the user picks between or runs\n * all of, beside a discovered offer from a compare group. A build that sends\n * `discovered` in its place gets the same services under their\n * `discovered:tenjin:` ids. `spec` asks for each offered service's request\n * spec beside its line, and for the picked service's spec in place of a\n * decision on a query with no id, which only a build that parses them can\n * take: the decision schemas are strict. `jobs` asks for each spec's `job`,\n * for the services that never answer inline, and for `count` on a media\n * offer's line. `bazaar` widens discovery to the open Bazaar and is sent only\n * while `experimental.bazaar` is on.\n */\nexport const CLIENT_ACCEPTS: readonly string[] = ['catalog', 'spec', 'jobs'];\nexport const BAZAAR_ACCEPT = 'bazaar';\n\n/** The `accepts` this build sends, with the open Bazaar or without it. */\nexport function acceptsFor(bazaar: boolean): string[] {\n return bazaar ? [...CLIENT_ACCEPTS, BAZAAR_ACCEPT] : [...CLIENT_ACCEPTS];\n}\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone. `sessionId` is the harness's own session id, which the\n * server uses only so one session is not offered the same discovered service\n * twice.\n */\nexport function buildHookBody(\n packet: Packet,\n extras: { sessionId?: string; accepts?: readonly string[] } = {},\n): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(extras.sessionId !== undefined ? { sessionId: extras.sessionId } : {}),\n ...(extras.accepts !== undefined ? { accepts: [...extras.accepts] } : {}),\n packet,\n };\n}\n\n/** The exact body the tool call sends. `id` is the offer the query is for,\n * sent only for an offer with no spec kept; `gateHint` is evidence, never\n * authority. */\nexport function buildToolBody(request: {\n query?: string;\n id?: string;\n gateHint?: GateHint;\n accepts?: readonly string[];\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n ...(request.accepts !== undefined ? { accepts: [...request.accepts] } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n /** `experimental.bazaar`: add {@link BAZAAR_ACCEPT}, so a service from the\n * open Bazaar may come back. Off by default: curated and the Tenjin list. */\n acceptsBazaar?: boolean;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n /** The paid path, when `tenjin mcp` takes it: the body goes to `path` and is\n * sent by `send`, which pays the routing fee with the stock x402 client.\n * Absent is the free path. */\n route?: DecisionRoute;\n}\n\n/** How a routing call reaches the paid path. `send` throws\n * {@link RouteSkipped} when it has no paid answer for the call, which then\n * takes the free path. */\nexport interface DecisionRoute {\n path: string;\n send: (url: string, options: HttpRequestOptions) => Promise<HttpResult>;\n /** What this route's calls deposited into the routing channel and the\n * router took, 0n for none: the caller says so once, where it is read. */\n deposited?: () => bigint;\n}\n\n/** The paid path gave this call no answer: the wallet locked, low or over\n * its spend limits, the channel busy, or the payment failed. */\nexport class RouteSkipped extends Error {\n /** `unreached`: the paid call could not reach the router\n * ({@link isUnreachable}), so the free path, on the same host, is not\n * tried and the call reads as that transport failure. */\n constructor(\n readonly why: string,\n readonly unreached?: FetchJsonFailure,\n ) {\n super(`routing fee not paid: ${why}`);\n }\n}\n\n/** Another session's call was in flight on the wallet's routing channel. */\nexport const CHANNEL_BUSY = 'channel_busy';\n/** The server answered no paid path. */\nexport const PAID_PATH_ABSENT = 'paid_path_absent';\n/** The paid call got no answer, a refused payment or a server error. */\nexport const PAYMENT_FAILED = 'payment_failed';\n/** The payment went out and the call's budget ran out before its answer:\n * no fault. `tenjin mcp` lets the request finish, so it is recorded. */\nexport const DEADLINE_AFTER_PAYMENT_SENT = 'deadline_after_payment_sent';\n\nexport type DecisionOutcome<T> =\n /** `freePath`: the paid path skipped the call for this reason and it went\n * to the free path instead, unpaid. */\n | { status: 'decided'; decision: T; freePath?: string }\n /** On the free path nothing was paid and nothing could be, so a failure here\n * costs the turn a routing answer and nothing else. */\n | {\n status: 'failed';\n reason: string;\n errorCode?: string;\n freePath?: string;\n /** The router could not be reached at all ({@link isUnreachable}). */\n unreachable?: true;\n /** No answer came back at all: a transport failure or a timeout. */\n noAnswer?: true;\n }\n /** The paid path gave no answer ({@link RouteSkipped}) and no time was left\n * for the free path: the native tool runs. */\n | { status: 'skipped'; why: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id and answers with\n * each offered service's spec. The tool sends `{ query }`, which the backend\n * answers with the spec of the service its gate picks, or `{ query, id }` for\n * the free docs offer, which has no spec and is bound from the query. Every\n * provider call is built here, from a spec, or for the docs lookup by the\n * backend from the query.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet; sessionId?: string },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n sessionId?: string;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(deps.route?.path ?? ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet, {\n ...(request.sessionId !== undefined ? { sessionId: request.sessionId } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n })\n : buildToolBody({\n ...(request.query !== undefined ? { query: request.query } : {}),\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n accepts: acceptsFor(deps.acceptsBazaar === true),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n const started = Date.now();\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n let response: HttpResult;\n try {\n response = await (deps.route?.send ?? httpRequest)(url, options);\n } catch (err) {\n if (!(err instanceof RouteSkipped)) throw err;\n if (err.unreached !== undefined) return readDecision(err.unreached, schema);\n const left = options.timeoutMs - (Date.now() - started);\n if (left <= 0) return { status: 'skipped', why: err.why };\n // A CALL THE PAID PATH COULD NOT TAKE STILL ROUTES, on the free path,\n // unpaid, inside what is left of its budget, and says why.\n response = await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n ...options,\n timeoutMs: left,\n });\n const free = readDecision(response, schema);\n // A failure here ran on what a paid attempt left of the budget, so it says\n // nothing about the router being down: it never starts the backoff.\n if (free.status === 'failed') {\n return {\n status: 'failed',\n reason: free.reason,\n ...(free.errorCode !== undefined ? { errorCode: free.errorCode } : {}),\n // Still no answer, which must not end another call's backoff.\n ...(free.noAnswer === true ? { noAnswer: true as const } : {}),\n freePath: err.why,\n };\n }\n return free.status === 'skipped' ? free : { ...free, freePath: err.why };\n }\n return readDecision(response, schema);\n}\n\n/** Why a call from a spec stopped before anything was signed: the input did\n * not fit, the live terms were not the spec's, the provider answered\n * something else, it could not be reached, or the wallet could not pay. */\nexport type UnpaidReason = 'input' | 'terms' | 'provider' | 'unreachable' | 'wallet';\n\n/** How a call run from a request spec ended, for the server's offer-to-call\n * count. No text: the id, the outcome, the provider's status and the time. */\nexport interface SpecOutcome {\n id: string;\n /** `unpaid`: stopped before anything was signed, which the server never\n * counts as the offer taken. `running`: paid, and the seller was still\n * rendering when the call ended. */\n status: 'fulfilled' | 'unverified' | 'failed' | 'needs_approval' | 'unpaid' | 'running';\n /** On `unpaid` only, where the server requires it. */\n reason?: UnpaidReason;\n httpStatus?: number;\n ms?: number;\n}\n\n/** The outcome report's own deadline: it is telemetry and never holds a result. */\nexport const OUTCOME_TIMEOUT_MS = 3_000;\n\n/**\n * TELL THE SERVER A SPEC WAS USED. The client called and paid the provider\n * itself, so this is the only word the server gets that its offer was taken,\n * or that a call for it stopped before payment and why. Never throws and never\n * waits on anything the caller needs: a lost report costs one count.\n */\nexport async function reportSpecOutcome(\n outcome: SpecOutcome,\n deps: Pick<DecisionDeps, 'ctx' | 'baseUrl' | 'fetchImpl'>,\n): Promise<void> {\n try {\n await httpRequest(new URL(ROUTER_PATH, deps.baseUrl).toString(), {\n method: 'POST',\n timeoutMs: OUTCOME_TIMEOUT_MS,\n blockRedirects: true,\n jsonBody: buildOutcomeBody(outcome),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n } catch {\n // Telemetry only.\n }\n}\n\n/** The exact body of an outcome report, pinned to the shared fixtures. */\nexport function buildOutcomeBody(outcome: SpecOutcome): Record<string, unknown> {\n return {\n schemaVersion: 1,\n id: outcome.id,\n status: outcome.status,\n ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}),\n ...(outcome.httpStatus !== undefined ? { httpStatus: outcome.httpStatus } : {}),\n ...(outcome.ms !== undefined ? { ms: Math.max(0, Math.round(outcome.ms)) } : {}),\n };\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) {\n return {\n status: 'failed',\n reason: fetchFailureToCliError(response).message,\n ...(isUnreachable(response) ? { unreachable: true as const } : {}),\n ...(response.status === undefined ? { noAnswer: true as const } : {}),\n };\n }\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n\n/** A dropped socket, which a fresh connection usually gets past. */\nconst RESET_CODES = new Set(['ECONNRESET', 'UND_ERR_SOCKET']);\n\n/**\n * A ROUTER THAT CANNOT BE REACHED: the transport named the layer that refused\n * the connection (DNS, TLS, a refused connection, a proxy refusing the tunnel)\n * and no status came back. Never the call's own timeout: that is the gate's\n * few seconds, and a slow decision or a cold start must not take the router\n * away from every session. Never a status, even with a body that failed to\n * read, and never a reset socket, which the free path retries on a fresh one.\n */\nexport function isUnreachable(failure: FetchJsonFailure): boolean {\n return (\n failure.kind === 'network' &&\n failure.status === undefined &&\n failure.transport !== undefined &&\n !RESET_CODES.has(failure.transport.code ?? '')\n );\n}\n"],"mappings":";;;;;;;;;;AA2BO,IAAM,cAAc;AAO3B,IAAM,gBAAgB,iBAAE,OAAO;AAAA,EAC7B,KAAK,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,KAAM;AAAA,EACjC,QAAQ,iBAAE,KAAK,CAAC,OAAO,QAAQ,OAAO,SAAS,UAAU,QAAQ,SAAS,CAAC;AAAA,EAC3E,SAAS,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,OAAO,CAAC;AAAA,EACxC,MAAM,iBACH,OAAO,EACP,IAAI,MAAM,IAAI,EACd,SAAS;AACd,CAAC;AAED,IAAM,iBAAiB,iBAAE,OAAO;AAAA;AAAA;AAAA,EAG9B,WAAW,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACtD,cAAc,iBAAE,OAAO,iBAAE,OAAO,GAAG,iBAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACzD,SAAS;AACX,CAAC;AAQD,IAAM,oBAAoB,iBAAE,OAAO;AAAA,EACjC,YAAY,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EACpC,OAAO,iBAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,EAAE;AAAA,EAC/B,SAAS,iBAAE,MAAM,iBAAE,OAAO,EAAE,IAAI,GAAG,CAAC,EAAE,IAAI,EAAE;AAAA,EAC5C,YAAY,iBAAE,OAAO,EAAE,IAAI,GAAG;AAChC,CAAC;AAiBD,IAAM,WAAW,iBACd,OAAO,EACP,MAAM,uBAAuB,EAC7B;AAAA,EACC;AAGF;AAGF,IAAM,gBAAgB,iBAAE,aAAa;A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