github-router 0.3.330 → 0.3.332
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/{aic-ledger-CsBx1crE.js → aic-ledger-D4fmThbS.js} +2 -2
- package/dist/{aic-ledger-CsBx1crE.js.map → aic-ledger-D4fmThbS.js.map} +1 -1
- package/dist/{attribution-settings-DepziZU8.js → attribution-settings-BeO1w_DL.js} +62 -51
- package/dist/attribution-settings-BeO1w_DL.js.map +1 -0
- package/dist/{auth-xgFZGZbf.js → auth-DjKEIiqG.js} +4 -4
- package/dist/{auth-xgFZGZbf.js.map → auth-DjKEIiqG.js.map} +1 -1
- package/dist/bluebird-client-DpYl1YmJ.js +1163 -0
- package/dist/bluebird-client-DpYl1YmJ.js.map +1 -0
- package/dist/bluebird-client-bn9Yv6Cb.js +2 -0
- package/dist/browser-ext/manifest.json +1 -1
- package/dist/{check-usage-vUDk6oV7.js → check-usage-B7UrDwD8.js} +4 -4
- package/dist/{check-usage-vUDk6oV7.js.map → check-usage-B7UrDwD8.js.map} +1 -1
- package/dist/{claude-Dw4V8o8l.js → claude-BQQPdXLb.js} +37 -29
- package/dist/claude-BQQPdXLb.js.map +1 -0
- package/dist/{codex-CXOpv4WP.js → codex-fW-hbxtT.js} +12 -8
- package/dist/codex-fW-hbxtT.js.map +1 -0
- package/dist/{copilot-discount-0lG67i9O.js → copilot-discount-BcUa3f-k.js} +2 -2
- package/dist/{copilot-discount-0lG67i9O.js.map → copilot-discount-BcUa3f-k.js.map} +1 -1
- package/dist/{debug-a737qcCC.js → debug-CigFsS-h.js} +2 -2
- package/dist/{debug-a737qcCC.js.map → debug-CigFsS-h.js.map} +1 -1
- package/dist/engine-E4WJGSeg.js +2 -0
- package/dist/{exec-COUT4QsS.js → exec-MCU1H-KZ.js} +63 -13
- package/dist/exec-MCU1H-KZ.js.map +1 -0
- package/dist/{gate-discovery-BGqS7R2g.js → gate-discovery-DbwVeERm.js} +6 -6
- package/dist/{gate-discovery-BGqS7R2g.js.map → gate-discovery-DbwVeERm.js.map} +1 -1
- package/dist/{get-copilot-usage-VKU2IvuE.js → get-copilot-usage-CGaV01dC.js} +4 -3
- package/dist/{get-copilot-usage-VKU2IvuE.js.map → get-copilot-usage-CGaV01dC.js.map} +1 -1
- package/dist/hooks.mjs +90 -27
- package/dist/hooks.sha256 +1 -1
- package/dist/index-cmd-DXYWgKS6.js +330 -0
- package/dist/index-cmd-DXYWgKS6.js.map +1 -0
- package/dist/{internal-aic-status-Cfl5HiAN.js → internal-aic-status-Bma0r0ZS.js} +6 -5
- package/dist/internal-aic-status-Bma0r0ZS.js.map +1 -0
- package/dist/{internal-artifact-open-CX2fRP_D.js → internal-artifact-open-lta2UPnE.js} +2 -2
- package/dist/{internal-artifact-open-CX2fRP_D.js.map → internal-artifact-open-lta2UPnE.js.map} +1 -1
- package/dist/{internal-fast-dispatch-guard-Cxattkm4.js → internal-fast-dispatch-guard-DPR16qUE.js} +1 -1
- package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js → internal-fast-dispatch-guard-DoXO3X7P.js} +2 -2
- package/dist/{internal-fast-dispatch-guard-BoTxjO6b.js.map → internal-fast-dispatch-guard-DoXO3X7P.js.map} +1 -1
- package/dist/{internal-first-mate-guard-D_JFcrl_.js → internal-first-mate-guard-BEwDjHfX.js} +3 -3
- package/dist/{internal-first-mate-guard-D_JFcrl_.js.map → internal-first-mate-guard-BEwDjHfX.js.map} +1 -1
- package/dist/{internal-first-mate-guard-97qsseTP.js → internal-first-mate-guard-CAefr6Ce.js} +1 -1
- package/dist/{internal-max-dispatch-guard-DQMyOds8.js → internal-max-dispatch-guard-6ZCEanI6.js} +1 -1
- package/dist/{internal-max-dispatch-guard-Cxe8h12x.js → internal-max-dispatch-guard-CtIO7pm1.js} +3 -3
- package/dist/{internal-max-dispatch-guard-Cxe8h12x.js.map → internal-max-dispatch-guard-CtIO7pm1.js.map} +1 -1
- package/dist/{internal-plan-review-O2dwnQv3.js → internal-plan-review-jIts3KYd.js} +3 -3
- package/dist/{internal-plan-review-O2dwnQv3.js.map → internal-plan-review-jIts3KYd.js.map} +1 -1
- package/dist/{internal-prompt-submit-CD0UFkT-.js → internal-prompt-submit-BfoWVyzs.js} +10 -7
- package/dist/internal-prompt-submit-BfoWVyzs.js.map +1 -0
- package/dist/{internal-session-bind-CHIOd5ys.js → internal-session-bind-IpZ5hJzR.js} +2 -2
- package/dist/{internal-session-bind-CHIOd5ys.js.map → internal-session-bind-IpZ5hJzR.js.map} +1 -1
- package/dist/{internal-stop-hook-CH9SKjZ9.js → internal-stop-hook-DO8RKfKB.js} +6 -6
- package/dist/{internal-stop-hook-CH9SKjZ9.js.map → internal-stop-hook-DO8RKfKB.js.map} +1 -1
- package/dist/{internal-stop-review-a3rpzzhd.js → internal-stop-review-BtGDVrv-.js} +2 -2
- package/dist/{internal-stop-review-a3rpzzhd.js.map → internal-stop-review-BtGDVrv-.js.map} +1 -1
- package/dist/{internal-worker-guard-BY5seBqp.js → internal-worker-guard-C0FJ4b29.js} +2 -2
- package/dist/{internal-worker-guard-BY5seBqp.js.map → internal-worker-guard-C0FJ4b29.js.map} +1 -1
- package/dist/{internal-workspace-header-CPZNphnk.js → internal-workspace-header-tvJVAXpv.js} +2 -2
- package/dist/{internal-workspace-header-CPZNphnk.js.map → internal-workspace-header-tvJVAXpv.js.map} +1 -1
- package/dist/{lifecycle-D8vQXfeC.js → lifecycle-BqWTXaeC.js} +3 -3
- package/dist/{lifecycle-D8vQXfeC.js.map → lifecycle-BqWTXaeC.js.map} +1 -1
- package/dist/lifecycle-DMRZswwc.js +2 -0
- package/dist/lifecycle-FT75ohVw.js +2 -0
- package/dist/{lifecycle-MmpJWRcl.js → lifecycle-kpLzHUgD.js} +2 -2
- package/dist/{lifecycle-MmpJWRcl.js.map → lifecycle-kpLzHUgD.js.map} +1 -1
- package/dist/main.js +21 -21
- package/dist/{max-profile-contract-Bl7I_EOC.js → max-profile-contract-MJJt0zm-.js} +2 -2
- package/dist/{max-profile-contract-Bl7I_EOC.js.map → max-profile-contract-MJJt0zm-.js.map} +1 -1
- package/dist/{mcp-workspace-header-DX_mD0JT.js → mcp-workspace-header-B77WqVFw.js} +2 -2
- package/dist/{mcp-workspace-header-DX_mD0JT.js.map → mcp-workspace-header-B77WqVFw.js.map} +1 -1
- package/dist/{models-BjCRO0AC.js → models-68HDOEPK.js} +3 -3
- package/dist/{models-BjCRO0AC.js.map → models-68HDOEPK.js.map} +1 -1
- package/dist/{orchestration-Dn5v8c0a.js → orchestration-Ccmfslh4.js} +3 -3
- package/dist/{orchestration-Dn5v8c0a.js.map → orchestration-Ccmfslh4.js.map} +1 -1
- package/dist/{paths-P5ajjpzU.js → paths-CpbTHKeP.js} +3 -3
- package/dist/{paths-P5ajjpzU.js.map → paths-CpbTHKeP.js.map} +1 -1
- package/dist/paths-Dfivvq21.js +2 -0
- package/dist/{peer-mcp-personas-CnYMTizo.js → peer-mcp-personas-CeB2Kcn2.js} +184 -76
- package/dist/peer-mcp-personas-CeB2Kcn2.js.map +1 -0
- package/dist/{plan-review-hook-CfZBvsHd.js → plan-review-hook-ciat1jgZ.js} +4 -4
- package/dist/{plan-review-hook-CfZBvsHd.js.map → plan-review-hook-ciat1jgZ.js.map} +1 -1
- package/dist/{prompt-submit-hook-CRH6m7Vz.js → prompt-submit-hook-C8q_hDOv.js} +21 -17
- package/dist/prompt-submit-hook-C8q_hDOv.js.map +1 -0
- package/dist/{provision-D5KOOw6n.js → provision-DZLsyRYh.js} +7 -6
- package/dist/provision-DZLsyRYh.js.map +1 -0
- package/dist/{self-invocation-DBWyjvGm.js → self-invocation-DIUyoRgL.js} +2 -2
- package/dist/{self-invocation-DBWyjvGm.js.map → self-invocation-DIUyoRgL.js.map} +1 -1
- package/dist/{serve-fJWhiivo.js → serve-ik_96Q2Z.js} +33 -21
- package/dist/serve-ik_96Q2Z.js.map +1 -0
- package/dist/{server-setup-DHMPOXKT.js → server-setup-CK3O_Hwf.js} +37 -13
- package/dist/{server-setup-DHMPOXKT.js.map → server-setup-CK3O_Hwf.js.map} +1 -1
- package/dist/{service-backend-DYEPoszR.js → service-backend-7SPDLUB9.js} +411 -25
- package/dist/service-backend-7SPDLUB9.js.map +1 -0
- package/dist/{start-Gs4jAwUR.js → start-DPOJJSvp.js} +4 -4
- package/dist/{start-Gs4jAwUR.js.map → start-DPOJJSvp.js.map} +1 -1
- package/dist/{state-BlMpEFAt.js → state-CVp30CBF.js} +7 -1
- package/dist/state-CVp30CBF.js.map +1 -0
- package/dist/{stop-gate-hook-BACb8dlj.js → stop-gate-hook-DZVfKoSh.js} +4 -4
- package/dist/{stop-gate-hook-BACb8dlj.js.map → stop-gate-hook-DZVfKoSh.js.map} +1 -1
- package/dist/{stop-gate-policy-D6jIeOXB.js → stop-gate-policy-Gd_cNT9-.js} +3 -3
- package/dist/{stop-gate-policy-D6jIeOXB.js.map → stop-gate-policy-Gd_cNT9-.js.map} +1 -1
- package/dist/{token-Dlb_84hW.js → token-DATA_OQK.js} +5 -383
- package/dist/token-DATA_OQK.js.map +1 -0
- package/dist/upstream-retry-i1k1Xai2.js +383 -0
- package/dist/upstream-retry-i1k1Xai2.js.map +1 -0
- package/dist/{worker-dispatch-DtjQchvM.js → worker-dispatch-lRhno09M.js} +2 -2
- package/dist/{worker-dispatch-DtjQchvM.js.map → worker-dispatch-lRhno09M.js.map} +1 -1
- package/docs/bluebird-search.md +338 -0
- package/package.json +3 -2
- package/dist/attribution-settings-DepziZU8.js.map +0 -1
- package/dist/claude-Dw4V8o8l.js.map +0 -1
- package/dist/codex-CXOpv4WP.js.map +0 -1
- package/dist/engine-CYba_zi7.js +0 -2
- package/dist/exec-COUT4QsS.js.map +0 -1
- package/dist/index-cmd-DUjQs9zw.js +0 -182
- package/dist/index-cmd-DUjQs9zw.js.map +0 -1
- package/dist/internal-aic-status-Cfl5HiAN.js.map +0 -1
- package/dist/internal-prompt-submit-CD0UFkT-.js.map +0 -1
- package/dist/lifecycle-B2eB8nRg.js +0 -2
- package/dist/lifecycle-Dz-Rq8pD.js +0 -2
- package/dist/paths-DVXBtLyo.js +0 -2
- package/dist/peer-mcp-personas-CnYMTizo.js.map +0 -1
- package/dist/prompt-submit-hook-CRH6m7Vz.js.map +0 -1
- package/dist/provision-D5KOOw6n.js.map +0 -1
- package/dist/serve-fJWhiivo.js.map +0 -1
- package/dist/service-backend-DYEPoszR.js.map +0 -1
- package/dist/state-BlMpEFAt.js.map +0 -1
- package/dist/token-Dlb_84hW.js.map +0 -1
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import consola from "consola";
|
|
2
|
+
//#region src/lib/upstream-retry.ts
|
|
3
|
+
/**
|
|
4
|
+
* Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).
|
|
5
|
+
*
|
|
6
|
+
* Retries ONLY on transient conditions — never on success, never on a
|
|
7
|
+
* deterministic 4xx (400/401/403/404…), so a malformed request or auth
|
|
8
|
+
* failure fails fast instead of being hammered. 401 is intentionally NOT
|
|
9
|
+
* retried here: it stays with the existing token-refresh path so the
|
|
10
|
+
* 401→503 forwardError invariant is preserved.
|
|
11
|
+
*
|
|
12
|
+
* Retryable:
|
|
13
|
+
* - HTTP 429 + 5xx (500/502/503/504) — the "upstream is sick" class.
|
|
14
|
+
* - network errors (ECONNRESET / "fetch failed" / "terminated" / EPIPE …).
|
|
15
|
+
* - upstream TIMEOUT aborts: an AbortError thrown while the CALLER'S
|
|
16
|
+
* `signal` is NOT aborted (a user cancel aborts the caller's signal
|
|
17
|
+
* and is rethrown immediately, never retried).
|
|
18
|
+
*
|
|
19
|
+
* Exponential backoff + FULL jitter, capped, honoring `Retry-After`. The
|
|
20
|
+
* inter-attempt sleep is abortable so a user cancel during backoff
|
|
21
|
+
* returns promptly. Bounded `attempts` keep a single call from holding an
|
|
22
|
+
* inflight slot indefinitely (robust AND fast).
|
|
23
|
+
*
|
|
24
|
+
* Streaming note: the user-facing passthrough and the worker loop must
|
|
25
|
+
* only retry in the PRE-FIRST-BYTE window — a retry after bytes have
|
|
26
|
+
* streamed would duplicate output. Callers there pass a `doFetch` that
|
|
27
|
+
* has not yet handed its body to the consumer.
|
|
28
|
+
*/
|
|
29
|
+
const DEFAULT_RETRY_STATUSES = [
|
|
30
|
+
429,
|
|
31
|
+
500,
|
|
32
|
+
502,
|
|
33
|
+
503,
|
|
34
|
+
504
|
|
35
|
+
];
|
|
36
|
+
const TRANSPORT_MESSAGE_MAX = 512;
|
|
37
|
+
const TRANSIENT_CODES = /* @__PURE__ */ new Set([
|
|
38
|
+
"ECONNRESET",
|
|
39
|
+
"ETIMEDOUT",
|
|
40
|
+
"EPIPE",
|
|
41
|
+
"EAI_AGAIN",
|
|
42
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
43
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
44
|
+
"UND_ERR_SOCKET",
|
|
45
|
+
"UND_ERR_CLOSED",
|
|
46
|
+
"ERR_HTTP2_INVALID_SESSION",
|
|
47
|
+
"ERR_HTTP2_GOAWAY_SESSION",
|
|
48
|
+
"ERR_HTTP2_STREAM_CANCEL"
|
|
49
|
+
]);
|
|
50
|
+
/**
|
|
51
|
+
* TLS faults that are genuinely permanent: a protocol/version/cipher mismatch,
|
|
52
|
+
* or a certificate this client cannot validate. Retrying any of these buys
|
|
53
|
+
* three times the latency before the identical failure.
|
|
54
|
+
*
|
|
55
|
+
* Deliberately NOT the blanket `"ssl routines"` match this replaces. Every
|
|
56
|
+
* OpenSSL error carries that string, so the catch-all also swallowed alert 20
|
|
57
|
+
* (`bad record mac`) — an integrity fault a fresh connection routinely clears.
|
|
58
|
+
* See TRANSIENT_TLS_MESSAGES.
|
|
59
|
+
*
|
|
60
|
+
* Each entry must stay disjoint from TRANSIENT_TLS_MESSAGES. The bucket order
|
|
61
|
+
* in `classifyTransportError` checks the narrower transient alert first, so an
|
|
62
|
+
* overlap would resolve as transient; `tests/upstream-retry.test.ts` pins that
|
|
63
|
+
* no error matches two buckets.
|
|
64
|
+
*/
|
|
65
|
+
const DETERMINISTIC_TLS_MESSAGES = [
|
|
66
|
+
"self signed certificate",
|
|
67
|
+
"certificate has expired",
|
|
68
|
+
"unable to verify the first certificate",
|
|
69
|
+
"unable to get local issuer certificate",
|
|
70
|
+
"hostname/ip does not match certificate",
|
|
71
|
+
"certificate verify failed",
|
|
72
|
+
"unknown ca",
|
|
73
|
+
"wrong version number",
|
|
74
|
+
"unsupported protocol",
|
|
75
|
+
"no protocols available",
|
|
76
|
+
"alert handshake failure",
|
|
77
|
+
"alert protocol version",
|
|
78
|
+
"alert insufficient security",
|
|
79
|
+
"tls handshake"
|
|
80
|
+
];
|
|
81
|
+
/**
|
|
82
|
+
* TLS alert 20 (`bad_record_mac`) ONLY — a record failed AEAD authentication
|
|
83
|
+
* somewhere on the path. The connection is unusable, but the next one is
|
|
84
|
+
* typically fine, which is exactly what a bounded retry is for.
|
|
85
|
+
*
|
|
86
|
+
* This also matches OpenSSL's local-detection wording ("decryption failed or
|
|
87
|
+
* bad record mac", reason 281) as well as the received-alert wording ("ssl/tls
|
|
88
|
+
* alert bad record mac", reason 1020). Both are integrity faults and both
|
|
89
|
+
* warrant the same one-bounded-replay policy.
|
|
90
|
+
*
|
|
91
|
+
* An earlier revision promoted four alert phrases; three were wrong and stay
|
|
92
|
+
* deterministic on purpose. Alert 10 (`unexpected message`) is protocol state,
|
|
93
|
+
* alert 21 (`decryption failed`) is legacy-server incompatibility, and alert 22
|
|
94
|
+
* (`record overflow`) is a malformed or desynchronised stream. Promoting those
|
|
95
|
+
* converts fail-fast configuration errors into 3x latency.
|
|
96
|
+
*/
|
|
97
|
+
const TRANSIENT_TLS_MESSAGES = ["bad record mac"];
|
|
98
|
+
const DETERMINISTIC_CODES = /* @__PURE__ */ new Set([
|
|
99
|
+
"ENOTFOUND",
|
|
100
|
+
"ECONNREFUSED",
|
|
101
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
102
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
103
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
104
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
105
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
106
|
+
"CERT_HAS_EXPIRED",
|
|
107
|
+
"CERT_NOT_YET_VALID",
|
|
108
|
+
"ERR_TLS_CERT_ALTNAME_INVALID",
|
|
109
|
+
"ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED",
|
|
110
|
+
"ERR_SSL_WRONG_VERSION_NUMBER"
|
|
111
|
+
]);
|
|
112
|
+
const CREDENTIAL_RE = /\b(eyJ[A-Za-z0-9_-]{20,}(?:\.[A-Za-z0-9_-]+){0,2}|gh[opsu]_[A-Za-z0-9_]{20,}|Bearer\s+\S{20,})\b/gi;
|
|
113
|
+
const SECRET_ASSIGNMENT_RE = /\b(authorization|api[_-]?key|access[_-]?token|token|password)\s*[:=]\s*([^\s,;]+)/gi;
|
|
114
|
+
const REQUEST_BODY_RE = /\b(request\s+body|body)\s*[:=]\s*.*$/gi;
|
|
115
|
+
var TransportExhaustionError = class extends Error {
|
|
116
|
+
endpoint;
|
|
117
|
+
label;
|
|
118
|
+
attempts;
|
|
119
|
+
classification;
|
|
120
|
+
lastError;
|
|
121
|
+
constructor(metadata, cause) {
|
|
122
|
+
const target = metadata.endpoint ?? metadata.label ?? "upstream";
|
|
123
|
+
const lastError = {
|
|
124
|
+
name: sanitizeTransportText(metadata.lastError.name),
|
|
125
|
+
message: sanitizeTransportText(metadata.lastError.message),
|
|
126
|
+
code: metadata.lastError.code ? sanitizeTransportText(metadata.lastError.code) : void 0,
|
|
127
|
+
causeCode: metadata.lastError.causeCode ? sanitizeTransportText(metadata.lastError.causeCode) : void 0
|
|
128
|
+
};
|
|
129
|
+
const code = lastError.causeCode ?? lastError.code;
|
|
130
|
+
const suffix = code ? ` (${code})` : "";
|
|
131
|
+
super(`Upstream transport ${metadata.classification === "transient" ? "failed" : "is unreachable"} at ${sanitizeTransportText(target)} after ${metadata.attempts} attempt${metadata.attempts === 1 ? "" : "s"}: ${lastError.name}: ${lastError.message}${suffix}`, { cause });
|
|
132
|
+
this.name = "TransportExhaustionError";
|
|
133
|
+
this.endpoint = metadata.endpoint ? sanitizeTransportText(metadata.endpoint) : void 0;
|
|
134
|
+
this.label = metadata.label ? sanitizeTransportText(metadata.label) : void 0;
|
|
135
|
+
this.attempts = metadata.attempts;
|
|
136
|
+
this.classification = metadata.classification;
|
|
137
|
+
this.lastError = lastError;
|
|
138
|
+
}
|
|
139
|
+
};
|
|
140
|
+
function readStringProperty(value, key) {
|
|
141
|
+
if (typeof value !== "object" && typeof value !== "function" || value === null) return;
|
|
142
|
+
try {
|
|
143
|
+
const property = value[key];
|
|
144
|
+
return typeof property === "string" ? property : void 0;
|
|
145
|
+
} catch {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function readCause(value) {
|
|
150
|
+
if (typeof value !== "object" && typeof value !== "function" || value === null) return;
|
|
151
|
+
try {
|
|
152
|
+
return value.cause;
|
|
153
|
+
} catch {
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
function safeString(value) {
|
|
158
|
+
try {
|
|
159
|
+
return String(value);
|
|
160
|
+
} catch {
|
|
161
|
+
return "[unserializable error]";
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
function sanitizeTransportText(value) {
|
|
165
|
+
const sanitized = value.replace(/\r\n|\r|\n/g, " ").replace(CREDENTIAL_RE, "[REDACTED]").replace(SECRET_ASSIGNMENT_RE, "$1=[REDACTED]").replace(REQUEST_BODY_RE, "$1=[REDACTED]");
|
|
166
|
+
return sanitized.length > TRANSPORT_MESSAGE_MAX ? `${sanitized.slice(0, TRANSPORT_MESSAGE_MAX)}…` : sanitized;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Classify errors thrown before the first response byte. Deterministic
|
|
170
|
+
* connectivity/configuration signals win over generic runtime wording such as
|
|
171
|
+
* TypeError("fetch failed"), because the nested cause is more specific.
|
|
172
|
+
*
|
|
173
|
+
* Buckets are evaluated in a stated total order, narrowest first, and the first
|
|
174
|
+
* match wins — so no error can land in two of them:
|
|
175
|
+
*
|
|
176
|
+
* 1. caller cancel
|
|
177
|
+
* 2. TLS alert 20 (`bad record mac`) — integrity, retryable
|
|
178
|
+
* 3. deterministic cert/config codes and messages, plus refused/DNS-miss
|
|
179
|
+
* 4. transient codes (incl. HTTP/2 session death) and generic transport text
|
|
180
|
+
* 5. everything else — `non_transport`, rethrown raw
|
|
181
|
+
*/
|
|
182
|
+
function classifyTransportError(error, opts = {}) {
|
|
183
|
+
const name = readStringProperty(error, "name") ?? "Error";
|
|
184
|
+
const rawMessage = readStringProperty(error, "message") ?? (typeof error === "string" ? error : safeString(error));
|
|
185
|
+
const message = sanitizeTransportText(rawMessage);
|
|
186
|
+
const code = readStringProperty(error, "code");
|
|
187
|
+
const causes = [];
|
|
188
|
+
const seen = /* @__PURE__ */ new Set();
|
|
189
|
+
let current = readCause(error);
|
|
190
|
+
for (let depth = 0; current !== void 0 && depth < 4; depth++) {
|
|
191
|
+
if ((typeof current === "object" || typeof current === "function") && current !== null) {
|
|
192
|
+
if (seen.has(current)) break;
|
|
193
|
+
seen.add(current);
|
|
194
|
+
}
|
|
195
|
+
causes.push(current);
|
|
196
|
+
current = readCause(current);
|
|
197
|
+
}
|
|
198
|
+
const causeCode = causes.map((cause) => readStringProperty(cause, "code")).find((value) => value !== void 0);
|
|
199
|
+
const codes = [code, ...causes.map((cause) => readStringProperty(cause, "code"))].filter((value) => value !== void 0).map((value) => value.toUpperCase());
|
|
200
|
+
const messages = [rawMessage, ...causes.map((cause) => readStringProperty(cause, "message") ?? "")].join(" ").toLowerCase();
|
|
201
|
+
if (opts.callerCancelled) return {
|
|
202
|
+
classification: "cancelled",
|
|
203
|
+
name,
|
|
204
|
+
message,
|
|
205
|
+
code,
|
|
206
|
+
causeCode
|
|
207
|
+
};
|
|
208
|
+
if (TRANSIENT_TLS_MESSAGES.some((phrase) => messages.includes(phrase))) return {
|
|
209
|
+
classification: "transient",
|
|
210
|
+
name,
|
|
211
|
+
message,
|
|
212
|
+
code,
|
|
213
|
+
causeCode
|
|
214
|
+
};
|
|
215
|
+
if (codes.some((value) => DETERMINISTIC_CODES.has(value)) || DETERMINISTIC_TLS_MESSAGES.some((phrase) => messages.includes(phrase)) || messages.includes("ssl routines") || messages.includes("econnrefused") || messages.includes("enotfound")) return {
|
|
216
|
+
classification: "deterministic",
|
|
217
|
+
name,
|
|
218
|
+
message,
|
|
219
|
+
code,
|
|
220
|
+
causeCode
|
|
221
|
+
};
|
|
222
|
+
if (name === "AbortError" || name === "TimeoutError" || name === "InactivityTimeout" || codes.some((value) => TRANSIENT_CODES.has(value)) || messages.includes("terminated") || messages.includes("fetch failed") || messages.includes("network error") || messages.includes("socket hang up") || messages.includes("socket closed") || messages.includes("econnreset") || messages.includes("etimedout") || messages.includes("epipe") || messages.includes("eai_again")) return {
|
|
223
|
+
classification: "transient",
|
|
224
|
+
name,
|
|
225
|
+
message,
|
|
226
|
+
code,
|
|
227
|
+
causeCode
|
|
228
|
+
};
|
|
229
|
+
return {
|
|
230
|
+
classification: "non_transport",
|
|
231
|
+
name,
|
|
232
|
+
message,
|
|
233
|
+
code,
|
|
234
|
+
causeCode
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
function transportExhaustion(error, attempts, opts, details) {
|
|
238
|
+
if (details.classification !== "transient" && details.classification !== "deterministic") throw new TypeError("transportExhaustion requires a transport error");
|
|
239
|
+
return new TransportExhaustionError({
|
|
240
|
+
endpoint: opts.endpoint ?? opts.label,
|
|
241
|
+
label: opts.label,
|
|
242
|
+
attempts,
|
|
243
|
+
classification: details.classification,
|
|
244
|
+
lastError: {
|
|
245
|
+
name: details.name,
|
|
246
|
+
message: details.message,
|
|
247
|
+
code: details.code,
|
|
248
|
+
causeCode: details.causeCode
|
|
249
|
+
}
|
|
250
|
+
}, error);
|
|
251
|
+
}
|
|
252
|
+
function parseRetryAfter(headerValue) {
|
|
253
|
+
if (!headerValue) return void 0;
|
|
254
|
+
const secs = Number(headerValue);
|
|
255
|
+
if (Number.isFinite(secs)) return Math.max(0, secs * 1e3);
|
|
256
|
+
const dateMs = Date.parse(headerValue);
|
|
257
|
+
if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now());
|
|
258
|
+
}
|
|
259
|
+
/** Sleep that resolves early (does not reject) when `signal` aborts — the
|
|
260
|
+
* retry loop re-checks `signal.aborted` at the top and throws there. */
|
|
261
|
+
function abortableSleep(ms, signal) {
|
|
262
|
+
if (ms <= 0) return Promise.resolve();
|
|
263
|
+
return new Promise((resolve) => {
|
|
264
|
+
let settled = false;
|
|
265
|
+
const done = () => {
|
|
266
|
+
if (settled) return;
|
|
267
|
+
settled = true;
|
|
268
|
+
clearTimeout(timer);
|
|
269
|
+
signal?.removeEventListener("abort", done);
|
|
270
|
+
resolve();
|
|
271
|
+
};
|
|
272
|
+
const timer = setTimeout(done, ms);
|
|
273
|
+
if (signal) {
|
|
274
|
+
if (signal.aborted) {
|
|
275
|
+
done();
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
signal.addEventListener("abort", done, { once: true });
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Run `doFetch` with bounded transient-failure retries. `doFetch` is a
|
|
284
|
+
* thunk so each attempt issues a FRESH request (bodies can't be replayed
|
|
285
|
+
* from a consumed stream). Returns the final `Response` — which may still
|
|
286
|
+
* carry a retryable status if all attempts are exhausted (the caller
|
|
287
|
+
* handles that as it would a single-shot failure).
|
|
288
|
+
*/
|
|
289
|
+
async function fetchWithTransientRetry(doFetch, opts = {}) {
|
|
290
|
+
const attempts = Math.max(1, opts.attempts ?? 3);
|
|
291
|
+
const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES;
|
|
292
|
+
const baseDelayMs = opts.baseDelayMs ?? 250;
|
|
293
|
+
const maxDelayMs = opts.maxDelayMs ?? 4e3;
|
|
294
|
+
const { signal, label } = opts;
|
|
295
|
+
for (let attempt = 1;; attempt++) {
|
|
296
|
+
if (signal?.aborted) throw new DOMException("This operation was aborted", "AbortError");
|
|
297
|
+
let res;
|
|
298
|
+
let caught;
|
|
299
|
+
try {
|
|
300
|
+
res = await doFetch(attempt);
|
|
301
|
+
} catch (err) {
|
|
302
|
+
caught = err;
|
|
303
|
+
}
|
|
304
|
+
if (res && !retryStatuses.includes(res.status)) return res;
|
|
305
|
+
if (caught !== void 0) {
|
|
306
|
+
if (signal?.aborted) throw caught;
|
|
307
|
+
const details = classifyTransportError(caught);
|
|
308
|
+
if (details.classification === "deterministic") throw transportExhaustion(caught, attempt, opts, details);
|
|
309
|
+
if (details.classification !== "transient") throw caught;
|
|
310
|
+
}
|
|
311
|
+
if (attempt >= attempts) {
|
|
312
|
+
if (res) return res;
|
|
313
|
+
const details = classifyTransportError(caught);
|
|
314
|
+
throw transportExhaustion(caught, attempt, opts, details);
|
|
315
|
+
}
|
|
316
|
+
const retryAfterMs = res ? parseRetryAfter(res.headers.get("retry-after")) : void 0;
|
|
317
|
+
if (res?.body) try {
|
|
318
|
+
await res.body.cancel();
|
|
319
|
+
} catch {}
|
|
320
|
+
const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
|
|
321
|
+
const delay = Math.min(maxDelayMs, retryAfterMs ?? Math.round(Math.random() * expCap));
|
|
322
|
+
if (label) {
|
|
323
|
+
const why = res ? `HTTP ${res.status}` : caught?.name ?? "error";
|
|
324
|
+
consola.debug(`[upstream-retry] ${label}: attempt ${attempt}/${attempts} failed (${why}); retrying in ${delay}ms`);
|
|
325
|
+
}
|
|
326
|
+
await abortableSleep(delay, signal);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
/** Extract an HTTP status from a thrown error (HTTPError carries
|
|
330
|
+
* `.response.status`; others may carry `.status`/`.statusCode`; last
|
|
331
|
+
* resort parses `"HTTP <code>"` from the message). */
|
|
332
|
+
function errorStatus(err) {
|
|
333
|
+
const e = err;
|
|
334
|
+
for (const v of [
|
|
335
|
+
e?.status,
|
|
336
|
+
e?.statusCode,
|
|
337
|
+
e?.response?.status
|
|
338
|
+
]) if (typeof v === "number") return v;
|
|
339
|
+
const m = /\bHTTP (\d{3})\b/.exec(e?.message ?? "");
|
|
340
|
+
return m ? Number(m[1]) : void 0;
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Generic transient-retry for a non-`Response`-returning call (e.g. the
|
|
344
|
+
* Copilot service clients, which throw `HTTPError` on non-OK and throw on
|
|
345
|
+
* network errors). Retries `fn()` when it throws a transient error — an
|
|
346
|
+
* `HTTPError`-like with a retryable status (429/5xx) OR a transient
|
|
347
|
+
* network/timeout error — using the same backoff + abort semantics as
|
|
348
|
+
* `fetchWithTransientRetry`. Never retries a deterministic 4xx (incl.
|
|
349
|
+
* 401), a non-transient throw, or a user cancel.
|
|
350
|
+
*/
|
|
351
|
+
async function withTransientRetry(fn, opts = {}) {
|
|
352
|
+
const attempts = Math.max(1, opts.attempts ?? 3);
|
|
353
|
+
const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES;
|
|
354
|
+
const baseDelayMs = opts.baseDelayMs ?? 250;
|
|
355
|
+
const maxDelayMs = opts.maxDelayMs ?? 4e3;
|
|
356
|
+
const { signal, label } = opts;
|
|
357
|
+
for (let attempt = 1;; attempt++) {
|
|
358
|
+
if (signal?.aborted) throw new DOMException("This operation was aborted", "AbortError");
|
|
359
|
+
try {
|
|
360
|
+
return await fn(attempt);
|
|
361
|
+
} catch (err) {
|
|
362
|
+
if (signal?.aborted) throw err;
|
|
363
|
+
const status = errorStatus(err);
|
|
364
|
+
const details = classifyTransportError(err);
|
|
365
|
+
if (status !== void 0) {
|
|
366
|
+
if (!retryStatuses.includes(status) || attempt >= attempts) throw err;
|
|
367
|
+
} else {
|
|
368
|
+
if (details.classification === "deterministic") throw transportExhaustion(err, attempt, opts, details);
|
|
369
|
+
if (details.classification !== "transient") throw err;
|
|
370
|
+
if (attempt >= attempts) throw transportExhaustion(err, attempt, opts, details);
|
|
371
|
+
}
|
|
372
|
+
const retryAfterMs = parseRetryAfter(err?.response?.headers?.get?.("retry-after") ?? null);
|
|
373
|
+
const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
|
|
374
|
+
const delay = Math.min(maxDelayMs, retryAfterMs ?? Math.round(Math.random() * expCap));
|
|
375
|
+
if (label) consola.debug(`[upstream-retry] ${label}: attempt ${attempt}/${attempts} threw (${status !== void 0 ? `HTTP ${status}` : err?.name ?? "error"}); retrying in ${delay}ms`);
|
|
376
|
+
await abortableSleep(delay, signal);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
//#endregion
|
|
381
|
+
export { withTransientRetry as a, sanitizeTransportText as i, classifyTransportError as n, fetchWithTransientRetry as r, TransportExhaustionError as t };
|
|
382
|
+
|
|
383
|
+
//# sourceMappingURL=upstream-retry-i1k1Xai2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"upstream-retry-i1k1Xai2.js","names":[],"sources":["../src/lib/upstream-retry.ts"],"sourcesContent":["/**\n * Shared transient-failure retry for upstream calls (`src/lib/upstream-retry.ts`).\n *\n * Retries ONLY on transient conditions — never on success, never on a\n * deterministic 4xx (400/401/403/404…), so a malformed request or auth\n * failure fails fast instead of being hammered. 401 is intentionally NOT\n * retried here: it stays with the existing token-refresh path so the\n * 401→503 forwardError invariant is preserved.\n *\n * Retryable:\n * - HTTP 429 + 5xx (500/502/503/504) — the \"upstream is sick\" class.\n * - network errors (ECONNRESET / \"fetch failed\" / \"terminated\" / EPIPE …).\n * - upstream TIMEOUT aborts: an AbortError thrown while the CALLER'S\n * `signal` is NOT aborted (a user cancel aborts the caller's signal\n * and is rethrown immediately, never retried).\n *\n * Exponential backoff + FULL jitter, capped, honoring `Retry-After`. The\n * inter-attempt sleep is abortable so a user cancel during backoff\n * returns promptly. Bounded `attempts` keep a single call from holding an\n * inflight slot indefinitely (robust AND fast).\n *\n * Streaming note: the user-facing passthrough and the worker loop must\n * only retry in the PRE-FIRST-BYTE window — a retry after bytes have\n * streamed would duplicate output. Callers there pass a `doFetch` that\n * has not yet handed its body to the consumer.\n */\n\nimport consola from \"consola\"\n\nexport interface TransientRetryOpts {\n /** Total attempts including the first (default 3 → up to 2 retries). */\n attempts?: number\n /** Retryable HTTP statuses (default 429, 500, 502, 503, 504). */\n retryStatuses?: ReadonlyArray<number>\n /** Backoff base (default 250ms) and cap (default 4000ms). */\n baseDelayMs?: number\n maxDelayMs?: number\n /** Caller's abort signal — a user cancel fails fast (never retried). */\n signal?: AbortSignal\n /** Short label for debug logging (e.g. \"codex_critic\", \"advisor\"). */\n label?: string\n /** Upstream endpoint when it differs from the human-readable label. */\n endpoint?: string\n}\n\nconst DEFAULT_RETRY_STATUSES: ReadonlyArray<number> = [429, 500, 502, 503, 504]\nconst TRANSPORT_MESSAGE_MAX = 512\nconst TRANSIENT_CODES = new Set([\n \"ECONNRESET\",\n \"ETIMEDOUT\",\n \"EPIPE\",\n \"EAI_AGAIN\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\",\n \"UND_ERR_SOCKET\",\n // A dispatch that raced a pool teardown. Previously in NEITHER set, so it\n // fell through to \"non_transport\" and was rethrown raw at the retry loop —\n // an unclassified error escaping a classifier is a gap, not a policy.\n \"UND_ERR_CLOSED\",\n // HTTP/2 session death. These reached \"transient\" only incidentally, via the\n // outer TypeError(\"fetch failed\") message match, which means a future change\n // to that string would silently reclassify them. Name them.\n \"ERR_HTTP2_INVALID_SESSION\",\n \"ERR_HTTP2_GOAWAY_SESSION\",\n \"ERR_HTTP2_STREAM_CANCEL\",\n])\n\n/**\n * TLS faults that are genuinely permanent: a protocol/version/cipher mismatch,\n * or a certificate this client cannot validate. Retrying any of these buys\n * three times the latency before the identical failure.\n *\n * Deliberately NOT the blanket `\"ssl routines\"` match this replaces. Every\n * OpenSSL error carries that string, so the catch-all also swallowed alert 20\n * (`bad record mac`) — an integrity fault a fresh connection routinely clears.\n * See TRANSIENT_TLS_MESSAGES.\n *\n * Each entry must stay disjoint from TRANSIENT_TLS_MESSAGES. The bucket order\n * in `classifyTransportError` checks the narrower transient alert first, so an\n * overlap would resolve as transient; `tests/upstream-retry.test.ts` pins that\n * no error matches two buckets.\n */\nconst DETERMINISTIC_TLS_MESSAGES = [\n \"self signed certificate\",\n \"certificate has expired\",\n \"unable to verify the first certificate\",\n \"unable to get local issuer certificate\",\n \"hostname/ip does not match certificate\",\n \"certificate verify failed\",\n \"unknown ca\",\n \"wrong version number\",\n \"unsupported protocol\",\n \"no protocols available\",\n \"alert handshake failure\",\n \"alert protocol version\",\n \"alert insufficient security\",\n \"tls handshake\",\n]\n\n/**\n * TLS alert 20 (`bad_record_mac`) ONLY — a record failed AEAD authentication\n * somewhere on the path. The connection is unusable, but the next one is\n * typically fine, which is exactly what a bounded retry is for.\n *\n * This also matches OpenSSL's local-detection wording (\"decryption failed or\n * bad record mac\", reason 281) as well as the received-alert wording (\"ssl/tls\n * alert bad record mac\", reason 1020). Both are integrity faults and both\n * warrant the same one-bounded-replay policy.\n *\n * An earlier revision promoted four alert phrases; three were wrong and stay\n * deterministic on purpose. Alert 10 (`unexpected message`) is protocol state,\n * alert 21 (`decryption failed`) is legacy-server incompatibility, and alert 22\n * (`record overflow`) is a malformed or desynchronised stream. Promoting those\n * converts fail-fast configuration errors into 3x latency.\n */\nconst TRANSIENT_TLS_MESSAGES = [\"bad record mac\"]\nconst DETERMINISTIC_CODES = new Set([\n \"ENOTFOUND\",\n \"ECONNREFUSED\",\n \"DEPTH_ZERO_SELF_SIGNED_CERT\",\n \"SELF_SIGNED_CERT_IN_CHAIN\",\n \"UNABLE_TO_GET_ISSUER_CERT\",\n \"UNABLE_TO_GET_ISSUER_CERT_LOCALLY\",\n \"UNABLE_TO_VERIFY_LEAF_SIGNATURE\",\n \"CERT_HAS_EXPIRED\",\n \"CERT_NOT_YET_VALID\",\n \"ERR_TLS_CERT_ALTNAME_INVALID\",\n \"ERR_TLS_CERT_SIGNATURE_ALGORITHM_UNSUPPORTED\",\n \"ERR_SSL_WRONG_VERSION_NUMBER\",\n])\nconst CREDENTIAL_RE =\n /\\b(eyJ[A-Za-z0-9_-]{20,}(?:\\.[A-Za-z0-9_-]+){0,2}|gh[opsu]_[A-Za-z0-9_]{20,}|Bearer\\s+\\S{20,})\\b/gi\nconst SECRET_ASSIGNMENT_RE =\n /\\b(authorization|api[_-]?key|access[_-]?token|token|password)\\s*[:=]\\s*([^\\s,;]+)/gi\nconst REQUEST_BODY_RE =\n /\\b(request\\s+body|body)\\s*[:=]\\s*.*$/gi\n\nexport type TransportErrorClassification =\n | \"transient\"\n | \"deterministic\"\n | \"non_transport\"\n | \"cancelled\"\n\nexport interface TransportErrorDetails {\n classification: TransportErrorClassification\n name: string\n message: string\n code?: string\n causeCode?: string\n}\n\nexport interface TransportExhaustionMetadata {\n endpoint?: string\n label?: string\n attempts: number\n classification: \"transient\" | \"deterministic\"\n lastError: Omit<TransportErrorDetails, \"classification\">\n}\n\nexport class TransportExhaustionError extends Error {\n readonly endpoint?: string\n readonly label?: string\n readonly attempts: number\n readonly classification: \"transient\" | \"deterministic\"\n readonly lastError: Omit<TransportErrorDetails, \"classification\">\n\n constructor(metadata: TransportExhaustionMetadata, cause: unknown) {\n const target = metadata.endpoint ?? metadata.label ?? \"upstream\"\n const lastError = {\n name: sanitizeTransportText(metadata.lastError.name),\n message: sanitizeTransportText(metadata.lastError.message),\n code: metadata.lastError.code\n ? sanitizeTransportText(metadata.lastError.code)\n : undefined,\n causeCode: metadata.lastError.causeCode\n ? sanitizeTransportText(metadata.lastError.causeCode)\n : undefined,\n }\n const code = lastError.causeCode ?? lastError.code\n const suffix = code ? ` (${code})` : \"\"\n super(\n `Upstream transport ${metadata.classification === \"transient\" ? \"failed\" : \"is unreachable\"} at ${sanitizeTransportText(target)} after ${metadata.attempts} attempt${metadata.attempts === 1 ? \"\" : \"s\"}: ${lastError.name}: ${lastError.message}${suffix}`,\n { cause },\n )\n this.name = \"TransportExhaustionError\"\n this.endpoint = metadata.endpoint\n ? sanitizeTransportText(metadata.endpoint)\n : undefined\n this.label = metadata.label ? sanitizeTransportText(metadata.label) : undefined\n this.attempts = metadata.attempts\n this.classification = metadata.classification\n this.lastError = lastError\n }\n}\n\nfunction readStringProperty(value: unknown, key: string): string | undefined {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n const property = (value as Record<string, unknown>)[key]\n return typeof property === \"string\" ? property : undefined\n } catch {\n return undefined\n }\n}\n\nfunction readCause(value: unknown): unknown {\n if (\n (typeof value !== \"object\" && typeof value !== \"function\")\n || value === null\n ) {\n return undefined\n }\n try {\n return (value as { cause?: unknown }).cause\n } catch {\n return undefined\n }\n}\n\nfunction safeString(value: unknown): string {\n try {\n return String(value)\n } catch {\n return \"[unserializable error]\"\n }\n}\n\nexport function sanitizeTransportText(value: string): string {\n const sanitized = value\n .replace(/\\r\\n|\\r|\\n/g, \" \")\n .replace(CREDENTIAL_RE, \"[REDACTED]\")\n .replace(SECRET_ASSIGNMENT_RE, \"$1=[REDACTED]\")\n .replace(REQUEST_BODY_RE, \"$1=[REDACTED]\")\n return sanitized.length > TRANSPORT_MESSAGE_MAX\n ? `${sanitized.slice(0, TRANSPORT_MESSAGE_MAX)}…`\n : sanitized\n}\n\n/**\n * Classify errors thrown before the first response byte. Deterministic\n * connectivity/configuration signals win over generic runtime wording such as\n * TypeError(\"fetch failed\"), because the nested cause is more specific.\n *\n * Buckets are evaluated in a stated total order, narrowest first, and the first\n * match wins — so no error can land in two of them:\n *\n * 1. caller cancel\n * 2. TLS alert 20 (`bad record mac`) — integrity, retryable\n * 3. deterministic cert/config codes and messages, plus refused/DNS-miss\n * 4. transient codes (incl. HTTP/2 session death) and generic transport text\n * 5. everything else — `non_transport`, rethrown raw\n */\nexport function classifyTransportError(\n error: unknown,\n opts: { callerCancelled?: boolean } = {},\n): TransportErrorDetails {\n const name = readStringProperty(error, \"name\") ?? \"Error\"\n const rawMessage =\n readStringProperty(error, \"message\")\n ?? (typeof error === \"string\" ? error : safeString(error))\n const message = sanitizeTransportText(rawMessage)\n const code = readStringProperty(error, \"code\")\n\n const causes: unknown[] = []\n const seen = new Set<unknown>()\n let current = readCause(error)\n for (let depth = 0; current !== undefined && depth < 4; depth++) {\n if (\n (typeof current === \"object\" || typeof current === \"function\")\n && current !== null\n ) {\n if (seen.has(current)) break\n seen.add(current)\n }\n causes.push(current)\n current = readCause(current)\n }\n const causeCode = causes\n .map((cause) => readStringProperty(cause, \"code\"))\n .find((value): value is string => value !== undefined)\n const codes = [code, ...causes.map((cause) => readStringProperty(cause, \"code\"))]\n .filter((value): value is string => value !== undefined)\n .map((value) => value.toUpperCase())\n const messages = [\n rawMessage,\n ...causes.map((cause) => readStringProperty(cause, \"message\") ?? \"\"),\n ]\n .join(\" \")\n .toLowerCase()\n\n if (opts.callerCancelled) {\n return { classification: \"cancelled\", name, message, code, causeCode }\n }\n // Narrowest match first: TLS alert 20 is an integrity fault, not a\n // configuration fault, and it must not be swallowed by the broader cert /\n // protocol patterns below (which is exactly what the old blanket\n // `\"ssl routines\"` match did — it failed the alert after ONE attempt).\n if (TRANSIENT_TLS_MESSAGES.some((phrase) => messages.includes(phrase))) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n if (\n codes.some((value) => DETERMINISTIC_CODES.has(value))\n || DETERMINISTIC_TLS_MESSAGES.some((phrase) => messages.includes(phrase))\n // Catch-all for every OTHER OpenSSL failure. Safe here, and only here,\n // because the one retryable alert already returned above — so this keeps\n // fail-fast for the long tail (`tlsv13 alert certificate required`,\n // `sslv3 alert bad certificate`, `tlsv1 alert internal error`, …) without\n // re-swallowing alert 20.\n //\n // Without it those errors fall through to the generic transient branch via\n // the outer `TypeError: fetch failed`, turning a permanent configuration\n // failure into three attempts. Narrowing the deterministic list alone was\n // not sufficient; the residue has to land somewhere deliberate.\n || messages.includes(\"ssl routines\")\n // A refused connection or a DNS miss is a configuration signal, so it\n // fails fast rather than being hammered. Kept deliberately, not inherited:\n // transient DNS is already covered by EAI_AGAIN, and a genuinely\n // restarting upstream surfaces as ECONNRESET or a 5xx, both of which do\n // retry.\n || messages.includes(\"econnrefused\")\n || messages.includes(\"enotfound\")\n ) {\n return { classification: \"deterministic\", name, message, code, causeCode }\n }\n if (\n name === \"AbortError\"\n || name === \"TimeoutError\"\n || name === \"InactivityTimeout\"\n || codes.some((value) => TRANSIENT_CODES.has(value))\n || messages.includes(\"terminated\")\n || messages.includes(\"fetch failed\")\n || messages.includes(\"network error\")\n || messages.includes(\"socket hang up\")\n || messages.includes(\"socket closed\")\n || messages.includes(\"econnreset\")\n || messages.includes(\"etimedout\")\n || messages.includes(\"epipe\")\n || messages.includes(\"eai_again\")\n ) {\n return { classification: \"transient\", name, message, code, causeCode }\n }\n return { classification: \"non_transport\", name, message, code, causeCode }\n}\n\nfunction transportExhaustion(\n error: unknown,\n attempts: number,\n opts: TransientRetryOpts,\n details: TransportErrorDetails,\n): TransportExhaustionError {\n if (\n details.classification !== \"transient\"\n && details.classification !== \"deterministic\"\n ) {\n throw new TypeError(\"transportExhaustion requires a transport error\")\n }\n return new TransportExhaustionError(\n {\n endpoint: opts.endpoint ?? opts.label,\n label: opts.label,\n attempts,\n classification: details.classification,\n lastError: {\n name: details.name,\n message: details.message,\n code: details.code,\n causeCode: details.causeCode,\n },\n },\n error,\n )\n}\n\nfunction parseRetryAfter(headerValue: string | null): number | undefined {\n if (!headerValue) return undefined\n const secs = Number(headerValue)\n if (Number.isFinite(secs)) return Math.max(0, secs * 1000)\n const dateMs = Date.parse(headerValue)\n if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now())\n return undefined\n}\n\n/** Sleep that resolves early (does not reject) when `signal` aborts — the\n * retry loop re-checks `signal.aborted` at the top and throws there. */\nfunction abortableSleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (ms <= 0) return Promise.resolve()\n return new Promise<void>((resolve) => {\n let settled = false\n const done = (): void => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n signal?.removeEventListener(\"abort\", done)\n resolve()\n }\n const timer = setTimeout(done, ms)\n if (signal) {\n if (signal.aborted) {\n done()\n return\n }\n signal.addEventListener(\"abort\", done, { once: true })\n }\n })\n}\n\n/**\n * Run `doFetch` with bounded transient-failure retries. `doFetch` is a\n * thunk so each attempt issues a FRESH request (bodies can't be replayed\n * from a consumed stream). Returns the final `Response` — which may still\n * carry a retryable status if all attempts are exhausted (the caller\n * handles that as it would a single-shot failure).\n */\nexport async function fetchWithTransientRetry(\n doFetch: (attempt: number) => Promise<Response>,\n opts: TransientRetryOpts = {},\n): Promise<Response> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n\n let res: Response | undefined\n let caught: unknown\n try {\n res = await doFetch(attempt)\n } catch (err) {\n caught = err\n }\n\n // Success or a non-retryable status → done.\n if (res && !retryStatuses.includes(res.status)) return res\n\n // A thrown error: a user cancel fails fast; otherwise only retry the\n // transient network/timeout class.\n if (caught !== undefined) {\n if (signal?.aborted) throw caught\n const details = classifyTransportError(caught)\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(caught, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw caught\n }\n\n // Out of attempts → return the last error response (or rethrow).\n if (attempt >= attempts) {\n if (res) return res\n const details = classifyTransportError(caught)\n throw transportExhaustion(caught, attempt, opts, details)\n }\n\n // Free the connection before retrying a retryable-status response.\n const retryAfterMs = res\n ? parseRetryAfter(res.headers.get(\"retry-after\"))\n : undefined\n if (res?.body) {\n try {\n await res.body.cancel()\n } catch {\n /* already torn down */\n }\n }\n\n // Full jitter (random within the exponential cap), Retry-After wins.\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n const why = res\n ? `HTTP ${res.status}`\n : (caught as { name?: string } | undefined)?.name ?? \"error\"\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} failed (${why}); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n}\n\n/** Extract an HTTP status from a thrown error (HTTPError carries\n * `.response.status`; others may carry `.status`/`.statusCode`; last\n * resort parses `\"HTTP <code>\"` from the message). */\nfunction errorStatus(err: unknown): number | undefined {\n const e = err as\n | {\n status?: unknown\n statusCode?: unknown\n response?: { status?: unknown }\n message?: string\n }\n | undefined\n for (const v of [e?.status, e?.statusCode, e?.response?.status]) {\n if (typeof v === \"number\") return v\n }\n const m = /\\bHTTP (\\d{3})\\b/.exec(e?.message ?? \"\")\n return m ? Number(m[1]) : undefined\n}\n\n/**\n * Generic transient-retry for a non-`Response`-returning call (e.g. the\n * Copilot service clients, which throw `HTTPError` on non-OK and throw on\n * network errors). Retries `fn()` when it throws a transient error — an\n * `HTTPError`-like with a retryable status (429/5xx) OR a transient\n * network/timeout error — using the same backoff + abort semantics as\n * `fetchWithTransientRetry`. Never retries a deterministic 4xx (incl.\n * 401), a non-transient throw, or a user cancel.\n */\nexport async function withTransientRetry<T>(\n fn: (attempt: number) => Promise<T>,\n opts: TransientRetryOpts = {},\n): Promise<T> {\n const attempts = Math.max(1, opts.attempts ?? 3)\n const retryStatuses = opts.retryStatuses ?? DEFAULT_RETRY_STATUSES\n const baseDelayMs = opts.baseDelayMs ?? 250\n const maxDelayMs = opts.maxDelayMs ?? 4000\n const { signal, label } = opts\n\n for (let attempt = 1; ; attempt++) {\n if (signal?.aborted) {\n throw new DOMException(\"This operation was aborted\", \"AbortError\")\n }\n try {\n return await fn(attempt)\n } catch (err) {\n if (signal?.aborted) throw err\n const status = errorStatus(err)\n const details = classifyTransportError(err)\n if (status !== undefined) {\n if (!retryStatuses.includes(status) || attempt >= attempts) throw err\n } else {\n if (details.classification === \"deterministic\") {\n throw transportExhaustion(err, attempt, opts, details)\n }\n if (details.classification !== \"transient\") throw err\n if (attempt >= attempts) {\n throw transportExhaustion(err, attempt, opts, details)\n }\n }\n\n const retryAfterMs = parseRetryAfter(\n (err as { response?: { headers?: { get?: (k: string) => string | null } } })\n ?.response?.headers?.get?.(\"retry-after\") ?? null,\n )\n const expCap = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1))\n const delay = Math.min(\n maxDelayMs,\n retryAfterMs ?? Math.round(Math.random() * expCap),\n )\n if (label) {\n consola.debug(\n `[upstream-retry] ${label}: attempt ${attempt}/${attempts} threw (${\n status !== undefined ? `HTTP ${status}` : (err as { name?: string })?.name ?? \"error\"\n }); retrying in ${delay}ms`,\n )\n }\n await abortableSleep(delay, signal)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,yBAAgD;CAAC;CAAK;CAAK;CAAK;CAAK;AAAG;AAC9E,MAAM,wBAAwB;AAC9B,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CAIA;CAIA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;AAiBD,MAAM,6BAA6B;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;;;;;;AAkBA,MAAM,yBAAyB,CAAC,gBAAgB;AAChD,MAAM,sCAAsB,IAAI,IAAI;CAClC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CA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"./self-invocation-
|
|
1
|
+
import { t as buildSelfCommand } from "./self-invocation-DIUyoRgL.js";
|
|
2
2
|
//#region src/lib/worker-dispatch.ts
|
|
3
3
|
/**
|
|
4
4
|
* Frozen contract for the NON-BLOCKING workers surface.
|
|
@@ -249,4 +249,4 @@ Object.freeze({
|
|
|
249
249
|
//#endregion
|
|
250
250
|
export { dispatcherAgentName as a, dispatcherTools as c, decideWorkerGuard as i, guardToolMatcher as l, activeDispatchModes as n, dispatcherDescription as o, buildWorkerGuardHookCommand as r, dispatcherPrompt as s, ALL_WORKER_DISPATCH_MODES as t, parseModesCsv as u };
|
|
251
251
|
|
|
252
|
-
//# sourceMappingURL=worker-dispatch-
|
|
252
|
+
//# sourceMappingURL=worker-dispatch-lRhno09M.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-dispatch-DtjQchvM.js","names":[],"sources":["../src/lib/worker-dispatch.ts"],"sourcesContent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n return SKILL_WORKER_CONFIGS[role]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;;;AAOlC,MAAa,4BAA+D,CAC1E,GAAG,mBACH,kBACF;;AAGA,SAAgB,oBAAoB,MAAkC;CACpE,OAAO,UAAU;AACnB;AAIE,0BAA0B,IAAI,mBAAmB;;AAGnD,SAAgB,eAAe,YAAoB,MAAkC;CACnF,OAAO,QAAQ,WAAW,IAAI;AAChC;;;AAIA,SAAgB,oBAAoB,MAAsD;CACxF,OAAO,KAAK,SAAS,CAAC,GAAG,mBAAmB,kBAAkB,IAAI,CAAC,GAAG,iBAAiB;AACzF;AAEA,SAAS,YAAY,GAAmB;CACtC,OAAO,EAAE,QAAQ,uBAAuB,MAAM;AAChD;;;;;;;;AASA,SAAgB,iBAAiB,YAAoB,OAAkD;CACrG,MAAM,MAAM,MAAM,KAAK,MAAM,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,GAAG;CACrD,OAAO,SAAS,YAAY,UAAU,EAAE,KAAK,IAAI;AACnD;;;AAIA,SAAgB,oBACd,UACA,YACA,OAC2B;CAC3B,MAAM,SAAS,QAAQ,WAAW;CAClC,IAAI,CAAC,SAAS,WAAW,MAAM,GAAG,OAAO;CACzC,MAAM,OAAO,SAAS,MAAM,OAAO,MAAM;CACzC,OAAQ,MAAgC,SAAS,IAAI,IAAK,OAA8B;AAC1F;;;;AAKA,SAAgB,gBAAgB,MAAyC;CAIvE,OACE,mGAJa,OACX,yBAAyB,oBAAoB,IAAI,EAAE,mCACnD,gE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ent":["/**\n * Frozen contract for the NON-BLOCKING workers surface.\n *\n * The `workers` MCP tools (`explore`/`implement`/`review`/`plan`/`test`, and\n * `browse` when the browse agent is enabled) BLOCK the caller for up to 6h\n * (`runWorkerAgent`). The MAIN Claude Code agent must never block on one, so a\n * per-mode `worker-*` DISPATCHER SUBAGENT — which Claude Code runs in the\n * background and reports on via a completion notification — is the only\n * sanctioned way to run a worker. This module is the single source of truth for\n * three things that must never drift:\n *\n * 1. the tool → dispatcher map (`mcp__<workersKey>__<mode>` ↔ `worker-<mode>`),\n * 2. the PreToolUse GUARD decision that denies a raw worker call from the main\n * agent (or any non-dispatcher subagent) and redirects it to the matching\n * `worker-*` agent, allowing it only from the dispatcher itself, and\n * 3. the dispatcher subagent bodies (description / system prompt / `tools:`\n * allowlist).\n *\n * Imported by `codex-mcp-config.ts` (dispatcher `.md` generation + the hook\n * command it bakes into settings.json) AND `internal-worker-guard.ts` (the\n * runtime PreToolUse hook). Keeping the map here means the settings matcher, the\n * redirect target, the dispatcher names, and the `tools:` allowlist are all\n * derived from one place.\n *\n * Discrimination mechanism: a Claude Code PreToolUse payload carries\n * `agent_type` (the invoking subagent's name) ONLY inside a subagent context —\n * absent for the top-level/main agent. So `agent_type === \"worker-<mode>\"` is\n * the reliable \"this call came from the dispatcher, allow it\" signal, and its\n * absence (or any other value) means \"main agent or an unrelated subagent →\n * deny\". This is the SAME field this repo's Stop / prompt-submit hooks already\n * key off (`isSubagentContext` in `orchestration/stop-gate-policy.ts`); the\n * guard here is the inverse (allow-only-dispatcher rather than skip-any-sub).\n */\n\nimport { buildSelfCommand, type SelfInvocation } from \"./hook-launcher/self-invocation\"\n\n/** The five always-available worker modes (gated by `workerToolsEnabled()`). */\nexport const CORE_WORKER_MODES = [\n \"explore\",\n \"implement\",\n \"review\",\n \"plan\",\n \"test\",\n] as const\n\n/** The browse worker mode, gated separately by `browseAgentEnabled()`. */\nexport const BROWSE_WORKER_MODE = \"browse\" as const\n\nexport type CoreWorkerMode = (typeof CORE_WORKER_MODES)[number]\nexport type WorkerDispatchMode = CoreWorkerMode | typeof BROWSE_WORKER_MODE\n\n/** Every mode the surface can expose — used to build the sweep-regex allowlist\n * and to validate `--modes`. Order is stable (core first, browse last). */\nexport const ALL_WORKER_DISPATCH_MODES: ReadonlyArray<WorkerDispatchMode> = [\n ...CORE_WORKER_MODES,\n BROWSE_WORKER_MODE,\n]\n\n/** The dispatcher subagent name for a mode, e.g. `implement` → `worker-implement`. */\nexport function dispatcherAgentName(mode: WorkerDispatchMode): string {\n return `worker-${mode}`\n}\n\n/** Every possible dispatcher subagent name (used by the stale-`.md` sweep). */\nexport const ALL_DISPATCHER_AGENT_NAMES: ReadonlyArray<string> =\n ALL_WORKER_DISPATCH_MODES.map(dispatcherAgentName)\n\n/** The MCP tool name the workers server exposes for a mode under the resolved key. */\nexport function workerToolName(workersKey: string, mode: WorkerDispatchMode): string {\n return `mcp__${workersKey}__${mode}`\n}\n\n/** The active dispatch modes for a launch: the five core modes plus `browse`\n * only when the browse agent is enabled. */\nexport function activeDispatchModes(opts: { browse: boolean }): Array<WorkerDispatchMode> {\n return opts.browse ? [...CORE_WORKER_MODES, BROWSE_WORKER_MODE] : [...CORE_WORKER_MODES]\n}\n\nfunction escapeRegex(s: string): string {\n return s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\n/**\n * The Claude Code PreToolUse `matcher` (a regex over the tool name) that scopes\n * the guard hook to exactly the active worker tools — nothing else invokes the\n * hook. Anchored + exact-alternation so an unrelated `mcp__<key>__status` (a\n * future non-blocking tool with no dispatcher) is never matched, hence never\n * denied.\n */\nexport function guardToolMatcher(workersKey: string, modes: ReadonlyArray<WorkerDispatchMode>): string {\n const alt = modes.map((m) => escapeRegex(m)).join(\"|\")\n return `^mcp__${escapeRegex(workersKey)}__(${alt})$`\n}\n\n/** Parse the worker mode out of a tool name for the resolved key, or null if it\n * isn't one of the recognized worker tools. */\nexport function parseWorkerToolCall(\n toolName: string,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): WorkerDispatchMode | null {\n const prefix = `mcp__${workersKey}__`\n if (!toolName.startsWith(prefix)) return null\n const rest = toolName.slice(prefix.length)\n return (modes as ReadonlyArray<string>).includes(rest) ? (rest as WorkerDispatchMode) : null\n}\n\n/** The `permissionDecisionReason` shown to the model on a deny, steering it to\n * the matching background dispatcher. `mode` is null when the payload was\n * unparseable (fail-closed generic message). */\nexport function guardDenyReason(mode: WorkerDispatchMode | null): string {\n const target = mode\n ? `Agent(subagent_type: \"${dispatcherAgentName(mode)}\", prompt: <your worker brief>)`\n : `the matching background \\`worker-*\\` agent via the Agent tool`\n return (\n \"Workers run as background subagents in this session so your turn never blocks. \"\n + `Re-issue this as ${target}. `\n + \"It returns immediately and delivers the worker's result as a completion notification — \"\n + \"do not call the raw `mcp__…__` worker tool from the main thread.\"\n )\n}\n\n/** The stdout JSON a PreToolUse hook prints to DENY a tool call. */\nexport function guardDenyOutput(mode: WorkerDispatchMode | null): string {\n return JSON.stringify({\n hookSpecificOutput: {\n hookEventName: \"PreToolUse\",\n permissionDecision: \"deny\",\n permissionDecisionReason: guardDenyReason(mode),\n },\n })\n}\n\nexport interface WorkerGuardResult {\n /** JSON to print to stdout (a deny decision), or null to ALLOW (print nothing). */\n output: string | null\n /** Machine-readable verdict for tests/telemetry. */\n verdict: \"allow-dispatcher\" | \"allow-non-worker\" | \"deny-main\" | \"deny-malformed\"\n}\n\n/**\n * Pure PreToolUse guard decision. Given the raw stdin payload, the resolved\n * workers key, and the active modes, decide whether to DENY the tool call.\n *\n * Rules (fail toward protecting the \"main never blocks\" invariant):\n * - Payload unparseable / no string `tool_name`: the matcher only fires this\n * hook for worker tools, so a payload we can't read is still a worker call\n * → DENY (fail closed, generic redirect).\n * - `tool_name` is not a recognized worker tool for this key: ALLOW (not a\n * tool we guard — never deny a non-worker tool).\n * - `agent_type` equals one of the active dispatcher names: ALLOW (the call\n * came from the dispatcher subagent that is meant to run the worker).\n * - Otherwise (main agent: `agent_type` absent; or a non-dispatcher subagent):\n * DENY with a redirect to the matching `worker-<mode>` agent.\n */\nexport function decideWorkerGuard(input: {\n stdin: string\n workersKey: string\n modes: ReadonlyArray<WorkerDispatchMode>\n}): WorkerGuardResult {\n let payload: { tool_name?: unknown; agent_type?: unknown } | null = null\n try {\n const parsed: unknown = JSON.parse(input.stdin)\n if (parsed && typeof parsed === \"object\") {\n payload = parsed as { tool_name?: unknown; agent_type?: unknown }\n }\n } catch {\n payload = null\n }\n\n const toolName = typeof payload?.tool_name === \"string\" ? payload.tool_name : null\n if (!toolName) {\n // Fail CLOSED: the settings matcher only routes worker-tool calls here, so\n // an unreadable payload is still a worker call we must not let through.\n return { output: guardDenyOutput(null), verdict: \"deny-malformed\" }\n }\n\n const mode = parseWorkerToolCall(toolName, input.workersKey, input.modes)\n if (mode === null) {\n // Not one of the worker tools we guard (matcher over-fired, or a future\n // non-blocking tool under the same server) → allow the normal flow.\n return { output: null, verdict: \"allow-non-worker\" }\n }\n\n const agentType = payload?.agent_type\n if (typeof agentType === \"string\" && agentType === dispatcherAgentName(mode)) {\n // The call originated inside the `worker-<mode>` dispatcher subagent that is\n // meant to run THIS worker. Require an exact mode match (not just \"any\n // dispatcher\"), so a read-only `worker-explore` can't invoke the\n // write-capable `implement` worker if it misroutes or is prompt-injected.\n // If a matching dispatcher is still denied, the payload that reached this\n // hook did not carry this exact top-level `agent_type`, or a different\n // PreToolUse hook denied the call after this guard allowed it.\n return { output: null, verdict: \"allow-dispatcher\" }\n }\n\n // Main agent (agent_type absent), a non-dispatcher subagent, or a dispatcher\n // for a DIFFERENT mode → deny + redirect. Denying non-dispatcher subagents\n // too closes the transitive-blocking hole (a foreground subagent that blocked\n // on a worker would transitively block the main agent).\n return { output: guardDenyOutput(mode), verdict: \"deny-main\" }\n}\n\n// ─── Dispatcher subagent bodies ──────────────────────────────────────────────\n\n/** One-line human description shown to the lead when picking a subagent. Uses\n * the documented \"Use proactively\" auto-delegation idiom. */\nexport function dispatcherDescription(mode: WorkerDispatchMode): string {\n const blurb: Record<WorkerDispatchMode, string> = {\n explore:\n \"Non-blocking `explore` worker: dispatches a read-only autonomous worker (its own context) in the background and delivers its summary as a completion notification.\",\n implement:\n \"Non-blocking `implement` worker: dispatches an autonomous coding worker (read/write/bash) that ALWAYS runs in an isolated git worktree and returns the diff (for in-place edits use the `implementer` subagent), in the background, and delivers its result as a completion notification.\",\n review:\n \"Non-blocking `review` worker: the backgrounded counterpart of the `reviewer` subagent, running a cross-lab model. It has explore's read-and-search tools plus `bash`, so it can VERIFY rather than only read: reproduce a failure, or run the build or suite to check a claim. By default it works directly in the workspace, where it gets no edit/write tools but `bash` still runs real commands, so a build or test it invokes can touch the tree. Pass `worktree: true` to run it isolated in a replayed git worktree instead, which also lets it author a throwaway probe test. Returns severity-ranked findings with file:line and a go/no-go, as a completion notification. Use `explore` instead when you just need to find or understand something.\",\n plan:\n \"Non-blocking `plan` worker: dispatches a read-only planner that returns an ordered implementation plan, in the background, and delivers it as a completion notification.\",\n test:\n \"Non-blocking `test` worker: dispatches an independent test author (in an isolated git worktree) that writes tests trying to break the implementation, in the background, and delivers pass/fail as a completion notification.\",\n browse:\n \"Non-blocking `browse` worker: dispatches an autonomous browser agent in the background and delivers its result as a completion notification.\",\n }\n return (\n `${blurb[mode]} Use proactively for any ${mode}-mode worker task so a long run never blocks your turn: `\n + \"it returns immediately and notifies you when done.\"\n )\n}\n\n/** The dispatcher subagent's full system prompt: call the one worker tool once,\n * relay verbatim, do nothing else. */\nexport function dispatcherPrompt(mode: WorkerDispatchMode, workersKey: string): string {\n const tool = workerToolName(workersKey, mode)\n const briefField = mode === \"browse\" ? \"task\" : \"prompt\"\n const briefDescription = mode === \"browse\" ? \"the lead's browse task, copied verbatim\" : \"the lead's worker brief, copied verbatim\"\n const modeSpecificPassThrough = mode === \"browse\"\n ? \"\\n - `sessionId` (optional): pass through if the lead specified one\"\n : mode === \"review\"\n ? \"\\n - `worktree` (optional): pass `true` only if the lead asked for an isolated review\"\n : \"\"\n return [\n `# Subagent: ${dispatcherAgentName(mode)}`,\n \"\",\n `You are a thin DISPATCHER for the \\`${mode}\\` worker. You run in the background so the`,\n \"lead agent's turn is never blocked while the (up-to-6-hour) worker runs.\",\n \"\",\n \"## Your only job\",\n \"\",\n `Call the \\`${tool}\\` tool EXACTLY ONCE, passing through the fields from the lead's brief:`,\n ` - \\`${briefField}\\`: ${briefDescription}`,\n \" - `workspace`: ALWAYS pass this. Use the absolute path of the directory the\",\n \" lead named, or, when the lead named none, your own current working\",\n \" directory. The proxy runs as a separate long-lived process and cannot see\",\n \" where you are, so if you omit this it falls back to the session's directory,\",\n \" which may be a different checkout than the files the lead is asking about.\",\n \" - `model` / `thinking` (optional): only if the lead specified them\",\n \" - `maxWallClockMs` (optional): per-call wall-clock budget in ms, if the lead specified one\"\n + modeSpecificPassThrough,\n \"\",\n \"When the tool returns, output its result VERBATIM as your final message. That final\",\n \"message is what the lead receives in the completion notification — it IS the result.\",\n \"\",\n \"## Hard rules\",\n \"\",\n \"- Call the worker tool exactly once. Do not retry on a normal (non-error) return.\",\n \"- Do NOT attempt the task yourself, do NOT read/edit files, do NOT run other tools.\",\n \"- Do NOT spawn other agents (you have no Agent tool and must not try to gain one).\",\n \"- Do NOT summarize, paraphrase, or add commentary — relay the worker output verbatim.\",\n \"- If the worker returns an error, relay that error verbatim (do not mask it).\",\n ].join(\"\\n\")\n}\n\n/** The `tools:` frontmatter allowlist for a dispatcher: the workers MCP server\n * wildcard (`mcp__<workersKey>__*`). Claude Code's `tools:` field supports\n * MCP patterns only at SERVER granularity (`mcp__<server>__*`), not individual\n * tool names, so this grants exactly the workers tools and NOTHING else — no\n * Agent/Task (so it cannot spawn further agents → no recursion), no Read/Bash\n * (so it cannot do extra work). The dispatcher's prompt narrows it to the one\n * mode; the guard allows only the exact dispatcher for that worker mode. */\nexport function dispatcherTools(_mode: WorkerDispatchMode, workersKey: string): Array<string> {\n return [`mcp__${workersKey}__*`]\n}\n\n/**\n * Build the shell command Claude Code runs for the workers `PreToolUse` guard\n * hook — the running github-router via its node/bun binary so it works\n * regardless of PATH. Mirrors `buildPromptSubmitHookCommand`.\n *\n * The resolved `workersKey` and the active `modes` are baked into the command\n * ARGS (not env): `mergeStopHookIntoSettings` dedups hooks by the command\n * string only, so baking the key/modes makes a changed resolution produce a\n * DISTINCT command — no stale-matcher entry can survive from a prior launch.\n */\nexport function buildWorkerGuardHookCommand(\n invocation: SelfInvocation,\n workersKey: string,\n modes: ReadonlyArray<WorkerDispatchMode>,\n): string {\n const q = (s: string): string => `\"${s}\"`\n const args = `internal-worker-guard --workers-key ${q(workersKey)} --modes ${q(modes.join(\",\"))}`\n return buildSelfCommand(invocation, args)\n}\n\n/** Parse a `--modes` CSV back into validated modes (drops unknown tokens). */\nexport function parseModesCsv(csv: string | undefined): Array<WorkerDispatchMode> {\n if (!csv) return [...CORE_WORKER_MODES]\n const known = new Set<string>(ALL_WORKER_DISPATCH_MODES)\n const out = csv\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => known.has(s)) as Array<WorkerDispatchMode>\n return out.length > 0 ? out : [...CORE_WORKER_MODES]\n}\n\n// ─── Pipeline skill worker configs (additive, non-guard) ─────────────────────\n\n/**\n * Bounded worker configs for the `/gh-gather-context`, `/gh-plan`, and\n * `/gh-implement` pipeline skills. These reuse the existing\n * `worker-explore` / `worker-implement` / `worker-review` / `worker-plan`\n * dispatchers (so the PreToolUse guard above is untouched); the configs only\n * pin the 200K-default model alias, the wall-clock budget, and the worktree\n * policy each skill brief must use. All models are bare slugs (no `[1m]`).\n *\n * No output-token cap is listed: worker tools accept `{prompt, model,\n * thinking, workspace, maxWallClockMs, worktree}` and have no output-token\n * parameter, so such a cap would be unenforced. `timeoutMs` IS enforceable:\n * the skill bodies instruct the lead to pass it as the real `maxWallClockMs`\n * worker arg (honored by `worker-agent/budget.ts`, clamped to the per-call\n * ceiling in `peer-mcp-personas.ts`).\n */\nexport type SkillWorkerRole =\n | \"gather-context-explore\"\n | \"implement-task\"\n | \"review-pass1\"\n | \"review-pass2\"\n\nexport interface SkillWorkerConfig {\n /** Existing dispatcher to reuse (guard-compatible, no new modes). */\n dispatcher: WorkerDispatchMode\n /** Router-owned model alias (200K default, effort pinned). */\n modelAlias: string\n /**\n * Wall-clock budget per worker call, passed by the lead as the real\n * `maxWallClockMs` worker arg (well under the 6h per-call ceiling).\n */\n timeoutMs: number\n /** Whether the worker runs in an isolated git worktree. */\n worktree: boolean\n}\n\nexport const SKILL_WORKER_CONFIGS: Readonly<Record<SkillWorkerRole, SkillWorkerConfig>> = Object.freeze({\n \"gather-context-explore\": Object.freeze({\n dispatcher: \"explore\",\n modelAlias: \"gh-router-skill-gather-context-explore-high\",\n timeoutMs: 180_000,\n worktree: false,\n }),\n \"implement-task\": Object.freeze({\n dispatcher: \"implement\",\n modelAlias: \"gh-router-skill-implement-task-max\",\n timeoutMs: 600_000,\n worktree: true,\n }),\n \"review-pass1\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass1-max\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n \"review-pass2\": Object.freeze({\n dispatcher: \"review\",\n modelAlias: \"gh-router-skill-review-pass2-medium\",\n timeoutMs: 300_000,\n worktree: false,\n }),\n})\n\nexport function skillWorkerConfig(role: SkillWorkerRole): SkillWorkerConfig {\n return SKILL_WORKER_CONFIGS[role]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;CAC/B;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,qBAAqB;;;AAOlC,MAAa,4BAA+D,CAC1E,GAAG,mBACH,kBACF;;AAGA,SAAgB,oBAAoB,MAAkC;CACpE,OAAO,UAAU;AACnB;AAIE,0BAA0B,IAAI,mBAAmB;;AAGnD,SAAgB,eAAe,YAAoB,MAAkC;CACnF,OAAO,QAAQ,WAAW,IAAI;AAChC;;;AAIA,SAAgB,oBAAoB,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