tenjin-cli 0.1.0-alpha.16 → 0.1.0-alpha.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +5 -0
  2. package/dist/chunk-2G2WLVHB.js +102 -0
  3. package/dist/chunk-2G2WLVHB.js.map +1 -0
  4. package/dist/chunk-2I4QTOLB.js +11 -0
  5. package/dist/chunk-2I4QTOLB.js.map +1 -0
  6. package/dist/chunk-35M3VITA.js +102 -0
  7. package/dist/chunk-35M3VITA.js.map +1 -0
  8. package/dist/chunk-3KKKB2AQ.js +40 -0
  9. package/dist/chunk-3KKKB2AQ.js.map +1 -0
  10. package/dist/{chunk-OIM4HLN6.js → chunk-7QKHZQKW.js} +295 -20
  11. package/dist/chunk-7QKHZQKW.js.map +1 -0
  12. package/dist/{chunk-BBVUVBUO.js → chunk-AR7U7BRG.js} +44 -7
  13. package/dist/{chunk-BBVUVBUO.js.map → chunk-AR7U7BRG.js.map} +1 -1
  14. package/dist/{chunk-DMZZLPZN.js → chunk-AUKDYPPX.js} +14 -89
  15. package/dist/chunk-AUKDYPPX.js.map +1 -0
  16. package/dist/{chunk-56MOAIP5.js → chunk-BTX2QE2Y.js} +9 -6
  17. package/dist/chunk-BTX2QE2Y.js.map +1 -0
  18. package/dist/{chunk-HVRC33OL.js → chunk-EPCOMXLF.js} +4 -6
  19. package/dist/{chunk-HVRC33OL.js.map → chunk-EPCOMXLF.js.map} +1 -1
  20. package/dist/{chunk-25TJPVBF.js → chunk-F3FUGWPZ.js} +28 -15
  21. package/dist/chunk-F3FUGWPZ.js.map +1 -0
  22. package/dist/{chunk-2U5ZVEV3.js → chunk-FGR734LZ.js} +6 -6
  23. package/dist/{chunk-PZEN5PHN.js → chunk-J5INH7WB.js} +17 -3
  24. package/dist/chunk-J5INH7WB.js.map +1 -0
  25. package/dist/{chunk-7WEQQJLG.js → chunk-JLEF5WHM.js} +66 -2
  26. package/dist/chunk-JLEF5WHM.js.map +1 -0
  27. package/dist/{chunk-YEETV6IW.js → chunk-KUBEYXSO.js} +10 -12
  28. package/dist/{chunk-YEETV6IW.js.map → chunk-KUBEYXSO.js.map} +1 -1
  29. package/dist/{chunk-L3PVMIYQ.js → chunk-N44H5TFB.js} +82 -150
  30. package/dist/chunk-N44H5TFB.js.map +1 -0
  31. package/dist/{chunk-BFFM2WFK.js → chunk-NRQMOVKM.js} +2 -2
  32. package/dist/{chunk-BFFM2WFK.js.map → chunk-NRQMOVKM.js.map} +1 -1
  33. package/dist/{chunk-GULLJQXA.js → chunk-ON6C6WOX.js} +127 -17
  34. package/dist/chunk-ON6C6WOX.js.map +1 -0
  35. package/dist/{chunk-OJLYNM4Z.js → chunk-PDA2BVFY.js} +77 -19
  36. package/dist/chunk-PDA2BVFY.js.map +1 -0
  37. package/dist/chunk-S2NRVRPF.js +171 -0
  38. package/dist/chunk-S2NRVRPF.js.map +1 -0
  39. package/dist/chunk-TGLKKLQG.js +11 -0
  40. package/dist/chunk-TGLKKLQG.js.map +1 -0
  41. package/dist/{chunk-SKAHDQH7.js → chunk-TJMCBIZU.js} +6 -7
  42. package/dist/{chunk-SKAHDQH7.js.map → chunk-TJMCBIZU.js.map} +1 -1
  43. package/dist/chunk-TP4D47BY.js +127 -0
  44. package/dist/chunk-TP4D47BY.js.map +1 -0
  45. package/dist/{chunk-WH7OWT6G.js → chunk-U2DZISAH.js} +2 -8
  46. package/dist/chunk-U2DZISAH.js.map +1 -0
  47. package/dist/{chunk-YJHHCWM3.js → chunk-WLMJE3GJ.js} +3 -3
  48. package/dist/{chunk-U5DXNFJC.js → chunk-WS4JA6TC.js} +3 -3
  49. package/dist/{chunk-5X4SZ5BF.js → chunk-WUHY2AXD.js} +4 -4
  50. package/dist/{chunk-USS336NF.js → chunk-YPQSMIDH.js} +5 -5
  51. package/dist/chunk-YPQSMIDH.js.map +1 -0
  52. package/dist/{chunk-3AJS6LLN.js → chunk-ZG7SFI34.js} +7 -7
  53. package/dist/{cli-M3XCSOU6.js → cli-MP3RAYHL.js} +43 -29
  54. package/dist/{cli-M3XCSOU6.js.map → cli-MP3RAYHL.js.map} +1 -1
  55. package/dist/{config-MXOX7XDR.js → config-BJK6U5VY.js} +11 -10
  56. package/dist/{doctor-LU4YIZWM.js → doctor-KJROWE5V.js} +108 -21
  57. package/dist/doctor-KJROWE5V.js.map +1 -0
  58. package/dist/{fund-A54P2QFK.js → fund-I5COXPEJ.js} +13 -11
  59. package/dist/{fund-A54P2QFK.js.map → fund-I5COXPEJ.js.map} +1 -1
  60. package/dist/hook-command-EJO2564A.js +821 -0
  61. package/dist/hook-command-EJO2564A.js.map +1 -0
  62. package/dist/index.js +2 -2
  63. package/dist/{install-XUM2XSHW.js → install-NUQLLHS2.js} +21 -14
  64. package/dist/{install-wallet-QIOFORTX.js → install-wallet-JPFTEC6H.js} +12 -10
  65. package/dist/{install-wallet-QIOFORTX.js.map → install-wallet-JPFTEC6H.js.map} +1 -1
  66. package/dist/{mcp-HJC2PLRV.js → mcp-I5XMVE64.js} +77 -34
  67. package/dist/{mcp-HJC2PLRV.js.map → mcp-I5XMVE64.js.map} +1 -1
  68. package/dist/{pay-SBXZEPEP.js → pay-WA3JSCNB.js} +21 -14
  69. package/dist/{redact-46ZHF2NH.js → redact-6W23GGJC.js} +4 -6
  70. package/dist/{send-ASD2ZXJD.js → send-KVUH5WDO.js} +12 -10
  71. package/dist/{send-ASD2ZXJD.js.map → send-KVUH5WDO.js.map} +1 -1
  72. package/dist/{skill-placement-NFVHY6A3.js → skill-placement-JMDPSKE6.js} +12 -13
  73. package/dist/{skill-placement-NFVHY6A3.js.map → skill-placement-JMDPSKE6.js.map} +1 -1
  74. package/dist/{status-T2SDB57A.js → status-FFC6FO72.js} +8 -7
  75. package/dist/{status-T2SDB57A.js.map → status-FFC6FO72.js.map} +1 -1
  76. package/dist/{status-line-CGPUSDMC.js → status-line-SAXSU6CR.js} +19 -3
  77. package/dist/status-line-SAXSU6CR.js.map +1 -0
  78. package/dist/{status-line-wiring-BYPHTYZE.js → status-line-wiring-DQZCWIUO.js} +5 -6
  79. package/dist/tenjin-daemon.mjs +384 -23
  80. package/dist/{uninstall-FKYZHAM3.js → uninstall-SWICHBTF.js} +41 -18
  81. package/dist/uninstall-SWICHBTF.js.map +1 -0
  82. package/dist/{update-ANJ2AOTN.js → update-W572AMXG.js} +6 -7
  83. package/dist/{update-ANJ2AOTN.js.map → update-W572AMXG.js.map} +1 -1
  84. package/dist/{wallet-PWAHVKWW.js → wallet-L2YLAJFN.js} +12 -10
  85. package/docs/agent-permissions.md +17 -9
  86. package/docs/safety-model.md +1 -1
  87. package/package.json +1 -1
  88. package/dist/chunk-25TJPVBF.js.map +0 -1
  89. package/dist/chunk-56MOAIP5.js.map +0 -1
  90. package/dist/chunk-7WEQQJLG.js.map +0 -1
  91. package/dist/chunk-DMZZLPZN.js.map +0 -1
  92. package/dist/chunk-GULLJQXA.js.map +0 -1
  93. package/dist/chunk-L3PVMIYQ.js.map +0 -1
  94. package/dist/chunk-OCBHUHWB.js +0 -69
  95. package/dist/chunk-OCBHUHWB.js.map +0 -1
  96. package/dist/chunk-OIM4HLN6.js.map +0 -1
  97. package/dist/chunk-OJLYNM4Z.js.map +0 -1
  98. package/dist/chunk-PZEN5PHN.js.map +0 -1
  99. package/dist/chunk-USS336NF.js.map +0 -1
  100. package/dist/chunk-WH7OWT6G.js.map +0 -1
  101. package/dist/doctor-LU4YIZWM.js.map +0 -1
  102. package/dist/hook-command-U6KWPEDQ.js +0 -377
  103. package/dist/hook-command-U6KWPEDQ.js.map +0 -1
  104. package/dist/status-line-CGPUSDMC.js.map +0 -1
  105. package/dist/uninstall-FKYZHAM3.js.map +0 -1
  106. /package/dist/{chunk-2U5ZVEV3.js.map → chunk-FGR734LZ.js.map} +0 -0
  107. /package/dist/{chunk-YJHHCWM3.js.map → chunk-WLMJE3GJ.js.map} +0 -0
  108. /package/dist/{chunk-U5DXNFJC.js.map → chunk-WS4JA6TC.js.map} +0 -0
  109. /package/dist/{chunk-5X4SZ5BF.js.map → chunk-WUHY2AXD.js.map} +0 -0
  110. /package/dist/{chunk-3AJS6LLN.js.map → chunk-ZG7SFI34.js.map} +0 -0
  111. /package/dist/{config-MXOX7XDR.js.map → config-BJK6U5VY.js.map} +0 -0
  112. /package/dist/{install-XUM2XSHW.js.map → install-NUQLLHS2.js.map} +0 -0
  113. /package/dist/{pay-SBXZEPEP.js.map → pay-WA3JSCNB.js.map} +0 -0
  114. /package/dist/{redact-46ZHF2NH.js.map → redact-6W23GGJC.js.map} +0 -0
  115. /package/dist/{status-line-wiring-BYPHTYZE.js.map → status-line-wiring-DQZCWIUO.js.map} +0 -0
  116. /package/dist/{wallet-PWAHVKWW.js.map → wallet-L2YLAJFN.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/lib/money.ts","../src/lib/errno.ts","../src/lib/policy.ts"],"sourcesContent":["import { CliError } from './errors';\nimport { ATOMIC_RE } from './ids';\nimport type { Money } from '../schemas';\n\n/** USDC is a 6-decimal token; one dollar is 1_000_000 atomic units. */\nconst USDC_DECIMALS = 6;\n\n/**\n * Decimal USD at the CLI edge -> atomic USDC string (O1). Accepts \"0\", \"0.25\",\n * \"5\"; rejects negatives, non-numeric input, and more than 6 decimal places as\n * USAGE so a fat-fingered amount fails loudly instead of truncating money.\n * String math throughout — a float would lose precision at the 6th decimal.\n */\nexport function parseUsdToAtomic(input: string): string {\n const trimmed = input.trim();\n if (!/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n throw new CliError('USAGE', `Invalid USD amount: ${JSON.stringify(input)}`, {\n fix: 'Pass a non-negative decimal like 0.25 or 5.',\n });\n }\n const [whole, frac = ''] = trimmed.split('.');\n if (frac.length > USDC_DECIMALS) {\n throw new CliError(\n 'USAGE',\n `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,\n {\n fix: 'USDC supports at most 6 decimal places (micro-dollars).',\n },\n );\n }\n const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, '0')}`);\n return atomic.toString();\n}\n\n/**\n * Atomic USDC string -> decimal USD string, trailing zeros trimmed (\"250000\" ->\n * \"0.25\", \"5000000\" -> \"5\", \"0\" -> \"0\"). Throws INTERNAL on a malformed atomic\n * value: atomic strings come from validated config or on-chain reads, so a bad\n * one is a bug, not user input.\n */\nexport function atomicToUsd(atomic: string): string {\n const trimmed = atomic.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new CliError('INTERNAL', `Malformed atomic amount: ${JSON.stringify(atomic)}`);\n }\n const value = BigInt(trimmed);\n const base = 10n ** BigInt(USDC_DECIMALS);\n const whole = value / base;\n const frac = (value % base).toString().padStart(USDC_DECIMALS, '0').replace(/0+$/, '');\n return frac.length > 0 ? `${whole}.${frac}` : whole.toString();\n}\n\n/**\n * Whether an atomic price would actually cost something: true paid, false free,\n * null when the string is not an atomic amount at all and so cannot answer.\n *\n * A Tenjin piece may be priced at zero and is then delivered by `read` with no\n * payment, so \"there is a price field\" and \"there is a purchase to make\" are\n * different questions. The third state is not decoration: only the wire schema\n * enforces ATOMIC_RE, and the local search store types `price` as a bare string,\n * so a hand-edited or half-written entry can hold \"-1\" or \"0.1\". Those must not\n * read as \"free\", or corrupt local data would start refusing honest reports.\n * Never throws, which is why the check is a regex and not a BigInt compare.\n *\n * Matched against the RAW string, with no trimming. The contract carries the\n * canonical form and nothing else, so \" 0 \" did not come off the wire; padding is\n * evidence the value was edited, and normalizing it away would launder a corrupt\n * entry into a confident \"free\" and hand back the false refusal this avoids.\n */\nexport function isPaidPrice(atomic: string): boolean | null {\n if (!ATOMIC_RE.test(atomic)) return null;\n return /[1-9]/.test(atomic);\n}\n\n/** Dual-form money object for machine output. */\nexport function toMoney(atomic: string): Money {\n return { atomic, usd: atomicToUsd(atomic) };\n}\n\n/**\n * Canonical USD for human COPY (a price a person reads): always at least two\n * decimals (\"0.10\", \"5.00\"), keeping any finer precision below a cent\n * (\"0.000001\"). Distinct from `atomicToUsd`, which trims to the shortest exact\n * form for machine output; use this only where a dollar amount is shown to a human.\n */\nexport function formatUsdDisplay(atomic: string): string {\n const [whole, frac = ''] = atomicToUsd(atomic).split('.');\n return `${whole}.${frac.padEnd(2, '0')}`;\n}\n","/**\n * True when `err` is a Node system error carrying the given `code` (ENOENT,\n * EEXIST, …). One definition so the fs-error checks scattered across the wallet\n * store, config loader, and session cache stay identical.\n */\nexport function hasCode(err: unknown, code: string): boolean {\n return (\n typeof err === 'object' &&\n err !== null &&\n 'code' in err &&\n (err as { code?: unknown }).code === code\n );\n}\n","/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\n/** How a `confirm` gate is configured (parsed from the stored config string). */\nexport type ConfirmPolicy = { mode: 'always' } | { mode: 'above'; thresholdAtomic: bigint };\n\nexport interface SpendPolicy {\n /** Amounts at or below this auto-approve WITHOUT a prompt (still subject to the\n * confirm gate below). Default 0 → nothing auto-approves. */\n maxAutoSpendAtomic: bigint;\n /** Rolling local ceiling on cumulative session spend. 0 = disabled (no ceiling). */\n sessionBudgetAtomic: bigint;\n /** When a human confirmation is requested. */\n confirm: ConfirmPolicy;\n /** Creators (handle or 0x-address, lowercased) auto-payment is restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always'\n | 'above_confirm_threshold';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/**\n * Evaluate one spend against the policy. Hard gates run first (price cap →\n * allowlist → session budget); only if all pass is the confirm gate consulted. A\n * spend at or below `maxAutoSpend` that the confirm policy would not prompt for is\n * the only `allow`; everything else within the hard gates is `confirm`.\n */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (policy.sessionBudgetAtomic > 0n) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; confirmation required.`,\n };\n }\n\n if (policy.confirm.mode === 'always') {\n return {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'confirm policy is \"always\"; confirmation required.',\n };\n }\n\n if (req.amountAtomic > policy.confirm.thresholdAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_confirm_threshold',\n message: `Price ${req.amountAtomic} is above the confirm threshold ${policy.confirm.thresholdAtomic}; confirmation required.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/** Parse the stored `confirm` config value (\"always\" | \"above:<atomic>\"). */\nexport function parseConfirmPolicy(stored: string): ConfirmPolicy {\n if (stored === 'always') return { mode: 'always' };\n const m = /^above:(\\d+)$/.exec(stored);\n if (m && m[1] !== undefined) return { mode: 'above', thresholdAtomic: BigInt(m[1]) };\n // The config schema already constrains this; a malformed value here is a bug,\n // so fail closed to the safest interpretation rather than throwing mid-buy.\n return { mode: 'always' };\n}\n"],"mappings":";;;;;;AAKA,IAAM,gBAAgB;AAQf,SAAS,iBAAiB,OAAuB;AACtD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,gBAAgB,KAAK,OAAO,GAAG;AAClC,UAAM,IAAI,SAAS,SAAS,uBAAuB,KAAK,UAAU,KAAK,CAAC,IAAI;AAAA,MAC1E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,QAAQ,MAAM,GAAG;AAC5C,MAAI,KAAK,SAAS,eAAe;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,MACA,cAAc,KAAK,UAAU,KAAK,CAAC;AAAA,MACnC;AAAA,QACE,KAAK;AAAA,M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UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,YAAY,IAAI,OAAO;AAAA,MAClC;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,sBAAsB,IAAI;AACnC,UAAM,YAAY,IAAI,qBAAqB,IAAI;AAC/C,QAAI,YAAY,OAAO,qBAAqB;AAC1C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,MAAI,OAAO,QAAQ,SAAS,UAAU;AACpC,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,QAAQ,iBAAiB;AACrD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,mCAAmC,OAAO,QAAQ,eAAe;AAAA,IACrG;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;AAGO,SAAS,mBAAmB,QAA+B;AAChE,MAAI,WAAW,SAAU,QAAO,EAAE,MAAM,SAAS;AACjD,QAAM,IAAI,gBAAgB,KAAK,MAAM;AACrC,MAAI,KAAK,EAAE,CAAC,MAAM,OAAW,QAAO,EAAE,MAAM,SAAS,iBAAiB,OAAO,EAAE,CAAC,CAAC,EAAE;AAGnF,SAAO,EAAE,MAAM,SAAS;AAC1B;","names":[]}
@@ -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 } 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 { ROUTER_PATH } from './decision';\nimport {\n ALLOW_RULE,\n MCP_SERVER_NAME,\n mcpAddCommand,\n mcpScope,\n readMcpEntry,\n routerSettingsPath,\n type McpEntryState,\n} from './install';\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 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));\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(...(await walletCheck(ctx)));\n checks.push(await routerCheck(settings.baseUrl, ctx.flags.timeout, deps.fetchImpl));\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\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(path: string, dataDir: string): 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 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 return {\n name: 'hooks',\n status: 'ok',\n required: true,\n detail: `${events.join(' and ')} registered, ${ALLOW_RULE} allowed`,\n };\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\nfunction spendCheck(maxAutoSpendAtomic: bigint, sessionBudgetAtomic: bigint): RouterCheck {\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 === 0n\n ? 'no daily ceiling'\n : `${toMoney(sessionBudgetAtomic.toString()).usd} USD a day`;\n return {\n name: 'spend',\n status: sessionBudgetAtomic === 0n ? 'warn' : 'ok',\n required: false,\n detail: `at most ${toMoney(maxAutoSpendAtomic.toString()).usd} USD a call, ${budget}`,\n ...(sessionBudgetAtomic === 0n\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,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAmC1B,IAAM,OAAO,UAAU,QAAQ;AA+B/B,IAAM,aAAa;AAEnB,eAAsB,gBACpB,KACA,OAAyB,CAAC,GACF;AACxB,QAAM,MAAM,KAAK,OAAO,QAAQ;AAChC,QAAM,WAAW,MAAM,uBAAuB,GAAG;AAIjD,QAAM,eAAe,mBAAmB;AAAA,IACtC,GAAI,KAAK,YAAY,OAAO,EAAE,SAAS,KAAK,IAAI,CAAC;AAAA,IACjD,GAAI,KAAK,YAAY,SAAY,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;AAAA,IAC9D,GAAI,KAAK,QAAQ,SAAY,EAAE,KAAK,KAAK,IAAI,IAAI,CAAC;AAAA,EACpD,CAAC;AACD,QAAM,SAAwB,CAAC,UAAU,KAAK,eAAe,QAAQ,OAAO,CAAC;AAC7E,SAAO,KAAK,MAAM,WAAW,cAAc,IAAI,OAAO,CAAC;AACvD,SAAO,KAAK,MAAM,gBAAgB,YAAY,CAAC;AAC/C,SAAO;AAAA,IACL,MAAM;AAAA,MACJ;AAAA,MACA;AAAA,MACA,KAAK,YAAY;AAAA,MACjB,KAAK,OAAO,QAAQ,IAAI;AAAA,MACxB,KAAK,WAAW,QAAQ;AAAA,IAC1B;AAAA,EACF;AACA,SAAO,KAAK,WAAW,SAAS,OAAO,oBAAoB,SAAS,OAAO,mBAAmB,CAAC;AAC/F,SAAO,KAAK,GAAI,MAAM,YAAY,GAAG,CAAE;AACvC,SAAO,KAAK,MAAM,YAAY,SAAS,SAAS,IAAI,MAAM,SAAS,KAAK,SAAS,CAAC;AAElF,QAAM,UA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AM,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,377 +0,0 @@
1
- import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- ROUTER_PATH,
4
- requestDecision
5
- } from "./chunk-USS336NF.js";
6
- import "./chunk-5X4SZ5BF.js";
7
- import {
8
- mask
9
- } from "./chunk-OIM4HLN6.js";
10
- import {
11
- bindDecision,
12
- newCallId,
13
- noteSession,
14
- pruneProgress,
15
- pruneSessions,
16
- sessionDir,
17
- writeProgress
18
- } from "./chunk-PZEN5PHN.js";
19
- import {
20
- external_exports,
21
- loadRawConfig,
22
- resolveSettings
23
- } from "./chunk-BBVUVBUO.js";
24
- import "./chunk-BFFM2WFK.js";
25
- import "./chunk-OCBHUHWB.js";
26
- import "./chunk-2BKS2FVE.js";
27
- import "./chunk-7WEQQJLG.js";
28
- import "./chunk-ZXTAQYNA.js";
29
-
30
- // src/router/context.ts
31
- import { open } from "node:fs/promises";
32
- var MAX_HISTORY = 6;
33
- var MAX_PACKET_BYTES = 16 * 1024;
34
- var MAX_MESSAGE_CHARS = 16e3;
35
- var MAX_TRANSCRIPT_BYTES = 4e6;
36
- var MAX_LITERAL_URLS = 8;
37
- var MAX_LITERAL_URL_CHARS = 2e3;
38
- var URL_RE = /\bhttps?:\/\/[^\s<>"'`)\]]+/gi;
39
- function literalUrlsIn(text) {
40
- const found = /* @__PURE__ */ new Set();
41
- for (const match of text.matchAll(URL_RE)) {
42
- const candidate = match[0].replace(/[.,;:!?]+$/, "");
43
- try {
44
- const normalized = new URL(candidate).toString();
45
- if (normalized.length <= MAX_LITERAL_URL_CHARS) found.add(normalized);
46
- } catch {
47
- continue;
48
- }
49
- if (found.size >= MAX_LITERAL_URLS) break;
50
- }
51
- return [...found];
52
- }
53
- function fit(packet) {
54
- const size = (value) => Buffer.byteLength(JSON.stringify(value));
55
- const next = { ...packet, history: packet.history.slice(-MAX_HISTORY) };
56
- while (next.history.length > 0 && size(next) > MAX_PACKET_BYTES) {
57
- next.history = next.history.slice(1);
58
- }
59
- while (next.literalUrls.length > 0 && size(next) > MAX_PACKET_BYTES) {
60
- next.literalUrls = next.literalUrls.slice(0, -1);
61
- }
62
- while (size(next) > MAX_PACKET_BYTES && next.current.text.length > 1) {
63
- const over = size(next) - MAX_PACKET_BYTES;
64
- const keep = Math.max(1, next.current.text.length - Math.max(over, 1));
65
- next.current = { ...next.current, text: next.current.text.slice(0, keep) };
66
- }
67
- return next;
68
- }
69
- async function buildPromptPacket(transcriptPath, sessionId, prompt) {
70
- const masked = mask(prompt.trim()).slice(0, MAX_MESSAGE_CHARS);
71
- const text = masked.length > 0 ? masked : "(empty prompt)";
72
- const read = await readHistory(transcriptPath, sessionId);
73
- return fit({
74
- current: { role: "user", text },
75
- history: read ?? [],
76
- literalUrls: literalUrlsIn(text),
77
- historyStatus: read === null ? "unavailable" : "ok"
78
- });
79
- }
80
- async function buildNativePacket(transcriptPath, sessionId, pending) {
81
- const subject = "query" in pending ? pending.query : pending.url;
82
- const read = await readHistory(transcriptPath, sessionId);
83
- const messages = read ?? [];
84
- const lastUser = messages.map((message, index) => ({ message, index })).filter((entry) => entry.message.role === "user");
85
- const current = lastUser.at(-1);
86
- const bounded = mask(subject).slice(0, MAX_MESSAGE_CHARS);
87
- return fit({
88
- current: current?.message ?? { role: "user", text: bounded },
89
- history: current === void 0 ? messages : messages.slice(0, current.index),
90
- literalUrls: literalUrlsIn(`${current?.message.text ?? ""}
91
- ${bounded}`),
92
- historyStatus: read === null ? "unavailable" : "ok",
93
- pendingCall: pending
94
- });
95
- }
96
- async function readHistory(path, sessionId) {
97
- if (path === void 0 || path.length === 0) return null;
98
- let raw;
99
- let file;
100
- try {
101
- file = await open(path, "r");
102
- } catch {
103
- return null;
104
- }
105
- try {
106
- const stat = await file.stat();
107
- if (!stat.isFile() || stat.size > MAX_TRANSCRIPT_BYTES) return null;
108
- const buffer = Buffer.alloc(MAX_TRANSCRIPT_BYTES + 1);
109
- const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
110
- if (bytesRead > MAX_TRANSCRIPT_BYTES) return null;
111
- raw = buffer.subarray(0, bytesRead).toString("utf8");
112
- } catch {
113
- return null;
114
- } finally {
115
- await file.close();
116
- }
117
- try {
118
- return parseRows(raw, sessionId);
119
- } catch {
120
- return null;
121
- }
122
- }
123
- function parseRows(raw, sessionId) {
124
- let messages = [];
125
- for (const line of raw.split("\n")) {
126
- if (line.trim().length === 0) continue;
127
- let row;
128
- try {
129
- row = JSON.parse(line);
130
- } catch {
131
- continue;
132
- }
133
- if (row === null || typeof row !== "object" || Array.isArray(row)) continue;
134
- if (row.type === "system" && row.subtype === "compact_boundary") {
135
- messages = [];
136
- continue;
137
- }
138
- if (typeof row.sessionId === "string" && row.sessionId !== sessionId) continue;
139
- if (row.isSidechain === true) continue;
140
- if (row.type !== "user" && row.type !== "assistant") continue;
141
- if (row.sessionId !== sessionId) continue;
142
- let text;
143
- try {
144
- text = textOf(row.message);
145
- } catch {
146
- continue;
147
- }
148
- const bounded = mask(text).slice(0, MAX_MESSAGE_CHARS);
149
- if (bounded.length > 0) messages.push({ role: row.type, text: bounded });
150
- }
151
- return messages;
152
- }
153
- function textOf(message) {
154
- if (message === null || typeof message !== "object" || Array.isArray(message)) {
155
- throw new Error("malformed message");
156
- }
157
- const content = message.content;
158
- if (typeof content === "string") return content;
159
- if (!Array.isArray(content)) throw new Error("malformed content");
160
- const parts = [];
161
- for (const part of content) {
162
- if (part === null || typeof part !== "object" || typeof part.type !== "string") {
163
- throw new Error("malformed block");
164
- }
165
- const block = part;
166
- if (block.type !== "text") continue;
167
- if (typeof block.text !== "string") throw new Error("malformed text block");
168
- parts.push(block.text);
169
- }
170
- return parts.join("\n");
171
- }
172
-
173
- // src/router/gate.ts
174
- var GATE_TIMEOUT_MS = 3500;
175
-
176
- // src/router/hooks.ts
177
- var PromptEventSchema = external_exports.object({
178
- session_id: external_exports.string().min(1).max(200),
179
- transcript_path: external_exports.string().optional(),
180
- prompt: external_exports.string()
181
- });
182
- var NativeEventSchema = external_exports.object({
183
- session_id: external_exports.string().min(1).max(200),
184
- /** The harness's own path for THIS session: the native decision reads the
185
- * same bounded history the prompt one does, so a restriction the user gave
186
- * reaches both gates. */
187
- transcript_path: external_exports.string().optional(),
188
- tool_name: external_exports.enum(["WebSearch", "WebFetch"]),
189
- tool_input: external_exports.record(external_exports.string(), external_exports.unknown())
190
- });
191
- var ACKNOWLEDGEMENTS = /* @__PURE__ */ new Set(["y", "yes", "ok", "okay", "continue", "go", "sure", "thanks"]);
192
- function promptSkipReason(prompt) {
193
- const trimmed = prompt.trim();
194
- if (trimmed.startsWith("/")) return "slash";
195
- const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, "");
196
- return ACKNOWLEDGEMENTS.has(normalized) ? "acknowledgement" : null;
197
- }
198
- async function resolveBaseUrl(deps) {
199
- if (deps.baseUrl !== void 0) return deps.baseUrl;
200
- const config = await loadRawConfig(deps.dataDir).catch(() => ({}));
201
- return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;
202
- }
203
- async function runPromptHook(raw, deps) {
204
- const parsed = PromptEventSchema.safeParse(raw);
205
- if (!parsed.success) return { response: null };
206
- const event = parsed.data;
207
- const skipped = promptSkipReason(event.prompt);
208
- if (skipped !== null) return { response: null, skipped };
209
- const packet = await buildPromptPacket(event.transcript_path, event.session_id, event.prompt);
210
- const footer = await openFooter(deps, event.session_id, "prompt");
211
- const outcome = await decide(packet, deps);
212
- await footer.close(outcome);
213
- if (outcome === null) return { response: null };
214
- if (outcome.action !== "execute") return { response: null, action: outcome.action };
215
- return { action: "execute", id: outcome.id, ...injection(outcome.hint) };
216
- }
217
- function injection(line) {
218
- return {
219
- response: {
220
- hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: line }
221
- }
222
- };
223
- }
224
- async function runNativeHook(raw, deps) {
225
- const parsed = NativeEventSchema.safeParse(raw);
226
- if (!parsed.success) return { response: null, decision: "allow" };
227
- const event = parsed.data;
228
- const pending = pendingCallOf(event.tool_name, event.tool_input);
229
- if (pending === null) return { response: null, decision: "allow" };
230
- const packet = await buildNativePacket(event.transcript_path, event.session_id, pending);
231
- if (packet.historyStatus !== "ok") {
232
- (deps.warn ?? ((line) => process.stderr.write(`${line}
233
- `)))(
234
- "tenjin hook: this session's transcript could not be read, so the native call runs unrouted"
235
- );
236
- return { response: null, decision: "allow" };
237
- }
238
- const footer = await openFooter(deps, event.session_id, "search");
239
- const outcome = await decide(packet, deps);
240
- await footer.close(outcome);
241
- if (outcome === null || outcome.action !== "execute") {
242
- return {
243
- response: null,
244
- decision: "allow",
245
- ...outcome !== null ? { action: outcome.action } : {}
246
- };
247
- }
248
- return {
249
- response: {
250
- hookSpecificOutput: {
251
- hookEventName: "PreToolUse",
252
- permissionDecision: "deny",
253
- // THE SERVER'S LINE, VERBATIM. It already carries the id and, on a
254
- // native call, the exact search or URL that was denied, so there is
255
- // nothing left here to compose and nothing to trim.
256
- permissionDecisionReason: outcome.hint
257
- }
258
- },
259
- decision: "deny",
260
- action: "execute",
261
- id: outcome.id
262
- };
263
- }
264
- async function openFooter(deps, sessionId, operation) {
265
- const now = () => deps.now?.() ?? Date.now();
266
- const directory = sessionDir(deps.dataDir, sessionId);
267
- const callId = newCallId();
268
- await noteSession(deps.dataDir, sessionId, now());
269
- await writeProgress(
270
- directory,
271
- callId,
272
- { phase: "routing", operation, outcome: "selecting service" },
273
- now()
274
- );
275
- await pruneProgress(directory, now());
276
- await pruneSessions(deps.dataDir, now());
277
- return {
278
- close: async (decision) => {
279
- await writeProgress(
280
- directory,
281
- callId,
282
- { phase: "done", operation, outcome: hookOutcome(decision) },
283
- now()
284
- );
285
- if (decision !== null && decision.action === "execute") {
286
- await bindDecision(deps.dataDir, sessionId, decision.id, now());
287
- }
288
- }
289
- };
290
- }
291
- function hookOutcome(decision) {
292
- if (decision === null) return "native tools (router unavailable)";
293
- if (decision.action === "execute") return `paid lookup offered (${decision.provider})`;
294
- if (decision.action === "native") return "native tools (no x402 payment)";
295
- return "needs input";
296
- }
297
- async function decide(packet, deps) {
298
- const baseUrl = await resolveBaseUrl(deps);
299
- const warn = deps.warn ?? ((line) => process.stderr.write(`${line}
300
- `));
301
- const outcome = await requestDecision(
302
- "hook",
303
- { packet },
304
- {
305
- ctx: {
306
- flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },
307
- dataDir: deps.dataDir,
308
- io: { stdout: nullStream(), stderr: nullStream(), isTTY: false }
309
- },
310
- baseUrl,
311
- timeoutMs: deps.timeoutMs ?? GATE_TIMEOUT_MS,
312
- ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
313
- }
314
- );
315
- if (outcome.status === "failed") {
316
- warn(`tenjin hook: ${baseUrl}${ROUTER_PATH} ${outcome.reason}`);
317
- return null;
318
- }
319
- return outcome.decision.decision;
320
- }
321
- function nullStream() {
322
- return { write: () => true };
323
- }
324
- function pendingCallOf(tool, input) {
325
- const value = tool === "WebSearch" ? input.query : input.url;
326
- if (typeof value !== "string") return null;
327
- const bounded = value.trim().slice(0, 4e3);
328
- if (bounded.length === 0) return null;
329
- return tool === "WebSearch" ? { tool, query: bounded } : { tool, url: bounded };
330
- }
331
-
332
- // src/router/hook-command.ts
333
- var MAX_EVENT_BYTES = 1e6;
334
- var STDIN_TIMEOUT_MS = 1e3;
335
- async function runHookCommand(kind, io, deps) {
336
- let response;
337
- try {
338
- const raw = await (deps.readEvent ?? readStdin)();
339
- const event = JSON.parse(raw);
340
- const outcome = kind === "prompt" ? await runPromptHook(event, deps) : await runNativeHook(event, deps);
341
- response = outcome.response;
342
- } catch {
343
- response = null;
344
- }
345
- if (response !== null) io.stdout.write(`${JSON.stringify(response)}
346
- `);
347
- }
348
- async function readStdin() {
349
- return new Promise((resolve, reject) => {
350
- const chunks = [];
351
- let size = 0;
352
- const timer = setTimeout(() => reject(new Error("no harness event")), STDIN_TIMEOUT_MS);
353
- const done = (value) => {
354
- clearTimeout(timer);
355
- resolve(value);
356
- };
357
- process.stdin.on("data", (chunk) => {
358
- size += chunk.length;
359
- if (size > MAX_EVENT_BYTES) {
360
- clearTimeout(timer);
361
- reject(new Error("harness event too large"));
362
- return;
363
- }
364
- chunks.push(chunk);
365
- });
366
- process.stdin.once("end", () => done(Buffer.concat(chunks).toString("utf8")));
367
- process.stdin.once("error", () => {
368
- clearTimeout(timer);
369
- reject(new Error("harness event unreadable"));
370
- });
371
- });
372
- }
373
- export {
374
- STDIN_TIMEOUT_MS,
375
- runHookCommand
376
- };
377
- //# sourceMappingURL=hook-command-U6KWPEDQ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/context.ts","../src/router/gate.ts","../src/router/hooks.ts","../src/router/hook-command.ts"],"sourcesContent":["import { open } from 'node:fs/promises';\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, redacted, at most {@link MAX_HISTORY} prior messages and at most\n * {@link MAX_PACKET_BYTES} in total, oldest dropped first. Tool results are\n * excluded: a tool result is other people's content, and a packet that carried\n * it would be a channel from a fetched page into a routing decision.\n *\n * WHAT NEVER HAPPENS: a transcript this reader cannot vouch for (another\n * session, a subagent sidechain, a compaction boundary, malformed rows, an\n * oversized file) is reported as `unavailable` rather than partially believed,\n * and the user's turn is never blocked by any of that. 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;\nconst MAX_TRANSCRIPT_BYTES = 4_000_000;\nconst MAX_LITERAL_URLS = 8;\nconst MAX_LITERAL_URL_CHARS = 2_000;\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}\n\n/** The pending native call, INSIDE the packet: the gate request is a strict\n * object with exactly `schemaVersion`, `source` and `packet`. */\nexport type PendingCall = { tool: 'WebSearch'; query: string } | { tool: 'WebFetch'; url: string };\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\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`.\n */\nexport async function buildPromptPacket(\n transcriptPath: string | undefined,\n sessionId: string,\n prompt: string,\n): Promise<Packet> {\n const masked = mask(prompt.trim()).slice(0, MAX_MESSAGE_CHARS);\n const text = masked.length > 0 ? masked : '(empty prompt)';\n const read = await readHistory(transcriptPath, sessionId);\n return fit({\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 the host is about to make. SAME BOUNDS as\n * a prompt packet, and the same reader: the six most recent messages, 16 KiB,\n * masked, with tool results excluded.\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 pending call rides INSIDE the packet as the proposed operation, which is\n * the shape the route takes and the one `wire-gate-request.json` pins.\n */\nexport async function buildNativePacket(\n transcriptPath: string | undefined,\n sessionId: string,\n pending: PendingCall,\n): Promise<Packet> {\n const subject = 'query' in pending ? pending.query : pending.url;\n const read = await readHistory(transcriptPath, sessionId);\n const messages = read ?? [];\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 const bounded = mask(subject).slice(0, MAX_MESSAGE_CHARS);\n return fit({\n current: current?.message ?? { role: 'user', text: bounded },\n history: current === undefined ? messages : messages.slice(0, current.index),\n literalUrls: literalUrlsIn(`${current?.message.text ?? ''}\\n${bounded}`),\n historyStatus: read === null ? 'unavailable' : 'ok',\n pendingCall: pending,\n });\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 sessionId: string,\n): Promise<PacketMessage[] | null> {\n if (path === undefined || path.length === 0) return null;\n let raw: string;\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() || stat.size > MAX_TRANSCRIPT_BYTES) return 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 raw = buffer.subarray(0, bytesRead).toString('utf8');\n } catch {\n return null;\n } finally {\n await file.close();\n }\n try {\n return parseRows(raw, sessionId);\n } catch {\n return null;\n }\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, sessionId: string): PacketMessage[] {\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 if (row.isSidechain === true) continue;\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 const bounded = mask(text).slice(0, MAX_MESSAGE_CHARS);\n if (bounded.length > 0) messages.push({ role: row.type, text: bounded });\n }\n return messages;\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 * 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 { z } from 'zod';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport type { PartialConfig } from '../lib/config';\nimport { buildNativePacket, buildPromptPacket, type Packet, type PendingCall } from './context';\nimport { requestDecision, ROUTER_PATH, type HookDecision } from './decision';\nimport { GATE_TIMEOUT_MS } from './gate';\nimport {\n bindDecision,\n newCallId,\n noteSession,\n pruneProgress,\n pruneSessions,\n sessionDir,\n writeProgress,\n} from './progress';\n\n/**\n * The two hook handlers. Between them they do exactly three things: build the\n * bounded packet, ask for one free decision, and say one thing back to the\n * harness.\n *\n * NOTHING ELSE IS IN REACH FROM HERE. No wallet, no signer, no payment SDK, no\n * MCP server: a dist test asserts the chunk graph, because the hooks run on\n * every prompt and every native search, and their cost is 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 native call allowed and the prompt unchanged; the cause goes to\n * stderr. The user's turn is never blocked by this.\n */\n\nconst PromptEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n transcript_path: z.string().optional(),\n prompt: z.string(),\n});\n\nconst NativeEventSchema = z.object({\n session_id: z.string().min(1).max(200),\n /** The harness's own path for THIS session: the native decision reads the\n * same 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});\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';\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 if (trimmed.startsWith('/')) return 'slash';\n const normalized = trimmed.toLowerCase().replace(/[.!,]+$/, '');\n return ACKNOWLEDGEMENTS.has(normalized) ? 'acknowledgement' : null;\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 fetchImpl?: typeof fetch;\n timeoutMs?: number;\n now?: () => number;\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}\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 */\nasync function resolveBaseUrl(deps: HookDeps): Promise<string> {\n if (deps.baseUrl !== undefined) return deps.baseUrl;\n const config: PartialConfig = await loadRawConfig(deps.dataDir).catch(() => ({}));\n return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;\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}\n\n/**\n * `tenjin hook prompt` (UserPromptSubmit). One free decision from the user's\n * own words. Only an `execute` gets a line, the server's hint verbatim.\n * `native`, `needs_input` and a decision that 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 */\nexport async function runPromptHook(raw: unknown, deps: HookDeps): Promise<PromptHookOutcome> {\n const parsed = PromptEventSchema.safeParse(raw);\n if (!parsed.success) return { response: null };\n const event = parsed.data;\n const skipped = promptSkipReason(event.prompt);\n if (skipped !== null) return { response: null, skipped };\n\n const packet = await buildPromptPacket(event.transcript_path, event.session_id, event.prompt);\n const footer = await openFooter(deps, event.session_id, 'prompt');\n const outcome = await decide(packet, deps);\n await footer.close(outcome);\n if (outcome === null) return { response: null };\n if (outcome.action !== 'execute') return { response: null, action: outcome.action };\n return { action: 'execute', id: outcome.id, ...injection(outcome.hint) };\n}\n\nfunction injection(line: string): { response: unknown } {\n return {\n response: {\n hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: line },\n },\n };\n}\n\nexport interface NativeHookOutcome {\n response: unknown | null;\n decision: 'allow' | 'deny';\n action?: HookDecision['action'];\n id?: string;\n}\n\n/**\n * `tenjin hook native` (PreToolUse on `WebSearch|WebFetch`). ALLOW IS THE\n * DEFAULT and a redirect is the exception: it fires only on a clear `execute`,\n * and it carries the id so the redirected call runs the decision that was just\n * made rather than paying for a second one. Anything else, including silence,\n * a slow backend and a `needs_input`, lets the native call run.\n */\nexport async function runNativeHook(raw: unknown, deps: HookDeps): Promise<NativeHookOutcome> {\n const parsed = NativeEventSchema.safeParse(raw);\n if (!parsed.success) return { response: null, decision: 'allow' };\n const event = parsed.data;\n const pending = pendingCallOf(event.tool_name, event.tool_input);\n if (pending === null) return { response: null, decision: 'allow' };\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.\n const packet = await buildNativePacket(event.transcript_path, event.session_id, pending);\n // AND WHEN THEY CANNOT BE READ, THE CALL RUNS. Routing a redirect on the tool\n // argument alone is how an instruction the user gave this turn gets\n // overruled by a decision that never saw it. A native call the user's own\n // assistant chose is the safe default; the only cost is a lookup this turn\n // does not route.\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 the native call runs unrouted\",\n );\n return { response: null, decision: 'allow' };\n }\n const footer = await openFooter(deps, event.session_id, 'search');\n const outcome = await decide(packet, deps);\n await footer.close(outcome);\n if (outcome === null || outcome.action !== 'execute') {\n return {\n response: null,\n decision: 'allow',\n ...(outcome !== null ? { action: outcome.action } : {}),\n };\n }\n return {\n response: {\n hookSpecificOutput: {\n hookEventName: 'PreToolUse',\n permissionDecision: 'deny',\n // THE SERVER'S LINE, VERBATIM. It already carries the id and, on a\n // native call, the exact search or URL that was denied, so there is\n // nothing left here to compose and nothing to trim.\n permissionDecisionReason: outcome.hint,\n },\n },\n decision: 'deny',\n action: 'execute',\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 an `execute`\n * also leaves the id-to-session binding the tool resolves its progress through.\n */\nasync function openFooter(\n deps: HookDeps,\n sessionId: string,\n operation: 'prompt' | 'search',\n): Promise<{ close: (decision: HookDecision | null) => Promise<void> }> {\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) => {\n await writeProgress(\n directory,\n callId,\n { phase: 'done', operation, outcome: hookOutcome(decision) },\n now(),\n );\n if (decision !== null && decision.action === 'execute') {\n await bindDecision(deps.dataDir, sessionId, decision.id, now());\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 (decision.action === 'execute') return `paid lookup offered (${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. */\nasync function decide(packet: Packet, deps: HookDeps): Promise<HookDecision | null> {\n const baseUrl = await resolveBaseUrl(deps);\n const warn = deps.warn ?? ((line: string) => process.stderr.write(`${line}\\n`));\n const outcome = await requestDecision(\n 'hook',\n { packet },\n {\n ctx: {\n flags: { json: true, timeout: deps.timeoutMs ?? GATE_TIMEOUT_MS },\n dataDir: deps.dataDir,\n io: { stdout: nullStream(), stderr: nullStream(), isTTY: false },\n },\n baseUrl,\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\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 const bounded = value.trim().slice(0, 4_000);\n if (bounded.length === 0) return null;\n return tool === 'WebSearch' ? { tool, query: bounded } : { tool, url: bounded };\n}\n","import { runNativeHook, runPromptHook, type HookDeps } from './hooks';\nimport type { Io } from '../lib/output';\n\n/**\n * `tenjin hook prompt` and `tenjin hook native`. The harness writes its event on\n * stdin and reads a JSON object (or nothing) from stdout, so these two 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';\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' ? await runPromptHook(event, deps) : await runNativeHook(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,YAAY;AAoBd,IAAM,cAAc;AACpB,IAAM,mBAAmB,KAAK;AAG9B,IAAM,oBAAoB;AACjC,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB;AACzB,IAAM,wBAAwB;AAuB9B,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;AACnD,QAAI;AACF,YAAM,aAAa,IAAI,IAAI,SAAS,EAAE,SAAS;AAC/C,UAAI,WAAW,UAAU,sBAAuB,OAAM,IAAI,UAAU;AAAA,IACtE,QAAQ;AACN;AAAA,IACF;AACA,QAAI,MAAM,QAAQ,iBAAkB;AAAA,EACtC;AACA,SAAO,CAAC,GAAG,KAAK;AAClB;AAYO,SAAS,IAAI,QAAwB;AAC1C,QA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,0BAA0B,CAAC;AAAA,IAC9C,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/router/status-line.ts"],"sourcesContent":["import { renderProgress } from './progress';\nimport type { Io } from '../lib/output';\n\n/**\n * `tenjin status-line`: the live footer Claude Code runs on its own refresh.\n *\n * CHEAP AND READ-ONLY. One JSON event on stdin for the session identity, one\n * read of that session's progress directory, one line out. No network call, no\n * wallet, no config read, no write: it runs once a second for as long as a\n * session is open, so anything it touched would be touched 3,600 times an hour.\n *\n * IT CANNOT FAIL LOUDLY either. Every error path writes nothing and returns, so\n * the command exits 0 with empty output and the harness shows no footer.\n */\n\n/** Claude Code's status event is small; anything larger is not one. */\nconst MAX_EVENT_BYTES = 64_000;\n/** The harness writes the event immediately, so this is a liveness check. */\nexport const STDIN_TIMEOUT_MS = 1_000;\n\nexport interface StatusLineDeps {\n dataDir: string;\n /** Test seam for the harness event; production reads stdin. */\n readEvent?: () => Promise<string>;\n env?: NodeJS.ProcessEnv;\n now?: () => number;\n}\n\n/**\n * The bin entry's fast path for a bare `tenjin status-line`, which runs on a\n * one-second timer: commander, zod and the command tree cost about 120 ms of\n * parse per tick over this path. `dist-chunks.test.ts` pins what it may load.\n */\nexport async function statusLineMain(): Promise<void> {\n const { dataDir } = await import('../lib/paths');\n await runStatusLine(\n { stdout: process.stdout, stderr: process.stderr, isTTY: false },\n { dataDir: dataDir(process.env) },\n );\n}\n\nexport async function runStatusLine(io: Io, deps: StatusLineDeps): Promise<void> {\n let rendered: string;\n try {\n const raw = await (deps.readEvent ?? readStdin)();\n const event: unknown = JSON.parse(raw);\n const sessionId = sessionIdOf(event);\n if (sessionId === null) return;\n const columns = Number((deps.env ?? process.env).COLUMNS);\n rendered = await renderProgress(deps.dataDir, sessionId, {\n ...(Number.isFinite(columns) && columns > 0 ? { columns } : {}),\n ...(deps.now !== undefined ? { now: deps.now() } : {}),\n });\n } catch {\n return;\n }\n if (rendered.length > 0) io.stdout.write(`${rendered}\\n`);\n}\n\n/**\n * The session identity, and nothing else off the event. A footer that showed\n * the wrong session's lookups would be a leak between two terminals, so an\n * event without a plain, bounded `session_id` renders nothing at all.\n */\nfunction sessionIdOf(event: unknown): string | null {\n if (event === null || typeof event !== 'object' || Array.isArray(event)) return null;\n const value = (event as { session_id?: unknown }).session_id;\n if (typeof value !== 'string' || value.length === 0 || value.length > 200) return null;\n return value;\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 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', () => {\n clearTimeout(timer);\n resolve(Buffer.concat(chunks).toString('utf8'));\n });\n process.stdin.once('error', () => {\n clearTimeout(timer);\n reject(new Error('harness event unreadable'));\n });\n });\n}\n"],"mappings":";;;;;;;;AAgBA,IAAM,kBAAkB;AAEjB,IAAM,mBAAmB;AAehC,eAAsB,iBAAgC;AACpD,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,qBAAc;AAC/C,QAAM;AAAA,IACJ,EAAE,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,OAAO,MAAM;AAAA,IAC/D,EAAE,SAAS,QAAQ,QAAQ,GAAG,EAAE;AAAA,EAClC;AACF;AAEA,eAAsB,cAAc,IAAQ,MAAqC;AAC/E,MAAI;AACJ,MAAI;AACF,UAAM,MAAM,OAAO,KAAK,aAAa,WAAW;AAChD,UAAM,QAAiB,KAAK,MAAM,GAAG;AACrC,UAAM,YAAY,YAAY,KAAK;AACnC,QAAI,cAAc,KAAM;AACxB,UAAM,UAAU,QAAQ,KAAK,OAAO,QAAQ,KAAK,OAAO;AACxD,eAAW,MAAM,eAAe,KAAK,SAAS,WAAW;AAA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{ execFile } from 'node:child_process';\nimport { homedir } from 'node:os';\nimport { readFile, stat } from 'node:fs/promises';\nimport { isAbsolute } from 'node:path';\nimport { promisify } from 'node:util';\nimport { persistRouterProject } from '../commands/config';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { inspectHooksFile, pruneHooks } from '../lib/harness-hooks';\nimport { onPath } from '../lib/skill-wiring';\nimport type { CommandContext, CommandResult } from '../context';\nimport {\n ALLOW_RULE,\n MCP_SERVER_NAME,\n mcpRemoveCommand,\n mcpScope,\n routerSettingsPath,\n} from './install';\nimport { removeStatusLine } from './status-line-wiring';\n\n/**\n * `tenjin uninstall`: take out the hook entries, the allow rule and the MCP\n * registration, and nothing else.\n *\n * THE WALLET AND `spend.json` STAY. Removing an integration is not a reason to\n * destroy a key that holds funds or a ledger that records what was spent; both\n * are the user's, and `tenjin wallet` is where they go to move either.\n */\n\nconst exec = promisify(execFile);\n/** The user-scope form; `--project` removes at project scope symmetrically. */\nexport const MCP_REMOVE_COMMAND = mcpRemoveCommand();\n\nexport interface RouterUninstallArgs {\n project?: boolean;\n}\n\nexport interface RouterUninstallDeps {\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n removeMcp?: (opts: { scope: 'user' | 'project'; cwd: string }) => Promise<void>;\n}\n\nexport async function runRouterUninstall(\n args: RouterUninstallArgs,\n ctx: CommandContext,\n deps: RouterUninstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) throw new Error('The home directory is not an absolute path.');\n const cwd = deps.cwd ?? process.cwd();\n const settingsPath = routerSettingsPath({\n ...(args.project === true ? { project: true } : {}),\n homeDir: home,\n cwd,\n });\n\n const removed = await removeFromSettings(settingsPath, ctx.dataDir);\n // OURS ALONE, and after the hooks write so the two never touch the file at\n // once. A COMPOSED status line is the user's own text with ours appended:\n // deleting it would take their line with it, so it is reported and kept.\n const statusLine = await removeStatusLine(settingsPath);\n // Forgotten, so a later `tenjin update` does not go looking for a project\n // this machine no longer wires.\n if (args.project === true) {\n await persistRouterProject(ctx.dataDir, cwd, false).catch(() => undefined);\n }\n // The SAME scope the install used, or a `--project` uninstall would leave the\n // project's registration behind and reach into the user's file instead.\n const mcp = await removeMcpServer(deps, env, args.project === true, cwd);\n const data = {\n settingsPath,\n ...removed,\n statusLine,\n mcp,\n kept: ['wallet.json', 'spend.json', 'config.json'],\n };\n return {\n data,\n humanLines: [\n removed.warning === undefined\n ? `removed ${removed.events.length > 0 ? removed.events.join(', ') : 'no'} hook entries and ${removed.ruleRemoved ? 'the' : 'no'} permission rule from ${settingsPath}`\n : `${settingsPath} was left untouched (${removed.warning})`,\n statusLine.wrote\n ? 'removed the x402 status line'\n : statusLine.state === 'composed'\n ? 'status line: yours also runs the x402 footer; edit that command to drop it'\n : 'status line: none of ours was registered',\n mcp.removed\n ? `removed the ${MCP_SERVER_NAME} MCP server (${mcp.scope} scope)`\n : `mcp: run ${mcp.command}`,\n 'Your wallet, spend ledger and config are kept.',\n ],\n };\n}\n\ninterface SettingsRemoval {\n /** The events an entry of ours was taken out of. */\n events: string[];\n ruleRemoved: boolean;\n wrote: boolean;\n warning?: string;\n}\n\nasync function removeFromSettings(path: string, dataDir: string): Promise<SettingsRemoval> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n return { events: [], ruleRemoved: false, wrote: false, warning: found.refusal.reason };\n }\n const { raw, settings, hooks } = found;\n if (raw === null) return { events: [], ruleRemoved: false, wrote: false };\n const pruned = pruneHooks(hooks, dataDir);\n const permissions =\n settings.permissions !== null &&\n typeof settings.permissions === 'object' &&\n !Array.isArray(settings.permissions)\n ? (settings.permissions as Record<string, unknown>)\n : undefined;\n const allow = Array.isArray(permissions?.allow) ? permissions.allow : undefined;\n const ruleRemoved = allow?.includes(ALLOW_RULE) === true;\n const next = {\n ...settings,\n hooks: pruned.next,\n ...(permissions !== undefined && allow !== undefined\n ? { permissions: { ...permissions, allow: allow.filter((r) => r !== ALLOW_RULE) } }\n : {}),\n };\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n if (body === raw) {\n return { events: pruned.removed, ruleRemoved, wrote: false };\n }\n const mode = await stat(found.path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n if ((await readFile(found.path, 'utf8').catch(() => null)) !== raw) {\n return { events: [], ruleRemoved: false, wrote: false, warning: 'changed-since-read' };\n }\n try {\n await writeFileAtomic(found.path, body, mode);\n } catch (err) {\n return {\n events: [],\n ruleRemoved: false,\n wrote: false,\n warning: err instanceof Error ? err.message : String(err),\n };\n }\n return { events: pruned.removed, ruleRemoved, wrote: true };\n}\n\nasync function removeMcpServer(\n deps: RouterUninstallDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n): Promise<{ removed: boolean; scope: 'user' | 'project'; command: string; reason?: string }> {\n const scope = mcpScope(project);\n const command = mcpRemoveCommand(project);\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (!which('claude')) {\n return { removed: false, scope, command, reason: 'the `claude` binary is not on PATH' };\n }\n try {\n await (deps.removeMcp ?? runClaudeMcpRemove)({ scope, cwd });\n return { removed: true, scope, command };\n } catch (err) {\n return {\n removed: false,\n scope,\n command,\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nasync function runClaudeMcpRemove(opts: { scope: 'user' | 'project'; cwd: string }): Promise<void> {\n await exec('claude', ['mcp', 'remove', MCP_SERVER_NAME, '-s', opts.scope], {\n timeout: 20_000,\n cwd: opts.cwd,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,UAAU,YAAY;AAC/B,SAAS,kBAAkB;AAC3B,SAAS,iBAAiB;AAwB1B,IAAM,OAAO,UAAU,QAAQ;AAExB,IAAM,qBAAqB,iBAAiB;AAcnD,eAAsB,mBACpB,MACA,KACA,OAA4B,CA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