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

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 (119) hide show
  1. package/README.md +16 -43
  2. package/dist/{chunk-EOGJKIOG.js → chunk-2TYQD22Q.js} +16 -7
  3. package/dist/chunk-2TYQD22Q.js.map +1 -0
  4. package/dist/{chunk-SCAE6PW6.js → chunk-4L7KMA7P.js} +6 -6
  5. package/dist/{chunk-UDWGT4FX.js → chunk-5FGO6TYT.js} +13 -5
  6. package/dist/chunk-5FGO6TYT.js.map +1 -0
  7. package/dist/{chunk-IYLECN4D.js → chunk-5NEHH2E5.js} +3 -3
  8. package/dist/{chunk-EACMJEF3.js → chunk-64SE3QC5.js} +75 -176
  9. package/dist/chunk-64SE3QC5.js.map +1 -0
  10. package/dist/chunk-6ZSGER3A.js +52 -0
  11. package/dist/chunk-6ZSGER3A.js.map +1 -0
  12. package/dist/{chunk-QF4SSCQV.js → chunk-AWKQSKUL.js} +4 -3
  13. package/dist/chunk-AWKQSKUL.js.map +1 -0
  14. package/dist/chunk-B2L53TMK.js +70 -0
  15. package/dist/chunk-B2L53TMK.js.map +1 -0
  16. package/dist/chunk-BOAI23CX.js +222 -0
  17. package/dist/chunk-BOAI23CX.js.map +1 -0
  18. package/dist/{chunk-OZ3LWLCI.js → chunk-DATCR7AU.js} +3 -3
  19. package/dist/{chunk-NTYQHAIM.js → chunk-DSNXKUXI.js} +2 -2
  20. package/dist/{chunk-HII5HOQV.js → chunk-G4AM2SOL.js} +5 -3
  21. package/dist/{chunk-HII5HOQV.js.map → chunk-G4AM2SOL.js.map} +1 -1
  22. package/dist/{chunk-VYONGSMQ.js → chunk-GU4GGKYP.js} +85 -6
  23. package/dist/chunk-GU4GGKYP.js.map +1 -0
  24. package/dist/{chunk-YSW57KUT.js → chunk-H2L33M7F.js} +31 -27
  25. package/dist/chunk-H2L33M7F.js.map +1 -0
  26. package/dist/{chunk-ODH7UXIS.js → chunk-HC3QEZKT.js} +5 -4
  27. package/dist/chunk-HC3QEZKT.js.map +1 -0
  28. package/dist/chunk-MAQUL5BD.js +99 -0
  29. package/dist/chunk-MAQUL5BD.js.map +1 -0
  30. package/dist/{chunk-EG7P4SM6.js → chunk-O7CUHHYU.js} +4 -4
  31. package/dist/{chunk-EG7P4SM6.js.map → chunk-O7CUHHYU.js.map} +1 -1
  32. package/dist/{chunk-CEMXMUIU.js → chunk-OHZYNZSD.js} +36 -7
  33. package/dist/chunk-OHZYNZSD.js.map +1 -0
  34. package/dist/{chunk-3ZYPVSIU.js → chunk-PY7MQUKP.js} +238 -43
  35. package/dist/chunk-PY7MQUKP.js.map +1 -0
  36. package/dist/chunk-PZ5N6BAL.js +268 -0
  37. package/dist/chunk-PZ5N6BAL.js.map +1 -0
  38. package/dist/chunk-S4SAZ7OD.js +30 -0
  39. package/dist/chunk-S4SAZ7OD.js.map +1 -0
  40. package/dist/{chunk-NYPFOHSJ.js → chunk-SKQQOEWH.js} +4 -4
  41. package/dist/{chunk-XICKN3CH.js → chunk-VIOUZW7Z.js} +2 -46
  42. package/dist/chunk-VIOUZW7Z.js.map +1 -0
  43. package/dist/{chunk-YTM7OURD.js → chunk-VNNXAYJE.js} +2 -2
  44. package/dist/{chunk-CKDD554V.js → chunk-VXIBZ6W5.js} +5 -3
  45. package/dist/{chunk-CKDD554V.js.map → chunk-VXIBZ6W5.js.map} +1 -1
  46. package/dist/{chunk-GT6W3VJM.js → chunk-X7I343ZY.js} +3 -53
  47. package/dist/chunk-X7I343ZY.js.map +1 -0
  48. package/dist/{chunk-KGTQRJGS.js → chunk-XVYATBKD.js} +5 -10
  49. package/dist/{chunk-KGTQRJGS.js.map → chunk-XVYATBKD.js.map} +1 -1
  50. package/dist/{chunk-DRXDTITB.js → chunk-YKM2ZTA2.js} +59 -25
  51. package/dist/chunk-YKM2ZTA2.js.map +1 -0
  52. package/dist/{chunk-CP7O6M55.js → chunk-YQOQ6XEI.js} +109 -27
  53. package/dist/chunk-YQOQ6XEI.js.map +1 -0
  54. package/dist/{cli-4WMGZPBP.js → cli-6JNIPZQ6.js} +43 -39
  55. package/dist/{cli-4WMGZPBP.js.map → cli-6JNIPZQ6.js.map} +1 -1
  56. package/dist/{config-VU6U7QOU.js → config-G75YT6NC.js} +15 -10
  57. package/dist/{doctor-26JS2SG3.js → doctor-3GMDOW4Y.js} +140 -98
  58. package/dist/doctor-3GMDOW4Y.js.map +1 -0
  59. package/dist/env-proxy-XL4P73MZ.js +15 -0
  60. package/dist/{fund-JJN3FRRF.js → fund-3IPR5YRJ.js} +26 -14
  61. package/dist/{fund-JJN3FRRF.js.map → fund-3IPR5YRJ.js.map} +1 -1
  62. package/dist/hook-command-ZXX4FT4N.js +32 -0
  63. package/dist/index.js +7 -5
  64. package/dist/index.js.map +1 -1
  65. package/dist/{install-GXQ33J4G.js → install-6OROTYHZ.js} +20 -14
  66. package/dist/{install-identity-HFQUXPSI.js → install-identity-PM4AGFFX.js} +7 -6
  67. package/dist/{install-wallet-27LTEHBI.js → install-wallet-6756NOB5.js} +11 -8
  68. package/dist/{install-wallet-27LTEHBI.js.map → install-wallet-6756NOB5.js.map} +1 -1
  69. package/dist/{mcp-AHCZVD2U.js → mcp-33FAAZ7F.js} +723 -123
  70. package/dist/mcp-33FAAZ7F.js.map +1 -0
  71. package/dist/{pay-3TCOPGCX.js → pay-XOYR4PCH.js} +14 -12
  72. package/dist/{payments-H3LSBGSL.js → payments-UTQDBO7H.js} +8 -6
  73. package/dist/{payments-H3LSBGSL.js.map → payments-UTQDBO7H.js.map} +1 -1
  74. package/dist/{send-LKCLN5GA.js → send-CVGNOQW3.js} +12 -9
  75. package/dist/{send-LKCLN5GA.js.map → send-CVGNOQW3.js.map} +1 -1
  76. package/dist/{status-2FDGI4LQ.js → status-NACN4DGX.js} +10 -7
  77. package/dist/{status-2FDGI4LQ.js.map → status-NACN4DGX.js.map} +1 -1
  78. package/dist/{status-line-QKDJYZGV.js → status-line-3IQKGRUH.js} +6 -5
  79. package/dist/{status-line-QKDJYZGV.js.map → status-line-3IQKGRUH.js.map} +1 -1
  80. package/dist/{status-line-wiring-ZDBYHNYR.js → status-line-wiring-QXBOOY2T.js} +4 -4
  81. package/dist/{uninstall-ZXWABDHS.js → uninstall-NYFKSYW4.js} +22 -16
  82. package/dist/{uninstall-ZXWABDHS.js.map → uninstall-NYFKSYW4.js.map} +1 -1
  83. package/dist/{update-HEIWVOP5.js → update-RJDA5ZY3.js} +11 -13
  84. package/dist/update-RJDA5ZY3.js.map +1 -0
  85. package/dist/{wallet-T7JYWI6O.js → wallet-B3FVHNTS.js} +11 -8
  86. package/dist/wallet-B3FVHNTS.js.map +1 -0
  87. package/docs/agent-permissions.md +18 -7
  88. package/docs/troubleshooting.md +13 -0
  89. package/package.json +4 -3
  90. package/dist/chunk-3ZYPVSIU.js.map +0 -1
  91. package/dist/chunk-CEMXMUIU.js.map +0 -1
  92. package/dist/chunk-CP7O6M55.js.map +0 -1
  93. package/dist/chunk-DRXDTITB.js.map +0 -1
  94. package/dist/chunk-EACMJEF3.js.map +0 -1
  95. package/dist/chunk-EOGJKIOG.js.map +0 -1
  96. package/dist/chunk-GT6W3VJM.js.map +0 -1
  97. package/dist/chunk-ODH7UXIS.js.map +0 -1
  98. package/dist/chunk-QF4SSCQV.js.map +0 -1
  99. package/dist/chunk-UDWGT4FX.js.map +0 -1
  100. package/dist/chunk-VYONGSMQ.js.map +0 -1
  101. package/dist/chunk-XICKN3CH.js.map +0 -1
  102. package/dist/chunk-YSW57KUT.js.map +0 -1
  103. package/dist/doctor-26JS2SG3.js.map +0 -1
  104. package/dist/hook-command-S2V4UNB3.js +0 -28
  105. package/dist/mcp-AHCZVD2U.js.map +0 -1
  106. package/dist/update-HEIWVOP5.js.map +0 -1
  107. /package/dist/{chunk-SCAE6PW6.js.map → chunk-4L7KMA7P.js.map} +0 -0
  108. /package/dist/{chunk-IYLECN4D.js.map → chunk-5NEHH2E5.js.map} +0 -0
  109. /package/dist/{chunk-OZ3LWLCI.js.map → chunk-DATCR7AU.js.map} +0 -0
  110. /package/dist/{chunk-NTYQHAIM.js.map → chunk-DSNXKUXI.js.map} +0 -0
  111. /package/dist/{chunk-NYPFOHSJ.js.map → chunk-SKQQOEWH.js.map} +0 -0
  112. /package/dist/{chunk-YTM7OURD.js.map → chunk-VNNXAYJE.js.map} +0 -0
  113. /package/dist/{config-VU6U7QOU.js.map → config-G75YT6NC.js.map} +0 -0
  114. /package/dist/{hook-command-S2V4UNB3.js.map → env-proxy-XL4P73MZ.js.map} +0 -0
  115. /package/dist/{install-GXQ33J4G.js.map → hook-command-ZXX4FT4N.js.map} +0 -0
  116. /package/dist/{install-identity-HFQUXPSI.js.map → install-6OROTYHZ.js.map} +0 -0
  117. /package/dist/{pay-3TCOPGCX.js.map → install-identity-PM4AGFFX.js.map} +0 -0
  118. /package/dist/{status-line-wiring-ZDBYHNYR.js.map → pay-XOYR4PCH.js.map} +0 -0
  119. /package/dist/{wallet-T7JYWI6O.js.map → status-line-wiring-QXBOOY2T.js.map} +0 -0
@@ -1,10 +1,14 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ evaluateSpendPolicy
4
+ } from "./chunk-B2L53TMK.js";
2
5
  import {
3
6
  hasCode
4
7
  } from "./chunk-2I4QTOLB.js";
5
8
  import {
6
- formatUsdDisplay
7
- } from "./chunk-XICKN3CH.js";
9
+ formatUsdDisplay,
10
+ toMoney
11
+ } from "./chunk-6ZSGER3A.js";
8
12
 
9
13
  // src/router/fee.ts
10
14
  import { createHash } from "node:crypto";
@@ -14,6 +18,21 @@ var ROUTE_PAID_PATH = "/api/x402-router/route";
14
18
  var ROUTING_FEE_ATOMIC = 3000n;
15
19
  var CHANNEL_DEPOSIT_ATOMIC = 250000n;
16
20
  var MIN_DEPOSIT_ATOMIC = 10n * ROUTING_FEE_ATOMIC;
21
+ var REFUSED = {
22
+ not_allowlisted: "not_allowlisted",
23
+ session_budget_exceeded: "budget_reached",
24
+ above_auto_spend: "limit_below_deposit"
25
+ };
26
+ function refusedWhy(reason) {
27
+ return REFUSED[reason] ?? reason;
28
+ }
29
+ function feeRefusal(policy, host) {
30
+ const evaluation = evaluateSpendPolicy(
31
+ { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },
32
+ { mode: "automatic", amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n }
33
+ );
34
+ return evaluation.decision === "allow" ? null : refusedWhy(evaluation.reason);
35
+ }
17
36
  var FEE_REQUIRED = "fee_required";
18
37
  function isFeeRequired(response) {
19
38
  const decision = response?.decision;
@@ -38,7 +57,7 @@ var UNPAID = {
38
57
  fix: "Run `tenjin doctor`."
39
58
  },
40
59
  budget_reached: {
41
- reason: "the daily spend limit has no room left for a routing deposit",
60
+ reason: "the daily spend limit has no room left for the routing fee or its deposit",
42
61
  fix: "Run `tenjin doctor`."
43
62
  },
44
63
  not_allowlisted: {
@@ -54,7 +73,13 @@ var UNPAID = {
54
73
  fix: "Run `tenjin doctor`."
55
74
  }
56
75
  };
57
- var NO_FAULT = /* @__PURE__ */ new Set(["channel_busy", "paid_path_absent", "busy", "no_call"]);
76
+ var NO_FAULT = /* @__PURE__ */ new Set([
77
+ "channel_busy",
78
+ "paid_path_absent",
79
+ "busy",
80
+ "no_call",
81
+ "deadline_after_payment_sent"
82
+ ]);
58
83
  function unpaid(why) {
59
84
  if (NO_FAULT.has(why)) return null;
60
85
  return UNPAID[why] ?? UNPAID["payment_failed"];
@@ -103,17 +128,71 @@ async function createExclusive(path, body) {
103
128
  }
104
129
  }
105
130
 
131
+ // src/router/spend-question.ts
132
+ var ROUTER_DEFAULTS = {
133
+ maxAutoSpend: "250000",
134
+ sessionBudget: "5000000"
135
+ };
136
+ function shownLimits(config) {
137
+ return {
138
+ maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,
139
+ sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget
140
+ };
141
+ }
142
+ function limitsUsd(limits) {
143
+ return {
144
+ maxAutoSpend: toMoney(limits.maxAutoSpend).usd,
145
+ sessionBudget: limits.sessionBudget === "none" ? "none" : toMoney(limits.sessionBudget).usd
146
+ };
147
+ }
148
+ function limitsPhrase(limits) {
149
+ const usdOf = limitsUsd(limits);
150
+ const daily = usdOf.sessionBudget === "none" ? "with no daily limit" : `and $${usdOf.sessionBudget} a day`;
151
+ return `up to $${usdOf.maxAutoSpend} a call ${daily}`;
152
+ }
153
+ var ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;
154
+ var ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;
155
+ var OWN_LIMITS_COMMANDS = "`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`";
156
+ var FEE_APPROVAL = "Using these limits or choosing your own also approves the routing fee.";
157
+ function spendQuestion(limits) {
158
+ return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;
159
+ }
160
+ function unansweredNotice(limits, reader) {
161
+ const open2 = "Tenjin pays for nothing on its own yet: the spend limits are not answered.";
162
+ if (reader === "agent") {
163
+ return `${open2} Ask the user: ${spendQuestion(limits)} For a yes, run \`${ACCEPT_COMMAND}\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;
164
+ }
165
+ return `${open2} It can pay for tool calls without asking you each time, ${limitsPhrase(limits)}. ${ROUTING_FEE_TERMS} ${FEE_APPROVAL} To use these limits, run \`${ACCEPT_COMMAND}\`; to choose your own, run ${OWN_LIMITS_COMMANDS}.`;
166
+ }
167
+ function unpaidNotice(why, config, reader) {
168
+ if (why === "limit_below_deposit" && config.maxAutoSpend === void 0) {
169
+ return unansweredNotice(shownLimits(config), reader);
170
+ }
171
+ return unpaidSentence(why);
172
+ }
173
+
106
174
  export {
107
175
  ROUTE_PAID_PATH,
108
176
  ROUTING_FEE_ATOMIC,
109
177
  CHANNEL_DEPOSIT_ATOMIC,
110
178
  MIN_DEPOSIT_ATOMIC,
179
+ refusedWhy,
180
+ feeRefusal,
111
181
  FEE_REQUIRED,
112
182
  isFeeRequired,
113
183
  unpaid,
114
184
  unpaidSentence,
115
185
  payerDir,
116
186
  usd,
117
- firstNoticeFor
187
+ firstNoticeFor,
188
+ ROUTER_DEFAULTS,
189
+ shownLimits,
190
+ limitsUsd,
191
+ ROUTING_FEE_TERMS,
192
+ ACCEPT_COMMAND,
193
+ OWN_LIMITS_COMMANDS,
194
+ FEE_APPROVAL,
195
+ spendQuestion,
196
+ unpaidNotice
118
197
  };
119
- //# sourceMappingURL=chunk-VYONGSMQ.js.map
198
+ //# sourceMappingURL=chunk-GU4GGKYP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/fee.ts","../src/router/spend-question.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { mkdir, open, readFile, readdir, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { hasCode } from '../lib/errno';\nimport { formatUsdDisplay } from '../lib/money';\nimport { evaluateSpendPolicy, type PolicyReason, type SpendPolicy } from '../lib/policy';\nimport type { DecisionRoute } from './decision';\n\n/**\n * THE ROUTING FEE, WITHOUT ANYTHING THAT PAYS. Every routing call on the paid\n * path pays $0.003 over x402 `batch-settlement`, and the stock SDK client in\n * `tenjin mcp` does all of it (`routing-payer.ts`). Everything else, `tenjin\n * hook` included, is the free path exactly as before this fee existed.\n *\n * Hook-safe: `tenjin hook` loads this module, and its chunk graph stays free\n * of the wallet and the x402 SDK (`dist-chunks.test.ts`).\n */\n\nexport const ROUTE_PAID_PATH = '/api/x402-router/route';\n\n/** The flat fee per routing call, atomic USDC ($0.003). */\nexport const ROUTING_FEE_ATOMIC = 3_000n;\n/** The largest channel deposit, atomic USDC ($0.25), made inline by the SDK\n * on the first paid call of a channel that cannot cover the next fee. */\nexport const CHANNEL_DEPOSIT_ATOMIC = 250_000n;\n/**\n * The smallest deposit worth signing: ten fees ($0.03). A per-call limit under\n * $0.25 sizes the deposit down to the limit while it still covers this many.\n */\nexport const MIN_DEPOSIT_ATOMIC = 10n * ROUTING_FEE_ATOMIC;\n\n/** A spend refusal, as the reason the call was not paid. */\nconst REFUSED: Partial<Record<PolicyReason, string>> = {\n not_allowlisted: 'not_allowlisted',\n session_budget_exceeded: 'budget_reached',\n above_auto_spend: 'limit_below_deposit',\n};\n\n/** The reason a spend refusal leaves a routing call unpaid. */\nexport function refusedWhy(reason: PolicyReason): string {\n return REFUSED[reason] ?? reason;\n}\n\n/**\n * THE DEPOSIT IS THE SPEND. It meets the whole policy once, the day's budget\n * included, when the SDK's `depositStrategy` reserves it. Each fee paid from\n * it then gets only the per-payment checks: the per-call limit, the creator\n * allowlist (the router's host) and an explicit zero daily limit. It is never\n * refused for the day's running total, which the deposit already consumed.\n * Null when those checks allow the fee.\n */\nexport function feeRefusal(policy: SpendPolicy, host: string): string | null {\n const evaluation = evaluateSpendPolicy(\n { ...policy, sessionBudgetAtomic: policy.sessionBudgetAtomic === 0n ? 0n : null },\n { mode: 'automatic', amountAtomic: ROUTING_FEE_ATOMIC, creator: host, sessionSpentAtomic: 0n },\n );\n return evaluation.decision === 'allow' ? null : refusedWhy(evaluation.reason);\n}\n\n/** The paid path for this call, or null for the free path. `tenjin mcp` passes\n * its payer's; absent, every call is free. */\nexport type RouteFor = (baseUrl: string) => Promise<DecisionRoute | null>;\n\n/** The free path's reason code once the server routes only paid calls. */\nexport const FEE_REQUIRED = 'fee_required';\n\n/** Whether a decision is the free path's `fee_required` answer. */\nexport function isFeeRequired(response: unknown): boolean {\n const decision = (response as { decision?: { action?: unknown; diagnostics?: unknown } })\n ?.decision;\n const diagnostics = decision?.diagnostics as { reasonCode?: unknown } | undefined;\n return decision?.action === 'native' && diagnostics?.reasonCode === FEE_REQUIRED;\n}\n\n/**\n * WHY A CALL WAS NOT PAID, for the user: the reason and the fix, keyed by the\n * payer's skip reason (or `fee_required`, when the free path answered it and\n * nothing else explains why). Null for a reason that is no fault and needs no\n * fix: another session's call on the channel, a server with no paid path, or\n * a call queued past its own budget, or a payment still out when the call's\n * budget ran out (it finishes in the background).\n */\nconst UNPAID: Record<string, { reason: string; fix: string }> = {\n wallet_low: {\n reason: `the wallet holds less than the $${usd(CHANNEL_DEPOSIT_ATOMIC)} routing deposit`,\n fix: `Fund it with \\`tenjin wallet fund ${usd(CHANNEL_DEPOSIT_ATOMIC)}\\`.`,\n },\n wallet_locked: {\n reason: '`tenjin mcp` cannot unlock the wallet without a prompt',\n fix: 'Set TENJIN_WALLET_PASSPHRASE in the environment Claude Code starts from, then restart Claude Code.',\n },\n no_wallet: {\n reason: 'this machine has no wallet',\n fix: 'Run `tenjin doctor`.',\n },\n limit_below_deposit: {\n reason: `the per-call spend limit is below the smallest routing deposit ($${usd(MIN_DEPOSIT_ATOMIC)})`,\n fix: 'Run `tenjin doctor`.',\n },\n budget_reached: {\n reason: 'the daily spend limit has no room left for the routing fee or its deposit',\n fix: 'Run `tenjin doctor`.',\n },\n not_allowlisted: {\n reason: 'allowlistCreators does not include the router',\n fix: 'Run `tenjin doctor`.',\n },\n payment_failed: {\n reason: 'the routing payment failed',\n fix: 'Run `tenjin doctor`.',\n },\n [FEE_REQUIRED]: {\n reason: 'the router now charges it, and this session cannot pay it',\n fix: 'Run `tenjin doctor`.',\n },\n};\nconst NO_FAULT = new Set([\n 'channel_busy',\n 'paid_path_absent',\n 'busy',\n 'no_call',\n 'deadline_after_payment_sent',\n]);\n\n/** The reason and fix for an unpaid call, or null when it needs no word. */\nexport function unpaid(why: string): { reason: string; fix: string } | null {\n if (NO_FAULT.has(why)) return null;\n return UNPAID[why] ?? UNPAID['payment_failed']!;\n}\n\n/** The one line the user sees, once per session, when a call was not paid. */\nexport function unpaidSentence(why: string): string | null {\n const u = unpaid(why);\n if (u === null) return null;\n return `Tenjin routing could not pay its $${usd(ROUTING_FEE_ATOMIC)} fee (${u.reason}), so calls take the free path until that is fixed. ${u.fix}`;\n}\n\nconst ADDRESS_RE = /^0x[0-9a-f]{40}$/;\n\n/** One wallet's folder: the SDK's file storage for its routing channel\n * (`client/<channelId>.json`). */\nexport function payerDir(dataDir: string, payer: string): string {\n const name = payer.toLowerCase();\n if (!ADDRESS_RE.test(name)) throw new Error(`not a wallet address: ${payer}`);\n return join(dataDir, 'router', 'fee', name);\n}\n\n/** Atomic USDC as dollars with at least two decimals, never a float. */\nexport function usd(atomic: bigint): string {\n return formatUsdDisplay(atomic.toString());\n}\n\n/** How long a session's notice marker is kept. */\nconst NOTICE_KEEP_MS = 7 * 86_400_000;\n\n/**\n * TRUE ONCE PER SESSION: the first caller for a session id creates its marker\n * and gets true; every later one gets false. Each marker holds the time it was\n * made, and those older than a week go on the way past, so the directory does\n * not grow with every session ever run.\n */\nexport async function firstNoticeFor(\n dataDir: string,\n sessionId: string,\n now: number,\n): Promise<boolean> {\n const dir = join(dataDir, 'router', 'notices');\n const name = createHash('sha256').update(sessionId).digest('hex').slice(0, 32);\n const created = await createExclusive(join(dir, name), String(now));\n if (created) {\n for (const entry of await readdir(dir).catch(() => [] as string[])) {\n const path = join(dir, entry);\n const at = Number(await readFile(path, 'utf8').catch(() => 'NaN'));\n if (!Number.isFinite(at) || now - at > NOTICE_KEEP_MS) await rm(path, { force: true });\n }\n }\n return created;\n}\n\nasync function createExclusive(path: string, body: string): Promise<boolean> {\n try {\n await mkdir(join(path, '..'), { recursive: true, mode: 0o700 });\n const handle = await open(path, 'wx', 0o600);\n try {\n await handle.writeFile(body);\n } finally {\n await handle.close();\n }\n return true;\n } catch (err) {\n if (hasCode(err, 'EEXIST')) return false;\n throw err;\n }\n}\n","import { toMoney } from '../lib/money';\nimport { CHANNEL_DEPOSIT_ATOMIC, ROUTING_FEE_ATOMIC, unpaidSentence, usd } from './fee';\n\n/**\n * THE SPEND QUESTION, ONE TEXT FOR EVERY PLACE THAT ASKS IT. The selector in a\n * terminal, the question an install that could not ask hands to its agent,\n * doctor's warning and the routing notice all show the same limits, the same\n * routing-fee terms and the same one-step yes, so the agent can put to the\n * user exactly what the selector would have.\n */\n\n/** Absent-only automatic router defaults, in atomic USDC. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: '250000',\n sessionBudget: '5000000',\n} as const;\n\n/** The automatic limits a fresh install fills in, in atomic USDC; `sessionBudget` may be `none`. */\nexport interface RouterLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\n/** What the question shows: the file's own value where it names one, else the default. */\nexport function shownLimits(config: {\n maxAutoSpend?: string | undefined;\n sessionBudget?: string | undefined;\n}): RouterLimits {\n return {\n maxAutoSpend: config.maxAutoSpend ?? ROUTER_DEFAULTS.maxAutoSpend,\n sessionBudget: config.sessionBudget ?? ROUTER_DEFAULTS.sessionBudget,\n };\n}\n\n/** The limits in USD, as the question shows them. */\nexport function limitsUsd(limits: RouterLimits): { maxAutoSpend: string; sessionBudget: string } {\n return {\n maxAutoSpend: toMoney(limits.maxAutoSpend).usd,\n sessionBudget: limits.sessionBudget === 'none' ? 'none' : toMoney(limits.sessionBudget).usd,\n };\n}\n\n/** \"up to $0.25 a call and $5 a day\" */\nexport function limitsPhrase(limits: RouterLimits): string {\n const usdOf = limitsUsd(limits);\n const daily =\n usdOf.sessionBudget === 'none' ? 'with no daily limit' : `and $${usdOf.sessionBudget} a day`;\n return `up to $${usdOf.maxAutoSpend} a call ${daily}`;\n}\n\n/** The routing fee's terms, as the selector names them. */\nexport const ROUTING_FEE_TERMS = `Routing costs $${usd(ROUTING_FEE_ATOMIC)} a call, paid from channel deposits of up to $${usd(CHANNEL_DEPOSIT_ATOMIC)} that stay yours until spent; each deposit counts against these limits.`;\n\n/**\n * The yes to the limits shown, where the command install ran is not known\n * (doctor, the routing notice, the request tool): the per-call limit only.\n * The daily limit already defaults to the one shown. A bare `install --yes`\n * here would undo a `--project`, `--no-wallet` or `--status-line skip`\n * install; install's own output names that command with its flags instead.\n */\nexport const ACCEPT_COMMAND = `tenjin config set maxAutoSpend ${toMoney(ROUTER_DEFAULTS.maxAutoSpend).usd}`;\n\n/** The commands for limits of the user's own, each in backticks. */\nexport const OWN_LIMITS_COMMANDS =\n '`tenjin config set maxAutoSpend <usd>` and `tenjin config set sessionBudget <usd|none>`';\n\n/** The selector's own line: either answer approves the fee. */\nexport const FEE_APPROVAL =\n 'Using these limits or choosing your own also approves the routing fee.';\n\n/** The question, for the agent to put to the user as written. */\nexport function spendQuestion(limits: RouterLimits): string {\n return `May Tenjin pay for tool calls without asking you each time, ${limitsPhrase(limits)}? ${ROUTING_FEE_TERMS} ${FEE_APPROVAL}`;\n}\n\n/** Who reads a notice: the user, in the hook's `systemMessage`, or the agent,\n * in the request tool's answer. */\nexport type NoticeReader = 'user' | 'agent';\n\n/**\n * The routing notice for a machine whose limits nobody has answered: the\n * question and the one-step yes, put to the user directly, or handed to the\n * agent to ask.\n */\nexport function unansweredNotice(limits: RouterLimits, reader: NoticeReader): string {\n const open = 'Tenjin pays for nothing on its own yet: the spend limits are not answered.';\n if (reader === 'agent') {\n return `${open} Ask the user: ${spendQuestion(limits)} For a yes, run \\`${ACCEPT_COMMAND}\\`; for other amounts, run ${OWN_LIMITS_COMMANDS}.`;\n }\n return `${open} It can pay for tool calls without asking you each time, ${limitsPhrase(limits)}. ${ROUTING_FEE_TERMS} ${FEE_APPROVAL} To use these limits, run \\`${ACCEPT_COMMAND}\\`; to choose your own, run ${OWN_LIMITS_COMMANDS}.`;\n}\n\n/**\n * The routing notice for a call that was not paid: the limits question when\n * the per-call limit is the code default's zero because nobody has answered\n * it, else the reason and fix for `why`.\n */\nexport function unpaidNotice(\n why: string,\n config: { maxAutoSpend?: string | undefined; sessionBudget?: string | undefined },\n reader: NoticeReader,\n): string | null {\n if (why === 'limit_below_deposit' && config.maxAutoSpend === undefined) {\n return unansweredNotice(shownLimits(config), reader);\n }\n return unpaidSentence(why);\n}\n"],"mappings":";;;;;;;;;;;;;AAAA,SAAS,kBAAkB;AAC3B,SAAS,OAAO,MAAM,UAAU,SAAS,UAAU;AACnD,SAAS,YAAY;AAgBd,IAAM,kBAAkB;AAGxB,IAAM,qBAAqB;AAG3B,IAAM,yBAAyB;AAK/B,IAAM,qBAAqB,MAAM;AAGxC,IAAM,UAAiD;AAAA,EACrD,iBAAiB;AAAA,EACjB,yBAAyB;AAAA,EACzB,kBAAkB;AACpB;AAGO,SAAS,WAAW,QAA8B;AACvD,SAAO,QAAQ,MAAM,KAAK;AAC5B;AAUO,SAAS,WAAW,QAAqB,MAA6B;AAC3E,QAAM,aAAa;AAAA,IACjB,EAAE,GAAG,QAAQ,qBAAqB,OAAO,wBAAwB,KAAK,KAAK,KAAK;AAAA,IAChF,EAAE,MAAM,aAAa,cAAc,oBAAoB,SAAS,MAAM,oBAAoB,GAAG;AAAA,EAC/F;AACA,SAAO,WAAW,aAAa,UAAU,OAAO,WAAW,WAAW,MAAM;AAC9E;AAOO,IAAM,eAAe;AAGrB,SAAS,cAAc,UAA4B;AACxD,QAAM,WAAY,UACd;AACJ,QAAM,cAAc,UAAU;AAC9B,SAAO,UAAU,WAAW,YAAY,aAAa,eAAe;AACtE;AAUA,IAAM,SAA0D;AAAA,EAC9D,YAAY;AAAA,IACV,QAAQ,mCAAmC,IAAI,sBAAsB,CAAC;AAAA,IACtE,KAAK,qCAAqC,IAAI,sBAAsB,CAAC;AAAA,EACvE;AAAA,EACA,eAAe;AAAA,IACb,QAAQ;AAAA,IACR,KAAK;AAAA,EACP;AAAA,EACA,WAAW;AAAA,IACT,QAAQ;AAAA,IACR,KAAK;AAAA,EACP;AAAA,EACA,qBAAqB;AAAA,IACnB,QAAQ,oEAAoE,IAAI,kBAAkB,CAAC;AAAA,IACnG,KAAK;AAAA,EACP;AAAA,EACA,gBAAgB;AAAA,IACd,QA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AM,oBAAoB,kBAAkB,IAAI,kBAAkB,CAAC,iDAAiD,IAAI,sBAAsB,CAAC;AAS/I,IAAM,iBAAiB,kCAAkC,QAAQ,gBAAgB,YAAY,EAAE,GAAG;AAGlG,IAAM,sBACX;AAGK,IAAM,eACX;AAGK,SAAS,cAAc,QAA8B;AAC1D,SAAO,+DAA+D,aAAa,MAAM,CAAC,KAAK,iBAAiB,IAAI,YAAY;AAClI;AAWO,SAAS,iBAAiB,QAAsB,QAA8B;AACnF,QAAMA,QAAO;AACb,MAAI,WAAW,SAAS;AACtB,WAAO,GAAGA,KAAI,kBAAkB,cAAc,MAAM,CAAC,qBAAqB,cAAc,8BAA8B,mBAAmB;AAAA,EAC3I;AACA,SAAO,GAAGA,KAAI,4DAA4D,aAAa,MAAM,CAAC,KAAK,iBAAiB,IAAI,YAAY,+BAA+B,cAAc,+BAA+B,mBAAmB;AACrO;AAOO,SAAS,aACd,KACA,QACA,QACe;AACf,MAAI,QAAQ,yBAAyB,OAAO,iBAAiB,QAAW;AACtE,WAAO,iBAAiB,YAAY,MAAM,GAAG,MAAM;AAAA,EACrD;AACA,SAAO,eAAe,GAAG;AAC3B;","names":["open"]}
@@ -1,7 +1,18 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ ROUTER_DEFAULTS
4
+ } from "./chunk-GU4GGKYP.js";
2
5
  import {
3
6
  modeGatedPointer
4
7
  } from "./chunk-A36LQPHV.js";
8
+ import {
9
+ ADAPTERS,
10
+ MODE_GATED_RULES,
11
+ inspectFreeVerbRules,
12
+ registeredHooks,
13
+ retractModeGatedRules,
14
+ wireFreeVerbAllowlist
15
+ } from "./chunk-XVYATBKD.js";
5
16
  import {
6
17
  confirmChoice
7
18
  } from "./chunk-P7LABKCW.js";
@@ -9,18 +20,25 @@ import {
9
20
  LockTimeoutError,
10
21
  withFileLock
11
22
  } from "./chunk-MEFB5KHA.js";
23
+ import {
24
+ style
25
+ } from "./chunk-5FGO6TYT.js";
12
26
  import {
13
27
  projectRouterPath,
14
28
  readProjectRouterFile,
15
29
  routerSettings
16
- } from "./chunk-OZ3LWLCI.js";
30
+ } from "./chunk-DATCR7AU.js";
17
31
  import {
18
32
  hasCode
19
33
  } from "./chunk-2I4QTOLB.js";
20
34
  import {
21
35
  isTeamShelfOrigin,
22
36
  loadProjectConfig
23
- } from "./chunk-HII5HOQV.js";
37
+ } from "./chunk-G4AM2SOL.js";
38
+ import {
39
+ parseUsdToAtomic,
40
+ toMoney
41
+ } from "./chunk-6ZSGER3A.js";
24
42
  import {
25
43
  CONFIG_KEYS,
26
44
  EXPERIMENTAL_CONFIG_KEYS,
@@ -42,19 +60,9 @@ import {
42
60
  parseLoopValue,
43
61
  parsePublicFallbackFlag,
44
62
  parseUpdateModeFlag,
45
- parseUsdToAtomic,
46
63
  resolveSettings,
47
- retiredPaymentKeys,
48
- toMoney
49
- } from "./chunk-XICKN3CH.js";
50
- import {
51
- ADAPTERS,
52
- MODE_GATED_RULES,
53
- inspectFreeVerbRules,
54
- registeredHooks,
55
- retractModeGatedRules,
56
- wireFreeVerbAllowlist
57
- } from "./chunk-KGTQRJGS.js";
64
+ retiredPaymentKeys
65
+ } from "./chunk-VIOUZW7Z.js";
58
66
  import {
59
67
  CliError,
60
68
  writeFileAtomic
@@ -67,7 +75,6 @@ import {
67
75
  import { mkdir } from "node:fs/promises";
68
76
  import { homedir } from "node:os";
69
77
  import { dirname as dirname2 } from "node:path";
70
- import { styleText } from "node:util";
71
78
 
72
79
  // src/lib/skill-wiring.ts
73
80
  import { existsSync, statSync } from "node:fs";
@@ -717,10 +724,6 @@ async function persistRouterProject(dir, projectDir, present = true) {
717
724
  return { ...existing, install: { ...existing.install, routerProjects: [...known].sort() } };
718
725
  });
719
726
  }
720
- var ROUTER_DEFAULTS = {
721
- maxAutoSpend: "250000",
722
- sessionBudget: "5000000"
723
- };
724
727
  async function persistRouterDefaults(dir, refresh = false, limits = ROUTER_DEFAULTS) {
725
728
  const result = { set: [], kept: [], removed: [] };
726
729
  if (refresh && retiredPaymentKeys(await loadRawConfig(dir)).length === 0) return result;
@@ -729,11 +732,13 @@ async function persistRouterDefaults(dir, refresh = false, limits = ROUTER_DEFAU
729
732
  result.removed = retiredPaymentKeys(existing);
730
733
  for (const key of result.removed) delete next[key];
731
734
  if (refresh) return next;
732
- for (const [key, value] of Object.entries(limits)) {
733
- if (existing[key] === void 0) {
735
+ for (const key of Object.keys(ROUTER_DEFAULTS)) {
736
+ const value = limits[key];
737
+ if (existing[key] !== void 0) result.kept.push(key);
738
+ else if (value !== void 0) {
734
739
  next[key] = value;
735
740
  result.set.push(key);
736
- } else result.kept.push(key);
741
+ }
737
742
  }
738
743
  return next;
739
744
  });
@@ -891,16 +896,16 @@ async function persist(dir, merge) {
891
896
  function formatLine(key, entry) {
892
897
  const label = key.padEnd(KEY_WIDTH);
893
898
  const where = entry.path !== void 0 && (entry.source === "project" || entry.source === "local") ? ` ${entry.path}` : "";
894
- return ` ${label} ${displayValue(entry)} ${styleText("dim", `(${entry.source}${where})`)}`;
899
+ return ` ${label} ${displayValue(entry)} ${style("dim", `(${entry.source}${where})`)}`;
895
900
  }
896
901
  function describedLine(key, entry, note) {
897
902
  const description = KEY_DESCRIPTIONS[key];
898
903
  let line = formatLine(key, entry);
899
- if (description !== void 0) line += ` ${styleText("dim", `- ${description}`)}`;
904
+ if (description !== void 0) line += ` ${style("dim", `- ${description}`)}`;
900
905
  return withNote(line, note);
901
906
  }
902
907
  function withNote(line, note) {
903
- return note !== void 0 ? `${line} ${styleText("dim", `(${note})`)}` : line;
908
+ return note !== void 0 ? `${line} ${style("dim", `(${note})`)}` : line;
904
909
  }
905
910
  function downgradeNote(key, settings) {
906
911
  if (key !== "publish.mode" || settings.publishMode.downgradedWarning === void 0) {
@@ -932,9 +937,8 @@ export {
932
937
  persistHookArm,
933
938
  persistPublishMode,
934
939
  persistRouterProject,
935
- ROUTER_DEFAULTS,
936
940
  persistRouterDefaults,
937
941
  persistInstallHarness,
938
942
  persistGrantDeclined
939
943
  };
940
- //# sourceMappingURL=chunk-YSW57KUT.js.map
944
+ //# sourceMappingURL=chunk-H2L33M7F.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/commands/config.ts","../src/lib/skill-wiring.ts","../src/lib/skills-source.ts","../src/lib/harness-presence.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport type { CodexGrantResult } from '../lib/harness-permissions';\nimport {\n inspectFreeVerbRules,\n MODE_GATED_RULES,\n retractModeGatedRules,\n wireFreeVerbAllowlist,\n type PermissionsResult,\n} from '../lib/harness-permissions';\nimport { modeGatedPointer } from '../lib/permissions';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from '../lib/production-origin';\nimport {\n CONFIG_KEYS,\n RETIRED_PAYMENT_GUIDANCE,\n retiredPaymentKeys,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n LOOP_CONFIG_KEYS,\n TEAM_CONFIG_KEYS,\n EXPERIMENTAL_CONFIG_KEYS,\n ROUTER_CONFIG_KEYS,\n ROUTER_CONTEXTS,\n loadRawConfig,\n parseLoopValue,\n parsePublicFallbackFlag,\n parseAckServerWarnings,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HookArm,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n UpdateConfigKey,\n LoopConfigKey,\n TeamConfigKey,\n ExperimentalConfigKey,\n RouterConfigKey,\n RouterContext,\n} from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { Harness, HarnessAdapter } from '../adapters/types';\nimport { ADAPTERS } from '../adapters/registry';\nimport { isTeamShelfOrigin, loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { installedHarnessInPlay } from '../lib/harness-presence';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\nimport { ROUTER_DEFAULTS, type RouterLimits } from '../router/spend-question';\nimport {\n projectRouterPath,\n readProjectRouterFile,\n routerSettings,\n type RouterSettings,\n} from '../router/settings';\nimport { style } from '../lib/output';\n\n/** Machine values use Money for spending keys and scalars for other settings. */\ninterface RenderedValue {\n value: Money | string | string[] | boolean | null;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n /** The file a router key came from, when one did. */\n path?: string;\n}\n\n/**\n * Seams for the one `config set` path that touches a file outside the data dir.\n * Tests inject all of them; nothing here is reachable from a flag.\n */\nexport interface ConfigSetDeps {\n /** Harness lifecycle implementations; tests inject adapters at this boundary. */\n adapters?: Readonly<Record<Harness, HarnessAdapter>>;\n /** Home whose `.claude/settings.json` is synced; defaults to os.homedir(). */\n homeDir?: string;\n /** Overrides TTY detection, exactly as install's own seam does. */\n isInteractive?: boolean;\n /** The yes/no for a loosening write; defaults to the clack confirm (default yes). */\n confirmRule?: (label: string) => Promise<boolean>;\n /** Settled harness selection; absent, each registered adapter is detected normally. */\n harnessesInPlay?: readonly Harness[];\n /** The retraction-only pass `review` runs; defaults to the real writer. */\n retractModeGated?: (home: string) => Promise<PermissionsResult>;\n /** PATH probe for harness detection; defaults to probing `env.PATH`. */\n which?: (bin: string) => boolean;\n /** Environment for that probe; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n inspectAllowlist?: typeof inspectFreeVerbRules;\n wireAllowlist?: (home: string, mode: PublishMode) => Promise<PermissionsResult>;\n}\n\n/**\n * The shelf's settings. `config get/set` still accept them and `--json` still\n * carries them, but the human listing shows only what the router CLI uses: it\n * ships no shelf command that reads these.\n */\nconst SHELF_KEYS: ReadonlySet<string> = new Set<string>([\n 'allowlistCreators',\n 'publicShelfUrl',\n 'shelfBypassSecret',\n 'evalCohort',\n ...PUBLISH_CONFIG_KEYS,\n ...HOOKS_CONFIG_KEYS,\n ...LOOP_CONFIG_KEYS,\n ...TEAM_CONFIG_KEYS,\n]);\n\nconst KEY_WIDTH = Math.max(\n ...[...CONFIG_KEYS, ...UPDATE_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS]\n .filter((key) => !SHELF_KEYS.has(key))\n .map((key) => key.length),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'automatic router limit per call',\n sessionBudget: 'automatic router daily limit: 0 blocks automatic spend, none removes the ceiling',\n sendMaxAmount:\n 'hard cap per tenjin wallet send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL the router asks',\n publicShelfUrl:\n 'the public marketplace, consume-only: the second shelf a team-mode search falls through to',\n shelfBypassSecret:\n \"the team shelf's Vercel protection-bypass secret; setting it is what turns team mode on (printed as set/unset)\",\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n bazaarRegistries: 'x402 registries used to verify direct-payment listings',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'publish.ackServerWarnings':\n \"whether a yes covers the MARKETPLACE scan's warn findings: mode=only the ones an earlier render already showed you (full-auto still acks), on=any of them, off=never\",\n 'hooks.prompt': 'answer the prompt you just typed with what the shelves already know',\n 'hooks.web-search': 'ask Tenjin before the agent runs a WebSearch',\n 'hooks.web-fetch': 'ask Tenjin before the agent fetches a page',\n 'hooks.subagent':\n 'ask Tenjin with a subagent work order (the most sensitive payload any hook sees) and hand the answer to the child at its start',\n 'hooks.failure': 'answer a failing command with the fix this machine or a shelf already has',\n 'hooks.publish':\n 'the turn-end ask to publish what this turn settled, spoken to you and to each subagent at its own end',\n 'hooks.primer': 'one-paragraph search-first primer at session start',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n 'loop.human_wait_ms':\n 'ms a hook fire may take when a human is waiting on it (prompt, Stop, SessionStart)',\n 'loop.tool_wait_ms': 'ms a hook fire may take when a tool call is waiting on it',\n 'loop.idle_exit_min': 'minutes without a hook fire before the loop daemon exits',\n 'loop.port':\n \"the loop daemon's loopback port; null derives one from the data dir (set only when doctor reports a foreign listener)\",\n 'team.publicFallback':\n 'on=a team-shelf miss falls through to the public marketplace, off=team-only (public-only lookup stages are dropped)',\n 'router.enabled':\n 'false stops every router hook and the request tool; --project sets it for this repository, --project --local for you alone in it',\n 'router.context':\n 'session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled',\n 'experimental.bazaar':\n \"EXPERIMENTAL. on=the router may also suggest unreviewed sellers from Coinbase's open x402 Bazaar, off=curated services and Tenjin's reviewed list only\",\n};\n\n/**\n * What turning the experimental list on means, said when it is turned on:\n * whose services these are, that the price is theirs, and how to turn it off.\n */\nexport const EXPERIMENTAL_BAZAAR_WARNING =\n \"Experimental: the router may now also suggest sellers from Coinbase's open x402 Bazaar. \" +\n 'They are unreviewed third parties, Tenjin has not checked them, matches can be noisy, ' +\n 'prices can vary with the input, and payments are real, under your spend limits. ' +\n \"To find them, short snippets of your prompts are sent to Coinbase's public Bazaar search. \" +\n \"Tenjin's reviewed list stays on either way. Turn this off with \" +\n '`tenjin config set experimental.bazaar off`.';\n\nfunction isExperimentalKey(key: string): key is ExperimentalConfigKey {\n return (EXPERIMENTAL_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isLoopKey(key: string): key is LoopConfigKey {\n return (LOOP_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isTeamKey(key: string): key is TeamConfigKey {\n return (TEAM_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isRouterKey(key: string): key is RouterConfigKey {\n return (ROUTER_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/** The list/get shape for a router key, with the file that set it. */\nfunction renderRouterSetting(key: RouterConfigKey, settings: RouterSettings): RenderedSetting {\n const { value, source, path } = key === 'router.enabled' ? settings.enabled : settings.context;\n return { value, source, ...(path !== undefined ? { path } : {}) };\n}\n\n/** Router keys resolve against the directory the command runs in, as a hook would. */\nasync function resolveRouterFromContext(ctx: CommandContext): Promise<RouterSettings> {\n return routerSettings({ cwd: process.cwd(), dataDir: ctx.dataDir });\n}\n\nfunction renderLoopSetting(key: LoopConfigKey, settings: EffectiveSettings): RenderedSetting {\n const field = key.slice('loop.'.length) as keyof EffectiveSettings['loop'];\n const { value, source } = settings.loop[field];\n return { value: value === null ? 'null' : String(value), source };\n}\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n const show = (key: string, line: string) => {\n if (!SHELF_KEYS.has(key)) humanLines.push(line);\n };\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of LOOP_CONFIG_KEYS) {\n const entry = renderLoopSetting(key, settings);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of TEAM_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.teamPublicFallback.value,\n source: settings.teamPublicFallback.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n const router = await resolveRouterFromContext(ctx);\n for (const key of ROUTER_CONFIG_KEYS) {\n const entry = renderRouterSetting(key, router);\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n for (const key of EXPERIMENTAL_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.experimentalBazaar.value,\n source: settings.experimentalBazaar.source,\n };\n data[key] = entry;\n show(key, describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isLoopKey(key)) {\n const entry = renderLoopSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isTeamKey(key)) {\n const { teamPublicFallback } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: teamPublicFallback.value,\n source: teamPublicFallback.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isRouterKey(key)) {\n const entry = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isExperimentalKey(key)) {\n const { experimentalBazaar } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: experimentalBazaar.value,\n source: experimentalBazaar.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n {\n key,\n value,\n project,\n local,\n }: { key: string; value: string; project?: boolean; local?: boolean },\n ctx: CommandContext,\n deps: ConfigSetDeps = {},\n): Promise<CommandResult> {\n if (local === true && project !== true) {\n throw new CliError('USAGE', '--local names the personal project file, so it needs --project', {\n fix: `Run \\`tenjin config set --project --local ${key} ${value}\\`.`,\n });\n }\n if (isRouterKey(key)) {\n return setRouterKey(key, value, ctx, project === true ? { local: local === true } : undefined);\n }\n if (project === true) {\n throw new CliError('USAGE', `${key} is not a project key`, {\n fix: `--project applies to ${ROUTER_CONFIG_KEYS.join(' and ')} only; drop it to set ${key} for this machine.`,\n });\n }\n if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n if (isLoopKey(key)) return setLoopKey(key, value, ctx);\n if (isTeamKey(key)) return setTeamKey(key, value, ctx);\n if (isExperimentalKey(key)) return setExperimentalKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n const warning = await halfWiredTeamShelf(configKey, ctx.dataDir);\n return {\n data: { key: configKey, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(configKey, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * The half-wired team shelf, said out loud at the moment it is created.\n *\n * Team mode takes TWO settings — a private deployment in `baseUrl` and its\n * bypass secret — and the setup is two independent commands, so a machine can\n * easily end up with the secret and no shelf (run in the other order, or the\n * secret line alone on a second machine). The CLI fails that state safe to\n * public mode, which means an operator who thinks they are on the team shelf\n * would otherwise get no signal at all: publishes would go to the marketplace\n * under the public gates. Warn, do not refuse — the pair is legitimately\n * half-set between two commands, and refusing would make the documented order\n * the only order.\n *\n * THREE KEYS, not two. `isTeamShelfOrigin` also returns false when `baseUrl`\n * matches `publicShelfUrl`, so pointing `publicShelfUrl` at the team deployment\n * drops the machine out of team mode just as surely as unsetting the secret\n * would. It fails safe and doctor catches it later; this is the warning at the\n * moment it happens, on the third key of the same triple.\n */\nasync function halfWiredTeamShelf(\n configKey: ScalarConfigKey,\n dataDir: string,\n): Promise<string | undefined> {\n if (\n configKey !== 'shelfBypassSecret' &&\n configKey !== 'baseUrl' &&\n configKey !== 'publicShelfUrl'\n ) {\n return undefined;\n }\n const config = await loadRawConfig(dataDir).catch(() => undefined);\n if (config === undefined) return undefined;\n const s = resolveSettings({ config, flags: {}, env: {} });\n if (s.shelfBypassSecret.value.length === 0) return undefined;\n const baseUrl = s.baseUrl.value;\n if (isTeamShelfOrigin(new URL(baseUrl).origin, s.publicShelfUrl.value)) return undefined;\n // WHICH KEY BROKE THE PAIR decides which fix to name. A baseUrl that now\n // matches publicShelfUrl is not \"the marketplace\" in any recognizable sense —\n // it is the operator's own two keys pointed at one place — and telling them to\n // re-point baseUrl would be advice for the other half of the same collision.\n const isProduction = isSameDeployment(new URL(baseUrl).origin, PRODUCTION_ORIGIN);\n const cause = isProduction\n ? `baseUrl is the public marketplace (${baseUrl})`\n : `baseUrl and publicShelfUrl are the same shelf (${baseUrl})`;\n const fix = isProduction\n ? 'Point baseUrl at the team deployment to finish team mode: `tenjin config set baseUrl <team shelf url>`.'\n : `A team shelf must differ from the shelf it falls through to: \\`tenjin config set publicShelfUrl ${PRODUCTION_ORIGIN}\\`.`;\n return (\n `Warning: shelfBypassSecret is set, but ${cause}, ` +\n 'so this machine stays in PUBLIC mode — publishes go to the marketplace with the scan’s ' +\n 'warn tier and the confirm cascade on. ' +\n fix\n );\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice|publish.ackServerWarnings`. mode\n * and ackServerWarnings validate to their enums; defaultPrice parses decimal USD\n * at the edge into atomic (matching the spend keys). The subkey is merged into\n * the nested publish block, so a sibling subkey (or an unknown one a newer CLI\n * wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : key === 'publish.ackServerWarnings'\n ? { value: parseAckServerWarnings(value, key), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey =\n key === 'publish.mode'\n ? 'mode'\n : key === 'publish.ackServerWarnings'\n ? 'ackServerWarnings'\n : 'defaultPrice';\n const stored =\n key === 'publish.defaultPrice' ? (entry.value as Money).atomic : (entry.value as string);\n const persistEntry = async (): Promise<void> =>\n persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n const humanLines = [formatLine(key, entry)];\n if (key !== 'publish.mode') {\n await persistEntry();\n return { data: { key, ...entry }, humanLines };\n }\n\n // The mode decides whether a publish asks; the harness rule decides whether the\n // harness asks ANYWAY. Settling one and leaving the other to the next `tenjin\n // install` is the seam that made publish.mode look broken (tenjin-agent #161),\n // so the two move together from here too.\n // Synchronize before committing the mode. A grant writer may refuse after\n // consent (permissions, concurrent edits, an unwritable parent); persisting\n // first made the command exit successfully with an unattended mode that its\n // harness could not carry. Grant-first is also the least-authority failure\n // order: if a later config write fails, the CLI still resolves the old mode.\n const allowlist = await syncPublishRule(entry.value as PublishMode, ctx, deps);\n const failure = grantSyncFailure(allowlist);\n if (failure !== undefined) {\n throw new CliError(\n 'REFUSED',\n `publish.mode was not changed because the ${failure.harness} grant could not be updated: ${failure.reason}`,\n {\n fix:\n failure.fix ??\n `Fix the permissions for ${failure.path}, then re-run \\`tenjin config set publish.mode ${entry.value as string}\\`.`,\n details: { key, value: entry.value, allowlist },\n },\n );\n }\n await persistEntry();\n return {\n data: { key, ...entry, allowlist },\n humanLines: [...humanLines, ...allowlistLines(allowlist)],\n };\n}\n\n/**\n * What `config set publish.mode` did about the harness rule the mode carries.\n * `skipped` names why nothing was written; `pointer` is the line to show when it\n * is the operator's move.\n */\ninterface AllowlistSync {\n byHarness: Partial<Record<Harness, PermissionsResult | CodexGrantResult>>;\n skipped?: 'not-claude' | 'no-tty' | 'declined' | 'unwritable';\n pointer?: string;\n}\n\n/** A writer refusal is an error, not informational output: the mode and every\n * harness grant are one operator decision and may not report success apart. */\nfunction grantSyncFailure(\n sync: AllowlistSync,\n): { harness: Harness; path: string; reason: string; fix?: string } | undefined {\n for (const [harness, result] of Object.entries(sync.byHarness) as [\n Harness,\n PermissionsResult | CodexGrantResult,\n ][]) {\n if ('error' in result && result.error !== undefined) {\n return { harness, path: result.path, reason: result.error };\n }\n if ('warning' in result && result.warning !== undefined) {\n return {\n harness,\n path: result.path ?? '(unknown path)',\n reason: result.warning,\n ...(result.fix !== undefined ? { fix: result.fix } : {}),\n };\n }\n }\n return undefined;\n}\n\n/** Names what the write actually carries: on a machine that never ran `install`,\n * the free tier is pending too, and a question naming two lines while eleven\n * land is asking about something else. */\nfunction publishRuleQuestion(\n mode: PublishMode,\n pending: readonly string[],\n harnesses: readonly Harness[],\n): string {\n const gated = new Set<string>(MODE_GATED_RULES);\n const others = pending.filter((rule) => !gated.has(rule)).length;\n const also =\n others > 0 ? ` Also adds the ${others} command-grant rule(s) \\`tenjin install\\` writes.` : '';\n const targets = harnesses\n .map((harness) =>\n harness === 'claude' ? 'Claude Code' : harness === 'codex' ? 'Codex' : harness,\n )\n .join(' and ');\n return (\n `publish.mode ${mode} is unattended only if ${targets} carries the matching grant for ` +\n `${MODE_GATED_RULES.join(' and ')}. Update the ${targets} grant now?${also}`\n );\n}\n\n/**\n * Keep the harness allowlist in step with the mode just written.\n *\n * ASYMMETRIC ON PURPOSE, and the asymmetry is the consent rule:\n * - Loosening (auto/full-auto) ADDS a grant, so it needs a human in the loop.\n * No TTY, `--json`, or a declined prompt all leave the file alone and return\n * the pointer instead; nothing here writes on silence.\n * - Tightening (review) only ever REMOVES a rule this CLI wrote under a setting\n * the operator has just changed, so it runs unconditionally — the same reason\n * install sweeps a retired rule without asking. Leaving it behind would keep\n * publishing pre-cleared after the operator said \"ask me first\", which is the\n * failure that matters.\n */\nasync function syncPublishRule(\n mode: PublishMode,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<AllowlistSync> {\n const home = deps.homeDir ?? homedir();\n const nothing: AllowlistSync = { byHarness: {} };\n\n const write = async (): Promise<AllowlistSync> => {\n const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);\n if (result.skipped !== undefined) {\n return {\n byHarness: { claude: result },\n skipped: 'unwritable',\n ...(result.fix !== undefined ? { pointer: result.fix } : {}),\n };\n }\n return { byHarness: { claude: result } };\n };\n\n const adapters = deps.adapters ?? ADAPTERS;\n const env = deps.env ?? process.env;\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n const requested = await loadRawConfig(ctx.dataDir)\n .then((config) => config.install?.harness ?? [])\n .catch(() => [] as Harness[]);\n const inPlay =\n deps.harnessesInPlay ??\n (\n await Promise.all(\n Object.values(adapters).map(async (adapter) => ({\n adapter,\n selected: await installedHarnessInPlay(adapter, home, ctx.dataDir, {\n env,\n which,\n requested,\n }),\n })),\n )\n )\n .filter((entry) => entry.selected)\n .map((entry) => entry.adapter.id);\n const selectedAdapters = inPlay.map((harness) => adapters[harness]);\n const isClaude = inPlay.includes('claude');\n\n const withOtherGrants = async (sync: AllowlistSync): Promise<AllowlistSync> => {\n const byHarness = { ...sync.byHarness };\n for (const adapter of selectedAdapters) {\n if (adapter.id === 'claude' || adapter.registrar.grant === undefined) continue;\n const result = await adapter.registrar.grant.write(home, mode, env);\n byHarness[adapter.id] = result;\n }\n return { ...sync, byHarness };\n };\n\n // Only Claude Code has a settings file of this shape; guessing at another\n // harness's config is the uninvited write lib/harness-permissions.ts avoids.\n // DETECTED, never assumed: a codex-only machine has a ~/.claude/settings.json\n // that nothing reads, so prompting about it is noise and writing to it is an\n // uninvited edit — and the retraction would sweep a file we never owned.\n if (selectedAdapters.every((adapter) => adapter.registrar.grant === undefined)) {\n // No settings file of ours to be missing anything, so the pointer would be\n // advice about a machine this is not.\n return { ...nothing, skipped: 'not-claude' };\n }\n\n const probe = isClaude\n ? await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode)\n : { pending: [] as string[] };\n const gated = new Set<string>(MODE_GATED_RULES);\n const missing = (probe.pending ?? []).filter((r) => gated.has(r));\n // Only ever names rules this machine does not have. A pointer built from the\n // mode alone told a fully-wired operator to go add what they already had.\n const pointer = modeGatedPointer(mode, missing) ?? undefined;\n\n // Tightening runs with no question and with no precondition, through a pass\n // that can only ever REMOVE. Riding the additive writer made this decline\n // whenever the free tier was not byte-exact — silently, and in the tightening\n // direction, on the undo the operator just typed.\n if (mode === 'review') {\n const retracted = isClaude\n ? await (deps.retractModeGated ?? retractModeGatedRules)(home)\n : undefined;\n if (retracted?.skipped !== undefined) {\n return {\n ...nothing,\n skipped: 'unwritable',\n ...(retracted.fix !== undefined ? { pointer: retracted.fix } : {}),\n };\n }\n return await withOtherGrants({\n byHarness: retracted === undefined ? {} : { claude: retracted },\n });\n }\n\n // SATISFIED BEFORE TTY, and the order is the point: a fully-wired machine has\n // nothing to ask about and nothing to write, so a `--json` or headless run\n // there is a no-op rather than a `no-tty` skip carrying a pointer at rules it\n // already has.\n if (probe.satisfied !== undefined && selectedAdapters.length === 1 && isClaude) return nothing;\n\n const canPrompt =\n ctx.flags.json === true ? false : (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n if (!canPrompt) {\n return { ...nothing, skipped: 'no-tty', ...(pointer ? { pointer } : {}) };\n }\n\n const confirm = deps.confirmRule ?? ((label: string) => confirmChoice(label, true));\n const grantable = selectedAdapters\n .filter((adapter) => adapter.registrar.grant !== undefined)\n .map((adapter) => adapter.id);\n if (!(await confirm(publishRuleQuestion(mode, probe.pending ?? [], grantable)))) {\n return { ...nothing, skipped: 'declined', ...(pointer ? { pointer } : {}) };\n }\n return await withOtherGrants(isClaude ? await write() : nothing);\n}\n\n/** The human rendering of {@link syncPublishRule}, or nothing when it was a no-op. */\nfunction allowlistLines(sync: AllowlistSync): string[] {\n const lines: string[] = [];\n const claude = sync.byHarness.claude as PermissionsResult | undefined;\n if ((claude?.added.length ?? 0) > 0) {\n lines.push(`Added ${claude?.added.length ?? 0} harness rule(s) to your allowlist.`);\n }\n if ((claude?.removed.length ?? 0) > 0) {\n lines.push(`Removed ${claude?.removed.join(', ')} from your allowlist.`);\n }\n const grant = sync.byHarness.codex as CodexGrantResult | undefined;\n if (grant !== undefined && grant.error === undefined && grant.wrote) {\n lines.push(\n `Codex now allows ${grant.granted.length} tenjin command prefix(es) in ${grant.path}.`,\n );\n }\n if (grant?.error !== undefined) {\n lines.push(`Codex's grant at ${grant.path} could not be updated (${grant.error}).`);\n }\n if (sync.pointer !== undefined) lines.push(sync.pointer);\n return lines;\n}\n\n/**\n * `config set hooks.<arm>`. Merged into the nested hooks block through the same\n * locked read-modify-write every other set uses, so a subkey a newer CLI wrote\n * survives. The daemon re-stats this file per fire, so every value takes effect\n * on the next prompt with no re-install and no process to restart.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const arm = key.slice('hooks.'.length) as HookArm;\n const parsed = parseBoolean(value);\n await persistHookArm(ctx.dataDir, arm, parsed);\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n // NO STALENESS WARNING, and there is nothing left to warn about: every hooks\n // key is read out of `config.json` by the daemon on each fire, so a value set\n // here takes effect on the next prompt with nothing to re-install.\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set loop.*` and `config set team.publicFallback`. The daemon stats\n * `config.json` per fire and reloads on an mtime change, so a set takes effect\n * on the next hook fire with no restart (02-redesign.md §4a).\n */\nasync function setLoopKey(\n key: LoopConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseLoopValue(key, value);\n const field = key.slice('loop.'.length);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n loop: { ...existing.loop, [field]: parsed },\n }));\n const entry: RenderedSetting = {\n value: parsed === null ? 'null' : String(parsed),\n source: 'file',\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nasync function setTeamKey(\n key: TeamConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n team: { ...existing.team, publicFallback: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/** `config set experimental.bazaar on|off`; turning it on says what it means. */\nasync function setExperimentalKey(\n key: ExperimentalConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n experimental: { ...existing.experimental, bazaar: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n const warning = parsed === 'on' ? EXPERIMENTAL_BAZAAR_WARNING : undefined;\n return {\n data: { key, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(key, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * `config set [--project [--local]] router.enabled|router.context`. Without\n * `--project` the key goes into the global config through the same locked merge\n * every set uses. With it, into the project file {@link projectRouterPath}\n * names from here, merged so a sibling key survives. The line after the write\n * is what a hook here would now resolve, which differs from the value written\n * when an outer layer is tighter.\n */\nasync function setRouterKey(\n key: RouterConfigKey,\n value: string,\n ctx: CommandContext,\n project: { local: boolean } | undefined,\n): Promise<CommandResult> {\n const field = key === 'router.enabled' ? 'enabled' : 'context';\n const parsed = field === 'enabled' ? parseBoolean(value) : parseRouterContext(value);\n let written: RenderedSetting;\n if (project === undefined) {\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n router: { ...existing.router, [field]: parsed },\n }));\n written = { value: parsed, source: 'file', path: configPath(ctx.dataDir) };\n } else {\n const path = await projectRouterPath({ cwd: process.cwd(), local: project.local });\n await persistProjectRouter(path, field, parsed);\n written = { value: parsed, source: project.local ? 'local' : 'project', path };\n }\n const effective = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n const humanLines = [formatLine(key, written)];\n if (effective.value !== written.value) {\n humanLines.push(\n `Still ${String(effective.value)} here: ${effective.path ?? 'the default'} is tighter, and a nearer file can only tighten an outer one.`,\n );\n }\n if (project?.local === true) {\n humanLines.push('Keep .tenjin/config.local.json out of git: add it to .gitignore.');\n }\n return { data: { key, ...written, effective }, humanLines };\n}\n\nfunction parseRouterContext(value: string): RouterContext {\n const found = ROUTER_CONTEXTS.find((context) => context === value);\n if (found !== undefined) return found;\n throw new CliError('USAGE', `Invalid router.context: ${JSON.stringify(value)}`, {\n fix: 'Use \"session\" or \"turn\".',\n });\n}\n\n/**\n * Merge one router key into a project file. It holds the router block and\n * nothing else this CLI reads, so it is written 0644 like any committed file;\n * an existing file that is not a JSON object is refused rather than replaced.\n * The read, merge and write run under the same cross-process lock the global\n * writer takes, so two concurrent sets both land.\n */\nasync function persistProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true, mode: 0o755 });\n const lockPath = `${path}.lock`;\n try {\n await withFileLock(lockPath, () => mergeProjectRouter(path, field, value));\n } catch (err) {\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nasync function mergeProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n // Through the one parser: a file that is not an object, or whose block is\n // invalid, is refused rather than replaced. A router subkey this build does\n // not know rides along untouched, as in the global file; it is never read.\n const existing = await readProjectRouterFile(path);\n const block = existing?.json.router;\n const next = {\n ...(existing?.json ?? {}),\n router: { ...(block !== undefined ? (block as object) : {}), [field]: value },\n };\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o755,\n });\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * The one writer of a `hooks.<arm>` boolean, through the same locked merge-write\n * every `config set` uses, so a sibling arm or an unknown block a newer CLI\n * wrote survives. `config set hooks.<arm>` and `tenjin hooks enable|disable`\n * are two spellings of this call and never two writers.\n */\nexport async function persistHookArm(dir: string, arm: HookArm, value: boolean): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [arm]: value },\n }));\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Remember, or forget, a project directory this machine wired with\n * `install --project`. `tenjin update` spawns its refresh from the HOME\n * directory, so a project install is unfindable by looking around; this list is\n * how a later refresh reaches it. Absolute paths, de-duplicated, and pruned\n * when a project is uninstalled or its settings file stops carrying our\n * entries.\n */\nexport async function persistRouterProject(\n dir: string,\n projectDir: string,\n present = true,\n): Promise<void> {\n await persist(dir, (existing) => {\n const known = new Set(existing.install?.routerProjects ?? []);\n if (present) known.add(projectDir);\n else known.delete(projectDir);\n return { ...existing, install: { ...existing.install, routerProjects: [...known].sort() } };\n });\n}\n\n/** Absent-only automatic router defaults; defined beside the spend question that shows them. */\nexport { ROUTER_DEFAULTS, type RouterLimits };\n\nexport interface RouterDefaultsResult {\n /** Keys this run wrote, because the file did not name them. */\n set: string[];\n /** Keys the operator had already written, left exactly as they are. */\n kept: string[];\n removed: string[];\n}\n\n/** Remove/report retired keys in the same locked write. Refresh preserves absent\n * current settings; a fresh install fills only missing automatic limits, with the\n * values the person at the terminal approved or chose. A key `limits` leaves out\n * stays absent: that is how an install with nobody to approve keeps\n * `maxAutoSpend` at the bare CLI's zero. */\nexport async function persistRouterDefaults(\n dir: string,\n refresh = false,\n limits: Partial<RouterLimits> = ROUTER_DEFAULTS,\n): Promise<RouterDefaultsResult> {\n const result: RouterDefaultsResult = { set: [], kept: [], removed: [] };\n if (refresh && retiredPaymentKeys(await loadRawConfig(dir)).length === 0) return result;\n await persist(dir, (existing) => {\n const next: PartialConfig = { ...existing };\n result.removed = retiredPaymentKeys(existing);\n for (const key of result.removed) delete next[key];\n if (refresh) return next;\n for (const key of Object.keys(ROUTER_DEFAULTS) as (keyof RouterLimits)[]) {\n const value = limits[key];\n if (existing[key] !== undefined) result.kept.push(key);\n else if (value !== undefined) {\n next[key] = value;\n result.set.push(key);\n }\n }\n return next;\n });\n return result;\n}\n\n/**\n * Record the settled harness selection through the same locked merge-write. It\n * replaces the previous record rather than unioning with it: the last operator\n * answer is the current intent. Doctor still re-probes detection independently;\n * the record keeps a deliberately selected but currently undetected harness in play.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly Harness[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\n/**\n * Record the EXACT free-verb rules `install` declined, through the same locked\n * read-modify-write every `config set` uses. Set to whatever was pending at the\n * moment of `--no-grant`; cleared back to `[]` the moment an install\n * actually wires the allowlist, or finds it already fully satisfied. `--refresh` subtracts this list from what it would otherwise\n * report as pending, so a settled no stays settled per rule — without also\n * silencing a genuinely NEW rule a later version adds (tenjin-agent#234).\n */\nexport async function persistGrantDeclined(dir: string, declined: string[]): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, grantDeclined: declined },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if (key === 'bazaarPay' || key === 'confirm') {\n throw new CliError('USAGE', `Retired config key: ${key}`, { fix: RETIRED_PAYMENT_GUIDANCE });\n }\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n if (key === 'publish.ackServerWarnings') {\n return {\n value: settings.publishAckServerWarnings.value,\n source: settings.publishAckServerWarnings.source,\n };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: the arm's boolean and where it came from. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const { value, source } = settings.hooks[key.slice('hooks.'.length) as HookArm];\n return { value, source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n // REDACTED IN THE MACHINE ENVELOPE TOO, not just in the human line. `config\n // --json` is what an agent reads and what a bug report pastes, and the whole\n // point of a door key is that it opens the door for whoever holds it. What a\n // caller actually needs from this key is whether team mode is on, and\n // set/unset says exactly that. The value is still readable, by the operator,\n // in ~/.tenjin/config.json.\n if (key === 'shelfBypassSecret') {\n return { value: typeof stored === 'string' && stored.length > 0 ? 'set' : 'unset' };\n }\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'sessionBudget' && stored === 'none') return { value: null };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'sessionBudget':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'maxAutoSpend':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'publicShelfUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'shelfBypassSecret':\n // A free string: it is whatever Vercel generated. Empty clears it, which\n // is how team mode is turned back off.\n return value.trim();\n case 'evalCohort':\n return parseBoolean(value);\n case 'bazaarRegistries':\n return parseRegistryList(value);\n }\n}\n\n/** \"\" clears to []; comma-split, each entry an absolute http(s) URL. */\nfunction parseRegistryList(value: string): string[] {\n return value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n .map((entry) => parseHttpUrl(entry));\n}\n\n// Boolean settings accept both on/off and true/false.\nfunction parseBoolean(value: string): boolean {\n if (value === 'true' || value === 'on') return true;\n if (value === 'false' || value === 'off') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"on\" or \"off\" (or \"true\"/\"false\").',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n // 0600, matching lib/config.ts's `writeConfig`: this file holds\n // `shelfBypassSecret`, and this is the writer `config set` uses to put it\n // there. See that function for why dirMode alone is not enough.\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n // A router key from a project names its file: which of several is in force is the question.\n const where =\n entry.path !== undefined && (entry.source === 'project' || entry.source === 'local')\n ? ` ${entry.path}`\n : '';\n return ` ${label} ${displayValue(entry)} ${style('dim', `(${entry.source}${where})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${style('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${style('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (value === null) return 'none (no daily limit)';\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n return value; // 'always', baseUrl, rpcUrl\n}\n","import { existsSync, statSync } from 'node:fs';\nimport { constants, open } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { delimiter, join } from 'node:path';\nimport { SKILL_NAMES } from './skills-source';\nimport type { SkillName } from './skills-source';\nimport type { Harness } from '../adapters/types';\n\n/**\n * CLI_SKILL_NAMES are the thin adapter skills (roadmap C1), both required for the\n * CLI to be usable from a harness; HOSTED_SKILL_NAME is the zero-install\n * curriculum mirror (roadmap G4), typed as their complement so a rename in\n * skills-source.ts is a compile error here rather than a silently-always-false\n * `cliSkillsWired`.\n */\nexport const CLI_SKILL_NAMES = [\n 'tenjin-search',\n 'tenjin-publish',\n] as const satisfies readonly SkillName[];\nexport type CliSkillName = (typeof CLI_SKILL_NAMES)[number];\nexport type HostedSkillName = Exclude<SkillName, CliSkillName>;\nexport const HOSTED_SKILL_NAME: HostedSkillName = 'tenjin';\n\nexport type NotInvocableReason = 'disabled' | 'unreadable';\n\nexport interface SkillWiring {\n name: string;\n present: boolean;\n /** Undefined when absent. False means on disk yet never surfaced to the model. */\n modelInvocable?: boolean;\n reason?: NotInvocableReason;\n}\n\n/**\n * One directory's verdict. `shadowed` and `partial` are actionable; `hosted-only`\n * is a working zero-install machine, not a defect; `empty` is not a Tenjin dir.\n */\nexport type DirState = 'empty' | 'hosted-only' | 'partial' | 'shadowed' | 'wired';\n\nexport interface HarnessWiring {\n dir: string;\n exists: boolean;\n skills: SkillWiring[];\n state: DirState;\n}\n\n/** Every skills directory a harness on this machine reads. */\nexport function skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\n/** The skills directory a real harness reads. */\nexport function harnessTargetDir(home: string, harness: Harness): string {\n if (harness === 'claude') return join(home, '.claude', 'skills');\n return join(home, '.agents', 'skills');\n}\n\n/**\n * The `--harness` value that targets `dir`. A Claude-only machine never targets\n * ~/.agents/skills by default, so a bare `tenjin install` cannot clear a problem\n * found there.\n */\nexport function harnessFlagFor(home: string, dir: string): Harness {\n if (dir === join(home, '.claude', 'skills')) return 'claude';\n return 'codex';\n}\n\n/**\n * Why we think `harness` is on this machine: its home dir (~/.claude, ~/.codex) and\n * its binary on PATH. Single-sourced so `install` picks its targets and `doctor`\n * decides which directories MUST be wired from the same two probes — a directory no\n * harness here reads is a leftover, not a defect.\n */\nexport function harnessDetectedBy(\n home: string,\n harness: Harness,\n which: (bin: string) => boolean,\n): string[] {\n const reasons: string[] = [];\n if (existsSync(join(home, `.${harness}`))) reasons.push('home-dir');\n if (which(harness)) reasons.push('binary');\n return reasons;\n}\n\nexport interface HarnessPresence {\n claude: boolean;\n codex: boolean;\n}\n\nexport function detectHarnesses(home: string, which: (bin: string) => boolean): HarnessPresence {\n return {\n claude: harnessDetectedBy(home, 'claude', which).length > 0,\n codex: harnessDetectedBy(home, 'codex', which).length > 0,\n };\n}\n\n/**\n * Does a harness ON THIS MACHINE read `dir`? Claude Code reads ~/.claude/skills and\n * Codex reads ~/.agents/skills, so a wired .agents does NOT make Claude Code wired:\n * the question has to be asked per directory.\n */\nexport function harnessReads(home: string, dir: string, present: HarnessPresence): boolean {\n if (harnessFlagFor(home, dir) === 'claude') return present.claude;\n return present.codex;\n}\n\n/**\n * Did the last settled install selection name `dir` on purpose? Detection is a\n * current machine fact; `requested` is the operator's answer and outranks it.\n */\nexport function harnessRequested(\n home: string,\n dir: string,\n requested: readonly Harness[],\n): boolean {\n return requested.some((h) => harnessTargetDir(home, h) === dir);\n}\n\n/**\n * Is `dir` this machine's business at all? Once the operator has settled an install\n * selection, that answer is authoritative. Detection is only the fallback for homes\n * that predate the selection record. `harnessPresent` remains a separate detection\n * fact for reporting.\n */\nexport function harnessInPlay(\n home: string,\n dir: string,\n present: HarnessPresence,\n requested: readonly Harness[],\n): boolean {\n if (requested.length > 0) return harnessRequested(home, dir, requested);\n return harnessReads(home, dir, present);\n}\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nexport function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nexport async function readHarnessWiring(dir: string): Promise<HarnessWiring> {\n const exists = existsSync(dir);\n const skills: SkillWiring[] = [];\n for (const name of SKILL_NAMES) skills.push(await readSkillWiring(dir, name));\n return { dir, exists, skills, state: classify(skills) };\n}\n\nexport async function readAllWiring(home: string): Promise<HarnessWiring[]> {\n const out: HarnessWiring[] = [];\n for (const dir of skillsDirsFor(home)) out.push(await readHarnessWiring(dir));\n return out;\n}\n\nfunction classify(skills: SkillWiring[]): DirState {\n const cli = CLI_SKILL_NAMES.map((n) => skills.find((s) => s.name === n)).filter(\n (s) => s?.present === true,\n );\n if (cli.length === 0) return skills.some((s) => s.present) ? 'hosted-only' : 'empty';\n if (cli.some((s) => s?.modelInvocable === false)) return 'shadowed';\n return cli.length === CLI_SKILL_NAMES.length ? 'wired' : 'partial';\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\nexport type SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin doctor` and `tenjin install` past\n * SIGTERM. Opening non-blocking returns immediately whatever the node type is,\n * `fstat` on that descriptor says what it actually is, and only a regular file is\n * read. Checking the pathname and then reading the pathname would let the two\n * answer about different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nexport async function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function readSkillWiring(dir: string, name: string): Promise<SkillWiring> {\n const read = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (read.kind === 'absent') return { name, present: false };\n // A pipe or a device is there, but it is not a skill and must never be read as\n // one; `unreadable` is the state that already describes \"present, unusable\".\n if (read.kind !== 'ok')\n return { name, present: true, modelInvocable: false, reason: 'unreadable' };\n const text = read.bytes.toString('utf8');\n if (isModelInvocationDisabled(text)) {\n return { name, present: true, modelInvocable: false, reason: 'disabled' };\n }\n return { name, present: true, modelInvocable: true };\n}\n\n/** YAML 1.1 truthy spellings a harness frontmatter parser may accept. */\nconst YAML_TRUE = /^(?:true|yes|on)$/i;\n\n/**\n * Deliberately not a general YAML parse: only the leading `---` block is read,\n * because this repo's own skills discuss the key in prose and a whole-file match\n * would call a working skill disabled.\n */\nexport function isModelInvocationDisabled(skillMd: string): boolean {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return false;\n return frontmatter.some((line) => {\n const m = /^disable-model-invocation:\\s*(.+?)\\s*$/.exec(line.trim());\n if (m === null) return false;\n // Strip an inline `# comment` and optional quotes before testing truthiness.\n const value = (m[1] ?? '').replace(/\\s+#.*$/, '').replace(/^[\"']|[\"']$/g, '');\n return YAML_TRUE.test(value);\n });\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours: the\n * unattended self-heal refuses to overwrite a same-named third-party skill.\n */\nexport function skillFrontmatterName(skillMd: string): string | null {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return null;\n for (const line of frontmatter) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\nfunction extractFrontmatter(text: string): string[] | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n if (end === -1) return null;\n return lines.slice(open + 1, end);\n}\n\nexport function cliSkillsWired(wiring: HarnessWiring): boolean {\n return wiring.state === 'wired';\n}\n\nexport function missingCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter(\n (name) => wiring.skills.find((x) => x.name === name)?.present !== true,\n );\n}\n\nexport function shadowedCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter((name) => {\n const s = wiring.skills.find((x) => x.name === name);\n return s?.present === true && s.modelInvocable === false;\n });\n}\n\nexport function anyTenjinSkill(wiring: HarnessWiring): boolean {\n return wiring.state !== 'empty';\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\nexport const RETIRED_SKILL_NAMES = ['tenjin-pay'] as const;\n\n/** Retired names remain known to uninstall, but are never packaged or healed. */\nexport const PACKAGED_SKILL_NAMES = [...SKILL_NAMES] as const;\n\n/**\n * Every file a packaged skill ships, per skill, as a path relative to the skill\n * directory.\n *\n * DECLARED rather than discovered, because `uninstall` needs it on a machine\n * where the packaged source may be gone or unreadable, and \"remove exactly the\n * files this package wrote\" is not a question it can answer by listing the\n * operator's directory — everything else in there is theirs. `install` still\n * copies the real tree; a test pins this list against it, so a new reference\n * file that nobody declares fails the build rather than becoming litter no\n * uninstall can reclaim.\n *\n */\nexport const SHIPPED_SKILL_FILES: Record<\n SkillName | (typeof RETIRED_SKILL_NAMES)[number],\n readonly string[]\n> = {\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n tenjin: ['SKILL.md'],\n 'tenjin-pay': ['SKILL.md'],\n};\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\n details: { startDir },\n });\n}\n","import type { Harness, HarnessAdapter } from '../adapters/types';\nimport { registeredHooks } from './harness-hooks';\nimport { detectHarnesses, harnessInPlay, harnessTargetDir, onPath } from './skill-wiring';\n\n/**\n * Is one adapter part of this machine's settled installation?\n *\n * An explicit install selection outranks current detection; homes predating\n * that record fall back to the harness directory/PATH probes. Registered hook\n * entries are final evidence, so config and doctor agree even if the binary or\n * home-directory marker later moves.\n */\nexport async function installedHarnessInPlay(\n adapter: HarnessAdapter,\n home: string,\n dataDir: string,\n options: {\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n requested?: readonly Harness[];\n } = {},\n): Promise<boolean> {\n const env = options.env ?? process.env;\n const which = options.which ?? ((bin: string) => onPath(bin, env));\n if (\n harnessInPlay(\n home,\n harnessTargetDir(home, adapter.id),\n detectHarnesses(home, which),\n options.requested ?? [],\n )\n ) {\n return true;\n }\n return (await registeredHooks(adapter, home, dataDir, env)).entries > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,WAAAA,gBAAe;;;ACFxB,SAAS,YAAY,gBAAgB;AACrC,SAAS,WAAW,YAAY;AAGhC,SAAS,WAAW,QAAAC,aAAY;;;ACHhC,SAAS,SAAS,YAAY;AASvB,IAAM,cAAc,CAAC,iBAAiB,kBAAkB,QAAQ;AAGhE,IAAM,sBAAsB,CAAC,YAAY;AAGzC,IAAM,uBAAuB,CAAC,GAAG,WAAW;AAe5C,IAAM,sBAGT;AAAA,EACF,iBAAiB,CAAC,YAAY,2BAA2B;AAAA,EACzD,kBAAkB,CAAC,YAAY,wBAAwB;AAAA,EACvD,QAAQ,CAAC,UAAU;AAAA,EACnB,cAAc,CAAC,UAA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AAc,KAAa,OAAwB,MAAuB;AACjF,QAAM,cAAc,iBAAiB,GAAG;AACxC,MAAI,OAAO,WAAW,KAAK,KAAK;AAChC,MAAI,gBAAgB,OAAW,SAAQ,KAAK,MAAM,OAAO,KAAK,WAAW,EAAE,CAAC;AAC5E,SAAO,SAAS,MAAM,IAAI;AAC5B;AAGA,SAAS,SAAS,MAAc,MAAuB;AACrD,SAAO,SAAS,SAAY,GAAG,IAAI,KAAK,MAAM,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK;AACxE;AAOA,SAAS,cAAc,KAAuB,UAAiD;AAC7F,MAAI,QAAQ,kBAAkB,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,SAAO;AACT;","names":["dirname","join","join","open","settings","entry","dirname"]}
@@ -3,7 +3,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
3
3
  // package.json
4
4
  var package_default = {
5
5
  name: "tenjin-cli",
6
- version: "0.1.0-alpha.25",
6
+ version: "0.1.0-alpha.27",
7
7
  type: "module",
8
8
  description: "The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.",
9
9
  repository: {
@@ -32,7 +32,7 @@ var package_default = {
32
32
  tenjin: "dist/index.js"
33
33
  },
34
34
  engines: {
35
- node: ">=24"
35
+ node: ">=22.0.0"
36
36
  },
37
37
  files: [
38
38
  "dist",
@@ -59,7 +59,7 @@ var package_default = {
59
59
  "@clack/prompts": "^1.7.0",
60
60
  "@eslint/js": "^10",
61
61
  "@modelcontextprotocol/sdk": "1.31.0",
62
- "@types/node": "^25",
62
+ "@types/node": "^22.20.5",
63
63
  "@x402/core": "2.28.0",
64
64
  "@x402/evm": "2.28.0",
65
65
  "@x402/extensions": "2.28.0",
@@ -69,6 +69,7 @@ var package_default = {
69
69
  commander: "^14.0.1",
70
70
  eslint: "^10",
71
71
  "eslint-config-prettier": "^10",
72
+ "lean-qr": "^2.7.4",
72
73
  ox: "0.14.30",
73
74
  prettier: "^3",
74
75
  tsup: "^8.5.0",
@@ -83,4 +84,4 @@ var package_default = {
83
84
  export {
84
85
  package_default
85
86
  };
86
- //# sourceMappingURL=chunk-ODH7UXIS.js.map
87
+ //# sourceMappingURL=chunk-HC3QEZKT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"sourcesContent":["{\n \"name\": \"tenjin-cli\",\n \"version\": \"0.1.0-alpha.27\",\n \"type\": \"module\",\n \"description\": \"The tool router for coding agents. Tenjin picks the right tool when your agent needs one, and one wallet pays for every call.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/BackTrackCo/tenjin-agent.git\"\n },\n \"homepage\": \"https://tenjin.sh/agents\",\n \"bugs\": \"https://github.com/BackTrackCo/tenjin-agent/issues\",\n \"keywords\": [\n \"claude-code\",\n \"coding-agents\",\n \"tool-router\",\n \"ai-agents\",\n \"agent-tools\",\n \"mcp\",\n \"x402\",\n \"usdc\",\n \"base\",\n \"micropayments\",\n \"agent-payments\",\n \"claude\",\n \"codex\",\n \"cli\"\n ],\n \"bin\": {\n \"tenjin\": \"dist/index.js\"\n },\n \"engines\": {\n \"node\": \">=22.0.0\"\n },\n \"files\": [\n \"dist\",\n \"docs\",\n \"NOTICE.md\"\n ],\n \"packageManager\": \"pnpm@11.11.0\",\n \"scripts\": {\n \"build\": \"rm -rf dist && tsup\",\n \"test\": \"vitest run\",\n \"typecheck\": \"tsc --noEmit\",\n \"lint\": \"eslint .\",\n \"format\": \"prettier --write .\",\n \"format:check\": \"prettier --check .\",\n \"check\": \"pnpm run build && pnpm run test\",\n \"sync:skill\": \"node scripts/sync-skill.mjs\",\n \"pack-smoke\": \"bash scripts/pack-smoke.sh\",\n \"changeset\": \"changeset\",\n \"prepublishOnly\": \"pnpm run build\",\n \"githooks\": \"git config core.hooksPath .githooks\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^3.0.3\",\n \"@clack/prompts\": \"^1.7.0\",\n \"@eslint/js\": \"^10\",\n \"@modelcontextprotocol/sdk\": \"1.31.0\",\n \"@types/node\": \"^22.20.5\",\n \"@x402/core\": \"2.28.0\",\n \"@x402/evm\": \"2.28.0\",\n \"@x402/extensions\": \"2.28.0\",\n \"@x402/fetch\": \"2.28.0\",\n \"ajv\": \"^8.20.0\",\n \"ajv-formats\": \"^3.0.1\",\n \"commander\": \"^14.0.1\",\n \"eslint\": \"^10\",\n \"eslint-config-prettier\": \"^10\",\n \"lean-qr\": \"^2.7.4\",\n \"ox\": \"0.14.30\",\n \"prettier\": \"^3\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^6\",\n \"typescript-eslint\": \"^8\",\n \"viem\": \"^2.53.1\",\n \"vitest\": \"^4.1.9\",\n \"zod\": \"^4.4.3\"\n }\n}\n"],"mappings":";;;AAAA;AAAA,EACE,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,MAAQ;AAAA,EACR,aAAe;AAAA,EACf,YAAc;AAAA,IACZ,MAAQ;AAAA,IACR,KAAO;AAAA,EACT;AAAA,EACA,UAAY;AAAA,EACZ,MAAQ;AAAA,EACR,UAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAAA,EACA,KAAO;AAAA,IACL,QAAU;AAAA,EACZ;AAAA,EACA,SAAW;AAAA,IACT,MAAQ;AAAA,EACV;AAAA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