tenjin-cli 0.1.0-alpha.23 → 0.1.0-alpha.25
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.
- package/NOTICE.md +1 -1
- package/README.md +7 -8
- package/dist/{chunk-Y3LKUXZA.js → chunk-3ZYPVSIU.js} +145 -36
- package/dist/chunk-3ZYPVSIU.js.map +1 -0
- package/dist/chunk-7EKYXMUO.js +7536 -0
- package/dist/chunk-7EKYXMUO.js.map +1 -0
- package/dist/chunk-AKWGE6JQ.js +49 -0
- package/dist/chunk-AKWGE6JQ.js.map +1 -0
- package/dist/{chunk-3IOS6YG6.js → chunk-CEMXMUIU.js} +3 -3
- package/dist/{chunk-NYJCBQL5.js → chunk-CKDD554V.js} +2 -2
- package/dist/{hook-command-RDT754KQ.js → chunk-CP7O6M55.js} +209 -41
- package/dist/chunk-CP7O6M55.js.map +1 -0
- package/dist/{chunk-YT7A7DLY.js → chunk-DRXDTITB.js} +1821 -141
- package/dist/chunk-DRXDTITB.js.map +1 -0
- package/dist/{chunk-HTC4VJFT.js → chunk-EACMJEF3.js} +206 -16
- package/dist/chunk-EACMJEF3.js.map +1 -0
- package/dist/{chunk-DHCOGDJB.js → chunk-EG7P4SM6.js} +4 -4
- package/dist/{chunk-RGVOODF4.js → chunk-EL56RW2J.js} +164 -7463
- package/dist/chunk-EL56RW2J.js.map +1 -0
- package/dist/{chunk-2RMXTNLT.js → chunk-EOGJKIOG.js} +6 -8
- package/dist/{chunk-2RMXTNLT.js.map → chunk-EOGJKIOG.js.map} +1 -1
- package/dist/{chunk-WXFVJPZD.js → chunk-GT6W3VJM.js} +2 -2
- package/dist/{chunk-UHEMZEGW.js → chunk-HII5HOQV.js} +3 -5
- package/dist/chunk-HII5HOQV.js.map +1 -0
- package/dist/{chunk-GONDQ27X.js → chunk-IYLECN4D.js} +3 -3
- package/dist/{chunk-6O6DFYF3.js → chunk-KGTQRJGS.js} +17 -8
- package/dist/chunk-KGTQRJGS.js.map +1 -0
- package/dist/chunk-LFZJM56J.js +159 -0
- package/dist/chunk-LFZJM56J.js.map +1 -0
- package/dist/{chunk-HJYI52HM.js → chunk-NTYQHAIM.js} +2 -2
- package/dist/{chunk-K63HPLYT.js → chunk-NYPFOHSJ.js} +4 -4
- package/dist/{chunk-RA2J3TWG.js → chunk-ODH7UXIS.js} +17 -14
- package/dist/chunk-ODH7UXIS.js.map +1 -0
- package/dist/{chunk-XBYTP4SP.js → chunk-OZ3LWLCI.js} +3 -3
- package/dist/{chunk-2QYORQBF.js → chunk-P7LABKCW.js} +36 -1
- package/dist/{chunk-2QYORQBF.js.map → chunk-P7LABKCW.js.map} +1 -1
- package/dist/{chunk-N7A5EXJZ.js → chunk-SCAE6PW6.js} +4 -4
- package/dist/{chunk-UGLTSPXQ.js → chunk-UDWGT4FX.js} +2 -2
- package/dist/chunk-VYONGSMQ.js +119 -0
- package/dist/chunk-VYONGSMQ.js.map +1 -0
- package/dist/{chunk-SAN5PFTL.js → chunk-XICKN3CH.js} +49 -4
- package/dist/chunk-XICKN3CH.js.map +1 -0
- package/dist/chunk-YHKXNYTB.js +105 -0
- package/dist/chunk-YHKXNYTB.js.map +1 -0
- package/dist/{chunk-I2GBBIDI.js → chunk-YSW57KUT.js} +46 -32
- package/dist/chunk-YSW57KUT.js.map +1 -0
- package/dist/{chunk-F4IJQBGP.js → chunk-YTM7OURD.js} +2 -2
- package/dist/{cli-MUYFTWWB.js → cli-4WMGZPBP.js} +28 -29
- package/dist/{cli-MUYFTWWB.js.map → cli-4WMGZPBP.js.map} +1 -1
- package/dist/{config-IIRRO3XC.js → config-VU6U7QOU.js} +10 -9
- package/dist/{doctor-KGHM2CAC.js → doctor-26JS2SG3.js} +124 -32
- package/dist/doctor-26JS2SG3.js.map +1 -0
- package/dist/{fund-DOWIT3JT.js → fund-JJN3FRRF.js} +13 -14
- package/dist/fund-JJN3FRRF.js.map +1 -0
- package/dist/hook-command-S2V4UNB3.js +28 -0
- package/dist/index.js +3 -3
- package/dist/{install-BYQUMYBN.js → install-GXQ33J4G.js} +20 -17
- package/dist/{install-identity-KTQPYVAO.js → install-identity-HFQUXPSI.js} +6 -7
- package/dist/{install-wallet-T737X74E.js → install-wallet-27LTEHBI.js} +9 -10
- package/dist/{install-wallet-T737X74E.js.map → install-wallet-27LTEHBI.js.map} +1 -1
- package/dist/{mcp-ZKOTURQN.js → mcp-AHCZVD2U.js} +604 -93
- package/dist/mcp-AHCZVD2U.js.map +1 -0
- package/dist/{pay-LZPU2HUT.js → pay-3TCOPGCX.js} +14 -13
- package/dist/{payments-26NVMFR2.js → payments-H3LSBGSL.js} +6 -7
- package/dist/{payments-26NVMFR2.js.map → payments-H3LSBGSL.js.map} +1 -1
- package/dist/{send-4RUBQQKP.js → send-LKCLN5GA.js} +9 -11
- package/dist/{send-4RUBQQKP.js.map → send-LKCLN5GA.js.map} +1 -1
- package/dist/{status-CEHZKHBU.js → status-2FDGI4LQ.js} +7 -9
- package/dist/{status-CEHZKHBU.js.map → status-2FDGI4LQ.js.map} +1 -1
- package/dist/{status-line-QRAO3Y2E.js → status-line-QKDJYZGV.js} +4 -5
- package/dist/{status-line-QRAO3Y2E.js.map → status-line-QKDJYZGV.js.map} +1 -1
- package/dist/{status-line-wiring-7D2CSV3K.js → status-line-wiring-ZDBYHNYR.js} +6 -4
- package/dist/{uninstall-VR44B4KD.js → uninstall-ZXWABDHS.js} +34 -30
- package/dist/uninstall-ZXWABDHS.js.map +1 -0
- package/dist/{update-SOYQLDBF.js → update-HEIWVOP5.js} +17 -6
- package/dist/update-HEIWVOP5.js.map +1 -0
- package/dist/{wallet-IB2EFAUP.js → wallet-T7JYWI6O.js} +8 -9
- package/dist/wallet-T7JYWI6O.js.map +1 -0
- package/docs/agent-permissions.md +11 -8
- package/docs/safety-model.md +10 -23
- package/package.json +16 -13
- package/dist/chunk-6O6DFYF3.js.map +0 -1
- package/dist/chunk-A2XMQSWI.js +0 -140
- package/dist/chunk-A2XMQSWI.js.map +0 -1
- package/dist/chunk-HTC4VJFT.js.map +0 -1
- package/dist/chunk-I2GBBIDI.js.map +0 -1
- package/dist/chunk-O2JYBOUO.js +0 -47
- package/dist/chunk-O2JYBOUO.js.map +0 -1
- package/dist/chunk-RA2J3TWG.js.map +0 -1
- package/dist/chunk-RGVOODF4.js.map +0 -1
- package/dist/chunk-S2NRVRPF.js +0 -171
- package/dist/chunk-S2NRVRPF.js.map +0 -1
- package/dist/chunk-SAN5PFTL.js.map +0 -1
- package/dist/chunk-UHEMZEGW.js.map +0 -1
- package/dist/chunk-Y3LKUXZA.js.map +0 -1
- package/dist/chunk-YT7A7DLY.js.map +0 -1
- package/dist/doctor-KGHM2CAC.js.map +0 -1
- package/dist/fund-DOWIT3JT.js.map +0 -1
- package/dist/hook-command-RDT754KQ.js.map +0 -1
- package/dist/mcp-ZKOTURQN.js.map +0 -1
- package/dist/tenjin-daemon.mjs +0 -20601
- package/dist/tenjin-shim.mjs +0 -251
- package/dist/tenjin-vitest-reporter.mjs +0 -49
- package/dist/uninstall-VR44B4KD.js.map +0 -1
- package/dist/update-SOYQLDBF.js.map +0 -1
- /package/dist/{chunk-3IOS6YG6.js.map → chunk-CEMXMUIU.js.map} +0 -0
- /package/dist/{chunk-NYJCBQL5.js.map → chunk-CKDD554V.js.map} +0 -0
- /package/dist/{chunk-DHCOGDJB.js.map → chunk-EG7P4SM6.js.map} +0 -0
- /package/dist/{chunk-WXFVJPZD.js.map → chunk-GT6W3VJM.js.map} +0 -0
- /package/dist/{chunk-GONDQ27X.js.map → chunk-IYLECN4D.js.map} +0 -0
- /package/dist/{chunk-HJYI52HM.js.map → chunk-NTYQHAIM.js.map} +0 -0
- /package/dist/{chunk-K63HPLYT.js.map → chunk-NYPFOHSJ.js.map} +0 -0
- /package/dist/{chunk-XBYTP4SP.js.map → chunk-OZ3LWLCI.js.map} +0 -0
- /package/dist/{chunk-N7A5EXJZ.js.map → chunk-SCAE6PW6.js.map} +0 -0
- /package/dist/{chunk-UGLTSPXQ.js.map → chunk-UDWGT4FX.js.map} +0 -0
- /package/dist/{chunk-F4IJQBGP.js.map → chunk-YTM7OURD.js.map} +0 -0
- /package/dist/{config-IIRRO3XC.js.map → config-VU6U7QOU.js.map} +0 -0
- /package/dist/{install-BYQUMYBN.js.map → hook-command-S2V4UNB3.js.map} +0 -0
- /package/dist/{install-identity-KTQPYVAO.js.map → install-GXQ33J4G.js.map} +0 -0
- /package/dist/{pay-LZPU2HUT.js.map → install-identity-HFQUXPSI.js.map} +0 -0
- /package/dist/{status-line-wiring-7D2CSV3K.js.map → pay-3TCOPGCX.js.map} +0 -0
- /package/dist/{wallet-IB2EFAUP.js.map → status-line-wiring-ZDBYHNYR.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/doctor.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { homedir } from 'node:os';\nimport { promisify } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile, ownsHookEntry, pruneOurHandlers } from '../lib/harness-hooks';\nimport { httpRequest } from '../lib/http';\nimport { toMoney } from '../lib/money';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { resolveContextSettings } from '../lib/settings';\nimport { onPath } from '../lib/skill-wiring';\nimport { describeWallet, resolveWalletProvider } from '../lib/wallet';\nimport { walletFileExists } from '../lib/wallet/store';\nimport type { CommandContext, CommandResult } from '../context';\nimport { agentsWithoutRequestTool } from './agent-tools';\nimport { ROUTER_PATH } from './decision';\nimport {\n ALLOW_RULE,\n MCP_SERVER_NAME,\n mcpAddCommand,\n mcpScope,\n readMcpEntry,\n routerHookPlan,\n routerSettingsPath,\n type McpEntryState,\n} from './install';\nimport { routerSettings, type RouterSettings } from './settings';\nimport { REQUEST_TOOL } from './names';\nimport { inspectStatusLine, STATUS_LINE_COMMAND } from './status-line-wiring';\n\n/**\n * `tenjin doctor` for the router product: the six things that decide whether a\n * lookup can happen at all.\n *\n * THE SHELF'S DOCTOR IS NOT THIS ONE. It checks a loop daemon, a skills tree\n * and a marketplace contract, and prescribes `tenjin daemon start`, a command\n * this release does not register: on a router install every one of those lines\n * was a failure about a product that is not installed. That doctor stays with\n * the product it belongs to (`src/commands/doctor.ts`, unregistered), and this\n * one reports the router's own wiring.\n */\n\nconst exec = promisify(execFile);\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n}\n\nexport interface RouterDoctorDeps {\n homeDir?: string;\n cwd?: string;\n /** Look at this project's `.claude/settings.json`, as `--project` installed it. */\n project?: boolean;\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n fetchImpl?: typeof fetch;\n /** The harness's own read-back, for a user-scope registration this build\n * cannot find on disk; tests inject it so nothing is spawned. */\n readMcp?: (opts: { scope: 'user' | 'project'; cwd: string }) => Promise<boolean>;\n /** Reads the registration entry from the file the scope writes. */\n readMcpEntry?: (\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n ) => Promise<{ found: boolean; state: McpEntryState }>;\n /** Node's own version, for the floor check. */\n nodeVersion?: string;\n}\n\nconst NODE_FLOOR = 24;\n\nexport async function runRouterDoctor(\n ctx: CommandContext,\n deps: RouterDoctorDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n // From the directory doctor runs in, which is the one a session there would use.\n const router = await routerSettings(\n { cwd: deps.cwd ?? process.cwd(), dataDir: ctx.dataDir },\n deps.homeDir !== undefined ? { homeDir: deps.homeDir } : {},\n ).catch((err: unknown) => (err instanceof Error ? err : new Error(String(err))));\n const settings = await resolveContextSettings(ctx);\n // The SAME resolution `install` and `uninstall` use. Reading the home file\n // only made a correctly wired `--project` install, which the README tells\n // people to do, fail a required check and exit 3.\n const settingsPath = routerSettingsPath({\n ...(deps.project === true ? { project: true } : {}),\n ...(deps.homeDir !== undefined ? { homeDir: deps.homeDir } : {}),\n ...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}),\n });\n const checks: RouterCheck[] = [nodeCheck(deps.nodeVersion ?? process.version)];\n checks.push(await hooksCheck(settingsPath, ctx.dataDir, router));\n checks.push(await statusLineCheck(settingsPath));\n checks.push(\n await mcpCheck(\n deps,\n env,\n deps.project === true,\n deps.cwd ?? process.cwd(),\n deps.homeDir ?? homedir(),\n ),\n );\n checks.push(spendCheck(settings.policy.maxAutoSpendAtomic, settings.policy.sessionBudgetAtomic));\n checks.push(experimentalCheck(settings.experimentalBazaar));\n checks.push(...(await walletCheck(ctx)));\n checks.push(await routerCheck(settings.baseUrl, ctx.flags.timeout, deps.fetchImpl));\n const agents = await subagentsCheck(deps.cwd ?? process.cwd(), deps.homeDir ?? homedir());\n if (agents !== null) checks.push(agents);\n\n const failure = checks.find((c) => c.status === 'fail' && c.required);\n const data = { checks, dataDir: ctx.dataDir, baseUrl: settings.baseUrl, settingsPath };\n if (failure !== undefined) {\n // REFUSED, the exit-3 class: a machine this command found unready is\n // understood and refused, not a runtime failure of the command itself.\n throw new CliError('REFUSED', failure.detail, {\n ...(failure.fix !== undefined ? { fix: failure.fix } : {}),\n details: data,\n });\n }\n const bad = checks.filter((c) => c.status !== 'ok').length;\n return {\n data,\n humanLines: [\n ...checks.map(\n (c) =>\n `${c.status === 'ok' ? 'ok ' : c.status === 'warn' ? 'warn' : 'fail'} ${c.name}: ${c.detail}`,\n ),\n bad === 0\n ? `${checks.length} checks, all pass.`\n : `${checks.length} checks, ${bad} to look at.`,\n ],\n };\n}\n\n/**\n * INFORMATIONAL, NEVER A FAILURE. A custom agent whose `tools:` leave the\n * request tool out is a choice its author may have meant, so this names those\n * agents and the one line that would change it, and counts as passing. It is\n * absent when there is nothing to name. The files are only read.\n */\nasync function subagentsCheck(cwd: string, homeDir: string): Promise<RouterCheck | null> {\n const excluded = await agentsWithoutRequestTool({ cwd, homeDir });\n if (excluded.length === 0) return null;\n return {\n name: 'subagents',\n status: 'ok',\n required: false,\n detail: `${excluded.join(', ')} ${excluded.length === 1 ? 'is' : 'are'} offered no paid lookups: add ${REQUEST_TOOL} to tools: to allow paid lookups there`,\n };\n}\n\nfunction nodeCheck(version: string): RouterCheck {\n const major = Number(/^v(\\d+)/.exec(version)?.[1] ?? '0');\n return major >= NODE_FLOOR\n ? { name: 'node', status: 'ok', required: true, detail: version }\n : {\n name: 'node',\n status: 'fail',\n required: true,\n detail: `${version} is below the Node ${NODE_FLOOR} floor.`,\n fix: `Install Node ${NODE_FLOOR} or newer, then re-run \\`tenjin doctor\\`.`,\n };\n}\n\n/**\n * The live footer, which is the one check here that is never required: a lookup\n * runs exactly the same without it. It reports what is in the file, including a\n * status line of the user's that this CLI deliberately did not touch.\n */\nasync function statusLineCheck(path: string): Promise<RouterCheck> {\n const found = await inspectStatusLine(path);\n const name = 'status line';\n if (found.warning !== undefined) {\n return { name, status: 'warn', required: false, detail: found.warning };\n }\n switch (found.state) {\n case 'ours':\n return { name, status: 'ok', required: false, detail: `\\`${STATUS_LINE_COMMAND}\\`` };\n case 'composed':\n return {\n name,\n status: 'ok',\n required: false,\n detail: 'yours, with the x402 footer appended',\n };\n case 'foreign':\n return {\n name,\n status: 'warn',\n required: false,\n detail: 'yours is registered and was left alone, so there is no live x402 footer',\n fix: 'Run `tenjin install --status-line compose` to show both.',\n };\n default:\n return {\n name,\n status: 'warn',\n required: false,\n detail: 'not registered, so lookups run without the live footer',\n fix: 'Run `tenjin install` to register it.',\n };\n }\n}\n\nasync function hooksCheck(\n path: string,\n dataDir: string,\n router: RouterSettings | Error,\n): Promise<RouterCheck> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n return {\n name: 'hooks',\n status: 'fail',\n required: true,\n detail: found.refusal.message,\n fix: 'Fix the reported file, then run `tenjin install`.',\n };\n }\n const events = Object.entries(found.hooks)\n .filter(([, list]) => list.some((entry) => ownsHookEntry(entry, dataDir)))\n .map(([event]) => event);\n const allow = allowRules(found.settings);\n if (events.length === 0) {\n return {\n name: 'hooks',\n status: 'fail',\n required: true,\n detail: `no Tenjin hook entries in ${path}`,\n fix: 'Run `tenjin install`, then restart Claude Code.',\n };\n }\n // WIRED BUT SWITCHED OFF is a choice, not a fault, so it warns and names the\n // file that made it: the entries are there and every one of them is silent.\n if (router instanceof Error) {\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but the router is off here: ${router.message}`,\n fix: 'Fix or delete that file.',\n };\n }\n if (!router.enabled.value) {\n const file = router.enabled.path ?? 'the config';\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but router.enabled is false in ${file}, so nothing is routed from this directory`,\n fix:\n router.enabled.source === 'file'\n ? 'Run `tenjin config set router.enabled true` to route again.'\n : `Remove router.enabled from ${file} to route here again.`,\n };\n }\n if (!allow.includes(ALLOW_RULE)) {\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but ${ALLOW_RULE} is not allowed, so every lookup asks`,\n fix: 'Run `tenjin install` to write the permission rule.',\n };\n }\n // AN INSTALL FROM AN OLDER BUILD STILL WORKS, so this is a warning with its\n // one-command remedy, not a failure: its `tenjin hook native` entry is a\n // no-op now, and the entries it lacks are offers it does not make.\n const drift = planDrift(found.hooks, dataDir);\n if (drift.missing.length > 0 || drift.stale.length > 0) {\n const parts = [\n ...(drift.missing.length > 0 ? [`missing ${drift.missing.join(', ')}`] : []),\n ...(drift.stale.length > 0 ? [`stale ${drift.stale.join(', ')}`] : []),\n ];\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but not as this build writes them: ${parts.join('; ')}`,\n fix: 'Run `tenjin install --refresh`.',\n };\n }\n return {\n name: 'hooks',\n status: 'ok',\n required: true,\n detail: `${events.join(' and ')} registered, ${ALLOW_RULE} allowed`,\n };\n}\n\n/** One entry as `event matcher → command`, the way doctor names it. */\nfunction entryLabel(event: string, matcher: unknown, command: string): string {\n return `${event}${typeof matcher === 'string' ? ` ${matcher}` : ''} → ${command}`;\n}\n\n/**\n * Which of `routerHookPlan()`'s entries this file lacks, and which handlers of\n * ours it carries that the plan no longer writes (an older install's\n * `tenjin hook native`, or a shelf-era entry). Compared by event, matcher and\n * command, so a timeout the writer would raise is not called drift here.\n */\nfunction planDrift(\n hooks: Record<string, unknown[]>,\n dataDir: string,\n): { missing: string[]; stale: string[] } {\n const planned = (routerHookPlan() as PlannedEntry[]).map((entry) =>\n entryLabel(entry.event, entry.matcher, entry.hooks[0]!.command),\n );\n const present: string[] = [];\n for (const [event, list] of Object.entries(hooks)) {\n for (const entry of list) {\n if (!ownsHookEntry(entry, dataDir)) continue;\n const { matcher, hooks: handlers } = entry as { matcher?: unknown; hooks: unknown[] };\n // Ours only: a handler someone hand-merged beside ours is not drift.\n const kept = pruneOurHandlers(entry, dataDir) as { hooks: unknown[] } | null;\n for (const handler of handlers.filter((h) => kept === null || !kept.hooks.includes(h))) {\n const command = (handler as { command?: unknown }).command;\n const url = (handler as { url?: unknown }).url;\n const label = typeof command === 'string' ? command : typeof url === 'string' ? url : '?';\n present.push(entryLabel(event, matcher, label));\n }\n }\n }\n return {\n missing: planned.filter((label) => !present.includes(label)),\n stale: present.filter((label) => !planned.includes(label)),\n };\n}\n\ninterface PlannedEntry {\n event: string;\n matcher?: string;\n hooks: { command: string }[];\n}\n\nfunction allowRules(settings: Record<string, unknown>): string[] {\n const permissions = settings.permissions;\n if (permissions === null || typeof permissions !== 'object' || Array.isArray(permissions)) {\n return [];\n }\n const allow = (permissions as { allow?: unknown }).allow;\n return Array.isArray(allow) ? allow.filter((r): r is string => typeof r === 'string') : [];\n}\n\nasync function mcpCheck(\n deps: RouterDoctorDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n home: string,\n): Promise<RouterCheck> {\n const scope = mcpScope(project);\n const add = mcpAddCommand(project);\n const where = scope === 'project' ? \"this project's .mcp.json\" : '~/.claude.json';\n const { found, state } = await (deps.readMcpEntry ?? readMcpEntry)(scope, cwd, home);\n\n if (state === 'ok') {\n return {\n name: 'mcp',\n status: 'ok',\n required: true,\n detail: `${MCP_SERVER_NAME} registered (${scope} scope), running \\`tenjin mcp\\``,\n };\n }\n if (state === 'wrong-command') {\n return {\n name: 'mcp',\n status: 'fail',\n required: true,\n detail: `${MCP_SERVER_NAME} registered but not \\`tenjin mcp\\`: the entry in ${where} launches something else, so the request tool is not there`,\n fix: `Remove it and re-run \\`tenjin install\\`${project ? ' --project' : ''}, or: ${add}`,\n };\n }\n // A file that is there and unreadable is not an absence: \"run install\" would\n // be the wrong instruction, since `install` refuses to write over it too.\n if (state === 'unreadable') {\n return {\n name: 'mcp',\n status: 'fail',\n required: true,\n detail: `${where} could not be read, so whether ${MCP_SERVER_NAME} is registered is unknown`,\n fix: `Fix the JSON in ${where}, then re-run \\`tenjin install\\`${project ? ' --project' : ''}.`,\n };\n }\n // Absent. On USER scope the file may simply not be where this build looks,\n // so the harness's own answer is worth asking before calling it missing.\n if (scope === 'user') {\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (which('claude')) {\n const seen = await (deps.readMcp ?? claudeHasServer)({ scope, cwd }).catch(() => false);\n if (seen) {\n return {\n name: 'mcp',\n status: 'warn',\n required: false,\n detail: `${MCP_SERVER_NAME} is registered somewhere this check cannot read, so what it launches was not verified`,\n fix: `Re-run \\`tenjin install\\` to write a registration this build can check, or: ${add}`,\n };\n }\n }\n }\n return {\n name: 'mcp',\n status: 'fail',\n required: true,\n detail: found\n ? `${MCP_SERVER_NAME} is not in ${where}, so there is no request tool`\n : `${where} does not exist, so ${MCP_SERVER_NAME} is not registered`,\n fix: `Run \\`tenjin install\\`${project ? ' --project' : ''}, or: ${add}`,\n };\n}\n\n/** The harness's own answer, for a user-scope registration this build cannot\n * find on disk. It resolves across scopes, which is why it is a last resort\n * and only ever downgrades the verdict to a warn. */\nasync function claudeHasServer(opts: { scope: 'user' | 'project'; cwd: string }): Promise<boolean> {\n const { stdout } = await exec('claude', ['mcp', 'get', MCP_SERVER_NAME], {\n timeout: 15_000,\n cwd: opts.cwd,\n });\n return stdout.includes(MCP_SERVER_NAME) && !/no mcp server/i.test(stdout);\n}\n\n/** INFORMATIONAL: which experiment is on, in one line. Either state passes. */\nfunction experimentalCheck(bazaar: boolean): RouterCheck {\n return {\n name: 'experimental',\n status: 'ok',\n required: false,\n detail: bazaar\n ? 'list: on; bazaar: on (experimental): the router may also suggest unreviewed sellers from the open x402 Bazaar'\n : 'list: on; bazaar: off (experimental): `tenjin config set experimental.bazaar on` to add the open x402 Bazaar',\n };\n}\n\nfunction spendCheck(maxAutoSpendAtomic: bigint, sessionBudgetAtomic: bigint | null): RouterCheck {\n if (sessionBudgetAtomic === 0n) {\n return {\n name: 'spend',\n status: 'fail',\n required: true,\n detail: 'The daily limit is 0, so positive payments are refused even with --yes.',\n fix: 'Choose a daily limit with `tenjin config set sessionBudget <usd|none>`.',\n };\n }\n if (maxAutoSpendAtomic === 0n) {\n return {\n name: 'spend',\n status: 'fail',\n required: true,\n detail: 'maxAutoSpend is 0, so every lookup needs approval and none can pay',\n fix: 'Run `tenjin install`, or `tenjin config set maxAutoSpend 0.10`.',\n };\n }\n const budget =\n sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : `${toMoney(sessionBudgetAtomic.toString()).usd} USD a day`;\n return {\n name: 'spend',\n status: sessionBudgetAtomic === null ? 'warn' : 'ok',\n required: false,\n detail: `automatic approval up to ${toMoney(maxAutoSpendAtomic.toString()).usd} USD a call, ${budget}`,\n ...(sessionBudgetAtomic === null\n ? { fix: 'Set one with `tenjin config set sessionBudget 1.00`.' }\n : {}),\n };\n}\n\nasync function walletCheck(ctx: CommandContext): Promise<RouterCheck[]> {\n if (!(await walletFileExists(ctx.dataDir))) {\n return [\n {\n name: 'wallet',\n status: 'fail',\n required: true,\n detail: 'no wallet on this machine, so nothing can pay',\n fix: 'Run `tenjin wallet create`, then `tenjin wallet fund`.',\n },\n ];\n }\n try {\n const described = await describeWallet(resolveWalletProvider(ctx));\n return [{ name: 'wallet', status: 'ok', required: true, detail: described.address }];\n } catch (err) {\n return [\n {\n name: 'wallet',\n status: 'fail',\n required: true,\n detail: err instanceof CliError ? err.message : String(err),\n ...(err instanceof CliError && err.fix !== undefined ? { fix: err.fix } : {}),\n },\n ];\n }\n}\n\n/**\n * One cheap request to the free decision route with an empty body. It checks\n * the route is reachable and enabled, not that it routes: a 400 is the route\n * refusing that body, and a 404 is the route switched off. Nothing is signed\n * and no Jev request is spent.\n */\nasync function routerCheck(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl: typeof fetch | undefined,\n): Promise<RouterCheck> {\n const url = new URL(ROUTER_PATH, baseUrl).toString();\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs,\n blockRedirects: true,\n jsonBody: {},\n ...(fetchImpl !== undefined ? { fetchImpl } : {}),\n });\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n const checkBase =\n 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n if (!probe.ok) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, checkBase);\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 401 || probe.status === 403) {\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,g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A,WACA,WACsB;AACtB,QAAM,MAAM,IAAI,IAAI,aAAa,OAAO,EAAE,SAAS;AACnD,QAAM,QAAQ,MAAM,YAAY,KAAK;AAAA,IACnC,QAAQ;AAAA,IACR;AAAA,IACA,gBAAgB;AAAA,IAChB,UAAU,CAAC;AAAA,IACX,GAAI,cAAc,SAAY,EAAE,UAAU,IAAI,CAAC;AAAA,EACjD,CAAC;AACD,QAAM,OAAO,CAAC,QAAgB,SAA8B;AAAA,IAC1D,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EACF;AACA,QAAM,YACJ;AACF,MAAI,CAAC,MAAM,IAAI;AACb,WAAO,KAAK,iBAAiB,GAAG,gCAAgC,MAAM,OAAO,KAAK,SAAS;AAAA,EAC7F;AAEA,MAAI,MAAM,WAAW,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW,KAAK;AACxE,WAAO,EAAE,MAAM,UAAU,QAAQ,MAAM,UAAU,MAAM,QAAQ,GAAG,GAAG,WAAW;AAAA,EAClF;AACA,MAAI,MAAM,WAAW,KAAK;AACxB,WAAO,KAAK,gCAAgC,GAAG,IAAI,SAAS;AAAA,EAC9D;AACA,MAAI,MAAM,WAAW,OAAO,MAAM,WAAW,KAAK;AAChD,WAAO;AAAA,MACL,GAAG,GAAG;AAAA,MACN,uDAAuD,iBAAiB;AAAA,IAC1E;AAAA,EACF;AACA,MAAI,MAAM,UAAU,KAAK;AACvB,WAAO,KAAK,iBAAiB,GAAG,gCAAgC,MAAM,MAAM,KAAK,SAAS;AAAA,EAC5F;AACA,SAAO;AAAA,IACL,GAAG,GAAG,aAAa,MAAM,MAAM;AAAA,IAC/B;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n","import { execFile } from 'node:child_process';\n\n/**\n * Open a URL in the platform's default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.',\n );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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-1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router/hooks.ts","../src/router/context.ts","../src/router/fetch-result.ts","../src/router/gate.ts","../src/router/augment.ts","../src/router/hook-command.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { z } from 'zod';\nimport { loadRawConfig, resolveExperimentalBazaar, resolveSettings } from '../lib/config';\nimport type { PartialConfig } from '../lib/config';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport { walletPath } from '../lib/paths';\nimport { evaluateSpendPolicy } from '../lib/policy';\nimport { resolveContextSettings } from '../lib/settings';\nimport { readSpendSummary, spentOf } from '../lib/spend-ledger';\nimport { rememberingBalanceReader } from '../lib/usdc-balance';\nimport type { CommandContext } from '../context';\nimport {\n buildNativePacket,\n buildPromptPacket,\n isHandback,\n seal,\n type NativeOutcome,\n type Packet,\n type PendingCall,\n type Sealed,\n} from './context';\nimport { storeSpecs } from './specs';\nimport { requestDecision, ROUTER_PATH, type HookDecision } from './decision';\nimport { readsAsEmptyPage, savedPdfOf } from './fetch-result';\nimport { GATE_TIMEOUT_MS } from './gate';\nimport { REQUEST_TOOL } from './names';\nimport { requestToolAccess, type AgentLookup } from './agent-tools';\nimport { finishAugment, startAugment, type PrefetchJob, type SearchResponse } from './augment';\nimport {\n bindDecision,\n claimRedirect,\n markOffered,\n newCallId,\n noteSession,\n pruneProgress,\n pruneSessions,\n redirectClaimed,\n sessionDir,\n wasOffered,\n writeProgress,\n} from './progress';\nimport { routerSettings, type RouterSettings } from './settings';\n\n/**\n * The six hook handlers. Between them they do exactly three things: build and\n * seal the packet, ask for one free decision, and say one thing back to the\n * harness. Before an `execute` is shown where nobody can approve it, they also\n * read the wallet's address from its file and its USDC balance from the RPC\n * (`spendShortfall`). A free offer on a search starts one free docs fetch in a\n * detached `node` (`augment.ts`); that is the only other thing they touch.\n *\n * NOTHING ELSE IS IN REACH FROM HERE. No wallet module, no signer, no payment\n * SDK, no viem, no MCP server: a dist test asserts the chunk graph, because the\n * hooks run on every prompt and after every native search, and their cost is\n * the product's floor.\n * The decision is free, so nothing on this path can spend anything either.\n *\n * EVERY FAILURE IS SILENT. A backend that is down, slow or answering nonsense\n * leaves the prompt and the native result unchanged; the cause goes to\n * stderr. The user's turn is never blocked by this.\n *\n * A DENY ONLY WHERE IT CAN BE ACTED ON. The pre-call arm redirects a native\n * call the router routes, as every release has, because a note beside the call\n * was followed 0 times in 11 where the redirect is followed. But a denied\n * WebFetch stranded every subagent that could not reach `request`\n * (tenjin-agent#377), so a subagent is denied only when it is known to have\n * the tool (`requestToolAccess`) and the spend would auto-execute from a wallet\n * that can cover it; anyone else's call runs free. No arm ever returns `allow`: that would skip the user's own permission\n * rules for the call.\n */\n\nconst PromptEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n /** The directory the session works in; `router.*` resolves from it. */\n cwd: z.string().optional(),\n transcript_path: z.string().optional(),\n prompt: z.string(),\n});\n\n/** What both native arms read: the call, whose it is, and where it runs. */\nconst NativeCallFields = {\n session_id: z.string().min(1).max(200),\n /** The harness's own path for THIS session: the decision reads the same\n * bounded history the prompt one does, so a restriction the user gave\n * reaches both gates. */\n transcript_path: z.string().optional(),\n tool_name: z.enum(['WebSearch', 'WebFetch']),\n tool_input: z.record(z.string(), z.unknown()),\n /** The harness's id for this one call, shared by its Pre and Post events. */\n tool_use_id: z.string().min(1).max(200).optional(),\n /** Present only inside a subagent, which is the one caller that cannot reach\n * the user to approve a spend. */\n agent_id: z.string().min(1).max(200).optional(),\n /** The subagent's type, which names its definition file. */\n agent_type: z.string().min(1).max(200).optional(),\n cwd: z.string().optional(),\n};\n\nconst NativeEventSchema = z.object({\n hook_event_name: z.literal('PreToolUse').optional(),\n ...NativeCallFields,\n});\n\nconst ShortfallEventSchema = z.object({\n hook_event_name: z.enum(['PostToolUse', 'PostToolUseFailure']),\n ...NativeCallFields,\n /** PostToolUse only: WebFetch's `{bytes, code, codeText, result, durationMs}`,\n * or WebSearch's `{query, results, durationSeconds, searchCount}`. */\n tool_response: z.unknown().optional(),\n /** PostToolUseFailure only: the failed call's own error, such as\n * `getaddrinfo ENOTFOUND x.test`. */\n error: z.unknown().optional(),\n is_interrupt: z.boolean().optional(),\n});\n\n/** Before the host asks the user: its questions and their options. */\nconst AskEventSchema = z.object({\n hook_event_name: z.literal('PreToolUse').optional(),\n ...NativeCallFields,\n tool_name: z.literal('AskUserQuestion'),\n});\n\n/** After the user answered: `tool_response` is `{questions, answers,\n * annotations}`, `answers` keyed by each question's text. */\nconst AnswerEventSchema = z.object({\n hook_event_name: z.literal('PostToolUse'),\n session_id: z.string().min(1).max(200),\n transcript_path: z.string().optional(),\n tool_name: z.literal('AskUserQuestion'),\n tool_input: z.record(z.string(), z.unknown()),\n tool_response: z.unknown().optional(),\n cwd: z.string().optional(),\n});\n\nconst DelegationEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n transcript_path: z.string().optional(),\n /** `Task` is the tool's older name; the matcher `install` writes takes both. */\n tool_name: z.enum(['Agent', 'Task']),\n tool_input: z.record(z.string(), z.unknown()),\n cwd: z.string().optional(),\n});\n\n/** A native call as every arm past {@link decodeEvent} reads it. */\nexport interface NativeCall {\n sessionId: string;\n transcriptPath?: string;\n tool: 'WebSearch' | 'WebFetch';\n /** The search or URL, or null when the call carries none. */\n pending: PendingCall | null;\n toolUseId?: string;\n /** Present only inside a subagent. */\n agentId?: string;\n agentType?: string;\n cwd?: string;\n}\n\n/** One hook event, as this file uses it. */\nexport type HookEvent =\n | { kind: 'prompt'; sessionId: string; transcriptPath?: string; prompt: string; cwd?: string }\n | ({ kind: 'native' } & NativeCall)\n | ({\n kind: 'ask';\n /** The questions and their options, joined; null when there are none. */\n pending: PendingCall | null;\n } & Omit<NativeCall, 'tool' | 'pending'>)\n | {\n kind: 'answer';\n sessionId: string;\n transcriptPath?: string;\n /** The user's answers, joined; null when there are none. */\n answers: string | null;\n cwd?: string;\n }\n | ({\n kind: 'shortfall';\n eventName: 'PostToolUse' | 'PostToolUseFailure';\n /** What the harness reported, when it was a shortfall; null means none. */\n nativeOutcome: NativeOutcome | null;\n /** A WebSearch's whole response after it ran, kept to be echoed back with\n * free docs on top; null for anything else. */\n search: SearchResponse | null;\n /** Where a WebFetch saved the PDF it fetched ({@link savedPdfOf}); null\n * for anything else. */\n savedPdf: string | null;\n } & NativeCall)\n | {\n kind: 'delegation';\n sessionId: string;\n transcriptPath?: string;\n /** `tool_input.prompt`: the subagent's whole task. */\n task: string | null;\n subagentType: string;\n /** The whole tool input, echoed back with the task changed. */\n toolInput: Record<string, unknown>;\n cwd?: string;\n };\n\n/**\n * THE ONLY READER OF A HARNESS FIELD. `session_id`, `transcript_path`,\n * `prompt`, `tool_name`, `tool_input` (its `query`, `url`, `prompt`,\n * `subagent_type` and `questions`), `tool_use_id`, `agent_id`, `agent_type`,\n * `cwd`, `tool_response` (and its `answers`) and `error` are Claude Code's names; everything past this\n * function reads {@link HookEvent}, so a second harness is a second decoder\n * rather than a change to each arm. `null` is an event no arm handles.\n */\nexport function decodeEvent(raw: unknown): HookEvent | null {\n const shortfall = ShortfallEventSchema.safeParse(raw);\n if (shortfall.success) {\n return {\n kind: 'shortfall',\n eventName: shortfall.data.hook_event_name,\n nativeOutcome: shortfallOf(shortfall.data),\n search: searchOf(shortfall.data),\n savedPdf: savedPdfIn(shortfall.data),\n ...nativeCallOf(shortfall.data),\n };\n }\n const native = NativeEventSchema.safeParse(raw);\n if (native.success) return { kind: 'native', ...nativeCallOf(native.data) };\n const answer = AnswerEventSchema.safeParse(raw);\n if (answer.success) {\n return {\n kind: 'answer',\n sessionId: answer.data.session_id,\n ...optional('transcriptPath', answer.data.transcript_path),\n answers: answersOf(answer.data.tool_response, answer.data.tool_input),\n ...optional('cwd', answer.data.cwd),\n };\n }\n const ask = AskEventSchema.safeParse(raw);\n if (ask.success) {\n const question = questionOf(ask.data.tool_input);\n return {\n kind: 'ask',\n ...callFieldsOf(ask.data),\n pending: question === null ? null : { tool: 'AskUserQuestion', question },\n };\n }\n const delegation = DelegationEventSchema.safeParse(raw);\n if (delegation.success) {\n const input = delegation.data.tool_input;\n return {\n kind: 'delegation',\n sessionId: delegation.data.session_id,\n ...optional('transcriptPath', delegation.data.transcript_path),\n task: typeof input.prompt === 'string' ? input.prompt : null,\n // With no type the harness runs its general-purpose agent.\n subagentType:\n typeof input.subagent_type === 'string' ? input.subagent_type : 'general-purpose',\n toolInput: input,\n ...optional('cwd', delegation.data.cwd),\n };\n }\n const prompt = PromptEventSchema.safeParse(raw);\n if (!prompt.success) return null;\n return {\n kind: 'prompt',\n sessionId: prompt.data.session_id,\n ...optional('transcriptPath', prompt.data.transcript_path),\n prompt: prompt.data.prompt,\n ...optional('cwd', prompt.data.cwd),\n };\n}\n\nfunction nativeCallOf(\n event: Omit<z.infer<typeof NativeEventSchema>, 'hook_event_name'>,\n): NativeCall {\n return {\n ...callFieldsOf(event),\n tool: event.tool_name,\n pending: pendingCallOf(event.tool_name, event.tool_input),\n };\n}\n\n/** Whose call it is and where it runs, the same for every tool. */\nfunction callFieldsOf(event: {\n session_id: string;\n transcript_path?: string | undefined;\n tool_use_id?: string | undefined;\n agent_id?: string | undefined;\n agent_type?: string | undefined;\n cwd?: string | undefined;\n}): Omit<NativeCall, 'tool' | 'pending'> {\n return {\n sessionId: event.session_id,\n ...optional('transcriptPath', event.transcript_path),\n ...optional('toolUseId', event.tool_use_id),\n ...optional('agentId', event.agent_id),\n ...optional('agentType', event.agent_type),\n ...optional('cwd', event.cwd),\n };\n}\n\n/**\n * THE HOST'S OWN WORDS BEFORE IT ASKS: each question, then each option's label\n * and description, in the order the host wrote them. Not cut here: seal()\n * masks it first and bounds it after, as it does a search.\n */\nfunction questionOf(input: Record<string, unknown>): string | null {\n const questions = Array.isArray(input.questions) ? input.questions : [];\n const parts: string[] = [];\n for (const entry of questions) {\n if (entry === null || typeof entry !== 'object') continue;\n const { question, options } = entry as { question?: unknown; options?: unknown };\n if (typeof question === 'string' && question.trim().length > 0) parts.push(question.trim());\n for (const option of Array.isArray(options) ? options : []) {\n if (option === null || typeof option !== 'object') continue;\n const { label, description } = option as { label?: unknown; description?: unknown };\n if (typeof label !== 'string' || label.trim().length === 0) continue;\n parts.push(\n typeof description === 'string' && description.trim().length > 0\n ? `${label.trim()}: ${description.trim()}`\n : label.trim(),\n );\n }\n }\n const joined = parts.join(' ');\n return joined.length > 0 ? joined : null;\n}\n\n/** The user's answers, one per line, from the tool's response, or from its\n * input where a harness puts them there instead. */\nfunction answersOf(response: unknown, input: Record<string, unknown>): string | null {\n for (const holder of [response, input]) {\n if (holder === null || typeof holder !== 'object' || Array.isArray(holder)) continue;\n const answers = (holder as { answers?: unknown }).answers;\n if (answers === null || typeof answers !== 'object' || Array.isArray(answers)) continue;\n const texts = Object.values(answers as Record<string, unknown>)\n .filter((value): value is string => typeof value === 'string')\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n if (texts.length > 0) return texts.join('\\n');\n }\n return null;\n}\n\n/** WebSearch's `{query, results, durationSeconds, searchCount}` after it ran. */\nfunction searchOf(event: z.infer<typeof ShortfallEventSchema>): SearchResponse | null {\n if (event.hook_event_name !== 'PostToolUse' || event.tool_name !== 'WebSearch') return null;\n const response = event.tool_response;\n if (response === null || typeof response !== 'object' || Array.isArray(response)) return null;\n const raw = response as Record<string, unknown>;\n return Array.isArray(raw.results) ? { raw, results: raw.results } : null;\n}\n\n/** WebFetch's `result`, when it names the PDF it saved whole. */\nfunction savedPdfIn(event: z.infer<typeof ShortfallEventSchema>): string | null {\n if (event.hook_event_name !== 'PostToolUse' || event.tool_name !== 'WebFetch') return null;\n const response = event.tool_response;\n if (response === null || typeof response !== 'object' || Array.isArray(response)) return null;\n const result = (response as { result?: unknown }).result;\n return typeof result === 'string' ? savedPdfOf(result, event.session_id) : null;\n}\n\nfunction optional<K extends string>(key: K, value: string | undefined): Partial<Record<K, string>> {\n return value === undefined ? {} : ({ [key]: value } as Record<K, string>);\n}\n\n/** Acknowledgements that cannot be a lookup; `install` never gates them. */\nconst ACKNOWLEDGEMENTS = new Set(['y', 'yes', 'ok', 'okay', 'continue', 'go', 'sure', 'thanks']);\n\nexport type PromptSkip = 'slash' | 'acknowledgement' | 'handback';\n\n/**\n * Prompts that cannot need a lookup, decided locally with no network call. Any\n * OTHER short prompt still goes to the backend: `2^1000`, a bare URL and a task\n * typed without spaces can all need one, and a computation has no later\n * WebSearch or WebFetch hook to recover a skipped classification.\n */\nexport function promptSkipReason(prompt: string): PromptSkip | null {\n const trimmed = prompt.trim();\n // A hand-back from the harness or another agent ({@link isHandback}).\n if (isHandback(trimmed)) return 'handback';\n if (trimmed.startsWith('/')) return 'slash';\n const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, '');\n return ACKNOWLEDGEMENTS.has(normalized) ? 'acknowledgement' : null;\n}\n\n/**\n * EVERY LINE SAYS WHERE IT CAME FROM AND NAMES THE REAL TOOL. An unattributed\n * line asking for a call the model cannot find by that name reads like an\n * injection, and a subagent looking for `request` in its tool list finds\n * nothing. So each line opens with its source, and the server's `request({`\n * becomes the name the harness actually exposes, from the one place `install`\n * registers it. The server's words are otherwise untouched: this client names\n * no provider and no price of its own.\n */\nexport const HINT_SOURCE = 'Tenjin router (installed by the user)';\n\nconst BARE_CALL_RE = /(?<![\\w$])request\\(\\{/g;\n\nexport function toolNamed(hint: string): string {\n return hint.replace(BARE_CALL_RE, `${REQUEST_TOOL}({`);\n}\n\n/** The server's line as the prompt hint and the redirect both carry it. */\nfunction attributed(hint: string): string {\n return `${HINT_SOURCE}: ${toolNamed(hint)}`;\n}\n\n/** This client's one sentence on a redirect: the promise {@link runNativeHook} keeps. */\nconst ONE_BLOCK =\n 'If this does not cover it, make your own call again: you will not be redirected twice in a row for the same search or URL.';\n\n/** The same promise, for a question the ask arm redirected. */\nconst ONE_BLOCK_QUESTION =\n 'If this does not cover it, ask your question again: you will not be redirected twice in a row for the same question.';\n\n/** The free line after WebFetch saved a PDF its summary could not read. */\nfunction savedPdfHint(path: string): string {\n return `${HINT_SOURCE}: WebFetch's summary cannot read a PDF, but it saved this one whole to ${path}. Read that file for its text, free (pass pages, such as \"1-10\", for a long one).`;\n}\n\n/** Where the offer sits after the free tool came back short. */\nfunction shortfallOffer(tool: 'WebSearch' | 'WebFetch', hint: string): string {\n return `${HINT_SOURCE}: your ${tool} call came back short. Optional: ${toolNamed(hint)}`;\n}\n\n/**\n * A WebFetch body smaller than this is empty for any purpose a reader has. The\n * smallest real page measured, example.com (a heading and two sentences),\n * reports 559 bytes; a 404 and x.com's blocked read both report 0. Sixty-four\n * bytes has no room for one sentence of content, so nothing a person would\n * call a page falls under it.\n */\nexport const NEAR_EMPTY_BYTES = 64;\n\n/**\n * DID THE FREE TOOL FALL SHORT, decided from the harness's own report and\n * nothing else: no model, no network call. Only clear signals count, and\n * everything else is `null`, which means the router is never asked:\n *\n * - a failed call (PostToolUseFailure), unless the user interrupted it;\n * - WebFetch refused or failing upstream: 401, 402, 403, 429 or any 5xx. A\n * 404 or 410 is not one: a page that is missing is missing for a paid\n * reader too;\n * - WebFetch answering 2xx, or no code, with under {@link NEAR_EMPTY_BYTES};\n * - WebFetch answering 2xx, or no code, whose summary says the page had no\n * main content (`reason: 'no_main_content'`, {@link readsAsEmptyPage}): a\n * JavaScript app's title, a video page's footer. Both are 200s with tens of\n * kilobytes, so the size never caught them;\n * - WebSearch answering with no result links at all.\n *\n * A search that returned unrelated links is NOT one: it looks exactly like a\n * good search from here, and guessing would put the router on every call.\n * Nor is a PDF WebFetch saved whole: its summary fails, but `Read` opens the\n * file for free ({@link savedPdfOf}).\n */\nexport function shortfallOf(event: {\n hook_event_name: 'PostToolUse' | 'PostToolUseFailure';\n session_id: string;\n tool_name: 'WebSearch' | 'WebFetch';\n tool_response?: unknown;\n error?: unknown;\n is_interrupt?: boolean;\n}): NativeOutcome | null {\n if (event.hook_event_name === 'PostToolUseFailure') {\n if (event.is_interrupt === true) return null;\n // Neither masked nor cut here: seal() does both, in that order.\n const error = typeof event.error === 'string' ? event.error.trim() : '';\n return error.length > 0 ? { error } : null;\n }\n const response = event.tool_response;\n if (response === null || typeof response !== 'object' || Array.isArray(response)) return null;\n const fields = response as Record<string, unknown>;\n if (event.tool_name === 'WebFetch') {\n const code = wholeNumber(fields.code, 999);\n const bytes = wholeNumber(fields.bytes, Number.MAX_SAFE_INTEGER);\n const outcome = {\n ...(code !== undefined ? { code } : {}),\n ...(bytes !== undefined ? { bytes } : {}),\n };\n if (code !== undefined && isShortStatus(code)) return outcome;\n const success = code === undefined || (code >= 200 && code < 300);\n if (!success) return null;\n if (bytes !== undefined && bytes < NEAR_EMPTY_BYTES) return outcome;\n const result = typeof fields.result === 'string' ? fields.result : '';\n // A PDF it saved is read for free (`runShortfallHook`), never paid for.\n if (savedPdfOf(result, event.session_id) !== null) return null;\n return readsAsEmptyPage(result) ? { ...outcome, reason: 'no_main_content' } : null;\n }\n const results = fields.results;\n if (!Array.isArray(results)) return null;\n const linked = results.some(\n (entry) =>\n entry !== null &&\n typeof entry === 'object' &&\n Array.isArray((entry as { content?: unknown }).content) &&\n (entry as { content: unknown[] }).content.length > 0,\n );\n return linked ? null : { error: 'Web search returned no results' };\n}\n\n/** The statuses a paid reader can get past: auth walls, paywalls, bot blocks,\n * rate limits and upstream failures. Every other 4xx is the page's answer. */\nconst SHORT_STATUSES = new Set([401, 402, 403, 429]);\n\nfunction isShortStatus(code: number): boolean {\n return SHORT_STATUSES.has(code) || (code >= 500 && code <= 599);\n}\n\nfunction wholeNumber(value: unknown, max: number): number | undefined {\n return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= max\n ? value\n : undefined;\n}\n\nfunction delegationOffer(hint: string): string {\n return `${HINT_SOURCE}, optional if your own tools fall short: ${toolNamed(hint)} Your own tools are fine when they are enough.`;\n}\n\nexport interface HookDeps {\n dataDir: string;\n /** Overrides the resolved base URL entirely; tests point it at a local stub. */\n baseUrl?: string;\n /** The environment the base URL precedence reads `TENJIN_BASE_URL` from. */\n env?: NodeJS.ProcessEnv;\n /** Every request a hook makes: the decision, and the balance read before an\n * offer. Tests answer both from one stub. */\n fetchImpl?: typeof fetch;\n timeoutMs?: number;\n now?: () => number;\n /** Where `~/.claude` is, for the user's agent definitions; tests point it\n * at a scratch directory. */\n homeDir?: string;\n /**\n * Where a silent failure says why. The harness keeps hook stderr in its log,\n * so one line there is the difference between \"the feature is off\" and \"the\n * router answered 401 at this URL\". Never stdout: that is the harness's\n * protocol channel.\n */\n warn?: (line: string) => void;\n /** Starts the free docs fetch beside a search; tests replace the detached\n * process it spawns. */\n prefetch?: (job: PrefetchJob) => void;\n /** How long the after-call hook waits for that fetch; tests shorten it. */\n augmentWaitMs?: number;\n}\n\n/**\n * The CLI's ONE precedence, not a second copy of it: flag, then\n * `TENJIN_BASE_URL`, then the config file, then the production default. The\n * hook read the file alone, so a session pointed somewhere by the environment\n * had its prompts routed against whatever the file said instead; on a machine\n * whose file named a protected deployment that was a 401, and a 401 is silence.\n */\nfunction resolveBaseUrl(deps: HookDeps, config: PartialConfig): string {\n if (deps.baseUrl !== undefined) return deps.baseUrl;\n return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;\n}\n\n/** The balance read's own ceiling, inside what the decision left of the gate's\n * budget. Base's public RPC answered `balanceOf` in 0.16 to 0.26 s. */\nconst BALANCE_TIMEOUT_MS = 1_000;\n\n/** When the gate's budget runs out. The decision and the balance read share it,\n * so the pair still fits the hook timeout `wire.test.ts` pins. */\nfunction gateDeadline(deps: HookDeps): number {\n return (deps.now?.() ?? Date.now()) + (deps.timeoutMs ?? GATE_TIMEOUT_MS);\n}\n\n/**\n * WHY THE PAID CALL WOULD NOT RUN ON ITS OWN, in the footer's words, or null\n * when it would. Every line that points at `request` where nobody can approve\n * asks this first: a subagent cannot reach the user, and the main agent's\n * pre-call deny and prompt hint send it to a call that has to run rather than\n * to the free tools that would have answered. Two things stop that call:\n *\n * - THE SPEND POLICY, asked the way `request` will ask it: the same settings,\n * the same session ledger and the same evaluation, with the provider's host\n * as the creator the way `pay` names it. Only `allow` runs alone. Nothing is\n * reserved, and the amount actually signed is still `gateSpend`'s to cap.\n * - THE WALLET. A fresh install's wallet holds no USDC, and the authorization\n * it signs is refused after the free call was already denied: the user got\n * neither. One `balanceOf`, read only once the policy said yes.\n *\n * ONLY A BALANCE READ BELOW THE PRICE WITHHOLDS. One that cannot be read (no\n * wallet file, an RPC that fails, rate-limits or runs past the gate's budget)\n * leaves the policy to decide alone, as before this check. Base's public RPC\n * refused the sixth `eth_call` in a second, and parallel fetches are an\n * ordinary turn, so withholding on a failed read would drop the redirect on\n * funded wallets exactly when the router is used most, and a dead `rpcUrl`\n * would switch it off for good. The cost of the other direction needs an\n * empty wallet AND a failed read, and lasts one call. A `TENJIN_WALLET_KEY`\n * wallet is left to the policy too: its address takes a curve this chunk\n * does not load, and the file beside it is not the wallet that pays.\n */\nasync function spendShortfall(\n decision: { providerPriceAtomic: string; endpoint: string },\n deps: HookDeps,\n deadline: number,\n): Promise<Shortfall | null> {\n const price = `$${toMoney(decision.providerPriceAtomic).usd}`;\n const approval = (detail: string): Shortfall => ({\n withheld: 'offer needs approval',\n note: `Note: ${price} ${detail}; request will return needs_approval with the command the user runs to approve it — ask the user first.`,\n });\n let rpcUrl: string;\n try {\n const settings = await resolveContextSettings(hookContext(deps));\n const ledger = await readSpendSummary(deps.dataDir, {\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n });\n const evaluation = evaluateSpendPolicy(settings.policy, {\n amountAtomic: BigInt(decision.providerPriceAtomic),\n creator: new URL(decision.endpoint).host,\n sessionSpentAtomic: ledger === null ? 0n : spentOf(ledger),\n });\n if (evaluation.decision !== 'allow') {\n return approval(\n evaluation.reason === 'above_auto_spend'\n ? `is above this machine's automatic per-call limit ($${toMoney(settings.policy.maxAutoSpendAtomic.toString()).usd})`\n : \"needs approval under this machine's spend limits\",\n );\n }\n rpcUrl = settings.rpcUrl;\n } catch {\n return approval(\"needs approval under this machine's spend limits\");\n }\n if ((deps.env ?? process.env).TENJIN_WALLET_KEY?.trim()) return null;\n const address = await walletAddress(deps.dataDir);\n if (address === null) return null;\n // A balance read in the last minute stands: a burst of parallel lookups\n // otherwise asks the public RPC once each, past its rate limit.\n const readBalance = rememberingBalanceReader(deps.dataDir, {\n ...(deps.now !== undefined ? { now: deps.now } : {}),\n });\n const balance = await readBalance(address, rpcUrl, {\n timeoutMs: Math.min(BALANCE_TIMEOUT_MS, deadline - (deps.now?.() ?? Date.now())),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n });\n if (balance === null) {\n (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n `tenjin hook: the wallet's USDC balance could not be read from ${new URL(rpcUrl).host}, so the spend policy alone decides`,\n );\n return null;\n }\n return balance < BigInt(decision.providerPriceAtomic)\n ? {\n withheld: 'wallet needs USDC',\n note: `Note: the wallet holds $${toMoney(balance.toString()).usd}; fund it with \\`tenjin wallet fund\\`.`,\n }\n : null;\n}\n\n/** Why a paid call would not run on its own: the footer's words, and the\n * sentence a discovered offer carries instead of being withheld. */\ninterface Shortfall {\n withheld: string;\n note: string;\n}\n\n/**\n * AN OFFER, OR WHY IT IS NOT SHOWN. A curated offer the paid call could not\n * make good on alone is withheld, as it always was. A DISCOVERED one is never\n * withheld where someone can ask the user: it is the only line naming a\n * service that can do the step, so it is shown with one sentence saying the\n * call needs approval or funds, and the host asks first. Where nobody can ask\n * (a subagent's call, a delegated task) it is withheld like any other.\n *\n * An offer that is shown can still list OTHER services beside its own: a Tenjin\n * list menu, or an alternative after a curated line. One priced over the cap\n * gets a sentence saying so ({@link overCapNote}), so the host picks one that\n * runs rather than one that stops on `needs_approval`.\n */\nasync function vetOffer<T extends OfferDecision>(\n offer: T,\n deps: HookDeps,\n deadline: number,\n canAskUser: boolean,\n): Promise<{ offer: T; withheld?: undefined } | { withheld: string }> {\n const shortfall = await spendShortfall(termsOf(offer), deps, deadline);\n if (shortfall === null) {\n const note = await overCapNote(offer.hint, deps, canAskUser);\n return { offer: note === null ? offer : { ...offer, hint: `${offer.hint} ${note}` } };\n }\n if (offer.action === 'discovered' && canAskUser) {\n return { offer: { ...offer, hint: `${offer.hint} ${shortfall.note}` } };\n }\n return { withheld: shortfall.withheld };\n}\n\n/** Where the server (`lib/x402-router/policy.ts`) writes a price, and only\n * there: \"about $0.28 per call\" in a list entry, \"about $0.03: request(\" or\n * \"about $0.03 (price can vary\" in an alternative, \"$0.30): request(\" closing\n * a curated alternative, and \"$0.30 via https://\" for a curated offer's own\n * (already checked as a field, so it fits). A dollar amount anywhere else is\n * a description's words (\"seats from $500/month\"), never a price. */\nconst LISTED_PRICE_RE =\n /about \\$(\\d+(?:\\.\\d+)?)(?= per call|: request\\(| \\(price can vary)|\\$(\\d+(?:\\.\\d+)?)(?=\\): request\\(| via https?:\\/\\/)/g;\n\n/** A JSON string in the hint: the user's query, an id, or a seller's own words.\n * A dollar amount there is data (\"a laptop under $1000\"), never a price. */\nconst QUOTED_RE = /\"(?:[^\"\\\\]|\\\\.)*\"/g;\n\n/**\n * ONE SENTENCE FOR A LISTED SERVICE OVER THE AUTO-SPEND CAP, or null. The offer\n * itself already fits (it passed {@link spendShortfall}), so a price over the\n * cap here is another entry: People Data Labs at $0.28 beside a $0.005 email\n * finder, under a $0.25 cap, was picked and refused. Quiet when the hint\n * quotes no such price or the settings cannot be read.\n */\nasync function overCapNote(\n hint: string,\n deps: HookDeps,\n canAskUser: boolean,\n): Promise<string | null> {\n const listed = [...hint.replace(QUOTED_RE, '\"\"').matchAll(LISTED_PRICE_RE)].map(\n (match) => (match[1] ?? match[2]) as string,\n );\n if (listed.length === 0) return null;\n let cap: bigint;\n try {\n cap = (await resolveContextSettings(hookContext(deps))).policy.maxAutoSpendAtomic;\n } catch {\n return null;\n }\n const over = [\n ...new Set(\n listed.filter((usd) => {\n try {\n return BigInt(parseUsdToAtomic(usd)) > cap;\n } catch {\n return false;\n }\n }),\n ),\n ];\n if (over.length === 0) return null;\n const prices = over.map((usd) => `$${usd}`).join(' and ');\n const which = over.length > 1 ? 'those services' : 'that service';\n return (\n `Note: ${prices} ${over.length > 1 ? 'are' : 'is'} above this machine's automatic per-call limit ` +\n `($${toMoney(cap.toString()).usd}), so request returns needs_approval for ${which}; ` +\n (canAskUser\n ? 'prefer one within the limit, or ask the user first.'\n : 'use one within the limit.')\n );\n}\n\n/**\n * The wallet file's address, which `lib/wallet/store.ts` keeps top-level in\n * cleartext so it reads without a passphrase; null when there is none to read.\n * Read here rather than through the wallet module, which stays out of this\n * chunk graph.\n */\nasync function walletAddress(dataDir: string): Promise<string | null> {\n try {\n const record: unknown = JSON.parse(await readFile(walletPath(dataDir), 'utf8'));\n const address = (record as { address?: unknown } | null)?.address;\n return typeof address === 'string' && /^0x[0-9a-fA-F]{40}$/.test(address) ? address : null;\n } catch {\n return null;\n }\n}\n\nfunction agentLookup(cwd: string | undefined, deps: HookDeps): AgentLookup {\n return { ...(cwd !== undefined ? { cwd } : {}), homeDir: deps.homeDir ?? homedir() };\n}\n\n/** The context the hook's own library calls run in: JSON, silent, no TTY. */\nfunction hookContext(deps: HookDeps): CommandContext {\n return {\n flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },\n dataDir: deps.dataDir,\n io: { stdout: nullStream(), stderr: nullStream(), isTTY: false },\n };\n}\n\nexport interface PromptHookOutcome {\n /** What the harness is told, or null for \"nothing to say\". */\n response: unknown | null;\n skipped?: PromptSkip;\n action?: HookDecision['action'];\n /** The turn id, for the smoke to correlate against. */\n id?: string;\n /** An `execute` whose hint was not shown: the paid call would not run on its\n * own, for want of approval or of funds. */\n withheld?: true;\n}\n\n/**\n * `tenjin hook prompt` (UserPromptSubmit). One free decision from the user's\n * own words. Only an offer (`execute`, or a `discovered` service) gets a line:\n * the server's hint, attributed. `native`, `needs_input` and a decision that\n * failed or timed out are silence:\n * a turn with no lookup carries nothing extra, and `decide` has already written\n * any failure cause to stderr.\n *\n * THE HINT ASKS FOR A CALL THAT HAS TO RUN. Over the cap or past the budget,\n * `request` answers `needs_approval`, and a model sent there stops to ask the\n * user where its free tools would have done: so a curated line is shown only\n * when the paid call would auto-execute, the same rule the pre-call deny\n * follows. A discovered line is shown anyway, with a sentence saying it needs\n * approval or funds ({@link vetOffer}): it may be the only service for the step.\n */\nexport async function runPromptHook(raw: unknown, deps: HookDeps): Promise<PromptHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'prompt') return { response: null };\n return offerOnUserText(event, event.prompt, 'UserPromptSubmit', deps);\n}\n\n/**\n * `tenjin hook answer` (PostToolUse on `AskUserQuestion`). THE USER JUST\n * ANSWERED, which is a user turn in all but name: an answer like \"I can get an\n * API key\" is exactly when a pay-per-call service would do instead. So it is\n * routed the way a prompt is, with the answers as the current message and the\n * session's history before them, and an offer is added beside the answers the\n * host reads next. Anything else is no output at all.\n */\nexport async function runAnswerHook(raw: unknown, deps: HookDeps): Promise<PromptHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'answer' || event.answers === null) return { response: null };\n return offerOnUserText(event, event.answers, 'PostToolUse', deps);\n}\n\n/** The prompt route, for any text that is the user's own words this turn. */\nasync function offerOnUserText(\n event: { sessionId: string; transcriptPath?: string; cwd?: string },\n text: string,\n hookEventName: 'UserPromptSubmit' | 'PostToolUse',\n deps: HookDeps,\n): Promise<PromptHookOutcome> {\n const skipped = promptSkipReason(text);\n if (skipped !== null) return { response: null, skipped };\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { response: null };\n\n const sealed = seal(\n scoped(await buildPromptPacket(event.transcriptPath, event.sessionId, text), router.settings),\n );\n const footer = await openFooter(deps, event.sessionId, 'prompt');\n const deadline = gateDeadline(deps);\n const outcome = await decide(sealed, deps, router.config, event.sessionId);\n if (!isOffer(outcome)) {\n await footer.close(outcome);\n return { response: null, ...(outcome !== null ? { action: outcome.action } : {}) };\n }\n const vetted = await vetOffer(outcome, deps, deadline, true);\n if (vetted.withheld !== undefined) {\n await footer.close(outcome, { withheld: vetted.withheld });\n return { response: null, action: outcome.action, withheld: true };\n }\n await footer.close(outcome);\n return {\n action: outcome.action,\n id: outcome.id,\n ...injection(hookEventName, attributed(vetted.offer.hint)),\n };\n}\n\nfunction injection(\n hookEventName: 'UserPromptSubmit' | 'PostToolUse',\n line: string,\n): { response: unknown } {\n return { response: { hookSpecificOutput: { hookEventName, additionalContext: line } } };\n}\n\n/** What either native arm reports about itself; `response` is all the harness sees. */\nexport interface NativeHookOutcome {\n response: unknown | null;\n action?: HookDecision['action'];\n id?: string;\n /** An `execute` whose offer was not shown: the paid call would not run on\n * its own, for want of approval or of funds. */\n withheld?: true;\n /** No router call at all: the subagent is not known to have the request tool. */\n noRequestTool?: true;\n /** No redirect: this agent was already redirected on this same search or\n * URL. Found before the router was asked there is no `action`; only a\n * parallel copy that lost the claim after its decision carries one. */\n alreadyRedirected?: true;\n /** A free offer, which the pre-call arm never redirects: the call runs. */\n free?: true;\n /** And its docs are being fetched, to ride above the search's results. */\n augmenting?: true;\n}\n\nexport interface ShortfallHookOutcome extends NativeHookOutcome {\n /** What the harness reported, when it was a shortfall; absent means the\n * router was never asked. */\n nativeOutcome?: NativeOutcome;\n /** The pre-call arm already redirected this very call, so nothing more is said. */\n alreadyOffered?: true;\n /** The pre-call arm fetched free docs for this call: they were added to its\n * results, or there were none to add. Never an offer as well. */\n augmented?: 'added' | 'nothing';\n /** WebFetch saved a PDF whole, and the agent was pointed at it, free. */\n savedPdf?: true;\n}\n\ntype ExecuteDecision = Extract<HookDecision, { action: 'execute' }>;\n\n/**\n * AN ANSWER THAT OFFERS SOMETHING: a curated capability (`execute`), or a\n * pay-per-call service the server found for a step nothing curated serves\n * (`discovered`). Both carry an id and a finished line, and every hook shows\n * them in the same place, under the same spend and one-block rules.\n */\ntype OfferDecision = Extract<HookDecision, { action: 'execute' | 'discovered' }>;\n\nfunction isOffer(decision: HookDecision | null): decision is OfferDecision {\n return decision?.action === 'execute' || decision?.action === 'discovered';\n}\n\n/** What the spend check and the footer read, for either kind of offer. */\nfunction termsOf(offer: OfferDecision): {\n provider: string;\n providerPriceAtomic: string;\n endpoint: string;\n} {\n if (offer.action === 'execute') return offer;\n const { candidate } = offer;\n return {\n provider: candidate.provider,\n providerPriceAtomic: candidate.providerPriceAtomic,\n endpoint: candidate.url,\n };\n}\n\n/** A free curated offer: nothing to pay, so nothing for the spend policy or\n * the wallet. A discovered service is never one: it is always a sale. */\nfunction isFree(offer: OfferDecision): offer is ExecuteDecision {\n return offer.action === 'execute' && offer.providerPriceAtomic === '0';\n}\n\n/**\n * THE ONE ROUTE BOTH NATIVE ARMS TAKE, before the call and after it: the\n * agent's tool list, the packet from the right transcript, one free decision,\n * and the subagent spend rule. An `execute` that survives all of it comes back\n * as `offer`; everything else is the reason there is none. `repeated` is the\n * pre-call arm's one-block rule, asked only of an offer that would be shown;\n * `redirected` is its read half, asked before the router is, so a retry the\n * arm would only withhold costs no decision and writes no offer row.\n * `passFree` is the pre-call arm's too: a free offer comes back marked `free`,\n * with the base URL it was decided on, before the spend policy, the wallet or\n * `repeated` is asked, since it is never a redirect.\n */\nasync function routeNativeCall(\n event: Omit<NativeCall, 'tool' | 'pending'>,\n pending: PendingCall,\n deps: HookDeps,\n opts: {\n nativeOutcome?: NativeOutcome;\n repeated?: () => Promise<boolean>;\n redirected?: () => Promise<boolean>;\n passFree?: boolean;\n operation?: 'prompt' | 'search';\n /** False where a discovered offer must be affordable as it stands: the\n * call it would replace is the one way to reach the user. */\n canAskUser?: boolean;\n } = {},\n): Promise<\n | { offer: OfferDecision; free?: undefined }\n | { offer: ExecuteDecision; free: true; baseUrl: string }\n | { offer: null; outcome: NativeHookOutcome }\n> {\n const { nativeOutcome, repeated } = opts;\n // OFF MEANS NOTHING ABOUT THE TURN IS READ: the switch comes before the\n // agent lookup and the transcript, for both native arms.\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { offer: null, outcome: { response: null } };\n // A SUBAGENT IS ROUTED ONLY WHEN IT IS KNOWN TO HAVE THE TOOL: redirecting\n // or offering to one that cannot make the call strands it (#377). Decided\n // before the router is asked, so an unknown one costs nothing.\n if (\n event.agentId !== undefined &&\n (await requestToolAccess(event.agentType, agentLookup(event.cwd, deps))) !== 'allowed'\n ) {\n return { offer: null, outcome: { response: null, noRequestTool: true } };\n }\n // ALREADY REDIRECTED HERE: the retry the one-block rule lets run. Asking the\n // router first cost a gate decision and wrote an offer row nobody saw, about\n // 45% of an active session's rows. The claim after the decision still\n // settles two parallel copies of one call.\n if (opts.redirected !== undefined && (await opts.redirected())) {\n const footer = await openFooter(deps, event.sessionId, opts.operation ?? 'search');\n await footer.close(null, { withheld: 'already redirected once' });\n return { offer: null, outcome: { response: null, alreadyRedirected: true } };\n }\n // THE USER'S WORDS COME WITH IT. Building this from the tool argument alone\n // made the search string the whole conversation, so \"native tools only, no\n // paid services\" never reached this gate. Inside a subagent, its own task\n // comes first: see `buildNativePacket`.\n const sealed = seal(\n scoped(\n await buildNativePacket(event.transcriptPath, event.sessionId, pending, {\n ...(event.agentId !== undefined ? { agentId: event.agentId } : {}),\n ...(nativeOutcome !== undefined ? { nativeOutcome } : {}),\n }),\n router.settings,\n ),\n );\n const { packet } = sealed;\n // A LOCAL TARGET ONLY EVER HAS A NATIVE ANSWER, so asking costs a round trip\n // and sends the conversation for nothing.\n if (sealed.localTarget) return { offer: null, outcome: { response: null } };\n // A CREDENTIAL IN THE SEARCH OR URL NEVER LEAVES. Sending it masked would put\n // the mask into the hint the server writes from it, and the model would call\n // the provider with the mask. The call stays native.\n if (sealed.subjectChanged) {\n (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n 'tenjin hook: the native call carries a credential-shaped value, so it is not routed',\n );\n return { offer: null, outcome: { response: null } };\n }\n // AND WHEN THEY CANNOT BE READ, NOTHING IS OFFERED. An offer routed on the\n // tool argument alone is how an instruction the user gave this turn gets\n // overruled by a decision that never saw it.\n if (packet.historyStatus !== 'ok') {\n (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n \"tenjin hook: this session's transcript could not be read, so no paid lookup is offered\",\n );\n return { offer: null, outcome: { response: null } };\n }\n const footer = await openFooter(deps, event.sessionId, opts.operation ?? 'search');\n const deadline = gateDeadline(deps);\n const outcome = await decide(sealed, deps, router.config, event.sessionId);\n if (!isOffer(outcome)) {\n await footer.close(outcome);\n return {\n offer: null,\n outcome: { response: null, ...(outcome !== null ? { action: outcome.action } : {}) },\n };\n }\n if (opts.passFree === true && isFree(outcome)) {\n await footer.close(outcome, { withheld: 'free lookup, call runs' });\n return { offer: outcome, free: true, baseUrl: resolveBaseUrl(deps, router.config) };\n }\n const vetted = await vetOffer(\n outcome,\n deps,\n deadline,\n event.agentId === undefined && opts.canAskUser !== false,\n );\n if (vetted.withheld !== undefined) {\n await footer.close(outcome, { withheld: vetted.withheld });\n return { offer: null, outcome: { response: null, action: outcome.action, withheld: true } };\n }\n if (repeated !== undefined && (await repeated())) {\n await footer.close(outcome, { withheld: 'already redirected once' });\n return {\n offer: null,\n outcome: { response: null, action: outcome.action, alreadyRedirected: true },\n };\n }\n await footer.close(outcome);\n return { offer: vetted.offer };\n}\n\n/**\n * `tenjin hook native` (PreToolUse on `WebSearch|WebFetch`). PER-LOOKUP\n * ROUTING BEFORE THE CALL, exactly as main: a clear offer denies the native\n * call with the server's hint as the reason, carrying the id so the redirected\n * call runs the decision just made. Anything else, including silence, a slow\n * backend and a `needs_input`, lets the call run with no output at all.\n *\n * WHAT IS NEW is who can be denied. A subagent not known to have the request\n * tool, or whose spend would need an approval it cannot ask for, is never\n * redirected: `routeNativeCall` answers without an offer, and its\n * call runs free. Neither is the main agent when the paid call would stop on\n * `needs_approval` or its wallet cannot cover the price: its free call runs,\n * and the after-call arm can still offer.\n *\n * A redirect leaves a mark under the call's `tool_use_id`, so the after-call\n * arm never offers on that same call.\n *\n * NEVER REDIRECTED TWICE FOR ONE TARGET. A redirect claims its exact search or\n * URL for this agent first ({@link claimRedirect}). A call on a target this\n * agent was already redirected on runs without asking the router at all\n * ({@link redirectClaimed}), however its lookup went and whatever other calls\n * ran in between; a parallel copy that got past that check loses the claim\n * after its decision and runs too. Parallel calls each hold their own claim,\n * so none can spend another's. Any other target gets its own redirect.\n *\n * A FREE OFFER IS NEVER A REDIRECT. Denying a search for the free docs lookup\n * sent the agent on a detour, and round a loop when the docs missed. The call\n * runs with no output and nothing is recorded against it; on a WebSearch the\n * docs are fetched meanwhile and the after-call arm adds them above the\n * search's results (`augment.ts`). A WebFetch just runs.\n */\nexport async function runNativeHook(raw: unknown, deps: HookDeps): Promise<NativeHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'native' || event.pending === null) return { response: null };\n const target = redirectTarget(event.pending);\n const routed = await routeNativeCall(event, event.pending, deps, {\n passFree: true,\n repeated: async () =>\n !(await claimRedirect(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.())),\n redirected: () =>\n redirectClaimed(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.()),\n });\n if (routed.offer === null) return routed.outcome;\n if (routed.free === true) {\n const { pending } = event;\n const augmenting =\n pending.tool === 'WebSearch' &&\n (await startAugment(\n {\n sessionId: event.sessionId,\n query: pending.query,\n ...(event.agentId !== undefined ? { agentId: event.agentId } : {}),\n ...(event.toolUseId !== undefined ? { toolUseId: event.toolUseId } : {}),\n },\n routed.offer,\n routed.baseUrl,\n deps,\n ));\n return {\n response: null,\n action: 'execute',\n id: routed.offer.id,\n free: true,\n ...(augmenting ? { augmenting: true as const } : {}),\n };\n }\n if (event.toolUseId !== undefined) {\n await markOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.());\n }\n return redirect(routed.offer);\n}\n\n/**\n * Deny the call once with the server's line: the redirect both pre-call arms\n * make, after `routeNativeCall` has claimed its target ({@link claimRedirect}).\n */\nfunction redirect(offer: OfferDecision, oneBlock = ONE_BLOCK): NativeHookOutcome {\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: 'deny',\n // THE SERVER'S LINE, attributed and tool-named, then this client's one\n // sentence. The line already carries the id and the exact search, URL\n // or question that was denied.\n permissionDecisionReason: `${attributed(offer.hint)} ${oneBlock}`,\n },\n },\n action: offer.action,\n id: offer.id,\n };\n}\n\n/**\n * `tenjin hook ask` (PreToolUse on `AskUserQuestion`). THE HOST IS ABOUT TO\n * ASK THE USER FOR SOMETHING, often an API key or an account for a one-off\n * step, which is the moment a pay-per-call service could answer instead. The\n * questions and their options ride as the pending call, and an offer denies\n * the question once with the server's line: never twice for the same\n * question, and a free offer never denies anything. The host can ask again,\n * and that question runs.\n *\n * AN OFFER THE CALL COULD NOT MAKE GOOD ON ALONE NEVER TAKES THE QUESTION'S\n * PLACE. Elsewhere a discovered offer over the cap or the balance is shown\n * with a note telling the host to ask the user first; here the question IS\n * the asking, so denying it to say \"ask the user\" strands the turn. Any\n * shortfall, curated or discovered, withholds the offer and the question runs.\n */\nexport async function runAskHook(raw: unknown, deps: HookDeps): Promise<NativeHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'ask' || event.pending === null) return { response: null };\n // The question itself is the target, claimed exactly as a search or a URL is.\n const target = redirectTarget(event.pending);\n const routed = await routeNativeCall(event, event.pending, deps, {\n passFree: true,\n operation: 'prompt',\n canAskUser: false,\n repeated: async () =>\n !(await claimRedirect(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.())),\n redirected: () =>\n redirectClaimed(deps.dataDir, event.sessionId, event.agentId, target, deps.now?.()),\n });\n if (routed.offer === null) return routed.outcome;\n if (routed.free === true) {\n return { response: null, action: routed.offer.action, id: routed.offer.id, free: true };\n }\n return redirect(routed.offer, ONE_BLOCK_QUESTION);\n}\n\n/**\n * `tenjin hook shortfall` (PostToolUse and PostToolUseFailure on\n * `WebSearch|WebFetch`). THE FREE TOOL HAS ALREADY RUN, and a result that is\n * fine ends here: no router call, no footer, no added latency. Only a clear\n * shortfall ({@link shortfallOf}) asks for one free decision, with what the\n * harness reported riding in the packet as `nativeOutcome`, and only an offer\n * (`execute` or `discovered`) says anything. A call the pre-call arm already redirected is not\n * offered on again. The one free line is a PDF WebFetch saved whole: the agent\n * is pointed at the file, and the router is not asked.\n *\n * A SEARCH THE PRE-CALL ARM IS FETCHING FREE DOCS FOR waits for them first,\n * the one wait in the hook, bounded by `AUGMENT_WAIT_MS`. When docs came back\n * they go on top of its results (`updatedToolOutput`, the response the harness\n * reported with one string prepended to `results`), and that call is not\n * offered on as well. When none were added (no match, a refusal, a timeout, or\n * a call that failed outright) it is an ordinary call from there: a search that\n * came back fine says nothing, and one that came back short takes the shortfall\n * route like any other, so a failed docs lookup never costs it the paid offer.\n * The wait and that decision can follow one another, which is why this entry's\n * timeout is longer than the others' (`wire.test.ts` pins the sum).\n *\n * A server that does not know `nativeOutcome` yet refuses the packet; that is\n * a failed decision like any other, so the hook stays silent.\n */\nexport async function runShortfallHook(\n raw: unknown,\n deps: HookDeps,\n): Promise<ShortfallHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'shortfall') return { response: null };\n const augment = await finishAugment(\n {\n sessionId: event.sessionId,\n search: event.search,\n ...(event.toolUseId !== undefined ? { toolUseId: event.toolUseId } : {}),\n },\n deps,\n );\n if (augment !== null && augment.updatedToolOutput !== null) {\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PostToolUse',\n updatedToolOutput: augment.updatedToolOutput,\n },\n },\n augmented: 'added',\n };\n }\n if (event.savedPdf !== null) return await pointAtSavedPdf(event, event.savedPdf, deps);\n const outcome = await offerOnShortfall(event, deps, augment !== null);\n return augment === null ? outcome : { ...outcome, augmented: 'nothing' };\n}\n\n/**\n * A PDF WEBFETCH SAVED IS READ FOR FREE. Its summary was handed the compressed\n * bytes and says it cannot parse them, but the harness saved the file whole,\n * and `Read` returns every page. So the line says that, and the router is\n * never asked: a paid reader would only fetch the same file again. Silent when\n * `router.enabled` is off, like every other line this hook writes.\n */\nasync function pointAtSavedPdf(\n event: Extract<HookEvent, { kind: 'shortfall' }>,\n path: string,\n deps: HookDeps,\n): Promise<ShortfallHookOutcome> {\n if ((await routerFor(event.cwd, deps)) === null) return { response: null };\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: event.eventName,\n additionalContext: savedPdfHint(path),\n },\n },\n savedPdf: true,\n };\n}\n\n/** The shortfall route itself: ask about a call that came back short, once. */\nasync function offerOnShortfall(\n event: Extract<HookEvent, { kind: 'shortfall' }>,\n deps: HookDeps,\n docsJustMissed = false,\n): Promise<ShortfallHookOutcome> {\n const { nativeOutcome, pending, eventName } = event;\n if (nativeOutcome === null) return { response: null };\n if (pending === null) return { response: null };\n if (\n event.toolUseId !== undefined &&\n (await wasOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.()))\n ) {\n return { response: null, nativeOutcome, alreadyOffered: true };\n }\n const routed = await routeNativeCall(event, pending, deps, { nativeOutcome });\n if (routed.offer === null) return { ...routed.outcome, nativeOutcome };\n // The free docs lookup for this very search just came back empty: offering\n // it again would send the agent to the same miss. Only a paid offer stands.\n if (docsJustMissed && isFree(routed.offer))\n return { response: null, nativeOutcome, action: 'execute' };\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: eventName,\n // THE SERVER'S LINE, attributed and framed as the option it is. It\n // already carries the id and the exact search or URL that came back short.\n additionalContext: shortfallOffer(event.tool, routed.offer.hint),\n },\n },\n nativeOutcome,\n action: routed.offer.action,\n id: routed.offer.id,\n };\n}\n\nexport interface DelegationHookOutcome {\n response: unknown | null;\n action?: HookDecision['action'];\n id?: string;\n withheld?: true;\n noRequestTool?: true;\n}\n\n/**\n * `tenjin hook agent` (PreToolUse on `Agent|Task`). The one moment a subagent's\n * whole assignment is visible: its task prompt IS the current message, and the\n * parent's own turn is the history, so the router decides on exactly what the\n * subagent will do. On a clear offer, it is appended to that task as\n * one optional line, which reaches the subagent as part of its instructions\n * from its parent, before it starts. Anything else is no output at all.\n *\n * The subagent will be the payer, so the same auto-execute rule applies here.\n */\nexport async function runDelegationHook(\n raw: unknown,\n deps: HookDeps,\n): Promise<DelegationHookOutcome> {\n const event = decodeEvent(raw);\n if (event?.kind !== 'delegation') return { response: null };\n const { task } = event;\n if (task === null || task.trim().length === 0) return { response: null };\n const router = await routerFor(event.cwd, deps);\n if (router === null) return { response: null };\n // The subagent this task goes to is the one that would have to make the\n // call, so the same rule: only a type known to have the tool is offered. With\n // no type the harness runs its general-purpose agent, which inherits it.\n if ((await requestToolAccess(event.subagentType, agentLookup(event.cwd, deps))) !== 'allowed') {\n return { response: null, noRequestTool: true };\n }\n const sealed = seal(\n scoped(await buildPromptPacket(event.transcriptPath, event.sessionId, task), router.settings),\n );\n // The native hook's two rules, with the task as the subject: a task the mask\n // would change is not sent, since the offer is written back into it, and a\n // task naming a local target only ever has a native answer.\n if (sealed.localUrl) return { response: null };\n if (sealed.currentChanged) {\n (deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`)))(\n 'tenjin hook: the delegated task carries a credential-shaped value, so it is not routed',\n );\n return { response: null };\n }\n // The native hook's rule, for the same reason: a delegation routed without\n // the user's words could offer what they just ruled out.\n if (sealed.packet.historyStatus !== 'ok') return { response: null };\n const footer = await openFooter(deps, event.sessionId, 'delegate');\n const deadline = gateDeadline(deps);\n const outcome = await decide(sealed, deps, router.config, event.sessionId);\n if (!isOffer(outcome)) {\n await footer.close(outcome);\n return { response: null, ...(outcome !== null ? { action: outcome.action } : {}) };\n }\n // The subagent will make the call and cannot ask the user, so nothing it\n // could not pay for alone is offered to it.\n const vetted = await vetOffer(outcome, deps, deadline, false);\n if (vetted.withheld !== undefined) {\n await footer.close(outcome, { withheld: vetted.withheld });\n return { response: null, action: outcome.action, withheld: true };\n }\n await footer.close(outcome);\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n // The whole input, with one line appended: `updatedInput` replaces it.\n updatedInput: {\n ...event.toolInput,\n prompt: `${task}\\n\\n${delegationOffer(outcome.hint)}`,\n },\n },\n },\n action: outcome.action,\n id: outcome.id,\n };\n}\n\n/**\n * THE HOOK STAGE, WHICH IS THE ONE THE DEMO OPENS WITH. The decision is in\n * flight for about a second, and at a one-second refresh a state that is\n * written and then erased inside that second is a state nobody ever sees. So\n * the record is not cleared: `selecting service` is REPLACED by what the\n * decision turned out to be, and that outcome holds the line until the next\n * state arrives or its hold runs out.\n *\n * Display only. Every write inside swallows its own failure, and a shown offer\n * also leaves the id-to-session binding the tool resolves its progress through,\n * and the request specs the line names, which the tool reads by id.\n */\nasync function openFooter(\n deps: HookDeps,\n sessionId: string,\n operation: 'prompt' | 'search' | 'delegate',\n): Promise<{\n /** `withheld` is why an `execute` was not shown, in the footer's words. */\n close: (decision: HookDecision | null, opts?: { withheld?: string }) => Promise<void>;\n}> {\n const now = (): number => deps.now?.() ?? Date.now();\n const directory = sessionDir(deps.dataDir, sessionId);\n const callId = newCallId();\n await noteSession(deps.dataDir, sessionId, now());\n await writeProgress(\n directory,\n callId,\n { phase: 'routing', operation, outcome: 'selecting service' },\n now(),\n );\n await pruneProgress(directory, now());\n // The root, not just this session: a directory per session ever opened would\n // eventually be more than the resolver can scan.\n await pruneSessions(deps.dataDir, now());\n return {\n close: async (decision, opts) => {\n const withheld = opts?.withheld;\n await writeProgress(\n directory,\n callId,\n {\n phase: 'done',\n operation,\n outcome: withheld !== undefined ? `native tools (${withheld})` : hookOutcome(decision),\n },\n now(),\n );\n if (withheld === undefined && isOffer(decision)) {\n await bindDecision(deps.dataDir, sessionId, decision.id, now());\n // The line is shown, so the specs of the services it names are what\n // `request({id, input})` runs and `request({id})` shows.\n await storeSpecs(deps.dataDir, decision.specs);\n }\n },\n };\n}\n\n/** What the gate decided, in the footer's own words. A silent backend is not a\n * blank line: the turn runs on native tools and the footer says which. */\nfunction hookOutcome(decision: HookDecision | null): string {\n if (decision === null) return 'native tools (router unavailable)';\n if (isOffer(decision)) return `paid lookup offered (${termsOf(decision).provider})`;\n if (decision.action === 'native') return 'native tools (no x402 payment)';\n return 'needs input';\n}\n\n/** One free decision, with the hook's own deadline and its own silence. It\n * takes what {@link seal} returns rather than a bare packet, so a call site\n * that skips the mask does not typecheck. */\nasync function decide(\n { packet }: Sealed,\n deps: HookDeps,\n config: PartialConfig,\n sessionId: string,\n): Promise<HookDecision | null> {\n const baseUrl = resolveBaseUrl(deps, config);\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const outcome = await requestDecision(\n 'hook',\n { packet, sessionId },\n {\n ctx: hookContext(deps),\n baseUrl,\n acceptsBazaar: resolveExperimentalBazaar(config).value === 'on',\n timeoutMs: deps.timeoutMs ?? GATE_TIMEOUT_MS,\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n },\n );\n if (outcome.status === 'failed') {\n warn(`tenjin hook: ${baseUrl}${ROUTER_PATH} ${outcome.reason}`);\n return null;\n }\n return outcome.decision.decision;\n}\n\n/** The hooks write their own protocol answer on stdout and nothing else. */\nfunction nullStream(): NodeJS.WritableStream {\n return { write: () => true } as unknown as NodeJS.WritableStream;\n}\n\n/**\n * What one redirect is for: the search as the agent wrote it, or the URL as\n * `URL` parses it, so a retry that differs only in how the URL is spelled is\n * still the same call.\n */\nfunction redirectTarget(pending: PendingCall): string {\n if (pending.tool === 'WebSearch') return `WebSearch ${pending.query}`;\n if (pending.tool === 'AskUserQuestion') return `AskUserQuestion ${pending.question}`;\n let url = pending.url;\n try {\n url = new URL(url).toString();\n } catch {\n // Not a URL the parser takes: the agent's own spelling is the target.\n }\n return `WebFetch ${url}`;\n}\n\nfunction pendingCallOf(\n tool: 'WebSearch' | 'WebFetch',\n input: Record<string, unknown>,\n): PendingCall | null {\n const value = tool === 'WebSearch' ? input.query : input.url;\n if (typeof value !== 'string') return null;\n // Not cut here: seal() masks the subject first and bounds it after, so a\n // token crossing the bound is seen whole by the mask.\n const subject = value.trim();\n if (subject.length === 0) return null;\n return tool === 'WebSearch' ? { tool, query: subject } : { tool, url: subject };\n}\n\n/**\n * `router.*` for the event's directory with the global config it came from,\n * which is read ONCE per event and also names the base URL; null when the\n * router is off there. FIRST, before any packet is built: `router.enabled\n * false` means nothing about this turn is read for the router or leaves the\n * machine. A config that cannot be read is off too, since a switch the user\n * set must not fail open.\n */\nasync function routerFor(\n cwd: string | undefined,\n deps: HookDeps,\n): Promise<{ settings: RouterSettings; config: PartialConfig } | null> {\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n try {\n const config = await loadRawConfig(deps.dataDir);\n const settings = await routerSettings(\n { cwd: cwd ?? process.cwd(), dataDir: deps.dataDir, config },\n { warn: (line) => warn(`tenjin hook: ${line}`) },\n );\n return settings.enabled.value ? { settings, config } : null;\n } catch (err) {\n warn(`tenjin hook: ${err instanceof Error ? err.message : String(err)}, so the router is off`);\n return null;\n }\n}\n\n/**\n * `router.context turn`: the current turn and nothing before it. `current` is\n * kept (the prompt, the latest user message on a native call, the task on a\n * delegation) so an instruction given this turn still reaches the gate;\n * `historyStatus` is left as read, so a call whose turn could not be found is\n * still offered nothing.\n */\nfunction scoped(packet: Packet, router: RouterSettings): Packet {\n return router.context.value === 'turn' ? { ...packet, history: [] } : packet;\n}\n","import { open } from 'node:fs/promises';\nimport { isIP } from 'node:net';\nimport { dirname, join } from 'node:path';\nimport { isPublicAddress } from '../lib/destination';\nimport { mask } from '../lib/redact';\n\n/**\n * The bounded conversation packet the router's gate and paid decision read.\n *\n * WHAT GOES IN IT: ordinary user and assistant text from the CURRENT session\n * only (and, for a subagent's own native call, that one subagent's rows), at\n * most {@link MAX_HISTORY} prior messages and at most {@link MAX_PACKET_BYTES}\n * in total, oldest dropped first. The builders below choose the text;\n * {@link seal} masks and bounds it, and is the only way a packet reaches the\n * wire. Tool results are excluded: a tool result is other people's content,\n * and a packet that carried it would be a channel from a fetched page into a\n * routing decision.\n *\n * WHAT NEVER HAPPENS: a transcript this reader cannot vouch for is reported\n * as `unavailable` rather than partially believed, and the user's turn is\n * never blocked by any of that. Another session's rows, a subagent sidechain,\n * malformed rows and everything before a compaction boundary are skipped row\n * by row. A file over {@link MAX_TRANSCRIPT_BYTES} is read from its tail\n * ({@link readTail}), where this turn's own words are. Adapted from the draft\n * auto-mode experiment (PR #369 `context.ts`), whose 48,000-character reader\n * this tightens.\n */\n\nexport const MAX_HISTORY = 6;\nexport const MAX_PACKET_BYTES = 16 * 1024;\n/** Every bound here is the server's own (tenjin `lib/x402-router/wire.ts`). A\n * packet this side lets through and that side refuses is a paid 400. */\nexport const MAX_MESSAGE_CHARS = 16_000;\n/** How much of a transcript is read: all of a smaller one, the last this many\n * bytes of a larger one. A long working session passes 4 MB in a day. */\nconst MAX_TRANSCRIPT_BYTES = 4_000_000;\nconst MAX_LITERAL_URLS = 8;\nconst MAX_LITERAL_URL_CHARS = 2_000;\nconst MAX_PENDING_CHARS = 4_000;\n/** The server's cap on a native outcome's error text. */\nconst MAX_OUTCOME_ERROR_CHARS = 1_000;\n/** Scanned past each bound: longer than any secret shape the mask knows. */\nconst MASK_MARGIN = 4_096;\n\nexport type PacketRole = 'user' | 'assistant';\nexport interface PacketMessage {\n role: PacketRole;\n text: string;\n}\n\nexport type HistoryStatus = 'ok' | 'unavailable';\n\nexport interface Packet {\n current: PacketMessage;\n history: PacketMessage[];\n /** Absolute http(s) URLs written literally in the current message. */\n literalUrls: string[];\n historyStatus: HistoryStatus;\n pendingCall?: PendingCall;\n /** How the free tool already fared on `pendingCall`, sent only when it fell\n * short. Never without `pendingCall`: the server refuses it alone. */\n nativeOutcome?: NativeOutcome;\n}\n\n/** What the harness reported about a native call that came back short: its\n * status and size (WebFetch), or the error a failed call carried. At least one\n * field, always; the server's schema is the same strict object. */\nexport interface NativeOutcome {\n code?: number;\n bytes?: number;\n error?: string;\n /** Why a call whose status and size look fine still came back short. */\n reason?: NativeShortfallReason;\n}\n\n/**\n * The client's own reading of a native result, named where the code and the\n * size say nothing. `no_main_content`: WebFetch answered 2xx with a full body,\n * and its summary says the page was empty, only a title, navigation or a\n * footer, or needed JavaScript it did not run (a script-rendered app, a video\n * page) (`readsAsEmptyPage`). The server picks the reader from the URL.\n */\nexport type NativeShortfallReason = 'no_main_content';\n\n/** The pending native call, INSIDE the packet: the gate request is a strict\n * object with exactly `schemaVersion`, `source` and `packet`. An\n * `AskUserQuestion` carries the host's own question and its options, joined. */\nexport type PendingCall =\n | { tool: 'WebSearch'; query: string }\n | { tool: 'WebFetch'; url: string }\n | { tool: 'AskUserQuestion'; question: string };\n\n/** The one string a pending call is about: its search, its URL or its question. */\nexport function subjectOf(pending: PendingCall): string {\n return 'query' in pending ? pending.query : 'url' in pending ? pending.url : pending.question;\n}\n\n/** The same call about a different subject, of the same kind. */\nfunction withSubject(pending: PendingCall, subject: string): PendingCall {\n if ('query' in pending) return { tool: pending.tool, query: subject };\n if ('url' in pending) return { tool: pending.tool, url: subject };\n return { tool: pending.tool, question: subject };\n}\n\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)\\]]+/gi;\n\nexport function literalUrlsIn(text: string): string[] {\n const found = new Set<string>();\n for (const match of text.matchAll(URL_RE)) {\n const candidate = match[0].replace(/[.,;:!?]+$/, '');\n try {\n const normalized = new URL(candidate).toString();\n if (normalized.length <= MAX_LITERAL_URL_CHARS) found.add(normalized);\n } catch {\n continue;\n }\n if (found.size >= MAX_LITERAL_URLS) break;\n }\n return [...found];\n}\n\n/**\n * Bring the packet inside the server's caps: oldest history first, then the\n * current message itself, measured on the WHOLE packet rather than on the two\n * message lists, because `literalUrls` and a pending call are bytes too.\n *\n * EXPORTED BECAUSE ATTACHING ANYTHING RE-OPENS THE QUESTION. A packet this\n * returned at exactly the cap is over it the moment a caller adds a field, and\n * the server refuses rather than truncates, so every caller that adds one runs\n * this again on what it is actually going to send.\n */\nexport function fit(packet: Packet): Packet {\n const size = (value: Packet): number => Buffer.byteLength(JSON.stringify(value));\n const next: Packet = { ...packet, history: packet.history.slice(-MAX_HISTORY) };\n // In order of what is cheapest to lose. History first: a prior turn is\n // context. Then the literal URLs, which are a convenience the server can\n // re-derive from the text. The current message LAST, because it is the task\n // itself, and only down to one character, so a packet is never empty.\n while (next.history.length > 0 && size(next) > MAX_PACKET_BYTES) {\n next.history = next.history.slice(1);\n }\n while (next.literalUrls.length > 0 && size(next) > MAX_PACKET_BYTES) {\n next.literalUrls = next.literalUrls.slice(0, -1);\n }\n while (size(next) > MAX_PACKET_BYTES && next.current.text.length > 1) {\n const over = size(next) - MAX_PACKET_BYTES;\n const keep = Math.max(1, next.current.text.length - Math.max(over, 1));\n next.current = { ...next.current, text: next.current.text.slice(0, keep) };\n }\n return next;\n}\n\nexport interface Sealed {\n packet: Packet;\n /** The mask changed the pending call's search or URL. */\n subjectChanged: boolean;\n /** The pending WebFetch targets this machine or a private network. */\n localTarget: boolean;\n /** The mask changed the current message. */\n currentChanged: boolean;\n /** A literal URL in the packet targets this machine or a private network. */\n localUrl: boolean;\n}\n\n/**\n * THE ONE OUTBOUND CHOKEPOINT. Every string that leaves in a hook packet is\n * masked here, `current`, `history`, `literalUrls` and the pending call alike,\n * and only then bounded ({@link maskWithin}): a secret cut in half by a bound\n * before the mask no longer matches its row, and its first half would leave. The server stores\n * the packet against the id, so a secret here is a secret in its database.\n *\n * It also says what the caller must not send at all. A masked subject would\n * become the query the server writes into its hint, and a local or private\n * target can only ever be answered natively; both run unrouted.\n */\nexport function seal(packet: Packet): Sealed {\n const pending = packet.pendingCall;\n const subject = pending === undefined ? '' : subjectOf(pending);\n const sealedSubject = maskWithin(subject, MAX_PENDING_CHARS);\n const bound = (text: string): string => maskWithin(text, MAX_MESSAGE_CHARS).text;\n const sealedCurrent = maskWithin(packet.current.text, MAX_MESSAGE_CHARS);\n const current = sealedCurrent.text;\n const outcome = packet.nativeOutcome;\n const sealed = fit({\n current: { role: packet.current.role, text: current.length > 0 ? current : '(no task text)' },\n history: packet.history\n .slice(-MAX_HISTORY)\n .map((message) => ({ role: message.role, text: bound(message.text) }))\n .filter((message) => message.text.length > 0),\n literalUrls: packet.literalUrls\n .filter((url) => !isLocalTarget(url))\n .map(mask)\n .filter((url) => url.length <= MAX_LITERAL_URL_CHARS),\n historyStatus: packet.historyStatus,\n ...(pending === undefined ? {} : { pendingCall: withSubject(pending, sealedSubject.text) }),\n ...(outcome === undefined\n ? {}\n : {\n nativeOutcome: {\n ...outcome,\n ...(outcome.error !== undefined\n ? { error: maskWithin(outcome.error, MAX_OUTCOME_ERROR_CHARS).text }\n : {}),\n },\n }),\n });\n return {\n packet: sealed,\n subjectChanged: sealedSubject.changed,\n localTarget: pending !== undefined && 'url' in pending && isLocalTarget(pending.url),\n currentChanged: sealedCurrent.changed,\n localUrl: packet.literalUrls.some(isLocalTarget),\n };\n}\n\n/**\n * MASKED, THEN BOUNDED, over a window: the mask scans what can be sent plus a\n * margin longer than any secret shape, so its cost is bounded however large\n * the input, and a secret crossing `max` is seen whole before the cut. A PEM\n * block that opens inside the window is masked to the window's end. When the\n * window itself cut the text, the last `MASK_MARGIN` characters of its masked\n * form are never sent either: a secret cut at the window's edge can sit there\n * after earlier masks shortened the text, and must not leave in part.\n */\nfunction maskWithin(text: string, max: number): { text: string; changed: boolean } {\n const window = text.slice(0, max + MASK_MARGIN);\n const masked = mask(window);\n const limit = window.length < text.length ? Math.min(max, masked.length - MASK_MARGIN) : max;\n return { text: masked.slice(0, Math.max(0, limit)), changed: masked !== window };\n}\n\nconst LOCAL_NAME = /(?:^|\\.)(?:localhost|local)$/i;\n\n/**\n * A URL no public service can fetch: another scheme, a `localhost` or `.local`\n * name, or a literal address that is not public (loopback, private,\n * link-local, IPv6 ULA and the other reserved ranges `isPublicAddress` knows).\n * A string that does not parse as a URL is not a public target either.\n */\nfunction isLocalTarget(raw: string): boolean {\n let url: URL;\n try {\n url = new URL(raw);\n } catch {\n return true;\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return true;\n const host = url.hostname.replace(/^\\[|\\]$/g, '');\n if (LOCAL_NAME.test(host)) return true;\n return isIP(host) !== 0 && !isPublicAddress(host);\n}\n\n/**\n * A packet for a caller that has no conversation to send: the query itself is\n * the current message, because the server's message text is `min(1)` and an\n * empty one is a 400 after the routing fee has already settled.\n */\nexport function packetForText(text: string): Packet {\n const bounded = text.trim().slice(0, MAX_MESSAGE_CHARS);\n return fit({\n current: { role: 'user', text: bounded.length > 0 ? bounded : '(no task text)' },\n history: [],\n literalUrls: literalUrlsIn(bounded),\n historyStatus: 'unavailable',\n });\n}\n\n/**\n * Build the packet for one user prompt. `transcriptPath` is the harness's own\n * path for this session; an absent or unusable one yields `unavailable`. The\n * result is neither masked nor bounded: {@link seal} does both.\n */\nexport async function buildPromptPacket(\n transcriptPath: string | undefined,\n sessionId: string,\n prompt: string,\n): Promise<Packet> {\n const trimmed = prompt.trim();\n const text = trimmed.length > 0 ? trimmed : '(empty prompt)';\n const read = await readHistory(transcriptPath, { sessionId });\n return {\n current: { role: 'user', text },\n history: read ?? [],\n literalUrls: literalUrlsIn(text),\n historyStatus: read === null ? 'unavailable' : 'ok',\n };\n}\n\n/**\n * Build the packet for a native call, before it runs or after it came back\n * short. The same reader as a prompt packet, with tool results excluded, and\n * the same {@link seal} before it is sent.\n *\n * THE USER'S WORDS ARE WHAT CARRY THEIR AUTHORITY. Building this packet from\n * the tool argument alone made the search string the entire conversation, so a\n * turn that said \"native tools only, no paid services\" reached the prompt gate\n * and never reached this one: the same session could then be redirected to a\n * paid provider on a bare URL. Reading the transcript at the hook event is not\n * session guessing; the harness hands this hook the path to its own session.\n *\n * The call rides INSIDE the packet as `pendingCall`, with how it fared beside\n * it as `nativeOutcome`: the shape the route takes, pinned by\n * `wire-hook-request-native-shortfall.json`.\n */\nexport async function buildNativePacket(\n transcriptPath: string | undefined,\n sessionId: string,\n pending: PendingCall,\n opts: { agentId?: string; nativeOutcome?: NativeOutcome } = {},\n): Promise<Packet> {\n const { agentId, nativeOutcome } = opts;\n const subject = subjectOf(pending);\n const read = await readHistory(transcriptPath, { sessionId });\n // A SUBAGENT'S CALL BELONGS TO ITS OWN TASK. The harness hands every\n // subagent hook the PARENT's transcript, whose latest user message is not\n // what this subagent was asked to do, so two subagents with different\n // assignments sent the same packet (tenjin-agent#377). Its own transcript\n // opens with the delegated task; the parent's messages stay in front of it\n // as history, which is how a restriction the user gave the parent still\n // reaches this call. A subagent file that cannot be read is today's\n // behaviour, not a refusal.\n const own =\n agentId === undefined\n ? null\n : await readHistory(subagentTranscriptPath(transcriptPath, sessionId, agentId), {\n sessionId,\n agentId,\n });\n const messages = own === null ? (read ?? []) : [...(read ?? []), ...own];\n // The most recent user message is the turn this call belongs to; everything\n // before it is context. With no transcript the call speaks for itself, which\n // is what this hook did before it could read one.\n const lastUser = messages\n .map((message, index) => ({ message, index }))\n .filter((entry) => entry.message.role === 'user');\n const current = lastUser.at(-1);\n return {\n current: current?.message ?? { role: 'user', text: subject },\n history: current === undefined ? messages : messages.slice(0, current.index),\n literalUrls: literalUrlsIn(`${current?.message.text ?? ''}\\n${subject}`),\n historyStatus: read === null && own === null ? 'unavailable' : 'ok',\n pendingCall: pending,\n ...(nativeOutcome !== undefined ? { nativeOutcome } : {}),\n };\n}\n\n/** Both ids become path segments, so anything but an opaque token is refused. */\nconst PATH_SEGMENT_RE = /^[A-Za-z0-9_-]{1,200}$/;\n\n/**\n * Where the harness keeps one subagent's transcript: beside the parent's\n * `<session>.jsonl`, under `<session>/subagents/agent-<agent_id>.jsonl`\n * (Claude Code 2.1.x). `undefined` when either id could not be a path segment.\n */\nexport function subagentTranscriptPath(\n transcriptPath: string | undefined,\n sessionId: string,\n agentId: string,\n): string | undefined {\n if (transcriptPath === undefined || transcriptPath.length === 0) return undefined;\n if (!PATH_SEGMENT_RE.test(sessionId) || !PATH_SEGMENT_RE.test(agentId)) return undefined;\n return join(dirname(transcriptPath), sessionId, 'subagents', `agent-${agentId}.jsonl`);\n}\n\n/**\n * Whose rows a transcript read admits: the session's own, or with `agentId`,\n * exactly one subagent's sidechain and no other.\n */\ninterface RowScope {\n sessionId: string;\n agentId?: string;\n}\n\n/** `null` means \"cannot be vouched for\"; an empty array is a genuinely fresh session. */\nasync function readHistory(\n path: string | undefined,\n scope: RowScope,\n): Promise<PacketMessage[] | null> {\n if (path === undefined || path.length === 0) return null;\n let raw: string;\n let tail: boolean;\n let file;\n try {\n file = await open(path, 'r');\n } catch {\n return null;\n }\n try {\n const stat = await file.stat();\n if (!stat.isFile()) return null;\n tail = stat.size > MAX_TRANSCRIPT_BYTES;\n const read = tail ? await readTail(file, stat.size) : await readHead(file);\n if (read === null) return null;\n raw = read;\n } catch {\n return null;\n } finally {\n await file.close();\n }\n try {\n const messages = parseRows(raw, scope);\n // A TAIL MUST HOLD THE TURN. The latest user message is the newest of\n // them, so a tail with any user message holds this turn's; one with none\n // is a single turn longer than the window, whose instruction was cut off.\n if (tail && !messages.some((message) => message.role === 'user')) return null;\n return messages;\n } catch {\n return null;\n }\n}\n\ntype TranscriptFile = Awaited<ReturnType<typeof open>>;\n\n/** All of a transcript within the bound; null if it grew past it meanwhile. */\nasync function readHead(file: TranscriptFile): Promise<string | null> {\n const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);\n if (bytesRead > MAX_TRANSCRIPT_BYTES) return null;\n return buffer.subarray(0, bytesRead).toString('utf8');\n}\n\n/**\n * THE LAST {@link MAX_TRANSCRIPT_BYTES} OF A LONGER TRANSCRIPT, from the first\n * line that starts inside them: the one byte before the window is read too,\n * so a window that opens on a line boundary keeps its first line, and one\n * that opens mid-line drops the fragment. Cutting after a newline never\n * splits a UTF-8 character. Null when the window holds no line start at all.\n */\nasync function readTail(file: TranscriptFile, size: number): Promise<string | null> {\n const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);\n const { bytesRead } = await file.read(buffer, 0, buffer.length, size - buffer.length);\n const window = buffer.subarray(0, bytesRead);\n const newline = window.indexOf(0x0a);\n return newline === -1 ? null : window.subarray(newline + 1).toString('utf8');\n}\n\n/**\n * TOLERANT BY ROW, STRICT BY CONTENT. Every rule below still holds about what\n * may enter a packet: no other session's text, no subagent's, no tool results.\n * What changed is the blast radius of one bad row. Rejecting the whole\n * transcript over a compaction boundary or a sidechain line meant the native\n * hook routed on the tool argument alone, which is exactly how a current-turn\n * \"native tools only\" instruction went missing from the decision it was about.\n *\n * A compaction boundary is not a reason to read nothing: the rows after it are\n * the live context, so the collected messages start again there.\n */\nfunction parseRows(raw: string, scope: RowScope): PacketMessage[] {\n const { sessionId, agentId } = scope;\n let messages: PacketMessage[] = [];\n for (const line of raw.split('\\n')) {\n if (line.trim().length === 0) continue;\n let row: Record<string, unknown>;\n try {\n row = JSON.parse(line) as Record<string, unknown>;\n } catch {\n continue; // One unreadable line is one line, not the conversation.\n }\n if (row === null || typeof row !== 'object' || Array.isArray(row)) continue;\n // Everything before the boundary belongs to a context that was summarized\n // away; what follows is the turn in play.\n if (row.type === 'system' && row.subtype === 'compact_boundary') {\n messages = [];\n continue;\n }\n // Never ours to read: another window's rows and a subagent's are skipped\n // rather than allowed to void the file.\n if (typeof row.sessionId === 'string' && row.sessionId !== sessionId) continue;\n // Harness meta rows (a skill body, a command caveat) are not the user's words.\n if (row.isMeta === true) continue;\n // A subagent read admits that one sidechain and nothing else; the harness's\n // own reminders in it are not the task. Every other read admits none.\n if (agentId === undefined ? row.isSidechain === true : !ownSidechainRow(row, agentId)) {\n continue;\n }\n if (row.type !== 'user' && row.type !== 'assistant') continue;\n if (row.sessionId !== sessionId) continue;\n let text: string;\n try {\n text = textOf(row.message);\n } catch {\n continue; // A row this build cannot read contributes nothing, and no more.\n }\n // Nor is what the harness writes back into the user's turn (tenjin-agent#401).\n if (row.type === 'user' && harnessUserRow(row, text)) continue;\n if (text.length > 0) messages.push({ role: row.type, text });\n }\n return messages;\n}\n\n/** Output of a local command, as the harness wraps it into a user row. */\nconst LOCAL_COMMAND_OUTPUT = /^\\s*<local-command-(?:stdout|stderr)>/;\n\n/**\n * A turn the harness or another agent wrote, not the user: a background task\n * finishing, a subagent's hand-back or a teammate's message, a message from\n * another session. It hands work back; it asks for none, and routing it offers\n * a lookup nobody requested. The prompt hook skips these and the transcript\n * reader drops them, from this one list.\n */\nconst HANDBACK_PREFIXES = [\n '<task-notification>',\n '<agent-message',\n '<teammate-message',\n '<cross-session-message',\n 'Another Claude session sent a message',\n];\n\nexport function isHandback(text: string): boolean {\n const trimmed = text.trimStart();\n return HANDBACK_PREFIXES.some((prefix) => trimmed.startsWith(prefix));\n}\n\n/** The `origin.kind` of a user row another agent or the harness wrote. */\nconst HARNESS_ORIGINS = new Set(['task-notification', 'peer']);\n\n/**\n * A `type: \"user\"` row the user never typed. The harness writes these without\n * `isMeta`: a background task finishing (`origin.kind: \"task-notification\"`),\n * a subagent's hand-back or another session's message (`origin.kind: \"peer\"`,\n * text `Another Claude session sent a message:` then `<agent-message …>`), and\n * a local command's output (`<local-command-stdout>`). None is the user's\n * words, and none can become `current`: a hand-back read as this turn put a\n * subagent's report in place of the user's own instruction. A\n * `<command-name>` row stays: that is the command the user did type.\n */\nfunction harnessUserRow(row: Record<string, unknown>, text: string): boolean {\n const origin = row.origin;\n if (\n origin !== null &&\n typeof origin === 'object' &&\n HARNESS_ORIGINS.has((origin as { kind?: unknown }).kind as string)\n ) {\n return true;\n }\n return isHandback(text) || LOCAL_COMMAND_OUTPUT.test(text);\n}\n\nfunction ownSidechainRow(row: Record<string, unknown>, agentId: string): boolean {\n return row.isSidechain === true && row.agentId === agentId && row.isMeta !== true;\n}\n\n/** Ordinary text blocks only; a tool result contributes nothing. */\nfunction textOf(message: unknown): string {\n if (message === null || typeof message !== 'object' || Array.isArray(message)) {\n throw new Error('malformed message');\n }\n const content = (message as { content?: unknown }).content;\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) throw new Error('malformed content');\n const parts: string[] = [];\n for (const part of content) {\n if (\n part === null ||\n typeof part !== 'object' ||\n typeof (part as { type?: unknown }).type !== 'string'\n ) {\n throw new Error('malformed block');\n }\n const block = part as { type: string; text?: unknown };\n if (block.type !== 'text') continue;\n if (typeof block.text !== 'string') throw new Error('malformed text block');\n parts.push(block.text);\n }\n return parts.join('\\n');\n}\n","/**\n * WHAT A WEBFETCH RESULT SAYS ABOUT THE PAGE IT READ. WebFetch does not hand\n * back the page: `result` is a small model's answer to the agent's prompt,\n * written from the page's text. So a page that came back as a shell (a\n * JavaScript app's title, a video page's footer) still answers 200 with tens\n * of kilobytes, and the only place that says nothing was there is that\n * answer's own opening.\n *\n * Read deterministically, with no model and no network call, from the opening\n * alone, where the summarizer says what it was given. Every pattern names the\n * WHOLE page as empty or as page furniture only (a title, navigation, a\n * footer) or as needing JavaScript. \"The page does not mention X\" is the page\n * answering, not a shell, and matches nothing here. Over 682 recorded 2xx\n * WebFetch results these match the eight shells among them and nothing else;\n * `fixtures/harness/claude-WebFetch-results.json` keeps those eight and the\n * near misses a looser rule would take.\n */\n\n/** Where the summarizer says what it was given: its first few sentences. */\nconst OPENING_CHARS = 600;\n\n/** The page as a whole, as the summarizer refers to it. */\nconst PAGE = String.raw`(?:web ?page|page|site|content|excerpt)`;\n/** \"only shows\", \"contains only\", and their kin, in either order. */\nconst ONLY = String.raw`(?:only (?:shows?|contains?|includes?|consists? of|has|displays?)|(?:shows?|contains?|includes?|consists? of|has|displays?) only)`;\n/** Page furniture: what every page has and no page is about. A title counts\n * alone, not as the first of \"the title and abstract\". */\nconst FURNITURE = String.raw`(?:navigation|nav (?:bar|links|menu)|footer|legal links|boilerplate|loading (?:screen|spinner|indicator|message)|title\\b(?!\\s*(?:,|and\\b|&)))`;\n/** Within one sentence: no full stop, no line break. */\nconst SAME_SENTENCE = (max: number): string => String.raw`[^.\\n]{0,${max}}?`;\n\nconst EMPTY_PAGE_PATTERNS: readonly RegExp[] = [\n // \"the web page content provided is empty\", \"\\\"Web page content:\\\" appears to be empty\"\n new RegExp(\n String.raw`\\b(?:web ?page|page) content\\b${SAME_SENTENCE(40)}\\b(?:is|was|appears to be|seems to be) (?:entirely |completely )?empty\\b`,\n 'i',\n ),\n // \"I don't see any web page content provided\"\n /\\b(?:don't|do not|can't|cannot) see any (?:web ?page |page )?content\\b/i,\n // \"the webpage content provided only shows YouTube's footer navigation\",\n // \"contains only navigation elements, footer links\", \"only contains a title\"\n new RegExp(\n String.raw`\\b${PAGE}\\b${SAME_SENTENCE(60)}\\b${ONLY}\\b${SAME_SENTENCE(80)}\\b${FURNITURE}`,\n 'i',\n ),\n // \"The only information shown is \\\"Uniswap Interface,\\\" ... a page title or header\"\n new RegExp(\n String.raw`\\bthe only (?:information|content|text|thing)s? (?:shown|present|visible|available|provided|included)\\b${SAME_SENTENCE(120)}\\b${FURNITURE}`,\n 'i',\n ),\n // \"looks like a shell\", \"appears to be an empty app shell\"\n /\\b(?:looks like|appears to be|seems to be|is (?:just|only|merely)) an? (?:(?:empty|javascript|js|html|page|app|application|loading) ){0,2}(?:shell|skeleton)\\b/i,\n // A page that needs the JavaScript the fetch did not run: React's own\n // noscript line is \"You need to enable JavaScript to run this app.\"\n /\\benable JavaScript\\b/i,\n /\\bJavaScript (?:is )?(?:required|disabled|must be enabled)\\b/i,\n new RegExp(String.raw`\\b${PAGE}\\b${SAME_SENTENCE(60)}\\b(?:requires?|needs?) JavaScript\\b`, 'i'),\n // PyPI's script-less fallback: \"A required part of this site couldn't load\".\n /\\b(?:site|page) (?:couldn't|could not) load\\b/i,\n];\n\n/**\n * True when the summarizer says the page it was given had no main content:\n * empty, only a title, navigation or footer, or a script-rendered shell.\n */\nexport function readsAsEmptyPage(result: string): boolean {\n const opening = result.slice(0, OPENING_CHARS);\n return EMPTY_PAGE_PATTERNS.some((pattern) => pattern.test(opening));\n}\n\n/**\n * The note Claude Code appends as the result's last line when the body was\n * binary: `[Binary content (application/pdf, 2.1MB) also saved to <path>]`.\n */\nconst SAVED_PDF_RE =\n /\\n\\[Binary content \\(application\\/pdf, [^)\\n]{1,24}\\) also saved to ([^\\]\\n]+)\\]\\s*$/;\n/** How WebFetch names the file it saved, in `<session id>/tool-results`. */\nconst SAVED_PDF_NAME_RE = /[\\\\/]([^\\\\/]+)[\\\\/]tool-results[\\\\/]webfetch-\\d+-[a-z0-9]+\\.pdf$/i;\nconst PARENT_SEGMENT_RE = /(?:^|[\\\\/])\\.\\.(?:[\\\\/]|$)/;\n\n/**\n * Where WebFetch saved the PDF it fetched, or null. Its summary cannot read a\n * PDF (it is handed the compressed bytes: arxiv.org/pdf/1706.03762 came back\n * as \"a corrupted or binary PDF file that I cannot parse\"), but the file it\n * saved is whole, and `Read` parses its pages for free.\n *\n * Trusted only as the result's LAST line, only for a file named the way\n * WebFetch names one, and only in this session's own `tool-results`, so a\n * summary quoting a page that says otherwise cannot point the agent at any\n * other file, another session's included.\n */\nexport function savedPdfOf(result: string, sessionId: string): string | null {\n const path = SAVED_PDF_RE.exec(result)?.[1];\n if (path === undefined || PARENT_SEGMENT_RE.test(path)) return null;\n return SAVED_PDF_NAME_RE.exec(path)?.[1] === sessionId ? path : null;\n}\n","/**\n * THE HOOK'S TIME BUDGET, which is the only thing this module still owns.\n *\n * There is no separate gate call any more: the hook asks `POST\n * /api/x402-router` for the one free decision, and the backend answers as soon\n * as the native-versus-paid question is settled, binding whatever it chose in\n * the background. What used to live here, the `/prepare` client and the\n * category-shaped hint validator, went with that second round trip.\n */\n\n/**\n * The hook's whole budget is 5 s (the timeout `install` writes). Stdin waits up\n * to 1 s of it, so the decision gets 3.5 s and the two together still leave\n * 500 ms for node's boot and the transcript read; `wire.test.ts` pins the sum.\n * The expected wait is about 1 s: the backend answers on the gate question and\n * binds afterwards.\n *\n * AN ABORT HERE IS A LOST HINT, not a lost turn. The hook falls back to one\n * line telling the model to call `request` with its own query, and the tool\n * makes the decision instead. One of four live prompts was swallowed at a 1.5 s\n * abort against a backend measured at 0.4 to 0.5 s, so this holds the slack the\n * harness budget was already leaving unused.\n */\nexport const GATE_TIMEOUT_MS = 3_500;\n","import { spawn } from 'node:child_process';\nimport { constants } from 'node:fs';\nimport { open, rm } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { composeUserAgent } from '../lib/client-meta';\nimport { isSameDeployment } from '../lib/production-origin';\nimport { augmentOf, claimQuery, markAugment } from './progress';\n\n/**\n * FREE DOCS ON TOP OF A SEARCH, NEVER IN PLACE OF ONE. When the gate answers a\n * WebSearch with a free offer (the library docs lookup), denying the search for\n * it sent the agent on a detour and, when the docs missed, round a loop, and\n * the `request` call it was sent to rewrote the query. So the search runs as\n * the agent wrote it, and the docs ride above its results:\n *\n * - BEFORE THE CALL, the pre-call hook marks the call (by `tool_use_id`) and\n * starts the fetch in a detached `node`, so the lookup's few seconds overlap\n * the search's own instead of following them. The hook does not wait for it.\n * - AFTER THE CALL, the after-call hook waits, bounded, for what the fetch\n * wrote. A 200 with text becomes one string item prepended to the search's\n * `results`; anything else (404 no match, 503, 429, a timeout, a crash) is no\n * output at all, and the agent reads its search as it came back.\n *\n * Nothing here pays, so neither the spend policy nor the wallet is asked, and\n * nothing is denied, so the one-block rule is not either.\n */\n\n/** Longest query the docs endpoint accepts, in its own units (UTF-16). */\nexport const DOCS_QUERY_MAX = 500;\n/** The prefetch's own deadline. The endpoint's upstream answers in 3 to 5 s. */\nconst PREFETCH_TIMEOUT_MS = 12_000;\n/**\n * How long the after-call hook waits for the prefetch, from its own start. The\n * search has already taken about 5 s of the lookup's time by then. It fits,\n * with stdin, inside the after-call hook's timeout (`wire.test.ts` pins it).\n */\nexport const AUGMENT_WAIT_MS = 9_000;\n/** A bound on the docs text, far above what the endpoint sends. */\nconst MAX_DOCS_CHARS = 100_000;\n/** A body file larger than this is not one the prefetch wrote. */\nconst MAX_BODY_BYTES = 1_000_000;\nconst POLL_MS = 100;\n\n/** One prefetch: the GET, where its answer goes, and the identity it sends. */\nexport interface PrefetchJob {\n url: string;\n out: string;\n userAgent: string;\n}\n\nexport interface AugmentDeps {\n dataDir: string;\n now?: () => number;\n /** Starts the fetch; tests replace the detached process. */\n prefetch?: (job: PrefetchJob) => void;\n /** The after-call wait; tests shorten it. */\n augmentWaitMs?: number;\n}\n\n/**\n * THE PREFETCH, AS THE DETACHED PROCESS RUNS IT: one GET, then one file, then\n * exit. Plain JavaScript in a string because it runs as `node -e` with no module\n * graph behind it, so it costs a bare node boot and cannot pull anything else\n * in. It always writes `{status, text}`, status 0 for a failure that has none,\n * through a dot-named temp file and a rename, so the after-call hook reads a\n * whole answer or nothing, and then exits: it is gone by its deadline whatever\n * the lookup is doing. Redirects are refused: the one origin checked is the one\n * fetched. argv: url, out, user agent, timeout ms, max chars.\n */\nexport const PREFETCH_SCRIPT = [\n \"const { renameSync, rmSync, writeFileSync } = require('node:fs');\",\n \"const { basename, dirname, join } = require('node:path');\",\n 'const [url, out, agent, timeout, max] = process.argv.slice(1);',\n \"const tmp = join(dirname(out), '.' + basename(out) + '.' + process.pid + '.tmp');\",\n // The deadline is a plain timer that answers and exits, not an\n // `AbortSignal.timeout`: that one's timer does not hold the process open, so\n // a stalled lookup let it exit without writing anything.\n \"const timer = setTimeout(() => done(0, ''), Number(timeout));\",\n 'const done = (status, text) => {',\n ' clearTimeout(timer);',\n ' try {',\n \" writeFileSync(tmp, JSON.stringify({ status, text }), { mode: 0o600, flag: 'wx' });\",\n ' renameSync(tmp, out);',\n ' } catch {',\n ' try { rmSync(tmp, { force: true }); } catch {}',\n ' }',\n ' process.exit(0);',\n '};',\n 'fetch(url, {',\n \" headers: { accept: 'text/plain', 'user-agent': agent },\",\n \" redirect: 'error',\",\n '})',\n \" .then(async (res) => done(res.status, res.ok ? (await res.text()).slice(0, Number(max)) : ''))\",\n \" .catch(() => done(0, ''));\",\n].join('\\n');\n\n/**\n * Detached and unreferenced, with no stdio of the hook's: the harness waits for\n * the hook's own exit and pipes, and neither is held. `-e` is CommonJS, so the\n * script's `require` resolves builtins only.\n */\nfunction spawnPrefetch(job: PrefetchJob): void {\n const child = spawn(\n process.execPath,\n [\n '-e',\n PREFETCH_SCRIPT,\n job.url,\n job.out,\n job.userAgent,\n String(PREFETCH_TIMEOUT_MS),\n String(MAX_DOCS_CHARS),\n ],\n {\n detached: true,\n stdio: 'ignore',\n // Never the session's project: a live child would pin its worktree.\n cwd: dirname(job.out),\n windowsHide: true,\n },\n );\n // A spawn that fails reports it here, and an unhandled one would crash the hook.\n child.on('error', () => undefined);\n child.unref();\n}\n\n/**\n * The GET the prefetch makes, or null when this build will not make it: the\n * endpoint has to be the deployment the gate itself answered from. The hook\n * puts what comes back in front of the model, so a URL the answer names\n * anywhere else is not fetched.\n */\nexport function docsUrl(endpoint: string, query: string, baseUrl: string): string | null {\n let url: URL;\n let base: URL;\n try {\n url = new URL(endpoint);\n base = new URL(baseUrl);\n } catch {\n return null;\n }\n if (url.username !== '' || url.password !== '') return null;\n if (!isSameDeployment(url.origin, base.origin)) return null;\n url.searchParams.set('query', query.slice(0, DOCS_QUERY_MAX));\n return url.toString();\n}\n\n/**\n * THE PRE-CALL HALF. Only a WebSearch the harness gave an id can be matched to\n * its after-call event, so only that one is augmented; and one agent's identical\n * search within a few minutes (`AUGMENT_REPEAT_MS`) is not fetched again,\n * whatever the first fetch got. True when the fetch was started.\n */\nexport async function startAugment(\n call: {\n sessionId: string;\n agentId?: string;\n toolUseId?: string;\n query: string;\n },\n offer: { endpoint: string; provider: string },\n baseUrl: string,\n deps: AugmentDeps,\n): Promise<boolean> {\n if (call.toolUseId === undefined) return false;\n const url = docsUrl(offer.endpoint, call.query, baseUrl);\n if (url === null) return false;\n const now = deps.now?.() ?? Date.now();\n if (!(await claimQuery(deps.dataDir, call.sessionId, call.agentId, call.query, now))) {\n return false;\n }\n const out = await markAugment(deps.dataDir, call.sessionId, call.toolUseId, offer.provider, now);\n if (out === null) return false;\n try {\n (deps.prefetch ?? spawnPrefetch)({ url, out, userAgent: composeUserAgent() });\n return true;\n } catch {\n return false;\n }\n}\n\n/** A WebSearch response as the harness reported it, and its `results`. */\nexport interface SearchResponse {\n raw: Record<string, unknown>;\n results: unknown[];\n}\n\n/**\n * THE AFTER-CALL HALF. Null when this call was not augmented, so the caller\n * goes on as it always has. Otherwise the search's own response with the docs\n * as its first item, or `updatedToolOutput: null` for \"say nothing\": the\n * lookup found nothing, failed or ran out of time, or the call itself failed.\n */\nexport async function finishAugment(\n call: { sessionId: string; toolUseId?: string; search: SearchResponse | null },\n deps: AugmentDeps,\n): Promise<{ updatedToolOutput: Record<string, unknown> | null } | null> {\n if (call.toolUseId === undefined) return null;\n const now = deps.now?.() ?? Date.now();\n const marker = await augmentOf(deps.dataDir, call.sessionId, call.toolUseId, now);\n if (marker === null) return null;\n if (call.search === null) return { updatedToolOutput: null };\n // Past the prefetch's own deadline there is nothing left to wait for: it has\n // written, or it never will.\n const budget = Math.min(\n deps.augmentWaitMs ?? AUGMENT_WAIT_MS,\n PREFETCH_TIMEOUT_MS + 1_000 - (now - marker.at),\n );\n const answer = await awaitBody(marker.body, Date.now() + Math.max(0, budget));\n await rm(marker.body, { force: true }).catch(() => undefined);\n const text = answer?.status === 200 ? answer.text.trim() : '';\n if (text.length === 0) return { updatedToolOutput: null };\n return {\n updatedToolOutput: {\n ...call.search.raw,\n results: [docsLine(marker.provider || 'library', text), ...call.search.results],\n },\n };\n}\n\n/** The one string prepended to the search's results. */\nfunction docsLine(provider: string, text: string): string {\n return `Tenjin router added ${provider} docs for this search (free). If they don't cover it, use the web results below.\\n\\n${text}`;\n}\n\nasync function awaitBody(\n path: string,\n deadline: number,\n): Promise<{ status: number; text: string } | null> {\n for (;;) {\n const body = await readBody(path);\n if (body !== null) return body;\n const left = deadline - Date.now();\n if (left <= 0) return null;\n await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_MS, left)));\n }\n}\n\n/** What the prefetch wrote, or null while there is nothing (or nothing whole)\n * to read. `O_NOFOLLOW`, as every read under the progress directory. */\nasync function readBody(path: string): Promise<{ status: number; text: string } | null> {\n const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => undefined);\n if (file === undefined) return null;\n try {\n if ((await file.stat()).size > MAX_BODY_BYTES) return { status: 0, text: '' };\n const parsed: unknown = JSON.parse(await file.readFile('utf8'));\n const { status, text } = (parsed ?? {}) as { status?: unknown; text?: unknown };\n if (typeof status !== 'number' || typeof text !== 'string') return { status: 0, text: '' };\n return { status, text: text.slice(0, MAX_DOCS_CHARS) };\n } catch {\n return { status: 0, text: '' };\n } finally {\n await file.close().catch(() => undefined);\n }\n}\n","import {\n runAnswerHook,\n runAskHook,\n runDelegationHook,\n runNativeHook,\n runPromptHook,\n runShortfallHook,\n type HookDeps,\n} from './hooks';\nimport type { Io } from '../lib/output';\n\n/**\n * `tenjin hook prompt`, `native`, `shortfall`, `agent`, `ask` and `answer`. The harness writes\n * its event on stdin and reads a JSON object (or nothing) from stdout, so these\n * commands\n * bypass the CLI's envelope entirely. They never fail the turn: a stdin that\n * never arrives, an unreadable event or a handler that throws all exit 0 with\n * an empty stdout, which the harness reads as \"no opinion\".\n */\n\nconst MAX_EVENT_BYTES = 1_000_000;\n/** One fifth of the hook's 5 s budget, leaving the gate its 3.5 s; `wire.test.ts`\n * pins the sum against the timeout `install` writes. The harness writes its\n * event immediately, so this wait is a liveness check rather than a budget to\n * spend: every second it holds is a second the gate does not get. */\nexport const STDIN_TIMEOUT_MS = 1_000;\n\nexport type HookKind = 'prompt' | 'native' | 'shortfall' | 'agent' | 'ask' | 'answer';\n\nexport interface HookCommandDeps extends HookDeps {\n /** Test seam for the harness event; production reads stdin. */\n readEvent?: () => Promise<string>;\n}\n\nexport async function runHookCommand(kind: HookKind, io: Io, deps: HookCommandDeps): Promise<void> {\n let response: unknown;\n try {\n const raw = await (deps.readEvent ?? readStdin)();\n const event: unknown = JSON.parse(raw);\n const outcome =\n kind === 'prompt'\n ? await runPromptHook(event, deps)\n : kind === 'native'\n ? await runNativeHook(event, deps)\n : kind === 'shortfall'\n ? await runShortfallHook(event, deps)\n : kind === 'ask'\n ? await runAskHook(event, deps)\n : kind === 'answer'\n ? await runAnswerHook(event, deps)\n : await runDelegationHook(event, deps);\n response = outcome.response;\n } catch {\n response = null;\n }\n if (response !== null) io.stdout.write(`${JSON.stringify(response)}\\n`);\n}\n\nasync function readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n let size = 0;\n const timer = setTimeout(() => reject(new Error('no harness event')), STDIN_TIMEOUT_MS);\n const done = (value: string): void => {\n clearTimeout(timer);\n resolve(value);\n };\n process.stdin.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > MAX_EVENT_BYTES) {\n clearTimeout(timer);\n reject(new Error('harness event too large'));\n return;\n }\n chunks.push(chunk);\n });\n process.stdin.once('end', () => done(Buffer.concat(chunks).toString('utf8')));\n process.stdin.once('error', () => {\n clearTimeout(timer);\n reject(new Error('harness event unreadable'));\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;;;ACDxB,SAAS,YAAY;AACrB,SAAS,YAAY;AACrB,SAAS,SAAS,YAAY;AA0BvB,IAAM,cAAc;AACpB,IAAM,mBAAmB,KAAK;AAG9B,IAAM,oBAAoB;AAGjC,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAC9B,IAAM,oBAAoB;AAE1B,IAAM,0BAA0B;AAEhC,IAAM,cAAc;AAmDb,SAAS,UAAU,SAA8B;AACtD,SAAO,WAAW,UAAU,QAAQ,QAAQ,SAAS,UAAU,QAAQ,MAAM,QAAQ;AACvF;AAGA,SAAS,YAAY,SAAsB,SAA8B;AACvE,MAAI,WAAW,QAAS,QAAO,EAAE,MAAM,QAAQ,MAAM,OAAO,QAAQ;AACpE,MAAI,SAAS,QAAS,QAAO,EAAE,MAAM,QAAQ,MAAM,KAAK,QAAQ;AAChE,SAAO,EAAE,MAAM,QAAQ,MAAM,UAAU,QAAQ;AACjD;AAEA,IAAM,SAAS;AAER,SAAS,cAAc,MAAwB;AACpD,QAAM,QAAQ,oBAAI,IAAY;AAC9B,aAAW,SAAS,KAAK,SAAS,MAAM,GAAG;AACzC,UAAM,YAAY,MAAM,CAAC,EAAE,QAAQ,cAAc,EAAE;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