tenjin-cli 0.1.0-alpha.2 → 0.1.0-alpha.21
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/NOTICE.md +54 -7
- package/README.md +175 -256
- package/dist/{_esm-FEASBWRP.js → _esm-CE7KNONL.js} +9 -10
- package/dist/{ccip-NQXCEK2U.js → ccip-7RMRLAGV.js} +4 -4
- package/dist/{ccip-XR5NE5QK.js → ccip-NLCSCHKI.js} +5 -5
- package/dist/chunk-2AQO4YDI.js +291 -0
- package/dist/chunk-2AQO4YDI.js.map +1 -0
- package/dist/chunk-2QYORQBF.js +55 -0
- package/dist/chunk-2QYORQBF.js.map +1 -0
- package/dist/chunk-3EUTWC2B.js +194 -0
- package/dist/chunk-3EUTWC2B.js.map +1 -0
- package/dist/{chunk-ZMHYXMO6.js → chunk-5IEP5EGE.js} +3 -3
- package/dist/chunk-7QKHZQKW.js +1680 -0
- package/dist/chunk-7QKHZQKW.js.map +1 -0
- package/dist/chunk-A36LQPHV.js +29 -0
- package/dist/chunk-A36LQPHV.js.map +1 -0
- package/dist/{chunk-XJIW7USF.js → chunk-AQRUD5GQ.js} +115 -11
- package/dist/chunk-AQRUD5GQ.js.map +1 -0
- package/dist/{chunk-UGX7YPX2.js → chunk-AWQPGIR6.js} +7 -9
- package/dist/{chunk-UGX7YPX2.js.map → chunk-AWQPGIR6.js.map} +1 -1
- package/dist/{chunk-5CLSD5YN.js → chunk-BPMWXTFX.js} +2 -2
- package/dist/chunk-C363JZN2.js +127 -0
- package/dist/chunk-C363JZN2.js.map +1 -0
- package/dist/{chunk-YALGASEU.js → chunk-EGELTSPU.js} +2 -2
- package/dist/chunk-ETW2ASBP.js +10562 -0
- package/dist/chunk-ETW2ASBP.js.map +1 -0
- package/dist/chunk-GHTPYKDT.js +112 -0
- package/dist/chunk-GHTPYKDT.js.map +1 -0
- package/dist/{chunk-CYOF7ROH.js → chunk-HPWO4O6S.js} +3 -3
- package/dist/chunk-IOB7URFH.js +242 -0
- package/dist/chunk-IOB7URFH.js.map +1 -0
- package/dist/chunk-IOIHYOU4.js +1784 -0
- package/dist/chunk-IOIHYOU4.js.map +1 -0
- package/dist/chunk-JLEF5WHM.js +132 -0
- package/dist/chunk-JLEF5WHM.js.map +1 -0
- package/dist/chunk-JN7TMXVF.js +172 -0
- package/dist/chunk-JN7TMXVF.js.map +1 -0
- package/dist/{chunk-QVX5MWJZ.js → chunk-JRGFKVAZ.js} +2 -2
- package/dist/chunk-K6AXXYCG.js +109 -0
- package/dist/chunk-K6AXXYCG.js.map +1 -0
- package/dist/{chunk-HIVZG55D.js → chunk-KG3D7FIF.js} +2 -2
- package/dist/chunk-LAIZ2AQA.js +107 -0
- package/dist/chunk-LAIZ2AQA.js.map +1 -0
- package/dist/chunk-LHHMV4GU.js +27 -0
- package/dist/chunk-LHHMV4GU.js.map +1 -0
- package/dist/{chunk-YBMMV4Y4.js → chunk-MEFB5KHA.js} +13 -5
- package/dist/chunk-MEFB5KHA.js.map +1 -0
- package/dist/{chunk-NCE5NSN6.js → chunk-N35E6CM2.js} +140 -10
- package/dist/chunk-N35E6CM2.js.map +1 -0
- package/dist/chunk-N4DJEQAF.js +190 -0
- package/dist/chunk-N4DJEQAF.js.map +1 -0
- package/dist/chunk-O2JYBOUO.js +47 -0
- package/dist/chunk-O2JYBOUO.js.map +1 -0
- package/dist/chunk-OSUD6YZZ.js +451 -0
- package/dist/chunk-OSUD6YZZ.js.map +1 -0
- package/dist/chunk-OTPEH3AH.js +926 -0
- package/dist/chunk-OTPEH3AH.js.map +1 -0
- package/dist/chunk-PJEG2JIJ.js +242 -0
- package/dist/chunk-PJEG2JIJ.js.map +1 -0
- package/dist/{chunk-ZABPQJ3M.js → chunk-POUWHWID.js} +2 -2
- package/dist/chunk-QF4SSCQV.js +377 -0
- package/dist/chunk-QF4SSCQV.js.map +1 -0
- package/dist/chunk-QHILSA6G.js +82 -0
- package/dist/chunk-QHILSA6G.js.map +1 -0
- package/dist/chunk-QRFONFRW.js +231 -0
- package/dist/chunk-QRFONFRW.js.map +1 -0
- package/dist/{chunk-N62ROTMC.js → chunk-RCJQARZF.js} +14 -10
- package/dist/chunk-RCJQARZF.js.map +1 -0
- package/dist/{chunk-S3IGX57D.js → chunk-RGVOODF4.js} +7703 -7475
- package/dist/chunk-RGVOODF4.js.map +1 -0
- package/dist/chunk-S2NRVRPF.js +171 -0
- package/dist/chunk-S2NRVRPF.js.map +1 -0
- package/dist/chunk-SRVDXR6B.js +337 -0
- package/dist/chunk-SRVDXR6B.js.map +1 -0
- package/dist/chunk-TGLKKLQG.js +11 -0
- package/dist/chunk-TGLKKLQG.js.map +1 -0
- package/dist/{chunk-RRN3YTK7.js → chunk-TTNESUPQ.js} +3 -3
- package/dist/chunk-U2ATFMKZ.js +164 -0
- package/dist/chunk-U2ATFMKZ.js.map +1 -0
- package/dist/chunk-UY2TOI3B.js +208 -0
- package/dist/chunk-UY2TOI3B.js.map +1 -0
- package/dist/{chunk-OYMYCW7J.js → chunk-W3LVZ2EN.js} +605 -97
- package/dist/chunk-W3LVZ2EN.js.map +1 -0
- package/dist/{chunk-HSDCI7OV.js → chunk-XZKD7DIF.js} +3 -3
- package/dist/{chunk-Z6MFJV5Z.js → chunk-YVODPFTL.js} +851 -500
- package/dist/chunk-YVODPFTL.js.map +1 -0
- package/dist/{cli-4NNBEQYH.js → cli-7KJ4QLUU.js} +367 -216
- package/dist/cli-7KJ4QLUU.js.map +1 -0
- package/dist/config-MSN6H4MD.js +41 -0
- package/dist/dist-3LOO6M4U.js +2842 -0
- package/dist/dist-3LOO6M4U.js.map +1 -0
- package/dist/doctor-ITUCKN6C.js +453 -0
- package/dist/doctor-ITUCKN6C.js.map +1 -0
- package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js → ethersCompat-Df4a6QIZ-THAVUGIJ.js} +5 -5
- package/dist/fund-XPB4IIG5.js +298 -0
- package/dist/fund-XPB4IIG5.js.map +1 -0
- package/dist/hook-command-VVV2Q23L.js +1265 -0
- package/dist/hook-command-VVV2Q23L.js.map +1 -0
- package/dist/index.js +11 -3
- package/dist/index.js.map +1 -1
- package/dist/install-OSJRM2ME.js +63 -0
- package/dist/install-identity-YIWKQOUD.js +27 -0
- package/dist/install-wallet-BWJO2SUC.js +107 -0
- package/dist/install-wallet-BWJO2SUC.js.map +1 -0
- package/dist/mcp-KE5YKPS2.js +10174 -0
- package/dist/mcp-KE5YKPS2.js.map +1 -0
- package/dist/paths-MUXHUOCM.js +57 -0
- package/dist/pay-MUV2U232.js +46 -0
- package/dist/payments-4D27K4L2.js +48 -0
- package/dist/payments-4D27K4L2.js.map +1 -0
- package/dist/redact-6W23GGJC.js +15 -0
- package/dist/{secp256k1-N3ZHU7LB.js → secp256k1-ZZZT2CAX.js} +3 -3
- package/dist/secp256k1-ZZZT2CAX.js.map +1 -0
- package/dist/send-BXHFKDBF.js +225 -0
- package/dist/send-BXHFKDBF.js.map +1 -0
- package/dist/status-3Z3YPRSE.js +71 -0
- package/dist/status-3Z3YPRSE.js.map +1 -0
- package/dist/status-line-CKRMGZ3Q.js +87 -0
- package/dist/status-line-CKRMGZ3Q.js.map +1 -0
- package/dist/status-line-wiring-GECLIIBT.js +29 -0
- package/dist/status-line-wiring-GECLIIBT.js.map +1 -0
- package/dist/tenjin-daemon.mjs +20598 -0
- package/dist/tenjin-shim.mjs +251 -0
- package/dist/tenjin-vitest-reporter.mjs +49 -0
- package/dist/uninstall-BZTVWJ7W.js +165 -0
- package/dist/uninstall-BZTVWJ7W.js.map +1 -0
- package/dist/update-IQQTEOI5.js +433 -0
- package/dist/update-IQQTEOI5.js.map +1 -0
- package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js → viemAdapter-By13KInL-X2VY6CY3.js} +5 -5
- package/dist/viemAdapter-By13KInL-X2VY6CY3.js.map +1 -0
- package/dist/wallet-UFXQ57TZ.js +33 -0
- package/dist/wallet-UFXQ57TZ.js.map +1 -0
- package/dist/wallet-kdf-worker.mjs +980 -0
- package/docs/agent-permissions.md +141 -0
- package/docs/safety-model.md +70 -0
- package/package.json +14 -9
- package/LICENSE +0 -21
- package/dist/buy-U35DQ6XM.js +0 -1598
- package/dist/buy-U35DQ6XM.js.map +0 -1
- package/dist/candidate-RLYCQMF5.js +0 -127
- package/dist/candidate-RLYCQMF5.js.map +0 -1
- package/dist/chunk-27ONARHV.js +0 -171
- package/dist/chunk-27ONARHV.js.map +0 -1
- package/dist/chunk-3OV7E5G5.js +0 -18
- package/dist/chunk-3OV7E5G5.js.map +0 -1
- package/dist/chunk-7KUW4MJD.js +0 -59
- package/dist/chunk-7KUW4MJD.js.map +0 -1
- package/dist/chunk-7PHSZKQS.js +0 -333
- package/dist/chunk-7PHSZKQS.js.map +0 -1
- package/dist/chunk-IYLHQMT5.js +0 -211
- package/dist/chunk-IYLHQMT5.js.map +0 -1
- package/dist/chunk-JPHG2JW3.js +0 -96
- package/dist/chunk-JPHG2JW3.js.map +0 -1
- package/dist/chunk-MUBUQVC3.js +0 -67
- package/dist/chunk-MUBUQVC3.js.map +0 -1
- package/dist/chunk-N62ROTMC.js.map +0 -1
- package/dist/chunk-NCE5NSN6.js.map +0 -1
- package/dist/chunk-OYMYCW7J.js.map +0 -1
- package/dist/chunk-QNP7H47L.js +0 -152
- package/dist/chunk-QNP7H47L.js.map +0 -1
- package/dist/chunk-RY4XKNV3.js +0 -140
- package/dist/chunk-RY4XKNV3.js.map +0 -1
- package/dist/chunk-S3IGX57D.js.map +0 -1
- package/dist/chunk-TFGSOPWR.js +0 -261
- package/dist/chunk-TFGSOPWR.js.map +0 -1
- package/dist/chunk-TLCMMYLY.js +0 -126
- package/dist/chunk-TLCMMYLY.js.map +0 -1
- package/dist/chunk-UO22YNY4.js +0 -69
- package/dist/chunk-UO22YNY4.js.map +0 -1
- package/dist/chunk-UPIEAMGH.js +0 -160
- package/dist/chunk-UPIEAMGH.js.map +0 -1
- package/dist/chunk-XJIW7USF.js.map +0 -1
- package/dist/chunk-YBMMV4Y4.js.map +0 -1
- package/dist/chunk-YIYQ2ZNT.js +0 -286
- package/dist/chunk-YIYQ2ZNT.js.map +0 -1
- package/dist/chunk-YN5SHIXQ.js +0 -126
- package/dist/chunk-YN5SHIXQ.js.map +0 -1
- package/dist/chunk-Z52RA3NC.js +0 -137
- package/dist/chunk-Z52RA3NC.js.map +0 -1
- package/dist/chunk-Z6MFJV5Z.js.map +0 -1
- package/dist/cli-4NNBEQYH.js.map +0 -1
- package/dist/config-2VSXWWHK.js +0 -21
- package/dist/doctor-JJPNIBYH.js +0 -20
- package/dist/inspect-JGYJWFDP.js +0 -96
- package/dist/inspect-JGYJWFDP.js.map +0 -1
- package/dist/install-ZQRMSRGW.js +0 -378
- package/dist/install-ZQRMSRGW.js.map +0 -1
- package/dist/lookup-WYVTOMVY.js +0 -113
- package/dist/lookup-WYVTOMVY.js.map +0 -1
- package/dist/outcome-HKKT6QIA.js +0 -66
- package/dist/outcome-HKKT6QIA.js.map +0 -1
- package/dist/publish-D76B3MBK.js +0 -1480
- package/dist/publish-D76B3MBK.js.map +0 -1
- package/dist/usdc-JIAJW4SV.js +0 -22
- package/dist/wallet-6QKS6UHW.js +0 -179
- package/dist/wallet-6QKS6UHW.js.map +0 -1
- package/dist/wallet-PA54CRBL.js +0 -30
- package/skills/tenjin/SKILL.md +0 -199
- package/skills/tenjin-publish/SKILL.md +0 -96
- package/skills/tenjin-search/SKILL.md +0 -122
- /package/dist/{_esm-FEASBWRP.js.map → _esm-CE7KNONL.js.map} +0 -0
- /package/dist/{ccip-NQXCEK2U.js.map → ccip-7RMRLAGV.js.map} +0 -0
- /package/dist/{ccip-XR5NE5QK.js.map → ccip-NLCSCHKI.js.map} +0 -0
- /package/dist/{chunk-ZMHYXMO6.js.map → chunk-5IEP5EGE.js.map} +0 -0
- /package/dist/{chunk-5CLSD5YN.js.map → chunk-BPMWXTFX.js.map} +0 -0
- /package/dist/{chunk-YALGASEU.js.map → chunk-EGELTSPU.js.map} +0 -0
- /package/dist/{chunk-CYOF7ROH.js.map → chunk-HPWO4O6S.js.map} +0 -0
- /package/dist/{chunk-QVX5MWJZ.js.map → chunk-JRGFKVAZ.js.map} +0 -0
- /package/dist/{chunk-HIVZG55D.js.map → chunk-KG3D7FIF.js.map} +0 -0
- /package/dist/{chunk-ZABPQJ3M.js.map → chunk-POUWHWID.js.map} +0 -0
- /package/dist/{chunk-RRN3YTK7.js.map → chunk-TTNESUPQ.js.map} +0 -0
- /package/dist/{chunk-HSDCI7OV.js.map → chunk-XZKD7DIF.js.map} +0 -0
- /package/dist/{config-2VSXWWHK.js.map → config-MSN6H4MD.js.map} +0 -0
- /package/dist/{doctor-JJPNIBYH.js.map → ethersCompat-Df4a6QIZ-THAVUGIJ.js.map} +0 -0
- /package/dist/{ethersCompat-Df4a6QIZ-3YZIAXDK.js.map → install-OSJRM2ME.js.map} +0 -0
- /package/dist/{secp256k1-N3ZHU7LB.js.map → install-identity-YIWKQOUD.js.map} +0 -0
- /package/dist/{usdc-JIAJW4SV.js.map → paths-MUXHUOCM.js.map} +0 -0
- /package/dist/{viemAdapter-By13KInL-ZZE6UV4Y.js.map → pay-MUV2U232.js.map} +0 -0
- /package/dist/{wallet-PA54CRBL.js.map → redact-6W23GGJC.js.map} +0 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/lib/atomic-json.ts
|
|
4
|
+
import { chmod, link, mkdir, open, rename, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { randomBytes } from "node:crypto";
|
|
6
|
+
import { basename, dirname, join } from "node:path";
|
|
7
|
+
var isWindows = process.platform === "win32";
|
|
8
|
+
async function writeFileAtomic(targetPath, data, opts = {}) {
|
|
9
|
+
const dir = dirname(targetPath);
|
|
10
|
+
const fileMode = opts.mode ?? 420;
|
|
11
|
+
const dirMode = opts.dirMode ?? 493;
|
|
12
|
+
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
13
|
+
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
14
|
+
try {
|
|
15
|
+
await writeFile(tmpPath, data, isWindows ? void 0 : { mode: fileMode });
|
|
16
|
+
if (!isWindows) await chmod(tmpPath, fileMode);
|
|
17
|
+
await rename(tmpPath, targetPath);
|
|
18
|
+
} catch (err) {
|
|
19
|
+
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
20
|
+
throw err;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
async function writeFileAtomicExclusive(targetPath, data, opts = {}) {
|
|
24
|
+
const dir = dirname(targetPath);
|
|
25
|
+
const fileMode = opts.mode ?? 420;
|
|
26
|
+
const dirMode = opts.dirMode ?? 493;
|
|
27
|
+
await mkdir(dir, { recursive: true, ...isWindows ? {} : { mode: dirMode } });
|
|
28
|
+
if (isWindows) {
|
|
29
|
+
const handle = await open(targetPath, "wx");
|
|
30
|
+
try {
|
|
31
|
+
await handle.writeFile(data);
|
|
32
|
+
await handle.sync();
|
|
33
|
+
} finally {
|
|
34
|
+
await handle.close();
|
|
35
|
+
}
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString("hex")}.tmp`);
|
|
39
|
+
try {
|
|
40
|
+
const handle = await open(tmpPath, "wx", fileMode);
|
|
41
|
+
try {
|
|
42
|
+
await handle.writeFile(data);
|
|
43
|
+
await handle.chmod(fileMode);
|
|
44
|
+
await handle.sync();
|
|
45
|
+
} finally {
|
|
46
|
+
await handle.close();
|
|
47
|
+
}
|
|
48
|
+
await link(tmpPath, targetPath);
|
|
49
|
+
await fsyncDir(dir);
|
|
50
|
+
} finally {
|
|
51
|
+
await rm(tmpPath, { force: true }).catch(() => void 0);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function fsyncDir(dir) {
|
|
55
|
+
const handle = await open(dir, "r");
|
|
56
|
+
try {
|
|
57
|
+
await handle.sync();
|
|
58
|
+
} finally {
|
|
59
|
+
await handle.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// src/lib/errors.ts
|
|
64
|
+
var EXIT_BY_CODE = {
|
|
65
|
+
NODE_UNSUPPORTED: 1,
|
|
66
|
+
USAGE: 2,
|
|
67
|
+
CONFIG_INVALID: 2,
|
|
68
|
+
WALLET_EXISTS: 3,
|
|
69
|
+
WALLET_MISSING: 1,
|
|
70
|
+
WALLET_INVALID_KEY: 1,
|
|
71
|
+
PROVIDER_ERROR: 1,
|
|
72
|
+
RPC_ERROR: 1,
|
|
73
|
+
API_UNREACHABLE: 1,
|
|
74
|
+
CONTRACT_MISMATCH: 1,
|
|
75
|
+
REFUSED: 3,
|
|
76
|
+
NETWORK_ERROR: 1,
|
|
77
|
+
INTERNAL: 1,
|
|
78
|
+
NOT_IMPLEMENTED: 1,
|
|
79
|
+
POLICY_REFUSED: 3,
|
|
80
|
+
PAYMENT_FAILED: 4,
|
|
81
|
+
RESOURCE_NOT_FOUND: 1,
|
|
82
|
+
SEARCH_NOT_FOUND: 1,
|
|
83
|
+
RATE_LIMITED: 1,
|
|
84
|
+
// A publish awaiting confirmation or hard-blocked is understood-but-refused (3),
|
|
85
|
+
// the same posture as POLICY_REFUSED; a write that failed after approval is a
|
|
86
|
+
// settlement-class failure (4), like PAYMENT_FAILED.
|
|
87
|
+
NEEDS_CONFIRMATION: 3,
|
|
88
|
+
PUBLISH_BLOCKED: 3,
|
|
89
|
+
PUBLISH_FAILED: 4,
|
|
90
|
+
// A send that reverted or stalled AFTER the human approved it and it was
|
|
91
|
+
// broadcast: the post-decision failure class (4), like PAYMENT_FAILED.
|
|
92
|
+
SEND_FAILED: 4,
|
|
93
|
+
// A delete the operator confirmed and the server then refused: same class.
|
|
94
|
+
DELETE_FAILED: 4,
|
|
95
|
+
UPDATE_FAILED: 1,
|
|
96
|
+
// Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.
|
|
97
|
+
REGISTRY_MISMATCH: 3,
|
|
98
|
+
// The seller's 402 challenge does not fit this process's header limit, so the
|
|
99
|
+
// terms could not be read and nothing was sent. Understood and refused (3),
|
|
100
|
+
// not a transport failure: the connection was fine and a retry changes
|
|
101
|
+
// nothing without an operator raising `--max-http-header-size`.
|
|
102
|
+
CHALLENGE_TOO_LARGE: 3
|
|
103
|
+
};
|
|
104
|
+
function exitCodeFor(code) {
|
|
105
|
+
return EXIT_BY_CODE[code];
|
|
106
|
+
}
|
|
107
|
+
var CliError = class extends Error {
|
|
108
|
+
code;
|
|
109
|
+
exitCode;
|
|
110
|
+
fix;
|
|
111
|
+
details;
|
|
112
|
+
constructor(code, message, opts = {}) {
|
|
113
|
+
super(message, opts.cause !== void 0 ? { cause: opts.cause } : void 0);
|
|
114
|
+
this.name = "CliError";
|
|
115
|
+
this.code = code;
|
|
116
|
+
this.exitCode = opts.exitCode ?? exitCodeFor(code);
|
|
117
|
+
this.fix = opts.fix;
|
|
118
|
+
this.details = opts.details;
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
// src/adapters/types.ts
|
|
123
|
+
var HARNESSES = ["claude", "codex"];
|
|
124
|
+
|
|
125
|
+
export {
|
|
126
|
+
writeFileAtomic,
|
|
127
|
+
writeFileAtomicExclusive,
|
|
128
|
+
fsyncDir,
|
|
129
|
+
CliError,
|
|
130
|
+
HARNESSES
|
|
131
|
+
};
|
|
132
|
+
//# sourceMappingURL=chunk-JLEF5WHM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/atomic-json.ts","../src/lib/errors.ts","../src/adapters/types.ts"],"sourcesContent":["import { chmod, link, mkdir, open, rename, rm, writeFile } from 'node:fs/promises';\nimport { randomBytes } from 'node:crypto';\nimport { basename, dirname, join } from 'node:path';\n\n/** fs modes are no-ops on Windows; the 0600/0700 custody story does not apply. */\nconst isWindows = process.platform === 'win32';\n\nexport interface AtomicWriteOptions {\n /** Mode for the written file (ignored on win32). Default 0o644. */\n mode?: number;\n /** Mode for the parent dir when this call creates it (ignored on win32). Default 0o755. */\n dirMode?: number;\n}\n\n/**\n * Write `data` to `targetPath` atomically: a uniquely-named temp file is created\n * in the SAME directory (so the rename is atomic — a cross-filesystem rename is\n * not), given the final mode at open time, then renamed over the target. A\n * reader therefore sees either the old file or the fully-written new one, never\n * a partial write.\n *\n * The temp file is born with the caller's `mode` (0o600 for a wallet key) so the\n * bytes are never written through a world-readable descriptor; the follow-up\n * chmod only makes the mode exact under an unusual umask and only ever touches\n * the temp path, so the live target still appears atomically at its final mode.\n */\nexport async function writeFileAtomic(\n targetPath: string,\n data: string | Buffer,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n await writeFile(tmpPath, data, isWindows ? undefined : { mode: fileMode });\n if (!isWindows) await chmod(tmpPath, fileMode);\n await rename(tmpPath, targetPath);\n } catch (err) {\n await rm(tmpPath, { force: true }).catch(() => undefined);\n throw err;\n }\n}\n\n/**\n * Like {@link writeFileAtomic} but NO-CLOBBER and crash-durable: the commit fails\n * with `EEXIST` when `targetPath` already exists instead of replacing it, and the\n * new entry is fsynced before returning. This is what a wallet key needs — two\n * concurrent `create`/`import` runs must not both \"succeed\" and silently lose one\n * key; the loser gets a distinguishable EEXIST the wallet layer maps to\n * WALLET_EXISTS.\n *\n * The temp file is fsynced, then `link()` commits it — link is atomic and throws\n * EEXIST if the target already exists, so the check-then-write race is closed at\n * the filesystem, not by an earlier stat. The parent dir is then fsynced so the\n * new entry survives a crash. On win32, link semantics differ and a directory\n * cannot be fsynced, so we fall back to an exclusive `wx` open (still atomic\n * create-or-EEXIST, just not crash-durable — win32 has no 0600 custody story to\n * protect anyway).\n */\nexport async function writeFileAtomicExclusive(\n targetPath: string,\n data: string,\n opts: AtomicWriteOptions = {},\n): Promise<void> {\n const dir = dirname(targetPath);\n const fileMode = opts.mode ?? 0o644;\n const dirMode = opts.dirMode ?? 0o755;\n\n await mkdir(dir, { recursive: true, ...(isWindows ? {} : { mode: dirMode }) });\n\n if (isWindows) {\n const handle = await open(targetPath, 'wx');\n try {\n await handle.writeFile(data);\n await handle.sync();\n } finally {\n await handle.close();\n }\n return;\n }\n\n const tmpPath = join(dir, `.${basename(targetPath)}.${randomBytes(6).toString('hex')}.tmp`);\n try {\n const handle = await open(tmpPath, 'wx', fileMode);\n try {\n await handle.writeFile(data);\n await handle.chmod(fileMode); // exact mode even under an unusual umask\n await handle.sync();\n } finally {\n await handle.close();\n }\n await link(tmpPath, targetPath); // atomic; throws EEXIST when the target exists\n await fsyncDir(dir);\n } finally {\n // On success the temp is now a redundant link to the target; on EEXIST it is\n // the orphaned write. Either way remove it before returning/throwing.\n await rm(tmpPath, { force: true }).catch(() => undefined);\n }\n}\n\n/** fsync a directory so a freshly linked entry is durable. Never call on win32. */\nexport async function fsyncDir(dir: string): Promise<void> {\n const handle = await open(dir, 'r');\n try {\n await handle.sync();\n } finally {\n await handle.close();\n }\n}\n","import type { ErrorCode } from '../schemas';\n\n/**\n * The process exit code is API (spec 10): 0 success, 1 runtime/network, 2 usage,\n * 3 understood-but-refused (policy refusal, publish confirmation/hard-block), 4 a\n * failure AFTER an approved spend or write (a settlement that failed, a publish\n * that failed post-consent).\n */\nexport type ExitCode = 1 | 2 | 3 | 4;\n\nexport interface CliErrorOptions {\n /** A copy-pasteable command or one-line remediation. */\n fix?: string;\n /** Structured detail for machine consumers; serialized into the envelope. */\n details?: unknown;\n /** Override the default exit code for this error's code. */\n exitCode?: ExitCode;\n /** Underlying cause, preserved on the Error but never serialized. */\n cause?: unknown;\n}\n\n/**\n * Default code -> exit-code mapping. USAGE/CONFIG_INVALID are malformed\n * invocations (2); WALLET_EXISTS/REFUSED are understood-but-refused (3);\n * everything else is a runtime/network failure (1). A CliError may override its\n * own exit code, but the table is the default every caller relies on.\n */\nconst EXIT_BY_CODE: Record<ErrorCode, ExitCode> = {\n NODE_UNSUPPORTED: 1,\n USAGE: 2,\n CONFIG_INVALID: 2,\n WALLET_EXISTS: 3,\n WALLET_MISSING: 1,\n WALLET_INVALID_KEY: 1,\n PROVIDER_ERROR: 1,\n RPC_ERROR: 1,\n API_UNREACHABLE: 1,\n CONTRACT_MISMATCH: 1,\n REFUSED: 3,\n NETWORK_ERROR: 1,\n INTERNAL: 1,\n NOT_IMPLEMENTED: 1,\n POLICY_REFUSED: 3,\n PAYMENT_FAILED: 4,\n RESOURCE_NOT_FOUND: 1,\n SEARCH_NOT_FOUND: 1,\n RATE_LIMITED: 1,\n // A publish awaiting confirmation or hard-blocked is understood-but-refused (3),\n // the same posture as POLICY_REFUSED; a write that failed after approval is a\n // settlement-class failure (4), like PAYMENT_FAILED.\n NEEDS_CONFIRMATION: 3,\n PUBLISH_BLOCKED: 3,\n PUBLISH_FAILED: 4,\n // A send that reverted or stalled AFTER the human approved it and it was\n // broadcast: the post-decision failure class (4), like PAYMENT_FAILED.\n SEND_FAILED: 4,\n // A delete the operator confirmed and the server then refused: same class.\n DELETE_FAILED: 4,\n UPDATE_FAILED: 1,\n // Refused BEFORE any signature existed: the Bazaar lane's fail-closed check.\n REGISTRY_MISMATCH: 3,\n // The seller's 402 challenge does not fit this process's header limit, so the\n // terms could not be read and nothing was sent. Understood and refused (3),\n // not a transport failure: the connection was fine and a retry changes\n // nothing without an operator raising `--max-http-header-size`.\n CHALLENGE_TOO_LARGE: 3,\n};\n\nexport function exitCodeFor(code: ErrorCode): ExitCode {\n return EXIT_BY_CODE[code];\n}\n\n/**\n * The one error type commands throw. It carries the machine `code`, the resolved\n * `exitCode`, and an optional `fix`/`details` that flow straight into the failure\n * envelope. Commands throw it; the CLI dispatcher catches, serializes, and exits.\n */\nexport class CliError extends Error {\n readonly code: ErrorCode;\n readonly exitCode: ExitCode;\n readonly fix?: string;\n readonly details?: unknown;\n\n constructor(code: ErrorCode, message: string, opts: CliErrorOptions = {}) {\n super(message, opts.cause !== undefined ? { cause: opts.cause } : undefined);\n this.name = 'CliError';\n this.code = code;\n this.exitCode = opts.exitCode ?? exitCodeFor(code);\n this.fix = opts.fix;\n this.details = opts.details;\n }\n}\n","/**\n * The harness adapter contract (tenjin-notes loop-redesign/04-harness-adapters.md).\n *\n * This and `error-markers.ts` (data both sides read) are the ONLY files the\n * kernel (`src/hooks/*`) imports from `src/adapters/`.\n * A harness is one module exporting a {@link HarnessAdapter}: a pure `decode`\n * from its native payload to {@link HookInput}, a pure `encode` from the\n * kernel's {@link Emit} to its native response, and a {@link Registrar} the\n * installer uses to write its hook entries. The daemon holds one adapter per\n * member of {@link Harness} and one route, `POST /hook/:harness`.\n *\n * Adding a harness is an adapter file plus a transport; nothing in `src/hooks`\n * or `src/daemon` changes. The union gains a member when an adapter lands, not\n * before.\n */\n\nimport type { PublishMode } from '../lib/config';\nimport type {\n CodexGrantResult,\n HarnessPermissions,\n PermissionsResult,\n} from '../lib/harness-permissions';\nimport type { CodexTrustReport, TrustProbeOptions, TrustResult } from '../lib/codex-trust';\n\n/** Harnesses with an adapter in this build. */\nexport type Harness = 'claude' | 'codex';\n\n/** The same union at run time: the installer's ownership predicate matches a\n * registered URL against `/hook/<harness>`, and a list it cannot iterate would\n * have to be spelled a second time. */\nexport const HARNESSES: readonly Harness[] = ['claude', 'codex'];\n\n/**\n * The canonical event vocabulary every adapter maps its native events onto.\n * `session.end` is deliberately absent: no arm registers on it and retention\n * never runs there (a daemon serves many sessions; one ending is not the\n * machine going quiet).\n */\nexport type Event =\n | 'session.start'\n | 'prompt'\n | 'tool.before'\n | 'tool.after'\n | 'agent.start'\n | 'agent.stop'\n | 'turn.end';\n\nexport const EVENTS: readonly Event[] = [\n 'session.start',\n 'prompt',\n 'tool.before',\n 'tool.after',\n 'agent.start',\n 'agent.stop',\n 'turn.end',\n];\n\n/**\n * What a tool IS to the arms. Anything unmatched is `'other'`, never a key.\n *\n * `web` and `fetch` are separate kinds because they are separate arms: a page\n * fetch and a real web search ask different questions, and one agent's six page\n * fetches must not spend the budget its search needed.\n */\nexport type ToolKind = 'web' | 'fetch' | 'dispatch' | 'shell' | 'edit' | 'read';\n\nexport interface ToolResult {\n stdout?: string;\n stderr?: string;\n error?: string;\n text?: string;\n}\n\ninterface ToolBase {\n /** The native tool name, verbatim. */\n name: string;\n callId?: string;\n /**\n * `tool.after` only, and DECIDED IN DECODE, never by an arm reading the\n * result text. `false` is a failure the harness stated or an error marker in\n * a shell's output; `true` is a completion the harness vouched for;\n * `undefined` is unknown, which is what a harness that reports no exit status\n * leaves behind. No marker never means success.\n */\n ok?: boolean;\n result?: ToolResult;\n interrupted?: boolean;\n}\n\n/**\n * The fields the arms read, canonical per kind. Native argument shapes (a\n * `file_path`, a patch body, a `message`) stop at the adapter; an arm never\n * reads a vendor field. One native invocation is one tool value, so an edit\n * that touches several files carries them all in `paths` and the context arm\n * marks every one in a single fire.\n */\nexport type HookTool = ToolBase &\n (\n | { kind: 'shell'; command: string }\n | { kind: 'edit'; paths: string[] }\n | { kind: 'read'; paths: string[] }\n | { kind: 'dispatch'; task: string; description?: string }\n | { kind: 'web'; query: string }\n | { kind: 'fetch'; url: string; prompt: string }\n | { kind: 'other' }\n );\n\n/** The normalized payload the kernel runs on. */\nexport interface HookInput {\n harness: Harness;\n event: Event;\n /** `hook_event_name` verbatim; `encode` stamps its response with it. */\n native: { event: string };\n /** The ROOT session as the harness names it: the id the lead and all its\n * children share. `actorOf` namespaces it by harness before anything is\n * stored, so equal native ids across harnesses never share state. */\n session: string;\n /** Child id; undefined = the lead. Present-but-invalid makes `decode` return null. */\n agent?: string;\n /** Required; '' is allowed and recorded. */\n cwd: string;\n /** Claude `prompt_id`, Codex `turn_id`. */\n turn?: string;\n tool?: HookTool;\n /** The prompt on `prompt`; the spawn prompt on `agent.start` when the harness has it. */\n prompt?: string;\n agentType?: string;\n lastMessage?: string;\n /** Claude/Codex `stop_hook_active`: this stop was raised by a hook's own\n * feedback rather than by the agent finishing. The capture arm reads it to\n * tell an ask turn from the answer turn after one. */\n stopFuse?: boolean;\n transcript?: { path?: string; agentPath?: string };\n /** `session.start` source (`startup`, `clear`, `compact`, `resume`). */\n source?: string;\n /** The native payload. Ledger `question` on error rows and tests only; never read by arms. */\n raw: unknown;\n}\n\n/**\n * What the kernel hands back to the harness. `null` is \"nothing to say\" (204).\n *\n * ONE CHANNEL. Everything an arm says is context beside the turn, including the\n * turn-end ask: on Stop and SubagentStop `additionalContext` keeps the\n * conversation going through the same loop protections a blocking decision\n * would, and shows in the transcript as hook feedback rather than a hook error.\n * A second channel with a red banner said the same words for a worse price.\n */\nexport interface Emit {\n context?: string;\n}\n\n/**\n * What the installer needs to register a harness, and nothing the daemon runs\n * on: `selectArm` reads the event and tool kind off the decoded input, so a\n * registrar carries no event or tool metadata that would claim an enforcement\n * nothing performs.\n */\nexport interface Registrar {\n /** The harness's own hooks file under `home`. */\n configPath(home: string, env?: NodeJS.ProcessEnv): string;\n /**\n * Entries the installer merges additively into that file, each\n * `{ event, matcher?, hooks }` in the harness's own JSON shape.\n */\n plan(target: { url: string; token: string; shimPath: string; timeoutSeconds: number }): unknown[];\n /**\n * The steps left to a PERSON once the file is written, for a harness that\n * gates entries it has not been told to trust. Takes the path actually\n * written, because a machine on `$CODEX_HOME` is not reading `~/.codex`.\n * One sentence was not enough: as a clause on the undo line, operators\n * finished an install reporting \"7 entries\" with a loop that never fired\n * (tenjin-agent#342).\n */\n activation?(hooksPath: string): string[];\n /** The harness-native persistent command grant, when this harness has one. */\n grant?: {\n path(home: string, env?: NodeJS.ProcessEnv): string;\n inspect(home: string, mode: PublishMode, env?: NodeJS.ProcessEnv): Promise<HarnessPermissions>;\n write(\n home: string,\n mode: PublishMode,\n env?: NodeJS.ProcessEnv,\n ): Promise<PermissionsResult | CodexGrantResult>;\n remove?(home: string, env?: NodeJS.ProcessEnv): Promise<{ path: string; removed: boolean }>;\n };\n /** A harness-native trust gate for registered hook handlers. */\n trust?: {\n ensure(\n home: string,\n keys: readonly string[],\n ownedBy: (row: { command?: unknown; sourcePath?: unknown }) => boolean,\n opts?: TrustProbeOptions,\n ): Promise<TrustResult>;\n read(\n home: string,\n keys: readonly string[],\n opts?: TrustProbeOptions,\n ): Promise<CodexTrustReport>;\n };\n}\n\nexport interface HarnessAdapter {\n id: Harness;\n /** Pure. `null` = drop the fire quietly (unknown event, invalid identity). */\n decode(raw: unknown): HookInput | null;\n /** Pure. `null` = respond 204 with no body. */\n encode(emit: Emit | null, input: HookInput): unknown;\n registrar: Registrar;\n}\n"],"mappings":";;;AAAA,SAAS,OAAO,MAAM,OAAO,MAAM,QAAQ,IAAI,iBAAiB;AAChE,SAAS,mBAAmB;AAC5B,SAAS,UAAU,SAAS,YAAY;AAGxC,IAAM,YAAY,QAAQ,aAAa;AAqBvC,eAAsB,gBACpB,YACA,MACA,OAA2B,CAAC,GACb;AACf,QAAM,MAAM,QAAQ,UAAU;AAC9B,QAAM,WAAW,KAAK,QAAQ;AAC9B,QAAM,UAAU,KAAK,WAAW;AAEhC,QAAM,MAAM,KAAK,EAAE,WAAW,MAAM,GAAI,YAAY,CAAC,IAAI,EAAE,MAAM,QAAQ,EAAG,CAAC;AAE7E,QAAM,UAAU,KAAK,KAAK,IAAI,SAAS,UAAU,CAAC,IAAI,YAAY,CAAC,EAAE,SAAS,KAAK,CAAC,MAAM;AAC1F,MAAI;AACF,UAAM,UAAU,SAAS,MAAM,YAAY,SAAY,EAAE,MAAM,SAAS,CAAC;AACzE,QAAI,CAAC,UAAW,OAAM,MAAM,SAAS,QAAQ;AAC7C,UAAM,OAAO,SAAS,UAAU;AAAA,EAClC,SAAS,KAAK;AACZ,UAAM,GAAG,SAAS,EAAE,OAAO,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AACxD,UA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B;AAAA,EACpB,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,eAAe;AAAA,EACf,UAAU;AAAA,EACV,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,cAAc;AAAA;AAAA;AAAA;AAAA,EAId,oBAAoB;AAAA,EACpB,iBAAiB;AAAA,EACjB,gBAAgB;AAAA;AAAA;AAAA,EAGhB,aAAa;AAAA;AAAA,EAEb,eAAe;AAAA,EACf,eAAe;AAAA;AAAA,EAEf,mBAAmB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKnB,qBAAqB;AACvB;AAEO,SAAS,YAAY,MAA2B;AACrD,SAAO,aAAa,IAAI;AAC1B;AAOO,IAAM,WAAN,cAAuB,MAAM;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,MAAiB,SAAiB,OAAwB,CAAC,GAAG;AACxE,UAAM,SAAS,KAAK,UAAU,SAAY,EAAE,OAAO,KAAK,MAAM,IAAI,MAAS;AAC3E,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,WAAW,KAAK,YAAY,YAAY,IAAI;AACjD,SAAK,MAAM,KAAK;AAChB,SAAK,UAAU,KAAK;AAAA,EACtB;AACF;;;AC7DO,IAAM,YAAgC,CAAC,UAAU,OAAO;","names":[]}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
inspectHooksFile
|
|
4
|
+
} from "./chunk-IOIHYOU4.js";
|
|
5
|
+
import {
|
|
6
|
+
CliError,
|
|
7
|
+
writeFileAtomic
|
|
8
|
+
} from "./chunk-JLEF5WHM.js";
|
|
9
|
+
|
|
10
|
+
// src/router/status-line-wiring.ts
|
|
11
|
+
import { readFile, stat } from "node:fs/promises";
|
|
12
|
+
var STATUS_LINE_COMMAND = "tenjin status-line";
|
|
13
|
+
var STATUS_LINE_REFRESH_SECONDS = 1;
|
|
14
|
+
var OUR_MARKER = STATUS_LINE_COMMAND;
|
|
15
|
+
var MODES = ["own", "compose", "skip"];
|
|
16
|
+
function statusLineMode(value) {
|
|
17
|
+
const mode = MODES.find((known) => known === value);
|
|
18
|
+
if (mode === void 0) {
|
|
19
|
+
throw new CliError("USAGE", `--status-line takes ${MODES.join(", ")}, not "${value}".`, {
|
|
20
|
+
fix: "Run `tenjin install --status-line own`."
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
return mode;
|
|
24
|
+
}
|
|
25
|
+
function classifyStatusLine(value) {
|
|
26
|
+
if (value === null || value === void 0) return "absent";
|
|
27
|
+
const command = typeof value === "string" ? value : typeof value === "object" && !Array.isArray(value) ? value.command : void 0;
|
|
28
|
+
if (typeof command !== "string" || command.trim().length === 0) return "foreign";
|
|
29
|
+
if (command.trim() === OUR_MARKER) return "ours";
|
|
30
|
+
return command.includes(OUR_MARKER) ? "composed" : "foreign";
|
|
31
|
+
}
|
|
32
|
+
function ours() {
|
|
33
|
+
return {
|
|
34
|
+
type: "command",
|
|
35
|
+
command: STATUS_LINE_COMMAND,
|
|
36
|
+
refreshInterval: STATUS_LINE_REFRESH_SECONDS
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
var shQuote = (value) => `'${value.replaceAll("'", String.raw`'\''`)}'`;
|
|
40
|
+
var shUnquote = (value) => value.replaceAll(String.raw`'\''`, "'");
|
|
41
|
+
function composedScript(existing) {
|
|
42
|
+
return [
|
|
43
|
+
"event=$(cat)",
|
|
44
|
+
`yours=$(printf %s "$event" | ${existing})`,
|
|
45
|
+
`tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND})`,
|
|
46
|
+
'printf %s "$yours${tenjin:+ \xB7 $tenjin}"'
|
|
47
|
+
].join("; ");
|
|
48
|
+
}
|
|
49
|
+
function decomposeCommand(command) {
|
|
50
|
+
const trimmed = command.trim();
|
|
51
|
+
if (!trimmed.startsWith("sh -c '") || !trimmed.endsWith("'")) return null;
|
|
52
|
+
const script = shUnquote(trimmed.slice("sh -c '".length, -1));
|
|
53
|
+
const prefix = 'event=$(cat); yours=$(printf %s "$event" | ';
|
|
54
|
+
if (!script.startsWith(prefix)) return null;
|
|
55
|
+
const rest = script.slice(prefix.length);
|
|
56
|
+
const suffix = `); tenjin=$(printf %s "$event" | ${STATUS_LINE_COMMAND}); printf %s "$yours\${tenjin:+ \xB7 $tenjin}"`;
|
|
57
|
+
if (!rest.endsWith(suffix)) return null;
|
|
58
|
+
const existing = rest.slice(0, -suffix.length);
|
|
59
|
+
return existing.length > 0 && composedScript(existing) === script ? existing : null;
|
|
60
|
+
}
|
|
61
|
+
function composeCommand(existing) {
|
|
62
|
+
return `sh -c ${shQuote(composedScript(existing))}`;
|
|
63
|
+
}
|
|
64
|
+
function commandOf(value) {
|
|
65
|
+
const command = typeof value === "string" ? value : typeof value === "object" && value !== null && !Array.isArray(value) ? value.command : void 0;
|
|
66
|
+
return typeof command === "string" && command.trim().length > 0 ? command.trim() : void 0;
|
|
67
|
+
}
|
|
68
|
+
function composeFor(value) {
|
|
69
|
+
const command = commandOf(value);
|
|
70
|
+
return command === void 0 ? void 0 : composeCommand(command);
|
|
71
|
+
}
|
|
72
|
+
async function ensureStatusLine(settingsPath, opts = {}) {
|
|
73
|
+
const found = await inspectHooksFile(settingsPath);
|
|
74
|
+
if ("refusal" in found) {
|
|
75
|
+
return { path: settingsPath, state: "absent", wrote: false, warning: found.refusal.reason };
|
|
76
|
+
}
|
|
77
|
+
const { path, settings } = found;
|
|
78
|
+
const current = settings.statusLine;
|
|
79
|
+
const state = classifyStatusLine(current);
|
|
80
|
+
if (opts.mode === "skip") {
|
|
81
|
+
return { path, state, wrote: false, ...state === "foreign" ? kept(current) : {} };
|
|
82
|
+
}
|
|
83
|
+
if (opts.mode === "compose") {
|
|
84
|
+
const composed = composeFor(current);
|
|
85
|
+
if (composed === void 0) return writeStatusLine(found, ours(), "ours");
|
|
86
|
+
const base = typeof current === "object" && current !== null && !Array.isArray(current) ? current : ours();
|
|
87
|
+
return state === "composed" ? { path, state, wrote: false, command: composed } : writeStatusLine(found, { ...base, command: composed }, "composed");
|
|
88
|
+
}
|
|
89
|
+
if (state === "foreign") {
|
|
90
|
+
return { path, state, wrote: false, ...kept(current) };
|
|
91
|
+
}
|
|
92
|
+
if (state === "composed") return { path, state, wrote: false };
|
|
93
|
+
if (state === "absent" && opts.refreshOnly === true) {
|
|
94
|
+
return { path, state, wrote: false };
|
|
95
|
+
}
|
|
96
|
+
return writeStatusLine(found, ours(), "ours");
|
|
97
|
+
}
|
|
98
|
+
async function removeStatusLine(settingsPath) {
|
|
99
|
+
const found = await inspectHooksFile(settingsPath);
|
|
100
|
+
if ("refusal" in found) {
|
|
101
|
+
return { path: settingsPath, state: "absent", wrote: false, warning: found.refusal.reason };
|
|
102
|
+
}
|
|
103
|
+
const { path, settings } = found;
|
|
104
|
+
const current = settings.statusLine;
|
|
105
|
+
const state = classifyStatusLine(current);
|
|
106
|
+
if (state === "ours") return writeStatusLine(found, void 0, "absent");
|
|
107
|
+
if (state === "composed") {
|
|
108
|
+
const command = commandOf(current);
|
|
109
|
+
const original = command === void 0 ? null : decomposeCommand(command);
|
|
110
|
+
if (original === null) return { path, state, wrote: false };
|
|
111
|
+
const kept2 = { ...current, command: original };
|
|
112
|
+
return writeStatusLine(found, kept2, "foreign");
|
|
113
|
+
}
|
|
114
|
+
return { path, state, wrote: false };
|
|
115
|
+
}
|
|
116
|
+
async function inspectStatusLine(settingsPath) {
|
|
117
|
+
const found = await inspectHooksFile(settingsPath);
|
|
118
|
+
if ("refusal" in found) {
|
|
119
|
+
return { path: settingsPath, state: "absent", warning: found.refusal.reason };
|
|
120
|
+
}
|
|
121
|
+
return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };
|
|
122
|
+
}
|
|
123
|
+
function kept(current) {
|
|
124
|
+
const compose = composeFor(current);
|
|
125
|
+
return compose === void 0 ? {} : { compose };
|
|
126
|
+
}
|
|
127
|
+
async function writeStatusLine(found, value, state) {
|
|
128
|
+
const { path, raw, settings } = found;
|
|
129
|
+
const next = { ...settings };
|
|
130
|
+
if (value === void 0) delete next.statusLine;
|
|
131
|
+
else next.statusLine = value;
|
|
132
|
+
const body = `${JSON.stringify(next, null, 2)}
|
|
133
|
+
`;
|
|
134
|
+
const result = {
|
|
135
|
+
path,
|
|
136
|
+
state,
|
|
137
|
+
wrote: false,
|
|
138
|
+
...typeof value?.command === "string" ? { command: value.command } : {}
|
|
139
|
+
};
|
|
140
|
+
if (body === raw) return result;
|
|
141
|
+
const mode = await stat(path).then((s) => ({ mode: s.mode & 511 })).catch(() => ({}));
|
|
142
|
+
if (raw !== null && await readFile(path, "utf8").catch(() => null) !== raw) {
|
|
143
|
+
return {
|
|
144
|
+
...result,
|
|
145
|
+
state: classifyStatusLine(settings.statusLine),
|
|
146
|
+
warning: "changed-since-read"
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
try {
|
|
150
|
+
await writeFileAtomic(path, body, mode);
|
|
151
|
+
} catch (err) {
|
|
152
|
+
return {
|
|
153
|
+
...result,
|
|
154
|
+
state: classifyStatusLine(settings.statusLine),
|
|
155
|
+
warning: err instanceof Error ? err.message : String(err)
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
return { ...result, wrote: true };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export {
|
|
162
|
+
STATUS_LINE_COMMAND,
|
|
163
|
+
STATUS_LINE_REFRESH_SECONDS,
|
|
164
|
+
statusLineMode,
|
|
165
|
+
classifyStatusLine,
|
|
166
|
+
decomposeCommand,
|
|
167
|
+
composeCommand,
|
|
168
|
+
ensureStatusLine,
|
|
169
|
+
removeStatusLine,
|
|
170
|
+
inspectStatusLine
|
|
171
|
+
};
|
|
172
|
+
//# sourceMappingURL=chunk-JN7TMXVF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/status-line-wiring.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { CliError } from '../lib/errors';\nimport { inspectHooksFile } from '../lib/harness-hooks';\n\n/**\n * The `statusLine` key in Claude Code's settings file: the one setting the live\n * footer needs, and the one piece of harness configuration a person is most\n * likely to have already set for themselves.\n *\n * SO IT IS NEVER REPLACED. An existing status line that is not ours is left\n * exactly as it is, and `install` prints the composition line instead;\n * `--status-line compose` writes that line only because it was asked for by\n * name. Writing over it and saying so in the output destroys a configuration\n * this CLI did not create.\n *\n * OWNERSHIP IS ONE MARKER, the command naming `tenjin status-line`, used by\n * `install`, `install --refresh`, `uninstall` and `doctor` alike, so the four\n * can never disagree about which status line is Tenjin's.\n */\n\n/** The command `install` registers, in the shape the hook entries use: a plain\n * command line on PATH, with no path into this build's dist directory. */\nexport const STATUS_LINE_COMMAND = 'tenjin status-line';\n/** Claude Code re-runs the command on this interval, in seconds. */\nexport const STATUS_LINE_REFRESH_SECONDS = 1;\n/** The marker that makes a status line ours, composed or not. */\nconst OUR_MARKER = STATUS_LINE_COMMAND;\n\n/** What the user asked for, when they asked. Absent means the default path. */\nexport type StatusLineMode = 'own' | 'compose' | 'skip';\n\nconst MODES: readonly StatusLineMode[] = ['own', 'compose', 'skip'];\n\n/** `--status-line <mode>`, refused rather than guessed at. */\nexport function statusLineMode(value: string): StatusLineMode {\n const mode = MODES.find((known) => known === value);\n if (mode === undefined) {\n throw new CliError('USAGE', `--status-line takes ${MODES.join(', ')}, not \"${value}\".`, {\n fix: 'Run `tenjin install --status-line own`.',\n });\n }\n return mode;\n}\n\n/**\n * What is in the file: ours alone, ours appended to someone else's, someone\n * else's alone, or nothing.\n */\nexport type StatusLineState = 'ours' | 'composed' | 'foreign' | 'absent';\n\nexport interface StatusLineResult {\n path: string;\n state: StatusLineState;\n /** True when this run changed the file. */\n wrote: boolean;\n /** The command now registered, when one of ours is. */\n command?: string;\n /** The exact command to set by hand, printed when a foreign line is kept. */\n compose?: string;\n /** Why nothing was written, for a file this run would not touch. */\n warning?: string;\n}\n\nexport function classifyStatusLine(value: unknown): StatusLineState {\n if (value === null || value === undefined) return 'absent';\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n // A status line whose command this build cannot read is still the user's.\n if (typeof command !== 'string' || command.trim().length === 0) return 'foreign';\n if (command.trim() === OUR_MARKER) return 'ours';\n return command.includes(OUR_MARKER) ? 'composed' : 'foreign';\n}\n\nfunction ours(): Record<string, unknown> {\n return {\n type: 'command',\n command: STATUS_LINE_COMMAND,\n refreshInterval: STATUS_LINE_REFRESH_SECONDS,\n };\n}\n\nconst shQuote = (value: string): string => `'${value.replaceAll(\"'\", String.raw`'\\''`)}'`;\nconst shUnquote = (value: string): string => value.replaceAll(String.raw`'\\''`, \"'\");\n\n/** The inner script, with the user's own command as the one hole in it. */\nfunction composedScript(existing: string): string {\n return [\n 'event=$(cat)',\n `yours=$(printf %s \"$event\" | ${existing})`,\n `tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND})`,\n 'printf %s \"$yours${tenjin:+ · $tenjin}\"',\n ].join('; ');\n}\n\n/**\n * The command a composition was built from, or null when this is not a\n * composition this build wrote. It is the exact inverse of\n * {@link composeCommand}: a hand-edited line matches nothing and is kept whole,\n * because guessing at someone's shell is how an uninstall breaks a prompt.\n */\nexport function decomposeCommand(command: string): string | null {\n const trimmed = command.trim();\n if (!trimmed.startsWith(\"sh -c '\") || !trimmed.endsWith(\"'\")) return null;\n const script = shUnquote(trimmed.slice(\"sh -c '\".length, -1));\n const prefix = 'event=$(cat); yours=$(printf %s \"$event\" | ';\n if (!script.startsWith(prefix)) return null;\n const rest = script.slice(prefix.length);\n const suffix = `); tenjin=$(printf %s \"$event\" | ${STATUS_LINE_COMMAND}); printf %s \"$yours\\${tenjin:+ · $tenjin}\"`;\n if (!rest.endsWith(suffix)) return null;\n const existing = rest.slice(0, -suffix.length);\n return existing.length > 0 && composedScript(existing) === script ? existing : null;\n}\n\n/**\n * The user's status line with ours appended after a separator, on one line.\n *\n * The harness writes its event on stdin ONCE, so a composition cannot simply\n * run two commands in sequence: the event is captured first and replayed into\n * each. Ours contributes nothing when this session has no activity, and the\n * separator goes with it, so a quiet session looks exactly as it did before.\n */\nexport function composeCommand(existing: string): string {\n return `sh -c ${shQuote(composedScript(existing))}`;\n}\n\n/** The command a status-line setting runs, in either shape it can take. */\nfunction commandOf(value: unknown): string | undefined {\n const command =\n typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as { command?: unknown }).command\n : undefined;\n return typeof command === 'string' && command.trim().length > 0 ? command.trim() : undefined;\n}\n\n/** What a foreign status line's owner is told to set, verbatim. */\nfunction composeFor(value: unknown): string | undefined {\n const command = commandOf(value);\n return command === undefined ? undefined : composeCommand(command);\n}\n\nexport interface EnsureStatusLineOpts {\n mode?: StatusLineMode;\n /**\n * `install --refresh` and the refresh `tenjin update` spawns: converge a\n * status line of ours that is already registered, and ADD NOTHING. A machine\n * whose owner removed ours, or never had it, keeps that answer across every\n * upgrade without a second place to record it.\n */\n refreshOnly?: boolean;\n}\n\nexport async function ensureStatusLine(\n settingsPath: string,\n opts: EnsureStatusLineOpts = {},\n): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (opts.mode === 'skip') {\n return { path, state, wrote: false, ...(state === 'foreign' ? kept(current) : {}) };\n }\n if (opts.mode === 'compose') {\n const composed = composeFor(current);\n if (composed === undefined) return writeStatusLine(found, ours(), 'ours');\n // THEIR OBJECT, with the command swapped. Rebuilding it from ours would\n // drop whatever else they had set on it, such as their own padding.\n const base =\n typeof current === 'object' && current !== null && !Array.isArray(current)\n ? (current as Record<string, unknown>)\n : ours();\n return state === 'composed'\n ? { path, state, wrote: false, command: composed }\n : writeStatusLine(found, { ...base, command: composed }, 'composed');\n }\n if (state === 'foreign') {\n // NOT REPLACED, AND NOT WRITTEN AROUND. The user keeps what they set, and\n // gets the one command that adds ours to it.\n return { path, state, wrote: false, ...kept(current) };\n }\n if (state === 'composed') return { path, state, wrote: false };\n if (state === 'absent' && opts.refreshOnly === true) {\n return { path, state, wrote: false };\n }\n return writeStatusLine(found, ours(), 'ours');\n}\n\n/** `uninstall`: take out a status line of OURS, and only if it is ours alone. */\nexport async function removeStatusLine(settingsPath: string): Promise<StatusLineResult> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', wrote: false, warning: found.refusal.reason };\n }\n const { path, settings } = found;\n const current = settings.statusLine;\n const state = classifyStatusLine(current);\n if (state === 'ours') return writeStatusLine(found, undefined, 'absent');\n // A COMPOSED LINE IS MOSTLY THE USER'S TEXT, so it is not deleted: the half\n // this build wrote is unwound and their own command is put back exactly as it\n // was. A composition that was hand-edited since inverts to nothing and is\n // left whole, because guessing at someone's shell is the worse failure.\n if (state === 'composed') {\n const command = commandOf(current);\n const original = command === undefined ? null : decomposeCommand(command);\n if (original === null) return { path, state, wrote: false };\n const kept = { ...(current as Record<string, unknown>), command: original };\n return writeStatusLine(found, kept, 'foreign');\n }\n return { path, state, wrote: false };\n}\n\n/** What `doctor` reports, without writing anything. */\nexport async function inspectStatusLine(\n settingsPath: string,\n): Promise<{ path: string; state: StatusLineState; warning?: string }> {\n const found = await inspectHooksFile(settingsPath);\n if ('refusal' in found) {\n return { path: settingsPath, state: 'absent', warning: found.refusal.reason };\n }\n return { path: found.path, state: classifyStatusLine(found.settings.statusLine) };\n}\n\nfunction kept(current: unknown): { compose?: string } {\n const compose = composeFor(current);\n return compose === undefined ? {} : { compose };\n}\n\ntype Inspection = { path: string; raw: string | null; settings: Record<string, unknown> };\n\n/**\n * One key, written through the same read-compare-write the hooks writer uses:\n * every other key is copied through in its original order, the bytes are\n * re-read before the rename so a concurrent edit is refused rather than lost,\n * and the file keeps its mode.\n */\nasync function writeStatusLine(\n found: Inspection,\n value: Record<string, unknown> | undefined,\n state: StatusLineState,\n): Promise<StatusLineResult> {\n const { path, raw, settings } = found;\n const next: Record<string, unknown> = { ...settings };\n if (value === undefined) delete next.statusLine;\n else next.statusLine = value;\n const body = `${JSON.stringify(next, null, 2)}\\n`;\n const result: StatusLineResult = {\n path,\n state,\n wrote: false,\n ...(typeof value?.command === 'string' ? { command: value.command } : {}),\n };\n if (body === raw) return result;\n const mode = await stat(path)\n .then((s) => ({ mode: s.mode & 0o777 }))\n .catch(() => ({}));\n if (raw !== null && (await readFile(path, 'utf8').catch(() => null)) !== raw) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: 'changed-since-read',\n };\n }\n try {\n await writeFileAtomic(path, body, mode);\n } catch (err) {\n return {\n ...result,\n state: classifyStatusLine(settings.statusLine),\n warning: err instanceof Error ? err.message : String(err),\n };\n }\n return { ...result, wrote: true };\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,UAAU,YAAY;AAuBxB,IAAM,sBAAsB;AAE5B,IAAM,8BAA8B;AAE3C,IAAM,aAAa;AAKnB,IAAM,QAAmC,CAAC,OAAO,WAAW,MAAM;AAG3D,SAAS,eAAe,OAA+B;AAC5D,QAAM,OAAO,MAAM,KAAK,CAAC,UAAU,UAAU,KAAK;AAClD,MAAI,SAAS,QAAW;AACtB,UAAM,IAAI,SAAS,SAAS,uBAAuB,MAAM,KAAK,IAAI,CAAC,UAAU,KAAK,MAAM;AAAA,MACtF,KAAK;AAAA,IACP,CAAC;AAAA,EACH;AACA,SAAO;AACT;AAqBO,SAAS,mBAAmB,OAAiC;AAClE,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,QAAM,UACJ,OAA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ACA,OAC2B;AAC3B,QAAM,EAAE,MAAM,KAAK,SAAS,IAAI;AAChC,QAAM,OAAgC,EAAE,GAAG,SAAS;AACpD,MAAI,UAAU,OAAW,QAAO,KAAK;AAAA,MAChC,MAAK,aAAa;AACvB,QAAM,OAAO,GAAG,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;AAAA;AAC7C,QAAM,SAA2B;AAAA,IAC/B;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,GAAI,OAAO,OAAO,YAAY,WAAW,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,EACzE;AACA,MAAI,SAAS,IAAK,QAAO;AACzB,QAAM,OAAO,MAAM,KAAK,IAAI,EACzB,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,IAAM,EAAE,EACtC,MAAM,OAAO,CAAC,EAAE;AACnB,MAAI,QAAQ,QAAS,MAAM,SAAS,MAAM,MAAM,EAAE,MAAM,MAAM,IAAI,MAAO,KAAK;AAC5E,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,mBAAmB,SAAS,UAAU;AAAA,MAC7C,SAAS;AAAA,IACX;AAAA,EACF;AACA,MAAI;AACF,UAAM,gBAAgB,MAAM,MAAM,IAAI;AAAA,EACxC,SAAS,KAAK;AACZ,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,mBAAmB,SAAS,UAAU;AAAA,MAC7C,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IAC1D;AAAA,EACF;AACA,SAAO,EAAE,GAAG,QAAQ,OAAO,KAAK;AAClC;","names":["kept"]}
|
|
@@ -35,7 +35,7 @@ import {
|
|
|
35
35
|
randomBytes,
|
|
36
36
|
rotr,
|
|
37
37
|
toBytes
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-BPMWXTFX.js";
|
|
39
39
|
|
|
40
40
|
// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
|
|
41
41
|
function setBigUint64(view, byteOffset, value, isLE) {
|
|
@@ -2250,4 +2250,4 @@ export {
|
|
|
2250
2250
|
@noble/curves/esm/secp256k1.js:
|
|
2251
2251
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
2252
2252
|
*/
|
|
2253
|
-
//# sourceMappingURL=chunk-
|
|
2253
|
+
//# sourceMappingURL=chunk-JRGFKVAZ.js.map
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/lib/paths.ts
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join, resolve } from "node:path";
|
|
6
|
+
function dataDir(env = process.env) {
|
|
7
|
+
const override = env.TENJIN_DATA_DIR;
|
|
8
|
+
if (override !== void 0 && override.length > 0) return resolve(override);
|
|
9
|
+
return defaultDataDir();
|
|
10
|
+
}
|
|
11
|
+
function defaultDataDir(home = homedir()) {
|
|
12
|
+
return join(home, ".tenjin");
|
|
13
|
+
}
|
|
14
|
+
function configPath(dir = dataDir()) {
|
|
15
|
+
return join(dir, "config.json");
|
|
16
|
+
}
|
|
17
|
+
function walletPath(dir = dataDir()) {
|
|
18
|
+
return join(dir, "wallet.json");
|
|
19
|
+
}
|
|
20
|
+
function installIdPath(dir = dataDir()) {
|
|
21
|
+
return join(dir, "install-id");
|
|
22
|
+
}
|
|
23
|
+
function sessionPath(dir = dataDir()) {
|
|
24
|
+
return join(dir, "session.json");
|
|
25
|
+
}
|
|
26
|
+
function spendLedgerPath(dir = dataDir()) {
|
|
27
|
+
return join(dir, "spend.json");
|
|
28
|
+
}
|
|
29
|
+
function balanceCachePath(dir = dataDir()) {
|
|
30
|
+
return join(dir, "balance.json");
|
|
31
|
+
}
|
|
32
|
+
function updateCheckPath(dir = dataDir()) {
|
|
33
|
+
return join(dir, "update-check.json");
|
|
34
|
+
}
|
|
35
|
+
function hooksDir(dir = dataDir()) {
|
|
36
|
+
return join(dir, "hooks");
|
|
37
|
+
}
|
|
38
|
+
function hookHealthPath(dir = dataDir()) {
|
|
39
|
+
return join(dir, "hook-health.json");
|
|
40
|
+
}
|
|
41
|
+
function passphraseBlobPath(dir = dataDir()) {
|
|
42
|
+
return join(dir, "passphrase.dpapi");
|
|
43
|
+
}
|
|
44
|
+
function passphraseBlobPathFor(account, dir = dataDir()) {
|
|
45
|
+
return join(dir, `passphrase.${account}.dpapi`);
|
|
46
|
+
}
|
|
47
|
+
function archivedWalletPath(account, dir = dataDir()) {
|
|
48
|
+
return join(dir, `wallet.${account}.json.bak`);
|
|
49
|
+
}
|
|
50
|
+
function loopDbPath(dir = dataDir()) {
|
|
51
|
+
return join(dir, "loop.db");
|
|
52
|
+
}
|
|
53
|
+
function daemonTokenPath(dir = dataDir()) {
|
|
54
|
+
return join(dir, "daemon.token");
|
|
55
|
+
}
|
|
56
|
+
function daemonPidPath(dir = dataDir()) {
|
|
57
|
+
return join(dir, "daemon.pid");
|
|
58
|
+
}
|
|
59
|
+
function daemonLogPath(dir = dataDir()) {
|
|
60
|
+
return join(dir, "daemon.log");
|
|
61
|
+
}
|
|
62
|
+
function daemonSpawnPath(dir = dataDir()) {
|
|
63
|
+
return join(dir, "daemon.spawn");
|
|
64
|
+
}
|
|
65
|
+
function daemonBundlePath(dir = dataDir()) {
|
|
66
|
+
return join(hooksDir(dir), "tenjin-daemon.mjs");
|
|
67
|
+
}
|
|
68
|
+
function shimBundlePath(dir = dataDir()) {
|
|
69
|
+
return join(hooksDir(dir), "tenjin-shim.mjs");
|
|
70
|
+
}
|
|
71
|
+
var VITEST_REPORTER_FILE = "tenjin-vitest-reporter.mjs";
|
|
72
|
+
function vitestReporterPath(dir = dataDir()) {
|
|
73
|
+
return join(hooksDir(dir), VITEST_REPORTER_FILE);
|
|
74
|
+
}
|
|
75
|
+
function downloadsDir(dir = dataDir()) {
|
|
76
|
+
return join(dir, "downloads");
|
|
77
|
+
}
|
|
78
|
+
function paidLedgerPath(dir = dataDir()) {
|
|
79
|
+
return join(dir, "paid", "ledger.jsonl");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export {
|
|
83
|
+
dataDir,
|
|
84
|
+
defaultDataDir,
|
|
85
|
+
configPath,
|
|
86
|
+
walletPath,
|
|
87
|
+
installIdPath,
|
|
88
|
+
sessionPath,
|
|
89
|
+
spendLedgerPath,
|
|
90
|
+
balanceCachePath,
|
|
91
|
+
updateCheckPath,
|
|
92
|
+
hooksDir,
|
|
93
|
+
hookHealthPath,
|
|
94
|
+
passphraseBlobPath,
|
|
95
|
+
passphraseBlobPathFor,
|
|
96
|
+
archivedWalletPath,
|
|
97
|
+
loopDbPath,
|
|
98
|
+
daemonTokenPath,
|
|
99
|
+
daemonPidPath,
|
|
100
|
+
daemonLogPath,
|
|
101
|
+
daemonSpawnPath,
|
|
102
|
+
daemonBundlePath,
|
|
103
|
+
shimBundlePath,
|
|
104
|
+
VITEST_REPORTER_FILE,
|
|
105
|
+
vitestReporterPath,
|
|
106
|
+
downloadsDir,
|
|
107
|
+
paidLedgerPath
|
|
108
|
+
};
|
|
109
|
+
//# sourceMappingURL=chunk-K6AXXYCG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/paths.ts"],"sourcesContent":["import { homedir } from 'node:os';\nimport { join, resolve } from 'node:path';\n\n/**\n * Where the CLI keeps its config and wallet. Defaults to ~/.tenjin, overridable\n * via TENJIN_DATA_DIR (CI, ephemeral agents, and every test — which point it at\n * a temp dir so the real home is never touched).\n */\nexport function dataDir(env: NodeJS.ProcessEnv = process.env): string {\n const override = env.TENJIN_DATA_DIR;\n // Absolute, always: the daemon compares this string against its own\n // `data_dir` and is spawned with it as `cwd`, so a relative override must\n // mean the same directory from every process.\n if (override !== undefined && override.length > 0) return resolve(override);\n return defaultDataDir();\n}\n\n/**\n * The data dir a run with no override resolves. Split out of {@link dataDir} so\n * a caller holding a home directory can ask whether some other profile IS the\n * default one, without a second copy of the `.tenjin` literal.\n */\nexport function defaultDataDir(home: string = homedir()): string {\n return join(home, '.tenjin');\n}\n\nexport function configPath(dir: string = dataDir()): string {\n return join(dir, 'config.json');\n}\n\nexport function walletPath(dir: string = dataDir()): string {\n return join(dir, 'wallet.json');\n}\n\n/**\n * The anonymous install id sent to Tenjin as `X-Tenjin-Install` (lib/install-identity).\n * Under the data dir so it survives upgrades and reinstalls of the CLI itself.\n */\nexport function installIdPath(dir: string = dataDir()): string {\n return join(dir, 'install-id');\n}\n\n/**\n * Where the delegated P-256 session key + its wallet-signed SIWX delegation are\n * cached (B3, D35). A short-lived (≤24h) hot key: lower stakes than wallet.json,\n * but still written 0600 and address-bound so a wallet change invalidates it.\n */\nexport function sessionPath(dir: string = dataDir()): string {\n return join(dir, 'session.json');\n}\n\n/**\n * Where the client-side rolling spend ledger lives (lib/wallet/spend.ts).\n *\n * Its own file, NOT session.json: the two schemas are incompatible and both\n * readers treat a parse failure as \"absent\", so a shared path meant each writer\n * silently destroyed the other's file — a session key wiped the spend window, and\n * the next spend wiped the session key.\n */\nexport function spendLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'spend.json');\n}\n\n/**\n * The wallet's last USDC balance read (lib/usdc-balance). A pure cache, a\n * minute long: an unreadable file is simply read again from the chain.\n */\nexport function balanceCachePath(dir: string = dataDir()): string {\n return join(dir, 'balance.json');\n}\n\n/**\n * Where the once-a-day \"a newer tenjin-cli exists\" check caches the registry\n * answer. A pure cache: nothing here is authoritative, so an unreadable file is\n * simply re-fetched.\n */\nexport function updateCheckPath(dir: string = dataDir()): string {\n return join(dir, 'update-check.json');\n}\n\n/**\n * Where `install` writes the standalone harness hook scripts. Under the data dir\n * rather than the harness's own config directory: the scripts are ours, a harness\n * only ever holds the path to them, and one location serves every harness.\n */\nexport function hooksDir(dir: string = dataDir()): string {\n return join(dir, 'hooks');\n}\n\n/**\n * How the marketplace has been answering the dispatch hook lately, so a run of\n * failures stops the arm instead of paying the fetch budget per subagent through\n * an outage. Hook-written, unlocked, and cheap to lose, since a missing file\n * reads as \"healthy\". Its own file because two hooks writing one unlocked file\n * would erase each other.\n */\nexport function hookHealthPath(dir: string = dataDir()): string {\n return join(dir, 'hook-health.json');\n}\n\n/**\n * Where the LEGACY (pre-per-wallet) Windows DPAPI passphrase blob lives. The\n * file holds a DPAPI CurrentUser ciphertext, not the passphrase in plaintext.\n * New writes go to the per-wallet path below; this one is only read as a\n * migration fallback and removed after a verified per-wallet copy exists.\n */\nexport function passphraseBlobPath(dir: string = dataDir()): string {\n return join(dir, 'passphrase.dpapi');\n}\n\n/**\n * The per-wallet Windows DPAPI passphrase blob: one file per wallet address\n * (lowercase), so creating a new wallet never clobbers an old wallet's blob.\n * Only ever written on win32; other platforms use their own OS store.\n */\nexport function passphraseBlobPathFor(account: string, dir: string = dataDir()): string {\n return join(dir, `passphrase.${account}.dpapi`);\n}\n\n/**\n * Where `wallet create --replace` parks the outgoing wallet's keystore, keyed by\n * its lowercase address so successive replaces can never collide. Together with\n * the wallet's per-address passphrase entry in the OS store, this file keeps the\n * replaced wallet's funds recoverable; it is never read by the active-wallet\n * path.\n */\nexport function archivedWalletPath(account: string, dir: string = dataDir()): string {\n return join(dir, `wallet.${account}.json.bak`);\n}\n\n/**\n * The loop daemon's own state, all under the data dir (tenjin-notes\n * loop-redesign/02-redesign.md §4, §10).\n */\nexport function loopDbPath(dir: string = dataDir()): string {\n return join(dir, 'loop.db');\n}\n\n/** 32 random bytes, hex, 0600. Minted by `tenjin daemon start`, rotated only by\n * reinstall, NEVER deleted by the daemon: every transport reads it, and an idle\n * exit that removed it would strand them all. */\nexport function daemonTokenPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.token');\n}\n\n/** `{ pid, port, started_at, data_dir }`, advisory: written after the bind,\n * removed at exit only by the process whose pid it names. Liveness is\n * `GET /health`, never this file alone. */\nexport function daemonPidPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.pid');\n}\n\n/** Where a detached daemon's stdout and stderr go, and where the shim writes its\n * one `daemon-down` line when it cannot reach one. */\nexport function daemonLogPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.log');\n}\n\n/** An empty file whose mtime is the last spawn attempt; the shim's backoff. */\nexport function daemonSpawnPath(dir: string = dataDir()): string {\n return join(dir, 'daemon.spawn');\n}\n\n/** The single-file daemon bundle `tenjin daemon start` copies from `dist`. */\nexport function daemonBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-daemon.mjs');\n}\n\n/** The ensure-and-forward shim the two `command` hook entries run. */\nexport function shimBundlePath(dir: string = dataDir()): string {\n return join(hooksDir(dir), 'tenjin-shim.mjs');\n}\n\n/** Tenjin's own vitest reporter, copied beside the bundles. NOT A HOOK ENTRY\n * and never spawned: a repo's own `vitest.config.ts` imports it by this\n * absolute path, which is why `doctor` can hint at it verbatim. */\nexport const VITEST_REPORTER_FILE = 'tenjin-vitest-reporter.mjs';\n\nexport function vitestReporterPath(dir: string = dataDir()): string {\n return join(hooksDir(dir), VITEST_REPORTER_FILE);\n}\n\n/**\n * Where a router lookup that bought a file (a sound, an image) saves it. The\n * bytes cannot ride in the tool result, so the result names this file instead.\n */\nexport function downloadsDir(dir: string = dataDir()): string {\n return join(dir, 'downloads');\n}\n\n/**\n * One JSON line per paid router call: what was bought, from whom, for how much,\n * the settlement it carried and the files it saved. The user's own record; only\n * reconcile reads it back (`tenjin payments reconcile`, and the `request` tool's\n * pass beside each lookup), to settle what was left unknown.\n */\nexport function paidLedgerPath(dir: string = dataDir()): string {\n return join(dir, 'paid', 'ledger.jsonl');\n}\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,MAAM,eAAe;AAOvB,SAAS,QAAQ,MAAyB,QAAQ,KAAa;AACpE,QAAM,WAAW,IAAI;AAIrB,MAAI,aAAa,UAAa,SAAS,SAAS,EAAG,QAAO,QAAQ,QAAQ;AAC1E,SAAO,eAAe;AACxB;AAOO,SAAS,eAAe,OAAe,QAAQ,GA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AS,cAAc,MAAc,QAAQ,GAAW;AAC7D,SAAO,KAAK,KAAK,YAAY;AAC/B;AAGO,SAAS,gBAAgB,MAAc,QAAQ,GAAW;AAC/D,SAAO,KAAK,KAAK,cAAc;AACjC;AAGO,SAAS,iBAAiB,MAAc,QAAQ,GAAW;AAChE,SAAO,KAAK,SAAS,GAAG,GAAG,mBAAmB;AAChD;AAGO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,SAAS,GAAG,GAAG,iBAAiB;AAC9C;AAKO,IAAM,uBAAuB;AAE7B,SAAS,mBAAmB,MAAc,QAAQ,GAAW;AAClE,SAAO,KAAK,SAAS,GAAG,GAAG,oBAAoB;AACjD;AAMO,SAAS,aAAa,MAAc,QAAQ,GAAW;AAC5D,SAAO,KAAK,KAAK,WAAW;AAC9B;AAQO,SAAS,eAAe,MAAc,QAAQ,GAAW;AAC9D,SAAO,KAAK,KAAK,QAAQ,cAAc;AACzC;","names":[]}
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
swap32IfBE,
|
|
16
16
|
toBytes,
|
|
17
17
|
u32
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-BPMWXTFX.js";
|
|
19
19
|
|
|
20
20
|
// node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js
|
|
21
21
|
var _0n = BigInt(0);
|
|
@@ -201,4 +201,4 @@ var keccak_256 = /* @__PURE__ */ (() => gen(1, 136, 256 / 8))();
|
|
|
201
201
|
export {
|
|
202
202
|
keccak_256
|
|
203
203
|
};
|
|
204
|
-
//# sourceMappingURL=chunk-
|
|
204
|
+
//# sourceMappingURL=chunk-KG3D7FIF.js.map
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
CliError
|
|
4
|
+
} from "./chunk-JLEF5WHM.js";
|
|
5
|
+
|
|
6
|
+
// src/lib/destination.ts
|
|
7
|
+
import { lookup } from "node:dns/promises";
|
|
8
|
+
import { BlockList, isIP } from "node:net";
|
|
9
|
+
var blockedV4 = new BlockList();
|
|
10
|
+
for (const [base, prefix] of [
|
|
11
|
+
["0.0.0.0", 8],
|
|
12
|
+
["10.0.0.0", 8],
|
|
13
|
+
["100.64.0.0", 10],
|
|
14
|
+
["127.0.0.0", 8],
|
|
15
|
+
["169.254.0.0", 16],
|
|
16
|
+
["172.16.0.0", 12],
|
|
17
|
+
["192.0.0.0", 24],
|
|
18
|
+
["192.0.2.0", 24],
|
|
19
|
+
["192.168.0.0", 16],
|
|
20
|
+
["198.18.0.0", 15],
|
|
21
|
+
["198.51.100.0", 24],
|
|
22
|
+
["203.0.113.0", 24],
|
|
23
|
+
["224.0.0.0", 4],
|
|
24
|
+
["240.0.0.0", 4]
|
|
25
|
+
]) {
|
|
26
|
+
blockedV4.addSubnet(base, prefix, "ipv4");
|
|
27
|
+
}
|
|
28
|
+
var blockedV6 = new BlockList();
|
|
29
|
+
for (const [base, prefix] of [
|
|
30
|
+
["::", 128],
|
|
31
|
+
["::1", 128],
|
|
32
|
+
["64:ff9b::", 96],
|
|
33
|
+
["100::", 64],
|
|
34
|
+
["2001:db8::", 32],
|
|
35
|
+
["fc00::", 7],
|
|
36
|
+
["fe80::", 10],
|
|
37
|
+
["ff00::", 8]
|
|
38
|
+
]) {
|
|
39
|
+
blockedV6.addSubnet(base, prefix, "ipv6");
|
|
40
|
+
}
|
|
41
|
+
function isPublicAddress(value) {
|
|
42
|
+
const kind = isIP(value);
|
|
43
|
+
if (kind === 4) return !blockedV4.check(value, "ipv4");
|
|
44
|
+
return kind === 6 && /^[23]/i.test(value) && !blockedV6.check(value, "ipv6");
|
|
45
|
+
}
|
|
46
|
+
var LOCAL_SUFFIX = /(?:^|\.)(?:localhost|local|internal|home|lan)$/i;
|
|
47
|
+
function refuse(message, details) {
|
|
48
|
+
throw new CliError("USAGE", message, {
|
|
49
|
+
fix: "Paid requests go to public HTTPS endpoints only; nothing was signed.",
|
|
50
|
+
...details !== void 0 ? { details } : {}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
function assertPublicHttpsUrl(raw) {
|
|
54
|
+
let url;
|
|
55
|
+
try {
|
|
56
|
+
url = new URL(raw);
|
|
57
|
+
} catch {
|
|
58
|
+
return refuse(`Invalid URL: ${JSON.stringify(raw.slice(0, 200))}`);
|
|
59
|
+
}
|
|
60
|
+
if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.hash !== "" || url.port !== "" && url.port !== "443" || raw.length > 16384) {
|
|
61
|
+
refuse("Only public HTTPS endpoints without credentials, fragments or custom ports are paid.");
|
|
62
|
+
}
|
|
63
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
64
|
+
if (!host.includes(".") && isIP(host) === 0) refuse("The endpoint host is not a public name.");
|
|
65
|
+
if (LOCAL_SUFFIX.test(host)) refuse("Private or local destinations are not paid.");
|
|
66
|
+
if (isIP(host) !== 0 && !isPublicAddress(host)) {
|
|
67
|
+
refuse("Private or reserved IP destinations are not paid.");
|
|
68
|
+
}
|
|
69
|
+
return url;
|
|
70
|
+
}
|
|
71
|
+
async function assertPublicDestination(raw, options = {}) {
|
|
72
|
+
return (await resolvePublicDestination(raw, options)).url;
|
|
73
|
+
}
|
|
74
|
+
async function resolvePublicDestination(raw, options = {}) {
|
|
75
|
+
const url = assertPublicHttpsUrl(raw);
|
|
76
|
+
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
77
|
+
if (isIP(host) !== 0) return { url, address: host, family: isIP(host) === 6 ? 6 : 4 };
|
|
78
|
+
const resolve = options.resolveHostname ?? ((name) => lookup(name, { all: true }));
|
|
79
|
+
const signal = AbortSignal.timeout(options.timeoutMs ?? 5e3);
|
|
80
|
+
let addresses;
|
|
81
|
+
try {
|
|
82
|
+
addresses = await Promise.race([
|
|
83
|
+
resolve(host),
|
|
84
|
+
new Promise((_, reject) => {
|
|
85
|
+
signal.addEventListener("abort", () => reject(new Error("DNS lookup timed out.")), {
|
|
86
|
+
once: true
|
|
87
|
+
});
|
|
88
|
+
})
|
|
89
|
+
]);
|
|
90
|
+
} catch (err) {
|
|
91
|
+
return refuse(`The endpoint host ${host} could not be resolved.`, {
|
|
92
|
+
cause: err instanceof Error ? err.message : String(err)
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
if (addresses.length === 0 || addresses.some((entry) => !isPublicAddress(entry.address))) {
|
|
96
|
+
refuse(`The endpoint host ${host} resolves to a private or unsupported network address.`);
|
|
97
|
+
}
|
|
98
|
+
const first = addresses[0];
|
|
99
|
+
return { url, address: first.address, family: isIP(first.address) === 6 ? 6 : 4 };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export {
|
|
103
|
+
isPublicAddress,
|
|
104
|
+
assertPublicDestination,
|
|
105
|
+
resolvePublicDestination
|
|
106
|
+
};
|
|
107
|
+
//# sourceMappingURL=chunk-LAIZ2AQA.js.map
|