tenjin-cli 0.1.0-alpha.20 → 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/README.md +17 -2
- package/dist/{chunk-3BS55ANY.js → chunk-2AQO4YDI.js} +50 -4
- package/dist/{chunk-3BS55ANY.js.map → chunk-2AQO4YDI.js.map} +1 -1
- package/dist/{chunk-HH3PDYIG.js → chunk-3EUTWC2B.js} +5 -5
- package/dist/{chunk-BTX2QE2Y.js → chunk-AQRUD5GQ.js} +2 -2
- package/dist/{chunk-CXUYCDPX.js → chunk-C363JZN2.js} +4 -4
- package/dist/{chunk-PO4HAXAW.js → chunk-ETW2ASBP.js} +52 -18
- package/dist/chunk-ETW2ASBP.js.map +1 -0
- package/dist/{chunk-RPR2C2JO.js → chunk-GHTPYKDT.js} +5 -5
- package/dist/{chunk-5KD5HRAJ.js → chunk-IOB7URFH.js} +3 -2
- package/dist/chunk-IOB7URFH.js.map +1 -0
- package/dist/{chunk-5FYKPQNX.js → chunk-IOIHYOU4.js} +3 -3
- package/dist/{chunk-LN2HISWU.js → chunk-JN7TMXVF.js} +2 -2
- package/dist/{chunk-TU7XH3JJ.js → chunk-K6AXXYCG.js} +14 -2
- package/dist/chunk-K6AXXYCG.js.map +1 -0
- package/dist/{chunk-2G2WLVHB.js → chunk-LAIZ2AQA.js} +9 -4
- package/dist/chunk-LAIZ2AQA.js.map +1 -0
- package/dist/{chunk-YREKMJPP.js → chunk-N4DJEQAF.js} +65 -6
- package/dist/chunk-N4DJEQAF.js.map +1 -0
- package/dist/{chunk-NSG5TVZQ.js → chunk-OSUD6YZZ.js} +14 -10
- package/dist/chunk-OSUD6YZZ.js.map +1 -0
- package/dist/{chunk-2E6GVIRP.js → chunk-OTPEH3AH.js} +47 -9
- package/dist/chunk-OTPEH3AH.js.map +1 -0
- package/dist/{chunk-LI44XLMB.js → chunk-PJEG2JIJ.js} +5 -5
- package/dist/{chunk-4M5FBWT5.js → chunk-QF4SSCQV.js} +10 -1
- 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-72UHZRG6.js → chunk-QRFONFRW.js} +2 -2
- package/dist/{chunk-P42QX3QF.js → chunk-RCJQARZF.js} +2 -2
- package/dist/{chunk-P42QX3QF.js.map → chunk-RCJQARZF.js.map} +1 -1
- package/dist/chunk-SRVDXR6B.js +337 -0
- package/dist/chunk-SRVDXR6B.js.map +1 -0
- package/dist/{chunk-7ACHDNJA.js → chunk-U2ATFMKZ.js} +13 -4
- package/dist/chunk-U2ATFMKZ.js.map +1 -0
- package/dist/{chunk-4AS52HUG.js → chunk-UY2TOI3B.js} +70 -27
- package/dist/chunk-UY2TOI3B.js.map +1 -0
- package/dist/{chunk-CCDOV45D.js → chunk-W3LVZ2EN.js} +25 -8
- package/dist/{chunk-CCDOV45D.js.map → chunk-W3LVZ2EN.js.map} +1 -1
- package/dist/{chunk-YEBNE5NW.js → chunk-YVODPFTL.js} +5 -5
- package/dist/{cli-XJQYUOHI.js → cli-7KJ4QLUU.js} +42 -29
- package/dist/{cli-XJQYUOHI.js.map → cli-7KJ4QLUU.js.map} +1 -1
- package/dist/{config-KMJLFPSI.js → config-MSN6H4MD.js} +10 -8
- package/dist/{doctor-KMN55D7U.js → doctor-ITUCKN6C.js} +25 -16
- package/dist/{doctor-KMN55D7U.js.map → doctor-ITUCKN6C.js.map} +1 -1
- package/dist/{fund-LT6ZPGEQ.js → fund-XPB4IIG5.js} +11 -11
- package/dist/{hook-command-U5XPEHAJ.js → hook-command-VVV2Q23L.js} +293 -80
- package/dist/hook-command-VVV2Q23L.js.map +1 -0
- package/dist/index.js +4 -4
- package/dist/{install-MMNXJ5LM.js → install-OSJRM2ME.js} +13 -11
- package/dist/{install-identity-B7FVIWML.js → install-identity-YIWKQOUD.js} +7 -7
- package/dist/{install-wallet-XMVUBCHS.js → install-wallet-BWJO2SUC.js} +10 -10
- package/dist/{mcp-TUPRIPSI.js → mcp-KE5YKPS2.js} +203 -29
- package/dist/{mcp-TUPRIPSI.js.map → mcp-KE5YKPS2.js.map} +1 -1
- package/dist/{paths-LRMWNTJP.js → paths-MUXHUOCM.js} +8 -2
- package/dist/{pay-XAWW3NV3.js → pay-MUV2U232.js} +18 -16
- package/dist/payments-4D27K4L2.js +48 -0
- package/dist/payments-4D27K4L2.js.map +1 -0
- package/dist/{send-HESQYRKM.js → send-BXHFKDBF.js} +10 -10
- package/dist/{status-ANZPRZJJ.js → status-3Z3YPRSE.js} +6 -6
- package/dist/{status-line-J3TUWVRQ.js → status-line-CKRMGZ3Q.js} +7 -7
- package/dist/{status-line-wiring-HSV7DXO5.js → status-line-wiring-GECLIIBT.js} +5 -5
- package/dist/tenjin-daemon.mjs +57 -6
- package/dist/{uninstall-GUU34YKP.js → uninstall-BZTVWJ7W.js} +11 -11
- package/dist/{update-KO2NZRJ5.js → update-IQQTEOI5.js} +6 -6
- package/dist/{wallet-3URC5QPK.js → wallet-UFXQ57TZ.js} +10 -10
- package/docs/agent-permissions.md +4 -2
- package/docs/safety-model.md +2 -2
- package/package.json +1 -1
- package/dist/chunk-2E6GVIRP.js.map +0 -1
- package/dist/chunk-2G2WLVHB.js.map +0 -1
- package/dist/chunk-3KKKB2AQ.js +0 -40
- package/dist/chunk-3KKKB2AQ.js.map +0 -1
- package/dist/chunk-4AS52HUG.js.map +0 -1
- package/dist/chunk-4M5FBWT5.js.map +0 -1
- package/dist/chunk-5KD5HRAJ.js.map +0 -1
- package/dist/chunk-7ACHDNJA.js.map +0 -1
- package/dist/chunk-NSG5TVZQ.js.map +0 -1
- package/dist/chunk-PO4HAXAW.js.map +0 -1
- package/dist/chunk-TU7XH3JJ.js.map +0 -1
- package/dist/chunk-YREKMJPP.js.map +0 -1
- package/dist/hook-command-U5XPEHAJ.js.map +0 -1
- /package/dist/{chunk-HH3PDYIG.js.map → chunk-3EUTWC2B.js.map} +0 -0
- /package/dist/{chunk-BTX2QE2Y.js.map → chunk-AQRUD5GQ.js.map} +0 -0
- /package/dist/{chunk-CXUYCDPX.js.map → chunk-C363JZN2.js.map} +0 -0
- /package/dist/{chunk-RPR2C2JO.js.map → chunk-GHTPYKDT.js.map} +0 -0
- /package/dist/{chunk-5FYKPQNX.js.map → chunk-IOIHYOU4.js.map} +0 -0
- /package/dist/{chunk-LN2HISWU.js.map → chunk-JN7TMXVF.js.map} +0 -0
- /package/dist/{chunk-LI44XLMB.js.map → chunk-PJEG2JIJ.js.map} +0 -0
- /package/dist/{chunk-72UHZRG6.js.map → chunk-QRFONFRW.js.map} +0 -0
- /package/dist/{chunk-YEBNE5NW.js.map → chunk-YVODPFTL.js.map} +0 -0
- /package/dist/{config-KMJLFPSI.js.map → config-MSN6H4MD.js.map} +0 -0
- /package/dist/{fund-LT6ZPGEQ.js.map → fund-XPB4IIG5.js.map} +0 -0
- /package/dist/{install-MMNXJ5LM.js.map → install-OSJRM2ME.js.map} +0 -0
- /package/dist/{install-identity-B7FVIWML.js.map → install-identity-YIWKQOUD.js.map} +0 -0
- /package/dist/{install-wallet-XMVUBCHS.js.map → install-wallet-BWJO2SUC.js.map} +0 -0
- /package/dist/{paths-LRMWNTJP.js.map → paths-MUXHUOCM.js.map} +0 -0
- /package/dist/{pay-XAWW3NV3.js.map → pay-MUV2U232.js.map} +0 -0
- /package/dist/{send-HESQYRKM.js.map → send-BXHFKDBF.js.map} +0 -0
- /package/dist/{status-ANZPRZJJ.js.map → status-3Z3YPRSE.js.map} +0 -0
- /package/dist/{status-line-J3TUWVRQ.js.map → status-line-CKRMGZ3Q.js.map} +0 -0
- /package/dist/{status-line-wiring-HSV7DXO5.js.map → status-line-wiring-GECLIIBT.js.map} +0 -0
- /package/dist/{uninstall-GUU34YKP.js.map → uninstall-BZTVWJ7W.js.map} +0 -0
- /package/dist/{update-KO2NZRJ5.js.map → update-IQQTEOI5.js.map} +0 -0
- /package/dist/{wallet-3URC5QPK.js.map → wallet-UFXQ57TZ.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/router/install.ts","../src/lib/skill-placement.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { readFile, realpath } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { isAbsolute, join } from 'node:path';\nimport { promisify } from 'node:util';\nimport { claudeAdapter } from '../adapters/claude';\nimport { persistRouterDefaults } from '../commands/config';\nimport { CliError } from '../lib/errors';\nimport { appendAllowlistRules, claudeSettingsPath } from '../lib/harness-permissions';\nimport {\n inspectHooksFile,\n ownsHookEntry,\n pruneHooks,\n writeHooks,\n type HooksResult,\n} from '../lib/harness-hooks';\nimport { toMoney } from '../lib/money';\nimport { paint } from '../lib/output';\nimport { resolveContextSettings } from '../lib/settings';\nimport type { SpendPolicy } from '../lib/policy';\nimport { removeRetiredSkills } from '../lib/skill-placement';\nimport { loadRawConfig } from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { WalletDeps, WalletOutcome } from '../commands/install-wallet';\nimport type { CommandContext, CommandResult } from '../context';\nimport { MCP_SERVER_NAME, REQUEST_TOOL } from './names';\nimport { ensureStatusLine, type StatusLineMode, type StatusLineResult } from './status-line-wiring';\n\n/**\n * `tenjin install` for the router product: seven hook entries, one MCP server,\n * one permission rule, the spend defaults, and a wallet when there is none.\n *\n * WHAT IT WRITES IS WHAT IT SAYS. There is no skill to materialize and no\n * daemon to start: the hooks are plain command lines, the tool lives in an MCP\n * server the harness starts per session, and every other key in the settings\n * file is preserved byte for byte. The one process a hook starts is the free\n * docs fetch beside a search, which exits within `PREFETCH_TIMEOUT_MS`.\n */\n\nconst exec = promisify(execFile);\n\n/**\n * The harness's kill budget for each hook entry, and the number every other\n * wait inside the hook is cut from: 1 s of stdin plus 3.5 s of gate, with\n * 500 ms left for node's boot and the transcript read (`wire.test.ts` pins it).\n * Raised from 3 s because a gate abort costs the turn its hint silently.\n *\n * A machine carrying the old number is converged by the writer, not by the\n * user: the entries are ours by marker, so `install`, `install --refresh` and\n * the refresh `tenjin update` spawns all rewrite them in place.\n */\nexport const HOOK_TIMEOUT_SECONDS = 5;\n/**\n * The after-call entries' kill budget, longer than the rest for the one wait\n * any hook makes: a search the pre-call arm is fetching free docs for waits up\n * to `AUGMENT_WAIT_MS` for them, and when none came back and the search was\n * short, the gate is asked after that (`wire.test.ts` pins the sum). Every\n * other after-call event returns as fast as before, so the number is a\n * ceiling, not a cost. The pre-call entry stays at\n * {@link HOOK_TIMEOUT_SECONDS}: it starts that fetch and never waits for it.\n */\nexport const AFTER_CALL_TIMEOUT_SECONDS = 15;\nexport { MCP_SERVER_NAME };\nexport const ALLOW_RULE = REQUEST_TOOL;\n/**\n * The MCP registration follows the SAME SCOPE the hook entries do. A\n * `--project` install that wrote its hooks into the project and then registered\n * the server at user scope would reach into `~/.claude.json` on a run whose\n * whole point is to touch this project and nothing else, and `tenjin uninstall\n * --project` would leave that behind.\n *\n * Project scope writes `<project>/.mcp.json`, so the registration lives beside\n * the settings file that names the hooks and travels with the repository.\n */\nexport function mcpScope(project: boolean | undefined): 'user' | 'project' {\n return project === true ? 'project' : 'user';\n}\n\nexport function mcpAddCommand(project?: boolean): string {\n return `claude mcp add ${MCP_SERVER_NAME} -s ${mcpScope(project)} -- tenjin mcp`;\n}\n\nexport function mcpRemoveCommand(project?: boolean): string {\n return `claude mcp remove ${MCP_SERVER_NAME} -s ${mcpScope(project)}`;\n}\n\n/** The user-scope form, kept as the name the docs and the tests already use. */\nexport const MCP_ADD_COMMAND = mcpAddCommand();\n\n/**\n * Which settings file this machine's router wiring lives in, spelled once so\n * `install`, `uninstall` and `doctor` can never disagree about where to look.\n * A doctor reading the home file on a `--project` install reported a correctly\n * wired machine as unwired and exited 3.\n */\nexport function routerSettingsPath(\n opts: { project?: boolean; homeDir?: string; cwd?: string } = {},\n): string {\n if (opts.project === true) return join(opts.cwd ?? process.cwd(), '.claude', 'settings.json');\n return claudeSettingsPath(opts.homeDir ?? homedir());\n}\n\n/** The subagent tool, under its current name and its older one. */\nexport const DELEGATION_MATCHER = 'Agent|Task';\n\n/** The native tools both native arms watch. */\nexport const NATIVE_MATCHER = 'WebSearch|WebFetch';\n\n/** The host's question to the user, watched before it is asked and after. */\nexport const ASK_MATCHER = 'AskUserQuestion';\n\n/**\n * The seven entries, spelled once so `uninstall`, `doctor` and the tests read\n * the same list. The native tools are routed twice over one lookup: BEFORE the\n * call, as every release has, with a line pointing to a paid lookup when one\n * fits; and AFTER it, only when it came back short and nothing was said before,\n * or to add the free docs the pre-call arm fetched to a search's results. A\n * failed call fires PostToolUseFailure rather than PostToolUse, so the second\n * takes both. The host's question to the user is routed the same two ways:\n * before it is asked, when a service could stand in for what it asks for, and\n * after, with the user's answers read as their own words.\n */\nexport function routerHookPlan(): unknown[] {\n const handler = (command: string, timeout = HOOK_TIMEOUT_SECONDS) => [\n { type: 'command', command, timeout },\n ];\n const afterCall = () => handler('tenjin hook shortfall', AFTER_CALL_TIMEOUT_SECONDS);\n return [\n { event: 'UserPromptSubmit', hooks: handler('tenjin hook prompt') },\n { event: 'PreToolUse', matcher: NATIVE_MATCHER, hooks: handler('tenjin hook native') },\n { event: 'PreToolUse', matcher: DELEGATION_MATCHER, hooks: handler('tenjin hook agent') },\n { event: 'PostToolUse', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PostToolUseFailure', matcher: NATIVE_MATCHER, hooks: afterCall() },\n { event: 'PreToolUse', matcher: ASK_MATCHER, hooks: handler('tenjin hook ask') },\n { event: 'PostToolUse', matcher: ASK_MATCHER, hooks: handler('tenjin hook answer') },\n ];\n}\n\nexport const DISCLOSURE: readonly string[] = [\n \"What leaves this machine: the bounded text of each prompt, each native search query or URL (and, when one came back short, its status, size or error), each task handed to a subagent, and each question your assistant asks you with your answers, sent to Tenjin for the free routing gate, beside this session's id. When the gate offers free library docs for a search, that search query also goes to Tenjin's docs lookup, which asks Context7.\",\n 'What is kept when a lookup is paid: the capability chosen, a hash of the contract, a hash of the arguments, and your wallet address. No prompt text, no arguments, no hint text.',\n 'What never leaves: your private key. It is decrypted in this CLI to sign, and never sent anywhere.',\n];\n\nexport interface RouterInstallArgs {\n /** Write into this project's `.claude/settings.json` instead of your home one. */\n project?: boolean;\n /**\n * Bring the entries this machine ALREADY has up to the running build, and\n * add nothing: no config write, no MCP registration, and a refusal when\n * nothing of ours is here. `tenjin update` spawns exactly this after it swaps\n * the binary, so the flag's name and meaning are a compatibility contract.\n */\n refresh?: boolean;\n /**\n * What to do about Claude Code's `statusLine`. Absent is the default path:\n * write ours when the key is free, and print the composition line when it is\n * not. `compose` wraps the status line already there and appends ours;\n * `skip` leaves the key alone entirely.\n */\n statusLine?: StatusLineMode;\n /** Create no wallet, for CI and scripted machines. */\n noWallet?: boolean;\n}\n\nexport interface RouterInstallDeps extends WalletDeps {\n homeDir?: string;\n cwd?: string;\n env?: NodeJS.ProcessEnv;\n /** PATH probe for the `claude` binary. */\n which?: (bin: string) => boolean;\n /** Runs `claude mcp add`; tests inject it so no binary is spawned. The scope\n * and the working directory are passed, because project scope is decided by\n * where the command runs as much as by the flag. */\n registerMcp?: (\n command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n ) => Promise<void>;\n /** Reads the registration the scope's own file holds; tests inject it. */\n readMcpEntry?: (\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n ) => Promise<{ found: boolean; state: McpEntryState }>;\n}\n\nexport interface McpRegistration {\n name: string;\n registered: boolean;\n /** Which scope it went to, following the hook entries rather than the flag\n * being read twice. `project` writes `<project>/.mcp.json`. */\n scope: 'user' | 'project';\n /** The command to run by hand, when this run could not. */\n command: string;\n /**\n * WHAT THIS RUN ACTUALLY DID, which `registered` alone cannot say:\n * `already-registered` (the scope's file already launches `tenjin mcp`, and\n * nothing was spawned), `added`, `repaired` (a same-name entry launching\n * something else was removed and re-added, which only `uninstall` does now),\n * `unrepaired` (a registration this run KNOWS is wrong or unreadable and will\n * not touch) or `unavailable` (it is simply not there and this machine could\n * not add it, e.g. no `claude` on PATH). A refresh fails on `unrepaired`,\n * because reporting convergence over a registration that launches something\n * else is the thing to avoid; it still only prints the manual command for\n * `unavailable`.\n */\n reconciled: 'already-registered' | 'added' | 'repaired' | 'unrepaired' | 'unavailable';\n reason?: string;\n}\n\nasync function inferRefreshProject(\n cwd: string,\n home: string,\n dataDir: string,\n readRegistration: typeof readMcpEntry,\n): Promise<boolean> {\n const hooks = await probeOurEntries(routerSettingsPath({ project: true, cwd }), dataDir);\n if (hooks.state !== 'present') return false;\n const [cwdPath, homePath] = await Promise.all([\n realpath(cwd),\n realpath(home).catch((err: NodeJS.ErrnoException) => {\n // A missing home cannot alias this existing project. Do not require it\n // to exist (or create it) just to refresh the project's own settings.\n if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;\n throw err;\n }),\n ]);\n if (cwdPath !== homePath) return true;\n\n // Home shares one hooks file between scopes. Preserve a project-only install,\n // but prefer user scope when both registrations exist (including alpha.18's\n // accidental duplicate). With neither registration, the default is user.\n // Unreadable/conflicting entries stay in their scope so reconciliation refuses\n // them instead of silently creating a registration in the other scope.\n const user = await readRegistration('user', cwd, home);\n if (user.state !== 'absent') return false;\n const project = await readRegistration('project', cwd, home);\n return project.state !== 'absent';\n}\n\nexport async function runRouterInstall(\n args: RouterInstallArgs,\n ctx: CommandContext,\n deps: RouterInstallDeps = {},\n): Promise<CommandResult> {\n const env = deps.env ?? process.env;\n const home = deps.homeDir ?? homedir();\n if (!isAbsolute(home)) {\n throw new CliError('INTERNAL', 'The home directory is not an absolute path.', {\n fix: 'Set HOME to your home directory (`export HOME=...`), then re-run `tenjin install`.',\n });\n }\n await loadRawConfig(ctx.dataDir); // Validate before any install writes; retired keys remain readable.\n const cwd = deps.cwd ?? process.cwd();\n // `tenjin update` runs from home, where the hooks file cannot prove scope.\n // An explicit --project still wins, including for a project rooted at home.\n const project =\n args.project ??\n (args.refresh === true &&\n (await inferRefreshProject(cwd, home, ctx.dataDir, deps.readMcpEntry ?? readMcpEntry)));\n const settingsPath = routerSettingsPath({\n ...(project ? { project: true } : {}),\n homeDir: home,\n cwd,\n });\n\n if (args.refresh === true) {\n const probe = await probeOurEntries(settingsPath, ctx.dataDir);\n // An unreadable file is not an absence, and telling someone to install over\n // it is the wrong instruction: the writer would refuse it too.\n if (probe.state === 'unreadable') {\n throw new CliError('CONFIG_INVALID', `Could not inspect ${settingsPath}: ${probe.reason}`, {\n fix: `Fix ${settingsPath}, then re-run: tenjin update`,\n });\n }\n if (probe.state === 'absent') {\n throw new CliError(\n 'REFUSED',\n `Nothing to refresh in ${settingsPath}: no Tenjin hook entries are registered here.`,\n { fix: 'Run `tenjin install` to set this machine up.' },\n );\n }\n }\n const spend = await persistRouterDefaults(ctx.dataDir, args.refresh === true);\n const removedKeysLines =\n spend.removed.length > 0\n ? [\n `Removed retired settings: ${spend.removed.join(', ')}. Automatic router limits remain in effect; manual pay always requires consent.`,\n ]\n : [];\n const removedSkills = await removeRetiredSkills(home, project ? cwd : undefined);\n const hooks = await writeHooks({\n adapter: claudeAdapter,\n homeDir: home,\n dataDir: ctx.dataDir,\n env,\n plan: routerHookPlan(),\n settingsPath,\n });\n const permissions = await ensureAllowRule(settingsPath);\n const statusLine = await ensureStatusLine(settingsPath, {\n ...(args.statusLine !== undefined ? { mode: args.statusLine } : {}),\n ...(args.refresh === true ? { refreshOnly: true } : {}),\n });\n const mcp = await registerMcpServer(deps, env, project, cwd, home);\n if (args.refresh === true) {\n // The SAME writers, minus the one that decides anything: the entries are\n // rewritten in place by their ownership marker so an upgrade never\n // duplicates them, the rule and the registration are re-checked because a\n // new version can change either. Config cleanup only removes retired keys;\n // the wallet, current limits and `spend.json` are unchanged. Widening an agent's spend policy\n // during an unattended upgrade is not a convergence.\n // RECONCILED, not re-added: `claude mcp add` exits 1 on an existing entry,\n // so the registration is read first and only written when it is missing or\n // wrong (see {@link registerMcpServer}).\n // A registration this run KNOWS is wrong and could not repair is not a\n // converged install, and `tenjin update` reporting success over it is how\n // a machine keeps a stale `x402` server across upgrade after upgrade.\n if (mcp.reconciled === 'unrepaired') {\n throw new CliError(\n 'REFUSED',\n `The ${MCP_SERVER_NAME} MCP registration (${mcpScope(project)} scope) is not the router's and this run could not repair it: ${mcp.reason ?? 'unknown reason'}.`,\n { fix: `Run: ${mcp.command}`, details: { settingsPath, hooks, permissions, mcp } },\n );\n }\n return {\n data: {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n mcp,\n refresh: true,\n spend,\n removedSkills,\n scope: mcpScope(project),\n },\n humanLines: [\n ...refreshLines(ctx, problems(ctx, hooks, permissions, statusLine, mcp)),\n ...removedKeysLines,\n ],\n };\n }\n // The shelf install's wallet step, unchanged except that it never asks: a\n // lookup cannot be paid without a wallet, so install makes one. A failure is\n // reported, never fatal; everything above is useful without it.\n const { resolveWallet } = await import('../commands/install-wallet');\n const wallet = await resolveWallet(ctx, deps, args.noWallet === true ? 'flag' : undefined, false);\n // Read back AFTER the write: a machine that already carried its own caps\n // keeps them, and a readout quoting the defaults would describe limits this\n // run did not set.\n const effective = await resolveContextSettings(ctx);\n\n const data = {\n settingsPath,\n hooks,\n permissions,\n statusLine,\n spend: { ...spend, effective: effectiveLimits(effective.policy) },\n mcp,\n wallet,\n disclosure: DISCLOSURE,\n removedSkills,\n };\n return {\n data,\n humanLines: [\n ...lines(ctx, {\n project,\n hooks,\n permissions,\n statusLine,\n mcp,\n wallet,\n policy: effective.policy,\n }),\n ...removedKeysLines,\n ],\n };\n}\n\nexport interface AllowRuleResult {\n path: string;\n rule: string;\n added: boolean;\n /** Set when the file could not be written; the rule is then not in force. */\n warning?: string;\n}\n\n/**\n * The one permission rule, through the shared allowlist writer rather than a\n * third hand-rolled one: it resolves a symlinked settings.json before the\n * rename, refuses a file it cannot parse, and compares the bytes it read before\n * committing, none of which a local copy of the merge would have.\n */\nasync function ensureAllowRule(path: string): Promise<AllowRuleResult> {\n const result = await appendAllowlistRules(path, [ALLOW_RULE]);\n return {\n path: result.path,\n rule: ALLOW_RULE,\n added: result.added.length > 0,\n ...(result.warning !== undefined\n ? { warning: result.warning }\n : result.skipped !== undefined\n ? { warning: `${result.path} was left untouched (${result.skipped}).` }\n : {}),\n };\n}\n\n/**\n * RECONCILE, do not re-add blindly. `claude mcp add` is not idempotent: Claude\n * Code 2.1.280 exits 1 on a second identical add with \"MCP server x402 already\n * exists in .mcp.json\". Running it unconditionally therefore reported a\n * perfectly healthy machine as an unregistered one and printed a repair command\n * that would fail the same way, while a same-name entry launching something\n * else never converged, because `add` refuses to overwrite it.\n *\n * So the scope's own file is read first: an entry that already launches\n * `tenjin mcp` is the goal state and nothing is spawned, and a file that cannot\n * be read is refused out loud rather than written over.\n *\n * AN `x402` ENTRY THAT LAUNCHES SOMETHING ELSE IS SOMEBODY ELSE'S. This command\n * will not delete it. It may be another tool of the user's that happens to\n * share the name, and an installer that removes a registration nobody asked it\n * to touch has destroyed configuration to make its own output look tidy. The\n * conflict is reported with the exact two commands to run, and the user decides.\n */\nasync function registerMcpServer(\n deps: RouterInstallDeps,\n env: NodeJS.ProcessEnv,\n project: boolean,\n cwd: string,\n home: string,\n): Promise<McpRegistration> {\n const scope = mcpScope(project);\n const command = mcpAddCommand(project);\n const base = { name: MCP_SERVER_NAME, scope, command };\n const existing = await (deps.readMcpEntry ?? readMcpEntry)(scope, cwd, home);\n if (existing.state === 'ok') {\n return { ...base, registered: true, reconciled: 'already-registered' };\n }\n if (existing.state === 'unreadable') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n reason: `the ${scope}-scope registration file could not be read, so nothing was written over it`,\n };\n }\n // REFUSED, NOT REPLACED. Nothing of the user's is removed to make room.\n if (existing.state === 'wrong-command') {\n return {\n ...base,\n registered: false,\n reconciled: 'unrepaired',\n command: `${mcpRemoveCommand(project)} && ${command}`,\n reason: `an MCP server named ${MCP_SERVER_NAME} is already registered at ${scope} scope and launches something else. This command will not remove a registration it did not write; run the two commands above if that entry is stale`,\n };\n }\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n if (!which('claude')) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: 'the `claude` binary is not on PATH',\n };\n }\n try {\n await (deps.registerMcp ?? runClaudeMcpAdd)(command, { scope, cwd });\n return { ...base, registered: true, reconciled: 'added' };\n } catch (err) {\n return {\n ...base,\n registered: false,\n reconciled: 'unavailable',\n reason: err instanceof Error ? err.message : String(err),\n };\n }\n}\n\nexport type McpEntryState = 'ok' | 'absent' | 'wrong-command' | 'unreadable';\n\n/**\n * What an entry named `x402` actually launches. The name proves nothing: a\n * stale entry pointing at another binary would read as a working request tool.\n */\nexport function classifyMcpEntry(entry: unknown): McpEntryState {\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return 'absent';\n const { command, args } = entry as { command?: unknown; args?: unknown };\n if (typeof command !== 'string' || command.length === 0) return 'wrong-command';\n // The basename, so `/opt/homebrew/bin/tenjin` and a bare `tenjin` both pass.\n const binary = command.split(/[\\\\/]/).pop();\n const runsRouter =\n binary === 'tenjin' && Array.isArray(args) && args.length === 1 && args[0] === 'mcp';\n return runsRouter ? 'ok' : 'wrong-command';\n}\n\n/**\n * The file each scope writes: the project's own `.mcp.json`, or the user's\n * `~/.claude.json`. Neither can inherit from the other. Shared by `install`,\n * which reconciles against it, and `doctor`, which reports it.\n */\nexport async function readMcpEntry(\n scope: 'user' | 'project',\n cwd: string,\n home: string,\n): Promise<{ found: boolean; state: McpEntryState }> {\n const path = scope === 'project' ? join(cwd, '.mcp.json') : join(home, '.claude.json');\n // ONLY \"it is not there\" is an absence. A permission or filesystem error on a\n // file that DOES exist says nothing about what is registered in it, and\n // treating it as missing sent the refresh on to `claude mcp add` over a\n // registration it had never read: a failed add then looked like a machine\n // that simply lacks the tooling, and `tenjin update` exited 0 over whatever\n // was actually in there.\n let raw: string;\n try {\n raw = await readFile(path, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT' || code === 'ENOTDIR') return { found: false, state: 'absent' };\n return { found: true, state: 'unreadable' };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // NOT an absence: the harness's own file is there and unreadable to this\n // build, so neither \"register it\" nor \"it is missing\" is a true statement.\n return { found: true, state: 'unreadable' };\n }\n const servers = (parsed as { mcpServers?: unknown } | null)?.mcpServers;\n if (servers === undefined) return { found: true, state: 'absent' };\n if (servers === null || typeof servers !== 'object' || Array.isArray(servers)) {\n return { found: true, state: 'unreadable' };\n }\n const entry = (servers as Record<string, unknown>)[MCP_SERVER_NAME];\n if (entry === undefined) return { found: true, state: 'absent' };\n return { found: true, state: classifyMcpEntry(entry) };\n}\n\n/** Project scope is decided by the working directory as well as the flag:\n * `claude` writes `.mcp.json` beside the project it was run in. */\nasync function runClaudeMcpAdd(\n _command: string,\n opts: { scope: 'user' | 'project'; cwd: string },\n): Promise<void> {\n await exec('claude', ['mcp', 'add', MCP_SERVER_NAME, '-s', opts.scope, '--', 'tenjin', 'mcp'], {\n timeout: 20_000,\n cwd: opts.cwd,\n });\n}\n\ninterface EffectiveLimits {\n maxAutoSpend: string;\n sessionBudget: string;\n}\n\nfunction effectiveLimits(policy: SpendPolicy): EffectiveLimits {\n return {\n maxAutoSpend: toMoney(policy.maxAutoSpendAtomic.toString()).usd,\n sessionBudget:\n policy.sessionBudgetAtomic === null\n ? 'no daily ceiling'\n : toMoney(policy.sessionBudgetAtomic.toString()).usd,\n };\n}\n\n/** Only the status-line state that needs the user: one this install would not\n * touch, with the command that adds the footer beside it. */\nexport function statusLineProblems(ctx: CommandContext, result: StatusLineResult): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n if (result.warning !== undefined) {\n return [warn(`The live status line was not registered (${result.warning})`)];\n }\n if (result.state !== 'foreign') return [];\n return [\n warn('You already have a status line, so it was left exactly as it is.'),\n ' To show the live x402 footer beside it, run:',\n ' tenjin install --status-line compose',\n ...(result.compose === undefined\n ? []\n : [' or set this command yourself:', ` ${result.compose}`]),\n ];\n}\n\n/**\n * A few lines a first-time user can read at a glance: it worked, here is your\n * wallet, here is the one thing to do next. The file paths, entry counts and\n * data-handling detail stay in `--json` and the docs; the terminal only grows\n * a line when something needs the user.\n */\nfunction lines(\n ctx: CommandContext,\n s: {\n project: boolean;\n hooks: HooksResult;\n permissions: AllowRuleResult;\n statusLine: StatusLineResult;\n mcp: McpRegistration;\n wallet: WalletOutcome;\n policy: SpendPolicy;\n },\n): string[] {\n const ok = paint(ctx.io, 'green', '✓');\n const limits = effectiveLimits(s.policy);\n const daily =\n s.policy.sessionBudgetAtomic === null ? 'no daily limit' : `$${limits.sessionBudget} a day`;\n // The first line only says \"set up\" when it is: a settings file this run\n // would not write to means nothing was set up, and hooks without the MCP\n // server point at a `request` tool that is not there.\n const blocked = s.hooks.skipped !== undefined;\n const needsMcp = !blocked && !s.mcp.registered;\n const where = s.project ? ' in this project' : '';\n const fund = paint(ctx.io, 'bold', 'tenjin wallet fund');\n return [\n blocked\n ? paint(ctx.io, 'yellow', `! Tenjin could not finish setting up Claude Code${where}`)\n : needsMcp\n ? paint(ctx.io, 'yellow', '! Almost done: Claude Code needs one command')\n : `${ok} Tenjin is set up for Claude Code${where}`,\n ...walletLines(ctx, ok, s.wallet),\n ` Automatic router: up to $${limits.maxAutoSpend} per call; daily limit ${daily}`,\n ...(s.statusLine.state === 'ours' || s.statusLine.state === 'composed'\n ? [' Live status line on: each lookup names its provider while it runs']\n : []),\n ...problems(ctx, s.hooks, s.permissions, s.statusLine, s.mcp),\n '',\n blocked\n ? 'Next: fix the file above, then run tenjin install again'\n : needsMcp\n ? s.wallet.status === 'created'\n ? `Next: run the command above and ${fund}, then restart Claude Code`\n : 'Next: run the command above, then restart Claude Code'\n : s.wallet.status === 'created'\n ? `Next: ${fund}, then restart Claude Code`\n : 'Next: restart Claude Code',\n ];\n}\n\n/** \"Up to date\" only when nothing below it needs the user. */\nfunction refreshLines(ctx: CommandContext, issues: string[]): string[] {\n if (issues.length === 0) return [`${paint(ctx.io, 'green', '✓')} Tenjin is up to date`];\n return [paint(ctx.io, 'yellow', '! Tenjin is updated, but needs one fix'), ...issues];\n}\n\nfunction walletLines(ctx: CommandContext, ok: string, w: WalletOutcome): string[] {\n if (w.status === 'created') return [`${ok} Wallet created: ${w.address}`];\n if (w.status === 'existing') return [`${ok} Wallet: ${w.address}`];\n if (w.reason === 'flag') return [' No wallet yet. Create one with: tenjin wallet create'];\n return [\n paint(ctx.io, 'yellow', `! No wallet was created. ${w.warning ?? ''}`.trimEnd()),\n ` ${w.fix ?? 'Create one with: tenjin wallet create'}`,\n ];\n}\n\n/** Only what needs the user, each with the command that fixes it. */\nfunction problems(\n ctx: CommandContext,\n hooks: HooksResult,\n permissions: AllowRuleResult,\n statusLine: StatusLineResult,\n mcp: McpRegistration,\n): string[] {\n const warn = (text: string) => paint(ctx.io, 'yellow', `! ${text}`);\n const out: string[] = [];\n // The hooks and the permission rule share one settings file, so a file this\n // run would not touch is reported once, not once per writer.\n if (hooks.skipped !== undefined) {\n out.push(\n warn(\n hooks.warning ??\n `${hooks.path ?? 'Your Claude Code settings file'} was left untouched (${hooks.skipped}).`,\n ),\n );\n } else {\n if (hooks.warning !== undefined) out.push(warn(hooks.warning));\n if (permissions.warning !== undefined) out.push(warn(permissions.warning));\n }\n if (!mcp.registered) {\n // The reason stays in --json: raw exec output is noise here, the fix is not.\n out.push(warn('Could not add the request tool to Claude Code. Run:'));\n out.push(` ${mcp.command}`);\n }\n out.push(...statusLineProblems(ctx, statusLine));\n return out;\n}\n\n/**\n * THREE ANSWERS, NOT TWO. A settings file that cannot be read or parsed is not\n * a file without our entries, and collapsing the two let `refreshEveryInstall`\n * read a momentarily broken project settings file as confirmed absence and\n * strike the project off `install.routerProjects` for good: repairing the file\n * afterwards did not bring it back, so every later `tenjin update` from HOME\n * silently skipped it.\n */\ntype EntriesProbe =\n { state: 'present' } | { state: 'absent' } | { state: 'unreadable'; reason: string };\n\nasync function probeOurEntries(path: string, dataDir: string): Promise<EntriesProbe> {\n const found = await inspectHooksFile(path);\n if ('refusal' in found) {\n // `unreadable` here is the inspection's own vocabulary for \"the file exists\n // and this build could not use it\"; a file that is simply not there comes\n // back as an empty, readable inspection rather than a refusal.\n return { state: 'unreadable', reason: found.refusal.reason };\n }\n const present = Object.values(found.hooks).some((list) =>\n list.some((entry) => ownsHookEntry(entry, dataDir)),\n );\n return present ? { state: 'present' } : { state: 'absent' };\n}\n\n/** Shared with `uninstall`: the prune this module's writer already performs. */\nexport { pruneHooks };\n","import { lstatSync } from 'node:fs';\nimport { readdir, rm, rmdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { readSkillFile, skillFrontmatterName, skillsDirsFor } from './skill-wiring';\nimport { RETIRED_SKILL_NAMES } from './skills-source';\nimport { hasCode } from './errno';\n\nfunction isRealDirectory(path: string): boolean {\n try {\n return lstatSync(path, { throwIfNoEntry: false })?.isDirectory() === true;\n } catch (err) {\n // Linux reports ENOTDIR when an ancestor is a regular file. Nothing can\n // be installed below it, just as with an absent path. Do not follow symlinks.\n if (hasCode(err, 'ENOENT') || hasCode(err, 'ENOTDIR')) return false;\n throw err;\n }\n}\n\n/** Remove only our named skill file; preserve foreign skills and adjacent user files. */\nexport async function removeOwnedSkill(\n name: string,\n skillsDir: string,\n): Promise<{ changed: boolean }> {\n if (!isRealDirectory(skillsDir)) {\n return { changed: false };\n }\n const skillDir = join(skillsDir, name);\n if (!isRealDirectory(skillDir)) {\n return { changed: false };\n }\n const path = join(skillDir, 'SKILL.md');\n const read = await readSkillFile(path);\n if (read.kind === 'absent') return { changed: false };\n if (read.kind !== 'ok' || skillFrontmatterName(read.bytes.toString('utf8')) !== name) {\n return { changed: false }; // not ours to delete for sitting at our path\n }\n await rm(path, { force: true });\n const rest = await readdir(skillDir).catch(() => null);\n if (rest !== null && rest.length === 0) await rmdir(skillDir).catch(() => undefined);\n return { changed: true };\n}\n\n/** Refresh retires obsolete skills without needing their old packaged source. */\nexport async function removeRetiredSkills(home: string, project?: string): Promise<string[]> {\n const removed: string[] = [];\n const dirs = [...skillsDirsFor(home), ...(project ? skillsDirsFor(project) : [])];\n for (const dir of new Set(dirs)) {\n for (const name of RETIRED_SKILL_NAMES) {\n if ((await removeOwnedSkill(name, dir)).changed) removed.push(join(dir, name));\n }\n }\n return removed;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,UAAU,gBAAgB;AACnC,SAAS,eAAe;AACxB,SAAS,YAAY,QAAAA,aAAY;AACjC,SAAS,iBAAiB;;;ACJ1B,SAAS,iBAAiB;AAC1B,SAAS,SAAS,IAAI,aAAa;AACnC,SAAS,YAAY;AAKrB,SAAS,gBAAgB,MAAuB;AAC9C,MAAI;AACF,WAAO,UAAU,MAAM,EAAE,gBAAgB,MAAM,CAAC,GAAG,YAAY,MAAM;AAAA,EACvE,SAAS,KAAK;AAGZ,QAAI,QAAQ,KAAK,QAAQ,KAAK,QAAQ,KAAK,SAAS,EAAG,QAAO;AAC9D,UAAM;AAAA,EACR;AACF;AAGA,eAAsB,iBACpB,MACA,WAC+B;AAC/B,MAAI,CAAC,gBAAgB,SAAS,GAAG;AAC/B,WAAO,EAAE,SAAS,MAAM;AAAA,EAC1B;AACA,QAAM,WAAW,KAAK,WAAW,IAAI;AACrC,MAAI,CAAC,gBAAgB,QAAQ,GAAG;AAC9B,WAAO,EAAE,SAAS,MAAM;AAAA,EAC1B;AACA,QAAM,OAAO,KAAK,UAAU,UAAU;AACtC,QAAM,OAAO,MAAM,cAAc,IAAI;AACrC,MAAI,KAAK,SAAS,SAAU,QAAO,EAAE,SAAS,MAAM;AACpD,MAAI,KAAK,SAAS,QAAQ,qBAAqB,KAAK,MAAM,SAAS,MAAM,CAAC,MAAM,MAAM;AACpF,WAAO,EAAE,SAAS,MAAM;AAAA,EAC1B;AACA,QAAM,GAAG,MAAM,EAAE,OAAO,KAAK,CAAC;AAC9B,QAAM,OAAO,MAAM,QAA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O;AAAA,EAC7D;AACA,QAAM,UAAU,OAAO,OAAO,MAAM,KAAK,EAAE;AAAA,IAAK,CAAC,SAC/C,KAAK,KAAK,CAAC,UAAU,cAAc,OAAO,OAAO,CAAC;AAAA,EACpD;AACA,SAAO,UAAU,EAAE,OAAO,UAAU,IAAI,EAAE,OAAO,SAAS;AAC5D;","names":["join","join"]}
|
|
@@ -13,20 +13,21 @@ import {
|
|
|
13
13
|
projectRouterPath,
|
|
14
14
|
readProjectRouterFile,
|
|
15
15
|
routerSettings
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-C363JZN2.js";
|
|
17
17
|
import {
|
|
18
18
|
hasCode
|
|
19
19
|
} from "./chunk-2I4QTOLB.js";
|
|
20
20
|
import {
|
|
21
21
|
isTeamShelfOrigin,
|
|
22
22
|
loadProjectConfig
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-IOB7URFH.js";
|
|
24
24
|
import {
|
|
25
25
|
parseUsdToAtomic,
|
|
26
26
|
toMoney
|
|
27
27
|
} from "./chunk-O2JYBOUO.js";
|
|
28
28
|
import {
|
|
29
29
|
CONFIG_KEYS,
|
|
30
|
+
EXPERIMENTAL_CONFIG_KEYS,
|
|
30
31
|
HOOKS_CONFIG_KEYS,
|
|
31
32
|
LOOP_CONFIG_KEYS,
|
|
32
33
|
PRODUCTION_ORIGIN,
|
|
@@ -47,7 +48,7 @@ import {
|
|
|
47
48
|
parseUpdateModeFlag,
|
|
48
49
|
resolveSettings,
|
|
49
50
|
retiredPaymentKeys
|
|
50
|
-
} from "./chunk-
|
|
51
|
+
} from "./chunk-W3LVZ2EN.js";
|
|
51
52
|
import {
|
|
52
53
|
ADAPTERS,
|
|
53
54
|
MODE_GATED_RULES,
|
|
@@ -55,14 +56,14 @@ import {
|
|
|
55
56
|
registeredHooks,
|
|
56
57
|
retractModeGatedRules,
|
|
57
58
|
wireFreeVerbAllowlist
|
|
58
|
-
} from "./chunk-
|
|
59
|
+
} from "./chunk-IOIHYOU4.js";
|
|
59
60
|
import {
|
|
60
61
|
CliError,
|
|
61
62
|
writeFileAtomic
|
|
62
63
|
} from "./chunk-JLEF5WHM.js";
|
|
63
64
|
import {
|
|
64
65
|
configPath
|
|
65
|
-
} from "./chunk-
|
|
66
|
+
} from "./chunk-K6AXXYCG.js";
|
|
66
67
|
|
|
67
68
|
// src/commands/config.ts
|
|
68
69
|
import { mkdir } from "node:fs/promises";
|
|
@@ -194,7 +195,8 @@ var KEY_WIDTH = Math.max(
|
|
|
194
195
|
...UPDATE_CONFIG_KEYS,
|
|
195
196
|
...LOOP_CONFIG_KEYS,
|
|
196
197
|
...TEAM_CONFIG_KEYS,
|
|
197
|
-
...ROUTER_CONFIG_KEYS
|
|
198
|
+
...ROUTER_CONFIG_KEYS,
|
|
199
|
+
...EXPERIMENTAL_CONFIG_KEYS
|
|
198
200
|
].map((key) => key.length)
|
|
199
201
|
);
|
|
200
202
|
var KEY_DESCRIPTIONS = {
|
|
@@ -225,8 +227,13 @@ var KEY_DESCRIPTIONS = {
|
|
|
225
227
|
"loop.port": "the loop daemon's loopback port; null derives one from the data dir (set only when doctor reports a foreign listener)",
|
|
226
228
|
"team.publicFallback": "on=a team-shelf miss falls through to the public marketplace, off=team-only (public-only lookup stages are dropped)",
|
|
227
229
|
"router.enabled": "false stops every router hook and the request tool; --project sets it for this repository, --project --local for you alone in it",
|
|
228
|
-
"router.context": "session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled"
|
|
230
|
+
"router.context": "session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled",
|
|
231
|
+
"experimental.bazaar": "EXPERIMENTAL. on=the router may also suggest unreviewed sellers from Coinbase's open x402 Bazaar, off=curated services and Tenjin's reviewed list only"
|
|
229
232
|
};
|
|
233
|
+
var EXPERIMENTAL_BAZAAR_WARNING = "Experimental: the router may now also suggest sellers from Coinbase's open x402 Bazaar. They are unreviewed third parties, Tenjin has not checked them, matches can be noisy, prices can vary with the input, and payments are real, under your spend limits. To find them, short snippets of your prompts are sent to Coinbase's public Bazaar search. Tenjin's reviewed list stays on either way. Turn this off with `tenjin config set experimental.bazaar off`.";
|
|
234
|
+
function isExperimentalKey(key) {
|
|
235
|
+
return EXPERIMENTAL_CONFIG_KEYS.includes(key);
|
|
236
|
+
}
|
|
230
237
|
function isLoopKey(key) {
|
|
231
238
|
return LOOP_CONFIG_KEYS.includes(key);
|
|
232
239
|
}
|
|
@@ -303,6 +310,14 @@ async function runConfigList(ctx) {
|
|
|
303
310
|
data[key] = entry;
|
|
304
311
|
humanLines.push(describedLine(key, entry));
|
|
305
312
|
}
|
|
313
|
+
for (const key of EXPERIMENTAL_CONFIG_KEYS) {
|
|
314
|
+
const entry = {
|
|
315
|
+
value: settings.experimentalBazaar.value,
|
|
316
|
+
source: settings.experimentalBazaar.source
|
|
317
|
+
};
|
|
318
|
+
data[key] = entry;
|
|
319
|
+
humanLines.push(describedLine(key, entry));
|
|
320
|
+
}
|
|
306
321
|
return { data, humanLines };
|
|
307
322
|
}
|
|
308
323
|
async function runConfigGet({ key }, ctx) {
|
|
@@ -339,6 +354,14 @@ async function runConfigGet({ key }, ctx) {
|
|
|
339
354
|
const entry2 = renderRouterSetting(key, await resolveRouterFromContext(ctx));
|
|
340
355
|
return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
|
|
341
356
|
}
|
|
357
|
+
if (isExperimentalKey(key)) {
|
|
358
|
+
const { experimentalBazaar } = await resolveFromContext(ctx);
|
|
359
|
+
const entry2 = {
|
|
360
|
+
value: experimentalBazaar.value,
|
|
361
|
+
source: experimentalBazaar.source
|
|
362
|
+
};
|
|
363
|
+
return { data: { key, ...entry2 }, humanLines: [formatLine(key, entry2)] };
|
|
364
|
+
}
|
|
342
365
|
const configKey = assertKey(key);
|
|
343
366
|
const settings = await resolveFromContext(ctx);
|
|
344
367
|
const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);
|
|
@@ -368,6 +391,7 @@ async function runConfigSet({
|
|
|
368
391
|
if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);
|
|
369
392
|
if (isLoopKey(key)) return setLoopKey(key, value, ctx);
|
|
370
393
|
if (isTeamKey(key)) return setTeamKey(key, value, ctx);
|
|
394
|
+
if (isExperimentalKey(key)) return setExperimentalKey(key, value, ctx);
|
|
371
395
|
const configKey = assertKey(key);
|
|
372
396
|
const stored = parseValue(configKey, value);
|
|
373
397
|
await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));
|
|
@@ -579,6 +603,19 @@ async function setTeamKey(key, value, ctx) {
|
|
|
579
603
|
const entry = { value: parsed, source: "file" };
|
|
580
604
|
return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };
|
|
581
605
|
}
|
|
606
|
+
async function setExperimentalKey(key, value, ctx) {
|
|
607
|
+
const parsed = parsePublicFallbackFlag(value, key);
|
|
608
|
+
await persist(ctx.dataDir, (existing) => ({
|
|
609
|
+
...existing,
|
|
610
|
+
experimental: { ...existing.experimental, bazaar: parsed }
|
|
611
|
+
}));
|
|
612
|
+
const entry = { value: parsed, source: "file" };
|
|
613
|
+
const warning = parsed === "on" ? EXPERIMENTAL_BAZAAR_WARNING : void 0;
|
|
614
|
+
return {
|
|
615
|
+
data: { key, ...entry, ...warning !== void 0 ? { warning } : {} },
|
|
616
|
+
humanLines: [formatLine(key, entry), ...warning !== void 0 ? [warning] : []]
|
|
617
|
+
};
|
|
618
|
+
}
|
|
582
619
|
async function setRouterKey(key, value, ctx, project) {
|
|
583
620
|
const field = key === "router.enabled" ? "enabled" : "context";
|
|
584
621
|
const parsed = field === "enabled" ? parseBoolean(value) : parseRouterContext(value);
|
|
@@ -718,7 +755,7 @@ function assertKey(key) {
|
|
|
718
755
|
}
|
|
719
756
|
if (CONFIG_KEYS.includes(key)) return key;
|
|
720
757
|
throw new CliError("USAGE", `Unknown config key: ${JSON.stringify(key)}`, {
|
|
721
|
-
fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS].join(", ")}.`
|
|
758
|
+
fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].join(", ")}.`
|
|
722
759
|
});
|
|
723
760
|
}
|
|
724
761
|
function renderSetting(key, stored, source) {
|
|
@@ -874,6 +911,7 @@ export {
|
|
|
874
911
|
onPath,
|
|
875
912
|
readSkillFile,
|
|
876
913
|
skillFrontmatterName,
|
|
914
|
+
EXPERIMENTAL_BAZAAR_WARNING,
|
|
877
915
|
runConfigList,
|
|
878
916
|
runConfigGet,
|
|
879
917
|
runConfigSet,
|
|
@@ -885,4 +923,4 @@ export {
|
|
|
885
923
|
persistInstallHarness,
|
|
886
924
|
persistGrantDeclined
|
|
887
925
|
};
|
|
888
|
-
//# sourceMappingURL=chunk-
|
|
926
|
+
//# sourceMappingURL=chunk-OTPEH3AH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/commands/config.ts","../src/lib/skill-wiring.ts","../src/lib/skills-source.ts","../src/lib/harness-presence.ts"],"sourcesContent":["import { mkdir } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname } from 'node:path';\nimport { styleText } from 'node:util';\nimport { CliError } from '../lib/errors';\nimport { confirmChoice } from '../lib/clack';\nimport type { CodexGrantResult } from '../lib/harness-permissions';\nimport {\n inspectFreeVerbRules,\n MODE_GATED_RULES,\n retractModeGatedRules,\n wireFreeVerbAllowlist,\n type PermissionsResult,\n} from '../lib/harness-permissions';\nimport { modeGatedPointer } from '../lib/permissions';\nimport { PRODUCTION_ORIGIN, isSameDeployment } from '../lib/production-origin';\nimport {\n CONFIG_KEYS,\n RETIRED_PAYMENT_GUIDANCE,\n retiredPaymentKeys,\n HOOKS_CONFIG_KEYS,\n PUBLISH_CONFIG_KEYS,\n PublishModeSchema,\n RawConfigSchema,\n SEND_MAX_UNSET,\n UPDATE_CONFIG_KEYS,\n LOOP_CONFIG_KEYS,\n TEAM_CONFIG_KEYS,\n EXPERIMENTAL_CONFIG_KEYS,\n ROUTER_CONFIG_KEYS,\n ROUTER_CONTEXTS,\n loadRawConfig,\n parseLoopValue,\n parsePublicFallbackFlag,\n parseAckServerWarnings,\n parseUpdateModeFlag,\n resolveSettings,\n} from '../lib/config';\nimport type {\n EffectiveSettings,\n HookArm,\n HooksConfigKey,\n PartialConfig,\n Provenance,\n PublishConfigKey,\n PublishMode,\n ScalarConfigKey,\n UpdateConfigKey,\n LoopConfigKey,\n TeamConfigKey,\n ExperimentalConfigKey,\n RouterConfigKey,\n RouterContext,\n} from '../lib/config';\nimport { onPath } from '../lib/skill-wiring';\nimport type { Harness, HarnessAdapter } from '../adapters/types';\nimport { ADAPTERS } from '../adapters/registry';\nimport { isTeamShelfOrigin, loadProjectConfig } from '../lib/settings';\nimport { configPath } from '../lib/paths';\nimport { writeFileAtomic } from '../lib/atomic-json';\nimport { installedHarnessInPlay } from '../lib/harness-presence';\nimport { withFileLock, LockTimeoutError } from '../lib/lock';\nimport { parseUsdToAtomic, toMoney } from '../lib/money';\nimport type { Money } from '../schemas';\nimport type { CommandContext, CommandResult } from '../context';\nimport {\n projectRouterPath,\n readProjectRouterFile,\n routerSettings,\n type RouterSettings,\n} from '../router/settings';\n\n/** Machine values use Money for spending keys and scalars for other settings. */\ninterface RenderedValue {\n value: Money | string | string[] | boolean | null;\n}\ninterface RenderedSetting extends RenderedValue {\n source: Provenance;\n /** The file a router key came from, when one did. */\n path?: string;\n}\n\n/**\n * Seams for the one `config set` path that touches a file outside the data dir.\n * Tests inject all of them; nothing here is reachable from a flag.\n */\nexport interface ConfigSetDeps {\n /** Harness lifecycle implementations; tests inject adapters at this boundary. */\n adapters?: Readonly<Record<Harness, HarnessAdapter>>;\n /** Home whose `.claude/settings.json` is synced; defaults to os.homedir(). */\n homeDir?: string;\n /** Overrides TTY detection, exactly as install's own seam does. */\n isInteractive?: boolean;\n /** The yes/no for a loosening write; defaults to the clack confirm (default yes). */\n confirmRule?: (label: string) => Promise<boolean>;\n /** Settled harness selection; absent, each registered adapter is detected normally. */\n harnessesInPlay?: readonly Harness[];\n /** The retraction-only pass `review` runs; defaults to the real writer. */\n retractModeGated?: (home: string) => Promise<PermissionsResult>;\n /** PATH probe for harness detection; defaults to probing `env.PATH`. */\n which?: (bin: string) => boolean;\n /** Environment for that probe; defaults to process.env. */\n env?: NodeJS.ProcessEnv;\n inspectAllowlist?: typeof inspectFreeVerbRules;\n wireAllowlist?: (home: string, mode: PublishMode) => Promise<PermissionsResult>;\n}\n\nconst KEY_WIDTH = Math.max(\n ...[\n ...CONFIG_KEYS,\n ...PUBLISH_CONFIG_KEYS,\n ...HOOKS_CONFIG_KEYS,\n ...UPDATE_CONFIG_KEYS,\n ...LOOP_CONFIG_KEYS,\n ...TEAM_CONFIG_KEYS,\n ...ROUTER_CONFIG_KEYS,\n ...EXPERIMENTAL_CONFIG_KEYS,\n ].map((key) => key.length),\n);\n\n/**\n * A one-line human description per key, appended (dim) to the bare `config`\n * listing only. Machine `data` is unchanged; these are humanLines decoration.\n */\nconst KEY_DESCRIPTIONS: Record<string, string> = {\n maxAutoSpend: 'automatic router limit per call',\n sessionBudget: 'automatic router daily limit: 0 blocks automatic spend, none removes the ceiling',\n sendMaxAmount:\n 'hard cap per tenjin wallet send; unset = send refuses until set, 0 disables send, none = uncapped; never bypassed by --yes',\n allowlistCreators: 'only auto-pay these creators (empty = any)',\n baseUrl: 'Tenjin API base URL: what publish/read/search go to (the team shelf, in team mode)',\n publicShelfUrl:\n 'the public marketplace, consume-only: the second shelf a team-mode search falls through to',\n shelfBypassSecret:\n \"the team shelf's Vercel protection-bypass secret; setting it is what turns team mode on (printed as set/unset)\",\n rpcUrl: 'Base RPC endpoint for balance reads',\n evalCohort: 'opt in to the search evaluation cohort',\n bazaarRegistries: 'x402 registries used to verify direct-payment listings',\n 'publish.mode': 'review=always ask, auto=ask on findings, full-auto=only hard blocks stop it',\n 'publish.defaultPrice': 'price used when none is given',\n 'publish.ackServerWarnings':\n \"whether a yes covers the MARKETPLACE scan's warn findings: mode=only the ones an earlier render already showed you (full-auto still acks), on=any of them, off=never\",\n 'hooks.prompt': 'answer the prompt you just typed with what the shelves already know',\n 'hooks.web-search': 'ask Tenjin before the agent runs a WebSearch',\n 'hooks.web-fetch': 'ask Tenjin before the agent fetches a page',\n 'hooks.subagent':\n 'ask Tenjin with a subagent work order (the most sensitive payload any hook sees) and hand the answer to the child at its start',\n 'hooks.failure': 'answer a failing command with the fix this machine or a shelf already has',\n 'hooks.publish':\n 'the turn-end ask to publish what this turn settled, spoken to you and to each subagent at its own end',\n 'hooks.primer': 'one-paragraph search-first primer at session start',\n 'update.mode':\n 'nudge=report a newer version (stderr line, JSON envelope, hook output), off=neither report nor ask npm',\n 'loop.human_wait_ms':\n 'ms a hook fire may take when a human is waiting on it (prompt, Stop, SessionStart)',\n 'loop.tool_wait_ms': 'ms a hook fire may take when a tool call is waiting on it',\n 'loop.idle_exit_min': 'minutes without a hook fire before the loop daemon exits',\n 'loop.port':\n \"the loop daemon's loopback port; null derives one from the data dir (set only when doctor reports a foreign listener)\",\n 'team.publicFallback':\n 'on=a team-shelf miss falls through to the public marketplace, off=team-only (public-only lookup stages are dropped)',\n 'router.enabled':\n 'false stops every router hook and the request tool; --project sets it for this repository, --project --local for you alone in it',\n 'router.context':\n 'session=a hook packet carries up to six prior messages, turn=the current turn only; --project and --local as for router.enabled',\n 'experimental.bazaar':\n \"EXPERIMENTAL. on=the router may also suggest unreviewed sellers from Coinbase's open x402 Bazaar, off=curated services and Tenjin's reviewed list only\",\n};\n\n/**\n * What turning the experimental list on means, said when it is turned on:\n * whose services these are, that the price is theirs, and how to turn it off.\n */\nexport const EXPERIMENTAL_BAZAAR_WARNING =\n \"Experimental: the router may now also suggest sellers from Coinbase's open x402 Bazaar. \" +\n 'They are unreviewed third parties, Tenjin has not checked them, matches can be noisy, ' +\n 'prices can vary with the input, and payments are real, under your spend limits. ' +\n \"To find them, short snippets of your prompts are sent to Coinbase's public Bazaar search. \" +\n \"Tenjin's reviewed list stays on either way. Turn this off with \" +\n '`tenjin config set experimental.bazaar off`.';\n\nfunction isExperimentalKey(key: string): key is ExperimentalConfigKey {\n return (EXPERIMENTAL_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isLoopKey(key: string): key is LoopConfigKey {\n return (LOOP_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isTeamKey(key: string): key is TeamConfigKey {\n return (TEAM_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isRouterKey(key: string): key is RouterConfigKey {\n return (ROUTER_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/** The list/get shape for a router key, with the file that set it. */\nfunction renderRouterSetting(key: RouterConfigKey, settings: RouterSettings): RenderedSetting {\n const { value, source, path } = key === 'router.enabled' ? settings.enabled : settings.context;\n return { value, source, ...(path !== undefined ? { path } : {}) };\n}\n\n/** Router keys resolve against the directory the command runs in, as a hook would. */\nasync function resolveRouterFromContext(ctx: CommandContext): Promise<RouterSettings> {\n return routerSettings({ cwd: process.cwd(), dataDir: ctx.dataDir });\n}\n\nfunction renderLoopSetting(key: LoopConfigKey, settings: EffectiveSettings): RenderedSetting {\n const field = key.slice('loop.'.length) as keyof EffectiveSettings['loop'];\n const { value, source } = settings.loop[field];\n return { value: value === null ? 'null' : String(value), source };\n}\n\nfunction isPublishKey(key: string): key is PublishConfigKey {\n return (PUBLISH_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isHooksKey(key: string): key is HooksConfigKey {\n return (HOOKS_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\nfunction isUpdateKey(key: string): key is UpdateConfigKey {\n return (UPDATE_CONFIG_KEYS as readonly string[]).includes(key);\n}\n\n/**\n * Show every effective key with its value and provenance. `data` is keyed by\n * config key; provenance comes from resolveSettings over the *raw* file (not the\n * defaults-merged config), so a key the user never set reads `default`, not\n * `file`.\n */\nexport async function runConfigList(ctx: CommandContext): Promise<CommandResult> {\n const settings = await resolveFromContext(ctx);\n const data: Record<string, RenderedSetting> = {};\n const humanLines: string[] = [];\n for (const key of CONFIG_KEYS) {\n const entry = renderSetting(key, settings[key].value, settings[key].source);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of PUBLISH_CONFIG_KEYS) {\n const entry = renderPublishSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry, downgradeNote(key, settings)));\n }\n for (const key of HOOKS_CONFIG_KEYS) {\n const entry = renderHooksSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of UPDATE_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.updateMode.value,\n source: settings.updateMode.source,\n };\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of LOOP_CONFIG_KEYS) {\n const entry = renderLoopSetting(key, settings);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of TEAM_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.teamPublicFallback.value,\n source: settings.teamPublicFallback.source,\n };\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n const router = await resolveRouterFromContext(ctx);\n for (const key of ROUTER_CONFIG_KEYS) {\n const entry = renderRouterSetting(key, router);\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n for (const key of EXPERIMENTAL_CONFIG_KEYS) {\n const entry: RenderedSetting = {\n value: settings.experimentalBazaar.value,\n source: settings.experimentalBazaar.source,\n };\n data[key] = entry;\n humanLines.push(describedLine(key, entry));\n }\n return { data, humanLines };\n}\n\n/** Same per-key shape as list, for one key. Unknown key is a USAGE failure. */\nexport async function runConfigGet(\n { key }: { key: string },\n ctx: CommandContext,\n): Promise<CommandResult> {\n if (isPublishKey(key)) {\n const settings = await resolveFromContext(ctx);\n const entry = renderPublishSetting(key, settings);\n return {\n data: { key, ...entry },\n humanLines: [withNote(formatLine(key, entry), downgradeNote(key, settings))],\n };\n }\n if (isHooksKey(key)) {\n const entry = renderHooksSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isUpdateKey(key)) {\n const { updateMode } = await resolveFromContext(ctx);\n const entry: RenderedSetting = { value: updateMode.value, source: updateMode.source };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isLoopKey(key)) {\n const entry = renderLoopSetting(key, await resolveFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isTeamKey(key)) {\n const { teamPublicFallback } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: teamPublicFallback.value,\n source: teamPublicFallback.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isRouterKey(key)) {\n const entry = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n if (isExperimentalKey(key)) {\n const { experimentalBazaar } = await resolveFromContext(ctx);\n const entry: RenderedSetting = {\n value: experimentalBazaar.value,\n source: experimentalBazaar.source,\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n }\n const configKey = assertKey(key);\n const settings = await resolveFromContext(ctx);\n const entry = renderSetting(configKey, settings[configKey].value, settings[configKey].source);\n return { data: { key: configKey, ...entry }, humanLines: [formatLine(configKey, entry)] };\n}\n\n/**\n * Parse the value for this key, then persist it merged into the existing raw\n * file — never materializing defaults for keys the user did not set, so\n * provenance stays truthful. The written key now reads `file`.\n */\nexport async function runConfigSet(\n {\n key,\n value,\n project,\n local,\n }: { key: string; value: string; project?: boolean; local?: boolean },\n ctx: CommandContext,\n deps: ConfigSetDeps = {},\n): Promise<CommandResult> {\n if (local === true && project !== true) {\n throw new CliError('USAGE', '--local names the personal project file, so it needs --project', {\n fix: `Run \\`tenjin config set --project --local ${key} ${value}\\`.`,\n });\n }\n if (isRouterKey(key)) {\n return setRouterKey(key, value, ctx, project === true ? { local: local === true } : undefined);\n }\n if (project === true) {\n throw new CliError('USAGE', `${key} is not a project key`, {\n fix: `--project applies to ${ROUTER_CONFIG_KEYS.join(' and ')} only; drop it to set ${key} for this machine.`,\n });\n }\n if (isPublishKey(key)) return setPublishKey(key, value, ctx, deps);\n if (isHooksKey(key)) return setHooksKey(key, value, ctx);\n if (isUpdateKey(key)) return setUpdateKey(key, value, ctx);\n if (isLoopKey(key)) return setLoopKey(key, value, ctx);\n if (isTeamKey(key)) return setTeamKey(key, value, ctx);\n if (isExperimentalKey(key)) return setExperimentalKey(key, value, ctx);\n const configKey = assertKey(key);\n const stored = parseValue(configKey, value);\n await persist(ctx.dataDir, (existing) => ({ ...existing, [configKey]: stored }));\n const entry = renderSetting(configKey, stored, 'file');\n const warning = await halfWiredTeamShelf(configKey, ctx.dataDir);\n return {\n data: { key: configKey, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(configKey, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * The half-wired team shelf, said out loud at the moment it is created.\n *\n * Team mode takes TWO settings — a private deployment in `baseUrl` and its\n * bypass secret — and the setup is two independent commands, so a machine can\n * easily end up with the secret and no shelf (run in the other order, or the\n * secret line alone on a second machine). The CLI fails that state safe to\n * public mode, which means an operator who thinks they are on the team shelf\n * would otherwise get no signal at all: publishes would go to the marketplace\n * under the public gates. Warn, do not refuse — the pair is legitimately\n * half-set between two commands, and refusing would make the documented order\n * the only order.\n *\n * THREE KEYS, not two. `isTeamShelfOrigin` also returns false when `baseUrl`\n * matches `publicShelfUrl`, so pointing `publicShelfUrl` at the team deployment\n * drops the machine out of team mode just as surely as unsetting the secret\n * would. It fails safe and doctor catches it later; this is the warning at the\n * moment it happens, on the third key of the same triple.\n */\nasync function halfWiredTeamShelf(\n configKey: ScalarConfigKey,\n dataDir: string,\n): Promise<string | undefined> {\n if (\n configKey !== 'shelfBypassSecret' &&\n configKey !== 'baseUrl' &&\n configKey !== 'publicShelfUrl'\n ) {\n return undefined;\n }\n const config = await loadRawConfig(dataDir).catch(() => undefined);\n if (config === undefined) return undefined;\n const s = resolveSettings({ config, flags: {}, env: {} });\n if (s.shelfBypassSecret.value.length === 0) return undefined;\n const baseUrl = s.baseUrl.value;\n if (isTeamShelfOrigin(new URL(baseUrl).origin, s.publicShelfUrl.value)) return undefined;\n // WHICH KEY BROKE THE PAIR decides which fix to name. A baseUrl that now\n // matches publicShelfUrl is not \"the marketplace\" in any recognizable sense —\n // it is the operator's own two keys pointed at one place — and telling them to\n // re-point baseUrl would be advice for the other half of the same collision.\n const isProduction = isSameDeployment(new URL(baseUrl).origin, PRODUCTION_ORIGIN);\n const cause = isProduction\n ? `baseUrl is the public marketplace (${baseUrl})`\n : `baseUrl and publicShelfUrl are the same shelf (${baseUrl})`;\n const fix = isProduction\n ? 'Point baseUrl at the team deployment to finish team mode: `tenjin config set baseUrl <team shelf url>`.'\n : `A team shelf must differ from the shelf it falls through to: \\`tenjin config set publicShelfUrl ${PRODUCTION_ORIGIN}\\`.`;\n return (\n `Warning: shelfBypassSecret is set, but ${cause}, ` +\n 'so this machine stays in PUBLIC mode — publishes go to the marketplace with the scan’s ' +\n 'warn tier and the confirm cascade on. ' +\n fix\n );\n}\n\n/**\n * `config set publish.mode|publish.defaultPrice|publish.ackServerWarnings`. mode\n * and ackServerWarnings validate to their enums; defaultPrice parses decimal USD\n * at the edge into atomic (matching the spend keys). The subkey is merged into\n * the nested publish block, so a sibling subkey (or an unknown one a newer CLI\n * wrote) is preserved.\n */\nasync function setPublishKey(\n key: PublishConfigKey,\n value: string,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<CommandResult> {\n const entry: RenderedSetting =\n key === 'publish.mode'\n ? { value: parsePublishMode(value), source: 'file' }\n : key === 'publish.ackServerWarnings'\n ? { value: parseAckServerWarnings(value, key), source: 'file' }\n : { value: toMoney(parseUsdToAtomic(value)), source: 'file' };\n const subkey =\n key === 'publish.mode'\n ? 'mode'\n : key === 'publish.ackServerWarnings'\n ? 'ackServerWarnings'\n : 'defaultPrice';\n const stored =\n key === 'publish.defaultPrice' ? (entry.value as Money).atomic : (entry.value as string);\n const persistEntry = async (): Promise<void> =>\n persist(ctx.dataDir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, [subkey]: stored },\n }));\n const humanLines = [formatLine(key, entry)];\n if (key !== 'publish.mode') {\n await persistEntry();\n return { data: { key, ...entry }, humanLines };\n }\n\n // The mode decides whether a publish asks; the harness rule decides whether the\n // harness asks ANYWAY. Settling one and leaving the other to the next `tenjin\n // install` is the seam that made publish.mode look broken (tenjin-agent #161),\n // so the two move together from here too.\n // Synchronize before committing the mode. A grant writer may refuse after\n // consent (permissions, concurrent edits, an unwritable parent); persisting\n // first made the command exit successfully with an unattended mode that its\n // harness could not carry. Grant-first is also the least-authority failure\n // order: if a later config write fails, the CLI still resolves the old mode.\n const allowlist = await syncPublishRule(entry.value as PublishMode, ctx, deps);\n const failure = grantSyncFailure(allowlist);\n if (failure !== undefined) {\n throw new CliError(\n 'REFUSED',\n `publish.mode was not changed because the ${failure.harness} grant could not be updated: ${failure.reason}`,\n {\n fix:\n failure.fix ??\n `Fix the permissions for ${failure.path}, then re-run \\`tenjin config set publish.mode ${entry.value as string}\\`.`,\n details: { key, value: entry.value, allowlist },\n },\n );\n }\n await persistEntry();\n return {\n data: { key, ...entry, allowlist },\n humanLines: [...humanLines, ...allowlistLines(allowlist)],\n };\n}\n\n/**\n * What `config set publish.mode` did about the harness rule the mode carries.\n * `skipped` names why nothing was written; `pointer` is the line to show when it\n * is the operator's move.\n */\ninterface AllowlistSync {\n byHarness: Partial<Record<Harness, PermissionsResult | CodexGrantResult>>;\n skipped?: 'not-claude' | 'no-tty' | 'declined' | 'unwritable';\n pointer?: string;\n}\n\n/** A writer refusal is an error, not informational output: the mode and every\n * harness grant are one operator decision and may not report success apart. */\nfunction grantSyncFailure(\n sync: AllowlistSync,\n): { harness: Harness; path: string; reason: string; fix?: string } | undefined {\n for (const [harness, result] of Object.entries(sync.byHarness) as [\n Harness,\n PermissionsResult | CodexGrantResult,\n ][]) {\n if ('error' in result && result.error !== undefined) {\n return { harness, path: result.path, reason: result.error };\n }\n if ('warning' in result && result.warning !== undefined) {\n return {\n harness,\n path: result.path ?? '(unknown path)',\n reason: result.warning,\n ...(result.fix !== undefined ? { fix: result.fix } : {}),\n };\n }\n }\n return undefined;\n}\n\n/** Names what the write actually carries: on a machine that never ran `install`,\n * the free tier is pending too, and a question naming two lines while eleven\n * land is asking about something else. */\nfunction publishRuleQuestion(\n mode: PublishMode,\n pending: readonly string[],\n harnesses: readonly Harness[],\n): string {\n const gated = new Set<string>(MODE_GATED_RULES);\n const others = pending.filter((rule) => !gated.has(rule)).length;\n const also =\n others > 0 ? ` Also adds the ${others} command-grant rule(s) \\`tenjin install\\` writes.` : '';\n const targets = harnesses\n .map((harness) =>\n harness === 'claude' ? 'Claude Code' : harness === 'codex' ? 'Codex' : harness,\n )\n .join(' and ');\n return (\n `publish.mode ${mode} is unattended only if ${targets} carries the matching grant for ` +\n `${MODE_GATED_RULES.join(' and ')}. Update the ${targets} grant now?${also}`\n );\n}\n\n/**\n * Keep the harness allowlist in step with the mode just written.\n *\n * ASYMMETRIC ON PURPOSE, and the asymmetry is the consent rule:\n * - Loosening (auto/full-auto) ADDS a grant, so it needs a human in the loop.\n * No TTY, `--json`, or a declined prompt all leave the file alone and return\n * the pointer instead; nothing here writes on silence.\n * - Tightening (review) only ever REMOVES a rule this CLI wrote under a setting\n * the operator has just changed, so it runs unconditionally — the same reason\n * install sweeps a retired rule without asking. Leaving it behind would keep\n * publishing pre-cleared after the operator said \"ask me first\", which is the\n * failure that matters.\n */\nasync function syncPublishRule(\n mode: PublishMode,\n ctx: CommandContext,\n deps: ConfigSetDeps,\n): Promise<AllowlistSync> {\n const home = deps.homeDir ?? homedir();\n const nothing: AllowlistSync = { byHarness: {} };\n\n const write = async (): Promise<AllowlistSync> => {\n const result = await (deps.wireAllowlist ?? wireFreeVerbAllowlist)(home, mode);\n if (result.skipped !== undefined) {\n return {\n byHarness: { claude: result },\n skipped: 'unwritable',\n ...(result.fix !== undefined ? { pointer: result.fix } : {}),\n };\n }\n return { byHarness: { claude: result } };\n };\n\n const adapters = deps.adapters ?? ADAPTERS;\n const env = deps.env ?? process.env;\n const which = deps.which ?? ((bin: string) => onPath(bin, env));\n const requested = await loadRawConfig(ctx.dataDir)\n .then((config) => config.install?.harness ?? [])\n .catch(() => [] as Harness[]);\n const inPlay =\n deps.harnessesInPlay ??\n (\n await Promise.all(\n Object.values(adapters).map(async (adapter) => ({\n adapter,\n selected: await installedHarnessInPlay(adapter, home, ctx.dataDir, {\n env,\n which,\n requested,\n }),\n })),\n )\n )\n .filter((entry) => entry.selected)\n .map((entry) => entry.adapter.id);\n const selectedAdapters = inPlay.map((harness) => adapters[harness]);\n const isClaude = inPlay.includes('claude');\n\n const withOtherGrants = async (sync: AllowlistSync): Promise<AllowlistSync> => {\n const byHarness = { ...sync.byHarness };\n for (const adapter of selectedAdapters) {\n if (adapter.id === 'claude' || adapter.registrar.grant === undefined) continue;\n const result = await adapter.registrar.grant.write(home, mode, env);\n byHarness[adapter.id] = result;\n }\n return { ...sync, byHarness };\n };\n\n // Only Claude Code has a settings file of this shape; guessing at another\n // harness's config is the uninvited write lib/harness-permissions.ts avoids.\n // DETECTED, never assumed: a codex-only machine has a ~/.claude/settings.json\n // that nothing reads, so prompting about it is noise and writing to it is an\n // uninvited edit — and the retraction would sweep a file we never owned.\n if (selectedAdapters.every((adapter) => adapter.registrar.grant === undefined)) {\n // No settings file of ours to be missing anything, so the pointer would be\n // advice about a machine this is not.\n return { ...nothing, skipped: 'not-claude' };\n }\n\n const probe = isClaude\n ? await (deps.inspectAllowlist ?? inspectFreeVerbRules)(home, mode)\n : { pending: [] as string[] };\n const gated = new Set<string>(MODE_GATED_RULES);\n const missing = (probe.pending ?? []).filter((r) => gated.has(r));\n // Only ever names rules this machine does not have. A pointer built from the\n // mode alone told a fully-wired operator to go add what they already had.\n const pointer = modeGatedPointer(mode, missing) ?? undefined;\n\n // Tightening runs with no question and with no precondition, through a pass\n // that can only ever REMOVE. Riding the additive writer made this decline\n // whenever the free tier was not byte-exact — silently, and in the tightening\n // direction, on the undo the operator just typed.\n if (mode === 'review') {\n const retracted = isClaude\n ? await (deps.retractModeGated ?? retractModeGatedRules)(home)\n : undefined;\n if (retracted?.skipped !== undefined) {\n return {\n ...nothing,\n skipped: 'unwritable',\n ...(retracted.fix !== undefined ? { pointer: retracted.fix } : {}),\n };\n }\n return await withOtherGrants({\n byHarness: retracted === undefined ? {} : { claude: retracted },\n });\n }\n\n // SATISFIED BEFORE TTY, and the order is the point: a fully-wired machine has\n // nothing to ask about and nothing to write, so a `--json` or headless run\n // there is a no-op rather than a `no-tty` skip carrying a pointer at rules it\n // already has.\n if (probe.satisfied !== undefined && selectedAdapters.length === 1 && isClaude) return nothing;\n\n const canPrompt =\n ctx.flags.json === true ? false : (deps.isInteractive ?? Boolean(process.stdin.isTTY));\n if (!canPrompt) {\n return { ...nothing, skipped: 'no-tty', ...(pointer ? { pointer } : {}) };\n }\n\n const confirm = deps.confirmRule ?? ((label: string) => confirmChoice(label, true));\n const grantable = selectedAdapters\n .filter((adapter) => adapter.registrar.grant !== undefined)\n .map((adapter) => adapter.id);\n if (!(await confirm(publishRuleQuestion(mode, probe.pending ?? [], grantable)))) {\n return { ...nothing, skipped: 'declined', ...(pointer ? { pointer } : {}) };\n }\n return await withOtherGrants(isClaude ? await write() : nothing);\n}\n\n/** The human rendering of {@link syncPublishRule}, or nothing when it was a no-op. */\nfunction allowlistLines(sync: AllowlistSync): string[] {\n const lines: string[] = [];\n const claude = sync.byHarness.claude as PermissionsResult | undefined;\n if ((claude?.added.length ?? 0) > 0) {\n lines.push(`Added ${claude?.added.length ?? 0} harness rule(s) to your allowlist.`);\n }\n if ((claude?.removed.length ?? 0) > 0) {\n lines.push(`Removed ${claude?.removed.join(', ')} from your allowlist.`);\n }\n const grant = sync.byHarness.codex as CodexGrantResult | undefined;\n if (grant !== undefined && grant.error === undefined && grant.wrote) {\n lines.push(\n `Codex now allows ${grant.granted.length} tenjin command prefix(es) in ${grant.path}.`,\n );\n }\n if (grant?.error !== undefined) {\n lines.push(`Codex's grant at ${grant.path} could not be updated (${grant.error}).`);\n }\n if (sync.pointer !== undefined) lines.push(sync.pointer);\n return lines;\n}\n\n/**\n * `config set hooks.<arm>`. Merged into the nested hooks block through the same\n * locked read-modify-write every other set uses, so a subkey a newer CLI wrote\n * survives. The daemon re-stats this file per fire, so every value takes effect\n * on the next prompt with no re-install and no process to restart.\n */\nasync function setHooksKey(\n key: HooksConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const arm = key.slice('hooks.'.length) as HookArm;\n const parsed = parseBoolean(value);\n await persistHookArm(ctx.dataDir, arm, parsed);\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n // NO STALENESS WARNING, and there is nothing left to warn about: every hooks\n // key is read out of `config.json` by the daemon on each fire, so a value set\n // here takes effect on the next prompt with nothing to re-install.\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set update.mode`. Same locked merge-write as every other set, so the\n * next command reports (or stops reporting) under the new mode immediately,\n * with nothing to re-install and no process to restart.\n */\nasync function setUpdateKey(\n key: UpdateConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseUpdateModeFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n update: { ...existing.update, mode: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/**\n * `config set loop.*` and `config set team.publicFallback`. The daemon stats\n * `config.json` per fire and reloads on an mtime change, so a set takes effect\n * on the next hook fire with no restart (02-redesign.md §4a).\n */\nasync function setLoopKey(\n key: LoopConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parseLoopValue(key, value);\n const field = key.slice('loop.'.length);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n loop: { ...existing.loop, [field]: parsed },\n }));\n const entry: RenderedSetting = {\n value: parsed === null ? 'null' : String(parsed),\n source: 'file',\n };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\nasync function setTeamKey(\n key: TeamConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n team: { ...existing.team, publicFallback: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n return { data: { key, ...entry }, humanLines: [formatLine(key, entry)] };\n}\n\n/** `config set experimental.bazaar on|off`; turning it on says what it means. */\nasync function setExperimentalKey(\n key: ExperimentalConfigKey,\n value: string,\n ctx: CommandContext,\n): Promise<CommandResult> {\n const parsed = parsePublicFallbackFlag(value, key);\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n experimental: { ...existing.experimental, bazaar: parsed },\n }));\n const entry: RenderedSetting = { value: parsed, source: 'file' };\n const warning = parsed === 'on' ? EXPERIMENTAL_BAZAAR_WARNING : undefined;\n return {\n data: { key, ...entry, ...(warning !== undefined ? { warning } : {}) },\n humanLines: [formatLine(key, entry), ...(warning !== undefined ? [warning] : [])],\n };\n}\n\n/**\n * `config set [--project [--local]] router.enabled|router.context`. Without\n * `--project` the key goes into the global config through the same locked merge\n * every set uses. With it, into the project file {@link projectRouterPath}\n * names from here, merged so a sibling key survives. The line after the write\n * is what a hook here would now resolve, which differs from the value written\n * when an outer layer is tighter.\n */\nasync function setRouterKey(\n key: RouterConfigKey,\n value: string,\n ctx: CommandContext,\n project: { local: boolean } | undefined,\n): Promise<CommandResult> {\n const field = key === 'router.enabled' ? 'enabled' : 'context';\n const parsed = field === 'enabled' ? parseBoolean(value) : parseRouterContext(value);\n let written: RenderedSetting;\n if (project === undefined) {\n await persist(ctx.dataDir, (existing) => ({\n ...existing,\n router: { ...existing.router, [field]: parsed },\n }));\n written = { value: parsed, source: 'file', path: configPath(ctx.dataDir) };\n } else {\n const path = await projectRouterPath({ cwd: process.cwd(), local: project.local });\n await persistProjectRouter(path, field, parsed);\n written = { value: parsed, source: project.local ? 'local' : 'project', path };\n }\n const effective = renderRouterSetting(key, await resolveRouterFromContext(ctx));\n const humanLines = [formatLine(key, written)];\n if (effective.value !== written.value) {\n humanLines.push(\n `Still ${String(effective.value)} here: ${effective.path ?? 'the default'} is tighter, and a nearer file can only tighten an outer one.`,\n );\n }\n if (project?.local === true) {\n humanLines.push('Keep .tenjin/config.local.json out of git: add it to .gitignore.');\n }\n return { data: { key, ...written, effective }, humanLines };\n}\n\nfunction parseRouterContext(value: string): RouterContext {\n const found = ROUTER_CONTEXTS.find((context) => context === value);\n if (found !== undefined) return found;\n throw new CliError('USAGE', `Invalid router.context: ${JSON.stringify(value)}`, {\n fix: 'Use \"session\" or \"turn\".',\n });\n}\n\n/**\n * Merge one router key into a project file. It holds the router block and\n * nothing else this CLI reads, so it is written 0644 like any committed file;\n * an existing file that is not a JSON object is refused rather than replaced.\n * The read, merge and write run under the same cross-process lock the global\n * writer takes, so two concurrent sets both land.\n */\nasync function persistProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n await mkdir(dirname(path), { recursive: true, mode: 0o755 });\n const lockPath = `${path}.lock`;\n try {\n await withFileLock(lockPath, () => mergeProjectRouter(path, field, value));\n } catch (err) {\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\nasync function mergeProjectRouter(\n path: string,\n field: 'enabled' | 'context',\n value: boolean | RouterContext,\n): Promise<void> {\n // Through the one parser: a file that is not an object, or whose block is\n // invalid, is refused rather than replaced. A router subkey this build does\n // not know rides along untouched, as in the global file; it is never read.\n const existing = await readProjectRouterFile(path);\n const block = existing?.json.router;\n const next = {\n ...(existing?.json ?? {}),\n router: { ...(block !== undefined ? (block as object) : {}), [field]: value },\n };\n await writeFileAtomic(path, `${JSON.stringify(next, null, 2)}\\n`, {\n mode: 0o644,\n dirMode: 0o755,\n });\n}\n\nfunction parsePublishMode(value: string): string {\n const parsed = PublishModeSchema.safeParse(value);\n if (parsed.success) return parsed.data;\n throw new CliError('USAGE', `Invalid publish mode: ${JSON.stringify(value)}`, {\n fix: 'Use \"review\", \"auto\", or \"full-auto\".',\n });\n}\n\n/**\n * The one writer of a `hooks.<arm>` boolean, through the same locked merge-write\n * every `config set` uses, so a sibling arm or an unknown block a newer CLI\n * wrote survives. `config set hooks.<arm>` and `tenjin hooks enable|disable`\n * are two spellings of this call and never two writers.\n */\nexport async function persistHookArm(dir: string, arm: HookArm, value: boolean): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n hooks: { ...existing.hooks, [arm]: value },\n }));\n}\n\n/**\n * Persist just `publish.mode` into the global config through the same locked\n * merge-write every `config set` uses (never a raw overwrite), so a sibling\n * subkey or an unknown block a newer CLI wrote is preserved. Used by `install`'s\n * setup prompt; the mode is a validated PublishMode.\n */\nexport async function persistPublishMode(dir: string, mode: PublishMode): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n publish: { ...existing.publish, mode },\n }));\n}\n\n/**\n * Remember, or forget, a project directory this machine wired with\n * `install --project`. `tenjin update` spawns its refresh from the HOME\n * directory, so a project install is unfindable by looking around; this list is\n * how a later refresh reaches it. Absolute paths, de-duplicated, and pruned\n * when a project is uninstalled or its settings file stops carrying our\n * entries.\n */\nexport async function persistRouterProject(\n dir: string,\n projectDir: string,\n present = true,\n): Promise<void> {\n await persist(dir, (existing) => {\n const known = new Set(existing.install?.routerProjects ?? []);\n if (present) known.add(projectDir);\n else known.delete(projectDir);\n return { ...existing, install: { ...existing.install, routerProjects: [...known].sort() } };\n });\n}\n\n/** Absent-only automatic router defaults, in atomic USDC. */\nexport const ROUTER_DEFAULTS = {\n maxAutoSpend: '250000',\n sessionBudget: '5000000',\n} as const;\n\nexport interface RouterDefaultsResult {\n /** Keys this run wrote, because the file did not name them. */\n set: string[];\n /** Keys the operator had already written, left exactly as they are. */\n kept: string[];\n removed: string[];\n}\n\n/** Remove/report retired keys in the same locked write. Refresh preserves absent\n * current settings; a fresh install fills only missing automatic limits. */\nexport async function persistRouterDefaults(\n dir: string,\n refresh = false,\n): Promise<RouterDefaultsResult> {\n const result: RouterDefaultsResult = { set: [], kept: [], removed: [] };\n if (refresh && retiredPaymentKeys(await loadRawConfig(dir)).length === 0) return result;\n await persist(dir, (existing) => {\n const next: PartialConfig = { ...existing };\n result.removed = retiredPaymentKeys(existing);\n for (const key of result.removed) delete next[key];\n if (refresh) return next;\n for (const [key, value] of Object.entries(ROUTER_DEFAULTS) as [\n keyof typeof ROUTER_DEFAULTS,\n string,\n ][]) {\n if (existing[key] === undefined) {\n next[key] = value;\n result.set.push(key);\n } else result.kept.push(key);\n }\n return next;\n });\n return result;\n}\n\n/**\n * Record the settled harness selection through the same locked merge-write. It\n * replaces the previous record rather than unioning with it: the last operator\n * answer is the current intent. Doctor still re-probes detection independently;\n * the record keeps a deliberately selected but currently undetected harness in play.\n */\nexport async function persistInstallHarness(\n dir: string,\n harness: readonly Harness[],\n): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, harness: [...harness] },\n }));\n}\n\n/**\n * Record the EXACT free-verb rules `install` declined, through the same locked\n * read-modify-write every `config set` uses. Set to whatever was pending at the\n * moment of `--no-grant`; cleared back to `[]` the moment an install\n * actually wires the allowlist, or finds it already fully satisfied. `--refresh` subtracts this list from what it would otherwise\n * report as pending, so a settled no stays settled per rule — without also\n * silencing a genuinely NEW rule a later version adds (tenjin-agent#234).\n */\nexport async function persistGrantDeclined(dir: string, declined: string[]): Promise<void> {\n await persist(dir, (existing) => ({\n ...existing,\n install: { ...existing.install, grantDeclined: declined },\n }));\n}\n\nasync function resolveFromContext(ctx: CommandContext): Promise<EffectiveSettings> {\n const config = await loadRawConfig(ctx.dataDir);\n // Feed the per-project `.tenjin.json` layer so the publish keys read out what a\n // real `publish` would resolve (project/env included), not a global-only guess.\n const project = await loadProjectConfig(process.cwd());\n return resolveSettings({\n config,\n flags: { baseUrl: ctx.flags.baseUrl },\n env: process.env,\n project: project?.layer,\n });\n}\n\nfunction assertKey(key: string): ScalarConfigKey {\n if (key === 'bazaarPay' || key === 'confirm') {\n throw new CliError('USAGE', `Retired config key: ${key}`, { fix: RETIRED_PAYMENT_GUIDANCE });\n }\n if ((CONFIG_KEYS as string[]).includes(key)) return key as ScalarConfigKey;\n throw new CliError('USAGE', `Unknown config key: ${JSON.stringify(key)}`, {\n fix: `Valid keys: ${[...CONFIG_KEYS, ...PUBLISH_CONFIG_KEYS, ...HOOKS_CONFIG_KEYS, ...ROUTER_CONFIG_KEYS, ...EXPERIMENTAL_CONFIG_KEYS].join(', ')}.`,\n });\n}\n\nfunction renderSetting(\n key: ScalarConfigKey,\n stored: string | string[] | boolean,\n source: Provenance,\n): RenderedSetting {\n return { ...renderValue(key, stored), source };\n}\n\n/**\n * The list/get shape for a publish key, read from the resolved effective\n * settings, which now include the per-project `.tenjin.json` layer (see\n * resolveFromContext) so the source reflects what a publish would actually use.\n */\nfunction renderPublishSetting(key: PublishConfigKey, settings: EffectiveSettings): RenderedSetting {\n if (key === 'publish.mode') {\n return { value: settings.publishMode.value, source: settings.publishMode.source };\n }\n if (key === 'publish.ackServerWarnings') {\n return {\n value: settings.publishAckServerWarnings.value,\n source: settings.publishAckServerWarnings.source,\n };\n }\n return {\n value: toMoney(settings.publishDefaultPrice.value),\n source: settings.publishDefaultPrice.source,\n };\n}\n\n/** The list/get shape for a hooks key: the arm's boolean and where it came from. */\nfunction renderHooksSetting(key: HooksConfigKey, settings: EffectiveSettings): RenderedSetting {\n const { value, source } = settings.hooks[key.slice('hooks.'.length) as HookArm];\n return { value, source };\n}\n\nfunction renderValue(key: ScalarConfigKey, stored: string | string[] | boolean): RenderedValue {\n // REDACTED IN THE MACHINE ENVELOPE TOO, not just in the human line. `config\n // --json` is what an agent reads and what a bug report pastes, and the whole\n // point of a door key is that it opens the door for whoever holds it. What a\n // caller actually needs from this key is whether team mode is on, and\n // set/unset says exactly that. The value is still readable, by the operator,\n // in ~/.tenjin/config.json.\n if (key === 'shelfBypassSecret') {\n return { value: typeof stored === 'string' && stored.length > 0 ? 'set' : 'unset' };\n }\n if (Array.isArray(stored) || typeof stored === 'boolean') return { value: stored };\n if (key === 'sessionBudget' && stored === 'none') return { value: null };\n if (key === 'maxAutoSpend' || key === 'sessionBudget') return { value: toMoney(stored) };\n if (key === 'sendMaxAmount') {\n // 'unset' is the resolved sentinel for an absent key (send refuses), never\n // a stored value; 'none' is the explicit uncapped opt-in.\n return { value: stored === 'none' || stored === SEND_MAX_UNSET ? stored : toMoney(stored) };\n }\n return { value: stored };\n}\n\n/** Per-key edge parsing. Returns the persisted form; throws USAGE on bad input. */\nfunction parseValue(key: ScalarConfigKey, value: string): string | string[] | boolean {\n switch (key) {\n case 'sessionBudget':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'maxAutoSpend':\n return parseUsdToAtomic(value); // throws USAGE on a bad amount\n case 'sendMaxAmount':\n return value === 'none' ? 'none' : parseUsdToAtomic(value);\n case 'allowlistCreators':\n return parseAllowlist(value);\n case 'baseUrl':\n case 'publicShelfUrl':\n case 'rpcUrl':\n return parseHttpUrl(value);\n case 'shelfBypassSecret':\n // A free string: it is whatever Vercel generated. Empty clears it, which\n // is how team mode is turned back off.\n return value.trim();\n case 'evalCohort':\n return parseBoolean(value);\n case 'bazaarRegistries':\n return parseRegistryList(value);\n }\n}\n\n/** \"\" clears to []; comma-split, each entry an absolute http(s) URL. */\nfunction parseRegistryList(value: string): string[] {\n return value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0)\n .map((entry) => parseHttpUrl(entry));\n}\n\n// Boolean settings accept both on/off and true/false.\nfunction parseBoolean(value: string): boolean {\n if (value === 'true' || value === 'on') return true;\n if (value === 'false' || value === 'off') return false;\n throw new CliError('USAGE', `Invalid boolean value: ${JSON.stringify(value)}`, {\n fix: 'Use \"on\" or \"off\" (or \"true\"/\"false\").',\n });\n}\n\nfunction parseAllowlist(value: string): string[] {\n // \"\" clears to []; comma-split, trim, drop empties. Reject an entry with\n // internal whitespace — a creator handle/address is a single token.\n const entries = value\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n for (const entry of entries) {\n if (/\\s/.test(entry)) {\n throw new CliError('USAGE', `Invalid creator entry: ${JSON.stringify(entry)}`, {\n fix: 'Creator entries cannot contain spaces; separate multiple with commas.',\n });\n }\n }\n return entries;\n}\n\nfunction parseHttpUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new CliError('USAGE', `Invalid URL: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n if (url.protocol !== 'http:' && url.protocol !== 'https:') {\n throw new CliError('USAGE', `URL must be http or https: ${JSON.stringify(value)}`, {\n fix: `Pass an absolute http(s) URL like ${PRODUCTION_ORIGIN}.`,\n });\n }\n return value;\n}\n\n/**\n * Apply `merge` to the raw file and write it back atomically. Uses the partial\n * schema and writeFileAtomic (not writeConfig, which would materialize every\n * default into the file and corrupt provenance). loadRawConfig surfaces a\n * corrupt existing file as CONFIG_INVALID, which propagates.\n *\n * The whole read-merge-write runs under a cross-process file lock: without it two\n * concurrent `config set` on different keys race on the read, and the last writer\n * drops the other's update (worst case, a zeroed maxAutoSpend resurrected). The\n * data dir is ensured first so the lock's mkdir has a parent on a fresh install.\n */\nasync function persist(\n dir: string,\n merge: (existing: PartialConfig) => PartialConfig,\n): Promise<void> {\n await mkdir(dir, { recursive: true, mode: 0o700 });\n const lockPath = `${configPath(dir)}.lock`;\n try {\n await withFileLock(lockPath, async () => {\n const existing = await loadRawConfig(dir);\n const merged = merge(existing);\n const validated = RawConfigSchema.parse(merged);\n // 0600, matching lib/config.ts's `writeConfig`: this file holds\n // `shelfBypassSecret`, and this is the writer `config set` uses to put it\n // there. See that function for why dirMode alone is not enough.\n await writeFileAtomic(configPath(dir), `${JSON.stringify(validated, null, 2)}\\n`, {\n mode: 0o600,\n dirMode: 0o700,\n });\n });\n } catch (err) {\n // A lock timeout is not the user's malformed input; surface it as INTERNAL with\n // the one manual step (there is no auto-steal), keeping the JSON error contract.\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\nfunction formatLine(key: string, entry: RenderedSetting): string {\n const label = key.padEnd(KEY_WIDTH);\n // A router key from a project names its file: which of several is in force is the question.\n const where =\n entry.path !== undefined && (entry.source === 'project' || entry.source === 'local')\n ? ` ${entry.path}`\n : '';\n return ` ${label} ${displayValue(entry)} ${styleText('dim', `(${entry.source}${where})`)}`;\n}\n\n/** The list variant: the value line, a dim description, and an optional dim note. */\nfunction describedLine(key: string, entry: RenderedSetting, note?: string): string {\n const description = KEY_DESCRIPTIONS[key];\n let line = formatLine(key, entry);\n if (description !== undefined) line += ` ${styleText('dim', `- ${description}`)}`;\n return withNote(line, note);\n}\n\n/** Append a dim parenthetical note (e.g. the full-auto downgrade) when present. */\nfunction withNote(line: string, note?: string): string {\n return note !== undefined ? `${line} ${styleText('dim', `(${note})`)}` : line;\n}\n\n/**\n * The `publish.mode` line gains a downgrade note when the effective mode came from\n * a committed `.tenjin.json` asking for `full-auto` (the loosening gate demoted it\n * to `auto`). Human-only; the machine `data` shape is unchanged.\n */\nfunction downgradeNote(key: PublishConfigKey, settings: EffectiveSettings): string | undefined {\n if (key !== 'publish.mode' || settings.publishMode.downgradedWarning === undefined) {\n return undefined;\n }\n return 'downgraded from full-auto: committed .tenjin.json (gitignore it to opt in)';\n}\n\nfunction displayValue(entry: RenderedSetting): string {\n const { value } = entry;\n if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '(empty)';\n if (typeof value === 'boolean') return value ? 'true' : 'false'; // evalCohort\n if (value === null) return 'none (no daily limit)';\n if (typeof value === 'object') return `${value.usd} USD`; // Money (spend keys)\n return value; // 'always', baseUrl, rpcUrl\n}\n","import { existsSync, statSync } from 'node:fs';\nimport { constants, open } from 'node:fs/promises';\nimport type { FileHandle } from 'node:fs/promises';\nimport { hasCode } from './errno';\nimport { delimiter, join } from 'node:path';\nimport { SKILL_NAMES } from './skills-source';\nimport type { SkillName } from './skills-source';\nimport type { Harness } from '../adapters/types';\n\n/**\n * CLI_SKILL_NAMES are the thin adapter skills (roadmap C1), both required for the\n * CLI to be usable from a harness; HOSTED_SKILL_NAME is the zero-install\n * curriculum mirror (roadmap G4), typed as their complement so a rename in\n * skills-source.ts is a compile error here rather than a silently-always-false\n * `cliSkillsWired`.\n */\nexport const CLI_SKILL_NAMES = [\n 'tenjin-search',\n 'tenjin-publish',\n] as const satisfies readonly SkillName[];\nexport type CliSkillName = (typeof CLI_SKILL_NAMES)[number];\nexport type HostedSkillName = Exclude<SkillName, CliSkillName>;\nexport const HOSTED_SKILL_NAME: HostedSkillName = 'tenjin';\n\nexport type NotInvocableReason = 'disabled' | 'unreadable';\n\nexport interface SkillWiring {\n name: string;\n present: boolean;\n /** Undefined when absent. False means on disk yet never surfaced to the model. */\n modelInvocable?: boolean;\n reason?: NotInvocableReason;\n}\n\n/**\n * One directory's verdict. `shadowed` and `partial` are actionable; `hosted-only`\n * is a working zero-install machine, not a defect; `empty` is not a Tenjin dir.\n */\nexport type DirState = 'empty' | 'hosted-only' | 'partial' | 'shadowed' | 'wired';\n\nexport interface HarnessWiring {\n dir: string;\n exists: boolean;\n skills: SkillWiring[];\n state: DirState;\n}\n\n/** Every skills directory a harness on this machine reads. */\nexport function skillsDirsFor(home: string): string[] {\n return [join(home, '.claude', 'skills'), join(home, '.agents', 'skills')];\n}\n\n/** The skills directory a real harness reads. */\nexport function harnessTargetDir(home: string, harness: Harness): string {\n if (harness === 'claude') return join(home, '.claude', 'skills');\n return join(home, '.agents', 'skills');\n}\n\n/**\n * The `--harness` value that targets `dir`. A Claude-only machine never targets\n * ~/.agents/skills by default, so a bare `tenjin install` cannot clear a problem\n * found there.\n */\nexport function harnessFlagFor(home: string, dir: string): Harness {\n if (dir === join(home, '.claude', 'skills')) return 'claude';\n return 'codex';\n}\n\n/**\n * Why we think `harness` is on this machine: its home dir (~/.claude, ~/.codex) and\n * its binary on PATH. Single-sourced so `install` picks its targets and `doctor`\n * decides which directories MUST be wired from the same two probes — a directory no\n * harness here reads is a leftover, not a defect.\n */\nexport function harnessDetectedBy(\n home: string,\n harness: Harness,\n which: (bin: string) => boolean,\n): string[] {\n const reasons: string[] = [];\n if (existsSync(join(home, `.${harness}`))) reasons.push('home-dir');\n if (which(harness)) reasons.push('binary');\n return reasons;\n}\n\nexport interface HarnessPresence {\n claude: boolean;\n codex: boolean;\n}\n\nexport function detectHarnesses(home: string, which: (bin: string) => boolean): HarnessPresence {\n return {\n claude: harnessDetectedBy(home, 'claude', which).length > 0,\n codex: harnessDetectedBy(home, 'codex', which).length > 0,\n };\n}\n\n/**\n * Does a harness ON THIS MACHINE read `dir`? Claude Code reads ~/.claude/skills and\n * Codex reads ~/.agents/skills, so a wired .agents does NOT make Claude Code wired:\n * the question has to be asked per directory.\n */\nexport function harnessReads(home: string, dir: string, present: HarnessPresence): boolean {\n if (harnessFlagFor(home, dir) === 'claude') return present.claude;\n return present.codex;\n}\n\n/**\n * Did the last settled install selection name `dir` on purpose? Detection is a\n * current machine fact; `requested` is the operator's answer and outranks it.\n */\nexport function harnessRequested(\n home: string,\n dir: string,\n requested: readonly Harness[],\n): boolean {\n return requested.some((h) => harnessTargetDir(home, h) === dir);\n}\n\n/**\n * Is `dir` this machine's business at all? Once the operator has settled an install\n * selection, that answer is authoritative. Detection is only the fallback for homes\n * that predate the selection record. `harnessPresent` remains a separate detection\n * fact for reporting.\n */\nexport function harnessInPlay(\n home: string,\n dir: string,\n present: HarnessPresence,\n requested: readonly Harness[],\n): boolean {\n if (requested.length > 0) return harnessRequested(home, dir, requested);\n return harnessReads(home, dir, present);\n}\n\n/**\n * Is `bin` a real executable file on PATH? Gates on statSync().isFile() so a\n * same-named DIRECTORY on PATH never false-positives as the binary, and probes the\n * PATHEXT extensions on win32 where the real binary is `claude.cmd`/`claude.exe`\n * rather than a bare `claude`.\n */\nexport function onPath(bin: string, env: NodeJS.ProcessEnv): boolean {\n const raw = env.PATH ?? '';\n const exts =\n process.platform === 'win32'\n ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter((e) => e.length > 0)]\n : [''];\n for (const part of raw.split(delimiter)) {\n if (part.length === 0) continue;\n for (const ext of exts) {\n if (isFile(join(part, bin + ext))) return true;\n }\n }\n return false;\n}\n\nfunction isFile(p: string): boolean {\n try {\n return statSync(p).isFile();\n } catch {\n return false;\n }\n}\n\nexport async function readHarnessWiring(dir: string): Promise<HarnessWiring> {\n const exists = existsSync(dir);\n const skills: SkillWiring[] = [];\n for (const name of SKILL_NAMES) skills.push(await readSkillWiring(dir, name));\n return { dir, exists, skills, state: classify(skills) };\n}\n\nexport async function readAllWiring(home: string): Promise<HarnessWiring[]> {\n const out: HarnessWiring[] = [];\n for (const dir of skillsDirsFor(home)) out.push(await readHarnessWiring(dir));\n return out;\n}\n\nfunction classify(skills: SkillWiring[]): DirState {\n const cli = CLI_SKILL_NAMES.map((n) => skills.find((s) => s.name === n)).filter(\n (s) => s?.present === true,\n );\n if (cli.length === 0) return skills.some((s) => s.present) ? 'hosted-only' : 'empty';\n if (cli.some((s) => s?.modelInvocable === false)) return 'shadowed';\n return cli.length === CLI_SKILL_NAMES.length ? 'wired' : 'partial';\n}\n\n/**\n * What reading a SKILL.md found. A skill path is operator-controlled, so it is not\n * necessarily a file at all.\n */\nexport type SkillFileRead =\n | { kind: 'ok'; bytes: Buffer }\n | { kind: 'absent' }\n | { kind: 'not-regular' }\n | { kind: 'unreadable'; err: unknown };\n\n/**\n * Read a SKILL.md through ONE descriptor, and only when it is a regular file.\n *\n * `readFile` on a FIFO blocks until a writer appears, and on a character device it\n * streams without end; neither call fails, so no error handling reaches them. A\n * pipe at a wired SKILL.md path hung `tenjin doctor` and `tenjin install` past\n * SIGTERM. Opening non-blocking returns immediately whatever the node type is,\n * `fstat` on that descriptor says what it actually is, and only a regular file is\n * read. Checking the pathname and then reading the pathname would let the two\n * answer about different files.\n *\n * O_NONBLOCK does not exist on Windows, where it degrades to 0; FIFOs are not a\n * meaningful case there.\n */\nexport async function readSkillFile(path: string): Promise<SkillFileRead> {\n let handle: FileHandle;\n try {\n handle = await open(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));\n } catch (err) {\n if (hasCode(err, 'ENOENT')) return { kind: 'absent' };\n return { kind: 'unreadable', err };\n }\n try {\n if (!(await handle.stat()).isFile()) return { kind: 'not-regular' };\n return { kind: 'ok', bytes: await handle.readFile() };\n } catch (err) {\n return { kind: 'unreadable', err };\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\nasync function readSkillWiring(dir: string, name: string): Promise<SkillWiring> {\n const read = await readSkillFile(join(dir, name, 'SKILL.md'));\n if (read.kind === 'absent') return { name, present: false };\n // A pipe or a device is there, but it is not a skill and must never be read as\n // one; `unreadable` is the state that already describes \"present, unusable\".\n if (read.kind !== 'ok')\n return { name, present: true, modelInvocable: false, reason: 'unreadable' };\n const text = read.bytes.toString('utf8');\n if (isModelInvocationDisabled(text)) {\n return { name, present: true, modelInvocable: false, reason: 'disabled' };\n }\n return { name, present: true, modelInvocable: true };\n}\n\n/** YAML 1.1 truthy spellings a harness frontmatter parser may accept. */\nconst YAML_TRUE = /^(?:true|yes|on)$/i;\n\n/**\n * Deliberately not a general YAML parse: only the leading `---` block is read,\n * because this repo's own skills discuss the key in prose and a whole-file match\n * would call a working skill disabled.\n */\nexport function isModelInvocationDisabled(skillMd: string): boolean {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return false;\n return frontmatter.some((line) => {\n const m = /^disable-model-invocation:\\s*(.+?)\\s*$/.exec(line.trim());\n if (m === null) return false;\n // Strip an inline `# comment` and optional quotes before testing truthiness.\n const value = (m[1] ?? '').replace(/\\s+#.*$/, '').replace(/^[\"']|[\"']$/g, '');\n return YAML_TRUE.test(value);\n });\n}\n\n/**\n * The `name:` a SKILL.md declares in its leading frontmatter, or null when it\n * declares none. It is what a harness registers the skill AS, so it is also the\n * cheapest evidence that a file at one of our paths is one of ours: the\n * unattended self-heal refuses to overwrite a same-named third-party skill.\n */\nexport function skillFrontmatterName(skillMd: string): string | null {\n const frontmatter = extractFrontmatter(skillMd);\n if (frontmatter === null) return null;\n for (const line of frontmatter) {\n const m = /^name:\\s*(.+?)\\s*$/.exec(line);\n if (m !== null) return (m[1] ?? '').replace(/^[\"']|[\"']$/g, '');\n }\n return null;\n}\n\nfunction extractFrontmatter(text: string): string[] | null {\n // Tolerate a UTF-8 BOM, CRLF, and leading blank lines before the opening fence.\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 if (end === -1) return null;\n return lines.slice(open + 1, end);\n}\n\nexport function cliSkillsWired(wiring: HarnessWiring): boolean {\n return wiring.state === 'wired';\n}\n\nexport function missingCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter(\n (name) => wiring.skills.find((x) => x.name === name)?.present !== true,\n );\n}\n\nexport function shadowedCliSkills(wiring: HarnessWiring): string[] {\n return CLI_SKILL_NAMES.filter((name) => {\n const s = wiring.skills.find((x) => x.name === name);\n return s?.present === true && s.modelInvocable === false;\n });\n}\n\nexport function anyTenjinSkill(wiring: HarnessWiring): boolean {\n return wiring.state !== 'empty';\n}\n","import { existsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { CliError } from './errors';\n\n/**\n * The packaged skills `install` copies into every target harness. All three go to\n * every target: `tenjin` (the zero-install curriculum, works with no CLI),\n * `tenjin-search` and `tenjin-publish` (thin CLI adapters). Order is the install\n * order and the human-render order.\n */\nexport const SKILL_NAMES = ['tenjin-search', 'tenjin-publish', 'tenjin'] as const;\nexport type SkillName = (typeof SKILL_NAMES)[number];\n\nexport const RETIRED_SKILL_NAMES = ['tenjin-pay'] as const;\n\n/** Retired names remain known to uninstall, but are never packaged or healed. */\nexport const PACKAGED_SKILL_NAMES = [...SKILL_NAMES] as const;\n\n/**\n * Every file a packaged skill ships, per skill, as a path relative to the skill\n * directory.\n *\n * DECLARED rather than discovered, because `uninstall` needs it on a machine\n * where the packaged source may be gone or unreadable, and \"remove exactly the\n * files this package wrote\" is not a question it can answer by listing the\n * operator's directory — everything else in there is theirs. `install` still\n * copies the real tree; a test pins this list against it, so a new reference\n * file that nobody declares fails the build rather than becoming litter no\n * uninstall can reclaim.\n *\n */\nexport const SHIPPED_SKILL_FILES: Record<\n SkillName | (typeof RETIRED_SKILL_NAMES)[number],\n readonly string[]\n> = {\n 'tenjin-search': ['SKILL.md', 'references/permissions.md'],\n 'tenjin-publish': ['SKILL.md', 'references/maintain.md'],\n tenjin: ['SKILL.md'],\n 'tenjin-pay': ['SKILL.md'],\n};\n\n// A `skills/` directory is the real one iff it holds `tenjin/SKILL.md`; a bare\n// `skills/` created for some other reason up the tree can't false-positive.\nconst SENTINEL = join('tenjin', 'SKILL.md');\n\n/**\n * Locate the packaged `skills/` directory by walking up from `startDir`. This has\n * to work in two layouts from one resolver: a global npm install where the module\n * lives in `dist/` with `skills/` a sibling (the `files` array ships it), and a\n * repo/source run where the module is under `src/` and `skills/` sits at the repo\n * root. Walking up until a `skills/` with the sentinel appears covers both without\n * hard-coding either depth. Sync (existsSync) on purpose: this is one-shot path\n * resolution at command start, the same shape as `require.resolve`.\n */\nexport function resolveSkillsSource(startDir: string): string {\n let dir = startDir;\n for (let i = 0; i < 8; i += 1) {\n const candidate = join(dir, 'skills');\n if (existsSync(join(candidate, SENTINEL))) return candidate;\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new CliError('INTERNAL', 'Could not locate the packaged Tenjin skills directory', {\n fix: 'Reinstall tenjin-cli; the published package must ship the skills/ directory (files array).',\n details: { startDir },\n });\n}\n","import type { Harness, HarnessAdapter } from '../adapters/types';\nimport { registeredHooks } from './harness-hooks';\nimport { detectHarnesses, harnessInPlay, harnessTargetDir, onPath } from './skill-wiring';\n\n/**\n * Is one adapter part of this machine's settled installation?\n *\n * An explicit install selection outranks current detection; homes predating\n * that record fall back to the harness directory/PATH probes. Registered hook\n * entries are final evidence, so config and doctor agree even if the binary or\n * home-directory marker later moves.\n */\nexport async function installedHarnessInPlay(\n adapter: HarnessAdapter,\n home: string,\n dataDir: string,\n options: {\n env?: NodeJS.ProcessEnv;\n which?: (bin: string) => boolean;\n requested?: readonly Harness[];\n } = {},\n): Promise<boolean> {\n const env = options.env ?? process.env;\n const which = options.which ?? ((bin: string) => onPath(bin, env));\n if (\n harnessInPlay(\n home,\n harnessTargetDir(home, adapter.id),\n detectHarnesses(home, which),\n options.requested ?? [],\n )\n ) {\n return true;\n }\n return (await registeredHooks(adapter, home, dataDir, env)).entries > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,WAAAA,gBAAe;AACxB,SAAS,iBAAiB;;;ACH1B,SAAS,YAAY,gBAAgB;AACrC,SAAS,WAAW,YAAY;AAGhC,SAAS,WAAW,QAAAC,aAAY;;;ACHhC,SAAS,SAAS,YAAY;AASvB,IAAM,cAAc,CAAC,iBAAiB,kBAAkB,QAAQ;AAGhE,IAAM,sBAAsB,CAAC,YAAY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MAAc,MAAuB;AACrD,SAAO,SAAS,SAAY,GAAG,IAAI,KAAK,UAAU,OAAO,IAAI,IAAI,GAAG,CAAC,KAAK;AAC5E;AAOA,SAAS,cAAc,KAAuB,UAAiD;AAC7F,MAAI,QAAQ,kBAAkB,SAAS,YAAY,sBAAsB,QAAW;AAClF,WAAO;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,aAAa,OAAgC;AACpD,QAAM,EAAE,MAAM,IAAI;AAClB,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,SAAS,IAAI,MAAM,KAAK,IAAI,IAAI;AACvE,MAAI,OAAO,UAAU,UAAW,QAAO,QAAQ,SAAS;AACxD,MAAI,UAAU,KAAM,QAAO;AAC3B,MAAI,OAAO,UAAU,SAAU,QAAO,GAAG,MAAM,GAAG;AAClD,SAAO;AACT;","names":["dirname","join","join","open","settings","entry","dirname"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __tenjinCreateRequire } from 'node:module'; const require = __tenjinCreateRequire(import.meta.url);
|
|
2
2
|
import {
|
|
3
3
|
getUsdcBalance
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-AQRUD5GQ.js";
|
|
5
5
|
import {
|
|
6
6
|
commitLocalWallet,
|
|
7
7
|
createLocalWallet,
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
verifyAndPreserveOutgoingWallet,
|
|
15
15
|
walletExistsError,
|
|
16
16
|
walletFileExists
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-YVODPFTL.js";
|
|
18
18
|
import {
|
|
19
19
|
LockTimeoutError,
|
|
20
20
|
withFileLock
|
|
@@ -25,13 +25,13 @@ import {
|
|
|
25
25
|
import {
|
|
26
26
|
loadRawConfig,
|
|
27
27
|
resolveSettings
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-W3LVZ2EN.js";
|
|
29
29
|
import {
|
|
30
30
|
CliError
|
|
31
31
|
} from "./chunk-JLEF5WHM.js";
|
|
32
32
|
import {
|
|
33
33
|
walletPath
|
|
34
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-K6AXXYCG.js";
|
|
35
35
|
|
|
36
36
|
// src/commands/wallet.ts
|
|
37
37
|
import { mkdir } from "node:fs/promises";
|
|
@@ -239,4 +239,4 @@ export {
|
|
|
239
239
|
runWalletShow,
|
|
240
240
|
runWalletBalance
|
|
241
241
|
};
|
|
242
|
-
//# sourceMappingURL=chunk-
|
|
242
|
+
//# sourceMappingURL=chunk-PJEG2JIJ.js.map
|
|
@@ -132,6 +132,14 @@ async function claimRedirect(dataDir, sessionId, agentId, target, now = Date.now
|
|
|
132
132
|
return false;
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
|
+
async function redirectClaimed(dataDir, sessionId, agentId, target, now = Date.now()) {
|
|
136
|
+
const window = Math.floor(now / EXPIRY_MS);
|
|
137
|
+
for (const at of [window, window - 1]) {
|
|
138
|
+
const stamp = await readStamp(redirectPath(dataDir, sessionId, agentId, target, at));
|
|
139
|
+
if (stamp !== null && now - stamp.at <= EXPIRY_MS) return true;
|
|
140
|
+
}
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
135
143
|
async function resolveProgressSession(dataDir, opts = {}) {
|
|
136
144
|
const now = opts.now ?? Date.now();
|
|
137
145
|
const root = join(dataDir, PROGRESS_DIR);
|
|
@@ -359,10 +367,11 @@ export {
|
|
|
359
367
|
augmentOf,
|
|
360
368
|
claimQuery,
|
|
361
369
|
claimRedirect,
|
|
370
|
+
redirectClaimed,
|
|
362
371
|
writeProgress,
|
|
363
372
|
openLookupFooter,
|
|
364
373
|
pruneProgress,
|
|
365
374
|
pruneSessions,
|
|
366
375
|
renderProgress
|
|
367
376
|
};
|
|
368
|
-
//# sourceMappingURL=chunk-
|
|
377
|
+
//# sourceMappingURL=chunk-QF4SSCQV.js.map
|