@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,752 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash, timingSafeEqual } from 'node:crypto';
3
+ import { lstatSync, readFileSync, realpathSync, statSync, existsSync } from 'node:fs';
4
+ import { open } from 'node:fs/promises';
5
+ import { join, isAbsolute, normalize, sep } from 'node:path';
6
+ import { RunIdSchema } from '../../../../packages/contracts/dist/index.js';
7
+ import { isWindowsJobSupervisor, STDIN_MAX_BYTES } from './windows/windowsJobSupervisor.js';
8
+ /** Sanitized: only a fixed code, never a path, argument, environment value or output. */
9
+ export class ProcessHostError extends Error {
10
+ code;
11
+ constructor(code) {
12
+ super(code);
13
+ this.code = code;
14
+ this.name = 'ProcessHostError';
15
+ }
16
+ }
17
+ /**
18
+ * SW-052: the largest per-run timeout a trusted constructor may configure. The DEFAULT stays 30 s; only the trusted owner (never a
19
+ * request) can raise it, and never above this ceiling.
20
+ */
21
+ export const MAX_PROCESS_HOST_TIMEOUT_MS = 120000;
22
+ export const DEFAULT_PROCESS_HOST_LIMITS = Object.freeze({
23
+ timeoutMs: 30000,
24
+ maxStdoutBytes: 1048576,
25
+ maxStderrBytes: 1048576,
26
+ maxArgvBytes: 16384,
27
+ maxArguments: 64,
28
+ });
29
+ const WIN = process.platform === 'win32';
30
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
31
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
32
+ /** PRIVATE host rule; the shared RunIdSchema is only a non-empty string and is intentionally not changed. */
33
+ const HOST_RUN_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
34
+ const MAX_ENV_VALUE_BYTES = 2048;
35
+ const MAX_PATH_CHARS = 1024;
36
+ const MAX_RUN_HISTORY = 4096;
37
+ const MAX_EXECUTABLE_BYTES = 1024n * 1024n * 1024n;
38
+ const SHA256_HEX = /^[0-9a-fA-F]{64}$/;
39
+ const REQUEST_KEYS = new Set(['runId', 'executablePath', 'args', 'cwd', 'environment']);
40
+ /** SW-052: accepted ONLY by a host whose trusted constructor enabled stdin; otherwise any request carrying it is refused. */
41
+ const STDIN_REQUEST_KEY = 'stdinUtf8';
42
+ const KILL_ESCALATION_MS = 3000;
43
+ const PIPE_DRAIN_GRACE_MS = 1000;
44
+ const fail = (code) => {
45
+ throw new ProcessHostError(code);
46
+ };
47
+ const sameFs = (a, b) => (WIN ? a.toLowerCase() === b.toLowerCase() : a === b);
48
+ const trimSep = (p) => (p.length > 3 ? p.replace(new RegExp(`\\${sep}+$`), '') : p);
49
+ function resolveLimits(over) {
50
+ if (over === undefined)
51
+ return DEFAULT_PROCESS_HOST_LIMITS;
52
+ if (over === null || typeof over !== 'object' || Array.isArray(over))
53
+ return fail('LIMITS_INVALID');
54
+ const out = { ...DEFAULT_PROCESS_HOST_LIMITS };
55
+ const defaults = DEFAULT_PROCESS_HOST_LIMITS;
56
+ for (const [key, value] of Object.entries(over)) {
57
+ if (!Object.prototype.hasOwnProperty.call(defaults, key))
58
+ return fail('LIMITS_INVALID');
59
+ if (value === undefined)
60
+ continue;
61
+ const ceiling = key === 'timeoutMs' ? MAX_PROCESS_HOST_TIMEOUT_MS : defaults[key];
62
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1 || value > ceiling)
63
+ return fail('LIMITS_INVALID');
64
+ out[key] = value;
65
+ }
66
+ return Object.freeze(out);
67
+ }
68
+ function cleanPath(p, code) {
69
+ if (typeof p !== 'string' || p.length === 0 || p.length > MAX_PATH_CHARS || CONTROL.test(p) || LONE_SURROGATE.test(p))
70
+ return fail(code);
71
+ if (!isAbsolute(p))
72
+ return fail(code);
73
+ if (WIN && !/^[A-Za-z]:[\\/]/.test(p))
74
+ return fail(code); // rejects UNC, device (\\?\) and drive-relative forms
75
+ const parts = p.split(/[\\/]+/);
76
+ if (parts.includes('..') || parts.includes('.'))
77
+ return fail(code);
78
+ return p;
79
+ }
80
+ /** Existing, real (non-link, non-junction, no short-name alias) directory or regular file; returns the canonical path. */
81
+ function canonicalReal(p, kind, code) {
82
+ const s = cleanPath(p, code);
83
+ try {
84
+ const st = lstatSync(s);
85
+ if (st.isSymbolicLink())
86
+ return fail(code);
87
+ if (kind === 'dir' ? !st.isDirectory() : !st.isFile())
88
+ return fail(code);
89
+ const real = trimSep(realpathSync.native(s));
90
+ if (!sameFs(real, trimSep(normalize(s))))
91
+ return fail(code);
92
+ return real;
93
+ }
94
+ catch (e) {
95
+ if (e instanceof ProcessHostError)
96
+ throw e;
97
+ return fail(code);
98
+ }
99
+ }
100
+ const identityOf = (p) => {
101
+ const st = statSync(p, { bigint: true });
102
+ return `${st.dev}:${st.ino}:${st.size}`;
103
+ };
104
+ const pinnedIdentityOf = (p) => {
105
+ const st = statSync(p, { bigint: true });
106
+ return { dev: st.dev, ino: st.ino, size: st.size };
107
+ };
108
+ /**
109
+ * Streams the pinned executable through SHA-256 on ONE handle and fails closed unless: the handle names the pinned file
110
+ * (device, file id, length), the byte count equals that length, size/file id/mtime are unchanged after reading, the path
111
+ * still names the same file, and the digest equals the trusted expected digest (constant-time compare).
112
+ */
113
+ async function verifyExecutableContent(path, pinned, expected) {
114
+ let fh;
115
+ try {
116
+ fh = await open(path, 'r');
117
+ const before = await fh.stat({ bigint: true });
118
+ if (!before.isFile() || before.dev !== pinned.dev || before.ino !== pinned.ino || before.size !== pinned.size)
119
+ return fail('EXECUTABLE_MISMATCH');
120
+ if (before.size > MAX_EXECUTABLE_BYTES)
121
+ return fail('EXECUTABLE_UNSTABLE');
122
+ const hash = createHash('sha256');
123
+ const buf = Buffer.allocUnsafe(1 << 20);
124
+ let total = 0n;
125
+ for (;;) {
126
+ const { bytesRead } = await fh.read(buf, 0, buf.length, null);
127
+ if (bytesRead === 0)
128
+ break;
129
+ total += BigInt(bytesRead);
130
+ if (total > before.size)
131
+ return fail('EXECUTABLE_UNSTABLE');
132
+ hash.update(buf.subarray(0, bytesRead));
133
+ }
134
+ const after = await fh.stat({ bigint: true });
135
+ if (total !== before.size || after.size !== before.size || after.ino !== before.ino || after.dev !== before.dev || after.mtimeNs !== before.mtimeNs)
136
+ return fail('EXECUTABLE_UNSTABLE');
137
+ const atPath = lstatSync(path, { bigint: true });
138
+ if (atPath.ino !== before.ino || atPath.dev !== before.dev)
139
+ return fail('EXECUTABLE_MISMATCH');
140
+ const digest = hash.digest();
141
+ if (digest.length !== expected.length || !timingSafeEqual(digest, expected))
142
+ return fail('EXECUTABLE_DIGEST_MISMATCH');
143
+ }
144
+ catch (e) {
145
+ if (e instanceof ProcessHostError)
146
+ throw e;
147
+ return fail('EXECUTABLE_UNSTABLE');
148
+ }
149
+ finally {
150
+ try {
151
+ await fh?.close();
152
+ }
153
+ catch { /* already closed */ }
154
+ }
155
+ }
156
+ function validateRunId(value) {
157
+ const parsed = RunIdSchema.safeParse(value);
158
+ if (!parsed.success)
159
+ return fail('RUN_ID_INVALID');
160
+ const id = parsed.data;
161
+ if (!HOST_RUN_ID.test(id))
162
+ return fail('RUN_ID_INVALID');
163
+ return id;
164
+ }
165
+ function validateArgs(args, limits) {
166
+ if (!Array.isArray(args) || args.length > limits.maxArguments)
167
+ return fail('ARGV_INVALID');
168
+ let bytes = 0;
169
+ const out = [];
170
+ for (const a of args) {
171
+ if (typeof a !== 'string' || CONTROL.test(a) || LONE_SURROGATE.test(a))
172
+ return fail('ARGV_INVALID');
173
+ bytes += Buffer.byteLength(a, 'utf8') + 1; // UTF-8 bytes plus one separator each
174
+ if (bytes > limits.maxArgvBytes)
175
+ return fail('ARGV_INVALID');
176
+ out.push(a);
177
+ }
178
+ return out;
179
+ }
180
+ const ENV_KEYS = new Set(['systemroot', 'windir', 'temp', 'tmp', 'path']);
181
+ /**
182
+ * Brand-new environment from an explicit allowlist. Nothing is inherited from process.env. Unknown keys (which
183
+ * covers every credential, token, home, configuration and vendor variable), duplicates differing only by case,
184
+ * non-strings and control characters are rejected. SystemRoot/WINDIR must be this machine's own; TEMP/TMP must be
185
+ * real directories (their containment in a task-owned scratch root is the trusted caller's duty, not provable here);
186
+ * PATH may list only the pinned executable's directory and System32.
187
+ */
188
+ function buildEnvironment(env, exeDir) {
189
+ if (env === null || typeof env !== 'object' || Array.isArray(env))
190
+ return fail('ENV_INVALID');
191
+ const proto = Object.getPrototypeOf(env);
192
+ if (proto !== Object.prototype && proto !== null)
193
+ return fail('ENV_INVALID');
194
+ const keys = Object.keys(env);
195
+ if (keys.length > ENV_KEYS.size)
196
+ return fail('ENV_INVALID');
197
+ const seen = new Set();
198
+ const out = {};
199
+ const hostRoot = process.env.SystemRoot ?? process.env.windir ?? process.env.WINDIR;
200
+ for (const key of keys) {
201
+ const lower = key.toLowerCase();
202
+ if (!ENV_KEYS.has(lower) || seen.has(lower))
203
+ return fail('ENV_INVALID');
204
+ seen.add(lower);
205
+ const value = env[key];
206
+ if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value, 'utf8') > MAX_ENV_VALUE_BYTES || CONTROL.test(value) || LONE_SURROGATE.test(value))
207
+ return fail('ENV_INVALID');
208
+ if (lower === 'systemroot' || lower === 'windir') {
209
+ if (typeof hostRoot !== 'string')
210
+ return fail('ENV_INVALID');
211
+ if (!sameFs(canonicalReal(value, 'dir', 'ENV_INVALID'), trimSep(normalize(hostRoot))))
212
+ return fail('ENV_INVALID');
213
+ }
214
+ else if (lower === 'temp' || lower === 'tmp') {
215
+ canonicalReal(value, 'dir', 'ENV_INVALID');
216
+ }
217
+ else {
218
+ const allowed = [exeDir];
219
+ if (typeof hostRoot === 'string')
220
+ allowed.push(join(hostRoot, 'System32'));
221
+ for (const entry of value.split(WIN ? ';' : ':')) {
222
+ if (entry.length === 0 || !allowed.some((a) => sameFs(trimSep(normalize(entry)), trimSep(normalize(a)))))
223
+ return fail('ENV_INVALID');
224
+ }
225
+ }
226
+ out[key] = value;
227
+ }
228
+ return out;
229
+ }
230
+ /** UTF-8 decode of an already bounded buffer; a cut that splits a multi-byte sequence drops the partial tail. */
231
+ function decodeBounded(chunks, truncated) {
232
+ let buf = Buffer.concat(chunks);
233
+ if (truncated) {
234
+ let i = buf.length - 1;
235
+ let back = 0;
236
+ while (i >= 0 && back < 3 && (buf[i] & 0xc0) === 0x80) {
237
+ i -= 1;
238
+ back += 1;
239
+ }
240
+ if (i >= 0 && buf[i] >= 0xc0) {
241
+ const need = buf[i] >= 0xf0 ? 4 : buf[i] >= 0xe0 ? 3 : 2;
242
+ if (buf.length - i < need)
243
+ buf = buf.subarray(0, i);
244
+ }
245
+ }
246
+ return new TextDecoder('utf-8', { fatal: false }).decode(buf);
247
+ }
248
+ /**
249
+ * Trusted runtime environment (SW-048). A trusted in-process owner may approve a small, fixed set of EXTRA environment
250
+ * entries at construction time (for example a scratch-isolated per-process home directory that a CLI needs to start). It is
251
+ * not part of the run request: the request schema and its environment allowlist are unchanged, and a request can never
252
+ * add, replace or shadow one of these entries (a case-insensitive collision is ENV_INVALID).
253
+ *
254
+ * Every entry is validated when the host is built AND again before each run: the name must be a plain identifier that is
255
+ * not request-controlled, not a loader/interpreter/shell/home hook and not credential-shaped; the value must be either the
256
+ * machine's own SystemDrive or an existing canonical directory (no link, junction, short-name alias) that lies inside a
257
+ * trusted containment root. Nothing is read from the process environment except the machine's own SystemDrive/SystemRoot.
258
+ * The OS may still add variables of its own to a child; this host cannot remove those and does not claim to.
259
+ */
260
+ const TRUSTED_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
261
+ const TRUSTED_ENV_MAX_ENTRIES = 6;
262
+ const TRUSTED_ENV_RESERVED = new Set([
263
+ 'systemroot', 'windir', 'temp', 'tmp', 'path', 'pathext', 'comspec', 'psmodulepath', 'prompt', 'home', 'homedrive', 'homepath', 'userprofile',
264
+ 'username', 'userdomain', 'logonserver', 'programdata', 'programfiles', 'allusersprofile', 'public', 'computername',
265
+ 'java_tool_options', '_java_options', 'jdk_java_options', 'pythonstartup', 'pythonpath', 'pythonhome', 'perl5opt', 'perllib', 'rubyopt', 'rubylib',
266
+ 'electron_run_as_node', 'ld_preload', 'ld_library_path', 'dyld_insert_libraries', 'cmd',
267
+ ]);
268
+ const TRUSTED_ENV_DENY = [/^node_/i, /^npm_/i, /^git_/i, /^dyld_/i, /^ld_/i, /token|secret|passw|credential|api_?key|bearer|approval|pairing|cookie|session/i];
269
+ const within = (path, root) => sameFs(path, root) || (WIN ? path.toLowerCase().startsWith((root + sep).toLowerCase()) : path.startsWith(root + sep));
270
+ function hostSystemDrive() {
271
+ const d = process.env.SystemDrive ?? (typeof process.env.SystemRoot === 'string' ? process.env.SystemRoot.slice(0, 2) : undefined);
272
+ return typeof d === 'string' && /^[A-Za-z]:$/.test(d) ? d : undefined;
273
+ }
274
+ function validateTrustedEnvironment(cfg) {
275
+ if (cfg === undefined)
276
+ return undefined;
277
+ if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg))
278
+ return fail('CONFIG_INVALID');
279
+ const proto = Object.getPrototypeOf(cfg);
280
+ if (proto !== Object.prototype && proto !== null)
281
+ return fail('CONFIG_INVALID');
282
+ const top = Object.keys(cfg);
283
+ // SW-069: an optional third key, `files`, names PINNED FILE values (for example a CA bundle path): name -> { path, sha256 }. The file must be an existing regular, non-link file of at
284
+ // most 2 MiB whose SHA-256 equals the pinned digest, and is re-hashed before EVERY run.
285
+ if (!(top.length === 2 || (top.length === 3 && top.includes('files'))) || !top.includes('containmentRoot') || !top.includes('entries'))
286
+ return fail('CONFIG_INVALID');
287
+ const root = canonicalReal(cfg.containmentRoot, 'dir', 'CONFIG_INVALID');
288
+ const raw = cfg.entries;
289
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw))
290
+ return fail('CONFIG_INVALID');
291
+ const rproto = Object.getPrototypeOf(raw);
292
+ if (rproto !== Object.prototype && rproto !== null)
293
+ return fail('CONFIG_INVALID');
294
+ const keys = Object.keys(raw);
295
+ if (keys.length === 0 || keys.length > TRUSTED_ENV_MAX_ENTRIES)
296
+ return fail('CONFIG_INVALID');
297
+ const seen = new Set();
298
+ const entries = [];
299
+ for (const key of keys) {
300
+ const lower = key.toLowerCase();
301
+ if (!TRUSTED_ENV_NAME.test(key) || seen.has(lower))
302
+ return fail('CONFIG_INVALID');
303
+ seen.add(lower);
304
+ if (lower !== 'systemdrive' && (TRUSTED_ENV_RESERVED.has(lower) || TRUSTED_ENV_DENY.some((re) => re.test(key))))
305
+ return fail('CONFIG_INVALID');
306
+ const value = raw[key];
307
+ if (typeof value !== 'string' || value.length === 0 || Buffer.byteLength(value, 'utf8') > MAX_ENV_VALUE_BYTES || CONTROL.test(value) || LONE_SURROGATE.test(value))
308
+ return fail('CONFIG_INVALID');
309
+ if (lower === 'systemdrive') {
310
+ const d = hostSystemDrive();
311
+ if (d === undefined || value.toLowerCase() !== d.toLowerCase())
312
+ return fail('CONFIG_INVALID'); // a reference to the real runtime, never a substitute
313
+ entries.push({ key, value, kind: 'drive' });
314
+ }
315
+ else {
316
+ const real = canonicalReal(value, 'dir', 'CONFIG_INVALID');
317
+ if (!within(real, root) || value.includes(';'))
318
+ return fail('CONFIG_INVALID');
319
+ entries.push({ key, value: real, kind: 'dir' });
320
+ }
321
+ }
322
+ const filesRaw = cfg.files;
323
+ if (filesRaw !== undefined) {
324
+ if (filesRaw === null || typeof filesRaw !== 'object' || Array.isArray(filesRaw))
325
+ return fail('CONFIG_INVALID');
326
+ const fproto = Object.getPrototypeOf(filesRaw);
327
+ if (fproto !== Object.prototype && fproto !== null)
328
+ return fail('CONFIG_INVALID');
329
+ for (const [key, spec] of Object.entries(filesRaw)) {
330
+ const lower = key.toLowerCase();
331
+ if (!TRUSTED_ENV_NAME.test(key) || seen.has(lower) || TRUSTED_ENV_RESERVED.has(lower) || TRUSTED_ENV_DENY.some((re) => re.test(key)))
332
+ return fail('CONFIG_INVALID');
333
+ seen.add(lower);
334
+ if (spec === null || typeof spec !== 'object' || Array.isArray(spec))
335
+ return fail('CONFIG_INVALID');
336
+ const sk = Object.keys(spec);
337
+ const sp = spec.path;
338
+ const sd = spec.sha256;
339
+ if (sk.length !== 2 || typeof sd !== 'string' || !/^[a-f0-9]{64}$/.test(sd))
340
+ return fail('CONFIG_INVALID');
341
+ const real = canonicalReal(sp, 'file', 'CONFIG_INVALID');
342
+ if (!pinnedFileOk(real, sd))
343
+ return fail('CONFIG_INVALID');
344
+ entries.push({ key, value: real, kind: 'file', sha256: sd });
345
+ }
346
+ }
347
+ return Object.freeze({ root, entries: Object.freeze(entries.map((e) => Object.freeze(e))) });
348
+ }
349
+ /** A pinned file value: regular, not a link, at most 2 MiB, SHA-256 equals the pin. Read synchronously (small files only). */
350
+ function pinnedFileOk(path, sha256) {
351
+ try {
352
+ const st = lstatSync(path);
353
+ if (!st.isFile() || st.isSymbolicLink() || st.size < 1 || st.size > 2 * 1024 * 1024)
354
+ return false;
355
+ return createHash('sha256').update(readFileSync(path)).digest('hex') === sha256;
356
+ }
357
+ catch {
358
+ return false;
359
+ }
360
+ }
361
+ /**
362
+ * Exact-bytes policy for delivered input. Empty input, a NUL, a lone surrogate (which would silently become U+FFFD in UTF-8), or more than
363
+ * the smaller of the host's and the shared ceiling is refused; every other character, including CR, LF, tab, quotes, backslashes, code
364
+ * fences and any Unicode, is allowed and preserved byte for byte.
365
+ */
366
+ function validateStdin(v, maxBytes) {
367
+ if (typeof v !== 'string' || v.length === 0 || LONE_SURROGATE.test(v) || v.includes('\u0000'))
368
+ return fail('STDIN_INVALID');
369
+ const b = Buffer.from(v, 'utf8');
370
+ if (b.length < 1 || b.length > maxBytes)
371
+ return fail('STDIN_INVALID');
372
+ return b;
373
+ }
374
+ export function createBoundedProcessHost(config) {
375
+ if (config === null || typeof config !== 'object')
376
+ fail('CONFIG_INVALID');
377
+ const limits = resolveLimits(config.limits);
378
+ const observer = config.observer;
379
+ const obsLife = (stage, data) => { try {
380
+ observer?.lifecycle(stage, data);
381
+ }
382
+ catch { /* evidence is best-effort */ } };
383
+ const obsChunk = (stream, b) => { try {
384
+ observer?.chunk(stream, b);
385
+ }
386
+ catch { /* evidence is best-effort */ } };
387
+ const supervisor = config.supervisor;
388
+ if (supervisor !== undefined && !WIN)
389
+ fail('UNSUPPORTED_PLATFORM');
390
+ if (supervisor !== undefined && !isWindowsJobSupervisor(supervisor))
391
+ fail('CONFIG_INVALID');
392
+ const rootCanon = canonicalReal(config.approvedProjectRoot, 'dir', 'CONFIG_INVALID');
393
+ if (!existsSync(join(rootCanon, '.git')))
394
+ fail('CONFIG_INVALID');
395
+ const exeCanon = canonicalReal(config.approvedExecutablePath, 'file', 'CONFIG_INVALID');
396
+ if (typeof config.approvedExecutableSha256 !== 'string' || !SHA256_HEX.test(config.approvedExecutableSha256))
397
+ fail('CONFIG_INVALID');
398
+ const expectedDigest = Buffer.from(config.approvedExecutableSha256, 'hex'); // immutable for the host lifetime
399
+ const exeIdentity = identityOf(exeCanon);
400
+ const exePinned = pinnedIdentityOf(exeCanon);
401
+ const exeDir = trimSep(normalize(join(exeCanon, '..')));
402
+ const trustedEnv = validateTrustedEnvironment(config.trustedEnvironment); // frozen copy; later mutation of config has no effect
403
+ let stdinMax = 0; // 0 = stdin not enabled
404
+ if (config.stdin !== undefined) {
405
+ const c = config.stdin;
406
+ if (c === null || typeof c !== 'object' || Object.keys(c).length !== 1 || !supervisor)
407
+ return fail('CONFIG_INVALID');
408
+ const mb = c.maxBytes;
409
+ if (typeof mb !== 'number' || !Number.isSafeInteger(mb) || mb < 1 || mb > STDIN_MAX_BYTES)
410
+ return fail('CONFIG_INVALID');
411
+ stdinMax = mb;
412
+ }
413
+ const used = new Set();
414
+ let active;
415
+ let closed = false;
416
+ let closePromise;
417
+ /** Merges the frozen trusted entries after re-validating them against the live filesystem; a request key can never collide. */
418
+ function withTrustedEnvironment(base) {
419
+ if (!trustedEnv)
420
+ return base;
421
+ const rootNow = canonicalReal(trustedEnv.root, 'dir', 'ENV_INVALID');
422
+ if (!sameFs(rootNow, trustedEnv.root))
423
+ return fail('ENV_INVALID');
424
+ const out = { ...base };
425
+ const present = new Set(Object.keys(base).map((k) => k.toLowerCase()));
426
+ for (const e of trustedEnv.entries) {
427
+ if (present.has(e.key.toLowerCase()))
428
+ return fail('ENV_INVALID');
429
+ if (e.kind === 'dir') {
430
+ const real = canonicalReal(e.value, 'dir', 'ENV_INVALID');
431
+ if (!sameFs(real, e.value) || !within(real, rootNow))
432
+ return fail('ENV_INVALID');
433
+ }
434
+ else if (e.kind === 'file') {
435
+ // SW-069: a missing, replaced, modified, linked or unreadable pinned file stops the launch (fail closed) - no process exists yet.
436
+ if (!pinnedFileOk(e.value, e.sha256))
437
+ return fail('ENV_INVALID');
438
+ }
439
+ out[e.key] = e.value;
440
+ }
441
+ if (supervisor && Object.keys(out).length > 8)
442
+ return fail('ENV_INVALID'); // the Windows helper accepts at most 8 entries
443
+ return out;
444
+ }
445
+ function run(request) {
446
+ // Everything up to the spawn is synchronous, so the single-flight slot is taken atomically.
447
+ try {
448
+ return start(request);
449
+ }
450
+ catch (e) {
451
+ return Promise.reject(e);
452
+ }
453
+ }
454
+ function start(request) {
455
+ if (closed)
456
+ return fail('HOST_CLOSED');
457
+ if (request === null || typeof request !== 'object' || Array.isArray(request))
458
+ return fail('REQUEST_INVALID');
459
+ // The expected digest is trusted configuration. A request that carries any key beyond the five known ones (for
460
+ // example an attempted digest override) is refused outright.
461
+ for (const key of Object.keys(request)) {
462
+ if (key === STDIN_REQUEST_KEY) {
463
+ if (stdinMax === 0)
464
+ return fail('STDIN_NOT_ENABLED');
465
+ continue;
466
+ }
467
+ if (!REQUEST_KEYS.has(key))
468
+ return fail('REQUEST_INVALID');
469
+ }
470
+ const runId = validateRunId(request.runId);
471
+ if (used.has(runId) || active?.runId === runId)
472
+ return fail('DUPLICATE_RUN_ID');
473
+ if (active)
474
+ return fail('HOST_BUSY');
475
+ if (used.size >= MAX_RUN_HISTORY)
476
+ return fail('RUN_HISTORY_FULL');
477
+ const exe = canonicalReal(request.executablePath, 'file', 'EXECUTABLE_MISMATCH');
478
+ if (!sameFs(exe, exeCanon) || identityOf(exe) !== exeIdentity)
479
+ return fail('EXECUTABLE_MISMATCH');
480
+ if (!sameFs(canonicalReal(config.approvedProjectRoot, 'dir', 'ROOT_CHANGED'), rootCanon))
481
+ return fail('ROOT_CHANGED');
482
+ const cwd = canonicalReal(request.cwd, 'dir', 'CWD_NOT_APPROVED_ROOT');
483
+ if (!sameFs(cwd, rootCanon))
484
+ return fail('CWD_NOT_APPROVED_ROOT');
485
+ const args = validateArgs(request.args, limits);
486
+ const env = withTrustedEnvironment(buildEnvironment(request.environment, exeDir));
487
+ let stdinBytes;
488
+ if (request.stdinUtf8 !== undefined) {
489
+ stdinBytes = validateStdin(request.stdinUtf8, stdinMax);
490
+ // Dry-run the helper request now so an input that cannot be carried is refused BEFORE the slot and before any process.
491
+ try {
492
+ supervisor.checkLaunchRequest({ exe, sha256: config.approvedExecutableSha256, cwd, args, env, stdin: stdinBytes });
493
+ }
494
+ catch {
495
+ return fail('STDIN_INVALID');
496
+ }
497
+ }
498
+ // Single-flight slot is taken NOW, synchronously, before the asynchronous content check below.
499
+ const startedAt = process.hrtime.bigint();
500
+ const elapsedMs = () => Number((process.hrtime.bigint() - startedAt) / 1000000n);
501
+ let resolveDone = () => undefined;
502
+ const done = new Promise((r) => { resolveDone = r; });
503
+ let preCancelled = false;
504
+ const ctl = {
505
+ runId,
506
+ done,
507
+ // Until the child exists, a cancel or close only records the intent; the pending run then ends without a spawn.
508
+ requestKill: () => { if (preCancelled)
509
+ return false; preCancelled = true; return true; },
510
+ };
511
+ active = ctl;
512
+ const release = () => {
513
+ if (active === ctl)
514
+ active = undefined;
515
+ resolveDone();
516
+ };
517
+ const launch = () => {
518
+ const out = { chunks: [], len: 0, truncated: false };
519
+ const err = { chunks: [], len: 0, truncated: false };
520
+ let cause;
521
+ let killIssued = false;
522
+ let spawned = false;
523
+ let spawnFailed = false;
524
+ let exited = false;
525
+ let exitCode = null;
526
+ let exitSignal = null;
527
+ let settled = false;
528
+ let child;
529
+ let supervised;
530
+ const timers = new Set();
531
+ return new Promise((resolve) => {
532
+ const finish = () => {
533
+ if (settled)
534
+ return;
535
+ settled = true;
536
+ for (const t of timers)
537
+ clearTimeout(t);
538
+ timers.clear();
539
+ try {
540
+ child?.stdout?.destroy();
541
+ child?.stderr?.destroy();
542
+ }
543
+ catch { /* already closed */ }
544
+ child?.removeAllListeners('exit');
545
+ child?.removeAllListeners('close');
546
+ let outcome;
547
+ const sev = supervised?.evidence();
548
+ const completedByItself = cause === undefined || (cause !== 'OUTPUT_LIMIT_EXCEEDED' && exited && exitSignal === null && exitCode === 0);
549
+ if (spawnFailed && cause === 'CANCELLED' && sev?.helperFailureCode === 'CANCELLED_BEFORE_RESUME')
550
+ outcome = 'CANCELLED'; // the supervisor aborted before the target could run
551
+ else if (spawnFailed)
552
+ outcome = 'SPAWN_FAILED';
553
+ // A broken supervision stream, or a run that "completed" while its process tree could not be positively confirmed gone,
554
+ // is never reported as a plain success.
555
+ else if (sev && sev.processLaunched && (sev.protocol !== 'OK' || (completedByItself && !sev.knownTreeTerminatedAndChecked)))
556
+ outcome = 'SUPERVISION_FAILED';
557
+ else if (completedByItself)
558
+ outcome = 'EXITED';
559
+ else
560
+ outcome = cause;
561
+ const result = Object.freeze({
562
+ runId,
563
+ outcome,
564
+ exitCode: spawnFailed ? null : exitCode,
565
+ signal: spawnFailed ? null : exitSignal,
566
+ stdoutUtf8: decodeBounded(out.chunks, out.truncated),
567
+ stderrUtf8: decodeBounded(err.chunks, err.truncated),
568
+ stdoutTruncated: out.truncated,
569
+ stderrTruncated: err.truncated,
570
+ processTreeTerminated: sev
571
+ ? (sev.processLaunched ? sev.knownTreeTerminatedAndChecked : null)
572
+ : (killIssued ? (exited ? null : false) : null),
573
+ durationMs: elapsedMs(),
574
+ ...(sev ? { supervision: sev } : {}),
575
+ });
576
+ obsLife('HOST_SETTLED', { outcome, exitCode: result.exitCode, signal: result.signal, tree: String(result.processTreeTerminated), stdin: sev ? sev.stdinStatus : 'NOT_SUPERVISED', protocol: sev ? sev.protocol : 'NONE', helperFailure: sev?.helperFailureCode ?? null, stdoutTruncated: out.truncated, stderrTruncated: err.truncated, durationMs: result.durationMs });
577
+ if (active?.runId === runId)
578
+ active = undefined;
579
+ resolve(result);
580
+ resolveDone();
581
+ };
582
+ const issueKill = (why) => {
583
+ if (cause !== undefined || exited || settled)
584
+ return false;
585
+ cause = why;
586
+ killIssued = true;
587
+ obsLife('FAILED_KILL_ISSUED', { cause: why, elapsedMs: elapsedMs() });
588
+ try {
589
+ child?.kill();
590
+ }
591
+ catch { /* the exit/close events decide the outcome */ }
592
+ const escalate = setTimeout(() => {
593
+ if (exited || settled)
594
+ return;
595
+ try {
596
+ child?.kill('SIGKILL');
597
+ }
598
+ catch { /* ignored */ }
599
+ const giveUp = setTimeout(() => finish(), KILL_ESCALATION_MS); // direct child still not confirmed gone
600
+ timers.add(giveUp);
601
+ }, KILL_ESCALATION_MS);
602
+ timers.add(escalate);
603
+ return true;
604
+ };
605
+ const collect = (s, limit, which) => (chunk) => {
606
+ if (!s.truncated)
607
+ obsChunk(which, chunk.length > limit - s.len ? chunk.subarray(0, Math.max(0, limit - s.len)) : chunk);
608
+ if (s.truncated)
609
+ return;
610
+ const room = limit - s.len;
611
+ if (chunk.length > room) {
612
+ if (room > 0)
613
+ s.chunks.push(chunk.subarray(0, room));
614
+ s.len = limit;
615
+ s.truncated = true;
616
+ issueKill('OUTPUT_LIMIT_EXCEEDED');
617
+ }
618
+ else {
619
+ s.chunks.push(chunk);
620
+ s.len += chunk.length;
621
+ }
622
+ };
623
+ ctl.requestKill = (why) => issueKill(why);
624
+ obsLife('HOST_ACCEPTED', { stdinBytes: stdinBytes ? stdinBytes.length : 0, timeoutMs: limits.timeoutMs, supervised: supervisor !== undefined });
625
+ try {
626
+ if (supervisor) {
627
+ supervised = supervisor.spawn({ exe, sha256: config.approvedExecutableSha256, cwd, args, env, ...(stdinBytes ? { stdin: stdinBytes } : {}) });
628
+ child = supervised;
629
+ }
630
+ else {
631
+ child = spawn(exe, args, {
632
+ cwd,
633
+ env,
634
+ shell: false,
635
+ windowsHide: true,
636
+ detached: false,
637
+ stdio: ['ignore', 'pipe', 'pipe'],
638
+ });
639
+ }
640
+ }
641
+ catch (e) {
642
+ spawnFailed = true;
643
+ obsLife('FAILED_SPAWN', { code: String(e?.code ?? e?.name ?? 'THROWN').slice(0, 40), phase: 'SYNC' });
644
+ finish();
645
+ return;
646
+ }
647
+ obsLife('SPAWN_REQUESTED');
648
+ const c = child;
649
+ c.once('spawn', () => { spawned = true; obsLife('PROCESS_SPAWNED'); });
650
+ c.once('error', (e) => {
651
+ obsLife('FAILED_SPAWN', { code: String(e?.code ?? 'ERROR').slice(0, 40), phase: spawned ? 'AFTER_SPAWN' : 'ASYNC' });
652
+ if (!spawned) {
653
+ spawnFailed = true;
654
+ finish();
655
+ }
656
+ });
657
+ c.stdout?.on('data', collect(out, limits.maxStdoutBytes, 'stdout'));
658
+ c.stderr?.on('data', collect(err, limits.maxStderrBytes, 'stderr'));
659
+ c.stdout?.on('error', () => undefined);
660
+ c.stderr?.on('error', () => undefined);
661
+ c.once('exit', (code, signal) => {
662
+ obsLife('PROCESS_EXITED', { code: code ?? null, signal: signal ?? null, elapsedMs: elapsedMs() });
663
+ exited = true;
664
+ exitCode = code;
665
+ exitSignal = signal;
666
+ timers.add(setTimeout(() => finish(), PIPE_DRAIN_GRACE_MS)); // a descendant holding a pipe cannot hold the result
667
+ });
668
+ c.once('close', () => finish());
669
+ timers.add(setTimeout(() => { issueKill('TIMEOUT'); }, limits.timeoutMs));
670
+ });
671
+ };
672
+ return (async () => {
673
+ let verdict;
674
+ try {
675
+ await verifyExecutableContent(exeCanon, exePinned, expectedDigest);
676
+ }
677
+ catch (e) {
678
+ verdict = e instanceof ProcessHostError ? e.code : 'EXECUTABLE_UNSTABLE';
679
+ }
680
+ if (verdict === undefined && supervisor) {
681
+ // Fail closed: an unbuilt, changed or unverifiable helper never falls back to a plain spawn.
682
+ try {
683
+ await supervisor.verifyHelper();
684
+ }
685
+ catch {
686
+ verdict = 'SUPERVISOR_UNAVAILABLE';
687
+ }
688
+ }
689
+ if (preCancelled || closed) {
690
+ // A cancel or close arrived before any child existed: a truthful non-launch outcome, and no later spawn.
691
+ used.add(runId);
692
+ const result = Object.freeze({
693
+ runId, outcome: 'CANCELLED', exitCode: null, signal: null, stdoutUtf8: '', stderrUtf8: '',
694
+ stdoutTruncated: false, stderrTruncated: false, processTreeTerminated: null, durationMs: elapsedMs(),
695
+ });
696
+ release();
697
+ return result;
698
+ }
699
+ if (verdict === undefined) {
700
+ // Immediately before the spawn: re-check path, file identity and approved root once more (synchronous).
701
+ try {
702
+ // Uses the path captured at validation time, not the caller's (mutable) request object.
703
+ const again = canonicalReal(exe, 'file', 'EXECUTABLE_MISMATCH');
704
+ if (!sameFs(again, exeCanon) || identityOf(again) !== exeIdentity)
705
+ verdict = 'EXECUTABLE_MISMATCH';
706
+ else if (!sameFs(canonicalReal(config.approvedProjectRoot, 'dir', 'ROOT_CHANGED'), rootCanon))
707
+ verdict = 'ROOT_CHANGED';
708
+ }
709
+ catch (e) {
710
+ verdict = e instanceof ProcessHostError ? e.code : 'EXECUTABLE_UNSTABLE';
711
+ }
712
+ }
713
+ if (verdict !== undefined) {
714
+ release(); // nothing was spawned and the id was not spent
715
+ throw new ProcessHostError(verdict);
716
+ }
717
+ used.add(runId); // no automatic retry: an id is spent once a launch is attempted
718
+ return launch();
719
+ })();
720
+ }
721
+ async function cancel(runId) {
722
+ let id;
723
+ try {
724
+ id = validateRunId(runId);
725
+ }
726
+ catch {
727
+ return false;
728
+ }
729
+ const a = active;
730
+ if (!a || a.runId !== id)
731
+ return false; // wrong, unknown or terminal ids can never kill anything
732
+ if (!a.requestKill('CANCELLED'))
733
+ return false;
734
+ await a.done;
735
+ return true;
736
+ }
737
+ function close() {
738
+ if (closePromise)
739
+ return closePromise;
740
+ closed = true;
741
+ closePromise = (async () => {
742
+ const a = active;
743
+ if (a) {
744
+ a.requestKill('CANCELLED');
745
+ await a.done;
746
+ }
747
+ })();
748
+ return closePromise;
749
+ }
750
+ return { run, cancel, close };
751
+ }
752
+ //# sourceMappingURL=boundedProcessHost.js.map