tenjin-cli 0.1.0-alpha.24 → 0.1.0-alpha.26
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 +19 -42
- package/dist/{chunk-GPLSNGKX.js → chunk-4HAV6IFE.js} +6 -6
- package/dist/{chunk-UXSF7IFD.js → chunk-5HS54CLI.js} +3 -3
- package/dist/{chunk-RCJ64OXH.js → chunk-5INS5ZZF.js} +36 -7
- package/dist/chunk-5INS5ZZF.js.map +1 -0
- package/dist/{chunk-XZUGRTSV.js → chunk-5NUF4BHR.js} +5 -3
- package/dist/{chunk-XZUGRTSV.js.map → chunk-5NUF4BHR.js.map} +1 -1
- package/dist/{chunk-YZTIYDWU.js → chunk-65EJJVT3.js} +2 -2
- package/dist/{chunk-ZMFDMALH.js → chunk-6JIYGYRB.js} +3 -53
- package/dist/chunk-6JIYGYRB.js.map +1 -0
- package/dist/chunk-7EKYXMUO.js +7536 -0
- package/dist/chunk-7EKYXMUO.js.map +1 -0
- package/dist/chunk-AKWGE6JQ.js +49 -0
- package/dist/chunk-AKWGE6JQ.js.map +1 -0
- package/dist/{chunk-KC24CYGV.js → chunk-ALJRB7NG.js} +14 -9
- package/dist/chunk-ALJRB7NG.js.map +1 -0
- package/dist/{chunk-S2NRVRPF.js → chunk-BOAI23CX.js} +53 -2
- package/dist/chunk-BOAI23CX.js.map +1 -0
- package/dist/{chunk-SQSKVKX6.js → chunk-DI7WHXOZ.js} +20 -16
- package/dist/chunk-DI7WHXOZ.js.map +1 -0
- package/dist/{chunk-UBOFYC6J.js → chunk-EJXIK6WY.js} +1817 -137
- package/dist/chunk-EJXIK6WY.js.map +1 -0
- package/dist/{chunk-RGVOODF4.js → chunk-EL56RW2J.js} +164 -7463
- package/dist/chunk-EL56RW2J.js.map +1 -0
- package/dist/{chunk-ZNZGBUV6.js → chunk-GHR4BTNJ.js} +9 -7
- package/dist/chunk-GHR4BTNJ.js.map +1 -0
- package/dist/chunk-H4BOQLWW.js +99 -0
- package/dist/chunk-H4BOQLWW.js.map +1 -0
- package/dist/{chunk-TMLCEPCD.js → chunk-HII5HOQV.js} +3 -5
- package/dist/chunk-HII5HOQV.js.map +1 -0
- package/dist/chunk-LFZJM56J.js +159 -0
- package/dist/chunk-LFZJM56J.js.map +1 -0
- package/dist/chunk-OBPZ36HG.js +145 -0
- package/dist/chunk-OBPZ36HG.js.map +1 -0
- package/dist/{chunk-NSDZESRS.js → chunk-OZ3LWLCI.js} +3 -3
- package/dist/chunk-PM2MOXJ3.js +66 -0
- package/dist/chunk-PM2MOXJ3.js.map +1 -0
- package/dist/chunk-PZ5N6BAL.js +268 -0
- package/dist/chunk-PZ5N6BAL.js.map +1 -0
- package/dist/{chunk-O2WN732M.js → chunk-UDWGT4FX.js} +2 -2
- package/dist/{chunk-W2ARIOAZ.js → chunk-VNT3CQFV.js} +23 -25
- package/dist/chunk-VNT3CQFV.js.map +1 -0
- package/dist/{chunk-XRW4N23F.js → chunk-W36HL4TB.js} +6 -6
- package/dist/{chunk-IIE65SJC.js → chunk-WT7DHJNJ.js} +4 -4
- package/dist/{chunk-P22ZWXFX.js → chunk-XICKN3CH.js} +49 -4
- package/dist/chunk-XICKN3CH.js.map +1 -0
- package/dist/chunk-XMIVHQ35.js +55 -0
- package/dist/chunk-XMIVHQ35.js.map +1 -0
- package/dist/chunk-YHKXNYTB.js +105 -0
- package/dist/chunk-YHKXNYTB.js.map +1 -0
- package/dist/{chunk-H5UR3GFJ.js → chunk-YHWBDCGS.js} +272 -54
- package/dist/chunk-YHWBDCGS.js.map +1 -0
- package/dist/{hook-command-GMIDXVFK.js → chunk-YLCWI6ZR.js} +231 -40
- package/dist/chunk-YLCWI6ZR.js.map +1 -0
- package/dist/{chunk-FFL5M5BC.js → chunk-YTM7OURD.js} +2 -2
- package/dist/{chunk-EP5P2STS.js → chunk-Z7R2QDX2.js} +67 -10
- package/dist/chunk-Z7R2QDX2.js.map +1 -0
- package/dist/chunk-ZLD6MJVJ.js +30 -0
- package/dist/chunk-ZLD6MJVJ.js.map +1 -0
- package/dist/{cli-GGNOQQEB.js → cli-2U5JB7OQ.js} +38 -36
- package/dist/{cli-GGNOQQEB.js.map → cli-2U5JB7OQ.js.map} +1 -1
- package/dist/{config-XUUFICXK.js → config-44EGO636.js} +14 -9
- package/dist/{doctor-3LGF6CWI.js → doctor-BD42BBEG.js} +231 -97
- package/dist/doctor-BD42BBEG.js.map +1 -0
- package/dist/env-proxy-KEGEMWKX.js +15 -0
- package/dist/{fund-3URFMBMN.js → fund-WQOOUESE.js} +26 -17
- package/dist/fund-WQOOUESE.js.map +1 -0
- package/dist/hook-command-23LC5NRN.js +32 -0
- package/dist/index.js +5 -3
- package/dist/index.js.map +1 -1
- package/dist/{install-FRTG4KHF.js → install-REPLHNU7.js} +25 -16
- package/dist/{install-identity-WNXSYP6N.js → install-identity-4RDWTLJ2.js} +6 -7
- package/dist/{install-wallet-MXLJJP3N.js → install-wallet-USHWL7AX.js} +10 -9
- package/dist/{install-wallet-MXLJJP3N.js.map → install-wallet-USHWL7AX.js.map} +1 -1
- package/dist/{mcp-O2WJ3QBW.js → mcp-T5SYCLP7.js} +778 -83
- package/dist/mcp-T5SYCLP7.js.map +1 -0
- package/dist/{pay-43WUYTW5.js → pay-276DSSYG.js} +16 -14
- package/dist/{payments-7UTMMTIO.js → payments-TZYLJXK3.js} +7 -7
- package/dist/{send-ALHG2RXT.js → send-YHDKZPED.js} +10 -11
- package/dist/{send-ALHG2RXT.js.map → send-YHDKZPED.js.map} +1 -1
- package/dist/{status-CFPNHB6R.js → status-X2INT6VD.js} +8 -9
- package/dist/{status-CFPNHB6R.js.map → status-X2INT6VD.js.map} +1 -1
- package/dist/{status-line-FJ6N7MKJ.js → status-line-QKDJYZGV.js} +4 -5
- package/dist/{status-line-FJ6N7MKJ.js.map → status-line-QKDJYZGV.js.map} +1 -1
- package/dist/{status-line-wiring-GXFNXHPE.js → status-line-wiring-LW4HFRHB.js} +6 -4
- package/dist/status-line-wiring-LW4HFRHB.js.map +1 -0
- package/dist/{uninstall-5P2GFYBY.js → uninstall-NVTGU7JD.js} +43 -33
- package/dist/uninstall-NVTGU7JD.js.map +1 -0
- package/dist/{update-QJ5YHJ7I.js → update-QXVH2DE7.js} +25 -7
- package/dist/update-QXVH2DE7.js.map +1 -0
- package/dist/{wallet-6OJPGNEV.js → wallet-CKKB23D5.js} +10 -9
- package/dist/wallet-CKKB23D5.js.map +1 -0
- package/docs/agent-permissions.md +18 -5
- package/docs/troubleshooting.md +13 -0
- package/package.json +8 -6
- package/dist/chunk-EP5P2STS.js.map +0 -1
- package/dist/chunk-H5UR3GFJ.js.map +0 -1
- package/dist/chunk-KC24CYGV.js.map +0 -1
- package/dist/chunk-O2JYBOUO.js +0 -47
- package/dist/chunk-O2JYBOUO.js.map +0 -1
- package/dist/chunk-P22ZWXFX.js.map +0 -1
- package/dist/chunk-RCJ64OXH.js.map +0 -1
- package/dist/chunk-RGVOODF4.js.map +0 -1
- package/dist/chunk-S2NRVRPF.js.map +0 -1
- package/dist/chunk-SQSKVKX6.js.map +0 -1
- package/dist/chunk-TMLCEPCD.js.map +0 -1
- package/dist/chunk-UBOFYC6J.js.map +0 -1
- package/dist/chunk-W2ARIOAZ.js.map +0 -1
- package/dist/chunk-YXLG7Q6Q.js +0 -140
- package/dist/chunk-YXLG7Q6Q.js.map +0 -1
- package/dist/chunk-ZMFDMALH.js.map +0 -1
- package/dist/chunk-ZNZGBUV6.js.map +0 -1
- package/dist/doctor-3LGF6CWI.js.map +0 -1
- package/dist/fund-3URFMBMN.js.map +0 -1
- package/dist/hook-command-GMIDXVFK.js.map +0 -1
- package/dist/mcp-O2WJ3QBW.js.map +0 -1
- package/dist/uninstall-5P2GFYBY.js.map +0 -1
- package/dist/update-QJ5YHJ7I.js.map +0 -1
- /package/dist/{chunk-GPLSNGKX.js.map → chunk-4HAV6IFE.js.map} +0 -0
- /package/dist/{chunk-UXSF7IFD.js.map → chunk-5HS54CLI.js.map} +0 -0
- /package/dist/{chunk-YZTIYDWU.js.map → chunk-65EJJVT3.js.map} +0 -0
- /package/dist/{chunk-NSDZESRS.js.map → chunk-OZ3LWLCI.js.map} +0 -0
- /package/dist/{chunk-O2WN732M.js.map → chunk-UDWGT4FX.js.map} +0 -0
- /package/dist/{chunk-XRW4N23F.js.map → chunk-W36HL4TB.js.map} +0 -0
- /package/dist/{chunk-IIE65SJC.js.map → chunk-WT7DHJNJ.js.map} +0 -0
- /package/dist/{chunk-FFL5M5BC.js.map → chunk-YTM7OURD.js.map} +0 -0
- /package/dist/{config-XUUFICXK.js.map → config-44EGO636.js.map} +0 -0
- /package/dist/{install-FRTG4KHF.js.map → env-proxy-KEGEMWKX.js.map} +0 -0
- /package/dist/{install-identity-WNXSYP6N.js.map → hook-command-23LC5NRN.js.map} +0 -0
- /package/dist/{pay-43WUYTW5.js.map → install-REPLHNU7.js.map} +0 -0
- /package/dist/{status-line-wiring-GXFNXHPE.js.map → install-identity-4RDWTLJ2.js.map} +0 -0
- /package/dist/{wallet-6OJPGNEV.js.map → pay-276DSSYG.js.map} +0 -0
- /package/dist/{payments-7UTMMTIO.js.map → payments-TZYLJXK3.js.map} +0 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
|
|
3
|
+
// src/router/hook-tool.ts
|
|
4
|
+
var HOOK_KINDS = ["prompt", "native", "shortfall", "agent", "ask", "answer"];
|
|
5
|
+
var HOOK_TOOL = "hook";
|
|
6
|
+
var COMMON = ["hook_event_name", "session_id", "transcript_path", "cwd"];
|
|
7
|
+
var CALL = ["tool_name", "tool_input", "tool_use_id", "agent_id", "agent_type"];
|
|
8
|
+
var FIELDS = {
|
|
9
|
+
prompt: [...COMMON, "prompt"],
|
|
10
|
+
native: [...COMMON, ...CALL],
|
|
11
|
+
agent: [...COMMON, ...CALL],
|
|
12
|
+
ask: [...COMMON, ...CALL],
|
|
13
|
+
answer: [...COMMON, ...CALL, "tool_response"],
|
|
14
|
+
shortfall: [...COMMON, ...CALL, "tool_response", "error", "is_interrupt"]
|
|
15
|
+
};
|
|
16
|
+
var JSON_FIELDS = /* @__PURE__ */ new Set(["tool_input", "tool_response", "is_interrupt"]);
|
|
17
|
+
function hookToolInput(kind) {
|
|
18
|
+
return Object.fromEntries([
|
|
19
|
+
["kind", kind],
|
|
20
|
+
...FIELDS[kind].map((field) => [field, `\${${field}}`])
|
|
21
|
+
]);
|
|
22
|
+
}
|
|
23
|
+
var HOOK_TOOL_FIELDS = [...new Set(Object.values(FIELDS).flat())];
|
|
24
|
+
function eventFromToolInput(args) {
|
|
25
|
+
const event = {};
|
|
26
|
+
for (const field of HOOK_TOOL_FIELDS) {
|
|
27
|
+
const value = args[field];
|
|
28
|
+
if (typeof value !== "string" || value.length === 0) continue;
|
|
29
|
+
if (!JSON_FIELDS.has(field)) {
|
|
30
|
+
event[field] = value;
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
try {
|
|
34
|
+
event[field] = JSON.parse(value);
|
|
35
|
+
} catch {
|
|
36
|
+
event[field] = value;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return event;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export {
|
|
43
|
+
HOOK_KINDS,
|
|
44
|
+
HOOK_TOOL,
|
|
45
|
+
hookToolInput,
|
|
46
|
+
HOOK_TOOL_FIELDS,
|
|
47
|
+
eventFromToolInput
|
|
48
|
+
};
|
|
49
|
+
//# sourceMappingURL=chunk-AKWGE6JQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/hook-tool.ts"],"sourcesContent":["/**\n * THE HOOK EVENT, CARRIED BY AN `mcp_tool` ENTRY. Claude Code calls the `hook`\n * tool of the session's own `tenjin mcp` for each routing leg, with the event's\n * fields substituted into the entry's `input` (`${session_id}` and so on): a\n * string field arrives as written, an object one (`tool_input`,\n * `tool_response`) as its JSON text, a boolean as `true` or `false`, and a\n * field the event lacks as an empty string. This turns that back into the\n * event the handlers already read, and spells the `input` `install` writes.\n */\n\n/** The routing legs, one per hook entry `install` writes. */\nexport const HOOK_KINDS = ['prompt', 'native', 'shortfall', 'agent', 'ask', 'answer'] as const;\nexport type HookKind = (typeof HOOK_KINDS)[number];\n\n/** The tool `tenjin mcp` registers for the hook entries. */\nexport const HOOK_TOOL = 'hook';\n\n/** The event fields each leg reads, as Claude Code names them. */\nconst COMMON = ['hook_event_name', 'session_id', 'transcript_path', 'cwd'] as const;\nconst CALL = ['tool_name', 'tool_input', 'tool_use_id', 'agent_id', 'agent_type'] as const;\n\nconst FIELDS: Record<HookKind, readonly string[]> = {\n prompt: [...COMMON, 'prompt'],\n native: [...COMMON, ...CALL],\n agent: [...COMMON, ...CALL],\n ask: [...COMMON, ...CALL],\n answer: [...COMMON, ...CALL, 'tool_response'],\n shortfall: [...COMMON, ...CALL, 'tool_response', 'error', 'is_interrupt'],\n};\n\n/** Fields whose value is an object or a boolean, sent as JSON text. */\nconst JSON_FIELDS = new Set(['tool_input', 'tool_response', 'is_interrupt']);\n\n/** The `input` of one leg's `mcp_tool` entry. */\nexport function hookToolInput(kind: HookKind): Record<string, string> {\n return Object.fromEntries([\n ['kind', kind],\n ...FIELDS[kind].map((field) => [field, `\\${${field}}`]),\n ]);\n}\n\n/** Every field any leg sends, for the tool's input schema. */\nexport const HOOK_TOOL_FIELDS: readonly string[] = [...new Set(Object.values(FIELDS).flat())];\n\nexport function isHookKind(value: unknown): value is HookKind {\n return typeof value === 'string' && (HOOK_KINDS as readonly string[]).includes(value);\n}\n\n/**\n * The harness event from the tool's arguments: empty fields dropped (the\n * event did not carry them), the JSON ones parsed back. A JSON field that does\n * not parse is kept as the string it is.\n */\nexport function eventFromToolInput(args: Record<string, unknown>): Record<string, unknown> {\n const event: Record<string, unknown> = {};\n for (const field of HOOK_TOOL_FIELDS) {\n const value = args[field];\n if (typeof value !== 'string' || value.length === 0) continue;\n if (!JSON_FIELDS.has(field)) {\n event[field] = value;\n continue;\n }\n try {\n event[field] = JSON.parse(value) as unknown;\n } catch {\n event[field] = value;\n }\n }\n return event;\n}\n"],"mappings":";;;AAWO,IAAM,aAAa,CAAC,UAAU,UAAU,aAAa,SAAS,OAAO,QAAQ;AAI7E,IAAM,YAAY;AAGzB,IAAM,SAAS,CAAC,mBAAmB,cAAc,mBAAmB,KAAK;AACzE,IAAM,OAAO,CAAC,aAAa,cAAc,eAAe,YAAY,YAAY;AAEhF,IAAM,SAA8C;AAAA,EAClD,QAAQ,CAAC,GAAG,QAAQ,QAAQ;AAAA,EAC5B,QAAQ,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EAC3B,OAAO,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EAC1B,KAAK,CAAC,GAAG,QAAQ,GAAG,IAAI;AAAA,EACxB,QAAQ,CAAC,GAAG,QAAQ,GAAG,MAAM,eAAe;AAAA,EAC5C,WAAW,CAAC,GAAG,QAAQ,GAAG,MAAM,iBAAiB,SAAS,cAAc;AAC1E;AAGA,IAAM,cAAc,oBAAI,IAAI,CAAC,cAAc,iBAAiB,cAAc,CAAC;AAGpE,SAAS,cAAc,MAAwC;AACpE,SAAO,OAAO,YAAY;AAAA,IACxB,CAAC,QAAQ,IAAI;AAAA,IACb,GAAG,OAAO,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,OAAO,MAAM,KAAK,GAAG,CAAC;AAAA,EACxD,CAAC;AACH;AAGO,IAAM,mBAAsC,CAAC,GAAG,IAAI,IAAI,OAAO,OAAO,MAAM,EAAE,KAAK,CAAC,CAAC;AAWrF,SAAS,mBAAmB,MAAwD;AACzF,QAAM,QAAiC,CAAC;AACxC,aAAW,SAAS,kBAAkB;AACpC,UAAM,QAAQ,KAAK,KAAK;AACxB,QAAI,OAAO,UAAU,YAAY,MAAM,WAAW,EAAG;AACrD,QAAI,CAAC,YAAY,IAAI,KAAK,GAAG;AAC3B,YAAM,KAAK,IAAI;AACf;AAAA,IACF;AACA,QAAI;AACF,YAAM,KAAK,IAAI,KAAK,MAAM,KAAK;AAAA,IACjC,QAAQ;AACN,YAAM,KAAK,IAAI;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
addressQrLines
|
|
4
|
+
} from "./chunk-PZ5N6BAL.js";
|
|
2
5
|
import {
|
|
3
6
|
getUsdcBalance
|
|
4
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-YTM7OURD.js";
|
|
5
8
|
import {
|
|
6
9
|
commitLocalWallet,
|
|
7
10
|
createLocalWallet,
|
|
@@ -14,18 +17,16 @@ import {
|
|
|
14
17
|
verifyAndPreserveOutgoingWallet,
|
|
15
18
|
walletExistsError,
|
|
16
19
|
walletFileExists
|
|
17
|
-
} from "./chunk-
|
|
20
|
+
} from "./chunk-4HAV6IFE.js";
|
|
18
21
|
import {
|
|
19
22
|
LockTimeoutError,
|
|
20
23
|
withFileLock
|
|
21
24
|
} from "./chunk-MEFB5KHA.js";
|
|
22
|
-
import {
|
|
23
|
-
toMoney
|
|
24
|
-
} from "./chunk-O2JYBOUO.js";
|
|
25
25
|
import {
|
|
26
26
|
loadRawConfig,
|
|
27
|
-
resolveSettings
|
|
28
|
-
|
|
27
|
+
resolveSettings,
|
|
28
|
+
toMoney
|
|
29
|
+
} from "./chunk-XICKN3CH.js";
|
|
29
30
|
import {
|
|
30
31
|
CliError
|
|
31
32
|
} from "./chunk-JLEF5WHM.js";
|
|
@@ -171,7 +172,11 @@ async function runWalletShow(ctx, opts = {}) {
|
|
|
171
172
|
archivedWallets,
|
|
172
173
|
warnings
|
|
173
174
|
} = await provider.diagnostics();
|
|
174
|
-
const humanLines = [
|
|
175
|
+
const humanLines = [
|
|
176
|
+
`Address: ${desc.address}`,
|
|
177
|
+
...opts.qr !== false && ctx.io.isTTY && !ctx.flags.json ? addressQrLines(desc.address, ctx.io.stdout) : [],
|
|
178
|
+
`Key source: ${desc.credentialSource}`
|
|
179
|
+
];
|
|
175
180
|
if (keyStorage !== void 0) humanLines.push(`Key storage: ${keyStorage}`);
|
|
176
181
|
if (passphraseSource !== void 0) humanLines.push(`Passphrase: ${passphraseSource}`);
|
|
177
182
|
if (archivedWallets !== void 0 && archivedWallets.length > 0) {
|
|
@@ -239,4 +244,4 @@ export {
|
|
|
239
244
|
runWalletShow,
|
|
240
245
|
runWalletBalance
|
|
241
246
|
};
|
|
242
|
-
//# sourceMappingURL=chunk-
|
|
247
|
+
//# sourceMappingURL=chunk-ALJRB7NG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/wallet.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { CliError } from '../lib/errors';\nimport { walletPath } from '../lib/paths';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { loadRawConfig, resolveSettings } from '../lib/config';\nimport { toMoney } from '../lib/money';\nimport { getUsdcBalance } from '../lib/usdc';\nimport { addressQrLines } from '../lib/qr';\nimport {\n commitLocalWallet,\n createLocalWallet,\n describeWallet,\n parkOutgoingWallet,\n prepareLocalWallet,\n resolveWalletProvider,\n restoreParkedWallet,\n verifyAndPreserveOutgoingWallet,\n type ArchivedWalletInfo,\n type ResolveWalletProviderOptions,\n} from '../lib/wallet';\nimport { walletExistsError, walletFileExists } from '../lib/wallet/store';\nimport { resolvePassphraseForCreate, type PassphraseSource } from '../lib/wallet/passphrase';\nimport type { PassphraseOverrides } from '../lib/wallet/local';\nimport type { CommandContext, CommandResult } from '../context';\n\nconst FUNDING_LINE =\n 'Fund it with `tenjin wallet fund` (card via Coinbase), or send USDC on Base. $5 covers ~50 typical resources.';\nconst KEY_STORAGE = 'encrypted (keystore v3, scrypt)';\nconst isWindows = process.platform === 'win32';\n\nexport interface WalletCreateOptions {\n /**\n * Explicitly replace the existing active wallet (mirrors the `--yes`-style\n * explicit-flag precedent): the outgoing wallet is ARCHIVED — passphrase\n * verified against its keystore and preserved under its own address, keystore\n * parked beside the new one — never destroyed. Without it, create refuses\n * when a wallet exists. There is always exactly ONE active wallet.\n */\n replace?: boolean;\n /** Test seam for passphrase resolution (keychain exec, TTY prompt, platform). */\n passphrase?: PassphraseOverrides;\n /**\n * The environment TENJIN_WALLET_PASSPHRASE is read from; defaults to\n * process.env. A seam rather than a global read so a caller (and above all a\n * test) can settle the passphrase source WITHOUT mutating the real process\n * environment, which under a parallel runner leaks across whole test files.\n */\n env?: NodeJS.ProcessEnv;\n}\n\nexport async function runWalletCreate(\n ctx: CommandContext,\n opts: WalletCreateOptions = {},\n): Promise<CommandResult> {\n const {\n address,\n walletPath: path,\n source,\n replaced,\n } = await createWalletLocked(ctx.dataDir, opts);\n\n const warnings = custodyWarnings();\n return {\n data: {\n address,\n walletPath: path,\n provider: 'local',\n policyEnforcement: 'client-only',\n keyStorage: KEY_STORAGE,\n passphraseSource: source,\n ...(replaced !== undefined\n ? {\n replaced: {\n address: replaced.address,\n archivedWalletPath: replaced.archivedPath,\n passphrasePreserved: replaced.passphraseLocation,\n ...(replaced.unarchivedReason !== undefined\n ? { unarchivedReason: replaced.unarchivedReason }\n : {}),\n },\n }\n : {}),\n warnings,\n },\n humanLines: [\n `Wallet created: ${address}`,\n `Key stored ${KEY_STORAGE}.`,\n passphraseNote(source, address),\n ...(replaced !== undefined ? replacedNote(replaced, path) : []),\n FUNDING_LINE,\n ...warnings,\n ],\n };\n}\n\n/** Where the outgoing wallet's funds live, why they remain reachable, and how to restore it. */\nfunction replacedNote(replaced: ArchivedWalletInfo, activeWalletPath: string): string[] {\n const passphraseLine =\n replaced.passphraseLocation === 'store'\n ? `its passphrase is preserved in the OS credential store (service tenjin-cli, account ${replaced.account}).`\n : replaced.passphraseLocation === 'env'\n ? 'its passphrase is TENJIN_WALLET_PASSPHRASE — keep that value.'\n : replaced.unarchivedReason === 'rejected-characters'\n ? 'its passphrase was NOT archived: the macOS keychain writer only stores machine-generated (base64url) passphrases, and this typed one contains other characters. Keep it yourself, or set TENJIN_WALLET_PASSPHRASE to it.'\n : replaced.unarchivedReason === 'no-store'\n ? 'its passphrase was NOT archived: this platform has no OS credential store. It exists only where you keep it.'\n : 'its passphrase was NOT archived: the OS credential store write failed. It exists only where you keep it.';\n return [\n `Previous wallet archived: ${replaced.address} still holds any funds sent to it.`,\n `Its keystore was moved to ${replaced.archivedPath}; ${passphraseLine}`,\n `To make it the active wallet again later: move the current ${activeWalletPath} aside first, then \\`mv ${replaced.archivedPath} ${activeWalletPath}\\`.`,\n ];\n}\n\n/**\n * Run the whole create critical section under a cross-process file lock: the\n * existence pre-check, the passphrase generate-and-store, and the no-clobber\n * write. Without the lock these interleave across two concurrent creates — each\n * generates a distinct passphrase and persists it to the OS store BEFORE the\n * exclusive file write, so a different process could win the file while this\n * one's per-address entry names a wallet that never landed. Serializing means\n * the loser blocks until the winner commits, then trips the exists check and\n * exits WALLET_EXISTS having never generated or stored a passphrase. The\n * store-before-write ordering stays (it still guards the single-process crash\n * window), and the exclusive write stays the final authority.\n *\n * The passphrase is resolved inside the prepare step's address callback so the\n * OS-store entry is keyed to the new wallet's own address (issue #32).\n *\n * `--replace` ordering closes the no-active-wallet window: verify-and-preserve\n * the outgoing wallet (no file moves), fully PREPARE the replacement (key,\n * stored passphrase, encrypted keystore — every fallible step) while the old\n * wallet is still active, and only then park the old keystore and commit the\n * new one. A commit failure rolls the park back, so at every exit either the\n * old or the new wallet is the active one.\n */\nasync function createWalletLocked(\n dir: string,\n opts: WalletCreateOptions,\n): Promise<{\n address: string;\n walletPath: string;\n source: PassphraseSource;\n replaced?: ArchivedWalletInfo;\n}> {\n // Ensure the data dir exists so the lock's own mkdir has a parent on a fresh\n // install; the exclusive wallet write below re-ensures it at 0700 regardless.\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = join(dir, 'wallet.create.lock');\n try {\n return await withFileLock(lockPath, async () => {\n const env = opts.env ?? process.env;\n let source: PassphraseSource = 'env';\n const passphraseFor = async (forAddress: string): Promise<string> => {\n const resolved = await resolvePassphraseForCreate(\n { env, dir, ...opts.passphrase },\n forAddress,\n );\n source = resolved.source;\n return resolved.passphrase;\n };\n\n if (!(await walletFileExists(dir))) {\n const { address, walletPath: path } = await createLocalWallet(dir, passphraseFor);\n return { address, walletPath: path, source };\n }\n\n if (opts.replace !== true) throw walletExistsError(dir);\n const preserved = await verifyAndPreserveOutgoingWallet({\n dir,\n env,\n ...(opts.passphrase !== undefined ? { passphrase: opts.passphrase } : {}),\n });\n const prepared = await prepareLocalWallet(passphraseFor);\n const archivedPath = await parkOutgoingWallet(dir, preserved.account);\n try {\n const { address, walletPath: path } = await commitLocalWallet(dir, prepared);\n return { address, walletPath: path, source, replaced: { ...preserved, archivedPath } };\n } catch (err) {\n try {\n await restoreParkedWallet(dir, archivedPath);\n } catch (restoreErr) {\n // The no-clobber restore also refuses when a wallet.json appeared out\n // of band (commit EEXIST) — never overwrite it; name both files.\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed after the old wallet was parked, and restoring it also failed.',\n {\n fix: `Your old wallet ${preserved.address} is intact at ${archivedPath} with its passphrase preserved. If a ${walletPath(dir)} now exists, another process wrote it — move it aside first. Then restore with \\`mv ${archivedPath} ${walletPath(dir)}\\`.`,\n cause: restoreErr,\n },\n );\n }\n // Old wallet restored as the active one; say so rather than surfacing a\n // raw fs error (or a WALLET_EXISTS whose fix suggests re-running --replace).\n throw new CliError(\n 'INTERNAL',\n 'Creating the replacement wallet failed; the previous wallet was restored and is the active wallet again.',\n {\n fix: 'Nothing was lost. Fix the underlying error, then retry `tenjin wallet create --replace`.',\n cause: err,\n },\n );\n }\n });\n } catch (err) {\n // A lock timeout is not the user's error; surface it as INTERNAL with the one\n // manual step (there is no auto-steal), keeping the JSON error contract. Every\n // other error — notably the loser's WALLET_EXISTS — propagates unchanged.\n if (err instanceof LockTimeoutError) {\n throw new CliError('INTERNAL', err.message, {\n fix: `If no other tenjin process is running, remove ${lockPath} and retry.`,\n cause: err,\n });\n }\n throw err;\n }\n}\n\n/** Where the encryption passphrase lives, and what the user must remember. */\nfunction passphraseNote(source: PassphraseSource, address: string): string {\n const account = address.toLowerCase();\n switch (source) {\n case 'keychain':\n return `Passphrase saved to your macOS keychain (service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'dpapi':\n return `Passphrase saved to a DPAPI-encrypted per-wallet file (passphrase.${account}.dpapi), readable only by you on this Windows machine; signing will be transparent here.`;\n case 'secret-service':\n return `Passphrase saved to your Linux keyring (Secret Service, service tenjin-cli, account ${account}); signing will be transparent on this machine.`;\n case 'env':\n return 'Encrypted with TENJIN_WALLET_PASSPHRASE; keep that value to sign.';\n case 'prompt':\n return 'Remember your passphrase: it is required to sign and cannot be recovered.';\n }\n}\n\nexport interface WalletShowOptions extends ResolveWalletProviderOptions {\n /** `--no-qr`: print the address without the QR block at a TTY. */\n qr?: boolean;\n}\n\nexport async function runWalletShow(\n ctx: CommandContext,\n opts: WalletShowOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n // Diagnostics are the provider's own: a remote provider reports no local file\n // path or perms warning, so `show` never contaminates a remote wallet's output\n // with a stale local wallet.json's state. keyStorage/passphraseSource are the\n // custody posture reported without decrypting or requiring a passphrase.\n const {\n walletPath: path,\n keyStorage,\n passphraseSource,\n archivedWallets,\n warnings,\n } = await provider.diagnostics();\n\n const humanLines = [\n `Address: ${desc.address}`,\n ...(opts.qr !== false && ctx.io.isTTY && !ctx.flags.json\n ? addressQrLines(desc.address, ctx.io.stdout)\n : []),\n `Key source: ${desc.credentialSource}`,\n ];\n if (keyStorage !== undefined) humanLines.push(`Key storage: ${keyStorage}`);\n if (passphraseSource !== undefined) humanLines.push(`Passphrase: ${passphraseSource}`);\n if (archivedWallets !== undefined && archivedWallets.length > 0) {\n // A recovery hint, not a wallet switcher: exactly one wallet is ever active.\n humanLines.push(\n `Archived (replaced) wallets, funds recoverable via their preserved passphrases: ${archivedWallets.join(', ')}`,\n );\n }\n humanLines.push(...warnings);\n\n return {\n data: {\n address: desc.address,\n provider: desc.provider,\n credentialSource: desc.credentialSource,\n policyEnforcement: desc.policyEnforcement,\n ...(path !== undefined ? { walletPath: path } : {}),\n ...(keyStorage !== undefined ? { keyStorage } : {}),\n ...(passphraseSource !== undefined ? { passphraseSource } : {}),\n ...(archivedWallets !== undefined && archivedWallets.length > 0 ? { archivedWallets } : {}),\n warnings,\n },\n humanLines,\n };\n}\n\nexport async function runWalletBalance(\n ctx: CommandContext,\n opts: ResolveWalletProviderOptions = {},\n): Promise<CommandResult> {\n const provider = resolveWalletProvider(ctx, opts);\n const desc = await describeWallet(provider);\n\n const config = await loadRawConfig(ctx.dataDir);\n const rpcUrl = resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n }).rpcUrl.value;\n\n let atomic: bigint;\n try {\n atomic = await getUsdcBalance(desc.address, rpcUrl);\n } catch (err) {\n throw new CliError('RPC_ERROR', `Could not read the USDC balance from ${rpcUrl}.`, {\n fix: 'Check your network, or set a working RPC with `tenjin config set rpcUrl <url>`.',\n cause: err,\n });\n }\n\n const balance = toMoney(atomic.toString());\n return {\n data: { address: desc.address, balance },\n humanLines: [`Balance: ${balance.usd} USDC on Base`],\n };\n}\n\nfunction custodyWarnings(): string[] {\n const warnings: string[] = [];\n if (hasEnvKey()) {\n warnings.push('TENJIN_WALLET_KEY is set and shadows this file at runtime.');\n }\n if (isWindows) {\n warnings.push('File permissions are not enforced on Windows; the key file is not restricted.');\n }\n return warnings;\n}\n\nfunction hasEnvKey(): boolean {\n const envKey = process.env.TENJIN_WALLET_KEY;\n return envKey !== undefined && envKey.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;A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,SAAO;AAAA,IACL,MAAM,EAAE,SAAS,KAAK,SAAS,QAAQ;AAAA,IACvC,YAAY,CAAC,YAAY,QAAQ,GAAG,eAAe;AAAA,EACrD;AACF;AAEA,SAAS,kBAA4B;AACnC,QAAM,WAAqB,CAAC;AAC5B,MAAI,UAAU,GAAG;AACf,aAAS,KAAK,4DAA4D;AAAA,EAC5E;AACA,MAAI,WAAW;AACb,aAAS,KAAK,+EAA+E;AAAA,EAC/F;AACA,SAAO;AACT;AAEA,SAAS,YAAqB;AAC5B,QAAM,SAAS,QAAQ,IAAI;AAC3B,SAAO,WAAW,UAAa,OAAO,SAAS;AACjD;","names":[]}
|
|
@@ -3,6 +3,9 @@ import {
|
|
|
3
3
|
MCP_SERVER_NAME,
|
|
4
4
|
REQUEST_TOOL
|
|
5
5
|
} from "./chunk-TGLKKLQG.js";
|
|
6
|
+
import {
|
|
7
|
+
writeFileAtomic
|
|
8
|
+
} from "./chunk-JLEF5WHM.js";
|
|
6
9
|
|
|
7
10
|
// src/router/agent-tools.ts
|
|
8
11
|
import { readdir, readFile } from "node:fs/promises";
|
|
@@ -164,8 +167,56 @@ function unquote(value) {
|
|
|
164
167
|
return quoted === null ? value : quoted[2];
|
|
165
168
|
}
|
|
166
169
|
|
|
170
|
+
// src/router/router-memo.ts
|
|
171
|
+
import { createHash } from "node:crypto";
|
|
172
|
+
import { readFile as readFile2, rm } from "node:fs/promises";
|
|
173
|
+
import { join as join2 } from "node:path";
|
|
174
|
+
var UNREACHABLE_BACKOFF_MS = 6e4;
|
|
175
|
+
function memoPath(dataDir, kind, baseUrl) {
|
|
176
|
+
const origin = new URL(baseUrl).origin;
|
|
177
|
+
const key = createHash("sha256").update(origin).digest("hex").slice(0, 16);
|
|
178
|
+
return join2(dataDir, "router-memo", `${kind}-${key}.json`);
|
|
179
|
+
}
|
|
180
|
+
async function readRouterMemo(dataDir, kind, baseUrl, now) {
|
|
181
|
+
try {
|
|
182
|
+
const raw = JSON.parse(await readFile2(memoPath(dataDir, kind, baseUrl), "utf8"));
|
|
183
|
+
if (raw === null || typeof raw !== "object") return null;
|
|
184
|
+
const { at, until, detail } = raw;
|
|
185
|
+
if (typeof at !== "number" || typeof until !== "number") return null;
|
|
186
|
+
if (at > now || until <= now) return null;
|
|
187
|
+
return { at, until, ...typeof detail === "string" ? { detail } : {} };
|
|
188
|
+
} catch {
|
|
189
|
+
return null;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async function writeRouterMemo(dataDir, kind, baseUrl, memo) {
|
|
193
|
+
const body = {
|
|
194
|
+
at: memo.now,
|
|
195
|
+
until: memo.now + memo.ttlMs,
|
|
196
|
+
...memo.detail !== void 0 ? { detail: memo.detail.slice(0, 300) } : {}
|
|
197
|
+
};
|
|
198
|
+
try {
|
|
199
|
+
await writeFileAtomic(memoPath(dataDir, kind, baseUrl), `${JSON.stringify(body)}
|
|
200
|
+
`, {
|
|
201
|
+
mode: 384,
|
|
202
|
+
dirMode: 448
|
|
203
|
+
});
|
|
204
|
+
} catch {
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
async function clearRouterMemo(dataDir, kind, baseUrl) {
|
|
208
|
+
try {
|
|
209
|
+
await rm(memoPath(dataDir, kind, baseUrl), { force: true });
|
|
210
|
+
} catch {
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
167
214
|
export {
|
|
168
215
|
requestToolAccess,
|
|
169
|
-
agentsWithoutRequestTool
|
|
216
|
+
agentsWithoutRequestTool,
|
|
217
|
+
UNREACHABLE_BACKOFF_MS,
|
|
218
|
+
readRouterMemo,
|
|
219
|
+
writeRouterMemo,
|
|
220
|
+
clearRouterMemo
|
|
170
221
|
};
|
|
171
|
-
//# sourceMappingURL=chunk-
|
|
222
|
+
//# sourceMappingURL=chunk-BOAI23CX.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/agent-tools.ts","../src/router/router-memo.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\n\n/**\n * CAN THIS SUBAGENT CALL `request` AT ALL? An offer to an agent whose definition\n * leaves the tool out is a line it cannot act on, and a router call spent to\n * write it. Claude Code defines a custom agent in a Markdown file whose\n * frontmatter may carry `tools:` (an allowlist) and `disallowedTools:`; this\n * reads that, and nothing else, and never writes to it.\n *\n * ONLY `allowed` IS ACTED ON. A subagent is redirected or offered a lookup\n * only when this KNOWS it can make the call: a definition whose tools cover\n * the request tool (or that has no `tools:` and so inherits everything), or a\n * built-in in {@link MCP_INHERITING_BUILTINS}. Every other built-in, and any\n * type with no definition this can find or read, is `unknown`, and `unknown`\n * gets no router call: `claude-code-guide` ships with Bash, Read, WebFetch and\n * WebSearch and no MCP tools, and denying its WebFetch would strand it exactly\n * as #377 reported.\n *\n * WHERE A DEFINITION LIVES, in the harness's own precedence: the project's\n * `.claude/agents` (from `cwd` up to the filesystem root, nearest first), then\n * `~/.claude/agents`, then an installed plugin's `agents/` for a `plugin:agent`\n * type. A file is found by its name first and by its frontmatter `name:`\n * second, because the type is the `name:` and the file name only usually\n * matches it.\n */\n\nexport type RequestToolAccess = 'allowed' | 'excluded' | 'unknown';\n\n/**\n * The built-in agent types that have no definition file and still inherit MCP\n * tools, so can call `mcp__x402__request`. From Claude Code's own Agent tool\n * listing (2.1.28x): `general-purpose` has every tool, and `Explore` and `Plan`\n * exclude only editing and agent tools, never MCP. Built-ins with a fixed tool\n * list, such as `claude-code-guide` (Bash, Read, WebFetch, WebSearch) and\n * `statusline-setup` (Read, Edit), are deliberately absent.\n */\nexport const MCP_INHERITING_BUILTINS: ReadonlySet<string> = new Set([\n 'general-purpose',\n 'Explore',\n 'Plan',\n]);\n\nexport interface AgentLookup {\n cwd?: string;\n homeDir: string;\n}\n\nconst MAX_AGENT_FILE_BYTES = 256 * 1024;\nconst TYPE_RE = /^[A-Za-z0-9_.:-]{1,200}$/;\n\nexport async function requestToolAccess(\n agentType: string | undefined,\n lookup: AgentLookup,\n): Promise<RequestToolAccess> {\n if (agentType === undefined || !TYPE_RE.test(agentType)) return 'unknown';\n try {\n const text = await findDefinition(agentType, lookup);\n if (text !== null) return accessOf(text);\n return MCP_INHERITING_BUILTINS.has(agentType) ? 'allowed' : 'unknown';\n } catch {\n return 'unknown';\n }\n}\n\n/** What one definition's frontmatter says about the request tool. */\nexport function accessOf(definition: string): RequestToolAccess {\n const frontmatter = frontmatterOf(definition);\n if (frontmatter === null) return 'unknown';\n const disallowed = listField(frontmatter, 'disallowedTools');\n if (disallowed !== undefined && disallowed.some(namesRequestTool)) return 'excluded';\n const tools = listField(frontmatter, 'tools');\n if (tools === undefined) return 'allowed';\n return tools.some(namesRequestTool) ? 'allowed' : 'excluded';\n}\n\n/**\n * Does one `tools:` or `disallowedTools:` entry cover the request tool? The\n * tool itself, the bare server, or any `*`-suffixed pattern the tool's name\n * starts with: `*`, `mcp__*`, `mcp__x402__*` and every prefix between.\n */\nfunction namesRequestTool(tool: string): boolean {\n if (tool === REQUEST_TOOL || tool === `mcp__${MCP_SERVER_NAME}`) return true;\n return tool.endsWith('*') && REQUEST_TOOL.startsWith(tool.slice(0, -1));\n}\n\n/**\n * Every custom agent this project and this user define whose tools leave the\n * request tool out, for `doctor` to name. Plugin agents are not listed: their\n * files are not the user's to edit.\n */\nexport async function agentsWithoutRequestTool(lookup: AgentLookup): Promise<string[]> {\n const found: string[] = [];\n const seen = new Set<string>();\n for (const directory of agentDirs(lookup)) {\n for (const { name, text } of await definitionsIn(directory)) {\n const type = nameOf(text) ?? name;\n if (seen.has(type)) continue;\n seen.add(type);\n if (accessOf(text) === 'excluded') found.push(type);\n }\n }\n return found.sort();\n}\n\nasync function findDefinition(agentType: string, lookup: AgentLookup): Promise<string | null> {\n for (const directory of agentDirs(lookup)) {\n const text = await definitionIn(directory, agentType);\n if (text !== null) return text;\n }\n const colon = agentType.indexOf(':');\n if (colon > 0) {\n const plugin = agentType.slice(0, colon);\n const agent = agentType.slice(colon + 1);\n for (const root of await pluginRoots(plugin, lookup.homeDir)) {\n const text = await definitionIn(join(root, 'agents'), agent);\n if (text !== null) return text;\n }\n }\n return null;\n}\n\nfunction agentDirs(lookup: AgentLookup): string[] {\n const dirs: string[] = [];\n if (lookup.cwd !== undefined && lookup.cwd.length > 0) {\n let current = resolve(lookup.cwd);\n for (;;) {\n dirs.push(join(current, '.claude', 'agents'));\n const parent = dirname(current);\n if (parent === current) break;\n current = parent;\n }\n }\n const user = join(resolve(lookup.homeDir), '.claude', 'agents');\n // The user's directory is also an ancestor of most projects; it counts once,\n // in its own place in the order.\n return [...dirs.filter((d) => d !== user), user];\n}\n\nasync function definitionIn(directory: string, agentType: string): Promise<string | null> {\n const direct = await readBounded(join(directory, `${agentType}.md`));\n if (direct !== null && (nameOf(direct) ?? agentType) === agentType) return direct;\n for (const { text } of await definitionsIn(directory)) {\n if (nameOf(text) === agentType) return text;\n }\n return null;\n}\n\nasync function definitionsIn(directory: string): Promise<{ name: string; text: string }[]> {\n let names: string[];\n try {\n names = (await readdir(directory)).filter((n) => n.endsWith('.md')).slice(0, 200);\n } catch {\n return [];\n }\n const out: { name: string; text: string }[] = [];\n for (const file of names) {\n const text = await readBounded(join(directory, file));\n if (text !== null) out.push({ name: file.slice(0, -3), text });\n }\n return out;\n}\n\n/** Install paths `installed_plugins.json` records for `<plugin>@<marketplace>`. */\nasync function pluginRoots(plugin: string, homeDir: string): Promise<string[]> {\n const raw = await readBounded(join(homeDir, '.claude', 'plugins', 'installed_plugins.json'));\n if (raw === null) return [];\n const parsed = JSON.parse(raw) as { plugins?: Record<string, unknown> };\n const roots: string[] = [];\n for (const [key, entries] of Object.entries(parsed.plugins ?? {})) {\n if (key.split('@')[0] !== plugin || !Array.isArray(entries)) continue;\n for (const entry of entries) {\n const path = (entry as { installPath?: unknown }).installPath;\n if (typeof path === 'string' && path.length > 0) roots.push(path);\n }\n }\n return roots;\n}\n\nasync function readBounded(path: string): Promise<string | null> {\n try {\n const text = await readFile(path, 'utf8');\n return text.length > MAX_AGENT_FILE_BYTES ? null : text;\n } catch {\n return null;\n }\n}\n\nfunction frontmatterOf(text: string): string[] | null {\n const lines = text.replace(/^\\uFEFF/, '').split(/\\r?\\n/);\n const open = lines.findIndex((l) => l.trim().length > 0);\n if (open === -1 || lines[open]?.trim() !== '---') return null;\n const end = lines.findIndex((l, i) => i > open && l.trim() === '---');\n return end === -1 ? null : lines.slice(open + 1, end);\n}\n\nfunction nameOf(text: string): string | null {\n const frontmatter = frontmatterOf(text);\n if (frontmatter === null) return null;\n const line = frontmatter.find((l) => /^name\\s*:/.test(l));\n const value = line === undefined ? '' : unquote(line.slice(line.indexOf(':') + 1).trim());\n return value.length > 0 ? value : null;\n}\n\n/**\n * A top-level list field in the three spellings agent files use: `a, b, c`,\n * `[a, b]`, or a block of `- a` lines. `undefined` when the key is absent.\n */\nfunction listField(frontmatter: string[], key: string): string[] | undefined {\n const index = frontmatter.findIndex((l) => new RegExp(`^${key}\\\\s*:`).test(l));\n if (index === -1) return undefined;\n const line = frontmatter[index]!;\n const inline = line.slice(line.indexOf(':') + 1).trim();\n if (inline.length > 0) {\n const body = inline.startsWith('[') && inline.endsWith(']') ? inline.slice(1, -1) : inline;\n return body\n .split(',')\n .map((part) => unquote(part.trim()))\n .filter((part) => part.length > 0);\n }\n const items: string[] = [];\n for (const next of frontmatter.slice(index + 1)) {\n const item = /^\\s+-\\s*(.*)$/.exec(next);\n if (item === null) {\n if (next.trim().length === 0) continue;\n break;\n }\n const value = unquote(item[1]!.trim());\n if (value.length > 0) items.push(value);\n }\n return items;\n}\n\nfunction unquote(value: string): string {\n const quoted = /^(['\"])(.*)\\1$/.exec(value);\n return quoted === null ? value : quoted[2]!;\n}\n","import { createHash } from 'node:crypto';\nimport { readFile, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { writeFileAtomic } from '../lib/atomic-json';\n\n/**\n * ONE MEMO FOR \"DO NOT ASK THE ROUTER YET\", per machine and per router origin,\n * in the data dir, so every hook leg and every `tenjin mcp` process reads the\n * same answer. Two facts use it:\n *\n * - `unreachable`: a routing leg's call could not reach the router (DNS, TLS,\n * a refused connection, a proxy refusing the tunnel; see `isUnreachable`). For\n * {@link UNREACHABLE_BACKOFF_MS} every leg skips the router and the native\n * tool runs at once, instead of each prompt and search waiting out the gate.\n * Doctor's probe ends it early when it reaches the router.\n * - `paid-path-absent`: the router answered no paid path (the fee is off), so\n * calls take the free path without asking for an hour, or until the free\n * path answers `fee_required`.\n *\n * A memo is a file written atomically and read with the clock: one older than\n * its window, or dated in the future, reads as absent, so nothing cleans up\n * after it. An unreadable file reads as absent too: the cost of a lost memo is\n * one more call to the router.\n */\nexport type RouterMemoKind = 'unreachable' | 'paid-path-absent';\n\nexport interface RouterMemo {\n /** When it was written, in epoch ms. */\n at: number;\n /** When it ends, in epoch ms. */\n until: number;\n /** What happened, for doctor. */\n detail?: string;\n}\n\n/** How long routing legs skip a router that did not answer. */\nexport const UNREACHABLE_BACKOFF_MS = 60_000;\n\nfunction memoPath(dataDir: string, kind: RouterMemoKind, baseUrl: string): string {\n const origin = new URL(baseUrl).origin;\n const key = createHash('sha256').update(origin).digest('hex').slice(0, 16);\n return join(dataDir, 'router-memo', `${kind}-${key}.json`);\n}\n\n/** The memo in force at `now`, or null. Never throws. */\nexport async function readRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n now: number,\n): Promise<RouterMemo | null> {\n try {\n const raw = JSON.parse(await readFile(memoPath(dataDir, kind, baseUrl), 'utf8')) as unknown;\n if (raw === null || typeof raw !== 'object') return null;\n const { at, until, detail } = raw as Record<string, unknown>;\n if (typeof at !== 'number' || typeof until !== 'number') return null;\n if (at > now || until <= now) return null;\n return { at, until, ...(typeof detail === 'string' ? { detail } : {}) };\n } catch {\n return null;\n }\n}\n\n/** Starts a memo of `ttlMs` from `now`. Never throws. */\nexport async function writeRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n memo: { now: number; ttlMs: number; detail?: string },\n): Promise<void> {\n const body: RouterMemo = {\n at: memo.now,\n until: memo.now + memo.ttlMs,\n ...(memo.detail !== undefined ? { detail: memo.detail.slice(0, 300) } : {}),\n };\n try {\n await writeFileAtomic(memoPath(dataDir, kind, baseUrl), `${JSON.stringify(body)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n } catch {\n // Best effort: a memo that did not land costs one more call.\n }\n}\n\n/** Ends a memo before its window does. Never throws. */\nexport async function clearRouterMemo(\n dataDir: string,\n kind: RouterMemoKind,\n baseUrl: string,\n): Promise<void> {\n try {\n await rm(memoPath(dataDir, kind, baseUrl), { force: true });\n } catch {\n // Best effort: the window ends it anyway.\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAClC,SAAS,SAAS,MAAM,eAAe;AAqChC,IAAM,0BAA+C,oBAAI,IAAI;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAOD,IAAM,uBAAuB,MAAM;AACnC,IAAM,UAAU;AAEhB,eAAsB,kBACpB,WACA,QAC4B;AAC5B,MAAI,cAAc,UAAa,CAAC,QAAQ,KAAK,SAAS,EAAG,QAAO;AAChE,MAAI;AACF,UAAM,OAAO,MAAM,eAAe,WAAW,MAAM;AACnD,QAAI,SAAS,KAAM,QAAO,SAAS,IAAI;AACvC,WAAO,wBAAwB,IAAI,SAAS,IAAI,YAAY;AAAA,EAC9D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,SAAS,YAAuC;AAC9D,QAAM,cAAc,cAAc,UAAU;AAC5C,MAAI,gBAAgB,KAAM,QAAO;AACjC,QAAM,aAAa,UAAU,aAAa,iBAAiB;AAC3D,MAAI,eAAe,UAAa,WAAW,KAAK,gBAAgB,EAAG,QAAO;AAC1E,QAAM,QAAQ,UAAU,aAAa,OAAO;AAC5C,MAAI,UAAU,OAAW,QAAO;AAChC,SAAO,MAAM,KAAK,gBAAgB,IA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,SACA,MACA,SACA,KAC4B;AAC5B,MAAI;AACF,UAAM,MAAM,KAAK,MAAM,MAAMC,UAAS,SAAS,SAAS,MAAM,OAAO,GAAG,MAAM,CAAC;AAC/E,QAAI,QAAQ,QAAQ,OAAO,QAAQ,SAAU,QAAO;AACpD,UAAM,EAAE,IAAI,OAAO,OAAO,IAAI;AAC9B,QAAI,OAAO,OAAO,YAAY,OAAO,UAAU,SAAU,QAAO;AAChE,QAAI,KAAK,OAAO,SAAS,IAAK,QAAO;AACrC,WAAO,EAAE,IAAI,OAAO,GAAI,OAAO,WAAW,WAAW,EAAE,OAAO,IAAI,CAAC,EAAG;AAAA,EACxE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGA,eAAsB,gBACpB,SACA,MACA,SACA,MACe;AACf,QAAM,OAAmB;AAAA,IACvB,IAAI,KAAK;AAAA,IACT,OAAO,KAAK,MAAM,KAAK;AAAA,IACvB,GAAI,KAAK,WAAW,SAAY,EAAE,QAAQ,KAAK,OAAO,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC;AAAA,EAC3E;AACA,MAAI;AACF,UAAM,gBAAgB,SAAS,SAAS,MAAM,OAAO,GAAG,GAAG,KAAK,UAAU,IAAI,CAAC;AAAA,GAAM;AAAA,MACnF,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH,QAAQ;AAAA,EAER;AACF;AAGA,eAAsB,gBACpB,SACA,MACA,SACe;AACf,MAAI;AACF,UAAM,GAAG,SAAS,SAAS,MAAM,OAAO,GAAG,EAAE,OAAO,KAAK,CAAC;AAAA,EAC5D,QAAQ;AAAA,EAER;AACF;","names":["readFile","join","join","readFile"]}
|
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
HOOK_TOOL
|
|
4
|
+
} from "./chunk-AKWGE6JQ.js";
|
|
5
|
+
import {
|
|
6
|
+
MCP_SERVER_NAME
|
|
7
|
+
} from "./chunk-TGLKKLQG.js";
|
|
2
8
|
import {
|
|
3
9
|
package_default
|
|
4
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-GHR4BTNJ.js";
|
|
5
11
|
import {
|
|
6
12
|
CliError,
|
|
7
13
|
HARNESSES,
|
|
@@ -818,7 +824,7 @@ async function inspectFreeVerbRules(homeDir, mode = "review") {
|
|
|
818
824
|
async function inspectAllowlist(homeDir, mode) {
|
|
819
825
|
return inspectAllowlistAt(claudeSettingsPath(homeDir), rulesForPublishMode(mode));
|
|
820
826
|
}
|
|
821
|
-
async function inspectAllowlistAt(declaredPath, rules) {
|
|
827
|
+
async function inspectAllowlistAt(declaredPath, rules, list = "allow") {
|
|
822
828
|
const refuse = (p, reason, warning) => ({ result: skip("claude", p, reason, warning) });
|
|
823
829
|
const entry = await lstat(declaredPath).catch(() => null);
|
|
824
830
|
let path = declaredPath;
|
|
@@ -873,12 +879,12 @@ async function inspectAllowlistAt(declaredPath, rules) {
|
|
|
873
879
|
);
|
|
874
880
|
}
|
|
875
881
|
const permissions = permissionsValue ?? {};
|
|
876
|
-
const allowValue = permissions
|
|
882
|
+
const allowValue = permissions[list];
|
|
877
883
|
if (allowValue !== void 0 && !Array.isArray(allowValue)) {
|
|
878
884
|
return refuse(
|
|
879
885
|
path,
|
|
880
886
|
"unexpected-shape",
|
|
881
|
-
`${path} has a "permissions
|
|
887
|
+
`${path} has a "permissions.${list}" key that is not an array; it was left exactly as it is.`
|
|
882
888
|
);
|
|
883
889
|
}
|
|
884
890
|
const allow = allowValue ?? [];
|
|
@@ -887,8 +893,8 @@ async function inspectAllowlistAt(declaredPath, rules) {
|
|
|
887
893
|
const alreadyPresent = rules.filter((rule) => present.has(rule));
|
|
888
894
|
return { path, raw, settings, permissions, allow, added, alreadyPresent: [...alreadyPresent] };
|
|
889
895
|
}
|
|
890
|
-
async function appendAllowlistRules(declaredPath, rules) {
|
|
891
|
-
const found = await inspectAllowlistAt(declaredPath, rules);
|
|
896
|
+
async function appendAllowlistRules(declaredPath, rules, list = "allow") {
|
|
897
|
+
const found = await inspectAllowlistAt(declaredPath, rules, list);
|
|
892
898
|
if ("result" in found) {
|
|
893
899
|
const result = found.result;
|
|
894
900
|
return {
|
|
@@ -901,7 +907,7 @@ async function appendAllowlistRules(declaredPath, rules) {
|
|
|
901
907
|
}
|
|
902
908
|
const { path, raw, settings, permissions, allow, added, alreadyPresent } = found;
|
|
903
909
|
if (added.length === 0) return { path, added: [], alreadyPresent };
|
|
904
|
-
const next = { ...settings, permissions: { ...permissions,
|
|
910
|
+
const next = { ...settings, permissions: { ...permissions, [list]: [...allow, ...added] } };
|
|
905
911
|
const current = await readFile(path, "utf8").catch(() => null);
|
|
906
912
|
if (current !== raw) {
|
|
907
913
|
return {
|
|
@@ -1405,7 +1411,7 @@ function skip2(reason, args) {
|
|
|
1405
1411
|
return {
|
|
1406
1412
|
harness: args.harness,
|
|
1407
1413
|
...args.path !== void 0 ? { path: args.path } : {},
|
|
1408
|
-
hooksDir: args.hooksDir,
|
|
1414
|
+
...args.hooksDir !== void 0 ? { hooksDir: args.hooksDir } : {},
|
|
1409
1415
|
entries: 0,
|
|
1410
1416
|
wrote: false,
|
|
1411
1417
|
skipped: reason,
|
|
@@ -1433,6 +1439,9 @@ function isPlainObject2(value) {
|
|
|
1433
1439
|
}
|
|
1434
1440
|
function ownsHandler(handler, dataDir2) {
|
|
1435
1441
|
if (!isPlainObject2(handler)) return false;
|
|
1442
|
+
if (handler.type === "mcp_tool") {
|
|
1443
|
+
return handler.server === MCP_SERVER_NAME && handler.tool === HOOK_TOOL;
|
|
1444
|
+
}
|
|
1436
1445
|
const url = handler.url;
|
|
1437
1446
|
if (typeof url === "string" && LOOP_URL_RE.test(url)) return true;
|
|
1438
1447
|
const command = handler.command;
|
|
@@ -1593,8 +1602,7 @@ async function writeHooks(opts) {
|
|
|
1593
1602
|
const declaredPath = opts.settingsPath ?? adapter.registrar.configPath(homeDir, env);
|
|
1594
1603
|
const steps = adapter.registrar.activation?.(declaredPath);
|
|
1595
1604
|
const activation = steps !== void 0 ? { activation: steps } : {};
|
|
1596
|
-
if (opts.plan !== void 0)
|
|
1597
|
-
return writePlainEntries(opts, opts.plan, declaredPath, dir, activation);
|
|
1605
|
+
if (opts.plan !== void 0) return writePlainEntries(opts, opts.plan, declaredPath, activation);
|
|
1598
1606
|
let started;
|
|
1599
1607
|
try {
|
|
1600
1608
|
started = await (opts.start ?? startDaemon)(dataDir2, {
|
|
@@ -1699,14 +1707,13 @@ async function tightenFile(path) {
|
|
|
1699
1707
|
if (found === null || (found.mode & 63) === 0) return;
|
|
1700
1708
|
await chmod2(path, 384).catch(() => void 0);
|
|
1701
1709
|
}
|
|
1702
|
-
async function writePlainEntries(opts, plan, declaredPath,
|
|
1710
|
+
async function writePlainEntries(opts, plan, declaredPath, activation) {
|
|
1703
1711
|
const harness = opts.adapter.id;
|
|
1704
1712
|
const found = await inspectHooksFile(declaredPath);
|
|
1705
1713
|
if ("refusal" in found) {
|
|
1706
1714
|
return skip2(found.refusal.reason, {
|
|
1707
1715
|
harness,
|
|
1708
1716
|
path: found.refusal.path,
|
|
1709
|
-
hooksDir: dir,
|
|
1710
1717
|
warning: found.refusal.message,
|
|
1711
1718
|
fix: fixFor2(found.refusal.reason)
|
|
1712
1719
|
});
|
|
@@ -1722,7 +1729,6 @@ async function writePlainEntries(opts, plan, declaredPath, dir, activation) {
|
|
|
1722
1729
|
const result = {
|
|
1723
1730
|
harness,
|
|
1724
1731
|
path,
|
|
1725
|
-
hooksDir: dir,
|
|
1726
1732
|
entries: plan.length,
|
|
1727
1733
|
wrote: next !== raw,
|
|
1728
1734
|
...activation
|
|
@@ -1735,7 +1741,6 @@ async function writePlainEntries(opts, plan, declaredPath, dir, activation) {
|
|
|
1735
1741
|
return skip2("changed-since-read", {
|
|
1736
1742
|
harness,
|
|
1737
1743
|
path,
|
|
1738
|
-
hooksDir: dir,
|
|
1739
1744
|
warning: `${path} changed while it was being updated, so no hooks were registered. Re-run \`tenjin install\`.`,
|
|
1740
1745
|
fix: fixFor2("changed-since-read")
|
|
1741
1746
|
});
|
|
@@ -1746,7 +1751,6 @@ async function writePlainEntries(opts, plan, declaredPath, dir, activation) {
|
|
|
1746
1751
|
return skip2("unwritable", {
|
|
1747
1752
|
harness,
|
|
1748
1753
|
path,
|
|
1749
|
-
hooksDir: dir,
|
|
1750
1754
|
warning: `${path} could not be written (${err instanceof Error ? err.message : String(err)}); no hook entry was registered.`,
|
|
1751
1755
|
fix: fixFor2("unwritable")
|
|
1752
1756
|
});
|
|
@@ -1781,4 +1785,4 @@ export {
|
|
|
1781
1785
|
registeredHooks,
|
|
1782
1786
|
writeHooks
|
|
1783
1787
|
};
|
|
1784
|
-
//# sourceMappingURL=chunk-
|
|
1788
|
+
//# sourceMappingURL=chunk-DI7WHXOZ.js.map
|