@ran-sh/dsh-crew 1.8.0 → 1.9.1

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 +1 -1
  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 -332
  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 +455 -401
  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,255 +1,255 @@
1
- // Versioned, transport-neutral contracts for one DSH Crew workflow.
2
- //
3
- // The workflow runtime may keep richer internal state for recovery and debug,
4
- // but callers receive this bounded event/evidence layer by default. Full
5
- // internal details remain available only through an explicit detail=full
6
- // request at the MCP boundary.
7
-
8
- export const JOB_CONTRACT_SCHEMA_VERSION = 1;
9
-
10
- export const JOB_EVENT_TYPES = Object.freeze([
11
- 'job.created',
12
- 'job.started',
13
- 'runtime.bound',
14
- 'model.selected',
15
- 'model.admitted',
16
- 'agent.created',
17
- 'model.fallback',
18
- 'worker.started',
19
- 'worker.completed',
20
- 'review.started',
21
- 'review.completed',
22
- 'approval.required',
23
- 'job.completed',
24
- 'job.failed',
25
- 'job.cancelled',
26
- ]);
27
-
28
- const EVENT_TYPE_SET = new Set(JOB_EVENT_TYPES);
29
- const RESULT_STATUSES = Object.freeze(['PASS', 'FAIL', 'PARTIAL', 'BLOCKED']);
30
-
31
- function boundedText(value, limit = 800) {
32
- if (value == null) return null;
33
- const text = String(value).trim();
34
- if (!text) return null;
35
- return text.length <= limit ? text : `${text.slice(0, limit)}…`;
36
- }
37
-
38
- function boundedStrings(values, { count = 80, length = 400 } = {}) {
39
- if (!Array.isArray(values)) return [];
40
- return values.slice(0, count)
41
- .map((value) => boundedText(value, length))
42
- .filter(Boolean);
43
- }
44
-
45
- function boundedTests(values) {
46
- if (!Array.isArray(values)) return [];
47
- return values.slice(0, 40).map((test) => ({
48
- status: RESULT_STATUSES.includes(test?.status) ? test.status : boundedText(test?.status, 40),
49
- command: boundedText(test?.command, 300),
50
- summary: boundedText(test?.summary, 500),
51
- }));
52
- }
53
-
54
- /** Create one canonical, monotonically sequenced workflow event. */
55
- export function createCanonicalJobEvent({
56
- jobId,
57
- type,
58
- sequence,
59
- at,
60
- role = null,
61
- attempt = null,
62
- data = {},
63
- } = {}) {
64
- if (!EVENT_TYPE_SET.has(type)) throw new Error(`unknown canonical job event: ${String(type)}`);
65
- if (typeof jobId !== 'string' || !jobId) throw new Error('canonical job event requires jobId');
66
- if (!Number.isInteger(sequence) || sequence < 1) throw new Error('canonical job event requires a positive sequence');
67
- return {
68
- schema_version: JOB_CONTRACT_SCHEMA_VERSION,
69
- event_id: `${jobId}:${sequence}`,
70
- job_id: jobId,
71
- sequence,
72
- type,
73
- at,
74
- role,
75
- attempt,
76
- data: data && typeof data === 'object' && !Array.isArray(data) ? { ...data } : {},
77
- };
78
- }
79
-
80
- function evidenceStatus(view) {
81
- if (view?.status === 'cancelled' || view?.phase === 'cancelled') return 'BLOCKED';
82
- if (view?.status === 'failed' || view?.phase === 'failed' || view?.outcome?.execution_status === 'failed') return 'FAIL';
83
- if (view?.review?.verdict === 'request_changes' || view?.outcome?.task_status === 'partial') return 'PARTIAL';
84
- if (view?.outcome?.task_status === 'blocked') return 'BLOCKED';
85
- if (view?.role === 'reviewer' && view?.outcome == null) {
86
- return view.status === 'done' && view.review?.status === 'done'
87
- && view.review.verdict === 'approve' && view.review.delivery_complete === true
88
- && view.review.mutated_candidate !== true ? 'PASS' : 'PARTIAL';
89
- }
90
- if (view?.status === 'done' && view?.outcome?.task_status === 'success') return 'PASS';
91
- return 'PARTIAL';
92
- }
93
-
94
- function compactSelectionTrace(attempts) {
95
- if (!Array.isArray(attempts)) return [];
96
- return attempts.slice(0, 16).map((attempt) => {
97
- const trace = attempt?.selection_trace ?? {};
98
- const rawSelected = trace.selected ?? (
99
- attempt?.provider || attempt?.model
100
- ? { provider: attempt?.provider ?? null, model: attempt?.model ?? null, source: attempt?.selection_source ?? null }
101
- : null
102
- );
103
- const selected = rawSelected ? {
104
- provider: boundedText(rawSelected.provider, 200),
105
- model: boundedText(rawSelected.model, 300),
106
- source: boundedText(rawSelected.source, 100),
107
- } : null;
108
- const candidates = Array.isArray(trace.ordered_candidates)
109
- ? trace.ordered_candidates.slice(0, 32).map((candidate) => ({
110
- model: boundedText(candidate?.model, 300),
111
- provider: boundedText(candidate?.provider, 200),
112
- status: String(candidate?.status ?? 'CANDIDATE').toUpperCase(),
113
- ...(candidate?.reason ? { reason: boundedText(candidate.reason, 200) } : {}),
114
- }))
115
- : selected ? [{ model: selected.model ?? null, provider: selected.provider ?? null, status: 'SELECTED' }] : [];
116
- return {
117
- attempt: attempt?.attempt ?? null,
118
- role: attempt?.role ?? null,
119
- selected,
120
- selected_model: selected?.model ?? null,
121
- candidates,
122
- fallback_chain: trace.fallback_reason ? [boundedText(trace.fallback_reason, 200)] : [],
123
- decision_reason: boundedText(selected?.source ?? attempt?.selection_source, 200),
124
- fallback_reason: boundedText(trace.fallback_reason, 200),
125
- escalation_reason: boundedText(trace.escalation_reason, 200),
126
- };
127
- });
128
- }
129
-
130
- function changedFilesFromView(view) {
131
- if (Array.isArray(view?.candidate?.changed_files)) return view.candidate.changed_files;
132
- const changes = view?.workspace_diff?.changes;
133
- if (!changes || typeof changes !== 'object') return [];
134
- return [...new Set([
135
- ...(Array.isArray(changes.modified) ? changes.modified : []),
136
- ...(Array.isArray(changes.deleted) ? changes.deleted : []),
137
- ...(Array.isArray(changes.renamed) ? changes.renamed : []),
138
- ...(Array.isArray(changes.untracked) ? changes.untracked : []),
139
- ])];
140
- }
141
-
142
- function boundedExecutionContext(value) {
143
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
144
- const executionPlane = boundedText(value.execution_plane, 64);
145
- const profile = boundedText(value.profile, 64);
146
- const runtimeId = boundedText(value.runtime_id, 128);
147
- const port = Number.isInteger(value.listen_port) ? value.listen_port : null;
148
- const ingress = value.ingress === 'official-3080' || value.ingress === 'direct-3210' ? value.ingress : null;
149
- if (!executionPlane && !profile && !runtimeId && port === null && !ingress) return null;
150
- return {
151
- execution_plane: executionPlane,
152
- profile,
153
- listen_port: port,
154
- runtime_id: runtimeId,
155
- ...(ingress ? { ingress } : {}),
156
- };
157
- }
158
-
159
- /**
160
- * Build the machine-first Result Contract for a workflow.
161
- *
162
- * Deliberately excluded: worker prose, raw provider payloads and candidate
163
- * patch text. The envelope contains enough evidence for orchestration while
164
- * artifact inspection remains an explicit follow-up operation.
165
- */
166
- export function buildEvidenceEnvelope(view = {}) {
167
- const outcome = view.outcome ?? {};
168
- const candidate = view.candidate ?? {};
169
- const review = view.review ?? null;
170
- const errorMessage = boundedText(view.error, 1000);
171
- const changedFiles = boundedStrings(changedFilesFromView(view), { count: 120, length: 500 });
172
- const status = evidenceStatus(view);
173
- const reviewOnly = view.role === 'reviewer' && view.outcome == null;
174
- const selectionAttempts = Array.isArray(view.child_attempts) && view.child_attempts.length > 0
175
- ? view.child_attempts
176
- : (view.selection_trace || view.provider || view.model ? [view] : []);
177
- return {
178
- schema_version: JOB_CONTRACT_SCHEMA_VERSION,
179
- job_id: view.id ?? null,
180
- client_job_id: view.client_job_id ?? null,
181
- role: view.role ?? null,
182
- status,
183
- summary: {
184
- phase: view.phase ?? null,
185
- task_status: outcome.task_status ?? (reviewOnly && status === 'PASS' ? 'success' : null),
186
- execution_status: outcome.execution_status ?? (reviewOnly && review?.status === 'done' ? 'completed' : null),
187
- tests_status: outcome.tests_status ?? null,
188
- delivery_complete: reviewOnly ? review?.delivery_complete === true : outcome.delivery?.complete === true,
189
- review_verdict: review?.verdict ?? null,
190
- },
191
- selection_trace: compactSelectionTrace(selectionAttempts),
192
- execution_context: boundedExecutionContext(view.execution_context ?? selectionAttempts[0]?.execution_context),
193
- changed_files: changedFiles,
194
- changes: boundedStrings(outcome.changes),
195
- tests: boundedTests(outcome.tests),
196
- risks: boundedStrings(reviewOnly ? review?.risks : outcome.risks),
197
- unverified: boundedStrings(outcome.unverified),
198
- review: review ? {
199
- verdict: review.verdict ?? null,
200
- status: review.status ?? null,
201
- findings: boundedStrings(review.findings),
202
- evidence: boundedStrings(review.evidence),
203
- risks: boundedStrings(review.risks),
204
- delivery_complete: review.delivery_complete === true,
205
- mutated_candidate: review.mutated_candidate === true,
206
- } : null,
207
- artifacts: {
208
- candidate_available: view.candidate_available === true || changedFiles.length > 0,
209
- candidate_fingerprint: candidate.fingerprint ?? null,
210
- base_revision: candidate.base_revision ?? view.base_revision ?? null,
211
- workspace_retained: view.workspace_retained === true,
212
- candidate_capture_failed: view.candidate_capture_failed === true,
213
- },
214
- errors: errorMessage || view.error_code ? [{ code: view.error_code ?? null, message: errorMessage }] : [],
215
- };
216
- }
217
-
218
- /** Project a rich internal workflow view onto compact or explicit full detail. */
219
- export function projectWorkflowView(view, { detail = 'compact', afterSequence = 0 } = {}) {
220
- if (!view || typeof view !== 'object') return view;
221
- const evidence = buildEvidenceEnvelope(view);
222
- const allCanonical = Array.isArray(view.canonical_events) ? view.canonical_events : [];
223
- const cursor = allCanonical.at(-1)?.sequence ?? view.event_cursor ?? 0;
224
- const canonicalEvents = allCanonical.filter((event) => Number(event?.sequence) > afterSequence);
225
- const eventProjection = {
226
- canonical_events: canonicalEvents,
227
- event_cursor: cursor,
228
- events_truncated_before_cursor: afterSequence > 0 && canonicalEvents.length > 0
229
- ? canonicalEvents[0].sequence !== afterSequence + 1
230
- : false,
231
- };
232
- if (detail === 'full') return { ...view, ...eventProjection, detail: 'full', evidence };
233
-
234
- const {
235
- candidate: _candidate,
236
- outcome: _outcome,
237
- review: _review,
238
- events: _legacyEvents,
239
- child_attempts: _childAttempts,
240
- selection_trace: _rawSelectionTrace,
241
- selection_source: _rawSelectionSource,
242
- result: _rawResult,
243
- workspace_diff: _workspaceDiff,
244
- reasonDetail: _reasonDetail,
245
- ...safe
246
- } = view;
247
- return {
248
- ...safe,
249
- ...eventProjection,
250
- error: boundedText(view.error, 1000),
251
- cleanup_warning: boundedText(view.cleanup_warning, 1000),
252
- detail: 'compact',
253
- evidence,
254
- };
255
- }
1
+ // Versioned, transport-neutral contracts for one DSH Crew workflow.
2
+ //
3
+ // The workflow runtime may keep richer internal state for recovery and debug,
4
+ // but callers receive this bounded event/evidence layer by default. Full
5
+ // internal details remain available only through an explicit detail=full
6
+ // request at the MCP boundary.
7
+
8
+ export const JOB_CONTRACT_SCHEMA_VERSION = 1;
9
+
10
+ export const JOB_EVENT_TYPES = Object.freeze([
11
+ 'job.created',
12
+ 'job.started',
13
+ 'runtime.bound',
14
+ 'model.selected',
15
+ 'model.admitted',
16
+ 'agent.created',
17
+ 'model.fallback',
18
+ 'worker.started',
19
+ 'worker.completed',
20
+ 'review.started',
21
+ 'review.completed',
22
+ 'approval.required',
23
+ 'job.completed',
24
+ 'job.failed',
25
+ 'job.cancelled',
26
+ ]);
27
+
28
+ const EVENT_TYPE_SET = new Set(JOB_EVENT_TYPES);
29
+ const RESULT_STATUSES = Object.freeze(['PASS', 'FAIL', 'PARTIAL', 'BLOCKED']);
30
+
31
+ function boundedText(value, limit = 800) {
32
+ if (value == null) return null;
33
+ const text = String(value).trim();
34
+ if (!text) return null;
35
+ return text.length <= limit ? text : `${text.slice(0, limit)}…`;
36
+ }
37
+
38
+ function boundedStrings(values, { count = 80, length = 400 } = {}) {
39
+ if (!Array.isArray(values)) return [];
40
+ return values.slice(0, count)
41
+ .map((value) => boundedText(value, length))
42
+ .filter(Boolean);
43
+ }
44
+
45
+ function boundedTests(values) {
46
+ if (!Array.isArray(values)) return [];
47
+ return values.slice(0, 40).map((test) => ({
48
+ status: RESULT_STATUSES.includes(test?.status) ? test.status : boundedText(test?.status, 40),
49
+ command: boundedText(test?.command, 300),
50
+ summary: boundedText(test?.summary, 500),
51
+ }));
52
+ }
53
+
54
+ /** Create one canonical, monotonically sequenced workflow event. */
55
+ export function createCanonicalJobEvent({
56
+ jobId,
57
+ type,
58
+ sequence,
59
+ at,
60
+ role = null,
61
+ attempt = null,
62
+ data = {},
63
+ } = {}) {
64
+ if (!EVENT_TYPE_SET.has(type)) throw new Error(`unknown canonical job event: ${String(type)}`);
65
+ if (typeof jobId !== 'string' || !jobId) throw new Error('canonical job event requires jobId');
66
+ if (!Number.isInteger(sequence) || sequence < 1) throw new Error('canonical job event requires a positive sequence');
67
+ return {
68
+ schema_version: JOB_CONTRACT_SCHEMA_VERSION,
69
+ event_id: `${jobId}:${sequence}`,
70
+ job_id: jobId,
71
+ sequence,
72
+ type,
73
+ at,
74
+ role,
75
+ attempt,
76
+ data: data && typeof data === 'object' && !Array.isArray(data) ? { ...data } : {},
77
+ };
78
+ }
79
+
80
+ function evidenceStatus(view) {
81
+ if (view?.status === 'cancelled' || view?.phase === 'cancelled') return 'BLOCKED';
82
+ if (view?.status === 'failed' || view?.phase === 'failed' || view?.outcome?.execution_status === 'failed') return 'FAIL';
83
+ if (view?.review?.verdict === 'request_changes' || view?.outcome?.task_status === 'partial') return 'PARTIAL';
84
+ if (view?.outcome?.task_status === 'blocked') return 'BLOCKED';
85
+ if (view?.role === 'reviewer' && view?.outcome == null) {
86
+ return view.status === 'done' && view.review?.status === 'done'
87
+ && view.review.verdict === 'approve' && view.review.delivery_complete === true
88
+ && view.review.mutated_candidate !== true ? 'PASS' : 'PARTIAL';
89
+ }
90
+ if (view?.status === 'done' && view?.outcome?.task_status === 'success') return 'PASS';
91
+ return 'PARTIAL';
92
+ }
93
+
94
+ function compactSelectionTrace(attempts) {
95
+ if (!Array.isArray(attempts)) return [];
96
+ return attempts.slice(0, 16).map((attempt) => {
97
+ const trace = attempt?.selection_trace ?? {};
98
+ const rawSelected = trace.selected ?? (
99
+ attempt?.provider || attempt?.model
100
+ ? { provider: attempt?.provider ?? null, model: attempt?.model ?? null, source: attempt?.selection_source ?? null }
101
+ : null
102
+ );
103
+ const selected = rawSelected ? {
104
+ provider: boundedText(rawSelected.provider, 200),
105
+ model: boundedText(rawSelected.model, 300),
106
+ source: boundedText(rawSelected.source, 100),
107
+ } : null;
108
+ const candidates = Array.isArray(trace.ordered_candidates)
109
+ ? trace.ordered_candidates.slice(0, 32).map((candidate) => ({
110
+ model: boundedText(candidate?.model, 300),
111
+ provider: boundedText(candidate?.provider, 200),
112
+ status: String(candidate?.status ?? 'CANDIDATE').toUpperCase(),
113
+ ...(candidate?.reason ? { reason: boundedText(candidate.reason, 200) } : {}),
114
+ }))
115
+ : selected ? [{ model: selected.model ?? null, provider: selected.provider ?? null, status: 'SELECTED' }] : [];
116
+ return {
117
+ attempt: attempt?.attempt ?? null,
118
+ role: attempt?.role ?? null,
119
+ selected,
120
+ selected_model: selected?.model ?? null,
121
+ candidates,
122
+ fallback_chain: trace.fallback_reason ? [boundedText(trace.fallback_reason, 200)] : [],
123
+ decision_reason: boundedText(selected?.source ?? attempt?.selection_source, 200),
124
+ fallback_reason: boundedText(trace.fallback_reason, 200),
125
+ escalation_reason: boundedText(trace.escalation_reason, 200),
126
+ };
127
+ });
128
+ }
129
+
130
+ function changedFilesFromView(view) {
131
+ if (Array.isArray(view?.candidate?.changed_files)) return view.candidate.changed_files;
132
+ const changes = view?.workspace_diff?.changes;
133
+ if (!changes || typeof changes !== 'object') return [];
134
+ return [...new Set([
135
+ ...(Array.isArray(changes.modified) ? changes.modified : []),
136
+ ...(Array.isArray(changes.deleted) ? changes.deleted : []),
137
+ ...(Array.isArray(changes.renamed) ? changes.renamed : []),
138
+ ...(Array.isArray(changes.untracked) ? changes.untracked : []),
139
+ ])];
140
+ }
141
+
142
+ function boundedExecutionContext(value) {
143
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
144
+ const executionPlane = boundedText(value.execution_plane, 64);
145
+ const profile = boundedText(value.profile, 64);
146
+ const runtimeId = boundedText(value.runtime_id, 128);
147
+ const port = Number.isInteger(value.listen_port) ? value.listen_port : null;
148
+ const ingress = value.ingress === 'official-3080' || value.ingress === 'direct-3210' ? value.ingress : null;
149
+ if (!executionPlane && !profile && !runtimeId && port === null && !ingress) return null;
150
+ return {
151
+ execution_plane: executionPlane,
152
+ profile,
153
+ listen_port: port,
154
+ runtime_id: runtimeId,
155
+ ...(ingress ? { ingress } : {}),
156
+ };
157
+ }
158
+
159
+ /**
160
+ * Build the machine-first Result Contract for a workflow.
161
+ *
162
+ * Deliberately excluded: worker prose, raw provider payloads and candidate
163
+ * patch text. The envelope contains enough evidence for orchestration while
164
+ * artifact inspection remains an explicit follow-up operation.
165
+ */
166
+ export function buildEvidenceEnvelope(view = {}) {
167
+ const outcome = view.outcome ?? {};
168
+ const candidate = view.candidate ?? {};
169
+ const review = view.review ?? null;
170
+ const errorMessage = boundedText(view.error, 1000);
171
+ const changedFiles = boundedStrings(changedFilesFromView(view), { count: 120, length: 500 });
172
+ const status = evidenceStatus(view);
173
+ const reviewOnly = view.role === 'reviewer' && view.outcome == null;
174
+ const selectionAttempts = Array.isArray(view.child_attempts) && view.child_attempts.length > 0
175
+ ? view.child_attempts
176
+ : (view.selection_trace || view.provider || view.model ? [view] : []);
177
+ return {
178
+ schema_version: JOB_CONTRACT_SCHEMA_VERSION,
179
+ job_id: view.id ?? null,
180
+ client_job_id: view.client_job_id ?? null,
181
+ role: view.role ?? null,
182
+ status,
183
+ summary: {
184
+ phase: view.phase ?? null,
185
+ task_status: outcome.task_status ?? (reviewOnly && status === 'PASS' ? 'success' : null),
186
+ execution_status: outcome.execution_status ?? (reviewOnly && review?.status === 'done' ? 'completed' : null),
187
+ tests_status: outcome.tests_status ?? null,
188
+ delivery_complete: reviewOnly ? review?.delivery_complete === true : outcome.delivery?.complete === true,
189
+ review_verdict: review?.verdict ?? null,
190
+ },
191
+ selection_trace: compactSelectionTrace(selectionAttempts),
192
+ execution_context: boundedExecutionContext(view.execution_context ?? selectionAttempts[0]?.execution_context),
193
+ changed_files: changedFiles,
194
+ changes: boundedStrings(outcome.changes),
195
+ tests: boundedTests(outcome.tests),
196
+ risks: boundedStrings(reviewOnly ? review?.risks : outcome.risks),
197
+ unverified: boundedStrings(outcome.unverified),
198
+ review: review ? {
199
+ verdict: review.verdict ?? null,
200
+ status: review.status ?? null,
201
+ findings: boundedStrings(review.findings),
202
+ evidence: boundedStrings(review.evidence),
203
+ risks: boundedStrings(review.risks),
204
+ delivery_complete: review.delivery_complete === true,
205
+ mutated_candidate: review.mutated_candidate === true,
206
+ } : null,
207
+ artifacts: {
208
+ candidate_available: view.candidate_available === true || changedFiles.length > 0,
209
+ candidate_fingerprint: candidate.fingerprint ?? null,
210
+ base_revision: candidate.base_revision ?? view.base_revision ?? null,
211
+ workspace_retained: view.workspace_retained === true,
212
+ candidate_capture_failed: view.candidate_capture_failed === true,
213
+ },
214
+ errors: errorMessage || view.error_code ? [{ code: view.error_code ?? null, message: errorMessage }] : [],
215
+ };
216
+ }
217
+
218
+ /** Project a rich internal workflow view onto compact or explicit full detail. */
219
+ export function projectWorkflowView(view, { detail = 'compact', afterSequence = 0 } = {}) {
220
+ if (!view || typeof view !== 'object') return view;
221
+ const evidence = buildEvidenceEnvelope(view);
222
+ const allCanonical = Array.isArray(view.canonical_events) ? view.canonical_events : [];
223
+ const cursor = allCanonical.at(-1)?.sequence ?? view.event_cursor ?? 0;
224
+ const canonicalEvents = allCanonical.filter((event) => Number(event?.sequence) > afterSequence);
225
+ const eventProjection = {
226
+ canonical_events: canonicalEvents,
227
+ event_cursor: cursor,
228
+ events_truncated_before_cursor: afterSequence > 0 && canonicalEvents.length > 0
229
+ ? canonicalEvents[0].sequence !== afterSequence + 1
230
+ : false,
231
+ };
232
+ if (detail === 'full') return { ...view, ...eventProjection, detail: 'full', evidence };
233
+
234
+ const {
235
+ candidate: _candidate,
236
+ outcome: _outcome,
237
+ review: _review,
238
+ events: _legacyEvents,
239
+ child_attempts: _childAttempts,
240
+ selection_trace: _rawSelectionTrace,
241
+ selection_source: _rawSelectionSource,
242
+ result: _rawResult,
243
+ workspace_diff: _workspaceDiff,
244
+ reasonDetail: _reasonDetail,
245
+ ...safe
246
+ } = view;
247
+ return {
248
+ ...safe,
249
+ ...eventProjection,
250
+ error: boundedText(view.error, 1000),
251
+ cleanup_warning: boundedText(view.cleanup_warning, 1000),
252
+ detail: 'compact',
253
+ evidence,
254
+ };
255
+ }
@@ -1,60 +1,60 @@
1
- // Shared local-request trust primitives for the two loopback surfaces:
2
- // the isolated 3210 hub API (src/hub/index.mjs) and the 3080→3210
3
- // official-web bridge (src/official-web-bridge.mjs). One implementation keeps
4
- // the two guards from drifting apart again.
5
- //
6
- // Trust model (see docs/ui-surfaces.md): both surfaces are loopback-only and
7
- // have no bearer token by design — every process running as the local user is
8
- // inside the trust boundary. The guards exist to keep off-machine browsers,
9
- // DNS-rebinding pages, and cross-machine proxies out, not to authenticate
10
- // local users. `localRequestCore` proves the peer is this machine (loopback
11
- // socket, local Host header, browser fetch-metadata pass); each surface then
12
- // layers its own Origin policy on top — the hub accepts any loopback origin
13
- // because the 3080 panel calls it cross-port, while the bridge requires an
14
- // exact authority match because it only serves its own same-origin client.
15
-
16
- function isIpv4Loopback(a) { return /^127(\.\d{1,3}){3}$/.test(a); }
17
-
18
- export function isLoopbackAddress(address) {
19
- if (!address) return false;
20
- const n = address.toLowerCase().split('%', 1)[0];
21
- if (n === '::1' || isIpv4Loopback(n)) return true;
22
- if (!n.startsWith('::ffff:')) return false;
23
- return isIpv4Loopback(n.slice(7));
24
- }
25
-
26
- export function isLocalHostname(hostname) {
27
- return hostname === 'localhost' || hostname === '::1' || hostname === '[::1]' || isIpv4Loopback(hostname);
28
- }
29
-
30
- /**
31
- * Core of both guards: loopback peer, loopback Host header, and (when the
32
- * client is a browser) a same-origin/none fetch-metadata request. Returns
33
- * false for anything that cannot be proven local.
34
- */
35
- export function localRequestCore(req) {
36
- if (!isLoopbackAddress(req?.socket?.remoteAddress)) return false;
37
- const host = typeof req?.headers?.host === 'string' ? req.headers.host.trim().toLowerCase() : '';
38
- if (!host) return false;
39
- let authority;
40
- try { authority = new URL(`http://${host}`); } catch { return false; }
41
- if (!isLocalHostname(authority.hostname.toLowerCase())) return false;
42
- const fetchSite = String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase();
43
- if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'none') return false;
44
- return true;
45
- }
46
-
47
- /** Hub Origin policy: an Origin, when present, must name a loopback host. */
48
- export function originLoopback(originHeader) {
49
- if (typeof originHeader !== 'string') return false;
50
- let parsed;
51
- try { parsed = new URL(originHeader); } catch { return false; }
52
- return isLocalHostname(parsed.hostname.toLowerCase());
53
- }
54
-
55
- /** Bridge Origin policy: the Origin authority must equal the request authority. */
56
- export function originAuthorityMatches(originHeader, host) {
57
- if (!originLoopback(originHeader)) return false;
58
- const parsed = new URL(originHeader);
59
- return parsed.host.toLowerCase() === String(host).trim().toLowerCase();
60
- }
1
+ // Shared local-request trust primitives for the two loopback surfaces:
2
+ // the isolated 3210 hub API (src/hub/index.mjs) and the 3080→3210
3
+ // official-web bridge (src/official-web-bridge.mjs). One implementation keeps
4
+ // the two guards from drifting apart again.
5
+ //
6
+ // Trust model (see docs/ui-surfaces.md): both surfaces are loopback-only and
7
+ // have no bearer token by design — every process running as the local user is
8
+ // inside the trust boundary. The guards exist to keep off-machine browsers,
9
+ // DNS-rebinding pages, and cross-machine proxies out, not to authenticate
10
+ // local users. `localRequestCore` proves the peer is this machine (loopback
11
+ // socket, local Host header, browser fetch-metadata pass); each surface then
12
+ // layers its own Origin policy on top — the hub accepts any loopback origin
13
+ // because the 3080 panel calls it cross-port, while the bridge requires an
14
+ // exact authority match because it only serves its own same-origin client.
15
+
16
+ function isIpv4Loopback(a) { return /^127(\.\d{1,3}){3}$/.test(a); }
17
+
18
+ export function isLoopbackAddress(address) {
19
+ if (!address) return false;
20
+ const n = address.toLowerCase().split('%', 1)[0];
21
+ if (n === '::1' || isIpv4Loopback(n)) return true;
22
+ if (!n.startsWith('::ffff:')) return false;
23
+ return isIpv4Loopback(n.slice(7));
24
+ }
25
+
26
+ export function isLocalHostname(hostname) {
27
+ return hostname === 'localhost' || hostname === '::1' || hostname === '[::1]' || isIpv4Loopback(hostname);
28
+ }
29
+
30
+ /**
31
+ * Core of both guards: loopback peer, loopback Host header, and (when the
32
+ * client is a browser) a same-origin/none fetch-metadata request. Returns
33
+ * false for anything that cannot be proven local.
34
+ */
35
+ export function localRequestCore(req) {
36
+ if (!isLoopbackAddress(req?.socket?.remoteAddress)) return false;
37
+ const host = typeof req?.headers?.host === 'string' ? req.headers.host.trim().toLowerCase() : '';
38
+ if (!host) return false;
39
+ let authority;
40
+ try { authority = new URL(`http://${host}`); } catch { return false; }
41
+ if (!isLocalHostname(authority.hostname.toLowerCase())) return false;
42
+ const fetchSite = String(req?.headers?.['sec-fetch-site'] ?? '').toLowerCase();
43
+ if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'none') return false;
44
+ return true;
45
+ }
46
+
47
+ /** Hub Origin policy: an Origin, when present, must name a loopback host. */
48
+ export function originLoopback(originHeader) {
49
+ if (typeof originHeader !== 'string') return false;
50
+ let parsed;
51
+ try { parsed = new URL(originHeader); } catch { return false; }
52
+ return isLocalHostname(parsed.hostname.toLowerCase());
53
+ }
54
+
55
+ /** Bridge Origin policy: the Origin authority must equal the request authority. */
56
+ export function originAuthorityMatches(originHeader, host) {
57
+ if (!originLoopback(originHeader)) return false;
58
+ const parsed = new URL(originHeader);
59
+ return parsed.host.toLowerCase() === String(host).trim().toLowerCase();
60
+ }