@agimon-ai/po-workflow 0.0.0-alpha.21 → 0.0.0-alpha.210

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 (58) hide show
  1. package/LICENSE +110 -149
  2. package/README.md +155 -53
  3. package/dist/apiContracts.cjs +205 -36
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +205 -36
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/contract-BpzJeyjh.mjs +33 -0
  10. package/dist/contract-BpzJeyjh.mjs.map +1 -0
  11. package/dist/contract-D80yV2d-.cjs +68 -0
  12. package/dist/contract-D80yV2d-.cjs.map +1 -0
  13. package/dist/extensions/native.mjs +4643 -1020
  14. package/dist/extensions/native.mjs.map +1 -1
  15. package/dist/extensions/server.cjs +21507 -3593
  16. package/dist/extensions/server.cjs.map +1 -1
  17. package/dist/extensions/server.d.mts.map +1 -1
  18. package/dist/extensions/server.mjs +21495 -3558
  19. package/dist/extensions/server.mjs.map +1 -1
  20. package/dist/extensions/web.mjs +5224 -2610
  21. package/dist/extensions/web.mjs.map +1 -1
  22. package/dist/index-CxS__mkJ.d.mts +5210 -0
  23. package/dist/index-CxS__mkJ.d.mts.map +1 -0
  24. package/dist/index.cjs +41 -3
  25. package/dist/index.cjs.map +1 -0
  26. package/dist/index.d.mts +104 -4
  27. package/dist/index.d.mts.map +1 -1
  28. package/dist/index.mjs +38 -1
  29. package/dist/index.mjs.map +1 -0
  30. package/dist/po-runtime-identity.json +1 -0
  31. package/dist/workflowHost-B8ludUOG.cjs +4190 -0
  32. package/dist/workflowHost-B8ludUOG.cjs.map +1 -0
  33. package/dist/workflowHost-DB4GtWpM.mjs +3974 -0
  34. package/dist/workflowHost-DB4GtWpM.mjs.map +1 -0
  35. package/dist/workflowHost.cjs +7 -0
  36. package/dist/workflowHost.d.mts +29 -0
  37. package/dist/workflowHost.d.mts.map +1 -0
  38. package/dist/workflowHost.mjs +3 -0
  39. package/dist/workflowServices-CSHleLJo.mjs +273 -0
  40. package/dist/workflowServices-CSHleLJo.mjs.map +1 -0
  41. package/dist/workflowServices-DYXhIDVE.cjs +350 -0
  42. package/dist/workflowServices-DYXhIDVE.cjs.map +1 -0
  43. package/llms.txt +10 -8
  44. package/locales/vi.json +492 -0
  45. package/locales/zh-CN.json +492 -0
  46. package/package.json +150 -26
  47. package/src/prompts/codemode-how-to-workflow/SKILL.md +226 -0
  48. package/src/prompts/help-how-to-workflow/SKILL.md +185 -0
  49. package/src/prompts/help-how-to-workflow-settings/SKILL.md +33 -0
  50. package/src/types/webWorkflowTerminal.ts +21 -0
  51. package/src/types/webWorkflows.ts +52 -2
  52. package/dist/workflowLaunchCommand-C69Nn3k5.cjs +0 -139
  53. package/dist/workflowLaunchCommand-C69Nn3k5.cjs.map +0 -1
  54. package/dist/workflowLaunchCommand-GGqimmTC.mjs +0 -122
  55. package/dist/workflowLaunchCommand-GGqimmTC.mjs.map +0 -1
  56. package/skills/workflow-recovery/SKILL.md +0 -85
  57. package/src/prompts/po-author-workflow/SKILL.md +0 -64
  58. package/src/prompts/po-use-workflow/SKILL.md +0 -21
@@ -0,0 +1,4190 @@
1
+ //#region \0rolldown/runtime.js
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+ //#endregion
23
+ const require_contract = require("./contract-D80yV2d-.cjs");
24
+ let liquidjs = require("liquidjs");
25
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
26
+ let node_path = require("node:path");
27
+ node_path = __toESM(node_path, 1);
28
+ let js_yaml = require("js-yaml");
29
+ let _agimon_ai_po_core_workflow = require("@agimon-ai/po-core/workflow");
30
+ let typebox_value = require("typebox/value");
31
+ let zod = require("zod");
32
+ let node_child_process = require("node:child_process");
33
+ let node_fs = require("node:fs");
34
+ let node_fs_promises = require("node:fs/promises");
35
+ node_fs_promises = __toESM(node_fs_promises, 1);
36
+ let node_module = require("node:module");
37
+ let node_readline = require("node:readline");
38
+ let node_url = require("node:url");
39
+ let proper_lockfile = require("proper-lockfile");
40
+ let node_perf_hooks = require("node:perf_hooks");
41
+ let node_os = require("node:os");
42
+ let node_crypto = require("node:crypto");
43
+ let node_net = require("node:net");
44
+ //#region src/services/workflowLaunchCommand/index.ts
45
+ /**
46
+ * The `/workflow-launch` line, parsed.
47
+ *
48
+ * WHY A VERB AT ALL:
49
+ * A browser can only send a session a prompt frame, so every cockpit action
50
+ * that has to run inside the session travels as a slash line, the way the
51
+ * agent catalog sends `/run`. The workflow tools answer to the agent, not to a
52
+ * page, and the leader board answers to a keyboard, so neither of them can be
53
+ * what the launch dialog sends.
54
+ *
55
+ * THE SHAPE:
56
+ * /workflow-launch <workflow> [key=value ...] [prompt words]
57
+ *
58
+ * Key-value pairs come first and stop at the first token that is not one, so
59
+ * everything after them is the prompt exactly as it was typed, including any
60
+ * `=` inside it. `runner`, `command`, `choice` and `profile` are reserved keys, and so is
61
+ * every `assign.<role>=<stable profile ref>` pair; the rest are the workflow's own
62
+ * `workflow_dispatch` inputs. Values may be double quoted to hold spaces.
63
+ */
64
+ /** Reserved key: which runner map entry the run executes with. */
65
+ const RUNNER_KEY = "runner";
66
+ /** Reserved key: which command templated steps run through. */
67
+ const COMMAND_KEY = "command";
68
+ /** Reserved key: which model choice steps without their own run with. */
69
+ const CHOICE_KEY = "choice";
70
+ /** Reserved key: which Po profile run step `secrets` resolve from. */
71
+ const PROFILE_KEY = "profile";
72
+ /** Reserved key prefix: `assign.<role>` names the stable profile reference that role runs as. */
73
+ const ASSIGN_PREFIX = "assign.";
74
+ const KEY_VALUE = /^([A-Za-z_][\w.-]*)=(.*)$/s;
75
+ /** Strips one layer of surrounding double quotes, which is how a value holds spaces. */
76
+ function unquote(value) {
77
+ return value.length > 1 && value.startsWith("\"") && value.endsWith("\"") ? value.slice(1, -1) : value;
78
+ }
79
+ /**
80
+ * Splits on whitespace, keeping double-quoted runs together.
81
+ *
82
+ * Returns each token with the offset it started at, so the caller can take the
83
+ * rest of the line verbatim rather than rebuilding it from tokens and losing
84
+ * the spacing a prompt was written with.
85
+ */
86
+ function tokenize(line) {
87
+ const tokens = [];
88
+ let index = 0;
89
+ while (index < line.length) {
90
+ while (index < line.length && /\s/.test(line[index])) index += 1;
91
+ if (index >= line.length) break;
92
+ const start = index;
93
+ let quoted = false;
94
+ while (index < line.length && (quoted || !/\s/.test(line[index]))) {
95
+ if (line[index] === "\"") quoted = !quoted;
96
+ index += 1;
97
+ }
98
+ tokens.push({
99
+ text: line.slice(start, index),
100
+ start
101
+ });
102
+ }
103
+ return tokens;
104
+ }
105
+ function parseWorkflowLaunchCommand(args) {
106
+ const tokens = tokenize(args.trim());
107
+ const first = tokens[0];
108
+ if (first === void 0) return { error: "Usage: /workflow-launch <workflow> [key=value …] [prompt]" };
109
+ const inputs = {};
110
+ const reserved = {};
111
+ const assignments = {};
112
+ let index = 1;
113
+ for (; index < tokens.length; index += 1) {
114
+ const token = tokens[index];
115
+ if (token.text === "--") {
116
+ index += 1;
117
+ break;
118
+ }
119
+ const match = KEY_VALUE.exec(token.text);
120
+ if (!match) break;
121
+ const key = match[1];
122
+ const value = unquote(match[2]);
123
+ if (key.startsWith(ASSIGN_PREFIX)) {
124
+ const role = key.slice(7);
125
+ if (role === "") return { error: "Name a role after assign., as assign.<role>=<profile reference>." };
126
+ if (value === "") return { error: `Give assign.${role} a profile reference.` };
127
+ if (Object.hasOwn(assignments, role)) return { error: `Role ${role} is assigned twice.` };
128
+ assignments[role] = value;
129
+ } else if (key === RUNNER_KEY || key === COMMAND_KEY || key === CHOICE_KEY || key === PROFILE_KEY) reserved[key] = value;
130
+ else inputs[key] = value;
131
+ }
132
+ const rest = tokens[index];
133
+ const prompt = rest === void 0 ? void 0 : args.trim().slice(rest.start).trim();
134
+ return {
135
+ workflow: unquote(first.text),
136
+ ...reserved,
137
+ ...Object.keys(assignments).length === 0 ? {} : { assignments },
138
+ inputs,
139
+ ...prompt === void 0 || prompt === "" ? {} : { prompt }
140
+ };
141
+ }
142
+ /**
143
+ * The workflow a token names: its name, its path in the repository, or the
144
+ * tail of that path. Case-insensitive on the name, because the catalog shows
145
+ * names as their author capitalised them and nobody types that back exactly.
146
+ */
147
+ function resolveWorkflowEntry(entries, token) {
148
+ const needle = token.trim();
149
+ const lower = needle.toLocaleLowerCase();
150
+ return entries.find((entry) => entry.name.toLocaleLowerCase() === lower) ?? entries.find((entry) => entry.relativePath === needle || entry.path === needle) ?? entries.find((entry) => entry.relativePath.endsWith(`/${needle}`) || entry.path.endsWith(`/${needle}`));
151
+ }
152
+ /** The trigger that makes a prompt mandatory: the run waits for one otherwise. */
153
+ const USER_PROMPT_TRIGGER = "user_prompt";
154
+ /**
155
+ * Everything wrong with a launch, before it is started.
156
+ *
157
+ * Checked here rather than left to the engine because the failure would
158
+ * otherwise be a run that starts and then waits forever for terminal input, or
159
+ * one that dies on a runner its steps never declared. Both read as the launch
160
+ * having worked.
161
+ */
162
+ function validateWorkflowLaunch(requirements, parsed) {
163
+ const problems = [];
164
+ if (requirements.triggers.includes(USER_PROMPT_TRIGGER) && (parsed.prompt ?? "") === "") problems.push("This workflow is triggered by a prompt, so it needs one.");
165
+ const missing = requirements.inputs.filter((input) => input.required === true && (parsed.inputs[input.name] ?? "") === "").map((input) => input.name);
166
+ if (missing.length > 0) problems.push(`Missing required input${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}.`);
167
+ for (const input of requirements.inputs) {
168
+ const value = parsed.inputs[input.name];
169
+ if (value === void 0 || input.options === void 0 || input.options.includes(value)) continue;
170
+ problems.push(`Input ${input.name} must be one of: ${input.options.join(", ")}.`);
171
+ }
172
+ const declared = requirements.runners;
173
+ if (parsed.runner !== void 0 && declared !== void 0 && !declared.includes(parsed.runner)) problems.push(declared.length === 0 ? "This workflow declares no runner its steps agree on." : `Runner ${parsed.runner} is not one this workflow declares: ${declared.join(", ")}.`);
174
+ if (parsed.command !== void 0 && !(requirements.commands ?? []).includes(parsed.command)) problems.push(requirements.commands === void 0 || requirements.commands.length === 0 ? "This workflow has no templated steps to run through a command." : `Command ${parsed.command} is not one every step offers: ${requirements.commands.join(", ")}.`);
175
+ if (parsed.choice !== void 0 && !(requirements.choices ?? []).includes(parsed.choice)) problems.push(`Choice ${parsed.choice} is not declared${requirements.choices?.length ? `: ${requirements.choices.join(", ")}` : ""}.`);
176
+ return problems;
177
+ }
178
+ //#endregion
179
+ //#region src/services/workflowShell/index.ts
180
+ /**
181
+ * Shell-quoting helpers for safely interpolating values into shell command strings.
182
+ *
183
+ * DESIGN PATTERNS:
184
+ * - Pure functions with no side effects
185
+ * - Context-aware escaping driven by the surrounding quote character
186
+ *
187
+ * AVOID:
188
+ * - String.prototype.replace with a value as the replacement string: its replacement
189
+ * patterns ($&, $1, $$, ...) would corrupt any value containing `$`. Build the result
190
+ * with slice/concat or a function replacer instead.
191
+ */
192
+ /**
193
+ * Escape a string for safe use as a single-quoted shell argument.
194
+ *
195
+ * Wraps the value in single quotes and neutralises embedded single quotes via the
196
+ * quote-break-escape-requote pattern (`'\''`).
197
+ */
198
+ function escapeShellArg(value) {
199
+ return `'${value.replace(/'/g, "'\\''")}'`;
200
+ }
201
+ //#endregion
202
+ //#region src/services/workflowCommandTemplate/index.ts
203
+ const commandTemplates = new liquidjs.Liquid({
204
+ strictVariables: true,
205
+ strictFilters: true,
206
+ lenientIf: true
207
+ });
208
+ commandTemplates.registerFilter("shell", (value) => escapeShellArg(Array.isArray(value) ? value.join(",") : String(value ?? "")));
209
+ /** Render a Liquid workflow command template with the same strict shell semantics as the workflow engine. */
210
+ function renderWorkflowCommandTemplate(template, values) {
211
+ return commandTemplates.parseAndRenderSync(template, values).trim();
212
+ }
213
+ /** Return top-level variables referenced by a workflow command template. */
214
+ function workflowCommandTemplateVariables(template) {
215
+ return commandTemplates.globalVariablesSync(template);
216
+ }
217
+ //#endregion
218
+ //#region src/schemas/workflowEngine.ts
219
+ /**
220
+ * Zod Schemas for Workflow YAML Validation
221
+ *
222
+ * DESIGN PATTERNS:
223
+ * - Schema-first development: Zod schemas are the source of truth
224
+ * - Types inferred from schemas via z.infer<>
225
+ * - Runtime validation at YAML parse boundary
226
+ *
227
+ * CODING STANDARDS:
228
+ * - Export all schemas and inferred types from this file
229
+ * - Use descriptive names matching the workflow YAML structure
230
+ *
231
+ * AVOID:
232
+ * - Duplicating type definitions manually (use z.infer<>)
233
+ * - Validating deep inside services (validate at parse boundary)
234
+ */
235
+ /** Keep JSON-schema transport while sharing neutral reference and role validation with core. */
236
+ const WorkflowAssignmentsSchema = zod.z.record(zod.z.string(), zod.z.string()).refine((value) => (0, typebox_value.Check)(_agimon_ai_po_core_workflow.PoWorkflowAssignmentsSchema, value), "Malformed explicit workflow assignments.").describe("Exact role-to-stable-profile-reference assignments for this launch. No team or default fills omissions.");
237
+ const MAX_PORT = 65535;
238
+ const CoercedEnvRecord = zod.z.record(zod.z.string(), zod.z.coerce.string());
239
+ const WorkflowInputSchema = zod.z.object({
240
+ description: zod.z.string().optional(),
241
+ required: zod.z.boolean().optional(),
242
+ default: zod.z.string().optional(),
243
+ type: zod.z.string().optional(),
244
+ options: zod.z.array(zod.z.string()).optional()
245
+ });
246
+ const MatrixEntrySchema = zod.z.record(zod.z.string(), zod.z.string());
247
+ const StepCommandMapSchema = zod.z.record(zod.z.string(), zod.z.string());
248
+ const StepCommandSchema = zod.z.union([zod.z.string(), StepCommandMapSchema]);
249
+ const WorkflowRelativePathSchema = zod.z.string().min(1).describe("Path relative to WORKFLOW_RUN_DIR using forward slashes.").refine((value) => !value.startsWith("/") && !value.includes("\\") && !value.split("/").some((segment) => segment === "" || segment === "." || segment === ".."), "Workflow artifact paths must be safe relative paths without empty, dot, or parent segments.");
250
+ const StepArtifactsSchema = zod.z.array(WorkflowRelativePathSchema).min(1).refine((paths) => new Set(paths).size === paths.length, "Step artifact paths must be unique.").describe("Declared run-directory files that an interactive step must update before stopping.");
251
+ /**
252
+ * Execution settings a step shares between its runners.
253
+ *
254
+ * Deliberately generic: the engine never reads a key, it only interpolates
255
+ * them (`${{ runConfig.<key> }}`, lists joined with commas) and hands the map to
256
+ * a host executor, which owns and validates the keys it understands.
257
+ */
258
+ const RunConfigSchema = zod.z.record(zod.z.string(), zod.z.union([
259
+ zod.z.string(),
260
+ zod.z.array(zod.z.string()),
261
+ zod.z.null()
262
+ ])).describe("Host execution settings shared by customRun and command runners.");
263
+ /** What only an in-process host executor needs, beside the shared `runConfig`. */
264
+ const CustomRunEntrySchema = zod.z.object({
265
+ prompt: zod.z.string().min(1).describe("Prompt the host executor runs. Interpolated like a command."),
266
+ systemPrompt: zod.z.string().min(1).optional().describe("Text the host appends to the agent system prompt. Interpolated like the prompt."),
267
+ runConfig: RunConfigSchema.optional().describe("Settings laid over the step's shared runConfig.")
268
+ }).describe("Step executed in-process by a host executor instead of a shell.");
269
+ /**
270
+ * One in-process run for any runner, or one per runner keyed like an
271
+ * interactiveRun map, each with its own prompt and settings.
272
+ */
273
+ const CustomRunSchema = zod.z.union([CustomRunEntrySchema, zod.z.record(zod.z.string(), CustomRunEntrySchema)]);
274
+ /**
275
+ * A named custom runner. Selecting it by name, the way a command map's key is
276
+ * selected, runs every customRun step with this `runConfig` over its own.
277
+ */
278
+ const RunnerSchema = zod.z.object({ runConfig: RunConfigSchema.optional().describe("Settings laid over each customRun step runConfig.") }).describe("Named custom runner a launch can select.");
279
+ /**
280
+ * A command a step can run through, as a Liquid template rendered into its
281
+ * shell command. `inProcess` tells a host that runs agent sessions itself that
282
+ * it may run the step in-process from the structured values instead; such a
283
+ * command may leave out `run`, and then no other host can run it.
284
+ */
285
+ const CommandTemplateSchema = zod.z.union([zod.z.string().min(1), zod.z.object({
286
+ run: zod.z.string().min(1).optional().describe("Liquid template rendered into the shell command. An inProcess command may leave it out."),
287
+ inProcess: zod.z.boolean().optional().describe("A host that runs agent sessions may run this command in-process instead of the shell.")
288
+ }).strict().refine((command) => command.run !== void 0 || command.inProcess === true, {
289
+ message: "A command without run must set inProcess: true.",
290
+ path: ["run"]
291
+ })]);
292
+ const ChoiceSettingsSchema = zod.z.object({
293
+ model: zod.z.string().min(1).optional(),
294
+ thinking: zod.z.string().min(1).optional(),
295
+ subagentModel: zod.z.string().min(1).optional(),
296
+ subagentThinking: zod.z.string().min(1).optional()
297
+ }).strict();
298
+ /**
299
+ * A named model composition: independent step and subagent settings, plus overrides
300
+ * keyed by command name for commands whose model ids differ.
301
+ */
302
+ const ChoiceSchema = zod.z.record(zod.z.string(), zod.z.union([zod.z.string().min(1), ChoiceSettingsSchema])).superRefine((choice, context) => {
303
+ for (const [key, value] of Object.entries(choice)) {
304
+ const setting = Object.hasOwn(ChoiceSettingsSchema.shape, key);
305
+ if (setting !== (typeof value === "string")) context.addIssue({
306
+ code: "custom",
307
+ message: setting ? `Choice ${key} must be a string.` : `Choice override "${key}" must be an object of choice settings for that command.`,
308
+ path: [key]
309
+ });
310
+ }
311
+ });
312
+ /** One command a step offers, with what it overrides for that command. */
313
+ const CommandRefSchema = zod.z.object({
314
+ command: zod.z.string().min(1).describe("Name of a command declared under the workflow commands."),
315
+ choice: zod.z.string().min(1).optional().describe("Choice this command always runs with."),
316
+ runConfig: RunConfigSchema.optional().describe("Settings laid over the step's runConfig for this command."),
317
+ prompt: zod.z.string().min(1).optional(),
318
+ systemPrompt: zod.z.string().min(1).optional()
319
+ }).strict();
320
+ /** Commands a step offers (the template form), or a legacy command string or runner map. */
321
+ const InteractiveRunSchema = zod.z.union([zod.z.array(CommandRefSchema).min(1), StepCommandSchema]);
322
+ const StrategySchema = zod.z.object({
323
+ "fail-fast": zod.z.boolean().optional(),
324
+ matrix: zod.z.looseObject({ include: zod.z.array(MatrixEntrySchema).optional() }).optional()
325
+ });
326
+ const StepFieldsSchema = zod.z.object({
327
+ name: zod.z.string().optional(),
328
+ uses: zod.z.string().optional(),
329
+ run: StepCommandSchema.optional(),
330
+ interactiveRun: InteractiveRunSchema.optional(),
331
+ customRun: CustomRunSchema.optional(),
332
+ runConfig: RunConfigSchema.optional(),
333
+ prompt: zod.z.string().min(1).optional().describe("Prompt of a templated interactiveRun, interpolated with ${{ }}."),
334
+ systemPrompt: zod.z.string().min(1).optional().describe("System prompt of a templated interactiveRun, interpolated with ${{ }}."),
335
+ choice: zod.z.string().min(1).optional().describe("Choice this step runs with, whatever the launch selects."),
336
+ "restart-from": zod.z.string().min(1).optional().describe("Job a failing run step asks the workflow to restart from, instead of failing the job."),
337
+ artifacts: StepArtifactsSchema.optional(),
338
+ "timeout-minutes": zod.z.number().optional(),
339
+ env: CoercedEnvRecord.optional(),
340
+ secrets: zod.z.array(zod.z.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/, "Secret names are environment variable names.")).min(1).optional().describe("Env names a run step's command receives from its Po profile; values never reach logs or run records."),
341
+ with: zod.z.record(zod.z.string(), zod.z.string()).optional(),
342
+ "working-directory": zod.z.string().optional(),
343
+ if: zod.z.string().optional(),
344
+ "continue-on-error": zod.z.boolean().optional(),
345
+ "timeout-retries": zod.z.number().optional(),
346
+ "pause-policy": zod.z.enum(["replay", "protected"]).optional(),
347
+ id: zod.z.string().optional()
348
+ });
349
+ const GROUP_STEP_KEYS = /* @__PURE__ */ new Set([
350
+ "name",
351
+ "id",
352
+ "parallel"
353
+ ]);
354
+ function refineStep(step, context) {
355
+ if (step.artifacts && !step.interactiveRun && !step.customRun) context.addIssue({
356
+ code: "custom",
357
+ message: "Step artifacts are only supported for interactiveRun and customRun steps.",
358
+ path: ["artifacts"]
359
+ });
360
+ if (Array.isArray(step.interactiveRun)) {
361
+ if (step.run !== void 0 || step.customRun !== void 0) context.addIssue({
362
+ code: "custom",
363
+ message: "A templated interactiveRun cannot be combined with run or customRun.",
364
+ path: ["interactiveRun"]
365
+ });
366
+ const commands = step.interactiveRun;
367
+ if (step.prompt === void 0 && commands.some((entry) => entry.prompt === void 0)) context.addIssue({
368
+ code: "custom",
369
+ message: "A templated interactiveRun needs a prompt on the step or on every command.",
370
+ path: ["prompt"]
371
+ });
372
+ } else for (const key of [
373
+ "prompt",
374
+ "systemPrompt",
375
+ "choice"
376
+ ]) if (step[key] !== void 0) context.addIssue({
377
+ code: "custom",
378
+ message: `${key} is only supported with a templated interactiveRun.`,
379
+ path: [key]
380
+ });
381
+ if (step.secrets !== void 0 && (step.run === void 0 || step.interactiveRun || step.customRun)) context.addIssue({
382
+ code: "custom",
383
+ message: "secrets are only supported on run steps.",
384
+ path: ["secrets"]
385
+ });
386
+ if (step["restart-from"] !== void 0 && (step.run === void 0 || step.interactiveRun || step.customRun)) context.addIssue({
387
+ code: "custom",
388
+ message: "restart-from is only supported on run steps.",
389
+ path: ["restart-from"]
390
+ });
391
+ if (step.parallel !== void 0) {
392
+ for (const [key, value] of Object.entries(step)) if (value !== void 0 && !GROUP_STEP_KEYS.has(key)) context.addIssue({
393
+ code: "custom",
394
+ message: `A parallel group only takes name and id; move ${key} onto its steps.`,
395
+ path: [key]
396
+ });
397
+ }
398
+ }
399
+ const ParallelStepSchema = StepFieldsSchema.extend({ parallel: zod.z.undefined({ error: "Parallel groups cannot be nested." }).optional() }).superRefine(refineStep);
400
+ const StepSchema = StepFieldsSchema.extend({ parallel: zod.z.array(ParallelStepSchema).min(2).optional().describe("Steps run at the same time; their fix requests merge into one repair.") }).superRefine(refineStep);
401
+ /** Persisted detached service identities, checked before replay can signal their groups. */
402
+ const ServiceProcessesSchema = zod.z.array(zod.z.object({
403
+ name: zod.z.string(),
404
+ pid: zod.z.number().int().positive(),
405
+ pgid: zod.z.number().int().positive(),
406
+ startedAt: zod.z.string(),
407
+ command: zod.z.string()
408
+ }));
409
+ const ServiceDefSchema = zod.z.object({
410
+ name: zod.z.string(),
411
+ run: zod.z.string(),
412
+ env: CoercedEnvRecord.optional(),
413
+ "working-directory": zod.z.string().optional(),
414
+ "ready-check": zod.z.union([zod.z.string(), zod.z.boolean()]).optional(),
415
+ "ready-timeout": zod.z.number().optional(),
416
+ host: zod.z.string().optional(),
417
+ port: zod.z.number().int().min(1).max(MAX_PORT).optional(),
418
+ "port-range": zod.z.object({
419
+ min: zod.z.number().int().min(1).max(MAX_PORT),
420
+ max: zod.z.number().int().min(1).max(MAX_PORT)
421
+ }).optional(),
422
+ "service-type": zod.z.enum(["tool", "service"]).optional()
423
+ });
424
+ const PreBlockSchema = zod.z.object({
425
+ services: zod.z.array(ServiceDefSchema).optional(),
426
+ steps: zod.z.array(StepSchema).optional()
427
+ });
428
+ const JobHookBlockSchema = zod.z.object({ steps: zod.z.array(StepSchema).optional() });
429
+ const localPathSchema = (label) => zod.z.string().min(1).refine((value) => value.trim().length > 0 && !/^[a-z][a-z0-9+.-]*:/iu.test(value.trimStart()) && value.split("").every((character) => character.charCodeAt(0) >= 32 && character.charCodeAt(0) !== 127), `${label} must be a local filesystem path without URL schemes or control characters.`);
430
+ const WorkflowToolsPathSchema = localPathSchema("Workflow tools").describe("Tools folder relative to its declaring YAML file, containing index.mjs and SKILL.md.");
431
+ const WorkflowInstructionsPathSchema = localPathSchema("Workflow instructions").describe("Instructions file relative to its declaring YAML file. Step sessions read it instead of the AGENTS.md files they would discover.");
432
+ const ChildJobInputValueSchema = zod.z.union([
433
+ zod.z.string().max(4096),
434
+ zod.z.number().finite(),
435
+ zod.z.boolean()
436
+ ]);
437
+ const ChildJobInputSchema = zod.z.object({
438
+ description: zod.z.string().optional(),
439
+ type: zod.z.enum([
440
+ "string",
441
+ "number",
442
+ "boolean"
443
+ ]).default("string"),
444
+ required: zod.z.boolean().optional(),
445
+ default: ChildJobInputValueSchema.optional(),
446
+ options: zod.z.array(ChildJobInputValueSchema).min(1).optional()
447
+ }).strict().superRefine((input, context) => {
448
+ for (const [key, values] of [["default", input.default === void 0 ? [] : [input.default]], ["options", input.options ?? []]]) for (const value of values) if (typeof value !== input.type) context.addIssue({
449
+ code: "custom",
450
+ message: `Input ${key} must match type ${input.type}.`,
451
+ path: [key]
452
+ });
453
+ if (input.default !== void 0 && input.options && !input.options.includes(input.default)) context.addIssue({
454
+ code: "custom",
455
+ message: "Input default must be one of its options.",
456
+ path: ["default"]
457
+ });
458
+ });
459
+ const AcceptanceCriterionSchema = zod.z.object({
460
+ description: zod.z.string().trim().min(1).max(512),
461
+ "verified-by": zod.z.string().trim().min(1).max(128),
462
+ artifacts: StepArtifactsSchema.optional()
463
+ }).strict();
464
+ const JobCompletionSchema = zod.z.object({ "max-continuations": zod.z.number().int().nonnegative().default(3) }).strict();
465
+ const JobIdentitySchema = zod.z.object({ roles: zod.z.array(zod.z.string().trim().min(1)).min(1).refine((roles) => new Set(roles).size === roles.length, "Identity roles must be unique.").describe("Roles one member of the run team must hold; every step of the job runs as that member.") }).strict();
466
+ const JobSchema = zod.z.object({
467
+ identity: JobIdentitySchema.optional(),
468
+ tools: WorkflowToolsPathSchema.optional(),
469
+ instructions: WorkflowInstructionsPathSchema.optional(),
470
+ runConfig: RunConfigSchema.optional(),
471
+ inputs: zod.z.record(zod.z.string().min(1), ChildJobInputSchema).optional(),
472
+ children: zod.z.array(zod.z.string().trim().min(1)).min(1).refine((names) => new Set(names).size === names.length, "Child job names must be unique.").optional(),
473
+ "acceptance-criteria": zod.z.record(zod.z.string().min(1).max(128), AcceptanceCriterionSchema).refine((criteria) => Object.keys(criteria).length <= 32, "A job may declare at most 32 acceptance criteria.").refine((criteria) => new TextEncoder().encode(JSON.stringify(criteria)).byteLength <= 24576, "Acceptance criteria definitions must fit within 24 KiB, leaving room for status and feedback.").optional(),
474
+ completion: JobCompletionSchema.optional(),
475
+ "max-failures": zod.z.number().int().positive().optional().describe("Child jobs only: failed invocations in a row (default 3) that fail the lead which spawned them."),
476
+ session: zod.z.enum(["fresh"]).optional().describe("fresh starts every run of this job's agent steps in a new session; by default a step that runs again continues its earlier conversation."),
477
+ "runs-on": zod.z.string().optional(),
478
+ needs: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).optional(),
479
+ extends: zod.z.union([zod.z.string(), zod.z.array(zod.z.string())]).optional(),
480
+ description: zod.z.string().optional(),
481
+ strategy: StrategySchema.optional(),
482
+ steps: zod.z.array(StepSchema),
483
+ preJob: JobHookBlockSchema.optional(),
484
+ postJob: JobHookBlockSchema.optional(),
485
+ env: CoercedEnvRecord.optional(),
486
+ if: zod.z.string().optional(),
487
+ "system-prompt": zod.z.string().optional(),
488
+ context: zod.z.string().optional()
489
+ });
490
+ const RepairTriageSchema = JobSchema.omit({
491
+ extends: true,
492
+ needs: true
493
+ }).describe("Workflow-defined repair triage that runs before jobs in an active repair.");
494
+ const AgentDecisionTriggerSchema = zod.z.object({ steps: zod.z.array(StepSchema) });
495
+ const WorkflowKeybindingsSchema = zod.z.object({ STOP: zod.z.string().optional() });
496
+ const RUN_DIRECTORY_BUILT_IN_PATHS = /* @__PURE__ */ new Set([
497
+ "run.json",
498
+ "context.md",
499
+ "changelog.md",
500
+ "fix.md",
501
+ "issues",
502
+ "decisions",
503
+ "bin",
504
+ ".workflow"
505
+ ]);
506
+ const RunDirectoryEntrySchema = zod.z.object({
507
+ path: WorkflowRelativePathSchema,
508
+ kind: zod.z.enum(["file", "directory"]).describe("Filesystem entry kind."),
509
+ description: zod.z.string().min(1).describe("Agent-facing purpose of this entry."),
510
+ "produced-by": zod.z.array(zod.z.string().min(1)).optional().describe("Workflow jobs expected to create or update this entry."),
511
+ "initial-content": zod.z.string().optional().describe("Initial content used when creating a file.")
512
+ }).superRefine((entry, context) => {
513
+ if (entry.kind === "directory" && entry["initial-content"] !== void 0) context.addIssue({
514
+ code: "custom",
515
+ message: "initial-content is only valid for file entries.",
516
+ path: ["initial-content"]
517
+ });
518
+ });
519
+ const RunDirectorySchema = zod.z.object({
520
+ description: zod.z.string().min(1).describe("Agent-facing purpose of the workflow run directory."),
521
+ entries: zod.z.array(RunDirectoryEntrySchema).describe("Declared workflow-owned files and directories.")
522
+ }).superRefine((runDirectory, context) => {
523
+ const seen = /* @__PURE__ */ new Set();
524
+ for (const [index, entry] of runDirectory.entries.entries()) {
525
+ if (RUN_DIRECTORY_BUILT_IN_PATHS.has(entry.path)) context.addIssue({
526
+ code: "custom",
527
+ message: `Run-directory path is owned by workflow-mcp: ${entry.path}`,
528
+ path: [
529
+ "entries",
530
+ index,
531
+ "path"
532
+ ]
533
+ });
534
+ if (seen.has(entry.path)) context.addIssue({
535
+ code: "custom",
536
+ message: `Duplicate run-directory path: ${entry.path}`,
537
+ path: [
538
+ "entries",
539
+ index,
540
+ "path"
541
+ ]
542
+ });
543
+ seen.add(entry.path);
544
+ }
545
+ });
546
+ /** Structural validation before import and template references can be resolved. */
547
+ const WorkflowDefinitionSchema = zod.z.object({
548
+ name: zod.z.string().optional(),
549
+ tools: WorkflowToolsPathSchema.optional(),
550
+ instructions: WorkflowInstructionsPathSchema.optional(),
551
+ tags: zod.z.array(zod.z.string().trim().min(1)).optional().describe("Tags used to categorize and filter workflow definitions."),
552
+ workspace: zod.z.string().optional(),
553
+ team: zod.z.string().trim().min(1).optional().describe("Default team role-bound jobs resolve within; a launch may select another."),
554
+ runner: zod.z.string().optional().describe("Default runner key for step command maps when no CLI runner is provided."),
555
+ "default-runner": zod.z.string().optional().describe("Deprecated alias for runner."),
556
+ runners: zod.z.record(zod.z.string(), RunnerSchema).optional().describe("Named custom runners; selecting one lays its runConfig over every customRun step."),
557
+ commands: zod.z.record(zod.z.string(), CommandTemplateSchema).optional().describe("Command templates a templated interactiveRun selects with --command."),
558
+ choices: zod.z.record(zod.z.string(), ChoiceSchema).optional().describe("Model compositions a launch selects with --choice; \"default\" is used when none is named."),
559
+ runConfig: RunConfigSchema.optional().describe("Defaults laid under the runConfig of every interactiveRun and customRun step; a step key wins."),
560
+ sessionConfig: zod.z.object({
561
+ majorMode: zod.z.never({ error: "sessionConfig.majorMode was renamed to preset" }).optional(),
562
+ preset: zod.z.string().trim().min(1).optional().describe("Preset of the workflow session that owns the run; steps keep their runConfig.preset.")
563
+ }).strict().optional().describe("Settings for the workflow session a launch creates, not for its step sessions."),
564
+ imports: zod.z.array(zod.z.string()).optional(),
565
+ "system-prompt": zod.z.string().optional(),
566
+ "max-workflows": zod.z.number().int().positive().optional(),
567
+ "launch-command": zod.z.never({ error: "launch-command was removed: runs execute in the Po host. Delete this key." }).optional(),
568
+ launcher: zod.z.never({ error: "launcher was removed with launch-command. Delete this key." }).optional(),
569
+ keybindings: WorkflowKeybindingsSchema.optional(),
570
+ "run-directory": RunDirectorySchema.optional(),
571
+ on: zod.z.looseObject({
572
+ workflow_dispatch: zod.z.object({ inputs: zod.z.record(zod.z.string(), WorkflowInputSchema).optional() }).nullable().optional(),
573
+ agent_decision: AgentDecisionTriggerSchema.optional()
574
+ }).optional(),
575
+ env: CoercedEnvRecord.optional(),
576
+ pre: PreBlockSchema.optional(),
577
+ post: PreBlockSchema.optional(),
578
+ repair: RepairTriageSchema.optional(),
579
+ isolation: zod.z.enum(["checkout"]).optional().describe("Run in its own checkout. Reported to launchers only; the engine never creates one."),
580
+ jobs: zod.z.record(zod.z.string(), JobSchema),
581
+ "child-jobs": zod.z.record(zod.z.string().min(1), JobSchema).optional()
582
+ });
583
+ /** Where a `runConfig` under this value sets a profile, as schema issue paths. */
584
+ function profilePaths(value, path) {
585
+ if (Array.isArray(value)) return value.flatMap((item, index) => profilePaths(item, [...path, index]));
586
+ if (typeof value !== "object" || value === null) return [];
587
+ return Object.entries(value).flatMap(([key, child]) => key === "runConfig" && typeof child === "object" && child !== null && "profile" in child ? [[
588
+ ...path,
589
+ key,
590
+ "profile"
591
+ ]] : profilePaths(child, [...path, key]));
592
+ }
593
+ const WorkflowSchema = WorkflowDefinitionSchema.superRefine((workflow, context) => {
594
+ const declaredFiles = new Set((workflow["run-directory"]?.entries ?? []).filter((entry) => entry.kind === "file").map((entry) => entry.path));
595
+ const roleJobs = [...["jobs", "child-jobs"].flatMap((catalog) => Object.entries(workflow[catalog] ?? {}).map(([name, job]) => ({
596
+ job,
597
+ path: [catalog, name]
598
+ }))), ...workflow.repair ? [{
599
+ job: workflow.repair,
600
+ path: ["repair"]
601
+ }] : []].filter(({ job }) => job.identity !== void 0);
602
+ for (const { job, path } of roleJobs) {
603
+ const scope = {
604
+ runConfig: job.runConfig,
605
+ preJob: job.preJob,
606
+ steps: job.steps,
607
+ postJob: job.postJob
608
+ };
609
+ for (const issuePath of profilePaths(scope, path)) context.addIssue({
610
+ code: "custom",
611
+ message: "A job that declares identity.roles runs as its resolved member; remove this profile.",
612
+ path: issuePath
613
+ });
614
+ }
615
+ if (roleJobs.length > 0) {
616
+ const shared = {
617
+ runConfig: workflow.runConfig,
618
+ runners: workflow.runners,
619
+ commands: workflow.commands
620
+ };
621
+ for (const issuePath of profilePaths(shared, [])) context.addIssue({
622
+ code: "custom",
623
+ message: "A profile cannot apply across a workflow whose jobs declare identity.roles.",
624
+ path: issuePath
625
+ });
626
+ }
627
+ for (const catalog of ["jobs", "child-jobs"]) for (const [jobName, job] of Object.entries(workflow[catalog] ?? {})) for (const [stepIndex, step] of job.steps.entries()) {
628
+ const members = step.parallel ? step.parallel.map((child, childIndex) => ({
629
+ step: child,
630
+ path: [
631
+ stepIndex,
632
+ "parallel",
633
+ childIndex
634
+ ]
635
+ })) : [{
636
+ step,
637
+ path: [stepIndex]
638
+ }];
639
+ for (const member of members) for (const [artifactIndex, artifact] of (member.step.artifacts ?? []).entries()) if (!declaredFiles.has(artifact)) context.addIssue({
640
+ code: "custom",
641
+ message: `Step artifact must reference a declared run-directory file: ${artifact}`,
642
+ path: [
643
+ catalog,
644
+ jobName,
645
+ "steps",
646
+ ...member.path,
647
+ "artifacts",
648
+ artifactIndex
649
+ ]
650
+ });
651
+ }
652
+ for (const [entryIndex, entry] of (workflow["run-directory"]?.entries ?? []).entries()) for (const [producerIndex, producer] of (entry["produced-by"] ?? []).entries()) if (!workflow.jobs[producer] && !workflow["child-jobs"]?.[producer] || producer.startsWith(".")) context.addIssue({
653
+ code: "custom",
654
+ message: `Unknown producing job: ${producer}`,
655
+ path: [
656
+ "run-directory",
657
+ "entries",
658
+ entryIndex,
659
+ "produced-by",
660
+ producerIndex
661
+ ]
662
+ });
663
+ });
664
+ const WorkflowStageSchema = zod.z.enum([
665
+ "running",
666
+ "completed",
667
+ "error"
668
+ ]);
669
+ /** Run-directory control files a person may rewrite or remove through a repair; run.json is replaced only as a validated record. */
670
+ const WorkflowRepairableFileSchema = zod.z.enum([
671
+ "fix.md",
672
+ "proceed.md",
673
+ "stop-request.json",
674
+ "pause-request.json",
675
+ "finalizing.json",
676
+ "recovery-claim.json",
677
+ "recovery-adoption.json"
678
+ ]);
679
+ const WorkflowOutcomeSchema = zod.z.enum([
680
+ "success",
681
+ "skipped",
682
+ "failed",
683
+ "interrupted"
684
+ ]);
685
+ /**
686
+ * One line of the run progress log.
687
+ *
688
+ * Append-only NDJSON in the run directory, because a run is a detached process
689
+ * and anything held in its memory is invisible to every other process and lost
690
+ * on crash. A reader can tail this to know which job and step a run is on,
691
+ * which the run record cannot express: it carries only a stage.
692
+ */
693
+ const WorkflowExecutionStateSchema = zod.z.enum([
694
+ "running",
695
+ "pause_requested",
696
+ "paused",
697
+ "resume_requested"
698
+ ]).describe("Live execution state within a running workflow.");
699
+ const WorkflowResumeModeSchema = zod.z.enum(["replay-current", "continue-next"]).describe("How a paused workflow resumes at its execution cursor.");
700
+ const WorkflowExecutionCursorSchema = zod.z.object({
701
+ attempt: zod.z.number().int().positive().optional(),
702
+ executionGeneration: zod.z.number().int().positive(),
703
+ revision: zod.z.number().int().nonnegative().optional(),
704
+ job: zod.z.string().optional(),
705
+ matrixIndex: zod.z.number().int().nonnegative().optional(),
706
+ phase: zod.z.string(),
707
+ requestId: zod.z.string().uuid().optional(),
708
+ resumeMode: WorkflowResumeModeSchema,
709
+ stepIndex: zod.z.number().int().nonnegative().optional(),
710
+ stepName: zod.z.string().optional()
711
+ });
712
+ /** A host-owned handle a reader can follow, such as an agent session or a terminal pane. */
713
+ const StepExecutionRefSchema = zod.z.object({
714
+ kind: zod.z.string().min(1).describe("Host-defined handle kind, such as session or pane."),
715
+ id: zod.z.string().min(1),
716
+ label: zod.z.string().optional()
717
+ });
718
+ const WorkflowProgressEventSchema = zod.z.object({
719
+ at: zod.z.string().describe("ISO timestamp the event was recorded."),
720
+ index: zod.z.number().int().nonnegative().optional().describe("Zero-based position within its parent sequence."),
721
+ job: zod.z.string().describe("Job the event belongs to."),
722
+ /** Present on failures and skips, so a reader can show why without opening the log. */
723
+ reason: zod.z.string().optional(),
724
+ status: zod.z.enum([
725
+ "running",
726
+ "completed",
727
+ "failed",
728
+ "pause_requested",
729
+ "paused",
730
+ "resumed",
731
+ "skipped"
732
+ ]).describe("State the subject moved into."),
733
+ step: zod.z.string().optional().describe("Step name, absent for job-level events."),
734
+ group: zod.z.string().optional().describe("Parallel group a step runs in, beside the other steps of that group."),
735
+ ref: StepExecutionRefSchema.optional().describe("Where a host executor runs the step, once it started."),
736
+ total: zod.z.number().int().nonnegative().optional().describe("Length of the parent sequence, when known."),
737
+ type: zod.z.enum(["job", "step"])
738
+ });
739
+ const WorkflowRepairStatusSchema = zod.z.enum([
740
+ "pending",
741
+ "active",
742
+ "resolved",
743
+ "superseded",
744
+ "rejected"
745
+ ]);
746
+ const WorkflowRepairJobStatusSchema = zod.z.enum([
747
+ "pending",
748
+ "running",
749
+ "completed",
750
+ "failed",
751
+ "interrupted",
752
+ "skipped"
753
+ ]);
754
+ const WorkflowRepairJobAttemptSchema = zod.z.object({
755
+ attempt: zod.z.number().int().positive(),
756
+ finishedAt: zod.z.string().optional(),
757
+ startedAt: zod.z.string(),
758
+ status: zod.z.enum([
759
+ "running",
760
+ "completed",
761
+ "failed",
762
+ "interrupted"
763
+ ]),
764
+ workflowRunId: zod.z.string().optional()
765
+ });
766
+ const WorkflowRepairJobSchema = zod.z.object({
767
+ attempts: zod.z.array(WorkflowRepairJobAttemptSchema),
768
+ jobName: zod.z.string(),
769
+ status: WorkflowRepairJobStatusSchema
770
+ });
771
+ const WorkflowRepairRoutingFallbackSchema = zod.z.object({
772
+ reason: zod.z.enum(["missing", "unknown"]),
773
+ requestedTarget: zod.z.string().optional(),
774
+ resolvedTarget: zod.z.string()
775
+ });
776
+ const WorkflowRepairRecordSchema = zod.z.object({
777
+ createdAt: zod.z.string(),
778
+ fixCycle: zod.z.number().int().positive(),
779
+ issueFile: zod.z.string(),
780
+ jobs: zod.z.array(WorkflowRepairJobSchema),
781
+ rejectedAt: zod.z.string().optional(),
782
+ repairId: zod.z.string().regex(/^\d+$/),
783
+ resolvedAt: zod.z.string().optional(),
784
+ restartFrom: zod.z.string(),
785
+ routingFallback: WorkflowRepairRoutingFallbackSchema.optional(),
786
+ schemaVersion: zod.z.literal(1),
787
+ scopeJobs: zod.z.array(zod.z.string()),
788
+ status: WorkflowRepairStatusSchema,
789
+ supersededAt: zod.z.string().optional(),
790
+ supersededBy: zod.z.string().optional(),
791
+ updatedAt: zod.z.string(),
792
+ verificationJob: zod.z.string()
793
+ });
794
+ const CmuxWorkflowLauncherMetadataSchema = zod.z.object({
795
+ originSurfaceId: zod.z.string().optional(),
796
+ originWorkspaceId: zod.z.string().optional(),
797
+ surfaceId: zod.z.string().optional(),
798
+ type: zod.z.literal("cmux"),
799
+ workspaceId: zod.z.string()
800
+ });
801
+ const TmuxWorkflowLauncherMetadataSchema = zod.z.object({
802
+ originPaneId: zod.z.string().optional(),
803
+ originSessionId: zod.z.string().optional(),
804
+ originSurfaceId: zod.z.string().optional(),
805
+ originWorkspaceId: zod.z.string().optional(),
806
+ paneId: zod.z.string().optional(),
807
+ sessionId: zod.z.string().optional(),
808
+ sessionName: zod.z.string(),
809
+ type: zod.z.literal("tmux"),
810
+ windowId: zod.z.string().optional()
811
+ });
812
+ /**
813
+ * Compatibility metadata for the RMUX-backed launcher. The `native` literal is
814
+ * retained for existing run records and cockpit clients; the detached host pid
815
+ * and terminal socket remain the public identity.
816
+ */
817
+ const NativeWorkflowLauncherMetadataSchema = zod.z.object({
818
+ pid: zod.z.number().int().positive().optional(),
819
+ type: zod.z.literal("native")
820
+ });
821
+ const WorkflowLauncherMetadataSchema = zod.z.discriminatedUnion("type", [
822
+ CmuxWorkflowLauncherMetadataSchema,
823
+ TmuxWorkflowLauncherMetadataSchema,
824
+ NativeWorkflowLauncherMetadataSchema
825
+ ]);
826
+ const WorkflowAllocationSchema = zod.z.unknown().transform((value, context) => {
827
+ try {
828
+ return (0, _agimon_ai_po_core_workflow.parsePoWorkflowAllocation)(value);
829
+ } catch {
830
+ context.addIssue({
831
+ code: "custom",
832
+ message: "Invalid explicit workflow allocation snapshot."
833
+ });
834
+ return zod.z.NEVER;
835
+ }
836
+ });
837
+ /** Only trusted in-process launchers set this metadata, never workflow environment. */
838
+ const WorkflowAdmissionMetadataSchema = zod.z.object({
839
+ allocation: WorkflowAllocationSchema.optional(),
840
+ attemptId: zod.z.string().min(1),
841
+ admissionId: zod.z.string().uuid(),
842
+ ownerSessionId: zod.z.string().min(1),
843
+ launcherSessionId: zod.z.string().min(1),
844
+ reason: zod.z.enum([
845
+ "launch",
846
+ "recover",
847
+ "startup",
848
+ "resume"
849
+ ]),
850
+ previousRun: zod.z.object({
851
+ runId: zod.z.string(),
852
+ ownerSessionId: zod.z.string(),
853
+ runKey: zod.z.string(),
854
+ registryWorkspace: zod.z.string()
855
+ }).optional(),
856
+ environment: zod.z.record(zod.z.string(), zod.z.string()).optional(),
857
+ ready: zod.z.boolean().optional(),
858
+ binding: zod.z.object({
859
+ association: zod.z.object({
860
+ coordinator: zod.z.string().min(1),
861
+ key: zod.z.string().min(1)
862
+ }),
863
+ epoch: zod.z.object({
864
+ admissionId: zod.z.string().uuid(),
865
+ operationId: zod.z.string().uuid()
866
+ })
867
+ }).optional(),
868
+ /**
869
+ * What the bound coordinator is owed for this terminal generation. Undelivered settlements are
870
+ * retried until the coordinator acknowledges them, so a held lock is never orphaned.
871
+ */
872
+ settlement: zod.z.object({
873
+ outcome: zod.z.enum([
874
+ "success",
875
+ "skipped",
876
+ "failed",
877
+ "interrupted",
878
+ "abandoned"
879
+ ]),
880
+ delivered: zod.z.boolean(),
881
+ at: zod.z.string()
882
+ }).optional()
883
+ });
884
+ const WorkflowAdmissionIntentSchema = zod.z.object({
885
+ metadata: WorkflowAdmissionMetadataSchema,
886
+ requestHash: zod.z.string(),
887
+ rejected: zod.z.array(zod.z.string()).optional()
888
+ });
889
+ /** The member one role-bound job execution was admitted as; names and digests only, never secrets. */
890
+ const JobIdentityBindingSchema = zod.z.object({
891
+ team: zod.z.string().min(1),
892
+ teamRevision: zod.z.string().min(1),
893
+ product: zod.z.string().min(1).optional(),
894
+ roles: zod.z.array(zod.z.string().min(1)).min(1),
895
+ ref: zod.z.string().min(1),
896
+ profile: zod.z.string().min(1),
897
+ contentDigest: zod.z.string().min(1),
898
+ policyDigest: zod.z.string().min(1)
899
+ });
900
+ /** A run directory entry an agent step is held to, as it stood when the step began. */
901
+ const StepArtifactSnapshotSchema = zod.z.object({
902
+ fingerprint: zod.z.string().optional(),
903
+ path: zod.z.string(),
904
+ kind: zod.z.enum(["file", "directory"]).optional(),
905
+ description: zod.z.string().optional(),
906
+ job: zod.z.string().optional(),
907
+ mtimeMs: zod.z.number().optional()
908
+ });
909
+ /**
910
+ * One agent step parked on the person's approval. `slot` names the step within its job attempt
911
+ * (`<sequence>/<index>` plus `/<member>` inside a parallel group); `attemptId` is its parked store attempt.
912
+ */
913
+ const WorkflowStepWaitSchema = zod.z.object({
914
+ slot: zod.z.string().min(1),
915
+ stepName: zod.z.string(),
916
+ sessionId: zod.z.string().min(1),
917
+ approvalIds: zod.z.array(zod.z.string()),
918
+ timeoutAttempt: zod.z.number().int().nonnegative(),
919
+ attemptId: zod.z.string().optional(),
920
+ artifactSnapshot: zod.z.array(StepArtifactSnapshotSchema).optional()
921
+ });
922
+ /**
923
+ * Where a parked run waits: the job attempt whose step verdicts (`steps.ndjson`, keyed by `epoch`) replay on
924
+ * resume, and the steps that resume in their own sessions. `blocked` says why the last resume was refused.
925
+ */
926
+ const WorkflowRunWaitSchema = zod.z.object({
927
+ epoch: zod.z.string().min(1),
928
+ parkedRunId: zod.z.string(),
929
+ revision: zod.z.string().optional(),
930
+ blocked: zod.z.string().optional(),
931
+ job: zod.z.string().min(1),
932
+ jobAttempt: zod.z.number().int().positive(),
933
+ matrixIndex: zod.z.number().int().nonnegative(),
934
+ entries: zod.z.array(WorkflowStepWaitSchema).min(1)
935
+ });
936
+ const WorkflowRunRecordSchema = zod.z.object({
937
+ activeRepairId: zod.z.string().regex(/^\d+$/).optional(),
938
+ admission: WorkflowAdmissionMetadataSchema.optional(),
939
+ allocation: WorkflowAllocationSchema.optional(),
940
+ archivedProgress: zod.z.array(WorkflowProgressEventSchema).optional(),
941
+ configuration: zod.z.object({
942
+ revision: zod.z.string(),
943
+ workflow: zod.z.record(zod.z.string(), zod.z.unknown())
944
+ }).optional(),
945
+ /** Read-only legacy metadata. New runs only write runner. */
946
+ cliAgent: zod.z.string().optional(),
947
+ continueOnError: zod.z.boolean().optional(),
948
+ displayName: zod.z.string(),
949
+ dryRun: zod.z.boolean(),
950
+ env: zod.z.record(zod.z.string(), zod.z.string()).optional(),
951
+ executionCursor: WorkflowExecutionCursorSchema.optional(),
952
+ executionState: WorkflowExecutionStateSchema.optional(),
953
+ errorMessage: zod.z.string().optional(),
954
+ exitCode: zod.z.number().optional(),
955
+ failedJob: zod.z.string().optional(),
956
+ finishedAt: zod.z.string().optional(),
957
+ fixLoopCycle: zod.z.number().int().positive().optional(),
958
+ inputs: zod.z.record(zod.z.string(), zod.z.string()).optional(),
959
+ job: zod.z.string().optional(),
960
+ launcher: WorkflowLauncherMetadataSchema.optional(),
961
+ outcome: WorkflowOutcomeSchema.optional(),
962
+ hostOwner: zod.z.object({
963
+ token: zod.z.string().min(1),
964
+ generation: zod.z.number().int().positive()
965
+ }).optional(),
966
+ pid: zod.z.number().int().positive().optional(),
967
+ prompt: zod.z.string().optional(),
968
+ /** Forward jumps a repair took through proceed.md, in order; rendered into the read-only context export. */
969
+ proceeds: zod.z.array(zod.z.object({
970
+ repairId: zod.z.string(),
971
+ from: zod.z.string(),
972
+ to: zod.z.string(),
973
+ skipped: zod.z.array(zod.z.string())
974
+ })).optional(),
975
+ runner: zod.z.string().optional(),
976
+ command: zod.z.string().optional().describe("Command the launch selected for templated interactiveRun steps."),
977
+ choice: zod.z.string().optional().describe("Choice the launch selected for steps that do not pin one."),
978
+ profile: zod.z.string().optional().describe("Po profile name the launch selected as the default runConfig.profile; never its secrets."),
979
+ team: zod.z.string().min(1).optional().describe("Team pinned at launch; role-bound jobs resolve only within it."),
980
+ identities: zod.z.record(zod.z.string(), JobIdentityBindingSchema).optional().describe("Admitted member of each role-bound job execution, keyed job#matrixIndex."),
981
+ runId: zod.z.string().uuid().optional(),
982
+ resume: zod.z.object({
983
+ reason: zod.z.enum(["released", "host_shutdown"]),
984
+ at: zod.z.string()
985
+ }).optional(),
986
+ /** Written only by the registry when a recovery claim promotes the prior generation; never caller input. */
987
+ recoveredFrom: zod.z.object({
988
+ runId: zod.z.string(),
989
+ ownerSessionId: zod.z.string(),
990
+ runKey: zod.z.string(),
991
+ registryWorkspace: zod.z.string()
992
+ }).optional(),
993
+ /**
994
+ * Recoveries an agent or the person chose for this run key, carried across its generations. A restart or an
995
+ * approval wake resumes the same attempt and is not counted.
996
+ */
997
+ recoveries: zod.z.number().int().positive().optional(),
998
+ /** Set on an interrupted run parked on the person's approval; its decision resumes the waiting steps. */
999
+ wait: WorkflowRunWaitSchema.optional(),
1000
+ runKey: zod.z.string(),
1001
+ secretFile: zod.z.string().optional(),
1002
+ stale: zod.z.boolean().optional(),
1003
+ staleReason: zod.z.string().optional(),
1004
+ stage: WorkflowStageSchema,
1005
+ startedAt: zod.z.string(),
1006
+ /**
1007
+ * Read-only legacy metadata: the Unix socket a run hosted by the retired CLI answered screen, key and resize
1008
+ * requests on. New runs never write it.
1009
+ */
1010
+ terminalSocket: zod.z.string().optional(),
1011
+ failureReason: zod.z.string().optional(),
1012
+ /** Read-only legacy metadata from engine-owned worktrees, kept for display. Recovery refuses such runs. */
1013
+ worktreeBranch: zod.z.string().optional(),
1014
+ worktreePath: zod.z.string().optional(),
1015
+ workflowPath: zod.z.string(),
1016
+ workflowId: zod.z.string().optional(),
1017
+ workflowName: zod.z.string().optional(),
1018
+ runDirectory: RunDirectorySchema.optional(),
1019
+ workspace: zod.z.string(),
1020
+ effectiveStage: WorkflowStageSchema.optional(),
1021
+ effectiveOutcome: WorkflowOutcomeSchema.optional()
1022
+ });
1023
+ zod.z.discriminatedUnion("decision", [
1024
+ zod.z.object({
1025
+ decision: zod.z.literal("complete"),
1026
+ summary: zod.z.string().optional()
1027
+ }),
1028
+ zod.z.object({
1029
+ decision: zod.z.literal("fix"),
1030
+ restartFrom: zod.z.string().min(1),
1031
+ reason: zod.z.string().min(1)
1032
+ }),
1033
+ zod.z.object({
1034
+ decision: zod.z.literal("fail"),
1035
+ reason: zod.z.string().min(1)
1036
+ })
1037
+ ]);
1038
+ zod.z.object({
1039
+ changelogPath: zod.z.string(),
1040
+ contextPath: zod.z.string(),
1041
+ displayName: zod.z.string(),
1042
+ runDir: zod.z.string(),
1043
+ runId: zod.z.string().uuid(),
1044
+ runKey: zod.z.string(),
1045
+ workspace: zod.z.string()
1046
+ });
1047
+ //#endregion
1048
+ //#region src/models/WorkflowCapabilityError.ts
1049
+ /**
1050
+ * Raised before any effect when a workflow needs a capability this host does not mount, such as a
1051
+ * shell on a Worker. Nothing was admitted, spawned or written.
1052
+ */
1053
+ var WorkflowCapabilityError = class extends Error {
1054
+ code;
1055
+ needs;
1056
+ constructor(code, message, needs = []) {
1057
+ super(message);
1058
+ this.name = "WorkflowCapabilityError";
1059
+ this.code = code;
1060
+ this.needs = needs;
1061
+ }
1062
+ };
1063
+ //#endregion
1064
+ //#region src/services/workflowRuntime/index.ts
1065
+ /** The runtime's shell, or the typed refusal a host without one gives. */
1066
+ function requireShell(runtime) {
1067
+ if (runtime.shell === void 0) throw new WorkflowCapabilityError("WORKFLOW_SHELL_UNAVAILABLE", "This host has no shell to run this command.");
1068
+ return runtime.shell;
1069
+ }
1070
+ /** Freeze the admitted environment too, so concurrent runs cannot mutate each other's facts. */
1071
+ function createWorkflowRuntime(input) {
1072
+ return Object.freeze({
1073
+ ...input,
1074
+ baseEnvironment: Object.freeze({ ...input.baseEnvironment }),
1075
+ ioContext: input.ioContext ?? _agimon_ai_po_core_platform.BACKGROUND_CONTEXT
1076
+ });
1077
+ }
1078
+ /** A bounded command on the admitted platform, without inheriting the server process environment. */
1079
+ async function workflowShellOutput(runtime, command, options = {}) {
1080
+ let output = "";
1081
+ const env = Object.fromEntries(Object.entries(options.environment ?? runtime.baseEnvironment).filter((entry) => entry[1] !== void 0));
1082
+ const result = (0, _agimon_ai_po_core_platform.getOrThrow)(await requireShell(runtime).exec(typeof command === "string" ? command : [...command], {
1083
+ cwd: options.cwd ?? runtime.cwd,
1084
+ env,
1085
+ inheritEnv: false,
1086
+ ...options.timeoutMs === void 0 ? {} : { timeout: options.timeoutMs / 1e3 },
1087
+ onOutput: (text) => {
1088
+ output += text;
1089
+ }
1090
+ }, runtime.ioContext));
1091
+ if (result.exitCode !== 0) throw new Error(`Workflow command exited with code ${result.exitCode}: ${typeof command === "string" ? command : command.join(" ")}\n${output}`);
1092
+ return output;
1093
+ }
1094
+ //#endregion
1095
+ //#region src/services/WorkflowParserService/index.ts
1096
+ /**
1097
+ * WorkflowParserService
1098
+ *
1099
+ * DESIGN PATTERNS:
1100
+ * - Service pattern for business logic encapsulation
1101
+ * - Single responsibility principle
1102
+ *
1103
+ * CODING STANDARDS:
1104
+ * - Use async/await for asynchronous operations
1105
+ * - Throw descriptive errors for error cases
1106
+ * - Keep methods focused and well-named
1107
+ *
1108
+ * AVOID:
1109
+ * - Mixing concerns (keep focused on single domain)
1110
+ * - Direct tool implementation (services should be tool-agnostic)
1111
+ */
1112
+ const CUSTOM_RUN_KEY = "customRun";
1113
+ const RUN_CONFIG_KEY = "runConfig";
1114
+ const PROMPT_VARIABLE = "prompt";
1115
+ const SYSTEM_PROMPT_VARIABLE = "systemPrompt";
1116
+ const CHOICE_SETTING_KEYS = new Set(Object.keys(ChoiceSettingsSchema.shape));
1117
+ /** A prompt printed raw would be split and expanded by the shell, so templates must quote it. */
1118
+ const UNQUOTED_PROMPT_PATTERN = /\{\{-?\s*(prompt|systemPrompt)\s*-?\}\}/;
1119
+ const LEGACY_INTERPOLATION_MARKER = "${{";
1120
+ const REMOVED_WORKTREE_KEY = "worktree";
1121
+ const REMOVED_WORKTREE_MESSAGE = "`worktree:` was removed. Declare `isolation: checkout` and start the run with an isolating launcher such as po-sparo `worktrees.startWorkflow`; move hook steps into jobs.";
1122
+ /** The schema strips unknown keys, so a removed block must fail before it can be silently ignored. */
1123
+ function rejectRemovedKeys(definition, path) {
1124
+ if (definition && typeof definition === "object" && Object.hasOwn(definition, REMOVED_WORKTREE_KEY)) throw new Error(`${REMOVED_WORKTREE_MESSAGE} (${path})`);
1125
+ }
1126
+ /**
1127
+ * A declared command's template and host options, whichever form it was written
1128
+ * in. `run` is undefined for an in-process command with no shell form.
1129
+ */
1130
+ function commandTemplateOf(command) {
1131
+ return typeof command === "string" ? {
1132
+ run: command,
1133
+ inProcess: false
1134
+ } : {
1135
+ run: command.run,
1136
+ inProcess: command.inProcess === true
1137
+ };
1138
+ }
1139
+ /** Base step/subagent settings, with an optional command-specific override. */
1140
+ function choiceSettings(choice, command) {
1141
+ if (!choice) return {};
1142
+ const settings = {};
1143
+ for (const key of CHOICE_SETTING_KEYS) {
1144
+ const value = choice[key];
1145
+ if (typeof value === "string") settings[key] = value;
1146
+ }
1147
+ const override = command === void 0 ? void 0 : choice[command];
1148
+ if (override && typeof override !== "string") Object.assign(settings, override);
1149
+ return settings;
1150
+ }
1151
+ const SKIPPED_ACTIONS = [
1152
+ "actions/checkout",
1153
+ "actions/setup-node",
1154
+ "actions/cache",
1155
+ "actions/upload-artifact",
1156
+ "actions/download-artifact",
1157
+ "pnpm/action-setup"
1158
+ ];
1159
+ const ADJECTIVES = [
1160
+ "bold",
1161
+ "calm",
1162
+ "cool",
1163
+ "dark",
1164
+ "deep",
1165
+ "fair",
1166
+ "fast",
1167
+ "free",
1168
+ "gold",
1169
+ "keen",
1170
+ "kind",
1171
+ "loud",
1172
+ "neat",
1173
+ "pure",
1174
+ "rare",
1175
+ "safe",
1176
+ "slim",
1177
+ "soft",
1178
+ "tall",
1179
+ "warm",
1180
+ "wild",
1181
+ "wise",
1182
+ "blue",
1183
+ "gray",
1184
+ "jade",
1185
+ "iron",
1186
+ "zinc",
1187
+ "ruby",
1188
+ "opal",
1189
+ "onyx"
1190
+ ];
1191
+ const NOUNS = [
1192
+ "arch",
1193
+ "beam",
1194
+ "bird",
1195
+ "bolt",
1196
+ "cape",
1197
+ "cove",
1198
+ "dawn",
1199
+ "dove",
1200
+ "echo",
1201
+ "fern",
1202
+ "flux",
1203
+ "gale",
1204
+ "hawk",
1205
+ "haze",
1206
+ "iris",
1207
+ "jade",
1208
+ "kite",
1209
+ "lake",
1210
+ "lynx",
1211
+ "mesa",
1212
+ "moth",
1213
+ "node",
1214
+ "palm",
1215
+ "peak",
1216
+ "pine",
1217
+ "raft",
1218
+ "reef",
1219
+ "sage",
1220
+ "tide",
1221
+ "vale"
1222
+ ];
1223
+ var WorkflowParserService = class {
1224
+ runtime;
1225
+ inspectInterpolation;
1226
+ githubSha = "local";
1227
+ constructor(runtime, inspectInterpolation) {
1228
+ this.runtime = runtime;
1229
+ this.inspectInterpolation = inspectInterpolation;
1230
+ }
1231
+ generateHumanReadableId() {
1232
+ return `${ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)]}-${NOUNS[Math.floor(Math.random() * NOUNS.length)]}`;
1233
+ }
1234
+ async parseWorkflowFile(workflowPath) {
1235
+ const resolved = (0, node_path.resolve)(this.runtime.cwd, workflowPath);
1236
+ if (!await (0, _agimon_ai_po_core_platform.pathExists)(this.runtime.fs, resolved, this.runtime.ioContext)) throw new Error(`Workflow file not found: ${resolved}`);
1237
+ const content = (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.fs.readTextFile(resolved, this.runtime.ioContext));
1238
+ if (content.includes("github.sha")) try {
1239
+ this.githubSha = (await workflowShellOutput(this.runtime, "git rev-parse HEAD")).trim();
1240
+ } catch {
1241
+ this.githubSha = "local";
1242
+ }
1243
+ const definition = (0, js_yaml.load)(content);
1244
+ rejectRemovedKeys(definition, resolved);
1245
+ const workflow = WorkflowDefinitionSchema.parse(definition);
1246
+ this.resolveToolsPaths(workflow, resolved);
1247
+ if (workflow.imports) await this.resolveImports(workflow, resolved);
1248
+ if ((!workflow.jobs || Object.keys(workflow.jobs).length === 0) && !Object.keys(workflow["child-jobs"] ?? {}).length) throw new Error("No jobs found in workflow file");
1249
+ this.resolveExtends(workflow);
1250
+ const parsed = WorkflowSchema.parse(this.applyRunConfigDefaults(workflow));
1251
+ this.validateCommandTemplates(parsed);
1252
+ this.validateChildJobs(parsed);
1253
+ return parsed;
1254
+ }
1255
+ /**
1256
+ * Read and import-merge a partial workflow definition without concrete schema
1257
+ * validation or extends resolution. This is intentionally for inspection only.
1258
+ */
1259
+ async parseWorkflowTemplateFile(workflowPath) {
1260
+ const resolved = (0, node_path.resolve)(this.runtime.cwd, workflowPath);
1261
+ if (!await (0, _agimon_ai_po_core_platform.pathExists)(this.runtime.fs, resolved, this.runtime.ioContext)) throw new Error(`Workflow file not found: ${resolved}`);
1262
+ const content = (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.fs.readTextFile(resolved, this.runtime.ioContext));
1263
+ const parsed = (0, js_yaml.load)(content);
1264
+ rejectRemovedKeys(parsed, resolved);
1265
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error(`Workflow template must be a YAML object: ${resolved}`);
1266
+ const workflow = parsed;
1267
+ this.resolveToolsPaths(workflow, resolved);
1268
+ workflow.jobs ??= {};
1269
+ if (workflow.imports) await this.resolveImports(workflow, resolved);
1270
+ workflow.jobs ??= {};
1271
+ return workflow;
1272
+ }
1273
+ /** Resolve before merging so imported jobs and defaults keep their declaring file's origin. */
1274
+ resolveToolsPaths(workflow, workflowPath) {
1275
+ const stored = require_contract.librarySourceOf(workflowPath, this.runtime.library) !== void 0;
1276
+ if (stored && workflow.imports?.length) throw new Error(`Stored workflow ${workflowPath} cannot use imports; put what it needs in the workflow itself.`);
1277
+ for (const declaration of [
1278
+ workflow,
1279
+ ...Object.values(workflow.jobs ?? {}),
1280
+ ...Object.values(workflow["child-jobs"] ?? {}),
1281
+ workflow.repair
1282
+ ]) {
1283
+ for (const reference of [declaration?.tools, declaration?.instructions]) if (stored && reference !== void 0 && !(typeof reference === "string" && (0, node_path.isAbsolute)(reference))) throw new Error(`Stored workflow ${workflowPath} names ${String(reference)} by a relative path; use an absolute path such as /workspace/...`);
1284
+ if (declaration?.tools !== void 0) declaration.tools = (0, node_path.resolve)((0, node_path.dirname)(workflowPath), WorkflowToolsPathSchema.parse(declaration.tools));
1285
+ if (declaration?.instructions !== void 0) declaration.instructions = (0, node_path.resolve)((0, node_path.dirname)(workflowPath), WorkflowInstructionsPathSchema.parse(declaration.instructions));
1286
+ }
1287
+ }
1288
+ /**
1289
+ * Render a command template into the shell command a step runs.
1290
+ *
1291
+ * Values enter as data and are never rendered again, so `${{ }}` text a
1292
+ * prompt already went through, or Liquid syntax a prompt quotes, stays as it
1293
+ * is. Use the `shell` filter to quote a value as one shell word.
1294
+ */
1295
+ renderCommandTemplate(template, values) {
1296
+ return renderWorkflowCommandTemplate(template, values);
1297
+ }
1298
+ /** The top-level values a command template reads. */
1299
+ templateVariables(template) {
1300
+ return workflowCommandTemplateVariables(template);
1301
+ }
1302
+ /** Whether a template passes the system prompt itself; when not, it is folded into the prompt. */
1303
+ templateUsesSystemPrompt(template) {
1304
+ return workflowCommandTemplateVariables(template).includes(SYSTEM_PROMPT_VARIABLE);
1305
+ }
1306
+ /**
1307
+ * Check what the schema cannot see once imports and templates are merged:
1308
+ * that steps name declared commands and choices, that `parallel` and
1309
+ * `restart-from` sit in jobs, and that every command template parses and
1310
+ * quotes its prompts.
1311
+ */
1312
+ validateCommandTemplates(workflow) {
1313
+ const problems = [];
1314
+ const commands = workflow.commands ?? {};
1315
+ const choices = workflow.choices ?? {};
1316
+ const jobNames = new Set(Object.keys(workflow.jobs));
1317
+ for (const [name, command] of Object.entries(commands)) {
1318
+ const { run } = commandTemplateOf(command);
1319
+ if (run === void 0) continue;
1320
+ if (run.includes(LEGACY_INTERPOLATION_MARKER)) problems.push(`Command "${name}" uses \${{ }}; command templates are Liquid, use {{ }} instead.`);
1321
+ if (UNQUOTED_PROMPT_PATTERN.test(run)) problems.push(`Command "${name}" prints a prompt unquoted; write {{ prompt | shell }}.`);
1322
+ try {
1323
+ if (!workflowCommandTemplateVariables(run).includes(PROMPT_VARIABLE)) problems.push(`Command "${name}" never passes {{ prompt | shell }} to the agent.`);
1324
+ } catch (error) {
1325
+ problems.push(`Command "${name}" is not a valid Liquid template: ${error instanceof Error ? error.message : String(error)}`);
1326
+ }
1327
+ }
1328
+ for (const [name, choice] of Object.entries(choices)) for (const key of Object.keys(choice)) if (!CHOICE_SETTING_KEYS.has(key) && !(key in commands)) problems.push(`Choice "${name}" overrides "${key}", which is not a declared command.`);
1329
+ const checkStep = (step, where, inJob) => {
1330
+ if (Array.isArray(step.interactiveRun)) for (const entry of step.interactiveRun) {
1331
+ if (!(entry.command in commands)) problems.push(`${where} runs command "${entry.command}", which is not declared under commands.`);
1332
+ if (entry.choice !== void 0 && !(entry.choice in choices)) problems.push(`${where} names choice "${entry.choice}", which is not declared under choices.`);
1333
+ }
1334
+ if (step.choice !== void 0 && !(step.choice in choices)) problems.push(`${where} names choice "${step.choice}", which is not declared under choices.`);
1335
+ const restartFrom = step["restart-from"];
1336
+ if (restartFrom !== void 0) {
1337
+ if (!inJob) problems.push(`${where} sets restart-from, which only jobs support.`);
1338
+ else if (!jobNames.has(restartFrom)) problems.push(`${where} restarts from "${restartFrom}", which is not a job.`);
1339
+ }
1340
+ if (step.parallel) {
1341
+ if (!inJob) problems.push(`${where} is a parallel group, which only jobs support.`);
1342
+ const names = step.parallel.map((child) => child.name).filter((name) => name !== void 0);
1343
+ if (new Set(names).size !== names.length) problems.push(`${where} has parallel steps with the same name.`);
1344
+ for (const [index, child] of step.parallel.entries()) checkStep(child, `${where} parallel ${child.name ?? index + 1}`, inJob);
1345
+ }
1346
+ };
1347
+ const checkSteps = (steps, where, inJob) => {
1348
+ for (const [index, step] of (steps ?? []).entries()) checkStep(step, `${where} step ${step.name ?? index + 1}`, inJob);
1349
+ };
1350
+ const checkJob = (job, where) => {
1351
+ checkSteps(job.steps, where, true);
1352
+ checkSteps(job.preJob?.steps, `${where} preJob`, true);
1353
+ checkSteps(job.postJob?.steps, `${where} postJob`, true);
1354
+ };
1355
+ for (const [name, job] of Object.entries(workflow.jobs)) checkJob(job, `Job "${name}"`);
1356
+ for (const [name, job] of Object.entries(workflow["child-jobs"] ?? {})) checkJob(job, `Child job "${name}"`);
1357
+ if (workflow.repair) checkJob(workflow.repair, "Repair");
1358
+ checkSteps(workflow.pre?.steps, "pre", false);
1359
+ checkSteps(workflow.post?.steps, "post", false);
1360
+ checkSteps(workflow.on?.agent_decision?.steps, "agent_decision", false);
1361
+ if (problems.length > 0) throw new Error(`Invalid workflow:\n - ${problems.join("\n - ")}`);
1362
+ }
1363
+ /** Child references are checked after imports and extends, never before their definitions arrive. */
1364
+ validateChildJobs(workflow) {
1365
+ const problems = [];
1366
+ const children = workflow["child-jobs"] ?? {};
1367
+ const declaredFiles = new Set((workflow["run-directory"]?.entries ?? []).filter((entry) => entry.kind === "file").map((entry) => entry.path));
1368
+ const agentSteps = (steps) => steps.flatMap((step) => step.parallel ? agentSteps(step.parallel) : step.customRun || step.interactiveRun ? [step] : []);
1369
+ for (const [name, child] of Object.entries(children)) {
1370
+ if (Object.hasOwn(workflow.jobs, name)) problems.push(`Child job "${name}" collides with a scheduled job.`);
1371
+ if (name.startsWith(".")) problems.push(`Child job "${name}" must not be a dot-prefixed template.`);
1372
+ if (child.needs !== void 0) problems.push(`Child job "${name}" cannot declare needs; it runs only when invoked.`);
1373
+ if (child.children !== void 0 || child["acceptance-criteria"] !== void 0 || child.completion !== void 0) problems.push(`Child job "${name}" cannot declare lead completion or nested children.`);
1374
+ }
1375
+ if (workflow.repair?.["max-failures"] !== void 0) problems.push("The repair job declares max-failures, which only child jobs take.");
1376
+ for (const [name, job] of Object.entries(workflow.jobs)) {
1377
+ for (const child of job.children ?? []) if (!Object.hasOwn(children, child)) problems.push(`Job "${name}" allows unknown child job "${child}".`);
1378
+ if (job["max-failures"] !== void 0) problems.push(`Job "${name}" declares max-failures, which only child jobs take.`);
1379
+ const criteria = Object.entries(job["acceptance-criteria"] ?? {});
1380
+ if (criteria.length === 0 && job.completion !== void 0) problems.push(`Job "${name}" declares completion without acceptance-criteria.`);
1381
+ if (criteria.length > 0) {
1382
+ if (agentSteps(job.steps).length !== 1) problems.push(`Job "${name}" with acceptance-criteria requires exactly one agent step.`);
1383
+ if (job.steps.some((step) => step["continue-on-error"] || step.parallel)) problems.push(`Job "${name}" with acceptance-criteria cannot use continue-on-error or parallel lead steps.`);
1384
+ }
1385
+ for (const [key, criterion] of criteria) {
1386
+ const verifier = criterion["verified-by"];
1387
+ if (!(job.children ?? []).includes(verifier) || !Object.hasOwn(children, verifier)) problems.push(`Job "${name}" criterion "${key}" verified-by "${verifier}" must name an allowed child job.`);
1388
+ else if (agentSteps(children[verifier].steps).length === 0) problems.push(`Job "${name}" criterion "${key}" requires an agent verifier in child job "${verifier}".`);
1389
+ for (const artifact of criterion.artifacts ?? []) if (!declaredFiles.has(artifact)) problems.push(`Job "${name}" criterion "${key}" references undeclared artifact "${artifact}".`);
1390
+ }
1391
+ }
1392
+ if (problems.length > 0) throw new Error(`Invalid workflow:\n - ${problems.join("\n - ")}`);
1393
+ }
1394
+ /**
1395
+ * Lay the workflow's `runConfig` under the one of every agent step, a step
1396
+ * with an `interactiveRun` or `customRun`, wherever it sits. A key the step
1397
+ * sets itself wins, so a step runs on the workflow default unless it says
1398
+ * otherwise.
1399
+ */
1400
+ applyRunConfigDefaults(workflow) {
1401
+ const visit = (value, defaults = workflow.runConfig ?? {}) => {
1402
+ if (Array.isArray(value)) return value.map((item) => visit(item, defaults));
1403
+ if (!value || typeof value !== "object") return value;
1404
+ const object = value;
1405
+ const inherited = Array.isArray(object.steps) ? {
1406
+ ...defaults,
1407
+ ...object[RUN_CONFIG_KEY]
1408
+ } : defaults;
1409
+ const copy = Object.fromEntries(Object.entries(object).map(([key, nested]) => [key, visit(nested, inherited)]));
1410
+ if ((copy[CUSTOM_RUN_KEY] !== void 0 || copy.interactiveRun !== void 0) && Object.keys(inherited).length > 0) copy[RUN_CONFIG_KEY] = {
1411
+ ...inherited,
1412
+ ...copy[RUN_CONFIG_KEY]
1413
+ };
1414
+ return copy;
1415
+ };
1416
+ return visit(workflow);
1417
+ }
1418
+ /**
1419
+ * The workflow as it runs on `runner`.
1420
+ *
1421
+ * A runner declared under `runners` lays its `runConfig` over the one of
1422
+ * every step that has a `customRun`, wherever the step sits: jobs, hooks,
1423
+ * triage and trigger steps alike. Any other runner, including a command
1424
+ * map's key, leaves the workflow as parsed.
1425
+ */
1426
+ selectRunner(workflow, runner) {
1427
+ const overlay = runner === void 0 ? void 0 : workflow.runners?.[runner]?.runConfig;
1428
+ if (overlay === void 0) return workflow;
1429
+ const visit = (value) => {
1430
+ if (Array.isArray(value)) return value.map(visit);
1431
+ if (!value || typeof value !== "object") return value;
1432
+ const copy = Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, visit(nested)]));
1433
+ if (copy[CUSTOM_RUN_KEY] !== void 0) copy[RUN_CONFIG_KEY] = {
1434
+ ...copy[RUN_CONFIG_KEY],
1435
+ ...overlay
1436
+ };
1437
+ return copy;
1438
+ };
1439
+ const { runners, ...rest } = workflow;
1440
+ return {
1441
+ ...visit(rest),
1442
+ runners
1443
+ };
1444
+ }
1445
+ /**
1446
+ * Resolve `imports` references in a workflow.
1447
+ * Import paths are resolved relative to the importing workflow file.
1448
+ * Imported files provide base sections that the main workflow can override:
1449
+ * - env: merged (main overrides imported)
1450
+ * - pre.steps: imported steps prepended before main steps
1451
+ * - pre.services: imported services prepended before main services
1452
+ * - post.steps: imported steps prepended before main steps
1453
+ * - post.services: imported services prepended before main services
1454
+ * - isolation: scalar default (main wins, otherwise first imported declaration)
1455
+ * - jobs: imported template jobs (dot-prefixed) merged in, main overrides
1456
+ * - system-prompt: concatenated (imported + main)
1457
+ * - commands, choices: merged per name (main overrides imported)
1458
+ * - runConfig, sessionConfig: merged per key (main overrides imported)
1459
+ * - tools, instructions: scalar default (main wins, otherwise first imported selection)
1460
+ * Imports are processed in order; earlier merged values act as main overrides.
1461
+ * Circular imports are detected and throw an error.
1462
+ */
1463
+ async resolveImports(workflow, workflowPath, visited = /* @__PURE__ */ new Set()) {
1464
+ const normalizedPath = (0, node_path.resolve)(workflowPath);
1465
+ if (visited.has(normalizedPath)) throw new Error(`Circular import detected: ${normalizedPath}`);
1466
+ visited.add(normalizedPath);
1467
+ const baseDir = normalizedPath.replace(/\/[^/]+$/, "");
1468
+ for (const importPath of workflow.imports ?? []) {
1469
+ const resolvedImport = (0, node_path.resolve)(baseDir, importPath);
1470
+ if (!await (0, _agimon_ai_po_core_platform.pathExists)(this.runtime.fs, resolvedImport, this.runtime.ioContext)) throw new Error(`Imported workflow file not found: ${resolvedImport} (from ${normalizedPath})`);
1471
+ const importContent = (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.fs.readTextFile(resolvedImport, this.runtime.ioContext));
1472
+ const imported = (0, js_yaml.load)(importContent);
1473
+ rejectRemovedKeys(imported, resolvedImport);
1474
+ this.resolveToolsPaths(imported, resolvedImport);
1475
+ if (imported.imports) await this.resolveImports(imported, resolvedImport, visited);
1476
+ workflow.tools ??= imported.tools;
1477
+ workflow.instructions ??= imported.instructions;
1478
+ workflow.isolation ??= imported.isolation;
1479
+ if (imported.env) workflow.env = {
1480
+ ...imported.env,
1481
+ ...workflow.env
1482
+ };
1483
+ if (imported.pre) {
1484
+ if (!workflow.pre) workflow.pre = {};
1485
+ if (imported.pre.services) workflow.pre.services = [...imported.pre.services, ...workflow.pre.services ?? []];
1486
+ if (imported.pre.steps) workflow.pre.steps = [...imported.pre.steps, ...workflow.pre.steps ?? []];
1487
+ }
1488
+ if (imported.post) {
1489
+ if (!workflow.post) workflow.post = {};
1490
+ if (imported.post.services) workflow.post.services = [...imported.post.services, ...workflow.post.services ?? []];
1491
+ if (imported.post.steps) workflow.post.steps = [...imported.post.steps, ...workflow.post.steps ?? []];
1492
+ }
1493
+ if (imported["max-workflows"] && !workflow["max-workflows"]) workflow["max-workflows"] = imported["max-workflows"];
1494
+ if (imported.keybindings) workflow.keybindings = {
1495
+ ...imported.keybindings,
1496
+ ...workflow.keybindings
1497
+ };
1498
+ if (imported.commands) workflow.commands = {
1499
+ ...imported.commands,
1500
+ ...workflow.commands
1501
+ };
1502
+ if (imported.choices) workflow.choices = {
1503
+ ...imported.choices,
1504
+ ...workflow.choices
1505
+ };
1506
+ if (imported.runConfig) workflow.runConfig = {
1507
+ ...imported.runConfig,
1508
+ ...workflow.runConfig
1509
+ };
1510
+ if (imported.sessionConfig) workflow.sessionConfig = {
1511
+ ...imported.sessionConfig,
1512
+ ...workflow.sessionConfig
1513
+ };
1514
+ if (imported["run-directory"]) workflow["run-directory"] = this.mergeRunDirectories(imported["run-directory"], workflow["run-directory"]);
1515
+ if (imported.repair && !workflow.repair) workflow.repair = imported.repair;
1516
+ if (imported["system-prompt"]) {
1517
+ if (workflow["system-prompt"]) workflow["system-prompt"] = `${imported["system-prompt"]}\n\n${workflow["system-prompt"]}`;
1518
+ else workflow["system-prompt"] = imported["system-prompt"];
1519
+ }
1520
+ for (const [name, job] of Object.entries(imported["child-jobs"] ?? {})) {
1521
+ workflow["child-jobs"] ??= {};
1522
+ if (Object.hasOwn(workflow["child-jobs"], name)) throw new Error(`Duplicate child job "${name}" imported from ${resolvedImport}`);
1523
+ workflow["child-jobs"] = {
1524
+ ...workflow["child-jobs"],
1525
+ [name]: job
1526
+ };
1527
+ }
1528
+ if (imported.jobs) {
1529
+ for (const [name, job] of Object.entries(imported.jobs)) if (!(name in (workflow.jobs ?? {}))) {
1530
+ if (!workflow.jobs) workflow.jobs = {};
1531
+ workflow.jobs[name] = job;
1532
+ }
1533
+ }
1534
+ }
1535
+ delete workflow.imports;
1536
+ }
1537
+ mergeRunDirectories(base, override) {
1538
+ if (!override) return base;
1539
+ const entries = new Map(base.entries.map((entry) => [entry.path, entry]));
1540
+ for (const entry of override.entries) entries.set(entry.path, entry);
1541
+ return {
1542
+ description: override.description,
1543
+ entries: [...entries.values()]
1544
+ };
1545
+ }
1546
+ /**
1547
+ * Resolve `extends` references in jobs.
1548
+ * Dot-prefixed jobs (e.g. `.ios-prebuild`) are shared templates.
1549
+ * When a job has `extends: .template-name`, it merges:
1550
+ * - steps: template steps prepended before job steps
1551
+ * - preJob.steps: template steps prepended before job preJob steps
1552
+ * - postJob.steps: template steps prepended before job postJob steps
1553
+ * - env: merged (job overrides template)
1554
+ * - system-prompt: concatenated (template + job)
1555
+ * - runs-on, strategy, context, tools: inherited when not set on the job
1556
+ * Template jobs are removed from the jobs map after resolution.
1557
+ */
1558
+ resolveExtends(workflow) {
1559
+ const { jobs } = workflow;
1560
+ const templates = /* @__PURE__ */ new Map();
1561
+ for (const [name, job] of Object.entries(jobs)) if (name.startsWith(".")) templates.set(name, job);
1562
+ for (const [name, job] of [...Object.entries(jobs), ...Object.entries(workflow["child-jobs"] ?? {})]) {
1563
+ if (name.startsWith(".")) continue;
1564
+ if (!job.extends) continue;
1565
+ const templateNames = Array.isArray(job.extends) ? job.extends : [job.extends];
1566
+ const jobOwnSteps = [...job.steps ?? []];
1567
+ const jobOwnPreSteps = [...job.preJob?.steps ?? []];
1568
+ const jobOwnPostSteps = [...job.postJob?.steps ?? []];
1569
+ const prependedSteps = [];
1570
+ const prependedPreJobSteps = [];
1571
+ const prependedPostJobSteps = [];
1572
+ for (const templateName of templateNames) {
1573
+ const template = templates.get(templateName);
1574
+ if (!template) throw new Error(`Job "${name}" extends "${templateName}" but template not found`);
1575
+ prependedSteps.push(...template.steps ?? []);
1576
+ prependedPreJobSteps.push(...template.preJob?.steps ?? []);
1577
+ prependedPostJobSteps.push(...template.postJob?.steps ?? []);
1578
+ this.applyTemplate(job, template);
1579
+ }
1580
+ job.steps = [...prependedSteps, ...jobOwnSteps];
1581
+ this.assignJobHookSteps(job, "preJob", [...prependedPreJobSteps, ...jobOwnPreSteps]);
1582
+ this.assignJobHookSteps(job, "postJob", [...prependedPostJobSteps, ...jobOwnPostSteps]);
1583
+ delete job.extends;
1584
+ }
1585
+ for (const name of templates.keys()) delete jobs[name];
1586
+ }
1587
+ /**
1588
+ * Merge a single template into a job.
1589
+ * Called once per template when a job extends multiple templates.
1590
+ */
1591
+ applyTemplate(job, template) {
1592
+ job.steps = [...template.steps ?? [], ...job.steps ?? []];
1593
+ this.mergeJobHookSteps(job, template, "preJob");
1594
+ this.mergeJobHookSteps(job, template, "postJob");
1595
+ if (template.env || job.env) job.env = {
1596
+ ...template.env,
1597
+ ...job.env
1598
+ };
1599
+ if (template["system-prompt"] && job["system-prompt"]) job["system-prompt"] = `${template["system-prompt"]}\n\n${job["system-prompt"]}`;
1600
+ else if (template["system-prompt"]) job["system-prompt"] = template["system-prompt"];
1601
+ if (template["runs-on"] && !job["runs-on"]) job["runs-on"] = template["runs-on"];
1602
+ if (template.strategy && !job.strategy) job.strategy = template.strategy;
1603
+ if (template.context && !job.context) job.context = template.context;
1604
+ job.tools ??= template.tools;
1605
+ job.instructions ??= template.instructions;
1606
+ if (template.runConfig || job.runConfig) job.runConfig = {
1607
+ ...template.runConfig,
1608
+ ...job.runConfig
1609
+ };
1610
+ if (!job.identity && template.identity) job.identity = { roles: [...template.identity.roles] };
1611
+ job.inputs ??= template.inputs;
1612
+ job.children ??= template.children;
1613
+ job["acceptance-criteria"] ??= template["acceptance-criteria"];
1614
+ job.completion ??= template.completion;
1615
+ job["max-failures"] ??= template["max-failures"];
1616
+ }
1617
+ mergeJobHookSteps(job, template, hookKey) {
1618
+ const templateSteps = template[hookKey]?.steps ?? [];
1619
+ const jobSteps = job[hookKey]?.steps ?? [];
1620
+ this.assignJobHookSteps(job, hookKey, [...templateSteps, ...jobSteps]);
1621
+ }
1622
+ assignJobHookSteps(job, hookKey, steps) {
1623
+ if (steps.length > 0) {
1624
+ job[hookKey] = { steps };
1625
+ return;
1626
+ }
1627
+ delete job[hookKey];
1628
+ }
1629
+ async loadSecrets(secretFile) {
1630
+ const secrets = /* @__PURE__ */ new Map();
1631
+ if (!await (0, _agimon_ai_po_core_platform.pathExists)(this.runtime.fs, secretFile, this.runtime.ioContext)) return secrets;
1632
+ const content = (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.fs.readTextFile(secretFile, this.runtime.ioContext));
1633
+ for (const line of content.split("\n")) {
1634
+ const trimmed = line.trim();
1635
+ if (!trimmed || trimmed.startsWith("#")) continue;
1636
+ const eqIdx = trimmed.indexOf("=");
1637
+ if (eqIdx === -1) continue;
1638
+ secrets.set(trimmed.slice(0, eqIdx), trimmed.slice(eqIdx + 1));
1639
+ }
1640
+ return secrets;
1641
+ }
1642
+ interpolate(template, context) {
1643
+ return template.replace(/\$\{\{\s*(.+?)\s*\}\}/g, (_match, expr) => {
1644
+ const parts = expr.trim().split(".");
1645
+ const observed = (value) => {
1646
+ this.inspectInterpolation?.(expr.trim(), value);
1647
+ return value ?? "";
1648
+ };
1649
+ if (parts[0] === "inputs" && parts[1]) return observed(context.inputs.get(parts[1]));
1650
+ if (parts[0] === "matrix" && parts[1]) return observed(context.matrix[parts[1]]);
1651
+ if (parts[0] === "secrets" && parts[1]) return observed(context.secrets.get(parts[1]) || this.runtime.baseEnvironment[parts[1]] || (context.secrets.has(parts[1]) ? "" : void 0));
1652
+ if (parts[0] === "env" && parts[1]) return observed(context.env[parts[1]] || this.runtime.baseEnvironment[parts[1]] || (Object.hasOwn(context.env, parts[1]) ? "" : void 0));
1653
+ if (parts[0] === "runConfig" && parts[1]) {
1654
+ const value = context.runConfig?.[parts[1]];
1655
+ return observed(Array.isArray(value) ? value.join(",") : value ?? void 0);
1656
+ }
1657
+ if (parts[0] === "runner" && parts[1] === "os") return observed("macOS");
1658
+ if (parts[0] === "github" && parts[1] === "sha") return observed(this.githubSha);
1659
+ if (expr.includes("hashFiles")) return observed("local");
1660
+ this.inspectInterpolation?.(expr.trim(), void 0);
1661
+ return `\${{ ${expr} }}`;
1662
+ });
1663
+ }
1664
+ isActionSkipped(uses) {
1665
+ return SKIPPED_ACTIONS.some((prefix) => uses.startsWith(prefix));
1666
+ }
1667
+ resolveJobOrder(jobs, targetJob) {
1668
+ const visited = /* @__PURE__ */ new Set();
1669
+ const order = [];
1670
+ const visit = (jobName) => {
1671
+ if (visited.has(jobName)) return;
1672
+ visited.add(jobName);
1673
+ const job = jobs[jobName];
1674
+ if (!job) throw new Error(`Job not found: ${jobName}`);
1675
+ const deps = job.needs ? Array.isArray(job.needs) ? job.needs : [job.needs] : [];
1676
+ for (const dep of deps) visit(dep);
1677
+ order.push(jobName);
1678
+ };
1679
+ if (targetJob) visit(targetJob);
1680
+ else for (const jobName of Object.keys(jobs)) visit(jobName);
1681
+ return order;
1682
+ }
1683
+ expandMatrix(job) {
1684
+ if (!job.strategy?.matrix) return [{}];
1685
+ const { include, ...rest } = job.strategy.matrix;
1686
+ if (include && include.length > 0) return include;
1687
+ const keys = Object.keys(rest).filter((k) => Array.isArray(rest[k]));
1688
+ if (keys.length === 0) return [{}];
1689
+ let combos = [{}];
1690
+ for (const key of keys) {
1691
+ const values = rest[key];
1692
+ const newCombos = [];
1693
+ for (const combo of combos) for (const val of values) newCombos.push({
1694
+ ...combo,
1695
+ [key]: String(val)
1696
+ });
1697
+ combos = newCombos;
1698
+ }
1699
+ return combos;
1700
+ }
1701
+ };
1702
+ //#endregion
1703
+ //#region src/services/workflowInspection/index.ts
1704
+ /** Parses a workflow or template file without executing anything. */
1705
+ async function inspectWorkflowDefinition(runtime, workflowPath, options = {}, parser = new WorkflowParserService(runtime)) {
1706
+ const path = (0, node_path.resolve)(runtime.cwd, workflowPath);
1707
+ if (options.template && options.job !== void 0) throw new Error("Template inspection does not support a job.");
1708
+ let definition;
1709
+ let jobOrder = [];
1710
+ if (options.template === true) definition = await parser.parseWorkflowTemplateFile(path);
1711
+ else {
1712
+ definition = await parser.parseWorkflowFile(path);
1713
+ jobOrder = parser.resolveJobOrder(definition.jobs, options.job ?? null);
1714
+ }
1715
+ if (!definition || typeof definition !== "object" || Array.isArray(definition)) throw new Error(`Workflow definition is not an object: ${path}`);
1716
+ return {
1717
+ schemaVersion: 1,
1718
+ path,
1719
+ template: options.template === true,
1720
+ definition,
1721
+ jobOrder
1722
+ };
1723
+ }
1724
+ //#endregion
1725
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/errors.js
1726
+ var RmuxCommandError = class extends Error {
1727
+ run;
1728
+ constructor(run) {
1729
+ super(commandFailureMessage(run));
1730
+ this.name = "RmuxCommandError";
1731
+ this.run = run;
1732
+ }
1733
+ };
1734
+ var RmuxCompatibilityError = class extends Error {
1735
+ constructor(message) {
1736
+ super(message);
1737
+ this.name = "RmuxCompatibilityError";
1738
+ }
1739
+ };
1740
+ function commandFailureMessage(run) {
1741
+ const command = commandName(run.args);
1742
+ const outcome = run.signal === void 0 ? `status ${run.returnCode}` : `signal ${run.signal}`;
1743
+ const stderr = run.stderr.trim();
1744
+ const suffix = stderr.length > 0 ? `: ${stderr}` : "";
1745
+ return `rmux command ${JSON.stringify(command)} failed with ${outcome}${suffix}`;
1746
+ }
1747
+ function commandName(args) {
1748
+ for (let index = 1; index < args.length; index += 1) {
1749
+ const arg = args[index];
1750
+ if (arg === "-S" || arg === "-L") {
1751
+ index += 1;
1752
+ continue;
1753
+ }
1754
+ if (arg !== void 0) return arg;
1755
+ }
1756
+ return args[0] ?? "rmux";
1757
+ }
1758
+ //#endregion
1759
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/command.js
1760
+ var CommandRun = class {
1761
+ args;
1762
+ returnCode;
1763
+ signal;
1764
+ stdout;
1765
+ stderr;
1766
+ constructor(args, returnCode, stdout, stderr, signal) {
1767
+ this.args = [...args];
1768
+ this.returnCode = returnCode;
1769
+ if (signal !== void 0) this.signal = signal;
1770
+ this.stdout = stdout;
1771
+ this.stderr = stderr;
1772
+ }
1773
+ get returncode() {
1774
+ return this.returnCode;
1775
+ }
1776
+ checkReturnCode() {
1777
+ if (this.returnCode !== 0) throw new RmuxCommandError(this);
1778
+ return this;
1779
+ }
1780
+ };
1781
+ //#endregion
1782
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/duration.js
1783
+ function durationMilliseconds(value) {
1784
+ const milliseconds = typeof value === "number" ? value * 1e3 : (value.milliseconds ?? 0) + (value.seconds ?? 0) * 1e3;
1785
+ if (!Number.isFinite(milliseconds) || milliseconds < 0) throw new RangeError("duration must be a non-negative finite value");
1786
+ return milliseconds;
1787
+ }
1788
+ function sleep(milliseconds) {
1789
+ return new Promise((resolve) => {
1790
+ setTimeout(resolve, milliseconds);
1791
+ });
1792
+ }
1793
+ function deadlineFromNow(timeout) {
1794
+ return node_perf_hooks.performance.now() + durationMilliseconds(timeout);
1795
+ }
1796
+ function deadlineExpired(deadline) {
1797
+ return node_perf_hooks.performance.now() >= deadline;
1798
+ }
1799
+ function remainingMilliseconds(deadline) {
1800
+ return Math.max(0, deadline - node_perf_hooks.performance.now());
1801
+ }
1802
+ //#endregion
1803
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/process.js
1804
+ function mergedEnv(env) {
1805
+ if (env === void 0) return;
1806
+ return {
1807
+ ...process.env,
1808
+ ...env
1809
+ };
1810
+ }
1811
+ function runProcess(argv, options) {
1812
+ const command = argv[0];
1813
+ if (command === void 0) return Promise.reject(/* @__PURE__ */ new Error("argv must not be empty"));
1814
+ return new Promise((resolve, reject) => {
1815
+ const args = argv.slice(1);
1816
+ const child = (0, node_child_process.spawn)(command, args, {
1817
+ cwd: options.cwd,
1818
+ env: mergedEnv(options.env),
1819
+ stdio: "pipe"
1820
+ });
1821
+ child.stdin.end();
1822
+ let stdout = "";
1823
+ let stderr = "";
1824
+ child.stdout.setEncoding("utf8");
1825
+ child.stderr.setEncoding("utf8");
1826
+ child.stdout.on("data", (chunk) => {
1827
+ stdout += chunk;
1828
+ });
1829
+ child.stderr.on("data", (chunk) => {
1830
+ stderr += chunk;
1831
+ });
1832
+ child.on("error", reject);
1833
+ child.on("close", (code, signal) => {
1834
+ resolve({
1835
+ code: processReturnCode(code, signal),
1836
+ signal: signal ?? void 0,
1837
+ stdout,
1838
+ stderr
1839
+ });
1840
+ });
1841
+ });
1842
+ }
1843
+ function processReturnCode(code, signal) {
1844
+ if (code !== null) return code;
1845
+ if (signal !== null) {
1846
+ const signalNumber = node_os.constants.signals[signal];
1847
+ if (typeof signalNumber === "number") return -signalNumber;
1848
+ }
1849
+ return 1;
1850
+ }
1851
+ //#endregion
1852
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/control.js
1853
+ var ControlOutput = class {
1854
+ paneId;
1855
+ data;
1856
+ constructor(paneId, data) {
1857
+ this.paneId = paneId;
1858
+ this.data = data;
1859
+ }
1860
+ get pane_id() {
1861
+ return this.paneId;
1862
+ }
1863
+ };
1864
+ var ControlExtendedOutput = class {
1865
+ paneId;
1866
+ ageMs;
1867
+ data;
1868
+ constructor(paneId, ageMs, data) {
1869
+ this.paneId = paneId;
1870
+ this.ageMs = ageMs;
1871
+ this.data = data;
1872
+ }
1873
+ get pane_id() {
1874
+ return this.paneId;
1875
+ }
1876
+ get age_ms() {
1877
+ return this.ageMs;
1878
+ }
1879
+ };
1880
+ var ControlExit = class {
1881
+ reason;
1882
+ constructor(reason) {
1883
+ if (reason !== void 0) this.reason = reason;
1884
+ }
1885
+ };
1886
+ var ControlNotification = class {
1887
+ prefix;
1888
+ line;
1889
+ constructor(prefix, line) {
1890
+ this.prefix = prefix;
1891
+ this.line = line;
1892
+ }
1893
+ };
1894
+ var ControlMalformed = class {
1895
+ prefix;
1896
+ line;
1897
+ reason;
1898
+ constructor(prefix, line, reason) {
1899
+ this.prefix = prefix;
1900
+ this.line = line;
1901
+ this.reason = reason;
1902
+ }
1903
+ };
1904
+ var ControlModeStreamEndedError = class extends Error {
1905
+ constructor(message) {
1906
+ super(message);
1907
+ this.name = "ControlModeStreamEndedError";
1908
+ }
1909
+ };
1910
+ function spawnControlProcess(options) {
1911
+ return (0, node_child_process.spawn)(options.binary, options.args, {
1912
+ cwd: options.cwd,
1913
+ env: mergedEnv(options.env),
1914
+ stdio: [
1915
+ "pipe",
1916
+ "pipe",
1917
+ "pipe"
1918
+ ]
1919
+ });
1920
+ }
1921
+ function waitForControlProcessSpawn(process) {
1922
+ return new Promise((resolve, reject) => {
1923
+ const cleanup = () => {
1924
+ process.off("error", onError);
1925
+ process.off("spawn", onSpawn);
1926
+ };
1927
+ const onError = (error) => {
1928
+ cleanup();
1929
+ reject(error);
1930
+ };
1931
+ const onSpawn = () => {
1932
+ cleanup();
1933
+ resolve();
1934
+ };
1935
+ process.once("error", onError);
1936
+ process.once("spawn", onSpawn);
1937
+ });
1938
+ }
1939
+ var ControlModeClient = class {
1940
+ process;
1941
+ #lines = new AsyncQueue();
1942
+ #deferredEvents = [];
1943
+ #buffer = "";
1944
+ #stderr = "";
1945
+ #closed = false;
1946
+ #ended = false;
1947
+ #processError;
1948
+ #activeReader;
1949
+ constructor(process) {
1950
+ this.process = process;
1951
+ this.process.stdout.setEncoding("utf8");
1952
+ this.process.stderr.setEncoding("utf8");
1953
+ this.process.stdout.on("data", (chunk) => {
1954
+ this.feedStdout(chunk);
1955
+ });
1956
+ this.process.stdout.on("end", () => {
1957
+ if (this.#buffer.length > 0) {
1958
+ this.#lines.push({
1959
+ kind: "line",
1960
+ line: this.#buffer
1961
+ });
1962
+ this.#buffer = "";
1963
+ }
1964
+ this.finish();
1965
+ });
1966
+ this.process.stderr.on("data", (chunk) => {
1967
+ this.#stderr = (this.#stderr + chunk).slice(-4096);
1968
+ });
1969
+ this.process.on("error", (error) => {
1970
+ this.#processError = error;
1971
+ this.finish();
1972
+ });
1973
+ this.process.on("close", () => {
1974
+ this.finish();
1975
+ });
1976
+ }
1977
+ sendCommand(command) {
1978
+ if (isChildClosed(this.process)) throw new Error("control-mode process has exited");
1979
+ try {
1980
+ this.process.stdin.write(command);
1981
+ if (!command.endsWith("\n")) this.process.stdin.write("\n");
1982
+ } catch (error) {
1983
+ throw new Error(`failed to write control-mode command: ${errorMessage$1(error)}`);
1984
+ }
1985
+ }
1986
+ async runCommand(command, timeout = 5) {
1987
+ const releaseReader = this.acquireReader("runCommand");
1988
+ const deadline = deadlineFromNow(timeout);
1989
+ try {
1990
+ this.sendCommand(command);
1991
+ let commandKey;
1992
+ for (;;) {
1993
+ const event = await this.readEventFromLines({ milliseconds: remainingMilliseconds(deadline) });
1994
+ if (event instanceof ControlExit) throw new ControlModeStreamEndedError(`control-mode exited while running ${command}: ${event.reason ?? "unknown reason"}`);
1995
+ if (!(event instanceof ControlNotification)) {
1996
+ this.#deferredEvents.push(event);
1997
+ continue;
1998
+ }
1999
+ if (event.prefix === "%begin") {
2000
+ commandKey = controlCommandKey(event.line);
2001
+ continue;
2002
+ }
2003
+ if (event.prefix !== "%end" && event.prefix !== "%error") continue;
2004
+ const eventKey = controlCommandKey(event.line);
2005
+ if (commandKey !== void 0 && eventKey !== void 0 && eventKey !== commandKey) continue;
2006
+ if (event.prefix === "%error") throw new Error(`control-mode command failed: ${command}; event=${JSON.stringify(event.line)}`);
2007
+ return;
2008
+ }
2009
+ } finally {
2010
+ releaseReader();
2011
+ }
2012
+ }
2013
+ async readEvent(timeout) {
2014
+ const releaseReader = this.acquireReader("readEvent");
2015
+ try {
2016
+ return await this.readEventUnlocked(timeout);
2017
+ } finally {
2018
+ releaseReader();
2019
+ }
2020
+ }
2021
+ async readEventUnlocked(timeout) {
2022
+ const deferred = this.#deferredEvents.shift();
2023
+ if (deferred !== void 0) return deferred;
2024
+ return this.readEventFromLines(timeout);
2025
+ }
2026
+ async readEventFromLines(timeout) {
2027
+ const deadline = timeout === void 0 ? void 0 : deadlineFromNow(timeout);
2028
+ for (;;) {
2029
+ if (this.#ended && this.#lines.isEmpty()) throw this.streamEndedError();
2030
+ const timeoutMs = deadline === void 0 ? void 0 : remainingMilliseconds(deadline);
2031
+ const item = await this.#lines.shift(timeoutMs);
2032
+ if (item.kind === "end") throw this.streamEndedError();
2033
+ const event = parseControlLine(item.line.replace(/\n$/, ""));
2034
+ if (event !== void 0) return event;
2035
+ }
2036
+ }
2037
+ async *events(timeout) {
2038
+ const releaseReader = this.acquireReader("events");
2039
+ try {
2040
+ for (;;) {
2041
+ let event;
2042
+ try {
2043
+ event = await this.readEventUnlocked(timeout);
2044
+ } catch (error) {
2045
+ if (error instanceof ControlModeStreamEndedError) return;
2046
+ throw error;
2047
+ }
2048
+ yield event;
2049
+ if (event instanceof ControlExit) return;
2050
+ }
2051
+ } finally {
2052
+ releaseReader();
2053
+ }
2054
+ }
2055
+ async waitForExit(timeout) {
2056
+ for await (const event of this.events(timeout)) if (event instanceof ControlExit) return event;
2057
+ throw new Error("control-mode stream ended before %exit");
2058
+ }
2059
+ async close() {
2060
+ if (this.#closed) return;
2061
+ this.#closed = true;
2062
+ if (!isChildClosed(this.process)) {
2063
+ try {
2064
+ this.process.stdin.write("\n");
2065
+ this.process.stdin.end();
2066
+ } catch {}
2067
+ try {
2068
+ await waitForChildClose(this.process, 2e3);
2069
+ } catch {
2070
+ this.process.kill("SIGKILL");
2071
+ await waitForChildClose(this.process, 2e3);
2072
+ }
2073
+ }
2074
+ }
2075
+ acquireReader(operation) {
2076
+ if (this.#activeReader !== void 0) throw new Error(`control-mode already has an active reader: ${this.#activeReader}`);
2077
+ this.#activeReader = operation;
2078
+ return () => {
2079
+ if (this.#activeReader === operation) this.#activeReader = void 0;
2080
+ };
2081
+ }
2082
+ feedStdout(chunk) {
2083
+ this.#buffer += chunk;
2084
+ for (;;) {
2085
+ const index = this.#buffer.indexOf("\n");
2086
+ if (index < 0) return;
2087
+ const line = this.#buffer.slice(0, index + 1);
2088
+ this.#buffer = this.#buffer.slice(index + 1);
2089
+ this.#lines.push({
2090
+ kind: "line",
2091
+ line
2092
+ });
2093
+ }
2094
+ }
2095
+ finish() {
2096
+ if (this.#ended) return;
2097
+ this.#ended = true;
2098
+ this.#lines.push({ kind: "end" });
2099
+ }
2100
+ streamEndedError() {
2101
+ if (this.#processError !== void 0) return this.#processError;
2102
+ const stderr = this.#stderr.trim();
2103
+ if (stderr.length > 0) return new ControlModeStreamEndedError(`control-mode stream ended: ${stderr}`);
2104
+ return new ControlModeStreamEndedError("control-mode stream ended");
2105
+ }
2106
+ };
2107
+ function parseControlLine(line) {
2108
+ if (!line.startsWith("%")) return;
2109
+ if (line.startsWith("%output ")) {
2110
+ const [paneId, payload] = splitPayload(line.slice(8));
2111
+ if (paneId === void 0) return new ControlMalformed("%output", line, "missing pane id");
2112
+ return new ControlOutput(paneId, decodeTmuxOctal(payload));
2113
+ }
2114
+ if (line.startsWith("%extended-output ")) {
2115
+ const [paneId, rest] = splitPayload(line.slice(17));
2116
+ if (paneId === void 0) return new ControlMalformed("%extended-output", line, "missing pane id");
2117
+ const [age, payloadRaw] = splitPayload(rest);
2118
+ if (age === void 0) return new ControlMalformed("%extended-output", line, "missing age");
2119
+ const payload = payloadRaw.startsWith(": ") ? payloadRaw.slice(2) : payloadRaw;
2120
+ const ageMs = parseInteger(age);
2121
+ if (ageMs === void 0) return new ControlMalformed("%extended-output", line, "invalid age");
2122
+ return new ControlExtendedOutput(paneId, ageMs, decodeTmuxOctal(payload));
2123
+ }
2124
+ const prefix = line.split(" ", 1)[0] ?? line;
2125
+ if (prefix === "%exit") return new ControlExit(line.slice(5).trim() || void 0);
2126
+ return new ControlNotification(prefix, line);
2127
+ }
2128
+ function decodeTmuxOctal(value) {
2129
+ const chunks = [];
2130
+ let index = 0;
2131
+ while (index < value.length) {
2132
+ if (value[index] === "\\" && index + 3 < value.length && isOctal(value.slice(index + 1, index + 4))) {
2133
+ chunks.push(Number.parseInt(value.slice(index + 1, index + 4), 8));
2134
+ index += 4;
2135
+ continue;
2136
+ }
2137
+ const codePoint = value.codePointAt(index);
2138
+ if (codePoint === void 0) break;
2139
+ chunks.push(...Buffer.from(String.fromCodePoint(codePoint), "utf8"));
2140
+ index += codePoint > 65535 ? 2 : 1;
2141
+ }
2142
+ return Buffer.from(chunks);
2143
+ }
2144
+ function splitPayload(value) {
2145
+ const separator = value.indexOf(" ");
2146
+ if (separator <= 0) return [void 0, ""];
2147
+ return [value.slice(0, separator), value.slice(separator + 1)];
2148
+ }
2149
+ function isOctal(value) {
2150
+ return /^[0-7]{3}$/.test(value);
2151
+ }
2152
+ function parseInteger(value) {
2153
+ if (!/^-?[0-9]+$/.test(value)) return;
2154
+ return Number.parseInt(value, 10);
2155
+ }
2156
+ function controlCommandKey(line) {
2157
+ const parts = line.trim().split(/\s+/);
2158
+ if (parts.length < 4) return;
2159
+ return parts.slice(1, 4).join(" ");
2160
+ }
2161
+ function errorMessage$1(error) {
2162
+ return error instanceof Error ? error.message : String(error);
2163
+ }
2164
+ function waitForChildClose(child, timeoutMs) {
2165
+ if (isChildClosed(child)) return Promise.resolve();
2166
+ return new Promise((resolve, reject) => {
2167
+ const timer = setTimeout(() => {
2168
+ cleanup();
2169
+ reject(/* @__PURE__ */ new Error("timed out waiting for control-mode process"));
2170
+ }, timeoutMs);
2171
+ const onClose = () => {
2172
+ cleanup();
2173
+ resolve();
2174
+ };
2175
+ const cleanup = () => {
2176
+ clearTimeout(timer);
2177
+ child.off("close", onClose);
2178
+ };
2179
+ child.on("close", onClose);
2180
+ });
2181
+ }
2182
+ function isChildClosed(child) {
2183
+ return child.exitCode !== null || child.signalCode !== null;
2184
+ }
2185
+ var AsyncQueue = class {
2186
+ #items = [];
2187
+ #waiters = [];
2188
+ isEmpty() {
2189
+ return this.#items.length === 0;
2190
+ }
2191
+ push(value) {
2192
+ const waiter = this.#waiters.shift();
2193
+ if (waiter !== void 0) {
2194
+ waiter(value);
2195
+ return;
2196
+ }
2197
+ this.#items.push(value);
2198
+ }
2199
+ shift(timeoutMs) {
2200
+ if (this.#items.length > 0) {
2201
+ const item = this.#items.shift();
2202
+ if (item !== void 0) return Promise.resolve(item);
2203
+ }
2204
+ return new Promise((resolve, reject) => {
2205
+ let timer;
2206
+ const waiter = (value) => {
2207
+ if (timer !== void 0) clearTimeout(timer);
2208
+ resolve(value);
2209
+ };
2210
+ this.#waiters.push(waiter);
2211
+ if (timeoutMs !== void 0) timer = setTimeout(() => {
2212
+ const index = this.#waiters.indexOf(waiter);
2213
+ if (index >= 0) this.#waiters.splice(index, 1);
2214
+ reject(/* @__PURE__ */ new Error("timed out waiting for control-mode event"));
2215
+ }, timeoutMs);
2216
+ });
2217
+ }
2218
+ };
2219
+ //#endregion
2220
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/expectations.js
2221
+ var TextMatch = class {
2222
+ text;
2223
+ row;
2224
+ column;
2225
+ constructor(text, row, column) {
2226
+ this.text = text;
2227
+ this.row = row;
2228
+ this.column = column;
2229
+ }
2230
+ };
2231
+ var TextExpectation = class TextExpectation {
2232
+ #pane;
2233
+ #mode;
2234
+ #expected;
2235
+ #interval;
2236
+ constructor(pane, options = {}) {
2237
+ this.#pane = pane;
2238
+ this.#mode = options.mode;
2239
+ this.#expected = options.expected;
2240
+ this.#interval = options.interval ?? .05;
2241
+ }
2242
+ toContain(text, options = {}) {
2243
+ return new TextExpectation(this.#pane, {
2244
+ mode: "contains",
2245
+ expected: text,
2246
+ interval: options.interval ?? .05
2247
+ });
2248
+ }
2249
+ toHaveText(text, options = {}) {
2250
+ return new TextExpectation(this.#pane, {
2251
+ mode: "equals",
2252
+ expected: text,
2253
+ interval: options.interval ?? .05
2254
+ });
2255
+ }
2256
+ async timeout(value) {
2257
+ if (this.#mode === void 0 || this.#expected === void 0) throw new Error("choose an expectation before setting a timeout");
2258
+ if (this.#mode === "contains") return this.#pane.waitForText(this.#expected, {
2259
+ timeout: value,
2260
+ interval: this.#interval
2261
+ });
2262
+ return this.#pane.waitForExactText(this.#expected, {
2263
+ timeout: value,
2264
+ interval: this.#interval
2265
+ });
2266
+ }
2267
+ };
2268
+ function rowColumn(text, index) {
2269
+ const before = text.slice(0, index);
2270
+ const row = countOccurrences(before, "\n");
2271
+ const lineStart = before.lastIndexOf("\n");
2272
+ if (lineStart < 0) return [row, before.length];
2273
+ return [row, before.length - lineStart - 1];
2274
+ }
2275
+ function countOccurrences(text, needle) {
2276
+ let count = 0;
2277
+ let index = text.indexOf(needle);
2278
+ while (index >= 0) {
2279
+ count += 1;
2280
+ index = text.indexOf(needle, index + needle.length);
2281
+ }
2282
+ return count;
2283
+ }
2284
+ //#endregion
2285
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/compatibility.js
2286
+ async function ensureServerCompatible(server) {
2287
+ if (server.checkCompatibility) await server.capabilities();
2288
+ }
2289
+ //#endregion
2290
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/lifecycle.js
2291
+ var PaneExitState = class {
2292
+ dead;
2293
+ status;
2294
+ constructor(dead, status) {
2295
+ this.dead = dead;
2296
+ if (status !== void 0) this.status = status;
2297
+ }
2298
+ };
2299
+ //#endregion
2300
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/locators.js
2301
+ var TextLocator = class TextLocator {
2302
+ pane;
2303
+ text;
2304
+ index;
2305
+ constructor(pane, text, index) {
2306
+ this.pane = pane;
2307
+ this.text = text;
2308
+ if (index !== void 0) this.index = index;
2309
+ }
2310
+ async all() {
2311
+ return (await this.pane.snapshot()).findAllText(this.text);
2312
+ }
2313
+ async count() {
2314
+ return (await this.all()).length;
2315
+ }
2316
+ first() {
2317
+ return new TextLocator(this.pane, this.text, 0);
2318
+ }
2319
+ last() {
2320
+ return new TextLocator(this.pane, this.text, -1);
2321
+ }
2322
+ nth(index) {
2323
+ return new TextLocator(this.pane, this.text, index);
2324
+ }
2325
+ async isVisible() {
2326
+ return this.resolve(await this.all()) !== void 0;
2327
+ }
2328
+ expect() {
2329
+ return new LocatorExpectation(this);
2330
+ }
2331
+ resolve(matches) {
2332
+ if (this.index === void 0) return matches[0];
2333
+ return matches[this.index < 0 ? matches.length + this.index : this.index];
2334
+ }
2335
+ };
2336
+ var LocatorExpectation = class LocatorExpectation {
2337
+ #locator;
2338
+ #mode;
2339
+ #expected;
2340
+ #interval;
2341
+ constructor(locator, options = {}) {
2342
+ this.#locator = locator;
2343
+ this.#mode = options.mode;
2344
+ this.#expected = options.expected;
2345
+ this.#interval = options.interval ?? .05;
2346
+ }
2347
+ toBeVisible(options = {}) {
2348
+ return new LocatorExpectation(this.#locator, {
2349
+ mode: "visible",
2350
+ interval: options.interval ?? .05
2351
+ });
2352
+ }
2353
+ toHaveText(text, options = {}) {
2354
+ return new LocatorExpectation(this.#locator, {
2355
+ mode: "text",
2356
+ expected: text,
2357
+ interval: options.interval ?? .05
2358
+ });
2359
+ }
2360
+ toHaveCount(count, options = {}) {
2361
+ return new LocatorExpectation(this.#locator, {
2362
+ mode: "count",
2363
+ expected: count,
2364
+ interval: options.interval ?? .05
2365
+ });
2366
+ }
2367
+ async timeout(value) {
2368
+ if (this.#mode === void 0) throw new Error("choose an expectation before setting a timeout");
2369
+ const deadline = deadlineFromNow(value);
2370
+ const intervalMs = durationMilliseconds(this.#interval);
2371
+ let lastCount = 0;
2372
+ for (;;) {
2373
+ const matches = await this.#locator.all();
2374
+ lastCount = matches.length;
2375
+ const match = this.#locator.resolve(matches);
2376
+ if (this.#mode === "visible" && match !== void 0) return match;
2377
+ if (this.#mode === "text" && match !== void 0 && match.text === this.#expected) return match;
2378
+ if (this.#mode === "count" && lastCount === this.#expected) return lastCount;
2379
+ if (deadlineExpired(deadline)) throw new Error(this.failureMessage(lastCount));
2380
+ await sleep(intervalMs);
2381
+ }
2382
+ }
2383
+ failureMessage(lastCount) {
2384
+ if (this.#mode === "visible") return `text not visible before timeout: ${JSON.stringify(this.#locator.text)}`;
2385
+ if (this.#mode === "text") return `text locator did not resolve to expected text before timeout: ${JSON.stringify(this.#locator.text)} != ${JSON.stringify(this.#expected)}`;
2386
+ if (this.#mode === "count") return `text locator count did not match before timeout: ${lastCount} != ${this.#expected}`;
2387
+ return "locator expectation failed before timeout";
2388
+ }
2389
+ };
2390
+ //#endregion
2391
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/snapshot.js
2392
+ var PaneSnapshot = class {
2393
+ visibleText;
2394
+ constructor(visibleText) {
2395
+ this.visibleText = visibleText;
2396
+ }
2397
+ get visible_text() {
2398
+ return this.visibleText;
2399
+ }
2400
+ get lines() {
2401
+ return this.visibleText.split(/\r?\n/).filter((line, index, lines) => {
2402
+ return index < lines.length - 1 || line.length > 0;
2403
+ });
2404
+ }
2405
+ rowText(row) {
2406
+ const line = this.lines[row];
2407
+ if (line === void 0) throw new RangeError(`row is outside the snapshot: ${row}`);
2408
+ return line;
2409
+ }
2410
+ findText(text) {
2411
+ const index = this.visibleText.indexOf(text);
2412
+ if (index < 0) return;
2413
+ const [row, column] = rowColumn(this.visibleText, index);
2414
+ return new TextMatch(text, row, column);
2415
+ }
2416
+ findAllText(text) {
2417
+ if (text.length === 0) return [];
2418
+ const matches = [];
2419
+ let start = 0;
2420
+ for (;;) {
2421
+ const index = this.visibleText.indexOf(text, start);
2422
+ if (index < 0) return matches;
2423
+ const [row, column] = rowColumn(this.visibleText, index);
2424
+ matches.push(new TextMatch(text, row, column));
2425
+ start = index + text.length;
2426
+ }
2427
+ }
2428
+ };
2429
+ //#endregion
2430
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/streams.js
2431
+ var PaneOutputChunk = class {
2432
+ paneId;
2433
+ data;
2434
+ ageMs;
2435
+ constructor(paneId, data, ageMs) {
2436
+ this.paneId = paneId;
2437
+ this.data = data;
2438
+ if (ageMs !== void 0) this.ageMs = ageMs;
2439
+ }
2440
+ get pane_id() {
2441
+ return this.paneId;
2442
+ }
2443
+ get age_ms() {
2444
+ return this.ageMs;
2445
+ }
2446
+ };
2447
+ var PaneOutputStream = class PaneOutputStream {
2448
+ #paneId;
2449
+ #control;
2450
+ constructor(paneId, control) {
2451
+ this.#paneId = paneId;
2452
+ this.#control = control;
2453
+ }
2454
+ static async open(pane) {
2455
+ const paneId = await pane.id();
2456
+ const control = new ControlModeClient(await pane.server.controlMode());
2457
+ try {
2458
+ await control.runCommand(`attach-session -t ${paneId}`);
2459
+ } catch (error) {
2460
+ await control.close();
2461
+ throw error;
2462
+ }
2463
+ return new PaneOutputStream(paneId, control);
2464
+ }
2465
+ async close() {
2466
+ await this.#control.close();
2467
+ }
2468
+ async next(timeout) {
2469
+ const deadline = timeout === void 0 ? void 0 : deadlineFromNow(timeout);
2470
+ for (;;) {
2471
+ const event = await this.#control.readEvent(deadline === void 0 ? void 0 : { milliseconds: remainingMilliseconds(deadline) });
2472
+ if (event instanceof ControlExit) throw new Error("control-mode stream exited");
2473
+ if (event instanceof ControlOutput || event instanceof ControlExtendedOutput) {
2474
+ if (this.#paneId === void 0 || event.paneId === this.#paneId) return new PaneOutputChunk(event.paneId, event.data, event instanceof ControlExtendedOutput ? event.ageMs : void 0);
2475
+ }
2476
+ }
2477
+ }
2478
+ };
2479
+ var PaneLineStream = class {
2480
+ #output;
2481
+ #buffer = [];
2482
+ #pending = [];
2483
+ constructor(output) {
2484
+ this.#output = output;
2485
+ }
2486
+ async close() {
2487
+ await this.#output.close();
2488
+ }
2489
+ async next(timeout) {
2490
+ const deadline = timeout === void 0 ? void 0 : deadlineFromNow(timeout);
2491
+ for (;;) {
2492
+ const pending = this.#pending.shift();
2493
+ if (pending !== void 0) return pending;
2494
+ const chunk = await this.#output.next(deadline === void 0 ? void 0 : { milliseconds: remainingMilliseconds(deadline) });
2495
+ this.feed(chunk.data);
2496
+ }
2497
+ }
2498
+ feed(data) {
2499
+ for (const byte of data) if (byte === 10) {
2500
+ let line = Buffer.from(this.#buffer);
2501
+ this.#buffer.length = 0;
2502
+ if (line.at(-1) === 13) line = line.subarray(0, -1);
2503
+ this.#pending.push(line.toString("utf8"));
2504
+ } else this.#buffer.push(byte);
2505
+ }
2506
+ };
2507
+ var PaneRenderStream = class PaneRenderStream {
2508
+ #pane;
2509
+ #output;
2510
+ constructor(pane, output) {
2511
+ this.#pane = pane;
2512
+ this.#output = output;
2513
+ }
2514
+ static async open(pane) {
2515
+ return new PaneRenderStream(pane, await pane.outputStream());
2516
+ }
2517
+ async close() {
2518
+ await this.#output.close();
2519
+ }
2520
+ async next(timeout) {
2521
+ await this.#output.next(timeout);
2522
+ return this.#pane.snapshot();
2523
+ }
2524
+ };
2525
+ //#endregion
2526
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/validation.js
2527
+ function requiredString(value, context, field) {
2528
+ if (typeof value === "string" && value.length > 0) return value;
2529
+ throw new TypeError(`${context} is missing non-empty string field ${JSON.stringify(field)}`);
2530
+ }
2531
+ function requiredInteger(value, context, field) {
2532
+ if (typeof value === "number" && Number.isInteger(value)) return value;
2533
+ throw new TypeError(`${context} is missing integer field ${JSON.stringify(field)}`);
2534
+ }
2535
+ function requiredPaneId(value, context) {
2536
+ const paneId = requiredString(value, context, "pane_id");
2537
+ if (/^%[0-9]+$/.test(paneId)) return paneId;
2538
+ throw new TypeError(`${context} has invalid pane_id ${JSON.stringify(paneId)}`);
2539
+ }
2540
+ function requiredSessionId(value, context) {
2541
+ const sessionId = requiredString(value, context, "session_id");
2542
+ if (/^\$[0-9]+$/.test(sessionId)) return sessionId;
2543
+ throw new TypeError(`${context} has invalid session_id ${JSON.stringify(sessionId)}`);
2544
+ }
2545
+ function parseRequiredInteger(value, context) {
2546
+ if (/^-?[0-9]+$/.test(value)) return Number.parseInt(value, 10);
2547
+ throw new TypeError(`${context} is not an integer: ${JSON.stringify(value)}`);
2548
+ }
2549
+ function parsePaneId(value, context) {
2550
+ const paneId = value.trim();
2551
+ if (/^%[0-9]+$/.test(paneId)) return paneId;
2552
+ throw new TypeError(`${context} did not return a pane id: ${JSON.stringify(value)}`);
2553
+ }
2554
+ function parseWindowIndex(value, context) {
2555
+ const parsed = parseRequiredInteger(value.trim(), context);
2556
+ if (parsed < 0) throw new TypeError(`${context} must be non-negative: ${JSON.stringify(value)}`);
2557
+ return parsed;
2558
+ }
2559
+ function isJsonObject(value) {
2560
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2561
+ }
2562
+ //#endregion
2563
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/pane.js
2564
+ var Pane = class Pane {
2565
+ server;
2566
+ target;
2567
+ constructor(server, target) {
2568
+ this.server = server;
2569
+ this.target = target;
2570
+ }
2571
+ async sendKeys(...keys) {
2572
+ return this.server.sendKeys(this.target, ...keys);
2573
+ }
2574
+ async sendText(text) {
2575
+ return this.server.sendText(this.target, text);
2576
+ }
2577
+ async select() {
2578
+ await ensureServerCompatible(this.server);
2579
+ return this.server.cmd("select-pane", "-t", this.target, { check: true });
2580
+ }
2581
+ async resize(options) {
2582
+ await ensureServerCompatible(this.server);
2583
+ const args = [
2584
+ "resize-pane",
2585
+ "-t",
2586
+ this.target
2587
+ ];
2588
+ if (options.width !== void 0) args.push("-x", options.width);
2589
+ if (options.height !== void 0) args.push("-y", options.height);
2590
+ return this.server.cmd(...args, { check: true });
2591
+ }
2592
+ async split(options = {}) {
2593
+ await ensureServerCompatible(this.server);
2594
+ const direction = options.direction ?? "vertical";
2595
+ const args = [
2596
+ "split-window",
2597
+ "-P",
2598
+ "-F",
2599
+ "#{pane_id}",
2600
+ "-t",
2601
+ this.target
2602
+ ];
2603
+ if (direction === "horizontal" || direction === "h") args.push("-h");
2604
+ else if (direction === "vertical" || direction === "v") args.push("-v");
2605
+ else throw new Error("direction must be 'horizontal' or 'vertical'");
2606
+ if (options.size !== void 0) args.push("-l", options.size);
2607
+ if (options.shellCommand !== void 0) args.push(options.shellCommand);
2608
+ const run = await this.server.cmd(...args, { check: true });
2609
+ return new Pane(this.server, parsePaneId(run.stdout, "split-window output"));
2610
+ }
2611
+ async respawn(options = {}) {
2612
+ await ensureServerCompatible(this.server);
2613
+ const args = [
2614
+ "respawn-pane",
2615
+ "-t",
2616
+ this.target
2617
+ ];
2618
+ if (options.kill) args.push("-k");
2619
+ if (options.shellCommand !== void 0) args.push(options.shellCommand);
2620
+ return this.server.cmd(...args, { check: true });
2621
+ }
2622
+ async close() {
2623
+ await ensureServerCompatible(this.server);
2624
+ return this.server.cmd("kill-pane", "-t", this.target, { check: true });
2625
+ }
2626
+ async capture(options = {}) {
2627
+ return this.server.capturePane({
2628
+ target: this.target,
2629
+ ...options
2630
+ });
2631
+ }
2632
+ async captureText(options = {}) {
2633
+ return (await this.snapshot(options)).visibleText;
2634
+ }
2635
+ async snapshot(options = {}) {
2636
+ return new PaneSnapshot(await this.capture(options));
2637
+ }
2638
+ getByText(text) {
2639
+ return new TextLocator(this, text);
2640
+ }
2641
+ locator(text) {
2642
+ return this.getByText(text);
2643
+ }
2644
+ async id() {
2645
+ await ensureServerCompatible(this.server);
2646
+ return parsePaneId((await this.server.cmd("display-message", "-p", "-t", this.target, "#{pane_id}", { check: true })).stdout, "display-message #{pane_id}");
2647
+ }
2648
+ async outputStream() {
2649
+ return PaneOutputStream.open(this);
2650
+ }
2651
+ async lineStream() {
2652
+ return new PaneLineStream(await this.outputStream());
2653
+ }
2654
+ async renderStream() {
2655
+ return PaneRenderStream.open(this);
2656
+ }
2657
+ async waitForText(text, options = {}) {
2658
+ return this.waitForTextInner(text, false, options.timeout ?? 5, options.interval ?? .05);
2659
+ }
2660
+ async waitForExactText(text, options = {}) {
2661
+ return this.waitForTextInner(text, true, options.timeout ?? 5, options.interval ?? .05);
2662
+ }
2663
+ expectVisibleText() {
2664
+ return new TextExpectation(this);
2665
+ }
2666
+ async waitForExit(options = {}) {
2667
+ const timeout = options.timeout ?? 5;
2668
+ const intervalMs = durationMilliseconds(options.interval ?? .05);
2669
+ const deadline = deadlineFromNow(timeout);
2670
+ for (;;) {
2671
+ const state = await this.exitState();
2672
+ if (state.dead) return state;
2673
+ if (deadlineExpired(deadline)) throw new Error(`pane did not exit before timeout: ${this.target}`);
2674
+ await sleep(intervalMs);
2675
+ }
2676
+ }
2677
+ async waitForTextInner(text, exact, timeout, interval) {
2678
+ const intervalMs = durationMilliseconds(interval);
2679
+ const deadline = deadlineFromNow(timeout);
2680
+ for (;;) {
2681
+ const captured = await this.captureText();
2682
+ if (exact) {
2683
+ if (captured.replace(/\n+$/, "") === text) {
2684
+ const found = captured.indexOf(text);
2685
+ const [row, column] = rowColumn(captured, found < 0 ? 0 : found);
2686
+ return new TextMatch(text, row, column);
2687
+ }
2688
+ } else {
2689
+ const found = captured.indexOf(text);
2690
+ if (found >= 0) {
2691
+ const [row, column] = rowColumn(captured, found);
2692
+ return new TextMatch(text, row, column);
2693
+ }
2694
+ }
2695
+ if (deadlineExpired(deadline)) throw new Error(`text not found before timeout: ${JSON.stringify(text)}`);
2696
+ await sleep(intervalMs);
2697
+ }
2698
+ }
2699
+ async exitState() {
2700
+ await ensureServerCompatible(this.server);
2701
+ const output = (await this.server.cmd("display-message", "-p", "-t", this.target, "#{pane_dead}:#{pane_dead_status}", { check: true })).stdout.trim();
2702
+ const separator = output.indexOf(":");
2703
+ const dead = separator < 0 ? output : output.slice(0, separator);
2704
+ const status = separator < 0 ? "" : output.slice(separator + 1);
2705
+ if (dead !== "1" && dead !== "true") return new PaneExitState(false);
2706
+ return new PaneExitState(true, parseExitStatus(status));
2707
+ }
2708
+ };
2709
+ function parseExitStatus(value) {
2710
+ if (!/^[0-9]+$/.test(value)) return;
2711
+ return Number.parseInt(value, 10);
2712
+ }
2713
+ //#endregion
2714
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/window.js
2715
+ var Window = class {
2716
+ server;
2717
+ sessionName;
2718
+ sessionTarget;
2719
+ index;
2720
+ constructor(server, sessionName, sessionTarget, index) {
2721
+ this.server = server;
2722
+ this.sessionName = sessionName;
2723
+ this.sessionTarget = sessionTarget;
2724
+ this.index = index;
2725
+ }
2726
+ get target() {
2727
+ return `${this.sessionTarget}:${this.index}`;
2728
+ }
2729
+ async listPanes() {
2730
+ return this.server.listPanes({ target: this.target });
2731
+ }
2732
+ async panes() {
2733
+ const panes = [];
2734
+ for (const [index, pane] of (await this.listPanes()).entries()) panes.push(new Pane(this.server, requiredPaneId(pane["pane_id"], `list-panes row ${index}`)));
2735
+ return panes;
2736
+ }
2737
+ pane(index) {
2738
+ return new Pane(this.server, `${this.target}.${index}`);
2739
+ }
2740
+ async select() {
2741
+ await ensureServerCompatible(this.server);
2742
+ return this.server.cmd("select-window", "-t", this.target, { check: true });
2743
+ }
2744
+ async rename(name) {
2745
+ await ensureServerCompatible(this.server);
2746
+ return this.server.cmd("rename-window", "-t", this.target, name, { check: true });
2747
+ }
2748
+ async resize(options) {
2749
+ await ensureServerCompatible(this.server);
2750
+ const args = [
2751
+ "resize-window",
2752
+ "-t",
2753
+ this.target
2754
+ ];
2755
+ if (options.width !== void 0) args.push("-x", options.width);
2756
+ if (options.height !== void 0) args.push("-y", options.height);
2757
+ return this.server.cmd(...args, { check: true });
2758
+ }
2759
+ async selectLayout(layout) {
2760
+ await ensureServerCompatible(this.server);
2761
+ return this.server.cmd("select-layout", "-t", this.target, layout, { check: true });
2762
+ }
2763
+ async close() {
2764
+ await ensureServerCompatible(this.server);
2765
+ return this.server.cmd("kill-window", "-t", this.target, { check: true });
2766
+ }
2767
+ };
2768
+ //#endregion
2769
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/handles/session.js
2770
+ var Session = class Session {
2771
+ server;
2772
+ name;
2773
+ target;
2774
+ constructor(server, name, target = name) {
2775
+ this.server = server;
2776
+ this.name = name;
2777
+ this.target = target;
2778
+ }
2779
+ async listWindows() {
2780
+ return this.server.listWindows({ target: this.target });
2781
+ }
2782
+ async windows() {
2783
+ return (await this.listWindows()).map((window) => {
2784
+ return new Window(this.server, this.name, this.target, requiredInteger(window["window_index"], "list-windows row", "window_index"));
2785
+ });
2786
+ }
2787
+ window(index) {
2788
+ return new Window(this.server, this.name, this.target, index);
2789
+ }
2790
+ pane(windowIndex = 0, paneIndex = 0) {
2791
+ return this.window(windowIndex).pane(paneIndex);
2792
+ }
2793
+ async rename(name) {
2794
+ await ensureServerCompatible(this.server);
2795
+ await this.server.cmd("rename-session", "-t", this.target, name, { check: true });
2796
+ return new Session(this.server, name, this.target.startsWith("$") ? this.target : name);
2797
+ }
2798
+ async kill() {
2799
+ await ensureServerCompatible(this.server);
2800
+ return this.server.cmd("kill-session", "-t", this.target, { check: true });
2801
+ }
2802
+ async newWindow(options = {}) {
2803
+ await ensureServerCompatible(this.server);
2804
+ const args = [
2805
+ "new-window",
2806
+ "-P",
2807
+ "-F",
2808
+ "#{window_index}",
2809
+ "-t",
2810
+ this.target
2811
+ ];
2812
+ if (options.detached ?? true) args.push("-d");
2813
+ if (options.name !== void 0) args.push("-n", options.name);
2814
+ if (options.shellCommand !== void 0) args.push(options.shellCommand);
2815
+ const run = await this.server.cmd(...args, { check: true });
2816
+ return new Window(this.server, this.name, this.target, parseWindowIndex(run.stdout, "new-window output"));
2817
+ }
2818
+ };
2819
+ //#endregion
2820
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/pane-set.js
2821
+ var PaneSetOutcome = class {
2822
+ matched;
2823
+ snapshots;
2824
+ constructor(matched, snapshots) {
2825
+ this.matched = [...matched];
2826
+ this.snapshots = [...snapshots];
2827
+ }
2828
+ };
2829
+ var PaneSet = class {
2830
+ panes;
2831
+ constructor(panes) {
2832
+ this.panes = [...panes];
2833
+ }
2834
+ get length() {
2835
+ return this.panes.length;
2836
+ }
2837
+ [Symbol.iterator]() {
2838
+ return this.panes[Symbol.iterator]();
2839
+ }
2840
+ isEmpty() {
2841
+ return this.panes.length === 0;
2842
+ }
2843
+ async broadcastText(text) {
2844
+ return Promise.all(this.panes.map((pane) => pane.sendText(text)));
2845
+ }
2846
+ async broadcastKey(key) {
2847
+ return Promise.all(this.panes.map((pane) => pane.sendKeys(key)));
2848
+ }
2849
+ async snapshotAll() {
2850
+ const snapshots = [];
2851
+ for (const pane of this.panes) snapshots.push(await pane.snapshot());
2852
+ return snapshots;
2853
+ }
2854
+ expectAll() {
2855
+ return new PaneSetExpectation(this, "all");
2856
+ }
2857
+ expectAny() {
2858
+ return new PaneSetExpectation(this, "any");
2859
+ }
2860
+ waitAll() {
2861
+ return this.expectAll();
2862
+ }
2863
+ waitAny() {
2864
+ return this.expectAny();
2865
+ }
2866
+ };
2867
+ var PaneSetExpectation = class PaneSetExpectation {
2868
+ #paneSet;
2869
+ #mode;
2870
+ #text;
2871
+ #interval;
2872
+ constructor(paneSet, mode, options = {}) {
2873
+ this.#paneSet = paneSet;
2874
+ this.#mode = mode;
2875
+ this.#text = options.text;
2876
+ this.#interval = options.interval ?? .05;
2877
+ }
2878
+ visibleTextContains(text, options = {}) {
2879
+ return new PaneSetExpectation(this.#paneSet, this.#mode, {
2880
+ text,
2881
+ interval: options.interval ?? .05
2882
+ });
2883
+ }
2884
+ async timeout(value) {
2885
+ if (this.#text === void 0) throw new Error("choose an expectation before setting a timeout");
2886
+ const deadline = deadlineFromNow(value);
2887
+ const intervalMs = durationMilliseconds(this.#interval);
2888
+ for (;;) {
2889
+ const matched = [];
2890
+ const snapshots = [];
2891
+ for (const pane of this.#paneSet) {
2892
+ const snapshot = await pane.snapshot();
2893
+ if (snapshot.visibleText.includes(this.#text)) {
2894
+ matched.push(pane);
2895
+ snapshots.push(snapshot);
2896
+ }
2897
+ }
2898
+ if (this.#mode === "all" && matched.length === this.#paneSet.length) return new PaneSetOutcome(matched, snapshots);
2899
+ if (this.#mode === "any" && matched.length > 0) return new PaneSetOutcome(matched, snapshots);
2900
+ if (deadlineExpired(deadline)) throw new Error(`pane set did not match visible text before timeout: ${JSON.stringify(this.#text)}`);
2901
+ await sleep(intervalMs);
2902
+ }
2903
+ }
2904
+ };
2905
+ //#endregion
2906
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/builder.js
2907
+ var RmuxBuilder = class {
2908
+ #binary = "rmux";
2909
+ #socketPath;
2910
+ #socketName;
2911
+ #checkCompatibility = true;
2912
+ #env;
2913
+ #cwd;
2914
+ binary(value) {
2915
+ this.#binary = value;
2916
+ return this;
2917
+ }
2918
+ socketPath(value) {
2919
+ this.#socketPath = value;
2920
+ this.#socketName = void 0;
2921
+ return this;
2922
+ }
2923
+ socketName(value) {
2924
+ this.#socketName = value;
2925
+ this.#socketPath = void 0;
2926
+ return this;
2927
+ }
2928
+ checkCompatibility(enabled) {
2929
+ this.#checkCompatibility = enabled;
2930
+ return this;
2931
+ }
2932
+ env(value) {
2933
+ this.#env = value === void 0 ? void 0 : { ...value };
2934
+ return this;
2935
+ }
2936
+ cwd(value) {
2937
+ this.#cwd = value;
2938
+ return this;
2939
+ }
2940
+ async connectOrStart() {
2941
+ const rmux = new Rmux({
2942
+ binary: this.#binary,
2943
+ socketPath: this.#socketPath,
2944
+ socketName: this.#socketName,
2945
+ checkCompatibility: this.#checkCompatibility,
2946
+ env: this.#env,
2947
+ cwd: this.#cwd
2948
+ });
2949
+ await rmux.startServer();
2950
+ if (this.#checkCompatibility) await rmux.capabilities();
2951
+ return rmux;
2952
+ }
2953
+ };
2954
+ //#endregion
2955
+ //#region ../../../node_modules/.pnpm/@rmux+sdk@0.6.5/node_modules/@rmux/sdk/dist/trace.js
2956
+ var RmuxTraceBuilder = class {
2957
+ #maxEvents = 1e5;
2958
+ maxEvents(value) {
2959
+ if (!Number.isInteger(value) || value < 0) throw new RangeError("maxEvents must be a non-negative integer");
2960
+ this.#maxEvents = value;
2961
+ return this;
2962
+ }
2963
+ start() {
2964
+ const trace = new TraceSession(this.#maxEvents);
2965
+ trace.record("trace.start", {});
2966
+ return trace;
2967
+ }
2968
+ };
2969
+ var TraceSession = class {
2970
+ #maxEvents;
2971
+ #events = [];
2972
+ constructor(maxEvents) {
2973
+ this.#maxEvents = maxEvents;
2974
+ }
2975
+ recordAction(action) {
2976
+ this.record("action", { action });
2977
+ }
2978
+ async recordSnapshot(pane) {
2979
+ const snapshot = await pane.snapshot();
2980
+ this.record("snapshot", {
2981
+ pane: pane.target,
2982
+ visible_text: snapshot.visibleText
2983
+ });
2984
+ }
2985
+ async stop(directory) {
2986
+ this.record("trace.stop", {});
2987
+ await (0, node_fs_promises.mkdir)(directory, { recursive: true });
2988
+ const output = (0, node_path.join)(directory, "trace.jsonl");
2989
+ const content = this.#events.length === 0 ? "" : this.#events.map((event) => JSON.stringify(event)).join("\n") + "\n";
2990
+ await (0, node_fs_promises.writeFile)(output, content, "utf8");
2991
+ return output;
2992
+ }
2993
+ record(kind, payload) {
2994
+ const jsonPayload = copyJsonObject(payload, "payload");
2995
+ if (this.#maxEvents <= 0) return;
2996
+ if (this.#events.length === this.#maxEvents) this.#events.shift();
2997
+ this.#events.push({
2998
+ timestamp_ms: Date.now(),
2999
+ kind,
3000
+ payload: jsonPayload
3001
+ });
3002
+ }
3003
+ };
3004
+ function copyJsonObject(value, path) {
3005
+ if (!isPlainObject(value)) throw new TypeError(`${path} must be a JSON object`);
3006
+ const copy = {};
3007
+ for (const [key, item] of Object.entries(value)) copy[key] = copyJsonValue(item, `${path}.${key}`);
3008
+ return copy;
3009
+ }
3010
+ function copyJsonValue(value, path) {
3011
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
3012
+ if (typeof value === "number") {
3013
+ if (!Number.isFinite(value)) throw new TypeError(`${path} must be a finite JSON number`);
3014
+ return value;
3015
+ }
3016
+ if (Array.isArray(value)) return value.map((item, index) => copyJsonValue(item, `${path}[${index}]`));
3017
+ return copyJsonObject(value, path);
3018
+ }
3019
+ function isPlainObject(value) {
3020
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
3021
+ const prototype = Object.getPrototypeOf(value);
3022
+ return prototype === Object.prototype || prototype === null;
3023
+ }
3024
+ var Rmux = class {
3025
+ binary;
3026
+ socketPath;
3027
+ socketName;
3028
+ checkCompatibility;
3029
+ env;
3030
+ cwd;
3031
+ #capabilities;
3032
+ static builder() {
3033
+ return new RmuxBuilder();
3034
+ }
3035
+ constructor(options = {}) {
3036
+ if (options.socketPath !== void 0 && options.socketName !== void 0) throw new Error("choose only one of socketPath or socketName");
3037
+ this.binary = options.binary ?? "rmux";
3038
+ this.socketPath = options.socketPath;
3039
+ this.socketName = options.socketName;
3040
+ this.checkCompatibility = options.checkCompatibility ?? true;
3041
+ this.env = options.env === void 0 ? void 0 : { ...options.env };
3042
+ this.cwd = options.cwd;
3043
+ }
3044
+ async cmd(...argsAndOptions) {
3045
+ const { args, options } = splitCommandArguments(argsAndOptions);
3046
+ const argv = this.argv(args);
3047
+ const completed = await runProcess(argv, {
3048
+ cwd: this.cwd,
3049
+ env: this.env
3050
+ });
3051
+ const run = new CommandRun(argv, completed.code, completed.stdout, completed.stderr, completed.signal);
3052
+ if (options.check) run.checkReturnCode();
3053
+ return run;
3054
+ }
3055
+ async capabilities() {
3056
+ if (this.#capabilities === void 0) {
3057
+ const capabilities = await this.jsonObject("capabilities", "--json");
3058
+ if (this.checkCompatibility) this.validateCapabilities(capabilities);
3059
+ this.#capabilities = capabilities;
3060
+ }
3061
+ return { ...this.#capabilities };
3062
+ }
3063
+ async startServer() {
3064
+ return this.cmd("start-server", { check: true });
3065
+ }
3066
+ async killServer(options = {}) {
3067
+ return this.cmd("kill-server", { check: options.check ?? false });
3068
+ }
3069
+ async listSessions() {
3070
+ await this.ensureCompatible();
3071
+ return this.jsonList("list-sessions", "--json");
3072
+ }
3073
+ async sessions() {
3074
+ return (await this.listSessions()).map((session, index) => {
3075
+ return this.sessionFromRow(session, `list-sessions row ${index}`);
3076
+ });
3077
+ }
3078
+ session(name) {
3079
+ return new Session(this, name);
3080
+ }
3081
+ async ensureSession(name, options = {}) {
3082
+ await this.ensureCompatible();
3083
+ if ((await this.cmd("has-session", "-t", name)).returnCode !== 0) {
3084
+ const args = ["new-session"];
3085
+ if (options.detached ?? true) args.push("-d");
3086
+ args.push("-s", name);
3087
+ if (options.shellCommand !== void 0) args.push(options.shellCommand);
3088
+ await this.cmd(...args, { check: true });
3089
+ }
3090
+ return this.sessionForTarget(name, name);
3091
+ }
3092
+ async listWindows(options = {}) {
3093
+ await this.ensureCompatible();
3094
+ const args = ["list-windows"];
3095
+ if (options.allSessions) args.push("-a");
3096
+ if (options.target !== void 0) args.push("-t", options.target);
3097
+ args.push("--json");
3098
+ return this.jsonList(...args);
3099
+ }
3100
+ async listPanes(options = {}) {
3101
+ await this.ensureCompatible();
3102
+ const args = ["list-panes"];
3103
+ if (options.allSessions) args.push("-a");
3104
+ if (options.target !== void 0) args.push("-t", options.target);
3105
+ args.push("--json");
3106
+ return this.jsonList(...args);
3107
+ }
3108
+ async listClients(options = {}) {
3109
+ await this.ensureCompatible();
3110
+ const args = ["list-clients"];
3111
+ if (options.targetSession !== void 0) args.push("-t", options.targetSession);
3112
+ args.push("--json");
3113
+ return this.jsonList(...args);
3114
+ }
3115
+ async sendKeys(target, ...keys) {
3116
+ await this.ensureCompatible();
3117
+ return this.cmd("send-keys", "-t", target, ...keys, { check: true });
3118
+ }
3119
+ async sendText(target, text) {
3120
+ await this.ensureCompatible();
3121
+ return this.cmd("send-keys", "-t", target, "-l", text, { check: true });
3122
+ }
3123
+ async displayMessage(message, options = {}) {
3124
+ await this.ensureCompatible();
3125
+ const args = ["display-message", "--json"];
3126
+ if (options.target !== void 0) args.push("-t", options.target);
3127
+ args.push(message);
3128
+ return this.jsonObject(...args);
3129
+ }
3130
+ async capturePane(options = {}) {
3131
+ await this.ensureCompatible();
3132
+ const args = ["capture-pane", "-p"];
3133
+ if (options.target !== void 0) args.push("-t", options.target);
3134
+ if (options.start !== void 0) args.push("-S", options.start);
3135
+ if (options.end !== void 0) args.push("-E", options.end);
3136
+ if (options.escapeAnsi) args.push("-e");
3137
+ if (options.joinWrapped) args.push("-J");
3138
+ return (await this.cmd(...args, { check: true })).stdout;
3139
+ }
3140
+ async controlMode() {
3141
+ await this.ensureCompatible();
3142
+ const process = spawnControlProcess({
3143
+ binary: this.binary,
3144
+ args: this.endpointArgs(["-C"]),
3145
+ cwd: this.cwd,
3146
+ env: this.env
3147
+ });
3148
+ await waitForControlProcessSpawn(process);
3149
+ return process;
3150
+ }
3151
+ async control() {
3152
+ return new ControlModeClient(await this.controlMode());
3153
+ }
3154
+ paneSet(panes) {
3155
+ return new PaneSet(panes);
3156
+ }
3157
+ async broadcastText(panes, text) {
3158
+ return this.paneSet(panes).broadcastText(text);
3159
+ }
3160
+ async broadcastKey(panes, key) {
3161
+ return this.paneSet(panes).broadcastKey(key);
3162
+ }
3163
+ tracing() {
3164
+ return new RmuxTraceBuilder();
3165
+ }
3166
+ async jsonList(...args) {
3167
+ const value = await this.jsonValue(...args);
3168
+ if (!Array.isArray(value)) throw new TypeError("rmux JSON response is not an array");
3169
+ return value.map((item) => {
3170
+ if (!isJsonObject(item)) throw new TypeError("rmux JSON array contains a non-object item");
3171
+ return item;
3172
+ });
3173
+ }
3174
+ async jsonObject(...args) {
3175
+ const value = await this.jsonValue(...args);
3176
+ if (!isJsonObject(value)) throw new TypeError("rmux JSON response is not an object");
3177
+ return value;
3178
+ }
3179
+ async jsonValue(...args) {
3180
+ const run = await this.cmd(...args, { check: true });
3181
+ try {
3182
+ return JSON.parse(run.stdout);
3183
+ } catch (error) {
3184
+ throw new TypeError(`rmux returned invalid JSON for ${args.map(String).join(" ")}: ${errorMessage(error)}`);
3185
+ }
3186
+ }
3187
+ async ensureCompatible() {
3188
+ if (this.checkCompatibility) await this.capabilities();
3189
+ }
3190
+ async sessionForTarget(target, fallbackName) {
3191
+ const sessionId = requiredSessionId((await this.displayMessage("#{session_id}", { target }))["message"], `display-message #{session_id} for ${JSON.stringify(target)}`);
3192
+ const row = (await this.listSessions()).find((session) => {
3193
+ return session["session_id"] === sessionId;
3194
+ });
3195
+ if (row !== void 0) return this.sessionFromRow(row, `session ${sessionId}`);
3196
+ return new Session(this, fallbackName, sessionId);
3197
+ }
3198
+ sessionFromRow(session, context) {
3199
+ return new Session(this, requiredString(session["session_name"], context, "session_name"), requiredSessionId(session["session_id"], context));
3200
+ }
3201
+ validateCapabilities(capabilities) {
3202
+ const version = capabilities["binary_contract_version"];
3203
+ if (version !== 1) throw new RmuxCompatibilityError(`unsupported rmux binary contract version ${JSON.stringify(version)}; expected 1`);
3204
+ const commands = capabilities["json_commands"];
3205
+ if (!Array.isArray(commands) || ![
3206
+ "capabilities",
3207
+ "display-message",
3208
+ "list-clients",
3209
+ "list-panes",
3210
+ "list-sessions",
3211
+ "list-windows"
3212
+ ].every((command) => commands.includes(command))) throw new RmuxCompatibilityError("rmux binary does not advertise required JSON commands");
3213
+ const publicContract = capabilities["public_contract"];
3214
+ if (!Array.isArray(publicContract) || !publicContract.includes("control-mode")) throw new RmuxCompatibilityError("rmux binary does not advertise control-mode");
3215
+ }
3216
+ argv(args) {
3217
+ return [this.binary, ...this.endpointArgs(args)];
3218
+ }
3219
+ endpointArgs(args) {
3220
+ const argv = [];
3221
+ if (this.socketName !== void 0) argv.push("-L", this.socketName);
3222
+ if (this.socketPath !== void 0) argv.push("-S", this.socketPath);
3223
+ argv.push(...args.map(String));
3224
+ return argv;
3225
+ }
3226
+ };
3227
+ function splitCommandArguments(values) {
3228
+ const last = values.at(-1);
3229
+ if (isCommandOptionsCandidate(last)) return {
3230
+ args: values.slice(0, -1),
3231
+ options: parseCommandOptions(last)
3232
+ };
3233
+ return {
3234
+ args: values,
3235
+ options: {}
3236
+ };
3237
+ }
3238
+ function isCommandOptionsCandidate(value) {
3239
+ if (!isJsonObject(value)) return false;
3240
+ const prototype = Object.getPrototypeOf(value);
3241
+ return prototype === Object.prototype || prototype === null;
3242
+ }
3243
+ function parseCommandOptions(value) {
3244
+ for (const key of Object.keys(value)) if (key !== "check") throw new TypeError(`unknown rmux command option: ${key}`);
3245
+ if (value["check"] !== void 0 && typeof value["check"] !== "boolean") throw new TypeError("rmux command option check must be a boolean");
3246
+ return value["check"] === void 0 ? {} : { check: value["check"] };
3247
+ }
3248
+ function errorMessage(error) {
3249
+ return error instanceof Error ? error.message : String(error);
3250
+ }
3251
+ //#endregion
3252
+ //#region src/services/NativeTerminalService/terminalSocket.ts
3253
+ /** Unix socket paths are capped at 104 bytes on macOS; a long admitted root falls back to the host temp dir. */
3254
+ const SOCKET_PATH_LIMIT = 100;
3255
+ function terminalSocketPath(workspace, runKey, root) {
3256
+ const digest = (0, node_crypto.createHash)("sha256").update(`${workspace}/${runKey}`).digest("hex").slice(0, 24);
3257
+ const preferred = (0, node_path.join)(root, "workflow-mcp-terminals", `${digest}.sock`);
3258
+ if (Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT) return preferred;
3259
+ return (0, node_path.join)(_agimon_ai_po_core_platform.nodeHost.temporaryDirectory(), `workflow-mcp-${digest}.sock`);
3260
+ }
3261
+ function serveNativeTerminal$1(runtime, options) {
3262
+ return runtime.workflowHost.serveTerminal(options);
3263
+ }
3264
+ function connectNativeTerminal$1(runtime) {
3265
+ return runtime.workflowHost.connectTerminal();
3266
+ }
3267
+ //#endregion
3268
+ //#region src/services/workflowHost/nativeTerminal.ts
3269
+ /**
3270
+ * Terminal hosting for workflow runs through RMUX.
3271
+ *
3272
+ * DESIGN PATTERNS:
3273
+ * - RMUX owns the pseudo terminal, screen state, input, and process lifetime
3274
+ * - Platform payloads are optional and resolved at runtime, with PATH fallback
3275
+ * - The existing NativeTerminalService API remains stable for consumers
3276
+ *
3277
+ * CODING STANDARDS:
3278
+ * - Named exports only
3279
+ * - Explicit return types on exported members
3280
+ * - No top-level import of a platform payload package
3281
+ */
3282
+ const EXECUTABLE_MODE = 493;
3283
+ const EXECUTABLE_BITS = 73;
3284
+ const VENDOR_DIRECTORY = "vendor";
3285
+ const FALLBACK_COLUMNS = 120;
3286
+ const FALLBACK_ROWS = 40;
3287
+ const PANE_PID_FORMAT = "#{pane_pid}";
3288
+ const PANE_STATE_FORMAT = "#{pane_dead}:#{pane_dead_status}";
3289
+ const POLL_MS = 100;
3290
+ const RMUX_BINARY_ENV = "AGIMON_RMUX_BINARY";
3291
+ const RMUX_SOCKET_NAME = "agimon-workflow-mcp";
3292
+ const ENV_COMMAND = "/usr/bin/env";
3293
+ const GATE_SCRIPT = "while [ ! -e \"$1\" ]; do sleep 0.01; done; . \"$2\"; rm -f \"$2\"; shift 2; exec \"$@\"";
3294
+ const ENVIRONMENT_FILE = "environment";
3295
+ const PRIVATE_FILE_MODE = 384;
3296
+ /** Names a POSIX shell can export; any other name stays on the env command line. */
3297
+ const SHELL_VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
3298
+ const TERMINAL_ENV = {
3299
+ TERM: "xterm-256color",
3300
+ COLORTERM: "truecolor"
3301
+ };
3302
+ const PACKAGE_BY_PLATFORM = {
3303
+ "darwin-arm64": "@agimon-ai/rmux-darwin-arm64",
3304
+ "darwin-x64": "@agimon-ai/rmux-darwin-x64",
3305
+ "linux-arm64": "@agimon-ai/rmux-linux-arm64",
3306
+ "linux-x64": "@agimon-ai/rmux-linux-x64"
3307
+ };
3308
+ const requirePackage = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
3309
+ function defaultGeometry() {
3310
+ return {
3311
+ columns: process.stdout.columns || FALLBACK_COLUMNS,
3312
+ rows: process.stdout.rows || FALLBACK_ROWS
3313
+ };
3314
+ }
3315
+ function bundledBinary() {
3316
+ const packageName = PACKAGE_BY_PLATFORM[`${process.platform}-${process.arch}`];
3317
+ if (!packageName) return void 0;
3318
+ try {
3319
+ const manifest = requirePackage.resolve(`${packageName}/package.json`);
3320
+ return node_path.default.join(node_path.default.dirname(manifest), VENDOR_DIRECTORY, "bin", "rmux");
3321
+ } catch {
3322
+ return;
3323
+ }
3324
+ }
3325
+ /**
3326
+ * Make the bundled payload runnable before RMUX is asked for anything.
3327
+ *
3328
+ * The prebuilt packages reach npm with plain 0644 files. Restoring the
3329
+ * executable bit on the launcher alone is not enough: rmux execs
3330
+ * `bin/rmux-daemon` and `libexec/rmux/rmux` itself and fails on the first with
3331
+ * a permission error, so every file the vendor tree ships is restored. A
3332
+ * stand-alone override outside a vendor tree only gets itself restored, and a
3333
+ * file that is already executable is left alone, since chmod on a binary
3334
+ * someone else owns would throw and drop a usable candidate.
3335
+ */
3336
+ async function ensureExecutablePayload(binary) {
3337
+ const vendor = node_path.default.resolve(node_path.default.dirname(binary), "..");
3338
+ const payload = node_path.default.basename(vendor) === VENDOR_DIRECTORY ? (await node_fs_promises.default.readdir(vendor, {
3339
+ recursive: true,
3340
+ withFileTypes: true
3341
+ })).filter((entry) => entry.isFile()).map((entry) => node_path.default.join(entry.parentPath, entry.name)) : [binary];
3342
+ for (const file of payload) if (((await node_fs_promises.default.stat(file)).mode & EXECUTABLE_BITS) === 0) await node_fs_promises.default.chmod(file, EXECUTABLE_MODE);
3343
+ }
3344
+ async function createDefaultClient(options) {
3345
+ const candidates = [
3346
+ options.environment[RMUX_BINARY_ENV],
3347
+ bundledBinary(),
3348
+ "rmux"
3349
+ ].filter((candidate) => Boolean(candidate));
3350
+ for (const binary of candidates) try {
3351
+ if (binary !== "rmux") await ensureExecutablePayload(binary);
3352
+ const environment = Object.fromEntries(Object.entries(options.environment).filter((entry) => entry[1] !== void 0));
3353
+ const client = new Rmux({
3354
+ binary,
3355
+ socketName: RMUX_SOCKET_NAME,
3356
+ cwd: options.cwd,
3357
+ env: environment
3358
+ });
3359
+ client.cmd = async (...arguments_) => {
3360
+ const last = arguments_.at(-1);
3361
+ const check = typeof last === "object" ? last.check === true : false;
3362
+ const args = (typeof last === "object" ? arguments_.slice(0, -1) : arguments_).map(String);
3363
+ const argv = [
3364
+ "-L",
3365
+ RMUX_SOCKET_NAME,
3366
+ ...args
3367
+ ];
3368
+ const completed = await runRmux(binary, argv, options.cwd, environment);
3369
+ const run = new CommandRun([binary, ...argv], completed.code, completed.stdout, completed.stderr);
3370
+ return check ? run.checkReturnCode() : run;
3371
+ };
3372
+ await client.capabilities();
3373
+ return client;
3374
+ } catch {
3375
+ continue;
3376
+ }
3377
+ }
3378
+ /** Single-quotes a value for POSIX sh, which keeps newlines and every other byte literal. */
3379
+ function shellQuote(value) {
3380
+ return `'${value.replaceAll("'", `'\\''`)}'`;
3381
+ }
3382
+ /**
3383
+ * The run's environment, split into a script the pane sources and the few
3384
+ * assignments a shell cannot export.
3385
+ *
3386
+ * Passing the whole environment as arguments to RMUX's new-session breaks once
3387
+ * a host adds its own variables: RMUX refuses the command as too long. It also
3388
+ * puts every value, secrets included, into the process table. The script is
3389
+ * written to the run's private gate directory instead and deleted as soon as
3390
+ * the pane has read it.
3391
+ */
3392
+ function environmentScript(env) {
3393
+ const entries = Object.entries({
3394
+ ...env,
3395
+ ...TERMINAL_ENV
3396
+ }).sort(([left], [right]) => left.localeCompare(right));
3397
+ return {
3398
+ script: entries.filter(([name]) => SHELL_VARIABLE_NAME.test(name)).map(([name, value]) => `export ${name}=${shellQuote(value)}\n`).join(""),
3399
+ unexportable: entries.filter(([name]) => !SHELL_VARIABLE_NAME.test(name)).map(([name, value]) => `${name}=${value}`)
3400
+ };
3401
+ }
3402
+ function panePid(stdout) {
3403
+ const pid = Number(stdout.trim());
3404
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error(`RMUX returned an invalid pane pid: ${JSON.stringify(stdout)}`);
3405
+ return pid;
3406
+ }
3407
+ function delay(milliseconds) {
3408
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
3409
+ }
3410
+ async function waitForRunEnd(client, target) {
3411
+ for (;;) {
3412
+ const [dead, status] = (await client.cmd("display-message", "-p", "-t", target, PANE_STATE_FORMAT, { check: true })).stdout.trim().split(":", 2);
3413
+ if (dead === "1") {
3414
+ const code = Number(status || 0);
3415
+ return Number.isInteger(code) ? code : 0;
3416
+ }
3417
+ await delay(POLL_MS);
3418
+ }
3419
+ }
3420
+ function screenLines(screen) {
3421
+ const lines = screen.split("\n");
3422
+ while (lines.length > 0 && lines.at(-1)?.trim() === "") lines.pop();
3423
+ return lines;
3424
+ }
3425
+ /**
3426
+ * Hosts workflow runs in RMUX while preserving the package's existing terminal
3427
+ * socket contract for callers in another process.
3428
+ */
3429
+ var NativeTerminalService = class {
3430
+ options;
3431
+ dependencies;
3432
+ runs = /* @__PURE__ */ new Map();
3433
+ clientPromise;
3434
+ constructor(options, dependencies = {}) {
3435
+ this.options = options;
3436
+ this.dependencies = dependencies;
3437
+ }
3438
+ client() {
3439
+ this.clientPromise ??= this.dependencies.createClient?.() ?? createDefaultClient(this.options);
3440
+ return this.clientPromise;
3441
+ }
3442
+ async available() {
3443
+ return Boolean(await this.client());
3444
+ }
3445
+ async spawn(input) {
3446
+ const client = await this.client();
3447
+ if (!client) throw new Error("Terminal hosting is unavailable: RMUX did not load.");
3448
+ const { columns, rows } = defaultGeometry();
3449
+ if (!this.options.temporaryDirectory) throw new Error("Native workflow terminals require an admitted temporary directory.");
3450
+ const gateDirectory = await node_fs_promises.default.mkdtemp(node_path.default.join(this.options.temporaryDirectory, "workflow-mcp-rmux-"));
3451
+ const gate = node_path.default.join(gateDirectory, "start");
3452
+ const environmentFile = node_path.default.join(gateDirectory, ENVIRONMENT_FILE);
3453
+ const environment = environmentScript(input.env);
3454
+ let created = false;
3455
+ let released = false;
3456
+ try {
3457
+ await node_fs_promises.default.writeFile(environmentFile, environment.script, { mode: PRIVATE_FILE_MODE });
3458
+ const opened = await client.cmd("new-session", "-d", "-P", "-F", PANE_PID_FORMAT, "-s", input.runKey, "-c", input.cwd, "-x", columns, "-y", rows, "/usr/bin/env", "-i", "/bin/sh", "-c", GATE_SCRIPT, "workflow-mcp-gate", gate, environmentFile, ENV_COMMAND, ...environment.unexportable, input.command, ...input.args, { check: true });
3459
+ created = true;
3460
+ const pid = panePid(opened.stdout);
3461
+ await client.cmd("set-option", "-t", input.runKey, "remain-on-exit", "on", { check: true });
3462
+ const hosted = {
3463
+ pane: client.session(input.runKey).pane(0, 0),
3464
+ sessionName: input.runKey,
3465
+ exited: false,
3466
+ viewers: /* @__PURE__ */ new Set(),
3467
+ ended: Promise.resolve(0)
3468
+ };
3469
+ await node_fs_promises.default.writeFile(gate, "", { mode: 384 });
3470
+ hosted.ended = waitForRunEnd(client, input.runKey).then((code) => {
3471
+ hosted.exited = true;
3472
+ hosted.exitCode = code;
3473
+ return code;
3474
+ }).finally(() => node_fs_promises.default.rm(gateDirectory, {
3475
+ recursive: true,
3476
+ force: true
3477
+ }));
3478
+ released = true;
3479
+ this.runs.set(input.runKey, hosted);
3480
+ return { pid };
3481
+ } catch (error) {
3482
+ if (created) await client.session(input.runKey).kill().catch(() => void 0);
3483
+ throw error;
3484
+ } finally {
3485
+ if (!released) await node_fs_promises.default.rm(gateDirectory, {
3486
+ recursive: true,
3487
+ force: true
3488
+ });
3489
+ }
3490
+ }
3491
+ isHosted(runKey) {
3492
+ return this.runs.has(runKey);
3493
+ }
3494
+ exitOf(runKey) {
3495
+ const hosted = this.runs.get(runKey);
3496
+ if (!hosted) return void 0;
3497
+ return {
3498
+ exited: hosted.exited,
3499
+ ...hosted.exitCode === void 0 ? {} : { exitCode: hosted.exitCode }
3500
+ };
3501
+ }
3502
+ ended(runKey) {
3503
+ return this.runs.get(runKey)?.ended ?? Promise.resolve(0);
3504
+ }
3505
+ viewerCount(runKey) {
3506
+ return this.runs.get(runKey)?.viewers.size ?? 0;
3507
+ }
3508
+ async attach(runKey, columns, rows) {
3509
+ const hosted = this.runs.get(runKey);
3510
+ if (!hosted) throw new Error(`No RMUX-hosted workflow run matches ${JSON.stringify(runKey)}.`);
3511
+ const viewer = {};
3512
+ hosted.viewers.add(viewer);
3513
+ await hosted.pane.resize({
3514
+ width: columns,
3515
+ height: rows
3516
+ });
3517
+ return {
3518
+ snapshot: async () => screenLines(await hosted.pane.captureText()),
3519
+ resize: async (nextColumns, nextRows) => {
3520
+ await hosted.pane.resize({
3521
+ width: nextColumns,
3522
+ height: nextRows
3523
+ });
3524
+ },
3525
+ write: async (data) => {
3526
+ if (!hosted.exited) await hosted.pane.sendText(data);
3527
+ },
3528
+ detach: () => {
3529
+ hosted.viewers.delete(viewer);
3530
+ }
3531
+ };
3532
+ }
3533
+ async kill(runKey) {
3534
+ const hosted = this.runs.get(runKey);
3535
+ if (!hosted) return;
3536
+ await (await this.client())?.session(hosted.sessionName).kill();
3537
+ hosted.viewers.clear();
3538
+ this.runs.delete(runKey);
3539
+ }
3540
+ /** Reap panes owned by an earlier host, including pre-upgrade socket-only refs. */
3541
+ async killRunPanes(runId, paneRefs) {
3542
+ const client = await this.client();
3543
+ if (!client) return;
3544
+ let sessions;
3545
+ try {
3546
+ sessions = await client.listSessions();
3547
+ } catch (error) {
3548
+ if (/no server running|failed to connect|connection refused|no such file/i.test(String(error))) return;
3549
+ throw error;
3550
+ }
3551
+ for (const { session_name: name } of sessions) {
3552
+ if (typeof name !== "string") throw new Error("RMUX returned a session without a name.");
3553
+ const matchesRef = this.options.temporaryDirectory !== void 0 && paneRefs.includes(terminalSocketPath("po-workflow-steps", name, this.options.temporaryDirectory));
3554
+ if (runId !== void 0 && name.startsWith(`workflow-${runId}-`) || matchesRef) {
3555
+ await client.session(name).kill();
3556
+ this.runs.get(name)?.viewers.clear();
3557
+ this.runs.delete(name);
3558
+ }
3559
+ }
3560
+ }
3561
+ async disposeAll() {
3562
+ await Promise.all([...this.runs.keys()].map((runKey) => this.kill(runKey)));
3563
+ }
3564
+ };
3565
+ async function runRmux(binary, args, cwd, env) {
3566
+ return await new Promise((resolve, reject) => {
3567
+ const child = (0, node_child_process.spawn)(binary, args, {
3568
+ cwd,
3569
+ env,
3570
+ stdio: [
3571
+ "ignore",
3572
+ "pipe",
3573
+ "pipe"
3574
+ ]
3575
+ });
3576
+ let stdout = "";
3577
+ let stderr = "";
3578
+ child.stdout.on("data", (chunk) => {
3579
+ stdout += chunk.toString();
3580
+ });
3581
+ child.stderr.on("data", (chunk) => {
3582
+ stderr += chunk.toString();
3583
+ });
3584
+ child.once("error", reject);
3585
+ child.once("close", (code) => resolve({
3586
+ code: code ?? 1,
3587
+ stdout,
3588
+ stderr
3589
+ }));
3590
+ });
3591
+ }
3592
+ //#endregion
3593
+ //#region src/services/workflowHost/terminalSocket.ts
3594
+ /**
3595
+ * An RMUX-hosted run, reachable through the existing native-launcher socket.
3596
+ *
3597
+ * WHY A SOCKET:
3598
+ * The run record's `native` discriminator predates RMUX and points callers at
3599
+ * this transport. Keeping that contract avoids teaching every cockpit process
3600
+ * how to discover the private RMUX server and target.
3601
+ *
3602
+ * DESIGN PATTERNS:
3603
+ * - One line of JSON per request and per answer. A screen is a list of strings
3604
+ * and a keystroke is a string, so nothing here earns a framing format
3605
+ * - One viewer per socket server, shared by its clients. RMUX owns screen state,
3606
+ * so requests capture the pane without allocating an emulator
3607
+ * - The client connects per request. A unix socket connect costs a fraction of
3608
+ * a millisecond, and a stateless client cannot leak a connection or need
3609
+ * reconnect logic when a host restarts
3610
+ *
3611
+ * CODING STANDARDS:
3612
+ * - Named exports only
3613
+ * - Explicit return types on exported members
3614
+ *
3615
+ * AVOID:
3616
+ * - Putting the socket inside the run directory: a run directory path is
3617
+ * already close to the 104 byte limit macOS puts on a unix socket path
3618
+ */
3619
+ const REQUEST_TIMEOUT_MS = 2e3;
3620
+ /** Geometry a reader gets before it has said how much room it has. */
3621
+ const DEFAULT_COLUMNS = 120;
3622
+ const DEFAULT_ROWS = 40;
3623
+ /**
3624
+ * Serves one hosted run on a unix socket.
3625
+ *
3626
+ * The viewer is created on the first request rather than at bind time: a run
3627
+ * nobody ever opens should cost a socket file and nothing else.
3628
+ */
3629
+ async function serveNativeTerminal(options) {
3630
+ const notice = options.onNotice ?? (() => {});
3631
+ let viewer;
3632
+ const answer = async (request) => {
3633
+ if (viewer === void 0) viewer = await options.service.attach(options.runKey, request.columns ?? DEFAULT_COLUMNS, request.rows ?? DEFAULT_ROWS);
3634
+ if (request.op === "write") {
3635
+ await viewer.write(request.data ?? "");
3636
+ return { ok: true };
3637
+ }
3638
+ if (request.op === "resize") {
3639
+ await viewer.resize(request.columns ?? DEFAULT_COLUMNS, request.rows ?? DEFAULT_ROWS);
3640
+ return { ok: true };
3641
+ }
3642
+ if (request.columns !== void 0 && request.rows !== void 0) await viewer.resize(request.columns, request.rows);
3643
+ return {
3644
+ ok: true,
3645
+ lines: await viewer.snapshot()
3646
+ };
3647
+ };
3648
+ const server = (0, node_net.createServer)((socket) => {
3649
+ let buffered = "";
3650
+ socket.on("data", (chunk) => {
3651
+ buffered += chunk.toString();
3652
+ let newline = buffered.indexOf("\n");
3653
+ while (newline !== -1) {
3654
+ const line = buffered.slice(0, newline);
3655
+ buffered = buffered.slice(newline + 1);
3656
+ handle(line);
3657
+ newline = buffered.indexOf("\n");
3658
+ }
3659
+ });
3660
+ socket.on("error", () => socket.destroy());
3661
+ const handle = async (line) => {
3662
+ let response;
3663
+ try {
3664
+ response = await answer(JSON.parse(line));
3665
+ } catch (error) {
3666
+ response = {
3667
+ ok: false,
3668
+ error: error instanceof Error ? error.message : String(error)
3669
+ };
3670
+ }
3671
+ if (socket.writable) socket.write(`${JSON.stringify(response)}\n`);
3672
+ };
3673
+ });
3674
+ await (0, node_fs_promises.mkdir)((0, node_path.join)(options.socketPath, ".."), { recursive: true });
3675
+ await (0, node_fs_promises.rm)(options.socketPath, { force: true });
3676
+ await new Promise((resolve, reject) => {
3677
+ server.once("error", reject);
3678
+ server.listen(options.socketPath, () => {
3679
+ server.removeListener("error", reject);
3680
+ resolve();
3681
+ });
3682
+ });
3683
+ server.on("error", (error) => notice(`terminal socket for ${options.runKey}: ${error.message}`));
3684
+ return { close: async () => {
3685
+ viewer?.detach();
3686
+ viewer = void 0;
3687
+ await closeServer(server, options.socketPath);
3688
+ } };
3689
+ }
3690
+ async function closeServer(server, socketPath) {
3691
+ await new Promise((resolve) => {
3692
+ server.close(() => resolve());
3693
+ });
3694
+ await (0, node_fs_promises.rm)(socketPath, { force: true });
3695
+ }
3696
+ /** One request over a fresh connection, or a rejection naming what went wrong. */
3697
+ function request(socketPath, body) {
3698
+ return new Promise((resolve, reject) => {
3699
+ const socket = (0, node_net.createConnection)(socketPath);
3700
+ let buffered = "";
3701
+ const finish = (error, response) => {
3702
+ socket.destroy();
3703
+ if (error) reject(error);
3704
+ else if (response) resolve(response);
3705
+ };
3706
+ const timer = setTimeout(() => finish(/* @__PURE__ */ new Error(`The run's terminal did not answer within ${REQUEST_TIMEOUT_MS}ms.`)), REQUEST_TIMEOUT_MS);
3707
+ timer.unref?.();
3708
+ socket.on("connect", () => socket.write(`${JSON.stringify(body)}\n`));
3709
+ socket.on("data", (chunk) => {
3710
+ buffered += chunk.toString();
3711
+ const newline = buffered.indexOf("\n");
3712
+ if (newline === -1) return;
3713
+ clearTimeout(timer);
3714
+ try {
3715
+ finish(void 0, JSON.parse(buffered.slice(0, newline)));
3716
+ } catch (error) {
3717
+ finish(error instanceof Error ? error : new Error(String(error)));
3718
+ }
3719
+ });
3720
+ socket.on("error", (error) => {
3721
+ clearTimeout(timer);
3722
+ finish(error);
3723
+ });
3724
+ });
3725
+ }
3726
+ /**
3727
+ * The reader's half: a bridge over one run's socket, shaped for the terminal
3728
+ * facade so a natively hosted run reads like any other launcher.
3729
+ */
3730
+ function connectNativeTerminal() {
3731
+ return {
3732
+ async snapshot(socketPath, options) {
3733
+ const response = await request(socketPath, { op: "snapshot" });
3734
+ if (!response.ok) throw new Error(response.error ?? "The run refused to answer.");
3735
+ const lines = response.lines ?? [];
3736
+ return options.lines === void 0 ? lines : lines.slice(-options.lines);
3737
+ },
3738
+ async write(socketPath, data) {
3739
+ const response = await request(socketPath, {
3740
+ op: "write",
3741
+ data
3742
+ });
3743
+ if (!response.ok) throw new Error(response.error ?? "The run refused the keystrokes.");
3744
+ },
3745
+ async resize(socketPath, columns, rows) {
3746
+ const response = await request(socketPath, {
3747
+ op: "resize",
3748
+ columns,
3749
+ rows
3750
+ });
3751
+ if (!response.ok) throw new Error(response.error ?? "The run refused the resize.");
3752
+ }
3753
+ };
3754
+ }
3755
+ //#endregion
3756
+ //#region src/services/workflowHost/index.ts
3757
+ const nativeHosts = /* @__PURE__ */ new WeakSet();
3758
+ /** Factory-created native hosts capture per-root environment and directories. */
3759
+ function readBoundWorkflowHost(context) {
3760
+ const host = require_contract.readPoWorkflowHost(context);
3761
+ return host !== void 0 && nativeHosts.has(host) ? void 0 : host;
3762
+ }
3763
+ /** Node implementation of the exceptional native workflow operations. */
3764
+ function createWorkflowHost(options) {
3765
+ options = {
3766
+ ...options,
3767
+ environment: Object.freeze({ ...options.environment })
3768
+ };
3769
+ let shellPath = "/bin/sh";
3770
+ try {
3771
+ (0, node_fs.accessSync)("/bin/zsh", node_fs.constants.X_OK);
3772
+ shellPath = "/bin/zsh";
3773
+ } catch {}
3774
+ const host = Object.freeze({
3775
+ processId: process.pid,
3776
+ executablePath: process.execPath,
3777
+ platform: process.platform,
3778
+ shellPath,
3779
+ isElectron: Boolean(process.versions.electron),
3780
+ writeStdout: (text) => {
3781
+ process.stdout.write(text);
3782
+ },
3783
+ writeStderr: (text) => {
3784
+ process.stderr.write(text);
3785
+ },
3786
+ onSignal: (signal, listener) => {
3787
+ process.on(signal, listener);
3788
+ return () => {
3789
+ process.off(signal, listener);
3790
+ };
3791
+ },
3792
+ portRegistry: {
3793
+ reservePort: (request) => registryOperation(options, "reservePort", request),
3794
+ releasePort: (request) => registryOperation(options, "releasePort", request)
3795
+ },
3796
+ processRegistry: {
3797
+ registerProcess: (request) => registryOperation(options, "registerProcess", request),
3798
+ releaseProcess: (request) => registryOperation(options, "releaseProcess", request)
3799
+ },
3800
+ createTerminal: (dependencies) => new NativeTerminalService(options, dependencies),
3801
+ serveTerminal: serveNativeTerminal,
3802
+ connectTerminal: connectNativeTerminal,
3803
+ createPrompt: () => (0, node_readline.createInterface)({
3804
+ input: process.stdin,
3805
+ output: process.stdout
3806
+ }),
3807
+ importJobTools: (path) => import(
3808
+ /* @vite-ignore */
3809
+ (0, node_url.pathToFileURL)(path).href
3810
+ ),
3811
+ openArtifact,
3812
+ writeExclusive: (path, content) => (0, node_fs_promises.writeFile)(path, content, {
3813
+ flag: "wx",
3814
+ mode: 384
3815
+ }),
3816
+ publishExclusive: (source, destination) => (0, node_fs_promises.link)(source, destination),
3817
+ acquireRecoveryLock: (path, lockOptions) => (0, proper_lockfile.lock)(path, lockOptions),
3818
+ setMode: (path, mode) => (0, node_fs_promises.chmod)(path, mode),
3819
+ spawn: (command, args, spawnOptions) => (0, node_child_process.spawn)(command, [...args], spawnOptions),
3820
+ signal: (processId, signal) => process.kill(processId, signal),
3821
+ inspectProcesses: (columns, processId) => {
3822
+ return (0, node_child_process.execFileSync)("ps", columns === "command" || columns === "identity" ? [
3823
+ "-p",
3824
+ String(processId),
3825
+ "-o",
3826
+ columns === "identity" ? "lstart=,command=" : "command="
3827
+ ] : ["-axo", columns === "parents" ? "pid=,ppid=" : "pid=,pgid="], {
3828
+ cwd: options.cwd,
3829
+ env: {
3830
+ ...options.environment,
3831
+ LC_ALL: "C"
3832
+ },
3833
+ encoding: "utf-8",
3834
+ stdio: [
3835
+ "ignore",
3836
+ "pipe",
3837
+ "ignore"
3838
+ ]
3839
+ });
3840
+ },
3841
+ readTerminalState: () => {
3842
+ try {
3843
+ return (0, node_child_process.execFileSync)("stty", ["-g"], {
3844
+ cwd: options.cwd,
3845
+ env: options.environment,
3846
+ encoding: "utf-8",
3847
+ stdio: [
3848
+ "inherit",
3849
+ "pipe",
3850
+ "ignore"
3851
+ ]
3852
+ }).trim();
3853
+ } catch {
3854
+ return;
3855
+ }
3856
+ },
3857
+ restoreTerminalState: (state) => {
3858
+ if (state) (0, node_child_process.execFileSync)("stty", [state], {
3859
+ cwd: options.cwd,
3860
+ env: options.environment,
3861
+ stdio: [
3862
+ "inherit",
3863
+ "ignore",
3864
+ "ignore"
3865
+ ]
3866
+ });
3867
+ if (process.stdout.isTTY) process.stdout.write("\x1B[0m\x1B[?25h\x1B[?1049l");
3868
+ }
3869
+ });
3870
+ nativeHosts.add(host);
3871
+ return host;
3872
+ }
3873
+ async function openArtifact(path) {
3874
+ let file;
3875
+ try {
3876
+ file = await (0, node_fs_promises.open)(path, node_fs.constants.O_RDONLY | node_fs.constants.O_NOFOLLOW | node_fs.constants.O_NONBLOCK);
3877
+ } catch (error) {
3878
+ if (error instanceof Error && "code" in error && [
3879
+ "ENOENT",
3880
+ "ENOTDIR",
3881
+ "ELOOP",
3882
+ "EACCES",
3883
+ "EPERM"
3884
+ ].includes(String(error.code))) return void 0;
3885
+ throw error;
3886
+ }
3887
+ let closed = false;
3888
+ const close = async () => {
3889
+ if (closed) return;
3890
+ closed = true;
3891
+ await file.close();
3892
+ };
3893
+ try {
3894
+ const snapshot = await file.stat();
3895
+ if (!snapshot.isFile()) {
3896
+ await close();
3897
+ return;
3898
+ }
3899
+ const identity = (stat) => `"${stat.dev}-${stat.ino}-${stat.size}-${stat.mtimeMs}-${stat.ctimeMs}"`;
3900
+ const version = identity(snapshot);
3901
+ const unchanged = async () => !closed && identity(await file.stat()) === version;
3902
+ const readRange = async (start, end) => {
3903
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || end >= snapshot.size) return void 0;
3904
+ if (!await unchanged()) return void 0;
3905
+ const bytes = new Uint8Array(end - start + 1);
3906
+ let offset = 0;
3907
+ while (offset < bytes.length) {
3908
+ const read = await file.read(bytes, offset, bytes.length - offset, start + offset);
3909
+ if (read.bytesRead === 0) return void 0;
3910
+ offset += read.bytesRead;
3911
+ }
3912
+ return await unchanged() ? bytes : void 0;
3913
+ };
3914
+ return {
3915
+ size: snapshot.size,
3916
+ modifiedAt: snapshot.mtime.toUTCString(),
3917
+ version,
3918
+ readRange,
3919
+ stream: (start, end) => {
3920
+ let position = start;
3921
+ return new ReadableStream({
3922
+ async pull(controller) {
3923
+ try {
3924
+ if (position > end) {
3925
+ if (!await unchanged()) throw new Error("Workflow artifact changed while streaming.");
3926
+ await close();
3927
+ controller.close();
3928
+ return;
3929
+ }
3930
+ const next = Math.min(end, position + 65536 - 1);
3931
+ const bytes = await readRange(position, next);
3932
+ if (bytes === void 0) throw new Error("Workflow artifact changed while streaming.");
3933
+ position = next + 1;
3934
+ controller.enqueue(bytes);
3935
+ } catch (error) {
3936
+ await close();
3937
+ controller.error(error);
3938
+ }
3939
+ },
3940
+ cancel: close
3941
+ });
3942
+ },
3943
+ close
3944
+ };
3945
+ } catch (error) {
3946
+ await close();
3947
+ throw error;
3948
+ }
3949
+ }
3950
+ /** Foundation registries admit process environment internally, so isolate that admission per invocation. */
3951
+ async function registryOperation(options, operation, request) {
3952
+ const requirePackage = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
3953
+ const portModule = requirePackage.resolve("@agimon-ai/foundation-port-registry");
3954
+ const processModule = requirePackage.resolve("@agimon-ai/foundation-process-registry");
3955
+ const source = `
3956
+ const { PortRegistryService } = require(${JSON.stringify(portModule)});
3957
+ const { ProcessRegistryService } = require(${JSON.stringify(processModule)});
3958
+ let input = '';
3959
+ process.stdin.setEncoding('utf8');
3960
+ process.stdin.on('data', chunk => { input += chunk; });
3961
+ process.stdin.on('end', async () => {
3962
+ try {
3963
+ const { operation, request, portRegistryPath, processRegistryPath } = JSON.parse(input);
3964
+ const ports = new PortRegistryService(portRegistryPath);
3965
+ const processes = new ProcessRegistryService(processRegistryPath);
3966
+ const registry = operation === 'reservePort' || operation === 'releasePort' ? ports : processes;
3967
+ const result = await registry[operation](request);
3968
+ process.stdout.write(JSON.stringify(result));
3969
+ } catch (error) { console.error(error); process.exitCode = 1; }
3970
+ });
3971
+ `;
3972
+ return await new Promise((resolve, reject) => {
3973
+ const child = (0, node_child_process.spawn)(process.execPath, ["-e", source], {
3974
+ cwd: options.cwd,
3975
+ env: {
3976
+ ...options.environment,
3977
+ HOME: options.homeDirectory,
3978
+ ...options.temporaryDirectory === void 0 ? {} : { TMPDIR: options.temporaryDirectory }
3979
+ },
3980
+ stdio: [
3981
+ "pipe",
3982
+ "pipe",
3983
+ "pipe"
3984
+ ]
3985
+ });
3986
+ let output = "";
3987
+ let errors = "";
3988
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 15e3);
3989
+ child.stdout.on("data", (chunk) => {
3990
+ output += chunk.toString("utf8");
3991
+ if (output.length > 1048576) child.kill("SIGKILL");
3992
+ });
3993
+ child.stderr.on("data", (chunk) => {
3994
+ errors = (errors + chunk.toString("utf8")).slice(-65536);
3995
+ });
3996
+ child.once("error", (error) => {
3997
+ clearTimeout(timeout);
3998
+ reject(error);
3999
+ });
4000
+ child.once("close", (code) => {
4001
+ clearTimeout(timeout);
4002
+ if (code !== 0) {
4003
+ reject(/* @__PURE__ */ new Error(`Workflow ${operation} failed: ${errors}`));
4004
+ return;
4005
+ }
4006
+ try {
4007
+ resolve(JSON.parse(output));
4008
+ } catch (error) {
4009
+ reject(error);
4010
+ }
4011
+ });
4012
+ child.stdin.end(JSON.stringify({
4013
+ operation,
4014
+ request,
4015
+ portRegistryPath: options.environment.PORT_REGISTRY_PATH,
4016
+ processRegistryPath: options.environment.PROCESS_REGISTRY_PATH
4017
+ }));
4018
+ });
4019
+ }
4020
+ //#endregion
4021
+ Object.defineProperty(exports, "ServiceProcessesSchema", {
4022
+ enumerable: true,
4023
+ get: function() {
4024
+ return ServiceProcessesSchema;
4025
+ }
4026
+ });
4027
+ Object.defineProperty(exports, "WorkflowAdmissionIntentSchema", {
4028
+ enumerable: true,
4029
+ get: function() {
4030
+ return WorkflowAdmissionIntentSchema;
4031
+ }
4032
+ });
4033
+ Object.defineProperty(exports, "WorkflowAssignmentsSchema", {
4034
+ enumerable: true,
4035
+ get: function() {
4036
+ return WorkflowAssignmentsSchema;
4037
+ }
4038
+ });
4039
+ Object.defineProperty(exports, "WorkflowCapabilityError", {
4040
+ enumerable: true,
4041
+ get: function() {
4042
+ return WorkflowCapabilityError;
4043
+ }
4044
+ });
4045
+ Object.defineProperty(exports, "WorkflowParserService", {
4046
+ enumerable: true,
4047
+ get: function() {
4048
+ return WorkflowParserService;
4049
+ }
4050
+ });
4051
+ Object.defineProperty(exports, "WorkflowProgressEventSchema", {
4052
+ enumerable: true,
4053
+ get: function() {
4054
+ return WorkflowProgressEventSchema;
4055
+ }
4056
+ });
4057
+ Object.defineProperty(exports, "WorkflowRepairRecordSchema", {
4058
+ enumerable: true,
4059
+ get: function() {
4060
+ return WorkflowRepairRecordSchema;
4061
+ }
4062
+ });
4063
+ Object.defineProperty(exports, "WorkflowRepairableFileSchema", {
4064
+ enumerable: true,
4065
+ get: function() {
4066
+ return WorkflowRepairableFileSchema;
4067
+ }
4068
+ });
4069
+ Object.defineProperty(exports, "WorkflowRunRecordSchema", {
4070
+ enumerable: true,
4071
+ get: function() {
4072
+ return WorkflowRunRecordSchema;
4073
+ }
4074
+ });
4075
+ Object.defineProperty(exports, "WorkflowStageSchema", {
4076
+ enumerable: true,
4077
+ get: function() {
4078
+ return WorkflowStageSchema;
4079
+ }
4080
+ });
4081
+ Object.defineProperty(exports, "WorkflowToolsPathSchema", {
4082
+ enumerable: true,
4083
+ get: function() {
4084
+ return WorkflowToolsPathSchema;
4085
+ }
4086
+ });
4087
+ Object.defineProperty(exports, "__toESM", {
4088
+ enumerable: true,
4089
+ get: function() {
4090
+ return __toESM;
4091
+ }
4092
+ });
4093
+ Object.defineProperty(exports, "choiceSettings", {
4094
+ enumerable: true,
4095
+ get: function() {
4096
+ return choiceSettings;
4097
+ }
4098
+ });
4099
+ Object.defineProperty(exports, "commandTemplateOf", {
4100
+ enumerable: true,
4101
+ get: function() {
4102
+ return commandTemplateOf;
4103
+ }
4104
+ });
4105
+ Object.defineProperty(exports, "connectNativeTerminal", {
4106
+ enumerable: true,
4107
+ get: function() {
4108
+ return connectNativeTerminal$1;
4109
+ }
4110
+ });
4111
+ Object.defineProperty(exports, "createWorkflowHost", {
4112
+ enumerable: true,
4113
+ get: function() {
4114
+ return createWorkflowHost;
4115
+ }
4116
+ });
4117
+ Object.defineProperty(exports, "createWorkflowRuntime", {
4118
+ enumerable: true,
4119
+ get: function() {
4120
+ return createWorkflowRuntime;
4121
+ }
4122
+ });
4123
+ Object.defineProperty(exports, "escapeShellArg", {
4124
+ enumerable: true,
4125
+ get: function() {
4126
+ return escapeShellArg;
4127
+ }
4128
+ });
4129
+ Object.defineProperty(exports, "inspectWorkflowDefinition", {
4130
+ enumerable: true,
4131
+ get: function() {
4132
+ return inspectWorkflowDefinition;
4133
+ }
4134
+ });
4135
+ Object.defineProperty(exports, "parseWorkflowLaunchCommand", {
4136
+ enumerable: true,
4137
+ get: function() {
4138
+ return parseWorkflowLaunchCommand;
4139
+ }
4140
+ });
4141
+ Object.defineProperty(exports, "readBoundWorkflowHost", {
4142
+ enumerable: true,
4143
+ get: function() {
4144
+ return readBoundWorkflowHost;
4145
+ }
4146
+ });
4147
+ Object.defineProperty(exports, "renderWorkflowCommandTemplate", {
4148
+ enumerable: true,
4149
+ get: function() {
4150
+ return renderWorkflowCommandTemplate;
4151
+ }
4152
+ });
4153
+ Object.defineProperty(exports, "requireShell", {
4154
+ enumerable: true,
4155
+ get: function() {
4156
+ return requireShell;
4157
+ }
4158
+ });
4159
+ Object.defineProperty(exports, "resolveWorkflowEntry", {
4160
+ enumerable: true,
4161
+ get: function() {
4162
+ return resolveWorkflowEntry;
4163
+ }
4164
+ });
4165
+ Object.defineProperty(exports, "serveNativeTerminal", {
4166
+ enumerable: true,
4167
+ get: function() {
4168
+ return serveNativeTerminal$1;
4169
+ }
4170
+ });
4171
+ Object.defineProperty(exports, "terminalSocketPath", {
4172
+ enumerable: true,
4173
+ get: function() {
4174
+ return terminalSocketPath;
4175
+ }
4176
+ });
4177
+ Object.defineProperty(exports, "validateWorkflowLaunch", {
4178
+ enumerable: true,
4179
+ get: function() {
4180
+ return validateWorkflowLaunch;
4181
+ }
4182
+ });
4183
+ Object.defineProperty(exports, "workflowShellOutput", {
4184
+ enumerable: true,
4185
+ get: function() {
4186
+ return workflowShellOutput;
4187
+ }
4188
+ });
4189
+
4190
+ //# sourceMappingURL=workflowHost-B8ludUOG.cjs.map