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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +5 -0
  2. package/dist/chunk-2G2WLVHB.js +102 -0
  3. package/dist/chunk-2G2WLVHB.js.map +1 -0
  4. package/dist/chunk-2I4QTOLB.js +11 -0
  5. package/dist/chunk-2I4QTOLB.js.map +1 -0
  6. package/dist/chunk-35M3VITA.js +102 -0
  7. package/dist/chunk-35M3VITA.js.map +1 -0
  8. package/dist/chunk-3KKKB2AQ.js +40 -0
  9. package/dist/chunk-3KKKB2AQ.js.map +1 -0
  10. package/dist/{chunk-OIM4HLN6.js → chunk-7QKHZQKW.js} +295 -20
  11. package/dist/chunk-7QKHZQKW.js.map +1 -0
  12. package/dist/{chunk-BBVUVBUO.js → chunk-AR7U7BRG.js} +44 -7
  13. package/dist/{chunk-BBVUVBUO.js.map → chunk-AR7U7BRG.js.map} +1 -1
  14. package/dist/{chunk-DMZZLPZN.js → chunk-AUKDYPPX.js} +14 -89
  15. package/dist/chunk-AUKDYPPX.js.map +1 -0
  16. package/dist/{chunk-56MOAIP5.js → chunk-BTX2QE2Y.js} +9 -6
  17. package/dist/chunk-BTX2QE2Y.js.map +1 -0
  18. package/dist/{chunk-HVRC33OL.js → chunk-EPCOMXLF.js} +4 -6
  19. package/dist/{chunk-HVRC33OL.js.map → chunk-EPCOMXLF.js.map} +1 -1
  20. package/dist/{chunk-25TJPVBF.js → chunk-F3FUGWPZ.js} +28 -15
  21. package/dist/chunk-F3FUGWPZ.js.map +1 -0
  22. package/dist/{chunk-2U5ZVEV3.js → chunk-FGR734LZ.js} +6 -6
  23. package/dist/{chunk-PZEN5PHN.js → chunk-J5INH7WB.js} +17 -3
  24. package/dist/chunk-J5INH7WB.js.map +1 -0
  25. package/dist/{chunk-7WEQQJLG.js → chunk-JLEF5WHM.js} +66 -2
  26. package/dist/chunk-JLEF5WHM.js.map +1 -0
  27. package/dist/{chunk-YEETV6IW.js → chunk-KUBEYXSO.js} +10 -12
  28. package/dist/{chunk-YEETV6IW.js.map → chunk-KUBEYXSO.js.map} +1 -1
  29. package/dist/{chunk-L3PVMIYQ.js → chunk-N44H5TFB.js} +82 -150
  30. package/dist/chunk-N44H5TFB.js.map +1 -0
  31. package/dist/{chunk-BFFM2WFK.js → chunk-NRQMOVKM.js} +2 -2
  32. package/dist/{chunk-BFFM2WFK.js.map → chunk-NRQMOVKM.js.map} +1 -1
  33. package/dist/{chunk-GULLJQXA.js → chunk-ON6C6WOX.js} +127 -17
  34. package/dist/chunk-ON6C6WOX.js.map +1 -0
  35. package/dist/{chunk-OJLYNM4Z.js → chunk-PDA2BVFY.js} +77 -19
  36. package/dist/chunk-PDA2BVFY.js.map +1 -0
  37. package/dist/chunk-S2NRVRPF.js +171 -0
  38. package/dist/chunk-S2NRVRPF.js.map +1 -0
  39. package/dist/chunk-TGLKKLQG.js +11 -0
  40. package/dist/chunk-TGLKKLQG.js.map +1 -0
  41. package/dist/{chunk-SKAHDQH7.js → chunk-TJMCBIZU.js} +6 -7
  42. package/dist/{chunk-SKAHDQH7.js.map → chunk-TJMCBIZU.js.map} +1 -1
  43. package/dist/chunk-TP4D47BY.js +127 -0
  44. package/dist/chunk-TP4D47BY.js.map +1 -0
  45. package/dist/{chunk-WH7OWT6G.js → chunk-U2DZISAH.js} +2 -8
  46. package/dist/chunk-U2DZISAH.js.map +1 -0
  47. package/dist/{chunk-YJHHCWM3.js → chunk-WLMJE3GJ.js} +3 -3
  48. package/dist/{chunk-U5DXNFJC.js → chunk-WS4JA6TC.js} +3 -3
  49. package/dist/{chunk-5X4SZ5BF.js → chunk-WUHY2AXD.js} +4 -4
  50. package/dist/{chunk-USS336NF.js → chunk-YPQSMIDH.js} +5 -5
  51. package/dist/chunk-YPQSMIDH.js.map +1 -0
  52. package/dist/{chunk-3AJS6LLN.js → chunk-ZG7SFI34.js} +7 -7
  53. package/dist/{cli-M3XCSOU6.js → cli-MP3RAYHL.js} +43 -29
  54. package/dist/{cli-M3XCSOU6.js.map → cli-MP3RAYHL.js.map} +1 -1
  55. package/dist/{config-MXOX7XDR.js → config-BJK6U5VY.js} +11 -10
  56. package/dist/{doctor-LU4YIZWM.js → doctor-KJROWE5V.js} +108 -21
  57. package/dist/doctor-KJROWE5V.js.map +1 -0
  58. package/dist/{fund-A54P2QFK.js → fund-I5COXPEJ.js} +13 -11
  59. package/dist/{fund-A54P2QFK.js.map → fund-I5COXPEJ.js.map} +1 -1
  60. package/dist/hook-command-EJO2564A.js +821 -0
  61. package/dist/hook-command-EJO2564A.js.map +1 -0
  62. package/dist/index.js +2 -2
  63. package/dist/{install-XUM2XSHW.js → install-NUQLLHS2.js} +21 -14
  64. package/dist/{install-wallet-QIOFORTX.js → install-wallet-JPFTEC6H.js} +12 -10
  65. package/dist/{install-wallet-QIOFORTX.js.map → install-wallet-JPFTEC6H.js.map} +1 -1
  66. package/dist/{mcp-HJC2PLRV.js → mcp-I5XMVE64.js} +77 -34
  67. package/dist/{mcp-HJC2PLRV.js.map → mcp-I5XMVE64.js.map} +1 -1
  68. package/dist/{pay-SBXZEPEP.js → pay-WA3JSCNB.js} +21 -14
  69. package/dist/{redact-46ZHF2NH.js → redact-6W23GGJC.js} +4 -6
  70. package/dist/{send-ASD2ZXJD.js → send-KVUH5WDO.js} +12 -10
  71. package/dist/{send-ASD2ZXJD.js.map → send-KVUH5WDO.js.map} +1 -1
  72. package/dist/{skill-placement-NFVHY6A3.js → skill-placement-JMDPSKE6.js} +12 -13
  73. package/dist/{skill-placement-NFVHY6A3.js.map → skill-placement-JMDPSKE6.js.map} +1 -1
  74. package/dist/{status-T2SDB57A.js → status-FFC6FO72.js} +8 -7
  75. package/dist/{status-T2SDB57A.js.map → status-FFC6FO72.js.map} +1 -1
  76. package/dist/{status-line-CGPUSDMC.js → status-line-SAXSU6CR.js} +19 -3
  77. package/dist/status-line-SAXSU6CR.js.map +1 -0
  78. package/dist/{status-line-wiring-BYPHTYZE.js → status-line-wiring-DQZCWIUO.js} +5 -6
  79. package/dist/tenjin-daemon.mjs +384 -23
  80. package/dist/{uninstall-FKYZHAM3.js → uninstall-SWICHBTF.js} +41 -18
  81. package/dist/uninstall-SWICHBTF.js.map +1 -0
  82. package/dist/{update-ANJ2AOTN.js → update-W572AMXG.js} +6 -7
  83. package/dist/{update-ANJ2AOTN.js.map → update-W572AMXG.js.map} +1 -1
  84. package/dist/{wallet-PWAHVKWW.js → wallet-L2YLAJFN.js} +12 -10
  85. package/docs/agent-permissions.md +17 -9
  86. package/docs/safety-model.md +1 -1
  87. package/package.json +1 -1
  88. package/dist/chunk-25TJPVBF.js.map +0 -1
  89. package/dist/chunk-56MOAIP5.js.map +0 -1
  90. package/dist/chunk-7WEQQJLG.js.map +0 -1
  91. package/dist/chunk-DMZZLPZN.js.map +0 -1
  92. package/dist/chunk-GULLJQXA.js.map +0 -1
  93. package/dist/chunk-L3PVMIYQ.js.map +0 -1
  94. package/dist/chunk-OCBHUHWB.js +0 -69
  95. package/dist/chunk-OCBHUHWB.js.map +0 -1
  96. package/dist/chunk-OIM4HLN6.js.map +0 -1
  97. package/dist/chunk-OJLYNM4Z.js.map +0 -1
  98. package/dist/chunk-PZEN5PHN.js.map +0 -1
  99. package/dist/chunk-USS336NF.js.map +0 -1
  100. package/dist/chunk-WH7OWT6G.js.map +0 -1
  101. package/dist/doctor-LU4YIZWM.js.map +0 -1
  102. package/dist/hook-command-U6KWPEDQ.js +0 -377
  103. package/dist/hook-command-U6KWPEDQ.js.map +0 -1
  104. package/dist/status-line-CGPUSDMC.js.map +0 -1
  105. package/dist/uninstall-FKYZHAM3.js.map +0 -1
  106. /package/dist/{chunk-2U5ZVEV3.js.map → chunk-FGR734LZ.js.map} +0 -0
  107. /package/dist/{chunk-YJHHCWM3.js.map → chunk-WLMJE3GJ.js.map} +0 -0
  108. /package/dist/{chunk-U5DXNFJC.js.map → chunk-WS4JA6TC.js.map} +0 -0
  109. /package/dist/{chunk-5X4SZ5BF.js.map → chunk-WUHY2AXD.js.map} +0 -0
  110. /package/dist/{chunk-3AJS6LLN.js.map → chunk-ZG7SFI34.js.map} +0 -0
  111. /package/dist/{config-MXOX7XDR.js.map → config-BJK6U5VY.js.map} +0 -0
  112. /package/dist/{install-XUM2XSHW.js.map → install-NUQLLHS2.js.map} +0 -0
  113. /package/dist/{pay-SBXZEPEP.js.map → pay-WA3JSCNB.js.map} +0 -0
  114. /package/dist/{redact-46ZHF2NH.js.map → redact-6W23GGJC.js.map} +0 -0
  115. /package/dist/{status-line-wiring-BYPHTYZE.js.map → status-line-wiring-DQZCWIUO.js.map} +0 -0
  116. /package/dist/{wallet-PWAHVKWW.js.map → wallet-L2YLAJFN.js.map} +0 -0
@@ -11,19 +11,20 @@ import {
11
11
  runConfigGet,
12
12
  runConfigList,
13
13
  runConfigSet
14
- } from "./chunk-GULLJQXA.js";
14
+ } from "./chunk-ON6C6WOX.js";
15
15
  import "./chunk-WXC57XGG.js";
16
16
  import "./chunk-2QYORQBF.js";
17
17
  import "./chunk-MEFB5KHA.js";
18
- import "./chunk-U5DXNFJC.js";
19
- import "./chunk-OJLYNM4Z.js";
20
- import "./chunk-WH7OWT6G.js";
21
- import "./chunk-BBVUVBUO.js";
22
- import "./chunk-SKAHDQH7.js";
23
- import "./chunk-BFFM2WFK.js";
24
- import "./chunk-OCBHUHWB.js";
18
+ import "./chunk-TP4D47BY.js";
19
+ import "./chunk-WS4JA6TC.js";
20
+ import "./chunk-2I4QTOLB.js";
21
+ import "./chunk-PDA2BVFY.js";
22
+ import "./chunk-U2DZISAH.js";
23
+ import "./chunk-AR7U7BRG.js";
24
+ import "./chunk-TJMCBIZU.js";
25
+ import "./chunk-NRQMOVKM.js";
26
+ import "./chunk-JLEF5WHM.js";
25
27
  import "./chunk-2BKS2FVE.js";
26
- import "./chunk-7WEQQJLG.js";
27
28
  import "./chunk-ZXTAQYNA.js";
28
29
  export {
29
30
  ROUTER_DEFAULTS,
@@ -38,4 +39,4 @@ export {
38
39
  runConfigList,
39
40
  runConfigSet
40
41
  };
41
- //# sourceMappingURL=config-MXOX7XDR.js.map
42
+ //# sourceMappingURL=config-BJK6U5VY.js.map
@@ -1,16 +1,20 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ agentsWithoutRequestTool
4
+ } from "./chunk-S2NRVRPF.js";
2
5
  import {
3
6
  ROUTER_PATH
4
- } from "./chunk-USS336NF.js";
7
+ } from "./chunk-YPQSMIDH.js";
5
8
  import {
6
9
  httpRequest
7
- } from "./chunk-5X4SZ5BF.js";
10
+ } from "./chunk-WUHY2AXD.js";
8
11
  import {
9
12
  describeWallet,
10
13
  resolveWalletProvider,
11
14
  walletFileExists
12
- } from "./chunk-YEETV6IW.js";
13
- import "./chunk-DMZZLPZN.js";
15
+ } from "./chunk-KUBEYXSO.js";
16
+ import "./chunk-AUKDYPPX.js";
17
+ import "./chunk-35M3VITA.js";
14
18
  import "./chunk-N35E6CM2.js";
15
19
  import "./chunk-JRGFKVAZ.js";
16
20
  import "./chunk-EGELTSPU.js";
@@ -19,43 +23,51 @@ import "./chunk-RBJPAZFI.js";
19
23
  import "./chunk-BPMWXTFX.js";
20
24
  import {
21
25
  ALLOW_RULE,
22
- MCP_SERVER_NAME,
23
26
  mcpAddCommand,
24
27
  mcpScope,
25
28
  readMcpEntry,
29
+ routerHookPlan,
26
30
  routerSettingsPath
27
- } from "./chunk-25TJPVBF.js";
28
- import "./chunk-YJHHCWM3.js";
29
- import "./chunk-GULLJQXA.js";
31
+ } from "./chunk-F3FUGWPZ.js";
32
+ import {
33
+ MCP_SERVER_NAME,
34
+ REQUEST_TOOL
35
+ } from "./chunk-TGLKKLQG.js";
36
+ import "./chunk-WLMJE3GJ.js";
37
+ import "./chunk-ON6C6WOX.js";
30
38
  import "./chunk-WXC57XGG.js";
31
39
  import "./chunk-2QYORQBF.js";
32
40
  import "./chunk-MEFB5KHA.js";
41
+ import {
42
+ routerSettings
43
+ } from "./chunk-TP4D47BY.js";
33
44
  import {
34
45
  onPath
35
- } from "./chunk-U5DXNFJC.js";
46
+ } from "./chunk-WS4JA6TC.js";
47
+ import "./chunk-2I4QTOLB.js";
36
48
  import {
37
49
  resolveContextSettings
38
- } from "./chunk-OJLYNM4Z.js";
50
+ } from "./chunk-PDA2BVFY.js";
39
51
  import {
40
52
  toMoney
41
- } from "./chunk-WH7OWT6G.js";
53
+ } from "./chunk-U2DZISAH.js";
42
54
  import {
43
55
  PRODUCTION_ORIGIN
44
- } from "./chunk-BBVUVBUO.js";
56
+ } from "./chunk-AR7U7BRG.js";
45
57
  import {
46
58
  STATUS_LINE_COMMAND,
47
59
  inspectStatusLine
48
- } from "./chunk-HVRC33OL.js";
60
+ } from "./chunk-EPCOMXLF.js";
49
61
  import {
50
62
  inspectHooksFile,
51
- ownsHookEntry
52
- } from "./chunk-SKAHDQH7.js";
53
- import "./chunk-BFFM2WFK.js";
63
+ ownsHookEntry,
64
+ pruneOurHandlers
65
+ } from "./chunk-TJMCBIZU.js";
66
+ import "./chunk-NRQMOVKM.js";
54
67
  import {
55
68
  CliError
56
- } from "./chunk-OCBHUHWB.js";
69
+ } from "./chunk-JLEF5WHM.js";
57
70
  import "./chunk-2BKS2FVE.js";
58
- import "./chunk-7WEQQJLG.js";
59
71
  import "./chunk-ZXTAQYNA.js";
60
72
 
61
73
  // src/router/doctor.ts
@@ -66,6 +78,10 @@ var exec = promisify(execFile);
66
78
  var NODE_FLOOR = 24;
67
79
  async function runRouterDoctor(ctx, deps = {}) {
68
80
  const env = deps.env ?? process.env;
81
+ const router = await routerSettings(
82
+ { cwd: deps.cwd ?? process.cwd(), dataDir: ctx.dataDir },
83
+ deps.homeDir !== void 0 ? { homeDir: deps.homeDir } : {}
84
+ ).catch((err) => err instanceof Error ? err : new Error(String(err)));
69
85
  const settings = await resolveContextSettings(ctx);
70
86
  const settingsPath = routerSettingsPath({
71
87
  ...deps.project === true ? { project: true } : {},
@@ -73,7 +89,7 @@ async function runRouterDoctor(ctx, deps = {}) {
73
89
  ...deps.cwd !== void 0 ? { cwd: deps.cwd } : {}
74
90
  });
75
91
  const checks = [nodeCheck(deps.nodeVersion ?? process.version)];
76
- checks.push(await hooksCheck(settingsPath, ctx.dataDir));
92
+ checks.push(await hooksCheck(settingsPath, ctx.dataDir, router));
77
93
  checks.push(await statusLineCheck(settingsPath));
78
94
  checks.push(
79
95
  await mcpCheck(
@@ -87,6 +103,8 @@ async function runRouterDoctor(ctx, deps = {}) {
87
103
  checks.push(spendCheck(settings.policy.maxAutoSpendAtomic, settings.policy.sessionBudgetAtomic));
88
104
  checks.push(...await walletCheck(ctx));
89
105
  checks.push(await routerCheck(settings.baseUrl, ctx.flags.timeout, deps.fetchImpl));
106
+ const agents = await subagentsCheck(deps.cwd ?? process.cwd(), deps.homeDir ?? homedir());
107
+ if (agents !== null) checks.push(agents);
90
108
  const failure = checks.find((c) => c.status === "fail" && c.required);
91
109
  const data = { checks, dataDir: ctx.dataDir, baseUrl: settings.baseUrl, settingsPath };
92
110
  if (failure !== void 0) {
@@ -106,6 +124,16 @@ async function runRouterDoctor(ctx, deps = {}) {
106
124
  ]
107
125
  };
108
126
  }
127
+ async function subagentsCheck(cwd, homeDir) {
128
+ const excluded = await agentsWithoutRequestTool({ cwd, homeDir });
129
+ if (excluded.length === 0) return null;
130
+ return {
131
+ name: "subagents",
132
+ status: "ok",
133
+ required: false,
134
+ detail: `${excluded.join(", ")} ${excluded.length === 1 ? "is" : "are"} offered no paid lookups: add ${REQUEST_TOOL} to tools: to allow paid lookups there`
135
+ };
136
+ }
109
137
  function nodeCheck(version) {
110
138
  const major = Number(/^v(\d+)/.exec(version)?.[1] ?? "0");
111
139
  return major >= NODE_FLOOR ? { name: "node", status: "ok", required: true, detail: version } : {
@@ -150,7 +178,7 @@ async function statusLineCheck(path) {
150
178
  };
151
179
  }
152
180
  }
153
- async function hooksCheck(path, dataDir) {
181
+ async function hooksCheck(path, dataDir, router) {
154
182
  const found = await inspectHooksFile(path);
155
183
  if ("refusal" in found) {
156
184
  return {
@@ -172,6 +200,25 @@ async function hooksCheck(path, dataDir) {
172
200
  fix: "Run `tenjin install`, then restart Claude Code."
173
201
  };
174
202
  }
203
+ if (router instanceof Error) {
204
+ return {
205
+ name: "hooks",
206
+ status: "warn",
207
+ required: false,
208
+ detail: `${events.join(" and ")} registered, but the router is off here: ${router.message}`,
209
+ fix: "Fix or delete that file."
210
+ };
211
+ }
212
+ if (!router.enabled.value) {
213
+ const file = router.enabled.path ?? "the config";
214
+ return {
215
+ name: "hooks",
216
+ status: "warn",
217
+ required: false,
218
+ detail: `${events.join(" and ")} registered, but router.enabled is false in ${file}, so nothing is routed from this directory`,
219
+ fix: router.enabled.source === "file" ? "Run `tenjin config set router.enabled true` to route again." : `Remove router.enabled from ${file} to route here again.`
220
+ };
221
+ }
175
222
  if (!allow.includes(ALLOW_RULE)) {
176
223
  return {
177
224
  name: "hooks",
@@ -181,6 +228,20 @@ async function hooksCheck(path, dataDir) {
181
228
  fix: "Run `tenjin install` to write the permission rule."
182
229
  };
183
230
  }
231
+ const drift = planDrift(found.hooks, dataDir);
232
+ if (drift.missing.length > 0 || drift.stale.length > 0) {
233
+ const parts = [
234
+ ...drift.missing.length > 0 ? [`missing ${drift.missing.join(", ")}`] : [],
235
+ ...drift.stale.length > 0 ? [`stale ${drift.stale.join(", ")}`] : []
236
+ ];
237
+ return {
238
+ name: "hooks",
239
+ status: "warn",
240
+ required: false,
241
+ detail: `${events.join(" and ")} registered, but not as this build writes them: ${parts.join("; ")}`,
242
+ fix: "Run `tenjin install --refresh`."
243
+ };
244
+ }
184
245
  return {
185
246
  name: "hooks",
186
247
  status: "ok",
@@ -188,6 +249,32 @@ async function hooksCheck(path, dataDir) {
188
249
  detail: `${events.join(" and ")} registered, ${ALLOW_RULE} allowed`
189
250
  };
190
251
  }
252
+ function entryLabel(event, matcher, command) {
253
+ return `${event}${typeof matcher === "string" ? ` ${matcher}` : ""} \u2192 ${command}`;
254
+ }
255
+ function planDrift(hooks, dataDir) {
256
+ const planned = routerHookPlan().map(
257
+ (entry) => entryLabel(entry.event, entry.matcher, entry.hooks[0].command)
258
+ );
259
+ const present = [];
260
+ for (const [event, list] of Object.entries(hooks)) {
261
+ for (const entry of list) {
262
+ if (!ownsHookEntry(entry, dataDir)) continue;
263
+ const { matcher, hooks: handlers } = entry;
264
+ const kept = pruneOurHandlers(entry, dataDir);
265
+ for (const handler of handlers.filter((h) => kept === null || !kept.hooks.includes(h))) {
266
+ const command = handler.command;
267
+ const url = handler.url;
268
+ const label = typeof command === "string" ? command : typeof url === "string" ? url : "?";
269
+ present.push(entryLabel(event, matcher, label));
270
+ }
271
+ }
272
+ }
273
+ return {
274
+ missing: planned.filter((label) => !present.includes(label)),
275
+ stale: present.filter((label) => !planned.includes(label))
276
+ };
277
+ }
191
278
  function allowRules(settings) {
192
279
  const permissions = settings.permissions;
193
280
  if (permissions === null || typeof permissions !== "object" || Array.isArray(permissions)) {
@@ -346,4 +433,4 @@ async function routerCheck(baseUrl, timeoutMs, fetchImpl) {
346
433
  export {
347
434
  runRouterDoctor
348
435
  };
349
- //# sourceMappingURL=doctor-LU4YIZWM.js.map
436
+ //# sourceMappingURL=doctor-KJROWE5V.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/doctor.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { homedir } from 'node:os';\nimport { promisify } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile, ownsHookEntry, pruneOurHandlers } from '../lib/harness-hooks';\nimport { httpRequest } from '../lib/http';\nimport { toMoney } from '../lib/money';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport { resolveContextSettings } from '../lib/settings';\nimport { onPath } from '../lib/skill-wiring';\nimport { describeWallet, resolveWalletProvider } from '../lib/wallet';\nimport { walletFileExists } from '../lib/wallet/store';\nimport type { CommandContext, CommandResult } from '../context';\nimport { agentsWithoutRequestTool } from './agent-tools';\nimport { ROUTER_PATH } from './decision';\nimport {\n ALLOW_RULE,\n MCP_SERVER_NAME,\n mcpAddCommand,\n mcpScope,\n readMcpEntry,\n routerHookPlan,\n routerSettingsPath,\n type McpEntryState,\n} from './install';\nimport { routerSettings, type RouterSettings } from './settings';\nimport { REQUEST_TOOL } from './names';\nimport { inspectStatusLine, STATUS_LINE_COMMAND } from './status-line-wiring';\n\n/**\n * `tenjin doctor` for the router product: the six things that decide whether a\n * lookup can happen at all.\n *\n * THE SHELF'S DOCTOR IS NOT THIS ONE. It checks a loop daemon, a skills tree\n * and a marketplace contract, and prescribes `tenjin daemon start`, a command\n * this release does not register: on a router install every one of those lines\n * was a failure about a product that is not installed. That doctor stays with\n * the product it belongs to (`src/commands/doctor.ts`, unregistered), and this\n * one reports the router's own wiring.\n */\n\nconst exec = promisify(execFile);\n\nexport interface RouterCheck {\n name: string;\n status: 'ok' | 'warn' | 'fail';\n required: boolean;\n detail: string;\n fix?: string;\n}\n\nexport interface RouterDoctorDeps {\n homeDir?: string;\n cwd?: string;\n /** Look at this project's `.claude/settings.json`, as `--project` installed it. */\n project?: boolean;\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n fetchImpl?: typeof fetch;\n /** The harness's own read-back, for a user-scope registration this build\n * cannot find on disk; tests inject it so nothing is spawned. */\n readMcp?: (opts: { scope: 'user' | 'project'; cwd: string }) => Promise<boolean>;\n /** Reads the registration entry from the file the scope writes. */\n readMcpEntry?: (\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n ) => Promise<{ found: boolean; state: McpEntryState }>;\n /** Node's own version, for the floor check. */\n nodeVersion?: string;\n}\n\nconst NODE_FLOOR = 24;\n\nexport async function runRouterDoctor(\n ctx: CommandContext,\n deps: RouterDoctorDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n // From the directory doctor runs in, which is the one a session there would use.\n const router = await routerSettings(\n { cwd: deps.cwd ?? process.cwd(), dataDir: ctx.dataDir },\n deps.homeDir !== undefined ? { homeDir: deps.homeDir } : {},\n ).catch((err: unknown) => (err instanceof Error ? err : new Error(String(err))));\n const settings = await resolveContextSettings(ctx);\n // The SAME resolution `install` and `uninstall` use. Reading the home file\n // only made a correctly wired `--project` install, which the README tells\n // people to do, fail a required check and exit 3.\n const settingsPath = routerSettingsPath({\n ...(deps.project === true ? { project: true } : {}),\n ...(deps.homeDir !== undefined ? { homeDir: deps.homeDir } : {}),\n ...(deps.cwd !== undefined ? { cwd: deps.cwd } : {}),\n });\n const checks: RouterCheck[] = [nodeCheck(deps.nodeVersion ?? process.version)];\n checks.push(await hooksCheck(settingsPath, ctx.dataDir, router));\n checks.push(await statusLineCheck(settingsPath));\n checks.push(\n await mcpCheck(\n deps,\n env,\n deps.project === true,\n deps.cwd ?? process.cwd(),\n deps.homeDir ?? homedir(),\n ),\n );\n checks.push(spendCheck(settings.policy.maxAutoSpendAtomic, settings.policy.sessionBudgetAtomic));\n checks.push(...(await walletCheck(ctx)));\n checks.push(await routerCheck(settings.baseUrl, ctx.flags.timeout, deps.fetchImpl));\n const agents = await subagentsCheck(deps.cwd ?? process.cwd(), deps.homeDir ?? homedir());\n if (agents !== null) checks.push(agents);\n\n const failure = checks.find((c) => c.status === 'fail' && c.required);\n const data = { checks, dataDir: ctx.dataDir, baseUrl: settings.baseUrl, settingsPath };\n if (failure !== undefined) {\n // REFUSED, the exit-3 class: a machine this command found unready is\n // understood and refused, not a runtime failure of the command itself.\n throw new CliError('REFUSED', failure.detail, {\n ...(failure.fix !== undefined ? { fix: failure.fix } : {}),\n details: data,\n });\n }\n const bad = checks.filter((c) => c.status !== 'ok').length;\n return {\n data,\n humanLines: [\n ...checks.map(\n (c) =>\n `${c.status === 'ok' ? 'ok ' : c.status === 'warn' ? 'warn' : 'fail'} ${c.name}: ${c.detail}`,\n ),\n bad === 0\n ? `${checks.length} checks, all pass.`\n : `${checks.length} checks, ${bad} to look at.`,\n ],\n };\n}\n\n/**\n * INFORMATIONAL, NEVER A FAILURE. A custom agent whose `tools:` leave the\n * request tool out is a choice its author may have meant, so this names those\n * agents and the one line that would change it, and counts as passing. It is\n * absent when there is nothing to name. The files are only read.\n */\nasync function subagentsCheck(cwd: string, homeDir: string): Promise<RouterCheck | null> {\n const excluded = await agentsWithoutRequestTool({ cwd, homeDir });\n if (excluded.length === 0) return null;\n return {\n name: 'subagents',\n status: 'ok',\n required: false,\n detail: `${excluded.join(', ')} ${excluded.length === 1 ? 'is' : 'are'} offered no paid lookups: add ${REQUEST_TOOL} to tools: to allow paid lookups there`,\n };\n}\n\nfunction nodeCheck(version: string): RouterCheck {\n const major = Number(/^v(\\d+)/.exec(version)?.[1] ?? '0');\n return major >= NODE_FLOOR\n ? { name: 'node', status: 'ok', required: true, detail: version }\n : {\n name: 'node',\n status: 'fail',\n required: true,\n detail: `${version} is below the Node ${NODE_FLOOR} floor.`,\n fix: `Install Node ${NODE_FLOOR} or newer, then re-run \\`tenjin doctor\\`.`,\n };\n}\n\n/**\n * The live footer, which is the one check here that is never required: a lookup\n * runs exactly the same without it. It reports what is in the file, including a\n * status line of the user's that this CLI deliberately did not touch.\n */\nasync function statusLineCheck(path: string): Promise<RouterCheck> {\n const found = await inspectStatusLine(path);\n const name = 'status line';\n if (found.warning !== undefined) {\n return { name, status: 'warn', required: false, detail: found.warning };\n }\n switch (found.state) {\n case 'ours':\n return { name, status: 'ok', required: false, detail: `\\`${STATUS_LINE_COMMAND}\\`` };\n case 'composed':\n return {\n name,\n status: 'ok',\n required: false,\n detail: 'yours, with the x402 footer appended',\n };\n case 'foreign':\n return {\n name,\n status: 'warn',\n required: false,\n detail: 'yours is registered and was left alone, so there is no live x402 footer',\n fix: 'Run `tenjin install --status-line compose` to show both.',\n };\n default:\n return {\n name,\n status: 'warn',\n required: false,\n detail: 'not registered, so lookups run without the live footer',\n fix: 'Run `tenjin install` to register it.',\n };\n }\n}\n\nasync function hooksCheck(\n path: string,\n dataDir: string,\n router: RouterSettings | Error,\n): Promise<RouterCheck> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n return {\n name: 'hooks',\n status: 'fail',\n required: true,\n detail: found.refusal.message,\n fix: 'Fix the reported file, then run `tenjin install`.',\n };\n }\n const events = Object.entries(found.hooks)\n .filter(([, list]) => list.some((entry) => ownsHookEntry(entry, dataDir)))\n .map(([event]) => event);\n const allow = allowRules(found.settings);\n if (events.length === 0) {\n return {\n name: 'hooks',\n status: 'fail',\n required: true,\n detail: `no Tenjin hook entries in ${path}`,\n fix: 'Run `tenjin install`, then restart Claude Code.',\n };\n }\n // WIRED BUT SWITCHED OFF is a choice, not a fault, so it warns and names the\n // file that made it: the entries are there and every one of them is silent.\n if (router instanceof Error) {\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but the router is off here: ${router.message}`,\n fix: 'Fix or delete that file.',\n };\n }\n if (!router.enabled.value) {\n const file = router.enabled.path ?? 'the config';\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but router.enabled is false in ${file}, so nothing is routed from this directory`,\n fix:\n router.enabled.source === 'file'\n ? 'Run `tenjin config set router.enabled true` to route again.'\n : `Remove router.enabled from ${file} to route here again.`,\n };\n }\n if (!allow.includes(ALLOW_RULE)) {\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but ${ALLOW_RULE} is not allowed, so every lookup asks`,\n fix: 'Run `tenjin install` to write the permission rule.',\n };\n }\n // AN INSTALL FROM AN OLDER BUILD STILL WORKS, so this is a warning with its\n // one-command remedy, not a failure: its `tenjin hook native` entry is a\n // no-op now, and the entries it lacks are offers it does not make.\n const drift = planDrift(found.hooks, dataDir);\n if (drift.missing.length > 0 || drift.stale.length > 0) {\n const parts = [\n ...(drift.missing.length > 0 ? [`missing ${drift.missing.join(', ')}`] : []),\n ...(drift.stale.length > 0 ? [`stale ${drift.stale.join(', ')}`] : []),\n ];\n return {\n name: 'hooks',\n status: 'warn',\n required: false,\n detail: `${events.join(' and ')} registered, but not as this build writes them: ${parts.join('; ')}`,\n fix: 'Run `tenjin install --refresh`.',\n };\n }\n return {\n name: 'hooks',\n status: 'ok',\n required: true,\n detail: `${events.join(' and ')} registered, ${ALLOW_RULE} allowed`,\n };\n}\n\n/** One entry as `event matcher → command`, the way doctor names it. */\nfunction entryLabel(event: string, matcher: unknown, command: string): string {\n return `${event}${typeof matcher === 'string' ? ` ${matcher}` : ''} → ${command}`;\n}\n\n/**\n * Which of `routerHookPlan()`'s entries this file lacks, and which handlers of\n * ours it carries that the plan no longer writes (an older install's\n * `tenjin hook native`, or a shelf-era entry). Compared by event, matcher and\n * command, so a timeout the writer would raise is not called drift here.\n */\nfunction planDrift(\n hooks: Record<string, unknown[]>,\n dataDir: string,\n): { missing: string[]; stale: string[] } {\n const planned = (routerHookPlan() as PlannedEntry[]).map((entry) =>\n entryLabel(entry.event, entry.matcher, entry.hooks[0]!.command),\n );\n const present: string[] = [];\n for (const [event, list] of Object.entries(hooks)) {\n for (const entry of list) {\n if (!ownsHookEntry(entry, dataDir)) continue;\n const { matcher, hooks: handlers } = entry as { matcher?: unknown; hooks: unknown[] };\n // Ours only: a handler someone hand-merged beside ours is not drift.\n const kept = pruneOurHandlers(entry, dataDir) as { hooks: unknown[] } | null;\n for (const handler of handlers.filter((h) => kept === null || !kept.hooks.includes(h))) {\n const command = (handler as { command?: unknown }).command;\n const url = (handler as { url?: unknown }).url;\n const label = typeof command === 'string' ? command : typeof url === 'string' ? url : '?';\n present.push(entryLabel(event, matcher, label));\n }\n }\n }\n return {\n missing: planned.filter((label) => !present.includes(label)),\n stale: present.filter((label) => !planned.includes(label)),\n };\n}\n\ninterface PlannedEntry {\n event: string;\n matcher?: string;\n hooks: { command: string }[];\n}\n\nfunction allowRules(settings: Record<string, unknown>): string[] {\n const permissions = settings.permissions;\n if (permissions === null || typeof permissions !== 'object' || Array.isArray(permissions)) {\n return [];\n }\n const allow = (permissions as { allow?: unknown }).allow;\n return Array.isArray(allow) ? allow.filter((r): r is string => typeof r === 'string') : [];\n}\n\nasync function mcpCheck(\n deps: RouterDoctorDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n home: string,\n): Promise<RouterCheck> {\n const scope = mcpScope(project);\n const add = mcpAddCommand(project);\n const where = scope === 'project' ? \"this project's .mcp.json\" : '~/.claude.json';\n const { found, state } = await (deps.readMcpEntry ?? readMcpEntry)(scope, cwd, home);\n\n if (state === 'ok') {\n return {\n name: 'mcp',\n status: 'ok',\n required: true,\n detail: `${MCP_SERVER_NAME} registered (${scope} scope), running \\`tenjin mcp\\``,\n };\n }\n if (state === 'wrong-command') {\n return {\n name: 'mcp',\n status: 'fail',\n required: true,\n detail: `${MCP_SERVER_NAME} registered but not \\`tenjin mcp\\`: the entry in ${where} launches something else, so the request tool is not there`,\n fix: `Remove it and re-run \\`tenjin install\\`${project ? ' --project' : ''}, or: ${add}`,\n };\n }\n // A file that is there and unreadable is not an absence: \"run install\" would\n // be the wrong instruction, since `install` refuses to write over it too.\n if (state === 'unreadable') {\n return {\n name: 'mcp',\n status: 'fail',\n required: true,\n detail: `${where} could not be read, so whether ${MCP_SERVER_NAME} is registered is unknown`,\n fix: `Fix the JSON in ${where}, then re-run \\`tenjin install\\`${project ? ' --project' : ''}.`,\n };\n }\n // Absent. On USER scope the file may simply not be where this build looks,\n // so the harness's own answer is worth asking before calling it missing.\n if (scope === 'user') {\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (which('claude')) {\n const seen = await (deps.readMcp ?? claudeHasServer)({ scope, cwd }).catch(() => false);\n if (seen) {\n return {\n name: 'mcp',\n status: 'warn',\n required: false,\n detail: `${MCP_SERVER_NAME} is registered somewhere this check cannot read, so what it launches was not verified`,\n fix: `Re-run \\`tenjin install\\` to write a registration this build can check, or: ${add}`,\n };\n }\n }\n }\n return {\n name: 'mcp',\n status: 'fail',\n required: true,\n detail: found\n ? `${MCP_SERVER_NAME} is not in ${where}, so there is no request tool`\n : `${where} does not exist, so ${MCP_SERVER_NAME} is not registered`,\n fix: `Run \\`tenjin install\\`${project ? ' --project' : ''}, or: ${add}`,\n };\n}\n\n/** The harness's own answer, for a user-scope registration this build cannot\n * find on disk. It resolves across scopes, which is why it is a last resort\n * and only ever downgrades the verdict to a warn. */\nasync function claudeHasServer(opts: { scope: 'user' | 'project'; cwd: string }): Promise<boolean> {\n const { stdout } = await exec('claude', ['mcp', 'get', MCP_SERVER_NAME], {\n timeout: 15_000,\n cwd: opts.cwd,\n });\n return stdout.includes(MCP_SERVER_NAME) && !/no mcp server/i.test(stdout);\n}\n\nfunction spendCheck(maxAutoSpendAtomic: bigint, sessionBudgetAtomic: bigint): RouterCheck {\n if (maxAutoSpendAtomic === 0n) {\n return {\n name: 'spend',\n status: 'fail',\n required: true,\n detail: 'maxAutoSpend is 0, so every lookup needs approval and none can pay',\n fix: 'Run `tenjin install`, or `tenjin config set maxAutoSpend 0.10`.',\n };\n }\n const budget =\n sessionBudgetAtomic === 0n\n ? 'no daily ceiling'\n : `${toMoney(sessionBudgetAtomic.toString()).usd} USD a day`;\n return {\n name: 'spend',\n status: sessionBudgetAtomic === 0n ? 'warn' : 'ok',\n required: false,\n detail: `at most ${toMoney(maxAutoSpendAtomic.toString()).usd} USD a call, ${budget}`,\n ...(sessionBudgetAtomic === 0n\n ? { fix: 'Set one with `tenjin config set sessionBudget 1.00`.' }\n : {}),\n };\n}\n\nasync function walletCheck(ctx: CommandContext): Promise<RouterCheck[]> {\n if (!(await walletFileExists(ctx.dataDir))) {\n return [\n {\n name: 'wallet',\n status: 'fail',\n required: true,\n detail: 'no wallet on this machine, so nothing can pay',\n fix: 'Run `tenjin wallet create`, then `tenjin wallet fund`.',\n },\n ];\n }\n try {\n const described = await describeWallet(resolveWalletProvider(ctx));\n return [{ name: 'wallet', status: 'ok', required: true, detail: described.address }];\n } catch (err) {\n return [\n {\n name: 'wallet',\n status: 'fail',\n required: true,\n detail: err instanceof CliError ? err.message : String(err),\n ...(err instanceof CliError && err.fix !== undefined ? { fix: err.fix } : {}),\n },\n ];\n }\n}\n\n/**\n * One cheap request to the free decision route with an empty body. It checks\n * the route is reachable and enabled, not that it routes: a 400 is the route\n * refusing that body, and a 404 is the route switched off. Nothing is signed\n * and no Jev request is spent.\n */\nasync function routerCheck(\n baseUrl: string,\n timeoutMs: number,\n fetchImpl: typeof fetch | undefined,\n): Promise<RouterCheck> {\n const url = new URL(ROUTER_PATH, baseUrl).toString();\n const probe = await httpRequest(url, {\n method: 'POST',\n timeoutMs,\n blockRedirects: true,\n jsonBody: {},\n ...(fetchImpl !== undefined ? { fetchImpl } : {}),\n });\n const fail = (detail: string, fix: string): RouterCheck => ({\n name: 'router',\n status: 'fail',\n required: true,\n detail,\n fix,\n });\n const checkBase =\n 'Check that the configured base URL names the Tenjin router (`tenjin config get baseUrl`), then try again later.';\n if (!probe.ok) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.message})`, checkBase);\n }\n // 429 is the route's own rate limit: proof the router is there.\n if (probe.status === 200 || probe.status === 400 || probe.status === 429) {\n return { name: 'router', status: 'ok', required: true, detail: `${url} is live` };\n }\n if (probe.status === 404) {\n return fail(`the router is not enabled at ${url}`, checkBase);\n }\n if (probe.status === 401 || probe.status === 403) {\n return fail(\n `${url} is not a Tenjin router (it asked for credentials)`,\n `Set the router URL with \\`tenjin config set baseUrl ${PRODUCTION_ORIGIN}\\`.`,\n );\n }\n if (probe.status >= 500) {\n return fail(`the router at ${url} is unreachable or erroring (${probe.status})`, checkBase);\n }\n return fail(\n `${url} answered ${probe.status}, which a Tenjin router does not`,\n 'Check that the configured base URL names a Tenjin deployment (`tenjin config get baseUrl`).',\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAuC1B,IAAM,OAA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I,CAAC,MAAM,IAAI;AACb,WAAO,KAAK,iBAAiB,GAAG,gCAAgC,MAAM,OAAO,KAAK,SAAS;AAAA,EAC7F;AAEA,MAAI,MAAM,WAAW,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW,KAAK;AACxE,WAAO,EAAE,MAAM,UAAU,QAAQ,MAAM,UAAU,MAAM,QAAQ,GAAG,GAAG,WAAW;AAAA,EAClF;AACA,MAAI,MAAM,WAAW,KAAK;AACxB,WAAO,KAAK,gCAAgC,GAAG,IAAI,SAAS;AAAA,EAC9D;AACA,MAAI,MAAM,WAAW,OAAO,MAAM,WAAW,KAAK;AAChD,WAAO;AAAA,MACL,GAAG,GAAG;AAAA,MACN,uDAAuD,iBAAiB;AAAA,IAC1E;AAAA,EACF;AACA,MAAI,MAAM,UAAU,KAAK;AACvB,WAAO,KAAK,iBAAiB,GAAG,gCAAgC,MAAM,MAAM,KAAK,SAAS;AAAA,EAC5F;AACA,SAAO;AAAA,IACL,GAAG,GAAG,aAAa,MAAM,MAAM;AAAA,IAC/B;AAAA,EACF;AACF;","names":[]}
@@ -6,19 +6,21 @@ import {
6
6
  import {
7
7
  fetchFailureToCliError,
8
8
  httpRequest
9
- } from "./chunk-5X4SZ5BF.js";
9
+ } from "./chunk-WUHY2AXD.js";
10
10
  import "./chunk-TTNESUPQ.js";
11
11
  import "./chunk-HPWO4O6S.js";
12
12
  import "./chunk-POUWHWID.js";
13
13
  import "./chunk-XZKD7DIF.js";
14
14
  import {
15
15
  getUsdcBalance
16
- } from "./chunk-56MOAIP5.js";
16
+ } from "./chunk-BTX2QE2Y.js";
17
+ import "./chunk-3KKKB2AQ.js";
17
18
  import {
18
19
  describeWallet,
19
20
  resolveWalletProvider
20
- } from "./chunk-YEETV6IW.js";
21
- import "./chunk-DMZZLPZN.js";
21
+ } from "./chunk-KUBEYXSO.js";
22
+ import "./chunk-AUKDYPPX.js";
23
+ import "./chunk-35M3VITA.js";
22
24
  import "./chunk-AWQPGIR6.js";
23
25
  import "./chunk-N35E6CM2.js";
24
26
  import "./chunk-JRGFKVAZ.js";
@@ -33,23 +35,23 @@ import "./chunk-BPMWXTFX.js";
33
35
  import {
34
36
  emitNotice,
35
37
  emitWriteNotice
36
- } from "./chunk-YJHHCWM3.js";
38
+ } from "./chunk-WLMJE3GJ.js";
37
39
  import "./chunk-MEFB5KHA.js";
40
+ import "./chunk-2I4QTOLB.js";
38
41
  import {
39
42
  toMoney
40
- } from "./chunk-WH7OWT6G.js";
43
+ } from "./chunk-U2DZISAH.js";
41
44
  import {
42
45
  PRODUCTION_ORIGIN,
43
46
  external_exports,
44
47
  loadRawConfig,
45
48
  resolveSettings
46
- } from "./chunk-BBVUVBUO.js";
47
- import "./chunk-BFFM2WFK.js";
49
+ } from "./chunk-AR7U7BRG.js";
50
+ import "./chunk-NRQMOVKM.js";
48
51
  import {
49
52
  CliError
50
- } from "./chunk-OCBHUHWB.js";
53
+ } from "./chunk-JLEF5WHM.js";
51
54
  import "./chunk-2BKS2FVE.js";
52
- import "./chunk-7WEQQJLG.js";
53
55
  import "./chunk-ZXTAQYNA.js";
54
56
 
55
57
  // src/lib/session-key.ts
@@ -293,4 +295,4 @@ async function pollForFunds(ctx, desc, rpcUrl, startBalance, opts) {
293
295
  export {
294
296
  runFund
295
297
  };
296
- //# sourceMappingURL=fund-A54P2QFK.js.map
298
+ //# sourceMappingURL=fund-I5COXPEJ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n","import { execFile } from 'node:child_process';\n\n/**\n * Open a URL in the platform's default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.',\n );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,IAAM,gBAAgB,iBACnB,OAAO;AAAA,EACN,KAAK,iBAAE,QAAQ,IAAI;AAAA,EACnB,KAAK,iBAAE,QAAQ,OAAO;AAAA,EACtB,GAAG,iBAA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F;AACA,QAAM,IAAI;AAAA,IACR;AAAA,IACA,iCAAiC,MAAM,GAAG,SAAS,SAAY,KAAK,IAAI,MAAM,EAAE;AAAA,IAChF,EAAE,KAAK,mDAAmD;AAAA,EAC5D;AACF;AAGA,SAAS,UAAU,MAAmC;AACpD,MAAI,OAAO,SAAS,YAAY,SAAS,KAAM,QAAO;AACtD,QAAM,MAAO,KAA6B;AAC1C,MAAI,OAAO,QAAQ,YAAY,QAAQ,KAAM,QAAO;AACpD,QAAM,OAAQ,IAA2B;AACzC,SAAO,OAAO,SAAS,WAAW,OAAO;AAC3C;AAEA,eAAe,mBACb,MACA,QAC6B;AAC7B,MAAI;AACF,WAAO,MAAM,eAAe,KAAK,SAA0B,MAAM;AAAA,EACnE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASA,eAAe,aACb,KACA,MACA,QACA,cACA,MAC6B;AAC7B,QAAM,QACJ,KAAK,UAAU,CAAC,OAAe,IAAI,QAAc,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACvF,QAAM,WAAW,KAAK,kBAAkB;AACxC,QAAM,WAAW,KAAK,IAAI,KAAK,KAAK,iBAAiB;AACrD,aAAW,IAAI,IAAI,yEAAyE;AAAA,IAC1F,MAAM,IAAI,MAAM;AAAA,EAClB,CAAC;AACD,SAAO,KAAK,IAAI,IAAI,UAAU;AAC5B,UAAM,MAAM,QAAQ;AACpB,UAAM,UAAU,MAAM,mBAAmB,MAAM,MAAM;AACrD,QAAI,YAAY,UAAa,UAAU,aAAc,QAAO;AAAA,EAC9D;AACA,SAAO;AACT;","names":["webcrypto","subtle","webcrypto"]}
1
+ {"version":3,"sources":["../src/lib/session-key.ts","../src/lib/session-present.ts","../src/lib/open-url.ts","../src/commands/fund.ts"],"sourcesContent":["import { webcrypto } from 'node:crypto';\nimport { sessionPath } from './paths';\nimport { writeFileAtomic } from './atomic-json';\nimport { buildSiwxHeader } from './siwx';\nimport { originOf } from './url';\nimport {\n isSessionUsable,\n loadSessionFile,\n signWithSession,\n type SessionFile,\n type SessionKeyDeps,\n type SessionScope,\n type SignableRequest,\n} from './session-present';\nimport type { TenjinSigner } from './wallet/provider';\n\n/**\n * Session-key delegation (RFC 9421 signed HTTP, RFC 9530-shaped Content-Digest),\n * verified byte-for-byte against the live \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35).\n *\n * The point: a plain SIWX write burns a single-use nonce, so every write needs a\n * fresh WALLET signature. A session key trades that for ONE wallet signature per\n * session: generate a P-256 keypair, wallet-sign a SIWX message binding its\n * pubkey/exp/scope, then sign each subsequent write with the P-256 key (no wallet\n * popup) until the delegation expires. The delegated key is short-lived (≤24h,\n * server-clamped) and cached 0600, address-bound so a wallet change invalidates it.\n *\n * This module is the MINT half — everything that needs a wallet signer, i.e.\n * `establishSession`, the cache writer, and the two `WriteAuth` implementations.\n * The present-only half (load a file, sign one request with it) lives in\n * `session-present.ts` and is re-exported below, so `posts-api`/`publish`/`edit`\n * keep importing one module while a caller that only wants to present a live\n * delegation — `read`, on the reuse path — imports that half alone and touches\n * no keystore. Do not move a signer-touching function down into\n * `session-present.ts`: that free reuse path is what it buys.\n *\n * A minted delegation is a wallet-derived credential, so it is bound to the\n * ORIGIN it was minted against and every presenter re-checks that binding.\n *\n * Never hand-rolls crypto: P-256 keygen is node:crypto webcrypto (subtle) and the\n * wallet delegation reuses the siwx.ts seam.\n */\n\nexport {\n contentDigest,\n isSessionPresentable,\n readSessionFile,\n isSessionUsable,\n keyidFor,\n loadSessionFile,\n scopeSatisfies,\n signatureBase,\n signatureParams,\n signWithSession,\n targetUri,\n} from './session-present';\nexport type {\n SessionFile,\n SessionFileState,\n SessionKeyDeps,\n SessionScope,\n SignableRequest,\n SignatureParamsInput,\n} from './session-present';\n\n/**\n * The chain a session delegation is signed over. Writes require Base mainnet per\n * the server's SIWX chain constraint, and a session covers reads and writes\n * alike, so there is exactly ONE session chain id rather than a per-caller\n * choice: the read path and the write path must mint against the same chain or\n * the file they share would flip between two delegations.\n */\nexport const SESSION_CHAIN_ID = 'eip155:8453';\n\nconst SESSION_TTL_MS = 24 * 60 * 60 * 1000; // 24h; the server clamps to ≤24h.\n\n/**\n * The write-auth seam a posts client signs through. `headersFor` attaches the\n * signature headers (establishing the session lazily on first use); `recover`\n * reacts to a 401 by returning whether a retry is worthwhile.\n */\nexport interface WriteAuth {\n headersFor(req: SignableRequest): Promise<Record<string, string>>;\n /** React to a write's 401 `code`; true ⇒ the next headersFor retry may succeed. */\n recover(code: string | undefined): Promise<boolean>;\n}\n\nexport interface SessionKeyConfig {\n signer: TenjinSigner;\n baseUrl: string;\n chainId: string;\n dataDir: string;\n /**\n * The scope this session is minted at, and the scope a cached session must\n * cover to be reused. Required, not defaulted: over-granting silently is the\n * failure mode worth making impossible, so every caller states what it needs.\n */\n scope: SessionScope;\n}\n\nconst subtle = webcrypto.subtle;\n\nfunction generateP256KeyPair(): Promise<webcrypto.CryptoKeyPair> {\n return subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, [\n 'sign',\n 'verify',\n ]) as Promise<webcrypto.CryptoKeyPair>;\n}\n\n/** base64url (no padding) of raw bytes — the pubkey/keyid encoding. */\nfunction toBase64Url(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64url');\n}\n\n/** The three URNs bound into the delegation's SIWX `resources` array (D35). */\nexport function delegationResources(\n publicKeyRaw: string,\n expIso: string,\n scope: SessionScope,\n): string[] {\n return [\n `urn:tenjin:session:pubkey:p256:${publicKeyRaw}`,\n `urn:tenjin:session:exp:${expIso}`,\n `urn:tenjin:session:scope:${scope}`,\n ];\n}\n\n/**\n * Establish a session with ONE wallet signature: generate a P-256 keypair, bind\n * its pubkey/exp/scope into a SIWX message, wallet-sign it, and cache the result\n * 0600 address-bound. The returned file's `delegation` is the constant\n * `Tenjin-Session-Delegation` header for the session's life.\n */\nexport async function establishSession(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): Promise<SessionFile> {\n const now = deps.now ?? Date.now;\n const pair = await generateP256KeyPair();\n const rawPub = new Uint8Array(await subtle.exportKey('raw', pair.publicKey));\n const publicKeyRaw = toBase64Url(rawPub);\n const jwk = (await subtle.exportKey('jwk', pair.privateKey)) as SessionFile['privateKeyJwk'];\n\n const expIso = new Date(now() + SESSION_TTL_MS).toISOString();\n const delegation = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n ttlMs: SESSION_TTL_MS,\n statement: 'Delegate a Tenjin session key.',\n resources: delegationResources(publicKeyRaw, expIso, config.scope),\n });\n\n const file: SessionFile = {\n address: config.signer.address.toLowerCase(),\n origin: originOf(config.baseUrl),\n delegation,\n exp: expIso,\n scope: config.scope,\n publicKeyRaw,\n privateKeyJwk: jwk,\n };\n await saveSessionFile(config.dataDir, file);\n return file;\n}\n\n// ---------------------------------------------------------------------------\n// Cache writes (0600, address-bound). The reader lives in session-present.\n// ---------------------------------------------------------------------------\n\nexport async function saveSessionFile(dir: string, file: SessionFile): Promise<void> {\n await writeFileAtomic(sessionPath(dir), `${JSON.stringify(file, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n}\n\n// ---------------------------------------------------------------------------\n// The WriteAuth implementation: lazy establish, cache reuse, 401 recovery.\n// ---------------------------------------------------------------------------\n\n/** How each 401 `code` maps to recovery (per the llms-full.txt policy section). */\ntype Recovery = 'resign' | 'reestablish' | 'fatal';\n\nexport function recoveryFor(code: string | undefined): Recovery {\n switch (code) {\n case 'proof_expired':\n // The per-request signature is too old; just re-sign (no wallet).\n return 'resign';\n case 'session_expired':\n case 'proof_revoked':\n case 'insufficient_scope':\n // The delegation itself is gone/insufficient; re-establish (one wallet sig).\n return 'reestablish';\n case 'session_key_unbound':\n // keyid ≠ the delegation-bound key: retrying cannot fix it.\n return 'fatal';\n default:\n return 'fatal';\n }\n}\n\n/**\n * A session-key WriteAuth: mints (or loads) the delegation on first use and signs\n * every write with the P-256 key — so a returning agent never wallet-signs again\n * until the session expires. On a 401 it re-signs or re-establishes per the code.\n */\nexport function createSessionKeyAuth(\n config: SessionKeyConfig,\n deps: SessionKeyDeps = {},\n): WriteAuth {\n const now = deps.now ?? Date.now;\n let cached: SessionFile | null = null;\n let forceReestablish = false;\n\n const ensure = async (): Promise<SessionFile> => {\n if (\n !forceReestablish &&\n cached !== null &&\n isSessionUsable(cached, config.signer.address, now(), config.scope, originOf(config.baseUrl))\n ) {\n return cached;\n }\n if (!forceReestablish) {\n const onDisk = await loadSessionFile(config.dataDir);\n const origin = originOf(config.baseUrl);\n if (\n onDisk !== null &&\n isSessionUsable(onDisk, config.signer.address, now(), config.scope, origin)\n ) {\n cached = onDisk;\n return cached;\n }\n }\n cached = await establishSession(config, deps);\n forceReestablish = false;\n return cached;\n };\n\n return {\n async headersFor(req) {\n const file = await ensure();\n return signWithSession(file, req, deps);\n },\n async recover(code) {\n const recovery = recoveryFor(code);\n if (recovery === 'fatal') return false;\n if (recovery === 'reestablish') {\n cached = null;\n forceReestablish = true;\n }\n // 'resign' needs no state change: the next headersFor mints a fresh\n // created/nonce over the same (still-valid) delegation.\n return true;\n },\n };\n}\n\n/**\n * The plain-SIWX fallback (no session): every write carries its own fresh\n * wallet-signed `SIGN-IN-WITH-X` header. Used when session establishment is\n * disabled; a burned/stale nonce (401) is recovered by re-signing.\n */\nexport function createSiwxAuth(config: SessionKeyConfig): WriteAuth {\n return {\n async headersFor() {\n const header = await buildSiwxHeader(config.signer, {\n baseUrl: config.baseUrl,\n chainId: config.chainId,\n });\n return { 'SIGN-IN-WITH-X': header };\n },\n async recover(code) {\n // A single-use nonce burns on every write; a stale/burned nonce (or an\n // expired proof) is recovered by re-signing with a fresh nonce + issuedAt.\n return code === 'nonce_already_used' || code === 'invalid_proof' || code === 'proof_expired';\n },\n };\n}\n","import { createHash, randomBytes, webcrypto } from 'node:crypto';\nimport { readFile, stat } from 'node:fs/promises';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport { hasCode } from './errno';\nimport { sessionPath } from './paths';\n\n/**\n * The PRESENT half of the session-key layer: load a delegation that already\n * exists on disk and sign one request with it. Nothing here can MINT one — every\n * function that needs a wallet signer lives in `session-key.ts`, which imports\n * this module and re-exports it.\n *\n * The split earns its keep on the reuse path: presenting a live delegation costs\n * no keystore decryption, so `tenjin read` reaches this half alone whenever one\n * is cached and only falls through to the mint half (and one passphrase) when\n * there is none. Neither half says anything about what an already-minted\n * delegation is worth to whoever holds it — see `origin` below, and the tier\n * note in `permissions.ts`.\n *\n * Byte-exact against the \"Auth — session keys\" contract in\n * https://tenjin.blog/llms-full.txt (D35). P-256 signing is node:crypto webcrypto.\n */\n\n/** The delegation scopes the server recognizes. */\nexport type SessionScope = 'read' | 'read+write';\n\n/**\n * Does a cached session's scope cover what this run needs? Wider covers narrower,\n * so a cached `read+write` serves a `read` run with no new wallet signature; the\n * reverse must not hold.\n */\nexport function scopeSatisfies(cached: string, required: SessionScope): boolean {\n if (cached === required) return true;\n return required === 'read' && cached === 'read+write';\n}\n\n/** Re-establish this long before `exp` so a signed request cannot expire in flight. */\nconst EXP_SKEW_MS = 60_000;\n\n/**\n * The P-256 private key's SHAPE. This catches a structurally wrong file — `{}`, a\n * missing `d`, the wrong curve — at the load boundary, so those never reach the\n * crypto at all.\n *\n * It is deliberately not the whole guard, because it cannot be: a JWK can satisfy\n * every field here and still be cryptographically invalid (a 31-byte `d`, `d = 0`,\n * `d = n`, `x`/`y` off the curve), and nothing short of reimplementing P-256\n * validation in zod would catch that. The import site translates what WebCrypto\n * throws instead — see `importSigningKey` — so the two together are what make a\n * bad key a handled state rather than a crash.\n */\nconst P256JwkSchema = z\n .object({\n kty: z.literal('EC'),\n crv: z.literal('P-256'),\n d: z.string().min(1),\n x: z.string().min(1),\n y: z.string().min(1),\n })\n .passthrough();\n\n/** The persisted session: the wallet-signed delegation plus the P-256 key material. */\nconst SessionFileSchema = z.object({\n /** Lowercased wallet address this delegation is bound to. */\n address: z.string(),\n /**\n * The `scheme://host[:port]` this delegation was minted against.\n *\n * Load-bearing, not bookkeeping. The delegation is a wallet-derived credential\n * and `--base-url` rides every leaf command, including the always-safe `read`.\n * Without this field one auto-allowed `tenjin read <url> --base-url <attacker>`\n * hands the credential to a host the agent chose, with the origin guard\n * satisfied because the same flag set both sides of it. Binding the file to its\n * origin closes that however the base URL arrived — flag, environment, or a\n * rewritten config. It also makes a stale file after a prod/localhost/preview\n * switch fail closed rather than present a delegation that cannot verify.\n */\n origin: z.string(),\n /** The constant base64 SIWX `Tenjin-Session-Delegation` header value. */\n delegation: z.string(),\n /** Delegation expiry (ISO 8601); a request is never signed at/after this. */\n exp: z.string(),\n scope: z.string(),\n /** base64url raw 65-byte uncompressed P-256 point (0x04||X||Y). */\n publicKeyRaw: z.string(),\n privateKeyJwk: P256JwkSchema,\n});\nexport type SessionFile = z.infer<typeof SessionFileSchema>;\n\n/**\n * A request to sign. The body is part of the METHOD: a bodied request must carry\n * the exact bytes Content-Digest covers, and a GET or DELETE has no body to\n * cover at all, so content-digest drops out of the covered set. As a union,\n * \"GET with a body\" and \"PUT without one\" are both unrepresentable.\n */\nexport type SignableRequest =\n { method: 'GET' | 'DELETE'; url: string } | { method: 'POST' | 'PUT'; url: string; body: string };\n\nexport interface SessionKeyDeps {\n /** Clock seam (ms since epoch). */\n now?: () => number;\n /** Per-request nonce (≥16-byte CSPRNG hex). */\n nonce?: () => string;\n}\n\nconst subtle = webcrypto.subtle;\n\n// ---------------------------------------------------------------------------\n// Byte-exact RFC 9421 primitives (the wire contract; unit-tested against fixtures).\n// ---------------------------------------------------------------------------\n\nfunction toBase64(bytes: Uint8Array): string {\n return Buffer.from(bytes).toString('base64');\n}\n\n/** `sha-256=:<base64 SHA-256(body)>:` — RFC 9530 Content-Digest over the body. */\nexport function contentDigest(body: string): string {\n const hash = createHash('sha256').update(body, 'utf8').digest();\n return `sha-256=:${hash.toString('base64')}:`;\n}\n\n/** The `@target-uri` derivation: scheme://host[:port]path[?query], nothing more. */\nexport function targetUri(url: string): string {\n const u = new URL(url);\n return `${u.protocol}//${u.host}${u.pathname}${u.search}`;\n}\n\nexport interface SignatureParamsInput {\n method: 'POST' | 'PUT' | 'GET' | 'DELETE';\n url: string;\n /** Present ⇒ the request has a body and content-digest joins the covered set. */\n contentDigest?: string;\n created: number;\n nonce: string;\n keyid: string;\n}\n\n/**\n * The `@signature-params` value (also the `Signature-Input` value after the\n * `tenjin=` label), verbatim per llms-full.txt. `content-digest` is covered ONLY\n * on a bodied request.\n */\nexport function signatureParams(input: SignatureParamsInput): string {\n const covered =\n input.contentDigest !== undefined\n ? '\"@method\" \"@target-uri\" \"content-digest\"'\n : '\"@method\" \"@target-uri\"';\n return `(${covered});created=${input.created};nonce=\"${input.nonce}\";keyid=\"${input.keyid}\";alg=\"ecdsa-p256-sha256\"`;\n}\n\n/** The UTF-8 signing base: the LF-joined canonical block, with NO trailing newline. */\nexport function signatureBase(input: SignatureParamsInput): string {\n const params = signatureParams(input);\n const lines = [\n `\"@method\": ${input.method.toUpperCase()}`,\n `\"@target-uri\": ${targetUri(input.url)}`,\n ...(input.contentDigest !== undefined ? [`\"content-digest\": ${input.contentDigest}`] : []),\n `\"@signature-params\": ${params}`,\n ];\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Key import + per-request signing (generation lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Import the cached key, translating WebCrypto's raw DOMException into the error\n * contract every other failure here uses.\n *\n * Without this, a schema-valid but cryptographically invalid `d` (too short, zero,\n * ≥ n) or an off-curve point escapes as an exit-1 INTERNAL reading `Invalid\n * keyData`, with no `fix` — and it escapes from `publish` and `edit` too, which\n * have no equivalent of read's fall-through. Translating at the ONE place the key\n * becomes a key means every caller degrades the same way, and the fix line names\n * the one action that resolves it.\n */\nasync function importSigningKey(jwk: Record<string, unknown>): Promise<webcrypto.CryptoKey> {\n try {\n return await subtle.importKey(\n 'jwk',\n jwk as webcrypto.JsonWebKey,\n { name: 'ECDSA', namedCurve: 'P-256' },\n false,\n ['sign'],\n );\n } catch (err) {\n throw new CliError('INTERNAL', 'The cached session key is not a usable P-256 key.', {\n fix: 'Delete the session cache (`~/.tenjin/session.json`); the next read or write mints a fresh one.',\n cause: err,\n });\n }\n}\n\n/** P-256/SHA-256, IEEE-P1363 64-byte r||s. */\nasync function signBase(jwk: Record<string, unknown>, base: string): Promise<string> {\n const key = await importSigningKey(jwk);\n const sig = await subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, Buffer.from(base, 'utf8'));\n return toBase64(new Uint8Array(sig));\n}\n\n/** keyid = `p256:<base64url pubkey>`, the delegation-bound identifier. */\nexport function keyidFor(publicKeyRaw: string): string {\n return `p256:${publicKeyRaw}`;\n}\n\n/** Produce the RFC 9421 headers for `req`, signed by the loaded session key. */\nexport async function signWithSession(\n file: SessionFile,\n req: SignableRequest,\n deps: SessionKeyDeps = {},\n): Promise<Record<string, string>> {\n const now = deps.now ?? Date.now;\n const nonce = deps.nonce ?? (() => randomBytes(16).toString('hex'));\n // Signing a digest of \"\" would cover bytes the request never sends. Keyed on\n // the presence of a body rather than on the method list, so a bodiless method\n // added to the union above needs no second edit here to stay bodiless.\n const digest = 'body' in req ? contentDigest(req.body) : undefined;\n const params: SignatureParamsInput = {\n method: req.method,\n url: req.url,\n ...(digest !== undefined ? { contentDigest: digest } : {}),\n created: Math.floor(now() / 1000),\n nonce: nonce(),\n keyid: keyidFor(file.publicKeyRaw),\n };\n const signature = await signBase(file.privateKeyJwk, signatureBase(params));\n return {\n 'Tenjin-Session-Delegation': file.delegation,\n 'Signature-Input': `tenjin=${signatureParams(params)}`,\n Signature: `tenjin=:${signature}:`,\n ...(digest !== undefined ? { 'Content-Digest': digest } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Cache reads (the writer lives with the mint half).\n// ---------------------------------------------------------------------------\n\n/**\n * Why a session file is not usable, kept distinguishable for `doctor`.\n * `loadSessionFile` collapses these to null — to a caller that can re-establish\n * they are all the same instruction — but `loosened` and `corrupt` are TAMPER\n * signals, and a diagnostic verb that reports them as \"no session key\" hides the\n * signal at the one moment someone is looking for it.\n */\nexport type SessionFileState =\n | { kind: 'absent' }\n /** `mode` is the FULL permission bits, not the offending subset: a tamper\n * report that prints a mode the file does not have is worse than no number. */\n | { kind: 'loosened'; mode: number }\n | { kind: 'corrupt'; reason: string }\n /** An OLDER CLI's file, missing a field the shape has since required. Unusable\n * and re-mintable like an absent one, so NOT the tamper signal `corrupt` is. */\n | { kind: 'outdated'; field: string }\n | { kind: 'unreadable'; message: string; cause: unknown }\n | { kind: 'ok'; file: SessionFile };\n\n/**\n * Fields an OLDER CLI's file can legitimately lack. An allowlist, not \"any missing\n * key\": a file with no `privateKeyJwk.d` cannot sign and is broken whoever wrote\n * it. Add a name when the schema grows a required field, never to quiet a test.\n */\nconst LATER_ADDED_FIELDS: readonly string[] = ['origin'];\n\nexport async function readSessionFile(dir: string): Promise<SessionFileState> {\n const path = sessionPath(dir);\n // Fail closed on a loosened cache (ssh's posture for a private key): the file is\n // written 0600, so a now group- or world-readable one was touched out of band.\n // No-op on win32, which has no unix mode.\n if (process.platform !== 'win32') {\n try {\n const mode = (await stat(path)).mode & 0o777;\n if ((mode & 0o077) !== 0) return { kind: 'loosened', mode };\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n }\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', message: messageOf(err), cause: err };\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch {\n return { kind: 'corrupt', reason: 'not valid JSON' };\n }\n const parsed = SessionFileSchema.safeParse(json);\n if (!parsed.success) {\n const issues = parsed.error.issues;\n const legacy = (i: (typeof issues)[number]): boolean =>\n LATER_ADDED_FIELDS.includes(i.path.join('.')) && !hasPath(json, i.path);\n // Report the first NON-legacy issue when there is one: a file missing both\n // `origin` and its private scalar is corrupt because of the scalar, and naming\n // the benign field points the operator at the wrong thing.\n const issue = issues.find((i) => !legacy(i)) ?? issues[0];\n const field = issue?.path.join('.');\n const message = issue?.message ?? 'schema mismatch';\n // EVERY failure must be an allowlisted later field the file genuinely lacks.\n // One legacy omission cannot vouch for the rest of the file, and zod reports in\n // schema order, so the first issue alone would let a broken key ride in.\n const legacyOnly = issues.length > 0 && issues.every(legacy);\n if (legacyOnly && field !== undefined) return { kind: 'outdated', field };\n // Field-qualified: the message alone names none. zod never echoes the received\n // VALUE, so no key material reaches this string.\n return {\n kind: 'corrupt',\n reason: field !== undefined && field.length > 0 ? `${field}: ${message}` : message,\n };\n }\n return { kind: 'ok', file: parsed.data };\n}\n\n/** Does `value` actually carry the key at `path`, whatever it holds there? */\nfunction hasPath(value: unknown, path: readonly PropertyKey[]): boolean {\n let cur: unknown = value;\n for (const key of path) {\n if (typeof cur !== 'object' || cur === null) return false;\n if (!Object.hasOwn(cur, key)) return false;\n cur = (cur as Record<PropertyKey, unknown>)[key];\n }\n return true;\n}\n\n/** The session to present, or null for every reason there is not one. */\nexport async function loadSessionFile(dir: string): Promise<SessionFile | null> {\n const state = await readSessionFile(dir);\n if (state.kind === 'ok') return state.file;\n // An I/O failure is the one state a caller must not silently re-establish\n // through: the path exists and could not be read, so treating it as \"no\n // session\" would re-mint over a file that may be perfectly good.\n if (state.kind === 'unreadable') {\n throw new CliError('INTERNAL', `Could not read the session cache at ${sessionPath(dir)}`, {\n fix: `Check file permissions on ${sessionPath(dir)}, or delete it to re-establish.`,\n cause: state.cause,\n });\n }\n return null;\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Is this cached session usable for a run against `origin` — scope, expiry, and\n * the deployment it was minted for. No address comparison: `read` holds no\n * wallet, so it has nothing to compare against, and that costs nothing because a\n * foreign-wallet file simply does not entitle. Callers that DO hold a signer use\n * `isSessionUsable`, which adds the binding check.\n */\nexport function isSessionPresentable(\n file: SessionFile,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.origin !== origin) return false;\n if (!scopeSatisfies(file.scope, required)) return false;\n const expMs = Date.parse(file.exp);\n if (!Number.isFinite(expMs)) return false;\n return now < expMs - EXP_SKEW_MS;\n}\n\n/** `isSessionPresentable` plus the wallet binding, so a wallet swap invalidates. */\nexport function isSessionUsable(\n file: SessionFile,\n address: string,\n now: number,\n required: SessionScope,\n origin: string,\n): boolean {\n if (file.address !== address.toLowerCase()) return false;\n return isSessionPresentable(file, now, required, origin);\n}\n","import { execFile } from 'node:child_process';\n\n/**\n * Open a URL in the platform's default browser, best-effort. Follows the\n * passphrase.ts subprocess rules: an argv array (never a shell), a hard\n * timeout, and failure as a return value rather than a throw — callers print\n * the URL first, so a machine without an opener degrades to copy/paste.\n * Windows uses rundll32's FileProtocolHandler because `start` exists only\n * inside cmd.exe, and spawning a shell around an attacker-influenced string is\n * the injection shape this module exists to avoid.\n */\n\nexport interface OpenUrlOptions {\n platform?: NodeJS.Platform;\n execFileImpl?: typeof execFile;\n}\n\nconst OPEN_TIMEOUT_MS = 5000;\n\nexport function openerFor(platform: NodeJS.Platform): { cmd: string; args: string[] } {\n if (platform === 'darwin') return { cmd: 'open', args: [] };\n if (platform === 'win32') return { cmd: 'rundll32', args: ['url.dll,FileProtocolHandler'] };\n return { cmd: 'xdg-open', args: [] };\n}\n\nexport async function openInBrowser(url: string, opts: OpenUrlOptions = {}): Promise<boolean> {\n const { cmd, args } = openerFor(opts.platform ?? process.platform);\n const run = opts.execFileImpl ?? execFile;\n return await new Promise((resolve) => {\n run(cmd, [...args, url], { timeout: OPEN_TIMEOUT_MS, windowsHide: true }, (err) =>\n resolve(err === null),\n );\n });\n}\n","import { getAddress, isAddress } from 'viem';\nimport { CliError } from '../lib/errors';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { httpRequest, fetchFailureToCliError, type HttpRequestOptions } from '../lib/http';\nimport { buildSiwxHeader, SIWX_HEADER } from '../lib/siwx';\nimport { SESSION_CHAIN_ID } from '../lib/session-key';\nimport {\n describeWallet,\n resolveWalletProvider,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { toMoney } from '../lib/money';\nimport { emitNotice, emitWriteNotice } from '../lib/output';\nimport { openInBrowser } from '../lib/open-url';\nimport { PRODUCTION_ORIGIN } from '../lib/production-origin';\nimport type { CommandContext, CommandResult } from '../context';\n\n/*\n * `tenjin wallet fund`: card-fund THIS wallet via Coinbase Onramp. The CLI signs a\n * SIWX proof with the wallet's own key and asks the Tenjin backend to mint a\n * Coinbase-hosted checkout URL for that same address (the server refuses any\n * other address, per Coinbase's onboarding-verified auth model). The money\n * moves entirely on Coinbase's side; the minted session grants no spending\n * power over the wallet. Two Coinbase properties shape the UX here: the URL is\n * single-use and expires in ~5 minutes (mint fresh per run, open immediately,\n * never persist), and it is bound to this machine's public IP at mint time, so\n * it must be opened in a browser on this machine/network.\n */\n\n/** The only host a minted checkout URL may point at; anything else is refused unopened. */\nconst CHECKOUT_HOST = 'pay.coinbase.com';\n/**\n * fund talks to production, full stop (owner decision, 2026-08-12): the mint\n * signs with the wallet key, so this path takes no override -- not `--base-url`,\n * not the env, not config. Cutting the surface entirely is what lets the verb\n * sit in the free allowlist tier with nothing to caveat.\n */\nconst FUND_ORIGIN = PRODUCTION_ORIGIN;\n/** Matches the server's presetAmount bound (app/api/cdp/session bodySchema). */\nconst MAX_PRESET_USD = 100_000;\nconst POLL_INTERVAL_MS = 5_000;\nconst POLL_TIMEOUT_MS = 600_000;\n\n/**\n * Why the run is not reporting an arrival, kept distinct in the envelope because\n * three different outcomes otherwise collapse into `funded: false`: the run never\n * waited, it wanted to but could not read a baseline balance, or it waited and\n * the deadline won. Only `timed-out` says anything about the purchase.\n */\nexport type FundPollStatus = 'skipped' | 'unavailable' | 'timed-out' | 'arrived';\n\nexport interface FundOptions extends ResolveWalletProviderOptions {\n /** Optional USD preset forwarded to Coinbase (clamped upward to its own floor there). */\n amountUsd?: string;\n /** Skip the browser open (still prints the URL). */\n open?: boolean;\n /** Poll the balance after issuing the link. Defaults to ON at a TTY, OFF otherwise. */\n wait?: boolean;\n fetchImpl?: typeof fetch;\n openUrl?: typeof openInBrowser;\n /** Poll seams so tests never sleep for real. */\n sleep?: (ms: number) => Promise<void>;\n pollIntervalMs?: number;\n pollTimeoutMs?: number;\n}\n\nexport async function runFund(ctx: CommandContext, opts: FundOptions = {}): Promise<CommandResult> {\n const preset = parsePreset(opts.amountUsd);\n\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n const address = checksummed(desc.address);\n const signer = await provider.getSigner();\n\n const config = await loadRawConfig(ctx.dataDir);\n const settings = resolveSettings({ config, flags: {}, env: process.env });\n const baseUrl = FUND_ORIGIN;\n const rpcUrl = settings.rpcUrl.value;\n\n // Waiting is an INTERACTIVE posture: a human is standing at the terminal with\n // a browser open. Piped, --json, and MCP runs default to not waiting, because\n // the envelope carrying the link is written only after runFund returns, and a\n // link that expires in ~5 minutes is worthless after a 10-minute poll.\n const shouldWait = opts.wait ?? ctx.io.isTTY;\n\n // Read the balance BEFORE minting so the poll has a baseline; an RPC flake\n // here only disables the wait, it never blocks funding.\n const startBalance = shouldWait ? await balanceOrUndefined(desc, rpcUrl) : undefined;\n\n const siwxHeader = await buildSiwxHeader(signer, { baseUrl, chainId: SESSION_CHAIN_ID });\n const request: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: ctx.flags.timeout,\n headers: { [SIWX_HEADER]: siwxHeader },\n jsonBody: {\n mode: 'onramp',\n address,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n },\n ...(opts.fetchImpl !== undefined ? { fetchImpl: opts.fetchImpl } : {}),\n };\n const res = await httpRequest(`${baseUrl}/api/cdp/session`, request);\n if (!res.ok) {\n throw fetchFailureToCliError(res, {\n fix: 'Check your network, then retry.',\n });\n }\n const url = checkoutUrlFrom(res.status, res.json);\n\n // The link goes out on EVERY surface and before any waiting: it is single-use\n // with a ~5 minute expiry, and the stdout envelope that also carries it is\n // written only after this function returns. A piped or agent-driven run is\n // exactly the case that must not get the link after it has died, so these\n // three lines are write-notices (stderr, no TTY gate, no --json gate) rather\n // than human-mode notices. stdout stays exactly one JSON object.\n emitWriteNotice(ctx.io, `Coinbase Onramp checkout for ${address}:`);\n emitWriteNotice(ctx.io, ` ${url}`);\n emitWriteNotice(\n ctx.io,\n 'The link is single-use, expires in ~5 minutes, and only works in a browser on this machine (it is bound to this network). A Coinbase account is required.',\n );\n\n let opened = false;\n if (opts.open !== false && ctx.io.isTTY) {\n opened = await (opts.openUrl ?? openInBrowser)(url);\n emitNotice(\n ctx.io,\n opened ? 'Opened in your default browser.' : 'Could not open a browser; use the link above.',\n { json: ctx.flags.json },\n );\n }\n\n const funded =\n shouldWait && startBalance !== undefined\n ? await pollForFunds(ctx, desc, rpcUrl, startBalance, opts)\n : undefined;\n if (funded !== undefined) {\n emitWriteNotice(ctx.io, 'USDC arrived - you can close the checkout tab.');\n }\n const pollStatus: FundPollStatus = !shouldWait\n ? 'skipped'\n : startBalance === undefined\n ? 'unavailable'\n : funded !== undefined\n ? 'arrived'\n : 'timed-out';\n\n const balanceAtomic = funded ?? startBalance;\n return {\n data: {\n address,\n checkoutUrl: url,\n opened,\n ...(preset !== undefined ? { presetAmount: preset } : {}),\n funded: funded !== undefined,\n pollStatus,\n ...(balanceAtomic !== undefined ? { balance: toMoney(balanceAtomic.toString()) } : {}),\n },\n humanLines:\n funded !== undefined\n ? [`Funded: balance is now ${toMoney(funded.toString()).usd} USDC on Base.`]\n : [\n 'Checkout link issued (printed above).',\n ...(pollStatus === 'unavailable'\n ? ['Could not read the balance to wait on it; the link is unaffected.']\n : []),\n 'Confirm arrival later with `tenjin wallet balance`.',\n ],\n };\n}\n\n/**\n * The route parses the destination with strict EIP-55 (`checksummedAddress`) but\n * the local wallet store accepts any casing, so an imported or hand-edited wallet\n * file would earn an unactionable 400 on a purely local condition. Normalize here\n * instead, as `send` does for its recipient.\n */\nfunction checksummed(address: string): string {\n if (!isAddress(address, { strict: false })) {\n throw new CliError(\n 'USAGE',\n `The active wallet address is not a valid EVM address: ${address}`,\n {\n fix: 'Check the wallet file, or create a fresh wallet with `tenjin wallet create`.',\n },\n );\n }\n return getAddress(address);\n}\n\nfunction parsePreset(raw: string | undefined): number | undefined {\n if (raw === undefined) return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n) || n <= 0 || n > MAX_PRESET_USD) {\n throw new CliError('USAGE', `Amount must be a positive USD number up to ${MAX_PRESET_USD}.`, {\n fix: 'Example: tenjin wallet fund 5',\n });\n }\n return n;\n}\n\n/**\n * Map the mint response to either the checkout URL or the coded refusal. The\n * URL is opened by this process, so it is validated as https on Coinbase's\n * checkout host before anything else sees it: a compromised or misconfigured\n * server must not be able to steer the user's browser anywhere else.\n */\nfunction checkoutUrlFrom(status: number, json: unknown): string {\n if (status === 200) {\n const url =\n typeof json === 'object' && json !== null ? (json as { url?: unknown }).url : undefined;\n if (typeof url === 'string') {\n let parsed: URL | undefined;\n try {\n parsed = new URL(url);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && parsed.protocol === 'https:' && parsed.host === CHECKOUT_HOST) {\n return url;\n }\n }\n throw new CliError(\n 'CONTRACT_MISMATCH',\n `The server's checkout URL was missing or not https://${CHECKOUT_HOST}; refusing to open it.`,\n );\n }\n const code = errorCode(json);\n if (status === 403 && code === 'region_not_supported') {\n throw new CliError('REFUSED', 'Coinbase Onramp is not available in your region.');\n }\n // A rejected proof is a local condition (\"retry\" never fixes it): the signed\n // window is clock-relative, and the domain is always the pinned production origin.\n if (status === 401) {\n throw new CliError('REFUSED', 'The funding endpoint rejected the signed proof.', {\n fix: 'Check this machine’s clock, then retry.',\n });\n }\n if (status === 429) {\n throw new CliError('RATE_LIMITED', 'The funding endpoint is rate limited right now.', {\n fix: 'Wait a minute and retry.',\n });\n }\n if (status === 503) {\n throw new CliError(\n 'API_UNREACHABLE',\n 'Production has no Coinbase Onramp configured right now.',\n {\n fix: 'Retry later.',\n },\n );\n }\n throw new CliError(\n 'API_UNREACHABLE',\n `The funding endpoint returned ${status}${code !== undefined ? ` (${code})` : ''}.`,\n { fix: 'Retry; if it persists, check the service status.' },\n );\n}\n\n/** The `error.code` of the withApi failure envelope, when the server sent one. */\nfunction errorCode(json: unknown): string | undefined {\n if (typeof json !== 'object' || json === null) return undefined;\n const err = (json as { error?: unknown }).error;\n if (typeof err !== 'object' || err === null) return undefined;\n const code = (err as { code?: unknown }).code;\n return typeof code === 'string' ? code : undefined;\n}\n\nasync function balanceOrUndefined(\n desc: { address: string },\n rpcUrl: string,\n): Promise<bigint | undefined> {\n try {\n return await getUsdcBalance(desc.address as `0x${string}`, rpcUrl);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Wait for the purchased USDC to land: any balance above the pre-mint baseline\n * counts (Coinbase clamps presets, so an exact-amount check would be wrong).\n * RPC flakes mid-poll are tolerated; the deadline is the only exit besides\n * arrival, and timing out is a normal outcome (the human may still be paying),\n * not an error.\n */\nasync function pollForFunds(\n ctx: CommandContext,\n desc: { address: string },\n rpcUrl: string,\n startBalance: bigint,\n opts: FundOptions,\n): Promise<bigint | undefined> {\n const sleep =\n opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));\n const interval = opts.pollIntervalMs ?? POLL_INTERVAL_MS;\n const deadline = Date.now() + (opts.pollTimeoutMs ?? POLL_TIMEOUT_MS);\n emitNotice(ctx.io, 'Waiting for the USDC to arrive (Ctrl-C is safe; the purchase is not).', {\n json: ctx.flags.json,\n });\n while (Date.now() < deadline) {\n await sleep(interval);\n const balance = await balanceOrUndefined(desc, rpcUrl);\n if (balance !== undefined && balance > startBalance) return balance;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAAA,kBAAiB;;;ACA1B,SAAS,YAAY,aAAa,iBAAiB;AAoDnD,IAA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