github-router 0.3.295 → 0.3.302
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-pkIop1NU.js → attribution-settings-B1xutIts.js} +153 -16
- package/dist/attribution-settings-B1xutIts.js.map +1 -0
- package/dist/{auth-CluG5e-l.js → auth-CpjOjoUG.js} +4 -3
- package/dist/{auth-CluG5e-l.js.map → auth-CpjOjoUG.js.map} +1 -1
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-iOzfnKJe.js → check-usage-BsN3S4Fu.js} +4 -4
- package/dist/{check-usage-iOzfnKJe.js.map → check-usage-BsN3S4Fu.js.map} +1 -1
- package/dist/{claude-DNmxk-Rm.js → claude-uRuzEH0W.js} +216 -112
- package/dist/claude-uRuzEH0W.js.map +1 -0
- package/dist/{codex-Dl4gpHn-.js → codex-D5ag-liR.js} +6 -5
- package/dist/{codex-Dl4gpHn-.js.map → codex-D5ag-liR.js.map} +1 -1
- package/dist/{debug-DsEwleGg.js → debug-BXRPyeqO.js} +2 -2
- package/dist/{debug-DsEwleGg.js.map → debug-BXRPyeqO.js.map} +1 -1
- package/dist/engine-2uMJ4Isk.js +2 -0
- package/dist/fast-profile-contract-K3P58nj3.js +57 -0
- package/dist/fast-profile-contract-K3P58nj3.js.map +1 -0
- package/dist/{gate-discovery-WcduofL4.js → gate-discovery-BTRVyKWu.js} +5 -5
- package/dist/{gate-discovery-WcduofL4.js.map → gate-discovery-BTRVyKWu.js.map} +1 -1
- package/dist/{get-copilot-usage-B7Z4XVWj.js → get-copilot-usage-ByjQqhdi.js} +3 -2
- package/dist/{get-copilot-usage-B7Z4XVWj.js.map → get-copilot-usage-ByjQqhdi.js.map} +1 -1
- package/dist/hooks.mjs +351 -21
- package/dist/hooks.sha256 +1 -1
- package/dist/{internal-artifact-open-D6tKMg8v.js → internal-artifact-open-DRSxShAW.js} +2 -2
- package/dist/{internal-artifact-open-D6tKMg8v.js.map → internal-artifact-open-DRSxShAW.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-CPlCrTlU.js → internal-fast-dispatch-guard-CYOWbxjX.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-Xyu17k9X.js → internal-fast-dispatch-guard-D2HcfXZv.js} +22 -18
- package/dist/internal-fast-dispatch-guard-D2HcfXZv.js.map +1 -0
- package/dist/{internal-first-mate-guard-C9BV7J4U.js → internal-first-mate-guard-Bcb5JwiO.js} +3 -3
- package/dist/{internal-first-mate-guard-C9BV7J4U.js.map → internal-first-mate-guard-Bcb5JwiO.js.map} +1 -1
- package/dist/{internal-first-mate-guard-WJApyc8j.js → internal-first-mate-guard-Brh_uois.js} +1 -1
- package/dist/internal-max-dispatch-guard-Bcjavapx.js +2 -0
- package/dist/internal-max-dispatch-guard-BjSVXMvC.js +198 -0
- package/dist/internal-max-dispatch-guard-BjSVXMvC.js.map +1 -0
- package/dist/{internal-plan-review-t3PuNfuL.js → internal-plan-review-DVY-iV2x.js} +3 -3
- package/dist/{internal-plan-review-t3PuNfuL.js.map → internal-plan-review-DVY-iV2x.js.map} +1 -1
- package/dist/{internal-prompt-submit-C3KovHQG.js → internal-prompt-submit-BTqRn4FW.js} +4 -4
- package/dist/{internal-prompt-submit-C3KovHQG.js.map → internal-prompt-submit-BTqRn4FW.js.map} +1 -1
- package/dist/{internal-session-bind-d2uoja8I.js → internal-session-bind-YfH656lt.js} +2 -2
- package/dist/{internal-session-bind-d2uoja8I.js.map → internal-session-bind-YfH656lt.js.map} +1 -1
- package/dist/{internal-stop-hook-DJFtGCsE.js → internal-stop-hook-BZg__ab6.js} +5 -5
- package/dist/{internal-stop-hook-DJFtGCsE.js.map → internal-stop-hook-BZg__ab6.js.map} +1 -1
- package/dist/{internal-stop-review-YtDUGXpX.js → internal-stop-review-B8MmEyQ1.js} +2 -2
- package/dist/{internal-stop-review-YtDUGXpX.js.map → internal-stop-review-B8MmEyQ1.js.map} +1 -1
- package/dist/{internal-worker-guard-CdkeS9PN.js → internal-worker-guard-Dr6W83TC.js} +2 -2
- package/dist/{internal-worker-guard-CdkeS9PN.js.map → internal-worker-guard-Dr6W83TC.js.map} +1 -1
- package/dist/{internal-workspace-header-tuBXJV22.js → internal-workspace-header-Cep0WSIb.js} +2 -2
- package/dist/{internal-workspace-header-tuBXJV22.js.map → internal-workspace-header-Cep0WSIb.js.map} +1 -1
- package/dist/lifecycle-4TZrJuAa.js +2 -0
- package/dist/{lifecycle-CM9eTzvk.js → lifecycle-CmPJ6e_6.js} +2 -2
- package/dist/{lifecycle-CM9eTzvk.js.map → lifecycle-CmPJ6e_6.js.map} +1 -1
- package/dist/{lifecycle-Bg6doY3-.js → lifecycle-DgsJ_8Am.js} +2 -2
- package/dist/{lifecycle-Bg6doY3-.js.map → lifecycle-DgsJ_8Am.js.map} +1 -1
- package/dist/lifecycle-O91Vzzb-.js +2 -0
- package/dist/main.js +19 -18
- package/dist/main.js.map +1 -1
- package/dist/max-profile-contract-BTXowh6k.js +264 -0
- package/dist/max-profile-contract-BTXowh6k.js.map +1 -0
- package/dist/{mcp-workspace-header-dERl2YTT.js → mcp-workspace-header-NzFD0Wgd.js} +2 -2
- package/dist/{mcp-workspace-header-dERl2YTT.js.map → mcp-workspace-header-NzFD0Wgd.js.map} +1 -1
- package/dist/{models-DZ4hYsR7.js → models-1KwEUgzd.js} +3 -3
- package/dist/{models-DZ4hYsR7.js.map → models-1KwEUgzd.js.map} +1 -1
- package/dist/{orchestration-BiGCEwbH.js → orchestration-CYyp9w-t.js} +2 -2
- package/dist/{orchestration-BiGCEwbH.js.map → orchestration-CYyp9w-t.js.map} +1 -1
- package/dist/paths-DDAiPVto.js +2 -0
- package/dist/{paths-Ci485qSJ.js → paths-IcZW8gZx.js} +4 -4
- package/dist/{paths-Ci485qSJ.js.map → paths-IcZW8gZx.js.map} +1 -1
- package/dist/{peer-mcp-personas-BwNtC8jt.js → peer-mcp-personas-DwEiYeJS.js} +498 -260
- package/dist/peer-mcp-personas-DwEiYeJS.js.map +1 -0
- package/dist/{plan-review-hook-DuW0pSoM.js → plan-review-hook-szSNt6uU.js} +3 -3
- package/dist/{plan-review-hook-DuW0pSoM.js.map → plan-review-hook-szSNt6uU.js.map} +1 -1
- package/dist/{prompt-submit-hook-IMl7ssfr.js → prompt-submit-hook-ZUxo_jEl.js} +3 -3
- package/dist/{prompt-submit-hook-IMl7ssfr.js.map → prompt-submit-hook-ZUxo_jEl.js.map} +1 -1
- package/dist/{provision-DeNqzvSM.js → provision-BLT1pCFy.js} +4 -4
- package/dist/{provision-DeNqzvSM.js.map → provision-BLT1pCFy.js.map} +1 -1
- package/dist/{self-invocation-DAB_od0C.js → self-invocation-BJWbA8ka.js} +2 -2
- package/dist/{self-invocation-DAB_od0C.js.map → self-invocation-BJWbA8ka.js.map} +1 -1
- package/dist/{serve-BS5EmCpM.js → serve-wEZoOijw.js} +13 -12
- package/dist/{serve-BS5EmCpM.js.map → serve-wEZoOijw.js.map} +1 -1
- package/dist/{server-setup-DsGJnJ_O.js → server-setup-Zn5wkosb.js} +268 -41
- package/dist/server-setup-Zn5wkosb.js.map +1 -0
- package/dist/{start-vJdt2MiM.js → start-DSqU8d8h.js} +3 -3
- package/dist/{start-vJdt2MiM.js.map → start-DSqU8d8h.js.map} +1 -1
- package/dist/state-B8adscCv.js +51 -0
- package/dist/state-B8adscCv.js.map +1 -0
- package/dist/{stop-gate-hook-DQnh_KfI.js → stop-gate-hook-CJOk28zd.js} +3 -3
- package/dist/{stop-gate-hook-DQnh_KfI.js.map → stop-gate-hook-CJOk28zd.js.map} +1 -1
- package/dist/{stop-gate-policy-DMr3KVmw.js → stop-gate-policy-zhzRIj6G.js} +2 -2
- package/dist/{stop-gate-policy-DMr3KVmw.js.map → stop-gate-policy-zhzRIj6G.js.map} +1 -1
- package/dist/{token-BtJhjXXu.js → token-CbuFyx-B.js} +4 -50
- package/dist/token-CbuFyx-B.js.map +1 -0
- package/dist/{worker-dispatch-BEHkTbnH.js → worker-dispatch-DgP5yT26.js} +2 -2
- package/dist/{worker-dispatch-BEHkTbnH.js.map → worker-dispatch-DgP5yT26.js.map} +1 -1
- package/package.json +1 -1
- package/dist/attribution-settings-pkIop1NU.js.map +0 -1
- package/dist/claude-DNmxk-Rm.js.map +0 -1
- package/dist/engine-XnluJUs6.js +0 -2
- package/dist/internal-fast-dispatch-guard-Xyu17k9X.js.map +0 -1
- package/dist/lifecycle-CGLt1cJQ.js +0 -2
- package/dist/lifecycle-DoUwpVDB.js +0 -2
- package/dist/paths-GD7bgGGy.js +0 -2
- package/dist/peer-mcp-personas-BwNtC8jt.js.map +0 -1
- package/dist/server-setup-DsGJnJ_O.js.map +0 -1
- package/dist/token-BtJhjXXu.js.map +0 -1
package/dist/{internal-fast-dispatch-guard-Xyu17k9X.js → internal-fast-dispatch-guard-D2HcfXZv.js}
RENAMED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as FAST_PROFILE_DELEGATION_GRAPH, o as FAST_PROFILE_NATIVE_AGENT_NAMES } from "./fast-profile-contract-K3P58nj3.js";
|
|
2
|
+
import { t as buildSelfCommand } from "./self-invocation-BJWbA8ka.js";
|
|
2
3
|
import { defineCommand } from "citty";
|
|
3
4
|
import { readFileSync } from "node:fs";
|
|
4
5
|
//#region src/lib/fast-dispatch-acl.ts
|
|
@@ -10,25 +11,15 @@ import { readFileSync } from "node:fs";
|
|
|
10
11
|
* It is an in-session Task/Agent ACL, not a shell sandbox: role tool lists
|
|
11
12
|
* narrow the available tools while this graph narrows native dispatch edges.
|
|
12
13
|
*/
|
|
13
|
-
const FAST_NATIVE_AGENT_NAMES =
|
|
14
|
-
"scout",
|
|
15
|
-
"implementer",
|
|
16
|
-
"reviewer",
|
|
17
|
-
"planner",
|
|
18
|
-
"critic"
|
|
19
|
-
];
|
|
14
|
+
const FAST_NATIVE_AGENT_NAMES = FAST_PROFILE_NATIVE_AGENT_NAMES;
|
|
20
15
|
const FAST_NATIVE_AGENT_SET = new Set(FAST_NATIVE_AGENT_NAMES);
|
|
21
16
|
/** Frozen authority graph: each key is a caller and each value its targets. */
|
|
22
17
|
const FAST_DISPATCH_GRAPH = Object.freeze({
|
|
23
|
-
|
|
24
|
-
implementer:
|
|
25
|
-
reviewer:
|
|
26
|
-
planner:
|
|
27
|
-
|
|
28
|
-
"scout",
|
|
29
|
-
"critic"
|
|
30
|
-
]),
|
|
31
|
-
critic: /* @__PURE__ */ new Set()
|
|
18
|
+
Explore: new Set(FAST_PROFILE_DELEGATION_GRAPH.Explore),
|
|
19
|
+
implementer: new Set(FAST_PROFILE_DELEGATION_GRAPH.implementer),
|
|
20
|
+
reviewer: new Set(FAST_PROFILE_DELEGATION_GRAPH.reviewer),
|
|
21
|
+
planner: new Set(FAST_PROFILE_DELEGATION_GRAPH.planner),
|
|
22
|
+
critic: new Set(FAST_PROFILE_DELEGATION_GRAPH.critic)
|
|
32
23
|
});
|
|
33
24
|
/** The hook matcher is intentionally limited to native dispatch tool names. */
|
|
34
25
|
const FAST_DISPATCH_TOOL_MATCHER = "^(Task|Agent)$";
|
|
@@ -106,6 +97,8 @@ function decideFastDispatchGuard(stdin) {
|
|
|
106
97
|
const targetValue = targetResult.value;
|
|
107
98
|
if (!targetValue || !FAST_NATIVE_AGENT_SET.has(targetValue)) return deny(`fast dispatch denied: ${toolName} target must be one of ${FAST_NATIVE_AGENT_NAMES.join(", ")}`);
|
|
108
99
|
const target = targetValue;
|
|
100
|
+
const updatedInput = { ...payload.tool_input };
|
|
101
|
+
delete updatedInput.model;
|
|
109
102
|
const callerType = resolveAliasedString(payload, ["agent_type", "agentType"]);
|
|
110
103
|
const callerId = resolveAliasedString(payload, ["agent_id", "agentId"]);
|
|
111
104
|
const parentMarker = resolveAliasedString(payload, ["parent_tool_use_id", "parentToolUseId"]);
|
|
@@ -128,6 +121,7 @@ function decideFastDispatchGuard(stdin) {
|
|
|
128
121
|
allowed: true,
|
|
129
122
|
caller: "lead",
|
|
130
123
|
target,
|
|
124
|
+
updatedInput,
|
|
131
125
|
verdict: "allow"
|
|
132
126
|
};
|
|
133
127
|
}
|
|
@@ -138,9 +132,18 @@ function decideFastDispatchGuard(stdin) {
|
|
|
138
132
|
allowed: true,
|
|
139
133
|
caller,
|
|
140
134
|
target,
|
|
135
|
+
updatedInput,
|
|
141
136
|
verdict: "allow"
|
|
142
137
|
};
|
|
143
138
|
}
|
|
139
|
+
/** JSON response consumed by Claude Code for an allowed, model-pinned dispatch. */
|
|
140
|
+
function fastDispatchAllowOutput(updatedInput) {
|
|
141
|
+
return JSON.stringify({ hookSpecificOutput: {
|
|
142
|
+
hookEventName: "PreToolUse",
|
|
143
|
+
permissionDecision: "allow",
|
|
144
|
+
updatedInput
|
|
145
|
+
} });
|
|
146
|
+
}
|
|
144
147
|
/** JSON response consumed by Claude Code's PreToolUse hook protocol. */
|
|
145
148
|
function fastDispatchDenyOutput(reason) {
|
|
146
149
|
return JSON.stringify({ hookSpecificOutput: {
|
|
@@ -174,6 +177,7 @@ const internalFastDispatchGuard = defineCommand({
|
|
|
174
177
|
run() {
|
|
175
178
|
const decision = decideFastDispatchGuard(readStdinSync());
|
|
176
179
|
if (!decision.allowed && decision.reason) process.stdout.write(fastDispatchDenyOutput(decision.reason));
|
|
180
|
+
else if (decision.verdict === "allow" && decision.updatedInput) process.stdout.write(fastDispatchAllowOutput(decision.updatedInput));
|
|
177
181
|
process.exitCode = 0;
|
|
178
182
|
}
|
|
179
183
|
});
|
|
@@ -184,4 +188,4 @@ function buildFastDispatchGuardHookCommand(invocation) {
|
|
|
184
188
|
//#endregion
|
|
185
189
|
export { internalFastDispatchGuard as n, FAST_DISPATCH_TOOL_MATCHER as r, buildFastDispatchGuardHookCommand as t };
|
|
186
190
|
|
|
187
|
-
//# sourceMappingURL=internal-fast-dispatch-guard-
|
|
191
|
+
//# sourceMappingURL=internal-fast-dispatch-guard-D2HcfXZv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-fast-dispatch-guard-D2HcfXZv.js","names":[],"sources":["../src/lib/fast-dispatch-acl.ts","../src/internal-fast-dispatch-guard.ts"],"sourcesContent":["/**\n * Pure policy for the fast profile's native Task/Agent delegation graph.\n *\n * This policy is compiled into the hook rather than read from per-launch files,\n * so cleanup or a partial runtime-file write cannot silently disarm the guard.\n * It is an in-session Task/Agent ACL, not a shell sandbox: role tool lists\n * narrow the available tools while this graph narrows native dispatch edges.\n */\n\nimport {\n FAST_PROFILE_DELEGATION_GRAPH,\n FAST_PROFILE_NATIVE_AGENT_NAMES,\n type FastProfileNativeAgentName,\n} from \"./fast-profile-contract\"\n\nexport const FAST_NATIVE_AGENT_NAMES = FAST_PROFILE_NATIVE_AGENT_NAMES\n\nexport type FastNativeAgentName = FastProfileNativeAgentName\n\nconst FAST_NATIVE_AGENT_SET = new Set<string>(FAST_NATIVE_AGENT_NAMES)\n\n/** Frozen authority graph: each key is a caller and each value its targets. */\nexport const FAST_DISPATCH_GRAPH: Readonly<\n Record<FastNativeAgentName, ReadonlySet<FastNativeAgentName>>\n> = Object.freeze({\n Explore: new Set<FastNativeAgentName>(FAST_PROFILE_DELEGATION_GRAPH.Explore),\n implementer: new Set<FastNativeAgentName>(\n FAST_PROFILE_DELEGATION_GRAPH.implementer,\n ),\n reviewer: new Set<FastNativeAgentName>(FAST_PROFILE_DELEGATION_GRAPH.reviewer),\n planner: new Set<FastNativeAgentName>(FAST_PROFILE_DELEGATION_GRAPH.planner),\n critic: new Set<FastNativeAgentName>(FAST_PROFILE_DELEGATION_GRAPH.critic),\n})\n\n/** The hook matcher is intentionally limited to native dispatch tool names. */\nexport const FAST_DISPATCH_TOOL_MATCHER = \"^(Task|Agent)$\"\n\ninterface DispatchPayload {\n tool_name?: unknown\n tool_input?: unknown\n agent_type?: unknown\n agent_id?: unknown\n parent_tool_use_id?: unknown\n agentType?: unknown\n agentId?: unknown\n parentToolUseId?: unknown\n}\n\nexport interface FastDispatchGuardResult {\n allowed: boolean\n reason?: string\n caller?: FastNativeAgentName | \"lead\"\n target?: FastNativeAgentName\n /** Cloned Agent/Task input with a caller model override removed. */\n updatedInput?: Record<string, unknown>\n verdict: \"allow-non-dispatch\" | \"allow\" | \"deny\"\n}\n\nfunction hasOwn(obj: object, key: string): boolean {\n return Object.prototype.hasOwnProperty.call(obj, key)\n}\n\nfunction valuesForAliases(obj: Record<string, unknown>, names: ReadonlyArray<string>): Array<unknown> {\n return names.filter((name) => hasOwn(obj, name)).map((name) => obj[name])\n}\n\n/**\n * Resolve an aliased string field. Null and undefined are marker values. One\n * concrete value is accepted, while different concrete aliases are a conflict.\n */\nfunction resolveAliasedString(\n obj: Record<string, unknown>,\n names: ReadonlyArray<string>,\n): { present: boolean; value?: string; malformed: boolean; conflict: boolean } {\n const values = valuesForAliases(obj, names)\n if (values.length === 0) return { present: false, malformed: false, conflict: false }\n const concrete = values.filter((value) => value !== undefined && value !== null)\n if (concrete.some((value) => typeof value !== \"string\" || value.trim().length === 0)) {\n return { present: true, malformed: true, conflict: false }\n }\n const distinct = [...new Set((concrete as Array<string>).map((value) => value.trim()))]\n if (distinct.length > 1) return { present: true, malformed: false, conflict: true }\n return { present: true, value: distinct[0], malformed: false, conflict: false }\n}\n\nfunction deny(\n reason: string,\n target?: FastNativeAgentName,\n caller?: FastNativeAgentName | \"lead\",\n): FastDispatchGuardResult {\n return { allowed: false, reason, target, caller, verdict: \"deny\" }\n}\n\n/**\n * Evaluate one raw Claude Code PreToolUse payload.\n *\n * Classification happens before strict parsing. A malformed or unrelated\n * ordinary-tool hook therefore passes through, while a recognized Task/Agent\n * dispatch fails closed on malformed input or identity.\n */\nexport function decideFastDispatchGuard(stdin: string | unknown): FastDispatchGuardResult {\n let parsed: unknown\n try {\n parsed = typeof stdin === \"string\" ? JSON.parse(stdin) : stdin\n } catch {\n return deny(\"fast dispatch denied: malformed hook payload\")\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return deny(\"fast dispatch denied: hook payload must be an object\")\n }\n\n const payload = parsed as DispatchPayload\n if (typeof payload.tool_name !== \"string\") {\n return deny(\"fast dispatch denied: hook payload has no tool_name\")\n }\n const toolName = payload.tool_name\n if (!/^(Task|Agent)$/.test(toolName)) {\n return { allowed: true, verdict: \"allow-non-dispatch\" }\n }\n\n if (!payload.tool_input || typeof payload.tool_input !== \"object\" || Array.isArray(payload.tool_input)) {\n return deny(`fast dispatch denied: ${toolName} payload has malformed tool_input`)\n }\n const targetResult = resolveAliasedString(\n payload.tool_input as Record<string, unknown>,\n [\"subagent_type\", \"subagentType\"],\n )\n if (targetResult.malformed) {\n return deny(`fast dispatch denied: ${toolName} target identity is malformed`)\n }\n if (targetResult.conflict) {\n return deny(`fast dispatch denied: ${toolName} target aliases conflict`)\n }\n const targetValue = targetResult.value\n if (!targetValue || !FAST_NATIVE_AGENT_SET.has(targetValue)) {\n return deny(\n `fast dispatch denied: ${toolName} target must be one of ${FAST_NATIVE_AGENT_NAMES.join(\", \")}`,\n )\n }\n const target = targetValue as FastNativeAgentName\n const toolInput = payload.tool_input as Record<string, unknown>\n // Invocation-level `model` outranks custom-agent frontmatter in Claude Code.\n // The fast profile promises fixed role models, so allowed dispatches must\n // remove that one caller-owned field while preserving every other input.\n const updatedInput = { ...toolInput }\n delete updatedInput.model\n\n const callerType = resolveAliasedString(payload as Record<string, unknown>, [\"agent_type\", \"agentType\"])\n const callerId = resolveAliasedString(payload as Record<string, unknown>, [\"agent_id\", \"agentId\"])\n const parentMarker = resolveAliasedString(payload as Record<string, unknown>, [\n \"parent_tool_use_id\",\n \"parentToolUseId\",\n ])\n if (callerType.malformed || callerId.malformed || parentMarker.malformed) {\n return deny(`fast dispatch denied: ${toolName} caller identity is malformed`, target)\n }\n if (callerType.conflict || callerId.conflict || parentMarker.conflict) {\n return deny(`fast dispatch denied: ${toolName} caller identity aliases conflict`, target)\n }\n\n const callerTypeValue = callerType.value\n const callerIdValue = callerId.value\n const parentValue = parentMarker.value\n\n // A non-null agent id or parent marker cannot impersonate a role by itself.\n // A valid role may be accompanied by either marker as supplemental evidence.\n if (!callerTypeValue && callerIdValue) {\n return deny(`fast dispatch denied: ${toolName} has agent_id without agent_type`, target)\n }\n if (!callerTypeValue && parentValue) {\n return deny(`fast dispatch denied: ${toolName} has only a parent execution marker`, target)\n }\n\n // Absent or null identity fields are the only lead representation. Empty\n // strings and non-string values were rejected above; unknown roles fail closed.\n if (!callerTypeValue) {\n const hasPresentMarker = callerType.present || callerId.present || parentMarker.present\n const hasUnresolvedNonNullMarker = [callerType, callerId, parentMarker].some(\n (marker) => marker.value !== undefined,\n )\n if (hasPresentMarker && hasUnresolvedNonNullMarker) {\n return deny(`fast dispatch denied: ${toolName} has no resolvable caller role`, target)\n }\n return {\n allowed: true,\n caller: \"lead\",\n target,\n updatedInput,\n verdict: \"allow\",\n }\n }\n if (!FAST_NATIVE_AGENT_SET.has(callerTypeValue)) {\n return deny(`fast dispatch denied: unknown caller role ${JSON.stringify(callerTypeValue)}`, target)\n }\n const caller = callerTypeValue as FastNativeAgentName\n const allowedTargets = FAST_DISPATCH_GRAPH[caller]\n if (!allowedTargets.has(target)) {\n return deny(`fast dispatch denied: ${caller} cannot invoke ${target}`, target, caller)\n }\n return { allowed: true, caller, target, updatedInput, verdict: \"allow\" }\n}\n\n/** JSON response consumed by Claude Code for an allowed, model-pinned dispatch. */\nexport function fastDispatchAllowOutput(\n updatedInput: Record<string, unknown>,\n): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"allow\",\n updatedInput,\n },\n })\n}\n\n/** JSON response consumed by Claude Code's PreToolUse hook protocol. */\nexport function fastDispatchDenyOutput(reason: string): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: reason,\n },\n })\n}\n","/**\n * Internal PreToolUse guard for the `-m fast` native Task/Agent ACL.\n *\n * The policy is intentionally pure and compiled into this hook. This entrypoint\n * only performs synchronous stdin I/O, emits Claude Code's deny envelope, and\n * exits naturally so Windows libuv teardown is not raced by process.exit().\n */\n\nimport { defineCommand } from \"citty\"\nimport { readFileSync } from \"node:fs\"\n\nimport {\n decideFastDispatchGuard,\n fastDispatchAllowOutput,\n fastDispatchDenyOutput,\n} from \"./lib/fast-dispatch-acl\"\nimport { buildSelfCommand, type SelfInvocation } from \"./lib/hook-launcher/self-invocation\"\n\nfunction readStdinSync(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nexport const internalFastDispatchGuard = defineCommand({\n meta: {\n name: \"internal-fast-dispatch-guard\",\n description:\n \"Internal: PreToolUse guard enforcing the fast-profile native Task/Agent ACL.\",\n },\n run() {\n const decision = decideFastDispatchGuard(readStdinSync())\n if (!decision.allowed && decision.reason) {\n process.stdout.write(fastDispatchDenyOutput(decision.reason))\n } else if (decision.verdict === \"allow\" && decision.updatedInput) {\n process.stdout.write(fastDispatchAllowOutput(decision.updatedInput))\n }\n // Natural exit is required on Windows. Claude Code consumes the JSON\n // permission decision; an exit code is not used to deny this hook.\n process.exitCode = 0\n },\n})\n\n/** Build the persisted command for the fast-profile PreToolUse hook. */\nexport function buildFastDispatchGuardHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-fast-dispatch-guard\")\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAa,0BAA0B;AAIvC,MAAM,wBAAwB,IAAI,IAAY,uBAAuB;;AAGrE,MAAa,sBAET,OAAO,OAAO;CAChB,SAAS,IAAI,IAAyB,8BAA8B,OAAO;CAC3E,aAAa,IAAI,IACf,8BAA8B,WAChC;CACA,UAAU,IAAI,IAAyB,8BAA8B,QAAQ;CAC7E,SAAS,IAAI,IAAyB,8BAA8B,OAAO;CAC3E,QAAQ,IAAI,IAAyB,8BAA8B,MAAM;AAC3E,CAAC;;AAGD,MAAa,6BAA6B;AAuB1C,SAAS,OAAO,KAAa,KAAsB;CACjD,OAAO,OAAO,UAAU,e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S,YAAY,CAAC;EAIrE,QAAQ,WAAW;CACrB;AACF,CAAC;;AAGD,SAAgB,kCAAkC,YAAoC;CACpF,OAAO,iBAAiB,YAAY,8BAA8B;AACpE"}
|
package/dist/{internal-first-mate-guard-C9BV7J4U.js → internal-first-mate-guard-Bcb5JwiO.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as buildSelfCommand } from "./self-invocation-
|
|
2
|
-
import { a as dispatcherAgentName, t as ALL_WORKER_DISPATCH_MODES } from "./worker-dispatch-
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-BJWbA8ka.js";
|
|
2
|
+
import { a as dispatcherAgentName, t as ALL_WORKER_DISPATCH_MODES } from "./worker-dispatch-DgP5yT26.js";
|
|
3
3
|
import { defineCommand } from "citty";
|
|
4
4
|
import { readFileSync } from "node:fs";
|
|
5
5
|
//#region src/lib/first-mate/operator-shaping.ts
|
|
@@ -124,4 +124,4 @@ function buildFirstMateGuardHookCommand(invocation) {
|
|
|
124
124
|
//#endregion
|
|
125
125
|
export { assertShapingInstalled as i, buildFirstMateGuardHookCommand as n, internalFirstMateGuard as r, FIRST_MATE_GUARD_MATCHER as t };
|
|
126
126
|
|
|
127
|
-
//# sourceMappingURL=internal-first-mate-guard-
|
|
127
|
+
//# sourceMappingURL=internal-first-mate-guard-Bcb5JwiO.js.map
|
package/dist/{internal-first-mate-guard-C9BV7J4U.js.map → internal-first-mate-guard-Bcb5JwiO.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-first-mate-guard-
|
|
1
|
+
{"version":3,"file":"internal-first-mate-guard-Bcb5JwiO.js","names":[],"sources":["../src/lib/first-mate/operator-shaping.ts","../src/internal-first-mate-guard.ts"],"sourcesContent":["/**\n * Operator-mode steering for github-router `--agents` sessions.\n *\n * In first-mate/operator mode the spawned Claude is the cloud-agent operator, not\n * the product implementer. Product implementation is steered to GitHub cloud\n * agents by first-mate guidance and the gh-first-mate skill. This module no\n * longer hard-blocks local file writes or shell commands: Edit/Write/NotebookEdit\n * and Bash remain available as escape hatches when needed.\n *\n * The only enforced main-operator boundary is that local worker/orchestrate MCP\n * tools stay subagent-only. The main operator should invoke the worker-* Agent\n * subagents or delegate to GitHub cloud agents rather than calling\n * `mcp__workers__*` / `mcp__orchestrate__*` directly.\n */\n\nimport {\n ALL_WORKER_DISPATCH_MODES,\n dispatcherAgentName,\n type WorkerDispatchMode,\n} from \"../worker-dispatch\"\n\n/** Tools denied to the main operator by exact name. */\nexport const OPERATOR_DENIED_TOOLS = [] as const\n\n/** MCP prefixes denied to the main operator; these remain subagent-only. */\nexport const OPERATOR_DENIED_MCP_PREFIXES = [\"mcp__workers__\", \"mcp__orchestrate__\"] as const\n\n/** Tools explicitly preserved (documented; used by assertion tests). */\nexport const OPERATOR_KEPT_TOOLS = [\n \"Agent\",\n \"Task\",\n \"Edit\",\n \"Write\",\n \"NotebookEdit\",\n \"Bash\",\n \"Read\",\n \"Grep\",\n \"Glob\",\n \"mcp__first-mate__\",\n] as const\n\n/**\n * Least-privilege note for what the cloud agents themselves may touch — the\n * operator scopes missions to specific repos and forbids irreversible actions\n * without human approval (see first-mate house rules). This constant documents\n * the intent for the launcher/README; enforcement of the cloud-agent scope is\n * the GitHub agent-token scope (repo/workflow) + the mission house_rules.\n */\nexport const CLOUD_AGENT_SCOPE_NOTE =\n \"Cloud agents operate only within mission-listed repos; merges, releases, \" +\n \"Pages, and deletes require explicit human approval (first-mate merge gate).\"\n\nexport interface OperatorToolInput extends Record<string, unknown> {\n agent_type?: unknown\n}\n\nexport interface PreToolUseDecision {\n block: boolean\n reason?: string\n}\n\n/**\n * Decide whether a tool call must be blocked for the main operator. Pure — used\n * both by the PreToolUse hook handler and by config-assertion tests. When\n * operator mode is off, nothing is blocked (normal sessions unaffected).\n */\nfunction parseWorkerMode(toolName: string): WorkerDispatchMode | null {\n const workersPrefix = \"mcp__workers__\"\n if (!toolName.startsWith(workersPrefix)) return null\n const mode = toolName.slice(workersPrefix.length)\n return (ALL_WORKER_DISPATCH_MODES as ReadonlyArray<string>).includes(mode) ? (mode as WorkerDispatchMode) : null\n}\n\nfunction isMatchingWorkerDispatcher(toolName: string, input?: OperatorToolInput): boolean {\n const mode = parseWorkerMode(toolName)\n if (mode === null) return false\n return input?.agent_type === dispatcherAgentName(mode)\n}\n\nexport function shouldDenyOperatorTool(\n toolName: string,\n operatorMode: boolean,\n input?: OperatorToolInput,\n): boolean {\n if (!operatorMode) return false\n if (isMatchingWorkerDispatcher(toolName, input)) return false\n return OPERATOR_DENIED_MCP_PREFIXES.some((prefix) => toolName.startsWith(prefix))\n}\n\n/**\n * M4 — fail-CLOSED. If operator/`--agents` mode is active but the reduced\n * worker/orchestrate guard could NOT be installed (e.g. settings.json unwritable),\n * the operator session must NOT start with direct main-thread worker/orchestrate\n * MCP calls available. Non-agents sessions are never affected.\n */\nexport function assertShapingInstalled(agentsMode: boolean, injectionSucceeded: boolean): void {\n if (agentsMode && !injectionSucceeded) {\n throw new Error(\n \"cloud-agent operator mode requires the worker/orchestrate PreToolUse hook, \" +\n \"but it could not be installed — refusing to start an unguarded operator session.\",\n )\n }\n}\n\n/**\n * The PreToolUse hook decision for a given tool name in operator mode.\n *\n * Bash and file-authoring tools are always allowed. Only direct main-operator\n * calls to local worker/orchestrate MCP tools are blocked so those backends stay\n * reachable through the worker-* Agent subagents rather than the lead context.\n */\nexport function operatorPreToolUse(\n toolName: string,\n operatorMode: boolean,\n input?: OperatorToolInput,\n): PreToolUseDecision {\n if (!operatorMode) return { block: false }\n if (shouldDenyOperatorTool(toolName, operatorMode, input)) {\n return {\n block: true,\n reason: `${toolName} is subagent-only in cloud-agent operator mode — use the worker-* Agent subagents or delegate implementation to a GitHub cloud agent via the first-mate MCP instead of calling local worker/orchestrate MCP tools from the main operator.`,\n }\n }\n return { block: false }\n}\n","/**\n * The internal `internal-first-mate-guard` subcommand: a PreToolUse hook that\n * keeps local worker/orchestrate MCP tools subagent-only in cloud-agent OPERATOR\n * mode. It is injected into the spawned Claude session's settings ONLY in\n * `--agents`/operator mode, with a matcher scoped to those MCP tool prefixes.\n *\n * Reads the PreToolUse payload from stdin (`{tool_name, tool_input, ...}`) and,\n * if the tool is denied in operator mode, blocks via exit code 2 with a reason\n * on stderr (the repo's hook convention). Bash and file-authoring tools are not\n * matched by this guard and are not blocked.\n */\nimport { defineCommand } from \"citty\"\n\nimport { readFileSync } from \"node:fs\"\n\nimport { operatorPreToolUse, type OperatorToolInput } from \"./lib/first-mate/operator-shaping\"\nimport { buildSelfCommand, type SelfInvocation } from \"./lib/hook-launcher/self-invocation\"\n\nfunction readStdinSync(): string {\n try {\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nexport const internalFirstMateGuard = defineCommand({\n meta: {\n name: \"internal-first-mate-guard\",\n description: \"PreToolUse guard enforcing cloud-agent operator capability shaping.\",\n },\n run() {\n let toolName = \"\"\n let hookInput: OperatorToolInput | undefined\n let parsed: boolean\n try {\n const payload = JSON.parse(readStdinSync()) as {\n tool_name?: unknown\n tool_input?: unknown\n agent_type?: unknown\n }\n if (typeof payload.tool_name === \"string\") toolName = payload.tool_name\n if (typeof payload.agent_type === \"string\") hookInput = { agent_type: payload.agent_type }\n parsed = true\n } catch {\n parsed = false // fail-closed below for a named-but-unparseable payload\n }\n if (toolName.length === 0) {\n // Nothing to guard (empty/absent tool name) → allow. But if the payload\n // did not even parse we cannot know it was empty; the matcher only routes\n // the denied tools here, so a parse failure means one of THOSE arrived\n // unreadable → fail-closed.\n if (!parsed) {\n process.stderr.write(\"operator guard: unparseable PreToolUse payload — blocking (fail-closed)\")\n process.exit(2)\n }\n process.exit(0)\n }\n // This hook is only injected in operator mode, so operatorMode = true.\n const decision = operatorPreToolUse(toolName, true, hookInput)\n if (decision.block) {\n process.stderr.write(decision.reason ?? `${toolName} is disabled in operator mode`)\n process.exit(2) // exit 2 blocks the tool call (Claude Code hook convention)\n }\n process.exit(0)\n },\n})\n\n/** The regex matcher scoping the guard hook to exactly the denied tools. */\nexport const FIRST_MATE_GUARD_MATCHER = \"mcp__workers__.*|mcp__orchestrate__.*\"\n\n/** Build the hook command string that runs this subcommand. */\nexport function buildFirstMateGuardHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-first-mate-guard\")\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAyBA,MAAa,+BAA+B,CAAC,kBAAkB,oBAAoB;;;;;;AAyCnF,SAAS,gBAAgB,UAA6C;CAEpE,IAAI,CAAC,SAAS,WAAW,gBAAa,GAAG,OAAO;CAChD,MAAM,OAAO,SAAS,MAAM,EAAoB;CAChD,OAAQ,0BAAoD,SAAS,IAAI,IAAK,OAA8B;AAC9G;AAEA,SAAS,2BAA2B,UAAkB,OAAoC;CACxF,MAAM,OAAO,gBAAgB,QAAQ;CACrC,IAAI,SAAS,MAAM,OAAO;CAC1B,OAAO,OAAO,eAAe,oBAAoB,IAAI;AACvD;AAEA,SAAgB,uBACd,UACA,cACA,OACS;CACT,IAAI,CAAC,cAAc,OAAO;CAC1B,IAAI,2BAA2B,UAAU,KAAK,GAAG,OAAO;CACxD,OAAO,6BAA6B,MAAM,WAAW,SAAS,WAAW,MAAM,CAAC;AAClF;;;;;;;AAQA,SAAgB,uBAAuB,YAAqB,oBAAmC;CAC7F,IAAI,cAAc,CAAC,oBACjB,MAAM,IAAI,MACR,6JAEF;AAEJ;;;;;;;;AASA,SAAgB,mBACd,UACA,cACA,OACoB;CACpB,IAAI,CAAC,cAAc,OAAO,EAAE,OAAO,MAAM;CACzC,IAAI,uBAAuB,UAAU,cAAc,KAAK,GACtD,OAAO;EACL,OAAO;EACP,QAAQ,GAAG,SAAS;CACtB;CAEF,OAAO,EAAE,OAAO,MAAM;AACxB;;;;;;;;;;;;;;AC1GA,SAAS,gBAAwB;CAC/B,IAAI;EACF,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAa,yBAAyB,cAAc;CAClD,MAAM;EACJ,MAAM;EACN,aAAa;CACf;CACA,MAAM;EACJ,IAAI,WAAW;EACf,IAAI;EACJ,IAAI;EACJ,IAAI;GACF,MAAM,UAAU,KAAK,MAAM,cAAc,CAAC;GAK1C,IAAI,OAAO,QAAQ,cAAc,UAAU,WAAW,QAAQ;GAC9D,IAAI,OAAO,QAAQ,eAAe,UAAU,YAAY,EAAE,YAAY,QAAQ,WAAW;GACzF,SAAS;EACX,QAAQ;GACN,SAAS;EACX;EACA,IAAI,SAAS,WAAW,GAAG;GAKzB,IAAI,CAAC,QAAQ;IACX,QAAQ,OAAO,MAAM,yEAAyE;IAC9F,QAAQ,KAAK,CAAC;GAChB;GACA,QAAQ,KAAK,CAAC;EAChB;EAEA,MAAM,WAAW,mBAAmB,UAAU,MAAM,SAAS;EAC7D,IAAI,SAAS,OAAO;GAClB,QAAQ,OAAO,MAAM,SAAS,UAAU,GAAG,SAAS,8BAA8B;GAClF,QAAQ,KAAK,CAAC;EAChB;EACA,QAAQ,KAAK,CAAC;CAChB;AACF,CAAC;;AAGD,MAAa,2BAA2B;;AAGxC,SAAgB,+BAA+B,YAAoC;CACjF,OAAO,iBAAiB,YAAY,2BAA2B;AACjE"}
|
package/dist/{internal-first-mate-guard-WJApyc8j.js → internal-first-mate-guard-Brh_uois.js}
RENAMED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { r as internalFirstMateGuard } from "./internal-first-mate-guard-
|
|
1
|
+
import { r as internalFirstMateGuard } from "./internal-first-mate-guard-Bcb5JwiO.js";
|
|
2
2
|
export { internalFirstMateGuard };
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-BJWbA8ka.js";
|
|
2
|
+
import { a as MAX_PROFILE_NATIVE_AGENT_NAMES, s as MAX_PROFILE_NATIVE_MODELS } from "./max-profile-contract-BTXowh6k.js";
|
|
3
|
+
import { defineCommand } from "citty";
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
//#region src/lib/max-dispatch-acl.ts
|
|
6
|
+
const MAX_DISPATCH_TOOL_MATCHER = "^(Task|Agent)$";
|
|
7
|
+
const MAX_BROWSE_DISPATCH_AGENT = "worker-browse";
|
|
8
|
+
const MAX_NATIVE_AGENT_SET = /* @__PURE__ */ new Set([...MAX_PROFILE_NATIVE_AGENT_NAMES, MAX_BROWSE_DISPATCH_AGENT]);
|
|
9
|
+
/** Assert max launches never start without their native Task/Agent ACL. */
|
|
10
|
+
var MaxDispatchGuardInstallError = class extends Error {
|
|
11
|
+
constructor(message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "MaxDispatchGuardInstallError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
function assertMaxDispatchGuardInstalled(maxProfile, installationSucceeded) {
|
|
17
|
+
if (maxProfile && !installationSucceeded) throw new MaxDispatchGuardInstallError("max profile requires the native Task/Agent ACL hook, but it could not be installed; refusing to start an unguarded max session.");
|
|
18
|
+
}
|
|
19
|
+
const MAX_ALLOWED_MODEL_BASES = /* @__PURE__ */ new Set([
|
|
20
|
+
"gpt-5.6-luna",
|
|
21
|
+
"gemini-3.7-flash",
|
|
22
|
+
"grok-4.6"
|
|
23
|
+
]);
|
|
24
|
+
/**
|
|
25
|
+
* Claude Code's public Agent schema currently requires one of these built-in
|
|
26
|
+
* model aliases even when the selected custom agent already owns its model in
|
|
27
|
+
* frontmatter. They are transport placeholders in max, not model overrides.
|
|
28
|
+
* Strip them so the role's catalog-validated max model remains authoritative.
|
|
29
|
+
* Case and a trailing `[1m]` are ignored deliberately: neither can turn a
|
|
30
|
+
* client-owned placeholder into an Opus override in the closed max roster.
|
|
31
|
+
*/
|
|
32
|
+
const MAX_AGENT_SCHEMA_MODEL_ALIASES = Object.freeze([
|
|
33
|
+
"sonnet",
|
|
34
|
+
"opus",
|
|
35
|
+
"haiku",
|
|
36
|
+
"fable"
|
|
37
|
+
]);
|
|
38
|
+
const MAX_AGENT_SCHEMA_MODEL_ALIAS_SET = new Set(MAX_AGENT_SCHEMA_MODEL_ALIASES);
|
|
39
|
+
function isMaxAgentSchemaModelAlias(model) {
|
|
40
|
+
if (typeof model !== "string") return false;
|
|
41
|
+
return MAX_AGENT_SCHEMA_MODEL_ALIAS_SET.has(baseModel(model.trim()).toLowerCase());
|
|
42
|
+
}
|
|
43
|
+
function stringField(input, ...keys) {
|
|
44
|
+
const values = keys.filter((key) => Object.prototype.hasOwnProperty.call(input, key)).map((key) => input[key]).filter((value) => value !== void 0 && value !== null);
|
|
45
|
+
if (values.length === 0) return void 0;
|
|
46
|
+
if (values.some((value) => typeof value !== "string" || value.trim().length === 0)) return void 0;
|
|
47
|
+
const distinct = [...new Set(values.map((value) => value.trim()))];
|
|
48
|
+
return distinct.length === 1 ? distinct[0] : void 0;
|
|
49
|
+
}
|
|
50
|
+
function baseModel(model) {
|
|
51
|
+
return model.replace(/(?:\[1m\])+$/i, "");
|
|
52
|
+
}
|
|
53
|
+
function normalizeMaxDispatchModel(model) {
|
|
54
|
+
if (typeof model !== "string" || model.trim().length === 0) return void 0;
|
|
55
|
+
const base = baseModel(model.trim());
|
|
56
|
+
return MAX_ALLOWED_MODEL_BASES.has(base) ? base === "grok-4.6" ? base : `${base}[1m]` : void 0;
|
|
57
|
+
}
|
|
58
|
+
function normalizeMaxDispatchEffort(model, effort) {
|
|
59
|
+
if (effort === void 0 || effort === null) return void 0;
|
|
60
|
+
if (typeof effort !== "string") return void 0;
|
|
61
|
+
if ((model === "gpt-5.6-sol" ? [
|
|
62
|
+
"high",
|
|
63
|
+
"xhigh",
|
|
64
|
+
"max"
|
|
65
|
+
] : model === "gpt-5.6-luna" ? [
|
|
66
|
+
"none",
|
|
67
|
+
"low",
|
|
68
|
+
"medium",
|
|
69
|
+
"high",
|
|
70
|
+
"xhigh",
|
|
71
|
+
"max"
|
|
72
|
+
] : model === "grok-4.6" || model === "gemini-3.7-flash" ? [
|
|
73
|
+
"low",
|
|
74
|
+
"medium",
|
|
75
|
+
"high"
|
|
76
|
+
] : []).includes(effort)) return effort;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Native max Task/Agent ACL. Role frontmatter owns the fixed model. Required
|
|
80
|
+
* public-schema aliases are stripped as transport placeholders; a client that
|
|
81
|
+
* can express custom ids may override only to Luna, Gemini, or Grok with a
|
|
82
|
+
* live-ladder effort. Sol/Codex/unknown/private ids are rejected. The lead may
|
|
83
|
+
* target any emitted max role; role-to-role edges are unrestricted here.
|
|
84
|
+
*/
|
|
85
|
+
function decideMaxDispatchGuard(stdin) {
|
|
86
|
+
let parsed;
|
|
87
|
+
try {
|
|
88
|
+
parsed = typeof stdin === "string" ? JSON.parse(stdin) : stdin;
|
|
89
|
+
} catch {
|
|
90
|
+
return {
|
|
91
|
+
allowed: false,
|
|
92
|
+
reason: "max dispatch denied: malformed hook payload",
|
|
93
|
+
verdict: "deny"
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {
|
|
97
|
+
allowed: false,
|
|
98
|
+
reason: "max dispatch denied: hook payload must be an object",
|
|
99
|
+
verdict: "deny"
|
|
100
|
+
};
|
|
101
|
+
const payload = parsed;
|
|
102
|
+
if (typeof payload.tool_name !== "string") return {
|
|
103
|
+
allowed: false,
|
|
104
|
+
reason: "max dispatch denied: hook payload has no tool_name",
|
|
105
|
+
verdict: "deny"
|
|
106
|
+
};
|
|
107
|
+
if (!/^(Task|Agent)$/.test(payload.tool_name)) return {
|
|
108
|
+
allowed: true,
|
|
109
|
+
verdict: "allow-non-dispatch"
|
|
110
|
+
};
|
|
111
|
+
if (!payload.tool_input || typeof payload.tool_input !== "object" || Array.isArray(payload.tool_input)) return {
|
|
112
|
+
allowed: false,
|
|
113
|
+
reason: `max dispatch denied: ${payload.tool_name} payload has malformed tool_input`,
|
|
114
|
+
verdict: "deny"
|
|
115
|
+
};
|
|
116
|
+
const toolInput = payload.tool_input;
|
|
117
|
+
const target = stringField(toolInput, "subagent_type", "subagentType");
|
|
118
|
+
if (!target || !MAX_NATIVE_AGENT_SET.has(target)) return {
|
|
119
|
+
allowed: false,
|
|
120
|
+
reason: `max dispatch denied: target must be one of ${[...MAX_PROFILE_NATIVE_AGENT_NAMES, MAX_BROWSE_DISPATCH_AGENT].join(", ")}`,
|
|
121
|
+
verdict: "deny"
|
|
122
|
+
};
|
|
123
|
+
const nativeTarget = target;
|
|
124
|
+
const modelValue = toolInput.model;
|
|
125
|
+
const schemaAlias = isMaxAgentSchemaModelAlias(modelValue);
|
|
126
|
+
const normalizedModel = modelValue === void 0 || schemaAlias ? void 0 : normalizeMaxDispatchModel(modelValue);
|
|
127
|
+
if (modelValue !== void 0 && !schemaAlias && !normalizedModel) return {
|
|
128
|
+
allowed: false,
|
|
129
|
+
reason: "max dispatch denied: model must be a Claude Code Agent schema alias, Luna[1m], Gemini 3.7 Flash[1m], or bare Grok 4.6",
|
|
130
|
+
target,
|
|
131
|
+
verdict: "deny"
|
|
132
|
+
};
|
|
133
|
+
const requestedEffort = toolInput.thinking ?? toolInput.effort;
|
|
134
|
+
const effort = normalizeMaxDispatchEffort(normalizedModel ? baseModel(normalizedModel) : nativeTarget === "worker-browse" ? "gpt-5.6-luna" : MAX_PROFILE_NATIVE_MODELS[nativeTarget], requestedEffort);
|
|
135
|
+
if ((toolInput.thinking !== void 0 || toolInput.effort !== void 0) && !effort) return {
|
|
136
|
+
allowed: false,
|
|
137
|
+
reason: "max dispatch denied: reasoning override is not supported by the selected model",
|
|
138
|
+
target,
|
|
139
|
+
verdict: "deny"
|
|
140
|
+
};
|
|
141
|
+
const updatedInput = { ...toolInput };
|
|
142
|
+
if (normalizedModel) updatedInput.model = normalizedModel;
|
|
143
|
+
else delete updatedInput.model;
|
|
144
|
+
if (effort) if (toolInput.thinking !== void 0) updatedInput.thinking = effort;
|
|
145
|
+
else updatedInput.effort = effort;
|
|
146
|
+
if (toolInput.thinking !== void 0 && toolInput.effort !== void 0) delete updatedInput.effort;
|
|
147
|
+
if (toolInput.model === void 0 && normalizedModel === void 0) delete updatedInput.model;
|
|
148
|
+
return {
|
|
149
|
+
allowed: true,
|
|
150
|
+
target,
|
|
151
|
+
effort,
|
|
152
|
+
updatedInput,
|
|
153
|
+
verdict: "allow"
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
function maxDispatchAllowOutput(updatedInput) {
|
|
157
|
+
return JSON.stringify({ hookSpecificOutput: {
|
|
158
|
+
hookEventName: "PreToolUse",
|
|
159
|
+
permissionDecision: "allow",
|
|
160
|
+
updatedInput
|
|
161
|
+
} });
|
|
162
|
+
}
|
|
163
|
+
function maxDispatchDenyOutput(reason) {
|
|
164
|
+
return JSON.stringify({ hookSpecificOutput: {
|
|
165
|
+
hookEventName: "PreToolUse",
|
|
166
|
+
permissionDecision: "deny",
|
|
167
|
+
permissionDecisionReason: reason
|
|
168
|
+
} });
|
|
169
|
+
}
|
|
170
|
+
//#endregion
|
|
171
|
+
//#region src/internal-max-dispatch-guard.ts
|
|
172
|
+
function readStdinSync() {
|
|
173
|
+
try {
|
|
174
|
+
if (process.stdin.isTTY) return "";
|
|
175
|
+
return readFileSync(0, "utf8");
|
|
176
|
+
} catch {
|
|
177
|
+
return "";
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const internalMaxDispatchGuard = defineCommand({
|
|
181
|
+
meta: {
|
|
182
|
+
name: "internal-max-dispatch-guard",
|
|
183
|
+
description: "Internal: PreToolUse guard enforcing the max-profile native Task/Agent policy."
|
|
184
|
+
},
|
|
185
|
+
run() {
|
|
186
|
+
const decision = decideMaxDispatchGuard(readStdinSync());
|
|
187
|
+
if (!decision.allowed && decision.reason) process.stdout.write(maxDispatchDenyOutput(decision.reason));
|
|
188
|
+
else if (decision.verdict === "allow" && decision.updatedInput) process.stdout.write(maxDispatchAllowOutput(decision.updatedInput));
|
|
189
|
+
process.exitCode = 0;
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
function buildMaxDispatchGuardHookCommand(invocation) {
|
|
193
|
+
return buildSelfCommand(invocation, "internal-max-dispatch-guard");
|
|
194
|
+
}
|
|
195
|
+
//#endregion
|
|
196
|
+
export { assertMaxDispatchGuardInstalled as i, internalMaxDispatchGuard as n, MAX_DISPATCH_TOOL_MATCHER as r, buildMaxDispatchGuardHookCommand as t };
|
|
197
|
+
|
|
198
|
+
//# sourceMappingURL=internal-max-dispatch-guard-BjSVXMvC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-max-dispatch-guard-BjSVXMvC.js","names":[],"sources":["../src/lib/max-dispatch-acl.ts","../src/internal-max-dispatch-guard.ts"],"sourcesContent":["import {\n MAX_PROFILE_NATIVE_AGENT_NAMES,\n MAX_PROFILE_NATIVE_MODELS,\n type MaxProfileNativeAgentName,\n} from \"./max-profile-contract\"\nimport type { Effort } from \"./reasoning-effort\"\n\nexport const MAX_DISPATCH_TOOL_MATCHER = \"^(Task|Agent)$\"\n\nexport const MAX_BROWSE_DISPATCH_AGENT = \"worker-browse\" as const\n\nconst MAX_NATIVE_AGENT_SET = new Set<string>([\n ...MAX_PROFILE_NATIVE_AGENT_NAMES,\n MAX_BROWSE_DISPATCH_AGENT,\n])\n\n/** Assert max launches never start without their native Task/Agent ACL. */\nexport class MaxDispatchGuardInstallError extends Error {\n constructor(message: string) {\n super(message)\n this.name = \"MaxDispatchGuardInstallError\"\n }\n}\n\nexport function assertMaxDispatchGuardInstalled(\n maxProfile: boolean,\n installationSucceeded: boolean,\n): void {\n if (maxProfile && !installationSucceeded) {\n throw new MaxDispatchGuardInstallError(\n \"max profile requires the native Task/Agent ACL hook, but it could not be installed; refusing to start an unguarded max session.\",\n )\n }\n}\n\nconst MAX_ALLOWED_MODEL_BASES = new Set([\"gpt-5.6-luna\", \"gemini-3.7-flash\", \"grok-4.6\"])\n\n/**\n * Claude Code's public Agent schema currently requires one of these built-in\n * model aliases even when the selected custom agent already owns its model in\n * frontmatter. They are transport placeholders in max, not model overrides.\n * Strip them so the role's catalog-validated max model remains authoritative.\n * Case and a trailing `[1m]` are ignored deliberately: neither can turn a\n * client-owned placeholder into an Opus override in the closed max roster.\n */\nexport const MAX_AGENT_SCHEMA_MODEL_ALIASES = Object.freeze([\n \"sonnet\",\n \"opus\",\n \"haiku\",\n \"fable\",\n] as const)\n\nconst MAX_AGENT_SCHEMA_MODEL_ALIAS_SET = new Set<string>(\n MAX_AGENT_SCHEMA_MODEL_ALIASES,\n)\n\nfunction isMaxAgentSchemaModelAlias(model: unknown): boolean {\n if (typeof model !== \"string\") return false\n return MAX_AGENT_SCHEMA_MODEL_ALIAS_SET.has(baseModel(model.trim()).toLowerCase())\n}\n\nexport interface MaxDispatchDecision {\n allowed: boolean\n reason?: string\n updatedInput?: Record<string, unknown>\n target?: string\n effort?: Effort\n verdict: \"allow\" | \"deny\" | \"allow-non-dispatch\"\n}\n\nfunction stringField(input: Record<string, unknown>, ...keys: string[]): string | undefined {\n const values = keys\n .filter((key) => Object.prototype.hasOwnProperty.call(input, key))\n .map((key) => input[key])\n .filter((value) => value !== undefined && value !== null)\n if (values.length === 0) return undefined\n if (values.some((value) => typeof value !== \"string\" || value.trim().length === 0)) return undefined\n const distinct = [...new Set((values as string[]).map((value) => value.trim()))]\n return distinct.length === 1 ? distinct[0] : undefined\n}\n\nfunction baseModel(model: string): string {\n return model.replace(/(?:\\[1m\\])+$/i, \"\")\n}\n\nexport function normalizeMaxDispatchModel(model: unknown): string | undefined {\n if (typeof model !== \"string\" || model.trim().length === 0) return undefined\n const trimmed = model.trim()\n const base = baseModel(trimmed)\n return MAX_ALLOWED_MODEL_BASES.has(base)\n ? base === \"grok-4.6\" ? base : `${base}[1m]`\n : undefined\n}\n\nexport function normalizeMaxDispatchEffort(\n model: string,\n effort: unknown,\n): Effort | undefined {\n if (effort === undefined || effort === null) return undefined\n if (typeof effort !== \"string\") return undefined\n const allowed: ReadonlyArray<Effort> = model === \"gpt-5.6-sol\"\n ? [\"high\", \"xhigh\", \"max\"]\n : model === \"gpt-5.6-luna\"\n ? [\"none\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"]\n : model === \"grok-4.6\" || model === \"gemini-3.7-flash\"\n // The optional reviewer/brainstorm fallback swaps these two models;\n // their max-profile effort intersection is deliberately identical.\n ? [\"low\", \"medium\", \"high\"]\n : []\n if (allowed.includes(effort as Effort)) return effort as Effort\n return undefined\n}\n\n/**\n * Native max Task/Agent ACL. Role frontmatter owns the fixed model. Required\n * public-schema aliases are stripped as transport placeholders; a client that\n * can express custom ids may override only to Luna, Gemini, or Grok with a\n * live-ladder effort. Sol/Codex/unknown/private ids are rejected. The lead may\n * target any emitted max role; role-to-role edges are unrestricted here.\n */\nexport function decideMaxDispatchGuard(stdin: string | unknown): MaxDispatchDecision {\n let parsed: unknown\n try {\n parsed = typeof stdin === \"string\" ? JSON.parse(stdin) : stdin\n } catch {\n return { allowed: false, reason: \"max dispatch denied: malformed hook payload\", verdict: \"deny\" }\n }\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { allowed: false, reason: \"max dispatch denied: hook payload must be an object\", verdict: \"deny\" }\n }\n const payload = parsed as Record<string, unknown>\n if (typeof payload.tool_name !== \"string\") {\n return { allowed: false, reason: \"max dispatch denied: hook payload has no tool_name\", verdict: \"deny\" }\n }\n if (!/^(Task|Agent)$/.test(payload.tool_name)) {\n return { allowed: true, verdict: \"allow-non-dispatch\" }\n }\n if (!payload.tool_input || typeof payload.tool_input !== \"object\" || Array.isArray(payload.tool_input)) {\n return { allowed: false, reason: `max dispatch denied: ${payload.tool_name} payload has malformed tool_input`, verdict: \"deny\" }\n }\n const toolInput = payload.tool_input as Record<string, unknown>\n const target = stringField(toolInput, \"subagent_type\", \"subagentType\")\n if (!target || !MAX_NATIVE_AGENT_SET.has(target)) {\n return { allowed: false, reason: `max dispatch denied: target must be one of ${[...MAX_PROFILE_NATIVE_AGENT_NAMES, MAX_BROWSE_DISPATCH_AGENT].join(\", \")}`, verdict: \"deny\" }\n }\n const nativeTarget = target as MaxProfileNativeAgentName | typeof MAX_BROWSE_DISPATCH_AGENT\n const modelValue = toolInput.model\n const schemaAlias = isMaxAgentSchemaModelAlias(modelValue)\n const normalizedModel = modelValue === undefined || schemaAlias\n ? undefined\n : normalizeMaxDispatchModel(modelValue)\n if (modelValue !== undefined && !schemaAlias && !normalizedModel) {\n return { allowed: false, reason: \"max dispatch denied: model must be a Claude Code Agent schema alias, Luna[1m], Gemini 3.7 Flash[1m], or bare Grok 4.6\", target, verdict: \"deny\" }\n }\n const requestedEffort = toolInput.thinking ?? toolInput.effort\n const effectiveModel = normalizedModel\n ? baseModel(normalizedModel)\n : nativeTarget === MAX_BROWSE_DISPATCH_AGENT\n // Keep this aligned with BROWSE_DEFAULT_MODEL. Importing worker-agent/engine\n // here would pull the worker runtime into the small hook bundle.\n ? \"gpt-5.6-luna\"\n : MAX_PROFILE_NATIVE_MODELS[nativeTarget]\n const effort = normalizeMaxDispatchEffort(effectiveModel, requestedEffort)\n if ((toolInput.thinking !== undefined || toolInput.effort !== undefined) && !effort) {\n return { allowed: false, reason: \"max dispatch denied: reasoning override is not supported by the selected model\", target, verdict: \"deny\" }\n }\n const updatedInput = { ...toolInput }\n if (normalizedModel) updatedInput.model = normalizedModel\n else delete updatedInput.model\n if (effort) {\n // Claude Code's native Agent payload uses `model` and `effort`; preserve\n // the field it sent rather than inventing a `thinking` key that the\n // dispatcher schema may ignore. This rewrite is only a normalization of\n // the selected model/effort, not a change to the profile's role defaults.\n if (toolInput.thinking !== undefined) updatedInput.thinking = effort\n else updatedInput.effort = effort\n }\n if (toolInput.thinking !== undefined && toolInput.effort !== undefined) {\n delete updatedInput.effort\n }\n if (toolInput.model === undefined && normalizedModel === undefined) delete updatedInput.model\n return { allowed: true, target, effort, updatedInput, verdict: \"allow\" }\n}\n\nexport function maxDispatchAllowOutput(updatedInput: Record<string, unknown>): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"allow\",\n updatedInput,\n },\n })\n}\n\nexport function maxDispatchDenyOutput(reason: string): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: reason,\n },\n })\n}\n","import { defineCommand } from \"citty\"\nimport { readFileSync } from \"node:fs\"\n\nimport {\n decideMaxDispatchGuard,\n maxDispatchAllowOutput,\n maxDispatchDenyOutput,\n} from \"./lib/max-dispatch-acl\"\nimport { buildSelfCommand, type SelfInvocation } from \"./lib/hook-launcher/self-invocation\"\n\nfunction readStdinSync(): string {\n try {\n if (process.stdin.isTTY) return \"\"\n return readFileSync(0, \"utf8\")\n } catch {\n return \"\"\n }\n}\n\nexport const internalMaxDispatchGuard = defineCommand({\n meta: {\n name: \"internal-max-dispatch-guard\",\n description: \"Internal: PreToolUse guard enforcing the max-profile native Task/Agent policy.\",\n },\n run() {\n const decision = decideMaxDispatchGuard(readStdinSync())\n if (!decision.allowed && decision.reason) {\n process.stdout.write(maxDispatchDenyOutput(decision.reason))\n } else if (decision.verdict === \"allow\" && decision.updatedInput) {\n process.stdout.write(maxDispatchAllowOutput(decision.updatedInput))\n }\n process.exitCode = 0\n },\n})\n\nexport function buildMaxDispatchGuardHookCommand(invocation: SelfInvocation): string {\n return buildSelfCommand(invocation, \"internal-max-dispatch-guard\")\n}\n"],"mappings":";;;;;AAOA,MAAa,4BAA4B;AAEzC,MAAa,4BAA4B;AAEzC,MAAM,uCAAuB,IAAI,IAAY,CAC3C,GAAG,gCACH,yBACF,CAAC;;AAGD,IAAa,+BAAb,cAAkD,MAAM;CACtD,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,SAAgB,gCACd,YACA,uBACM;CACN,IAAI,cAAc,CAAC,uBACjB,MAAM,IAAI,6BACR,iIACF;AAEJ;AAEA,MAAM,0CAA0B,IAAI,IAAI;CAAC;CAAgB;CAAoB;AAAU,CAAC;;;;;;;;;AAUxF,MAAa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MAAM,WAAW,uBAAuB,cAAc,CAAC;EACvD,IAAI,CAAC,SAAS,WAAW,SAAS,QAChC,QAAQ,OAAO,MAAM,sBAAsB,SAAS,MAAM,CAAC;OACtD,IAAI,SAAS,YAAY,WAAW,SAAS,cAClD,QAAQ,OAAO,MAAM,uBAAuB,SAAS,YAAY,CAAC;EAEpE,QAAQ,WAAW;CACrB;AACF,CAAC;AAED,SAAgB,iCAAiC,YAAoC;CACnF,OAAO,iBAAiB,YAAY,6BAA6B;AACnE"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { n as explicitPackageRoot, t as PACKAGE_ROOT_FLAG } from "./package-root-B-osctCk.js";
|
|
2
|
-
import { n as fileFindingsStore, u as stopReviewStateDir } from "./stop-gate-policy-
|
|
2
|
+
import { n as fileFindingsStore, u as stopReviewStateDir } from "./stop-gate-policy-zhzRIj6G.js";
|
|
3
3
|
import { r as hookMcpRuntimeFromEnv } from "./hook-mcp-client-DBvm9608.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-szSNt6uU.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-DVY-iV2x.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-plan-review-
|
|
1
|
+
{"version":3,"file":"internal-plan-review-DVY-iV2x.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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,MAAM,QAAQ,UAAU;GAAC,GAAG;GAAY,GAAG;GAAiB;EAAsB,GAAG;GACjG,UAAU;GACV,aAAa;GACb,OAAO;GACP,KAAK;IAAE,GAAG,QAAQ;IAAK,+BAA+B;GAAY;EACpE,CAAC;EACD,MAAM,SAAS;EACf,MAAM,GAAG,eAAe;GACtB,IAAI,QACF,IAAI;IACF,WAAW,MAAM;GACnB,QAAQ,CAER;EAEJ,CAAC;EACD,MAAM,MAAM;CACd,QAAQ;EACN,IAAI,aACF,IAAI;GACF,WAAW,WAAW;EACxB,QAAQ,CAER;CAEJ;AACF;AAEA,MAAa,qBAAqB,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 { r as parseBoolEnv } from "./exec-y8C_MU8A.js";
|
|
2
|
-
import { o as fileBlockBudget } from "./stop-gate-hook-
|
|
3
|
-
import { n as fileFindingsStore, r as fileLastPromptStore, u as stopReviewStateDir } from "./stop-gate-policy-
|
|
2
|
+
import { o as fileBlockBudget } from "./stop-gate-hook-CJOk28zd.js";
|
|
3
|
+
import { n as fileFindingsStore, r as fileLastPromptStore, u as stopReviewStateDir } from "./stop-gate-policy-zhzRIj6G.js";
|
|
4
4
|
import { n as callMcpTool, r as hookMcpRuntimeFromEnv, t as callInference } from "./hook-mcp-client-DBvm9608.js";
|
|
5
|
-
import { n as decidePromptSubmit, r as decidePromptSubmitV2 } from "./prompt-submit-hook-
|
|
5
|
+
import { n as decidePromptSubmit, r as decidePromptSubmitV2 } from "./prompt-submit-hook-ZUxo_jEl.js";
|
|
6
6
|
import { defineCommand } from "citty";
|
|
7
7
|
import { readFileSync } from "node:fs";
|
|
8
8
|
import path from "node:path";
|
|
@@ -118,4 +118,4 @@ const internalPromptSubmit = defineCommand({
|
|
|
118
118
|
//#endregion
|
|
119
119
|
export { internalPromptSubmit };
|
|
120
120
|
|
|
121
|
-
//# sourceMappingURL=internal-prompt-submit-
|
|
121
|
+
//# sourceMappingURL=internal-prompt-submit-BTqRn4FW.js.map
|
package/dist/{internal-prompt-submit-C3KovHQG.js.map → internal-prompt-submit-BTqRn4FW.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-prompt-submit-
|
|
1
|
+
{"version":3,"file":"internal-prompt-submit-BTqRn4FW.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-5.6-sol call over the prompt + a parallel lexical+semantic code\n * search) — or, when the proxy URL/nonce isn't wired or anything errors,\n * falls open to the v1 regex goal.\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 { readFileSync } from \"node:fs\"\nimport { tmpdir } from \"node:os\"\nimport path from \"node:path\"\n\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 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 the single scope/goal inference. */\nconst INFER_TIMEOUT_MS = 18_000\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 const runtime = hookMcpRuntimeFromEnv()\n\n let decision: PromptSubmitDecision\n if (runtime) {\n const workspace = workspaceFromStdin(stdin)\n decision = await decidePromptSubmitV2({\n stdin,\n steerEnabled,\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-5.6-sol\",\n instructions: system,\n input: user,\n effort: \"low\",\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,SAAS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AW,oBAAoB,mBAAmB,CAAC,CAAC,CAAC,MAAM,KAAK,MAAM;KAC3F;IACF,CAAC;GACH,OAEE,WAAW,mBAAmB;IAAE;IAAO;GAAa,CAAC;GAGvD,IAAI,SAAS,cAEX,MAAM,gBAAgB,KAAK,KAAK,OAAO,GAAG,oBAAoB,CAAC,CAAC,CAC7D,MAAM,SAAS,YAAY,CAAC,CAC5B,YAAY,CAAC,CAAC;GAEnB,IAAI,SAAS,OAAO,SAAS,GAC3B,MAAM,IAAI,SAAe,YAAY,QAAQ,OAAO,MAAM,GAAG,SAAS,OAAO,WAAW,QAAQ,CAAC,CAAC;EAEtG,QAAQ,CAER;EAIA,QAAQ,WAAW;CACrB;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as isSubagentContext } from "./stop-gate-policy-
|
|
1
|
+
import { a as isSubagentContext } from "./stop-gate-policy-zhzRIj6G.js";
|
|
2
2
|
import { defineCommand } from "citty";
|
|
3
3
|
import { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
@@ -130,4 +130,4 @@ const internalSessionBind = defineCommand({
|
|
|
130
130
|
//#endregion
|
|
131
131
|
export { internalSessionBind };
|
|
132
132
|
|
|
133
|
-
//# sourceMappingURL=internal-session-bind-
|
|
133
|
+
//# sourceMappingURL=internal-session-bind-YfH656lt.js.map
|
package/dist/{internal-session-bind-d2uoja8I.js.map → internal-session-bind-YfH656lt.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internal-session-bind-
|
|
1
|
+
{"version":3,"file":"internal-session-bind-YfH656lt.js","names":[],"sources":["../src/internal-session-bind.ts"],"sourcesContent":["/**\n * The internal `internal-session-bind` subcommand: the executable a spawned Claude\n * Code session's SessionStart / SessionEnd hooks invoke (registered into the\n * mirrored settings.json by the launcher when `AIORDIE_CLAUDE_BIND` is set —\n * i.e. when github-router runs inside an ai-or-die Terminal tab).\n *\n * It reads Claude Code's hook payload from stdin and ATOMICALLY writes a tiny\n * \"sidecar\" JSON file (path passed via `--out`) describing the CURRENTLY active\n * claude session: its sessionId and the absolute transcript path. ai-or-die owns\n * the sidecar path and watches it, so it can bind that browser tab's session\n * summariser to the exact transcript — surviving in-session `/resume`, `/clear`,\n * `/compact`, and exit→relaunch, without guessing from the filesystem.\n *\n * Side-effect only: writes the file and exits 0. It NEVER writes to stdout (a\n * SessionStart hook's stdout is injected into the model's context) and NEVER\n * blocks (any error is swallowed → exit 0).\n *\n * Top-level filter: a SessionStart fired by a subagent/teammate carries\n * `agent_id`/`agent_type`; those are skipped so only the tab's top-level session\n * drives the binding (mirrors the Stop / UserPromptSubmit hooks).\n */\n\nimport { defineCommand } from \"citty\"\n\nimport { randomBytes } from \"node:crypto\"\nimport { mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from \"node:fs\"\nimport path from \"node:path\"\n\nimport { isSubagentContext } 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 process\n * teardown and trips a `uv_async_send` assertion; a synchronous read has no such\n * handle. Hooks always receive piped stdin (guarded against a TTY; 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/**\n * Resolve a transcript path to its real location. The path claude reports sits\n * under the per-launch CLAUDE_CONFIG_DIR mirror, whose `projects` entry is a\n * junction/symlink back to the real `~/.claude/projects`. ai-or-die reads the\n * real dir, and the per-launch mirror is swept on github-router shutdown, so we\n * persist the REAL path. The file (and even intermediate dirs) may not exist yet\n * at SessionStart, so we realpath the DEEPEST EXISTING ancestor and rejoin the\n * not-yet-created trailing segments. Best-effort: if nothing resolves, keep raw.\n */\nfunction realTranscriptPath(tp: string): string {\n if (!tp) return \"\"\n try {\n return realpathSync.native(tp)\n } catch {\n /* file doesn't exist yet — resolve the deepest existing ancestor below */\n }\n const missing: string[] = []\n let cur = tp\n for (let i = 0; i < 64; i++) {\n missing.unshift(path.basename(cur))\n const parent = path.dirname(cur)\n if (parent === cur) break // reached the root without an existing ancestor\n try {\n return path.join(realpathSync.native(parent), ...missing)\n } catch {\n cur = parent\n }\n }\n return tp\n}\n\n/**\n * Pure core: turn a raw Claude Code hook payload (stdin string) into the sidecar\n * record, or `null` when there's nothing to write. Returns null for: non-JSON\n * input, a subagent/teammate payload (agent_id/agent_type present — top-level\n * filter), or a missing session_id. Exported for unit tests.\n */\nexport function decodeSessionBind(stdin: string): Record<string, unknown> | null {\n let payload: {\n hook_event_name?: unknown\n session_id?: unknown\n transcript_path?: unknown\n cwd?: unknown\n source?: unknown\n reason?: unknown\n agent_id?: unknown\n agent_type?: unknown\n } = {}\n try {\n const p: unknown = JSON.parse(stdin)\n if (p && typeof p === \"object\") payload = p as typeof payload\n else return null\n } catch {\n return null // non-JSON stdin → tolerate, write nothing\n }\n\n // Top-level only: a subagent/teammate session must not steal the tab's\n // binding. Reuse the canonical fail-closed predicate (any present agent\n // marker ⇒ not the top-level session); main-session payloads omit the keys.\n if (isSubagentContext(payload)) return null\n\n const claudeSessionId = typeof payload.session_id === \"string\" ? payload.session_id : \"\"\n if (!claudeSessionId) return null // nothing to bind to\n\n const event =\n (typeof payload.hook_event_name === \"string\" ? payload.hook_event_name : \"\") === \"SessionEnd\"\n ? \"end\"\n : \"start\"\n const record: Record<string, unknown> = {\n schema: 1,\n claudeSessionId,\n transcriptPath: realTranscriptPath(\n typeof payload.transcript_path === \"string\" ? payload.transcript_path : \"\",\n ),\n cwd: typeof payload.cwd === \"string\" ? payload.cwd : \"\",\n event,\n at: Date.now(),\n }\n if (event === \"start\" && typeof payload.source === \"string\") record.source = payload.source\n if (event === \"end\" && typeof payload.reason === \"string\") record.reason = payload.reason\n return record\n}\n\n/** Atomically write the sidecar (temp + rename) so the reader never sees a partial file. */\nfunction writeSidecar(out: string, record: Record<string, unknown>): void {\n try {\n mkdirSync(path.dirname(out), { recursive: true })\n } catch {\n /* best-effort — ai-or-die owns and creates the dir */\n }\n const tmp = `${out}.${process.pid}.${randomBytes(4).toString(\"hex\")}.tmp`\n writeFileSync(tmp, JSON.stringify(record), { mode: 0o600 })\n renameSync(tmp, out)\n}\n\nexport const internalSessionBind = defineCommand({\n meta: {\n name: \"internal-session-bind\",\n description:\n \"Internal: the SessionStart/SessionEnd hook. Reads the Claude Code hook payload on stdin \"\n + \"and atomically writes the active session id + transcript path to the --out sidecar file \"\n + \"(consumed by ai-or-die to bind a tab's sticky-note summariser). Side-effect only.\",\n },\n args: {\n out: {\n type: \"string\",\n description: \"Absolute path to the sidecar file to (atomically) write.\",\n required: false,\n },\n },\n run({ args }) {\n // Never throw out of a hook: wrap the whole body and fall through to exit 0.\n try {\n const out = typeof args.out === \"string\" ? args.out.trim() : \"\"\n if (!out) return // no sidecar target → nothing to do\n const record = decodeSessionBind(readStdin())\n if (record) writeSidecar(out, record)\n } catch {\n /* a hook must never disrupt the session */\n }\n // Side-effect only: nothing on stdout (it would inject into the model's\n // context). Natural exit 0.\n process.exitCode = 0\n },\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAS,YAAoB;CAC3B,IAAI;EACF,IAAI,QAAQ,MAAM,OAAO,OAAO;EAChC,OAAO,aAAa,GAAG,MAAM;CAC/B,QAAQ;EACN,OAAO;CACT;AACF;;;;;;;;;;AAWA,SAAS,mBAAmB,IAAoB;CAC9C,IAAI,CAAC,IAAI,OAAO;CAChB,IAAI;EACF,OAAO,aAAa,OAAO,EAAE;CAC/B,QAAQ,CAER;CACA,MAAM,UAAoB,CAAC;CAC3B,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK;EAC3B,QAAQ,QAAQ,KAAK,SAAS,GAAG,CAAC;EAClC,MAAM,SAAS,KAAK,QAAQ,GAAG;EAC/B,IAAI,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