@dailephd/my-centcom 0.2.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,221 @@
1
+ import { createProjectReadService, PR_LIMITS, PR_TOOLS } from '../../context/projectReadService.js';
2
+ import { validateProposal, CP_LIMITS } from '../../context/changeProposal.js';
3
+ import { createProposalRecorder } from '../../context/proposalRecorder.js';
4
+ /**
5
+ * SW-074 LOCAL PROJECT-READ MCP ADAPTER (stdio). This is NOT the optional ChatGPT-facing gateway (C10/M12): it opens no port, serves no remote client and is started only as a
6
+ * child of a coding-agent CLI by trusted configuration. It is an ADAPTER: every tools/call is passed to the C07 read service, which independently authorizes it against the
7
+ * run-scoped capability. A valid connection, an "auto-approved" tool annotation or a well-formed request confers nothing by itself.
8
+ *
9
+ * Transport: newline-delimited JSON-RPC 2.0 on stdin/stdout (MCP stdio). Bounded: one line is at most PR_LIMITS-derived 64 KiB; batches, binary framing and unknown methods are
10
+ * refused; stdout carries protocol messages only. Exposed surface: initialize, notifications/initialized, ping, tools/list, tools/call for exactly three read-only tools.
11
+ * No resources, prompts, sampling, logging, roots, completion, command execution, write or network tool exists in this process.
12
+ */
13
+ export const MCP_SERVER_NAME = 'centcom-project-read';
14
+ export const MCP_SERVER_VERSION = '1.0.0';
15
+ export const MCP_SUPPORTED_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
16
+ export const MCP_MAX_LINE_BYTES = 65_536;
17
+ const PATH_PROP = { type: 'string', minLength: 1, maxLength: PR_LIMITS.maxPathChars, description: 'Project-relative path using forward slashes. Never absolute, never containing "..".' };
18
+ const ANNOT = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
19
+ export const MCP_TOOL_DEFINITIONS = Object.freeze([
20
+ {
21
+ name: 'list_project_entries', title: 'List project entries',
22
+ description: 'List the files and directories directly inside one directory of the approved project. Read-only. Entries the project policy withholds (credentials, Git internals, private directories, links) are omitted.',
23
+ inputSchema: { type: 'object', additionalProperties: false, properties: { path: { ...PATH_PROP, description: 'Project-relative directory; omit for the project root.' }, limit: { type: 'integer', minimum: 1, maximum: PR_LIMITS.maxListEntries } } },
24
+ annotations: { title: 'List project entries', ...ANNOT },
25
+ },
26
+ {
27
+ name: 'read_project_text', title: 'Read project text',
28
+ description: 'Read UTF-8 text from one regular file of the approved project. Read-only and size-bounded; returns the SHA-256 of the whole file and of the returned range. Binary or non-UTF-8 files are refused.',
29
+ inputSchema: { type: 'object', additionalProperties: false, required: ['path'], properties: { path: PATH_PROP, offset: { type: 'integer', minimum: 0, maximum: PR_LIMITS.maxFileBytes, description: 'Byte offset; must be on a character boundary.' }, max_bytes: { type: 'integer', minimum: 1, maximum: PR_LIMITS.maxReadBytes } } },
30
+ annotations: { title: 'Read project text', ...ANNOT },
31
+ },
32
+ {
33
+ name: 'get_project_file_metadata', title: 'Get project file metadata',
34
+ description: 'Return size, SHA-256 digest, file identity and modification time of one regular file of the approved project, without its content. Read-only.',
35
+ inputSchema: { type: 'object', additionalProperties: false, required: ['path'], properties: { path: PATH_PROP } },
36
+ annotations: { title: 'Get project file metadata', ...ANNOT },
37
+ },
38
+ ]);
39
+ /** SW-080: listed ONLY when the run's capability carries it (a PROPOSE grant authorized it). It records data; it can neither modify the project nor run anything. */
40
+ export const MCP_PROPOSE_TOOL_DEFINITION = Object.freeze({
41
+ name: 'propose_change', title: 'Propose a change',
42
+ description: 'Submit ONE proposed code change for human review. The project is NOT modified. Each operation names a project-relative path; modify, delete and rename must carry the SHA-256 of the file as you last read it (get_project_file_metadata). Operations: create (path, content), modify (path, preimageSha256, content = the complete new file text), delete (path, preimageSha256), rename (path, to, preimageSha256). Files under tests/ and executable configuration such as package.json cannot be proposed.',
43
+ inputSchema: { type: 'object', additionalProperties: false, required: ['summary', 'operations'], properties: {
44
+ summary: { type: 'string', minLength: 1, maxLength: CP_LIMITS.maxSummaryChars },
45
+ operations: { type: 'array', minItems: 1, maxItems: CP_LIMITS.maxOperations, items: { type: 'object', required: ['op', 'path'], properties: { op: { enum: ['create', 'modify', 'delete', 'rename'] }, path: PATH_PROP, to: PATH_PROP,
46
+ preimageSha256: { type: 'string', pattern: '^[a-f0-9]{64}$' }, content: { type: 'string', maxLength: CP_LIMITS.maxFileContentBytes } } } }
47
+ } },
48
+ annotations: { title: 'Propose a change', readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
49
+ });
50
+ const errorOf = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
51
+ /** Pure protocol adapter over an injected read service and an injected output sink (the entry point wires stdin/stdout). */
52
+ export function createMcpAdapter(service, out) {
53
+ let initialized = false;
54
+ let stopped = false;
55
+ function handle(msg) {
56
+ if (Array.isArray(msg))
57
+ return out(errorOf(null, -32600, 'batch requests are not supported'));
58
+ if (msg === null || typeof msg !== 'object')
59
+ return out(errorOf(null, -32600, 'invalid request'));
60
+ const m = msg;
61
+ const hasId = Object.prototype.hasOwnProperty.call(m, 'id');
62
+ const id = m.id;
63
+ if (m.jsonrpc !== '2.0' || typeof m.method !== 'string')
64
+ return out(errorOf(hasId && (typeof id === 'string' || typeof id === 'number') ? id : null, -32600, 'invalid request'));
65
+ if (hasId && typeof id !== 'string' && typeof id !== 'number')
66
+ return out(errorOf(null, -32600, 'invalid request id'));
67
+ const isRequest = hasId;
68
+ const method = m.method;
69
+ const params = m.params;
70
+ if (params !== undefined && (params === null || typeof params !== 'object' || Array.isArray(params)))
71
+ return isRequest ? out(errorOf(id, -32602, 'invalid params')) : undefined;
72
+ const p = (params ?? {});
73
+ if (!isRequest) {
74
+ if (method === 'notifications/initialized')
75
+ initialized = true;
76
+ return;
77
+ } // every other notification is ignored, never answered
78
+ switch (method) {
79
+ case 'initialize': {
80
+ const v = p.protocolVersion;
81
+ if (typeof v !== 'string')
82
+ return out(errorOf(id, -32602, 'protocolVersion is required'));
83
+ const chosen = MCP_SUPPORTED_VERSIONS.includes(v) ? v : MCP_SUPPORTED_VERSIONS[0];
84
+ return out({ jsonrpc: '2.0', id, result: { protocolVersion: chosen, capabilities: { tools: { listChanged: false } }, serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION } } });
85
+ }
86
+ case 'ping': return out({ jsonrpc: '2.0', id, result: {} });
87
+ case 'tools/list':
88
+ return out({ jsonrpc: '2.0', id, result: { tools: service.tools.includes('propose_change') ? [...MCP_TOOL_DEFINITIONS, MCP_PROPOSE_TOOL_DEFINITION] : MCP_TOOL_DEFINITIONS } });
89
+ case 'tools/call': {
90
+ if (typeof p.name !== 'string')
91
+ return out(errorOf(id, -32602, 'tool name is required'));
92
+ const args = p.arguments === undefined ? {} : p.arguments;
93
+ const r = service.call(p.name, args);
94
+ if (!r.ok && r.code === 'TOOL_UNKNOWN')
95
+ return out(errorOf(id, -32602, 'unknown tool'));
96
+ const body = r.ok ? r.value : { error: { code: r.code, message: r.message } };
97
+ const text = JSON.stringify(body);
98
+ return out({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }], ...(r.ok ? { structuredContent: body } : {}), isError: !r.ok } });
99
+ }
100
+ default:
101
+ return out(errorOf(id, -32601, 'method not found'));
102
+ }
103
+ }
104
+ return {
105
+ handleLine(line) {
106
+ if (stopped)
107
+ return;
108
+ if (Buffer.byteLength(line, 'utf8') > MCP_MAX_LINE_BYTES)
109
+ return out(errorOf(null, -32600, 'message too large'));
110
+ if (line.trim().length === 0)
111
+ return;
112
+ let msg;
113
+ try {
114
+ msg = JSON.parse(line);
115
+ }
116
+ catch {
117
+ return out(errorOf(null, -32700, 'parse error'));
118
+ }
119
+ try {
120
+ handle(msg);
121
+ }
122
+ catch {
123
+ out(errorOf(null, -32603, 'internal error'));
124
+ }
125
+ },
126
+ close() { if (!stopped) {
127
+ stopped = true;
128
+ try {
129
+ service.stop();
130
+ }
131
+ catch { /* best-effort */ }
132
+ } },
133
+ };
134
+ }
135
+ /** Bounded newline framing: a line over the cap is discarded WITHOUT being buffered and reported once. */
136
+ export function createLineSplitter(max, onLine, onOversize) {
137
+ let parts = [];
138
+ let size = 0;
139
+ let discarding = false;
140
+ const emit = () => { const b = Buffer.concat(parts, size); parts = []; size = 0; try {
141
+ onLine(new TextDecoder('utf-8', { fatal: false }).decode(b));
142
+ }
143
+ catch { /* handled by adapter */ } };
144
+ return {
145
+ push(chunk) {
146
+ let start = 0;
147
+ for (;;) {
148
+ const nl = chunk.indexOf(0x0a, start);
149
+ const end = nl < 0 ? chunk.length : nl;
150
+ if (!discarding) {
151
+ size += end - start;
152
+ if (size > max) {
153
+ discarding = true;
154
+ parts = [];
155
+ size = 0;
156
+ onOversize();
157
+ }
158
+ else if (end > start)
159
+ parts.push(chunk.subarray(start, end));
160
+ }
161
+ if (nl < 0)
162
+ return;
163
+ if (discarding)
164
+ discarding = false;
165
+ else
166
+ emit();
167
+ start = nl + 1;
168
+ }
169
+ },
170
+ end() { if (!discarding && size > 0)
171
+ emit(); },
172
+ };
173
+ }
174
+ // ---------------------------------------------------------------------------------------------------------------------------------------------------
175
+ // Entry point (only when executed, never when imported by tests).
176
+ // Configuration comes from the TRUSTED launcher's environment, never from the protocol:
177
+ // CENTCOM_PROJECT_READ_CAPABILITY absolute path of the run-scoped capability descriptor (host-pinned file)
178
+ // TEMP (or CENTCOM_PROJECT_READ_AUDIT_DIR, test override) the audit directory is <TEMP>/mcp-audit, created by the daemon; <capabilityId>.audit.jsonl is appended there
179
+ // CENTCOM_PROJECT_READ_RUN / _PROJECT optional expected bindings, rejected on mismatch
180
+ // ---------------------------------------------------------------------------------------------------------------------------------------------------
181
+ async function main() {
182
+ const capabilityPath = process.env.CENTCOM_PROJECT_READ_CAPABILITY;
183
+ if (!capabilityPath) {
184
+ process.stderr.write('centcom-project-read: capability missing\n');
185
+ process.exit(2);
186
+ }
187
+ const { readFileSync } = await import('node:fs');
188
+ const { join } = await import('node:path');
189
+ let auditPath;
190
+ const temp = process.env.TEMP ?? process.env.TMP;
191
+ const dir = process.env.CENTCOM_PROJECT_READ_AUDIT_DIR ?? (temp ? join(temp, 'mcp-audit') : undefined);
192
+ try {
193
+ const c = JSON.parse(readFileSync(capabilityPath, 'utf8'));
194
+ if (dir && typeof c.capabilityId === 'string' && /^cap\.[A-Za-z0-9_-]{16,64}$/.test(c.capabilityId))
195
+ auditPath = join(dir, `${c.capabilityId}.audit.jsonl`);
196
+ }
197
+ catch { /* the service refuses an unreadable capability below */ }
198
+ const expect = {};
199
+ if (process.env.CENTCOM_PROJECT_READ_RUN)
200
+ expect.runId = process.env.CENTCOM_PROJECT_READ_RUN;
201
+ if (process.env.CENTCOM_PROJECT_READ_PROJECT)
202
+ expect.projectId = process.env.CENTCOM_PROJECT_READ_PROJECT;
203
+ const proposeDir = temp ? join(temp, 'mcp-proposals') : undefined;
204
+ const svc = createProjectReadService({ capabilityPath, ...(auditPath ? { auditPath } : {}), expect,
205
+ ...(proposeDir ? { propose: { record: createProposalRecorder(proposeDir), validate: (input, root) => { const r = validateProposal(input, { root }); return r.ok ? { ok: true, canonicalJson: r.canonicalJson, digest: r.digest, effect: r.effect } : { ok: false, code: String(r.code), message: r.message }; } } } : {}) });
206
+ if (!svc.ok) {
207
+ process.stderr.write(`centcom-project-read: refused to start (${svc.code})\n`);
208
+ process.exit(2);
209
+ }
210
+ const adapter = createMcpAdapter(svc.value, (m) => { process.stdout.write(JSON.stringify(m) + '\n'); });
211
+ const split = createLineSplitter(MCP_MAX_LINE_BYTES, (l) => adapter.handleLine(l), () => process.stdout.write(JSON.stringify(errorOf(null, -32600, 'message too large')) + '\n'));
212
+ process.stdin.on('data', (c) => split.push(c));
213
+ process.stdin.on('end', () => { split.end(); adapter.close(); process.exit(0); });
214
+ process.stdin.on('error', () => { adapter.close(); process.exit(0); });
215
+ process.on('SIGTERM', () => { adapter.close(); process.exit(0); });
216
+ }
217
+ const entry = process.argv[1] ?? '';
218
+ if (/localProjectReadServer\.m?js$/i.test(entry.replace(/\\/g, '/')))
219
+ void main();
220
+ void PR_TOOLS;
221
+ //# sourceMappingURL=localProjectReadServer.js.map
@@ -0,0 +1,24 @@
1
+ import { type NativeResponseV1 } from '../../../../../packages/contracts/dist/index.js';
2
+ import { type HostConfigV1 } from '../../bootstrap/installLayout.js';
3
+ import { type Dpapi } from '../../storage/protectedSecrets.js';
4
+ import { DiagnosticLog } from '../../storage/diagnosticLog.js';
5
+ export interface HostIo {
6
+ readMessage(): Promise<Buffer | 'TOO_LARGE' | 'EOF'>;
7
+ writeMessage(obj: unknown): Promise<void>;
8
+ }
9
+ /** Chrome framing: 4-byte little-endian length, then UTF-8 JSON. The body is rejected before it is buffered if the announced length is too large. */
10
+ export declare function stdioHostIo(input?: NodeJS.ReadableStream, output?: NodeJS.WritableStream): HostIo;
11
+ export interface HostDeps {
12
+ dpapi: Dpapi;
13
+ /** Starts the daemon process (production: detached, hidden, no console). Returns the child pid. */
14
+ spawnDaemon(cfg: HostConfigV1): number;
15
+ now(): number;
16
+ startTimeoutMs: number;
17
+ log?: DiagnosticLog;
18
+ }
19
+ export declare const productionHostDeps: (log?: DiagnosticLog) => HostDeps;
20
+ /** The whole CONNECT decision. Exported for process-level tests (the same code the real host runs). */
21
+ export declare function connect(cfg: HostConfigV1, deps: HostDeps): Promise<NativeResponseV1>;
22
+ /** Handles exactly one message. `callerOrigin` is the origin argument Chrome passed (with its trailing slash). */
23
+ export declare function handleOne(io: HostIo, configPath: string | undefined, callerOrigin: string | undefined, deps: HostDeps): Promise<NativeResponseV1>;
24
+ //# sourceMappingURL=nativeHost.d.ts.map
@@ -0,0 +1,344 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { request } from 'node:http';
4
+ import { join } from 'node:path';
5
+ import { realpathSync } from 'node:fs';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { BootstrapSessionResponseV1Schema, NATIVE_MAX_INBOUND_BYTES, NATIVE_MAX_OUTBOUND_BYTES, NativeRequestV1Schema, NativeResponseV1Schema, SCHEMA_VERSION_V1, } from '../../../../../packages/contracts/dist/index.js';
8
+ import { HOST_VERSION, HostConfigV1Schema, daemonTreeDigest, macMatches, sha256File } from '../../bootstrap/installLayout.js';
9
+ import { windowsDpapi } from '../../storage/protectedSecrets.js';
10
+ import { DiagnosticLog, DIAG_LOG_DIR_NAME } from '../../storage/diagnosticLog.js';
11
+ /**
12
+ * C02 NATIVE MESSAGING BOOTSTRAP HOST (SW-062). Chrome starts this (hidden) for ONE message from the pinned extension and stops it after the reply.
13
+ *
14
+ * It is deliberately NOT a shell, proxy, file reader or agent executor. It understands exactly two requests:
15
+ * PING -> is an installation present for this extension?
16
+ * CONNECT -> find the installed daemon (or start it from the pinned, digest-verified files) and obtain a short-lived session bearer for the
17
+ * installation's principal, which it hands back to the extension. Bulk traffic stays on the authenticated loopback HTTP data plane.
18
+ * Nothing in a message selects a program, path, argument, port or environment: all of that comes from the pinned host configuration, whose fields are
19
+ * covered by an HMAC keyed with the DPAPI-protected installation secret. The calling origin is the one CHROME passes on the command line, compared with
20
+ * the single pinned extension origin. Messages are length-bounded and schema-validated; secrets are never logged.
21
+ */
22
+ const PID_RE = /^\d{1,10}$/;
23
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
24
+ /** Chrome framing: 4-byte little-endian length, then UTF-8 JSON. The body is rejected before it is buffered if the announced length is too large. */
25
+ export function stdioHostIo(input = process.stdin, output = process.stdout) {
26
+ let buf = Buffer.alloc(0);
27
+ let ended = false;
28
+ const waiters = [];
29
+ input.on('data', (d) => { buf = Buffer.concat([buf, d]); while (waiters.length)
30
+ waiters.shift()?.(); if (buf.length > NATIVE_MAX_INBOUND_BYTES + 4)
31
+ input.pause(); });
32
+ input.on('end', () => { ended = true; while (waiters.length)
33
+ waiters.shift()?.(); });
34
+ input.on('error', () => { ended = true; while (waiters.length)
35
+ waiters.shift()?.(); });
36
+ const need = async (n) => { while (buf.length < n && !ended)
37
+ await new Promise((r) => waiters.push(r)); return buf.length >= n; };
38
+ return {
39
+ async readMessage() {
40
+ if (!(await need(4)))
41
+ return 'EOF';
42
+ const len = buf.readUInt32LE(0);
43
+ if (len === 0 || len > NATIVE_MAX_INBOUND_BYTES)
44
+ return 'TOO_LARGE';
45
+ if (!(await need(4 + len)))
46
+ return 'EOF';
47
+ const body = buf.subarray(4, 4 + len);
48
+ buf = buf.subarray(4 + len);
49
+ return body;
50
+ },
51
+ async writeMessage(obj) {
52
+ const body = Buffer.from(JSON.stringify(obj), 'utf8');
53
+ if (body.length > NATIVE_MAX_OUTBOUND_BYTES)
54
+ throw new Error('OUTBOUND_TOO_LARGE');
55
+ const head = Buffer.alloc(4);
56
+ head.writeUInt32LE(body.length, 0);
57
+ await new Promise((resolve) => output.write(Buffer.concat([head, body]), () => resolve()));
58
+ },
59
+ };
60
+ }
61
+ class HostRefusal extends Error {
62
+ code;
63
+ constructor(code) {
64
+ super(code);
65
+ this.code = code;
66
+ }
67
+ }
68
+ function pidAlive(pid) {
69
+ try {
70
+ process.kill(pid, 0);
71
+ return true;
72
+ }
73
+ catch (e) {
74
+ return e.code === 'EPERM';
75
+ }
76
+ }
77
+ /** One loopback POST without any Origin or browser metadata. Bounded size and time. */
78
+ function postJson(port, path, body, timeoutMs = 4000) {
79
+ return new Promise((resolve) => {
80
+ const data = Buffer.from(JSON.stringify(body), 'utf8');
81
+ const req = request({ host: '127.0.0.1', port, path, method: 'POST', headers: { 'content-type': 'application/json', 'content-length': data.length }, timeout: timeoutMs }, (res) => {
82
+ const chunks = [];
83
+ let n = 0;
84
+ res.on('data', (c) => { n += c.length; if (n > 16384) {
85
+ req.destroy();
86
+ resolve('NOT_A_DAEMON');
87
+ }
88
+ else
89
+ chunks.push(c); });
90
+ res.on('end', () => {
91
+ if (!String(res.headers['content-type'] ?? '').startsWith('application/json'))
92
+ return resolve('NOT_A_DAEMON');
93
+ try {
94
+ resolve({ status: res.statusCode ?? 0, json: JSON.parse(Buffer.concat(chunks).toString('utf8')) });
95
+ }
96
+ catch {
97
+ resolve('NOT_A_DAEMON');
98
+ }
99
+ });
100
+ });
101
+ req.on('timeout', () => { req.destroy(); resolve('UNREACHABLE'); });
102
+ req.on('error', () => resolve('UNREACHABLE'));
103
+ req.end(data);
104
+ });
105
+ }
106
+ export const productionHostDeps = (log) => ({
107
+ dpapi: windowsDpapi,
108
+ now: Date.now,
109
+ startTimeoutMs: 30_000,
110
+ ...(log ? { log } : {}),
111
+ spawnDaemon(cfg) {
112
+ const env = {
113
+ SystemRoot: process.env.SystemRoot ?? 'C:\\Windows',
114
+ MY_CENTCOM_PROJECT_ROOT: cfg.projectRoot,
115
+ MY_CENTCOM_DATA_ROOT: cfg.dataRoot,
116
+ MY_CENTCOM_PUBLISH_RUNTIME: '1',
117
+ TEMP: join(cfg.projectRoot, '.switchyard-data', 'child-tmp'), TMP: join(cfg.projectRoot, '.switchyard-data', 'child-tmp'),
118
+ ...(cfg.approvedProject ? { MY_CENTCOM_APPROVED_PROJECT_ROOT: cfg.approvedProject.root, MY_CENTCOM_APPROVED_PROJECT_ID: cfg.approvedProject.projectId } : {}),
119
+ ...(cfg.devSmokeProfiles ? { MY_CENTCOM_DEV_SMOKE: '1' } : {}),
120
+ ...(process.env.ProgramFiles ? { ProgramFiles: process.env.ProgramFiles } : {}), ...(process.env.ProgramW6432 ? { ProgramW6432: process.env.ProgramW6432 } : {}),
121
+ ...(process.env.SystemDrive ? { SystemDrive: process.env.SystemDrive } : {}), ...(process.env.USERPROFILE ? { USERPROFILE: process.env.USERPROFILE } : {}),
122
+ ...(process.env.LOCALAPPDATA ? { LOCALAPPDATA: process.env.LOCALAPPDATA } : {}), ...(process.env.APPDATA ? { APPDATA: process.env.APPDATA } : {}),
123
+ };
124
+ mkdirSync(env.TEMP, { recursive: true });
125
+ // SW-063: a plain detached Node spawn (libuv bInheritHandles=TRUE) hands the daemon every inheritable handle of THIS process, which includes the
126
+ // pipe ends Chrome gave the host. A daemon holding them keeps the browser's pipes open after the browser quits (measured: Playwright's close()
127
+ // never resolved while the daemon lived). Start-Process goes through ShellExecute, which inherits NO handles, so the daemon is fully independent of
128
+ // Chrome. The short-lived PowerShell only carries three pinned paths (via its private environment, removed before the daemon starts) and exits.
129
+ for (const v of [cfg.nodeExe, cfg.daemonEntry, cfg.projectRoot])
130
+ if (/["'%\r\n`$;&|<>^]/.test(v))
131
+ throw new HostRefusal('DAEMON_START_FAILED');
132
+ const ps = join(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
133
+ const script = "$n=$env:MC_N;$e=$env:MC_E;$c=$env:MC_C;Remove-Item Env:MC_N,Env:MC_E,Env:MC_C;" +
134
+ "$p=Start-Process -FilePath $n -ArgumentList ('\"'+$e+'\"') -WorkingDirectory $c -WindowStyle Hidden -PassThru;[Console]::Out.Write($p.Id)";
135
+ const r = spawnSync(ps, ['-NoProfile', '-NonInteractive', '-Command', script], {
136
+ env: { ...env, MC_N: cfg.nodeExe, MC_E: cfg.daemonEntry, MC_C: cfg.projectRoot }, windowsHide: true, shell: false, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 20_000,
137
+ });
138
+ const pid = Number((r.stdout ?? '').trim());
139
+ if (r.status !== 0 || !Number.isInteger(pid) || pid <= 0)
140
+ throw new HostRefusal('DAEMON_START_FAILED');
141
+ return pid;
142
+ },
143
+ });
144
+ function readConfig(path) {
145
+ let raw;
146
+ try {
147
+ raw = JSON.parse(readFileSync(path, 'utf8'));
148
+ }
149
+ catch (e) {
150
+ throw new HostRefusal(e.code === 'ENOENT' ? 'HOST_NOT_INSTALLED' : 'HOST_CONFIG_INVALID');
151
+ }
152
+ const p = HostConfigV1Schema.safeParse(raw);
153
+ if (!p.success)
154
+ throw new HostRefusal('HOST_CONFIG_INVALID');
155
+ return p.data;
156
+ }
157
+ function readRuntime(dataRoot) {
158
+ try {
159
+ const r = JSON.parse(readFileSync(join(dataRoot, 'run', 'daemon.json'), 'utf8'));
160
+ if (typeof r.port === 'number' && Number.isInteger(r.port) && r.port > 0 && r.port < 65536 && typeof r.pid === 'number' && PID_RE.test(String(r.pid)))
161
+ return { port: r.port, pid: r.pid };
162
+ }
163
+ catch { /* absent */ }
164
+ return undefined;
165
+ }
166
+ async function trySession(cfg, secret, port) {
167
+ const r = await postJson(port, '/v1/bootstrap/session', { schemaVersion: SCHEMA_VERSION_V1, installationId: cfg.installationId, secret, extensionOrigin: cfg.extensionOrigin });
168
+ if (r === 'UNREACHABLE' || r === 'NOT_A_DAEMON')
169
+ return { ok: false, why: r };
170
+ if (r.status === 403)
171
+ return { ok: false, why: 'REFUSED' };
172
+ if (r.status !== 200)
173
+ return { ok: false, why: 'NOT_A_DAEMON' };
174
+ const p = BootstrapSessionResponseV1Schema.safeParse(r.json);
175
+ if (!p.success || p.data.installationId !== cfg.installationId)
176
+ return { ok: false, why: 'NOT_A_DAEMON' };
177
+ return { ok: true, bearer: p.data.bearerToken, expiresAt: p.data.expiresAt };
178
+ }
179
+ /** The whole CONNECT decision. Exported for process-level tests (the same code the real host runs). */
180
+ export async function connect(cfg, deps) {
181
+ let secret;
182
+ try {
183
+ secret = deps.dpapi.unprotect(Buffer.from(cfg.protectedSecretB64, 'base64')).toString('utf8');
184
+ }
185
+ catch {
186
+ throw new HostRefusal('HOST_CONFIG_INVALID');
187
+ }
188
+ if (!/^[A-Za-z0-9_-]{32,128}$/.test(secret) || !macMatches(secret, cfg))
189
+ throw new HostRefusal('HOST_CONFIG_TAMPERED');
190
+ const respond = (port, s, started) => NativeResponseV1Schema.parse({ v: 1, ok: true, type: 'CONNECTED', port, bearerToken: s.bearer, expiresAt: s.expiresAt, installationId: cfg.installationId, daemonStarted: started });
191
+ const rt = readRuntime(cfg.dataRoot);
192
+ if (rt && pidAlive(rt.pid)) {
193
+ const s = await trySession(cfg, secret, rt.port);
194
+ if (s.ok)
195
+ return respond(rt.port, s, false);
196
+ if (s.why === 'REFUSED')
197
+ throw new HostRefusal('SESSION_REFUSED');
198
+ // the record points at something that is not our daemon (stale port reused, hung process): fall through to a fresh, verified start
199
+ deps.log?.warn('DAEMON', 'host.connect', 'RUNTIME_RECORD_STALE', { outcome: 'REFUSED', meta: { why: s.why } });
200
+ }
201
+ // Pinned-file verification BEFORE anything is started.
202
+ try {
203
+ if (sha256File(cfg.nodeExe) !== cfg.nodeSha256)
204
+ throw new HostRefusal('INSTALL_INTEGRITY_FAILED');
205
+ }
206
+ catch (e) {
207
+ throw e instanceof HostRefusal ? e : new HostRefusal('INSTALL_INTEGRITY_FAILED');
208
+ }
209
+ if (!existsSync(cfg.daemonEntry) || daemonTreeDigest(cfg.projectRoot) !== cfg.daemonTreeSha256)
210
+ throw new HostRefusal('UPDATE_REQUIRES_RECONSENT');
211
+ // One starter at a time: a second host racing us waits for the first start instead of launching another daemon.
212
+ const runDir = join(cfg.dataRoot, 'run');
213
+ mkdirSync(runDir, { recursive: true });
214
+ const startLock = join(runDir, 'start.lock');
215
+ let iStart = false;
216
+ try {
217
+ writeFileSync(startLock, String(process.pid), { flag: 'wx' });
218
+ iStart = true;
219
+ }
220
+ catch {
221
+ // SW-063: a host killed right after taking the lock must not block the next connect for the whole timeout. The lock records its owner's pid, so a
222
+ // dead owner releases it at once. (If two hosts race this takeover the daemon's own single-instance lock still admits exactly one daemon.)
223
+ const ownerDead = () => { try {
224
+ const h = Number(readFileSync(startLock, 'utf8').trim());
225
+ return Number.isInteger(h) && h > 0 && !pidAlive(h);
226
+ }
227
+ catch {
228
+ return false;
229
+ } };
230
+ try {
231
+ if (ownerDead() || deps.now() - statSync(startLock).mtimeMs > deps.startTimeoutMs) {
232
+ rmSync(startLock, { force: true });
233
+ writeFileSync(startLock, String(process.pid), { flag: 'wx' });
234
+ iStart = true;
235
+ }
236
+ }
237
+ catch { /* another host owns the start */ }
238
+ }
239
+ try {
240
+ let childPid;
241
+ if (iStart) {
242
+ childPid = deps.spawnDaemon(cfg);
243
+ deps.log?.info('DAEMON', 'host.connect', 'DAEMON_START_REQUESTED', { outcome: 'STARTED', meta: { pid: childPid } });
244
+ }
245
+ const deadline = deps.now() + deps.startTimeoutMs;
246
+ while (deps.now() < deadline) {
247
+ const r = readRuntime(cfg.dataRoot);
248
+ if (r && (childPid === undefined || r.pid === childPid) && pidAlive(r.pid)) {
249
+ const s = await trySession(cfg, secret, r.port);
250
+ if (s.ok)
251
+ return respond(r.port, s, iStart);
252
+ if (s.why === 'REFUSED')
253
+ throw new HostRefusal('SESSION_REFUSED');
254
+ }
255
+ if (childPid !== undefined && !pidAlive(childPid))
256
+ throw new HostRefusal('DAEMON_START_FAILED');
257
+ await sleep(150);
258
+ }
259
+ throw new HostRefusal(iStart ? 'DAEMON_START_FAILED' : 'DAEMON_NOT_RESPONDING');
260
+ }
261
+ finally {
262
+ if (iStart)
263
+ rmSync(startLock, { force: true });
264
+ }
265
+ }
266
+ /** Handles exactly one message. `callerOrigin` is the origin argument Chrome passed (with its trailing slash). */
267
+ export async function handleOne(io, configPath, callerOrigin, deps) {
268
+ const refuse = (code) => ({ v: 1, ok: false, code });
269
+ const raw = await io.readMessage();
270
+ if (raw === 'EOF')
271
+ return refuse('HOST_MESSAGE_INVALID');
272
+ if (raw === 'TOO_LARGE')
273
+ return refuse('HOST_MESSAGE_TOO_LARGE');
274
+ let msg;
275
+ try {
276
+ msg = JSON.parse(raw.toString('utf8'));
277
+ }
278
+ catch {
279
+ return refuse('HOST_MESSAGE_INVALID');
280
+ }
281
+ const m = NativeRequestV1Schema.safeParse(msg);
282
+ if (!m.success)
283
+ return refuse('HOST_MESSAGE_INVALID');
284
+ try {
285
+ if (!configPath)
286
+ throw new HostRefusal('HOST_NOT_INSTALLED');
287
+ const cfg = readConfig(configPath);
288
+ const origin = typeof callerOrigin === 'string' ? callerOrigin.replace(/\/$/, '') : '';
289
+ if (origin !== cfg.extensionOrigin)
290
+ throw new HostRefusal('HOST_ORIGIN_MISMATCH');
291
+ if (m.data.type === 'PING')
292
+ return { v: 1, ok: true, type: 'PONG', installed: true, hostVersion: HOST_VERSION };
293
+ return await connect(cfg, deps);
294
+ }
295
+ catch (e) {
296
+ const code = e instanceof HostRefusal ? e.code : 'HOST_INTERNAL_ERROR';
297
+ deps.log?.warn('DAEMON', 'host.handle', code, { outcome: 'REFUSED' });
298
+ return refuse(code);
299
+ }
300
+ }
301
+ function argValue(argv, name) {
302
+ const i = argv.indexOf(name);
303
+ return i >= 0 && i + 1 < argv.length ? argv[i + 1] : undefined;
304
+ }
305
+ async function main() {
306
+ const argv = process.argv.slice(2);
307
+ const configPath = argValue(argv, '--config');
308
+ const callerOrigin = argv.find((a) => /^chrome-extension:\/\/[a-p]{32}\/?$/.test(a));
309
+ let log;
310
+ try {
311
+ if (configPath) {
312
+ const cfg = HostConfigV1Schema.safeParse(JSON.parse(readFileSync(configPath, 'utf8')));
313
+ if (cfg.success)
314
+ log = new DiagnosticLog({ dir: join(cfg.data.dataRoot, DIAG_LOG_DIR_NAME), fileName: 'native-host.log' });
315
+ }
316
+ }
317
+ catch { /* logging is optional; the reply still follows */ }
318
+ const io = stdioHostIo();
319
+ const reply = await handleOne(io, configPath, callerOrigin, productionHostDeps(log));
320
+ log?.info('DAEMON', 'host.reply', reply.ok ? reply.type : reply.code, { outcome: reply.ok ? 'OK' : 'REFUSED' });
321
+ await io.writeMessage(reply);
322
+ process.exit(0);
323
+ }
324
+ const isDirect = (() => { try {
325
+ return realpathSync(fileURLToPath(import.meta.url)).toLowerCase() === realpathSync(process.argv[1] ?? '').toLowerCase();
326
+ }
327
+ catch {
328
+ return false;
329
+ } })();
330
+ if (isDirect) {
331
+ main().catch(() => {
332
+ // last resort: a fixed refusal, never a stack trace or a path on the wire
333
+ try {
334
+ const b = Buffer.from(JSON.stringify({ v: 1, ok: false, code: 'HOST_INTERNAL_ERROR' }));
335
+ const h = Buffer.alloc(4);
336
+ h.writeUInt32LE(b.length, 0);
337
+ process.stdout.write(Buffer.concat([h, b]), () => process.exit(0));
338
+ }
339
+ catch {
340
+ process.exit(0);
341
+ }
342
+ });
343
+ }
344
+ //# sourceMappingURL=nativeHost.js.map
@@ -0,0 +1,24 @@
1
+ {
2
+ "name": "@my-centcom/daemon",
3
+ "version": "0.3.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "./dist/bootstrap/main.js",
7
+ "types": "./dist/bootstrap/main.d.ts",
8
+ "scripts": {
9
+ "build": "tsc --project tsconfig.json",
10
+ "build:supervisor": "node src/runtime/windows/buildSupervisor.mjs",
11
+ "build:supervisor:testhooks": "node src/runtime/windows/buildSupervisor.mjs --test-hooks",
12
+ "start:secure": "node dist/bootstrap/main.js",
13
+ "start:secure:operator": "node dist/bootstrap/main.js --operator-console",
14
+ "typecheck": "tsc --noEmit --project tsconfig.json"
15
+ },
16
+ "dependencies": {
17
+ "fastify": "^5.2.1",
18
+ "zod": "4.6.7"
19
+ },
20
+ "devDependencies": {
21
+ "@types/node": "^22.13.1",
22
+ "typescript": "^5.7.3"
23
+ }
24
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * SW-062 BENIGN REFERENCE "CLI" for the DEV_SMOKE profile `reference-script-stdin` and the setup self-test. NOT an agent, NOT a model, no network, no file
3
+ * writes. It speaks the JSONL frame shapes of `codex exec --json` (the codex-exec-jsonl-v1 parser): it reads ALL of stdin and reports it back as the final
4
+ * agent message followed by one trailing LF. It runs only when a trusted local setup provisioned it, pinned by digest, under the restricted Job supervisor.
5
+ *
6
+ * exec --json --mode stdin-echo echo stdin as the final message
7
+ * exec --json --mode stdin-stall never reads stdin, exits after 25 s (cancel / timeout / crash-recovery exercises)
8
+ */
9
+ const argv = process.argv.slice(2);
10
+ const emit = (o) => process.stdout.write(JSON.stringify(o) + '\n');
11
+ const usage = () => { process.stderr.write('REFERENCE_USAGE\n'); process.exit(64); };
12
+
13
+ if (argv[0] !== 'exec' || argv[1] !== '--json' || argv[2] !== '--mode' || argv.length !== 4) usage();
14
+ emit({ type: 'thread.started', thread_id: 'reference-thread' });
15
+ emit({ type: 'turn.started' });
16
+ if (argv[3] === 'stdin-echo') {
17
+ const chunks = [];
18
+ process.stdin.on('data', (c) => chunks.push(c));
19
+ process.stdin.on('end', () => {
20
+ emit({ type: 'item.completed', item: { id: 'item_1', type: 'agent_message', text: Buffer.concat(chunks).toString('utf8') + '\n' } });
21
+ emit({ type: 'turn.completed', usage: { input_tokens: 0, cached_input_tokens: 0, output_tokens: 0 } });
22
+ });
23
+ } else if (argv[3] === 'stdin-stall') {
24
+ setTimeout(() => process.exit(0), 25000);
25
+ } else {
26
+ usage();
27
+ }