github-router 0.3.349 → 0.3.350
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/{attribution-settings-BgYkynRc.js → attribution-settings-B9T-EsEs.js} +70 -4
- package/dist/attribution-settings-B9T-EsEs.js.map +1 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{claude-Chtd07VA.js → claude-BY4e9ueE.js} +11 -11
- package/dist/{claude-Chtd07VA.js.map → claude-BY4e9ueE.js.map} +1 -1
- package/dist/{codex-DayPQ8t5.js → codex-BOugL-uX.js} +4 -4
- package/dist/{codex-DayPQ8t5.js.map → codex-BOugL-uX.js.map} +1 -1
- package/dist/engine-DZfLaVcf.js +2 -0
- package/dist/{gate-discovery-CBOPoK9-.js → gate-discovery-BFqulsWz.js} +4 -4
- package/dist/{gate-discovery-CBOPoK9-.js.map → gate-discovery-BFqulsWz.js.map} +1 -1
- package/dist/hooks.mjs +634 -27
- package/dist/hooks.sha256 +1 -1
- package/dist/{internal-artifact-open-CXJbMXpq.js → internal-artifact-open-DErO3WpR.js} +2 -2
- package/dist/{internal-artifact-open-CXJbMXpq.js.map → internal-artifact-open-DErO3WpR.js.map} +1 -1
- package/dist/{internal-plan-review-F-WbltsT.js → internal-plan-review-DbX-mr9i.js} +3 -3
- package/dist/{internal-plan-review-F-WbltsT.js.map → internal-plan-review-DbX-mr9i.js.map} +1 -1
- package/dist/internal-prompt-submit-CA5Y4DWM.js +2 -0
- package/dist/{internal-prompt-submit-DRCJ5kWC.js → internal-prompt-submit-UhfnM_qG.js} +19 -5
- package/dist/internal-prompt-submit-UhfnM_qG.js.map +1 -0
- package/dist/internal-rebrief-BH9PMJhF.js +548 -0
- package/dist/internal-rebrief-BH9PMJhF.js.map +1 -0
- package/dist/{internal-session-bind-LrYEo-kg.js → internal-session-bind-DxdVbJ7x.js} +2 -2
- package/dist/{internal-session-bind-LrYEo-kg.js.map → internal-session-bind-DxdVbJ7x.js.map} +1 -1
- package/dist/{internal-stop-hook-CIe2kVss.js → internal-stop-hook-DlGc9WwJ.js} +5 -5
- package/dist/{internal-stop-hook-CIe2kVss.js.map → internal-stop-hook-DlGc9WwJ.js.map} +1 -1
- package/dist/{internal-stop-review-nL003JIj.js → internal-stop-review-CORT3UGr.js} +2 -2
- package/dist/{internal-stop-review-nL003JIj.js.map → internal-stop-review-CORT3UGr.js.map} +1 -1
- package/dist/main.js +13 -12
- package/dist/main.js.map +1 -1
- package/dist/{orchestration-DjuJRhXn.js → orchestration-Dkqv-iv0.js} +2 -2
- package/dist/{orchestration-DjuJRhXn.js.map → orchestration-Dkqv-iv0.js.map} +1 -1
- package/dist/{peer-mcp-personas-agpBeTgS.js → peer-mcp-personas-BwwSNnBC.js} +3 -3
- package/dist/{peer-mcp-personas-agpBeTgS.js.map → peer-mcp-personas-BwwSNnBC.js.map} +1 -1
- package/dist/{pi-BLDBFXg3.js → pi-Dpw8Otxw.js} +4 -4
- package/dist/{pi-BLDBFXg3.js.map → pi-Dpw8Otxw.js.map} +1 -1
- package/dist/{plan-review-hook-DMqPHBBN.js → plan-review-hook-LfG01VMp.js} +2 -2
- package/dist/{plan-review-hook-DMqPHBBN.js.map → plan-review-hook-LfG01VMp.js.map} +1 -1
- package/dist/{prompt-submit-hook-CBGlhEpU.js → prompt-submit-hook-DzhmQRs_.js} +39 -13
- package/dist/prompt-submit-hook-DzhmQRs_.js.map +1 -0
- package/dist/{provision-BKdrO1Sv.js → provision-9TAIgyL7.js} +2 -2
- package/dist/{provision-BKdrO1Sv.js.map → provision-9TAIgyL7.js.map} +1 -1
- package/dist/{serve-p_58sDJK.js → serve-BRKRWkd1.js} +8 -8
- package/dist/{serve-p_58sDJK.js.map → serve-BRKRWkd1.js.map} +1 -1
- package/dist/{server-setup-PAHohZ-u.js → server-setup-DXVFE7bf.js} +3 -3
- package/dist/{server-setup-PAHohZ-u.js.map → server-setup-DXVFE7bf.js.map} +1 -1
- package/dist/{start-CTHcqkQL.js → start-CoR3jqUR.js} +3 -3
- package/dist/{start-CTHcqkQL.js.map → start-CoR3jqUR.js.map} +1 -1
- package/dist/{stop-gate-hook-DRcYQAtf.js → stop-gate-hook-C9VNxmt1.js} +2 -2
- package/dist/{stop-gate-hook-DRcYQAtf.js.map → stop-gate-hook-C9VNxmt1.js.map} +1 -1
- package/dist/{stop-gate-policy-CbLklfV2.js → stop-gate-policy-DQsfjnsx.js} +29 -2
- package/dist/{stop-gate-policy-CbLklfV2.js.map → stop-gate-policy-DQsfjnsx.js.map} +1 -1
- package/package.json +1 -1
- package/dist/attribution-settings-BgYkynRc.js.map +0 -1
- package/dist/engine-T81FYVwK.js +0 -2
- package/dist/internal-prompt-submit-DRCJ5kWC.js.map +0 -1
- package/dist/prompt-submit-hook-CBGlhEpU.js.map +0 -1
package/dist/hooks.sha256
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
09ed0f914ebb8479a5dfd557770785dff3b5b71e4775c9c08b9e8d331bffc945
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as ArtifactClient } from "./client-CQMfroGV.js";
|
|
2
|
-
import {
|
|
2
|
+
import { s as isSubagentContext } from "./stop-gate-policy-DQsfjnsx.js";
|
|
3
3
|
import { defineCommand } from "citty";
|
|
4
4
|
import { readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
@@ -316,4 +316,4 @@ const internalArtifactOpen = defineCommand({
|
|
|
316
316
|
//#endregion
|
|
317
317
|
export { internalArtifactOpen };
|
|
318
318
|
|
|
319
|
-
//# sourceMappingURL=internal-artifact-open-
|
|
319
|
+
//# sourceMappingURL=internal-artifact-open-DErO3WpR.js.map
|
package/dist/{internal-artifact-open-CXJbMXpq.js.map → internal-artifact-open-DErO3WpR.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-artifact-open-CXJbMXpq.js","names":[],"sources":["../src/lib/artifact/plan-html.ts","../src/internal-artifact-open.ts"],"sourcesContent":["/**\n * Render a plan's markdown into a self-contained, styled HTML document for the\n * ai-or-die Artifact panel. HTML is the canonical review artifact (lavish's\n * model); converting here means the hands-off auto-open shows a formatted,\n * annotatable page instead of raw markdown.\n *\n * Security: the iframe ai-or-die serves this into runs with\n * `allow-scripts allow-same-origin`, so a `<script>` smuggled into the plan\n * markdown could read the per-session asset token. Two defenses:\n * 1. marked is configured to ESCAPE raw HTML tokens (render as visible text).\n * 2. `link`/`image` hrefs with script-bearing schemes (javascript:, vbscript:,\n * non-image data:) are neutralised before rendering.\n * No separate sanitizer/dep needed.\n */\nimport { Marked } from \"marked\"\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\")\n}\n\n/** Decode the HTML character references a browser would resolve in an attribute\n * value, so an entity-obfuscated scheme (`javascript:`, `javascript:`)\n * cannot slip past the scheme check below. Numeric refs cover any letter; the\n * small named map covers the scheme-relevant punctuation. */\nconst NAMED_REFS: Record<string, string> = {\n colon: \":\", tab: \"\\t\", newline: \"\\n\", sol: \"/\", semi: \";\", amp: \"&\", lpar: \"(\", rpar: \")\",\n}\nfunction decodeEntities(s: string): string {\n return s.replace(/&(#[xX][0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);?/g, (m, body: string) => {\n if (body[0] === \"#\") {\n const code = body[1] === \"x\" || body[1] === \"X\"\n ? Number.parseInt(body.slice(2), 16)\n : Number.parseInt(body.slice(1), 10)\n return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m\n }\n return NAMED_REFS[body.toLowerCase()] ?? m\n })\n}\n\n/** Block script-bearing URL schemes (defense-in-depth on top of HTML escaping). */\nfunction isDangerousUrl(url: string, isImage: boolean): boolean {\n // Decode entities first (a browser resolves them in href), then drop ASCII\n // control chars + spaces (code <= 0x20) a browser ignores inside a scheme.\n const v = Array.from(decodeEntities(url)).filter((c) => c.charCodeAt(0) > 0x20).join(\"\").toLowerCase()\n if (v.startsWith(\"javascript:\") || v.startsWith(\"vbscript:\")) return true\n if (v.startsWith(\"data:\")) {\n // Allow only raster image data URIs (and only for <img>); SVG can script.\n return !(isImage && v.startsWith(\"data:image/\") && !v.startsWith(\"data:image/svg\"))\n }\n return false\n}\n\n/** A marked instance that escapes raw HTML (raw markup never becomes live). */\nfunction makeMarked(): Marked {\n const m = new Marked({ gfm: true, breaks: false })\n m.use({\n renderer: {\n // Raw HTML in the source is rendered as escaped text, never live markup.\n html(token: unknown): string {\n const text = typeof token === \"string\" ? token : ((token as { text?: string }).text ?? \"\")\n return escapeHtml(text)\n },\n },\n })\n return m\n}\n\ninterface MdToken {\n type?: string\n href?: string\n tokens?: MdToken[]\n items?: MdToken[]\n header?: Array<{ tokens?: MdToken[] }>\n rows?: Array<Array<{ tokens?: MdToken[] }>>\n}\n\n/**\n * Recursively neutralise script-bearing link/image hrefs in the lexed token tree.\n * Done as an explicit walk (not marked's `walkTokens` hook) because we render via\n * the low-level `lexer`+`parser` split, which does not run registered walkTokens.\n */\nfunction neutralizeUrls(tokens: MdToken[]): void {\n for (const t of tokens) {\n if ((t.type === \"link\" || t.type === \"image\") && typeof t.href === \"string\") {\n if (isDangerousUrl(t.href, t.type === \"image\")) t.href = \"#\"\n }\n if (t.tokens) neutralizeUrls(t.tokens)\n if (t.items) neutralizeUrls(t.items)\n if (t.header) for (const cell of t.header) if (cell.tokens) neutralizeUrls(cell.tokens)\n if (t.rows) for (const row of t.rows) for (const cell of row) if (cell.tokens) neutralizeUrls(cell.tokens)\n }\n}\n\n/** Add `data-source-line=\"N\"` to the first opening tag of a rendered block. */\nfunction tagSourceLine(html: string, line: number): string {\n return html.replace(/^(\\s*)<([a-zA-Z][\\w-]*)/, `$1<$2 data-source-line=\"${line}\"`)\n}\n\n/**\n * Render markdown to inner HTML, tagging each top-level block with its 1-based\n * source line so an annotation in the panel can map back to a plan line.\n */\nexport function renderMarkdownBody(source: string): string {\n const m = makeMarked()\n let tokens: Array<{ raw?: string }>\n try {\n tokens = m.lexer(source) as Array<{ raw?: string }>\n } catch {\n // Lexing should not fail, but never throw out of the hook path.\n return `<pre>${escapeHtml(source)}</pre>`\n }\n neutralizeUrls(tokens as MdToken[])\n let line = 1\n let out = \"\"\n for (const tok of tokens) {\n let html: string\n try {\n html = m.parser([tok] as Parameters<typeof m.parser>[0])\n } catch {\n html = \"\"\n }\n if (html.trim()) out += tagSourceLine(html, line)\n line += (tok.raw?.match(/\\n/g)?.length ?? 0)\n }\n return out || `<pre>${escapeHtml(source)}</pre>`\n}\n\n/**\n * Wrap rendered markdown in a complete, self-contained HTML document with\n * readable typography (works even before ai-or-die injects its annotation SDK).\n */\nexport function renderPlanHtml(source: string, title = \"Plan\"): string {\n return wrapArtifactDocument(renderMarkdownBody(source), title)\n}\n\nconst BASE_STYLE = ` :root {\n --bg: #0f1115; --fg: #f7f3ea; --muted: #aeb6c6; --border: #2a2f3a;\n --accent: #f4c95d; --code-bg: #171a21;\n --serif: 'Iowan Old Style', Georgia, 'Times New Roman', serif;\n --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;\n --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n }\n * { box-sizing: border-box; }\n html, body { margin: 0; background: var(--bg); color: var(--fg); }\n body { font-family: var(--serif); font-size: 16px; line-height: 1.6;\n padding: 32px clamp(16px, 5vw, 56px); }\n main { max-width: 78ch; margin: 0 auto; }\n h1, h2, h3, h4 { font-family: var(--sans); line-height: 1.25; margin: 1.6em 0 0.5em; }\n h1 { font-size: 1.9em; } h2 { font-size: 1.45em; padding-bottom: 0.2em;\n border-bottom: 1px solid var(--border); } h3 { font-size: 1.2em; }\n p, li { color: var(--fg); }\n a { color: var(--accent); }\n code { font-family: var(--mono); font-size: 0.9em; background: var(--code-bg);\n padding: 0.12em 0.35em; border-radius: 5px; }\n pre { background: var(--code-bg); border: 1px solid var(--border); border-radius: 8px;\n padding: 12px 14px; overflow: auto; }\n pre code { background: none; padding: 0; }\n blockquote { margin: 1em 0; padding: 0.2em 1em; border-left: 3px solid var(--accent);\n color: var(--muted); }\n table { border-collapse: collapse; width: 100%; margin: 1em 0; font-family: var(--sans);\n font-size: 0.95em; }\n th, td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; }\n th { background: var(--code-bg); }\n hr { border: 0; border-top: 1px solid var(--border); margin: 1.5em 0; }\n ul, ol { padding-left: 1.4em; }`\n\nconst INTERACTIVE_STYLE = `\n .aod-group { margin: 1.4em 0; padding: 14px 16px; border: 1px solid var(--border);\n border-radius: 10px; background: var(--code-bg); }\n .aod-prompt { font-family: var(--sans); font-weight: 600; margin: 0 0 0.6em; }\n .aod-options { display: flex; flex-wrap: wrap; gap: 8px; }\n .aod-multi-select .aod-options { flex-direction: column; gap: 6px; }\n .aod-action, .aod-submit { font-family: var(--sans); font-size: 0.95em; font-weight: 600;\n cursor: pointer; border: 1px solid var(--border); border-radius: 8px;\n padding: 8px 12px; background: var(--bg); color: var(--fg); }\n .aod-action:hover, .aod-submit:hover { border-color: var(--accent); }\n .aod-submit { margin-top: 10px; background: var(--accent); color: #17130a; border-color: var(--accent); }\n .aod-check { display: flex; align-items: center; gap: 8px; font-family: var(--sans); cursor: pointer; }\n .aod-steps { list-style: decimal; }\n .aod-step { margin: 0.5em 0; }\n .aod-step-actions { display: inline-flex; gap: 6px; margin-left: 8px; }`\n\n/**\n * Wrap rendered inner HTML in the self-contained document shell. `extraStyle` is\n * appended to the inline stylesheet so the interactive variant can add its own\n * rules without a second `<style>` block. Static callers pass \"\" (default), so\n * the static document is byte-identical to the pre-refactor output.\n */\nfunction wrapArtifactDocument(body: string, title: string, extraStyle = \"\"): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(title)}</title>\n<style>\n${BASE_STYLE}${extraStyle}\n</style>\n</head>\n<body>\n<main>\n${body}\n</main>\n</body>\n</html>\n`\n}\n\n/* -------------------------------------------------------------------------- */\n/* Interactive artifacts (contract v2.2 §4: declarative data-aod-* vocab) */\n/* -------------------------------------------------------------------------- */\n\nexport interface InteractiveOption {\n /** Stable id echoed back as `elementId` in the action event. Required. */\n elementId: string\n /** Human-visible label. */\n label: string\n /** Optional value echoed as `data-aod-value` (checkbox submits use \"true\"/\"false\"). */\n value?: string\n}\n\n/** One immediate-fire choice group: each option posts an action the instant it is clicked. */\nexport interface ChooseOneBlock {\n kind: \"choose-one\"\n /** `data-aod-group` shared by the options (marks them as one decision). */\n group: string\n prompt?: string\n /** `data-aod-action` verb for every option (default \"choose\"). */\n action?: string\n options: InteractiveOption[]\n}\n\n/** A multi-select group: checkbox toggles plus one submit that carries {group, selected}. */\nexport interface MultiSelectBlock {\n kind: \"multi-select\"\n group: string\n prompt?: string\n submitLabel?: string\n submitElementId?: string\n options: InteractiveOption[]\n}\n\nexport interface StepAction {\n /** `data-aod-action` verb (e.g. \"approve\", \"skip\"). */\n action: string\n label: string\n value?: string\n}\n\nexport interface StepItem {\n /** Stable `data-aod-id` echoed as `elementId`. */\n elementId: string\n label: string\n sourceLine?: number\n actions: StepAction[]\n}\n\n/** An ordered list of plan steps, each with its own inline action buttons. */\nexport interface StepsBlock {\n kind: \"steps\"\n steps: StepItem[]\n}\n\nexport type InteractiveBlock = ChooseOneBlock | MultiSelectBlock | StepsBlock\n\nexport interface InteractivePlanModel {\n /** Optional prose rendered above the interactive blocks (same escaping as static). */\n markdown?: string\n blocks: InteractiveBlock[]\n}\n\n/** Build a ` data-x=\"y\"` attribute string, dropping undefined values, all escaped. */\nfunction dataAttrs(pairs: Array<[string, string | undefined]>): string {\n let out = \"\"\n for (const [name, value] of pairs) {\n if (value === undefined) continue\n out += ` ${name}=\"${escapeHtml(value)}\"`\n }\n return out\n}\n\nfunction renderChooseOne(block: ChooseOneBlock): string {\n const action = block.action && block.action.trim() ? block.action : \"choose\"\n const prompt = block.prompt ? `<p class=\"aod-prompt\">${escapeHtml(block.prompt)}</p>` : \"\"\n const options = block.options\n .filter((o) => o.elementId.trim() !== \"\")\n .map((o) => {\n const attrs = dataAttrs([\n [\"data-aod-action\", action],\n [\"data-aod-group\", block.group],\n [\"data-aod-id\", o.elementId],\n [\"data-aod-value\", o.value],\n ])\n return `<button type=\"button\" class=\"aod-action\"${attrs}>${escapeHtml(o.label)}</button>`\n })\n .join(\"\\n\")\n return `<div class=\"aod-group aod-choose-one\"${dataAttrs([[\"data-aod-group\", block.group]])}>\n${prompt}<div class=\"aod-options\">\n${options}\n</div>\n</div>`\n}\n\nfunction renderMultiSelect(block: MultiSelectBlock): string {\n const prompt = block.prompt ? `<p class=\"aod-prompt\">${escapeHtml(block.prompt)}</p>` : \"\"\n const options = block.options\n .filter((o) => o.elementId.trim() !== \"\")\n .map((o) => {\n const attrs = dataAttrs([\n [\"data-aod-action\", \"check\"],\n [\"data-aod-group\", block.group],\n [\"data-aod-id\", o.elementId],\n [\"data-aod-value\", o.value],\n ])\n return `<label class=\"aod-check\"><input type=\"checkbox\"${attrs}> <span>${escapeHtml(o.label)}</span></label>`\n })\n .join(\"\\n\")\n const submitId = block.submitElementId && block.submitElementId.trim()\n ? block.submitElementId\n : `${block.group}-submit`\n const submitAttrs = dataAttrs([\n [\"data-aod-action\", \"submit\"],\n [\"data-aod-group\", block.group],\n [\"data-aod-id\", submitId],\n ])\n const submitLabel = block.submitLabel && block.submitLabel.trim() ? block.submitLabel : \"Submit\"\n return `<div class=\"aod-group aod-multi-select\"${dataAttrs([[\"data-aod-group\", block.group]])}>\n${prompt}<div class=\"aod-options\">\n${options}\n</div>\n<button type=\"button\" class=\"aod-submit\"${submitAttrs}>${escapeHtml(submitLabel)}</button>\n</div>`\n}\n\nfunction renderSteps(block: StepsBlock): string {\n const items = block.steps\n .filter((s) => s.elementId.trim() !== \"\")\n .map((s) => {\n const liAttrs = dataAttrs([\n [\"data-aod-id\", s.elementId],\n [\"data-source-line\", s.sourceLine === undefined ? undefined : String(s.sourceLine)],\n ])\n const actions = s.actions\n .map((a) => {\n const attrs = dataAttrs([\n [\"data-aod-action\", a.action],\n [\"data-aod-id\", s.elementId],\n [\"data-aod-value\", a.value],\n ])\n return `<button type=\"button\" class=\"aod-action\"${attrs}>${escapeHtml(a.label)}</button>`\n })\n .join(\"\")\n return `<li class=\"aod-step\"${liAttrs}><span class=\"aod-step-label\">${escapeHtml(s.label)}</span><span class=\"aod-step-actions\">${actions}</span></li>`\n })\n .join(\"\\n\")\n return `<ol class=\"aod-steps\">\n${items}\n</ol>`\n}\n\nfunction renderInteractiveBlock(block: InteractiveBlock): string {\n switch (block.kind) {\n case \"choose-one\":\n return renderChooseOne(block)\n case \"multi-select\":\n return renderMultiSelect(block)\n case \"steps\":\n return renderSteps(block)\n default:\n return \"\"\n }\n}\n\n/**\n * Render a typed interactive plan model into a self-contained HTML document that\n * carries the declarative `data-aod-*` action vocabulary the ai-or-die panel SDK\n * wires (contract v2.2 §4). Optional prose (`markdown`) is rendered with the SAME\n * escaping + dangerous-URL neutralization as the static path; all control\n * attributes and labels are HTML-escaped, so no author string can break out of an\n * attribute or inject live markup.\n */\nexport function renderInteractivePlanHtml(model: InteractivePlanModel, title = \"Plan\"): string {\n const prose = model.markdown && model.markdown.trim() ? renderMarkdownBody(model.markdown) : \"\"\n const blocks = model.blocks.map(renderInteractiveBlock).filter((h) => h.trim() !== \"\").join(\"\\n\")\n const body = [prose, blocks].filter((s) => s.trim() !== \"\").join(\"\\n\")\n return wrapArtifactDocument(body || `<pre>${escapeHtml(JSON.stringify(model))}</pre>`, title, INTERACTIVE_STYLE)\n}\n","/**\n * The internal `internal-artifact-open` subcommand: invoked by a spawned Claude\n * Code session's `PostToolUse` hook (matcher `ExitPlanMode`), registered into the\n * mirrored settings.json by the launcher when running inside an ai-or-die tab\n * (`AIORDIE_SESSION_ID` set). It auto-opens the just-finalized plan in the\n * ai-or-die Artifact review panel so the human reviews it WITHOUT the model\n * having to call artifact_open itself.\n *\n * Auth: AIORDIE_TOKEN is stripped from the child env, so the token can't come via\n * env or argv (argv leaks to `ps`). The launcher writes a mode-600\n * `.aiordie-artifact.json` into CLAUDE_CONFIG_DIR; this hook reads it.\n *\n * Plan: the EXACT plan for THIS session comes from the ExitPlanMode payload —\n * `tool_input.planFilePath` (per-session; never the globally-newest file in the\n * shared plans dir) with `tool_input.plan` as the markdown fallback. The plan\n * markdown is rendered to a self-contained styled HTML file (HTML is the\n * canonical artifact, lavish's model — formatted + annotatable, not raw md), and\n * THAT `.html` is opened.\n *\n * Side-effect only: never writes stdout, never throws, always exits 0. Skips\n * subagent payloads (agent_id/agent_type) like the other hooks.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync, realpathSync, writeFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { ArtifactClient } from \"./lib/artifact/client\"\nimport { renderPlanHtml } from \"./lib/artifact/plan-html\"\nimport { isSubagentContext } from \"./lib/orchestration/stop-gate-policy\"\n\ninterface ArtifactCreds {\n baseUrl: string\n token: string\n sessionId: string\n insecureTLS: boolean\n}\n\ninterface ExitPlanPayload {\n planFilePath?: string\n planMarkdown?: string\n}\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nfunction credsPath(): string {\n const dir = process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), \".claude\")\n return path.join(dir, \".aiordie-artifact.json\")\n}\n\nfunction isSubagent(payload: unknown): boolean {\n try {\n return isSubagentContext(payload as Parameters<typeof isSubagentContext>[0])\n } catch {\n return false\n }\n}\n\n/** Pull the per-session plan path + markdown content out of the hook payload. */\nexport function parseExitPlanPayload(raw: string): ExitPlanPayload {\n try {\n const obj = JSON.parse(raw) as { tool_input?: { planFilePath?: unknown; plan?: unknown } }\n const ti = obj.tool_input ?? {}\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim() ? ti.planFilePath : undefined\n const planMarkdown = typeof ti.plan === \"string\" && ti.plan.trim() ? ti.plan : undefined\n return { planFilePath, planMarkdown }\n } catch {\n return {}\n }\n}\n\nfunction readCreds(): ArtifactCreds | undefined {\n try {\n const parsed = JSON.parse(readFileSync(credsPath(), \"utf8\")) as Partial<ArtifactCreds>\n if (!parsed.baseUrl || !parsed.token || !parsed.sessionId) return undefined\n return {\n baseUrl: parsed.baseUrl,\n token: parsed.token,\n sessionId: parsed.sessionId,\n insecureTLS: parsed.insecureTLS === true,\n }\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve the plan markdown + a title, preferring the file at `planFilePath`\n * (the source of truth, may be newer than the payload's snapshot), falling back\n * to the inline `tool_input.plan` content.\n */\nfunction resolvePlanMarkdown(p: ExitPlanPayload): { markdown: string; title: string; nearPath?: string } | undefined {\n if (p.planFilePath) {\n try {\n const md = readFileSync(p.planFilePath, \"utf8\")\n if (md.trim()) return { markdown: md, title: path.basename(p.planFilePath, path.extname(p.planFilePath)), nearPath: p.planFilePath }\n } catch {\n /* fall through to inline content */\n }\n }\n if (p.planMarkdown) return { markdown: p.planMarkdown, title: \"Plan\" }\n return undefined\n}\n\n/**\n * Write the rendered HTML next to the plan (an allowed root) when we have a real\n * path, else into the plans dir under CLAUDE_CONFIG_DIR. Returns the realpath of\n * the written `.html`, or undefined on failure.\n */\nfunction writePlanHtml(html: string, nearPath: string | undefined): string | undefined {\n let target: string\n if (nearPath) {\n // `<plan>.md` -> `<plan>.aiordie.html` (or append when there is no .md ext).\n const base = nearPath.replace(/\\.(md|markdown)$/i, \"\")\n target = `${base}.aiordie.html`\n } else {\n const dir = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), \".claude\"), \"plans\")\n target = path.join(dir, `aiordie-plan-${process.pid}.html`)\n }\n try {\n writeFileSync(target, html, \"utf8\")\n try {\n return realpathSync.native(target)\n } catch {\n return target\n }\n } catch {\n return undefined\n }\n}\n\nexport const internalArtifactOpen = defineCommand({\n meta: { name: \"internal-artifact-open\", description: \"Open the finalized plan in the ai-or-die panel\" },\n async run() {\n try {\n const raw = readStdin()\n let payload: unknown\n try {\n payload = JSON.parse(raw)\n } catch {\n payload = undefined\n }\n if (isSubagent(payload)) return\n const creds = readCreds()\n if (!creds) return\n const plan = resolvePlanMarkdown(parseExitPlanPayload(raw))\n if (!plan) return\n const htmlPath = writePlanHtml(renderPlanHtml(plan.markdown, plan.title), plan.nearPath)\n if (!htmlPath) return\n const client = new ArtifactClient(creds)\n await client.open(htmlPath)\n } catch {\n /* side-effect only: never block, never throw */\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAS,WAAW,GAAmB;CACrC,OAAO,EACJ,QAAQ,MAAM,OAAO,CAAC,CACtB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,QAAQ,CAAC,CACvB,QAAQ,MAAM,OAAO;AAC1B;;;;;AAMA,MAAM,aAAqC;CACzC,OAAO;CAAK,KAAK;CAAM,SAAS;CAAM,KAAK;CAAK,MAAM;CAAK,KAAK;CAAK,MAAM;CAAK,MAAM;AACxF;AACA,SAAS,eAAe,GAAmB;CACzC,OAAO,EAAE,QAAQ,8CAA8C,GAAG,SAAiB;EACjF,IAAI,KAAK,OAAO,KAAK;GACnB,MAAM,OAAO,KAAK,OAAO,OAAO,KAAK,OAAO,MACxC,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE,IACjC,OAAO,SAAS,KAAK,MAAM,CAAC,GAAG,EAAE;GACrC,OAAO,OAAO,SAAS,IAAI,KAAK,OAAO,KAAK,QAAQ,UAAW,OAAO,cAAc,IAAI,IAAI;EAC9F;EACA,OAAO,WAAW,KAAK,YAAY,MAAM;CAC3C,CAAC;AACH;;AAGA,SAAS,eAAe,KAAa,SAA2B;CAG9D,MAAM,IAAI,MAAM,KAAK,eAAe,GAAG,CAAC,CAAC,CAAC,QA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ACF;AAEA,MAAa,uBAAuB,cAAc;CAChD,MAAM;EAAE,MAAM;EAA0B,aAAa;CAAiD;CACtG,MAAM,MAAM;EACV,IAAI;GACF,MAAM,MAAM,UAAU;GACtB,IAAI;GACJ,IAAI;IACF,UAAU,KAAK,MAAM,GAAG;GAC1B,QAAQ;IACN,UAAU,KAAA;GACZ;GACA,IAAI,WAAW,OAAO,GAAG;GACzB,MAAM,QAAQ,UAAU;GACxB,IAAI,CAAC,OAAO;GACZ,MAAM,OAAO,oBAAoB,qBAAqB,GAAG,CAAC;GAC1D,IAAI,CAAC,MAAM;GACX,MAAM,WAAW,cAAc,eAAe,KAAK,UAAU,KAAK,KAAK,GAAG,KAAK,QAAQ;GACvF,IAAI,CAAC,UAAU;GAEf,MAAM,IADa,eAAe,KACvB,CAAC,CAAC,KAAK,QAAQ;EAC5B,QAAQ,CAER;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"internal-artifact-open-DErO3WpR.js","names":[],"sources":["../src/lib/artifact/plan-html.ts","../src/internal-artifact-open.ts"],"sourcesContent":["/**\n * Render a plan's markdown into a self-contained, styled HTML document for the\n * ai-or-die Artifact panel. HTML is the canonical review artifact (lavish's\n * model); converting here means the hands-off auto-open shows a formatted,\n * annotatable page instead of raw markdown.\n *\n * Security: the iframe ai-or-die serves this into runs with\n * `allow-scripts allow-same-origin`, so a `<script>` smuggled into the plan\n * markdown could read the per-session asset token. Two defenses:\n * 1. marked is configured to ESCAPE raw HTML tokens (render as visible text).\n * 2. `link`/`image` hrefs with script-bearing schemes (javascript:, vbscript:,\n * non-image data:) are neutralised before rendering.\n * No separate sanitizer/dep needed.\n */\nimport { Marked } from \"marked\"\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&\")\n .replace(/</g, \"<\")\n .replace(/>/g, \">\")\n .replace(/\"/g, \""\")\n .replace(/'/g, \"'\")\n}\n\n/** Decode the HTML character references a browser would resolve in an attribute\n * value, so an entity-obfuscated scheme (`javascript:`, `javascript:`)\n * cannot slip past the scheme check below. Numeric refs cover any letter; the\n * small named map covers the scheme-relevant punctuation. */\nconst NAMED_REFS: Record<string, string> = {\n colon: \":\", tab: \"\\t\", newline: \"\\n\", sol: \"/\", semi: \";\", amp: \"&\", lpar: \"(\", rpar: \")\",\n}\nfunction decodeEntities(s: string): string {\n return s.replace(/&(#[xX][0-9a-fA-F]+|#[0-9]+|[a-zA-Z]+);?/g, (m, body: string) => {\n if (body[0] === \"#\") {\n const code = body[1] === \"x\" || body[1] === \"X\"\n ? Number.parseInt(body.slice(2), 16)\n : Number.parseInt(body.slice(1), 10)\n return Number.isFinite(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m\n }\n return NAMED_REFS[body.toLowerCase()] ?? m\n })\n}\n\n/** Block script-bearing URL schemes (defense-in-depth on top of HTML escaping). */\nfunction isDangerousUrl(url: string, isImage: boolean): boolean {\n // Decode entities first (a browser resolves them in href), then drop ASCII\n // control chars + spaces (code <= 0x20) a browser ignores inside a scheme.\n const v = Array.from(decodeEntities(url)).filter((c) => c.charCodeAt(0) > 0x20).join(\"\").toLowerCase()\n if (v.startsWith(\"javascript:\") || v.startsWith(\"vbscript:\")) return true\n if (v.startsWith(\"data:\")) {\n // Allow only raster image data URIs (and only for <img>); SVG can script.\n return !(isImage && v.startsWith(\"data:image/\") && !v.startsWith(\"data:image/svg\"))\n }\n return false\n}\n\n/** A marked instance that escapes raw HTML (raw markup never becomes live). */\nfunction makeMarked(): Marked {\n const m = new Marked({ gfm: true, breaks: false })\n m.use({\n renderer: {\n // Raw HTML in the source is rendered as escaped text, never live markup.\n html(token: unknown): string {\n const text = typeof token === \"string\" ? token : ((token as { text?: string }).text ?? \"\")\n return escapeHtml(text)\n },\n },\n })\n return m\n}\n\ninterface MdToken {\n type?: string\n href?: string\n tokens?: MdToken[]\n items?: MdToken[]\n header?: Array<{ tokens?: MdToken[] }>\n rows?: Array<Array<{ tokens?: MdToken[] }>>\n}\n\n/**\n * Recursively neutralise script-bearing link/image hrefs in the lexed token tree.\n * Done as an explicit walk (not marked's `walkTokens` hook) because we render via\n * the low-level `lexer`+`parser` split, which does not run registered walkTokens.\n */\nfunction neutralizeUrls(tokens: MdToken[]): void {\n for (const t of tokens) {\n if ((t.type === \"link\" || t.type === \"image\") && typeof t.href === \"string\") {\n if (isDangerousUrl(t.href, t.type === \"image\")) t.href = \"#\"\n }\n if (t.tokens) neutralizeUrls(t.tokens)\n if (t.items) neutralizeUrls(t.items)\n if (t.header) for (const cell of t.header) if (cell.tokens) neutralizeUrls(cell.tokens)\n if (t.rows) for (const row of t.rows) for (const cell of row) if (cell.tokens) neutralizeUrls(cell.tokens)\n }\n}\n\n/** Add `data-source-line=\"N\"` to the first opening tag of a rendered block. */\nfunction tagSourceLine(html: string, line: number): string {\n return html.replace(/^(\\s*)<([a-zA-Z][\\w-]*)/, `$1<$2 data-source-line=\"${line}\"`)\n}\n\n/**\n * Render markdown to inner HTML, tagging each top-level block with its 1-based\n * source line so an annotation in the panel can map back to a plan line.\n */\nexport function renderMarkdownBody(source: string): string {\n const m = makeMarked()\n let tokens: Array<{ raw?: string }>\n try {\n tokens = m.lexer(source) as Array<{ raw?: string }>\n } catch {\n // Lexing should not fail, but never throw out of the hook path.\n return `<pre>${escapeHtml(source)}</pre>`\n }\n neutralizeUrls(tokens as MdToken[])\n let line = 1\n let out = \"\"\n for (const tok of tokens) {\n let html: string\n try {\n html = m.parser([tok] as Parameters<typeof m.parser>[0])\n } catch {\n html = \"\"\n }\n if (html.trim()) out += tagSourceLine(html, line)\n line += (tok.raw?.match(/\\n/g)?.length ?? 0)\n }\n return out || `<pre>${escapeHtml(source)}</pre>`\n}\n\n/**\n * Wrap rendered markdown in a complete, self-contained HTML document with\n * readable typography (works even before ai-or-die injects its annotation SDK).\n */\nexport function renderPlanHtml(source: string, title = \"Plan\"): string {\n return wrapArtifactDocument(renderMarkdownBody(source), title)\n}\n\nconst BASE_STYLE = ` :root {\n --bg: #0f1115; --fg: #f7f3ea; --muted: #aeb6c6; --border: #2a2f3a;\n --accent: #f4c95d; --code-bg: #171a21;\n --serif: 'Iowan Old Style', Georgia, 'Times New Roman', serif;\n --sans: ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;\n --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n }\n * { box-sizing: border-box; }\n html, body { margin: 0; background: var(--bg); color: var(--fg); }\n body { font-family: var(--serif); font-size: 16px; line-height: 1.6;\n padding: 32px clamp(16px, 5vw, 56px); }\n main { max-width: 78ch; margin: 0 auto; }\n h1, h2, h3, h4 { font-family: var(--sans); line-height: 1.25; margin: 1.6em 0 0.5em; }\n h1 { font-size: 1.9em; } h2 { font-size: 1.45em; padding-bottom: 0.2em;\n border-bottom: 1px solid var(--border); } h3 { font-size: 1.2em; }\n p, li { color: var(--fg); }\n a { color: var(--accent); }\n code { font-family: var(--mono); font-size: 0.9em; background: var(--code-bg);\n padding: 0.12em 0.35em; border-radius: 5px; }\n pre { background: var(--code-bg); border: 1px solid var(--border); border-radius: 8px;\n padding: 12px 14px; overflow: auto; }\n pre code { background: none; padding: 0; }\n blockquote { margin: 1em 0; padding: 0.2em 1em; border-left: 3px solid var(--accent);\n color: var(--muted); }\n table { border-collapse: collapse; width: 100%; margin: 1em 0; font-family: var(--sans);\n font-size: 0.95em; }\n th, td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; }\n th { background: var(--code-bg); }\n hr { border: 0; border-top: 1px solid var(--border); margin: 1.5em 0; }\n ul, ol { padding-left: 1.4em; }`\n\nconst INTERACTIVE_STYLE = `\n .aod-group { margin: 1.4em 0; padding: 14px 16px; border: 1px solid var(--border);\n border-radius: 10px; background: var(--code-bg); }\n .aod-prompt { font-family: var(--sans); font-weight: 600; margin: 0 0 0.6em; }\n .aod-options { display: flex; flex-wrap: wrap; gap: 8px; }\n .aod-multi-select .aod-options { flex-direction: column; gap: 6px; }\n .aod-action, .aod-submit { font-family: var(--sans); font-size: 0.95em; font-weight: 600;\n cursor: pointer; border: 1px solid var(--border); border-radius: 8px;\n padding: 8px 12px; background: var(--bg); color: var(--fg); }\n .aod-action:hover, .aod-submit:hover { border-color: var(--accent); }\n .aod-submit { margin-top: 10px; background: var(--accent); color: #17130a; border-color: var(--accent); }\n .aod-check { display: flex; align-items: center; gap: 8px; font-family: var(--sans); cursor: pointer; }\n .aod-steps { list-style: decimal; }\n .aod-step { margin: 0.5em 0; }\n .aod-step-actions { display: inline-flex; gap: 6px; margin-left: 8px; }`\n\n/**\n * Wrap rendered inner HTML in the self-contained document shell. `extraStyle` is\n * appended to the inline stylesheet so the interactive variant can add its own\n * rules without a second `<style>` block. Static callers pass \"\" (default), so\n * the static document is byte-identical to the pre-refactor output.\n */\nfunction wrapArtifactDocument(body: string, title: string, extraStyle = \"\"): string {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(title)}</title>\n<style>\n${BASE_STYLE}${extraStyle}\n</style>\n</head>\n<body>\n<main>\n${body}\n</main>\n</body>\n</html>\n`\n}\n\n/* -------------------------------------------------------------------------- */\n/* Interactive artifacts (contract v2.2 §4: declarative data-aod-* vocab) */\n/* -------------------------------------------------------------------------- */\n\nexport interface InteractiveOption {\n /** Stable id echoed back as `elementId` in the action event. Required. */\n elementId: string\n /** Human-visible label. */\n label: string\n /** Optional value echoed as `data-aod-value` (checkbox submits use \"true\"/\"false\"). */\n value?: string\n}\n\n/** One immediate-fire choice group: each option posts an action the instant it is clicked. */\nexport interface ChooseOneBlock {\n kind: \"choose-one\"\n /** `data-aod-group` shared by the options (marks them as one decision). */\n group: string\n prompt?: string\n /** `data-aod-action` verb for every option (default \"choose\"). */\n action?: string\n options: InteractiveOption[]\n}\n\n/** A multi-select group: checkbox toggles plus one submit that carries {group, selected}. */\nexport interface MultiSelectBlock {\n kind: \"multi-select\"\n group: string\n prompt?: string\n submitLabel?: string\n submitElementId?: string\n options: InteractiveOption[]\n}\n\nexport interface StepAction {\n /** `data-aod-action` verb (e.g. \"approve\", \"skip\"). */\n action: string\n label: string\n value?: string\n}\n\nexport interface StepItem {\n /** Stable `data-aod-id` echoed as `elementId`. */\n elementId: string\n label: string\n sourceLine?: number\n actions: StepAction[]\n}\n\n/** An ordered list of plan steps, each with its own inline action buttons. */\nexport interface StepsBlock {\n kind: \"steps\"\n steps: StepItem[]\n}\n\nexport type InteractiveBlock = ChooseOneBlock | MultiSelectBlock | StepsBlock\n\nexport interface InteractivePlanModel {\n /** Optional prose rendered above the interactive blocks (same escaping as static). */\n markdown?: string\n blocks: InteractiveBlock[]\n}\n\n/** Build a ` data-x=\"y\"` attribute string, dropping undefined values, all escaped. */\nfunction dataAttrs(pairs: Array<[string, string | undefined]>): string {\n let out = \"\"\n for (const [name, value] of pairs) {\n if (value === undefined) continue\n out += ` ${name}=\"${escapeHtml(value)}\"`\n }\n return out\n}\n\nfunction renderChooseOne(block: ChooseOneBlock): string {\n const action = block.action && block.action.trim() ? block.action : \"choose\"\n const prompt = block.prompt ? `<p class=\"aod-prompt\">${escapeHtml(block.prompt)}</p>` : \"\"\n const options = block.options\n .filter((o) => o.elementId.trim() !== \"\")\n .map((o) => {\n const attrs = dataAttrs([\n [\"data-aod-action\", action],\n [\"data-aod-group\", block.group],\n [\"data-aod-id\", o.elementId],\n [\"data-aod-value\", o.value],\n ])\n return `<button type=\"button\" class=\"aod-action\"${attrs}>${escapeHtml(o.label)}</button>`\n })\n .join(\"\\n\")\n return `<div class=\"aod-group aod-choose-one\"${dataAttrs([[\"data-aod-group\", block.group]])}>\n${prompt}<div class=\"aod-options\">\n${options}\n</div>\n</div>`\n}\n\nfunction renderMultiSelect(block: MultiSelectBlock): string {\n const prompt = block.prompt ? `<p class=\"aod-prompt\">${escapeHtml(block.prompt)}</p>` : \"\"\n const options = block.options\n .filter((o) => o.elementId.trim() !== \"\")\n .map((o) => {\n const attrs = dataAttrs([\n [\"data-aod-action\", \"check\"],\n [\"data-aod-group\", block.group],\n [\"data-aod-id\", o.elementId],\n [\"data-aod-value\", o.value],\n ])\n return `<label class=\"aod-check\"><input type=\"checkbox\"${attrs}> <span>${escapeHtml(o.label)}</span></label>`\n })\n .join(\"\\n\")\n const submitId = block.submitElementId && block.submitElementId.trim()\n ? block.submitElementId\n : `${block.group}-submit`\n const submitAttrs = dataAttrs([\n [\"data-aod-action\", \"submit\"],\n [\"data-aod-group\", block.group],\n [\"data-aod-id\", submitId],\n ])\n const submitLabel = block.submitLabel && block.submitLabel.trim() ? block.submitLabel : \"Submit\"\n return `<div class=\"aod-group aod-multi-select\"${dataAttrs([[\"data-aod-group\", block.group]])}>\n${prompt}<div class=\"aod-options\">\n${options}\n</div>\n<button type=\"button\" class=\"aod-submit\"${submitAttrs}>${escapeHtml(submitLabel)}</button>\n</div>`\n}\n\nfunction renderSteps(block: StepsBlock): string {\n const items = block.steps\n .filter((s) => s.elementId.trim() !== \"\")\n .map((s) => {\n const liAttrs = dataAttrs([\n [\"data-aod-id\", s.elementId],\n [\"data-source-line\", s.sourceLine === undefined ? undefined : String(s.sourceLine)],\n ])\n const actions = s.actions\n .map((a) => {\n const attrs = dataAttrs([\n [\"data-aod-action\", a.action],\n [\"data-aod-id\", s.elementId],\n [\"data-aod-value\", a.value],\n ])\n return `<button type=\"button\" class=\"aod-action\"${attrs}>${escapeHtml(a.label)}</button>`\n })\n .join(\"\")\n return `<li class=\"aod-step\"${liAttrs}><span class=\"aod-step-label\">${escapeHtml(s.label)}</span><span class=\"aod-step-actions\">${actions}</span></li>`\n })\n .join(\"\\n\")\n return `<ol class=\"aod-steps\">\n${items}\n</ol>`\n}\n\nfunction renderInteractiveBlock(block: InteractiveBlock): string {\n switch (block.kind) {\n case \"choose-one\":\n return renderChooseOne(block)\n case \"multi-select\":\n return renderMultiSelect(block)\n case \"steps\":\n return renderSteps(block)\n default:\n return \"\"\n }\n}\n\n/**\n * Render a typed interactive plan model into a self-contained HTML document that\n * carries the declarative `data-aod-*` action vocabulary the ai-or-die panel SDK\n * wires (contract v2.2 §4). Optional prose (`markdown`) is rendered with the SAME\n * escaping + dangerous-URL neutralization as the static path; all control\n * attributes and labels are HTML-escaped, so no author string can break out of an\n * attribute or inject live markup.\n */\nexport function renderInteractivePlanHtml(model: InteractivePlanModel, title = \"Plan\"): string {\n const prose = model.markdown && model.markdown.trim() ? renderMarkdownBody(model.markdown) : \"\"\n const blocks = model.blocks.map(renderInteractiveBlock).filter((h) => h.trim() !== \"\").join(\"\\n\")\n const body = [prose, blocks].filter((s) => s.trim() !== \"\").join(\"\\n\")\n return wrapArtifactDocument(body || `<pre>${escapeHtml(JSON.stringify(model))}</pre>`, title, INTERACTIVE_STYLE)\n}\n","/**\n * The internal `internal-artifact-open` subcommand: invoked by a spawned Claude\n * Code session's `PostToolUse` hook (matcher `ExitPlanMode`), registered into the\n * mirrored settings.json by the launcher when running inside an ai-or-die tab\n * (`AIORDIE_SESSION_ID` set). It auto-opens the just-finalized plan in the\n * ai-or-die Artifact review panel so the human reviews it WITHOUT the model\n * having to call artifact_open itself.\n *\n * Auth: AIORDIE_TOKEN is stripped from the child env, so the token can't come via\n * env or argv (argv leaks to `ps`). The launcher writes a mode-600\n * `.aiordie-artifact.json` into CLAUDE_CONFIG_DIR; this hook reads it.\n *\n * Plan: the EXACT plan for THIS session comes from the ExitPlanMode payload —\n * `tool_input.planFilePath` (per-session; never the globally-newest file in the\n * shared plans dir) with `tool_input.plan` as the markdown fallback. The plan\n * markdown is rendered to a self-contained styled HTML file (HTML is the\n * canonical artifact, lavish's model — formatted + annotatable, not raw md), and\n * THAT `.html` is opened.\n *\n * Side-effect only: never writes stdout, never throws, always exits 0. Skips\n * subagent payloads (agent_id/agent_type) like the other hooks.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync, realpathSync, writeFileSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport path from \"node:path\"\n\nimport { ArtifactClient } from \"./lib/artifact/client\"\nimport { renderPlanHtml } from \"./lib/artifact/plan-html\"\nimport { isSubagentContext } from \"./lib/orchestration/stop-gate-policy\"\n\ninterface ArtifactCreds {\n baseUrl: string\n token: string\n sessionId: string\n insecureTLS: boolean\n}\n\ninterface ExitPlanPayload {\n planFilePath?: string\n planMarkdown?: string\n}\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nfunction credsPath(): string {\n const dir = process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), \".claude\")\n return path.join(dir, \".aiordie-artifact.json\")\n}\n\nfunction isSubagent(payload: unknown): boolean {\n try {\n return isSubagentContext(payload as Parameters<typeof isSubagentContext>[0])\n } catch {\n return false\n }\n}\n\n/** Pull the per-session plan path + markdown content out of the hook payload. */\nexport function parseExitPlanPayload(raw: string): ExitPlanPayload {\n try {\n const obj = JSON.parse(raw) as { tool_input?: { planFilePath?: unknown; plan?: unknown } }\n const ti = obj.tool_input ?? {}\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim() ? ti.planFilePath : undefined\n const planMarkdown = typeof ti.plan === \"string\" && ti.plan.trim() ? ti.plan : undefined\n return { planFilePath, planMarkdown }\n } catch {\n return {}\n }\n}\n\nfunction readCreds(): ArtifactCreds | undefined {\n try {\n const parsed = JSON.parse(readFileSync(credsPath(), \"utf8\")) as Partial<ArtifactCreds>\n if (!parsed.baseUrl || !parsed.token || !parsed.sessionId) return undefined\n return {\n baseUrl: parsed.baseUrl,\n token: parsed.token,\n sessionId: parsed.sessionId,\n insecureTLS: parsed.insecureTLS === true,\n }\n } catch {\n return undefined\n }\n}\n\n/**\n * Resolve the plan markdown + a title, preferring the file at `planFilePath`\n * (the source of truth, may be newer than the payload's snapshot), falling back\n * to the inline `tool_input.plan` content.\n */\nfunction resolvePlanMarkdown(p: ExitPlanPayload): { markdown: string; title: string; nearPath?: string } | undefined {\n if (p.planFilePath) {\n try {\n const md = readFileSync(p.planFilePath, \"utf8\")\n if (md.trim()) return { markdown: md, title: path.basename(p.planFilePath, path.extname(p.planFilePath)), nearPath: p.planFilePath }\n } catch {\n /* fall through to inline content */\n }\n }\n if (p.planMarkdown) return { markdown: p.planMarkdown, title: \"Plan\" }\n return undefined\n}\n\n/**\n * Write the rendered HTML next to the plan (an allowed root) when we have a real\n * path, else into the plans dir under CLAUDE_CONFIG_DIR. Returns the realpath of\n * the written `.html`, or undefined on failure.\n */\nfunction writePlanHtml(html: string, nearPath: string | undefined): string | undefined {\n let target: string\n if (nearPath) {\n // `<plan>.md` -> `<plan>.aiordie.html` (or append when there is no .md ext).\n const base = nearPath.replace(/\\.(md|markdown)$/i, \"\")\n target = `${base}.aiordie.html`\n } else {\n const dir = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), \".claude\"), \"plans\")\n target = path.join(dir, `aiordie-plan-${process.pid}.html`)\n }\n try {\n writeFileSync(target, html, \"utf8\")\n try {\n return realpathSync.native(target)\n } catch {\n return target\n }\n } catch {\n return undefined\n }\n}\n\nexport const internalArtifactOpen = defineCommand({\n meta: { name: \"internal-artifact-open\", description: \"Open the finalized plan in the ai-or-die panel\" },\n async run() {\n try {\n const raw = readStdin()\n let payload: unknown\n try {\n payload = JSON.parse(raw)\n } catch {\n payload = undefined\n }\n if (isSubagent(payload)) return\n const creds = readCreds()\n if (!creds) return\n const plan = resolvePlanMarkdown(parseExitPlanPayload(raw))\n if (!plan) return\n const htmlPath = writePlanHtml(renderPlanHtml(plan.markdown, plan.title), plan.nearPath)\n if (!htmlPath) return\n const client = new ArtifactClient(creds)\n await client.open(htmlPath)\n } catch {\n /* side-effect only: never block, never throw */\n }\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAgBA,SAAS,WAAW,GAAmB;CACrC,OAAO,EACJ,QAAQ,MAAM,OAAO,CAAC,CACtB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,MAAM,CAAC,CACrB,QAAQ,MAAM,QAAQ,CAAC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
1
1
|
import { n as explicitPackageRoot, t as PACKAGE_ROOT_FLAG } from "./package-root-B-osctCk.js";
|
|
2
|
-
import {
|
|
2
|
+
import { f as stopReviewStateDir, n as fileFindingsStore } from "./stop-gate-policy-DQsfjnsx.js";
|
|
3
3
|
import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-BRL_y-bz.js";
|
|
4
|
-
import { a as runPlanReview, n as decidePlanReviewHook, r as filePlanReviewDebounce } from "./plan-review-hook-
|
|
4
|
+
import { a as runPlanReview, n as decidePlanReviewHook, r as filePlanReviewDebounce } from "./plan-review-hook-LfG01VMp.js";
|
|
5
5
|
import { defineCommand } from "citty";
|
|
6
6
|
import { mkdirSync, promises, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
7
|
import path from "node:path";
|
|
@@ -118,4 +118,4 @@ const internalPlanReview = defineCommand({
|
|
|
118
118
|
//#endregion
|
|
119
119
|
export { internalPlanReview };
|
|
120
120
|
|
|
121
|
-
//# sourceMappingURL=internal-plan-review-
|
|
121
|
+
//# sourceMappingURL=internal-plan-review-DbX-mr9i.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-plan-review-
|
|
1
|
+
{"version":3,"file":"internal-plan-review-DbX-mr9i.js","names":["fs"],"sources":["../src/internal-plan-review.ts"],"sourcesContent":["/**\n * The internal `internal-plan-review` subcommand: a PostToolUse(ExitPlanMode)\n * hook that spawns a bounded advisory critic review when the main agent finalizes\n * a substantive plan.\n *\n * It never blocks ExitPlanMode: the hook process exits 0 quickly after deciding\n * whether to spawn a detached reviewer. The detached child calls a cross-lab plan\n * critic and writes material findings to the SAME per-session findings store used\n * by the Stop review, so the next UserPromptSubmit surfaces them with the existing\n * non-authoritative findings path.\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 { promises as fs } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { PACKAGE_ROOT_FLAG, explicitPackageRoot } from \"./lib/package-root\"\n\nimport { hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport {\n decidePlanReviewHook,\n filePlanReviewDebounce,\n runPlanReview,\n type PlanReviewSpawnContext,\n} from \"./lib/orchestration/plan-review-hook\"\nimport { fileFindingsStore, stopReviewStateDir } from \"./lib/orchestration/stop-gate-policy\"\n\nfunction readStdin(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nasync function readDetachedPayload(): Promise<PlanReviewSpawnContext | undefined> {\n const payloadPath = (process.env.GH_ROUTER_PLAN_REVIEW_PAYLOAD ?? \"\").trim()\n if (payloadPath.length === 0) return undefined\n try {\n const raw = await fs.readFile(payloadPath, \"utf8\")\n await fs.unlink(payloadPath).catch(() => {})\n const parsed: unknown = JSON.parse(raw)\n if (!parsed || typeof parsed !== \"object\") return undefined\n const p = parsed as Partial<PlanReviewSpawnContext>\n if (!p.sessionId || !p.cwd || !p.plan || !p.planHash) return undefined\n return { sessionId: p.sessionId, cwd: p.cwd, plan: p.plan, planHash: p.planHash }\n } catch {\n await fs.unlink(payloadPath).catch(() => {})\n return undefined\n }\n}\n\nfunction spawnDetachedPlanReview(ctx: PlanReviewSpawnContext): void {\n let payloadPath: string | undefined\n try {\n const dir = stopReviewStateDir()\n mkdirSync(dir, { recursive: true })\n payloadPath = path.join(dir, `plan-review-${process.pid}-${randomBytes(4).toString(\"hex\")}.json`)\n writeFileSync(payloadPath, JSON.stringify(ctx), { mode: 0o600 })\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-plan-review\"], {\n detached: true,\n windowsHide: true,\n stdio: \"ignore\",\n env: { ...process.env, GH_ROUTER_PLAN_REVIEW_PAYLOAD: payloadPath },\n })\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 if (payloadPath) {\n try {\n unlinkSync(payloadPath)\n } catch {\n /* best-effort */\n }\n }\n }\n}\n\nexport const internalPlanReview = defineCommand({\n meta: {\n name: \"internal-plan-review\",\n description:\n \"Internal: advisory ExitPlanMode plan reviewer. Spawns a bounded detached critic review \"\n + \"for substantive plans and writes findings for the next prompt. Always exit 0.\",\n },\n async run() {\n try {\n const runtime = hookMcpRuntimeFromEnv()\n if (!runtime) return\n\n const detached = await readDetachedPayload()\n if (detached) {\n await runPlanReview({\n runtime,\n sessionId: detached.sessionId,\n cwd: detached.cwd,\n plan: detached.plan,\n findingsStore: fileFindingsStore(stopReviewStateDir()),\n })\n return\n }\n\n const decision = await decidePlanReviewHook({\n stdin: readStdin(),\n runtimeAvailable: true,\n debounce: filePlanReviewDebounce(stopReviewStateDir()),\n fallbackCwd: process.cwd(),\n })\n if (decision.kind === \"spawn\") spawnDetachedPlanReview(decision)\n } catch {\n /* side-effect only: never block ExitPlanMode */\n }\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAe,sBAAmE;CAChF,MAAM,eAAe,QAAQ,IAAI,iCAAiC,GAAA,CAAI,KAAK;CAC3E,IAAI,YAAY,WAAW,GAAG,OAAO,KAAA;CACrC,IAAI;EACF,MAAM,MAAM,MAAMA,SAAG,SAAS,aAAa,MAAM;EACjD,MAAMA,SAAG,OAAO,WAAW,CAAC,CAAC,YAAY,CAAC,CAAC;EAC3C,MAAM,SAAkB,KAAK,MAAM,GAAG;EACtC,I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qB,cAAc;CAC9C,MAAM;EACJ,MAAM;EACN,aACE;CAEJ;CACA,MAAM,MAAM;EACV,IAAI;GACF,MAAM,UAAU,sBAAsB;GACtC,IAAI,CAAC,SAAS;GAEd,MAAM,WAAW,MAAM,oBAAoB;GAC3C,IAAI,UAAU;IACZ,MAAM,cAAc;KAClB;KACA,WAAW,SAAS;KACpB,KAAK,SAAS;KACd,MAAM,SAAS;KACf,eAAe,kBAAkB,mBAAmB,CAAC;IACvD,CAAC;IACD;GACF;GAEA,MAAM,WAAW,MAAM,qBAAqB;IAC1C,OAAO,UAAU;IACjB,kBAAkB;IAClB,UAAU,uBAAuB,mBAAmB,CAAC;IACrD,aAAa,QAAQ,IAAI;GAC3B,CAAC;GACD,IAAI,SAAS,SAAS,SAAS,wBAAwB,QAAQ;EACjE,QAAQ,CAER;EACA,QAAQ,WAAW;CACrB;AACF,CAAC"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { i as parseBoolEnv } from "./exec-MCU1H-KZ.js";
|
|
2
|
-
import { o as fileBlockBudget } from "./stop-gate-hook-
|
|
3
|
-
import {
|
|
2
|
+
import { o as fileBlockBudget } from "./stop-gate-hook-C9VNxmt1.js";
|
|
3
|
+
import { f as stopReviewStateDir, i as fileRebriefBindingStore, n as fileFindingsStore, o as fileRewriteFlagStore, r as fileLastPromptStore } from "./stop-gate-policy-DQsfjnsx.js";
|
|
4
4
|
import { n as callMcpTool, r as hookMcpRuntimeFromEnv, t as callInference } from "./hook-mcp-client-BRL_y-bz.js";
|
|
5
|
-
import {
|
|
5
|
+
import { c as CHEAPEST_REWRITE_GUIDANCE_CAP, f as isCheapestRewriteDisabledEnv, i as decidePromptSubmitV2, l as CHEAPEST_REWRITE_MODEL, r as decidePromptSubmit, s as CHEAPEST_REWRITE_EFFORT, u as CHEAPEST_REWRITE_STRUCTURE_CAP } from "./prompt-submit-hook-DzhmQRs_.js";
|
|
6
6
|
import { defineCommand } from "citty";
|
|
7
7
|
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
8
8
|
import path from "node:path";
|
|
@@ -547,6 +547,20 @@ const internalPromptSubmit = defineCommand({
|
|
|
547
547
|
stdin,
|
|
548
548
|
steerEnabled
|
|
549
549
|
});
|
|
550
|
+
try {
|
|
551
|
+
const parsed = JSON.parse(stdin);
|
|
552
|
+
const sid = typeof parsed.session_id === "string" ? parsed.session_id : "";
|
|
553
|
+
const tp = typeof parsed.transcript_path === "string" ? parsed.transcript_path : "";
|
|
554
|
+
if (sid && tp) {
|
|
555
|
+
const ws = workspaceFromStdin(stdin);
|
|
556
|
+
await fileRebriefBindingStore(stopReviewStateDir()).write({
|
|
557
|
+
sessionId: sid,
|
|
558
|
+
transcriptPath: tp,
|
|
559
|
+
cwd: ws,
|
|
560
|
+
atMs: Date.now()
|
|
561
|
+
}).catch(() => {});
|
|
562
|
+
}
|
|
563
|
+
} catch {}
|
|
550
564
|
if (decision.resetSession) await fileBlockBudget(path.join(tmpdir(), "gh-router-stopgate")).reset(decision.resetSession).catch(() => {});
|
|
551
565
|
if (decision.inject.length > 0) await new Promise((resolve) => process.stdout.write(`${decision.inject}\n`, () => resolve()));
|
|
552
566
|
} catch {}
|
|
@@ -554,6 +568,6 @@ const internalPromptSubmit = defineCommand({
|
|
|
554
568
|
}
|
|
555
569
|
});
|
|
556
570
|
//#endregion
|
|
557
|
-
export { internalPromptSubmit };
|
|
571
|
+
export { internalPromptSubmit as n, buildStaticPack as t };
|
|
558
572
|
|
|
559
|
-
//# sourceMappingURL=internal-prompt-submit-
|
|
573
|
+
//# sourceMappingURL=internal-prompt-submit-UhfnM_qG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-prompt-submit-UhfnM_qG.js","names":[],"sources":["../src/internal-prompt-submit.ts"],"sourcesContent":["/**\n * The internal `internal-prompt-submit` subcommand: the executable a spawned\n * Claude Code session's `UserPromptSubmit` hook invokes (registered into the\n * mirrored settings.json by the launcher). It serves the front-end of the\n * floor-raising surface on one event:\n * 1. resets the Stop-gate's per-session block budget (making `maxBlocks`\n * per-prompt);\n * 2. stashes the prompt + surfaces the prior turn's advisory review findings;\n * 3. for a non-trivial prompt, injects a GROUNDED, user-derived scope/goal\n * note (one gpt-6-luna call at high effort over the prompt + grounding\n * code search — local ColBERT when --search is on, Bluebird when\n * --bluebird is on, lexical-only otherwise) — or, when the proxy URL/nonce\n * isn't wired or anything errors,\n * falls open to the v1 regex goal.\n * 4. on a cheapest-profile launch only, tries FIRST a Sol (gpt-5.6-sol,\n * medium) rewrite of the prompt into a short structured EXECUTION BRIEF over\n * the prompt + AGENTS.md/CLAUDE.md + repo structure + ecosystem's verify\n * command + grounding search\n * (adaptive 3 turns, up to 5 on Sol's deep-grounding flag) — additive,\n * never replacing the user prompt — and falls back to (3) on any miss.\n * One-shot per session (first non-trivial prompt only, marked on\n * attempt even if Sol fails open). Opt out with\n * GH_ROUTER_DISABLE_CHEAPEST_REWRITE=1.\n *\n * ALWAYS exits 0 (never blocks the prompt): the steer is additive context, and a\n * UserPromptSubmit hook that exit-2'd would refuse the user's prompt. The pure\n * v1 path (`decidePromptSubmit`) is the fail-open fallback; V2\n * (`decidePromptSubmitV2`) layers the grounded enrichment on top via injected IO.\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\nimport {\n CHEAPEST_REWRITE_EFFORT,\n CHEAPEST_REWRITE_GUIDANCE_CAP,\n CHEAPEST_REWRITE_MODEL,\n CHEAPEST_REWRITE_STRUCTURE_CAP,\n CHEAPEST_REWRITE_TEST_CMD_CAP,\n isCheapestRewriteDisabledEnv,\n} from \"./lib/cheapest-prompt-rewrite\"\nimport { parseBoolEnv } from \"./lib/exec\"\nimport { callInference, callMcpTool, hookMcpRuntimeFromEnv } from \"./lib/orchestration/hook-mcp-client\"\nimport { fileBlockBudget } from \"./lib/orchestration/stop-gate-hook\"\nimport {\n decidePromptSubmit,\n decidePromptSubmitV2,\n type PromptSubmitDecision,\n} from \"./lib/orchestration/prompt-submit-hook\"\nimport {\n fileFindingsStore,\n fileLastPromptStore,\n fileRebriefBindingStore,\n fileRewriteFlagStore,\n stopReviewStateDir,\n} from \"./lib/orchestration/stop-gate-policy\"\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/** Parse the session cwd from the payload — the workspace the grounding search\n * runs in. Falls back to the process cwd. */\nfunction workspaceFromStdin(stdin: string): string {\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") {\n const cwd = (p as { cwd?: unknown }).cwd\n if (typeof cwd === \"string\" && cwd.length > 0) return cwd\n }\n } catch {\n /* fall through */\n }\n return process.cwd()\n}\n\n/** Per-call timeout for the grounding search (short — it must not stall the prompt). */\nconst SEARCH_TIMEOUT_MS = 8_000\n/** Per-call timeout for a single Sol/Luna inference. */\nconst INFER_TIMEOUT_MS = 25_000\n/**\n * Overall budget for the cheapest Sol rewrite (search + Sol, 3 turns default\n * with one adaptive extension to 5). The hook is registered with a 90s host\n * timeout. A rewrite timeout is TERMINAL — the orchestrator falls open to the\n * cheap regex goal and does NOT then run the Luna scope path — so the worst\n * case is one rewrite (≤30s) OR one Luna scope (≤22s), never both.\n */\nconst REWRITE_TIMEOUT_MS = 30_000\n\n/** Read a text file best-effort, capped; missing/unreadable -> \"\". */\nfunction readCappedFile(absPath: string, cap: number): string {\n try {\n return readFileSync(absPath, \"utf8\").slice(0, cap)\n } catch {\n return \"\"\n }\n}\n\n/** The subset of package.json this module reads. */\ninterface PackageJsonShape {\n scripts?: Record<string, string>\n packageManager?: string\n dependencies?: Record<string, string>\n}\n\n/**\n * Markers that identify the top of a project when there is no `.git` above\n * (a plain directory, a tarball, a scratch tree). Ordered only for readability —\n * the walk is first-hit-wins.\n */\nconst PROJECT_ROOT_MARKERS = [\n \"package.json\", \"go.mod\", \"Cargo.toml\", \"pyproject.toml\", \"setup.py\",\n \"mix.exs\", \"Gemfile\", \"deno.json\", \"deno.jsonc\", \"global.json\",\n \"Makefile\", \"makefile\", \"GNUmakefile\",\n]\n\n/**\n * Resolve the project root for `startDir`: the nearest ancestor (inclusive)\n * holding a `.git` entry — a file in worktrees/submodules, else a directory.\n *\n * A `.git` anywhere in the walk WINS over a nearer project marker, because\n * inside a repository the root's guidance is the one that applies: a workspace\n * package with its own `package.json` must not become the root, or the\n * repo-root `AGENTS.md` would never be read. With no `.git` above (non-repo\n * working tree), the nearest project marker is the best available root, so\n * non-git projects still get hierarchical guidance.\n *\n * Sync `existsSync` only, deliberately: this runs inside the rewrite's 30s\n * budget on every non-trivial prompt, and the async `repoRoot()` helper in\n * `stop-gate-policy` spawns `git rev-parse` — too expensive for a value a\n * directory probe answers. Falls back to `startDir`, and the walk is bounded\n * so a deep or symlinked path can't spin.\n */\nfunction resolveProjectRoot(startDir: string): string {\n const start = path.resolve(startDir)\n const MAX_ROOT_LEVELS = 8\n let current = start\n let nearestMarker: string | undefined\n for (let i = 0; i < MAX_ROOT_LEVELS; i++) {\n if (existsSync(path.join(current, \".git\"))) return current\n if (!nearestMarker && PROJECT_ROOT_MARKERS.some((m) => existsSync(path.join(current, m)))) {\n nearestMarker = current\n }\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return nearestMarker ?? start\n}\n\n/**\n * Read the nearest AGENTS.md / CLAUDE.md guidance for `startDir`, walking up\n * toward (and including) `root`. Frontier guidance treats AGENTS.md as\n * hierarchical: the closest file to the work wins — so the chain is built and\n * joined CLOSEST-FIRST. That ordering is load-bearing, not cosmetic: the caller\n * truncates the joined text with `slice(0, CAP)`, which keeps the head, so\n * closest-first is what makes the nearest file survive the budget. (Root-first\n * ordering plus a head-truncating slice silently starves the nearest guidance.)\n *\n * The walk is bounded to `MAX_LEVELS` directories from the start dir and always\n * includes the root, so a deep subdirectory still sees repo-root conventions\n * without paying to read every level. AGENTS.md and CLAUDE.md are collected\n * independently; the caller uses CLAUDE.md only when no AGENTS.md was found at\n * any level. Returns empty strings when none exist.\n */\nfunction readHierarchicalGuidance(\n startDir: string,\n root: string,\n): { agentsMd: string; claudeMd: string } {\n const start = path.resolve(startDir)\n const rootAbs = path.resolve(root)\n // Closest-first chain: [start, …bounded ancestors…, root].\n const dirs: Array<string> = []\n let current = start\n const MAX_LEVELS = 3\n for (let i = 0; i < MAX_LEVELS; i++) {\n dirs.push(current)\n if (current === rootAbs) break\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n if (!dirs.includes(rootAbs)) dirs.push(rootAbs)\n\n const agentsParts: Array<string> = []\n const claudeParts: Array<string> = []\n for (const dir of dirs) {\n const agents = readCappedFile(path.join(dir, \"AGENTS.md\"), CHEAPEST_REWRITE_GUIDANCE_CAP)\n if (agents.length > 0) agentsParts.push(agents)\n const claude = readCappedFile(path.join(dir, \"CLAUDE.md\"), CHEAPEST_REWRITE_GUIDANCE_CAP)\n if (claude.length > 0) claudeParts.push(claude)\n }\n return {\n agentsMd: agentsParts.join(\"\\n\").slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP),\n claudeMd: claudeParts.join(\"\\n\").slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP),\n }\n}\n\n// ---------------------------------------------------------------------------\n// VERIFY COMMAND detection — ecosystem generic on purpose.\n//\n// The line is presented to Luna as *the* exact command to verify the work, so\n// a wrong guess is worse than no guess: an `npm`-only implementation (the\n// previous behavior) emitted `npm test` for bun/yarn/pnpm repos, `npx npm\n// test` whenever vitest happened to be a dependency, and `\"\"` for every\n// non-JavaScript repo. Three tiers, first hit wins, and `\"\"` stays the honest\n// answer when nothing is derivable:\n//\n// Tier 0 first-class toolchains with one canonical command\n// 0a package.json scripts at the session cwd\n// 0b an ancestor workspace manifest (monorepo sub-package), labeled\n// with the directory to run it in\n// 0c .NET (`*.sln` / `*.csproj`)\n// Tier 1 marker ladder: go, rust, python, elixir, ruby, deno, make\n//\n// Tier 0 outranks the ladder because a repo with a `Makefile` *and* a\n// `package.json` normally uses the Makefile as a wrapper, not as the gate.\n// ---------------------------------------------------------------------------\n\ntype PackageRunner = \"npm\" | \"pnpm\" | \"yarn\" | \"bun\"\n\n/** `packageManager` is versioned (`\"pnpm@9.1.0\"`) — take the leading name. */\nfunction runnerFromPackageManager(value: string | undefined): PackageRunner | undefined {\n if (typeof value !== \"string\") return undefined\n // Manager names are never scoped, so the version is everything after the\n // first `@`; taking the last segment would yield \"9.1.0\".\n const name = value.trim().split(\"@\")[0]?.trim() ?? \"\"\n return name === \"npm\" || name === \"pnpm\" || name === \"yarn\" || name === \"bun\"\n ? name\n : undefined\n}\n\n/** Lockfile → runner, searching `dirs` in order (nearest first). */\nfunction runnerFromLockfiles(dirs: Array<string>): PackageRunner | undefined {\n const table: Array<[string, PackageRunner]> = [\n [\"bun.lock\", \"bun\"],\n [\"bun.lockb\", \"bun\"],\n [\"pnpm-lock.yaml\", \"pnpm\"],\n [\"yarn.lock\", \"yarn\"],\n [\"package-lock.json\", \"npm\"],\n ]\n for (const dir of dirs) {\n for (const [lockfile, runner] of table) {\n if (existsSync(path.join(dir, lockfile))) return runner\n }\n }\n return undefined\n}\n\n/** Lockfile-less repos still name their runner in the script bodies. */\nfunction runnerFromScriptBodies(scripts: Record<string, string>): PackageRunner | undefined {\n for (const body of Object.values(scripts)) {\n if (typeof body !== \"string\") continue\n const head = body.trimStart()\n if (head.startsWith(\"bun \")) return \"bun\"\n if (head.startsWith(\"pnpm \")) return \"pnpm\"\n if (head.startsWith(\"yarn \")) return \"yarn\"\n if (head.startsWith(\"npm \")) return \"npm\"\n }\n return undefined\n}\n\n/** Resolve the package runner for `dir`'s project. */\nfunction resolvePackageRunner(\n dir: string,\n root: string,\n pkg: PackageJsonShape,\n): PackageRunner {\n return runnerFromPackageManager(pkg.packageManager)\n ?? runnerFromLockfiles([dir, root])\n ?? runnerFromScriptBodies(pkg.scripts ?? {})\n ?? \"npm\"\n}\n\n/**\n * `<runner> run <name>` for EVERY script name, including `test`.\n *\n * The obvious shorthand (`npm test`) is NOT safe: `bun test` invokes Bun's\n * built-in test runner and ignores the `test` script entirely, so a repo whose\n * `test` script is `bun run build && bun scripts/run-tests.ts` would be told to\n * skip its own build and orchestrator. `run` is accepted by npm, pnpm, yarn\n * (1 and berry) and bun alike.\n */\nfunction scriptCommand(runner: PackageRunner, name: string): string {\n return `${runner} run ${name}`\n}\n\n/** Pick test/build/lint scripts, in preference order. */\nfunction pickVerifyScripts(scripts: Record<string, string>): Array<string> {\n const preferred = [\"test\", \"test:unit\", \"build\", \"typecheck\", \"lint\"]\n return preferred.filter((name) => {\n const body = scripts[name]\n return typeof body === \"string\" && body.trim().length > 0\n })\n}\n\n/** Directories never worth descending when looking for project files. */\nconst SCAN_SKIP_DIRS = new Set([\n \".git\", \"node_modules\", \"dist\", \"build\", \"out\", \"target\", \"bin\", \"obj\",\n \"vendor\", \"venv\", \".venv\", \"__pycache__\", \"coverage\", \".next\", \".turbo\",\n])\n\n/**\n * Bounded search for a project file (`*.sln`, `*.csproj`) at `dir` and up to\n * `maxDepth` levels below it. Entries are capped per directory so a huge tree\n * can't stall the hook, and heavy/known-noise directories are skipped.\n */\nfunction findProjectFile(\n dir: string,\n matches: (name: string) => boolean,\n maxDepth = 2,\n): string | undefined {\n if (maxDepth < 0) return undefined\n let entries: Array<{ name: string; isDirectory: () => boolean }>\n try {\n entries = readdirSync(dir, { withFileTypes: true }).slice(0, 200)\n } catch {\n return undefined\n }\n for (const entry of entries) {\n if (matches(entry.name)) return entry.name\n }\n if (maxDepth === 0) return undefined\n for (const entry of entries) {\n if (!entry.isDirectory() || SCAN_SKIP_DIRS.has(entry.name)) continue\n const hit = findProjectFile(path.join(dir, entry.name), matches, maxDepth - 1)\n if (hit) return hit\n }\n return undefined\n}\n\ninterface Verification {\n /** Short ecosystem label for repoStructure; \"\" when undetermined. */\n ecosystem: string\n /** The VERIFY COMMAND line, or \"\" when nothing is derivable. */\n verifyCommand: string\n}\n\nconst NO_VERIFICATION: Verification = { ecosystem: \"\", verifyCommand: \"\" }\n\n/** Tier 0c: .NET. `dotnet test` restores + builds, but a solution-wide build\n * is still the gate, and `dotnet format` is only proposed when the repo\n * actually carries an .editorconfig to check against. */\nfunction dotnetVerification(root: string, cwd: string): Verification | undefined {\n for (const dir of root === cwd ? [cwd] : [root, cwd]) {\n const project = findProjectFile(dir, (name) => /\\.(sln|csproj)$/i.test(name))\n if (!project) continue\n const commands = [\"dotnet build\", \"dotnet test\"]\n if (existsSync(path.join(dir, \".editorconfig\"))) {\n commands.push(\"dotnet format --verify-no-changes\")\n }\n return {\n ecosystem: `dotnet (${project})`,\n verifyCommand: `VERIFY COMMAND: ${commands.join(\" ; \")}`,\n }\n }\n return undefined\n}\n\n/** Parse `name:` target lines out of a Makefile (skipping `%` pattern rules). */\nfunction makeTargets(dir: string): Set<string> {\n const body = readCappedFile(\n [\"Makefile\", \"makefile\", \"GNUmakefile\"]\n .map((name) => path.join(dir, name))\n .find((abs) => existsSync(abs)) ?? path.join(dir, \"Makefile\"),\n 8 * 1024,\n )\n const targets = new Set<string>()\n for (const line of body.split(\"\\n\")) {\n const match = /^([A-Za-z0-9][A-Za-z0-9_.-]*)\\s*:(?!=)/.exec(line)\n if (match?.[1] && !match[1].includes(\"%\")) targets.add(match[1])\n }\n return targets\n}\n\n/** Tier 1 ladder. First marker hit wins; each entry returns \"\" for a repo it\n * recognizes but can't derive a command for (which lets the next probe try). */\nfunction markerVerification(cwd: string, root: string): Verification {\n for (const dir of root === cwd ? [cwd] : [cwd, root]) {\n if (existsSync(path.join(dir, \"go.mod\"))) {\n return {\n ecosystem: \"go (go.mod)\",\n verifyCommand: \"VERIFY COMMAND: go build ./... ; go test ./... ; go vet ./...\",\n }\n }\n if (existsSync(path.join(dir, \"Cargo.toml\"))) {\n return {\n ecosystem: \"rust (Cargo.toml)\",\n verifyCommand: \"VERIFY COMMAND: cargo build ; cargo test\",\n }\n }\n if (existsSync(path.join(dir, \"mix.exs\"))) {\n return { ecosystem: \"elixir (mix.exs)\", verifyCommand: \"VERIFY COMMAND: mix test\" }\n }\n if (existsSync(path.join(dir, \"Gemfile\"))) {\n const spec = findProjectFile(dir, (name) => name === \"spec\", 0) !== undefined\n return {\n ecosystem: \"ruby (Gemfile)\",\n verifyCommand: spec\n ? \"VERIFY COMMAND: bundle exec rspec\"\n : \"VERIFY COMMAND: bundle exec rake test\",\n }\n }\n const denoConfig = [\"deno.json\", \"deno.jsonc\"]\n .map((name) => path.join(dir, name))\n .find((abs) => existsSync(abs))\n if (denoConfig) {\n const tasks = readCappedFile(denoConfig, 32 * 1024)\n if (/\"test\"\\s*:/.test(tasks) || /'test'\\s*:/.test(tasks)) {\n return { ecosystem: \"deno (deno.json)\", verifyCommand: \"VERIFY COMMAND: deno task test\" }\n }\n }\n // Python: propose a pytest line when a pytest config OR a test directory is\n // present — most projects run pytest with zero config, so requiring a\n // config section would miss them, while a repo with no tests at all still\n // gets no guess.\n const pyproject = path.join(dir, \"pyproject.toml\")\n const pyprojectBody = readCappedFile(pyproject, 32 * 1024)\n const setupCfg = readCappedFile(path.join(dir, \"setup.cfg\"), 32 * 1024)\n const hasTests = [\"tests\", \"test\"].some(\n (name) => findProjectFile(dir, (entry) => entry === name, 0) !== undefined,\n )\n const hasPytest = hasTests\n || existsSync(path.join(dir, \"pytest.ini\"))\n || existsSync(path.join(dir, \"tox.ini\"))\n || /\\[tool\\.pytest/.test(pyprojectBody)\n || /\\[tool:pytest\\]/.test(setupCfg)\n if (hasPytest) {\n const test = existsSync(path.join(dir, \"uv.lock\"))\n ? \"uv run pytest\"\n : existsSync(path.join(dir, \"poetry.lock\"))\n ? \"poetry run pytest\"\n : existsSync(path.join(dir, \"Pipfile\"))\n ? \"pipenv run pytest\"\n : \"pytest\"\n const commands = [test]\n if (existsSync(path.join(dir, \"mypy.ini\")) || /\\[tool\\.mypy/.test(pyprojectBody)) {\n commands.push(\"mypy .\")\n }\n if (existsSync(path.join(dir, \"ruff.toml\")) || /\\[tool\\.ruff/.test(pyprojectBody)) {\n commands.push(\"ruff check .\")\n }\n return {\n ecosystem: `python (${path.basename(pyproject)})`,\n verifyCommand: `VERIFY COMMAND: ${commands.join(\" ; \")}`,\n }\n }\n if (existsSync(path.join(dir, \"Makefile\")) || existsSync(path.join(dir, \"makefile\"))\n || existsSync(path.join(dir, \"GNUmakefile\"))) {\n const targets = makeTargets(dir)\n const picked = [\"test\", \"tests\", \"check\", \"ci\", \"verify\", \"build\", \"lint\"]\n .filter((name) => targets.has(name))\n .slice(0, 2)\n if (picked.length > 0) {\n return {\n ecosystem: \"make (Makefile)\",\n verifyCommand: `VERIFY COMMAND: ${picked.map((t) => `make ${t}`).join(\" ; \")}`,\n }\n }\n }\n }\n return NO_VERIFICATION\n}\n\n/** Full detection: JS/TS first, then .NET, then the marker ladder. */\nfunction detectVerification(cwd: string, root: string): Verification {\n const cwdPkg = readPackageJson(cwd)\n if (cwdPkg) {\n const picks = pickVerifyScripts(cwdPkg.scripts ?? {})\n if (picks.length > 0) {\n const runner = resolvePackageRunner(cwd, root, cwdPkg)\n return {\n ecosystem: `node (${runner})`,\n verifyCommand: `VERIFY COMMAND: ${picks.map((n) => scriptCommand(runner, n)).join(\" ; \")}`,\n }\n }\n }\n // Monorepo sub-package: an ancestor workspace manifest is the real gate, and\n // its scripts must be run from that directory — so say so in the line itself.\n // Walked explicitly (rather than only checking the project root) so a\n // workspace root several levels up is still found, and bounded so a deep\n // sub-package can't pay for a long ascent.\n const ancestor = findAncestorScriptRoot(cwd, root)\n if (ancestor) {\n const { dir, pkg } = ancestor\n const runner = resolvePackageRunner(dir, root, pkg)\n return {\n ecosystem: `node (${runner}, workspace root)`,\n verifyCommand:\n `VERIFY COMMAND (run from ${dir}): `\n + pickVerifyScripts(pkg.scripts ?? {}).map((n) => scriptCommand(runner, n)).join(\" ; \"),\n }\n }\n return dotnetVerification(root, cwd) ?? markerVerification(cwd, root)\n}\n\n/**\n * Nearest strict ancestor of `cwd` whose package.json declares at least one\n * recognized verify script — the monorepo case, where the workspace manifest is\n * the real gate. Never ascends above `root` (so a stray `~/package.json` can't\n * be picked up for a session already at the project root), and bounded so a\n * deep sub-package can't pay for a long ascent.\n */\nfunction findAncestorScriptRoot(\n cwd: string,\n root: string,\n): { dir: string; pkg: PackageJsonShape } | undefined {\n const start = path.resolve(cwd)\n const rootAbs = path.resolve(root)\n if (rootAbs === start) return undefined\n const MAX_ASCENT = 4\n let current = path.dirname(start)\n for (let i = 0; i <= MAX_ASCENT; i++) {\n const pkg = readPackageJson(current)\n if (pkg && pickVerifyScripts(pkg.scripts ?? {}).length > 0) {\n return { dir: current, pkg }\n }\n if (current === rootAbs) break\n const parent = path.dirname(current)\n if (parent === current) break\n current = parent\n }\n return undefined\n}\n\nfunction readPackageJson(dir: string): PackageJsonShape | undefined {\n const raw = readCappedFile(path.join(dir, \"package.json\"), 64 * 1024)\n if (raw.length === 0) return undefined\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as PackageJsonShape\n }\n } catch {\n /* malformed package.json is not fatal — fall through to the other tiers */\n }\n return undefined\n}\n\n/**\n * Static repo context for the cheapest rewrite: hierarchical AGENTS.md\n * (preferred) / CLAUDE.md (fallback) + top-level structure + a detected\n * ecosystem + its VERIFY COMMAND line. All synchronous (tiny reads) and\n * capped; missing files yield \"\".\n */\nexport function buildStaticPack(workspace: string): {\n agentsMd: string\n claudeMd: string\n repoStructure: string\n verifyCommand: string\n} {\n // The hook runs in the session cwd; walk guidance from there up to the repo\n // root, and reuse that root for lockfile/root-manifest detection.\n const root = resolveProjectRoot(workspace)\n const guidance = readHierarchicalGuidance(workspace, root)\n const agentsMd = guidance.agentsMd\n const claudeMd = agentsMd.length > 0 ? \"\" : guidance.claudeMd\n let listing: string\n try {\n const entries = readdirSync(workspace, { withFileTypes: true })\n .slice(0, 60)\n .map((e) => (e.isDirectory() ? `${e.name}/` : e.name))\n listing = entries.join(\", \")\n } catch {\n listing = \"\"\n }\n let pkgSnippet: string\n const pkg = readPackageJson(workspace)\n if (pkg) {\n const scripts = pkg.scripts ? Object.keys(pkg.scripts).slice(0, 20).join(\", \") : \"\"\n const deps = Object.keys(pkg.dependencies ?? {}).slice(0, 20).join(\", \")\n pkgSnippet = `scripts: [${scripts}] deps: [${deps}]`\n } else {\n pkgSnippet = \"\"\n }\n const { ecosystem, verifyCommand: detected } = detectVerification(workspace, root)\n // The ecosystem line gives Sol a type signal even when no command could be\n // derived, which is what makes an empty VERIFY COMMAND interpretable.\n const repoStructure = [\n `top-level: ${listing}`,\n ecosystem ? `ecosystem: ${ecosystem}` : \"\",\n pkgSnippet,\n ]\n .filter((s) => s.trim().length > 0 && s !== \"top-level: \")\n .join(\"\\n\")\n .slice(0, CHEAPEST_REWRITE_STRUCTURE_CAP)\n return {\n agentsMd,\n claudeMd,\n repoStructure,\n verifyCommand: detected.slice(0, CHEAPEST_REWRITE_TEST_CMD_CAP),\n }\n}\n\nexport const internalPromptSubmit = defineCommand({\n meta: {\n name: \"internal-prompt-submit\",\n description:\n \"Internal: the UserPromptSubmit hook. Resets the Stop-gate per-prompt block \"\n + \"budget, surfaces prior-turn review findings, and injects a grounded advisory goal \"\n + \"for non-trivial prompts. Always exit 0.\",\n },\n async run() {\n try {\n const stdin = readStdin()\n const steerEnabled = parseBoolEnv(process.env.GH_ROUTER_DISABLE_PROMPT_STEER) !== true\n // Search capability for tip/enrichment text. The launcher exports\n // GH_ROUTER_SEARCH_ENABLED (\"1\"/\"0\") from its resolved\n // `state.searchEnabled` before spawning the session, so this\n // short-lived hook process inherits the launch's capability even when\n // the opt-in came from the `--search` CLI flag (which otherwise would\n // not survive the process boundary). Falls back to the raw opt-in env\n // for standalone invocations.\n const searchEnabled = process.env.GH_ROUTER_SEARCH_ENABLED !== undefined\n ? process.env.GH_ROUTER_SEARCH_ENABLED === \"1\"\n : process.env.GH_ROUTER_ENABLE_SEMANTIC_SEARCH === \"1\"\n const bluebirdEnabled = process.env.GH_ROUTER_BLUEBIRD_ENABLED === \"1\"\n const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n // Cheapest-only Sol rewrite identity: the launcher exports\n // GH_ROUTER_PROFILE; only the literal \"cheapest\" alias enables the\n // rewrite branch (checked again inside decidePromptSubmitV2).\n const profile = (process.env.GH_ROUTER_PROFILE ?? \"\").trim().toLowerCase()\n const rewriteDisabled = isCheapestRewriteDisabledEnv()\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\n searchEnabled,\n bluebirdEnabled,\n profile,\n rewriteDisabled,\n rewrite: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n inferSol: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: CHEAPEST_REWRITE_MODEL,\n instructions: system,\n input: user,\n effort: CHEAPEST_REWRITE_EFFORT,\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n // Lazy: fs reads run only when the cheapest branch actually fires.\n staticPack: async () => buildStaticPack(workspace),\n // Session-keyed one-shot flag: first non-trivial prompt per\n // session spends the rewrite; later prompts use the Luna path.\n hasRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).hasRun(sid),\n markRewriteRun: (sid) => fileRewriteFlagStore(stopReviewStateDir()).markRun(sid),\n timeoutMs: REWRITE_TIMEOUT_MS,\n },\n io: {\n searchCode: async (query, mode, signal) => {\n const r = await callMcpTool({\n runtime,\n group: \"search\",\n tool: \"code\",\n args: { query, workspace, mode, limit: 10, summary: false },\n timeoutMs: SEARCH_TIMEOUT_MS,\n signal,\n })\n return r.isError ? \"\" : r.text\n },\n infer: (system, user, signal) =>\n callInference({\n serverUrl: runtime.serverUrl,\n model: \"gpt-6-luna\",\n instructions: system,\n input: user,\n effort: \"high\",\n timeoutMs: INFER_TIMEOUT_MS,\n signal,\n }),\n readFindings: (sid) => fileFindingsStore(stopReviewStateDir()).read(sid),\n clearFindings: (sid) => fileFindingsStore(stopReviewStateDir()).clear(sid),\n storePrompt: (sid, prompt) => fileLastPromptStore(stopReviewStateDir()).write(sid, prompt),\n },\n })\n } else {\n // Proxy URL/nonce not wired -> the LLM layer is off; use the pure v1 path.\n decision = decidePromptSubmit({ stdin, steerEnabled })\n }\n\n // Per-workspace rebrief binding: the only way skill-spawned\n // internal-rebrief (no hook stdin) can locate the live transcript, the\n // session id (for findings), and the stored prompt. Refreshed on EVERY\n // prompt so it always tracks the current session, surviving /resume and\n // /clear within the session (same cwd key).\n try {\n const parsed = JSON.parse(stdin) as Record<string, unknown>\n const sid = typeof parsed.session_id === \"string\" ? parsed.session_id : \"\"\n const tp = typeof parsed.transcript_path === \"string\" ? parsed.transcript_path : \"\"\n if (sid && tp) {\n const ws = workspaceFromStdin(stdin)\n await fileRebriefBindingStore(stopReviewStateDir()).write({\n sessionId: sid,\n transcriptPath: tp,\n cwd: ws,\n atMs: Date.now(),\n }).catch(() => {})\n }\n } catch {\n /* binding refresh is best-effort */\n }\n\n if (decision.resetSession) {\n // Same budget store the Stop hook uses, so a new prompt clears its count.\n await fileBlockBudget(path.join(tmpdir(), \"gh-router-stopgate\"))\n .reset(decision.resetSession)\n .catch(() => {})\n }\n if (decision.inject.length > 0) {\n await new Promise<void>((resolve) => process.stdout.write(`${decision.inject}\\n`, () => resolve()))\n }\n } catch {\n /* never let the front-end hook disrupt a prompt */\n }\n // Natural exit (exit code 0): a hard process.exit() races libuv stdio teardown\n // on Windows. No handles are kept alive once the (aborted) enrichment settles,\n // so returning lets the process exit cleanly with code 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;AAIA,SAAS,mBAAmB,OAAuB;CACjD,IAAI;EACF,MAAM,IAAa,KAAK,MAAM,KAAK;EACnC,IAAI,KAAK,OAAO,MAAM,UAAU;GAC9B,MAAM,MAAO,EAAwB;GACrC,IAAI,OAAO,QAAQ,YAAY,IAAI,SAAS,GAAG,OAAO;EACxD;CACF,QAAQ,CAER;CACA,OAAO,QAAQ,IAAI;AACrB;;AAGA,MAAM,oBAAoB;;AAE1B,MAAM,mBAAmB;;;;;;;;AAQzB,MAAM,qBAAqB;;AAG3B,SAAS,eAAe,SAAiB,KAAqB;CAC5D,IAAI;EACF,OAAO,aAAa,SAAS,MAAM,CAAC,CAAC,MAAM,GAAG,GAAG;CACnD,QAAQ;EACN,OAAO;CACT;AACF;;;;;;AAcA,MAAM,uBAAuB;CAC3B;CAAgB;CAAU;CAAc;CAAkB;CAC1D;CAAW;CAAW;CAAa;CAAc;CACjD;CAAY;CAAY;AAC1B;;;;;;;;;;;;;;;;;;AAmBA,SAAS,mBAAmB,UAA0B;CACpD,MAAM,QAAQ,KAAK,QAAQ,QAAQ;CACnC,MAAM,kBAAkB;CACxB,IAAI,UAAU;CACd,IAAI;CACJ,KAAK,IAAI,IAAI,GAAG,IAAI,iBAAiB,KAAK;EACxC,IAAI,WAAW,KAAK,KAAK,SAAS,MAAM,CAAC,GAAG,OAAO;EACnD,IAAI,CAAC,iBAAiB,qBAAqB,MAAM,MAAM,WAAW,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,GACtF,gBAAg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