github-router 0.3.321 → 0.3.322
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/dist/{aic-ledger-BrDqsuge.js → aic-ledger-BW3zMiCx.js} +19 -2
- package/dist/aic-ledger-BW3zMiCx.js.map +1 -0
- package/dist/{attribution-settings-DHWo0lyG.js → attribution-settings-z-U2L7ab.js} +4 -4
- package/dist/{attribution-settings-DHWo0lyG.js.map → attribution-settings-z-U2L7ab.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-uAFPKvuS.js → claude-DtWf7DEw.js} +8 -8
- package/dist/{claude-uAFPKvuS.js.map → claude-DtWf7DEw.js.map} +1 -1
- package/dist/{codex-CVHdye0h.js → codex-CDtFT-Qp.js} +4 -4
- package/dist/{codex-CVHdye0h.js.map → codex-CDtFT-Qp.js.map} +1 -1
- package/dist/{copilot-discount-BnJkEojk.js → copilot-discount-I6BrT7QE.js} +2 -2
- package/dist/{copilot-discount-BnJkEojk.js.map → copilot-discount-I6BrT7QE.js.map} +1 -1
- package/dist/engine-DA5laGIh.js +2 -0
- package/dist/{gate-discovery-DUBuxiLb.js → gate-discovery-j_hQ1IPc.js} +2 -2
- package/dist/{gate-discovery-DUBuxiLb.js.map → gate-discovery-j_hQ1IPc.js.map} +1 -1
- package/dist/{internal-aic-status-Dc2JQDsX.js → internal-aic-status-CKXxxb30.js} +3 -3
- package/dist/{internal-aic-status-Dc2JQDsX.js.map → internal-aic-status-CKXxxb30.js.map} +1 -1
- package/dist/{internal-stop-hook-DCjYE2x0.js → internal-stop-hook-BGTPRCtO.js} +2 -2
- package/dist/{internal-stop-hook-DCjYE2x0.js.map → internal-stop-hook-BGTPRCtO.js.map} +1 -1
- package/dist/main.js +6 -6
- package/dist/{peer-mcp-personas-BerVEkZ9.js → peer-mcp-personas-Gb0LfII0.js} +10 -7
- package/dist/{peer-mcp-personas-BerVEkZ9.js.map → peer-mcp-personas-Gb0LfII0.js.map} +1 -1
- package/dist/{provision-o4bXbsvB.js → provision-DagZEkdZ.js} +2 -2
- package/dist/{provision-o4bXbsvB.js.map → provision-DagZEkdZ.js.map} +1 -1
- package/dist/{serve-DSL2Fcnc.js → serve-DOMsmIk-.js} +5 -5
- package/dist/{serve-DSL2Fcnc.js.map → serve-DOMsmIk-.js.map} +1 -1
- package/dist/{server-setup-CXXKmPIE.js → server-setup-DQVRJluz.js} +23 -12
- package/dist/server-setup-DQVRJluz.js.map +1 -0
- package/dist/{start-Cl_1UMg_.js → start-CqSFR_s8.js} +3 -3
- package/dist/{start-Cl_1UMg_.js.map → start-CqSFR_s8.js.map} +1 -1
- package/package.json +1 -1
- package/dist/aic-ledger-BrDqsuge.js.map +0 -1
- package/dist/engine-57iIqICe.js +0 -2
- package/dist/server-setup-CXXKmPIE.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-stop-hook-DCjYE2x0.js","names":[],"sources":["../src/internal-stop-hook.ts"],"sourcesContent":["/**\n * The internal `internal-stop-hook` subcommand: the executable a spawned Claude\n * Code session's Stop hook invokes (registered into the mirrored settings.json by\n * the launcher when `GH_ROUTER_ENABLE_STOP_GATE` is set). It reads Claude Code's\n * hook payload from stdin, runs the SEALED structural gate over the session's\n * working-tree diff, and maps the result to the hook exit contract: exit 2 (with\n * the reason on stderr) blocks the stop so the model fixes the failure; exit 0\n * allows it. The `stop_hook_active` loop guard (in `decideStopHook`) guarantees\n * it can never wedge the session.\n *\n * All decision logic lives in `decideStopHook` (pure, unit-tested); this wrapper\n * only does stdin read + the live `git diff` capture + the exit. The live firing\n * is verified by the gated E2E (it needs a real spawned session).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { spawn } from \"node:child_process\"\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv, runCommandCapture } from \"./lib/exec\"\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\nimport { liveExec } from \"./lib/orchestration\"\nimport { readDiscoveredGate } from \"./lib/orchestration/gate-discovery\"\nimport { checksForDescriptor, descriptorHash, parseGateDescriptor, type GateDescriptor } from \"./lib/orchestration/harness-parse\"\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decideStopHook,\n fileBlockBudget,\n launchBaselineKey,\n stopGateId,\n stopReviewEnabled,\n type StopReviewContext,\n} from \"./lib/orchestration/stop-gate-hook\"\nimport {\n fileBaselineStore,\n fileLastPromptStore,\n fileReviewDebounce,\n repoRoot,\n stopGateEnabledForRepo,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { parseIntEnv } from \"./lib/exec\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Max diff bytes scanned for gate-weakening: a hard cap so a huge generated diff\n * (e.g. a lockfile) can never OOM or stall the hook. */\nconst MAX_DIFF_BYTES = 2 * 1024 * 1024\n\n/** Build a tiny synthetic diff for untracked paths so the weakening scan sees\n * their contents too. No index mutation (`git add -N`) is needed. */\nasync function captureUntrackedDiff(cwd: string, paths: string[]): Promise<string> {\n const chunks: string[] = []\n let bytes = 0\n for (const untrackedPath of paths) {\n const result = await runCommandCapture(\n [\"git\", \"diff\", \"--no-index\", \"--\", \"/dev/null\", untrackedPath],\n { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES },\n )\n // `git diff --no-index` returns 1 when differences exist; anything else is an\n // actual failure. A truncated untracked diff is unknown, never \"no diff\".\n if (result.code !== 1 || result.truncated) throw new Error(`git diff for untracked file failed with exit ${result.code}`)\n bytes += Buffer.byteLength(result.stdout, \"utf8\")\n if (bytes > MAX_DIFF_BYTES) throw new Error(\"git working-tree capture exceeded its size limit\")\n chunks.push(result.stdout)\n }\n return chunks.join(\"\")\n}\n\n/** Capture every working-tree change WITHOUT mutating the user's index (no\n * `git add -N`). `git diff HEAD` covers staged + unstaged tracked changes;\n * `git ls-files --others` catches untracked files and each is diffed against an\n * empty file so gate-weakening in new tests is visible. Git failures/truncation\n * reject, so the decision layer runs the full checks instead of mistaking an\n * unknown tree for a no-diff turn. */\nexport async function captureStopGateDiff(cwd: string): Promise<string> {\n const [diffResult, untrackedResult] = await Promise.all([\n runCommandCapture([\"git\", \"diff\", \"HEAD\"], { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES }),\n runCommandCapture([\"git\", \"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\n cwd,\n timeoutMs: 5_000,\n maxStdoutBytes: MAX_DIFF_BYTES,\n }),\n ])\n if (diffResult.code !== 0) throw new Error(`git diff failed with exit ${diffResult.code}`)\n if (untrackedResult.code !== 0) throw new Error(`git ls-files failed with exit ${untrackedResult.code}`)\n if (diffResult.truncated || untrackedResult.truncated) throw new Error(\"git working-tree capture exceeded its size limit\")\n\n const untrackedPaths = untrackedResult.stdout.split(\"\\0\").filter(Boolean)\n if (untrackedPaths.length === 0) return diffResult.stdout\n const untrackedDiff = await captureUntrackedDiff(cwd, untrackedPaths)\n if (Buffer.byteLength(diffResult.stdout, \"utf8\") + Buffer.byteLength(untrackedDiff, \"utf8\") > MAX_DIFF_BYTES) {\n throw new Error(\"git working-tree capture exceeded its size limit\")\n }\n return diffResult.stdout + untrackedDiff\n}\n\n/** Flush a message to stderr before exiting (process.exit can drop an unflushed\n * write; the model reads this stderr on a block). */\nasync function writeStderr(msg: string): Promise<void> {\n await new Promise<void>((resolve) => {\n process.stderr.write(msg, () => resolve())\n })\n}\n\n/**\n * Fire-and-forget spawn of the detached background reviewer. The payload (which\n * includes the up-to-2-MiB diff) is written to a temp file SYNCHRONOUSLY before\n * the spawn — a pipe to the child's stdin would race the parent's `process.exit`\n * and could deliver a truncated diff. The child reads the file (path passed via\n * `GH_ROUTER_STOP_REVIEW_PAYLOAD`), unlinks it, and inherits the proxy URL/nonce\n * env. Everything is swallowed: the advisory layer never affects the stop.\n */\nfunction spawnStopReview(ctx: StopReviewContext, extras: { prompt: string; transcriptPath: string }): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `payload-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(\n payloadPath,\n JSON.stringify({\n session_id: ctx.sessionId,\n cwd: ctx.cwd,\n diff: ctx.diff,\n prompt: extras.prompt,\n transcript_path: extras.transcriptPath,\n }),\n { mode: 0o600 },\n )\n // Invoke the same binary's `internal-stop-review` subcommand. Preserve the\n // package root when this hook itself runs from the relocated launcher.\n const scriptArgs = process.argv[1] && process.argv[1] !== process.execPath ? [process.argv[1]] : []\n const root = explicitPackageRoot()\n const packageRootArgs = root ? [PACKAGE_ROOT_FLAG, root] : []\n const child = spawn(process.execPath, [...scriptArgs, ...packageRootArgs, \"internal-stop-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_STOP_REVIEW_PAYLOAD: payloadPath },\n })\n // A spawn failure (EAGAIN / EACCES / fork limit) is delivered ASYNCHRONOUSLY\n // via the child's 'error' event, AFTER this synchronous try block exits. With\n // no listener Node escalates it to an uncaughtException — which main.ts turns\n // into process.exit(1), corrupting the Stop hook's exit code. Swallow it here\n // (and drop the now-orphaned payload the child never read) so the advisory\n // spawn truly never affects the stop.\n const orphan = payloadPath\n child.on(\"error\", () => {\n if (orphan) {\n try {\n unlinkSync(orphan)\n } catch {\n /* best-effort */\n }\n }\n })\n child.unref()\n } catch {\n // Advisory spawn is best-effort; never disrupt the stop. If we wrote the\n // payload file but the spawn failed, drop it so it doesn't orphan (the\n // child — which would normally unlink it — never started).\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\n/** The checks for a resolved descriptor: sealed descriptors resolve their sealed\n * command set; parsed/discovered carry their own. */\ntype ResolveChecks = NonNullable<Parameters<typeof decideStopHook>[0][\"resolveChecks\"]>\n\n/**\n * Build the dynamic `resolveChecks` for the live Stop hook, per the env the\n * launcher set:\n * - GH_ROUTER_STOP_GATE_PARSED → re-derive the deterministic parser at the\n * stop-time tree (stateless, no cache);\n * - GH_ROUTER_STOP_GATE_DISCOVERED → read the cached evidence-pinned record.\n * Both pin the checks to the descriptor's `workdir` (the repo root) and compute\n * the launch-stable baseline key so the launch-captured (pre-mutation) baseline\n * is read. Any miss → null → the hook fails OPEN.\n */\nfunction buildResolveChecks(mode: \"parsed\" | \"discovered\"): ResolveChecks {\n const includeTests = parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_RUN_TESTS) === true\n return async (cwd: string) => {\n const root = await repoRoot(cwd).catch(() => cwd)\n let descriptor: GateDescriptor | null = null\n if (mode === \"parsed\") {\n descriptor = await parseGateDescriptor(root, { includeTests }).catch(() => null)\n } else {\n const rec = await readDiscoveredGate(root).catch(() => null)\n if (rec) {\n descriptor = {\n kind: \"discovered\",\n checks: rec.checks,\n ecosystem: rec.ecosystem,\n workdir: root,\n evidence: rec.evidence,\n }\n }\n }\n if (!descriptor) return null\n const checks = checksForDescriptor(descriptor)\n if (checks.length === 0) return null\n const descriptorKey = descriptorHash(descriptor)\n const workdir = descriptor.workdir || root\n const token = process.env.GH_ROUTER_STOP_GATE_BASELINE_TOKEN || undefined\n return { checks, workdir, descriptorKey, baselineKey: launchBaselineKey(workdir, descriptorKey, token) }\n }\n}\n\n/** Which dynamic gate mode the launcher armed (sealed → undefined). */\nfunction dynamicMode(): \"parsed\" | \"discovered\" | undefined {\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_PARSED) === true) return \"parsed\"\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_DISCOVERED) === true) return \"discovered\"\n return undefined\n}\n\nexport const internalStopHook = defineCommand({\n meta: {\n name: \"internal-stop-hook\",\n description:\n \"Internal: the structural-gate Stop hook. Reads the Claude Code hook payload on stdin, \"\n + \"runs the sealed gate, exits 2 (blocks the stop) on a red gate or gate-weakening diff.\",\n },\n async run() {\n const stdin = readStdin()\n // The advisory review (hook V2) is wired only when it's enabled AND the\n // launcher injected the proxy URL/nonce. It is side-effect-only: the\n // deterministic gate below is unchanged and remains the only blocker.\n const reviewEnabled = stopReviewEnabled() && hookMcpRuntimeFromEnv() !== undefined\n let transcriptPath = \"\"\n let userPrompt = \"\"\n if (reviewEnabled) {\n // Parse the payload once for the transcript pointer + the session id used\n // to look up the user's last prompt (the Stop payload carries no prompt;\n // the UserPromptSubmit hook stashed it). Best-effort — a parse miss just\n // means the reviewer judges against the diff alone.\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const obj = p as { transcript_path?: unknown; session_id?: unknown }\n transcriptPath = typeof obj.transcript_path === \"string\" ? obj.transcript_path : \"\"\n const sid = typeof obj.session_id === \"string\" ? obj.session_id : \"\"\n if (sid) {\n userPrompt = (await fileLastPromptStore(stopReviewStateDir()).read(sid).catch(() => null)) ?? \"\"\n }\n }\n } catch {\n /* tolerate a non-JSON stdin */\n }\n }\n\n let decision: { exitCode: 0 | 2; stderr?: string }\n try {\n const timeoutEnv = parseIntEnv(process.env.GH_ROUTER_STOP_GATE_TIMEOUT_MS)\n const mode = dynamicMode()\n decision = await decideStopHook({\n stdin,\n gateId: stopGateId(),\n exec: liveExec,\n captureDiff: captureStopGateDiff,\n fallbackCwd: process.cwd(),\n budget: fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\")),\n baseline: fileBaselineStore(path.join(tmpdir(), \"gh-router-stopgate-baseline\")),\n isEnabledForRepo: (cwd) => stopGateEnabledForRepo(cwd),\n resolveChecks: mode ? buildResolveChecks(mode) : undefined,\n // parseIntEnv already rejects non-positive / non-integer / truncating\n // values, so undefined here means \"use the built-in default\".\n timeoutMs: timeoutEnv,\n reviewDebounce: reviewEnabled ? fileReviewDebounce(stopReviewStateDir()) : undefined,\n spawnReview: reviewEnabled\n ? (ctx) => spawnStopReview(ctx, { prompt: userPrompt, transcriptPath })\n : undefined,\n })\n } catch {\n // Fail OPEN on ANY unexpected error: a Stop hook must never wedge the\n // session, so an internal crash allows the stop (exit 0) rather than\n // surfacing a non-blocking error or a hang.\n process.exitCode = 0\n return\n }\n // Write any stderr the decision carries — both the exit-2 block reason AND\n // the LOUD exit-0 stand-down (max-block budget reached). A clean green stop\n // carries no stderr, so this stays silent on the common path.\n if (decision.stderr) {\n await writeStderr(`${decision.stderr}\\n`)\n }\n // Natural exit: set the code and return. A hard process.exit() races libuv's\n // stdio teardown on Windows (uv_async_send assertion) on the fast-return\n // paths. The detached review child is unref'd and the gate's children are\n // reaped, so no handle keeps the loop alive — the process exits with this\n // code. The exit-2 block contract is preserved (stderr is flushed above).\n process.exitCode = decision.exitCode\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,MAAM,iBAAiB;;;AAIvB,eAAe,qBAAqB,KAAa,OAAkC;CACjF,MAAM,SAAmB,CAAC;CAC1B,IAAI,QAAQ;CACZ,KAAK,MAAM,iBAAiB,OAAO;EACjC,MAAM,SAAS,MAAM,kBACnB;GAAC;GAAO;GAAQ;GAAc;GAAM;GAAa;EAAa,GAC9D;GAAE;GAAK,WAAW;GAAO,gBAAgB;EAAe,CAC1D;EAGA,IAAI,OAAO,SAA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AY;GACzB,WAAW,MAAM,eAAe;IAC9B;IACA,QAAQ,WAAW;IACnB,MAAM;IACN,aAAa;IACb,aAAa,QAAQ,IAAI;IACzB,QAAQ,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC;IACjE,UAAU,kBAAkB,KAAK,KAAK,OAAO,GAAG,6BAA6B,CAAC;IAC9E,mBAAmB,QAAQ,uBAAuB,GAAG;IACrD,eAAe,OAAO,mBAAmB,IAAI,IAAI,KAAA;IAGjD,WAAW;IACX,gBAAgB,gBAAgB,mBAAmB,mBAAmB,CAAC,IAAI,KAAA;IAC3E,aAAa,iBACR,QAAQ,gBAAgB,KAAK;KAAE,QAAQ;KAAY;IAAe,CAAC,IACpE,KAAA;GACN,CAAC;EACH,QAAQ;GAIN,QAAQ,WAAW;GACnB;EACF;EAIA,IAAI,SAAS,QACX,MAAM,YAAY,GAAG,SAAS,OAAO,GAAG;EAO1C,QAAQ,WAAW,SAAS;CAC9B;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"internal-stop-hook-BGTPRCtO.js","names":[],"sources":["../src/internal-stop-hook.ts"],"sourcesContent":["/**\n * The internal `internal-stop-hook` subcommand: the executable a spawned Claude\n * Code session's Stop hook invokes (registered into the mirrored settings.json by\n * the launcher when `GH_ROUTER_ENABLE_STOP_GATE` is set). It reads Claude Code's\n * hook payload from stdin, runs the SEALED structural gate over the session's\n * working-tree diff, and maps the result to the hook exit contract: exit 2 (with\n * the reason on stderr) blocks the stop so the model fixes the failure; exit 0\n * allows it. The `stop_hook_active` loop guard (in `decideStopHook`) guarantees\n * it can never wedge the session.\n *\n * All decision logic lives in `decideStopHook` (pure, unit-tested); this wrapper\n * only does stdin read + the live `git diff` capture + the exit. The live firing\n * is verified by the gated E2E (it needs a real spawned session).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { spawn } from \"node:child_process\"\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { parseBoolEnv, runCommandCapture } from \"./lib/exec\"\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\nimport { liveExec } from \"./lib/orchestration\"\nimport { readDiscoveredGate } from \"./lib/orchestration/gate-discovery\"\nimport { checksForDescriptor, descriptorHash, parseGateDescriptor, type GateDescriptor } from \"./lib/orchestration/harness-parse\"\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decideStopHook,\n fileBlockBudget,\n launchBaselineKey,\n stopGateId,\n stopReviewEnabled,\n type StopReviewContext,\n} from \"./lib/orchestration/stop-gate-hook\"\nimport {\n fileBaselineStore,\n fileLastPromptStore,\n fileReviewDebounce,\n repoRoot,\n stopGateEnabledForRepo,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\nimport { parseIntEnv } from \"./lib/exec\"\n\n/**\n * Read the hook payload from stdin SYNCHRONOUSLY (`readFileSync(0)`). An async\n * stdin read leaves an in-flight libuv FS request that, on Windows, races the\n * process teardown and trips a `uv_async_send` assertion; a synchronous read has\n * no such handle. Hooks always receive piped/redirected stdin, so this never\n * blocks (guarded against an interactive TTY, and any error -> \"\").\n */\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\n/** Max diff bytes scanned for gate-weakening: a hard cap so a huge generated diff\n * (e.g. a lockfile) can never OOM or stall the hook. */\nconst MAX_DIFF_BYTES = 2 * 1024 * 1024\n\n/** Build a tiny synthetic diff for untracked paths so the weakening scan sees\n * their contents too. No index mutation (`git add -N`) is needed. */\nasync function captureUntrackedDiff(cwd: string, paths: string[]): Promise<string> {\n const chunks: string[] = []\n let bytes = 0\n for (const untrackedPath of paths) {\n const result = await runCommandCapture(\n [\"git\", \"diff\", \"--no-index\", \"--\", \"/dev/null\", untrackedPath],\n { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES },\n )\n // `git diff --no-index` returns 1 when differences exist; anything else is an\n // actual failure. A truncated untracked diff is unknown, never \"no diff\".\n if (result.code !== 1 || result.truncated) throw new Error(`git diff for untracked file failed with exit ${result.code}`)\n bytes += Buffer.byteLength(result.stdout, \"utf8\")\n if (bytes > MAX_DIFF_BYTES) throw new Error(\"git working-tree capture exceeded its size limit\")\n chunks.push(result.stdout)\n }\n return chunks.join(\"\")\n}\n\n/** Capture every working-tree change WITHOUT mutating the user's index (no\n * `git add -N`). `git diff HEAD` covers staged + unstaged tracked changes;\n * `git ls-files --others` catches untracked files and each is diffed against an\n * empty file so gate-weakening in new tests is visible. Git failures/truncation\n * reject, so the decision layer runs the full checks instead of mistaking an\n * unknown tree for a no-diff turn. */\nexport async function captureStopGateDiff(cwd: string): Promise<string> {\n const [diffResult, untrackedResult] = await Promise.all([\n runCommandCapture([\"git\", \"diff\", \"HEAD\"], { cwd, timeoutMs: 5_000, maxStdoutBytes: MAX_DIFF_BYTES }),\n runCommandCapture([\"git\", \"ls-files\", \"--others\", \"--exclude-standard\", \"-z\"], {\n cwd,\n timeoutMs: 5_000,\n maxStdoutBytes: MAX_DIFF_BYTES,\n }),\n ])\n if (diffResult.code !== 0) throw new Error(`git diff failed with exit ${diffResult.code}`)\n if (untrackedResult.code !== 0) throw new Error(`git ls-files failed with exit ${untrackedResult.code}`)\n if (diffResult.truncated || untrackedResult.truncated) throw new Error(\"git working-tree capture exceeded its size limit\")\n\n const untrackedPaths = untrackedResult.stdout.split(\"\\0\").filter(Boolean)\n if (untrackedPaths.length === 0) return diffResult.stdout\n const untrackedDiff = await captureUntrackedDiff(cwd, untrackedPaths)\n if (Buffer.byteLength(diffResult.stdout, \"utf8\") + Buffer.byteLength(untrackedDiff, \"utf8\") > MAX_DIFF_BYTES) {\n throw new Error(\"git working-tree capture exceeded its size limit\")\n }\n return diffResult.stdout + untrackedDiff\n}\n\n/** Flush a message to stderr before exiting (process.exit can drop an unflushed\n * write; the model reads this stderr on a block). */\nasync function writeStderr(msg: string): Promise<void> {\n await new Promise<void>((resolve) => {\n process.stderr.write(msg, () => resolve())\n })\n}\n\n/**\n * Fire-and-forget spawn of the detached background reviewer. The payload (which\n * includes the up-to-2-MiB diff) is written to a temp file SYNCHRONOUSLY before\n * the spawn — a pipe to the child's stdin would race the parent's `process.exit`\n * and could deliver a truncated diff. The child reads the file (path passed via\n * `GH_ROUTER_STOP_REVIEW_PAYLOAD`), unlinks it, and inherits the proxy URL/nonce\n * env. Everything is swallowed: the advisory layer never affects the stop.\n */\nfunction spawnStopReview(ctx: StopReviewContext, extras: { prompt: string; transcriptPath: string }): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `payload-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(\n payloadPath,\n JSON.stringify({\n session_id: ctx.sessionId,\n cwd: ctx.cwd,\n diff: ctx.diff,\n prompt: extras.prompt,\n transcript_path: extras.transcriptPath,\n }),\n { mode: 0o600 },\n )\n // Invoke the same binary's `internal-stop-review` subcommand. Preserve the\n // package root when this hook itself runs from the relocated launcher.\n const scriptArgs = process.argv[1] && process.argv[1] !== process.execPath ? [process.argv[1]] : []\n const root = explicitPackageRoot()\n const packageRootArgs = root ? [PACKAGE_ROOT_FLAG, root] : []\n const child = spawn(process.execPath, [...scriptArgs, ...packageRootArgs, \"internal-stop-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_STOP_REVIEW_PAYLOAD: payloadPath },\n })\n // A spawn failure (EAGAIN / EACCES / fork limit) is delivered ASYNCHRONOUSLY\n // via the child's 'error' event, AFTER this synchronous try block exits. With\n // no listener Node escalates it to an uncaughtException — which main.ts turns\n // into process.exit(1), corrupting the Stop hook's exit code. Swallow it here\n // (and drop the now-orphaned payload the child never read) so the advisory\n // spawn truly never affects the stop.\n const orphan = payloadPath\n child.on(\"error\", () => {\n if (orphan) {\n try {\n unlinkSync(orphan)\n } catch {\n /* best-effort */\n }\n }\n })\n child.unref()\n } catch {\n // Advisory spawn is best-effort; never disrupt the stop. If we wrote the\n // payload file but the spawn failed, drop it so it doesn't orphan (the\n // child — which would normally unlink it — never started).\n if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\n/** The checks for a resolved descriptor: sealed descriptors resolve their sealed\n * command set; parsed/discovered carry their own. */\ntype ResolveChecks = NonNullable<Parameters<typeof decideStopHook>[0][\"resolveChecks\"]>\n\n/**\n * Build the dynamic `resolveChecks` for the live Stop hook, per the env the\n * launcher set:\n * - GH_ROUTER_STOP_GATE_PARSED → re-derive the deterministic parser at the\n * stop-time tree (stateless, no cache);\n * - GH_ROUTER_STOP_GATE_DISCOVERED → read the cached evidence-pinned record.\n * Both pin the checks to the descriptor's `workdir` (the repo root) and compute\n * the launch-stable baseline key so the launch-captured (pre-mutation) baseline\n * is read. Any miss → null → the hook fails OPEN.\n */\nfunction buildResolveChecks(mode: \"parsed\" | \"discovered\"): ResolveChecks {\n const includeTests = parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_RUN_TESTS) === true\n return async (cwd: string) => {\n const root = await repoRoot(cwd).catch(() => cwd)\n let descriptor: GateDescriptor | null = null\n if (mode === \"parsed\") {\n descriptor = await parseGateDescriptor(root, { includeTests }).catch(() => null)\n } else {\n const rec = await readDiscoveredGate(root).catch(() => null)\n if (rec) {\n descriptor = {\n kind: \"discovered\",\n checks: rec.checks,\n ecosystem: rec.ecosystem,\n workdir: root,\n evidence: rec.evidence,\n }\n }\n }\n if (!descriptor) return null\n const checks = checksForDescriptor(descriptor)\n if (checks.length === 0) return null\n const descriptorKey = descriptorHash(descriptor)\n const workdir = descriptor.workdir || root\n const token = process.env.GH_ROUTER_STOP_GATE_BASELINE_TOKEN || undefined\n return { checks, workdir, descriptorKey, baselineKey: launchBaselineKey(workdir, descriptorKey, token) }\n }\n}\n\n/** Which dynamic gate mode the launcher armed (sealed → undefined). */\nfunction dynamicMode(): \"parsed\" | \"discovered\" | undefined {\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_PARSED) === true) return \"parsed\"\n if (parseBoolEnv(process.env.GH_ROUTER_STOP_GATE_DISCOVERED) === true) return \"discovered\"\n return undefined\n}\n\nexport const internalStopHook = defineCommand({\n meta: {\n name: \"internal-stop-hook\",\n description:\n \"Internal: the structural-gate Stop hook. Reads the Claude Code hook payload on stdin, \"\n + \"runs the sealed gate, exits 2 (blocks the stop) on a red gate or gate-weakening diff.\",\n },\n async run() {\n const stdin = readStdin()\n // The advisory review (hook V2) is wired only when it's enabled AND the\n // launcher injected the proxy URL/nonce. It is side-effect-only: the\n // deterministic gate below is unchanged and remains the only blocker.\n const reviewEnabled = stopReviewEnabled() && hookMcpRuntimeFromEnv() !== undefined\n let transcriptPath = \"\"\n let userPrompt = \"\"\n if (reviewEnabled) {\n // Parse the payload once for the transcript pointer + the session id used\n // to look up the user's last prompt (the Stop payload carries no prompt;\n // the UserPromptSubmit hook stashed it). Best-effort — a parse miss just\n // means the reviewer judges against the diff alone.\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const obj = p as { transcript_path?: unknown; session_id?: unknown }\n transcriptPath = typeof obj.transcript_path === \"string\" ? obj.transcript_path : \"\"\n const sid = typeof obj.session_id === \"string\" ? obj.session_id : \"\"\n if (sid) {\n userPrompt = (await fileLastPromptStore(stopReviewStateDir()).read(sid).catch(() => null)) ?? \"\"\n }\n }\n } catch {\n /* tolerate a non-JSON stdin */\n }\n }\n\n let decision: { exitCode: 0 | 2; stderr?: string }\n try {\n const timeoutEnv = parseIntEnv(process.env.GH_ROUTER_STOP_GATE_TIMEOUT_MS)\n const mode = dynamicMode()\n decision = await decideStopHook({\n stdin,\n gateId: stopGateId(),\n exec: liveExec,\n captureDiff: captureStopGateDiff,\n fallbackCwd: process.cwd(),\n budget: fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\")),\n baseline: fileBaselineStore(path.join(tmpdir(), \"gh-router-stopgate-baseline\")),\n isEnabledForRepo: (cwd) => stopGateEnabledForRepo(cwd),\n resolveChecks: mode ? buildResolveChecks(mode) : undefined,\n // parseIntEnv already rejects non-positive / non-integer / truncating\n // values, so undefined here means \"use the built-in default\".\n timeoutMs: timeoutEnv,\n reviewDebounce: reviewEnabled ? fileReviewDebounce(stopReviewStateDir()) : undefined,\n spawnReview: reviewEnabled\n ? (ctx) => spawnStopReview(ctx, { prompt: userPrompt, transcriptPath })\n : undefined,\n })\n } catch {\n // Fail OPEN on ANY unexpected error: a Stop hook must never wedge the\n // session, so an internal crash allows the stop (exit 0) rather than\n // surfacing a non-blocking error or a hang.\n process.exitCode = 0\n return\n }\n // Write any stderr the decision carries — both the exit-2 block reason AND\n // the LOUD exit-0 stand-down (max-block budget reached). A clean green stop\n // carries no stderr, so this stays silent on the common path.\n if (decision.stderr) {\n await writeStderr(`${decision.stderr}\\n`)\n }\n // Natural exit: set the code and return. A hard process.exit() races libuv's\n // stdio teardown on Windows (uv_async_send assertion) on the fast-return\n // paths. The detached review child is unref'd and the gate's children are\n // reaped, so no handle keeps the loop alive — the process exits with this\n // code. The exit-2 block contract is preserved (stderr is flushed above).\n process.exitCode = decision.exitCode\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsDA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,MAAM,iBAAiB;;;AAIvB,eAAe,qBAAqB,KAAa,OAAkC;CACjF,MAAM,SAAmB,CAAC;CAC1B,IAAI,QAAQ;CACZ,KAAK,MAAM,iBAAiB,OAAO;EACjC,MAAM,SAAS,MAAM,kBACnB;GAAC;GAAO;GAAQ;GAAc;GAAM;GAAa;EAAa,GAC9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AAI;GACF,MAAM,aAAa,YAAY,QAAQ,IAAI,8BAA8B;GACzE,MAAM,OAAO,YAAY;GACzB,WAAW,MAAM,eAAe;IAC9B;IACA,QAAQ,WAAW;IACnB,MAAM;IACN,aAAa;IACb,aAAa,QAAQ,IAAI;IACzB,QAAQ,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC;IACjE,UAAU,kBAAkB,KAAK,KAAK,OAAO,GAAG,6BAA6B,CAAC;IAC9E,mBAAmB,QAAQ,uBAAuB,GAAG;IACrD,eAAe,OAAO,mBAAmB,IAAI,IAAI,KAAA;IAGjD,WAAW;IACX,gBAAgB,gBAAgB,mBAAmB,mBAAmB,CAAC,IAAI,KAAA;IAC3E,aAAa,iBACR,QAAQ,gBAAgB,KAAK;KAAE,QAAQ;KAAY;IAAe,CAAC,IACpE,KAAA;GACN,CAAC;EACH,QAAQ;GAIN,QAAQ,WAAW;GACnB;EACF;EAIA,IAAI,SAAS,QACX,MAAM,YAAY,GAAG,SAAS,OAAO,GAAG;EAO1C,QAAQ,WAAW,SAAS;CAC9B;AACF,CAAC"}
|
package/dist/main.js
CHANGED
|
@@ -47,14 +47,14 @@ const main = defineCommand({
|
|
|
47
47
|
},
|
|
48
48
|
subCommands: {
|
|
49
49
|
auth: () => import("./auth-Iun7ftd8.js").then((m) => m.auth),
|
|
50
|
-
start: () => import("./start-
|
|
51
|
-
claude: () => import("./claude-
|
|
52
|
-
codex: () => import("./codex-
|
|
53
|
-
serve: () => import("./serve-
|
|
50
|
+
start: () => import("./start-CqSFR_s8.js").then((m) => m.start),
|
|
51
|
+
claude: () => import("./claude-DtWf7DEw.js").then((m) => m.claude),
|
|
52
|
+
codex: () => import("./codex-CDtFT-Qp.js").then((m) => m.codex),
|
|
53
|
+
serve: () => import("./serve-DOMsmIk-.js").then((m) => m.serve),
|
|
54
54
|
models: () => import("./models-CSFIVxAH.js").then((m) => m.models),
|
|
55
55
|
"check-usage": () => import("./check-usage-1c-0z3iy.js").then((m) => m.checkUsage),
|
|
56
56
|
debug: () => import("./debug-CDyXUPcC.js").then((m) => m.debug),
|
|
57
|
-
"internal-stop-hook": () => import("./internal-stop-hook-
|
|
57
|
+
"internal-stop-hook": () => import("./internal-stop-hook-BGTPRCtO.js").then((m) => m.internalStopHook),
|
|
58
58
|
"internal-prompt-submit": () => import("./internal-prompt-submit-dov4UvBo.js").then((m) => m.internalPromptSubmit),
|
|
59
59
|
"internal-stop-review": () => import("./internal-stop-review-MBVYtrYS.js").then((m) => m.internalStopReview),
|
|
60
60
|
"internal-plan-review": () => import("./internal-plan-review-C73snnD8.js").then((m) => m.internalPlanReview),
|
|
@@ -65,7 +65,7 @@ const main = defineCommand({
|
|
|
65
65
|
"internal-worker-guard": () => import("./internal-worker-guard-dxGawAY3.js").then((m) => m.internalWorkerGuard),
|
|
66
66
|
"internal-fast-dispatch-guard": () => import("./internal-fast-dispatch-guard-D5kozMpo.js").then((m) => m.internalFastDispatchGuard),
|
|
67
67
|
"internal-max-dispatch-guard": () => import("./internal-max-dispatch-guard-BGOHRYRt.js").then((m) => m.internalMaxDispatchGuard),
|
|
68
|
-
"internal-aic-status": () => import("./internal-aic-status-
|
|
68
|
+
"internal-aic-status": () => import("./internal-aic-status-CKXxxb30.js").then((m) => m.internalAicStatus)
|
|
69
69
|
}
|
|
70
70
|
});
|
|
71
71
|
/**
|
|
@@ -10,7 +10,7 @@ import { i as registerExitHandlers$1, n as getInstanceUuid, r as recordWorkerRep
|
|
|
10
10
|
import { t as MCP_WORKSPACE_HEADER } from "./mcp-workspace-header-mXRLE8kg.js";
|
|
11
11
|
import { n as ArtifactError, r as applyInsecureTls, t as ArtifactClient } from "./client-CQMfroGV.js";
|
|
12
12
|
import { n as isPidAlive$1, r as registerColbertExitHandlers, s as trackChild, t as getColbertInstanceUuid } from "./lifecycle-_BE0SnNs.js";
|
|
13
|
-
import { a as extractAndRecordPricedAic,
|
|
13
|
+
import { a as extractAndRecordPricedAic, i as extractAndRecordAic, l as recordAic, p as extractCopilotUsage } from "./aic-ledger-BW3zMiCx.js";
|
|
14
14
|
import { h as runGateChecks, m as sealedGateIds, p as resolveSealedGate } from "./stop-gate-hook-D7N759TG.js";
|
|
15
15
|
import { t as liveExec } from "./orchestration-B8kypXcZ.js";
|
|
16
16
|
import { createRequire } from "node:module";
|
|
@@ -30921,6 +30921,7 @@ function buildAdvisorStream(opts) {
|
|
|
30921
30921
|
let pendingMessageDelta = null;
|
|
30922
30922
|
let pendingCopilotNano = 0;
|
|
30923
30923
|
const pendingCopilotDetails = [];
|
|
30924
|
+
let aicRecordedThisTurn = false;
|
|
30924
30925
|
const leadModelForAic = typeof opts.baseBody.model === "string" && opts.baseBody.model.length > 0 ? opts.baseBody.model : void 0;
|
|
30925
30926
|
const safeEnqueue = (bytes) => {
|
|
30926
30927
|
try {
|
|
@@ -30949,11 +30950,12 @@ function buildAdvisorStream(opts) {
|
|
|
30949
30950
|
}
|
|
30950
30951
|
for (const [key, value] of Object.entries(usage)) if (typeof value === "number" && Number.isFinite(value)) pendingMessageDelta.usage[key] = (pendingMessageDelta.usage[key] ?? 0) + value;
|
|
30951
30952
|
const turnAic = extractCopilotUsage(payload.copilot_usage);
|
|
30952
|
-
if (turnAic)
|
|
30953
|
-
|
|
30954
|
-
|
|
30955
|
-
|
|
30956
|
-
|
|
30953
|
+
if (!turnAic || turnAic.totalNanoAiu <= 0) return;
|
|
30954
|
+
if (aicRecordedThisTurn) return;
|
|
30955
|
+
aicRecordedThisTurn = true;
|
|
30956
|
+
pendingCopilotNano += turnAic.totalNanoAiu;
|
|
30957
|
+
pendingCopilotDetails.push(...turnAic.tokenDetails);
|
|
30958
|
+
recordAic(leadModelForAic, turnAic);
|
|
30957
30959
|
};
|
|
30958
30960
|
const emitTerminal = (forcedStopReason) => {
|
|
30959
30961
|
if (pendingMessageDelta || forcedStopReason) {
|
|
@@ -30984,6 +30986,7 @@ function buildAdvisorStream(opts) {
|
|
|
30984
30986
|
return safeEnqueueEvent("message_stop", { type: "message_stop" });
|
|
30985
30987
|
};
|
|
30986
30988
|
async function processOneTurn(response) {
|
|
30989
|
+
aicRecordedThisTurn = false;
|
|
30987
30990
|
const capturedBlocks = [];
|
|
30988
30991
|
const advisorToolUses = [];
|
|
30989
30992
|
let clientToolUseCount = 0;
|
|
@@ -37761,4 +37764,4 @@ function enumerateInjectedMcpToolNames(groupKeys, opts = {}) {
|
|
|
37761
37764
|
//#endregion
|
|
37762
37765
|
export { EFFORT_ORDER as $, parseJsonOrDiagnose as $t, TOOLBELT_TOOLS$1 as A, oneMContextDisabled as An, resolveGeminiReviewModel as At, resolveAdvisorEffort as B, CHEAP_PROFILE_MODELS as Bn, getTextTokenCount as Bt, runWorkerAgent as C, isBudgetClaudeLead as Cn, fastReviewerModel as Ct, toolbeltEnabled as D, upstreamMaxConnections as Dn, generalPurposeFastModel as Dt, buildToolbeltAwareness as E, upstreamAllowH2 as En, geminiAvailable as Et, ADVISOR_TOOL_INSTRUCTIONS as F, CHEAPEST_PROFILE_NATIVE_AGENT_NAMES as Fn, standInToolEnabled as Ft, repairKnownThinkingHistory as G, withInstallLock as Gn, unregisterLaunch as Gt, resolveCheapestAdvisorModel as H, CHEAP_PROFILE_NATIVE_EFFORTS as Hn, getTokenizerFromModel as Ht, FAST_ADVISOR_TOOL_INSTRUCTIONS as I, CHEAPEST_PROFILE_NATIVE_EFFORTS as In, workerToolsEnabled as It, buildOpenAIErrorEvent as J, resolveMcpToolTimeoutMs as Jt, repairRejectedThinkingHistory as K, assembleResponsesPayload as Kt, buildAdvisorStream as L, CHEAPEST_PROFILE_NATIVE_MODELS as Ln, shimDefaultsToXhigh as Lt, satisfiesMinVersion as M, withOneMSuffixForLead as Mn, reviewerModel as Mt, searchWeb as N, CHEAPEST_PROFILE_ADVISOR_CLIENT_MODEL as Nn, scoutModel as Nt, toolbeltSkipSet as O, classifyMessagesRoute as On, implementerFastModel as Ot, ADVISOR_INTERNAL_TOOL_NAME as P, CHEAPEST_PROFILE_MODELS as Pn, scribeModel as Pt, relayAnthropicStream as Q, readResponseBodyCapped as Qt, injectAdvisorTool as R, CHEAPEST_PROFILE_SUBAGENT_CONTEXT_TOKENS as Rn, countTokens as Rt, resolveWorkerRunOpts as S, generateRandomPort as Sn, fastPlanModel as St, availableToolCommands as T, resolveLeadSlugArg as Tn, fleetToolsEnabled as Tt, formatThinkingRepairDecline as U, CHEAP_PROFILE_NATIVE_MODELS as Un, findLaunchBySecret as Ut, resolveAdvisorModel as V, CHEAP_PROFILE_NATIVE_AGENT_NAMES as Vn, getTokenCount as Vt, rememberThinkingHistoryRepair as W, CHEAP_PROFILE_SUBAGENT_CONTEXT_TOKENS as Wn, registerLaunch as Wt, logStreamError as X, createChatCompletions as Xt, isControllerClosedError as Y, createResponses as Yt, readIteratorWithTimeout as Z, MAX_RESPONSE_BODY_BYTES as Zt, REVIEW_DEFAULT_MODEL as _, DEFAULT_CODEX_MODEL as _n, fastAdvisorModel as _t, buildAgentPrompt as a, extractTarGzMember as an, agentToolsEnabled as at, resolveDefaultModel as b, UPSTREAM_FETCH_TIMEOUT_MS as bn, fastImplementerModel as bt, enumerateInjectedMcpToolNames as c, provisionTreeSitterAssets as cn, browseAgentEnabled as ct, BROWSE_DEFAULT_MODEL as d, shouldUseInsecureTls as dn, cheapAdvisorModel as dt, normalizeOpenAIUsage as en, UNKNOWN_EFFORT_ANCHOR as et, DEFAULT_MODEL_CHAIN as f, collapsePathKeys as fn, cheapOracleModel as ft, PLAN_DEFAULT_MODEL as g, DEFAULT_CLAUDE_MODEL_FALLBACKS as gn, cheapestReviewerModel as gt, IMPLEMENT_DEFAULT_MODEL as h, BUDGET_SMALL_FAST_SLUG as hn, cheapestOracleModel as ht, assertMcpToolSurfaceConsistent as i, provisionAndIndexColbert as in, handleMcpPost as it, assetFor as j, withOneMSuffix as jn, reviewerFastModel as jt, vscodeRipgrepPath as k, catalogAdvertises1M as kn, nativeSubagentModel as kt, maxPersonasFor as l, CONDENSED_OPERATING_SEQUENCE as ln, browserCompoundToolsEnabled as lt, EXPLORE_DEFAULT_THINKING as m, BUDGET_SMALL_FAST_CATALOG_ID as mn, cheapestAdvisorModel as mt, MCP_GROUPS as n, hasSupportedBrowserInstalled as nn, clampEffort as nt, buildPeerAwarenessSnippet as o, extractZipMember as on, artifactToolsEnabled as ot, EXPLORE_DEFAULT_MODEL as p, toolbeltPathOverride as pn, cheapReviewerModel as pt, buildAnthropicErrorEvent as q, warnOnTokenPriceDrift as qt, agentNamesForToolAllowlist as r, colbertDegradedWarning as rn, handleMcpDelete as rt, buildPeerAwarenessSummary as s, warmTreeSitterPool as sn, brainstormModel as st, GROUP_META as t, provisionBrowserAssets as tn, bucketEffort as tt, personasFor as u, DEFINITION_OF_GREATNESS as un, browserToolsEnabled as ut, TEST_DEFAULT_MODEL as v, DEFAULT_CODEX_MODEL_FALLBACKS as vn, fastAstraModel as vt, buildEnv as w, pickClaudeDefault as wn, fastScoutModel as wt, resolveModeDefaults as x, UPSTREAM_INACTIVITY_TIMEOUT_MS as xn, fastOracleModel as xt, appendPlanReminder as y, DEFAULT_PORT as yn, fastGeneralPurposeModel as yt, isAdvisorRequested as z, CHEAP_PROFILE_ADVISOR_CLIENT_MODEL as zn, createMessages as zt };
|
|
37763
37766
|
|
|
37764
|
-
//# sourceMappingURL=peer-mcp-personas-
|
|
37767
|
+
//# sourceMappingURL=peer-mcp-personas-Gb0LfII0.js.map
|