@ran-sh/dsh-crew 1.9.0 → 1.10.0

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 (151) hide show
  1. package/.claude-plugin/marketplace.json +16 -16
  2. package/.claude-plugin/plugin.json +14 -14
  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 +126 -126
  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 +116 -116
  19. package/agents/ds-flash.md +24 -24
  20. package/agents/ds-pro.md +24 -24
  21. package/agents/ds-reviewer.md +23 -23
  22. package/agents/ds-worker.md +23 -23
  23. package/bin/dsh-crew.mjs +16 -16
  24. package/codex/agents/ds-flash.toml +34 -34
  25. package/codex/agents/ds-pro.toml +34 -34
  26. package/codex/agents/ds-reviewer.toml +32 -32
  27. package/codex/agents/ds-worker.toml +32 -32
  28. package/codex/prompts/dsh-config.md +19 -19
  29. package/codex/prompts/dsh-status.md +5 -5
  30. package/commands/config.md +23 -23
  31. package/commands/off.md +5 -5
  32. package/commands/on.md +5 -5
  33. package/commands/status.md +9 -9
  34. package/cordis.patch.yml +4 -4
  35. package/docs/gpt-relay-extension.md +103 -103
  36. package/docs/installation.md +138 -138
  37. package/docs/job-contracts.md +103 -103
  38. package/docs/readiness-matrix.md +85 -85
  39. package/docs/ui-surfaces.md +107 -107
  40. package/official-web-bridge/cordis.patch.yml +4 -4
  41. package/official-web-bridge/entry.mjs +1 -1
  42. package/official-web-bridge/overlay-entry.mjs +59 -59
  43. package/official-web-bridge/package.json +25 -25
  44. package/package.json +3 -2
  45. package/scripts/build-client.mjs +49 -49
  46. package/scripts/live-crew-smoke.mjs +39 -39
  47. package/scripts/live-policy-matrix.mjs +177 -177
  48. package/scripts/policy-probe.mjs +101 -101
  49. package/scripts/remove-legacy-official-bridge.ps1 +89 -89
  50. package/scripts/setup.mjs +393 -393
  51. package/scripts/smoke-real.mjs +110 -110
  52. package/scripts/smoke.mjs +78 -78
  53. package/scripts/verify-crew-ui-polish.mjs +145 -145
  54. package/scripts/verify-history-ui.mjs +97 -97
  55. package/scripts/verify-installer-fix.mjs +26 -26
  56. package/scripts/verify-npm-install.mjs +311 -311
  57. package/scripts/verify-official-bridge-e2e.mjs +192 -192
  58. package/src/adaptive-routing.mjs +260 -260
  59. package/src/client/activation-summary.tsx +64 -64
  60. package/src/client/collapsible-sections.mjs +55 -55
  61. package/src/client/history-panel.tsx +108 -108
  62. package/src/client/host-readiness.mjs +71 -71
  63. package/src/client/index.tsx +1711 -1711
  64. package/src/client/model-callability-view.mjs +17 -17
  65. package/src/client/panel-chrome.tsx +40 -40
  66. package/src/client/quick-entry.tsx +10 -10
  67. package/src/client/quick-panel.tsx +275 -275
  68. package/src/client/readiness-envelope.mjs +34 -34
  69. package/src/client/surface-detection.mjs +43 -43
  70. package/src/config-readiness.mjs +226 -226
  71. package/src/credential-reference.mjs +38 -38
  72. package/src/delivery.mjs +205 -205
  73. package/src/dsh-cli-runtime.mjs +1021 -1021
  74. package/src/dsh-cohort.mjs +20 -20
  75. package/src/extension-contract.mjs +104 -104
  76. package/src/failure-classification.mjs +201 -201
  77. package/src/history/admission-gate.mjs +67 -67
  78. package/src/history/archive-store.mjs +272 -272
  79. package/src/history/cleanup-plan.mjs +89 -89
  80. package/src/history/http.mjs +32 -32
  81. package/src/history/operation.mjs +86 -86
  82. package/src/history/runner-detach.mjs +34 -34
  83. package/src/history/runner.mjs +52 -52
  84. package/src/history/runtime.mjs +36 -36
  85. package/src/history/service.mjs +177 -177
  86. package/src/history/state.mjs +27 -27
  87. package/src/hub/entry.mjs +104 -104
  88. package/src/hub/index.mjs +2694 -2694
  89. package/src/hub-client.mjs +154 -154
  90. package/src/hub-compatibility.mjs +42 -42
  91. package/src/i18n.mjs +19 -19
  92. package/src/information-flow.mjs +67 -67
  93. package/src/install/cli.mjs +28 -28
  94. package/src/install/install-legacy.mjs +711 -711
  95. package/src/install/install.mjs +483 -483
  96. package/src/install/npx-lifecycle.mjs +3456 -3456
  97. package/src/install/official-frontend-assets.mjs +78 -78
  98. package/src/install/official-web.mjs +95 -95
  99. package/src/install/payload-content.mjs +88 -88
  100. package/src/install/windows-startup.mjs +236 -236
  101. package/src/install/windows-supervisor-adapter.mjs +443 -443
  102. package/src/install/windows-supervisor-lifecycle.mjs +782 -782
  103. package/src/install/zcode.mjs +397 -397
  104. package/src/job-contracts.mjs +255 -255
  105. package/src/local-request-guard.mjs +60 -60
  106. package/src/mcp-runtime.mjs +340 -340
  107. package/src/model-callability-contract.mjs +79 -79
  108. package/src/model-catalog.mjs +180 -180
  109. package/src/model-routing.mjs +586 -586
  110. package/src/model-schedule.mjs +207 -207
  111. package/src/official-web-bridge.mjs +447 -447
  112. package/src/policy.mjs +235 -235
  113. package/src/provider-delete-adapters.mjs +1934 -1934
  114. package/src/provider-health.mjs +130 -130
  115. package/src/provider-inventory.mjs +182 -182
  116. package/src/provider-layer-migration-adapters.mjs +759 -759
  117. package/src/provider-layer-migration.mjs +198 -198
  118. package/src/provider-lifecycle-state.mjs +103 -103
  119. package/src/provider-lifecycle.mjs +252 -252
  120. package/src/provider-profile-store.mjs +390 -390
  121. package/src/provider-settings-store.mjs +633 -633
  122. package/src/provider-store-lock.mjs +67 -67
  123. package/src/readiness-matrix.mjs +181 -181
  124. package/src/removable-waiter.mjs +29 -29
  125. package/src/role-profiles.mjs +107 -107
  126. package/src/runtime-controls.mjs +84 -84
  127. package/src/runtime-identity-contract.mjs +34 -34
  128. package/src/runtime-identity.mjs +235 -235
  129. package/src/runtime-readiness-snapshot.mjs +285 -285
  130. package/src/server.mjs +581 -581
  131. package/src/session-origins.mjs +60 -60
  132. package/src/standalone-sdk.mjs +23 -23
  133. package/src/status-shard.mjs +63 -63
  134. package/src/structured-error-code.mjs +38 -38
  135. package/src/supervisor/restart-request.mjs +256 -256
  136. package/src/workflow-runtime.mjs +739 -739
  137. package/src/workflow.mjs +155 -155
  138. package/src/workspace-audit.mjs +231 -231
  139. package/src/workspace-context.mjs +146 -146
  140. package/src/workspace-isolation.mjs +463 -455
  141. package/src/workspace-readiness.mjs +32 -32
  142. package/statusline/statusline.sh +14 -14
  143. package/statusline/worker-segment.sh +35 -35
  144. package/windows/start-dsh-crew.cmd +57 -57
  145. package/windows/start-dsh-crew.ps1 +1302 -1302
  146. package/windows/supervisor-control.ps1 +467 -467
  147. package/worker.cordis.yml +67 -67
  148. package/zcode/agents/ds-reviewer.md +31 -31
  149. package/zcode/agents/ds-worker.md +31 -31
  150. package/zcode/commands/dsh-config.md +17 -17
  151. package/zcode/commands/dsh-status.md +5 -5
@@ -1,285 +1,285 @@
1
- // Single, bounded readiness projection shared by the Hub extension surface,
2
- // MCP diagnostics and the client. It consumes already-collected evidence and
3
- // never performs I/O or carries raw task/result/error/credential content.
4
-
5
- import { isCompleteRuntimeIdentity, isExactNativeCrewIdentity, sameCompleteRuntimeIdentity } from './runtime-identity-contract.mjs';
6
- import { MODEL_CALLABILITY_SCHEMA_VERSION, validateModelCallabilityV2 } from './model-callability-contract.mjs';
7
-
8
- const MAX_HEALTH = 128;
9
- const DEFAULT_EXECUTION_EVIDENCE_TTL_MS = 5 * 60 * 1000;
10
- const MIN_EXECUTION_EVIDENCE_TTL_MS = 1_000;
11
- const MAX_EXECUTION_EVIDENCE_TTL_MS = 24 * 60 * 60 * 1000;
12
-
13
- function text(value) { return typeof value === 'string' && value.trim() ? value.trim() : null; }
14
-
15
- function projectRuntime(runtime) {
16
- if (!runtime || typeof runtime !== 'object') return null;
17
- return {
18
- execution_plane: text(runtime.execution_plane),
19
- profile: text(runtime.profile),
20
- listen_port: Number.isInteger(runtime.listen_port) ? runtime.listen_port : null,
21
- runtime_id: text(runtime.runtime_id),
22
- };
23
- }
24
-
25
- function runtimeIdentity(runtime) {
26
- return isExactNativeCrewIdentity(runtime)
27
- ? {
28
- execution_plane: runtime.execution_plane,
29
- profile: runtime.profile,
30
- listen_port: runtime.listen_port,
31
- runtime_id: runtime.runtime_id,
32
- }
33
- : null;
34
- }
35
-
36
- function projectSelection(value) {
37
- if (!value || typeof value !== 'object') return null;
38
- const provider = text(value.provider);
39
- const model = text(value.model);
40
- if (!provider || !model) return null;
41
- return { provider, model, ...(text(value.source) ? { source: text(value.source) } : {}) };
42
- }
43
-
44
- function projectHealth(entry) {
45
- if (!entry || typeof entry !== 'object') return null;
46
- const provider = text(entry.provider);
47
- const model = text(entry.model);
48
- const state = text(entry.state);
49
- if (!provider || !model || !state) return null;
50
- return {
51
- provider,
52
- model,
53
- state,
54
- ...(text(entry.reason_code) ? { reason_code: text(entry.reason_code) } : {}),
55
- ...(Number.isFinite(entry.observed_at) ? { observed_at: entry.observed_at } : {}),
56
- ...(Number.isFinite(entry.expires_at) ? { expires_at: entry.expires_at } : {}),
57
- fresh: entry.fresh === true,
58
- };
59
- }
60
-
61
- function matrixRow(matrix, id) {
62
- return Array.isArray(matrix?.rows) ? matrix.rows.find((row) => row?.id === id) ?? null : null;
63
- }
64
-
65
- function projectWorkspace(workspace) {
66
- if (!workspace || typeof workspace !== 'object') return null;
67
- return {
68
- ...(text(workspace.status) ? { status: text(workspace.status) } : {}),
69
- ...(text(workspace.reason_code) ? { reason_code: text(workspace.reason_code) } : {}),
70
- };
71
- }
72
-
73
- function routeKey(value) {
74
- return value?.provider && value?.model ? `${value.provider}\u0000${value.model}` : null;
75
- }
76
-
77
- function normalizeExecutionEvidenceTtl(value) {
78
- const parsed = Number(value);
79
- if (!Number.isFinite(parsed) || parsed < MIN_EXECUTION_EVIDENCE_TTL_MS) return DEFAULT_EXECUTION_EVIDENCE_TTL_MS;
80
- return Math.min(Math.floor(parsed), MAX_EXECUTION_EVIDENCE_TTL_MS);
81
- }
82
-
83
- function projectModelRole({ role, selected, health, jobs, runtime, now, executionEvidenceTtlMs, enabled }) {
84
- if (enabled === false) return { state: 'NOT_APPLICABLE', reason_code: 'ROLE_DISABLED', selected: selected ?? null, last_success: null };
85
- const route = routeKey(selected);
86
- if (!route || !isExactNativeCrewIdentity(runtime)) return { state: 'UNKNOWN', reason_code: 'MODEL_ROUTE_UNAVAILABLE', selected: selected ?? null, last_success: null };
87
- const matchingHealth = (Array.isArray(health) ? health : [])
88
- .filter((entry) => routeKey(entry) === route)
89
- .sort((left, right) => {
90
- const observedDelta = (Number(right?.observed_at) || 0) - (Number(left?.observed_at) || 0);
91
- if (observedDelta !== 0) return observedDelta;
92
- if (left?.state === 'callable' && right?.state !== 'callable') return 1;
93
- if (left?.state !== 'callable' && right?.state === 'callable') return -1;
94
- return 0;
95
- })[0];
96
- const expiresAt = Number.isFinite(matchingHealth?.expires_at) ? matchingHealth.expires_at : null;
97
- const observedAt = Number.isFinite(matchingHealth?.observed_at) ? matchingHealth.observed_at : null;
98
- if (matchingHealth) {
99
- if (observedAt === null || observedAt > now || expiresAt === null || expiresAt <= now
100
- || expiresAt - observedAt > MAX_EXECUTION_EVIDENCE_TTL_MS) {
101
- return { state: 'STALE', reason_code: 'PROVIDER_HEALTH_STALE_OR_INVALID', selected, observed_at: observedAt, expires_at: expiresAt, source: 'provider_health', last_success: null };
102
- }
103
- }
104
- const healthCurrent = matchingHealth && matchingHealth.fresh === true;
105
- if (healthCurrent && matchingHealth.state !== 'callable') {
106
- return { state: 'NOT_CALLABLE', reason_code: matchingHealth.reason_code ?? 'PROVIDER_ROUTE_UNCALLABLE', selected, observed_at: matchingHealth.observed_at ?? null, expires_at: expiresAt, source: 'provider_health', last_success: null };
107
- }
108
- if (healthCurrent && matchingHealth.state === 'callable') {
109
- return { state: 'CALLABLE', reason_code: matchingHealth.reason_code ?? 'PROVIDER_CALLABLE', selected, observed_at: matchingHealth.observed_at ?? null, expires_at: expiresAt, source: 'provider_health', last_success: null };
110
- }
111
- const completed = (Array.isArray(jobs) ? jobs : [])
112
- .filter((job) => job?.role === role && job?.provider === selected.provider && job?.model === selected.model
113
- && job?.status === 'done' && job?.task_status === 'success'
114
- && sameCompleteRuntimeIdentity(job.execution_context, runtime))
115
- .map((job) => ({ job, endedAt: Date.parse(job.endedAt ?? '') }))
116
- .filter(({ endedAt }) => Number.isFinite(endedAt))
117
- .sort((a, b) => b.endedAt - a.endedAt)[0];
118
- if (completed) {
119
- const expires = completed.endedAt + executionEvidenceTtlMs;
120
- const lastSuccess = { observed_at: completed.endedAt, expires_at: expires, job_id: completed.job.id };
121
- if (completed.endedAt > now) return { state: 'STALE', reason_code: 'EXECUTION_EVIDENCE_FUTURE_DATED', selected, observed_at: completed.endedAt, expires_at: expires, source: 'execution', last_success: lastSuccess };
122
- if (expires > now) return { state: 'CALLABLE', reason_code: 'RECENT_EXECUTION_PASSED', selected, observed_at: completed.endedAt, expires_at: expires, source: 'execution', last_success: lastSuccess };
123
- return { state: 'STALE', reason_code: 'EXECUTION_EVIDENCE_EXPIRED', selected, observed_at: completed.endedAt, expires_at: expires, source: 'execution', last_success: lastSuccess };
124
- }
125
- return { state: 'UNKNOWN', reason_code: 'NO_CURRENT_MODEL_EVIDENCE', selected, last_success: null };
126
- }
127
-
128
- export function projectModelCallability({ runtime = null, selections = {}, health = [], health_status = 'AVAILABLE', jobs = [], now = Date.now(), execution_evidence_ttl_ms = DEFAULT_EXECUTION_EVIDENCE_TTL_MS, enabled_roles = {} } = {}) {
129
- const ttl = normalizeExecutionEvidenceTtl(execution_evidence_ttl_ms);
130
- const enabledRoles = {
131
- worker: enabled_roles?.worker !== false,
132
- reviewer: enabled_roles?.reviewer !== false,
133
- };
134
- const roles = {
135
- worker: projectModelRole({ role: 'worker', selected: selections.worker ?? selections.flash, health, jobs, runtime, now, executionEvidenceTtlMs: ttl, enabled: enabledRoles.worker }),
136
- reviewer: projectModelRole({ role: 'reviewer', selected: selections.reviewer ?? selections.pro, health, jobs, runtime, now, executionEvidenceTtlMs: ttl, enabled: enabledRoles.reviewer }),
137
- };
138
- if (health_status !== 'AVAILABLE') {
139
- for (const [name, enabled] of Object.entries(enabledRoles)) {
140
- if (enabled) roles[name] = { ...roles[name], state: 'UNKNOWN', reason_code: 'PROVIDER_HEALTH_UNAVAILABLE', source: 'provider_health' };
141
- }
142
- }
143
- const states = Object.entries(roles).filter(([name]) => enabledRoles[name]).map(([, role]) => role.state);
144
- const overall = states.length === 0 ? 'UNKNOWN'
145
- : states.includes('NOT_CALLABLE') ? 'NOT_CALLABLE'
146
- : states.every((state) => state === 'CALLABLE') ? 'CALLABLE'
147
- : states.some((state) => state === 'STALE') ? 'STALE' : 'UNKNOWN';
148
- const expirations = Object.values(roles)
149
- .map((role) => role?.expires_at)
150
- .filter((value) => Number.isFinite(value));
151
- return {
152
- schema_version: MODEL_CALLABILITY_SCHEMA_VERSION,
153
- captured_at: now,
154
- expires_at: expirations.length ? Math.min(...expirations) : null,
155
- current_runtime_id: runtime?.runtime_id ?? null,
156
- runtime_identity: runtimeIdentity(runtime),
157
- execution_evidence_ttl_ms: ttl,
158
- enabled_roles: enabledRoles,
159
- overall,
160
- roles,
161
- };
162
- }
163
-
164
- export function buildRuntimeReadinessSnapshot({
165
- runtime = null,
166
- readinessMatrix = null,
167
- selections = {},
168
- health = [],
169
- health_status = null,
170
- jobs = [],
171
- workspace = null,
172
- enabled_roles = {},
173
- now = Date.now(),
174
- } = {}) {
175
- const healthObservations = Array.isArray(health) ? health : (Array.isArray(health?.observations) ? health.observations : []);
176
- const resolvedHealthStatus = health_status
177
- ?? (health && !Array.isArray(health) ? health.status : null)
178
- ?? (Array.isArray(health) && health.length > 0 ? 'AVAILABLE' : 'UNKNOWN');
179
- const projectedHealthAll = healthObservations.map(projectHealth).filter(Boolean);
180
- const projectedJobs = Array.isArray(jobs) ? jobs : [];
181
- const verified = projectedJobs.filter((job) => job?.status === 'done' && job?.task_status === 'success' && job?.delivery_complete === true).length;
182
- const workerJobs = projectedJobs.filter((job) => job?.role === 'worker').length;
183
- const reviewerJobs = projectedJobs.filter((job) => job?.role === 'reviewer').length;
184
- const workerSelection = projectSelection(selections.worker ?? selections.flash);
185
- const reviewerSelection = projectSelection(selections.reviewer ?? selections.pro);
186
- const selectedRoutes = [workerSelection, reviewerSelection].filter(Boolean);
187
- const selectedHealth = selectedRoutes.map((selection) => projectedHealthAll
188
- .filter((entry) => entry.provider === selection.provider && entry.model === selection.model)
189
- .sort((left, right) => (right.observed_at ?? 0) - (left.observed_at ?? 0))[0]).filter(Boolean);
190
- const selectedKeys = new Set(selectedHealth.map((entry) => `${entry.provider}\u0000${entry.model}`));
191
- const projectedHealth = [...selectedHealth, ...projectedHealthAll
192
- .filter((entry) => !selectedKeys.has(`${entry.provider}\u0000${entry.model}`))]
193
- .slice(0, MAX_HEALTH);
194
- const modelCallability = projectModelCallability({ runtime, selections: { worker: workerSelection, reviewer: reviewerSelection }, health: projectedHealthAll, health_status: resolvedHealthStatus, jobs: projectedJobs, enabled_roles, now });
195
- return {
196
- schema_version: 1,
197
- captured_at: now,
198
- expires_at: modelCallability.expires_at,
199
- health_status: resolvedHealthStatus,
200
- runtime: projectRuntime(runtime),
201
- runtime_identity: runtimeIdentity(runtime),
202
- readiness_matrix: readinessMatrix && typeof readinessMatrix === 'object' ? structuredClone(readinessMatrix) : null,
203
- provider_lifecycle: matrixRow(readinessMatrix, 'provider_lifecycle_consistent'),
204
- health: projectedHealth,
205
- worker: { selected: workerSelection, health: projectedHealth.filter((entry) => entry.provider === workerSelection?.provider && entry.model === workerSelection?.model) },
206
- reviewer: { selected: reviewerSelection, health: projectedHealth.filter((entry) => entry.provider === reviewerSelection?.provider && entry.model === reviewerSelection?.model) },
207
- historical_evidence: {
208
- job_count: projectedJobs.length,
209
- verified_job_count: verified,
210
- worker_job_count: workerJobs,
211
- reviewer_job_count: reviewerJobs,
212
- },
213
- workspace: projectWorkspace(workspace),
214
- model_callability: modelCallability,
215
- };
216
- }
217
-
218
- /** Re-project a Hub snapshot when the MCP session changes role enablement. */
219
- export function reprojectRuntimeModelCallability(snapshot, { enabled_roles = {}, now = Date.now() } = {}) {
220
- if (!snapshot || typeof snapshot !== 'object') return null;
221
- const sourceProjection = snapshot.model_callability;
222
- const sourceValidation = validateModelCallabilityV2({
223
- projection: sourceProjection,
224
- runtime: snapshot.runtime,
225
- expectedEnabledRoles: sourceProjection?.enabled_roles,
226
- expectedSelections: { worker: snapshot.worker?.selected ?? null, reviewer: snapshot.reviewer?.selected ?? null },
227
- now,
228
- });
229
- if (!sourceValidation.ok) {
230
- return projectModelCallability({
231
- runtime: snapshot.runtime,
232
- selections: { worker: snapshot.worker?.selected, reviewer: snapshot.reviewer?.selected },
233
- health: [],
234
- health_status: 'UNAVAILABLE',
235
- jobs: [],
236
- enabled_roles,
237
- now,
238
- });
239
- }
240
- const roles = {};
241
- for (const role of ['worker', 'reviewer']) {
242
- if (enabled_roles?.[role] === false) {
243
- roles[role] = { state: 'NOT_APPLICABLE', reason_code: 'ROLE_DISABLED', selected: null, last_success: null };
244
- } else if (sourceProjection.enabled_roles?.[role] === true) {
245
- roles[role] = structuredClone(sourceProjection.roles[role]);
246
- } else {
247
- roles[role] = { state: 'UNKNOWN', reason_code: 'ROLE_EVIDENCE_NOT_ENABLED', selected: snapshot[role]?.selected ?? null, last_success: null };
248
- }
249
- }
250
- const activeStates = Object.entries(roles).filter(([role]) => enabled_roles?.[role] === true).map(([, role]) => role.state);
251
- const overall = activeStates.includes('NOT_CALLABLE') ? 'NOT_CALLABLE'
252
- : activeStates.length > 0 && activeStates.every((state) => state === 'CALLABLE') ? 'CALLABLE'
253
- : activeStates.includes('STALE') ? 'STALE' : 'UNKNOWN';
254
- const expirations = Object.values(roles).map((role) => role?.expires_at).filter((value) => Number.isFinite(value));
255
- const projected = {
256
- ...structuredClone(sourceProjection),
257
- captured_at: now,
258
- enabled_roles: { worker: enabled_roles.worker === true, reviewer: enabled_roles.reviewer === true },
259
- roles,
260
- overall,
261
- expires_at: expirations.length ? Math.min(...expirations) : null,
262
- };
263
- const validation = validateModelCallabilityV2({
264
- projection: projected,
265
- runtime: snapshot.runtime,
266
- expectedEnabledRoles: projected.enabled_roles,
267
- expectedSelections: {
268
- worker: enabled_roles.worker === true ? snapshot.worker?.selected ?? null : null,
269
- reviewer: enabled_roles.reviewer === true ? snapshot.reviewer?.selected ?? null : null,
270
- },
271
- now,
272
- });
273
- if (!validation.ok) {
274
- return projectModelCallability({
275
- runtime: snapshot.runtime,
276
- selections: { worker: snapshot.worker?.selected, reviewer: snapshot.reviewer?.selected },
277
- health: [],
278
- health_status: 'UNAVAILABLE',
279
- jobs: [],
280
- enabled_roles,
281
- now,
282
- });
283
- }
284
- return projected;
285
- }
1
+ // Single, bounded readiness projection shared by the Hub extension surface,
2
+ // MCP diagnostics and the client. It consumes already-collected evidence and
3
+ // never performs I/O or carries raw task/result/error/credential content.
4
+
5
+ import { isCompleteRuntimeIdentity, isExactNativeCrewIdentity, sameCompleteRuntimeIdentity } from './runtime-identity-contract.mjs';
6
+ import { MODEL_CALLABILITY_SCHEMA_VERSION, validateModelCallabilityV2 } from './model-callability-contract.mjs';
7
+
8
+ const MAX_HEALTH = 128;
9
+ const DEFAULT_EXECUTION_EVIDENCE_TTL_MS = 5 * 60 * 1000;
10
+ const MIN_EXECUTION_EVIDENCE_TTL_MS = 1_000;
11
+ const MAX_EXECUTION_EVIDENCE_TTL_MS = 24 * 60 * 60 * 1000;
12
+
13
+ function text(value) { return typeof value === 'string' && value.trim() ? value.trim() : null; }
14
+
15
+ function projectRuntime(runtime) {
16
+ if (!runtime || typeof runtime !== 'object') return null;
17
+ return {
18
+ execution_plane: text(runtime.execution_plane),
19
+ profile: text(runtime.profile),
20
+ listen_port: Number.isInteger(runtime.listen_port) ? runtime.listen_port : null,
21
+ runtime_id: text(runtime.runtime_id),
22
+ };
23
+ }
24
+
25
+ function runtimeIdentity(runtime) {
26
+ return isExactNativeCrewIdentity(runtime)
27
+ ? {
28
+ execution_plane: runtime.execution_plane,
29
+ profile: runtime.profile,
30
+ listen_port: runtime.listen_port,
31
+ runtime_id: runtime.runtime_id,
32
+ }
33
+ : null;
34
+ }
35
+
36
+ function projectSelection(value) {
37
+ if (!value || typeof value !== 'object') return null;
38
+ const provider = text(value.provider);
39
+ const model = text(value.model);
40
+ if (!provider || !model) return null;
41
+ return { provider, model, ...(text(value.source) ? { source: text(value.source) } : {}) };
42
+ }
43
+
44
+ function projectHealth(entry) {
45
+ if (!entry || typeof entry !== 'object') return null;
46
+ const provider = text(entry.provider);
47
+ const model = text(entry.model);
48
+ const state = text(entry.state);
49
+ if (!provider || !model || !state) return null;
50
+ return {
51
+ provider,
52
+ model,
53
+ state,
54
+ ...(text(entry.reason_code) ? { reason_code: text(entry.reason_code) } : {}),
55
+ ...(Number.isFinite(entry.observed_at) ? { observed_at: entry.observed_at } : {}),
56
+ ...(Number.isFinite(entry.expires_at) ? { expires_at: entry.expires_at } : {}),
57
+ fresh: entry.fresh === true,
58
+ };
59
+ }
60
+
61
+ function matrixRow(matrix, id) {
62
+ return Array.isArray(matrix?.rows) ? matrix.rows.find((row) => row?.id === id) ?? null : null;
63
+ }
64
+
65
+ function projectWorkspace(workspace) {
66
+ if (!workspace || typeof workspace !== 'object') return null;
67
+ return {
68
+ ...(text(workspace.status) ? { status: text(workspace.status) } : {}),
69
+ ...(text(workspace.reason_code) ? { reason_code: text(workspace.reason_code) } : {}),
70
+ };
71
+ }
72
+
73
+ function routeKey(value) {
74
+ return value?.provider && value?.model ? `${value.provider}\u0000${value.model}` : null;
75
+ }
76
+
77
+ function normalizeExecutionEvidenceTtl(value) {
78
+ const parsed = Number(value);
79
+ if (!Number.isFinite(parsed) || parsed < MIN_EXECUTION_EVIDENCE_TTL_MS) return DEFAULT_EXECUTION_EVIDENCE_TTL_MS;
80
+ return Math.min(Math.floor(parsed), MAX_EXECUTION_EVIDENCE_TTL_MS);
81
+ }
82
+
83
+ function projectModelRole({ role, selected, health, jobs, runtime, now, executionEvidenceTtlMs, enabled }) {
84
+ if (enabled === false) return { state: 'NOT_APPLICABLE', reason_code: 'ROLE_DISABLED', selected: selected ?? null, last_success: null };
85
+ const route = routeKey(selected);
86
+ if (!route || !isExactNativeCrewIdentity(runtime)) return { state: 'UNKNOWN', reason_code: 'MODEL_ROUTE_UNAVAILABLE', selected: selected ?? null, last_success: null };
87
+ const matchingHealth = (Array.isArray(health) ? health : [])
88
+ .filter((entry) => routeKey(entry) === route)
89
+ .sort((left, right) => {
90
+ const observedDelta = (Number(right?.observed_at) || 0) - (Number(left?.observed_at) || 0);
91
+ if (observedDelta !== 0) return observedDelta;
92
+ if (left?.state === 'callable' && right?.state !== 'callable') return 1;
93
+ if (left?.state !== 'callable' && right?.state === 'callable') return -1;
94
+ return 0;
95
+ })[0];
96
+ const expiresAt = Number.isFinite(matchingHealth?.expires_at) ? matchingHealth.expires_at : null;
97
+ const observedAt = Number.isFinite(matchingHealth?.observed_at) ? matchingHealth.observed_at : null;
98
+ if (matchingHealth) {
99
+ if (observedAt === null || observedAt > now || expiresAt === null || expiresAt <= now
100
+ || expiresAt - observedAt > MAX_EXECUTION_EVIDENCE_TTL_MS) {
101
+ return { state: 'STALE', reason_code: 'PROVIDER_HEALTH_STALE_OR_INVALID', selected, observed_at: observedAt, expires_at: expiresAt, source: 'provider_health', last_success: null };
102
+ }
103
+ }
104
+ const healthCurrent = matchingHealth && matchingHealth.fresh === true;
105
+ if (healthCurrent && matchingHealth.state !== 'callable') {
106
+ return { state: 'NOT_CALLABLE', reason_code: matchingHealth.reason_code ?? 'PROVIDER_ROUTE_UNCALLABLE', selected, observed_at: matchingHealth.observed_at ?? null, expires_at: expiresAt, source: 'provider_health', last_success: null };
107
+ }
108
+ if (healthCurrent && matchingHealth.state === 'callable') {
109
+ return { state: 'CALLABLE', reason_code: matchingHealth.reason_code ?? 'PROVIDER_CALLABLE', selected, observed_at: matchingHealth.observed_at ?? null, expires_at: expiresAt, source: 'provider_health', last_success: null };
110
+ }
111
+ const completed = (Array.isArray(jobs) ? jobs : [])
112
+ .filter((job) => job?.role === role && job?.provider === selected.provider && job?.model === selected.model
113
+ && job?.status === 'done' && job?.task_status === 'success'
114
+ && sameCompleteRuntimeIdentity(job.execution_context, runtime))
115
+ .map((job) => ({ job, endedAt: Date.parse(job.endedAt ?? '') }))
116
+ .filter(({ endedAt }) => Number.isFinite(endedAt))
117
+ .sort((a, b) => b.endedAt - a.endedAt)[0];
118
+ if (completed) {
119
+ const expires = completed.endedAt + executionEvidenceTtlMs;
120
+ const lastSuccess = { observed_at: completed.endedAt, expires_at: expires, job_id: completed.job.id };
121
+ if (completed.endedAt > now) return { state: 'STALE', reason_code: 'EXECUTION_EVIDENCE_FUTURE_DATED', selected, observed_at: completed.endedAt, expires_at: expires, source: 'execution', last_success: lastSuccess };
122
+ if (expires > now) return { state: 'CALLABLE', reason_code: 'RECENT_EXECUTION_PASSED', selected, observed_at: completed.endedAt, expires_at: expires, source: 'execution', last_success: lastSuccess };
123
+ return { state: 'STALE', reason_code: 'EXECUTION_EVIDENCE_EXPIRED', selected, observed_at: completed.endedAt, expires_at: expires, source: 'execution', last_success: lastSuccess };
124
+ }
125
+ return { state: 'UNKNOWN', reason_code: 'NO_CURRENT_MODEL_EVIDENCE', selected, last_success: null };
126
+ }
127
+
128
+ export function projectModelCallability({ runtime = null, selections = {}, health = [], health_status = 'AVAILABLE', jobs = [], now = Date.now(), execution_evidence_ttl_ms = DEFAULT_EXECUTION_EVIDENCE_TTL_MS, enabled_roles = {} } = {}) {
129
+ const ttl = normalizeExecutionEvidenceTtl(execution_evidence_ttl_ms);
130
+ const enabledRoles = {
131
+ worker: enabled_roles?.worker !== false,
132
+ reviewer: enabled_roles?.reviewer !== false,
133
+ };
134
+ const roles = {
135
+ worker: projectModelRole({ role: 'worker', selected: selections.worker ?? selections.flash, health, jobs, runtime, now, executionEvidenceTtlMs: ttl, enabled: enabledRoles.worker }),
136
+ reviewer: projectModelRole({ role: 'reviewer', selected: selections.reviewer ?? selections.pro, health, jobs, runtime, now, executionEvidenceTtlMs: ttl, enabled: enabledRoles.reviewer }),
137
+ };
138
+ if (health_status !== 'AVAILABLE') {
139
+ for (const [name, enabled] of Object.entries(enabledRoles)) {
140
+ if (enabled) roles[name] = { ...roles[name], state: 'UNKNOWN', reason_code: 'PROVIDER_HEALTH_UNAVAILABLE', source: 'provider_health' };
141
+ }
142
+ }
143
+ const states = Object.entries(roles).filter(([name]) => enabledRoles[name]).map(([, role]) => role.state);
144
+ const overall = states.length === 0 ? 'UNKNOWN'
145
+ : states.includes('NOT_CALLABLE') ? 'NOT_CALLABLE'
146
+ : states.every((state) => state === 'CALLABLE') ? 'CALLABLE'
147
+ : states.some((state) => state === 'STALE') ? 'STALE' : 'UNKNOWN';
148
+ const expirations = Object.values(roles)
149
+ .map((role) => role?.expires_at)
150
+ .filter((value) => Number.isFinite(value));
151
+ return {
152
+ schema_version: MODEL_CALLABILITY_SCHEMA_VERSION,
153
+ captured_at: now,
154
+ expires_at: expirations.length ? Math.min(...expirations) : null,
155
+ current_runtime_id: runtime?.runtime_id ?? null,
156
+ runtime_identity: runtimeIdentity(runtime),
157
+ execution_evidence_ttl_ms: ttl,
158
+ enabled_roles: enabledRoles,
159
+ overall,
160
+ roles,
161
+ };
162
+ }
163
+
164
+ export function buildRuntimeReadinessSnapshot({
165
+ runtime = null,
166
+ readinessMatrix = null,
167
+ selections = {},
168
+ health = [],
169
+ health_status = null,
170
+ jobs = [],
171
+ workspace = null,
172
+ enabled_roles = {},
173
+ now = Date.now(),
174
+ } = {}) {
175
+ const healthObservations = Array.isArray(health) ? health : (Array.isArray(health?.observations) ? health.observations : []);
176
+ const resolvedHealthStatus = health_status
177
+ ?? (health && !Array.isArray(health) ? health.status : null)
178
+ ?? (Array.isArray(health) && health.length > 0 ? 'AVAILABLE' : 'UNKNOWN');
179
+ const projectedHealthAll = healthObservations.map(projectHealth).filter(Boolean);
180
+ const projectedJobs = Array.isArray(jobs) ? jobs : [];
181
+ const verified = projectedJobs.filter((job) => job?.status === 'done' && job?.task_status === 'success' && job?.delivery_complete === true).length;
182
+ const workerJobs = projectedJobs.filter((job) => job?.role === 'worker').length;
183
+ const reviewerJobs = projectedJobs.filter((job) => job?.role === 'reviewer').length;
184
+ const workerSelection = projectSelection(selections.worker ?? selections.flash);
185
+ const reviewerSelection = projectSelection(selections.reviewer ?? selections.pro);
186
+ const selectedRoutes = [workerSelection, reviewerSelection].filter(Boolean);
187
+ const selectedHealth = selectedRoutes.map((selection) => projectedHealthAll
188
+ .filter((entry) => entry.provider === selection.provider && entry.model === selection.model)
189
+ .sort((left, right) => (right.observed_at ?? 0) - (left.observed_at ?? 0))[0]).filter(Boolean);
190
+ const selectedKeys = new Set(selectedHealth.map((entry) => `${entry.provider}\u0000${entry.model}`));
191
+ const projectedHealth = [...selectedHealth, ...projectedHealthAll
192
+ .filter((entry) => !selectedKeys.has(`${entry.provider}\u0000${entry.model}`))]
193
+ .slice(0, MAX_HEALTH);
194
+ const modelCallability = projectModelCallability({ runtime, selections: { worker: workerSelection, reviewer: reviewerSelection }, health: projectedHealthAll, health_status: resolvedHealthStatus, jobs: projectedJobs, enabled_roles, now });
195
+ return {
196
+ schema_version: 1,
197
+ captured_at: now,
198
+ expires_at: modelCallability.expires_at,
199
+ health_status: resolvedHealthStatus,
200
+ runtime: projectRuntime(runtime),
201
+ runtime_identity: runtimeIdentity(runtime),
202
+ readiness_matrix: readinessMatrix && typeof readinessMatrix === 'object' ? structuredClone(readinessMatrix) : null,
203
+ provider_lifecycle: matrixRow(readinessMatrix, 'provider_lifecycle_consistent'),
204
+ health: projectedHealth,
205
+ worker: { selected: workerSelection, health: projectedHealth.filter((entry) => entry.provider === workerSelection?.provider && entry.model === workerSelection?.model) },
206
+ reviewer: { selected: reviewerSelection, health: projectedHealth.filter((entry) => entry.provider === reviewerSelection?.provider && entry.model === reviewerSelection?.model) },
207
+ historical_evidence: {
208
+ job_count: projectedJobs.length,
209
+ verified_job_count: verified,
210
+ worker_job_count: workerJobs,
211
+ reviewer_job_count: reviewerJobs,
212
+ },
213
+ workspace: projectWorkspace(workspace),
214
+ model_callability: modelCallability,
215
+ };
216
+ }
217
+
218
+ /** Re-project a Hub snapshot when the MCP session changes role enablement. */
219
+ export function reprojectRuntimeModelCallability(snapshot, { enabled_roles = {}, now = Date.now() } = {}) {
220
+ if (!snapshot || typeof snapshot !== 'object') return null;
221
+ const sourceProjection = snapshot.model_callability;
222
+ const sourceValidation = validateModelCallabilityV2({
223
+ projection: sourceProjection,
224
+ runtime: snapshot.runtime,
225
+ expectedEnabledRoles: sourceProjection?.enabled_roles,
226
+ expectedSelections: { worker: snapshot.worker?.selected ?? null, reviewer: snapshot.reviewer?.selected ?? null },
227
+ now,
228
+ });
229
+ if (!sourceValidation.ok) {
230
+ return projectModelCallability({
231
+ runtime: snapshot.runtime,
232
+ selections: { worker: snapshot.worker?.selected, reviewer: snapshot.reviewer?.selected },
233
+ health: [],
234
+ health_status: 'UNAVAILABLE',
235
+ jobs: [],
236
+ enabled_roles,
237
+ now,
238
+ });
239
+ }
240
+ const roles = {};
241
+ for (const role of ['worker', 'reviewer']) {
242
+ if (enabled_roles?.[role] === false) {
243
+ roles[role] = { state: 'NOT_APPLICABLE', reason_code: 'ROLE_DISABLED', selected: null, last_success: null };
244
+ } else if (sourceProjection.enabled_roles?.[role] === true) {
245
+ roles[role] = structuredClone(sourceProjection.roles[role]);
246
+ } else {
247
+ roles[role] = { state: 'UNKNOWN', reason_code: 'ROLE_EVIDENCE_NOT_ENABLED', selected: snapshot[role]?.selected ?? null, last_success: null };
248
+ }
249
+ }
250
+ const activeStates = Object.entries(roles).filter(([role]) => enabled_roles?.[role] === true).map(([, role]) => role.state);
251
+ const overall = activeStates.includes('NOT_CALLABLE') ? 'NOT_CALLABLE'
252
+ : activeStates.length > 0 && activeStates.every((state) => state === 'CALLABLE') ? 'CALLABLE'
253
+ : activeStates.includes('STALE') ? 'STALE' : 'UNKNOWN';
254
+ const expirations = Object.values(roles).map((role) => role?.expires_at).filter((value) => Number.isFinite(value));
255
+ const projected = {
256
+ ...structuredClone(sourceProjection),
257
+ captured_at: now,
258
+ enabled_roles: { worker: enabled_roles.worker === true, reviewer: enabled_roles.reviewer === true },
259
+ roles,
260
+ overall,
261
+ expires_at: expirations.length ? Math.min(...expirations) : null,
262
+ };
263
+ const validation = validateModelCallabilityV2({
264
+ projection: projected,
265
+ runtime: snapshot.runtime,
266
+ expectedEnabledRoles: projected.enabled_roles,
267
+ expectedSelections: {
268
+ worker: enabled_roles.worker === true ? snapshot.worker?.selected ?? null : null,
269
+ reviewer: enabled_roles.reviewer === true ? snapshot.reviewer?.selected ?? null : null,
270
+ },
271
+ now,
272
+ });
273
+ if (!validation.ok) {
274
+ return projectModelCallability({
275
+ runtime: snapshot.runtime,
276
+ selections: { worker: snapshot.worker?.selected, reviewer: snapshot.reviewer?.selected },
277
+ health: [],
278
+ health_status: 'UNAVAILABLE',
279
+ jobs: [],
280
+ enabled_roles,
281
+ now,
282
+ });
283
+ }
284
+ return projected;
285
+ }