@agimon-ai/po-workflow 0.0.0-alpha.170 → 0.0.0-alpha.171

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.
@@ -4,7 +4,7 @@ Object.defineProperties(exports, {
4
4
  });
5
5
  const require_workflowHost = require("../workflowHost-BZETMrK7.cjs");
6
6
  const require_contract = require("../contract-D80yV2d-.cjs");
7
- const require_workflow = require("../workflow-0eRzYn02.cjs");
7
+ const require_workflowServices = require("../workflowServices-DYXhIDVE.cjs");
8
8
  let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
9
9
  let node_path = require("node:path");
10
10
  node_path = require_workflowHost.__toESM(node_path, 1);
@@ -35,556 +35,6 @@ let _agimon_ai_po_core_notification = require("@agimon-ai/po-core/notification")
35
35
  let _agimon_ai_po_core_readiness = require("@agimon-ai/po-core/readiness");
36
36
  let _agimon_ai_po_core_help = require("@agimon-ai/po-core/help");
37
37
  let typebox = require("typebox");
38
- //#region src/services/WorkflowProgressService/index.ts
39
- /**
40
- * Progress log for a workflow run, kept as events in the workflow store.
41
- *
42
- * DESIGN PATTERNS:
43
- * - One `progress` event per transition, under the generation that made it. The
44
- * store is shared by every process and host, so a transition is visible to any
45
- * reader the moment it commits and survives a crash.
46
- * - Best-effort writes. Progress is an observability signal, never a
47
- * correctness one, so a failure to record must not fail the run.
48
- * - A recovered run keeps its history: readers fold every earlier generation of
49
- * the lineage before the one asked for.
50
- *
51
- * CODING STANDARDS:
52
- * - Named exports only
53
- * - Explicit return types on exported members
54
- *
55
- * AVOID:
56
- * - Reading progress from files: the store is the only authority
57
- * - Throwing from `record`: the run is the product, this is the commentary
58
- */
59
- /** The store event kind a progress transition is recorded under. */
60
- const PROGRESS_EVENT_KIND = "progress";
61
- const PHASE_JOB_POST$1 = "post";
62
- /** Classify a recorded job name as a phase block or a real job. */
63
- function workflowRunPhase(job) {
64
- if (job === "pre") return "pre";
65
- if (job === "post") return PHASE_JOB_POST$1;
66
- return "job";
67
- }
68
- /** Records job and step transitions for one run. */
69
- var WorkflowProgressService = class {
70
- sink;
71
- now;
72
- constructor(sink, now = () => (/* @__PURE__ */ new Date()).toISOString()) {
73
- this.sink = sink;
74
- this.now = now;
75
- }
76
- /**
77
- * Record one transition.
78
- *
79
- * Swallows write failures on purpose: a busy or unavailable database should not
80
- * turn a passing workflow into a failing one.
81
- */
82
- async record(event) {
83
- if (!this.sink) return;
84
- try {
85
- await this.sink.store.appendEvent(this.sink.runId, {
86
- kind: PROGRESS_EVENT_KIND,
87
- payload: {
88
- ...event,
89
- at: this.now()
90
- }
91
- });
92
- this.sink.onRecorded?.();
93
- } catch {}
94
- }
95
- jobStarted(job, index, total) {
96
- return this.record({
97
- type: "job",
98
- status: "running",
99
- job,
100
- index,
101
- total
102
- });
103
- }
104
- jobFinished(job, status, reason) {
105
- return this.record({
106
- type: "job",
107
- status,
108
- job,
109
- ...reason ? { reason } : {}
110
- });
111
- }
112
- /** A job a forward jump passed over: it never ran, so it never started either. */
113
- jobSkipped(job, reason) {
114
- return this.record({
115
- type: "job",
116
- status: "skipped",
117
- job,
118
- ...reason ? { reason } : {}
119
- });
120
- }
121
- /** `group` names the parallel group a step runs in, beside the other steps of that group. */
122
- stepStarted(job, step, index, total, group) {
123
- return this.record({
124
- type: "step",
125
- status: "running",
126
- job,
127
- step,
128
- index,
129
- total,
130
- ...group ? { group } : {}
131
- });
132
- }
133
- /** A host executor started the step; the ref says where a reader can follow it. */
134
- stepExecutionStarted(job, step, ref) {
135
- return this.record({
136
- type: "step",
137
- status: "running",
138
- job,
139
- step,
140
- ref
141
- });
142
- }
143
- stepFinished(job, step, status, reason) {
144
- return this.record({
145
- type: "step",
146
- status,
147
- job,
148
- step,
149
- ...reason ? { reason } : {}
150
- });
151
- }
152
- };
153
- function progressEvents(events) {
154
- const parsed = [];
155
- for (const event of events) {
156
- if (event.kind !== "progress") continue;
157
- const result = require_workflowHost.WorkflowProgressEventSchema.safeParse(event.payload);
158
- if (result.success) parsed.push(result.data);
159
- }
160
- return parsed;
161
- }
162
- /** The generations whose progress a run shows: its lineage up to and including itself. */
163
- async function progressGenerations(store, runId) {
164
- const run = await store.readRun(runId);
165
- if (!run) return [runId];
166
- return (await store.listLineage(run.lineageId)).filter((candidate) => candidate.generation <= run.generation).map((candidate) => candidate.runId);
167
- }
168
- /**
169
- * Read only what a run has recorded since `cursor`.
170
- *
171
- * Store sequences are per generation, so the cursor keeps one position per
172
- * generation. A recovered run's earlier generations are finished, and a reader
173
- * that already drained them reads nothing more from them.
174
- */
175
- async function readWorkflowProgressFrom(store, runId, cursor = {}) {
176
- const next = { ...cursor };
177
- const events = [];
178
- for (const generation of await progressGenerations(store, runId)) for (;;) {
179
- const recorded = await store.eventsAfter(generation, next[generation] ?? 0);
180
- const last = recorded.at(-1);
181
- if (!last) break;
182
- next[generation] = last.sequence;
183
- events.push(...progressEvents(recorded));
184
- }
185
- return {
186
- events,
187
- cursor: next
188
- };
189
- }
190
- /** Read a run's whole progress log, earlier generations first. */
191
- async function readWorkflowProgress(store, runId) {
192
- return (await readWorkflowProgressFrom(store, runId)).events;
193
- }
194
- /**
195
- * Fold the event log into the current job tree.
196
- *
197
- * Later events win, so a job that started and later failed reads as failed.
198
- * This is what a progress view renders: completed jobs collapse, the running
199
- * one expands.
200
- */
201
- function summarizeWorkflowProgress(events) {
202
- const jobs = /* @__PURE__ */ new Map();
203
- for (const event of events) {
204
- const job = jobs.get(event.job) ?? {
205
- name: event.job,
206
- status: "running",
207
- steps: []
208
- };
209
- if (event.type === "job") {
210
- job.status = event.status;
211
- if (event.index !== void 0) job.index = event.index;
212
- if (event.total !== void 0) job.total = event.total;
213
- if (event.reason) job.reason = event.reason;
214
- } else if (event.step) {
215
- const existing = job.steps.find((step) => step.name === event.step);
216
- if (existing) {
217
- existing.status = event.status;
218
- if (event.reason) existing.reason = event.reason;
219
- if (event.ref) existing.ref = event.ref;
220
- if (event.group) existing.group = event.group;
221
- } else job.steps.push({
222
- name: event.step,
223
- status: event.status,
224
- ...event.reason ? { reason: event.reason } : {},
225
- ...event.ref ? { ref: event.ref } : {},
226
- ...event.group ? { group: event.group } : {}
227
- });
228
- }
229
- jobs.set(event.job, job);
230
- }
231
- return [...jobs.values()];
232
- }
233
- //#endregion
234
- //#region src/services/WorkflowRunObserverService/types.ts
235
- /**
236
- * Event contract for observing workflow runs this process does not host.
237
- *
238
- * DESIGN PATTERNS:
239
- * - Named channels with typed payloads, so a subscriber asks for the one thing
240
- * it renders rather than switching over a union
241
- * - Every payload carries the whole record, because a caller that has the
242
- * record needs no follow-up read to answer "whose run, and how is it going"
243
- *
244
- * CODING STANDARDS:
245
- * - Named exports only
246
- * - Explicit return types on exported members
247
- *
248
- * AVOID:
249
- * - Events the files cannot support. A launch handed to a terminal launcher
250
- * writes nothing and never learns its own run key, so there is no
251
- * `delegated` event; `runStarted` fires when the run registers itself.
252
- */
253
- const WORKFLOW_REGISTRY_OBSERVER_SERVICE = "po/workflow-registry-observer";
254
- const WORKFLOW_REGISTRY_OBSERVER_CONTRACT = (0, _agimon_ai_po_core_extensionFile.defineServiceContract)(WORKFLOW_REGISTRY_OBSERVER_SERVICE, { scope: "host" });
255
- //#endregion
256
- //#region src/services/WorkflowRunObserverService/index.ts
257
- /**
258
- * Pushes workflow run lifecycle to a subscriber that does not host the run.
259
- *
260
- * DESIGN PATTERNS:
261
- * - Reconcile-and-diff. A sweep lists the registry, compares it against what
262
- * was last reported, and emits the difference. Every event is derived from
263
- * the same code path, so a notification-driven sweep and the periodic one
264
- * cannot disagree.
265
- * - Notifications are an optimisation, not the mechanism. The registry reports
266
- * writes made through this process, so they only ever schedule a sweep
267
- * sooner. Correctness rests on the interval, which is why a caller can turn
268
- * watching off entirely and still see everything, just later.
269
- * - Incremental log reads. Each tracked run keeps a cursor into its progress
270
- * events, so a sweep costs the transitions that happened, not the
271
- * transitions that ever happened.
272
- *
273
- * CODING STANDARDS:
274
- * - Named exports only
275
- * - Explicit return types on exported members
276
- *
277
- * AVOID:
278
- * - Emitting the same transition twice: subscribers append to a transcript, and
279
- * a repeated step reads as the run going backwards
280
- * - Reporting historical runs as news on the first sweep. The registry holds
281
- * every run the machine ever completed.
282
- */
283
- const DEFAULT_DEBOUNCE_MS = 150;
284
- /**
285
- * How often the sweep runs regardless of notifications.
286
- *
287
- * Slower than the 5s poll it replaces, because it is now the fallback rather
288
- * than the mechanism: a notification usually gets there first, and this only
289
- * has to bound how long a missed one stays missed.
290
- */
291
- const DEFAULT_RECONCILE_INTERVAL_MS = 3e4;
292
- const RUNNING_STAGE$3 = "running";
293
- /** Offer observation from non-session roots; the host elects one package copy. */
294
- function registerWorkflowRegistryObserver(plugin) {
295
- plugin.context.inject([_agimon_ai_po_core_serverPlugin.PO_HOST_SERVICES_SERVICE], (context) => (0, _agimon_ai_po_core_serverPlugin.readPoHostServices)(context)?.register(plugin.host, {
296
- packageName: "@agimon-ai/po-workflow",
297
- async activate(activation) {
298
- const observer = new WorkflowRegistryObserverService();
299
- await activation.provide(WORKFLOW_REGISTRY_OBSERVER_CONTRACT, observer);
300
- return () => observer.dispose();
301
- }
302
- }));
303
- }
304
- /** One elected instance owns the narrow watches, independent of package copies. */
305
- var WorkflowRegistryObserverService = class {
306
- entries = /* @__PURE__ */ new Map();
307
- subscribe(registry, onChange) {
308
- const directory = registry.workspacesDirectory();
309
- let entry = this.entries.get(directory);
310
- if (!entry) {
311
- const listeners = /* @__PURE__ */ new Set();
312
- entry = {
313
- listeners,
314
- unwatchRuns: registry.watchRuns(() => listeners.forEach((listener) => listener()))
315
- };
316
- this.entries.set(directory, entry);
317
- }
318
- const shared = entry;
319
- shared.listeners.add(onChange);
320
- return {
321
- update: async (_records) => {},
322
- close: () => {
323
- if (!shared.listeners.delete(onChange) || shared.listeners.size) return;
324
- if (this.entries.get(directory) === shared) this.entries.delete(directory);
325
- shared.unwatchRuns();
326
- }
327
- };
328
- }
329
- dispose() {
330
- for (const entry of this.entries.values()) entry.unwatchRuns();
331
- this.entries.clear();
332
- }
333
- };
334
- /**
335
- * Follow the registry's runs and their progress logs, and report what changes.
336
- *
337
- * Not named a control service on purpose: it only observes. Lifecycle control
338
- * already exists as `WorkflowControlService`, and the two are brought together
339
- * by `createRunControl` rather than merged here.
340
- */
341
- var WorkflowRunObserverService = class {
342
- registry;
343
- options;
344
- debounce;
345
- disposed = false;
346
- handlers = /* @__PURE__ */ new Map();
347
- reconciling = false;
348
- seen = /* @__PURE__ */ new Map();
349
- /** Epoch ms observing began, which is the line between history and news. */
350
- startedAt = 0;
351
- sweepQueued = false;
352
- timer;
353
- watcher;
354
- registryObserver;
355
- subscription;
356
- constructor(registry, options = {}) {
357
- this.registry = registry;
358
- this.options = options;
359
- this.registryObserver = options.registryObserver ?? new WorkflowRegistryObserverService();
360
- }
361
- on(name, handler) {
362
- const existing = this.handlers.get(name) ?? /* @__PURE__ */ new Set();
363
- existing.add(handler);
364
- this.handlers.set(name, existing);
365
- return () => {
366
- existing.delete(handler);
367
- };
368
- }
369
- /**
370
- * Begin observing, reporting the runs already in flight.
371
- *
372
- * Awaits the first sweep so a caller that subscribes and then asks "what is
373
- * running" gets an answer rather than a race.
374
- */
375
- async start() {
376
- if (this.disposed) return;
377
- this.startedAt = Date.now();
378
- await this.reconcile();
379
- if (this.disposed) return;
380
- const interval = this.options.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;
381
- if (interval > 0) {
382
- this.timer ??= setInterval(() => void this.reconcile(), interval);
383
- this.timer.unref?.();
384
- }
385
- this.attachWatcher();
386
- }
387
- /** Sweep now, rather than waiting for the interval. */
388
- async refresh() {
389
- await this.reconcile();
390
- }
391
- dispose() {
392
- this.disposed = true;
393
- if (this.timer) clearInterval(this.timer);
394
- this.timer = void 0;
395
- if (this.debounce) clearTimeout(this.debounce);
396
- this.debounce = void 0;
397
- this.subscription?.close();
398
- this.subscription = void 0;
399
- this.watcher?.close();
400
- this.watcher = void 0;
401
- this.handlers.clear();
402
- this.seen.clear();
403
- }
404
- /**
405
- * Watch the registry tree, tolerating a tree that is not there yet.
406
- *
407
- * Re-attempted on every sweep, because the directory is created by whichever
408
- * process registers the first run, which may well be later than this.
409
- */
410
- watching = false;
411
- async attachWatcher() {
412
- if (this.watcher || this.subscription || this.disposed || this.watching) return;
413
- this.watching = true;
414
- try {
415
- if (this.options.watch) this.watcher = this.options.watch(this.registry.workspacesDirectory(), () => this.scheduleSweep());
416
- else this.subscription ??= this.registryObserver.subscribe(this.registry, () => this.scheduleSweep());
417
- } catch {} finally {
418
- this.watching = false;
419
- }
420
- }
421
- /**
422
- * Coalesce a burst of notifications into one sweep.
423
- *
424
- * A job start records a progress event and a cursor update in quick
425
- * succession, and each one notifies.
426
- */
427
- scheduleSweep() {
428
- if (this.disposed || this.debounce) return;
429
- this.debounce = setTimeout(() => {
430
- this.debounce = void 0;
431
- this.reconcile();
432
- }, this.options.debounceMs ?? DEFAULT_DEBOUNCE_MS);
433
- this.debounce.unref?.();
434
- }
435
- /**
436
- * List, diff, emit.
437
- *
438
- * Serialised, because two overlapping sweeps would both read the same
439
- * progress events and report every transition twice. A sweep requested while
440
- * one is running is remembered and run once afterwards, so the change that
441
- * prompted it is never simply dropped.
442
- */
443
- async reconcile() {
444
- if (this.disposed) return;
445
- if (this.reconciling) {
446
- this.sweepQueued = true;
447
- return;
448
- }
449
- this.reconciling = true;
450
- try {
451
- do {
452
- this.sweepQueued = false;
453
- await this.sweep();
454
- } while (this.sweepQueued && !this.disposed);
455
- } finally {
456
- this.reconciling = false;
457
- }
458
- }
459
- async sweep() {
460
- this.attachWatcher();
461
- let records;
462
- try {
463
- records = await this.registry.listRuns();
464
- } catch {
465
- return;
466
- }
467
- try {
468
- await this.subscription?.update(records);
469
- } catch {}
470
- if (this.disposed) return;
471
- const filter = this.options.recordFilter;
472
- const visible = filter ? records.filter((record) => filter(record)) : records;
473
- const live = /* @__PURE__ */ new Set();
474
- for (const record of visible) {
475
- const identity = runIdentity(record);
476
- live.add(identity);
477
- const terminal = record.stage !== RUNNING_STAGE$3 || record.stale === true;
478
- let tracked = this.seen.get(identity);
479
- if (tracked?.finished) continue;
480
- if (!tracked) {
481
- if (terminal && !this.finishedWhileObserving(record)) continue;
482
- tracked = {
483
- finished: false,
484
- record,
485
- cursor: {}
486
- };
487
- this.seen.set(identity, tracked);
488
- this.emit("runStarted", {
489
- record,
490
- runKey: record.runKey,
491
- workspace: record.workspace
492
- });
493
- }
494
- await this.drainProgress(tracked, record);
495
- if (JSON.stringify(tracked.record) !== JSON.stringify(record)) {
496
- tracked.record = record;
497
- this.emit("runUpdated", {
498
- record,
499
- runKey: record.runKey,
500
- workspace: record.workspace
501
- });
502
- }
503
- if (terminal) {
504
- tracked.finished = true;
505
- this.emit("runFinished", {
506
- record,
507
- runKey: record.runKey,
508
- workspace: record.workspace,
509
- stage: record.effectiveStage ?? record.stage,
510
- ...record.effectiveOutcome ?? record.outcome ? { outcome: record.effectiveOutcome ?? record.outcome } : {},
511
- ...record.failedJob ? { failedJob: record.failedJob } : {},
512
- ...record.errorMessage ? { errorMessage: record.errorMessage } : {}
513
- });
514
- }
515
- }
516
- for (const identity of this.seen.keys()) if (!live.has(identity)) this.seen.delete(identity);
517
- }
518
- /**
519
- * Whether a run this observer never saw running finished on its watch.
520
- *
521
- * The discriminator between a run that began and ended inside one sweep,
522
- * which is news, and one that finished last week, which is not. An
523
- * unparseable timestamp counts as history: replaying an old run is worse than
524
- * missing an odd one.
525
- */
526
- finishedWhileObserving(record) {
527
- const finishedAt = Date.parse(record.finishedAt ?? record.startedAt);
528
- return Number.isFinite(finishedAt) && finishedAt >= this.startedAt;
529
- }
530
- /**
531
- * Report the transitions a run appended since the last sweep.
532
- *
533
- * A recovered run's progress includes its earlier generations, so a
534
- * subscriber sees the whole history of the run key whatever generation it is on.
535
- */
536
- async drainProgress(tracked, record) {
537
- const tail = await this.registry.readProgressFrom(record.runId, tracked.cursor);
538
- tracked.cursor = tail.cursor;
539
- for (const event of tail.events) {
540
- const shared = {
541
- at: event.at,
542
- job: event.job,
543
- phase: workflowRunPhase(event.job),
544
- record,
545
- runKey: record.runKey,
546
- status: event.status,
547
- workspace: record.workspace,
548
- ...event.reason ? { reason: event.reason } : {}
549
- };
550
- if (event.type === "step" && event.step) {
551
- this.emit("step", {
552
- ...shared,
553
- step: event.step
554
- });
555
- continue;
556
- }
557
- this.emit("job", {
558
- ...shared,
559
- ...event.index === void 0 ? {} : { index: event.index },
560
- ...event.total === void 0 ? {} : { total: event.total }
561
- });
562
- }
563
- }
564
- /**
565
- * Deliver to subscribers, absorbing their failures.
566
- *
567
- * A subscriber that throws is a rendering bug in somebody else's extension,
568
- * and it must not stop the sweep or starve every other subscriber.
569
- */
570
- emit(name, event) {
571
- const handlers = this.handlers.get(name);
572
- if (!handlers) return;
573
- for (const handler of [...handlers]) try {
574
- handler(event);
575
- } catch {}
576
- }
577
- };
578
- /**
579
- * The identity a run keeps across stage moves.
580
- *
581
- * `runId` when the record carries one; runs predating it fall back to the pair
582
- * that is unique within a workspace.
583
- */
584
- function runIdentity(record) {
585
- return record.runId ?? `${record.workspace}/${record.runKey}`;
586
- }
587
- //#endregion
588
38
  //#region src/constants/workflowStore.ts
589
39
  /** The po-db prefix every workflow table, index and migration record uses. */
590
40
  const WORKFLOW_DB_PREFIX = "workflow";
@@ -841,8 +291,8 @@ const STEP_TERMINAL_STATES = /* @__PURE__ */ new Set([
841
291
  "failed"
842
292
  ]);
843
293
  /** The engine records its pre:/post: blocks under these reserved pseudo-job names. */
844
- const PHASE_JOB_PRE = "pre";
845
- const PHASE_JOB_POST = "post";
294
+ const PHASE_JOB_PRE$1 = "pre";
295
+ const PHASE_JOB_POST$1 = "post";
846
296
  const ANSI_ESCAPE_PATTERN = /\u001b\[[0-9;]*[A-Za-z]/g;
847
297
  function isRecord(value) {
848
298
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -939,8 +389,8 @@ function parseWorkflowRunRecord(raw) {
939
389
  };
940
390
  }
941
391
  function jobPhase(name) {
942
- if (name === PHASE_JOB_PRE) return PHASE_JOB_PRE;
943
- if (name === PHASE_JOB_POST) return PHASE_JOB_POST;
392
+ if (name === PHASE_JOB_PRE$1) return PHASE_JOB_PRE$1;
393
+ if (name === PHASE_JOB_POST$1) return PHASE_JOB_POST$1;
944
394
  return "job";
945
395
  }
946
396
  /** Names match the engine's progress log, including unnamed parallel children. */
@@ -973,13 +423,13 @@ function planWorkflowJobs(workflow, order) {
973
423
  };
974
424
  });
975
425
  if (workflow.pre !== void 0) jobs.unshift({
976
- name: PHASE_JOB_PRE,
426
+ name: PHASE_JOB_PRE$1,
977
427
  phase: "pre",
978
428
  status: "pending",
979
429
  steps: plannedSteps(workflow.pre.steps)
980
430
  });
981
431
  if (workflow.post !== void 0) jobs.push({
982
- name: PHASE_JOB_POST,
432
+ name: PHASE_JOB_POST$1,
983
433
  phase: "post",
984
434
  status: "pending",
985
435
  steps: plannedSteps(workflow.post.steps)
@@ -1608,13 +1058,209 @@ var WorkflowContentService = class {
1608
1058
  if (!store) throw new WorkflowContentError("WORKFLOW_CONTENT_UNAVAILABLE", "Artifact versions need the workflow store.");
1609
1059
  return store;
1610
1060
  }
1611
- entryPath(runDir, path) {
1612
- const target = (0, node_path.resolve)(runDir, path);
1613
- const inside = (0, node_path.relative)((0, node_path.resolve)(runDir), target);
1614
- if (inside.startsWith("..") || inside === "") throw new Error(`Unsafe workflow run-directory path: ${path}`);
1615
- return target;
1061
+ entryPath(runDir, path) {
1062
+ const target = (0, node_path.resolve)(runDir, path);
1063
+ const inside = (0, node_path.relative)((0, node_path.resolve)(runDir), target);
1064
+ if (inside.startsWith("..") || inside === "") throw new Error(`Unsafe workflow run-directory path: ${path}`);
1065
+ return target;
1066
+ }
1067
+ };
1068
+ //#endregion
1069
+ //#region src/services/WorkflowProgressService/index.ts
1070
+ /**
1071
+ * Progress log for a workflow run, kept as events in the workflow store.
1072
+ *
1073
+ * DESIGN PATTERNS:
1074
+ * - One `progress` event per transition, under the generation that made it. The
1075
+ * store is shared by every process and host, so a transition is visible to any
1076
+ * reader the moment it commits and survives a crash.
1077
+ * - Best-effort writes. Progress is an observability signal, never a
1078
+ * correctness one, so a failure to record must not fail the run.
1079
+ * - A recovered run keeps its history: readers fold every earlier generation of
1080
+ * the lineage before the one asked for.
1081
+ *
1082
+ * CODING STANDARDS:
1083
+ * - Named exports only
1084
+ * - Explicit return types on exported members
1085
+ *
1086
+ * AVOID:
1087
+ * - Reading progress from files: the store is the only authority
1088
+ * - Throwing from `record`: the run is the product, this is the commentary
1089
+ */
1090
+ /** The store event kind a progress transition is recorded under. */
1091
+ const PROGRESS_EVENT_KIND = "progress";
1092
+ const PHASE_JOB_POST = "post";
1093
+ /** Classify a recorded job name as a phase block or a real job. */
1094
+ function workflowRunPhase(job) {
1095
+ if (job === "pre") return "pre";
1096
+ if (job === "post") return PHASE_JOB_POST;
1097
+ return "job";
1098
+ }
1099
+ /** Records job and step transitions for one run. */
1100
+ var WorkflowProgressService = class {
1101
+ sink;
1102
+ now;
1103
+ constructor(sink, now = () => (/* @__PURE__ */ new Date()).toISOString()) {
1104
+ this.sink = sink;
1105
+ this.now = now;
1106
+ }
1107
+ /**
1108
+ * Record one transition.
1109
+ *
1110
+ * Swallows write failures on purpose: a busy or unavailable database should not
1111
+ * turn a passing workflow into a failing one.
1112
+ */
1113
+ async record(event) {
1114
+ if (!this.sink) return;
1115
+ try {
1116
+ await this.sink.store.appendEvent(this.sink.runId, {
1117
+ kind: PROGRESS_EVENT_KIND,
1118
+ payload: {
1119
+ ...event,
1120
+ at: this.now()
1121
+ }
1122
+ });
1123
+ this.sink.onRecorded?.();
1124
+ } catch {}
1125
+ }
1126
+ jobStarted(job, index, total) {
1127
+ return this.record({
1128
+ type: "job",
1129
+ status: "running",
1130
+ job,
1131
+ index,
1132
+ total
1133
+ });
1134
+ }
1135
+ jobFinished(job, status, reason) {
1136
+ return this.record({
1137
+ type: "job",
1138
+ status,
1139
+ job,
1140
+ ...reason ? { reason } : {}
1141
+ });
1142
+ }
1143
+ /** A job a forward jump passed over: it never ran, so it never started either. */
1144
+ jobSkipped(job, reason) {
1145
+ return this.record({
1146
+ type: "job",
1147
+ status: "skipped",
1148
+ job,
1149
+ ...reason ? { reason } : {}
1150
+ });
1151
+ }
1152
+ /** `group` names the parallel group a step runs in, beside the other steps of that group. */
1153
+ stepStarted(job, step, index, total, group) {
1154
+ return this.record({
1155
+ type: "step",
1156
+ status: "running",
1157
+ job,
1158
+ step,
1159
+ index,
1160
+ total,
1161
+ ...group ? { group } : {}
1162
+ });
1163
+ }
1164
+ /** A host executor started the step; the ref says where a reader can follow it. */
1165
+ stepExecutionStarted(job, step, ref) {
1166
+ return this.record({
1167
+ type: "step",
1168
+ status: "running",
1169
+ job,
1170
+ step,
1171
+ ref
1172
+ });
1173
+ }
1174
+ stepFinished(job, step, status, reason) {
1175
+ return this.record({
1176
+ type: "step",
1177
+ status,
1178
+ job,
1179
+ step,
1180
+ ...reason ? { reason } : {}
1181
+ });
1182
+ }
1183
+ };
1184
+ function progressEvents(events) {
1185
+ const parsed = [];
1186
+ for (const event of events) {
1187
+ if (event.kind !== "progress") continue;
1188
+ const result = require_workflowHost.WorkflowProgressEventSchema.safeParse(event.payload);
1189
+ if (result.success) parsed.push(result.data);
1190
+ }
1191
+ return parsed;
1192
+ }
1193
+ /** The generations whose progress a run shows: its lineage up to and including itself. */
1194
+ async function progressGenerations(store, runId) {
1195
+ const run = await store.readRun(runId);
1196
+ if (!run) return [runId];
1197
+ return (await store.listLineage(run.lineageId)).filter((candidate) => candidate.generation <= run.generation).map((candidate) => candidate.runId);
1198
+ }
1199
+ /**
1200
+ * Read only what a run has recorded since `cursor`.
1201
+ *
1202
+ * Store sequences are per generation, so the cursor keeps one position per
1203
+ * generation. A recovered run's earlier generations are finished, and a reader
1204
+ * that already drained them reads nothing more from them.
1205
+ */
1206
+ async function readWorkflowProgressFrom(store, runId, cursor = {}) {
1207
+ const next = { ...cursor };
1208
+ const events = [];
1209
+ for (const generation of await progressGenerations(store, runId)) for (;;) {
1210
+ const recorded = await store.eventsAfter(generation, next[generation] ?? 0);
1211
+ const last = recorded.at(-1);
1212
+ if (!last) break;
1213
+ next[generation] = last.sequence;
1214
+ events.push(...progressEvents(recorded));
1215
+ }
1216
+ return {
1217
+ events,
1218
+ cursor: next
1219
+ };
1220
+ }
1221
+ /** Read a run's whole progress log, earlier generations first. */
1222
+ async function readWorkflowProgress(store, runId) {
1223
+ return (await readWorkflowProgressFrom(store, runId)).events;
1224
+ }
1225
+ /**
1226
+ * Fold the event log into the current job tree.
1227
+ *
1228
+ * Later events win, so a job that started and later failed reads as failed.
1229
+ * This is what a progress view renders: completed jobs collapse, the running
1230
+ * one expands.
1231
+ */
1232
+ function summarizeWorkflowProgress(events) {
1233
+ const jobs = /* @__PURE__ */ new Map();
1234
+ for (const event of events) {
1235
+ const job = jobs.get(event.job) ?? {
1236
+ name: event.job,
1237
+ status: "running",
1238
+ steps: []
1239
+ };
1240
+ if (event.type === "job") {
1241
+ job.status = event.status;
1242
+ if (event.index !== void 0) job.index = event.index;
1243
+ if (event.total !== void 0) job.total = event.total;
1244
+ if (event.reason) job.reason = event.reason;
1245
+ } else if (event.step) {
1246
+ const existing = job.steps.find((step) => step.name === event.step);
1247
+ if (existing) {
1248
+ existing.status = event.status;
1249
+ if (event.reason) existing.reason = event.reason;
1250
+ if (event.ref) existing.ref = event.ref;
1251
+ if (event.group) existing.group = event.group;
1252
+ } else job.steps.push({
1253
+ name: event.step,
1254
+ status: event.status,
1255
+ ...event.reason ? { reason: event.reason } : {},
1256
+ ...event.ref ? { ref: event.ref } : {},
1257
+ ...event.group ? { group: event.group } : {}
1258
+ });
1259
+ }
1260
+ jobs.set(event.job, job);
1616
1261
  }
1617
- };
1262
+ return [...jobs.values()];
1263
+ }
1618
1264
  //#endregion
1619
1265
  //#region src/services/workflowSettlement/index.ts
1620
1266
  /** What a terminal bound generation is owed and not yet acknowledged, or undefined when nothing is. */
@@ -1721,7 +1367,7 @@ function createWorkflowSettlement(options) {
1721
1367
  * - Direct tool implementation (services should be tool-agnostic)
1722
1368
  */
1723
1369
  const DEFAULT_WORKSPACE$1 = "default";
1724
- const RUNNING_STAGE$2 = "running";
1370
+ const RUNNING_STAGE$3 = "running";
1725
1371
  const COMPLETED_STAGE$2 = "completed";
1726
1372
  const ERROR_STAGE$3 = "error";
1727
1373
  const WORKSPACES_DIRNAME = "workspaces";
@@ -1761,7 +1407,7 @@ function workflowStopRequested(run) {
1761
1407
  return stop?.schemaVersion === 1 && stop.runId === run.runId;
1762
1408
  }
1763
1409
  function lifecycleOf(record) {
1764
- if (record.stage === RUNNING_STAGE$2) return "running";
1410
+ if (record.stage === RUNNING_STAGE$3) return "running";
1765
1411
  return record.stage === COMPLETED_STAGE$2 ? "completed" : "failed";
1766
1412
  }
1767
1413
  function isRevisionConflict(error) {
@@ -1846,12 +1492,12 @@ var WorkflowRegistryService = class {
1846
1492
  * while that outcome is still the one owed, so an abandon that lands mid-delivery is never marked delivered.
1847
1493
  */
1848
1494
  async recordSettlement(record, settlement, expected) {
1849
- if (record.stage === RUNNING_STAGE$2 || !record.admission?.binding || !record.runId) return false;
1495
+ if (record.stage === RUNNING_STAGE$3 || !record.admission?.binding || !record.runId) return false;
1850
1496
  if (!await this.ownRun(record.runId)) return false;
1851
1497
  return this.mutate(record.runId, (state) => {
1852
1498
  const current = state.record;
1853
1499
  const admission = current.admission;
1854
- if (current.stage === RUNNING_STAGE$2 || admission?.binding?.epoch.operationId !== record.admission?.binding?.epoch.operationId) return { result: false };
1500
+ if (current.stage === RUNNING_STAGE$3 || admission?.binding?.epoch.operationId !== record.admission?.binding?.epoch.operationId) return { result: false };
1855
1501
  if (expected !== void 0 && owedSettlement(current) !== expected) return { result: false };
1856
1502
  return {
1857
1503
  state: {
@@ -1895,7 +1541,7 @@ var WorkflowRegistryService = class {
1895
1541
  async authorizeExecution(handle, resume = false) {
1896
1542
  const prepared = await this.mutate(handle.runId, async (state) => {
1897
1543
  const current = state.record;
1898
- if (current.runId !== handle.runId || current.stage !== RUNNING_STAGE$2) throw new Error("Workflow generation changed before policy admission.");
1544
+ if (current.runId !== handle.runId || current.stage !== RUNNING_STAGE$3) throw new Error("Workflow generation changed before policy admission.");
1899
1545
  const request = resume ? this.currentPause(state, handle.runId) : void 0;
1900
1546
  if (resume && (request?.action !== "resume" || current.executionState !== "resume_requested" && current.executionState !== "paused")) throw new Error("Workflow resume request changed.");
1901
1547
  if (this.currentStop(state, handle.runId)) throw new Error("Workflow was stopped before policy admission.");
@@ -1949,7 +1595,7 @@ var WorkflowRegistryService = class {
1949
1595
  return this.mutate(handle.runId, (state) => {
1950
1596
  const current = state.record;
1951
1597
  const request = resume ? this.currentPause(state, handle.runId) : void 0;
1952
- if (current.runId !== handle.runId || current.stage !== RUNNING_STAGE$2 || current.admission?.binding?.epoch.operationId !== admission?.binding?.epoch.operationId || resume && (current.executionState !== prepared.record.executionState || request?.action !== "resume" || request.requestId !== prepared.request?.requestId) || this.currentStop(state, handle.runId)) throw new Error("Workflow policy operation changed or stopped.");
1598
+ if (current.runId !== handle.runId || current.stage !== RUNNING_STAGE$3 || current.admission?.binding?.epoch.operationId !== admission?.binding?.epoch.operationId || resume && (current.executionState !== prepared.record.executionState || request?.action !== "resume" || request.requestId !== prepared.request?.requestId) || this.currentStop(state, handle.runId)) throw new Error("Workflow policy operation changed or stopped.");
1953
1599
  const updated = { ...current };
1954
1600
  if (admission?.binding) {
1955
1601
  updated.admission = {
@@ -2040,7 +1686,7 @@ var WorkflowRegistryService = class {
2040
1686
  resumeMode: "continue-next",
2041
1687
  revision: 0
2042
1688
  },
2043
- stage: RUNNING_STAGE$2,
1689
+ stage: RUNNING_STAGE$3,
2044
1690
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
2045
1691
  ...this.runtime.workflowHost.durable ? { hostOwner: this.runtime.workflowHost.durable.owner } : { pid: input.pid ?? this.runtime.workflowHost.processId },
2046
1692
  workflowPath: input.workflowPath,
@@ -2081,7 +1727,7 @@ var WorkflowRegistryService = class {
2081
1727
  async finalizeRun(handle, input) {
2082
1728
  await this.mutate(handle.runId, (state) => {
2083
1729
  const currentRecord = state.record;
2084
- if (currentRecord.runId !== handle.runId || currentRecord.stage !== RUNNING_STAGE$2) throw new Error("Workflow generation changed before finalization.");
1730
+ if (currentRecord.runId !== handle.runId || currentRecord.stage !== RUNNING_STAGE$3) throw new Error("Workflow generation changed before finalization.");
2085
1731
  const finalRecord = {
2086
1732
  ...currentRecord,
2087
1733
  errorMessage: input.errorMessage,
@@ -2272,7 +1918,7 @@ var WorkflowRegistryService = class {
2272
1918
  async updateExecutionState(handle, executionState, executionCursor, expectedRevision) {
2273
1919
  return this.mutate(handle.runId, (state) => {
2274
1920
  const current = state.record;
2275
- if (current.stage !== RUNNING_STAGE$2 || current.runId && current.runId !== handle.runId) throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);
1921
+ if (current.stage !== RUNNING_STAGE$3 || current.runId && current.runId !== handle.runId) throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);
2276
1922
  const currentRevision = current.executionCursor?.revision ?? 0;
2277
1923
  if (expectedRevision !== void 0 && currentRevision !== expectedRevision) throw new Error(`Workflow control revision changed for ${handle.workspace}/${handle.runKey}`);
2278
1924
  const updated = {
@@ -2292,7 +1938,7 @@ var WorkflowRegistryService = class {
2292
1938
  async updateExecutionCursor(handle, patch) {
2293
1939
  return this.mutate(handle.runId, (state) => {
2294
1940
  const current = state.record;
2295
- if (current.stage !== RUNNING_STAGE$2 || current.runId && current.runId !== handle.runId) throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);
1941
+ if (current.stage !== RUNNING_STAGE$3 || current.runId && current.runId !== handle.runId) throw new Error(`Workflow run is no longer controllable: ${handle.workspace}/${handle.runKey}`);
2296
1942
  const currentCursor = current.executionCursor ?? {
2297
1943
  executionGeneration: 1,
2298
1944
  phase: "unknown",
@@ -2320,7 +1966,7 @@ var WorkflowRegistryService = class {
2320
1966
  async markResumable(run, reason) {
2321
1967
  await this.mutate(run.runId, (state) => {
2322
1968
  const current = state.record;
2323
- if (current.stage !== RUNNING_STAGE$2 || current.runId !== run.runId) throw new Error(`Workflow run is no longer controllable: ${run.workspace}/${run.runKey}`);
1969
+ if (current.stage !== RUNNING_STAGE$3 || current.runId !== run.runId) throw new Error(`Workflow run is no longer controllable: ${run.workspace}/${run.runKey}`);
2324
1970
  const resume = current.executionState === "paused" || this.currentStop(state, run.runId) ? void 0 : {
2325
1971
  reason,
2326
1972
  at: (/* @__PURE__ */ new Date()).toISOString()
@@ -2407,7 +2053,7 @@ var WorkflowRegistryService = class {
2407
2053
  async updateConfiguration(handle, configuration) {
2408
2054
  await this.mutate(handle.runId, (state) => {
2409
2055
  const record = state.record;
2410
- if (record.runId !== handle.runId || record.stage !== RUNNING_STAGE$2) throw new Error("Workflow configuration generation changed.");
2056
+ if (record.runId !== handle.runId || record.stage !== RUNNING_STAGE$3) throw new Error("Workflow configuration generation changed.");
2411
2057
  return {
2412
2058
  state: {
2413
2059
  ...state,
@@ -2433,7 +2079,7 @@ var WorkflowRegistryService = class {
2433
2079
  async markFinalizing(handle) {
2434
2080
  await this.mutate(handle.runId, (state) => {
2435
2081
  const current = state.record;
2436
- if (current.stage !== RUNNING_STAGE$2 || current.runId && current.runId !== handle.runId) throw new Error(`Workflow run is no longer finalizable: ${handle.workspace}/${handle.runKey}`);
2082
+ if (current.stage !== RUNNING_STAGE$3 || current.runId && current.runId !== handle.runId) throw new Error(`Workflow run is no longer finalizable: ${handle.workspace}/${handle.runKey}`);
2437
2083
  return {
2438
2084
  state: {
2439
2085
  ...state,
@@ -2752,7 +2398,7 @@ var WorkflowRegistryService = class {
2752
2398
  async recordIdentity(handle, key, binding) {
2753
2399
  await this.mutate(handle.runId, (state) => {
2754
2400
  const current = state.record;
2755
- if (current.stage !== RUNNING_STAGE$2 || current.runId !== handle.runId) throw new Error(`Workflow run is no longer admitting jobs: ${handle.workspace}/${handle.runKey}`);
2401
+ if (current.stage !== RUNNING_STAGE$3 || current.runId !== handle.runId) throw new Error(`Workflow run is no longer admitting jobs: ${handle.workspace}/${handle.runKey}`);
2756
2402
  return {
2757
2403
  state: {
2758
2404
  ...state,
@@ -2798,7 +2444,7 @@ var WorkflowRegistryService = class {
2798
2444
  record = this.validateRunRecord(input.record, `${input.workspace}/${input.runKey}`);
2799
2445
  if (record.workspace !== input.workspace || record.runKey !== input.runKey) throw new Error("A repaired run record cannot change its workspace or run key.");
2800
2446
  if (record.runId !== void 0 && record.runId !== run.runId) throw new Error("A repaired run record cannot change its run ID.");
2801
- if (record.stage === RUNNING_STAGE$2 && input.stage !== RUNNING_STAGE$2) throw new Error("A repair cannot move a run into running; repair it to error, then recover it.");
2447
+ if (record.stage === RUNNING_STAGE$3 && input.stage !== RUNNING_STAGE$3) throw new Error("A repair cannot move a run into running; repair it to error, then recover it.");
2802
2448
  }
2803
2449
  await this.mutate(run.runId, async (state, latestRun) => {
2804
2450
  if (latestRun.revision !== run.revision) throw new Error(`Workflow run ${input.workspace}/${input.runKey} changed since it was inspected; inspect it again before repairing.`);
@@ -2984,7 +2630,7 @@ var WorkflowRegistryService = class {
2984
2630
  }
2985
2631
  const revision = (0, node_crypto.createHash)("sha256").update(JSON.stringify(files)).digest("hex");
2986
2632
  const view = {
2987
- stage: run.lifecycle === "running" ? RUNNING_STAGE$2 : run.lifecycle === "completed" ? COMPLETED_STAGE$2 : ERROR_STAGE$3,
2633
+ stage: run.lifecycle === "running" ? RUNNING_STAGE$3 : run.lifecycle === "completed" ? COMPLETED_STAGE$2 : ERROR_STAGE$3,
2988
2634
  runDir,
2989
2635
  revision,
2990
2636
  files
@@ -3080,7 +2726,7 @@ var WorkflowRegistryService = class {
3080
2726
  }
3081
2727
  return reconciled;
3082
2728
  }
3083
- /** Reconcile only the dead run selected by its owner, never another session's runs. */
2729
+ /** Reconcile only the dead run of the recorded owner and generation. */
3084
2730
  async reconcileStaleRun(record, ownerSessionId) {
3085
2731
  return this.reconcileStaleRunningRecord(record.workspace, record.runKey, {
3086
2732
  runId: record.runId,
@@ -3122,7 +2768,7 @@ var WorkflowRegistryService = class {
3122
2768
  * without changing it, so a read-only query never destroys its failure metadata.
3123
2769
  */
3124
2770
  inspectRunning(record) {
3125
- if (record.stage !== RUNNING_STAGE$2 || !(record.pid || record.hostOwner) || this.isOwnerAlive(record)) return record;
2771
+ if (record.stage !== RUNNING_STAGE$3 || !(record.pid || record.hostOwner) || this.isOwnerAlive(record)) return record;
3126
2772
  return {
3127
2773
  ...record,
3128
2774
  effectiveOutcome: "interrupted",
@@ -3152,7 +2798,7 @@ var WorkflowRegistryService = class {
3152
2798
  if (expected?.stop) throw new Error(`Workflow process is not known to be dead: ${workspace}/${runKey}`);
3153
2799
  return { result: currentRecord };
3154
2800
  }
3155
- if (currentRecord.stage !== RUNNING_STAGE$2) {
2801
+ if (currentRecord.stage !== RUNNING_STAGE$3) {
3156
2802
  if (expected?.stop) throw new Error(`Workflow run is no longer controllable: ${workspace}/${runKey}`);
3157
2803
  return { result: currentRecord };
3158
2804
  }
@@ -3208,7 +2854,7 @@ var WorkflowRegistryService = class {
3208
2854
  if (!change.state) return change.result;
3209
2855
  const next = change.state;
3210
2856
  next.record = this.validateRunRecord(next.record, this.describe(run));
3211
- const terminal = next.record.stage !== RUNNING_STAGE$2;
2857
+ const terminal = next.record.stage !== RUNNING_STAGE$3;
3212
2858
  if (terminal && next.archivedProgress === void 0) next.archivedProgress = (await readWorkflowProgress(this.store, runId)).filter((event) => Date.parse(event.at) >= Date.parse(next.record.startedAt));
3213
2859
  if (!terminal) await durable?.setRunActive?.(runId, true);
3214
2860
  try {
@@ -3259,7 +2905,7 @@ var WorkflowRegistryService = class {
3259
2905
  return run;
3260
2906
  }
3261
2907
  assertControllable(state, runId, run) {
3262
- if (state.record.stage !== RUNNING_STAGE$2 || state.record.runId !== runId) throw new Error(`Workflow run ownership changed: ${run.workspaceId}/${run.runKey}`);
2908
+ if (state.record.stage !== RUNNING_STAGE$3 || state.record.runId !== runId) throw new Error(`Workflow run ownership changed: ${run.workspaceId}/${run.runKey}`);
3263
2909
  }
3264
2910
  currentStop(state, runId) {
3265
2911
  return state.stop?.schemaVersion === 1 && state.stop.runId === runId;
@@ -3358,285 +3004,354 @@ var WorkflowRegistryService = class {
3358
3004
  */
3359
3005
  async removeFileIfExists(path) {
3360
3006
  try {
3361
- (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.fs.remove(path, void 0, this.runtime.ioContext));
3362
- } catch (error) {
3363
- if (!["ENOENT", "not_found"].includes(String(error.code))) throw error;
3007
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.fs.remove(path, void 0, this.runtime.ioContext));
3008
+ } catch (error) {
3009
+ if (!["ENOENT", "not_found"].includes(String(error.code))) throw error;
3010
+ }
3011
+ }
3012
+ /**
3013
+ * Normalize a user-supplied workspace or run name into a safe directory key.
3014
+ */
3015
+ slugifySegment(value, fallback) {
3016
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, SLUG_SEPARATOR).replace(/^-+|-+$/g, "") || fallback;
3017
+ }
3018
+ isOwnerAlive(value) {
3019
+ const durable = this.runtime.workflowHost.durable;
3020
+ if (durable) return value.hostOwner !== void 0 && durable.isOwnerAlive(value.hostOwner);
3021
+ if (value.hostOwner !== void 0) return true;
3022
+ return value.pid !== void 0 && this.isProcessAlive(value.pid);
3023
+ }
3024
+ /** Check whether a locally tracked native process still exists. */
3025
+ isProcessAlive(pid) {
3026
+ try {
3027
+ this.runtime.workflowHost.signal(pid, 0);
3028
+ return true;
3029
+ } catch (error) {
3030
+ const code = error.code;
3031
+ if (code === "ESRCH") return false;
3032
+ if (code === "EPERM") return true;
3033
+ throw error;
3034
+ }
3035
+ }
3036
+ };
3037
+ //#endregion
3038
+ //#region src/services/WorkflowRunObserverService/index.ts
3039
+ const DEFAULT_DEBOUNCE_MS = 150;
3040
+ /**
3041
+ * How often the sweep runs regardless of notifications.
3042
+ *
3043
+ * Slower than the 5s poll it replaces, because it is now the fallback rather
3044
+ * than the mechanism: a notification usually gets there first, and this only
3045
+ * has to bound how long a missed one stays missed.
3046
+ */
3047
+ const DEFAULT_RECONCILE_INTERVAL_MS = 3e4;
3048
+ const RUNNING_STAGE$2 = "running";
3049
+ /** One elected instance owns the narrow watches, independent of package copies. */
3050
+ var WorkflowRegistryObserverService = class {
3051
+ entries = /* @__PURE__ */ new Map();
3052
+ subscribe(registry, onChange) {
3053
+ const directory = registry.workspacesDirectory();
3054
+ let entry = this.entries.get(directory);
3055
+ if (!entry) {
3056
+ const listeners = /* @__PURE__ */ new Set();
3057
+ entry = {
3058
+ listeners,
3059
+ unwatchRuns: registry.watchRuns(() => listeners.forEach((listener) => listener()))
3060
+ };
3061
+ this.entries.set(directory, entry);
3062
+ }
3063
+ const shared = entry;
3064
+ shared.listeners.add(onChange);
3065
+ return {
3066
+ update: async (_records) => {},
3067
+ close: () => {
3068
+ if (!shared.listeners.delete(onChange) || shared.listeners.size) return;
3069
+ if (this.entries.get(directory) === shared) this.entries.delete(directory);
3070
+ shared.unwatchRuns();
3071
+ }
3072
+ };
3073
+ }
3074
+ dispose() {
3075
+ for (const entry of this.entries.values()) entry.unwatchRuns();
3076
+ this.entries.clear();
3077
+ }
3078
+ };
3079
+ /**
3080
+ * Follow the registry's runs and their progress logs, and report what changes.
3081
+ *
3082
+ * Not named a control service on purpose: it only observes. Lifecycle control
3083
+ * already exists as `WorkflowControlService`, and the two are brought together
3084
+ * by `createRunControl` rather than merged here.
3085
+ */
3086
+ var WorkflowRunObserverService = class {
3087
+ registry;
3088
+ options;
3089
+ debounce;
3090
+ disposed = false;
3091
+ handlers = /* @__PURE__ */ new Map();
3092
+ reconciling = false;
3093
+ seen = /* @__PURE__ */ new Map();
3094
+ /** Epoch ms observing began, which is the line between history and news. */
3095
+ startedAt = 0;
3096
+ sweepQueued = false;
3097
+ timer;
3098
+ watcher;
3099
+ registryObserver;
3100
+ subscription;
3101
+ constructor(registry, options = {}) {
3102
+ this.registry = registry;
3103
+ this.options = options;
3104
+ this.registryObserver = options.registryObserver ?? new WorkflowRegistryObserverService();
3105
+ }
3106
+ on(name, handler) {
3107
+ const existing = this.handlers.get(name) ?? /* @__PURE__ */ new Set();
3108
+ existing.add(handler);
3109
+ this.handlers.set(name, existing);
3110
+ return () => {
3111
+ existing.delete(handler);
3112
+ };
3113
+ }
3114
+ /**
3115
+ * Begin observing, reporting the runs already in flight.
3116
+ *
3117
+ * Awaits the first sweep so a caller that subscribes and then asks "what is
3118
+ * running" gets an answer rather than a race.
3119
+ */
3120
+ async start() {
3121
+ if (this.disposed) return;
3122
+ this.startedAt = Date.now();
3123
+ await this.reconcile();
3124
+ if (this.disposed) return;
3125
+ const interval = this.options.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;
3126
+ if (interval > 0) {
3127
+ this.timer ??= setInterval(() => void this.reconcile(), interval);
3128
+ this.timer.unref?.();
3129
+ }
3130
+ this.attachWatcher();
3131
+ }
3132
+ /** Sweep now, rather than waiting for the interval. */
3133
+ async refresh() {
3134
+ await this.reconcile();
3135
+ }
3136
+ dispose() {
3137
+ this.disposed = true;
3138
+ if (this.timer) clearInterval(this.timer);
3139
+ this.timer = void 0;
3140
+ if (this.debounce) clearTimeout(this.debounce);
3141
+ this.debounce = void 0;
3142
+ this.subscription?.close();
3143
+ this.subscription = void 0;
3144
+ this.watcher?.close();
3145
+ this.watcher = void 0;
3146
+ this.handlers.clear();
3147
+ this.seen.clear();
3148
+ }
3149
+ /**
3150
+ * Watch the registry tree, tolerating a tree that is not there yet.
3151
+ *
3152
+ * Re-attempted on every sweep, because the directory is created by whichever
3153
+ * process registers the first run, which may well be later than this.
3154
+ */
3155
+ watching = false;
3156
+ async attachWatcher() {
3157
+ if (this.watcher || this.subscription || this.disposed || this.watching) return;
3158
+ this.watching = true;
3159
+ try {
3160
+ if (this.options.watch) this.watcher = this.options.watch(this.registry.workspacesDirectory(), () => this.scheduleSweep());
3161
+ else this.subscription ??= this.registryObserver.subscribe(this.registry, () => this.scheduleSweep());
3162
+ } catch {} finally {
3163
+ this.watching = false;
3164
+ }
3165
+ }
3166
+ /**
3167
+ * Coalesce a burst of notifications into one sweep.
3168
+ *
3169
+ * A job start records a progress event and a cursor update in quick
3170
+ * succession, and each one notifies.
3171
+ */
3172
+ scheduleSweep() {
3173
+ if (this.disposed || this.debounce) return;
3174
+ this.debounce = setTimeout(() => {
3175
+ this.debounce = void 0;
3176
+ this.reconcile();
3177
+ }, this.options.debounceMs ?? DEFAULT_DEBOUNCE_MS);
3178
+ this.debounce.unref?.();
3179
+ }
3180
+ /**
3181
+ * List, diff, emit.
3182
+ *
3183
+ * Serialised, because two overlapping sweeps would both read the same
3184
+ * progress events and report every transition twice. A sweep requested while
3185
+ * one is running is remembered and run once afterwards, so the change that
3186
+ * prompted it is never simply dropped.
3187
+ */
3188
+ async reconcile() {
3189
+ if (this.disposed) return;
3190
+ if (this.reconciling) {
3191
+ this.sweepQueued = true;
3192
+ return;
3193
+ }
3194
+ this.reconciling = true;
3195
+ try {
3196
+ do {
3197
+ this.sweepQueued = false;
3198
+ await this.sweep();
3199
+ } while (this.sweepQueued && !this.disposed);
3200
+ } finally {
3201
+ this.reconciling = false;
3202
+ }
3203
+ }
3204
+ async sweep() {
3205
+ this.attachWatcher();
3206
+ let records;
3207
+ try {
3208
+ records = await this.registry.listRuns();
3209
+ } catch {
3210
+ return;
3211
+ }
3212
+ try {
3213
+ await this.subscription?.update(records);
3214
+ } catch {}
3215
+ if (this.disposed) return;
3216
+ const filter = this.options.recordFilter;
3217
+ const visible = filter ? records.filter((record) => filter(record)) : records;
3218
+ const live = /* @__PURE__ */ new Set();
3219
+ for (const record of visible) {
3220
+ const identity = runIdentity(record);
3221
+ live.add(identity);
3222
+ const terminal = record.stage !== RUNNING_STAGE$2 || record.stale === true;
3223
+ let tracked = this.seen.get(identity);
3224
+ if (tracked?.finished) continue;
3225
+ if (!tracked) {
3226
+ if (terminal && !this.finishedWhileObserving(record)) continue;
3227
+ tracked = {
3228
+ finished: false,
3229
+ record,
3230
+ cursor: {}
3231
+ };
3232
+ this.seen.set(identity, tracked);
3233
+ this.emit("runStarted", {
3234
+ record,
3235
+ runKey: record.runKey,
3236
+ workspace: record.workspace
3237
+ });
3238
+ }
3239
+ await this.drainProgress(tracked, record);
3240
+ if (JSON.stringify(tracked.record) !== JSON.stringify(record)) {
3241
+ tracked.record = record;
3242
+ this.emit("runUpdated", {
3243
+ record,
3244
+ runKey: record.runKey,
3245
+ workspace: record.workspace
3246
+ });
3247
+ }
3248
+ if (terminal) {
3249
+ tracked.finished = true;
3250
+ this.emit("runFinished", {
3251
+ record,
3252
+ runKey: record.runKey,
3253
+ workspace: record.workspace,
3254
+ stage: record.effectiveStage ?? record.stage,
3255
+ ...record.effectiveOutcome ?? record.outcome ? { outcome: record.effectiveOutcome ?? record.outcome } : {},
3256
+ ...record.failedJob ? { failedJob: record.failedJob } : {},
3257
+ ...record.errorMessage ? { errorMessage: record.errorMessage } : {}
3258
+ });
3259
+ }
3364
3260
  }
3261
+ for (const identity of this.seen.keys()) if (!live.has(identity)) this.seen.delete(identity);
3365
3262
  }
3366
3263
  /**
3367
- * Normalize a user-supplied workspace or run name into a safe directory key.
3264
+ * Whether a run this observer never saw running finished on its watch.
3265
+ *
3266
+ * The discriminator between a run that began and ended inside one sweep,
3267
+ * which is news, and one that finished last week, which is not. An
3268
+ * unparseable timestamp counts as history: replaying an old run is worse than
3269
+ * missing an odd one.
3368
3270
  */
3369
- slugifySegment(value, fallback) {
3370
- return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, SLUG_SEPARATOR).replace(/^-+|-+$/g, "") || fallback;
3371
- }
3372
- isOwnerAlive(value) {
3373
- const durable = this.runtime.workflowHost.durable;
3374
- if (durable) return value.hostOwner !== void 0 && durable.isOwnerAlive(value.hostOwner);
3375
- if (value.hostOwner !== void 0) return true;
3376
- return value.pid !== void 0 && this.isProcessAlive(value.pid);
3377
- }
3378
- /** Check whether a locally tracked native process still exists. */
3379
- isProcessAlive(pid) {
3380
- try {
3381
- this.runtime.workflowHost.signal(pid, 0);
3382
- return true;
3383
- } catch (error) {
3384
- const code = error.code;
3385
- if (code === "ESRCH") return false;
3386
- if (code === "EPERM") return true;
3387
- throw error;
3388
- }
3271
+ finishedWhileObserving(record) {
3272
+ const finishedAt = Date.parse(record.finishedAt ?? record.startedAt);
3273
+ return Number.isFinite(finishedAt) && finishedAt >= this.startedAt;
3389
3274
  }
3390
- };
3391
- //#endregion
3392
- //#region src/services/workflowServices/index.ts
3393
- /** How long admission waits for a revived launcher's coordinator to register again. */
3394
- const LAUNCHER_REVIVE_TIMEOUT_MS = 6e4;
3395
- const LAUNCHER_SESSIONS = Symbol.for("@agimon-ai/po-workflow/launcher-sessions");
3396
- const launcherSlot = globalThis;
3397
- /** Lets admission reopen a dormant launcher session. Offered by the host-scoped contribution that can revive. */
3398
- function publishLauncherSessions(sessions) {
3399
- const slot = {
3400
- generation: (0, node_crypto.randomUUID)(),
3401
- sessions
3402
- };
3403
- launcherSlot[LAUNCHER_SESSIONS] = slot;
3404
- return { dispose() {
3405
- if (launcherSlot[LAUNCHER_SESSIONS]?.generation === slot.generation) delete launcherSlot[LAUNCHER_SESSIONS];
3406
- } };
3407
- }
3408
- const publishedLauncherSessions = () => launcherSlot[LAUNCHER_SESSIONS]?.sessions;
3409
- const POLICY_TABLE = Symbol.for("@agimon-ai/po-workflow/policies");
3410
- const policyTableSlot = globalThis;
3411
- const sharedPolicyTable = () => policyTableSlot[POLICY_TABLE] ??= {
3412
- policies: /* @__PURE__ */ new Map(),
3413
- waiters: /* @__PURE__ */ new Set()
3414
- };
3415
- /** Publishes the workspace's sources on a level's Context. A reused root's services do not run, so sessions call this too. */
3416
- const provideWorkflowSources = (services) => (scope) => {
3417
- scope.plugin((provider) => {
3418
- provider.provide(_agimon_ai_po_core_workflow.PO_WORKFLOW_DEFINITION_SOURCES_SERVICE, services);
3419
- });
3420
- };
3421
- /** Workspace-owned views. Authorization is attached by the owning runtime, never by a sibling lookup. */
3422
- function createWorkflowServices(options = {}) {
3423
- const sessions = options.sessions ?? publishedLauncherSessions;
3424
- const reviveTimeoutMs = options.reviveTimeoutMs ?? LAUNCHER_REVIVE_TIMEOUT_MS;
3425
- let disposed = false;
3426
- const { policies, waiters: policyWaiters } = sharedPolicyTable();
3427
- /** Generations registered through this copy, withdrawn when it disposes. */
3428
- const ownPolicies = /* @__PURE__ */ new Map();
3429
- /** Admissions of this copy waiting for a revived launcher; disposal releases them. */
3430
- const ownWaiters = /* @__PURE__ */ new Set();
3431
- /** Waits for `key` to register, or settles undefined on timeout, abort, disposal or `cancel`. */
3432
- const waitForPolicy = (key, signal) => {
3433
- let cancel;
3434
- return {
3435
- registered: new Promise((resolve) => {
3436
- const waiter = {
3437
- key,
3438
- resolve: (policy) => {
3439
- clearTimeout(timer);
3440
- signal.removeEventListener("abort", cancel);
3441
- policyWaiters.delete(waiter);
3442
- ownWaiters.delete(waiter);
3443
- resolve(policy);
3444
- }
3445
- };
3446
- cancel = () => waiter.resolve(void 0);
3447
- const timer = setTimeout(cancel, reviveTimeoutMs);
3448
- signal.addEventListener("abort", cancel, { once: true });
3449
- policyWaiters.add(waiter);
3450
- ownWaiters.add(waiter);
3451
- }),
3452
- cancel
3453
- };
3454
- };
3455
3275
  /**
3456
- * A launcher that went dormant (a Po restart, an idle release) holds its coordinator with it. Reopen it
3457
- * without a prompt, as the restart sweep does for owners, and wait for its coordinator to register again.
3276
+ * Report the transitions a run appended since the last sweep.
3277
+ *
3278
+ * A recovered run's progress includes its earlier generations, so a
3279
+ * subscriber sees the whole history of the run key whatever generation it is on.
3458
3280
  */
3459
- const reviveLauncher = async (launcher, key, signal) => {
3460
- const host = sessions();
3461
- if (!host?.dormant().some((entry) => entry.sessionId === launcher)) return void 0;
3462
- const { registered, cancel } = waitForPolicy(key, signal);
3463
- const outcome = await host.revive(launcher, { automatic: true }).catch(() => "not_found");
3464
- if (outcome === "paused" || outcome === "not_found") cancel();
3465
- return await registered ?? policies.get(key);
3466
- };
3467
- const owners = /* @__PURE__ */ new Map();
3468
- const sources = /* @__PURE__ */ new Map();
3469
- const sourceListeners = /* @__PURE__ */ new Set();
3470
- const runs = /* @__PURE__ */ new Map();
3471
- const listeners = /* @__PURE__ */ new Set();
3472
- const list = () => disposed ? [] : [...sources.values()].map(({ value }) => ({ ...value }));
3473
- const emitSources = () => {
3474
- for (const listener of sourceListeners) listener(list());
3475
- };
3476
- const read = (session, id) => {
3477
- const run = disposed ? void 0 : runs.get(id);
3478
- return run !== void 0 && (run.owner === session || run.launcher === session) ? run : void 0;
3479
- };
3480
- return {
3481
- registerPolicy(session, coordinator, callback, options) {
3482
- if (disposed || !session || !coordinator) throw new Error("Workflow policy registration is unavailable.");
3483
- const key = JSON.stringify([session, coordinator]);
3484
- const keys = new Set(options.environmentKeys);
3485
- for (const name of keys) if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || /^(PO_|WORKFLOW_)/.test(name)) throw new Error("Protected workflow policy environment key.");
3486
- const generation = (0, node_crypto.randomUUID)();
3487
- const policy = {
3488
- generation,
3489
- callback,
3490
- keys,
3491
- settle: options.settle
3281
+ async drainProgress(tracked, record) {
3282
+ const tail = await this.registry.readProgressFrom(record.runId, tracked.cursor);
3283
+ tracked.cursor = tail.cursor;
3284
+ for (const event of tail.events) {
3285
+ const shared = {
3286
+ at: event.at,
3287
+ job: event.job,
3288
+ phase: workflowRunPhase(event.job),
3289
+ record,
3290
+ runKey: record.runKey,
3291
+ status: event.status,
3292
+ workspace: record.workspace,
3293
+ ...event.reason ? { reason: event.reason } : {}
3492
3294
  };
3493
- policies.set(key, policy);
3494
- ownPolicies.set(key, generation);
3495
- for (const waiter of policyWaiters) if (waiter.key === key) waiter.resolve(policy);
3496
- return { dispose() {
3497
- if (policies.get(key)?.generation === generation) policies.delete(key);
3498
- if (ownPolicies.get(key) === generation) ownPolicies.delete(key);
3499
- } };
3500
- },
3501
- async beforeExecution(request) {
3502
- const key = JSON.stringify([request.launcherSessionId, request.binding.association.coordinator]);
3503
- let policy = policies.get(key);
3504
- if (!disposed && !policy) policy = await reviveLauncher(request.launcherSessionId, key, request.signal);
3505
- if (disposed) throw new Error("Workflow policy coordinator is unavailable for its source session: these services were replaced.");
3506
- if (!policy) {
3507
- const launcherPrefix = JSON.stringify([request.launcherSessionId]).slice(0, -1);
3508
- const known = [...policies.keys()].filter((entry) => entry.startsWith(launcherPrefix)).length;
3509
- throw new Error(`Workflow policy coordinator is unavailable for its source session (${String(known)} coordinator(s) registered for the launcher, ${String(policies.size)} in total).`);
3295
+ if (event.type === "step" && event.step) {
3296
+ this.emit("step", {
3297
+ ...shared,
3298
+ step: event.step
3299
+ });
3300
+ continue;
3510
3301
  }
3511
- request.signal.throwIfAborted();
3512
- const result = await policy.callback({
3513
- ...structuredClone({
3514
- ...request,
3515
- signal: void 0
3516
- }),
3517
- signal: request.signal
3518
- });
3519
- request.signal.throwIfAborted();
3520
- if (policies.get(key)?.generation !== policy.generation) throw new Error("Workflow policy registration changed during admission.");
3521
- for (const [name, value] of Object.entries(result?.environment ?? {})) if (!policy.keys.has(name) || typeof value !== "string") throw new Error("Workflow policy returned an unregistered environment key.");
3522
- return result === void 0 ? void 0 : structuredClone(result);
3523
- },
3524
- async settle(request) {
3525
- const key = JSON.stringify([request.launcherSessionId, request.binding.association.coordinator]);
3526
- const policy = policies.get(key);
3527
- if (disposed || !policy) return "unavailable";
3528
- if (!policy.settle) return "unsupported";
3529
- request.signal.throwIfAborted();
3530
- await policy.settle({
3531
- ...structuredClone({
3532
- ...request,
3533
- signal: void 0
3534
- }),
3535
- signal: request.signal
3536
- });
3537
- return policies.get(key)?.generation === policy.generation ? "delivered" : "unavailable";
3538
- },
3539
- registerOwner(session, owner) {
3540
- if (disposed) throw new Error("Workflow services are disposed.");
3541
- const generation = (0, node_crypto.randomUUID)();
3542
- owners.set(session, {
3543
- generation,
3544
- value: owner
3545
- });
3546
- return { dispose() {
3547
- if (owners.get(session)?.generation === generation) owners.delete(session);
3548
- } };
3549
- },
3550
- owner: (session) => disposed ? void 0 : owners.get(session)?.value,
3551
- register(value) {
3552
- if (disposed) throw new Error("Workflow services are disposed.");
3553
- if (!value.source || !(0, node_path.isAbsolute)(value.directory)) throw new Error("A workflow source requires a name and absolute directory.");
3554
- if (sources.has(value.source)) throw new Error(`Workflow source already registered: ${value.source}`);
3555
- const generation = (0, node_crypto.randomUUID)();
3556
- sources.set(value.source, {
3557
- generation,
3558
- value: {
3559
- source: value.source,
3560
- directory: (0, node_path.resolve)(value.directory)
3561
- }
3562
- });
3563
- emitSources();
3564
- return {
3565
- source: value.source,
3566
- generation,
3567
- dispose() {
3568
- if (sources.get(value.source)?.generation !== generation) return;
3569
- sources.delete(value.source);
3570
- emitSources();
3571
- }
3572
- };
3573
- },
3574
- list,
3575
- subscribe(listener) {
3576
- if (disposed) return () => {};
3577
- sourceListeners.add(listener);
3578
- listener(list());
3579
- return () => {
3580
- sourceListeners.delete(listener);
3581
- };
3582
- },
3583
- forSession(session) {
3584
- return {
3585
- async readConfig(id) {
3586
- const value = read(session, id)?.config;
3587
- return value === void 0 ? void 0 : structuredClone(value);
3588
- },
3589
- async readState(id) {
3590
- const value = read(session, id)?.state;
3591
- return value === void 0 ? void 0 : structuredClone(value);
3592
- },
3593
- subscribe(runId, listener) {
3594
- if (disposed) return () => {};
3595
- const entry = {
3596
- session,
3597
- runId,
3598
- listener
3599
- };
3600
- listeners.add(entry);
3601
- const state = read(session, runId)?.state;
3602
- if (state !== void 0) listener(structuredClone(state));
3603
- return () => {
3604
- listeners.delete(entry);
3605
- };
3606
- }
3607
- };
3608
- },
3609
- update(owner, state, launcher, config) {
3610
- if (disposed || state.run.ownerSessionId !== owner) return;
3611
- const previous = runs.get(state.run.runId);
3612
- if (previous !== void 0 && previous.owner !== owner) return;
3613
- runs.set(state.run.runId, {
3614
- owner,
3615
- launcher,
3616
- state: structuredClone(config !== void 0 && previous !== void 0 ? previous.state : state),
3617
- config: config === void 0 ? previous?.config : structuredClone(config)
3302
+ this.emit("job", {
3303
+ ...shared,
3304
+ ...event.index === void 0 ? {} : { index: event.index },
3305
+ ...event.total === void 0 ? {} : { total: event.total }
3618
3306
  });
3619
- for (const entry of listeners) if (entry.runId === state.run.runId && read(entry.session, entry.runId) !== void 0) entry.listener(structuredClone(runs.get(state.run.runId).state));
3620
- },
3621
- withdraw(owner) {
3622
- if (owners.has(owner)) return;
3623
- for (const [id, run] of runs) if (run.owner === owner) runs.delete(id);
3624
- for (const entry of listeners) if (entry.session === owner) listeners.delete(entry);
3625
- },
3626
- dispose() {
3627
- disposed = true;
3628
- for (const waiter of ownWaiters) waiter.resolve(void 0);
3629
- runs.clear();
3630
- for (const [key, generation] of ownPolicies) if (policies.get(key)?.generation === generation) policies.delete(key);
3631
- ownPolicies.clear();
3632
- owners.clear();
3633
- sources.clear();
3634
- listeners.clear();
3635
- sourceListeners.clear();
3636
3307
  }
3637
- };
3308
+ }
3309
+ /**
3310
+ * Deliver to subscribers, absorbing their failures.
3311
+ *
3312
+ * A subscriber that throws is a rendering bug in somebody else's extension,
3313
+ * and it must not stop the sweep or starve every other subscriber.
3314
+ */
3315
+ emit(name, event) {
3316
+ const handlers = this.handlers.get(name);
3317
+ if (!handlers) return;
3318
+ for (const handler of [...handlers]) try {
3319
+ handler(event);
3320
+ } catch {}
3321
+ }
3322
+ };
3323
+ /**
3324
+ * The identity a run keeps across stage moves.
3325
+ *
3326
+ * `runId` when the record carries one; runs predating it fall back to the pair
3327
+ * that is unique within a workspace.
3328
+ */
3329
+ function runIdentity(record) {
3330
+ return record.runId ?? `${record.workspace}/${record.runKey}`;
3638
3331
  }
3639
3332
  //#endregion
3333
+ //#region src/services/WorkflowRunObserverService/types.ts
3334
+ /**
3335
+ * Event contract for observing workflow runs this process does not host.
3336
+ *
3337
+ * DESIGN PATTERNS:
3338
+ * - Named channels with typed payloads, so a subscriber asks for the one thing
3339
+ * it renders rather than switching over a union
3340
+ * - Every payload carries the whole record, because a caller that has the
3341
+ * record needs no follow-up read to answer "whose run, and how is it going"
3342
+ *
3343
+ * CODING STANDARDS:
3344
+ * - Named exports only
3345
+ * - Explicit return types on exported members
3346
+ *
3347
+ * AVOID:
3348
+ * - Events the files cannot support. A launch handed to a terminal launcher
3349
+ * writes nothing and never learns its own run key, so there is no
3350
+ * `delegated` event; `runStarted` fires when the run registers itself.
3351
+ */
3352
+ const WORKFLOW_REGISTRY_OBSERVER_SERVICE = "po/workflow-registry-observer";
3353
+ const WORKFLOW_REGISTRY_OBSERVER_CONTRACT = (0, _agimon_ai_po_core_extensionFile.defineServiceContract)(WORKFLOW_REGISTRY_OBSERVER_SERVICE, { scope: "host" });
3354
+ //#endregion
3640
3355
  //#region src/services/workflowSession/index.ts
3641
3356
  /**
3642
3357
  * The workflow session: the child session a launch creates to own and run one
@@ -3658,7 +3373,7 @@ const MAX_CAUSE = 1e3;
3658
3373
  const WORKFLOW_FILE_SUFFIX = /\.workflow\.ya?ml$|\.ya?ml$/u;
3659
3374
  /** Whether this session was created to own a workflow run. */
3660
3375
  function isWorkflowSession(context) {
3661
- return context.sessionContext?.provenance === require_workflow.WORKFLOW_SESSION_PROVENANCE;
3376
+ return context.sessionContext?.provenance === require_workflowServices.WORKFLOW_SESSION_PROVENANCE;
3662
3377
  }
3663
3378
  /** The rail name of a workflow session: the catalog's name, else the file's stem. */
3664
3379
  function workflowSessionName(workflowPath, catalogName) {
@@ -4034,7 +3749,7 @@ const json = (value) => {
4034
3749
  }
4035
3750
  };
4036
3751
  /** The Node authority dynamic records are scoped by, the same one workflow runs use. */
4037
- const dynamicAuthority = (runtime) => (0, node_path.resolve)(runtime.homeDirectory, require_workflow.DEFAULT_WORKFLOW_HOME);
3752
+ const dynamicAuthority = (runtime) => (0, node_path.resolve)(runtime.homeDirectory, require_workflowServices.DEFAULT_WORKFLOW_HOME);
4038
3753
  /**
4039
3754
  * Dynamic records in the workflow store, of one session or, without one, of every session in the
4040
3755
  * authority. A record whose state is malformed is skipped, not run.
@@ -5113,11 +4828,23 @@ async function sweepWorkflowRestarts(runtime, activation, notice) {
5113
4828
  notice(`Workflow restart discovery failed: ${String(error)}`);
5114
4829
  }
5115
4830
  }
5116
- /** Offered by global and workspace roots; the host elects only one scanner. */
5117
- function createWorkflowRestartSweep(runtime) {
4831
+ /** Observation and restart share the package's one elected host offer. */
4832
+ function createWorkflowHostContribution(runtime) {
5118
4833
  return {
5119
4834
  packageName: "@agimon-ai/po-workflow",
5120
- activate(activation) {
4835
+ async activate(activation) {
4836
+ const observer = new WorkflowRegistryObserverService();
4837
+ try {
4838
+ await activation.provide(WORKFLOW_REGISTRY_OBSERVER_CONTRACT, observer);
4839
+ const sessions = activation.host.context.sessionService;
4840
+ if (sessions?.dormant && sessions.revive) await activation.provide(require_workflowServices.WORKFLOW_LAUNCHER_SESSIONS, {
4841
+ dormant: () => sessions.dormant?.() ?? [],
4842
+ revive: sessions.revive.bind(sessions)
4843
+ });
4844
+ } catch (error) {
4845
+ observer.dispose();
4846
+ throw error;
4847
+ }
5121
4848
  const telemetry = (0, _agimon_ai_po_core_telemetry.createPoTelemetry)({
5122
4849
  serviceName: "workflow-mcp",
5123
4850
  packageName: "@agimon-ai/po-workflow",
@@ -5128,14 +4855,9 @@ function createWorkflowRestartSweep(runtime) {
5128
4855
  const notice = (message) => {
5129
4856
  telemetry.recordWarning("po_workflow.restart_sweep", new Error(message));
5130
4857
  };
5131
- const sessions = activation.host.context.sessionService;
5132
- const launchers = sessions?.dormant && sessions.revive ? publishLauncherSessions({
5133
- dormant: () => sessions.dormant?.() ?? [],
5134
- revive: async (id, options) => sessions.revive?.(id, options) ?? "not_found"
5135
- }) : void 0;
5136
4858
  sweepWorkflowRestarts(runtime, activation, notice).catch((error) => notice(String(error)));
5137
4859
  return async () => {
5138
- launchers?.dispose();
4860
+ observer.dispose();
5139
4861
  await telemetry.shutdown();
5140
4862
  };
5141
4863
  }
@@ -7061,6 +6783,14 @@ const WorkflowInspectDefinitionSchema = zod.z.strictObject({
7061
6783
  template: zod.z.boolean().optional(),
7062
6784
  job: zod.z.string().min(1).optional()
7063
6785
  });
6786
+ const WorkflowDeleteDefinitionSchema = zod.z.strictObject({
6787
+ source: zod.z.enum([
6788
+ "org",
6789
+ "personal",
6790
+ "host"
6791
+ ]),
6792
+ key: zod.z.string().max(200).regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]*\.workflow\.ya?ml$/u, "Use one plain *.workflow.yml or *.workflow.yaml file name.")
6793
+ });
7064
6794
  const WorkflowRecoverSchema = zod.z.strictObject({
7065
6795
  ...serverRunSelector,
7066
6796
  dryRun: zod.z.boolean().optional(),
@@ -11443,13 +11173,13 @@ function parseProblems(message) {
11443
11173
  * - Runner maps no runner satisfies, customRun steps no terminal can run, and
11444
11174
  * `${{ inputs.X }}` for inputs the workflow does not declare.
11445
11175
  */
11446
- async function diagnoseWorkflow(workflowPath, options) {
11176
+ async function diagnoseWorkflow(workflowPath, options, savedDefinition) {
11447
11177
  options.signal?.throwIfAborted();
11448
11178
  const path = (0, node_path.resolve)(options.runtime.cwd, workflowPath);
11449
11179
  const parser = options.parser ?? new require_workflowHost.WorkflowParserService(options.runtime);
11450
11180
  let workflow;
11451
11181
  try {
11452
- workflow = await parser.parseWorkflowFile(path);
11182
+ workflow = savedDefinition ?? await parser.parseWorkflowFile(path);
11453
11183
  } catch (error) {
11454
11184
  options.signal?.throwIfAborted();
11455
11185
  return {
@@ -12153,7 +11883,7 @@ function launchedRunHint(record) {
12153
11883
  * run's workflow session, so a finished run is posted without starting a turn.
12154
11884
  */
12155
11885
  function isOwnedDelegatedRun(record, sessionId) {
12156
- const launcher = record.env?.[require_workflow.WORKFLOW_LAUNCHER_SESSION_ENV];
11886
+ const launcher = record.env?.[require_workflowServices.WORKFLOW_LAUNCHER_SESSION_ENV];
12157
11887
  return isSessionRun(record, sessionId) && typeof launcher === "string" && launcher !== "" && launcher !== sessionId;
12158
11888
  }
12159
11889
  /**
@@ -13678,7 +13408,7 @@ function createWorkflowsChannel(options = {}) {
13678
13408
  if (runtime === void 0) return;
13679
13409
  (async () => {
13680
13410
  const locations = await workflowRunLocations(runtime);
13681
- for (const { homeDir, ownerSessionId } of locations) if (ownerSessionId === void 0 || ownerSessionId === sessionId) await stopParkedRuns(new WorkflowRegistryService(runtime, homeDir), sessionId, options.approvals?.(), require_workflow.STOPPED_WHILE_WAITING);
13411
+ for (const { homeDir, ownerSessionId } of locations) if (ownerSessionId === void 0 || ownerSessionId === sessionId) await stopParkedRuns(new WorkflowRegistryService(runtime, homeDir), sessionId, options.approvals?.(), require_workflowServices.STOPPED_WHILE_WAITING);
13682
13412
  })().catch((error) => host.onNotice(`Parked workflow runs of removed session ${sessionId} could not be stopped: ${String(error)}`));
13683
13413
  },
13684
13414
  close() {
@@ -14554,7 +14284,7 @@ var index_server_default$1 = (async ({ host, context }) => {
14554
14284
  }],
14555
14285
  onStart: () => {
14556
14286
  if (host.scope === "session") return;
14557
- context.inject([_agimon_ai_po_core_serverPlugin.PO_HOST_SERVICES_SERVICE], (injected) => (0, _agimon_ai_po_core_serverPlugin.readPoHostServices)(injected)?.register(host, createWorkflowRestartSweep(admitted)));
14287
+ context.inject([_agimon_ai_po_core_serverPlugin.PO_HOST_SERVICES_SERVICE], (injected) => (0, _agimon_ai_po_core_serverPlugin.readPoHostServices)(injected)?.register(host, createWorkflowHostContribution(admitted)));
14558
14288
  },
14559
14289
  onDispose: async () => {
14560
14290
  await Promise.all([provider.dispose(), storeProvider.dispose()]);
@@ -14568,10 +14298,7 @@ var root_server_default$2 = (0, _agimon_ai_po_core_extensionFile.defineRoot)(asy
14568
14298
  return {
14569
14299
  value,
14570
14300
  services: value.services,
14571
- onStart: () => {
14572
- registerWorkflowRegistryObserver(context);
14573
- value.onStart?.();
14574
- },
14301
+ onStart: value.onStart,
14575
14302
  onDispose: value.onDispose
14576
14303
  };
14577
14304
  });
@@ -14581,19 +14308,23 @@ var root_server_default$2 = (0, _agimon_ai_po_core_extensionFile.defineRoot)(asy
14581
14308
  * The workspace's workflow sources and run views. Built at workspace scope:
14582
14309
  * the global root is shared by every workspace, so it cannot own the repo source.
14583
14310
  */
14584
- var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)((plugin) => {
14585
- const { host } = plugin;
14311
+ var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)(async (plugin) => {
14312
+ const { host, context, resources } = plugin;
14586
14313
  const directory = host.context.cwd ?? host.context.workspaceRoot;
14587
14314
  if (directory === void 0) throw new Error("Workflow sources require the admitted workspace directory.");
14588
- const workflowServices = createWorkflowServices();
14315
+ const durableHost = require_workflowHost.readBoundWorkflowHost(context)?.durable;
14316
+ const workflowServices = require_workflowServices.createWorkflowServices({
14317
+ durableHost,
14318
+ policyTable: durableHost ? void 0 : await resources.acquire("workflow-policies", require_workflowServices.createWorkflowPolicyTable),
14319
+ sessions: () => (0, _agimon_ai_po_core_serverPlugin.readPoServerScope)(context)?.resolve(require_workflowServices.WORKFLOW_LAUNCHER_SESSIONS)
14320
+ });
14589
14321
  workflowServices.register({
14590
14322
  source: "repo",
14591
14323
  directory
14592
14324
  });
14593
14325
  return {
14594
14326
  value: workflowServices,
14595
- onStart: () => registerWorkflowRegistryObserver(plugin),
14596
- services: [provideWorkflowSources(workflowServices)],
14327
+ services: [require_workflowServices.provideWorkflowSources(workflowServices)],
14597
14328
  onDispose: () => workflowServices.dispose()
14598
14329
  };
14599
14330
  });
@@ -15660,7 +15391,7 @@ const WORKFLOW_PHASE_ENV = "WORKFLOW_PHASE";
15660
15391
  * That is cosmetic rather than corrupting, and is not worth an escaping scheme.
15661
15392
  */
15662
15393
  const PRE_PHASE_JOB = "pre";
15663
- const POST_PHASE_JOB = PHASE_JOB_POST$1;
15394
+ const POST_PHASE_JOB = PHASE_JOB_POST;
15664
15395
  const WORKFLOW_EXIT_CODE_ENV = "WORKFLOW_EXIT_CODE";
15665
15396
  const WORKFLOW_OUTCOME_ENV = "WORKFLOW_OUTCOME";
15666
15397
  const WORKFLOW_FAILED_JOB_ENV = "WORKFLOW_FAILED_JOB";
@@ -16010,7 +15741,8 @@ var RunWorkflowService = class {
16010
15741
  assertShellCapability(workflow, this.runtime);
16011
15742
  const allocation = await this.admitAllocationForWorkflow(input, parsedWorkflow);
16012
15743
  this.registry.setAllocationAdmission(async (record) => {
16013
- await this.prepareAllocation({
15744
+ const savedDefinition = record.configuration?.workflow;
15745
+ const bindings = {
16014
15746
  workflowPath: record.workflowPath,
16015
15747
  job: record.job,
16016
15748
  allocation: record.allocation,
@@ -16019,7 +15751,10 @@ var RunWorkflowService = class {
16019
15751
  runner: record.runner,
16020
15752
  command: record.command,
16021
15753
  profile: record.profile
16022
- });
15754
+ };
15755
+ const expected = record.allocation ?? record.admission?.allocation;
15756
+ if (savedDefinition && (!expected || workflowDefinitionRevision(savedDefinition) === expected.requirements.revision)) await this.admitAllocationForWorkflow(bindings, savedDefinition);
15757
+ else await this.prepareAllocation(bindings);
16023
15758
  });
16024
15759
  const noProfile = allocation ? {
16025
15760
  profile: null,
@@ -16106,7 +15841,7 @@ var RunWorkflowService = class {
16106
15841
  if (running >= maxWorkflows) throw new WorkflowCapacityError(resolvedWorkspace, running, maxWorkflows);
16107
15842
  }
16108
15843
  const baseName = input.name || workflow.name || (0, node_path.basename)(workflowPath);
16109
- const workflowName = input.name ? baseName : `${baseName}-${this.parser.generateHumanReadableId()}`;
15844
+ const workflowName = input.name ? baseName : `${baseName}-${this.parser.generateHumanReadableId()}-${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
16110
15845
  const workflowId = (0, node_path.basename)(workflowPath, (0, node_path.extname)(workflowPath));
16111
15846
  if (dryRun && input.recovery) registryRun = await this.createRecoveryDryRunHandle(input, resolvedWorkspace);
16112
15847
  else registryRun = await this.registry.createRun({
@@ -17181,7 +16916,7 @@ function createWorkflowLaunchExecutor(dependencies) {
17181
16916
  if (agiflowJobKind && agiflowJobKind !== "task" && agiflowJobKind !== "work-unit") throw new Error("Agiflow workflow launches require AGIFLOW_JOB_KIND to be task or work-unit.");
17182
16917
  if (agiflowJobKind && !explicitProjectId) throw new Error("Agiflow workflow launches require AGIFLOW_PROJECT_ID with the job identity.");
17183
16918
  if (agiflowJobKind && !input.prompt?.trim()) throw new Error("Agiflow workflow launches require a non-empty prompt so user_prompt runs do not wait for terminal input.");
17184
- reportProgress(onUpdate, require_workflow.LAUNCH_WORKFLOW_TOOL_NAME, "Checking workflow capacity...");
16919
+ reportProgress(onUpdate, require_workflowServices.LAUNCH_WORKFLOW_TOOL_NAME, "Checking workflow capacity...");
17185
16920
  const maxConcurrent = resolveMaxConcurrent(dependencies.environment);
17186
16921
  const active = await dependencies.activeRunCount?.() ?? 0;
17187
16922
  if (active >= maxConcurrent) throw new Error(withOptions(`This session is at capacity: ${active}/${maxConcurrent} workflows running.`, [
@@ -17193,7 +16928,7 @@ function createWorkflowLaunchExecutor(dependencies) {
17193
16928
  const rejection = dependencies.rejectRunner?.(input.workflowPath, input.runner);
17194
16929
  if (rejection) throw new Error(rejection);
17195
16930
  }
17196
- reportProgress(onUpdate, require_workflow.LAUNCH_WORKFLOW_TOOL_NAME, `Launching workflow ${input.workflowPath}...`);
16931
+ reportProgress(onUpdate, require_workflowServices.LAUNCH_WORKFLOW_TOOL_NAME, `Launching workflow ${input.workflowPath}...`);
17197
16932
  const workflowEnv = { ...input.env };
17198
16933
  const dispatcherContextFile = dependencies.environment.AGIFLOW_DISPATCH_CONTEXT_FILE;
17199
16934
  const dispatcherProjectId = dependencies.environment[AGIFLOW_PROJECT_ID_ENV]?.trim();
@@ -17215,7 +16950,7 @@ function createWorkflowLaunchExecutor(dependencies) {
17215
16950
  env: {
17216
16951
  ...workflowEnv,
17217
16952
  [PO_SESSION_ENV$1]: sessionId,
17218
- [require_workflow.WORKFLOW_LAUNCH_ID_ENV]: launchId
16953
+ [require_workflowServices.WORKFLOW_LAUNCH_ID_ENV]: launchId
17219
16954
  }
17220
16955
  })));
17221
16956
  const ack = await awaitLaunchAck(settled, dependencies, {
@@ -17374,7 +17109,7 @@ function createServerLauncher(dependencies) {
17374
17109
  }
17375
17110
  };
17376
17111
  const runInProcess = async (input, helpActive) => {
17377
- const launchId = input.env?.[require_workflow.WORKFLOW_LAUNCH_ID_ENV];
17112
+ const launchId = input.env?.[require_workflowServices.WORKFLOW_LAUNCH_ID_ENV];
17378
17113
  if (launchId === void 0) throw new Error("An in-process launch needs its launch id.");
17379
17114
  const log = createRunLog(dependencies.runtime, telemetry);
17380
17115
  const service = feature.createRunService({ logger: log.logger });
@@ -18346,6 +18081,8 @@ declare const workflow: {
18346
18081
  */
18347
18082
  helpRepair(input: WorkflowHelpRepairInput): Promise<WorkflowRunState>;
18348
18083
  };`;
18084
+ const WORKFLOW_DELETE_DEFINITION_DECLARATION = `/** Delete one named stored workflow definition after human approval. Does not change run history or repository files. */
18085
+ deleteDefinition(input: { source: 'org' | 'personal' | 'host'; key: string }): Promise<{ source: 'org' | 'personal' | 'host'; key: string; deleted: true }>;`;
18349
18086
  /** Offered only when the trusted managed-session capability contains the method. */
18350
18087
  const WORKFLOW_CHILD_DECLARATIONS = {
18351
18088
  spawnChild: "spawnChild(input: { job: string; prompt: string; inputs?: Record<string, string | number | boolean>; /** Run-directory paths the child reads, sealed into its assignment. */ inputPaths?: string[] }): Promise<WorkflowChildInvocation>;",
@@ -18547,7 +18284,7 @@ function createWorkflowOperations(options) {
18547
18284
  if (!registry) throw new Error(WORKFLOW_ACTIVITY_INACTIVE);
18548
18285
  const record = await registry.readRunByKey(selected.view.workspace, "error", selected.view.runKey);
18549
18286
  if (record.runId === void 0 || record.runId !== input.expectedRunId) throw new Error(`Workflow run ownership changed: ${record.workspace}/${record.runKey}`);
18550
- await releaseWait(registry, record, options.approvals?.(), require_workflow.STOPPED_WHILE_WAITING);
18287
+ await releaseWait(registry, record, options.approvals?.(), require_workflowServices.STOPPED_WHILE_WAITING);
18551
18288
  return {
18552
18289
  reason: input.reason?.trim() || void 0,
18553
18290
  requestedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -18570,10 +18307,11 @@ function createWorkflowOperations(options) {
18570
18307
  return input.action === "pause" ? control.pause(input.runKey, input.expectedRunId, input.workspace, input.reason) : input.action === "resume" ? control.resume(input.runKey, input.expectedRunId, input.workspace) : control.stop(input.runKey, input.expectedRunId, input.workspace, input.reason);
18571
18308
  });
18572
18309
  };
18573
- const prepareValidation = (parameters, cwd, signal, expected, sourceDefinition) => {
18310
+ const prepareValidation = (parameters, cwd, signal, expected, sourceDefinition, recoveryDefinition) => {
18574
18311
  const input = WorkflowValidateInputSchema.parse(parameters);
18575
18312
  return perform("validate", false, signal, async () => {
18576
18313
  const workflowPath = (0, node_path.resolve)(cwd, input.workflowPath);
18314
+ const savedDefinition = recoveryDefinition && (!expected || workflowDefinitionRevision(recoveryDefinition) === expected.requirements.revision) ? recoveryDefinition : void 0;
18577
18315
  const report = await diagnoseWorkflow(workflowPath, {
18578
18316
  runtime: options.runtime,
18579
18317
  runConfigKeys: PO_RUN_CONFIG_KEYS,
@@ -18583,12 +18321,12 @@ function createWorkflowOperations(options) {
18583
18321
  workflowPath
18584
18322
  },
18585
18323
  signal
18586
- });
18324
+ }, savedDefinition);
18587
18325
  const diagnostics = [...report.diagnostics];
18588
18326
  let allocation;
18589
18327
  if (!diagnostics.some((diagnostic) => diagnostic.level === "error")) try {
18590
18328
  const parser = new require_workflowHost.WorkflowParserService(options.runtime);
18591
- const workflow = await parser.parseWorkflowFile(workflowPath);
18329
+ const workflow = savedDefinition ?? await parser.parseWorkflowFile(workflowPath);
18592
18330
  const definition = sourceDefinition ?? require_contract.workflowDefinitionRef(workflowPath, options.repoRoot ?? options.runtime.cwd, options.runtime.library);
18593
18331
  const jobs = parser.resolveJobOrder(workflow.jobs, input.job ?? null);
18594
18332
  const requirements = workflowIdentityRequirements(workflow, definition, jobs);
@@ -18665,6 +18403,20 @@ function createWorkflowOperations(options) {
18665
18403
  ...input.directory === void 0 ? { library: options.runtime.library } : {}
18666
18404
  }));
18667
18405
  },
18406
+ deleteDefinition(parameters, signal) {
18407
+ const input = WorkflowDeleteDefinitionSchema.parse(parameters);
18408
+ return perform("deleteDefinition", true, signal, async () => {
18409
+ const { runtime } = options;
18410
+ const set = runtime.library?.find(({ source }) => source === input.source);
18411
+ if (!set) throw new Error(`Stored workflow set "${input.source}" is not available in this session.`);
18412
+ const context = signal === void 0 ? runtime.ioContext : (0, _agimon_ai_po_core_platform.withAbortSignal)(signal, runtime.ioContext);
18413
+ (0, _agimon_ai_po_core_platform.getOrThrow)(await runtime.fs.remove((0, node_path.join)(set.directory, input.key), void 0, context));
18414
+ return {
18415
+ ...input,
18416
+ deleted: true
18417
+ };
18418
+ });
18419
+ },
18668
18420
  requirements(parameters, cwd, signal, sourceDefinition) {
18669
18421
  const input = WorkflowRequirementsInputSchema.parse(parameters);
18670
18422
  return perform("requirements", false, signal, async () => {
@@ -19002,11 +18754,12 @@ const CARD_TOOLS = {
19002
18754
  pause: ["workflow_run", "pause"],
19003
18755
  resume: ["workflow_run", "resume"],
19004
18756
  stop: ["workflow_run", "stop"],
19005
- listFailed: [require_workflow.WORKFLOW_TOOLS_TOOL_NAME, "list-failed"],
19006
- listRuns: [require_workflow.WORKFLOW_TOOLS_TOOL_NAME, "list-runs"],
19007
- inspectDefinition: [require_workflow.WORKFLOW_TOOLS_TOOL_NAME, "inspect-definition"],
19008
- recoveryEvidence: [require_workflow.WORKFLOW_TOOLS_TOOL_NAME, "recovery-evidence"],
19009
- recover: [require_workflow.WORKFLOW_TOOLS_TOOL_NAME, "recover"]
18757
+ listFailed: [require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME, "list-failed"],
18758
+ listRuns: [require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME, "list-runs"],
18759
+ inspectDefinition: [require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME, "inspect-definition"],
18760
+ deleteDefinition: [require_workflowServices.DELETE_WORKFLOW_DEFINITION_TOOL_NAME],
18761
+ recoveryEvidence: [require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME, "recovery-evidence"],
18762
+ recover: [require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME, "recover"]
19010
18763
  };
19011
18764
  function recordedArgs(input, action) {
19012
18765
  const value = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
@@ -19113,6 +18866,16 @@ function workflowApprovalPolicies(isHelpActive) {
19113
18866
  abandon: {
19114
18867
  requirement: "human",
19115
18868
  describe: describeAbandon
18869
+ },
18870
+ deleteDefinition: {
18871
+ requirement: "human",
18872
+ describe(input) {
18873
+ const { source, key } = WorkflowDeleteDefinitionSchema.parse(input);
18874
+ return {
18875
+ title: "Delete a stored workflow definition",
18876
+ summary: `Delete ${key} from the ${source} workflow set. Repository files and run history are unchanged.`
18877
+ };
18878
+ }
19116
18879
  }
19117
18880
  };
19118
18881
  }
@@ -19123,13 +18886,21 @@ function createWorkflowNamespace(options) {
19123
18886
  const childNames = new Set(Object.keys(childMethods));
19124
18887
  const stepMethods = createWorkflowStepMethods(options.outcome);
19125
18888
  const stepNames = new Set(Object.keys(stepMethods));
19126
- const declarations = [...Object.keys(childMethods).map((name) => WORKFLOW_CHILD_DECLARATIONS[name]), ...Object.keys(stepMethods).map((name) => WORKFLOW_STEP_DECLARATIONS[name])].join("\n ");
18889
+ const { deleteDefinition, ...otherApprovals } = workflowApprovalPolicies(isHelpActive);
18890
+ const declarations = [
18891
+ ...options.storedDefinitions ? [WORKFLOW_DELETE_DEFINITION_DECLARATION] : [],
18892
+ ...Object.keys(childMethods).map((name) => WORKFLOW_CHILD_DECLARATIONS[name]),
18893
+ ...Object.keys(stepMethods).map((name) => WORKFLOW_STEP_DECLARATIONS[name])
18894
+ ].join("\n ");
19127
18895
  return {
19128
18896
  name: "workflow",
19129
18897
  summary: "Discover, validate and launch YAML workflows, inspect runs, request generation-checked controls, and recover failed runs from evidence.",
19130
18898
  declarations: declarations ? WORKFLOW_DECLARATIONS.replace(/\n\};$/u, `\n ${declarations}\n};`) : WORKFLOW_DECLARATIONS,
19131
18899
  portable: true,
19132
- approval: workflowApprovalPolicies(isHelpActive),
18900
+ approval: options.storedDefinitions ? {
18901
+ ...otherApprovals,
18902
+ deleteDefinition
18903
+ } : otherApprovals,
19133
18904
  bind(run) {
19134
18905
  if (run.sessionId !== options.sessionId) throw new Error("Workflow namespace belongs to another session.");
19135
18906
  const disposed = new AbortController();
@@ -19155,6 +18926,7 @@ function createWorkflowNamespace(options) {
19155
18926
  members.listFailed = (input) => invoke(() => options.operations.listFailed(input, signal));
19156
18927
  members.listRuns = (input) => invoke(() => options.operations.listRuns(input, signal));
19157
18928
  members.inspectDefinition = (input) => invoke(() => options.operations.inspectDefinition(input, options.cwd, signal));
18929
+ if (options.storedDefinitions) members.deleteDefinition = (input) => invoke(() => options.operations.deleteDefinition(input, signal));
19158
18930
  members.recoveryEvidence = (input) => invoke(() => options.operations.recoveryEvidence(input, signal));
19159
18931
  members.recover = (input) => invoke(() => options.operations.recover(input, signal));
19160
18932
  members.abandon = (input) => invoke(() => options.operations.abandon(input, signal));
@@ -19427,7 +19199,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
19427
19199
  return activity.isIdle && !activity.hasPendingMessages;
19428
19200
  },
19429
19201
  ...communication === void 0 ? {} : {
19430
- requestRelease: (parent, runKeys) => communication.publish(parent, require_workflow.WORKFLOW_SESSION_RELEASE_TYPE, { runKeys }),
19202
+ requestRelease: (parent, runKeys) => communication.publish(parent, require_workflowServices.WORKFLOW_SESSION_RELEASE_TYPE, { runKeys }),
19431
19203
  onPeerReady: (listener) => communication.onPeerReady(listener)
19432
19204
  }
19433
19205
  }) : void 0;
@@ -19769,13 +19541,13 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
19769
19541
  if (disposed) throw new Error(RUNTIME_DISPOSED_MESSAGE);
19770
19542
  if (refusal !== void 0) return textResult(`Error: ${refusal}`, true);
19771
19543
  try {
19772
- const source = workflowSession ? host.context.environment[require_workflow.WORKFLOW_LAUNCHER_SESSION_ENV] : void 0;
19544
+ const source = workflowSession ? host.context.environment[require_workflowServices.WORKFLOW_LAUNCHER_SESSION_ENV] : void 0;
19773
19545
  const resolved = {
19774
19546
  ...input,
19775
19547
  workflowPath: (0, node_path.resolve)(where.cwd, input.workflowPath),
19776
19548
  ...source === void 0 ? {} : { env: {
19777
19549
  ...input.env,
19778
- [require_workflow.WORKFLOW_LAUNCHER_SESSION_ENV]: source
19550
+ [require_workflowServices.WORKFLOW_LAUNCHER_SESSION_ENV]: source
19779
19551
  } }
19780
19552
  };
19781
19553
  if (input.env?.[PUBLIC_LAUNCH_ENV] === PUBLIC_LAUNCH_ENABLED) {
@@ -19902,10 +19674,10 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
19902
19674
  cwd: where.cwd,
19903
19675
  name,
19904
19676
  parentSessionId: self,
19905
- sessionProvenance: require_workflow.WORKFLOW_SESSION_PROVENANCE,
19677
+ sessionProvenance: require_workflowServices.WORKFLOW_SESSION_PROVENANCE,
19906
19678
  interaction: preparation === void 0 ? "unattended" : "interactive",
19907
19679
  ...preparation === void 0 ? {} : {
19908
- environment: { [require_workflow.WORKFLOW_LAUNCHER_SESSION_ENV]: self },
19680
+ environment: { [require_workflowServices.WORKFLOW_LAUNCHER_SESSION_ENV]: self },
19909
19681
  appendSystemPrompt: preparation
19910
19682
  },
19911
19683
  selection
@@ -19922,7 +19694,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
19922
19694
  workflowPath,
19923
19695
  env: {
19924
19696
  ...input.env,
19925
- [require_workflow.WORKFLOW_LAUNCHER_SESSION_ENV]: self
19697
+ [require_workflowServices.WORKFLOW_LAUNCHER_SESSION_ENV]: self
19926
19698
  }
19927
19699
  };
19928
19700
  if (admission) {
@@ -19983,7 +19755,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
19983
19755
  await sessionService.release(source);
19984
19756
  telemetry.recordEvent("po_workflow.session_released", { outcome: "released" });
19985
19757
  };
19986
- const stopReleaseRequests = communication?.subscribe(require_workflow.WORKFLOW_SESSION_RELEASE_TYPE, (source) => {
19758
+ const stopReleaseRequests = communication?.subscribe(require_workflowServices.WORKFLOW_SESSION_RELEASE_TYPE, (source) => {
19987
19759
  releaseWorkflowSession(source).catch(reportLifecycleFailure);
19988
19760
  });
19989
19761
  const stopPeerReady = communication?.onPeerReady(() => void 0);
@@ -20008,7 +19780,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20008
19780
  cwd: host.context.cwd,
20009
19781
  name: workflowSessionName(run.workflowPath, run.workflowName),
20010
19782
  parentSessionId: host.context.sessionId,
20011
- sessionProvenance: require_workflow.WORKFLOW_SESSION_PROVENANCE,
19783
+ sessionProvenance: require_workflowServices.WORKFLOW_SESSION_PROVENANCE,
20012
19784
  interaction: "unattended",
20013
19785
  selection: sessionSelection({
20014
19786
  ...config,
@@ -20147,6 +19919,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20147
19919
  }
20148
19920
  };
20149
19921
  const isHelpActive = () => !disposed && (host.context.selection.state?.["mode"] ?? []).includes(HELP_MODE_ID);
19922
+ const storedDefinitions = !dispatcher && (runtime.library?.length ?? 0) > 0;
20150
19923
  const operations = createWorkflowOperations({
20151
19924
  runtime,
20152
19925
  sessionId: host.context.sessionId,
@@ -20329,7 +20102,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20329
20102
  inputs,
20330
20103
  env,
20331
20104
  prompt
20332
- }), validationLocation.cwd, void 0, expected, request.kind === "launch" ? request.definition : previous?.allocation?.requirements.definition ?? require_contract.workflowDefinitionRef(workflowPath, validationLocation.repoRoot, runtime.library));
20105
+ }), validationLocation.cwd, void 0, expected, request.kind === "launch" ? request.definition : previous?.allocation?.requirements.definition ?? require_contract.workflowDefinitionRef(workflowPath, validationLocation.repoRoot, runtime.library), input.recovery?.definition);
20333
20106
  const report = prepared.report;
20334
20107
  const errors = [...report.diagnostics.filter((item) => item.level === "error"), ...refusal ? [{
20335
20108
  code: "launch-request",
@@ -20435,7 +20208,14 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20435
20208
  const live = AbortSignal.any([signal, startupAbort.signal]);
20436
20209
  live.throwIfAborted();
20437
20210
  const initialRuns = await untilAborted(snapshot(), live);
20438
- for (const run of initialRuns) if (runLaunchedBySession(run, host.context.sessionId) && run.piSessionId !== void 0) watchOwner(run.piSessionId);
20211
+ for (const run of initialRuns) {
20212
+ if (!runLaunchedBySession(run, host.context.sessionId) || run.piSessionId === void 0) continue;
20213
+ watchOwner(run.piSessionId);
20214
+ if (runtime.workflowHost.durable && run.view.stage === "running" && run.view.stale && run.view.runId) {
20215
+ const { registry } = featureFor(run.registryHome ?? ownHome);
20216
+ await untilAborted(registry.reconcileStaleRun(run.view, run.piSessionId), live);
20217
+ }
20218
+ }
20439
20219
  for (const home of /* @__PURE__ */ new Set([
20440
20220
  ownHome,
20441
20221
  ...features.keys(),
@@ -20489,6 +20269,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20489
20269
  sessionId: host.context.sessionId,
20490
20270
  cwd: host.context.cwd,
20491
20271
  operations,
20272
+ storedDefinitions,
20492
20273
  children,
20493
20274
  outcome,
20494
20275
  assertAvailable,
@@ -20499,7 +20280,8 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20499
20280
  REQUIREMENTS_TOOL,
20500
20281
  LAUNCH_TOOL,
20501
20282
  RUN_TOOL,
20502
- require_workflow.WORKFLOW_TOOLS_TOOL_NAME,
20283
+ require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME,
20284
+ ...storedDefinitions ? [require_workflowServices.DELETE_WORKFLOW_DEFINITION_TOOL_NAME] : [],
20503
20285
  ...createWorkflowChildTools({
20504
20286
  sessionId: host.context.sessionId,
20505
20287
  capability: children,
@@ -20725,7 +20507,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20725
20507
  }
20726
20508
  },
20727
20509
  {
20728
- name: require_workflow.WORKFLOW_TOOLS_TOOL_NAME,
20510
+ name: require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME,
20729
20511
  label: "Workflow Tools",
20730
20512
  description: "Workflow actions beyond workflow_run: list-failed reads redacted failed-run summaries with optional workspace, runKey and exact env filters; recovery-evidence reads a failed run's durable evidence, including one an earlier session launched; recover resumes it from its active repair in this session. validate, abandon, inspect-run, repair-run, help-repair, list-runs and inspect-definition are the workflow namespace members of the same names.",
20731
20513
  promptGuidelines: [
@@ -20759,6 +20541,18 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20759
20541
  });
20760
20542
  }
20761
20543
  },
20544
+ ...storedDefinitions ? [{
20545
+ name: require_workflowServices.DELETE_WORKFLOW_DEFINITION_TOOL_NAME,
20546
+ label: "Delete Stored Workflow",
20547
+ description: "Delete one named definition from a stored org, personal or host workflow set. Requires human approval and leaves repository files and run history untouched.",
20548
+ parameters: zod.z.toJSONSchema(WorkflowDeleteDefinitionSchema),
20549
+ mainAgentOnly: true,
20550
+ executionMode: "serial",
20551
+ approval: workflowApprovalPolicies(isHelpActive).deleteDefinition,
20552
+ async execute(_toolCallId, parameters, signal) {
20553
+ return operationResult(() => operations.deleteDefinition(parameters, signal));
20554
+ }
20555
+ }] : [],
20762
20556
  {
20763
20557
  name: REQUIREMENTS_TOOL,
20764
20558
  label: "Workflow Requirements",
@@ -20853,7 +20647,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20853
20647
  }
20854
20648
  }
20855
20649
  }],
20856
- ...dispatcher ? { toolRestrictions: [{ excludedTools: [RUN_TOOL, require_workflow.WORKFLOW_TOOLS_TOOL_NAME] }] } : {},
20650
+ ...dispatcher ? { toolRestrictions: [{ excludedTools: [RUN_TOOL, require_workflowServices.WORKFLOW_TOOLS_TOOL_NAME] }] } : {},
20857
20651
  async onDispose() {
20858
20652
  disposed = true;
20859
20653
  publicServices?.withdraw(host.context.sessionId);
@@ -21110,7 +20904,7 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(async
21110
20904
  const value = await index_server_default(context);
21111
20905
  return {
21112
20906
  value,
21113
- services: [...context.hosted("workspace") ? [provideWorkflowSources(context.root)] : [], ...value.services ?? []],
20907
+ services: [...context.hosted("workspace") ? [require_workflowServices.provideWorkflowSources(context.root)] : [], ...value.services ?? []],
21114
20908
  activities: value.activities,
21115
20909
  onStart: value.onStart,
21116
20910
  onStop: value.onStop,
@@ -21614,6 +21408,9 @@ var scaffold_workflow_server_default = (0, _agimon_ai_po_core_extensionFile.defi
21614
21408
  });
21615
21409
  });
21616
21410
  //#endregion
21411
+ //#region src/extensions/workspaces/sessions/(backend)/tool/workflow-delete-definition.server.ts
21412
+ var workflow_delete_definition_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.tools?.find(({ name }) => name === require_workflowServices.DELETE_WORKFLOW_DEFINITION_TOOL_NAME), { cardinality: "optional" });
21413
+ //#endregion
21617
21414
  //#region src/extensions/workspaces/sessions/(backend)/tool/workflow-requirements.server.ts
21618
21415
  var workflow_requirements_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoutedContribution)((context) => context.root.tools?.find(({ name }) => name === "workflow_requirements"), { cardinality: "optional" });
21619
21416
  //#endregion
@@ -21740,6 +21537,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
21740
21537
  via({ name: "launch_workflow" }, at(launch_workflow_server_default, contextSession)),
21741
21538
  via({ name: "list_workflows" }, at(list_workflows_server_default, contextSession)),
21742
21539
  via({ name: "scaffold_workflow" }, at(scaffold_workflow_server_default, contextSession)),
21540
+ via({ name: "workflow_delete_definition" }, at(workflow_delete_definition_server_default, contextSession)),
21743
21541
  via({ name: "workflow_requirements" }, at(workflow_requirements_server_default, contextSession)),
21744
21542
  via({ name: "workflow_run" }, at(workflow_run_server_default, contextSession)),
21745
21543
  via({ name: "workflow_tools" }, at(workflow_tools_server_default, contextSession))