@abelxiaoxing/cadence 1.8.3 → 2.0.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 (208) hide show
  1. package/README.md +324 -111
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/agents/design-explorer.md +14 -26
  4. package/agents/diagnosis-worker.md +14 -25
  5. package/agents/implementation-worker.md +16 -35
  6. package/config/.env.example +2 -5
  7. package/config/workflow-task.example.json +7 -0
  8. package/docs/remote-access.md +60 -0
  9. package/docs/reuse-and-distribution.md +44 -0
  10. package/docs/service-management.md +108 -0
  11. package/licenses/bundled-web.txt +6245 -0
  12. package/licenses/pi-web-ui-MIT.txt +21 -0
  13. package/licenses/pi-web-ui-reuse.md +22 -0
  14. package/package.json +94 -21
  15. package/src/index.ts +22 -1807
  16. package/src/native-build.ts +6 -0
  17. package/src/native-client.ts +103 -0
  18. package/src/native-export.ts +58 -0
  19. package/src/native-history.ts +359 -0
  20. package/src/operator-cli.mjs +453 -1937
  21. package/src/plan-proposal.ts +87 -0
  22. package/src/sdk-worker.mjs +549 -0
  23. package/src/service/contracts/active.ts +82 -0
  24. package/src/service/contracts/budget.ts +148 -0
  25. package/src/service/contracts/build.ts +67 -0
  26. package/src/service/contracts/capture.ts +48 -0
  27. package/src/service/contracts/core.ts +33 -0
  28. package/src/service/contracts/current.ts +261 -0
  29. package/src/service/contracts/domain.ts +68 -0
  30. package/src/service/contracts/history.ts +2245 -0
  31. package/src/service/contracts/models.ts +139 -0
  32. package/src/service/coordination.ts +862 -0
  33. package/src/service/private-files.ts +204 -0
  34. package/src/service-cli.mjs +5592 -0
  35. package/src/service-client.ts +747 -0
  36. package/src/service-contract.ts +245 -0
  37. package/src/service-host.mjs +22382 -0
  38. package/src/service-http-client.ts +425 -0
  39. package/src/service-wire.ts +372 -0
  40. package/src/task-shell.ts +1045 -0
  41. package/src/task-store.ts +479 -0
  42. package/src/task-types.ts +184 -0
  43. package/src/verification-diagnostics.ts +29 -72
  44. package/src/worker-capture.mjs +1197 -0
  45. package/src/worker-public.mjs +1753 -0
  46. package/src/worker-redaction.mjs +608 -0
  47. package/src/worker-tools.mjs +202 -0
  48. package/web/dist/assets/KaTeX_AMS-Regular.ttf +0 -0
  49. package/web/dist/assets/KaTeX_AMS-Regular.woff +0 -0
  50. package/web/dist/assets/KaTeX_AMS-Regular.woff2 +0 -0
  51. package/web/dist/assets/KaTeX_Caligraphic-Bold.ttf +0 -0
  52. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff +0 -0
  53. package/web/dist/assets/KaTeX_Caligraphic-Bold.woff2 +0 -0
  54. package/web/dist/assets/KaTeX_Caligraphic-Regular.ttf +0 -0
  55. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff +0 -0
  56. package/web/dist/assets/KaTeX_Caligraphic-Regular.woff2 +0 -0
  57. package/web/dist/assets/KaTeX_Fraktur-Bold.ttf +0 -0
  58. package/web/dist/assets/KaTeX_Fraktur-Bold.woff +0 -0
  59. package/web/dist/assets/KaTeX_Fraktur-Bold.woff2 +0 -0
  60. package/web/dist/assets/KaTeX_Fraktur-Regular.ttf +0 -0
  61. package/web/dist/assets/KaTeX_Fraktur-Regular.woff +0 -0
  62. package/web/dist/assets/KaTeX_Fraktur-Regular.woff2 +0 -0
  63. package/web/dist/assets/KaTeX_Main-Bold.ttf +0 -0
  64. package/web/dist/assets/KaTeX_Main-Bold.woff +0 -0
  65. package/web/dist/assets/KaTeX_Main-Bold.woff2 +0 -0
  66. package/web/dist/assets/KaTeX_Main-BoldItalic.ttf +0 -0
  67. package/web/dist/assets/KaTeX_Main-BoldItalic.woff +0 -0
  68. package/web/dist/assets/KaTeX_Main-BoldItalic.woff2 +0 -0
  69. package/web/dist/assets/KaTeX_Main-Italic.ttf +0 -0
  70. package/web/dist/assets/KaTeX_Main-Italic.woff +0 -0
  71. package/web/dist/assets/KaTeX_Main-Italic.woff2 +0 -0
  72. package/web/dist/assets/KaTeX_Main-Regular.ttf +0 -0
  73. package/web/dist/assets/KaTeX_Main-Regular.woff +0 -0
  74. package/web/dist/assets/KaTeX_Main-Regular.woff2 +0 -0
  75. package/web/dist/assets/KaTeX_Math-BoldItalic.ttf +0 -0
  76. package/web/dist/assets/KaTeX_Math-BoldItalic.woff +0 -0
  77. package/web/dist/assets/KaTeX_Math-BoldItalic.woff2 +0 -0
  78. package/web/dist/assets/KaTeX_Math-Italic.ttf +0 -0
  79. package/web/dist/assets/KaTeX_Math-Italic.woff +0 -0
  80. package/web/dist/assets/KaTeX_Math-Italic.woff2 +0 -0
  81. package/web/dist/assets/KaTeX_SansSerif-Bold.ttf +0 -0
  82. package/web/dist/assets/KaTeX_SansSerif-Bold.woff +0 -0
  83. package/web/dist/assets/KaTeX_SansSerif-Bold.woff2 +0 -0
  84. package/web/dist/assets/KaTeX_SansSerif-Italic.ttf +0 -0
  85. package/web/dist/assets/KaTeX_SansSerif-Italic.woff +0 -0
  86. package/web/dist/assets/KaTeX_SansSerif-Italic.woff2 +0 -0
  87. package/web/dist/assets/KaTeX_SansSerif-Regular.ttf +0 -0
  88. package/web/dist/assets/KaTeX_SansSerif-Regular.woff +0 -0
  89. package/web/dist/assets/KaTeX_SansSerif-Regular.woff2 +0 -0
  90. package/web/dist/assets/KaTeX_Script-Regular.ttf +0 -0
  91. package/web/dist/assets/KaTeX_Script-Regular.woff +0 -0
  92. package/web/dist/assets/KaTeX_Script-Regular.woff2 +0 -0
  93. package/web/dist/assets/KaTeX_Size1-Regular.ttf +0 -0
  94. package/web/dist/assets/KaTeX_Size1-Regular.woff +0 -0
  95. package/web/dist/assets/KaTeX_Size1-Regular.woff2 +0 -0
  96. package/web/dist/assets/KaTeX_Size2-Regular.ttf +0 -0
  97. package/web/dist/assets/KaTeX_Size2-Regular.woff +0 -0
  98. package/web/dist/assets/KaTeX_Size2-Regular.woff2 +0 -0
  99. package/web/dist/assets/KaTeX_Size3-Regular.ttf +0 -0
  100. package/web/dist/assets/KaTeX_Size3-Regular.woff +0 -0
  101. package/web/dist/assets/KaTeX_Size3-Regular.woff2 +0 -0
  102. package/web/dist/assets/KaTeX_Size4-Regular.ttf +0 -0
  103. package/web/dist/assets/KaTeX_Size4-Regular.woff +0 -0
  104. package/web/dist/assets/KaTeX_Size4-Regular.woff2 +0 -0
  105. package/web/dist/assets/KaTeX_Typewriter-Regular.ttf +0 -0
  106. package/web/dist/assets/KaTeX_Typewriter-Regular.woff +0 -0
  107. package/web/dist/assets/KaTeX_Typewriter-Regular.woff2 +0 -0
  108. package/web/dist/assets/cadence.css +2 -0
  109. package/web/dist/assets/cadence.js +7 -0
  110. package/web/dist/assets/markdown.js +296 -0
  111. package/web/dist/assets/react.js +9 -0
  112. package/web/dist/assets/rolldown-runtime.js +1 -0
  113. package/web/dist/assets/timeline-client.js +41 -0
  114. package/web/dist/assets/vis-timeline.css +1274 -0
  115. package/web/dist/assets/vis-timeline.js +32 -0
  116. package/web/dist/index.html +18 -0
  117. package/web/dist/manifest.json +505 -0
  118. package/config/plan-draft.example.json +0 -125
  119. package/config/plan-draft.multiple-tasks.example.json +0 -375
  120. package/config/plan-draft.quick.example.json +0 -78
  121. package/config/routes.example.json +0 -39
  122. package/prompts/abel-design.md +0 -382
  123. package/prompts/abel-diagnose.md +0 -71
  124. package/prompts/abel-implement.md +0 -284
  125. package/prompts/abel-init.md +0 -52
  126. package/src/activation.ts +0 -44
  127. package/src/activity-contracts.ts +0 -82
  128. package/src/agent-registry.ts +0 -53
  129. package/src/apply-transaction.ts +0 -1437
  130. package/src/artifact-store.ts +0 -213
  131. package/src/build-windows-job.mjs +0 -95
  132. package/src/candidate-artifact.ts +0 -143
  133. package/src/candidate-patch.ts +0 -271
  134. package/src/candidate-workspace.ts +0 -80
  135. package/src/canonical.ts +0 -16
  136. package/src/change-contract-schema.ts +0 -191
  137. package/src/change-contract.ts +0 -324
  138. package/src/change-verification.ts +0 -1617
  139. package/src/child-budget.ts +0 -58
  140. package/src/child-model.ts +0 -142
  141. package/src/child-session.ts +0 -640
  142. package/src/contracts.ts +0 -2476
  143. package/src/control-contracts.ts +0 -382
  144. package/src/delivery-compiler.ts +0 -1805
  145. package/src/delivery-revision.ts +0 -42
  146. package/src/design-control.ts +0 -1299
  147. package/src/design-diagnostics.ts +0 -181
  148. package/src/design-journal.ts +0 -1773
  149. package/src/directory-sync.ts +0 -36
  150. package/src/durable-contracts.ts +0 -231
  151. package/src/durable-workflow.ts +0 -978
  152. package/src/evidence-draft.ts +0 -122
  153. package/src/execution-profile.ts +0 -64
  154. package/src/execution-retention.ts +0 -77
  155. package/src/file-snapshot.ts +0 -163
  156. package/src/implement-continuation.ts +0 -559
  157. package/src/implement-graph.ts +0 -690
  158. package/src/implement-plan.ts +0 -72
  159. package/src/install-config.d.mts +0 -6
  160. package/src/isolation-backend.ts +0 -353
  161. package/src/model-source.ts +0 -22
  162. package/src/openspec-cli.ts +0 -494
  163. package/src/operator-cli-entry.mjs +0 -24
  164. package/src/operator-tools.ts +0 -309
  165. package/src/package-candidate.ts +0 -227
  166. package/src/package-delivery.ts +0 -486
  167. package/src/package-state.ts +0 -320
  168. package/src/package-verification.ts +0 -635
  169. package/src/package-workflow.ts +0 -342
  170. package/src/packet-runtime.ts +0 -570
  171. package/src/parent-provider.ts +0 -375
  172. package/src/phase-execution.ts +0 -2259
  173. package/src/pi-adapter.ts +0 -19
  174. package/src/plan-draft-summary.ts +0 -527
  175. package/src/plan-draft.ts +0 -502
  176. package/src/remove-path.ts +0 -32
  177. package/src/route-policy.ts +0 -545
  178. package/src/run-state.ts +0 -420
  179. package/src/run-store.ts +0 -1179
  180. package/src/safe-path.ts +0 -77
  181. package/src/scoped-grep-worker.mjs +0 -23
  182. package/src/scoped-tools.ts +0 -775
  183. package/src/single-task-draft.ts +0 -142
  184. package/src/sqlite-schema.ts +0 -171
  185. package/src/state-root.ts +0 -215
  186. package/src/storage-schema.ts +0 -360
  187. package/src/subagent-activity.ts +0 -1417
  188. package/src/submit-tool.ts +0 -950
  189. package/src/task-ledger.ts +0 -1338
  190. package/src/transport-budget.ts +0 -52
  191. package/src/verification-capability.ts +0 -1191
  192. package/src/verification-environment-io.ts +0 -389
  193. package/src/verification-environment.ts +0 -162
  194. package/src/verification-identity.ts +0 -77
  195. package/src/verification-scan.ts +0 -64
  196. package/src/windows-job-backend.ts +0 -419
  197. package/src/windows-job.c +0 -149
  198. package/src/worker-broker.ts +0 -806
  199. package/src/workflow-engine.ts +0 -28
  200. package/src/workflow-policy.ts +0 -1679
  201. package/src/workflow-recovery-policy.ts +0 -97
  202. package/src/workflow-scheduling.ts +0 -105
  203. package/src/workflow-state-machine.ts +0 -4355
  204. package/src/workflow-status.ts +0 -576
  205. package/src/workspace-io-entry.mjs +0 -76
  206. package/src/workspace-io-worker.mjs +0 -1312
  207. package/src/workspace-io.ts +0 -89
  208. package/src/workspace-store.ts +0 -634
@@ -1,419 +0,0 @@
1
- import { spawn, spawnSync } from "node:child_process";
2
- import { createHash } from "node:crypto";
3
- import { lstatSync, readFileSync } from "node:fs";
4
- import path from "node:path";
5
- import {
6
- BoundedLog,
7
- ISOLATION_RUN_LIMITS,
8
- type IsolationRunInput,
9
- type IsolationRunResult,
10
- } from "./isolation-backend.ts";
11
-
12
- const SHUTDOWN_MS = 5000;
13
- const invalid = (): never => {
14
- throw new Error("windows-job-request-invalid");
15
- };
16
- const text = (value: unknown): value is string =>
17
- typeof value === "string" &&
18
- value.length <= 16384 &&
19
- !value.includes("\0") &&
20
- !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(
21
- value,
22
- );
23
- const absolute = (value: unknown): value is string =>
24
- text(value) && /^[A-Za-z]:\\/u.test(value) && path.win32.isAbsolute(value);
25
- export function encodeWindowsJobRequest(
26
- input: IsolationRunInput,
27
- timeoutMs: number,
28
- ): Buffer {
29
- if (
30
- !absolute(input.root) ||
31
- !absolute(input.executable) ||
32
- !input.executable.toLowerCase().endsWith(".exe") ||
33
- input.mounts?.length ||
34
- !Number.isSafeInteger(timeoutMs) ||
35
- timeoutMs < 1 ||
36
- timeoutMs > 86_400_000
37
- )
38
- invalid();
39
- const args = input.args ?? [];
40
- if (args.length > 128 || !args.every(text)) invalid();
41
- const seen = new Set<string>();
42
- const env = Object.entries(input.environment ?? {});
43
- for (const [name, value] of env) {
44
- if (
45
- !/^[A-Za-z_][A-Za-z0-9_]*$/u.test(name) ||
46
- !text(value) ||
47
- seen.has(name.toUpperCase())
48
- )
49
- invalid();
50
- seen.add(name.toUpperCase());
51
- }
52
- const quote = (value: string) =>
53
- `"${value.replace(/(\\*)"/gu, '$1$1\\"').replace(/(\\+)$/gu, "$1$1")}"`;
54
- const command = [input.executable, ...args].map(quote).join(" ");
55
- if (command.length >= 32767) invalid();
56
- const environment = `${env
57
- .sort(([a], [b]) => (a.toUpperCase() < b.toUpperCase() ? -1 : 1))
58
- .map(([k, v]) => `${k}=${v}`)
59
- .join("\0")}\0\0`;
60
- const parts = [
61
- `${input.executable}\0`,
62
- `${command}\0`,
63
- `${input.root}\0`,
64
- environment,
65
- ].map((s) => Buffer.from(s, "utf16le"));
66
- const header = Buffer.alloc(36);
67
- [2, timeoutMs, SHUTDOWN_MS, 0, ...parts.map((p) => p.length), 0].forEach(
68
- (n, i) => {
69
- header.writeUInt32LE(n, i * 4);
70
- },
71
- );
72
- const wire = Buffer.concat([header, ...parts]);
73
- if (wire.length > 65536 || parts.some((p) => p.length > 60000)) invalid();
74
- return wire;
75
- }
76
-
77
- /** A manifest binds a explicitly built native helper to the shipped source. */
78
- export function verifyWindowsJobHelper(helper: string): boolean {
79
- try {
80
- if (!path.isAbsolute(helper)) return false;
81
- const files = [helper, `${helper}.json`];
82
- if (
83
- files.some((file) => {
84
- const s = lstatSync(file);
85
- return !s.isFile() || s.isSymbolicLink() || s.size > 8 * 1024 * 1024;
86
- })
87
- )
88
- return false;
89
- const bytes = readFileSync(helper);
90
- const pe = bytes.length >= 64 ? bytes.readUInt32LE(60) : -1;
91
- if (
92
- bytes.toString("ascii", 0, 2) !== "MZ" ||
93
- pe < 64 ||
94
- pe + 6 > bytes.length ||
95
- bytes.readUInt32LE(pe) !== 0x4550 ||
96
- bytes.readUInt16LE(pe + 4) !== 0x8664
97
- )
98
- return false;
99
- const hash = (data: Uint8Array) =>
100
- createHash("sha256").update(data).digest("hex");
101
- const manifest = JSON.parse(readFileSync(`${helper}.json`, "utf8"));
102
- return (
103
- manifest.version === 2 &&
104
- manifest.arch === "x64" &&
105
- manifest.helperSha256 === hash(bytes) &&
106
- manifest.sourceSha256 ===
107
- hash(readFileSync(new URL("./windows-job.c", import.meta.url)))
108
- );
109
- } catch {
110
- return false;
111
- }
112
- }
113
-
114
- interface Observation {
115
- version: 2;
116
- outcome: "complete" | "failed" | "uncertain";
117
- reason: string;
118
- rootExited: boolean;
119
- managedSettled: boolean;
120
- exitCode: number | null;
121
- }
122
- function observation(value: unknown): Observation | undefined {
123
- if (!value || typeof value !== "object") return;
124
- const v = value as Observation;
125
- if (
126
- Object.keys(v).sort().join(",") !==
127
- "exitCode,managedSettled,outcome,reason,rootExited,version" ||
128
- v.version !== 2 ||
129
- !["complete", "failed", "uncertain"].includes(v.outcome) ||
130
- ![
131
- "exit",
132
- "timeout",
133
- "cancelled",
134
- "launch-failed",
135
- "termination-unconfirmed",
136
- ].includes(v.reason) ||
137
- typeof v.rootExited !== "boolean" ||
138
- typeof v.managedSettled !== "boolean" ||
139
- !(
140
- v.exitCode === null ||
141
- (Number.isInteger(v.exitCode) &&
142
- v.exitCode >= 0 &&
143
- v.exitCode <= 0xffffffff)
144
- )
145
- )
146
- return;
147
- if (
148
- v.outcome === "complete" &&
149
- (v.reason !== "exit" ||
150
- !v.rootExited ||
151
- !v.managedSettled ||
152
- v.exitCode === null)
153
- )
154
- return;
155
- if (
156
- v.outcome === "failed" &&
157
- (!v.managedSettled ||
158
- !["timeout", "cancelled", "launch-failed"].includes(v.reason))
159
- )
160
- return;
161
- return v;
162
- }
163
- const uncertain = (): IsolationRunResult => ({
164
- ok: false,
165
- state: "paused",
166
- code: "isolation-termination-unconfirmed",
167
- });
168
- function classify(
169
- v: Observation | undefined,
170
- helperExit: number | null,
171
- output: BoundedLog,
172
- cancelled: boolean,
173
- ): IsolationRunResult {
174
- if (!v?.managedSettled || v.outcome === "uncertain" || helperExit !== 0)
175
- return uncertain();
176
- if (cancelled || v.reason === "cancelled")
177
- return { ok: false, state: "cancelled", code: "cancelled" };
178
- if (v.reason === "timeout")
179
- return { ok: false, state: "paused", code: "isolation-execution-timeout" };
180
- if (v.reason === "launch-failed")
181
- return {
182
- ok: false,
183
- state: "paused",
184
- code: "isolation-backend-launch-failed",
185
- };
186
- if (v.outcome !== "complete" || v.exitCode === null) return uncertain();
187
- return {
188
- ok: true,
189
- state: "completed",
190
- exitCode: v.exitCode,
191
- stdout: output.text(),
192
- stderr: "",
193
- outputWitnessMatched: output.witnessMatched,
194
- logs: { stdout: output.metadata(), stderr: { bytes: 0, truncated: false } },
195
- };
196
- }
197
-
198
- /** Host files/network are trusted; the Job owns process lifetime, not a security sandbox. */
199
- interface WindowsJobOptions {
200
- helperPath: string;
201
- timeoutMs?: number;
202
- platform?: NodeJS.Platform;
203
- arch?: string;
204
- probe?: (helper: string) => boolean;
205
- spawnProcess?: typeof spawn;
206
- maxOutputBytes?: number;
207
- }
208
- export class WindowsJobBackend {
209
- readonly #options: WindowsJobOptions;
210
- constructor(options: WindowsJobOptions) {
211
- for (const [value, maximum] of [
212
- [options.timeoutMs ?? ISOLATION_RUN_LIMITS.timeoutMs, 86_400_000],
213
- [
214
- options.maxOutputBytes ?? ISOLATION_RUN_LIMITS.maxOutputBytes,
215
- 1024 * 1024,
216
- ],
217
- ])
218
- if (!Number.isSafeInteger(value) || value < 1 || value > maximum)
219
- throw new Error("isolation-run-limits-invalid");
220
- this.#options = options;
221
- }
222
- available(): boolean {
223
- return (
224
- (this.#options.platform ?? process.platform) === "win32" &&
225
- (this.#options.arch ?? process.arch) === "x64" &&
226
- (this.#options.probe ?? verifyWindowsJobHelper)(this.#options.helperPath)
227
- );
228
- }
229
- async run(input: IsolationRunInput): Promise<IsolationRunResult> {
230
- if (!this.available())
231
- return {
232
- ok: false,
233
- state: "paused",
234
- code: "isolation-backend-unavailable",
235
- };
236
- if (input.signal?.aborted)
237
- return { ok: false, state: "cancelled", code: "cancelled" };
238
- if (
239
- input.outputWitness !== undefined &&
240
- (!text(input.outputWitness) ||
241
- input.outputWitness.length < 1 ||
242
- input.outputWitness.length > 512)
243
- )
244
- return {
245
- ok: false,
246
- state: "paused",
247
- code: "isolation-backend-launch-failed",
248
- };
249
- const timeoutMs = this.#options.timeoutMs ?? ISOLATION_RUN_LIMITS.timeoutMs;
250
- let wire: Buffer;
251
- try {
252
- wire = encodeWindowsJobRequest(input, timeoutMs);
253
- } catch {
254
- return {
255
- ok: false,
256
- state: "paused",
257
- code: "isolation-backend-launch-failed",
258
- };
259
- }
260
- const output = new BoundedLog(
261
- this.#options.maxOutputBytes ?? ISOLATION_RUN_LIMITS.maxOutputBytes,
262
- input.outputWitness,
263
- );
264
- return new Promise((resolve) => {
265
- let child: ReturnType<typeof spawn>;
266
- let line = "",
267
- final: Observation | undefined,
268
- bad = false,
269
- closed = false,
270
- launchFailed = false;
271
- let timer: ReturnType<typeof setTimeout>;
272
- let stopping = false;
273
- const armDeadline = (duration: number) => {
274
- clearTimeout(timer);
275
- timer = setTimeout(() => {
276
- bad = true;
277
- child.kill();
278
- finish(uncertain());
279
- }, duration);
280
- timer.unref?.();
281
- };
282
- const cancel = () => {
283
- if (stopping || closed) return;
284
- stopping = true;
285
- child.stdin?.end();
286
- armDeadline(SHUTDOWN_MS + 5000);
287
- };
288
- const finish = (result: IsolationRunResult) => {
289
- if (closed) return;
290
- closed = true;
291
- clearTimeout(timer);
292
- input.signal?.removeEventListener("abort", cancel);
293
- resolve(result);
294
- };
295
- try {
296
- child = (this.#options.spawnProcess ?? spawn)(
297
- this.#options.helperPath,
298
- [],
299
- {
300
- cwd: input.root,
301
- shell: false,
302
- windowsHide: true,
303
- stdio: ["pipe", "pipe", "pipe"],
304
- },
305
- );
306
- } catch {
307
- finish({
308
- ok: false,
309
- state: "paused",
310
- code: "isolation-backend-launch-failed",
311
- });
312
- return;
313
- }
314
- const malformed = () => {
315
- bad = true;
316
- cancel();
317
- };
318
- child.stdout?.on("data", (chunk: Buffer) => {
319
- if (closed || bad) return;
320
- line += chunk.toString("utf8");
321
- // Helper lines are ASCII and <= 2200 bytes. Drain incrementally.
322
- while (line.includes("\n")) {
323
- const end = line.indexOf("\n");
324
- const row = line.slice(0, end);
325
- line = line.slice(end + 1);
326
- if (row.length > 4096 || final) {
327
- malformed();
328
- return;
329
- }
330
- try {
331
- const value = JSON.parse(row);
332
- if (
333
- Object.keys(value).length === 1 &&
334
- typeof value.outputHex === "string" &&
335
- /^(?:[a-f0-9]{2}){1,1024}$/u.test(value.outputHex)
336
- )
337
- output.append(Buffer.from(value.outputHex, "hex"));
338
- else {
339
- final = observation(value);
340
- if (!final) {
341
- malformed();
342
- return;
343
- }
344
- }
345
- } catch {
346
- malformed();
347
- return;
348
- }
349
- }
350
- if (line.length > 4096) malformed();
351
- });
352
- child.stderr?.on("data", () => {
353
- /* helper diagnostics are never product output */
354
- });
355
- child.stdin?.on("error", () => {
356
- bad = true;
357
- });
358
- child.once("error", () => {
359
- bad = true;
360
- launchFailed = child.pid === undefined;
361
- });
362
- child.once("close", (code) =>
363
- finish(
364
- launchFailed
365
- ? {
366
- ok: false,
367
- state: "paused",
368
- code: "isolation-backend-launch-failed",
369
- }
370
- : bad || line.length
371
- ? uncertain()
372
- : classify(final, code, output, input.signal?.aborted === true),
373
- ),
374
- );
375
- // Kill-on-close is containment; only a receipt establishes settlement.
376
- armDeadline(timeoutMs + SHUTDOWN_MS + 10_000);
377
- input.signal?.addEventListener("abort", cancel, { once: true });
378
- child.stdin?.write(wire);
379
- if (input.signal?.aborted) cancel();
380
- });
381
- }
382
- }
383
-
384
- export function probeWindowsJob(helper: string): boolean {
385
- if (
386
- process.platform !== "win32" ||
387
- process.arch !== "x64" ||
388
- !verifyWindowsJobHelper(helper)
389
- )
390
- return false;
391
- const wire = encodeWindowsJobRequest(
392
- {
393
- root: process.cwd(),
394
- executable: process.execPath,
395
- args: ["-e", "process.exit(0)"],
396
- environment: { SystemRoot: process.env.SystemRoot ?? "C:\\Windows" },
397
- },
398
- 5000,
399
- );
400
- // EOF means cancel, so doctor uses the helper's explicit probe path instead.
401
- const result = spawnSync(helper, ["--probe"], {
402
- input: wire,
403
- shell: false,
404
- encoding: "utf8",
405
- timeout: 15000,
406
- maxBuffer: 65536,
407
- });
408
- try {
409
- const v = observation(JSON.parse(result.stdout.trim()));
410
- return (
411
- !result.error &&
412
- result.status === 0 &&
413
- v?.outcome === "complete" &&
414
- v.exitCode === 0
415
- );
416
- } catch {
417
- return false;
418
- }
419
- }
package/src/windows-job.c DELETED
@@ -1,149 +0,0 @@
1
- /* Windows x64 host-trusted Job supervisor, protocol v2. Wire: nine LE uint32s,
2
- * then four sized UTF-16LE strings (exe, CRT command line, cwd, env block).
3
- * Remaining stdin is control: any byte or EOF cancels. No inherited Job handle.
4
- * Native qualification, not source assertions, establishes API behavior. */
5
- #define _WIN32_WINNT 0x0A00
6
- #include <windows.h>
7
- #include <stdio.h>
8
- #include <stdlib.h>
9
- #include <string.h>
10
- #include <wchar.h>
11
-
12
- static HANDLE controlEvent;
13
- static volatile LONG watchdogMs = 5000;
14
- static DWORD WINAPI watchdogThread(LPVOID unused) {
15
- ULONGLONG start = GetTickCount64();
16
- (void)unused;
17
- for (;;) {
18
- if (GetTickCount64() - start > (DWORD)InterlockedCompareExchange(&watchdogMs, 0, 0)) ExitProcess(2);
19
- Sleep(20);
20
- }
21
- }
22
- static DWORD WINAPI controlThread(LPVOID unused) {
23
- char byte; DWORD count;
24
- (void)unused;
25
- ReadFile(GetStdHandle(STD_INPUT_HANDLE), &byte, 1, &count, NULL);
26
- SetEvent(controlEvent);
27
- return 0;
28
- }
29
- static int exact(void *buffer, DWORD length) {
30
- DWORD count, available; char *p = (char *)buffer;
31
- ULONGLONG deadline = GetTickCount64() + 5000;
32
- while (length) {
33
- if (GetTickCount64() >= deadline || !PeekNamedPipe(GetStdHandle(STD_INPUT_HANDLE), NULL, 0, NULL, &available, NULL)) return 0;
34
- if (!available) { Sleep(10); continue; }
35
- if (!ReadFile(GetStdHandle(STD_INPUT_HANDLE), p, length < available ? length : available, &count, NULL) || !count) return 0;
36
- p += count; length -= count;
37
- }
38
- return 1;
39
- }
40
- static void report(const char *outcome, const char *reason, int root, int settled, DWORD exitCode) {
41
- printf("{\"version\":2,\"outcome\":\"%s\",\"reason\":\"%s\",\"rootExited\":%s,\"managedSettled\":%s,\"exitCode\":%lu}\n",
42
- outcome, reason, root ? "true" : "false", settled ? "true" : "false", (unsigned long)exitCode);
43
- fflush(stdout);
44
- }
45
- int wmain(int argc, wchar_t **argv) {
46
- DWORD h[9], total = 0, i, active = 1, count, available, exitCode = 1;
47
- wchar_t *parts[4] = {0};
48
- HANDLE job = NULL, completion = NULL, outRead = NULL, outWrite = NULL, nullInput = INVALID_HANDLE_VALUE;
49
- SECURITY_ATTRIBUTES sa = {sizeof(sa), NULL, TRUE};
50
- JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = {0};
51
- JOBOBJECT_ASSOCIATE_COMPLETION_PORT association = {0};
52
- JOBOBJECT_BASIC_ACCOUNTING_INFORMATION accounting;
53
- STARTUPINFOEXW si = {0}; PROCESS_INFORMATION pi = {0}; SIZE_T attributeBytes = 0;
54
- HANDLE inherited[2]; ULONGLONG start, stopping = 0;
55
- const char *reason = "exit"; int root = 0, settled = 0, result = 1;
56
- BOOL inJob = FALSE;
57
- int probe = argc == 2 && wcscmp(argv[1], L"--probe") == 0;
58
- { HANDLE watchdog = CreateThread(NULL, 0, watchdogThread, NULL, 0, NULL);
59
- if (!watchdog) return 2;
60
- CloseHandle(watchdog);
61
- }
62
- if (argc > 1 && !probe) goto done;
63
- if (!exact(h, sizeof(h)) || h[0] != 2 || h[8] != 0 || h[1] < 1 || h[1] > 86400000 || h[2] < 1 || h[2] > 10000 || h[3] != 0) goto done;
64
- for (i = 0; i < 4; i++) {
65
- if (h[4+i] < 2 || h[4+i] > 60000 || (h[4+i] & 1)) goto done;
66
- total += h[4+i]; if (total > 65500) goto done;
67
- parts[i] = (wchar_t *)calloc(1, h[4+i]);
68
- if (!parts[i] || !exact(parts[i], h[4+i]) || parts[i][h[4+i]/2-1] != 0) goto done;
69
- if (i < 3 && wcslen(parts[i]) != h[4+i]/2-1) goto done;
70
- }
71
- if (h[7] < 4 || parts[3][h[7]/2-2] != 0 || wcslen(parts[0]) < 3 || parts[0][1] != L':' || parts[0][2] != L'\\' || wcslen(parts[2]) < 3 || parts[2][1] != L':' || parts[2][2] != L'\\') goto done;
72
- InterlockedExchange(&watchdogMs, (LONG)(h[1] + h[2] + 6000));
73
- job = CreateJobObjectW(NULL, NULL);
74
- if (!job) goto done;
75
- limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
76
- if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &limits, sizeof(limits))) goto done;
77
- completion = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
78
- association.CompletionKey = job; association.CompletionPort = completion;
79
- if (!completion || !SetInformationJobObject(job, JobObjectAssociateCompletionPortInformation, &association, sizeof(association))) goto done;
80
- if (!CreatePipe(&outRead, &outWrite, &sa, 0) || !SetHandleInformation(outRead, HANDLE_FLAG_INHERIT, 0)) goto done;
81
- nullInput = CreateFileW(L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, NULL);
82
- if (nullInput == INVALID_HANDLE_VALUE) goto done;
83
- InitializeProcThreadAttributeList(NULL, 2, 0, &attributeBytes);
84
- si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(attributeBytes);
85
- if (!si.lpAttributeList) goto done;
86
- if (!InitializeProcThreadAttributeList(si.lpAttributeList, 2, 0, &attributeBytes)) { free(si.lpAttributeList); si.lpAttributeList = NULL; goto done; }
87
- inherited[0] = outWrite; inherited[1] = nullInput;
88
- if (!UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited, sizeof(inherited), NULL, NULL)) goto done;
89
- /* Atomic Job membership closes the helper-loss window between creation and
90
- * AssignProcessToJobObject. The root cannot exist outside this Job, even
91
- * while suspended; the Job handle is never inherited by target descendants. */
92
- if (!UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST, &job, sizeof(job), NULL, NULL)) goto done;
93
- si.StartupInfo.cb = sizeof(si); si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
94
- si.StartupInfo.hStdInput = nullInput; si.StartupInfo.hStdOutput = outWrite; si.StartupInfo.hStdError = outWrite;
95
- if (!CreateProcessW(parts[0], parts[1], NULL, NULL, TRUE, CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT, parts[3], parts[2], &si.StartupInfo, &pi)) goto done;
96
- if (!IsProcessInJob(pi.hProcess, job, &inJob) || !inJob) goto done;
97
- controlEvent = CreateEventW(NULL, TRUE, FALSE, NULL);
98
- if (!controlEvent) goto done;
99
- if (!probe) { HANDLE thread = CreateThread(NULL, 0, controlThread, NULL, 0, NULL);
100
- if (!thread) goto done;
101
- CloseHandle(thread);
102
- }
103
- if (ResumeThread(pi.hThread) == (DWORD)-1) goto done;
104
- CloseHandle(outWrite); outWrite = NULL;
105
- start = GetTickCount64();
106
- for (;;) {
107
- char buffer[1024]; DWORD message; ULONG_PTR key; LPOVERLAPPED overlap;
108
- GetQueuedCompletionStatus(completion, &message, &key, &overlap, 10);
109
- root = WaitForSingleObject(pi.hProcess, 0) == WAIT_OBJECT_0;
110
- if (QueryInformationJobObject(job, JobObjectBasicAccountingInformation, &accounting, sizeof(accounting), NULL)) active = accounting.ActiveProcesses;
111
- else { reason = "termination-unconfirmed"; break; }
112
- available = 0;
113
- if (PeekNamedPipe(outRead, NULL, 0, NULL, &available, NULL) && available) {
114
- if (ReadFile(outRead, buffer, available > (DWORD)sizeof(buffer) ? (DWORD)sizeof(buffer) : available, &count, NULL)) {
115
- printf("{\"outputHex\":\""); for (i = 0; i < count; i++) printf("%02x", (unsigned int)(unsigned char)buffer[i]); printf("\"}\n"); fflush(stdout);
116
- }
117
- }
118
- /* Job accounting can reach zero before the root process handle signals.
119
- * Both observations are required; keep polling under the original deadline. */
120
- if (!active && !available && root) { settled = 1; break; }
121
- if (!stopping) {
122
- if (WaitForSingleObject(controlEvent, 0) == WAIT_OBJECT_0) reason = "cancelled";
123
- else if (GetTickCount64() - start >= h[1]) reason = "timeout";
124
- if (strcmp(reason, "exit") != 0) { stopping = GetTickCount64(); TerminateJobObject(job, 1); }
125
- }
126
- if (stopping && GetTickCount64() - stopping >= h[2]) { reason = "termination-unconfirmed"; break; }
127
- }
128
- if (root && !GetExitCodeProcess(pi.hProcess, &exitCode)) { settled = 0; reason = "termination-unconfirmed"; }
129
- report(settled ? (strcmp(reason, "exit") == 0 ? "complete" : "failed") : "uncertain", reason, root, settled, exitCode);
130
- result = settled ? 0 : 2;
131
- goto cleanup;
132
- done:
133
- if (pi.hProcess) { TerminateProcess(pi.hProcess, 1); settled = WaitForSingleObject(pi.hProcess, 5000) == WAIT_OBJECT_0; }
134
- else settled = 1;
135
- report(settled ? "failed" : "uncertain", settled ? "launch-failed" : "termination-unconfirmed", pi.hProcess != NULL && settled, settled, 1);
136
- result = settled ? 0 : 2;
137
- cleanup:
138
- if (job) CloseHandle(job);
139
- if (pi.hThread) CloseHandle(pi.hThread);
140
- if (pi.hProcess) CloseHandle(pi.hProcess);
141
- if (outRead) CloseHandle(outRead);
142
- if (outWrite) CloseHandle(outWrite);
143
- if (nullInput != INVALID_HANDLE_VALUE) CloseHandle(nullInput);
144
- if (completion) CloseHandle(completion);
145
- if (si.lpAttributeList) { DeleteProcThreadAttributeList(si.lpAttributeList); free(si.lpAttributeList); }
146
- for (i = 0; i < 4; i++) free(parts[i]);
147
- /* Process exit ends the blocked control reader; do not close its live event. */
148
- return result;
149
- }