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

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 (110) hide show
  1. package/README.md +2 -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-HVRC33OL.js → chunk-2JGT3KDW.js} +4 -6
  7. package/dist/{chunk-HVRC33OL.js.map → chunk-2JGT3KDW.js.map} +1 -1
  8. package/dist/chunk-35M3VITA.js +102 -0
  9. package/dist/chunk-35M3VITA.js.map +1 -0
  10. package/dist/{chunk-5X4SZ5BF.js → chunk-5QHHRMRA.js} +4 -4
  11. package/dist/{chunk-BFFM2WFK.js → chunk-5UDD5VSY.js} +2 -2
  12. package/dist/{chunk-BFFM2WFK.js.map → chunk-5UDD5VSY.js.map} +1 -1
  13. package/dist/{chunk-OIM4HLN6.js → chunk-7QKHZQKW.js} +295 -20
  14. package/dist/chunk-7QKHZQKW.js.map +1 -0
  15. package/dist/{chunk-BBVUVBUO.js → chunk-AR7U7BRG.js} +44 -7
  16. package/dist/{chunk-BBVUVBUO.js.map → chunk-AR7U7BRG.js.map} +1 -1
  17. package/dist/{chunk-DMZZLPZN.js → chunk-AUKDYPPX.js} +14 -89
  18. package/dist/chunk-AUKDYPPX.js.map +1 -0
  19. package/dist/{chunk-PZEN5PHN.js → chunk-J5INH7WB.js} +17 -3
  20. package/dist/chunk-J5INH7WB.js.map +1 -0
  21. package/dist/{chunk-7WEQQJLG.js → chunk-JLEF5WHM.js} +66 -2
  22. package/dist/chunk-JLEF5WHM.js.map +1 -0
  23. package/dist/{chunk-GULLJQXA.js → chunk-KK4YGYTV.js} +127 -17
  24. package/dist/chunk-KK4YGYTV.js.map +1 -0
  25. package/dist/{chunk-YEETV6IW.js → chunk-KUBEYXSO.js} +10 -12
  26. package/dist/{chunk-YEETV6IW.js.map → chunk-KUBEYXSO.js.map} +1 -1
  27. package/dist/{chunk-2U5ZVEV3.js → chunk-LJ4DMVFI.js} +5 -5
  28. package/dist/{chunk-3AJS6LLN.js → chunk-MRGADYDD.js} +7 -7
  29. package/dist/{chunk-25TJPVBF.js → chunk-O4ZNKFRU.js} +28 -15
  30. package/dist/chunk-O4ZNKFRU.js.map +1 -0
  31. package/dist/{chunk-OJLYNM4Z.js → chunk-PDA2BVFY.js} +77 -19
  32. package/dist/chunk-PDA2BVFY.js.map +1 -0
  33. package/dist/{chunk-L3PVMIYQ.js → chunk-QDD2RN7G.js} +29 -119
  34. package/dist/chunk-QDD2RN7G.js.map +1 -0
  35. package/dist/chunk-S2NRVRPF.js +171 -0
  36. package/dist/chunk-S2NRVRPF.js.map +1 -0
  37. package/dist/chunk-TGLKKLQG.js +11 -0
  38. package/dist/chunk-TGLKKLQG.js.map +1 -0
  39. package/dist/chunk-TP4D47BY.js +127 -0
  40. package/dist/chunk-TP4D47BY.js.map +1 -0
  41. package/dist/{chunk-WH7OWT6G.js → chunk-U2DZISAH.js} +2 -8
  42. package/dist/chunk-U2DZISAH.js.map +1 -0
  43. package/dist/{chunk-USS336NF.js → chunk-WGQVJM56.js} +5 -5
  44. package/dist/chunk-WGQVJM56.js.map +1 -0
  45. package/dist/{chunk-YJHHCWM3.js → chunk-WLMJE3GJ.js} +3 -3
  46. package/dist/{chunk-U5DXNFJC.js → chunk-WS4JA6TC.js} +3 -3
  47. package/dist/{chunk-SKAHDQH7.js → chunk-XZOEUYMX.js} +6 -7
  48. package/dist/{chunk-SKAHDQH7.js.map → chunk-XZOEUYMX.js.map} +1 -1
  49. package/dist/{cli-M3XCSOU6.js → cli-VHYYYYXM.js} +43 -29
  50. package/dist/{cli-M3XCSOU6.js.map → cli-VHYYYYXM.js.map} +1 -1
  51. package/dist/{config-MXOX7XDR.js → config-5ADBAAXU.js} +11 -10
  52. package/dist/{doctor-LU4YIZWM.js → doctor-Q35VQW3S.js} +108 -21
  53. package/dist/doctor-Q35VQW3S.js.map +1 -0
  54. package/dist/{fund-A54P2QFK.js → fund-GDDPL2BB.js} +11 -10
  55. package/dist/{fund-A54P2QFK.js.map → fund-GDDPL2BB.js.map} +1 -1
  56. package/dist/hook-command-PBERPRE3.js +763 -0
  57. package/dist/hook-command-PBERPRE3.js.map +1 -0
  58. package/dist/index.js +2 -2
  59. package/dist/{install-XUM2XSHW.js → install-OKDKGUXM.js} +21 -14
  60. package/dist/{install-wallet-QIOFORTX.js → install-wallet-SI4LZ73K.js} +10 -9
  61. package/dist/{install-wallet-QIOFORTX.js.map → install-wallet-SI4LZ73K.js.map} +1 -1
  62. package/dist/{mcp-HJC2PLRV.js → mcp-XX3WRQEZ.js} +63 -31
  63. package/dist/{mcp-HJC2PLRV.js.map → mcp-XX3WRQEZ.js.map} +1 -1
  64. package/dist/{pay-SBXZEPEP.js → pay-3SYKHKWJ.js} +15 -13
  65. package/dist/{redact-46ZHF2NH.js → redact-6W23GGJC.js} +4 -6
  66. package/dist/{send-ASD2ZXJD.js → send-LQRKTEJT.js} +10 -9
  67. package/dist/{send-ASD2ZXJD.js.map → send-LQRKTEJT.js.map} +1 -1
  68. package/dist/{skill-placement-NFVHY6A3.js → skill-placement-JMDPSKE6.js} +12 -13
  69. package/dist/{skill-placement-NFVHY6A3.js.map → skill-placement-JMDPSKE6.js.map} +1 -1
  70. package/dist/{status-T2SDB57A.js → status-FFC6FO72.js} +8 -7
  71. package/dist/{status-T2SDB57A.js.map → status-FFC6FO72.js.map} +1 -1
  72. package/dist/{status-line-CGPUSDMC.js → status-line-SAXSU6CR.js} +19 -3
  73. package/dist/status-line-SAXSU6CR.js.map +1 -0
  74. package/dist/{status-line-wiring-BYPHTYZE.js → status-line-wiring-L2WYIYBM.js} +5 -6
  75. package/dist/tenjin-daemon.mjs +384 -23
  76. package/dist/{uninstall-FKYZHAM3.js → uninstall-OACH27UV.js} +18 -15
  77. package/dist/{uninstall-FKYZHAM3.js.map → uninstall-OACH27UV.js.map} +1 -1
  78. package/dist/{update-ANJ2AOTN.js → update-4W6EKLGZ.js} +6 -7
  79. package/dist/{update-ANJ2AOTN.js.map → update-4W6EKLGZ.js.map} +1 -1
  80. package/dist/{wallet-PWAHVKWW.js → wallet-BMEXRR3P.js} +10 -9
  81. package/docs/agent-permissions.md +16 -8
  82. package/docs/safety-model.md +1 -1
  83. package/package.json +1 -1
  84. package/dist/chunk-25TJPVBF.js.map +0 -1
  85. package/dist/chunk-7WEQQJLG.js.map +0 -1
  86. package/dist/chunk-DMZZLPZN.js.map +0 -1
  87. package/dist/chunk-GULLJQXA.js.map +0 -1
  88. package/dist/chunk-L3PVMIYQ.js.map +0 -1
  89. package/dist/chunk-OCBHUHWB.js +0 -69
  90. package/dist/chunk-OCBHUHWB.js.map +0 -1
  91. package/dist/chunk-OIM4HLN6.js.map +0 -1
  92. package/dist/chunk-OJLYNM4Z.js.map +0 -1
  93. package/dist/chunk-PZEN5PHN.js.map +0 -1
  94. package/dist/chunk-USS336NF.js.map +0 -1
  95. package/dist/chunk-WH7OWT6G.js.map +0 -1
  96. package/dist/doctor-LU4YIZWM.js.map +0 -1
  97. package/dist/hook-command-U6KWPEDQ.js +0 -377
  98. package/dist/hook-command-U6KWPEDQ.js.map +0 -1
  99. package/dist/status-line-CGPUSDMC.js.map +0 -1
  100. /package/dist/{chunk-5X4SZ5BF.js.map → chunk-5QHHRMRA.js.map} +0 -0
  101. /package/dist/{chunk-2U5ZVEV3.js.map → chunk-LJ4DMVFI.js.map} +0 -0
  102. /package/dist/{chunk-3AJS6LLN.js.map → chunk-MRGADYDD.js.map} +0 -0
  103. /package/dist/{chunk-YJHHCWM3.js.map → chunk-WLMJE3GJ.js.map} +0 -0
  104. /package/dist/{chunk-U5DXNFJC.js.map → chunk-WS4JA6TC.js.map} +0 -0
  105. /package/dist/{config-MXOX7XDR.js.map → config-5ADBAAXU.js.map} +0 -0
  106. /package/dist/{install-XUM2XSHW.js.map → install-OKDKGUXM.js.map} +0 -0
  107. /package/dist/{pay-SBXZEPEP.js.map → pay-3SYKHKWJ.js.map} +0 -0
  108. /package/dist/{redact-46ZHF2NH.js.map → redact-6W23GGJC.js.map} +0 -0
  109. /package/dist/{status-line-wiring-BYPHTYZE.js.map → status-line-wiring-L2WYIYBM.js.map} +0 -0
  110. /package/dist/{wallet-PWAHVKWW.js.map → wallet-BMEXRR3P.js.map} +0 -0
@@ -0,0 +1,171 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ MCP_SERVER_NAME,
4
+ REQUEST_TOOL
5
+ } from "./chunk-TGLKKLQG.js";
6
+
7
+ // src/router/agent-tools.ts
8
+ import { readdir, readFile } from "node:fs/promises";
9
+ import { dirname, join, resolve } from "node:path";
10
+ var MCP_INHERITING_BUILTINS = /* @__PURE__ */ new Set([
11
+ "general-purpose",
12
+ "Explore",
13
+ "Plan"
14
+ ]);
15
+ var MAX_AGENT_FILE_BYTES = 256 * 1024;
16
+ var TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;
17
+ async function requestToolAccess(agentType, lookup) {
18
+ if (agentType === void 0 || !TYPE_RE.test(agentType)) return "unknown";
19
+ try {
20
+ const text = await findDefinition(agentType, lookup);
21
+ if (text !== null) return accessOf(text);
22
+ return MCP_INHERITING_BUILTINS.has(agentType) ? "allowed" : "unknown";
23
+ } catch {
24
+ return "unknown";
25
+ }
26
+ }
27
+ function accessOf(definition) {
28
+ const frontmatter = frontmatterOf(definition);
29
+ if (frontmatter === null) return "unknown";
30
+ const disallowed = listField(frontmatter, "disallowedTools");
31
+ if (disallowed !== void 0 && disallowed.some(namesRequestTool)) return "excluded";
32
+ const tools = listField(frontmatter, "tools");
33
+ if (tools === void 0) return "allowed";
34
+ return tools.some(namesRequestTool) ? "allowed" : "excluded";
35
+ }
36
+ function namesRequestTool(tool) {
37
+ if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;
38
+ return tool.endsWith("*") && REQUEST_TOOL.startsWith(tool.slice(0, -1));
39
+ }
40
+ async function agentsWithoutRequestTool(lookup) {
41
+ const found = [];
42
+ const seen = /* @__PURE__ */ new Set();
43
+ for (const directory of agentDirs(lookup)) {
44
+ for (const { name, text } of await definitionsIn(directory)) {
45
+ const type = nameOf(text) ?? name;
46
+ if (seen.has(type)) continue;
47
+ seen.add(type);
48
+ if (accessOf(text) === "excluded") found.push(type);
49
+ }
50
+ }
51
+ return found.sort();
52
+ }
53
+ async function findDefinition(agentType, lookup) {
54
+ for (const directory of agentDirs(lookup)) {
55
+ const text = await definitionIn(directory, agentType);
56
+ if (text !== null) return text;
57
+ }
58
+ const colon = agentType.indexOf(":");
59
+ if (colon > 0) {
60
+ const plugin = agentType.slice(0, colon);
61
+ const agent = agentType.slice(colon + 1);
62
+ for (const root of await pluginRoots(plugin, lookup.homeDir)) {
63
+ const text = await definitionIn(join(root, "agents"), agent);
64
+ if (text !== null) return text;
65
+ }
66
+ }
67
+ return null;
68
+ }
69
+ function agentDirs(lookup) {
70
+ const dirs = [];
71
+ if (lookup.cwd !== void 0 && lookup.cwd.length > 0) {
72
+ let current = resolve(lookup.cwd);
73
+ for (; ; ) {
74
+ dirs.push(join(current, ".claude", "agents"));
75
+ const parent = dirname(current);
76
+ if (parent === current) break;
77
+ current = parent;
78
+ }
79
+ }
80
+ const user = join(resolve(lookup.homeDir), ".claude", "agents");
81
+ return [...dirs.filter((d) => d !== user), user];
82
+ }
83
+ async function definitionIn(directory, agentType) {
84
+ const direct = await readBounded(join(directory, `${agentType}.md`));
85
+ if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;
86
+ for (const { text } of await definitionsIn(directory)) {
87
+ if (nameOf(text) === agentType) return text;
88
+ }
89
+ return null;
90
+ }
91
+ async function definitionsIn(directory) {
92
+ let names;
93
+ try {
94
+ names = (await readdir(directory)).filter((n) => n.endsWith(".md")).slice(0, 200);
95
+ } catch {
96
+ return [];
97
+ }
98
+ const out = [];
99
+ for (const file of names) {
100
+ const text = await readBounded(join(directory, file));
101
+ if (text !== null) out.push({ name: file.slice(0, -3), text });
102
+ }
103
+ return out;
104
+ }
105
+ async function pluginRoots(plugin, homeDir) {
106
+ const raw = await readBounded(join(homeDir, ".claude", "plugins", "installed_plugins.json"));
107
+ if (raw === null) return [];
108
+ const parsed = JSON.parse(raw);
109
+ const roots = [];
110
+ for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {
111
+ if (key.split("@")[0] !== plugin || !Array.isArray(entries)) continue;
112
+ for (const entry of entries) {
113
+ const path = entry.installPath;
114
+ if (typeof path === "string" && path.length > 0) roots.push(path);
115
+ }
116
+ }
117
+ return roots;
118
+ }
119
+ async function readBounded(path) {
120
+ try {
121
+ const text = await readFile(path, "utf8");
122
+ return text.length > MAX_AGENT_FILE_BYTES ? null : text;
123
+ } catch {
124
+ return null;
125
+ }
126
+ }
127
+ function frontmatterOf(text) {
128
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
129
+ const open = lines.findIndex((l) => l.trim().length > 0);
130
+ if (open === -1 || lines[open]?.trim() !== "---") return null;
131
+ const end = lines.findIndex((l, i) => i > open && l.trim() === "---");
132
+ return end === -1 ? null : lines.slice(open + 1, end);
133
+ }
134
+ function nameOf(text) {
135
+ const frontmatter = frontmatterOf(text);
136
+ if (frontmatter === null) return null;
137
+ const line = frontmatter.find((l) => /^name\s*:/.test(l));
138
+ const value = line === void 0 ? "" : unquote(line.slice(line.indexOf(":") + 1).trim());
139
+ return value.length > 0 ? value : null;
140
+ }
141
+ function listField(frontmatter, key) {
142
+ const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\s*:`).test(l));
143
+ if (index === -1) return void 0;
144
+ const line = frontmatter[index];
145
+ const inline = line.slice(line.indexOf(":") + 1).trim();
146
+ if (inline.length > 0) {
147
+ const body = inline.startsWith("[") && inline.endsWith("]") ? inline.slice(1, -1) : inline;
148
+ return body.split(",").map((part) => unquote(part.trim())).filter((part) => part.length > 0);
149
+ }
150
+ const items = [];
151
+ for (const next of frontmatter.slice(index + 1)) {
152
+ const item = /^\s+-\s*(.*)$/.exec(next);
153
+ if (item === null) {
154
+ if (next.trim().length === 0) continue;
155
+ break;
156
+ }
157
+ const value = unquote(item[1].trim());
158
+ if (value.length > 0) items.push(value);
159
+ }
160
+ return items;
161
+ }
162
+ function unquote(value) {
163
+ const quoted = /^(['"])(.*)\1$/.exec(value);
164
+ return quoted === null ? value : quoted[2];
165
+ }
166
+
167
+ export {
168
+ requestToolAccess,
169
+ agentsWithoutRequestTool
170
+ };
171
+ //# sourceMappingURL=chunk-S2NRVRPF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/agent-tools.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\n\n/**\n * CAN THIS SUBAGENT CALL `request` AT ALL? An offer to an agent whose definition\n * leaves the tool out is a line it cannot act on, and a router call spent to\n * write it. Claude Code defines a custom agent in a Markdown file whose\n * frontmatter may carry `tools:` (an allowlist) and `disallowedTools:`; this\n * reads that, and nothing else, and never writes to it.\n *\n * ONLY `allowed` IS ACTED ON. A subagent is redirected or offered a lookup\n * only when this KNOWS it can make the call: a definition whose tools cover\n * the request tool (or that has no `tools:` and so inherits everything), or a\n * built-in in {@link MCP_INHERITING_BUILTINS}. Every other built-in, and any\n * type with no definition this can find or read, is `unknown`, and `unknown`\n * gets no router call: `claude-code-guide` ships with Bash, Read, WebFetch and\n * WebSearch and no MCP tools, and denying its WebFetch would strand it exactly\n * as #377 reported.\n *\n * WHERE A DEFINITION LIVES, in the harness's own precedence: the project's\n * `.claude/agents` (from `cwd` up to the filesystem root, nearest first), then\n * `~/.claude/agents`, then an installed plugin's `agents/` for a `plugin:agent`\n * type. A file is found by its name first and by its frontmatter `name:`\n * second, because the type is the `name:` and the file name only usually\n * matches it.\n */\n\nexport type RequestToolAccess = 'allowed' | 'excluded' | 'unknown';\n\n/**\n * The built-in agent types that have no definition file and still inherit MCP\n * tools, so can call `mcp__x402__request`. From Claude Code's own Agent tool\n * listing (2.1.28x): `general-purpose` has every tool, and `Explore` and `Plan`\n * exclude only editing and agent tools, never MCP. Built-ins with a fixed tool\n * list, such as `claude-code-guide` (Bash, Read, WebFetch, WebSearch) and\n * `statusline-setup` (Read, Edit), are deliberately absent.\n */\nexport const MCP_INHERITING_BUILTINS: ReadonlySet<string> = new Set([\n 'general-purpose',\n 'Explore',\n 'Plan',\n]);\n\nexport interface AgentLookup {\n cwd?: string;\n homeDir: string;\n}\n\nconst MAX_AGENT_FILE_BYTES = 256 * 1024;\nconst TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;\n\nexport async function requestToolAccess(\n agentType: string | undefined,\n lookup: AgentLookup,\n): Promise<RequestToolAccess> {\n if (agentType === undefined || !TYPE_RE.test(agentType)) return 'unknown';\n try {\n const text = await findDefinition(agentType, lookup);\n if (text !== null) return accessOf(text);\n return MCP_INHERITING_BUILTINS.has(agentType) ? 'allowed' : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/** What one definition's frontmatter says about the request tool. */\nexport function accessOf(definition: string): RequestToolAccess {\n const frontmatter = frontmatterOf(definition);\n if (frontmatter === null) return 'unknown';\n const disallowed = listField(frontmatter, 'disallowedTools');\n if (disallowed !== undefined && disallowed.some(namesRequestTool)) return 'excluded';\n const tools = listField(frontmatter, 'tools');\n if (tools === undefined) return 'allowed';\n return tools.some(namesRequestTool) ? 'allowed' : 'excluded';\n}\n\n/**\n * Does one `tools:` or `disallowedTools:` entry cover the request tool? The\n * tool itself, the bare server, or any `*`-suffixed pattern the tool's name\n * starts with: `*`, `mcp__*`, `mcp__x402__*` and every prefix between.\n */\nfunction namesRequestTool(tool: string): boolean {\n if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;\n return tool.endsWith('*') && REQUEST_TOOL.startsWith(tool.slice(0, -1));\n}\n\n/**\n * Every custom agent this project and this user define whose tools leave the\n * request tool out, for `doctor` to name. Plugin agents are not listed: their\n * files are not the user's to edit.\n */\nexport async function agentsWithoutRequestTool(lookup: AgentLookup): Promise<string[]> {\n const found: string[] = [];\n const seen = new Set<string>();\n for (const directory of agentDirs(lookup)) {\n for (const { name, text } of await definitionsIn(directory)) {\n const type = nameOf(text) ?? name;\n if (seen.has(type)) continue;\n seen.add(type);\n if (accessOf(text) === 'excluded') found.push(type);\n }\n }\n return found.sort();\n}\n\nasync function findDefinition(agentType: string, lookup: AgentLookup): Promise<string | null> {\n for (const directory of agentDirs(lookup)) {\n const text = await definitionIn(directory, agentType);\n if (text !== null) return text;\n }\n const colon = agentType.indexOf(':');\n if (colon > 0) {\n const plugin = agentType.slice(0, colon);\n const agent = agentType.slice(colon + 1);\n for (const root of await pluginRoots(plugin, lookup.homeDir)) {\n const text = await definitionIn(join(root, 'agents'), agent);\n if (text !== null) return text;\n }\n }\n return null;\n}\n\nfunction agentDirs(lookup: AgentLookup): string[] {\n const dirs: string[] = [];\n if (lookup.cwd !== undefined && lookup.cwd.length > 0) {\n let current = resolve(lookup.cwd);\n for (;;) {\n dirs.push(join(current, '.claude', 'agents'));\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n }\n const user = join(resolve(lookup.homeDir), '.claude', 'agents');\n // The user's directory is also an ancestor of most projects; it counts once,\n // in its own place in the order.\n return [...dirs.filter((d) => d !== user), user];\n}\n\nasync function definitionIn(directory: string, agentType: string): Promise<string | null> {\n const direct = await readBounded(join(directory, `${agentType}.md`));\n if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;\n for (const { text } of await definitionsIn(directory)) {\n if (nameOf(text) === agentType) return text;\n }\n return null;\n}\n\nasync function definitionsIn(directory: string): Promise<{ name: string; text: string }[]> {\n let names: string[];\n try {\n names = (await readdir(directory)).filter((n) => n.endsWith('.md')).slice(0, 200);\n } catch {\n return [];\n }\n const out: { name: string; text: string }[] = [];\n for (const file of names) {\n const text = await readBounded(join(directory, file));\n if (text !== null) out.push({ name: file.slice(0, -3), text });\n }\n return out;\n}\n\n/** Install paths `installed_plugins.json` records for `<plugin>@<marketplace>`. */\nasync function pluginRoots(plugin: string, homeDir: string): Promise<string[]> {\n const raw = await readBounded(join(homeDir, '.claude', 'plugins', 'installed_plugins.json'));\n if (raw === null) return [];\n const parsed = JSON.parse(raw) as { plugins?: Record<string, unknown> };\n const roots: string[] = [];\n for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {\n if (key.split('@')[0] !== plugin || !Array.isArray(entries)) continue;\n for (const entry of entries) {\n const path = (entry as { installPath?: unknown }).installPath;\n if (typeof path === 'string' && path.length > 0) roots.push(path);\n }\n }\n return roots;\n}\n\nasync function readBounded(path: string): Promise<string | null> {\n try {\n const text = await readFile(path, 'utf8');\n return text.length > MAX_AGENT_FILE_BYTES ? null : text;\n } catch {\n return null;\n }\n}\n\nfunction frontmatterOf(text: string): string[] | null {\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n return end === -1 ? null : lines.slice(open + 1, end);\n}\n\nfunction nameOf(text: string): string | null {\n const frontmatter = frontmatterOf(text);\n if (frontmatter === null) return null;\n const line = frontmatter.find((l) => /^name\\s*:/.test(l));\n const value = line === undefined ? '' : unquote(line.slice(line.indexOf(':') + 1).trim());\n return value.length > 0 ? value : null;\n}\n\n/**\n * A top-level list field in the three spellings agent files use: `a, b, c`,\n * `[a, b]`, or a block of `- a` lines. `undefined` when the key is absent.\n */\nfunction listField(frontmatter: string[], key: string): string[] | undefined {\n const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\\\s*:`).test(l));\n if (index === -1) return undefined;\n const line = frontmatter[index]!;\n const inline = line.slice(line.indexOf(':') + 1).trim();\n if (inline.length > 0) {\n const body = inline.startsWith('[') && inline.endsWith(']') ? inline.slice(1, -1) : inline;\n return body\n .split(',')\n .map((part) => unquote(part.trim()))\n .filter((part) => part.length > 0);\n }\n const items: string[] = [];\n for (const next of frontmatter.slice(index + 1)) {\n const item = /^\\s+-\\s*(.*)$/.exec(next);\n if (item === null) {\n if (next.trim().length === 0) continue;\n break;\n }\n const value = unquote(item[1]!.trim());\n if (value.length > 0) items.push(value);\n }\n return items;\n}\n\nfunction unquote(value: string): string {\n const quoted = /^(['\"])(.*)\\1$/.exec(value);\n return quoted === null ? value : quoted[2]!;\n}\n"],"mappings":";;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,MAAM,eAAe;AAqChC,IAAM,0BAA+C,oBAAI,IAAI;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,uBAAuB,MAAM;AACnC,IAAM,UAAU;AAEhB,eAAsB,kBACpB,WACA,QAC4B;AAC5B,MAAI,cAAc,UAAa,CAAC,QAAQ,KAAK,SAAS,EAAG,QAAO;AAChE,MAAI;AACF,UAAM,OAAO,MAAM,eAAe,WAAW,MAAM;AACnD,QAAI,SAAS,KAAM,QAAO,SAAS,IAAI;AACvC,WAAO,wBAAwB,IAAI,SAAS,IAAI,YAAY;AAAA,EAC9D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,SAAS,YAAuC;AAC9D,QAAM,cAAc,cAAc,UAAU;AAC5C,MAAI,gBAAgB,KAAM,QAAO;AACjC,QAAM,aAAa,UAAU,aAAa,iBAAiB;AAC3D,MAAI,eAAe,UAAa,WAAW,KAAK,gBAAgB,EAAG,QAAO;AAC1E,QAAM,QAAQ,UAAU,aAAa,OAAO;AAC5C,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,MAAM,KAAK,gBAAgB,IAAI,YAAY;AACpD;AAOA,SAAS,iBAAiB,MAAuB;AAC/C,MAAI,SAAS,gBAAgB,SAAS,QAAQ,eAAe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AAM,SAAS,KAAK,MAAM,KAAK,QAAQ,GAAG,IAAI,CAAC,EAAE,KAAK;AACtD,MAAI,OAAO,SAAS,GAAG;AACrB,UAAM,OAAO,OAAO,WAAW,GAAG,KAAK,OAAO,SAAS,GAAG,IAAI,OAAO,MAAM,GAAG,EAAE,IAAI;AACpF,WAAO,KACJ,MAAM,GAAG,EACT,IAAI,CAAC,SAAS,QAAQ,KAAK,KAAK,CAAC,CAAC,EAClC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC;AAAA,EACrC;AACA,QAAM,QAAkB,CAAC;AACzB,aAAW,QAAQ,YAAY,MAAM,QAAQ,CAAC,GAAG;AAC/C,UAAM,OAAO,gBAAgB,KAAK,IAAI;AACtC,QAAI,SAAS,MAAM;AACjB,UAAI,KAAK,KAAK,EAAE,WAAW,EAAG;AAC9B;AAAA,IACF;AACA,UAAM,QAAQ,QAAQ,KAAK,CAAC,EAAG,KAAK,CAAC;AACrC,QAAI,MAAM,SAAS,EAAG,OAAM,KAAK,KAAK;AAAA,EACxC;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,OAAuB;AACtC,QAAM,SAAS,iBAAiB,KAAK,KAAK;AAC1C,SAAO,WAAW,OAAO,QAAQ,OAAO,CAAC;AAC3C;","names":[]}
@@ -0,0 +1,11 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+
3
+ // src/router/names.ts
4
+ var MCP_SERVER_NAME = "x402";
5
+ var REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;
6
+
7
+ export {
8
+ MCP_SERVER_NAME,
9
+ REQUEST_TOOL
10
+ };
11
+ //# sourceMappingURL=chunk-TGLKKLQG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/names.ts"],"sourcesContent":["/**\n * THE NAMES THE HARNESS KNOWS THE ROUTER BY, spelled once. `install` registers\n * the MCP server under {@link MCP_SERVER_NAME}, and Claude Code exposes its tool\n * as {@link REQUEST_TOOL}; the permission rule, the server's own name and every\n * hint line the hooks inject all read these, so a rename moves them together.\n *\n * A module of its own because the hooks need the tool name and must not load\n * `install` to get it: their chunk graph is the product's floor.\n */\nexport const MCP_SERVER_NAME = 'x402';\nexport const REQUEST_TOOL = `mcp__${MCP_SERVER_NAME}__request`;\n"],"mappings":";;;AASO,IAAM,kBAAkB;AACxB,IAAM,eAAe,QAAQ,eAAe;","names":[]}
@@ -0,0 +1,127 @@
1
+ import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
+ import {
3
+ findAllProjectFiles,
4
+ findNearestProjectFiles,
5
+ mainWorktreeOf,
6
+ ownedCandidates,
7
+ projectRoot
8
+ } from "./chunk-PDA2BVFY.js";
9
+ import {
10
+ CONFIG_DEFAULTS,
11
+ loadRawConfig,
12
+ parseRouterLayer
13
+ } from "./chunk-AR7U7BRG.js";
14
+ import {
15
+ CliError
16
+ } from "./chunk-JLEF5WHM.js";
17
+ import {
18
+ configPath
19
+ } from "./chunk-2BKS2FVE.js";
20
+
21
+ // src/router/settings.ts
22
+ import { readFile } from "node:fs/promises";
23
+ import { homedir } from "node:os";
24
+ import { join, resolve } from "node:path";
25
+ var PROJECT_ROUTER_FILE = join(".tenjin", "config.json");
26
+ var LOCAL_ROUTER_FILE = join(".tenjin", "config.local.json");
27
+ async function routerSettings(input, deps = {}) {
28
+ const globalPath = configPath(input.dataDir);
29
+ const global = (input.config ?? await loadRawConfig(input.dataDir)).router;
30
+ let enabled = {
31
+ value: CONFIG_DEFAULTS.router.enabled,
32
+ source: "default"
33
+ };
34
+ let context = {
35
+ value: CONFIG_DEFAULTS.router.context,
36
+ source: "default"
37
+ };
38
+ if (global?.enabled !== void 0) {
39
+ enabled = { value: global.enabled, source: "file", path: globalPath };
40
+ }
41
+ if (global?.context !== void 0) {
42
+ context = { value: global.context, source: "file", path: globalPath };
43
+ }
44
+ for (const { source, path, layer } of await projectLayers(input, deps)) {
45
+ if (layer.enabled !== void 0 && (layer.enabled === false || enabled.value)) {
46
+ enabled = { value: layer.enabled, source, path };
47
+ }
48
+ if (layer.context !== void 0 && (layer.context === "turn" || context.value === "session")) {
49
+ context = { value: layer.context, source, path };
50
+ }
51
+ }
52
+ return { enabled, context };
53
+ }
54
+ var ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];
55
+ async function projectLayers(input, deps) {
56
+ const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {
57
+ ...deps,
58
+ // $HOME/.tenjin is the global scope, not a project.
59
+ homeIsProject: false
60
+ });
61
+ const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);
62
+ const outer = main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];
63
+ const layers = [];
64
+ for (const { dir, found } of [...outer, ...levels.reverse()]) {
65
+ if (resolve(dir, ".tenjin") === resolve(input.dataDir)) continue;
66
+ for (const path of found) {
67
+ const file = await readProjectRouterFile(path);
68
+ if (file === null) continue;
69
+ layers.push({
70
+ source: path === join(dir, LOCAL_ROUTER_FILE) ? "local" : "project",
71
+ path,
72
+ layer: file.layer
73
+ });
74
+ }
75
+ }
76
+ return layers;
77
+ }
78
+ var ABSENT = /* @__PURE__ */ new Set(["ENOENT", "ENOTDIR"]);
79
+ async function readProjectRouterFile(path) {
80
+ let raw;
81
+ try {
82
+ raw = await readFile(path, "utf8");
83
+ } catch (err) {
84
+ if (ABSENT.has(String(err.code))) return null;
85
+ throw invalid(path, "could not be read", err);
86
+ }
87
+ let json;
88
+ try {
89
+ json = JSON.parse(raw);
90
+ } catch (err) {
91
+ throw invalid(path, "is not valid JSON", err);
92
+ }
93
+ const layer = parseRouterLayer(json, path);
94
+ return { json, layer };
95
+ }
96
+ async function projectRouterPath(input, deps = {}) {
97
+ const home = deps.homeDir ?? homedir();
98
+ const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {
99
+ ...deps,
100
+ warn: () => void 0,
101
+ homeIsProject: false
102
+ });
103
+ const dir = hit?.dir ?? await projectRoot(input.cwd, home);
104
+ if (dir === home) {
105
+ throw new CliError(
106
+ "USAGE",
107
+ "Your home directory is not a project: its .tenjin is the global config.",
108
+ {
109
+ fix: "Run it from inside the project, or drop --project to set it for this machine."
110
+ }
111
+ );
112
+ }
113
+ return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);
114
+ }
115
+ function invalid(path, what, cause) {
116
+ return new CliError("CONFIG_INVALID", `Config at ${path} ${what}`, {
117
+ fix: `Fix ${path}, or delete it.`,
118
+ ...cause !== void 0 ? { cause } : {}
119
+ });
120
+ }
121
+
122
+ export {
123
+ routerSettings,
124
+ readProjectRouterFile,
125
+ projectRouterPath
126
+ };
127
+ //# sourceMappingURL=chunk-TP4D47BY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/settings.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\nimport {\n CONFIG_DEFAULTS,\n loadRawConfig,\n parseRouterLayer,\n type PartialConfig,\n type RouterContext,\n type RouterLayer,\n} from '../lib/config';\nimport { CliError } from '../lib/errors';\nimport { configPath } from '../lib/paths';\nimport {\n findAllProjectFiles,\n findNearestProjectFiles,\n mainWorktreeOf,\n ownedCandidates,\n projectRoot,\n type ProjectWalkDeps,\n} from '../lib/settings';\n\n/**\n * THE ONE READER OF THE ROUTER'S OWN KEYS, `router.enabled` and\n * `router.context`. Both hooks, the `request` tool, doctor, the status line and\n * `tenjin config` call {@link routerSettings} first, and nothing reads a router\n * key any other way.\n *\n * THE LAYERS: the default, `~/.tenjin/config.json`, then EVERY\n * `.tenjin/config.json` and `config.local.json` from the working directory up\n * to the git root, and in a linked git worktree the main checkout's pair too.\n * No environment variable.\n *\n * EVERY LAYER IS A FLOOR. `enabled` is false when any layer says false, and\n * `context` is `turn` when any layer says turn; a key a file leaves out\n * inherits, and a looser value is not read. So a file a cloned repository\n * carries cannot undo `tenjin config set router.enabled false` on this\n * machine, a package in a monorepo cannot undo its root, and a\n * `config.local.json` a repository commits anyway cannot undo the committed\n * one. Both keys fail toward less data sent, and no project file has a spend\n * key to loosen. The source reported is the nearest layer at the value.\n *\n * ONE PARSER. The global block is the one `loadRawConfig` already validated,\n * and a project file goes through `parseRouterLayer` from the same schema.\n */\n\n/** The committed project file and the personal one beside it. */\nexport const PROJECT_ROUTER_FILE = join('.tenjin', 'config.json');\nexport const LOCAL_ROUTER_FILE = join('.tenjin', 'config.local.json');\n\nexport type RouterSource = 'default' | 'file' | 'project' | 'local';\n\nexport interface RouterSetting<T> {\n value: T;\n source: RouterSource;\n /** The file that set it; absent for the default. */\n path?: string;\n}\n\nexport interface RouterSettings {\n enabled: RouterSetting<boolean>;\n context: RouterSetting<RouterContext>;\n}\n\nexport interface RouterSettingsInput {\n /** The directory the harness is working in. */\n cwd: string;\n /** The data dir whose `config.json` is the global layer. */\n dataDir: string;\n /** That file, when the caller has already loaded it; read here otherwise. */\n config?: PartialConfig;\n}\n\nexport async function routerSettings(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps = {},\n): Promise<RouterSettings> {\n const globalPath = configPath(input.dataDir);\n const global = (input.config ?? (await loadRawConfig(input.dataDir))).router;\n let enabled: RouterSetting<boolean> = {\n value: CONFIG_DEFAULTS.router.enabled,\n source: 'default',\n };\n let context: RouterSetting<RouterContext> = {\n value: CONFIG_DEFAULTS.router.context,\n source: 'default',\n };\n if (global?.enabled !== undefined) {\n enabled = { value: global.enabled, source: 'file', path: globalPath };\n }\n if (global?.context !== undefined) {\n context = { value: global.context, source: 'file', path: globalPath };\n }\n\n for (const { source, path, layer } of await projectLayers(input, deps)) {\n // Every layer is a floor: a value looser than the one so far is not read.\n if (layer.enabled !== undefined && (layer.enabled === false || enabled.value)) {\n enabled = { value: layer.enabled, source, path };\n }\n if (layer.context !== undefined && (layer.context === 'turn' || context.value === 'session')) {\n context = { value: layer.context, source, path };\n }\n }\n return { enabled, context };\n}\n\nconst ROUTER_FILES = [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE];\n\n/**\n * Every project layer, outermost first so the nearest one at a value is the\n * one reported: the main checkout's pair when this is a linked worktree, then\n * each directory from the git root down to `cwd`, its project file before its\n * personal one.\n */\nasync function projectLayers(\n input: RouterSettingsInput,\n deps: ProjectWalkDeps,\n): Promise<{ source: 'project' | 'local'; path: string; layer: RouterLayer }[]> {\n const { levels, gitRoot } = await findAllProjectFiles(input.cwd, ROUTER_FILES, {\n ...deps,\n // $HOME/.tenjin is the global scope, not a project.\n homeIsProject: false,\n });\n const main = gitRoot === null ? null : await mainWorktreeOf(gitRoot, deps.homeDir);\n const outer =\n main === null ? [] : [{ dir: main, found: await ownedCandidates(main, ROUTER_FILES, deps) }];\n const layers = [];\n for (const { dir, found } of [...outer, ...levels.reverse()]) {\n // A data dir kept inside a project is the global file, already read.\n if (resolve(dir, '.tenjin') === resolve(input.dataDir)) continue;\n for (const path of found) {\n const file = await readProjectRouterFile(path);\n if (file === null) continue;\n layers.push({\n source: path === join(dir, LOCAL_ROUTER_FILE) ? ('local' as const) : ('project' as const),\n path,\n layer: file.layer,\n });\n }\n }\n return layers;\n}\n\nconst ABSENT = new Set(['ENOENT', 'ENOTDIR']);\n\n/**\n * One project file: its whole JSON, for a writer that keeps sibling keys, and\n * its router layer through the one parser. Null when there is no file.\n */\nexport async function readProjectRouterFile(\n path: string,\n): Promise<{ json: Record<string, unknown>; layer: RouterLayer } | null> {\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n if (ABSENT.has(String((err as { code?: unknown }).code))) return null;\n throw invalid(path, 'could not be read', err);\n }\n let json: unknown;\n try {\n json = JSON.parse(raw);\n } catch (err) {\n throw invalid(path, 'is not valid JSON', err);\n }\n const layer = parseRouterLayer(json, path);\n return { json: json as Record<string, unknown>, layer };\n}\n\n/**\n * Where `tenjin config set --project [--local]` writes from `cwd`: beside the\n * layer {@link routerSettings} already reads there, else at the git root, else\n * in `cwd`. Never in $HOME, whose `.tenjin/config.json` is the global file.\n */\nexport async function projectRouterPath(\n input: { cwd: string; local: boolean },\n deps: ProjectWalkDeps = {},\n): Promise<string> {\n const home = deps.homeDir ?? homedir();\n const hit = await findNearestProjectFiles(input.cwd, [PROJECT_ROUTER_FILE, LOCAL_ROUTER_FILE], {\n ...deps,\n warn: () => undefined,\n homeIsProject: false,\n });\n const dir = hit?.dir ?? (await projectRoot(input.cwd, home));\n if (dir === home) {\n throw new CliError(\n 'USAGE',\n 'Your home directory is not a project: its .tenjin is the global config.',\n {\n fix: 'Run it from inside the project, or drop --project to set it for this machine.',\n },\n );\n }\n return join(dir, input.local ? LOCAL_ROUTER_FILE : PROJECT_ROUTER_FILE);\n}\n\nfunction invalid(path: string, what: string, cause?: unknown): CliError {\n return new CliError('CONFIG_INVALID', `Config at ${path} ${what}`, {\n fix: `Fix ${path}, or delete it.`,\n ...(cause !== undefined ? { cause } : {}),\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AA6CvB,IAAM,sBAAsB,KAAK,WAAW,aAAa;AACzD,IAAM,oBAAoB,KAAK,WAAW,mBAAmB;AAyBpE,eAAsB,eACpB,OACA,OAAwB,CAAC,GACA;AACzB,QAAM,aAAa,WAAW,MAAM,OAAO;AAC3C,QAAM,UAAU,MAAM,UAAW,MAAM,cAAc,MAAM,OAAO,GAAI;AACtE,MAAI,UAAkC;AAAA,IACpC,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,UAAwC;AAAA,IAC1C,OAAO,gBAAgB,OAAO;AAAA,IAC9B,QAAQ;AAAA,EACV;AACA,MAAI,QAAQ,YAAY,QAAW;AACjC,cAAU,EAAE,OAAO,OAAO,SAAS,QAAQ,QAAQ,MAAM,WAAW;AAAA,E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,CAAC;AACH;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  CliError
4
- } from "./chunk-OCBHUHWB.js";
4
+ } from "./chunk-JLEF5WHM.js";
5
5
 
6
6
  // src/lib/money.ts
7
7
  var USDC_DECIMALS = 6;
@@ -40,11 +40,6 @@ function toMoney(atomic) {
40
40
  return { atomic, usd: atomicToUsd(atomic) };
41
41
  }
42
42
 
43
- // src/lib/errno.ts
44
- function hasCode(err, code) {
45
- return typeof err === "object" && err !== null && "code" in err && err.code === code;
46
- }
47
-
48
43
  // src/lib/policy.ts
49
44
  function normCreator(value) {
50
45
  return value.trim().toLowerCase();
@@ -108,10 +103,9 @@ function parseConfirmPolicy(stored) {
108
103
  }
109
104
 
110
105
  export {
111
- hasCode,
112
106
  parseUsdToAtomic,
113
107
  toMoney,
114
108
  evaluateSpendPolicy,
115
109
  parseConfirmPolicy
116
110
  };
117
- //# sourceMappingURL=chunk-WH7OWT6G.js.map
111
+ //# sourceMappingURL=chunk-U2DZISAH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/money.ts","../src/lib/policy.ts"],"sourcesContent":["import { CliError } from './errors';\nimport { ATOMIC_RE } from './ids';\nimport type { Money } from '../schemas';\n\n/** USDC is a 6-decimal token; one dollar is 1_000_000 atomic units. */\nconst USDC_DECIMALS = 6;\n\n/**\n * Decimal USD at the CLI edge -> atomic USDC string (O1). Accepts \"0\", \"0.25\",\n * \"5\"; rejects negatives, non-numeric input, and more than 6 decimal places as\n * USAGE so a fat-fingered amount fails loudly instead of truncating money.\n * String math throughout — a float would lose precision at the 6th decimal.\n */\nexport function parseUsdToAtomic(input: string): string {\n const trimmed = input.trim();\n if (!/^\\d+(\\.\\d+)?$/.test(trimmed)) {\n throw new CliError('USAGE', `Invalid USD amount: ${JSON.stringify(input)}`, {\n fix: 'Pass a non-negative decimal like 0.25 or 5.',\n });\n }\n const [whole, frac = ''] = trimmed.split('.');\n if (frac.length > USDC_DECIMALS) {\n throw new CliError(\n 'USAGE',\n `USD amount ${JSON.stringify(input)} has more than 6 decimal places`,\n {\n fix: 'USDC supports at most 6 decimal places (micro-dollars).',\n },\n );\n }\n const atomic = BigInt(`${whole}${frac.padEnd(USDC_DECIMALS, '0')}`);\n return atomic.toString();\n}\n\n/**\n * Atomic USDC string -> decimal USD string, trailing zeros trimmed (\"250000\" ->\n * \"0.25\", \"5000000\" -> \"5\", \"0\" -> \"0\"). Throws INTERNAL on a malformed atomic\n * value: atomic strings come from validated config or on-chain reads, so a bad\n * one is a bug, not user input.\n */\nexport function atomicToUsd(atomic: string): string {\n const trimmed = atomic.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new CliError('INTERNAL', `Malformed atomic amount: ${JSON.stringify(atomic)}`);\n }\n const value = BigInt(trimmed);\n const base = 10n ** BigInt(USDC_DECIMALS);\n const whole = value / base;\n const frac = (value % base).toString().padStart(USDC_DECIMALS, '0').replace(/0+$/, '');\n return frac.length > 0 ? `${whole}.${frac}` : whole.toString();\n}\n\n/**\n * Whether an atomic price would actually cost something: true paid, false free,\n * null when the string is not an atomic amount at all and so cannot answer.\n *\n * A Tenjin piece may be priced at zero and is then delivered by `read` with no\n * payment, so \"there is a price field\" and \"there is a purchase to make\" are\n * different questions. The third state is not decoration: only the wire schema\n * enforces ATOMIC_RE, and the local search store types `price` as a bare string,\n * so a hand-edited or half-written entry can hold \"-1\" or \"0.1\". Those must not\n * read as \"free\", or corrupt local data would start refusing honest reports.\n * Never throws, which is why the check is a regex and not a BigInt compare.\n *\n * Matched against the RAW string, with no trimming. The contract carries the\n * canonical form and nothing else, so \" 0 \" did not come off the wire; padding is\n * evidence the value was edited, and normalizing it away would launder a corrupt\n * entry into a confident \"free\" and hand back the false refusal this avoids.\n */\nexport function isPaidPrice(atomic: string): boolean | null {\n if (!ATOMIC_RE.test(atomic)) return null;\n return /[1-9]/.test(atomic);\n}\n\n/** Dual-form money object for machine output. */\nexport function toMoney(atomic: string): Money {\n return { atomic, usd: atomicToUsd(atomic) };\n}\n\n/**\n * Canonical USD for human COPY (a price a person reads): always at least two\n * decimals (\"0.10\", \"5.00\"), keeping any finer precision below a cent\n * (\"0.000001\"). Distinct from `atomicToUsd`, which trims to the shortest exact\n * form for machine output; use this only where a dollar amount is shown to a human.\n */\nexport function formatUsdDisplay(atomic: string): string {\n const [whole, frac = ''] = atomicToUsd(atomic).split('.');\n return `${whole}.${frac.padEnd(2, '0')}`;\n}\n","/**\n * Spend-policy evaluation, pure and provider-agnostic. The wallet provider layer\n * (lib/wallet/spend.ts) owns the ledger and calls this; a future hosted provider\n * (Privy, B5) reuses the same decision rules, so the knobs live in exactly one\n * place. Nothing here does IO, the caller supplies the already-spent total and\n * decides how to satisfy a `confirm` decision (a `--yes`, a TTY prompt, or a\n * non-interactive refusal).\n */\n\n/** How a `confirm` gate is configured (parsed from the stored config string). */\nexport type ConfirmPolicy = { mode: 'always' } | { mode: 'above'; thresholdAtomic: bigint };\n\nexport interface SpendPolicy {\n /** Amounts at or below this auto-approve WITHOUT a prompt (still subject to the\n * confirm gate below). Default 0 → nothing auto-approves. */\n maxAutoSpendAtomic: bigint;\n /** Rolling local ceiling on cumulative session spend. 0 = disabled (no ceiling). */\n sessionBudgetAtomic: bigint;\n /** When a human confirmation is requested. */\n confirm: ConfirmPolicy;\n /** Creators (handle or 0x-address, lowercased) auto-payment is restricted to.\n * Empty = no restriction. A non-empty list is a hard gate: a non-member is\n * denied even with `--yes`. */\n allowlistCreators: string[];\n}\n\nexport interface SpendRequest {\n amountAtomic: bigint;\n /** Creator identity from the 402 preview / candidate, handle or 0x address. */\n creator: string;\n /** The caller's `--max-price` cap, if given. A hard ceiling, never bypassable. */\n maxPriceAtomic?: bigint;\n /** Cumulative spend already recorded in this rolling session window. */\n sessionSpentAtomic: bigint;\n}\n\n/**\n * `allow`: within policy, proceed silently. `confirm`: an approval is required ,\n * the caller satisfies it with `--yes`, an interactive prompt, or refuses. `deny`:\n * a hard gate blocked it (price cap, allowlist, session budget); NOT satisfiable\n * by `--yes` or a prompt.\n */\nexport type SpendDecision = 'allow' | 'confirm' | 'deny';\n\n/**\n * `duplicate_in_flight` is the one reason this pure evaluator never returns: it\n * is a fact about the ledger (an identical request already holds a reservation\n * in this turn), so the authorizer raises it. It lives in the union because\n * every caller renders a decision's reason from one vocabulary.\n */\nexport type PolicyReason =\n | 'within_policy'\n | 'duplicate_in_flight'\n | 'price_cap_exceeded'\n | 'not_allowlisted'\n | 'session_budget_exceeded'\n | 'above_auto_spend'\n | 'confirm_always'\n | 'above_confirm_threshold';\n\nexport interface PolicyEvaluation {\n decision: SpendDecision;\n reason: PolicyReason;\n message: string;\n}\n\n/** Normalize a creator identity for allowlist comparison (case-insensitive; a\n * word-handle and a 0x address are both single tokens). */\nfunction normCreator(value: string): string {\n return value.trim().toLowerCase();\n}\n\n/**\n * Evaluate one spend against the policy. Hard gates run first (price cap →\n * allowlist → session budget); only if all pass is the confirm gate consulted. A\n * spend at or below `maxAutoSpend` that the confirm policy would not prompt for is\n * the only `allow`; everything else within the hard gates is `confirm`.\n */\nexport function evaluateSpendPolicy(policy: SpendPolicy, req: SpendRequest): PolicyEvaluation {\n if (req.maxPriceAtomic !== undefined && req.amountAtomic > req.maxPriceAtomic) {\n return {\n decision: 'deny',\n reason: 'price_cap_exceeded',\n message: `Price ${req.amountAtomic} exceeds the --max-price cap ${req.maxPriceAtomic}.`,\n };\n }\n\n if (policy.allowlistCreators.length > 0) {\n const allowed = policy.allowlistCreators.map(normCreator);\n if (!allowed.includes(normCreator(req.creator))) {\n return {\n decision: 'deny',\n reason: 'not_allowlisted',\n message: `Creator \"${req.creator}\" is not in allowlistCreators.`,\n };\n }\n }\n\n if (policy.sessionBudgetAtomic > 0n) {\n const projected = req.sessionSpentAtomic + req.amountAtomic;\n if (projected > policy.sessionBudgetAtomic) {\n return {\n decision: 'deny',\n reason: 'session_budget_exceeded',\n message: `This spend would bring the session total to ${projected}, over sessionBudget ${policy.sessionBudgetAtomic}.`,\n };\n }\n }\n\n if (req.amountAtomic > policy.maxAutoSpendAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_auto_spend',\n message: `Price ${req.amountAtomic} is above maxAutoSpend ${policy.maxAutoSpendAtomic}; confirmation required.`,\n };\n }\n\n if (policy.confirm.mode === 'always') {\n return {\n decision: 'confirm',\n reason: 'confirm_always',\n message: 'confirm policy is \"always\"; confirmation required.',\n };\n }\n\n if (req.amountAtomic > policy.confirm.thresholdAtomic) {\n return {\n decision: 'confirm',\n reason: 'above_confirm_threshold',\n message: `Price ${req.amountAtomic} is above the confirm threshold ${policy.confirm.thresholdAtomic}; confirmation required.`,\n };\n }\n\n return { decision: 'allow', reason: 'within_policy', message: 'within spend policy' };\n}\n\n/** Parse the stored `confirm` config value (\"always\" | \"above:<atomic>\"). */\nexport function parseConfirmPolicy(stored: string): ConfirmPolicy {\n if (stored === 'always') return { mode: 'always' };\n const m = /^above:(\\d+)$/.exec(stored);\n if (m && m[1] !== undefined) return { mode: 'above', thresholdAtomic: BigInt(m[1]) };\n // The config schema already constrains this; a malformed value here is a bug,\n // so fail closed to the safest interpretation rather than throwing mid-buy.\n return { mode: 'always' };\n}\n"],"mappings":";;;;;;AAKA,IAAM,gBAAgB;AAQf,SAAS,iBAAiB,OAAuB;AACtD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,gBAAgB,KAAK,OAAO,GAAG;AAClC,UAAM,IAAI,SAAS,SAAS,uBAAuB,KAAK,UAAU,KAAK,CAAC,IAAI;AAAA,MAC1E,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,QAAM,CAAC,OAAO,OAAO,EAAE,IAAI,QAAQ,MAAM,GAAG;AAC5C,MAAI,KAAK,SAAS,eAAe;AAC/B,UAAM,IAAI;AAAA,MACR;AAAA,MACA,cAAc,KAAK,UAAU,KAAK,CAAC;AAAA,MACnC;AAAA,QACE,KAAK;AAAA,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,sBAAsB,IAAI;AACnC,UAAM,YAAY,IAAI,qBAAqB,IAAI;AAC/C,QAAI,YAAY,OAAO,qBAAqB;AAC1C,aAAO;AAAA,QACL,UAAU;AAAA,QACV,QAAQ;AAAA,QACR,SAAS,+CAA+C,SAAS,wBAAwB,OAAO,mBAAmB;AAAA,MACrH;AAAA,IACF;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,oBAAoB;AAChD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,0BAA0B,OAAO,kBAAkB;AAAA,IACvF;AAAA,EACF;AAEA,MAAI,OAAO,QAAQ,SAAS,UAAU;AACpC,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS;AAAA,IACX;AAAA,EACF;AAEA,MAAI,IAAI,eAAe,OAAO,QAAQ,iBAAiB;AACrD,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,SAAS,SAAS,IAAI,YAAY,mCAAmC,OAAO,QAAQ,eAAe;AAAA,IACrG;AAAA,EACF;AAEA,SAAO,EAAE,UAAU,SAAS,QAAQ,iBAAiB,SAAS,sBAAsB;AACtF;AAGO,SAAS,mBAAmB,QAA+B;AAChE,MAAI,WAAW,SAAU,QAAO,EAAE,MAAM,SAAS;AACjD,QAAM,IAAI,gBAAgB,KAAK,MAAM;AACrC,MAAI,KAAK,EAAE,CAAC,MAAM,OAAW,QAAO,EAAE,MAAM,SAAS,iBAAiB,OAAO,EAAE,CAAC,CAAC,EAAE;AAGnF,SAAO,EAAE,MAAM,SAAS;AAC1B;","names":[]}
@@ -2,10 +2,10 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
2
2
  import {
3
3
  fetchFailureToCliError,
4
4
  httpRequest
5
- } from "./chunk-5X4SZ5BF.js";
5
+ } from "./chunk-5QHHRMRA.js";
6
6
  import {
7
7
  external_exports
8
- } from "./chunk-BBVUVBUO.js";
8
+ } from "./chunk-AR7U7BRG.js";
9
9
 
10
10
  // src/router/decision.ts
11
11
  var ROUTER_PATH = "/api/x402-router";
@@ -41,8 +41,8 @@ var CapabilityFields = {
41
41
  /** The service's own name, not the x402 reseller in front of it. */
42
42
  provider: external_exports.string().min(1).max(120),
43
43
  capabilityDescription: external_exports.string().min(1).max(500),
44
- /** What the provider charges, atomic USDC. DISPLAY ONLY: the amount actually
45
- * signed is what `gateSpend` caps. */
44
+ /** What the provider charges, atomic USDC. The `request` tool refuses a live
45
+ * 402 above it; `gateSpend` still caps the amount actually signed. */
46
46
  providerPriceAtomic: external_exports.string().regex(/^\d+$/)
47
47
  };
48
48
  var HookDecisionSchema = external_exports.discriminatedUnion("action", [
@@ -162,4 +162,4 @@ export {
162
162
  ROUTER_PATH,
163
163
  requestDecision
164
164
  };
165
- //# sourceMappingURL=chunk-USS336NF.js.map
165
+ //# sourceMappingURL=chunk-WGQVJM56.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/router/decision.ts"],"sourcesContent":["import { z } from 'zod';\nimport { fetchFailureToCliError, httpRequest } from '../lib/http';\nimport type { HttpRequestOptions, HttpResult } from '../lib/http';\nimport type { CommandContext } from '../context';\nimport type { Packet } from './context';\n\n/**\n * `POST /api/x402-router`: ONE FREE DECISION PER LOOKUP.\n *\n * The routing decision costs nothing and nobody signs for it. The hook asks for\n * it from the user's own words, the backend answers with what it would do and\n * what the provider charges, and the only payment on the wire is the one\n * `runPay` makes to that provider. That deletes the router fee and everything\n * built to carry it: the 402 probe, the requirements cache, the stale-quote\n * retry, the settlement accounting and one Base settlement of about 1.5 s from\n * every paid lookup.\n *\n * NOTHING IS STORED LOCALLY. The bounded packet travels with the request and\n * the backend keeps it against the decision id until that id expires, which is\n * how `request({query})` reaches the same calibrated input with no session\n * file, no timestamp latch and no guess about which window this process serves.\n */\n\nexport const ROUTER_PATH = '/api/x402-router';\n\n/**\n * The request the server builds and this client sends verbatim. Query assembly,\n * body encoding and header choice are the server's; what stays here is every\n * check that decides whether to send it at all.\n */\nconst RequestSchema = z.object({\n url: z.string().min(1).max(16_384),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),\n headers: z.record(z.string(), z.string()),\n body: z\n .string()\n .max(256 * 1024)\n .optional(),\n});\n\nconst ContractSchema = z.object({\n /** Flat, for display and for the result check; never re-encoded into a call:\n * the server built `request` from them and this client sends that verbatim. */\n arguments: z.record(z.string(), z.unknown()).optional(),\n resultSchema: z.record(z.string(), z.unknown()).optional(),\n request: RequestSchema,\n});\nexport type DecisionContract = z.infer<typeof ContractSchema>;\n\n/**\n * What stopped an outcome this client cannot execute, in terms the host can act\n * on: a stable reason code, the stage that stopped, the fields or scope choices\n * the user can supply, and one concrete next action.\n */\nconst DiagnosticsSchema = z.object({\n reasonCode: z.string().min(1).max(64),\n stage: z.string().min(1).max(32),\n missing: z.array(z.string().max(200)).max(60),\n nextAction: z.string().max(500),\n});\nexport type DecisionDiagnostics = z.infer<typeof DiagnosticsSchema>;\n\n/**\n * ONE VARIANT PER ANSWER, DISCRIMINATED ON THE ACTION. Optional fields made\n * every shape legal: an `execute` with no contract parsed and came back to the\n * host as a routine `needs_input`, a non-execute with no diagnostics parsed\n * with nothing to act on, and a hook answer carrying a contract parsed as\n * though the hook had quoted a price. Each of those is drift the shared\n * fixtures exist to catch, so each is now a parse failure that names itself.\n *\n * The two calls ask different questions and get different answers, so they get\n * different parsers. The HOOK asks whether a paid lookup is worth offering: an\n * id, or a reason it is not. The TOOL asks for the decision: the capability,\n * its price and the contract together, so a caller cannot approve one offer and\n * receive another.\n */\nconst IdSchema = z\n .string()\n .regex(/^[A-Za-z0-9_-]{8,64}$/)\n .describe(\n 'The turn id, an OPAQUE HANDLE: it is the one piece of server text this ' +\n 'client puts in a model-facing line, so the alphabet is pinned here ' +\n 'rather than escaped later.',\n );\n\n/** Every non-execute answer carries these, beside the action they explain. */\nconst RefusedSchema = z.strictObject({\n reason: z.string().max(2_000).optional(),\n diagnostics: DiagnosticsSchema,\n});\n\n/**\n * WHAT THE SERVICE IS, AND WHAT IT DOES. The hook answer used to be an id and\n * nothing else, so the line the host injected could only say \"a paid lookup is\n * available\", which a model follows 8 to 20 times in 40 where a line naming the\n * task and the service is followed 40 in 40. The gate knows which capability\n * serves the category it chose, so it now says so; the CONTRACT is still not\n * here, because the task the host will run does not exist yet.\n */\nconst CapabilityFields = {\n capabilityId: z.string().min(1).max(200),\n category: z.string().min(1).max(64),\n /** The service's own name, not the x402 reseller in front of it. */\n provider: z.string().min(1).max(120),\n capabilityDescription: z.string().min(1).max(500),\n /** What the provider charges, atomic USDC. The `request` tool refuses a live\n * 402 above it; `gateSpend` still caps the amount actually signed. */\n providerPriceAtomic: z.string().regex(/^\\d+$/),\n};\n\nconst HookDecisionSchema = z.discriminatedUnion('action', [\n z\n .strictObject({\n action: z.literal('execute'),\n id: IdSchema,\n ...CapabilityFields,\n /** The x402 URL a lookup would pay, for the line the server writes. */\n endpoint: z.string().min(1).max(2_048),\n /** What to pass in `query`, in the service's own terms. */\n usage: z.string().min(1).max(300),\n /**\n * THE LINE, FINISHED. The server writes it with the real id in it and, on a\n * native call, the exact search or URL that was denied. The client injects\n * it and composes nothing, which is why there is no hint builder here any\n * more: two sides writing the same sentence is how they drift.\n */\n hint: z.string().min(1).max(1_000),\n })\n .superRefine((decision, ctx) => {\n // STRUCTURE, NEVER WORDING. This line lands in the model's context\n // verbatim, so the shape is checked the way the id's alphabet is: one\n // line, no control characters, and it has to be the call it claims to be,\n // naming the id this same answer carries. A hint that fails any of these\n // is a protocol error and the turn falls back to the generic line; nothing\n // here rewrites a word of a hint that passes.\n if (/[\\p{Cc}\\p{Cf}]/u.test(decision.hint)) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint is one plain line' });\n }\n if (!decision.hint.includes('request({')) {\n ctx.addIssue({ code: 'custom', path: ['hint'], message: 'a hint names the call to make' });\n }\n if (!decision.hint.includes(decision.id)) {\n ctx.addIssue({\n code: 'custom',\n path: ['hint'],\n message: \"a hint carries this answer's own id\",\n });\n }\n }),\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nconst ToolDecisionSchema = z.discriminatedUnion('action', [\n z.strictObject({\n action: z.literal('execute'),\n ...CapabilityFields,\n contract: ContractSchema,\n }),\n RefusedSchema.extend({ action: z.literal('native') }),\n RefusedSchema.extend({ action: z.literal('needs_input') }),\n]);\n\nfunction envelope<T extends z.ZodTypeAny>(decision: T) {\n return z.strictObject({\n schemaVersion: z.literal(1),\n routerVersion: z.string().min(1).max(64),\n decision,\n /** A plain sentence about the CALL, such as an id that had expired. Never a\n * failure: the decision beside it ran anyway. */\n note: z.string().max(500).optional(),\n jev: z.object({ calls: z.number(), latencyMs: z.number() }).optional(),\n });\n}\n\nconst HookResponseSchema = envelope(HookDecisionSchema);\nconst ToolResponseSchema = envelope(ToolDecisionSchema);\n\nexport type HookResponse = z.infer<typeof HookResponseSchema>;\nexport type ToolResponse = z.infer<typeof ToolResponseSchema>;\nexport type HookDecision = HookResponse['decision'];\nexport type ToolDecision = ToolResponse['decision'];\n\n/** Which call this is, and therefore which answer is legal for it. */\nexport type CallKind = 'hook' | 'tool';\n\n/**\n * The exact body the hook call sends, spelled once and pinned to the shared\n * fixtures. The route reads it with a strict object, so an extra field is a\n * 400, and a 400 is a turn with no hint.\n *\n * ONE BODY FOR BOTH HOOKS. Which hook is asking is not a field: the route reads\n * it from `packet.pendingCall`, which the native hook sets and the prompt hook\n * does not. A `source` beside the packet was the `/prepare` route's shape, and\n * that route is gone.\n */\nexport function buildHookBody(packet: Packet): Record<string, unknown> {\n return { schemaVersion: 1, packet };\n}\n\n/** The exact body the tool call sends. `id` is the turn whose packet decides\n * with this query; `gateHint` is evidence, never authority. */\nexport function buildToolBody(request: {\n query: string;\n id?: string;\n gateHint?: GateHint;\n}): Record<string, unknown> {\n return {\n schemaVersion: 1,\n query: request.query,\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n };\n}\n\n/** The parsers, exposed so the shared wire fixtures are checked against the\n * same schemas production parses with rather than against a copy of them. */\nexport function parseForTests(kind: CallKind, value: unknown): { success: boolean } {\n const schema = kind === 'hook' ? HookResponseSchema : ToolResponseSchema;\n return { success: schema.safeParse(value).success };\n}\n\n/**\n * The gate's own reading of this turn, travelling as EVIDENCE for the lookup it\n * was produced for. The backend may refine or reject it, and it authorizes no\n * money: the local spend policy does that. Optional on both call forms.\n */\nexport interface GateHint {\n category: string;\n turnId: string;\n lookupId: string;\n}\n\nexport interface DecisionDeps {\n ctx: CommandContext;\n baseUrl: string;\n fetchImpl?: typeof fetch;\n /** Overrides the per-call deadline; the hook passes its own, smaller one. */\n timeoutMs?: number;\n}\n\nexport type DecisionOutcome<T> =\n | { status: 'decided'; decision: T }\n /** Nothing was paid and nothing could be: the endpoint is free, so a failure\n * here costs the turn a routing answer and nothing else. */\n | { status: 'failed'; reason: string; errorCode?: string };\n\n/**\n * ONE FREE CALL, IN TWO FORMS. The hook sends `{ packet }`: the backend runs\n * the gate, and on `execute` stores that packet under an id. The tool sends\n * `{ query, id? }`: the backend makes THE decision from that query plus the\n * packet it stored, and answers with the contract to run.\n *\n * The tool never sends a packet of its own. The turn's context lives on the\n * backend against the id, and the query the model wrote is what the routing\n * corpus is calibrated against: 55 of 56 for query plus packet, 53 of 56 for\n * the raw prompt, measured on jev-1.13.0.\n */\nexport async function requestDecision(\n kind: 'hook',\n request: { packet: Packet },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse>>;\nexport async function requestDecision(\n kind: 'tool',\n request: { query: string; id?: string; gateHint?: GateHint },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<ToolResponse>>;\nexport async function requestDecision(\n kind: CallKind,\n request: {\n query?: string;\n packet?: Packet;\n id?: string;\n gateHint?: GateHint;\n },\n deps: DecisionDeps,\n): Promise<DecisionOutcome<HookResponse | ToolResponse>> {\n const url = new URL(ROUTER_PATH, deps.baseUrl).toString();\n const options: HttpRequestOptions = {\n method: 'POST',\n timeoutMs: deps.timeoutMs ?? deps.ctx.flags.timeout,\n blockRedirects: true,\n jsonBody:\n kind === 'hook'\n ? buildHookBody(request.packet as Packet)\n : buildToolBody({\n query: request.query as string,\n ...(request.id !== undefined ? { id: request.id } : {}),\n ...(request.gateHint !== undefined ? { gateHint: request.gateHint } : {}),\n }),\n ...(deps.fetchImpl !== undefined ? { fetchImpl: deps.fetchImpl } : {}),\n };\n return readDecision(\n await httpRequest(url, options),\n kind === 'hook' ? HookResponseSchema : ToolResponseSchema,\n );\n}\n\nfunction readDecision<T extends z.ZodTypeAny>(\n response: HttpResult,\n schema: T,\n): DecisionOutcome<z.infer<T>> {\n // A transport failure says its own reason; nothing was paid either way,\n // because there is nothing to pay for on this route.\n if (!response.ok) return { status: 'failed', reason: fetchFailureToCliError(response).message };\n if (response.status < 200 || response.status >= 300) {\n const named = errorOf(response.json);\n return {\n status: 'failed',\n // The backend's own code and message, never a bare status line: a typed\n // refusal the host could act on was arriving as \"answered 400\".\n reason:\n named === null\n ? `The router endpoint answered ${response.status}.`\n : `The router endpoint answered ${response.status} (${named.code}): ${named.message}`,\n ...(named !== null ? { errorCode: named.code } : {}),\n };\n }\n const parsed = schema.safeParse(response.json);\n if (!parsed.success) {\n return { status: 'failed', reason: 'The router returned a decision this build cannot read.' };\n }\n return { status: 'decided', decision: parsed.data as z.infer<T> };\n}\n\n/** `{ error: { code, message } }`, the envelope every Tenjin route answers a\n * refusal with. Anything else reads as no code rather than as a guess. */\nfunction errorOf(body: unknown): { code: string; message: string } | null {\n if (body === null || typeof body !== 'object') return null;\n const error = (body as { error?: unknown }).error;\n if (error === null || typeof error !== 'object') return null;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (typeof code !== 'string' || code.length === 0 || code.length > 64) return null;\n const text = typeof message === 'string' ? message.slice(0, 500) : '';\n return { code, message: text };\n}\n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AACxE,MAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO;AACtD,QAAM,QAAS,KAA6B;AAC5C,MAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AACxD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,KAAK,KAAK,SAAS,GAAI,QAAO;AAC9E,QAAM,OAAO,OAAO,YAAY,WAAW,QAAQ,MAAM,GAAG,GAAG,IAAI;AACnE,SAAO,EAAE,MAAM,SAAS,KAAK;AAC/B;","names":[]}
@@ -1,10 +1,10 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  external_exports
4
- } from "./chunk-BBVUVBUO.js";
4
+ } from "./chunk-AR7U7BRG.js";
5
5
  import {
6
6
  CliError
7
- } from "./chunk-OCBHUHWB.js";
7
+ } from "./chunk-JLEF5WHM.js";
8
8
 
9
9
  // src/lib/output.ts
10
10
  import { styleText } from "node:util";
@@ -228,4 +228,4 @@ export {
228
228
  sanitizeForTerminal,
229
229
  paint
230
230
  };
231
- //# sourceMappingURL=chunk-YJHHCWM3.js.map
231
+ //# sourceMappingURL=chunk-WLMJE3GJ.js.map
@@ -1,10 +1,10 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  hasCode
4
- } from "./chunk-WH7OWT6G.js";
4
+ } from "./chunk-2I4QTOLB.js";
5
5
  import {
6
6
  CliError
7
- } from "./chunk-OCBHUHWB.js";
7
+ } from "./chunk-JLEF5WHM.js";
8
8
 
9
9
  // src/lib/skills-source.ts
10
10
  import { existsSync } from "node:fs";
@@ -134,4 +134,4 @@ export {
134
134
  readSkillFile,
135
135
  skillFrontmatterName
136
136
  };
137
- //# sourceMappingURL=chunk-U5DXNFJC.js.map
137
+ //# sourceMappingURL=chunk-WS4JA6TC.js.map
@@ -1,11 +1,12 @@
1
1
  import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
2
2
  import {
3
3
  package_default
4
- } from "./chunk-BFFM2WFK.js";
4
+ } from "./chunk-5UDD5VSY.js";
5
5
  import {
6
6
  CliError,
7
- HARNESSES
8
- } from "./chunk-OCBHUHWB.js";
7
+ HARNESSES,
8
+ writeFileAtomic
9
+ } from "./chunk-JLEF5WHM.js";
9
10
  import {
10
11
  daemonBundlePath,
11
12
  daemonLogPath,
@@ -16,9 +17,6 @@ import {
16
17
  shimBundlePath,
17
18
  vitestReporterPath
18
19
  } from "./chunk-2BKS2FVE.js";
19
- import {
20
- writeFileAtomic
21
- } from "./chunk-7WEQQJLG.js";
22
20
 
23
21
  // src/lib/harness-permissions.ts
24
22
  import { chmod, lstat, mkdir, readFile, realpath, stat as stat2 } from "node:fs/promises";
@@ -1777,9 +1775,10 @@ export {
1777
1775
  claudeAdapter,
1778
1776
  ADAPTERS,
1779
1777
  ownsHookEntry,
1778
+ pruneOurHandlers,
1780
1779
  pruneHooks,
1781
1780
  inspectHooksFile,
1782
1781
  registeredHooks,
1783
1782
  writeHooks
1784
1783
  };
1785
- //# sourceMappingURL=chunk-SKAHDQH7.js.map
1784
+ //# sourceMappingURL=chunk-XZOEUYMX.js.map