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