@buaa_smat/hometrans 26.0.4 → 26.0.5

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 (102) hide show
  1. package/agents/code-reviewer.md +2 -0
  2. package/agents/model-render-worker.md +1 -1
  3. package/i18n/agents/code-reviewer.md +2 -0
  4. package/i18n/agents/model-render-worker.md +1 -1
  5. package/i18n/skills/a2h-app-migrate/SKILL.md +51 -3
  6. package/i18n/skills/a2h-app-migrate/references/workflow.yaml +140 -32
  7. package/i18n/skills/a2h-app-migrate/scripts/dag_graph.mjs +297 -0
  8. package/i18n/skills/a2h-app-migrate/scripts/validate_workflow.mjs +134 -21
  9. package/i18n/skills/a2h-app-migrate/test/test_finalize.mjs +21 -4
  10. package/i18n/skills/a2h-app-migrate/test/test_image_probe.mjs +3 -3
  11. package/i18n/skills/a2h-app-migrate/test/test_resume_plan.mjs +1 -1
  12. package/i18n/skills/a2h-app-migrate/test/test_reuse_static_utg.mjs +1 -1
  13. package/i18n/skills/a2h-app-migrate/test/test_utg_static_done.mjs +12 -5
  14. package/i18n/skills/a2h-arkts-logic-coder/SKILL.md +7 -8
  15. package/i18n/skills/a2h-arkts-logic-coder/references/ISSUES.md +1 -1
  16. package/i18n/skills/a2h-arkts-logic-coder/references/code-generation.md +27 -15
  17. package/i18n/skills/a2h-batch-ui-align/SKILL.md +1 -1
  18. package/i18n/skills/a2h-batch-ui-align/references/cards/widgets.md +4 -0
  19. package/i18n/skills/a2h-batch-ui-align/references/checker-rules.md +36 -0
  20. package/i18n/skills/a2h-batch-ui-align/references/conversion-procedure.md +4 -0
  21. package/i18n/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +4 -0
  22. package/i18n/skills/a2h-batch-ui-align/references/step5-convert.md +3 -3
  23. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/main.ts +8 -0
  24. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/overlay_in_linear.ts +164 -0
  25. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/self_drawn_sheet.ts +105 -0
  26. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/staggered_lanes.ts +127 -0
  27. package/i18n/skills/a2h-batch-ui-align/scripts/static_check/rules/window_size_constant.ts +114 -0
  28. package/i18n/skills/a2h-page-specgen/references/scenario-authoring.md +4 -1
  29. package/i18n/skills/a2h-page-specgen/references/spec-example.md +35 -5
  30. package/i18n/skills/a2h-page-specgen/references/spec-template.md +4 -4
  31. package/i18n/skills/a2h-spec-generate/SKILL.md +3 -1
  32. package/i18n/skills/a2h-spec-generate/references/fusion-task-contract.md +15 -3
  33. package/i18n/skills/a2h-spec-generate/references/review-checklist.md +1 -0
  34. package/i18n/skills/a2h-spec-generate/references/spec-sample-complex.md +16 -0
  35. package/i18n/skills/a2h-spec-generate/references/spec-sample-transfer.md +16 -0
  36. package/i18n/skills/a2h-spec-generate/references/spec-samples.md +5 -1
  37. package/i18n/skills/a2h-spec-generate/references/synthesis-rules.md +21 -1
  38. package/i18n/skills/a2h-spec-generate/references/worker-rules.md +25 -2
  39. package/i18n/skills/a2h-spec-generate/scripts/check_spec.ts +121 -6
  40. package/i18n/skills/a2h-spec-generate/scripts/reqgen/src/fusion/task-contract.ts +2 -1
  41. package/i18n/skills/a2h-spec-generate/scripts/reqgen/test/fusion-behavior-e2e.test.ts +3 -0
  42. package/i18n/skills/a2h-spec-generate/scripts/reqgen/test/fusion-spec.test.ts +16 -2
  43. package/i18n/skills/a2h-spec-generate/test/check-fused-spec.test.mjs +11 -2
  44. package/i18n/skills/a2h-spec-generate/test/check-spec.test.ts +35 -0
  45. package/package.json +1 -1
  46. package/skills/a2h-app-migrate/SKILL.md +53 -5
  47. package/skills/a2h-app-migrate/references/workflow.yaml +140 -32
  48. package/skills/a2h-app-migrate/scripts/assert_dag_complete.mjs +226 -0
  49. package/skills/a2h-app-migrate/scripts/dag_graph.mjs +297 -0
  50. package/skills/a2h-app-migrate/scripts/dag_process_executor.mjs +199 -0
  51. package/skills/a2h-app-migrate/scripts/dag_production_executor.mjs +897 -0
  52. package/skills/a2h-app-migrate/scripts/dag_runner.mjs +1767 -0
  53. package/skills/a2h-app-migrate/scripts/ledger.mjs +15 -2
  54. package/skills/a2h-app-migrate/scripts/lib-yaml-lite.mjs +8 -2
  55. package/skills/a2h-app-migrate/scripts/resume_plan.mjs +3 -8
  56. package/skills/a2h-app-migrate/scripts/validate_workflow.mjs +134 -21
  57. package/skills/a2h-app-migrate/test/test_dag_complete.mjs +222 -0
  58. package/skills/a2h-app-migrate/test/test_dag_production.mjs +670 -0
  59. package/skills/a2h-app-migrate/test/test_dag_runner.mjs +423 -0
  60. package/skills/a2h-app-migrate/test/test_finalize.mjs +21 -4
  61. package/skills/a2h-app-migrate/test/test_image_probe.mjs +1 -1
  62. package/skills/a2h-app-migrate/test/test_resume_plan.mjs +16 -1
  63. package/skills/a2h-app-migrate/test/test_reuse_static_utg.mjs +1 -1
  64. package/skills/a2h-app-migrate/test/test_utg_static_done.mjs +12 -5
  65. package/skills/a2h-arkts-logic-coder/SKILL.md +7 -8
  66. package/skills/a2h-arkts-logic-coder/references/ISSUES.md +1 -1
  67. package/skills/a2h-arkts-logic-coder/references/code-generation.md +27 -15
  68. package/skills/a2h-batch-ui-align/SKILL.md +1 -1
  69. package/skills/a2h-batch-ui-align/references/cards/widgets.md +4 -0
  70. package/skills/a2h-batch-ui-align/references/checker-rules.md +36 -0
  71. package/skills/a2h-batch-ui-align/references/conversion-procedure.md +4 -0
  72. package/skills/a2h-batch-ui-align/references/mappings/android-to-harmonyOS-ui-layout-mapping-reference.md +4 -0
  73. package/skills/a2h-batch-ui-align/references/step5-convert.md +3 -3
  74. package/skills/a2h-batch-ui-align/scripts/group_queue.mjs +49 -3
  75. package/skills/a2h-batch-ui-align/scripts/static_check/core/android.ts +36 -0
  76. package/skills/a2h-batch-ui-align/scripts/static_check/main.ts +8 -0
  77. package/skills/a2h-batch-ui-align/scripts/static_check/registry.ts +8 -0
  78. package/skills/a2h-batch-ui-align/scripts/static_check/rules/overlay_in_linear.ts +164 -0
  79. package/skills/a2h-batch-ui-align/scripts/static_check/rules/self_drawn_sheet.ts +105 -0
  80. package/skills/a2h-batch-ui-align/scripts/static_check/rules/staggered_lanes.ts +127 -0
  81. package/skills/a2h-batch-ui-align/scripts/static_check/rules/window_size_constant.ts +114 -0
  82. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_coolmall_ds1123.test.mjs +433 -0
  83. package/skills/a2h-batch-ui-align/scripts/tests/arkts_static_check_overlay_in_linear.test.mjs +288 -0
  84. package/skills/a2h-batch-ui-align/scripts/tests/group_queue.test.mjs +46 -0
  85. package/skills/a2h-page-specgen/references/scenario-authoring.md +4 -1
  86. package/skills/a2h-page-specgen/references/spec-example.md +35 -5
  87. package/skills/a2h-page-specgen/references/spec-template.md +4 -4
  88. package/skills/a2h-spec-generate/SKILL.md +3 -1
  89. package/skills/a2h-spec-generate/references/fusion-task-contract.md +15 -3
  90. package/skills/a2h-spec-generate/references/review-checklist.md +1 -0
  91. package/skills/a2h-spec-generate/references/spec-sample-complex.md +16 -0
  92. package/skills/a2h-spec-generate/references/spec-sample-transfer.md +16 -0
  93. package/skills/a2h-spec-generate/references/spec-samples.md +5 -1
  94. package/skills/a2h-spec-generate/references/synthesis-rules.md +21 -1
  95. package/skills/a2h-spec-generate/references/worker-rules.md +25 -2
  96. package/skills/a2h-spec-generate/scripts/check-fused-spec.mjs +3 -1
  97. package/skills/a2h-spec-generate/scripts/check_spec.ts +262 -6
  98. package/skills/a2h-spec-generate/scripts/reqgen/src/fusion/task-contract.ts +12 -2
  99. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-behavior-e2e.test.ts +3 -0
  100. package/skills/a2h-spec-generate/scripts/reqgen/test/fusion-spec.test.ts +16 -2
  101. package/skills/a2h-spec-generate/test/check-fused-spec.test.mjs +54 -3
  102. package/skills/a2h-spec-generate/test/check-spec.test.ts +247 -0
@@ -0,0 +1,297 @@
1
+ const TERMINAL_STATUSES = new Set(["done", "reused", "skipped", "failed"]);
2
+
3
+ /** Nodes cut by the profile: lane not in include_lanes, or named by force_skip (node id or lane id). */
4
+ export function profileSkipped(doc, profile) {
5
+ const conf = doc.profiles?.[profile] || {};
6
+ const lanes = conf.include_lanes === "all" || !conf.include_lanes ? null : new Set(conf.include_lanes);
7
+ const force = new Set(conf.force_skip || []);
8
+ return new Set((doc.nodes || []).filter((n) => (lanes && !lanes.has(n.lane)) || force.has(n.id) || force.has(n.lane)).map((n) => n.id));
9
+ }
10
+
11
+ function graphParts(doc) {
12
+ const nodes = doc.nodes || [];
13
+ const byId = new Map(nodes.map((node) => [node.id, node]));
14
+ const byGroup = {};
15
+ for (const node of nodes) {
16
+ if (node.parallel_group) (byGroup[node.parallel_group] ||= []).push(node.id);
17
+ }
18
+ const parents = {};
19
+ const children = {};
20
+ for (const node of nodes) {
21
+ const ids = new Set(node.needs || []);
22
+ for (const conditional of node.conditional_needs || []) {
23
+ for (const id of conditional.add || []) ids.add(id);
24
+ }
25
+ if (node.also_needs_group) {
26
+ for (const id of byGroup[node.also_needs_group] || []) {
27
+ if (id !== node.id) ids.add(id);
28
+ }
29
+ }
30
+ parents[node.id] = ids;
31
+ children[node.id] ||= new Set();
32
+ }
33
+ for (const [child, ids] of Object.entries(parents)) {
34
+ for (const parent of ids) (children[parent] ||= new Set()).add(child);
35
+ }
36
+ return { nodes, byId, byGroup, parents, children };
37
+ }
38
+
39
+ export function validateGraph(doc) {
40
+ const { nodes, byId, byGroup, parents } = graphParts(doc);
41
+ const ids = nodes.map((node) => node.id);
42
+ const errors = [];
43
+ const duplicates = new Set(ids.filter((id, index) => ids.indexOf(id) !== index));
44
+ if (duplicates.size) errors.push(`duplicate node ids: ${[...duplicates].sort()}`);
45
+
46
+ for (const node of nodes) {
47
+ for (const parent of node.needs || []) {
48
+ if (!byId.has(parent)) errors.push(`${node.id}: needs points to a missing node \`${parent}\``);
49
+ }
50
+ for (const conditional of node.conditional_needs || []) {
51
+ for (const parent of conditional.add || []) {
52
+ if (!byId.has(parent)) errors.push(`${node.id}: conditional_needs.add points to a missing node \`${parent}\``);
53
+ }
54
+ }
55
+ if (node.also_needs_group && !byGroup[node.also_needs_group]) {
56
+ errors.push(`${node.id}: also_needs_group points to a missing group \`${node.also_needs_group}\``);
57
+ }
58
+ }
59
+
60
+ const seen = new Set();
61
+ let todo = [...new Set(ids)];
62
+ while (todo.length) {
63
+ const ready = todo.filter((id) => [...(parents[id] || [])].every((parent) => !byId.has(parent) || seen.has(parent)));
64
+ if (!ready.length) {
65
+ errors.push(`the DAG has a cycle involving: ${todo.join(",")}`);
66
+ break;
67
+ }
68
+ for (const id of ready) seen.add(id);
69
+ todo = todo.filter((id) => !seen.has(id));
70
+ }
71
+ return errors;
72
+ }
73
+
74
+ export function buildGraph(doc, options = {}) {
75
+ const profile = typeof options === "string" ? options : options.profile || "";
76
+ const errors = validateGraph(doc);
77
+ if (errors.length) {
78
+ const error = new Error(errors.join("\n"));
79
+ error.code = "DAG_GRAPH_INVALID";
80
+ error.errors = errors;
81
+ throw error;
82
+ }
83
+ const { nodes, byId, parents, children } = graphParts(doc);
84
+ const skippedByProfile = profileSkipped(doc, profile);
85
+ const serialRank = new Map((doc.serial_order || []).map((id, index) => [id, index]));
86
+ return {
87
+ nodes,
88
+ byId,
89
+ parents,
90
+ children,
91
+ serialRank,
92
+ activeIds: new Set(nodes.filter((node) => !skippedByProfile.has(node.id)).map((node) => node.id)),
93
+ skippedByProfile,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Nodes a gate rewind to `targetId` must reset: the target plus everything that consumes its output,
99
+ * transitively. Only data edges count (needs, also_needs_group). conditional_needs are ordering-only
100
+ * (e.g. boot.workspace waits for discover.arch to create the shell under SERIALIZE_DISCOVER) and do not
101
+ * read the target's artifacts, so redoing the target must not re-run nodes hanging off such an edge.
102
+ */
103
+ export function rewindAffected(graph, targetId) {
104
+ const dataChildren = {};
105
+ for (const node of graph.nodes) {
106
+ for (const parent of resolveParents(graph, node, {}, { conditional: false })) {
107
+ (dataChildren[parent] ||= new Set()).add(node.id);
108
+ }
109
+ }
110
+ const affected = new Set([targetId]);
111
+ const queue = [targetId];
112
+ while (queue.length) {
113
+ for (const child of dataChildren[queue.shift()] || []) {
114
+ if (!affected.has(child)) {
115
+ affected.add(child);
116
+ queue.push(child);
117
+ }
118
+ }
119
+ }
120
+ return affected;
121
+ }
122
+
123
+ export function resolveParents(graph, node, vars = {}, { conditional = true } = {}) {
124
+ const parents = new Set(node.needs || []);
125
+ for (const entry of conditional ? node.conditional_needs || [] : []) {
126
+ if (evaluateExpression(entry.when, vars)) {
127
+ for (const id of entry.add || []) parents.add(id);
128
+ }
129
+ }
130
+ if (node.also_needs_group) {
131
+ for (const candidate of graph.nodes) {
132
+ if (candidate.id !== node.id && candidate.parallel_group === node.also_needs_group) parents.add(candidate.id);
133
+ }
134
+ }
135
+ return parents;
136
+ }
137
+
138
+ export function readyNodes(graph, statuses, vars = {}) {
139
+ const readStatus = (id) => statuses instanceof Map ? statuses.get(id) : statuses?.[id];
140
+ const isTerminal = (id) => {
141
+ const record = readStatus(id);
142
+ const status = record && typeof record === "object" && !Array.isArray(record) ? record.status : record;
143
+ return TERMINAL_STATUSES.has(status);
144
+ };
145
+ const declarationOrder = new Map(graph.nodes.map((node, index) => [node.id, index]));
146
+ return graph.nodes.filter((node) => {
147
+ if (!graph.activeIds.has(node.id) || isTerminal(node.id)) return false;
148
+ return [...resolveParents(graph, node, vars)].every((parent) => !graph.activeIds.has(parent) || isTerminal(parent));
149
+ }).sort((left, right) => {
150
+ const leftRank = graph.serialRank?.has(left.id) ? graph.serialRank.get(left.id) : Number.MAX_SAFE_INTEGER;
151
+ const rightRank = graph.serialRank?.has(right.id) ? graph.serialRank.get(right.id) : Number.MAX_SAFE_INTEGER;
152
+ return leftRank - rightRank || declarationOrder.get(left.id) - declarationOrder.get(right.id);
153
+ });
154
+ }
155
+
156
+ function unsupported(message) {
157
+ const error = new Error(message);
158
+ error.code = "UNSUPPORTED_EXPRESSION";
159
+ throw error;
160
+ }
161
+
162
+ function evaluateExpression(input, vars = {}) {
163
+ const source = String(input ?? "");
164
+ const readVar = (name) => {
165
+ if (name === "true") return true;
166
+ if (name === "false") return false;
167
+ if (name === "null") return null;
168
+ if (vars instanceof Map) return vars.get(name);
169
+ return vars != null && Object.prototype.hasOwnProperty.call(vars, name) ? vars[name] : undefined;
170
+ };
171
+ let at = 0;
172
+
173
+ function skipSpace() {
174
+ while (/\s/.test(source[at] || "")) at++;
175
+ }
176
+
177
+ function take(token) {
178
+ skipSpace();
179
+ if (!source.startsWith(token, at)) return false;
180
+ at += token.length;
181
+ return true;
182
+ }
183
+
184
+ function primary() {
185
+ skipSpace();
186
+ if (at >= source.length) unsupported(`missing expression at position ${at}`);
187
+ if (take("(")) {
188
+ const value = expression();
189
+ if (!take(")")) unsupported(`expected ) at position ${at}`);
190
+ return value;
191
+ }
192
+ if (source[at] === "'" || source[at] === '"') return string();
193
+ const number = source.slice(at).match(/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/);
194
+ if (number) {
195
+ at += number[0].length;
196
+ return Number(number[0]);
197
+ }
198
+ let name;
199
+ if (take("${")) {
200
+ name = source.slice(at).match(/^[A-Za-z_$][\w$]*/)?.[0];
201
+ if (!name) unsupported(`invalid variable at position ${at}`);
202
+ at += name.length;
203
+ if (!take("}")) unsupported(`invalid variable at position ${at}`);
204
+ return readVar(name);
205
+ }
206
+ name = source.slice(at).match(/^[A-Za-z_$][\w$]*/)?.[0];
207
+ if (!name) unsupported(`unsupported expression at position ${at}`);
208
+ at += name.length;
209
+ const value = readVar(name);
210
+ return value === undefined ? name : value;
211
+ }
212
+
213
+ function keyword(token) {
214
+ skipSpace();
215
+ if (!source.startsWith(token, at)) return false;
216
+ const before = source[at - 1] || "";
217
+ const after = source[at + token.length] || "";
218
+ if (/[A-Za-z0-9_$]/.test(before) || /[A-Za-z0-9_$]/.test(after)) return false;
219
+ at += token.length;
220
+ return true;
221
+ }
222
+
223
+ function unary() {
224
+ skipSpace();
225
+ if (take("!") || keyword("not")) return !unary();
226
+ return primary();
227
+ }
228
+
229
+ function string() {
230
+ const quote = source[at++];
231
+ let value = "";
232
+ while (at < source.length && source[at] !== quote) {
233
+ if (source[at] === "\\") unsupported(`string escapes are not supported at position ${at}`);
234
+ value += source[at++];
235
+ }
236
+ if (source[at] !== quote) unsupported(`unterminated string at position ${at}`);
237
+ at++;
238
+ return value;
239
+ }
240
+
241
+ function relational() {
242
+ let left = unary();
243
+ for (;;) {
244
+ const operator = [">=", "<=", ">", "<"].find((candidate) => take(candidate));
245
+ if (!operator) return left;
246
+ const right = unary();
247
+ if (operator === ">=") left = left >= right;
248
+ else if (operator === "<=") left = left <= right;
249
+ else if (operator === ">") left = left > right;
250
+ else left = left < right;
251
+ }
252
+ }
253
+
254
+ function equality() {
255
+ let left = relational();
256
+ for (;;) {
257
+ const operator = ["===", "!==", "==", "!="].find((candidate) => take(candidate));
258
+ if (!operator) return left;
259
+ const right = relational();
260
+ if (operator === "===") left = left === right;
261
+ else if (operator === "!==") left = left !== right;
262
+ else if (operator === "==") left = left == right;
263
+ else left = left != right;
264
+ }
265
+ }
266
+
267
+ function andExpression() {
268
+ let left = equality();
269
+ for (;;) {
270
+ skipSpace();
271
+ if (source.startsWith("&&", at)) at += 2;
272
+ else if (keyword("and")) { /* consumed */ }
273
+ else return left;
274
+ const right = equality();
275
+ left = left && right;
276
+ }
277
+ }
278
+
279
+ function expression() {
280
+ let left = andExpression();
281
+ for (;;) {
282
+ skipSpace();
283
+ if (source.startsWith("||", at)) at += 2;
284
+ else if (keyword("or")) { /* consumed */ }
285
+ else return left;
286
+ const right = andExpression();
287
+ left = left || right;
288
+ }
289
+ }
290
+
291
+ const value = expression();
292
+ skipSpace();
293
+ if (at !== source.length) unsupported(`unsupported expression at position ${at}`);
294
+ return value;
295
+ }
296
+
297
+ export { evaluateExpression };
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Generic external-process executor protocol.
3
+ *
4
+ * The caller atomically writes the request JSON and starts the configured command.
5
+ * A worker reads A2H_DAG_REQUEST (request file), A2H_DAG_RESULT (result file), and
6
+ * A2H_DAG_ATTEMPT (expected attempt id) from its environment. After a successful
7
+ * exit, the worker must have written a JSON object at A2H_DAG_RESULT containing
8
+ * status=done|failed|waiting_external|waiting_human and the same attempt_id.
9
+ * A failed result requires a non-empty reason; evidence, wait, and details are
10
+ * optional. An `ok: true` field never substitutes for a valid status.
11
+ *
12
+ * Paths are passed only through the environment, so Windows paths need no manual
13
+ * quoting in the command. The default shell mode supports configured node workers
14
+ * and cmd commands. This module does not retry execution or update any ledger.
15
+ */
16
+
17
+ import { spawn } from "node:child_process";
18
+ import fs from "node:fs";
19
+ import path from "node:path";
20
+
21
+ const RESULT_STATUSES = new Set(["done", "failed", "waiting_external", "waiting_human"]);
22
+ const STDERR_LIMIT = 4096;
23
+
24
+ export class ExecutorProtocolError extends Error {
25
+ constructor(code, message, cause) {
26
+ super(message, cause === undefined ? undefined : { cause });
27
+ this.name = "ExecutorProtocolError";
28
+ this.code = code;
29
+ if (cause !== undefined) this.cause = cause;
30
+ }
31
+ }
32
+
33
+ function invalidResult(message, cause) {
34
+ return new ExecutorProtocolError("EXECUTOR_INVALID_RESULT", message, cause);
35
+ }
36
+
37
+ export function readExecutorResult(resultPath, attemptId) {
38
+ let text;
39
+ try {
40
+ text = fs.readFileSync(resultPath, "utf8");
41
+ } catch (err) {
42
+ if (err?.code === "ENOENT") {
43
+ throw new ExecutorProtocolError(
44
+ "EXECUTOR_EARLY_STOP",
45
+ `Executor exited without producing a result: ${resultPath}`,
46
+ err,
47
+ );
48
+ }
49
+ throw invalidResult(`Unable to read executor result: ${resultPath}`, err);
50
+ }
51
+
52
+ let result;
53
+ try {
54
+ result = JSON.parse(text);
55
+ } catch (err) {
56
+ throw invalidResult(`Executor result is not valid JSON: ${resultPath}`, err);
57
+ }
58
+
59
+ if (result === null || typeof result !== "object" || Array.isArray(result)) {
60
+ throw invalidResult("Executor result must be a JSON object");
61
+ }
62
+ if (!RESULT_STATUSES.has(result.status)) {
63
+ throw invalidResult("Executor result has an invalid or missing status");
64
+ }
65
+ if (result.attempt_id !== attemptId) {
66
+ throw new ExecutorProtocolError(
67
+ "EXECUTOR_STALE_ATTEMPT",
68
+ `Executor result attempt_id ${JSON.stringify(result.attempt_id)} does not match ${JSON.stringify(attemptId)}`,
69
+ );
70
+ }
71
+ if (result.status === "failed" && (typeof result.reason !== "string" || result.reason.trim() === "")) {
72
+ throw invalidResult("A failed executor result requires a non-empty reason");
73
+ }
74
+ return result;
75
+ }
76
+
77
+ function writeJsonAtomic(filePath, value) {
78
+ const directory = path.dirname(filePath);
79
+ fs.mkdirSync(directory, { recursive: true });
80
+ const tmp = path.join(
81
+ directory,
82
+ `.${path.basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,
83
+ );
84
+ try {
85
+ fs.writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", flag: "wx" });
86
+ fs.renameSync(tmp, filePath);
87
+ } catch (err) {
88
+ fs.rmSync(tmp, { force: true });
89
+ throw err;
90
+ }
91
+ }
92
+
93
+ function stderrExcerpt(stderr) {
94
+ const text = stderr.trim();
95
+ if (!text) return "";
96
+ return text.length <= STDERR_LIMIT ? text : `...${text.slice(-STDERR_LIMIT)}`;
97
+ }
98
+
99
+ function exitError(code, signal, stderr) {
100
+ const excerpt = stderrExcerpt(stderr);
101
+ const termination = signal ? `signal ${signal}` : `exit code ${code}`;
102
+ return new ExecutorProtocolError(
103
+ "EXECUTOR_EXIT",
104
+ `Executor failed with ${termination}${excerpt ? `: ${excerpt}` : ""}`,
105
+ );
106
+ }
107
+
108
+ export async function runProcessExecutor({
109
+ command,
110
+ request,
111
+ requestPath,
112
+ resultPath,
113
+ cwd,
114
+ env = {},
115
+ timeoutMs = 0,
116
+ spawnImpl,
117
+ }) {
118
+ if (typeof command !== "string" || command.trim() === "") {
119
+ throw new ExecutorProtocolError("EXECUTOR_NOT_CONFIGURED", "No external executor command is configured");
120
+ }
121
+
122
+ writeJsonAtomic(requestPath, request);
123
+ fs.mkdirSync(path.dirname(resultPath), { recursive: true });
124
+ fs.rmSync(resultPath, { force: true });
125
+
126
+ const attemptId = request?.attempt_id;
127
+ const launch = spawnImpl || spawn;
128
+ let child;
129
+ try {
130
+ child = launch(command, {
131
+ cwd,
132
+ env: {
133
+ ...process.env,
134
+ ...env,
135
+ A2H_DAG_REQUEST: requestPath,
136
+ A2H_DAG_RESULT: resultPath,
137
+ A2H_DAG_ATTEMPT: attemptId == null ? "" : String(attemptId),
138
+ },
139
+ shell: true,
140
+ windowsHide: true,
141
+ });
142
+ } catch (err) {
143
+ throw new ExecutorProtocolError("EXECUTOR_SPAWN_FAILED", "Unable to start executor", err);
144
+ }
145
+
146
+ let stdout = "";
147
+ let stderr = "";
148
+ child.stdout?.setEncoding("utf8");
149
+ child.stderr?.setEncoding("utf8");
150
+ child.stdout?.on("data", (chunk) => {
151
+ stdout += chunk;
152
+ });
153
+ child.stderr?.on("data", (chunk) => {
154
+ stderr += chunk;
155
+ });
156
+
157
+ const outcome = await new Promise((resolve, reject) => {
158
+ let settled = false;
159
+ let timedOut = false;
160
+ let timer;
161
+
162
+ const finish = (callback, value) => {
163
+ if (settled) return;
164
+ settled = true;
165
+ if (timer) clearTimeout(timer);
166
+ callback(value);
167
+ };
168
+
169
+ child.once("error", (err) => {
170
+ const excerpt = stderrExcerpt(stderr);
171
+ finish(reject, new ExecutorProtocolError(
172
+ "EXECUTOR_SPAWN_FAILED",
173
+ `Unable to start executor${excerpt ? `: ${excerpt}` : ""}`,
174
+ err,
175
+ ));
176
+ });
177
+ child.once("close", (code, signal) => {
178
+ if (timedOut) {
179
+ finish(reject, new ExecutorProtocolError(
180
+ "EXECUTOR_TIMEOUT",
181
+ `Executor exceeded timeout of ${timeoutMs} ms${stderrExcerpt(stderr) ? `: ${stderrExcerpt(stderr)}` : ""}`,
182
+ ));
183
+ } else {
184
+ finish(resolve, { code, signal });
185
+ }
186
+ });
187
+
188
+ if (timeoutMs > 0) {
189
+ timer = setTimeout(() => {
190
+ timedOut = true;
191
+ child.kill();
192
+ }, timeoutMs);
193
+ }
194
+ });
195
+
196
+ if (outcome.code !== 0) throw exitError(outcome.code, outcome.signal, stderr);
197
+ const result = readExecutorResult(resultPath, attemptId);
198
+ return { result, stdout, stderr, exitCode: outcome.code };
199
+ }