github-router 0.3.346 → 0.3.348

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.
Files changed (72) hide show
  1. package/README.md +6 -6
  2. package/dist/{attribution-settings-DyzvcqWL.js → attribution-settings-P_vba-ri.js} +28 -18
  3. package/dist/attribution-settings-P_vba-ri.js.map +1 -0
  4. package/dist/{balanced-profile-contract-C6AgFJNp.js → balanced-profile-contract-XiIj4O1U.js} +7 -7
  5. package/dist/balanced-profile-contract-XiIj4O1U.js.map +1 -0
  6. package/dist/browser-ext/manifest.json +1 -1
  7. package/dist/{claude-Bc-4s27I.js → claude-D26fp1ih.js} +21 -20
  8. package/dist/claude-D26fp1ih.js.map +1 -0
  9. package/dist/{codex-D6ZfS7hJ.js → codex-DM97sCtu.js} +5 -5
  10. package/dist/{codex-D6ZfS7hJ.js.map → codex-DM97sCtu.js.map} +1 -1
  11. package/dist/copilot-discount-CilBhKQW.js.map +1 -1
  12. package/dist/engine-VTQo0qUy.js +2 -0
  13. package/dist/{gate-discovery-TC3k4dr1.js → gate-discovery-V-mslLHt.js} +4 -4
  14. package/dist/{gate-discovery-TC3k4dr1.js.map → gate-discovery-V-mslLHt.js.map} +1 -1
  15. package/dist/hooks.mjs +258 -10
  16. package/dist/hooks.sha256 +1 -1
  17. package/dist/{internal-artifact-open-lta2UPnE.js → internal-artifact-open-CXJbMXpq.js} +2 -2
  18. package/dist/{internal-artifact-open-lta2UPnE.js.map → internal-artifact-open-CXJbMXpq.js.map} +1 -1
  19. package/dist/{internal-fast-dispatch-guard-7UiD_vM5.js → internal-fast-dispatch-guard-DRsZJ-Rg.js} +2 -2
  20. package/dist/{internal-fast-dispatch-guard-7UiD_vM5.js.map → internal-fast-dispatch-guard-DRsZJ-Rg.js.map} +1 -1
  21. package/dist/{internal-fast-dispatch-guard-ByXUE5oO.js → internal-fast-dispatch-guard-DeZ6KilC.js} +1 -1
  22. package/dist/{internal-max-dispatch-guard-CioyE9wn.js → internal-max-dispatch-guard-DSjJwVH2.js} +3 -3
  23. package/dist/internal-max-dispatch-guard-DSjJwVH2.js.map +1 -0
  24. package/dist/{internal-max-dispatch-guard-BSRTtOit.js → internal-max-dispatch-guard-KmbYwh7h.js} +1 -1
  25. package/dist/{internal-plan-review-B4f0dpss.js → internal-plan-review-F-WbltsT.js} +3 -3
  26. package/dist/{internal-plan-review-B4f0dpss.js.map → internal-plan-review-F-WbltsT.js.map} +1 -1
  27. package/dist/{internal-prompt-submit-BMJ0A7vR.js → internal-prompt-submit-B1nd4y4V.js} +92 -6
  28. package/dist/internal-prompt-submit-B1nd4y4V.js.map +1 -0
  29. package/dist/{internal-session-bind-IpZ5hJzR.js → internal-session-bind-LrYEo-kg.js} +2 -2
  30. package/dist/{internal-session-bind-IpZ5hJzR.js.map → internal-session-bind-LrYEo-kg.js.map} +1 -1
  31. package/dist/{internal-stop-hook-BjdKy6On.js → internal-stop-hook-v5WF6Kc2.js} +5 -5
  32. package/dist/{internal-stop-hook-BjdKy6On.js.map → internal-stop-hook-v5WF6Kc2.js.map} +1 -1
  33. package/dist/{internal-stop-review-C7bOxX1q.js → internal-stop-review-nL003JIj.js} +2 -2
  34. package/dist/{internal-stop-review-C7bOxX1q.js.map → internal-stop-review-nL003JIj.js.map} +1 -1
  35. package/dist/main.js +13 -13
  36. package/dist/{max-profile-contract-LTJstj1e.js → max-profile-contract--dAYkEG1.js} +5 -4
  37. package/dist/max-profile-contract--dAYkEG1.js.map +1 -0
  38. package/dist/{orchestration-BMISq91N.js → orchestration-DjuJRhXn.js} +2 -2
  39. package/dist/{orchestration-BMISq91N.js.map → orchestration-DjuJRhXn.js.map} +1 -1
  40. package/dist/{peer-mcp-personas-CIV3aDP6.js → peer-mcp-personas-C200IycG.js} +107 -71
  41. package/dist/peer-mcp-personas-C200IycG.js.map +1 -0
  42. package/dist/{pi-CugyWYp7.js → pi-BWGfNpi7.js} +8 -5
  43. package/dist/pi-BWGfNpi7.js.map +1 -0
  44. package/dist/{plan-review-hook-BTvxvCCo.js → plan-review-hook-DMqPHBBN.js} +2 -2
  45. package/dist/{plan-review-hook-BTvxvCCo.js.map → plan-review-hook-DMqPHBBN.js.map} +1 -1
  46. package/dist/prompt-submit-hook-wjuHUrpS.js +352 -0
  47. package/dist/prompt-submit-hook-wjuHUrpS.js.map +1 -0
  48. package/dist/{provision-J68elA3c.js → provision-BFTONLfA.js} +3 -3
  49. package/dist/{provision-J68elA3c.js.map → provision-BFTONLfA.js.map} +1 -1
  50. package/dist/{serve-BEY7EjEv.js → serve-D9xQeGqi.js} +8 -8
  51. package/dist/{serve-BEY7EjEv.js.map → serve-D9xQeGqi.js.map} +1 -1
  52. package/dist/{server-setup-tNMUzFgE.js → server-setup-R1HQtpR9.js} +77 -35
  53. package/dist/server-setup-R1HQtpR9.js.map +1 -0
  54. package/dist/{start-BDxUhfDG.js → start-vg2n8UjI.js} +4 -4
  55. package/dist/{start-BDxUhfDG.js.map → start-vg2n8UjI.js.map} +1 -1
  56. package/dist/{stop-gate-hook-DBcxPgkF.js → stop-gate-hook-DRcYQAtf.js} +3 -3
  57. package/dist/{stop-gate-hook-DBcxPgkF.js.map → stop-gate-hook-DRcYQAtf.js.map} +1 -1
  58. package/dist/{stop-gate-policy-Gd_cNT9-.js → stop-gate-policy-CbLklfV2.js} +21 -2
  59. package/dist/{stop-gate-policy-Gd_cNT9-.js.map → stop-gate-policy-CbLklfV2.js.map} +1 -1
  60. package/package.json +1 -1
  61. package/dist/attribution-settings-DyzvcqWL.js.map +0 -1
  62. package/dist/balanced-profile-contract-C6AgFJNp.js.map +0 -1
  63. package/dist/claude-Bc-4s27I.js.map +0 -1
  64. package/dist/engine-PexAztE4.js +0 -2
  65. package/dist/internal-max-dispatch-guard-CioyE9wn.js.map +0 -1
  66. package/dist/internal-prompt-submit-BMJ0A7vR.js.map +0 -1
  67. package/dist/max-profile-contract-LTJstj1e.js.map +0 -1
  68. package/dist/peer-mcp-personas-CIV3aDP6.js.map +0 -1
  69. package/dist/pi-CugyWYp7.js.map +0 -1
  70. package/dist/prompt-submit-hook-BeLUDy_m.js +0 -173
  71. package/dist/prompt-submit-hook-BeLUDy_m.js.map +0 -1
  72. package/dist/server-setup-tNMUzFgE.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"plan-review-hook-BTvxvCCo.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/plan-review-hook.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv } from \"~/lib/exec\"\nimport { buildSelfCommand, type SelfInvocation } from \"~/lib/hook-launcher/self-invocation\"\n\nimport { callMcpTool, type HookMcpRuntime, type McpToolResult } from \"./hook-mcp-client\"\nimport {\n isSubagentContext,\n type FindingsStore,\n type ReviewDebounce,\n} from \"./stop-gate-policy\"\n\n/** Minimum finalized-plan size worth spending a model review on. */\nexport const PLAN_REVIEW_MIN_CHARS = 220\n\n/** Hard wall-clock for the advisory plan critic. */\nexport const PLAN_REVIEW_TIMEOUT_MS = 25_000\n\n/** Cap the plan embedded in the critic brief so a huge plan file cannot dominate. */\nconst MAX_REVIEWED_PLAN_CHARS = 80 * 1024\n\nexport interface PlanReviewSpawnContext {\n sessionId: string\n cwd: string\n plan: string\n planHash: string\n}\n\nexport type PlanReviewDecision =\n | { kind: \"skip\"; reason: string }\n | ({ kind: \"spawn\" } & PlanReviewSpawnContext)\n\n/** Default-on advisory plan review. Opt out with GH_ROUTER_DISABLE_PLAN_REVIEW=1. */\nexport function planReviewEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_DISABLE_PLAN_REVIEW) !== true\n}\n\n/** File-backed per-session debounce for finalized plans, separate from Stop diff hashes. */\nexport function filePlanReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `plan-review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, planHash) {\n if (planHash.length === 0) return false\n return (await readLast(sid)) !== planHash\n },\n async markReviewed(sid, planHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), planHash, { mode: 0o600 })\n },\n }\n}\n\nfunction parseObject(raw: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed as Record<string, unknown>\n } catch {\n /* malformed hook payload -> skip */\n }\n return undefined\n}\n\nasync function resolvePlanText(\n toolInput: unknown,\n readFile: (filePath: string) => Promise<string>,\n): Promise<string> {\n if (!toolInput || typeof toolInput !== \"object\") return \"\"\n const ti = toolInput as { planFilePath?: unknown; plan?: unknown }\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim().length > 0\n ? ti.planFilePath.trim()\n : \"\"\n if (planFilePath.length > 0) {\n try {\n const fromFile = await readFile(planFilePath)\n if (fromFile.trim().length > 0) return fromFile\n } catch {\n /* fall through to inline plan */\n }\n }\n return typeof ti.plan === \"string\" ? ti.plan : \"\"\n}\n\n/**\n * Decide whether the ExitPlanMode PostToolUse hook should spawn a detached review.\n * Pure aside from injected file reads + debounce store. Fail-open: any malformed\n * payload, missing runtime, subagent context, trivial/absent plan, or store error\n * returns a skip decision.\n */\nexport async function decidePlanReviewHook(input: {\n stdin: string\n runtimeAvailable: boolean\n debounce: ReviewDebounce\n fallbackCwd: string\n minChars?: number\n readFile?: (filePath: string) => Promise<string>\n}): Promise<PlanReviewDecision> {\n try {\n if (!input.runtimeAvailable) return { kind: \"skip\", reason: \"missing-runtime\" }\n const payload = parseObject(input.stdin)\n if (!payload) return { kind: \"skip\", reason: \"bad-payload\" }\n if (isSubagentContext(payload)) return { kind: \"skip\", reason: \"subagent\" }\n\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (!sessionId) return { kind: \"skip\", reason: \"missing-session\" }\n const cwd = typeof payload.cwd === \"string\" && payload.cwd.length > 0 ? payload.cwd : input.fallbackCwd\n const plan = await resolvePlanText(\n payload.tool_input,\n input.readFile ?? ((filePath: string) => fs.readFile(filePath, \"utf8\")),\n )\n const trimmed = plan.trim()\n if (trimmed.length < (input.minChars ?? PLAN_REVIEW_MIN_CHARS)) return { kind: \"skip\", reason: \"trivial-plan\" }\n\n const planHash = createHash(\"sha256\").update(trimmed).digest(\"hex\")\n if (!(await input.debounce.shouldReview(sessionId, planHash))) return { kind: \"skip\", reason: \"debounced\" }\n await input.debounce.markReviewed(sessionId, planHash)\n return { kind: \"spawn\", sessionId, cwd, plan: trimmed, planHash }\n } catch {\n return { kind: \"skip\", reason: \"error\" }\n }\n}\n\nfunction reviewBrief(plan: string, cwd: string): string {\n const embeddedPlan =\n plan.length > MAX_REVIEWED_PLAN_CHARS\n ? `${plan.slice(0, MAX_REVIEWED_PLAN_CHARS)}\\n\\n[plan truncated at ${MAX_REVIEWED_PLAN_CHARS} characters]`\n : plan\n return (\n \"You are an independent plan reviewer. A coding agent has just finalized a plan with ExitPlanMode. \"\n + \"Your job is to find load-bearing risks before implementation starts: unstated assumptions, missing \"\n + \"failure modes, gaps in verification, dangerous sequencing, or places where the plan could satisfy the \"\n + \"letter of the request while missing the user's likely intent.\\n\\n\"\n + \"Be concise and skeptical. Do NOT rewrite the plan, do NOT praise it, and do NOT invent new product \"\n + \"requirements. Report only material objections that would change what the agent should do next. Include \"\n + \"file:line anchors when the plan names concrete files or when the risk depends on repo code. If the plan \"\n + \"is sound, say exactly: \\\"no material objection\\\".\\n\\n\"\n + `Workspace: ${cwd}\\n\\n`\n + \"FINALIZED PLAN:\\n\"\n + embeddedPlan\n )\n}\n\nfunction hasMaterialFinding(text: string): boolean {\n const normalized = text.trim().toLowerCase().replace(/[.!]+$/g, \"\")\n return normalized.length > 0 && normalized !== \"no material objection\" && normalized !== \"no material objections\"\n}\n\nfunction framePlanFindings(text: string): string {\n return (\n \"PLAN REVIEW: an independent cross-lab critic reviewed the finalized plan and found \"\n + \"the following material concern(s).\\n\"\n + text.trim()\n )\n}\n\n/** Run the bounded critic call and write material findings to the shared findings store. */\nexport async function runPlanReview(input: {\n runtime: HookMcpRuntime\n sessionId: string\n cwd: string\n plan: string\n findingsStore: FindingsStore\n timeoutMs?: number\n callReview?: (brief: string, signal: AbortSignal) => Promise<McpToolResult>\n}): Promise<void> {\n const timeoutMs = input.timeoutMs ?? PLAN_REVIEW_TIMEOUT_MS\n let timer: ReturnType<typeof setTimeout> | undefined\n const controller = new AbortController()\n try {\n const brief = reviewBrief(input.plan, input.cwd)\n const review = (input.callReview ?? ((prompt: string, signal: AbortSignal) => callMcpTool({\n runtime: input.runtime,\n group: \"peers\",\n tool: \"codex_critic\",\n args: { prompt, effort: \"high\" },\n timeoutMs,\n signal,\n })))(brief, controller.signal)\n review.catch(() => {})\n const raced = await Promise.race<McpToolResult | \"timeout\">([\n review,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs)\n }),\n ])\n if (raced === \"timeout\" || raced.isError || !hasMaterialFinding(raced.text)) return\n\n const framed = framePlanFindings(raced.text)\n const existing = await input.findingsStore.read(input.sessionId).catch(() => null)\n const next = existing && existing.trim().length > 0 ? `${existing.trim()}\\n\\n${framed}` : framed\n await input.findingsStore.write(input.sessionId, next)\n } catch {\n /* advisory layer must never surface an error */\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n}\n\n/** Build the command registered for PostToolUse(ExitPlanMode). */\nexport function buildPlanReviewHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-plan-review\")\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,0BAA0B;;AAchC,SAAgB,kBAAkB,MAAyB,QAAQ,KAAc;CAC/E,OAAO,aAAa,IAAI,6BAA6B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AC5D"}
1
+ {"version":3,"file":"plan-review-hook-DMqPHBBN.js","names":["nodePath","fs"],"sources":["../src/lib/orchestration/plan-review-hook.ts"],"sourcesContent":["import { createHash } from \"node:crypto\"\nimport { promises as fs } from \"node:fs\"\nimport nodePath from \"node:path\"\n\nimport { parseBoolEnv } from \"~/lib/exec\"\nimport { buildSelfCommand, type SelfInvocation } from \"~/lib/hook-launcher/self-invocation\"\n\nimport { callMcpTool, type HookMcpRuntime, type McpToolResult } from \"./hook-mcp-client\"\nimport {\n isSubagentContext,\n type FindingsStore,\n type ReviewDebounce,\n} from \"./stop-gate-policy\"\n\n/** Minimum finalized-plan size worth spending a model review on. */\nexport const PLAN_REVIEW_MIN_CHARS = 220\n\n/** Hard wall-clock for the advisory plan critic. */\nexport const PLAN_REVIEW_TIMEOUT_MS = 25_000\n\n/** Cap the plan embedded in the critic brief so a huge plan file cannot dominate. */\nconst MAX_REVIEWED_PLAN_CHARS = 80 * 1024\n\nexport interface PlanReviewSpawnContext {\n sessionId: string\n cwd: string\n plan: string\n planHash: string\n}\n\nexport type PlanReviewDecision =\n | { kind: \"skip\"; reason: string }\n | ({ kind: \"spawn\" } & PlanReviewSpawnContext)\n\n/** Default-on advisory plan review. Opt out with GH_ROUTER_DISABLE_PLAN_REVIEW=1. */\nexport function planReviewEnabled(env: NodeJS.ProcessEnv = process.env): boolean {\n return parseBoolEnv(env.GH_ROUTER_DISABLE_PLAN_REVIEW) !== true\n}\n\n/** File-backed per-session debounce for finalized plans, separate from Stop diff hashes. */\nexport function filePlanReviewDebounce(stateDir: string): ReviewDebounce {\n const fileFor = (sid: string): string =>\n nodePath.join(stateDir, `plan-review-hash-${createHash(\"sha256\").update(sid).digest(\"hex\").slice(0, 32)}`)\n const readLast = async (sid: string): Promise<string> => {\n try {\n return (await fs.readFile(fileFor(sid), \"utf8\")).trim()\n } catch {\n return \"\"\n }\n }\n return {\n async shouldReview(sid, planHash) {\n if (planHash.length === 0) return false\n return (await readLast(sid)) !== planHash\n },\n async markReviewed(sid, planHash) {\n await fs.mkdir(stateDir, { recursive: true })\n await fs.writeFile(fileFor(sid), planHash, { mode: 0o600 })\n },\n }\n}\n\nfunction parseObject(raw: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(raw)\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) return parsed as Record<string, unknown>\n } catch {\n /* malformed hook payload -> skip */\n }\n return undefined\n}\n\nasync function resolvePlanText(\n toolInput: unknown,\n readFile: (filePath: string) => Promise<string>,\n): Promise<string> {\n if (!toolInput || typeof toolInput !== \"object\") return \"\"\n const ti = toolInput as { planFilePath?: unknown; plan?: unknown }\n const planFilePath = typeof ti.planFilePath === \"string\" && ti.planFilePath.trim().length > 0\n ? ti.planFilePath.trim()\n : \"\"\n if (planFilePath.length > 0) {\n try {\n const fromFile = await readFile(planFilePath)\n if (fromFile.trim().length > 0) return fromFile\n } catch {\n /* fall through to inline plan */\n }\n }\n return typeof ti.plan === \"string\" ? ti.plan : \"\"\n}\n\n/**\n * Decide whether the ExitPlanMode PostToolUse hook should spawn a detached review.\n * Pure aside from injected file reads + debounce store. Fail-open: any malformed\n * payload, missing runtime, subagent context, trivial/absent plan, or store error\n * returns a skip decision.\n */\nexport async function decidePlanReviewHook(input: {\n stdin: string\n runtimeAvailable: boolean\n debounce: ReviewDebounce\n fallbackCwd: string\n minChars?: number\n readFile?: (filePath: string) => Promise<string>\n}): Promise<PlanReviewDecision> {\n try {\n if (!input.runtimeAvailable) return { kind: \"skip\", reason: \"missing-runtime\" }\n const payload = parseObject(input.stdin)\n if (!payload) return { kind: \"skip\", reason: \"bad-payload\" }\n if (isSubagentContext(payload)) return { kind: \"skip\", reason: \"subagent\" }\n\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (!sessionId) return { kind: \"skip\", reason: \"missing-session\" }\n const cwd = typeof payload.cwd === \"string\" && payload.cwd.length > 0 ? payload.cwd : input.fallbackCwd\n const plan = await resolvePlanText(\n payload.tool_input,\n input.readFile ?? ((filePath: string) => fs.readFile(filePath, \"utf8\")),\n )\n const trimmed = plan.trim()\n if (trimmed.length < (input.minChars ?? PLAN_REVIEW_MIN_CHARS)) return { kind: \"skip\", reason: \"trivial-plan\" }\n\n const planHash = createHash(\"sha256\").update(trimmed).digest(\"hex\")\n if (!(await input.debounce.shouldReview(sessionId, planHash))) return { kind: \"skip\", reason: \"debounced\" }\n await input.debounce.markReviewed(sessionId, planHash)\n return { kind: \"spawn\", sessionId, cwd, plan: trimmed, planHash }\n } catch {\n return { kind: \"skip\", reason: \"error\" }\n }\n}\n\nfunction reviewBrief(plan: string, cwd: string): string {\n const embeddedPlan =\n plan.length > MAX_REVIEWED_PLAN_CHARS\n ? `${plan.slice(0, MAX_REVIEWED_PLAN_CHARS)}\\n\\n[plan truncated at ${MAX_REVIEWED_PLAN_CHARS} characters]`\n : plan\n return (\n \"You are an independent plan reviewer. A coding agent has just finalized a plan with ExitPlanMode. \"\n + \"Your job is to find load-bearing risks before implementation starts: unstated assumptions, missing \"\n + \"failure modes, gaps in verification, dangerous sequencing, or places where the plan could satisfy the \"\n + \"letter of the request while missing the user's likely intent.\\n\\n\"\n + \"Be concise and skeptical. Do NOT rewrite the plan, do NOT praise it, and do NOT invent new product \"\n + \"requirements. Report only material objections that would change what the agent should do next. Include \"\n + \"file:line anchors when the plan names concrete files or when the risk depends on repo code. If the plan \"\n + \"is sound, say exactly: \\\"no material objection\\\".\\n\\n\"\n + `Workspace: ${cwd}\\n\\n`\n + \"FINALIZED PLAN:\\n\"\n + embeddedPlan\n )\n}\n\nfunction hasMaterialFinding(text: string): boolean {\n const normalized = text.trim().toLowerCase().replace(/[.!]+$/g, \"\")\n return normalized.length > 0 && normalized !== \"no material objection\" && normalized !== \"no material objections\"\n}\n\nfunction framePlanFindings(text: string): string {\n return (\n \"PLAN REVIEW: an independent cross-lab critic reviewed the finalized plan and found \"\n + \"the following material concern(s).\\n\"\n + text.trim()\n )\n}\n\n/** Run the bounded critic call and write material findings to the shared findings store. */\nexport async function runPlanReview(input: {\n runtime: HookMcpRuntime\n sessionId: string\n cwd: string\n plan: string\n findingsStore: FindingsStore\n timeoutMs?: number\n callReview?: (brief: string, signal: AbortSignal) => Promise<McpToolResult>\n}): Promise<void> {\n const timeoutMs = input.timeoutMs ?? PLAN_REVIEW_TIMEOUT_MS\n let timer: ReturnType<typeof setTimeout> | undefined\n const controller = new AbortController()\n try {\n const brief = reviewBrief(input.plan, input.cwd)\n const review = (input.callReview ?? ((prompt: string, signal: AbortSignal) => callMcpTool({\n runtime: input.runtime,\n group: \"peers\",\n tool: \"codex_critic\",\n args: { prompt, effort: \"high\" },\n timeoutMs,\n signal,\n })))(brief, controller.signal)\n review.catch(() => {})\n const raced = await Promise.race<McpToolResult | \"timeout\">([\n review,\n new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs)\n }),\n ])\n if (raced === \"timeout\" || raced.isError || !hasMaterialFinding(raced.text)) return\n\n const framed = framePlanFindings(raced.text)\n const existing = await input.findingsStore.read(input.sessionId).catch(() => null)\n const next = existing && existing.trim().length > 0 ? `${existing.trim()}\\n\\n${framed}` : framed\n await input.findingsStore.write(input.sessionId, next)\n } catch {\n /* advisory layer must never surface an error */\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n}\n\n/** Build the command registered for PostToolUse(ExitPlanMode). */\nexport function buildPlanReviewHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-plan-review\")\n}\n"],"mappings":";;;;;;;;AAqBA,MAAM,0BAA0B;;AAchC,SAAgB,kBAAkB,MAAyB,QAAQ,KAAc;CAC/E,OAAO,aAAa,IAAI,6BAA6B,MAAM;AAC7D;;AAGA,SAAgB,uBAAuB,UAAkC;CACvE,MAAM,WAAW,QACfA,KAAS,KAAK,UAAU,oBAAoB,WAAW,QAAQ,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,OAAO,KAAK,C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AAC3F;AAEA,SAAS,kBAAkB,MAAsB;CAC/C,OACE,4HAEE,KAAK,KAAK;AAEhB;;AAGA,eAAsB,cAAc,OAQlB;CAChB,MAAM,YAAY,MAAM,aAAA;CACxB,IAAI;CACJ,MAAM,aAAa,IAAI,gBAAgB;CACvC,IAAI;EACF,MAAM,QAAQ,YAAY,MAAM,MAAM,MAAM,GAAG;EAC/C,MAAM,UAAU,MAAM,gBAAgB,QAAgB,WAAwB,YAAY;GACxF,SAAS,MAAM;GACf,OAAO;GACP,MAAM;GACN,MAAM;IAAE;IAAQ,QAAQ;GAAO;GAC/B;GACA;EACF,CAAC,GAAA,CAAI,OAAO,WAAW,MAAM;EAC7B,OAAO,YAAY,CAAC,CAAC;EACrB,MAAM,QAAQ,MAAM,QAAQ,KAAgC,CAC1D,QACA,IAAI,SAAoB,YAAY;GAClC,QAAQ,iBAAiB,QAAQ,SAAS,GAAG,SAAS;EACxD,CAAC,CACH,CAAC;EACD,IAAI,UAAU,aAAa,MAAM,WAAW,CAAC,mBAAmB,MAAM,IAAI,GAAG;EAE7E,MAAM,SAAS,kBAAkB,MAAM,IAAI;EAC3C,MAAM,WAAW,MAAM,MAAM,cAAc,KAAK,MAAM,SAAS,CAAC,CAAC,YAAY,IAAI;EACjF,MAAM,OAAO,YAAY,SAAS,KAAK,CAAC,CAAC,SAAS,IAAI,GAAG,SAAS,KAAK,EAAE,MAAM,WAAW;EAC1F,MAAM,MAAM,cAAc,MAAM,MAAM,WAAW,IAAI;CACvD,QAAQ,CAER,UAAU;EACR,IAAI,OAAO,aAAa,KAAK;EAC7B,WAAW,MAAM;CACnB;AACF;;AAGA,SAAgB,2BAA2B,YAAoC;CAC7E,OAAO,iBAAiB,YAAY,sBAAsB;AAC5D"}
@@ -0,0 +1,352 @@
1
+ import { t as buildSelfCommand } from "./self-invocation-DIUyoRgL.js";
2
+ import { o as isSubagentContext } from "./stop-gate-policy-CbLklfV2.js";
3
+ //#region src/lib/cheapest-prompt-rewrite.ts
4
+ /**
5
+ * Cheapest-only Sol → Luna prompt rewrite (additive, fail-open).
6
+ *
7
+ * The cheapest lead (`gpt-6-luna`) is the mini-tier analog: it follows
8
+ * explicit, short, structured briefs far better than vague prompts (see the
9
+ * OpenAI GPT-4.1 / GPT-5-mini prompting guides). This module is the pure
10
+ * decision + formatting layer for that rewrite. It never touches the network
11
+ * itself: all IO is injected so tests run with fakes and no Copilot spend.
12
+ *
13
+ * Design (per researched plan):
14
+ * - cheapest profile only, initial top-level prompt only, non-trivial only
15
+ * (caller passes the `isNonTrivialPrompt` verdict in — this module does
16
+ * not import the hook to avoid a dependency cycle).
17
+ * - static context pack first (user prompt + AGENTS.md/CLAUDE.md + repo
18
+ * structure + search snippets), all capped for cache-friendliness.
19
+ * - rewriter is `gpt-5.6-sol` bare 200K at medium effort (the existing
20
+ * cheapest Advisor identity), via the caller's `inferSol`.
21
+ * - adaptive turn budget: 3 tool turns by default, up to 5 only when Sol
22
+ * self-flags deep grounding. Sol is told the budget and may use zero
23
+ * tools and rewrite immediately.
24
+ * - output is an ADDITIVE advisory brief for Luna; the original prompt is
25
+ * never replaced. Empty/error/timeout yields null and the caller falls
26
+ * back to the existing V2 scope/goal path.
27
+ */
28
+ const CHEAPEST_REWRITE_MODEL = "gpt-5.6-sol";
29
+ const CHEAPEST_REWRITE_EFFORT = "medium";
30
+ /** Max chars per search-result blob fed to Sol. */
31
+ const CHEAPEST_REWRITE_SEARCH_CAP = 6144;
32
+ /** Max chars of repo guidance files (AGENTS.md / CLAUDE.md) fed to Sol. */
33
+ const CHEAPEST_REWRITE_GUIDANCE_CAP = 4096;
34
+ /** Max chars of structural repo info fed to Sol. */
35
+ const CHEAPEST_REWRITE_STRUCTURE_CAP = 2048;
36
+ /** Max chars of the wrapped Luna brief (keeps Luna-facing brief short). */
37
+ const CHEAPEST_REWRITE_BRIEF_CAP = 2e3;
38
+ /** Flag Sol emits when it needs the extended 5-turn budget. */
39
+ const DEEP_GROUNDING_FLAG = "needs_deep_grounding=true";
40
+ /** Follow-up signal: Sol names one more targeted query to ground. */
41
+ const NEED_MORE_PREFIX = "NEED_MORE:";
42
+ function isCheapestRewriteDisabledEnv(env = process.env) {
43
+ const v = (env.GH_ROUTER_DISABLE_CHEAPEST_REWRITE ?? "").trim().toLowerCase();
44
+ return v === "1" || v === "true" || v === "yes" || v === "on";
45
+ }
46
+ function isCheapestRewriteEligible(input) {
47
+ if (!input.steerEnabled) return false;
48
+ if (input.rewriteDisabled) return false;
49
+ if (input.profile !== "cheapest") return false;
50
+ return input.promptIsNonTrivial;
51
+ }
52
+ /** Adaptive budget: 5 only on Sol's explicit deep-grounding flag, else 3. */
53
+ function resolveRewriteTurnBudget(solText) {
54
+ if (typeof solText === "string" && solText.includes("needs_deep_grounding=true")) return 5;
55
+ return 3;
56
+ }
57
+ /** Extract a single follow-up query Sol names via `NEED_MORE: <query>. */
58
+ function parseNeedMoreQuery(solText) {
59
+ const idx = solText.indexOf(NEED_MORE_PREFIX);
60
+ if (idx < 0) return "";
61
+ return solText.slice(idx + 10).split("\n", 1)[0]?.trim().slice(0, 280) ?? "";
62
+ }
63
+ /**
64
+ * System prompt for the Sol rewriter. Names the turn budget explicitly so
65
+ * Sol knows what it is doing, how many turns it has, that zero-tool
66
+ * immediate rewrite is allowed, and that the output serves Luna (mini-tier:
67
+ * explicit, short, flat, outcome-first with stop rules).
68
+ */
69
+ function buildSolRewriteSystem(opts) {
70
+ const searchNoun = opts.bluebirdEnabled ? "Bluebird lexical + semantic code search" : opts.searchEnabled ? "local lexical + semantic code search" : "lexical code search";
71
+ return `You are a prompt-rewriting advisor for a coding agent. A cheap mini-tier model (Luna) will execute the user's request. Your job is to rewrite it into a SHORT structured brief that lets Luna do its best work.
72
+ Turn budget: you have at most ${opts.turnBudget} tool turns TOTAL (search/read). You may use ZERO tools and rewrite immediately when the static context already suffices — do not pad turns. If the task is large/cross-cutting and the context is genuinely insufficient, you may emit "${DEEP_GROUNDING_FLAG}" plus one line "${NEED_MORE_PREFIX} <single targeted query>" to earn follow-up grounding; otherwise finish now.\nGrounding available: ${searchNoun} results, repo guidance (AGENTS.md/CLAUDE.md), and repo structure are in your context. Prefer targeted reads over full-file reads.\nRules for the brief (tuned for a mini-tier executor):\n1. Outcome-first: state the user's OWN goal as one measurable objective, in their terms. Do NOT invent new requirements or acceptance criteria.\n2. Explicit + literal: flat numbered steps in order; front-load the key constraints; no nested hierarchies; no contradictory instructions.\n3. Tool rules: lexical search first (exact symbols/files/errors, zero model cost), semantic second for intent drift, Explore only when search is insufficient.\n4. Scope: name the files/symbols in play with file:line when known, or state the gap explicitly — never guess.\n5. Stop rules: when Luna is done, what check settles it (build/test/read), and when to ask vs proceed.\n6. Keep it SHORT (under ~300 words). Respond with the brief body only, no preamble.`;
73
+ }
74
+ /** Assemble the capped static pack Sol sees (static-first for cache hits). */
75
+ function buildStaticContextPack(pack) {
76
+ const parts = [`USER REQUEST:\n${pack.prompt}`];
77
+ if (pack.agentsMd.trim().length > 0) parts.push(`REPO GUIDANCE (AGENTS.md):\n${pack.agentsMd.slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP)}`);
78
+ if (pack.claudeMd.trim().length > 0) parts.push(`REPO GUIDANCE (CLAUDE.md):\n${pack.claudeMd.slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP)}`);
79
+ if (pack.repoStructure.trim().length > 0) parts.push(`REPO STRUCTURE:\n${pack.repoStructure.slice(0, CHEAPEST_REWRITE_STRUCTURE_CAP)}`);
80
+ if (pack.searchContext.trim().length > 0) parts.push(pack.searchContext);
81
+ return parts.join("\n\n");
82
+ }
83
+ /**
84
+ * Wrap Sol's raw brief as the additive Luna-facing block. Returns "" when
85
+ * Sol produced nothing usable (caller treats that as fail-open).
86
+ */
87
+ function wrapLunaBrief(solText) {
88
+ const body = solText.replace(DEEP_GROUNDING_FLAG, "").split("\n").filter((line) => !line.trimStart().startsWith(NEED_MORE_PREFIX)).join("\n").trim();
89
+ if (body.length === 0) return "";
90
+ return `LUNA BRIEF (advisory, additive — the original request above still stands):\n${body.length > 2e3 ? `${body.slice(0, CHEAPEST_REWRITE_BRIEF_CAP).trimEnd()}…` : body}`;
91
+ }
92
+ /**
93
+ * Run the adaptive rewrite. Returns the wrapped Luna brief, or null when
94
+ * anything is missing/empty/over-budget so the caller falls back to the
95
+ * existing V2 scope/goal path. Never throws to the orchestrator.
96
+ */
97
+ async function runCheapestRewrite(input) {
98
+ const timeoutMs = input.io.timeoutMs ?? 2e4;
99
+ const controller = new AbortController();
100
+ let timer;
101
+ try {
102
+ const work = (async () => {
103
+ const semanticAvailable = input.searchEnabled || input.bluebirdEnabled;
104
+ const [lexical, semantic, statik] = await Promise.all([
105
+ input.io.searchCode(input.prompt, "lexical", controller.signal).catch(() => ""),
106
+ semanticAvailable ? input.io.searchCode(input.prompt, "semantic", controller.signal).catch(() => "") : Promise.resolve(""),
107
+ input.io.staticPack().catch(() => ({
108
+ agentsMd: "",
109
+ claudeMd: "",
110
+ repoStructure: ""
111
+ }))
112
+ ]);
113
+ const searchContext = semanticAvailable ? `Lexical search results:\n${lexical.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}\n\nSemantic search results:\n${semantic.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}` : `Lexical search results:\n${lexical.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}`;
114
+ const user = buildStaticContextPack({
115
+ prompt: input.prompt,
116
+ agentsMd: statik.agentsMd,
117
+ claudeMd: statik.claudeMd,
118
+ repoStructure: statik.repoStructure,
119
+ searchContext
120
+ });
121
+ const first = await input.io.inferSol(buildSolRewriteSystem({
122
+ searchEnabled: input.searchEnabled,
123
+ bluebirdEnabled: input.bluebirdEnabled,
124
+ turnBudget: 3
125
+ }), user, controller.signal).catch(() => "");
126
+ if (!first || first.trim().length === 0) return null;
127
+ const budget = resolveRewriteTurnBudget(first);
128
+ const followUp = parseNeedMoreQuery(first);
129
+ if (budget !== 5 || followUp.length === 0) {
130
+ const brief = wrapLunaBrief(first);
131
+ return brief.length > 0 ? brief : null;
132
+ }
133
+ const extra = await input.io.searchCode(followUp, "lexical", controller.signal).catch(() => "");
134
+ if (extra.trim().length === 0) {
135
+ const brief = wrapLunaBrief(first);
136
+ return brief.length > 0 ? brief : null;
137
+ }
138
+ const second = await input.io.inferSol(buildSolRewriteSystem({
139
+ searchEnabled: input.searchEnabled,
140
+ bluebirdEnabled: input.bluebirdEnabled,
141
+ turnBudget: 5
142
+ }), `${user}\n\nFOLLOW-UP GROUNDING for "${followUp}":\n${extra.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}\n\nRewrite the brief with this grounding (same rules, short).`, controller.signal).catch(() => "");
143
+ const brief = wrapLunaBrief(second.trim().length > 0 ? second : first);
144
+ return brief.length > 0 ? brief : null;
145
+ })();
146
+ work.catch(() => {});
147
+ const raced = await Promise.race([work, new Promise((resolve) => {
148
+ timer = setTimeout(() => resolve("__timeout__"), timeoutMs);
149
+ })]);
150
+ if (raced === "__timeout__" || raced === null) return null;
151
+ return raced;
152
+ } catch {
153
+ return null;
154
+ } finally {
155
+ if (timer) clearTimeout(timer);
156
+ controller.abort();
157
+ }
158
+ }
159
+ //#endregion
160
+ //#region src/lib/orchestration/prompt-submit-hook.ts
161
+ /**
162
+ * Pure decision logic for the `UserPromptSubmit` hook (the front-end of the
163
+ * floor-raising surface). It serves TWO duties on the one event:
164
+ *
165
+ * 1. Per-prompt budget reset — clears the Stop-gate's block counter for this
166
+ * session so `maxBlocks` is "per user prompt", not "per session lifetime"
167
+ * (the per-prompt scoping the Stop-gate relies on).
168
+ * 2. Goal steer — for a NON-trivial prompt, inject an advisory GOAL directive
169
+ * (additive context, never blocking) pointing the model at `/gh-research`
170
+ * then `/gh-orchestrate`. It raises the prior; it does not force execution.
171
+ *
172
+ * Top-level only: like the Stop-gate, it stands down in a subagent/teammate
173
+ * context (the payload carries `agent_type`/`agent_id` there) so it never
174
+ * recurses into spawned workers. Fail-open and never blocking: any error or a
175
+ * trivial prompt yields an empty injection.
176
+ */
177
+ /**
178
+ * The advisory goal injected for a non-trivial prompt. Uses the skills' slash
179
+ * invocation form. The model still decides whether to follow it; the Stop-gate
180
+ * backstops correctness at the output end.
181
+ */
182
+ const PROMPT_STEER_GOAL = "GOAL (advisory): for a non-trivial task, FIRST run /gh-research on this ask to information saturation — verify the load-bearing claims against the actual code before planning, and do not plan or write code until research is saturated. THEN, for an implementation or change task, run /gh-orchestrate to compose and run a floor-raising workflow (it checkpoints before expensive work). Skip both for a trivial ask; you may decline if they do not fit.";
183
+ /**
184
+ * Cheap, conservative complexity heuristic — a long prompt, an imperative
185
+ * build/change verb, or an explicit multi-file scope. Trivial prompts get no
186
+ * steer (no analysis-paralysis tax on quick asks).
187
+ */
188
+ function isNonTrivialPrompt(prompt) {
189
+ const p = prompt.trim();
190
+ if (p.length === 0) return false;
191
+ if (p.length >= 280) return true;
192
+ if (/\b(implement|build|refactor|migrate|fix|debug|diagnose|design|add|create|rewrite|optimi[sz]e|integrate|architect|investigate|audit)\b/i.test(p)) return true;
193
+ return /\b(across|throughout|every|all)\b.*\b(file|module|test|route|component)s?\b/i.test(p);
194
+ }
195
+ function decidePromptSubmit(input) {
196
+ let payload = {};
197
+ try {
198
+ const p = JSON.parse(input.stdin);
199
+ if (p && typeof p === "object") payload = p;
200
+ } catch {
201
+ return { inject: "" };
202
+ }
203
+ if (isSubagentContext(payload)) return { inject: "" };
204
+ const decision = { inject: "" };
205
+ const sessionId = typeof payload.session_id === "string" && payload.session_id.length > 0 ? payload.session_id : "";
206
+ if (sessionId) decision.resetSession = sessionId;
207
+ const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
208
+ if (input.steerEnabled && isNonTrivialPrompt(prompt)) decision.inject = PROMPT_STEER_GOAL;
209
+ return decision;
210
+ }
211
+ /**
212
+ * Build the search tip for the launch's search backend. When Bluebird is
213
+ * enabled it owns both semantic and lexical calls; otherwise local ColBERT is
214
+ * used when enabled, or lexical-only search when neither backend is enabled.
215
+ */
216
+ function getPromptSearchTip(searchEnabled, bluebirdEnabled = false) {
217
+ if (bluebirdEnabled) return "TIP (advisory): when this task needs code context, search Bluebird semantic + lexical in parallel — two `mcp__search__code` calls issued in the same turn. Bluebird failures are visible and do not fall back locally.";
218
+ if (searchEnabled) return "TIP (advisory): when this task needs code context, search lexical + semantic in parallel — one `mcp__search__code` call with mode:\"lexical\" and one with mode:\"semantic\", issued in the same turn — before concluding.";
219
+ return "TIP (advisory): when this task needs code context, search lexical (`mcp__search__code` with mode:\"lexical\"/\"exact\"/\"regex\" for exact symbols, filenames, errors, routes, flags, and config keys), issuing parallel calls in the same turn — before concluding.";
220
+ }
221
+ /**
222
+ * Build the scope-inference system prompt for the launch's search backend.
223
+ * Mirrors `getPromptSearchTip`: Bluebird and local ColBERT variants ground the
224
+ * inference in lexical + semantic results; the local-only variant in lexical results.
225
+ */
226
+ function getPromptScopeSystem(searchEnabled, bluebirdEnabled = false) {
227
+ return `You are a scoping assistant for a coding agent about to act on a user's request. You are given the user's request and the results of ${bluebirdEnabled ? "a Bluebird lexical + semantic code search" : searchEnabled ? "a local lexical + semantic code search" : "a lexical code search"} over the relevant repository. Produce a SHORT advisory note (<= 120 words), plain text only:
228
+ 1. SCOPE: one line — is this trivial, focused (one area), or large/cross-cutting — grounded in what the search surfaced (reference the most relevant file(s) by name).
229
+ 2. GOAL: restate the user's OWN ask as a single measurable objective, in THEIR terms. Do NOT invent new requirements or acceptance criteria beyond what they asked.
230
+ 3. Only if the task is large/cross-cutting, add a final line: "Consider /gh-research first to saturate understanding, then /gh-orchestrate to compose a floor-raising workflow." Omit it for a focused or trivial task.
231
+ This is advisory — the agent decides whether to follow it. Be concrete and concise; no preamble.`;
232
+ }
233
+ /** Max chars of each search-result blob fed into the scope inference. */
234
+ const SEARCH_CONTEXT_CAP = 6144;
235
+ /** Wrap the prior-turn review findings in an explicitly NON-AUTHORITATIVE frame. */
236
+ function framePendingFindings(findings) {
237
+ return "ADVISORY — independent review of your PREVIOUS change (NON-AUTHORITATIVE): an independent gpt-6-luna reviewer flagged the following. Evaluate each on its merits — fix the real ones, and ignore any wrong one with a one-line reason. You are NOT obligated to act on these.\n" + findings.trim();
238
+ }
239
+ function joinSections(sections) {
240
+ return sections.map((s) => s.trim()).filter((s) => s.length > 0).join("\n\n");
241
+ }
242
+ /**
243
+ * V2 decision: budget reset (via resetSession) + a grounded, user-derived scope
244
+ * note + surfaced prior-turn findings. ASYNC and IO-driven, but every IO is
245
+ * best-effort and the substantive enrichment is timeout-bounded with a fail-open
246
+ * to the v1 regex goal — so this never blocks and never wedges the prompt.
247
+ *
248
+ * - subagent/teammate -> empty (top-level only, like v1).
249
+ * - findings -> always surfaced (+ cleared) regardless of triviality.
250
+ * - trivial prompt -> findings only (no search tip, no model call).
251
+ * - substantive prompt -> search tip + grounded enrichment (parallel
252
+ * lexical+semantic through Bluebird when enabled,
253
+ * otherwise local semantic when enabled, else lexical-only)
254
+ * -> ONE gpt-6-luna call
255
+ * -> grounded scope/goal note. Fail-open to PROMPT_STEER_GOAL.
256
+ * - steerEnabled=false -> findings only (no goal/tip).
257
+ */
258
+ async function decidePromptSubmitV2(input) {
259
+ let payload = {};
260
+ try {
261
+ const p = JSON.parse(input.stdin);
262
+ if (p && typeof p === "object") payload = p;
263
+ } catch {
264
+ return { inject: "" };
265
+ }
266
+ if (isSubagentContext(payload)) return { inject: "" };
267
+ const decision = { inject: "" };
268
+ const sessionId = typeof payload.session_id === "string" && payload.session_id.length > 0 ? payload.session_id : "";
269
+ if (sessionId) decision.resetSession = sessionId;
270
+ const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
271
+ if (sessionId) await input.io.storePrompt(sessionId, prompt).catch(() => {});
272
+ let findingsBlock = "";
273
+ if (sessionId) {
274
+ const pending = await input.io.readFindings(sessionId).catch(() => null);
275
+ if (pending && pending.trim().length > 0) {
276
+ findingsBlock = framePendingFindings(pending);
277
+ await input.io.clearFindings(sessionId).catch(() => {});
278
+ }
279
+ }
280
+ if (!input.steerEnabled) {
281
+ decision.inject = findingsBlock;
282
+ return decision;
283
+ }
284
+ if (!isNonTrivialPrompt(prompt)) {
285
+ decision.inject = findingsBlock;
286
+ return decision;
287
+ }
288
+ const searchEnabled = input.searchEnabled === true;
289
+ const bluebirdEnabled = input.bluebirdEnabled === true;
290
+ const semanticAvailable = searchEnabled || bluebirdEnabled;
291
+ const searchTip = getPromptSearchTip(searchEnabled, bluebirdEnabled);
292
+ if (input.rewrite && isCheapestRewriteEligible({
293
+ profile: input.profile,
294
+ promptIsNonTrivial: isNonTrivialPrompt(prompt),
295
+ steerEnabled: input.steerEnabled,
296
+ rewriteDisabled: input.rewriteDisabled === true
297
+ }) && sessionId.length > 0 && !await input.rewrite.hasRewriteRun(sessionId).catch(() => true)) {
298
+ await input.rewrite.markRewriteRun(sessionId).catch(() => {});
299
+ const brief = await runCheapestRewrite({
300
+ prompt,
301
+ searchEnabled,
302
+ bluebirdEnabled,
303
+ io: input.rewrite
304
+ }).catch(() => null);
305
+ if (brief && brief.length > 0) {
306
+ decision.inject = joinSections([
307
+ searchTip,
308
+ brief,
309
+ findingsBlock
310
+ ]);
311
+ return decision;
312
+ }
313
+ }
314
+ const scopeSystem = getPromptScopeSystem(searchEnabled, bluebirdEnabled);
315
+ const timeoutMs = input.io.timeoutMs ?? 22e3;
316
+ let goal = PROMPT_STEER_GOAL;
317
+ let timer;
318
+ const controller = new AbortController();
319
+ try {
320
+ const enrich = (async () => {
321
+ if (!semanticAvailable) {
322
+ const searchContext = `Lexical search results:\n${(await input.io.searchCode(prompt, "lexical", controller.signal).catch(() => "")).slice(0, SEARCH_CONTEXT_CAP)}`;
323
+ return (await input.io.infer(scopeSystem, `USER REQUEST:\n${prompt}\n\n${searchContext}`, controller.signal)).trim();
324
+ }
325
+ const [lexical, semantic] = await Promise.all([input.io.searchCode(prompt, "lexical", controller.signal).catch(() => ""), input.io.searchCode(prompt, "semantic", controller.signal).catch(() => "")]);
326
+ const searchContext = `Lexical search results:\n${lexical.slice(0, SEARCH_CONTEXT_CAP)}\n\nSemantic search results:\n${semantic.slice(0, SEARCH_CONTEXT_CAP)}`;
327
+ return (await input.io.infer(scopeSystem, `USER REQUEST:\n${prompt}\n\n${searchContext}`, controller.signal)).trim();
328
+ })();
329
+ enrich.catch(() => {});
330
+ const raced = await Promise.race([enrich, new Promise((resolve) => {
331
+ timer = setTimeout(() => resolve("__timeout__"), timeoutMs);
332
+ })]);
333
+ if (raced !== "__timeout__" && raced.length > 0) goal = raced;
334
+ } catch {} finally {
335
+ if (timer) clearTimeout(timer);
336
+ controller.abort();
337
+ }
338
+ decision.inject = joinSections([
339
+ searchTip,
340
+ goal,
341
+ findingsBlock
342
+ ]);
343
+ return decision;
344
+ }
345
+ /** Build the shell command Claude Code runs for the `UserPromptSubmit` hook. */
346
+ function buildPromptSubmitHookCommand(invocation) {
347
+ return buildSelfCommand(invocation, "internal-prompt-submit");
348
+ }
349
+ //#endregion
350
+ export { CHEAPEST_REWRITE_GUIDANCE_CAP as a, isCheapestRewriteDisabledEnv as c, CHEAPEST_REWRITE_EFFORT as i, decidePromptSubmit as n, CHEAPEST_REWRITE_MODEL as o, decidePromptSubmitV2 as r, CHEAPEST_REWRITE_STRUCTURE_CAP as s, buildPromptSubmitHookCommand as t };
351
+
352
+ //# sourceMappingURL=prompt-submit-hook-wjuHUrpS.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-submit-hook-wjuHUrpS.js","names":[],"sources":["../src/lib/cheapest-prompt-rewrite.ts","../src/lib/orchestration/prompt-submit-hook.ts"],"sourcesContent":["/**\n * Cheapest-only Sol → Luna prompt rewrite (additive, fail-open).\n *\n * The cheapest lead (`gpt-6-luna`) is the mini-tier analog: it follows\n * explicit, short, structured briefs far better than vague prompts (see the\n * OpenAI GPT-4.1 / GPT-5-mini prompting guides). This module is the pure\n * decision + formatting layer for that rewrite. It never touches the network\n * itself: all IO is injected so tests run with fakes and no Copilot spend.\n *\n * Design (per researched plan):\n * - cheapest profile only, initial top-level prompt only, non-trivial only\n * (caller passes the `isNonTrivialPrompt` verdict in — this module does\n * not import the hook to avoid a dependency cycle).\n * - static context pack first (user prompt + AGENTS.md/CLAUDE.md + repo\n * structure + search snippets), all capped for cache-friendliness.\n * - rewriter is `gpt-5.6-sol` bare 200K at medium effort (the existing\n * cheapest Advisor identity), via the caller's `inferSol`.\n * - adaptive turn budget: 3 tool turns by default, up to 5 only when Sol\n * self-flags deep grounding. Sol is told the budget and may use zero\n * tools and rewrite immediately.\n * - output is an ADDITIVE advisory brief for Luna; the original prompt is\n * never replaced. Empty/error/timeout yields null and the caller falls\n * back to the existing V2 scope/goal path.\n */\n\nexport const CHEAPEST_REWRITE_MODEL = \"gpt-5.6-sol\" as const\nexport const CHEAPEST_REWRITE_EFFORT = \"medium\" as const\n\n/** Default tool-turn budget for ordinary non-trivial prompts. */\nexport const CHEAPEST_REWRITE_DEFAULT_TURNS = 3\n/** Extended budget reserved for the hardest prompts (Sol must flag it). */\nexport const CHEAPEST_REWRITE_MAX_TURNS = 5\n\n/** Wall-clock budget for the whole rewrite (search + Sol), ms. */\nexport const CHEAPEST_REWRITE_TIMEOUT_MS = 20_000\n/** Max chars per search-result blob fed to Sol. */\nexport const CHEAPEST_REWRITE_SEARCH_CAP = 6 * 1024\n/** Max chars of repo guidance files (AGENTS.md / CLAUDE.md) fed to Sol. */\nexport const CHEAPEST_REWRITE_GUIDANCE_CAP = 4 * 1024\n/** Max chars of structural repo info fed to Sol. */\nexport const CHEAPEST_REWRITE_STRUCTURE_CAP = 2 * 1024\n/** Max chars of the wrapped Luna brief (keeps Luna-facing brief short). */\nexport const CHEAPEST_REWRITE_BRIEF_CAP = 2_000\n\n/** Flag Sol emits when it needs the extended 5-turn budget. */\nexport const DEEP_GROUNDING_FLAG = \"needs_deep_grounding=true\" as const\n/** Follow-up signal: Sol names one more targeted query to ground. */\nexport const NEED_MORE_PREFIX = \"NEED_MORE:\" as const\n\nexport interface CheapestRewriteEligibility {\n /** Launch profile id (only `\"cheapest\"` is eligible). */\n profile?: string\n /** Caller-computed `isNonTrivialPrompt(prompt)` verdict (regex, zero cost). */\n promptIsNonTrivial: boolean\n /** Master steer switch already resolved (false = findings only). */\n steerEnabled: boolean\n /** True when `GH_ROUTER_DISABLE_CHEAPEST_REWRITE` opts out. */\n rewriteDisabled: boolean\n}\n\nexport function isCheapestRewriteDisabledEnv(env: NodeJS.ProcessEnv = process.env): boolean {\n const v = (env.GH_ROUTER_DISABLE_CHEAPEST_REWRITE ?? \"\").trim().toLowerCase()\n return v === \"1\" || v === \"true\" || v === \"yes\" || v === \"on\"\n}\n\nexport function isCheapestRewriteEligible(input: CheapestRewriteEligibility): boolean {\n if (!input.steerEnabled) return false\n if (input.rewriteDisabled) return false\n if (input.profile !== \"cheapest\") return false\n return input.promptIsNonTrivial\n}\n\n/** Adaptive budget: 5 only on Sol's explicit deep-grounding flag, else 3. */\nexport function resolveRewriteTurnBudget(solText: string | null | undefined): number {\n if (typeof solText === \"string\" && solText.includes(DEEP_GROUNDING_FLAG)) {\n return CHEAPEST_REWRITE_MAX_TURNS\n }\n return CHEAPEST_REWRITE_DEFAULT_TURNS\n}\n\n/** Extract a single follow-up query Sol names via `NEED_MORE: <query>. */\nexport function parseNeedMoreQuery(solText: string): string {\n const idx = solText.indexOf(NEED_MORE_PREFIX)\n if (idx < 0) return \"\"\n return solText\n .slice(idx + NEED_MORE_PREFIX.length)\n .split(\"\\n\", 1)[0]\n ?.trim()\n .slice(0, 280) ?? \"\"\n}\n\n/**\n * System prompt for the Sol rewriter. Names the turn budget explicitly so\n * Sol knows what it is doing, how many turns it has, that zero-tool\n * immediate rewrite is allowed, and that the output serves Luna (mini-tier:\n * explicit, short, flat, outcome-first with stop rules).\n */\nexport function buildSolRewriteSystem(opts: {\n searchEnabled: boolean\n bluebirdEnabled: boolean\n turnBudget: number\n}): string {\n const searchNoun = opts.bluebirdEnabled\n ? \"Bluebird lexical + semantic code search\"\n : opts.searchEnabled\n ? \"local lexical + semantic code search\"\n : \"lexical code search\"\n return (\n `You are a prompt-rewriting advisor for a coding agent. A cheap mini-tier model (Luna) `\n + `will execute the user's request. Your job is to rewrite it into a SHORT structured brief that lets Luna do its best work.\\n`\n + `Turn budget: you have at most ${opts.turnBudget} tool turns TOTAL (search/read). You may use ZERO tools and rewrite immediately when the static context already suffices — do not pad turns. `\n + `If the task is large/cross-cutting and the context is genuinely insufficient, you may emit \"${DEEP_GROUNDING_FLAG}\" plus one line \"${NEED_MORE_PREFIX} <single targeted query>\" to earn follow-up grounding; otherwise finish now.\\n`\n + `Grounding available: ${searchNoun} results, repo guidance (AGENTS.md/CLAUDE.md), and repo structure are in your context. Prefer targeted reads over full-file reads.\\n`\n + `Rules for the brief (tuned for a mini-tier executor):\\n`\n + `1. Outcome-first: state the user's OWN goal as one measurable objective, in their terms. Do NOT invent new requirements or acceptance criteria.\\n`\n + `2. Explicit + literal: flat numbered steps in order; front-load the key constraints; no nested hierarchies; no contradictory instructions.\\n`\n + `3. Tool rules: lexical search first (exact symbols/files/errors, zero model cost), semantic second for intent drift, Explore only when search is insufficient.\\n`\n + `4. Scope: name the files/symbols in play with file:line when known, or state the gap explicitly — never guess.\\n`\n + `5. Stop rules: when Luna is done, what check settles it (build/test/read), and when to ask vs proceed.\\n`\n + `6. Keep it SHORT (under ~300 words). Respond with the brief body only, no preamble.`\n )\n}\n\nexport interface StaticContextPack {\n prompt: string\n agentsMd: string\n claudeMd: string\n repoStructure: string\n searchContext: string\n}\n\n/** Assemble the capped static pack Sol sees (static-first for cache hits). */\nexport function buildStaticContextPack(pack: StaticContextPack): string {\n const parts: Array<string> = [`USER REQUEST:\\n${pack.prompt}`]\n if (pack.agentsMd.trim().length > 0) {\n parts.push(`REPO GUIDANCE (AGENTS.md):\\n${pack.agentsMd.slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP)}`)\n }\n if (pack.claudeMd.trim().length > 0) {\n parts.push(`REPO GUIDANCE (CLAUDE.md):\\n${pack.claudeMd.slice(0, CHEAPEST_REWRITE_GUIDANCE_CAP)}`)\n }\n if (pack.repoStructure.trim().length > 0) {\n parts.push(`REPO STRUCTURE:\\n${pack.repoStructure.slice(0, CHEAPEST_REWRITE_STRUCTURE_CAP)}`)\n }\n if (pack.searchContext.trim().length > 0) {\n parts.push(pack.searchContext)\n }\n return parts.join(\"\\n\\n\")\n}\n\n/**\n * Wrap Sol's raw brief as the additive Luna-facing block. Returns \"\" when\n * Sol produced nothing usable (caller treats that as fail-open).\n */\nexport function wrapLunaBrief(solText: string): string {\n const body = solText\n .replace(DEEP_GROUNDING_FLAG, \"\")\n .split(\"\\n\")\n .filter((line) => !line.trimStart().startsWith(NEED_MORE_PREFIX))\n .join(\"\\n\")\n .trim()\n if (body.length === 0) return \"\"\n const capped = body.length > CHEAPEST_REWRITE_BRIEF_CAP\n ? `${body.slice(0, CHEAPEST_REWRITE_BRIEF_CAP).trimEnd()}…`\n : body\n return (\n `LUNA BRIEF (advisory, additive — the original request above still stands):\\n${capped}`\n )\n}\n\nexport interface CheapestRewriteIO {\n /** One `mcp__search__code` call; returns raw result text (\"\" on failure). */\n searchCode: (query: string, mode: \"lexical\" | \"semantic\", signal?: AbortSignal) => Promise<string>\n /** One Sol `/v1/responses` inference at medium effort; returns text (\"\" on failure). */\n inferSol: (system: string, user: string, signal?: AbortSignal) => Promise<string>\n /** Static repo guidance + structure (read by the caller via fs, capped). */\n staticPack: () => Promise<Omit<StaticContextPack, \"prompt\" | \"searchContext\">>\n /** One-shot flag: true when this session already spent its rewrite. */\n hasRewriteRun: (sessionId: string) => Promise<boolean>\n /** Record the spend (attempt-marking: called before running). Idempotent. */\n markRewriteRun: (sessionId: string) => Promise<void>\n /** Wall-clock budget for search + Sol (default 20s). */\n timeoutMs?: number\n}\n\n/**\n * Run the adaptive rewrite. Returns the wrapped Luna brief, or null when\n * anything is missing/empty/over-budget so the caller falls back to the\n * existing V2 scope/goal path. Never throws to the orchestrator.\n */\nexport async function runCheapestRewrite(input: {\n prompt: string\n searchEnabled: boolean\n bluebirdEnabled: boolean\n io: CheapestRewriteIO\n}): Promise<string | null> {\n const timeoutMs = input.io.timeoutMs ?? CHEAPEST_REWRITE_TIMEOUT_MS\n const controller = new AbortController()\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n const work = (async (): Promise<string | null> => {\n const semanticAvailable = input.searchEnabled || input.bluebirdEnabled\n const [lexical, semantic, statik] = await Promise.all([\n input.io.searchCode(input.prompt, \"lexical\", controller.signal).catch(() => \"\"),\n semanticAvailable\n ? input.io.searchCode(input.prompt, \"semantic\", controller.signal).catch(() => \"\")\n : Promise.resolve(\"\"),\n input.io.staticPack().catch(() => ({ agentsMd: \"\", claudeMd: \"\", repoStructure: \"\" })),\n ])\n const searchContext = semanticAvailable\n ? `Lexical search results:\\n${lexical.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}\\n\\nSemantic search results:\\n${semantic.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}`\n : `Lexical search results:\\n${lexical.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}`\n const user = buildStaticContextPack({\n prompt: input.prompt,\n agentsMd: statik.agentsMd,\n claudeMd: statik.claudeMd,\n repoStructure: statik.repoStructure,\n searchContext,\n })\n const first = await input.io\n .inferSol(\n buildSolRewriteSystem({\n searchEnabled: input.searchEnabled,\n bluebirdEnabled: input.bluebirdEnabled,\n turnBudget: CHEAPEST_REWRITE_DEFAULT_TURNS,\n }),\n user,\n controller.signal,\n )\n .catch(() => \"\")\n if (!first || first.trim().length === 0) return null\n\n // Adaptive extension: only when Sol flags deep grounding AND names a\n // follow-up query AND turns remain (3 used → up to 5). One extra\n // grounding round + one final re-inference, then stop regardless.\n const budget = resolveRewriteTurnBudget(first)\n const followUp = parseNeedMoreQuery(first)\n if (budget !== CHEAPEST_REWRITE_MAX_TURNS || followUp.length === 0) {\n const brief = wrapLunaBrief(first)\n return brief.length > 0 ? brief : null\n }\n const extra = await input.io.searchCode(followUp, \"lexical\", controller.signal).catch(() => \"\")\n if (extra.trim().length === 0) {\n const brief = wrapLunaBrief(first)\n return brief.length > 0 ? brief : null\n }\n const second = await input.io\n .inferSol(\n buildSolRewriteSystem({\n searchEnabled: input.searchEnabled,\n bluebirdEnabled: input.bluebirdEnabled,\n turnBudget: CHEAPEST_REWRITE_MAX_TURNS,\n }),\n `${user}\\n\\nFOLLOW-UP GROUNDING for \"${followUp}\":\\n${extra.slice(0, CHEAPEST_REWRITE_SEARCH_CAP)}\\n\\nRewrite the brief with this grounding (same rules, short).`,\n controller.signal,\n )\n .catch(() => \"\")\n const brief = wrapLunaBrief(second.trim().length > 0 ? second : first)\n return brief.length > 0 ? brief : null\n })()\n work.catch(() => {})\n const raced = await Promise.race<string | null | \"__timeout__\">([\n work,\n new Promise<\"__timeout__\">((resolve) => {\n timer = setTimeout(() => resolve(\"__timeout__\"), timeoutMs)\n }),\n ])\n if (raced === \"__timeout__\" || raced === null) return null\n return raced\n } catch {\n return null\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n}\n","/**\n * Pure decision logic for the `UserPromptSubmit` hook (the front-end of the\n * floor-raising surface). It serves TWO duties on the one event:\n *\n * 1. Per-prompt budget reset — clears the Stop-gate's block counter for this\n * session so `maxBlocks` is \"per user prompt\", not \"per session lifetime\"\n * (the per-prompt scoping the Stop-gate relies on).\n * 2. Goal steer — for a NON-trivial prompt, inject an advisory GOAL directive\n * (additive context, never blocking) pointing the model at `/gh-research`\n * then `/gh-orchestrate`. It raises the prior; it does not force execution.\n *\n * Top-level only: like the Stop-gate, it stands down in a subagent/teammate\n * context (the payload carries `agent_type`/`agent_id` there) so it never\n * recurses into spawned workers. Fail-open and never blocking: any error or a\n * trivial prompt yields an empty injection.\n */\n\nimport {\n isCheapestRewriteEligible,\n runCheapestRewrite,\n type CheapestRewriteIO,\n} from \"../cheapest-prompt-rewrite\"\nimport { buildSelfCommand, type SelfInvocation } from \"../hook-launcher/self-invocation\"\nimport { isSubagentContext } from \"./stop-gate-policy\"\n\n/**\n * The advisory goal injected for a non-trivial prompt. Uses the skills' slash\n * invocation form. The model still decides whether to follow it; the Stop-gate\n * backstops correctness at the output end.\n */\nexport const PROMPT_STEER_GOAL =\n \"GOAL (advisory): for a non-trivial task, FIRST run /gh-research on this ask to \"\n + \"information saturation — verify the load-bearing claims against the actual code \"\n + \"before planning, and do not plan or write code until research is saturated. THEN, \"\n + \"for an implementation or change task, run /gh-orchestrate to compose and run a \"\n + \"floor-raising workflow (it checkpoints before expensive work). Skip both for a \"\n + \"trivial ask; you may decline if they do not fit.\"\n\n/**\n * Cheap, conservative complexity heuristic — a long prompt, an imperative\n * build/change verb, or an explicit multi-file scope. Trivial prompts get no\n * steer (no analysis-paralysis tax on quick asks).\n */\nexport function isNonTrivialPrompt(prompt: string): boolean {\n const p = prompt.trim()\n if (p.length === 0) return false\n if (p.length >= 280) return true\n const verb =\n /\\b(implement|build|refactor|migrate|fix|debug|diagnose|design|add|create|rewrite|optimi[sz]e|integrate|architect|investigate|audit)\\b/i\n if (verb.test(p)) return true\n // Multi-file / cross-cutting scope signal.\n return /\\b(across|throughout|every|all)\\b.*\\b(file|module|test|route|component)s?\\b/i.test(p)\n}\n\nexport interface PromptSubmitDecision {\n /** Session whose Stop-gate block budget to reset (undefined = none). */\n resetSession?: string\n /** Text to print to stdout (added to the model's context). Empty = nothing. */\n inject: string\n}\n\nexport function decidePromptSubmit(input: { stdin: string; steerEnabled: boolean }): PromptSubmitDecision {\n let payload: { session_id?: unknown; prompt?: unknown; agent_type?: unknown; agent_id?: unknown } = {}\n try {\n const p: unknown = JSON.parse(input.stdin)\n if (p && typeof p === \"object\") payload = p as typeof payload\n } catch {\n return { inject: \"\" }\n }\n // Top-level only: a subagent/teammate prompt gets neither reset nor steer.\n if (isSubagentContext(payload)) return { inject: \"\" }\n const decision: PromptSubmitDecision = { inject: \"\" }\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (sessionId) decision.resetSession = sessionId\n const prompt = typeof payload.prompt === \"string\" ? payload.prompt : \"\"\n if (input.steerEnabled && isNonTrivialPrompt(prompt)) decision.inject = PROMPT_STEER_GOAL\n return decision\n}\n\n// ─── UserPromptSubmit V2 (advisory: classify + grounded scope/goal) ──────────\n\n/**\n * Static encouragement injected only for a non-trivial prompt (no extra model\n * call, no latency tax): nudge parallel lexical+semantic search before\n * concluding. Mirrors the v1 advisory tone: additive, never blocking.\n *\n * @deprecated Prefer `getPromptSearchTip(searchEnabled, bluebirdEnabled)` so\n * the tip matches the launch's search backend. Kept for callers without flags;\n * built with semantic search enabled.\n */\nexport const PROMPT_SEARCH_TIP = getPromptSearchTip(true)\n\n/**\n * Build the search tip for the launch's search backend. When Bluebird is\n * enabled it owns both semantic and lexical calls; otherwise local ColBERT is\n * used when enabled, or lexical-only search when neither backend is enabled.\n */\nexport function getPromptSearchTip(\n searchEnabled: boolean,\n bluebirdEnabled: boolean = false,\n): string {\n if (bluebirdEnabled) {\n return (\n \"TIP (advisory): when this task needs code context, search Bluebird semantic + \"\n + \"lexical in parallel — two `mcp__search__code` calls issued in the same turn. \"\n + \"Bluebird failures are visible and do not fall back locally.\"\n )\n }\n if (searchEnabled) {\n return (\n \"TIP (advisory): when this task needs code context, search lexical + semantic in \"\n + \"parallel — one `mcp__search__code` call with mode:\\\"lexical\\\" and one with \"\n + \"mode:\\\"semantic\\\", issued in the same turn — before concluding.\"\n )\n }\n return (\n \"TIP (advisory): when this task needs code context, search lexical \"\n + \"(`mcp__search__code` with mode:\\\"lexical\\\"/\\\"exact\\\"/\\\"regex\\\" for exact \"\n + \"symbols, filenames, errors, routes, flags, and config keys), issuing \"\n + \"parallel calls in the same turn — before concluding.\"\n )\n}\n\n/**\n * Build the scope-inference system prompt for the launch's search backend.\n * Mirrors `getPromptSearchTip`: Bluebird and local ColBERT variants ground the\n * inference in lexical + semantic results; the local-only variant in lexical results.\n */\nexport function getPromptScopeSystem(\n searchEnabled: boolean,\n bluebirdEnabled: boolean = false,\n): string {\n const searchNoun = bluebirdEnabled\n ? \"a Bluebird lexical + semantic code search\"\n : searchEnabled\n ? \"a local lexical + semantic code search\"\n : \"a lexical code search\"\n return (\n \"You are a scoping assistant for a coding agent about to act on a user's request. \"\n + `You are given the user's request and the results of ${searchNoun} `\n + \"over the relevant repository. Produce a SHORT advisory note (<= 120 words), plain text only:\\n\"\n + \"1. SCOPE: one line — is this trivial, focused (one area), or large/cross-cutting — grounded in \"\n + \"what the search surfaced (reference the most relevant file(s) by name).\\n\"\n + \"2. GOAL: restate the user's OWN ask as a single measurable objective, in THEIR terms. Do NOT \"\n + \"invent new requirements or acceptance criteria beyond what they asked.\\n\"\n + \"3. Only if the task is large/cross-cutting, add a final line: \\\"Consider /gh-research first to \"\n + \"saturate understanding, then /gh-orchestrate to compose a floor-raising workflow.\\\" Omit it for a \"\n + \"focused or trivial task.\\n\"\n + \"This is advisory — the agent decides whether to follow it. Be concrete and concise; no preamble.\"\n )\n}\n\n/** System prompt for the single gpt-6-luna scope/goal inference. Steers a SHORT,\n * user-derived (not invented) advisory note grounded in the search results.\n *\n * @deprecated Prefer `getPromptScopeSystem(searchEnabled, bluebirdEnabled)` so\n * the prompt matches the launch's search backend. Kept for callers without flags;\n * built with local semantic search enabled. */\nexport const PROMPT_SCOPE_SYSTEM = getPromptScopeSystem(true)\n\n/** Injected IO for V2, all best-effort. Each network call returns its text and\n * never throws to the orchestrator (the orchestrator wraps the enrichment in a\n * timeout + try/catch and falls open to the regex goal).\n *\n * INVARIANT for live callers: each IO call MUST self-timeout (the live wiring\n * passes a per-call timeoutMs to callMcpTool / callInference). The orchestrator's\n * outer `timeoutMs` race only bounds how long it WAITS for a result before\n * failing open — it does NOT abort the in-flight call. A non-self-timing-out IO\n * would leave a socket open until the hook process's terminal `process.exit(0)`,\n * which is the hard backstop but not a substitute for the per-call bound. */\nexport interface PromptSubmitV2IO {\n /** One `mcp__search__code` call; returns the raw result text (\"\" on failure).\n * Receives the orchestrator's AbortSignal so a timed-out enrichment cancels\n * the in-flight request (live callers thread it into the HTTP fetch). */\n searchCode: (query: string, mode: \"lexical\" | \"semantic\", signal?: AbortSignal) => Promise<string>\n /** One gpt-6-luna `/v1/responses` inference; returns assistant text (\"\" on failure).\n * Receives the orchestrator's AbortSignal (see `searchCode`). */\n infer: (system: string, user: string, signal?: AbortSignal) => Promise<string>\n /** Pending advisory findings from the prior turn's background review. */\n readFindings: (sessionId: string) => Promise<string | null>\n clearFindings: (sessionId: string) => Promise<void>\n /** Stash this prompt so the next Stop review can judge the diff against it. */\n storePrompt: (sessionId: string, prompt: string) => Promise<void>\n /** Wall-clock budget for the substantive-prompt enrichment (search+infer);\n * on overrun the decision falls open to the regex goal. Default 22s. */\n timeoutMs?: number\n}\n\n/** Max chars of each search-result blob fed into the scope inference. */\nconst SEARCH_CONTEXT_CAP = 6 * 1024\n\n/** Wrap the prior-turn review findings in an explicitly NON-AUTHORITATIVE frame. */\nfunction framePendingFindings(findings: string): string {\n return (\n \"ADVISORY — independent review of your PREVIOUS change (NON-AUTHORITATIVE): an independent \"\n + \"gpt-6-luna reviewer flagged the following. Evaluate each on its merits — fix the real ones, and \"\n + \"ignore any wrong one with a one-line reason. You are NOT obligated to act on these.\\n\"\n + findings.trim()\n )\n}\n\nfunction joinSections(sections: Array<string>): string {\n return sections\n .map((s) => s.trim())\n .filter((s) => s.length > 0)\n .join(\"\\n\\n\")\n}\n\n/**\n * V2 decision: budget reset (via resetSession) + a grounded, user-derived scope\n * note + surfaced prior-turn findings. ASYNC and IO-driven, but every IO is\n * best-effort and the substantive enrichment is timeout-bounded with a fail-open\n * to the v1 regex goal — so this never blocks and never wedges the prompt.\n *\n * - subagent/teammate -> empty (top-level only, like v1).\n * - findings -> always surfaced (+ cleared) regardless of triviality.\n * - trivial prompt -> findings only (no search tip, no model call).\n * - substantive prompt -> search tip + grounded enrichment (parallel\n * lexical+semantic through Bluebird when enabled,\n * otherwise local semantic when enabled, else lexical-only)\n * -> ONE gpt-6-luna call\n * -> grounded scope/goal note. Fail-open to PROMPT_STEER_GOAL.\n * - steerEnabled=false -> findings only (no goal/tip).\n */\nexport async function decidePromptSubmitV2(input: {\n stdin: string\n steerEnabled: boolean\n io: PromptSubmitV2IO\n /** Whether local ColBERT semantic search is enabled for this launch. */\n searchEnabled?: boolean\n /** Whether Bluebird owns semantic and lexical search for this launch. */\n bluebirdEnabled?: boolean\n /** Launch profile id; only `\"cheapest\"` enables the Sol rewrite branch. */\n profile?: string\n /** True when `GH_ROUTER_DISABLE_CHEAPEST_REWRITE` opts out of the rewrite. */\n rewriteDisabled?: boolean\n /** Sol rewrite IO (cheapest only). Absent = existing Luna scope path. */\n rewrite?: CheapestRewriteIO\n}): Promise<PromptSubmitDecision> {\n let payload: { session_id?: unknown; prompt?: unknown; agent_type?: unknown; agent_id?: unknown } = {}\n try {\n const p: unknown = JSON.parse(input.stdin)\n if (p && typeof p === \"object\") payload = p as typeof payload\n } catch {\n return { inject: \"\" }\n }\n if (isSubagentContext(payload)) return { inject: \"\" }\n\n const decision: PromptSubmitDecision = { inject: \"\" }\n const sessionId = typeof payload.session_id === \"string\" && payload.session_id.length > 0 ? payload.session_id : \"\"\n if (sessionId) decision.resetSession = sessionId\n const prompt = typeof payload.prompt === \"string\" ? payload.prompt : \"\"\n\n // Stash the prompt for the next Stop review (best-effort, fire-and-await so a\n // slow disk doesn't matter — it's a tiny local write).\n if (sessionId) await input.io.storePrompt(sessionId, prompt).catch(() => {})\n\n // Read + clear any pending findings from the prior turn's background review.\n let findingsBlock = \"\"\n if (sessionId) {\n const pending = await input.io.readFindings(sessionId).catch(() => null)\n if (pending && pending.trim().length > 0) {\n findingsBlock = framePendingFindings(pending)\n await input.io.clearFindings(sessionId).catch(() => {})\n }\n }\n\n // steer disabled -> findings only.\n if (!input.steerEnabled) {\n decision.inject = findingsBlock\n return decision\n }\n\n // Trivial prompt -> no search tip and no model call; surface findings only.\n if (!isNonTrivialPrompt(prompt)) {\n decision.inject = findingsBlock\n return decision\n }\n\n // Substantive prompt -> search tip + grounded enrichment, timeout-bounded + fail-open.\n const searchEnabled = input.searchEnabled === true\n const bluebirdEnabled = input.bluebirdEnabled === true\n const semanticAvailable = searchEnabled || bluebirdEnabled\n const searchTip = getPromptSearchTip(searchEnabled, bluebirdEnabled)\n\n // Cheapest-only Sol → Luna rewrite: adaptive 3/5-turn grounded brief,\n // additive and fail-open to the Luna scope path below on null.\n // One-shot per session (first non-trivial prompt only): the flag is marked\n // BEFORE running (attempt-marking bounds spend even if Sol fails open), and\n // a missing session id fails closed (never spend blindly).\n // NOTE: non-triviality is recomputed here (not assumed from the early\n // return above) so this branch stays correct if the flow is refactored.\n if (\n input.rewrite\n && isCheapestRewriteEligible({\n profile: input.profile,\n promptIsNonTrivial: isNonTrivialPrompt(prompt),\n steerEnabled: input.steerEnabled,\n rewriteDisabled: input.rewriteDisabled === true,\n })\n && sessionId.length > 0\n && !(await input.rewrite.hasRewriteRun(sessionId).catch(() => true))\n ) {\n await input.rewrite.markRewriteRun(sessionId).catch(() => {})\n const brief = await runCheapestRewrite({\n prompt,\n searchEnabled,\n bluebirdEnabled,\n io: input.rewrite,\n }).catch(() => null)\n if (brief && brief.length > 0) {\n decision.inject = joinSections([searchTip, brief, findingsBlock])\n return decision\n }\n // else: fall through to the existing Luna scope enrichment.\n }\n\n const scopeSystem = getPromptScopeSystem(searchEnabled, bluebirdEnabled)\n const timeoutMs = input.io.timeoutMs ?? 22_000\n let goal = PROMPT_STEER_GOAL // fail-open default.\n let timer: ReturnType<typeof setTimeout> | undefined\n // One controller cancels BOTH search calls + the inference when the race ends\n // (timeout OR success), so a lost-race fetch never keeps the short-lived hook\n // process alive past its decision. Aborting after success is a harmless no-op.\n const controller = new AbortController()\n try {\n const enrich = (async (): Promise<string> => {\n if (!semanticAvailable) {\n const lexical = await input.io.searchCode(prompt, \"lexical\", controller.signal).catch(() => \"\")\n const searchContext = `Lexical search results:\\n${lexical.slice(0, SEARCH_CONTEXT_CAP)}`\n const note = await input.io.infer(\n scopeSystem,\n `USER REQUEST:\\n${prompt}\\n\\n${searchContext}`,\n controller.signal,\n )\n return note.trim()\n }\n const [lexical, semantic] = await Promise.all([\n input.io.searchCode(prompt, \"lexical\", controller.signal).catch(() => \"\"),\n input.io.searchCode(prompt, \"semantic\", controller.signal).catch(() => \"\"),\n ])\n const searchContext =\n `Lexical search results:\\n${lexical.slice(0, SEARCH_CONTEXT_CAP)}\\n\\n`\n + `Semantic search results:\\n${semantic.slice(0, SEARCH_CONTEXT_CAP)}`\n const note = await input.io.infer(\n scopeSystem,\n `USER REQUEST:\\n${prompt}\\n\\n${searchContext}`,\n controller.signal,\n )\n return note.trim()\n })()\n // Mark `enrich` handled so a post-race rejection (e.g. the inference aborting\n // after the timeout already won) can't surface as an unhandled rejection.\n enrich.catch(() => {})\n // The timer is cleared in `finally` (so when `enrich` wins, no live timer\n // lingers for the rest of `timeoutMs`).\n const raced = await Promise.race<string | \"__timeout__\">([\n enrich,\n new Promise<\"__timeout__\">((resolve) => {\n timer = setTimeout(() => resolve(\"__timeout__\"), timeoutMs)\n }),\n ])\n if (raced !== \"__timeout__\" && raced.length > 0) goal = raced\n } catch {\n // keep the fail-open regex goal.\n } finally {\n if (timer) clearTimeout(timer)\n controller.abort()\n }\n\n decision.inject = joinSections([searchTip, goal, findingsBlock])\n return decision\n}\n\n/** Build the shell command Claude Code runs for the `UserPromptSubmit` hook. */\nexport function buildPromptSubmitHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-prompt-submit\")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,yBAAyB;AACtC,MAAa,0BAA0B;;AAUvC,MAAa,8BAA8B;;AAE3C,MAAa,gCAAgC;;AAE7C,MAAa,iCAAiC;;AAE9C,MAAa,6BAA6B;;AAG1C,MAAa,sBAAsB;;AAEnC,MAAa,mBAAmB;AAahC,SAAgB,6BAA6B,MAAyB,QAAQ,KAAc;CAC1F,MAAM,KAAK,IAAI,sCAAsC,GAAA,CAAI,KAAK,CAAC,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AkB;GAMrE,QAAO,MALY,MAAM,GAAG,MAC1B,aACA,kBAAkB,OAAO,MAAM,iBAC/B,WAAW,MACb,EAAA,CACY,KAAK;EACnB,EAAA,CAAG;EAGH,OAAO,YAAY,CAAC,CAAC;EAGrB,MAAM,QAAQ,MAAM,QAAQ,KAA6B,CACvD,QACA,IAAI,SAAwB,YAAY;GACtC,QAAQ,iBAAiB,QAAQ,aAAa,GAAG,SAAS;EAC5D,CAAC,CACH,CAAC;EACD,IAAI,UAAU,iBAAiB,MAAM,SAAS,GAAG,OAAO;CAC1D,QAAQ,CAER,UAAU;EACR,IAAI,OAAO,aAAa,KAAK;EAC7B,WAAW,MAAM;CACnB;CAEA,SAAS,SAAS,aAAa;EAAC;EAAW;EAAM;CAAa,CAAC;CAC/D,OAAO;AACT;;AAGA,SAAgB,6BAA6B,YAAoC;CAC/E,OAAO,iBAAiB,YAAY,wBAAwB;AAC9D"}
@@ -1,7 +1,7 @@
1
1
  import { E as extractZipMember, I as withInstallLock, T as extractTarGzMember } from "./service-backend-7SPDLUB9.js";
2
2
  import { t as PATHS } from "./paths-CpbTHKeP.js";
3
3
  import { i as parseBoolEnv, n as killChildProcessTree, o as resolveExecutable, s as runCommandCapture } from "./exec-MCU1H-KZ.js";
4
- import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, M as satisfiesMinVersion, O as toolbeltSkipSet, j as assetFor, k as vscodeRipgrepPath, un as collapsePathKeys } from "./peer-mcp-personas-CIV3aDP6.js";
4
+ import { A as TOOLBELT_TOOLS, D as toolbeltEnabled, M as satisfiesMinVersion, O as toolbeltSkipSet, fn as collapsePathKeys, j as assetFor, k as vscodeRipgrepPath } from "./peer-mcp-personas-C200IycG.js";
5
5
  import { a as sweepRegistry } from "./lifecycle-kpLzHUgD.js";
6
6
  import consola from "consola";
7
7
  import { existsSync } from "node:fs";
@@ -321,7 +321,7 @@ function getCodexVersion() {
321
321
  function buildCodexCmd(target) {
322
322
  const cmd = ["codex"];
323
323
  if (target.serverUrl) cmd.push(...buildCodexProviderConfigFlags(target.serverUrl));
324
- cmd.push("--sandbox", "workspace-write", "--ask-for-approval", "on-request", "-m", target.model ?? "gpt-6-sol", ...target.extraArgs);
324
+ cmd.push("--sandbox", "workspace-write", "--ask-for-approval", "on-request", "-m", target.model ?? "gpt-5.6-sol", ...target.extraArgs);
325
325
  return cmd;
326
326
  }
327
327
  function buildLaunchCommand(target) {
@@ -693,4 +693,4 @@ async function exposedCommands(binDir) {
693
693
  //#endregion
694
694
  export { STRIPPED_AUTH_ROUTING_ENV_KEYS as a, launchChild as i, buildCodexProviderConfigFlags as n, getCodexVersion as r, provisionToolbelt as t };
695
695
 
696
- //# sourceMappingURL=provision-J68elA3c.js.map
696
+ //# sourceMappingURL=provision-BFTONLfA.js.map