@osolmaz/pi-workflows 0.11.0 → 0.11.2

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 (36) hide show
  1. package/README.md +14 -2
  2. package/dist/builtins/autoimplement.workflow.d.ts +2 -0
  3. package/dist/builtins/autoimplement.workflow.js +186 -9
  4. package/dist/builtins/autoimplement.workflow.js.map +1 -1
  5. package/dist/controllers/sqlite.d.ts +55 -7
  6. package/dist/controllers/sqlite.js +195 -48
  7. package/dist/controllers/sqlite.js.map +1 -1
  8. package/dist/extension/index.js +246 -54
  9. package/dist/extension/index.js.map +1 -1
  10. package/dist/herdr/setup.d.ts +13 -1
  11. package/dist/herdr/setup.js +349 -36
  12. package/dist/herdr/setup.js.map +1 -1
  13. package/dist/host/runner.js +3 -0
  14. package/dist/host/runner.js.map +1 -1
  15. package/dist/viewer/cli.d.ts +1 -0
  16. package/dist/viewer/cli.js +21 -10
  17. package/dist/viewer/cli.js.map +1 -1
  18. package/dist/workflows/migrate-sources.d.ts +1 -1
  19. package/dist/workflows/migrate-sources.js.map +1 -1
  20. package/dist/workflows/tool-input.d.ts +1 -0
  21. package/dist/workflows/tool-input.js +2 -2
  22. package/dist/workflows/tool-input.js.map +1 -1
  23. package/docs/2026-08-20-durable-workflow-launch-plan.md +449 -0
  24. package/docs/plans/2026-08-20-autoimplement-blocker-challenge-plan.md +138 -0
  25. package/docs/plans/2026-08-20-herdr-plugin-sync-plan.md +104 -0
  26. package/docs/workflows.md +11 -0
  27. package/herdr-plugin.toml +1 -1
  28. package/package.json +1 -1
  29. package/src/builtins/autoimplement.workflow.ts +212 -9
  30. package/src/controllers/sqlite.ts +308 -54
  31. package/src/extension/index.ts +303 -58
  32. package/src/herdr/setup.ts +429 -39
  33. package/src/host/runner.ts +3 -0
  34. package/src/viewer/cli.ts +22 -10
  35. package/src/workflows/migrate-sources.ts +5 -1
  36. package/src/workflows/tool-input.ts +5 -2
@@ -3,83 +3,469 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { HERDR_PLUGIN_ID } from "./constants.js";
5
5
 
6
- export type HerdrSetupResult = {
6
+ const PACKAGE_NAME = "@osolmaz/pi-workflows";
7
+ const MANIFEST_NAME = "herdr-plugin.toml";
8
+ const VIEWER_PATH = "plugins/herdr/viewer.mjs";
9
+ const RESULT_SCHEMA = "pi-workflows.herdr-sync.v1" as const;
10
+ const MAX_COMMAND_OUTPUT_BYTES = 1024 * 1024;
11
+
12
+ export type HerdrSyncStatus = "linked" | "relinked" | "enabled" | "unchanged" | "unavailable";
13
+
14
+ export type HerdrSyncResult = {
15
+ schema: typeof RESULT_SCHEMA;
16
+ status: HerdrSyncStatus;
7
17
  changed: boolean;
18
+ pluginId: string;
19
+ expectedVersion: string;
20
+ effectiveVersion: string | null;
21
+ enabled: boolean | null;
22
+ runningPiProcessesNeedReload: true;
8
23
  message: string;
9
24
  };
10
25
 
26
+ export type HerdrSetupResult = HerdrSyncResult;
27
+
11
28
  type Spawn = (command: string, args: readonly string[]) => SpawnSyncReturns<string>;
12
29
 
13
- export function setupHerdrPlugin(packageRoot: string, spawn: Spawn = runCommand): HerdrSetupResult {
14
- const root = path.resolve(packageRoot);
15
- const manifest = path.join(root, "herdr-plugin.toml");
16
- if (!fs.existsSync(manifest)) {
17
- throw new Error(`Herdr plugin manifest not found: ${manifest}`);
30
+ type PluginPackage = {
31
+ root: string;
32
+ manifestPath: string;
33
+ version: string;
34
+ };
35
+
36
+ type InstalledPlugin = {
37
+ root: string;
38
+ manifestPath: string;
39
+ version: string;
40
+ enabled: boolean;
41
+ warnings: string[];
42
+ };
43
+
44
+ type Inspection = { available: true; plugin: InstalledPlugin | undefined } | { available: false };
45
+
46
+ type MutationResult = { ok: true } | { ok: false; error: string };
47
+
48
+ type RollbackTarget = { package: PluginPackage; enabled: boolean };
49
+
50
+ export function syncHerdrPlugin(packageRoot: string, spawn: Spawn = runCommand): HerdrSyncResult {
51
+ const expected = preflightPackage(packageRoot);
52
+ const initial = inspectHerdr(spawn, true);
53
+ if (!initial.available) {
54
+ return result("unavailable", false, expected.version, undefined);
18
55
  }
19
56
 
20
- const listed = spawn("herdr", ["plugin", "list", "--plugin", HERDR_PLUGIN_ID, "--json"]);
21
- if (listed.error) throw new Error(`Could not run Herdr: ${listed.error.message}`);
22
- if (listed.status !== 0) {
23
- throw new Error(`Could not inspect Herdr plugins: ${bounded(listed.stderr || listed.stdout)}`);
57
+ const installed = initial.plugin;
58
+ if (installed === undefined) {
59
+ const linked = mutate(spawn, "link", [expected.root]);
60
+ const adopted = verifyOrExplain(spawn, expected);
61
+ if (adopted.plugin !== undefined && matchesExpected(adopted.plugin, expected, true)) {
62
+ return result("linked", true, expected.version, adopted.plugin);
63
+ }
64
+ throw mutationError("link", linked, adopted.problem);
24
65
  }
25
- const installed = installedPlugin(listed.stdout);
26
- if (installed !== undefined) {
27
- if (path.resolve(installed.root) !== root) {
28
- throw new Error(
29
- `Herdr plugin ${HERDR_PLUGIN_ID} is already registered from ${installed.root}. Unlink it before linking ${root}.`,
30
- );
66
+
67
+ if (matchesExpected(installed, expected, true)) {
68
+ return result("unchanged", false, expected.version, installed);
69
+ }
70
+
71
+ if (matchesExpected(installed, expected, false) && !installed.enabled) {
72
+ const enabled = mutate(spawn, "enable", [HERDR_PLUGIN_ID]);
73
+ const adopted = verifyOrExplain(spawn, expected);
74
+ if (adopted.plugin !== undefined && matchesExpected(adopted.plugin, expected, true)) {
75
+ return result("enabled", true, expected.version, adopted.plugin);
31
76
  }
32
- if (installed.enabled) {
33
- return { changed: false, message: `Herdr plugin ${HERDR_PLUGIN_ID} is already linked.` };
77
+ throw mutationError("enable", enabled, adopted.problem);
78
+ }
79
+
80
+ const rollback = rollbackTarget(installed);
81
+ const unlinked = mutate(spawn, "unlink", [HERDR_PLUGIN_ID]);
82
+ const afterUnlink = inspectHerdr(spawn, false);
83
+ if (!afterUnlink.available) throw new Error("Herdr became unavailable during synchronization.");
84
+ if (afterUnlink.plugin !== undefined) {
85
+ if (matchesExpected(afterUnlink.plugin, expected, true)) {
86
+ return result("relinked", true, expected.version, afterUnlink.plugin);
34
87
  }
35
- const enabled = spawn("herdr", ["plugin", "enable", HERDR_PLUGIN_ID]);
36
- if (enabled.error) throw new Error(`Could not run Herdr: ${enabled.error.message}`);
37
- if (enabled.status !== 0) {
38
- throw new Error(
39
- `Could not enable the Herdr plugin: ${bounded(enabled.stderr || enabled.stdout)}`,
40
- );
88
+ throw mutationError(
89
+ "unlink the stale registration",
90
+ unlinked,
91
+ "Herdr still reports a conflicting registration.",
92
+ );
93
+ }
94
+
95
+ const linked = mutate(spawn, "link", [expected.root]);
96
+ const adopted = verifyOrExplain(spawn, expected);
97
+ if (adopted.plugin !== undefined && matchesExpected(adopted.plugin, expected, true)) {
98
+ return result("relinked", true, expected.version, adopted.plugin);
99
+ }
100
+
101
+ const rollbackMessage = restorePrevious(spawn, expected, rollback);
102
+ throw new Error(
103
+ `${mutationError("link the current package", linked, adopted.problem).message} ${rollbackMessage}`,
104
+ );
105
+ }
106
+
107
+ /** Compatibility alias for callers that used the original setup API. */
108
+ export function setupHerdrPlugin(packageRoot: string, spawn: Spawn = runCommand): HerdrSetupResult {
109
+ return syncHerdrPlugin(packageRoot, spawn);
110
+ }
111
+
112
+ function preflightPackage(packageRoot: string): PluginPackage {
113
+ const requestedRoot = path.resolve(packageRoot);
114
+ let root: string;
115
+ try {
116
+ root = fs.realpathSync(requestedRoot);
117
+ } catch (error) {
118
+ throw new Error(`Pi Workflows package root is missing: ${requestedRoot}`, { cause: error });
119
+ }
120
+ if (!fs.statSync(root).isDirectory()) {
121
+ throw new Error(`Pi Workflows package root is not a directory: ${requestedRoot}`);
122
+ }
123
+ const packagePath = checkedRegularFile(root, "package.json");
124
+ const manifestPath = checkedRegularFile(root, MANIFEST_NAME);
125
+ const packageJson = parseJsonObject(fs.readFileSync(packagePath, "utf8"), "package.json");
126
+ if (packageJson["name"] !== PACKAGE_NAME) {
127
+ throw new Error(`Unexpected Pi Workflows package name in ${packagePath}.`);
128
+ }
129
+ const packageVersion = packageJson["version"];
130
+ if (typeof packageVersion !== "string" || packageVersion.length === 0) {
131
+ throw new Error(`Pi Workflows package version is missing in ${packagePath}.`);
132
+ }
133
+
134
+ const manifest = fs.readFileSync(manifestPath, "utf8");
135
+ const topLevelManifest = manifest.split(/^\s*\[\[/mu, 1)[0] ?? "";
136
+ const pluginId = tomlString(topLevelManifest, "id", manifestPath);
137
+ const pluginVersion = tomlString(topLevelManifest, "version", manifestPath);
138
+ tomlString(topLevelManifest, "min_herdr_version", manifestPath);
139
+ const platforms = tomlStringArray(topLevelManifest, "platforms", manifestPath);
140
+ const command = tomlStringArray(manifest, "command", manifestPath);
141
+ if (pluginId !== HERDR_PLUGIN_ID) {
142
+ throw new Error(`Unexpected Herdr plugin ID in ${manifestPath}.`);
143
+ }
144
+ if (pluginVersion !== packageVersion) {
145
+ throw new Error(`Herdr plugin version does not match package version ${packageVersion}.`);
146
+ }
147
+ const platform = process.platform === "darwin" ? "macos" : process.platform;
148
+ if (!platforms.includes(platform)) {
149
+ throw new Error(`Herdr plugin does not support platform ${platform}.`);
150
+ }
151
+ if (command.length !== 2 || command[0] !== "node" || command[1] !== VIEWER_PATH) {
152
+ throw new Error(`Unexpected Herdr plugin viewer command in ${manifestPath}.`);
153
+ }
154
+ checkedRegularFile(root, VIEWER_PATH);
155
+ return { root, manifestPath, version: packageVersion };
156
+ }
157
+
158
+ function checkedRegularFile(root: string, relativePath: string): string {
159
+ const target = path.resolve(root, relativePath);
160
+ if (!isWithin(root, target)) {
161
+ throw new Error(`Package file escapes the package root: ${relativePath}`);
162
+ }
163
+ const stat = statOrThrow(target, `Package file ${relativePath}`);
164
+ if (!stat.isFile() || stat.isSymbolicLink()) {
165
+ throw new Error(`Package file is not a regular file: ${relativePath}`);
166
+ }
167
+ const real = fs.realpathSync(target);
168
+ if (!isWithin(root, real)) {
169
+ throw new Error(`Package file resolves outside the package root: ${relativePath}`);
170
+ }
171
+ return real;
172
+ }
173
+
174
+ function isWithin(root: string, target: string): boolean {
175
+ const relative = path.relative(root, target);
176
+ return relative === "" || (!relative.startsWith(`..${path.sep}`) && relative !== "..");
177
+ }
178
+
179
+ function statOrThrow(target: string, label: string): fs.Stats {
180
+ try {
181
+ return fs.lstatSync(target);
182
+ } catch (error) {
183
+ throw new Error(`${label} is missing: ${target}`, { cause: error });
184
+ }
185
+ }
186
+
187
+ function parseJsonObject(text: string, label: string): Record<string, unknown> {
188
+ let value: unknown;
189
+ try {
190
+ value = JSON.parse(text) as unknown;
191
+ } catch (error) {
192
+ throw new Error(`${label} is not valid JSON.`, { cause: error });
193
+ }
194
+ if (!isRecord(value)) throw new Error(`${label} must contain a JSON object.`);
195
+ return value;
196
+ }
197
+
198
+ function tomlString(text: string, key: string, manifestPath: string): string {
199
+ const expressions = matches(
200
+ text,
201
+ new RegExp(String.raw`^\s*${escapeRegExp(key)}\s*=\s*("(?:[^"\\]|\\.)*")\s*(?:#.*)?$`, "gmu"),
202
+ );
203
+ if (expressions.length !== 1) {
204
+ throw new Error(`Herdr manifest must contain one ${key} string: ${manifestPath}`);
205
+ }
206
+ try {
207
+ const value: unknown = JSON.parse(expressions[0] as string);
208
+ if (typeof value !== "string" || value.length === 0) throw new Error("empty string");
209
+ return value;
210
+ } catch (error) {
211
+ throw new Error(`Herdr manifest has an invalid ${key} string: ${manifestPath}`, {
212
+ cause: error,
213
+ });
214
+ }
215
+ }
216
+
217
+ function tomlStringArray(text: string, key: string, manifestPath: string): string[] {
218
+ const expressions = matches(
219
+ text,
220
+ new RegExp(
221
+ String.raw`^\s*${escapeRegExp(key)}\s*=\s*(\[(?:[^\]"\\]|"(?:[^"\\]|\\.)*")*\])\s*(?:#.*)?$`,
222
+ "gmu",
223
+ ),
224
+ );
225
+ if (expressions.length !== 1) {
226
+ throw new Error(`Herdr manifest must contain one ${key} string array: ${manifestPath}`);
227
+ }
228
+ try {
229
+ const value: unknown = JSON.parse(expressions[0] as string);
230
+ if (
231
+ !Array.isArray(value) ||
232
+ value.length === 0 ||
233
+ value.some((item) => typeof item !== "string")
234
+ ) {
235
+ throw new Error("invalid string array");
41
236
  }
42
- return { changed: true, message: `Enabled Herdr plugin ${HERDR_PLUGIN_ID}.` };
237
+ return value as string[];
238
+ } catch (error) {
239
+ throw new Error(`Herdr manifest has an invalid ${key} string array: ${manifestPath}`, {
240
+ cause: error,
241
+ });
43
242
  }
243
+ }
44
244
 
45
- const linked = spawn("herdr", ["plugin", "link", root]);
46
- if (linked.error) throw new Error(`Could not run Herdr: ${linked.error.message}`);
47
- if (linked.status !== 0) {
48
- throw new Error(`Could not link the Herdr plugin: ${bounded(linked.stderr || linked.stdout)}`);
245
+ function matches(text: string, expression: RegExp): string[] {
246
+ const values: string[] = [];
247
+ for (const match of text.matchAll(expression)) {
248
+ const value = match[1];
249
+ if (value !== undefined) values.push(value);
49
250
  }
50
- return { changed: true, message: `Linked Herdr plugin ${HERDR_PLUGIN_ID} from ${root}.` };
251
+ return values;
252
+ }
253
+
254
+ function escapeRegExp(value: string): string {
255
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
51
256
  }
52
257
 
53
- function installedPlugin(stdout: string): { root: string; enabled: boolean } | undefined {
258
+ function inspectHerdr(spawn: Spawn, allowUnavailable: boolean): Inspection {
259
+ const listed = spawn("herdr", ["plugin", "list", "--plugin", HERDR_PLUGIN_ID, "--json"]);
260
+ if (listed.error !== undefined) {
261
+ if (allowUnavailable && errorCode(listed.error) === "ENOENT") return { available: false };
262
+ throw new Error(`Could not run Herdr: ${listed.error.message}`);
263
+ }
264
+ if (listed.status !== 0) {
265
+ throw new Error(`Could not inspect Herdr plugins: ${bounded(listed.stderr || listed.stdout)}`);
266
+ }
267
+ return { available: true, plugin: installedPlugin(listed.stdout) };
268
+ }
269
+
270
+ function installedPlugin(stdout: string): InstalledPlugin | undefined {
54
271
  let value: unknown;
55
272
  try {
56
273
  value = JSON.parse(stdout) as unknown;
57
274
  } catch {
58
275
  throw new Error("Herdr returned invalid plugin JSON.");
59
276
  }
60
- if (!isRecord(value) || !isRecord(value.result) || !Array.isArray(value.result.plugins)) {
277
+ if (
278
+ !isRecord(value) ||
279
+ !isRecord(value["result"]) ||
280
+ !Array.isArray(value["result"]["plugins"])
281
+ ) {
61
282
  throw new Error("Herdr returned an invalid plugin list.");
62
283
  }
63
- for (const plugin of value.result.plugins) {
284
+ const candidates = value["result"]["plugins"].filter(
285
+ (plugin) => isRecord(plugin) && plugin["plugin_id"] === HERDR_PLUGIN_ID,
286
+ );
287
+ if (candidates.length > 1) {
288
+ throw new Error(`Herdr returned duplicate records for ${HERDR_PLUGIN_ID}.`);
289
+ }
290
+ const candidate = candidates[0];
291
+ if (candidate === undefined) return undefined;
292
+ if (
293
+ !isRecord(candidate) ||
294
+ typeof candidate["plugin_root"] !== "string" ||
295
+ typeof candidate["manifest_path"] !== "string" ||
296
+ typeof candidate["version"] !== "string" ||
297
+ typeof candidate["enabled"] !== "boolean"
298
+ ) {
299
+ throw new Error(`Herdr returned an incomplete record for ${HERDR_PLUGIN_ID}.`);
300
+ }
301
+ return {
302
+ root: normalizedPath(candidate["plugin_root"]),
303
+ manifestPath: normalizedPath(candidate["manifest_path"]),
304
+ version: candidate["version"],
305
+ enabled: candidate["enabled"],
306
+ warnings: pluginWarnings(candidate),
307
+ };
308
+ }
309
+
310
+ function pluginWarnings(plugin: Record<string, unknown>): string[] {
311
+ const warnings: string[] = [];
312
+ for (const key of ["warning", "manifest_warning"] as const) {
313
+ const value = plugin[key];
314
+ if (typeof value === "string" && value.trim().length > 0) warnings.push(value.trim());
315
+ }
316
+ const many = plugin["warnings"];
317
+ if (many !== undefined) {
318
+ if (!Array.isArray(many) || many.some((item) => typeof item !== "string")) {
319
+ throw new Error(`Herdr returned invalid warnings for ${HERDR_PLUGIN_ID}.`);
320
+ }
321
+ warnings.push(...many.filter((item) => item.trim().length > 0).map((item) => item.trim()));
322
+ }
323
+ return warnings;
324
+ }
325
+
326
+ function matchesExpected(
327
+ installed: InstalledPlugin,
328
+ expected: PluginPackage,
329
+ requireEnabled: boolean,
330
+ ): boolean {
331
+ return (
332
+ installed.root === normalizedPath(expected.root) &&
333
+ installed.manifestPath === normalizedPath(expected.manifestPath) &&
334
+ installed.version === expected.version &&
335
+ (!requireEnabled || installed.enabled) &&
336
+ installed.warnings.length === 0
337
+ );
338
+ }
339
+
340
+ function rollbackTarget(installed: InstalledPlugin): RollbackTarget | undefined {
341
+ try {
342
+ const previous = preflightPackage(installed.root);
343
+ return matchesExpected(installed, previous, installed.enabled)
344
+ ? { package: previous, enabled: installed.enabled }
345
+ : undefined;
346
+ } catch {
347
+ return undefined;
348
+ }
349
+ }
350
+
351
+ function restorePrevious(
352
+ spawn: Spawn,
353
+ expected: PluginPackage,
354
+ previous: RollbackTarget | undefined,
355
+ ): string {
356
+ if (previous === undefined) return "The previous registration could not be restored.";
357
+ try {
358
+ const current = inspectHerdr(spawn, false);
359
+ if (!current.available)
360
+ return "Herdr became unavailable; the previous registration was not restored.";
361
+ if (current.plugin !== undefined) {
362
+ if (!matchesExpected(current.plugin, expected, current.plugin.enabled)) {
363
+ return "A different registration appeared; the previous registration was not restored.";
364
+ }
365
+ const removed = mutate(spawn, "unlink", [HERDR_PLUGIN_ID]);
366
+ if (!removed.ok) return `The previous registration was not restored: ${removed.error}`;
367
+ }
368
+ const args = previous.enabled ? [previous.package.root] : [previous.package.root, "--disabled"];
369
+ const restored = mutate(spawn, "link", args);
370
+ if (!restored.ok) return `The previous registration was not restored: ${restored.error}`;
371
+ const verified = inspectHerdr(spawn, false);
64
372
  if (
65
- isRecord(plugin) &&
66
- plugin.plugin_id === HERDR_PLUGIN_ID &&
67
- typeof plugin.plugin_root === "string" &&
68
- typeof plugin.enabled === "boolean"
373
+ verified.available &&
374
+ verified.plugin !== undefined &&
375
+ matchesExpected(verified.plugin, previous.package, previous.enabled) &&
376
+ verified.plugin.enabled === previous.enabled
69
377
  ) {
70
- return { root: plugin.plugin_root, enabled: plugin.enabled };
378
+ return "The previous registration was restored.";
71
379
  }
380
+ return "Herdr did not verify the restored registration.";
381
+ } catch (error) {
382
+ return `The previous registration was not restored: ${bounded(errorMessage(error))}`;
383
+ }
384
+ }
385
+
386
+ function verifyOrExplain(
387
+ spawn: Spawn,
388
+ expected: PluginPackage,
389
+ ): { plugin?: InstalledPlugin; problem: string } {
390
+ try {
391
+ const inspected = inspectHerdr(spawn, false);
392
+ if (!inspected.available) return { problem: "Herdr became unavailable." };
393
+ if (inspected.plugin === undefined) return { problem: "Herdr reports no plugin registration." };
394
+ if (matchesExpected(inspected.plugin, expected, true)) {
395
+ return { plugin: inspected.plugin, problem: "" };
396
+ }
397
+ return {
398
+ plugin: inspected.plugin,
399
+ problem: "Herdr did not report the expected healthy registration.",
400
+ };
401
+ } catch (error) {
402
+ return { problem: errorMessage(error) };
403
+ }
404
+ }
405
+
406
+ function mutate(spawn: Spawn, action: string, args: readonly string[]): MutationResult {
407
+ const changed = spawn("herdr", ["plugin", action, ...args]);
408
+ if (changed.error !== undefined) return { ok: false, error: changed.error.message };
409
+ if (changed.status !== 0) {
410
+ return { ok: false, error: bounded(changed.stderr || changed.stdout) };
72
411
  }
73
- return undefined;
412
+ return { ok: true };
413
+ }
414
+
415
+ function mutationError(action: string, mutation: MutationResult, verification: string): Error {
416
+ const command = mutation.ok ? "The command completed" : `The command failed: ${mutation.error}`;
417
+ return new Error(`Could not ${action} the Herdr plugin. ${command}. ${verification}`);
418
+ }
419
+
420
+ function result(
421
+ status: HerdrSyncStatus,
422
+ changed: boolean,
423
+ expectedVersion: string,
424
+ effective: InstalledPlugin | undefined,
425
+ ): HerdrSyncResult {
426
+ const messages: Record<HerdrSyncStatus, string> = {
427
+ linked: `Linked Herdr plugin ${HERDR_PLUGIN_ID}.`,
428
+ relinked: `Repaired Herdr plugin ${HERDR_PLUGIN_ID}.`,
429
+ enabled: `Enabled Herdr plugin ${HERDR_PLUGIN_ID}.`,
430
+ unchanged: `Herdr plugin ${HERDR_PLUGIN_ID} is current.`,
431
+ unavailable: "Herdr is not installed; plugin synchronization was skipped.",
432
+ };
433
+ return {
434
+ schema: RESULT_SCHEMA,
435
+ status,
436
+ changed,
437
+ pluginId: HERDR_PLUGIN_ID,
438
+ expectedVersion,
439
+ effectiveVersion: effective?.version ?? null,
440
+ enabled: effective?.enabled ?? null,
441
+ runningPiProcessesNeedReload: true,
442
+ message: messages[status],
443
+ };
74
444
  }
75
445
 
76
446
  function runCommand(command: string, args: readonly string[]): SpawnSyncReturns<string> {
77
447
  return spawnSync(command, [...args], {
78
448
  encoding: "utf8",
79
449
  stdio: ["ignore", "pipe", "pipe"],
450
+ maxBuffer: MAX_COMMAND_OUTPUT_BYTES,
451
+ shell: false,
80
452
  });
81
453
  }
82
454
 
455
+ function errorCode(error: Error): string | undefined {
456
+ const value = error as Error & { code?: unknown };
457
+ return typeof value.code === "string" ? value.code : undefined;
458
+ }
459
+
460
+ function normalizedPath(value: string): string {
461
+ const resolved = path.resolve(value);
462
+ try {
463
+ return fs.realpathSync(resolved);
464
+ } catch {
465
+ return resolved;
466
+ }
467
+ }
468
+
83
469
  function bounded(value: string): string {
84
470
  const compact = value
85
471
  .replace(/[\r\n\t]+/gu, " ")
@@ -88,6 +474,10 @@ function bounded(value: string): string {
88
474
  return compact.length <= 300 ? compact : `${compact.slice(0, 299)}…`;
89
475
  }
90
476
 
477
+ function errorMessage(error: unknown): string {
478
+ return error instanceof Error ? error.message : String(error);
479
+ }
480
+
91
481
  function isRecord(value: unknown): value is Record<string, unknown> {
92
482
  return typeof value === "object" && value !== null && !Array.isArray(value);
93
483
  }
@@ -289,6 +289,9 @@ export class WorkflowHost {
289
289
  },
290
290
  },
291
291
  });
292
+ if (!store.markWorkflowRunRunning({ runId, claimToken })) {
293
+ throw new ClaimLostError(runId);
294
+ }
292
295
  const parkEngine = () => engine.park();
293
296
  this.parkedEngines.push(parkEngine);
294
297
 
package/src/viewer/cli.ts CHANGED
@@ -4,7 +4,7 @@ import path from "node:path";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
5
5
  import { SqliteControllerStore } from "../controllers/sqlite.js";
6
6
  import { projectControllerStoreBaseDir } from "../controllers/store.js";
7
- import { setupHerdrPlugin } from "../herdr/setup.js";
7
+ import { syncHerdrPlugin } from "../herdr/setup.js";
8
8
  import { sanitizeText } from "../render/ansi.js";
9
9
  import { listRunBundles, readRunBundle, workflowRunsBaseDir } from "../workflows/store.js";
10
10
  import {
@@ -24,7 +24,8 @@ Usage:
24
24
  pi-workflows controllers [--controller-dir <dir>]
25
25
  pi-workflows controller <controller> <key> [--controller-dir <dir>]
26
26
  pi-workflows host [--project <dir>] [-- <extra pi args>]
27
- pi-workflows herdr setup
27
+ pi-workflows herdr sync [--json]
28
+ pi-workflows herdr setup [--json]
28
29
 
29
30
  Commands:
30
31
  view Open the live workflow TUI. With --once, print a snapshot.
@@ -32,13 +33,14 @@ Commands:
32
33
  controllers List durable controller resources.
33
34
  controller Show one resource, its effects, child workflows, and events.
34
35
  host Run the always-on workflow host in the foreground.
35
- herdr Set up the bundled Herdr plugin.
36
+ herdr Synchronize the bundled Herdr plugin. setup is an alias for sync.
36
37
 
37
38
  Options:
38
39
  --dir <runsDir> Runs directory (default: ~/.pi/agent/workflows/runs)
39
40
  --controller-dir <dir> Controller directory (default: project-scoped local store)
40
41
  --once Render once without the interactive TUI
41
42
  --project <dir> Project directory for the host (default: cwd)
43
+ --json Print a versioned JSON result for herdr sync
42
44
  `;
43
45
 
44
46
  export type CliArgs = {
@@ -50,6 +52,7 @@ export type CliArgs = {
50
52
  dir: string;
51
53
  controllerDir: string;
52
54
  once: boolean;
55
+ json: boolean;
53
56
  project?: string | undefined;
54
57
  piArgs?: string[] | undefined;
55
58
  };
@@ -60,6 +63,7 @@ export function parseCliArgs(argv: string[]): CliArgs {
60
63
  let dir = workflowRunsBaseDir();
61
64
  let controllerDir = projectControllerStoreBaseDir(process.cwd());
62
65
  let once = false;
66
+ let json = false;
63
67
  const positionals: string[] = [];
64
68
  let project: string | undefined;
65
69
  const piArgs: string[] = [];
@@ -74,8 +78,10 @@ export function parseCliArgs(argv: string[]): CliArgs {
74
78
  project = requiredValue(args, "--project");
75
79
  } else if (arg === "--once") {
76
80
  once = true;
81
+ } else if (arg === "--json") {
82
+ json = true;
77
83
  } else if (arg === "--help" || arg === "-h") {
78
- return { command: "help", dir, controllerDir, once };
84
+ return { command: "help", dir, controllerDir, once, json };
79
85
  } else if (arg === "--") {
80
86
  piArgs.push(...args.splice(0));
81
87
  } else if (arg.startsWith("-")) {
@@ -85,8 +91,12 @@ export function parseCliArgs(argv: string[]): CliArgs {
85
91
  }
86
92
  }
87
93
 
94
+ if (command !== "herdr" && json) {
95
+ throw new Error("--json is available only for herdr sync");
96
+ }
97
+
88
98
  if (command === "host") {
89
- return { command, dir, controllerDir, once, project, piArgs };
99
+ return { command, dir, controllerDir, once, json, project, piArgs };
90
100
  }
91
101
 
92
102
  if (command === "controller") {
@@ -100,13 +110,14 @@ export function parseCliArgs(argv: string[]): CliArgs {
100
110
  dir,
101
111
  controllerDir,
102
112
  once,
113
+ json,
103
114
  };
104
115
  }
105
116
  if (command === "herdr") {
106
- if (positionals.length !== 1 || positionals[0] !== "setup") {
107
- throw new Error("herdr requires the setup action");
117
+ if (positionals.length !== 1 || (positionals[0] !== "sync" && positionals[0] !== "setup")) {
118
+ throw new Error("herdr requires the sync action");
108
119
  }
109
- return { command, herdrAction: positionals[0], dir, controllerDir, once };
120
+ return { command, herdrAction: positionals[0], dir, controllerDir, once, json };
110
121
  }
111
122
  if (positionals.length > 1) {
112
123
  throw new Error(`Unexpected argument: ${positionals[1]}`);
@@ -117,6 +128,7 @@ export function parseCliArgs(argv: string[]): CliArgs {
117
128
  dir,
118
129
  controllerDir,
119
130
  once,
131
+ json,
120
132
  };
121
133
  }
122
134
 
@@ -240,8 +252,8 @@ export async function main(argv: string[] = process.argv.slice(2)): Promise<numb
240
252
  return await runHost(args.project ?? process.cwd(), args.piArgs);
241
253
  }
242
254
  if (args.command === "herdr") {
243
- const result = setupHerdrPlugin(packageRoot());
244
- process.stdout.write(`${result.message}\n`);
255
+ const result = syncHerdrPlugin(packageRoot());
256
+ process.stdout.write(args.json ? `${JSON.stringify(result)}\n` : `${result.message}\n`);
245
257
  return 0;
246
258
  }
247
259
  if (args.command === "view") {
@@ -24,7 +24,11 @@ export type LegacySourceMigrationQueue = {
24
24
  leaseMs: number;
25
25
  }): boolean;
26
26
  parkWorkflowRun(options: { runId: string; claimToken: string }): boolean;
27
- getWorkflowRun(runId: string): { status: "claimed" | "parked" | "done" } | undefined;
27
+ getWorkflowRun(runId: string):
28
+ | {
29
+ status: "queued" | "starting" | "running" | "parked" | "done" | "failed" | "cancelled";
30
+ }
31
+ | undefined;
28
32
  setWorkflowRunOriginSession?(runId: string, originSessionId: string): boolean;
29
33
  };
30
34
 
@@ -11,7 +11,7 @@ const inputSchema = Type.Unknown({
11
11
  description: "Checkpoint answer for answer; optional structured workflow input for start",
12
12
  });
13
13
  const runIdSchema = Type.String({
14
- description: "Run id; optional for status and answer",
14
+ description: "Run id; optional for status, cancel, and answer",
15
15
  });
16
16
  const stepSchema = Type.String({
17
17
  description: "Workflow step id; required when action is update or submit",
@@ -50,7 +50,10 @@ export const WorkflowActionSchemas = {
50
50
  ),
51
51
  pause: Type.Object({ action: Type.Literal("pause") }, noExtraProperties),
52
52
  resume: Type.Object({ action: Type.Literal("resume") }, noExtraProperties),
53
- cancel: Type.Object({ action: Type.Literal("cancel") }, noExtraProperties),
53
+ cancel: Type.Object(
54
+ { action: Type.Literal("cancel"), runId: Type.Optional(runIdSchema) },
55
+ noExtraProperties,
56
+ ),
54
57
  answer: Type.Object(
55
58
  {
56
59
  action: Type.Literal("answer"),