tenjin-cli 0.1.0-alpha.17 → 0.1.0-alpha.19

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 (112) hide show
  1. package/README.md +152 -38
  2. package/dist/{_esm-CE7KNONL.js → _esm-OVVGTKHH.js} +4 -4
  3. package/dist/{chunk-5QHHRMRA.js → chunk-2SQEFBAM.js} +4 -3
  4. package/dist/chunk-3KKKB2AQ.js +40 -0
  5. package/dist/chunk-3KKKB2AQ.js.map +1 -0
  6. package/dist/{chunk-LJ4DMVFI.js → chunk-3VYGDRRL.js} +5 -5
  7. package/dist/{chunk-PDA2BVFY.js → chunk-5DOHKQ24.js} +4 -15
  8. package/dist/chunk-5DOHKQ24.js.map +1 -0
  9. package/dist/{chunk-N35E6CM2.js → chunk-6DCELMQA.js} +6 -6
  10. package/dist/{chunk-WXC57XGG.js → chunk-A36LQPHV.js} +1 -1
  11. package/dist/chunk-A36LQPHV.js.map +1 -0
  12. package/dist/{chunk-56MOAIP5.js → chunk-A6CY6BUW.js} +11 -8
  13. package/dist/chunk-A6CY6BUW.js.map +1 -0
  14. package/dist/{chunk-TP4D47BY.js → chunk-AISBL7EY.js} +3 -3
  15. package/dist/{chunk-KK4YGYTV.js → chunk-AMG4SONW.js} +138 -58
  16. package/dist/chunk-AMG4SONW.js.map +1 -0
  17. package/dist/{chunk-AUKDYPPX.js → chunk-BG2EXNAA.js} +7 -6
  18. package/dist/chunk-BG2EXNAA.js.map +1 -0
  19. package/dist/{chunk-O4ZNKFRU.js → chunk-FHBGTOFA.js} +121 -40
  20. package/dist/chunk-FHBGTOFA.js.map +1 -0
  21. package/dist/{chunk-HPWO4O6S.js → chunk-FPUPBQHX.js} +2 -2
  22. package/dist/{chunk-3AUDA53C.js → chunk-KTAW4KGH.js} +6 -5
  23. package/dist/{chunk-J5INH7WB.js → chunk-LSWVVSFX.js} +106 -5
  24. package/dist/chunk-LSWVVSFX.js.map +1 -0
  25. package/dist/chunk-O2JYBOUO.js +47 -0
  26. package/dist/chunk-O2JYBOUO.js.map +1 -0
  27. package/dist/{chunk-5UDD5VSY.js → chunk-PZQRSZJV.js} +2 -2
  28. package/dist/{chunk-5UDD5VSY.js.map → chunk-PZQRSZJV.js.map} +1 -1
  29. package/dist/{chunk-QDD2RN7G.js → chunk-SCAOYGKX.js} +356 -90
  30. package/dist/chunk-SCAOYGKX.js.map +1 -0
  31. package/dist/{chunk-35M3VITA.js → chunk-TDGN476R.js} +60 -7
  32. package/dist/chunk-TDGN476R.js.map +1 -0
  33. package/dist/{chunk-AR7U7BRG.js → chunk-UNV4K45L.js} +12 -18
  34. package/dist/{chunk-AR7U7BRG.js.map → chunk-UNV4K45L.js.map} +1 -1
  35. package/dist/{chunk-MRGADYDD.js → chunk-VFVFVQM6.js} +4 -4
  36. package/dist/{chunk-2JGT3KDW.js → chunk-WUU3BH6G.js} +2 -2
  37. package/dist/{chunk-KUBEYXSO.js → chunk-XDADPAWW.js} +22 -22
  38. package/dist/{chunk-WGQVJM56.js → chunk-XNP6VUAJ.js} +3 -3
  39. package/dist/{chunk-AWQPGIR6.js → chunk-Y66XUXVI.js} +5 -5
  40. package/dist/{chunk-XZOEUYMX.js → chunk-ZDKEU2GF.js} +2 -2
  41. package/dist/{chunk-WLMJE3GJ.js → chunk-ZTFIQC4C.js} +2 -2
  42. package/dist/{cli-VHYYYYXM.js → cli-456F77ZY.js} +33 -28
  43. package/dist/{cli-VHYYYYXM.js.map → cli-456F77ZY.js.map} +1 -1
  44. package/dist/{config-5ADBAAXU.js → config-BLUWOH6S.js} +9 -12
  45. package/dist/{doctor-Q35VQW3S.js → doctor-PS45CR3T.js} +37 -29
  46. package/dist/{doctor-Q35VQW3S.js.map → doctor-PS45CR3T.js.map} +1 -1
  47. package/dist/{fund-GDDPL2BB.js → fund-4SW2ZBWC.js} +18 -17
  48. package/dist/{fund-GDDPL2BB.js.map → fund-4SW2ZBWC.js.map} +1 -1
  49. package/dist/{hook-command-PBERPRE3.js → hook-command-YTV7X333.js} +318 -37
  50. package/dist/hook-command-YTV7X333.js.map +1 -0
  51. package/dist/index.js +2 -2
  52. package/dist/{install-OKDKGUXM.js → install-U4BIDCHH.js} +14 -13
  53. package/dist/{install-wallet-SI4LZ73K.js → install-wallet-EYHELQMG.js} +15 -14
  54. package/dist/{install-wallet-SI4LZ73K.js.map → install-wallet-EYHELQMG.js.map} +1 -1
  55. package/dist/{mcp-XX3WRQEZ.js → mcp-AC4PIXH5.js} +43 -28
  56. package/dist/{mcp-XX3WRQEZ.js.map → mcp-AC4PIXH5.js.map} +1 -1
  57. package/dist/{pay-3SYKHKWJ.js → pay-VJOP6TFT.js} +24 -19
  58. package/dist/{send-LQRKTEJT.js → send-YH75Z6LB.js} +15 -14
  59. package/dist/{send-LQRKTEJT.js.map → send-YH75Z6LB.js.map} +1 -1
  60. package/dist/{status-FFC6FO72.js → status-5CHCDLUE.js} +24 -17
  61. package/dist/status-5CHCDLUE.js.map +1 -0
  62. package/dist/{status-line-SAXSU6CR.js → status-line-CZAZUOAY.js} +6 -6
  63. package/dist/{status-line-wiring-L2WYIYBM.js → status-line-wiring-2ABDVXSJ.js} +4 -4
  64. package/dist/tenjin-daemon.mjs +3 -14
  65. package/dist/{uninstall-OACH27UV.js → uninstall-BYVGAQMO.js} +36 -18
  66. package/dist/uninstall-BYVGAQMO.js.map +1 -0
  67. package/dist/{update-4W6EKLGZ.js → update-7QJDSHST.js} +5 -5
  68. package/dist/{viemAdapter-By13KInL-X2VY6CY3.js → viemAdapter-By13KInL-N2GIVMZ7.js} +2 -2
  69. package/dist/{wallet-BMEXRR3P.js → wallet-YZOXIXBC.js} +15 -14
  70. package/docs/agent-permissions.md +30 -14
  71. package/docs/safety-model.md +7 -1
  72. package/package.json +1 -1
  73. package/dist/chunk-35M3VITA.js.map +0 -1
  74. package/dist/chunk-56MOAIP5.js.map +0 -1
  75. package/dist/chunk-AUKDYPPX.js.map +0 -1
  76. package/dist/chunk-J5INH7WB.js.map +0 -1
  77. package/dist/chunk-KK4YGYTV.js.map +0 -1
  78. package/dist/chunk-O4ZNKFRU.js.map +0 -1
  79. package/dist/chunk-PDA2BVFY.js.map +0 -1
  80. package/dist/chunk-QDD2RN7G.js.map +0 -1
  81. package/dist/chunk-U2DZISAH.js +0 -111
  82. package/dist/chunk-U2DZISAH.js.map +0 -1
  83. package/dist/chunk-WS4JA6TC.js +0 -137
  84. package/dist/chunk-WS4JA6TC.js.map +0 -1
  85. package/dist/chunk-WXC57XGG.js.map +0 -1
  86. package/dist/hook-command-PBERPRE3.js.map +0 -1
  87. package/dist/skill-placement-JMDPSKE6.js +0 -299
  88. package/dist/skill-placement-JMDPSKE6.js.map +0 -1
  89. package/dist/status-FFC6FO72.js.map +0 -1
  90. package/dist/uninstall-OACH27UV.js.map +0 -1
  91. /package/dist/{_esm-CE7KNONL.js.map → _esm-OVVGTKHH.js.map} +0 -0
  92. /package/dist/{chunk-5QHHRMRA.js.map → chunk-2SQEFBAM.js.map} +0 -0
  93. /package/dist/{chunk-LJ4DMVFI.js.map → chunk-3VYGDRRL.js.map} +0 -0
  94. /package/dist/{chunk-N35E6CM2.js.map → chunk-6DCELMQA.js.map} +0 -0
  95. /package/dist/{chunk-TP4D47BY.js.map → chunk-AISBL7EY.js.map} +0 -0
  96. /package/dist/{chunk-HPWO4O6S.js.map → chunk-FPUPBQHX.js.map} +0 -0
  97. /package/dist/{chunk-3AUDA53C.js.map → chunk-KTAW4KGH.js.map} +0 -0
  98. /package/dist/{chunk-MRGADYDD.js.map → chunk-VFVFVQM6.js.map} +0 -0
  99. /package/dist/{chunk-2JGT3KDW.js.map → chunk-WUU3BH6G.js.map} +0 -0
  100. /package/dist/{chunk-KUBEYXSO.js.map → chunk-XDADPAWW.js.map} +0 -0
  101. /package/dist/{chunk-WGQVJM56.js.map → chunk-XNP6VUAJ.js.map} +0 -0
  102. /package/dist/{chunk-AWQPGIR6.js.map → chunk-Y66XUXVI.js.map} +0 -0
  103. /package/dist/{chunk-XZOEUYMX.js.map → chunk-ZDKEU2GF.js.map} +0 -0
  104. /package/dist/{chunk-WLMJE3GJ.js.map → chunk-ZTFIQC4C.js.map} +0 -0
  105. /package/dist/{config-5ADBAAXU.js.map → config-BLUWOH6S.js.map} +0 -0
  106. /package/dist/{install-OKDKGUXM.js.map → install-U4BIDCHH.js.map} +0 -0
  107. /package/dist/{pay-3SYKHKWJ.js.map → pay-VJOP6TFT.js.map} +0 -0
  108. /package/dist/{status-line-SAXSU6CR.js.map → status-line-CZAZUOAY.js.map} +0 -0
  109. /package/dist/{status-line-wiring-L2WYIYBM.js.map → status-line-wiring-2ABDVXSJ.js.map} +0 -0
  110. /package/dist/{update-4W6EKLGZ.js.map → update-7QJDSHST.js.map} +0 -0
  111. /package/dist/{viemAdapter-By13KInL-X2VY6CY3.js.map → viemAdapter-By13KInL-N2GIVMZ7.js.map} +0 -0
  112. /package/dist/{wallet-BMEXRR3P.js.map → wallet-YZOXIXBC.js.map} +0 -0
@@ -1,19 +1,25 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
- import {
3
- isPublicAddress
4
- } from "./chunk-2G2WLVHB.js";
5
2
  import {
6
3
  requestToolAccess
7
4
  } from "./chunk-S2NRVRPF.js";
8
5
  import {
9
6
  ROUTER_PATH,
10
7
  requestDecision
11
- } from "./chunk-WGQVJM56.js";
12
- import "./chunk-5QHHRMRA.js";
8
+ } from "./chunk-XNP6VUAJ.js";
9
+ import {
10
+ isPublicAddress
11
+ } from "./chunk-2G2WLVHB.js";
13
12
  import {
13
+ composeUserAgent
14
+ } from "./chunk-2SQEFBAM.js";
15
+ import {
16
+ readUsdcBalance
17
+ } from "./chunk-3KKKB2AQ.js";
18
+ import {
19
+ evaluateSpendPolicy,
14
20
  readSpendSummary,
15
21
  spentOf
16
- } from "./chunk-35M3VITA.js";
22
+ } from "./chunk-TDGN476R.js";
17
23
  import {
18
24
  REQUEST_TOOL
19
25
  } from "./chunk-TGLKKLQG.js";
@@ -21,37 +27,44 @@ import {
21
27
  mask
22
28
  } from "./chunk-7QKHZQKW.js";
23
29
  import {
30
+ augmentOf,
24
31
  bindDecision,
32
+ claimQuery,
33
+ markAugment,
25
34
  markOffered,
26
35
  newCallId,
36
+ noteRedirect,
27
37
  noteSession,
28
38
  pruneProgress,
29
39
  pruneSessions,
30
40
  sessionDir,
41
+ takeUndelivered,
31
42
  wasOffered,
32
43
  writeProgress
33
- } from "./chunk-J5INH7WB.js";
44
+ } from "./chunk-LSWVVSFX.js";
45
+ import "./chunk-2I4QTOLB.js";
34
46
  import {
35
47
  routerSettings
36
- } from "./chunk-TP4D47BY.js";
37
- import "./chunk-2I4QTOLB.js";
48
+ } from "./chunk-AISBL7EY.js";
38
49
  import {
39
50
  resolveContextSettings
40
- } from "./chunk-PDA2BVFY.js";
41
- import {
42
- evaluateSpendPolicy
43
- } from "./chunk-U2DZISAH.js";
51
+ } from "./chunk-5DOHKQ24.js";
52
+ import "./chunk-O2JYBOUO.js";
44
53
  import {
45
54
  external_exports,
55
+ isSameDeployment,
46
56
  loadRawConfig,
47
57
  resolveSettings
48
- } from "./chunk-AR7U7BRG.js";
49
- import "./chunk-5UDD5VSY.js";
58
+ } from "./chunk-UNV4K45L.js";
59
+ import "./chunk-PZQRSZJV.js";
50
60
  import "./chunk-JLEF5WHM.js";
51
- import "./chunk-2BKS2FVE.js";
61
+ import {
62
+ walletPath
63
+ } from "./chunk-2BKS2FVE.js";
52
64
  import "./chunk-ZXTAQYNA.js";
53
65
 
54
66
  // src/router/hooks.ts
67
+ import { readFile } from "node:fs/promises";
55
68
  import { homedir } from "node:os";
56
69
 
57
70
  // src/router/context.ts
@@ -242,10 +255,19 @@ function parseRows(raw, scope) {
242
255
  } catch {
243
256
  continue;
244
257
  }
258
+ if (row.type === "user" && harnessUserRow(row, text)) continue;
245
259
  if (text.length > 0) messages.push({ role: row.type, text });
246
260
  }
247
261
  return messages;
248
262
  }
263
+ var LOCAL_COMMAND_OUTPUT = /^\s*<local-command-(?:stdout|stderr)>/;
264
+ function harnessUserRow(row, text) {
265
+ const origin = row.origin;
266
+ if (origin !== null && typeof origin === "object" && origin.kind === "task-notification") {
267
+ return true;
268
+ }
269
+ return text.trimStart().startsWith("<task-notification>") || LOCAL_COMMAND_OUTPUT.test(text);
270
+ }
249
271
  function ownSidechainRow(row, agentId) {
250
272
  return row.isSidechain === true && row.agentId === agentId && row.isMeta !== true;
251
273
  }
@@ -272,6 +294,148 @@ function textOf(message) {
272
294
  // src/router/gate.ts
273
295
  var GATE_TIMEOUT_MS = 3500;
274
296
 
297
+ // src/router/augment.ts
298
+ import { spawn } from "node:child_process";
299
+ import { constants } from "node:fs";
300
+ import { open as open2, rm } from "node:fs/promises";
301
+ import { dirname as dirname2 } from "node:path";
302
+ var DOCS_QUERY_MAX = 500;
303
+ var PREFETCH_TIMEOUT_MS = 12e3;
304
+ var AUGMENT_WAIT_MS = 9e3;
305
+ var MAX_DOCS_CHARS = 1e5;
306
+ var MAX_BODY_BYTES = 1e6;
307
+ var POLL_MS = 100;
308
+ var PREFETCH_SCRIPT = [
309
+ "const { renameSync, rmSync, writeFileSync } = require('node:fs');",
310
+ "const { basename, dirname, join } = require('node:path');",
311
+ "const [url, out, agent, timeout, max] = process.argv.slice(1);",
312
+ "const tmp = join(dirname(out), '.' + basename(out) + '.' + process.pid + '.tmp');",
313
+ // The deadline is a plain timer that answers and exits, not an
314
+ // `AbortSignal.timeout`: that one's timer does not hold the process open, so
315
+ // a stalled lookup let it exit without writing anything.
316
+ "const timer = setTimeout(() => done(0, ''), Number(timeout));",
317
+ "const done = (status, text) => {",
318
+ " clearTimeout(timer);",
319
+ " try {",
320
+ " writeFileSync(tmp, JSON.stringify({ status, text }), { mode: 0o600, flag: 'wx' });",
321
+ " renameSync(tmp, out);",
322
+ " } catch {",
323
+ " try { rmSync(tmp, { force: true }); } catch {}",
324
+ " }",
325
+ " process.exit(0);",
326
+ "};",
327
+ "fetch(url, {",
328
+ " headers: { accept: 'text/plain', 'user-agent': agent },",
329
+ " redirect: 'error',",
330
+ "})",
331
+ " .then(async (res) => done(res.status, res.ok ? (await res.text()).slice(0, Number(max)) : ''))",
332
+ " .catch(() => done(0, ''));"
333
+ ].join("\n");
334
+ function spawnPrefetch(job) {
335
+ const child = spawn(
336
+ process.execPath,
337
+ [
338
+ "-e",
339
+ PREFETCH_SCRIPT,
340
+ job.url,
341
+ job.out,
342
+ job.userAgent,
343
+ String(PREFETCH_TIMEOUT_MS),
344
+ String(MAX_DOCS_CHARS)
345
+ ],
346
+ {
347
+ detached: true,
348
+ stdio: "ignore",
349
+ // Never the session's project: a live child would pin its worktree.
350
+ cwd: dirname2(job.out),
351
+ windowsHide: true
352
+ }
353
+ );
354
+ child.on("error", () => void 0);
355
+ child.unref();
356
+ }
357
+ function docsUrl(endpoint, query, baseUrl) {
358
+ let url;
359
+ let base;
360
+ try {
361
+ url = new URL(endpoint);
362
+ base = new URL(baseUrl);
363
+ } catch {
364
+ return null;
365
+ }
366
+ if (url.username !== "" || url.password !== "") return null;
367
+ if (!isSameDeployment(url.origin, base.origin)) return null;
368
+ url.searchParams.set("query", query.slice(0, DOCS_QUERY_MAX));
369
+ return url.toString();
370
+ }
371
+ async function startAugment(call, offer, baseUrl, deps) {
372
+ if (call.toolUseId === void 0) return false;
373
+ const url = docsUrl(offer.endpoint, call.query, baseUrl);
374
+ if (url === null) return false;
375
+ const now = deps.now?.() ?? Date.now();
376
+ if (!await claimQuery(deps.dataDir, call.sessionId, call.agentId, call.query, now)) {
377
+ return false;
378
+ }
379
+ const out = await markAugment(deps.dataDir, call.sessionId, call.toolUseId, offer.provider, now);
380
+ if (out === null) return false;
381
+ try {
382
+ (deps.prefetch ?? spawnPrefetch)({ url, out, userAgent: composeUserAgent() });
383
+ return true;
384
+ } catch {
385
+ return false;
386
+ }
387
+ }
388
+ async function finishAugment(call, deps) {
389
+ if (call.toolUseId === void 0) return null;
390
+ const now = deps.now?.() ?? Date.now();
391
+ const marker = await augmentOf(deps.dataDir, call.sessionId, call.toolUseId, now);
392
+ if (marker === null) return null;
393
+ if (call.search === null) return { updatedToolOutput: null };
394
+ const budget = Math.min(
395
+ deps.augmentWaitMs ?? AUGMENT_WAIT_MS,
396
+ PREFETCH_TIMEOUT_MS + 1e3 - (now - marker.at)
397
+ );
398
+ const answer = await awaitBody(marker.body, Date.now() + Math.max(0, budget));
399
+ await rm(marker.body, { force: true }).catch(() => void 0);
400
+ const text = answer?.status === 200 ? answer.text.trim() : "";
401
+ if (text.length === 0) return { updatedToolOutput: null };
402
+ return {
403
+ updatedToolOutput: {
404
+ ...call.search.raw,
405
+ results: [docsLine(marker.provider || "library", text), ...call.search.results]
406
+ }
407
+ };
408
+ }
409
+ function docsLine(provider, text) {
410
+ return `Tenjin router added ${provider} docs for this search (free). If they don't cover it, use the web results below.
411
+
412
+ ${text}`;
413
+ }
414
+ async function awaitBody(path, deadline) {
415
+ for (; ; ) {
416
+ const body = await readBody(path);
417
+ if (body !== null) return body;
418
+ const left = deadline - Date.now();
419
+ if (left <= 0) return null;
420
+ await new Promise((resolve) => setTimeout(resolve, Math.min(POLL_MS, left)));
421
+ }
422
+ }
423
+ async function readBody(path) {
424
+ const file = await open2(path, constants.O_RDONLY | constants.O_NOFOLLOW).catch(() => void 0);
425
+ if (file === void 0) return null;
426
+ try {
427
+ if ((await file.stat()).size > MAX_BODY_BYTES) return { status: 0, text: "" };
428
+ const parsed = JSON.parse(await file.readFile("utf8"));
429
+ const { status, text } = parsed ?? {};
430
+ if (typeof status !== "number" || typeof text !== "string") return { status: 0, text: "" };
431
+ return { status, text: text.slice(0, MAX_DOCS_CHARS) };
432
+ } catch {
433
+ return { status: 0, text: "" };
434
+ } finally {
435
+ await file.close().catch(() => void 0);
436
+ }
437
+ }
438
+
275
439
  // src/router/hooks.ts
276
440
  var PromptEventSchema = external_exports.object({
277
441
  session_id: external_exports.string().min(1).max(200),
@@ -327,6 +491,7 @@ function decodeEvent(raw) {
327
491
  kind: "shortfall",
328
492
  eventName: shortfall.data.hook_event_name,
329
493
  nativeOutcome: shortfallOf(shortfall.data),
494
+ search: searchOf(shortfall.data),
330
495
  ...nativeCallOf(shortfall.data)
331
496
  };
332
497
  }
@@ -368,6 +533,13 @@ function nativeCallOf(event) {
368
533
  ...optional("cwd", event.cwd)
369
534
  };
370
535
  }
536
+ function searchOf(event) {
537
+ if (event.hook_event_name !== "PostToolUse" || event.tool_name !== "WebSearch") return null;
538
+ const response = event.tool_response;
539
+ if (response === null || typeof response !== "object" || Array.isArray(response)) return null;
540
+ const raw = response;
541
+ return Array.isArray(raw.results) ? { raw, results: raw.results } : null;
542
+ }
371
543
  function optional(key, value) {
372
544
  return value === void 0 ? {} : { [key]: value };
373
545
  }
@@ -386,6 +558,7 @@ function toolNamed(hint) {
386
558
  function attributed(hint) {
387
559
  return `${HINT_SOURCE}: ${toolNamed(hint)}`;
388
560
  }
561
+ var ONE_BLOCK = "If this does not cover it, make your own call again: you will not be redirected twice in a row.";
389
562
  function shortfallOffer(tool, hint) {
390
563
  return `${HINT_SOURCE}: your ${tool} call came back short. Optional: ${toolNamed(hint)}`;
391
564
  }
@@ -431,20 +604,50 @@ function resolveBaseUrl(deps, config) {
431
604
  if (deps.baseUrl !== void 0) return deps.baseUrl;
432
605
  return resolveSettings({ config, flags: {}, env: deps.env ?? process.env }).baseUrl.value;
433
606
  }
434
- async function wouldAutoExecute(decision, deps) {
607
+ var BALANCE_TIMEOUT_MS = 1e3;
608
+ function gateDeadline(deps) {
609
+ return (deps.now?.() ?? Date.now()) + (deps.timeoutMs ?? GATE_TIMEOUT_MS);
610
+ }
611
+ async function withheldBecause(decision, deps, deadline) {
612
+ let rpcUrl;
435
613
  try {
436
- const { policy } = await resolveContextSettings(hookContext(deps));
614
+ const settings = await resolveContextSettings(hookContext(deps));
437
615
  const ledger = await readSpendSummary(deps.dataDir, {
438
616
  ...deps.now !== void 0 ? { now: deps.now } : {}
439
617
  });
440
- const evaluation = evaluateSpendPolicy(policy, {
618
+ const evaluation = evaluateSpendPolicy(settings.policy, {
441
619
  amountAtomic: BigInt(decision.providerPriceAtomic),
442
620
  creator: new URL(decision.endpoint).host,
443
621
  sessionSpentAtomic: ledger === null ? 0n : spentOf(ledger)
444
622
  });
445
- return evaluation.decision === "allow";
623
+ if (evaluation.decision !== "allow") return "offer needs approval";
624
+ rpcUrl = settings.rpcUrl;
446
625
  } catch {
447
- return false;
626
+ return "offer needs approval";
627
+ }
628
+ if ((deps.env ?? process.env).TENJIN_WALLET_KEY?.trim()) return null;
629
+ const address = await walletAddress(deps.dataDir);
630
+ if (address === null) return null;
631
+ const balance = await readUsdcBalance(address, rpcUrl, {
632
+ timeoutMs: Math.min(BALANCE_TIMEOUT_MS, deadline - (deps.now?.() ?? Date.now())),
633
+ ...deps.fetchImpl !== void 0 ? { fetchImpl: deps.fetchImpl } : {}
634
+ });
635
+ if (balance === null) {
636
+ (deps.warn ?? ((line) => process.stderr.write(`${line}
637
+ `)))(
638
+ `tenjin hook: the wallet's USDC balance could not be read from ${new URL(rpcUrl).host}, so the spend policy alone decides`
639
+ );
640
+ return null;
641
+ }
642
+ return balance < BigInt(decision.providerPriceAtomic) ? "wallet needs USDC" : null;
643
+ }
644
+ async function walletAddress(dataDir) {
645
+ try {
646
+ const record = JSON.parse(await readFile(walletPath(dataDir), "utf8"));
647
+ const address = record?.address;
648
+ return typeof address === "string" && /^0x[0-9a-fA-F]{40}$/.test(address) ? address : null;
649
+ } catch {
650
+ return null;
448
651
  }
449
652
  }
450
653
  function agentLookup(cwd, deps) {
@@ -471,10 +674,18 @@ async function runPromptHook(raw, deps) {
471
674
  )
472
675
  );
473
676
  const footer = await openFooter(deps, event.sessionId, "prompt");
677
+ const deadline = gateDeadline(deps);
474
678
  const outcome = await decide(sealed, deps, router.config);
679
+ if (outcome === null || outcome.action !== "execute") {
680
+ await footer.close(outcome);
681
+ return { response: null, ...outcome !== null ? { action: outcome.action } : {} };
682
+ }
683
+ const withheld = await withheldBecause(outcome, deps, deadline);
684
+ if (withheld !== null) {
685
+ await footer.close(outcome, { withheld });
686
+ return { response: null, action: "execute", withheld: true };
687
+ }
475
688
  await footer.close(outcome);
476
- if (outcome === null) return { response: null };
477
- if (outcome.action !== "execute") return { response: null, action: outcome.action };
478
689
  return { action: "execute", id: outcome.id, ...injection(attributed(outcome.hint)) };
479
690
  }
480
691
  function injection(line) {
@@ -484,7 +695,11 @@ function injection(line) {
484
695
  }
485
696
  };
486
697
  }
487
- async function routeNativeCall(event, pending, deps, nativeOutcome) {
698
+ function isFree(offer) {
699
+ return offer.providerPriceAtomic === "0";
700
+ }
701
+ async function routeNativeCall(event, pending, deps, opts = {}) {
702
+ const { nativeOutcome, repeated } = opts;
488
703
  const router = await routerFor(event.cwd, deps);
489
704
  if (router === null) return { offer: null, outcome: { response: null } };
490
705
  if (event.agentId !== void 0 && await requestToolAccess(event.agentType, agentLookup(event.cwd, deps)) !== "allowed") {
@@ -516,6 +731,7 @@ async function routeNativeCall(event, pending, deps, nativeOutcome) {
516
731
  return { offer: null, outcome: { response: null } };
517
732
  }
518
733
  const footer = await openFooter(deps, event.sessionId, "search");
734
+ const deadline = gateDeadline(deps);
519
735
  const outcome = await decide(sealed, deps, router.config);
520
736
  if (outcome === null || outcome.action !== "execute") {
521
737
  await footer.close(outcome);
@@ -524,29 +740,67 @@ async function routeNativeCall(event, pending, deps, nativeOutcome) {
524
740
  outcome: { response: null, ...outcome !== null ? { action: outcome.action } : {} }
525
741
  };
526
742
  }
527
- if (event.agentId !== void 0 && !await wouldAutoExecute(outcome, deps)) {
528
- await footer.close(outcome, { withheld: true });
743
+ if (opts.passFree === true && isFree(outcome)) {
744
+ await footer.close(outcome, { withheld: "free lookup, call runs" });
745
+ return { offer: outcome, free: true, baseUrl: resolveBaseUrl(deps, router.config) };
746
+ }
747
+ const withheld = await withheldBecause(outcome, deps, deadline);
748
+ if (withheld !== null) {
749
+ await footer.close(outcome, { withheld });
529
750
  return { offer: null, outcome: { response: null, action: "execute", withheld: true } };
530
751
  }
752
+ if (repeated !== void 0 && await repeated(outcome)) {
753
+ await footer.close(outcome, { withheld: "already redirected once" });
754
+ return {
755
+ offer: null,
756
+ outcome: { response: null, action: "execute", redirectUndelivered: true }
757
+ };
758
+ }
531
759
  await footer.close(outcome);
532
760
  return { offer: outcome };
533
761
  }
534
762
  async function runNativeHook(raw, deps) {
535
763
  const event = decodeEvent(raw);
536
764
  if (event?.kind !== "native" || event.pending === null) return { response: null };
537
- const routed = await routeNativeCall(event, event.pending, deps);
765
+ const routed = await routeNativeCall(event, event.pending, deps, {
766
+ passFree: true,
767
+ repeated: (offer) => takeUndelivered(deps.dataDir, event.sessionId, event.agentId, offer.category, deps.now?.())
768
+ });
538
769
  if (routed.offer === null) return routed.outcome;
770
+ if (routed.free === true) {
771
+ const { pending } = event;
772
+ const augmenting = pending.tool === "WebSearch" && await startAugment(
773
+ {
774
+ sessionId: event.sessionId,
775
+ query: pending.query,
776
+ ...event.agentId !== void 0 ? { agentId: event.agentId } : {},
777
+ ...event.toolUseId !== void 0 ? { toolUseId: event.toolUseId } : {}
778
+ },
779
+ routed.offer,
780
+ routed.baseUrl,
781
+ deps
782
+ );
783
+ return {
784
+ response: null,
785
+ action: "execute",
786
+ id: routed.offer.id,
787
+ free: true,
788
+ ...augmenting ? { augmenting: true } : {}
789
+ };
790
+ }
539
791
  if (event.toolUseId !== void 0) {
540
792
  await markOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.());
541
793
  }
794
+ await noteRedirect(deps.dataDir, event.sessionId, event.agentId, routed.offer, deps.now?.());
542
795
  return {
543
796
  response: {
544
797
  hookSpecificOutput: {
545
798
  hookEventName: "PreToolUse",
546
799
  permissionDecision: "deny",
547
- // THE SERVER'S LINE, attributed and tool-named, and nothing else. It
548
- // already carries the id and the exact search or URL that was denied.
549
- permissionDecisionReason: attributed(routed.offer.hint)
800
+ // THE SERVER'S LINE, attributed and tool-named, then this client's one
801
+ // sentence. The line already carries the id and the exact search or URL
802
+ // that was denied.
803
+ permissionDecisionReason: `${attributed(routed.offer.hint)} ${ONE_BLOCK}`
550
804
  }
551
805
  },
552
806
  action: "execute",
@@ -556,14 +810,39 @@ async function runNativeHook(raw, deps) {
556
810
  async function runShortfallHook(raw, deps) {
557
811
  const event = decodeEvent(raw);
558
812
  if (event?.kind !== "shortfall") return { response: null };
813
+ const augment = await finishAugment(
814
+ {
815
+ sessionId: event.sessionId,
816
+ search: event.search,
817
+ ...event.toolUseId !== void 0 ? { toolUseId: event.toolUseId } : {}
818
+ },
819
+ deps
820
+ );
821
+ if (augment !== null && augment.updatedToolOutput !== null) {
822
+ return {
823
+ response: {
824
+ hookSpecificOutput: {
825
+ hookEventName: "PostToolUse",
826
+ updatedToolOutput: augment.updatedToolOutput
827
+ }
828
+ },
829
+ augmented: "added"
830
+ };
831
+ }
832
+ const outcome = await offerOnShortfall(event, deps, augment !== null);
833
+ return augment === null ? outcome : { ...outcome, augmented: "nothing" };
834
+ }
835
+ async function offerOnShortfall(event, deps, docsJustMissed = false) {
559
836
  const { nativeOutcome, pending, eventName } = event;
560
837
  if (nativeOutcome === null) return { response: null };
561
838
  if (pending === null) return { response: null };
562
839
  if (event.toolUseId !== void 0 && await wasOffered(deps.dataDir, event.sessionId, event.toolUseId, deps.now?.())) {
563
840
  return { response: null, nativeOutcome, alreadyOffered: true };
564
841
  }
565
- const routed = await routeNativeCall(event, pending, deps, nativeOutcome);
842
+ const routed = await routeNativeCall(event, pending, deps, { nativeOutcome });
566
843
  if (routed.offer === null) return { ...routed.outcome, nativeOutcome };
844
+ if (docsJustMissed && routed.offer.providerPriceAtomic === "0")
845
+ return { response: null, nativeOutcome, action: "execute" };
567
846
  return {
568
847
  response: {
569
848
  hookSpecificOutput: {
@@ -601,13 +880,15 @@ async function runDelegationHook(raw, deps) {
601
880
  }
602
881
  if (sealed.packet.historyStatus !== "ok") return { response: null };
603
882
  const footer = await openFooter(deps, event.sessionId, "delegate");
883
+ const deadline = gateDeadline(deps);
604
884
  const outcome = await decide(sealed, deps, router.config);
605
885
  if (outcome === null || outcome.action !== "execute") {
606
886
  await footer.close(outcome);
607
887
  return { response: null, ...outcome !== null ? { action: outcome.action } : {} };
608
888
  }
609
- if (!await wouldAutoExecute(outcome, deps)) {
610
- await footer.close(outcome, { withheld: true });
889
+ const withheld = await withheldBecause(outcome, deps, deadline);
890
+ if (withheld !== null) {
891
+ await footer.close(outcome, { withheld });
611
892
  return { response: null, action: "execute", withheld: true };
612
893
  }
613
894
  await footer.close(outcome);
@@ -643,18 +924,18 @@ async function openFooter(deps, sessionId, operation) {
643
924
  await pruneSessions(deps.dataDir, now());
644
925
  return {
645
926
  close: async (decision, opts) => {
646
- const withheld = opts?.withheld === true;
927
+ const withheld = opts?.withheld;
647
928
  await writeProgress(
648
929
  directory,
649
930
  callId,
650
931
  {
651
932
  phase: "done",
652
933
  operation,
653
- outcome: withheld ? "native tools (offer needs approval)" : hookOutcome(decision)
934
+ outcome: withheld !== void 0 ? `native tools (${withheld})` : hookOutcome(decision)
654
935
  },
655
936
  now()
656
937
  );
657
- if (!withheld && decision !== null && decision.action === "execute") {
938
+ if (withheld === void 0 && decision !== null && decision.action === "execute") {
658
939
  await bindDecision(deps.dataDir, sessionId, decision.id, now());
659
940
  }
660
941
  }
@@ -760,4 +1041,4 @@ export {
760
1041
  STDIN_TIMEOUT_MS,
761
1042
  runHookCommand
762
1043
  };
763
- //# sourceMappingURL=hook-command-PBERPRE3.js.map
1044
+ //# sourceMappingURL=hook-command-YTV7X333.js.map