@ran-sh/dsh-crew 0.3.6 → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/.claude-plugin/plugin.json +8 -8
  2. package/.mcp.json +8 -8
  3. package/LICENSE +21 -21
  4. package/README.de.md +359 -359
  5. package/README.es.md +359 -359
  6. package/README.fr.md +359 -359
  7. package/README.hi.md +359 -359
  8. package/README.id.md +359 -359
  9. package/README.ja.md +359 -359
  10. package/README.ko.md +359 -359
  11. package/README.md +94 -180
  12. package/README.pt.md +359 -359
  13. package/README.ru.md +359 -359
  14. package/README.th.md +359 -359
  15. package/README.tr.md +359 -359
  16. package/README.vi.md +359 -359
  17. package/README.zh-TW.md +359 -359
  18. package/README.zh.md +94 -180
  19. package/agents/ds-flash.md +26 -26
  20. package/agents/ds-pro.md +32 -32
  21. package/agents/ds-reviewer.md +23 -23
  22. package/agents/ds-worker.md +22 -22
  23. package/codex/agents/ds-flash.toml +30 -30
  24. package/codex/agents/ds-pro.toml +31 -31
  25. package/codex/agents/ds-reviewer.toml +28 -28
  26. package/codex/agents/ds-worker.toml +28 -28
  27. package/codex/prompts/dsh-config.md +3 -3
  28. package/codex/prompts/dsh-status.md +1 -1
  29. package/commands/config.md +11 -11
  30. package/commands/off.md +5 -5
  31. package/commands/on.md +5 -5
  32. package/commands/status.md +5 -5
  33. package/cordis.patch.yml +4 -4
  34. package/lib/client.js +1655 -974
  35. package/official-web-bridge/cordis.patch.yml +4 -0
  36. package/official-web-bridge/entry.mjs +1 -0
  37. package/official-web-bridge/lib/client.js +3446 -0
  38. package/official-web-bridge/package.json +26 -0
  39. package/package.json +133 -131
  40. package/scripts/build-client.mjs +32 -28
  41. package/scripts/live-crew-smoke.mjs +39 -39
  42. package/scripts/live-policy-matrix.mjs +177 -177
  43. package/scripts/policy-probe.mjs +101 -101
  44. package/scripts/setup.mjs +284 -284
  45. package/scripts/smoke-real.mjs +110 -110
  46. package/scripts/smoke.mjs +78 -78
  47. package/scripts/verify-installer-fix.mjs +26 -26
  48. package/scripts/verify-official-bridge-e2e.mjs +159 -0
  49. package/src/adaptive-routing.mjs +260 -260
  50. package/src/client/activation-summary.tsx +64 -64
  51. package/src/client/collapsible-sections.mjs +55 -0
  52. package/src/client/entry.tsx +236 -236
  53. package/src/client/index.tsx +1213 -1120
  54. package/src/config-readiness.mjs +59 -59
  55. package/src/delivery.mjs +205 -205
  56. package/src/dsh-cli-runtime.mjs +458 -447
  57. package/src/failure-classification.mjs +172 -172
  58. package/src/hub/entry.mjs +98 -98
  59. package/src/hub-client.mjs +132 -132
  60. package/src/hub-compatibility.mjs +49 -49
  61. package/src/i18n.mjs +19 -19
  62. package/src/install/cli.mjs +28 -28
  63. package/src/install/install-legacy.mjs +462 -462
  64. package/src/install/install.mjs +451 -451
  65. package/src/install/npx-lifecycle.mjs +1119 -1055
  66. package/src/install/official-web.mjs +132 -0
  67. package/src/mcp-runtime.mjs +257 -257
  68. package/src/model-catalog.mjs +173 -173
  69. package/src/model-routing.mjs +391 -391
  70. package/src/official-web-bridge.mjs +196 -0
  71. package/src/policy.mjs +197 -197
  72. package/src/readiness-matrix.mjs +169 -169
  73. package/src/runtime-controls.mjs +90 -90
  74. package/src/runtime-identity.mjs +108 -108
  75. package/src/server.mjs +477 -477
  76. package/src/status-shard.mjs +52 -52
  77. package/src/structured-error-code.mjs +38 -38
  78. package/src/vision-route.mjs +138 -138
  79. package/src/workflow-runtime.mjs +573 -573
  80. package/src/workflow.mjs +160 -160
  81. package/src/workspace-audit.mjs +231 -231
  82. package/src/workspace-isolation.mjs +365 -365
  83. package/statusline/statusline.sh +14 -14
  84. package/statusline/worker-segment.sh +35 -35
  85. package/worker.cordis.yml +77 -77
@@ -0,0 +1,196 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { existsSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { crewDshHome } from './install/install.mjs';
6
+ import { crewDshRuntimeModule } from './dsh-cli-runtime.mjs';
7
+
8
+ export const CREW_BRIDGE_PREFIX = '/_dsh/dsh-crew';
9
+ export const CREW_BRIDGE_TARGET = 'http://127.0.0.1:3210';
10
+ const MAX_BODY_BYTES = 4 * 1024 * 1024;
11
+ const HOP_BY_HOP = new Set([
12
+ 'connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization',
13
+ 'te', 'trailer', 'transfer-encoding', 'upgrade', 'host', 'content-length',
14
+ ]);
15
+
16
+ export function isLoopbackAddress(address) {
17
+ return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1';
18
+ }
19
+
20
+ function isLocalHostname(hostname) {
21
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '[::1]' || hostname === '::1';
22
+ }
23
+
24
+ export function isTrustedLocalRequest(req) {
25
+ if (!isLoopbackAddress(req?.socket?.remoteAddress)) return false;
26
+ const host = typeof req?.headers?.host === 'string' ? req.headers.host.trim().toLowerCase() : '';
27
+ if (!host) return false;
28
+ let authority;
29
+ try { authority = new URL(`http://${host}`); } catch { return false; }
30
+ if (!isLocalHostname(authority.hostname.toLowerCase())) return false;
31
+ const fetchSite = String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase();
32
+ if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'none') return false;
33
+ const origin = req?.headers?.origin;
34
+ if (origin !== undefined) {
35
+ if (typeof origin !== 'string') return false;
36
+ let parsedOrigin;
37
+ try { parsedOrigin = new URL(origin); } catch { return false; }
38
+ if (!isLocalHostname(parsedOrigin.hostname.toLowerCase()) || parsedOrigin.host.toLowerCase() !== host) return false;
39
+ }
40
+ return true;
41
+ }
42
+
43
+ function safeHeaders(source) {
44
+ const result = {};
45
+ for (const [rawName, rawValue] of Object.entries(source ?? {})) {
46
+ const name = rawName.toLowerCase();
47
+ if (HOP_BY_HOP.has(name) || rawValue === undefined) continue;
48
+ result[name] = Array.isArray(rawValue) ? rawValue.join(', ') : String(rawValue);
49
+ }
50
+ return result;
51
+ }
52
+
53
+ function sendJson(res, status, value) {
54
+ const body = Buffer.from(JSON.stringify(value));
55
+ res.writeHead(status, {
56
+ 'content-type': 'application/json; charset=utf-8',
57
+ 'content-length': String(body.length),
58
+ 'cache-control': 'no-store',
59
+ 'x-content-type-options': 'nosniff',
60
+ 'x-dsh-crew-bridge': '3080-to-3210',
61
+ });
62
+ res.end(body);
63
+ }
64
+
65
+ async function readBoundedBody(req, limit = MAX_BODY_BYTES) {
66
+ const chunks = [];
67
+ let size = 0;
68
+ for await (const chunk of req) {
69
+ const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
70
+ size += value.length;
71
+ if (size > limit) throw Object.assign(new Error('request too large'), { code: 'BODY_TOO_LARGE' });
72
+ chunks.push(value);
73
+ }
74
+ return Buffer.concat(chunks);
75
+ }
76
+
77
+ async function defaultHealthCheck(fetchImpl = globalThis.fetch) {
78
+ try {
79
+ const response = await fetchImpl(`${CREW_BRIDGE_TARGET}${CREW_BRIDGE_PREFIX}/ping`, {
80
+ signal: AbortSignal.timeout(1_500),
81
+ headers: { accept: 'application/json' },
82
+ });
83
+ return response.ok;
84
+ } catch { return false; }
85
+ }
86
+
87
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
88
+
89
+ export function createCrewSidecarSupervisor({
90
+ home = homedir(),
91
+ exists = existsSync,
92
+ healthCheck = () => defaultHealthCheck(),
93
+ spawnImpl = spawn,
94
+ wait = delay,
95
+ maxAttempts = 120,
96
+ pollInterval = 250,
97
+ } = {}) {
98
+ let starting = null;
99
+ let runningChild = null;
100
+ const runtime = crewDshRuntimeModule({ home });
101
+ const dshHome = crewDshHome({ home });
102
+
103
+ async function start() {
104
+ if (await healthCheck()) return { ok: true, started: false };
105
+ if (!exists(runtime)) return { ok: false, code: 'CREW_RUNTIME_NOT_INSTALLED' };
106
+ const childAlive = runningChild && runningChild.killed !== true && runningChild.exitCode == null;
107
+ if (!childAlive) {
108
+ runningChild = spawnImpl(process.execPath, [
109
+ runtime, '--profile', 'dsh-crew', '--host', '127.0.0.1', '--port', '3210',
110
+ ], {
111
+ cwd: dshHome,
112
+ env: { ...process.env, DSH_HOME: dshHome },
113
+ detached: true,
114
+ stdio: 'ignore',
115
+ windowsHide: true,
116
+ });
117
+ const ownedChild = runningChild;
118
+ ownedChild.once?.('exit', () => { if (runningChild === ownedChild) runningChild = null; });
119
+ ownedChild.unref?.();
120
+ }
121
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
122
+ if (await healthCheck()) return { ok: true, started: true };
123
+ await wait(pollInterval);
124
+ }
125
+ return { ok: false, code: 'CREW_BACKEND_START_TIMEOUT' };
126
+ }
127
+
128
+ return {
129
+ ensure() {
130
+ if (!starting) starting = start().finally(() => { starting = null; });
131
+ return starting;
132
+ },
133
+ };
134
+ }
135
+
136
+ const processSupervisor = createCrewSidecarSupervisor();
137
+
138
+ export async function proxyCrewRequest(req, res, {
139
+ fetchImpl = globalThis.fetch,
140
+ ensureBackend = () => processSupervisor.ensure(),
141
+ } = {}) {
142
+ if (!isTrustedLocalRequest(req)) {
143
+ sendJson(res, 403, { ok: false, code: 'LOCAL_SAME_ORIGIN_ONLY' });
144
+ return;
145
+ }
146
+ let pathname;
147
+ try { pathname = new URL(req.url, 'http://127.0.0.1:3080').pathname; } catch { pathname = ''; }
148
+ if (pathname !== CREW_BRIDGE_PREFIX && !pathname.startsWith(`${CREW_BRIDGE_PREFIX}/`)) {
149
+ sendJson(res, 404, { ok: false, code: 'NOT_FOUND' });
150
+ return;
151
+ }
152
+ try {
153
+ const backend = await ensureBackend();
154
+ if (backend?.ok === false) throw new Error('backend unavailable');
155
+ const method = String(req.method ?? 'GET').toUpperCase();
156
+ const bodyBuffer = method === 'GET' || method === 'HEAD' ? null : await readBoundedBody(req);
157
+ const response = await fetchImpl(`${CREW_BRIDGE_TARGET}${req.url}`, {
158
+ method,
159
+ headers: safeHeaders(req.headers),
160
+ body: bodyBuffer === null ? undefined : new Blob([bodyBuffer]),
161
+ signal: AbortSignal.timeout(120_000),
162
+ });
163
+ const responseBody = Buffer.from(await response.arrayBuffer());
164
+ const headers = safeHeaders(Object.fromEntries(response.headers.entries()));
165
+ headers['content-length'] = String(responseBody.length);
166
+ headers['x-dsh-crew-bridge'] = '3080-to-3210';
167
+ res.writeHead(response.status, headers);
168
+ res.end(responseBody);
169
+ } catch (error) {
170
+ if (error?.code === 'BODY_TOO_LARGE') sendJson(res, 413, { ok: false, code: 'REQUEST_TOO_LARGE' });
171
+ else sendJson(res, 503, { ok: false, code: 'CREW_BACKEND_UNAVAILABLE' });
172
+ }
173
+ }
174
+
175
+ export function registerOfficialWebBridge(ctx, options = {}) {
176
+ return ctx.inject(['webServer'], (webCtx) => {
177
+ const disposeStatus = webCtx.webServer.register({
178
+ kind: 'exact',
179
+ path: `${CREW_BRIDGE_PREFIX}/bridge-status`,
180
+ handler: (req, res) => {
181
+ if (!isTrustedLocalRequest(req)) return sendJson(res, 403, { ok: false, code: 'LOCAL_SAME_ORIGIN_ONLY' });
182
+ return sendJson(res, 200, { ok: true, mode: 'official-3080-isolated-3210' });
183
+ },
184
+ });
185
+ const disposeProxy = webCtx.webServer.register({
186
+ kind: 'prefix',
187
+ path: CREW_BRIDGE_PREFIX,
188
+ handler: (req, res) => proxyCrewRequest(req, res, options),
189
+ });
190
+ return () => { disposeProxy?.(); disposeStatus?.(); };
191
+ });
192
+ }
193
+
194
+ export async function apply(ctx) {
195
+ registerOfficialWebBridge(ctx);
196
+ }
package/src/policy.mjs CHANGED
@@ -1,197 +1,197 @@
1
- // v0.3 config-authority facade over the frozen v0.2 policy implementation.
2
- //
3
- // The v0.2 module remains byte-for-byte available as policy-legacy.mjs. New
4
- // callers import this facade. For schema-v3 persisted configs, the nested
5
- // worker/review/execution/legacy snapshot is authoritative; flat Flash/Pro
6
- // fields are compatibility mirrors only. Legacy files still flow through the
7
- // old migration exactly as before.
8
-
9
- export * from './policy-legacy.mjs';
10
- import * as legacy from './policy-legacy.mjs';
11
- import { normalizeAdaptiveRouting } from './adaptive-routing.mjs';
12
-
13
- export { normalizeAdaptiveRouting };
14
- export const CONFIG_SCHEMA_VERSION = 3;
15
-
16
- function validObject(value) {
17
- return !!value && typeof value === 'object' && !Array.isArray(value);
18
- }
19
-
20
- function hasCanonicalAuthority(raw) {
21
- return Number(raw?.config_schema_version) >= CONFIG_SCHEMA_VERSION
22
- && validObject(raw?.worker)
23
- && validObject(raw?.review)
24
- && validObject(raw?.execution);
25
- }
26
-
27
- function semanticLegacyMode(canonical) {
28
- if (canonical.review.auto_review === true && canonical.review.state === 'auto') return 'review-pipeline';
29
- if (canonical.worker.state === 'auto' && canonical.review.state === 'disabled'
30
- && canonical.worker.model_policy.strategy === 'economy') return 'flash-only';
31
- if (canonical.worker.state === 'auto' && canonical.review.state === 'disabled'
32
- && canonical.worker.model_policy.strategy === 'quality') return 'pro-only';
33
- if (canonical.worker.state === 'auto' && canonical.review.state === 'manual') return 'balanced';
34
- return 'custom';
35
- }
36
-
37
- function normalizeLegacySnapshot(raw, canonical) {
38
- // A nested v3 legacy snapshot is canonical compatibility metadata. Flat
39
- // fields are only a fallback for transitional/pre-v3 inputs.
40
- const nested = validObject(raw?.legacy) ? raw.legacy : {};
41
- const source = { ...raw, ...nested };
42
- const mode = legacy.COLLABORATION_MODES.includes(source.collaboration_mode)
43
- ? source.collaboration_mode
44
- : semanticLegacyMode(canonical);
45
-
46
- let flash = legacy.TIER_STATES.includes(source.flash_state) ? source.flash_state : undefined;
47
- let pro = legacy.TIER_STATES.includes(source.pro_state) ? source.pro_state : undefined;
48
- if (mode === 'flash-only') { flash = 'auto'; pro = 'disabled'; }
49
- else if (mode === 'pro-only') { flash = 'disabled'; pro = 'auto'; }
50
- else if (mode === 'balanced' || mode === 'review-pipeline') { flash = 'auto'; pro = 'auto'; }
51
- else {
52
- flash ??= canonical.worker.state;
53
- // reviewer=manual historically means the Pro tier is available/Auto but
54
- // review itself is on-demand. Preserve an explicit nested pro state when
55
- // present; otherwise use a conservative compatibility reconstruction.
56
- pro ??= canonical.review.state === 'disabled' ? 'disabled' : 'auto';
57
- }
58
-
59
- return {
60
- collaboration_mode: mode,
61
- tier_policy: mode === 'flash-only' ? 'flash-only' : mode === 'pro-only' ? 'pro-only' : 'auto',
62
- flash_state: flash,
63
- pro_state: pro,
64
- };
65
- }
66
-
67
- function modelPolicyWithAdaptive(basePolicy, rawPolicy) {
68
- return {
69
- ...basePolicy,
70
- adaptive: normalizeAdaptiveRouting(rawPolicy?.adaptive),
71
- };
72
- }
73
-
74
- function normalizeCanonical(raw) {
75
- const base = legacy.getCanonical(raw);
76
- const providerMode = legacy.normalizeWorkerProviderMode(base.worker?.provider_mode);
77
- const canonical = {
78
- ...base,
79
- execution: {
80
- ...base.execution,
81
- // There is one global dispatch permission. `execution.enabled` is a
82
- // canonical mirror of the top-level switch, never a second authority.
83
- enabled: base.subagents_enabled,
84
- },
85
- worker: {
86
- ...base.worker,
87
- provider_mode: providerMode,
88
- model_policy: modelPolicyWithAdaptive(base.worker.model_policy, raw?.worker?.model_policy),
89
- },
90
- review: {
91
- ...base.review,
92
- // v0.3 still exposes one Worker Provider selector. Until per-role
93
- // provider modes become first-class, keep both roles aligned.
94
- provider_mode: providerMode,
95
- model_policy: modelPolicyWithAdaptive(base.review.model_policy, raw?.review?.model_policy),
96
- },
97
- };
98
- canonical.legacy = normalizeLegacySnapshot(raw, canonical);
99
- return canonical;
100
- }
101
-
102
- function proMirror(canonical) {
103
- const escalation = canonical.worker.model_policy;
104
- const reviewer = canonical.review.model_policy;
105
- if (escalation.escalation_priority_configured || escalation.escalation_priority.length > 0) {
106
- return {
107
- priority: escalation.escalation_priority,
108
- configured: escalation.escalation_priority_configured,
109
- fallback: escalation.fallback,
110
- };
111
- }
112
- return {
113
- priority: reviewer.priority,
114
- configured: reviewer.priorityConfigured,
115
- fallback: reviewer.fallback,
116
- };
117
- }
118
-
119
- function legacyRoutingMirror(canonical) {
120
- // Legacy tier/UI behavior has its own canonical compatibility sub-domain.
121
- // Never infer this back from flat mirrors: schema-v3 `legacy` owns it.
122
- return normalizeLegacySnapshot({ legacy: canonical.legacy }, canonical);
123
- }
124
-
125
- /**
126
- * Re-exported normalizer with schema-v3 precedence.
127
- *
128
- * `legacy.normalizeGlobalConfig` remains the import path for legacy-file
129
- * migration. Once schema v3 is present, flat compatibility fields are rebuilt
130
- * from the canonical snapshot so a stale/manual mirror cannot override runtime
131
- * behavior.
132
- */
133
- export function normalizeGlobalConfig(raw = {}) {
134
- const normalized = legacy.normalizeGlobalConfig(raw);
135
- if (!hasCanonicalAuthority(raw)) return normalized;
136
-
137
- const canonical = normalizeCanonical(raw);
138
- const pro = proMirror(canonical);
139
- const routing = legacyRoutingMirror(canonical);
140
- return {
141
- ...normalized,
142
- config_schema_version: CONFIG_SCHEMA_VERSION,
143
- subagents_enabled: canonical.subagents_enabled,
144
- main_agent_mode: canonical.main_agent_mode,
145
- default_effort: canonical.execution.default_effort,
146
- default_timeout_seconds: canonical.execution.default_timeout_seconds,
147
- mode: canonical.execution.mode,
148
- max_parallel: canonical.execution.max_parallel,
149
- isolation: canonical.execution.isolation,
150
- collaboration_mode: routing.collaboration_mode,
151
- tier_policy: routing.tier_policy,
152
- flash_state: routing.flash_state,
153
- pro_state: routing.pro_state,
154
- worker_state: canonical.worker.state,
155
- review_state: canonical.review.state,
156
- auto_review: canonical.review.auto_review === true,
157
- worker_provider_mode: canonical.worker.provider_mode,
158
- flash_model_priority: [...canonical.worker.model_policy.priority],
159
- flash_model_priority_configured: canonical.worker.model_policy.priorityConfigured,
160
- flash_model_fallback: canonical.worker.model_policy.fallback,
161
- pro_model_priority: [...pro.priority],
162
- pro_model_priority_configured: pro.configured,
163
- pro_model_fallback: pro.fallback,
164
- escalate_on_failure: canonical.worker.model_policy.escalation.enabled,
165
- pro_reviews_flash: canonical.review.auto_review === true,
166
- execution: canonical.execution,
167
- worker: canonical.worker,
168
- review: canonical.review,
169
- legacy: canonical.legacy,
170
- };
171
- }
172
-
173
- /**
174
- * v0.3 model-policy view. The frozen v0.2 resolver remains authoritative for
175
- * every existing dimension. This facade only adds the normalized opt-in
176
- * adaptive sub-domain, so direct canonical-ish v0.2 callers retain the exact
177
- * priority/escalation semantics they had before schema-v3 existed.
178
- */
179
- export function resolveModelPolicy(config = {}, role = 'worker', context = {}) {
180
- const base = legacy.resolveModelPolicy(config, role, context);
181
- const rawPolicy = role === 'reviewer'
182
- ? config?.review?.model_policy
183
- : config?.worker?.model_policy;
184
- return {
185
- ...base,
186
- adaptive: normalizeAdaptiveRouting(rawPolicy?.adaptive ?? base.adaptive),
187
- };
188
- }
189
-
190
- /** Explicit legacy-import normalizer for the persistence layer. */
191
- export function normalizeLegacyGlobalConfig(raw = {}) {
192
- return legacy.normalizeGlobalConfig(raw);
193
- }
194
-
195
- export function configHasCanonicalAuthority(raw = {}) {
196
- return hasCanonicalAuthority(raw);
197
- }
1
+ // v0.3 config-authority facade over the frozen v0.2 policy implementation.
2
+ //
3
+ // The v0.2 module remains byte-for-byte available as policy-legacy.mjs. New
4
+ // callers import this facade. For schema-v3 persisted configs, the nested
5
+ // worker/review/execution/legacy snapshot is authoritative; flat Flash/Pro
6
+ // fields are compatibility mirrors only. Legacy files still flow through the
7
+ // old migration exactly as before.
8
+
9
+ export * from './policy-legacy.mjs';
10
+ import * as legacy from './policy-legacy.mjs';
11
+ import { normalizeAdaptiveRouting } from './adaptive-routing.mjs';
12
+
13
+ export { normalizeAdaptiveRouting };
14
+ export const CONFIG_SCHEMA_VERSION = 3;
15
+
16
+ function validObject(value) {
17
+ return !!value && typeof value === 'object' && !Array.isArray(value);
18
+ }
19
+
20
+ function hasCanonicalAuthority(raw) {
21
+ return Number(raw?.config_schema_version) >= CONFIG_SCHEMA_VERSION
22
+ && validObject(raw?.worker)
23
+ && validObject(raw?.review)
24
+ && validObject(raw?.execution);
25
+ }
26
+
27
+ function semanticLegacyMode(canonical) {
28
+ if (canonical.review.auto_review === true && canonical.review.state === 'auto') return 'review-pipeline';
29
+ if (canonical.worker.state === 'auto' && canonical.review.state === 'disabled'
30
+ && canonical.worker.model_policy.strategy === 'economy') return 'flash-only';
31
+ if (canonical.worker.state === 'auto' && canonical.review.state === 'disabled'
32
+ && canonical.worker.model_policy.strategy === 'quality') return 'pro-only';
33
+ if (canonical.worker.state === 'auto' && canonical.review.state === 'manual') return 'balanced';
34
+ return 'custom';
35
+ }
36
+
37
+ function normalizeLegacySnapshot(raw, canonical) {
38
+ // A nested v3 legacy snapshot is canonical compatibility metadata. Flat
39
+ // fields are only a fallback for transitional/pre-v3 inputs.
40
+ const nested = validObject(raw?.legacy) ? raw.legacy : {};
41
+ const source = { ...raw, ...nested };
42
+ const mode = legacy.COLLABORATION_MODES.includes(source.collaboration_mode)
43
+ ? source.collaboration_mode
44
+ : semanticLegacyMode(canonical);
45
+
46
+ let flash = legacy.TIER_STATES.includes(source.flash_state) ? source.flash_state : undefined;
47
+ let pro = legacy.TIER_STATES.includes(source.pro_state) ? source.pro_state : undefined;
48
+ if (mode === 'flash-only') { flash = 'auto'; pro = 'disabled'; }
49
+ else if (mode === 'pro-only') { flash = 'disabled'; pro = 'auto'; }
50
+ else if (mode === 'balanced' || mode === 'review-pipeline') { flash = 'auto'; pro = 'auto'; }
51
+ else {
52
+ flash ??= canonical.worker.state;
53
+ // reviewer=manual historically means the Pro tier is available/Auto but
54
+ // review itself is on-demand. Preserve an explicit nested pro state when
55
+ // present; otherwise use a conservative compatibility reconstruction.
56
+ pro ??= canonical.review.state === 'disabled' ? 'disabled' : 'auto';
57
+ }
58
+
59
+ return {
60
+ collaboration_mode: mode,
61
+ tier_policy: mode === 'flash-only' ? 'flash-only' : mode === 'pro-only' ? 'pro-only' : 'auto',
62
+ flash_state: flash,
63
+ pro_state: pro,
64
+ };
65
+ }
66
+
67
+ function modelPolicyWithAdaptive(basePolicy, rawPolicy) {
68
+ return {
69
+ ...basePolicy,
70
+ adaptive: normalizeAdaptiveRouting(rawPolicy?.adaptive),
71
+ };
72
+ }
73
+
74
+ function normalizeCanonical(raw) {
75
+ const base = legacy.getCanonical(raw);
76
+ const providerMode = legacy.normalizeWorkerProviderMode(base.worker?.provider_mode);
77
+ const canonical = {
78
+ ...base,
79
+ execution: {
80
+ ...base.execution,
81
+ // There is one global dispatch permission. `execution.enabled` is a
82
+ // canonical mirror of the top-level switch, never a second authority.
83
+ enabled: base.subagents_enabled,
84
+ },
85
+ worker: {
86
+ ...base.worker,
87
+ provider_mode: providerMode,
88
+ model_policy: modelPolicyWithAdaptive(base.worker.model_policy, raw?.worker?.model_policy),
89
+ },
90
+ review: {
91
+ ...base.review,
92
+ // v0.3 still exposes one Worker Provider selector. Until per-role
93
+ // provider modes become first-class, keep both roles aligned.
94
+ provider_mode: providerMode,
95
+ model_policy: modelPolicyWithAdaptive(base.review.model_policy, raw?.review?.model_policy),
96
+ },
97
+ };
98
+ canonical.legacy = normalizeLegacySnapshot(raw, canonical);
99
+ return canonical;
100
+ }
101
+
102
+ function proMirror(canonical) {
103
+ const escalation = canonical.worker.model_policy;
104
+ const reviewer = canonical.review.model_policy;
105
+ if (escalation.escalation_priority_configured || escalation.escalation_priority.length > 0) {
106
+ return {
107
+ priority: escalation.escalation_priority,
108
+ configured: escalation.escalation_priority_configured,
109
+ fallback: escalation.fallback,
110
+ };
111
+ }
112
+ return {
113
+ priority: reviewer.priority,
114
+ configured: reviewer.priorityConfigured,
115
+ fallback: reviewer.fallback,
116
+ };
117
+ }
118
+
119
+ function legacyRoutingMirror(canonical) {
120
+ // Legacy tier/UI behavior has its own canonical compatibility sub-domain.
121
+ // Never infer this back from flat mirrors: schema-v3 `legacy` owns it.
122
+ return normalizeLegacySnapshot({ legacy: canonical.legacy }, canonical);
123
+ }
124
+
125
+ /**
126
+ * Re-exported normalizer with schema-v3 precedence.
127
+ *
128
+ * `legacy.normalizeGlobalConfig` remains the import path for legacy-file
129
+ * migration. Once schema v3 is present, flat compatibility fields are rebuilt
130
+ * from the canonical snapshot so a stale/manual mirror cannot override runtime
131
+ * behavior.
132
+ */
133
+ export function normalizeGlobalConfig(raw = {}) {
134
+ const normalized = legacy.normalizeGlobalConfig(raw);
135
+ if (!hasCanonicalAuthority(raw)) return normalized;
136
+
137
+ const canonical = normalizeCanonical(raw);
138
+ const pro = proMirror(canonical);
139
+ const routing = legacyRoutingMirror(canonical);
140
+ return {
141
+ ...normalized,
142
+ config_schema_version: CONFIG_SCHEMA_VERSION,
143
+ subagents_enabled: canonical.subagents_enabled,
144
+ main_agent_mode: canonical.main_agent_mode,
145
+ default_effort: canonical.execution.default_effort,
146
+ default_timeout_seconds: canonical.execution.default_timeout_seconds,
147
+ mode: canonical.execution.mode,
148
+ max_parallel: canonical.execution.max_parallel,
149
+ isolation: canonical.execution.isolation,
150
+ collaboration_mode: routing.collaboration_mode,
151
+ tier_policy: routing.tier_policy,
152
+ flash_state: routing.flash_state,
153
+ pro_state: routing.pro_state,
154
+ worker_state: canonical.worker.state,
155
+ review_state: canonical.review.state,
156
+ auto_review: canonical.review.auto_review === true,
157
+ worker_provider_mode: canonical.worker.provider_mode,
158
+ flash_model_priority: [...canonical.worker.model_policy.priority],
159
+ flash_model_priority_configured: canonical.worker.model_policy.priorityConfigured,
160
+ flash_model_fallback: canonical.worker.model_policy.fallback,
161
+ pro_model_priority: [...pro.priority],
162
+ pro_model_priority_configured: pro.configured,
163
+ pro_model_fallback: pro.fallback,
164
+ escalate_on_failure: canonical.worker.model_policy.escalation.enabled,
165
+ pro_reviews_flash: canonical.review.auto_review === true,
166
+ execution: canonical.execution,
167
+ worker: canonical.worker,
168
+ review: canonical.review,
169
+ legacy: canonical.legacy,
170
+ };
171
+ }
172
+
173
+ /**
174
+ * v0.3 model-policy view. The frozen v0.2 resolver remains authoritative for
175
+ * every existing dimension. This facade only adds the normalized opt-in
176
+ * adaptive sub-domain, so direct canonical-ish v0.2 callers retain the exact
177
+ * priority/escalation semantics they had before schema-v3 existed.
178
+ */
179
+ export function resolveModelPolicy(config = {}, role = 'worker', context = {}) {
180
+ const base = legacy.resolveModelPolicy(config, role, context);
181
+ const rawPolicy = role === 'reviewer'
182
+ ? config?.review?.model_policy
183
+ : config?.worker?.model_policy;
184
+ return {
185
+ ...base,
186
+ adaptive: normalizeAdaptiveRouting(rawPolicy?.adaptive ?? base.adaptive),
187
+ };
188
+ }
189
+
190
+ /** Explicit legacy-import normalizer for the persistence layer. */
191
+ export function normalizeLegacyGlobalConfig(raw = {}) {
192
+ return legacy.normalizeGlobalConfig(raw);
193
+ }
194
+
195
+ export function configHasCanonicalAuthority(raw = {}) {
196
+ return hasCanonicalAuthority(raw);
197
+ }