@dailephd/my-centcom 0.1.0 → 0.3.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 (175) hide show
  1. package/README.md +10 -5
  2. package/apps/daemon/dist/artifacts/returnSnapshots.d.ts +12 -0
  3. package/apps/daemon/dist/artifacts/returnSnapshots.js +41 -0
  4. package/apps/daemon/dist/bootstrap/app.d.ts +21 -0
  5. package/apps/daemon/dist/bootstrap/app.js +27 -0
  6. package/apps/daemon/dist/bootstrap/installLayout.d.ts +81 -0
  7. package/apps/daemon/dist/bootstrap/installLayout.js +164 -0
  8. package/apps/daemon/dist/bootstrap/main.d.ts +14 -0
  9. package/apps/daemon/dist/bootstrap/main.js +141 -0
  10. package/apps/daemon/dist/bootstrap/operatorConsole.d.ts +75 -0
  11. package/apps/daemon/dist/bootstrap/operatorConsole.js +293 -0
  12. package/apps/daemon/dist/bootstrap/privateDataRoot.d.ts +38 -0
  13. package/apps/daemon/dist/bootstrap/privateDataRoot.js +204 -0
  14. package/apps/daemon/dist/bootstrap/secureMain.d.ts +118 -0
  15. package/apps/daemon/dist/bootstrap/secureMain.js +403 -0
  16. package/apps/daemon/dist/bootstrap/setup.d.ts +93 -0
  17. package/apps/daemon/dist/bootstrap/setup.js +738 -0
  18. package/apps/daemon/dist/context/changeProposal.d.ts +97 -0
  19. package/apps/daemon/dist/context/changeProposal.js +259 -0
  20. package/apps/daemon/dist/context/gitEvidence.d.ts +88 -0
  21. package/apps/daemon/dist/context/gitEvidence.js +332 -0
  22. package/apps/daemon/dist/context/gitObservation.d.ts +30 -0
  23. package/apps/daemon/dist/context/gitObservation.js +113 -0
  24. package/apps/daemon/dist/context/projectReadIssuer.d.ts +68 -0
  25. package/apps/daemon/dist/context/projectReadIssuer.js +158 -0
  26. package/apps/daemon/dist/context/projectReadService.d.ts +153 -0
  27. package/apps/daemon/dist/context/projectReadService.js +652 -0
  28. package/apps/daemon/dist/context/projectViewService.d.ts +85 -0
  29. package/apps/daemon/dist/context/projectViewService.js +332 -0
  30. package/apps/daemon/dist/context/proposalRecorder.d.ts +11 -0
  31. package/apps/daemon/dist/context/proposalRecorder.js +19 -0
  32. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.d.ts +40 -0
  33. package/apps/daemon/dist/plugins/drivers/codexMcpConfig.js +73 -0
  34. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.d.ts +49 -0
  35. package/apps/daemon/dist/plugins/drivers/codexModelCompatibility.js +70 -0
  36. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.d.ts +16 -0
  37. package/apps/daemon/dist/plugins/drivers/fakePluginDriver.js +115 -0
  38. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.d.ts +153 -0
  39. package/apps/daemon/dist/plugins/drivers/finiteCliDriver.js +505 -0
  40. package/apps/daemon/dist/plugins/registry/operationCatalog.d.ts +23 -0
  41. package/apps/daemon/dist/plugins/registry/operationCatalog.js +41 -0
  42. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.d.ts +14 -0
  43. package/apps/daemon/dist/plugins/registry/registryOperationCatalog.js +29 -0
  44. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.d.ts +151 -0
  45. package/apps/daemon/dist/plugins/registry/verifiedCapabilityRegistry.js +579 -0
  46. package/apps/daemon/dist/projects/codingAuthority.d.ts +102 -0
  47. package/apps/daemon/dist/projects/codingAuthority.js +244 -0
  48. package/apps/daemon/dist/projects/fixtureAuthorization.d.ts +54 -0
  49. package/apps/daemon/dist/projects/fixtureAuthorization.js +172 -0
  50. package/apps/daemon/dist/projects/pairedAuthority.d.ts +158 -0
  51. package/apps/daemon/dist/projects/pairedAuthority.js +273 -0
  52. package/apps/daemon/dist/projects/trustedCliConsent.d.ts +47 -0
  53. package/apps/daemon/dist/projects/trustedCliConsent.js +84 -0
  54. package/apps/daemon/dist/runs/changeApplier.d.ts +59 -0
  55. package/apps/daemon/dist/runs/changeApplier.js +319 -0
  56. package/apps/daemon/dist/runs/codingWorkflowService.d.ts +283 -0
  57. package/apps/daemon/dist/runs/codingWorkflowService.js +785 -0
  58. package/apps/daemon/dist/runs/durableIntentCoordinator.d.ts +72 -0
  59. package/apps/daemon/dist/runs/durableIntentCoordinator.js +160 -0
  60. package/apps/daemon/dist/runs/inMemoryCoordinator.d.ts +55 -0
  61. package/apps/daemon/dist/runs/inMemoryCoordinator.js +375 -0
  62. package/apps/daemon/dist/runs/runExecutor.d.ts +154 -0
  63. package/apps/daemon/dist/runs/runExecutor.js +295 -0
  64. package/apps/daemon/dist/runs/workflowService.d.ts +185 -0
  65. package/apps/daemon/dist/runs/workflowService.js +300 -0
  66. package/apps/daemon/dist/runtime/boundedProcessHost.d.ts +111 -0
  67. package/apps/daemon/dist/runtime/boundedProcessHost.js +752 -0
  68. package/apps/daemon/dist/runtime/evidenceRedaction.d.ts +30 -0
  69. package/apps/daemon/dist/runtime/evidenceRedaction.js +79 -0
  70. package/apps/daemon/dist/runtime/executionDiagnostics.d.ts +134 -0
  71. package/apps/daemon/dist/runtime/executionDiagnostics.js +213 -0
  72. package/apps/daemon/dist/runtime/modelExecutionPolicy.d.ts +22 -0
  73. package/apps/daemon/dist/runtime/modelExecutionPolicy.js +19 -0
  74. package/apps/daemon/dist/runtime/mxcExecution.d.ts +12 -0
  75. package/apps/daemon/dist/runtime/mxcExecution.js +163 -0
  76. package/apps/daemon/dist/runtime/mxcIntegrity.d.ts +24 -0
  77. package/apps/daemon/dist/runtime/mxcIntegrity.js +81 -0
  78. package/apps/daemon/dist/runtime/mxcWorker.d.ts +2 -0
  79. package/apps/daemon/dist/runtime/mxcWorker.js +45 -0
  80. package/apps/daemon/dist/runtime/provisionedExecution.d.ts +150 -0
  81. package/apps/daemon/dist/runtime/provisionedExecution.js +653 -0
  82. package/apps/daemon/dist/runtime/testExecution.d.ts +76 -0
  83. package/apps/daemon/dist/runtime/testExecution.js +106 -0
  84. package/apps/daemon/dist/runtime/testProfiles.d.ts +10 -0
  85. package/apps/daemon/dist/runtime/testProfiles.js +4 -0
  86. package/apps/daemon/dist/runtime/trustedAgentStaging.d.ts +89 -0
  87. package/apps/daemon/dist/runtime/trustedAgentStaging.js +262 -0
  88. package/apps/daemon/dist/runtime/trustedCaBundle.d.ts +77 -0
  89. package/apps/daemon/dist/runtime/trustedCaBundle.js +125 -0
  90. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.d.ts +166 -0
  91. package/apps/daemon/dist/runtime/windows/windowsJobSupervisor.js +521 -0
  92. package/apps/daemon/dist/storage/diagnosticLog.d.ts +63 -0
  93. package/apps/daemon/dist/storage/diagnosticLog.js +136 -0
  94. package/apps/daemon/dist/storage/executionTelemetry.d.ts +63 -0
  95. package/apps/daemon/dist/storage/executionTelemetry.js +247 -0
  96. package/apps/daemon/dist/storage/protectedSecrets.d.ts +39 -0
  97. package/apps/daemon/dist/storage/protectedSecrets.js +106 -0
  98. package/apps/daemon/dist/storage/sqliteLedger.d.ts +786 -0
  99. package/apps/daemon/dist/storage/sqliteLedger.js +1303 -0
  100. package/apps/daemon/dist/transports/http/dispatch.d.ts +43 -0
  101. package/apps/daemon/dist/transports/http/dispatch.js +405 -0
  102. package/apps/daemon/dist/transports/http/secureRoutes.d.ts +40 -0
  103. package/apps/daemon/dist/transports/http/secureRoutes.js +332 -0
  104. package/apps/daemon/dist/transports/http/workflowRoutes.d.ts +41 -0
  105. package/apps/daemon/dist/transports/http/workflowRoutes.js +473 -0
  106. package/apps/daemon/dist/transports/mcp/localProjectReadServer.d.ts +182 -0
  107. package/apps/daemon/dist/transports/mcp/localProjectReadServer.js +221 -0
  108. package/apps/daemon/dist/transports/native/nativeHost.d.ts +24 -0
  109. package/apps/daemon/dist/transports/native/nativeHost.js +344 -0
  110. package/apps/daemon/package.json +24 -0
  111. package/apps/daemon/src/runtime/benign/referenceEcho.mjs +27 -0
  112. package/apps/daemon/src/runtime/windows/buildSupervisor.mjs +87 -0
  113. package/apps/daemon/src/runtime/windows/supervisorMain.cs +676 -0
  114. package/apps/extension/manifest.secure.json +25 -0
  115. package/apps/extension/scripts/build.mjs +173 -0
  116. package/apps/extension/src/background/secureWorker.ts +1595 -0
  117. package/apps/extension/src/background/serviceWorker.ts +892 -0
  118. package/apps/extension/src/content/captureSelection.ts +64 -0
  119. package/apps/extension/src/content/secureInsert.ts +207 -0
  120. package/apps/extension/src/probe/index.html +41 -0
  121. package/apps/extension/src/probe/main.ts +201 -0
  122. package/apps/extension/src/sidepanel/index.html +203 -0
  123. package/apps/extension/src/sidepanel/main.ts +903 -0
  124. package/package.json +19 -3
  125. package/packages/contracts/dist/artifacts.d.ts +66 -0
  126. package/packages/contracts/dist/artifacts.js +64 -0
  127. package/packages/contracts/dist/automation.d.ts +540 -0
  128. package/packages/contracts/dist/automation.js +191 -0
  129. package/packages/contracts/dist/browser.d.ts +251 -0
  130. package/packages/contracts/dist/browser.js +131 -0
  131. package/packages/contracts/dist/context.d.ts +71 -0
  132. package/packages/contracts/dist/context.js +73 -0
  133. package/packages/contracts/dist/diagnostics.d.ts +99 -0
  134. package/packages/contracts/dist/diagnostics.js +284 -0
  135. package/packages/contracts/dist/effects.d.ts +42 -0
  136. package/packages/contracts/dist/effects.js +42 -0
  137. package/packages/contracts/dist/errors.d.ts +75 -0
  138. package/packages/contracts/dist/errors.js +70 -0
  139. package/packages/contracts/dist/events.d.ts +50 -0
  140. package/packages/contracts/dist/events.js +34 -0
  141. package/packages/contracts/dist/executionDiagnostics.d.ts +212 -0
  142. package/packages/contracts/dist/executionDiagnostics.js +101 -0
  143. package/packages/contracts/dist/identity.d.ts +54 -0
  144. package/packages/contracts/dist/identity.js +40 -0
  145. package/packages/contracts/dist/index.d.ts +20 -0
  146. package/packages/contracts/dist/index.js +20 -0
  147. package/packages/contracts/dist/invocation.d.ts +90 -0
  148. package/packages/contracts/dist/invocation.js +77 -0
  149. package/packages/contracts/dist/lifecycle.d.ts +130 -0
  150. package/packages/contracts/dist/lifecycle.js +135 -0
  151. package/packages/contracts/dist/plugin.d.ts +214 -0
  152. package/packages/contracts/dist/plugin.js +117 -0
  153. package/packages/contracts/dist/projectRead.d.ts +205 -0
  154. package/packages/contracts/dist/projectRead.js +162 -0
  155. package/packages/contracts/dist/secure.d.ts +128 -0
  156. package/packages/contracts/dist/secure.js +99 -0
  157. package/packages/contracts/package.json +32 -0
  158. package/packages/contracts/src/artifacts.ts +83 -0
  159. package/packages/contracts/src/automation.ts +238 -0
  160. package/packages/contracts/src/browser.ts +164 -0
  161. package/packages/contracts/src/context.ts +91 -0
  162. package/packages/contracts/src/diagnostics.ts +318 -0
  163. package/packages/contracts/src/effects.ts +49 -0
  164. package/packages/contracts/src/errors.ts +83 -0
  165. package/packages/contracts/src/events.ts +46 -0
  166. package/packages/contracts/src/executionDiagnostics.ts +116 -0
  167. package/packages/contracts/src/identity.ts +68 -0
  168. package/packages/contracts/src/index.ts +20 -0
  169. package/packages/contracts/src/invocation.ts +96 -0
  170. package/packages/contracts/src/lifecycle.ts +169 -0
  171. package/packages/contracts/src/plugin.ts +174 -0
  172. package/packages/contracts/src/projectRead.ts +179 -0
  173. package/packages/contracts/src/secure.ts +136 -0
  174. package/provenance.json +179 -9
  175. package/source.zip +0 -0
@@ -0,0 +1,43 @@
1
+ import { FastifyInstance } from 'fastify';
2
+ import { LoopbackHttpRequestV1, PluginDriver } from '../../../../../packages/contracts/dist/index.js';
3
+ import { M03Coordinator } from '../../runs/inMemoryCoordinator.js';
4
+ import { authorizeM03Fixture, FixtureEvidenceSource, ReadOnlyAuthorizer } from '../../projects/fixtureAuthorization.js';
5
+ /** Request metadata exposed to tests so real browser request headers can be recorded. */
6
+ export interface HttpRequestObservation {
7
+ method: string;
8
+ url: string;
9
+ origin?: string;
10
+ headers: Record<string, string | string[] | undefined>;
11
+ }
12
+ export interface M03Dependencies {
13
+ driver: PluginDriver;
14
+ authorize: typeof authorizeM03Fixture;
15
+ coordinator: M03Coordinator;
16
+ expectedToken: string;
17
+ observationHook?: (request: LoopbackHttpRequestV1) => void;
18
+ /**
19
+ * Exact browser Origin values allowed to call /v1/dispatch when an Origin header is present.
20
+ * When undefined or empty, any request that carries an Origin header is rejected (fail closed).
21
+ * An Origin header is a browser-enforced hint, NOT authentication: ordinary local clients may
22
+ * omit it, and the fixture token plus operation policy remain mandatory either way.
23
+ */
24
+ allowedOrigins?: string[];
25
+ requestObserver?: (observation: HttpRequestObservation) => void;
26
+ /**
27
+ * Explicit test dependency: a deterministic in-memory evidence source for the read-only GET_CONTEXT
28
+ * branch. When absent, read-only requests fail closed. Not a project context or artifact service.
29
+ */
30
+ evidenceSource?: FixtureEvidenceSource;
31
+ /** Read-only capability check; defaults to the fixture authorizer. Independent of `authorize`. */
32
+ authorizeReadOnly?: ReadOnlyAuthorizer;
33
+ }
34
+ /** Independent inbound byte ceiling, enforced by Fastify before any JSON parsing, Zod validation or authorization. */
35
+ export declare const M03_HTTP_BODY_LIMIT_BYTES = 65536;
36
+ /**
37
+ * Registers M03/M04 Fastify HTTP dispatch routes.
38
+ * Endpoints:
39
+ * GET /health
40
+ * POST /v1/dispatch
41
+ */
42
+ export declare function registerDispatchRoutes(app: FastifyInstance, dependencies: M03Dependencies): void;
43
+ //# sourceMappingURL=dispatch.d.ts.map
@@ -0,0 +1,405 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { LoopbackHttpRequestV1Schema, ContractError, BoundedFileResponseV1Schema, ArtifactRecordV1Schema, ShipmentSelectionV1Schema, verifyShipmentProvenance, createShipmentId, } from '../../../../../packages/contracts/dist/index.js';
3
+ import { authorizeFixtureReadOnly, isIssuedReadOnlyGrant, } from '../../projects/fixtureAuthorization.js';
4
+ const UNKNOWN_REQUEST_ID = 'req.m03-unknown';
5
+ /** Independent inbound byte ceiling, enforced by Fastify before any JSON parsing, Zod validation or authorization. */
6
+ export const M03_HTTP_BODY_LIMIT_BYTES = 65536;
7
+ const MAX_REQUEST_ID_LENGTH = 256;
8
+ function mapErrorCodeToHttpStatus(code) {
9
+ switch (code) {
10
+ case 'UNSUPPORTED_PROTOCOL_VERSION':
11
+ case 'INVALID_PAYLOAD':
12
+ return 400;
13
+ case 'MISSING_OR_INVALID_AUTHORIZATION':
14
+ return 401;
15
+ case 'UNAUTHORIZED_PROJECT_OR_OPERATION':
16
+ case 'CONTENT_BOUNDS_OR_PATH_DENIAL':
17
+ return 403;
18
+ case 'STALE_REQUEST_OR_SELECTION':
19
+ case 'IDEMPOTENCY_CONFLICT':
20
+ case 'DUPLICATE_REQUEST':
21
+ case 'DUPLICATE_OR_CONFLICTING_INVOCATION':
22
+ case 'WORKTREE_BUSY':
23
+ case 'CANCELLED':
24
+ // Client-visible representation of an already-canceled operation; the lifecycle
25
+ // record and cancellation receipt stay authoritative. Not a network or native CLI failure.
26
+ return 409;
27
+ case 'NATIVE_CLI_FAILURE':
28
+ return 502;
29
+ case 'UNKNOWN_PROCESS_OUTCOME':
30
+ case 'OFFLINE_OR_UNAVAILABLE_SERVICE':
31
+ return 503;
32
+ case 'TIMEOUT':
33
+ return 504;
34
+ case 'INTERNAL_ERROR':
35
+ default:
36
+ return 500;
37
+ }
38
+ }
39
+ const sha256Hex = (text) => createHash('sha256').update(text, 'utf8').digest('hex');
40
+ /** Cuts text to at most maxBytes of UTF-8 without splitting a code point, then to maxLines. */
41
+ function boundText(text, maxBytes, maxLines) {
42
+ let bytes = Buffer.from(text, 'utf8');
43
+ let truncated = false;
44
+ if (bytes.length > maxBytes) {
45
+ let end = maxBytes;
46
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
47
+ end--;
48
+ bytes = bytes.subarray(0, end);
49
+ truncated = true;
50
+ }
51
+ let out = bytes.toString('utf8');
52
+ if (maxLines !== undefined) {
53
+ const lines = out.split(/(?<=\n)/);
54
+ if (lines.length > maxLines) {
55
+ out = lines.slice(0, maxLines).join('');
56
+ truncated = true;
57
+ }
58
+ }
59
+ const sizeBytes = Buffer.byteLength(out, 'utf8');
60
+ const lineCount = out.length === 0 ? 0 : out.split('\n').length - (out.endsWith('\n') ? 1 : 0);
61
+ return { content: out, truncated, sizeBytes, lineCount };
62
+ }
63
+ function integrityFailure(requestId, projectId, reason) {
64
+ return new ContractError({
65
+ errorCode: 'INTERNAL_ERROR',
66
+ message: 'Evidence integrity check failed',
67
+ correlationId: requestId,
68
+ projectId,
69
+ details: { reason },
70
+ });
71
+ }
72
+ /**
73
+ * Read-only evidence branch. Never touches the plugin driver or the run coordinator, and never
74
+ * reads the real filesystem: data comes only from the explicitly injected fixture source, and every
75
+ * record is re-validated and digest-checked before it is returned.
76
+ */
77
+ function buildEvidenceData(grant, source, requestId) {
78
+ if (!isIssuedReadOnlyGrant(grant)) {
79
+ throw new ContractError({
80
+ errorCode: 'UNAUTHORIZED_PROJECT_OR_OPERATION',
81
+ message: 'Read-only grant was not issued by the project authorization authority',
82
+ correlationId: requestId,
83
+ });
84
+ }
85
+ const { fileRequest, projectId } = grant;
86
+ const record = source.readFile(projectId, fileRequest.relativePath);
87
+ if (!record) {
88
+ throw new ContractError({
89
+ errorCode: 'CONTENT_BOUNDS_OR_PATH_DENIAL',
90
+ message: 'Requested record is not available',
91
+ correlationId: requestId,
92
+ projectId,
93
+ });
94
+ }
95
+ const bounded = boundText(record.content, fileRequest.maxBytes, fileRequest.maxLines);
96
+ const file = BoundedFileResponseV1Schema.parse({
97
+ schemaVersion: 1,
98
+ projectId,
99
+ relativePath: fileRequest.relativePath,
100
+ canonicalPath: record.canonicalPath,
101
+ sizeBytes: bounded.sizeBytes,
102
+ lineCount: bounded.lineCount,
103
+ truncated: bounded.truncated,
104
+ content: bounded.content,
105
+ sha256: sha256Hex(bounded.content),
106
+ retrievedAt: new Date().toISOString(),
107
+ });
108
+ const data = {
109
+ kind: 'READ_ONLY_FIXTURE_EVIDENCE',
110
+ readOnly: true,
111
+ file,
112
+ provenance: {
113
+ sourceKind: source.kind,
114
+ realProjectFile: false,
115
+ durableArtifactService: false,
116
+ composerCapability: false,
117
+ pluginDriverInvoked: false,
118
+ userSelection: 'FIXTURE_DECLARED',
119
+ },
120
+ };
121
+ // A selection needs complete content; a truncated read never carries artifact snapshots.
122
+ if (bounded.truncated) {
123
+ data.returnShapeOmitted = 'CONTENT_TRUNCATED';
124
+ return data;
125
+ }
126
+ const candidates = source.getReturnCandidates(projectId);
127
+ if (!candidates) {
128
+ return data;
129
+ }
130
+ const declared = new Map();
131
+ for (const raw of candidates.artifacts) {
132
+ const artifact = ArtifactRecordV1Schema.parse(raw);
133
+ if (artifact.projectId !== projectId)
134
+ throw integrityFailure(requestId, projectId, 'ARTIFACT_PROJECT_MISMATCH');
135
+ declared.set(artifact.artifactId, artifact);
136
+ }
137
+ // Only explicitly selected artifacts are ever copied into the response.
138
+ const selected = [];
139
+ for (const id of candidates.selectedArtifactIds) {
140
+ const artifact = declared.get(id);
141
+ if (!artifact)
142
+ throw integrityFailure(requestId, projectId, 'SELECTED_ARTIFACT_UNDECLARED');
143
+ if (sha256Hex(artifact.contentSnapshot) !== artifact.immutableSnapshotSha256.toLowerCase() ||
144
+ Buffer.byteLength(artifact.contentSnapshot, 'utf8') !== artifact.sizeBytes) {
145
+ throw integrityFailure(requestId, projectId, 'ARTIFACT_DIGEST_MISMATCH');
146
+ }
147
+ selected.push(artifact);
148
+ }
149
+ if (selected.length === 0) {
150
+ return data;
151
+ }
152
+ const selection = ShipmentSelectionV1Schema.parse({
153
+ schemaVersion: 1,
154
+ shipmentId: createShipmentId('shipment.m04-fixture'),
155
+ runId: candidates.runId,
156
+ selectedItems: selected.map((a) => ({
157
+ artifactId: a.artifactId,
158
+ sha256: a.immutableSnapshotSha256,
159
+ sourcePathAtSnapshot: a.mutableSourcePath,
160
+ })),
161
+ markdownPresentation: selected
162
+ .map((a) => `### ${a.artifactId}\n\`\`\`text\n${a.contentSnapshot}\`\`\``)
163
+ .join('\n\n'),
164
+ selectedAt: new Date().toISOString(),
165
+ // No user has acted yet; approval is recorded only by an explicit browser-side action.
166
+ selectionApprovedByUser: false,
167
+ });
168
+ verifyShipmentProvenance(selection, new Map(selected.map((a) => [a.artifactId, a])));
169
+ data.artifacts = selected;
170
+ data.selection = selection;
171
+ data.conversationId = candidates.conversationId;
172
+ return data;
173
+ }
174
+ function safeRequestId(value) {
175
+ return typeof value === 'string' && value.length > 0 && value.length <= MAX_REQUEST_ID_LENGTH
176
+ ? value
177
+ : UNKNOWN_REQUEST_ID;
178
+ }
179
+ function correlationFromBody(body) {
180
+ if (typeof body === 'object' && body !== null && 'requestId' in body) {
181
+ return safeRequestId(body.requestId);
182
+ }
183
+ return UNKNOWN_REQUEST_ID;
184
+ }
185
+ /**
186
+ * Sends a LoopbackHttpResponseV1 error envelope containing a valid ContractErrorV1.
187
+ * Top-level errorCode/message/correlationId mirror the nested error for M03 client compatibility.
188
+ */
189
+ function sendContractError(reply, contractError, statusOverride) {
190
+ const httpStatus = statusOverride ?? mapErrorCodeToHttpStatus(contractError.errorCode);
191
+ const errorJson = contractError.toJSON();
192
+ return reply.status(httpStatus).send({
193
+ schemaVersion: 1,
194
+ requestId: safeRequestId(contractError.correlationId),
195
+ statusCode: httpStatus,
196
+ errorCode: contractError.errorCode,
197
+ message: contractError.message,
198
+ correlationId: contractError.correlationId,
199
+ timestamp: contractError.timestamp,
200
+ details: contractError.details,
201
+ error: errorJson,
202
+ });
203
+ }
204
+ function internalError(correlationId) {
205
+ // Sanitized: never include stack traces, driver exception text, or configuration.
206
+ return new ContractError({
207
+ errorCode: 'INTERNAL_ERROR',
208
+ message: 'Internal server error',
209
+ correlationId,
210
+ });
211
+ }
212
+ /**
213
+ * Registers M03/M04 Fastify HTTP dispatch routes.
214
+ * Endpoints:
215
+ * GET /health
216
+ * POST /v1/dispatch
217
+ */
218
+ export function registerDispatchRoutes(app, dependencies) {
219
+ // Framework-level failures (malformed JSON, unsupported media type, oversize body, ...)
220
+ app.setErrorHandler((error, req, reply) => {
221
+ const correlationId = correlationFromBody(req.body);
222
+ const statusCode = error.statusCode;
223
+ if (statusCode === 413) {
224
+ // Oversized body: rejected by the framework before parsing, authorization or the driver.
225
+ return sendContractError(reply, new ContractError({
226
+ errorCode: 'INVALID_PAYLOAD',
227
+ message: 'Request body exceeds the permitted size',
228
+ correlationId: UNKNOWN_REQUEST_ID,
229
+ details: { reason: 'BODY_TOO_LARGE', limitBytes: M03_HTTP_BODY_LIMIT_BYTES },
230
+ }), 413);
231
+ }
232
+ if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500) {
233
+ return sendContractError(reply, new ContractError({
234
+ errorCode: 'INVALID_PAYLOAD',
235
+ message: 'Request could not be parsed as a valid JSON request',
236
+ correlationId,
237
+ }));
238
+ }
239
+ return sendContractError(reply, internalError(correlationId));
240
+ });
241
+ app.addHook('onRequest', async (req) => {
242
+ if (!dependencies.requestObserver) {
243
+ return;
244
+ }
245
+ try {
246
+ dependencies.requestObserver({
247
+ method: req.method,
248
+ url: req.url,
249
+ origin: typeof req.headers.origin === 'string' ? req.headers.origin : undefined,
250
+ headers: { ...req.headers },
251
+ });
252
+ }
253
+ catch {
254
+ // Observation must never affect request handling.
255
+ }
256
+ });
257
+ const isOriginAllowed = (origin) => {
258
+ // Fail closed: with no configured exact origins, every present Origin is rejected.
259
+ // No prefix/wildcard matching: only exact configured values authorize a browser origin.
260
+ const allowed = dependencies.allowedOrigins;
261
+ if (!allowed || allowed.length === 0) {
262
+ return false;
263
+ }
264
+ return allowed.includes(origin);
265
+ };
266
+ // GET /health
267
+ app.get('/health', async (_req, reply) => {
268
+ return reply.status(200).send({
269
+ status: 'ok',
270
+ schemaVersion: 1,
271
+ timestamp: new Date().toISOString(),
272
+ });
273
+ });
274
+ // POST /v1/dispatch
275
+ app.post('/v1/dispatch', {
276
+ // Runs before body parsing so an untrusted web origin never reaches validation or the driver.
277
+ onRequest: async (req, reply) => {
278
+ const origin = req.headers.origin;
279
+ if (origin !== undefined && !(typeof origin === 'string' && isOriginAllowed(origin))) {
280
+ return sendContractError(reply, new ContractError({
281
+ errorCode: 'UNAUTHORIZED_PROJECT_OR_OPERATION',
282
+ message: 'Request origin is not trusted',
283
+ correlationId: UNKNOWN_REQUEST_ID,
284
+ details: { reason: 'UNTRUSTED_ORIGIN' },
285
+ }));
286
+ }
287
+ return undefined;
288
+ },
289
+ }, async (req, reply) => {
290
+ let correlationRequestId = correlationFromBody(req.body);
291
+ try {
292
+ const rawBody = req.body;
293
+ if (!rawBody || typeof rawBody !== 'object' || Array.isArray(rawBody)) {
294
+ throw new ContractError({
295
+ errorCode: 'INVALID_PAYLOAD',
296
+ message: 'Request body must be a valid JSON object',
297
+ correlationId: correlationRequestId,
298
+ });
299
+ }
300
+ const bodyObj = rawBody;
301
+ if (bodyObj.schemaVersion !== 1) {
302
+ throw new ContractError({
303
+ errorCode: 'UNSUPPORTED_PROTOCOL_VERSION',
304
+ message: 'Unsupported schema version (expected 1)',
305
+ correlationId: correlationRequestId,
306
+ });
307
+ }
308
+ // A missing credential is an authorization failure, not a payload-shape failure.
309
+ if (typeof bodyObj.authToken !== 'string' || bodyObj.authToken.length === 0) {
310
+ throw new ContractError({
311
+ errorCode: 'MISSING_OR_INVALID_AUTHORIZATION',
312
+ message: 'Missing or invalid authorization token',
313
+ correlationId: correlationRequestId,
314
+ });
315
+ }
316
+ // Untrusted body: validate completely before authorization or any driver execution.
317
+ const parseResult = LoopbackHttpRequestV1Schema.safeParse(rawBody);
318
+ if (!parseResult.success) {
319
+ throw new ContractError({
320
+ errorCode: 'INVALID_PAYLOAD',
321
+ message: 'Payload validation failed',
322
+ correlationId: correlationRequestId,
323
+ details: {
324
+ issues: parseResult.error.issues.map((issue) => ({
325
+ path: issue.path.join('.'),
326
+ code: issue.code,
327
+ })),
328
+ },
329
+ });
330
+ }
331
+ const loopbackRequest = parseResult.data;
332
+ correlationRequestId = loopbackRequest.requestId;
333
+ if (loopbackRequest.action === 'DISPATCH_PROMPT') {
334
+ const missing = [];
335
+ if (!loopbackRequest.pluginId)
336
+ missing.push('pluginId');
337
+ if (!loopbackRequest.operationId)
338
+ missing.push('operationId');
339
+ if (!loopbackRequest.idempotencyKey)
340
+ missing.push('idempotencyKey');
341
+ const prompt = loopbackRequest.payload?.prompt;
342
+ if (typeof prompt !== 'string' || prompt.trim().length === 0)
343
+ missing.push('payload.prompt');
344
+ if (missing.length > 0) {
345
+ throw new ContractError({
346
+ errorCode: 'INVALID_PAYLOAD',
347
+ message: 'Missing or empty required dispatch fields',
348
+ correlationId: loopbackRequest.requestId,
349
+ projectId: loopbackRequest.projectId,
350
+ details: { missing },
351
+ });
352
+ }
353
+ }
354
+ if (loopbackRequest.action === 'GET_CONTEXT') {
355
+ // Read-only branch: no coordinator, no driver, no run state.
356
+ const grant = (dependencies.authorizeReadOnly ?? authorizeFixtureReadOnly)(loopbackRequest, dependencies.expectedToken);
357
+ if (!dependencies.evidenceSource) {
358
+ throw new ContractError({
359
+ errorCode: 'UNAUTHORIZED_PROJECT_OR_OPERATION',
360
+ message: 'No evidence source is configured',
361
+ correlationId: loopbackRequest.requestId,
362
+ projectId: loopbackRequest.projectId,
363
+ });
364
+ }
365
+ const evidenceResponse = {
366
+ schemaVersion: 1,
367
+ requestId: loopbackRequest.requestId,
368
+ statusCode: 200,
369
+ data: buildEvidenceData(grant, dependencies.evidenceSource, loopbackRequest.requestId),
370
+ };
371
+ return reply.status(200).send(evidenceResponse);
372
+ }
373
+ // Only the fixture authorizer can mint an approved invocation.
374
+ const authorizedInvocation = dependencies.authorize(loopbackRequest, dependencies.expectedToken);
375
+ const dispatchResult = await dependencies.coordinator.dispatch(authorizedInvocation, loopbackRequest.requestId);
376
+ if (dependencies.observationHook) {
377
+ try {
378
+ dependencies.observationHook(loopbackRequest);
379
+ }
380
+ catch {
381
+ // Observation hook must not fail response
382
+ }
383
+ }
384
+ const response = {
385
+ schemaVersion: 1,
386
+ requestId: loopbackRequest.requestId,
387
+ statusCode: 200,
388
+ data: {
389
+ runId: dispatchResult.runId,
390
+ status: dispatchResult.lifecycleRecord.currentState,
391
+ outputSummary: dispatchResult.result.outputSummary,
392
+ result: dispatchResult.result,
393
+ events: dispatchResult.events,
394
+ lifecycleRecord: dispatchResult.lifecycleRecord,
395
+ },
396
+ };
397
+ return reply.status(200).send(response);
398
+ }
399
+ catch (err) {
400
+ const contractError = err instanceof ContractError ? err : internalError(correlationRequestId);
401
+ return sendContractError(reply, contractError);
402
+ }
403
+ });
404
+ }
405
+ //# sourceMappingURL=dispatch.js.map
@@ -0,0 +1,40 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import { type FieldIssue } from '../../../../../packages/contracts/dist/index.js';
3
+ import type { ZodError } from 'zod';
4
+ import { PairedAuthority } from '../../projects/pairedAuthority.js';
5
+ import { DurableIntentCoordinator } from '../../runs/durableIntentCoordinator.js';
6
+ import type { SqliteLedger } from '../../storage/sqliteLedger.js';
7
+ import { DiagnosticLog } from '../../storage/diagnosticLog.js';
8
+ import type { WorkflowService } from '../../runs/workflowService.js';
9
+ import type { CodingWorkflowService } from '../../runs/codingWorkflowService.js';
10
+ /** Secure-mode body limit (bytes). */
11
+ export declare const SECURE_HTTP_BODY_LIMIT_BYTES = 65536;
12
+ /**
13
+ * SW-053: OPAQUE port to whatever trusted composition runs approved work. The HTTP layer knows nothing about drivers, processes or
14
+ * paths: it only reports "this principal's run was just queued" and "this principal asks to cancel this run". Ownership, re-authorization
15
+ * at launch, durable intent and process supervision all live behind the port. Absent = the secure daemon launches nothing (B02 behaviour).
16
+ */
17
+ export interface QueuedRunLauncher {
18
+ /** Fire-and-forget after an approval committed QUEUED. Must not throw; failures are recorded by the owner, never surfaced here. */
19
+ launch(principalId: string, runId: string): void;
20
+ /** Cancel a run that is running in this process. 'NOT_EXECUTING' means nothing here owns it (the caller keeps the normal 409). */
21
+ cancel(principalId: string, runId: string): Promise<'REQUESTED' | 'NOT_EXECUTING' | 'NOT_FOUND'>;
22
+ }
23
+ /** Deliberately narrow: no driver, shell command or process host is accepted; execution is reachable only through the opaque launcher port. */
24
+ export interface SecureDependencies {
25
+ authority: PairedAuthority;
26
+ coordinator: DurableIntentCoordinator;
27
+ ledger: SqliteLedger;
28
+ launcher?: QueuedRunLauncher;
29
+ /** SW-062: the daemon's diagnostic log. Absent = a memory-only log (nothing is written to disk). */
30
+ diag?: DiagnosticLog;
31
+ /** Trusted per-operation prompt ceiling in UTF-8 bytes; the default (16384) applies when absent or for any other answer. */
32
+ promptCapBytes?: (pluginId: string, operationId: string) => number;
33
+ /** SW-062: the durable capture/run/return workflow. Absent = the workflow routes are not registered (B02-B05 behaviour). */
34
+ workflow?: WorkflowService;
35
+ codingWorkflow?: () => Promise<CodingWorkflowService>;
36
+ }
37
+ /** Safe field-level detail from a Zod error: field names and a fixed reason only. The received value is NEVER read. */
38
+ export declare function fieldIssues(err: ZodError): FieldIssue[];
39
+ export declare function registerSecureRoutes(app: FastifyInstance, deps: SecureDependencies): void;
40
+ //# sourceMappingURL=secureRoutes.d.ts.map