@agimon-ai/po-workflow 0.0.0-alpha.205 → 0.0.0-alpha.206

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.
@@ -1419,6 +1419,30 @@ const REGISTRY_LAUNCHER = "po-workflow/registry";
1419
1419
  const RECOVERY_PURPOSE = "recovery";
1420
1420
  const MAX_REVISION_RETRIES = 50;
1421
1421
  const CONTROL_POLL_MS = 250;
1422
+ /** Bind launch inputs, not mutable progress, receipts or recovery metadata. */
1423
+ function workflowLaunchFingerprint(input) {
1424
+ const { configuration, workspace, workflowPath, job, runner, command, choice, profile, team, allocation, inputs, env, prompt, secretFile, continueOnError, dryRun } = input;
1425
+ return (0, node_crypto.createHash)("sha256").update(JSON.stringify({
1426
+ version: 1,
1427
+ definition: configuration?.workflow,
1428
+ revision: configuration?.revision,
1429
+ workspace,
1430
+ workflowPath,
1431
+ job,
1432
+ runner,
1433
+ command,
1434
+ choice,
1435
+ profile,
1436
+ team,
1437
+ allocation,
1438
+ inputs,
1439
+ env,
1440
+ prompt,
1441
+ secretFile,
1442
+ continueOnError,
1443
+ dryRun
1444
+ })).digest("hex");
1445
+ }
1422
1446
  /** Control listeners per store and run, so a write by any registry instance wakes every waiter. */
1423
1447
  const controlListeners = /* @__PURE__ */ new WeakMap();
1424
1448
  /** The listener key for every run, which no run ID can collide with. */
@@ -1682,9 +1706,12 @@ var WorkflowRegistryService = class {
1682
1706
  if (previous?.lifecycle === "running") throw new WorkflowRunConflictError(workspace, runKey);
1683
1707
  const previousRecord = previous ? this.tryRecord(previous) : void 0;
1684
1708
  const previousStage = previousRecord?.stage;
1709
+ if (input.recoveryPreviousRunId !== void 0 && input.recoveryPreviousRunId !== previous?.runId) throw new Error("Workflow recovery generation changed.");
1685
1710
  let claim;
1686
- if (previousStage === ERROR_STAGE$3) claim = await this.assertRecoveryPromotion(workspace, runKey, input.recoveryClaimId);
1687
- else if (input.recoveryClaimId) throw new Error(previous ? `Workflow recovery claim does not target a failed run: ${workspace}/${runKey}` : `Workflow recovery claim target no longer exists: ${workspace}/${runKey}`);
1711
+ if (previousStage === ERROR_STAGE$3) {
1712
+ claim = await this.assertRecoveryPromotion(workspace, runKey, input.recoveryClaimId);
1713
+ if (claim.runId !== previous?.runId) throw new Error("Workflow recovery generation changed.");
1714
+ } else if (input.recoveryClaimId) throw new Error(previous ? `Workflow recovery claim does not target a failed run: ${workspace}/${runKey}` : `Workflow recovery claim target no longer exists: ${workspace}/${runKey}`);
1688
1715
  const runDir = await this.getRunDirectory(workspace, runKey);
1689
1716
  (0, _agimon_ai_po_core_platform.getOrThrow)(await this.runtime.fs.createDir(runDir, { recursive: true }, this.runtime.ioContext));
1690
1717
  if (previous) {
@@ -1737,6 +1764,12 @@ var WorkflowRegistryService = class {
1737
1764
  const record = this.validateRunRecord(runRecord, `${workspace}/${runKey}`);
1738
1765
  const durable = this.runtime.workflowHost.durable;
1739
1766
  durable?.assertOwnership();
1767
+ const recovery = claim && previous && {
1768
+ resourceKey: claim.resourceKey,
1769
+ claimId: claim.acquisitionId,
1770
+ previousRunId: previous.runId,
1771
+ fence: await this.fence()
1772
+ };
1740
1773
  await durable?.setRunActive?.(runId, true);
1741
1774
  const admitted = await this.store.admitRun({
1742
1775
  authorityId: this.authorityId,
@@ -1750,10 +1783,12 @@ var WorkflowRegistryService = class {
1750
1783
  configuration: input.configuration ?? {},
1751
1784
  context: input.prompt === void 0 ? {} : { prompt: input.prompt },
1752
1785
  state: { record },
1753
- ...input.maxActive === void 0 ? {} : { maxActive: input.maxActive }
1786
+ ...input.maxActive === void 0 ? {} : { maxActive: input.maxActive },
1787
+ ...recovery ? { recovery } : {}
1754
1788
  });
1755
1789
  if (admitted.status !== "admitted") {
1756
1790
  await durable?.setRunActive?.(runId, false);
1791
+ if (admitted.status === "rejected" && admitted.reason === "recovery-changed") throw new Error("Workflow recovery generation or claim changed before admission.");
1757
1792
  if (admitted.status === "rejected" && admitted.reason === "capacity") throw new Error(`Workspace "${workspace}" already has ${input.maxActive} running workflow(s); wait for one to finish.`);
1758
1793
  throw new WorkflowRunConflictError(workspace, runKey);
1759
1794
  }
@@ -2290,6 +2325,7 @@ var WorkflowRegistryService = class {
2290
2325
  return {
2291
2326
  claimId: claim.acquisitionId,
2292
2327
  claimedAt: typeof detail.claimedAt === "string" ? detail.claimedAt : (/* @__PURE__ */ new Date()).toISOString(),
2328
+ ...claim.runId === void 0 ? {} : { runId: claim.runId },
2293
2329
  ...typeof detail.ownerSessionId === "string" ? { ownerSessionId: detail.ownerSessionId } : {},
2294
2330
  ...owner
2295
2331
  };
@@ -7947,6 +7983,7 @@ var StepRunnerService = class StepRunnerService {
7947
7983
  "workflow.step.attempt": attempt + 1
7948
7984
  }, (trace) => this.startStepExecution({
7949
7985
  traceparent: trace?.traceparent,
7986
+ runId: run?.handle.runId ?? options.runId,
7950
7987
  command,
7951
7988
  inProcessOnly: inProcessOnly === true,
7952
7989
  custom,
@@ -8493,6 +8530,7 @@ var StepRunnerService = class StepRunnerService {
8493
8530
  const executor = this.stepExecutor;
8494
8531
  const base = {
8495
8532
  traceparent: request.traceparent,
8533
+ ...request.runId === void 0 ? {} : { runId: request.runId },
8496
8534
  ...request.identity === void 0 ? {} : { identity: request.identity },
8497
8535
  ...request.allocation === void 0 ? {} : { allocation: request.allocation },
8498
8536
  ...request.matrixIndex === void 0 ? {} : { matrixIndex: request.matrixIndex },
@@ -10460,6 +10498,7 @@ function createStepExecutor(dependencies) {
10460
10498
  const childSession = (request) => runSession({
10461
10499
  ...request,
10462
10500
  child,
10501
+ runId: child.context.run.runId,
10463
10502
  evidence,
10464
10503
  onUsage: (usage) => {
10465
10504
  usages.push(usage);
@@ -10592,10 +10631,9 @@ function createStepExecutor(dependencies) {
10592
10631
  return durable?.executeStep ? durable.executeStep(request, (recordRef) => runSessionUntracked(request, recordRef)) : runSessionUntracked(request);
10593
10632
  }
10594
10633
  /**
10595
- * Opens a step's session, reopening `previous` (this step's earlier session) so the agent continues its
10596
- * conversation. A host that refuses, or opens a new session instead, leaves the step a fresh one.
10634
+ * Reopens this step's earlier session. Only hosts without committed launch authority may fall back to a fresh one.
10597
10635
  */
10598
- async function openStepSession(creation, previous, attributes) {
10636
+ async function openStepSession(creation, previous, attributes, authorityRequired) {
10599
10637
  if (previous === void 0) return sessionService.create(creation);
10600
10638
  try {
10601
10639
  const scope = await sessionService.create({
@@ -10603,6 +10641,7 @@ function createStepExecutor(dependencies) {
10603
10641
  reopenSessionId: previous
10604
10642
  });
10605
10643
  const resumed = scope.sessionId === previous;
10644
+ if (!resumed && authorityRequired) throw new Error("The authorized workflow step session was not reopened.");
10606
10645
  telemetry?.recordEvent(STEP_SESSION_RESUME_EVENT, {
10607
10646
  ...attributes,
10608
10647
  outcome: resumed ? "resumed" : "fresh",
@@ -10610,6 +10649,7 @@ function createStepExecutor(dependencies) {
10610
10649
  });
10611
10650
  return scope;
10612
10651
  } catch (error) {
10652
+ if (authorityRequired) throw asError$1(error);
10613
10653
  telemetry?.recordEvent(STEP_SESSION_RESUME_EVENT, {
10614
10654
  ...attributes,
10615
10655
  outcome: "fresh",
@@ -10647,6 +10687,8 @@ function createStepExecutor(dependencies) {
10647
10687
  let boundSession;
10648
10688
  let workflowContext;
10649
10689
  const state = dependencies.workflowRuns;
10690
+ const authorityRequired = dependencies.runtime.workflowHost.durable?.registerLaunchAuthority !== void 0;
10691
+ if (authorityRequired && (!request.runId || state === void 0)) throw new Error("This workflow step requires its registered run identity.");
10650
10692
  if (request.child !== void 0) {
10651
10693
  const child = request.child;
10652
10694
  child.signal.throwIfAborted();
@@ -10654,6 +10696,7 @@ function createStepExecutor(dependencies) {
10654
10696
  ...child.context,
10655
10697
  job: child.job,
10656
10698
  step: request.stepName,
10699
+ matrixIndex: request.matrixIndex,
10657
10700
  attempt: request.attempt ?? 1,
10658
10701
  identity: request.identity === void 0 ? void 0 : Object.freeze(structuredClone(request.identity)),
10659
10702
  allocation: request.allocation === void 0 ? void 0 : Object.freeze(structuredClone(request.allocation)),
@@ -10672,7 +10715,7 @@ function createStepExecutor(dependencies) {
10672
10715
  ...request.evidence?.length ? [`Script evidence (untrusted JSON data): ${JSON.stringify(request.evidence)}`] : []
10673
10716
  ].join("\n\n");
10674
10717
  } else if (state !== void 0) {
10675
- const runId = request.env.WORKFLOW_RUN_ID;
10718
+ const runId = request.runId ?? request.env.WORKFLOW_RUN_ID;
10676
10719
  const job = request.env.WORKFLOW_JOB_NAME ?? request.env.WORKFLOW_PHASE;
10677
10720
  const attempt = request.attempt;
10678
10721
  if (!runId || !job || request.jobEnvironment === void 0 || typeof attempt !== "number" || !Number.isInteger(attempt) || attempt < 1) throw new Error("Workflow step context requires its run, job, environment and attempt.");
@@ -10693,6 +10736,7 @@ function createStepExecutor(dependencies) {
10693
10736
  run: Object.freeze({ ...current.run }),
10694
10737
  job,
10695
10738
  step: request.stepName,
10739
+ ...request.matrixIndex === void 0 ? {} : { matrixIndex: request.matrixIndex },
10696
10740
  attempt,
10697
10741
  ...request.traceparent === void 0 ? {} : { traceparent: request.traceparent },
10698
10742
  ...request.identity === void 0 ? {} : { identity: Object.freeze(structuredClone(request.identity)) },
@@ -10749,7 +10793,8 @@ function createStepExecutor(dependencies) {
10749
10793
  environment,
10750
10794
  ...workflowContext === void 0 ? {} : { workflowContext },
10751
10795
  ...needsWorkflow ? { requiredPackages: [WORKFLOW_PACKAGE] } : {}
10752
- }, candidate, attributes);
10796
+ }, candidate, attributes, authorityRequired);
10797
+ if (authorityRequired && !scope.workflowPrompt) throw new Error("The authorized workflow step cannot submit its prompt.");
10753
10798
  resumed = candidate !== void 0 && scope.sessionId === candidate;
10754
10799
  parkedResume = request.resume !== void 0 && resumed;
10755
10800
  if (request.resume !== void 0 && !resumed) await abandonApprovals(request.resume.sessionId);
@@ -10813,7 +10858,7 @@ function createStepExecutor(dependencies) {
10813
10858
  */
10814
10859
  const remind = async (message) => {
10815
10860
  for (;;) try {
10816
- return await prompt(sessionId, message);
10861
+ return await (scope.workflowPrompt ? scope.workflowPrompt(message) : prompt(sessionId, message));
10817
10862
  } catch (error) {
10818
10863
  if (!BUSY_SESSION_PATTERN.test(asError$1(error).message)) throw error;
10819
10864
  telemetry?.recordEvent(STEP_REMINDER_EVENT, {
@@ -10988,6 +11033,7 @@ function createStepExecutor(dependencies) {
10988
11033
  async custom(request) {
10989
11034
  return runSession({
10990
11035
  cwd: request.cwd,
11036
+ runId: request.runId,
10991
11037
  env: request.env,
10992
11038
  stepName: request.stepName,
10993
11039
  runConfig: request.runConfig,
@@ -11008,6 +11054,7 @@ function createStepExecutor(dependencies) {
11008
11054
  const template = request.template;
11009
11055
  if (template?.inProcess && prompt !== void 0) return runSession({
11010
11056
  cwd: request.cwd,
11057
+ runId: request.runId,
11011
11058
  env: request.env,
11012
11059
  stepName: request.stepName,
11013
11060
  runConfig: request.runConfig,
@@ -13042,7 +13089,9 @@ function createWorkflowHubApi(options) {
13042
13089
  });
13043
13090
  app.post(routes.launch.path, async (context) => {
13044
13091
  if (options.launch === void 0) return context.json({ error: "Launching needs the mount of a session with a workflow runtime." }, 409);
13045
- const response = await options.launch(await jsonBody(context));
13092
+ const parameters = await jsonBody(context);
13093
+ const member = context.env?.enablingMember;
13094
+ const response = await (member === void 0 ? options.launch(parameters) : options.launch(parameters, member));
13046
13095
  return context.json(response);
13047
13096
  });
13048
13097
  app.delete(routes.remove.path, async (context) => {
@@ -13388,7 +13437,7 @@ function createWorkflowApi(runtime, launch, resolveHome) {
13388
13437
  return app;
13389
13438
  };
13390
13439
  return {
13391
- async fetch(request) {
13440
+ async fetch(request, admittedMember) {
13392
13441
  const pathname = new URL(request.url).pathname;
13393
13442
  const operation = Object.entries(routes).find(([, route]) => route.method === request.method && new RegExp(`^${route.path.replace(":name{.+}", ".+").replace(/:[a-zA-Z]+/gu, "[^/]+")}$`, "u").test(pathname))?.[0] ?? "other";
13394
13443
  return telemetry.runInSpan("po_workflow.request", { operation }, async () => {
@@ -13433,7 +13482,7 @@ function createWorkflowApi(runtime, launch, resolveHome) {
13433
13482
  url.pathname = segments.join("/");
13434
13483
  }
13435
13484
  request.signal.throwIfAborted();
13436
- return appFor(location.homeDir).fetch(new Request(url, request));
13485
+ return appFor(location.homeDir).fetch(new Request(url, request), { enablingMember: admittedMember });
13437
13486
  });
13438
13487
  },
13439
13488
  close: () => telemetry.shutdown()
@@ -14023,14 +14072,7 @@ function attemptIdentityKey(input) {
14023
14072
  input.childInvocationId ?? null
14024
14073
  ]);
14025
14074
  }
14026
- /**
14027
- * The process's activations per database, then authority and owner. Kept on `globalThis` so every
14028
- * store wrapper and every loaded copy of this module shares one activation: activating again would
14029
- * fence this process's own earlier activation and mark its in-flight attempts uncertain. One found
14030
- * stale is dropped, so the next use activates again instead of staying fenced for the process's life.
14031
- */
14032
14075
  const ACTIVATIONS = Symbol.for("@agimon-ai/po-workflow/activations");
14033
- const processActivations = globalThis[ACTIVATIONS] ??= /* @__PURE__ */ new WeakMap();
14034
14076
  const activationKey = (authorityId, owner) => JSON.stringify([authorityId, owner]);
14035
14077
  /**
14036
14078
  * Durable workflow run, admission, ownership, claim, attempt and event state in the shared Po database.
@@ -14040,10 +14082,13 @@ const activationKey = (authorityId, owner) => JSON.stringify([authorityId, owner
14040
14082
  */
14041
14083
  var PoDbWorkflowStoreService = class PoDbWorkflowStoreService {
14042
14084
  db;
14085
+ activations;
14043
14086
  now;
14044
14087
  id;
14045
14088
  constructor(options) {
14046
14089
  this.db = options.db;
14090
+ const db = options.db;
14091
+ this.activations = db[ACTIVATIONS] ??= /* @__PURE__ */ new Map();
14047
14092
  this.now = options.now ?? Date.now;
14048
14093
  this.id = options.id ?? (() => crypto.randomUUID());
14049
14094
  }
@@ -14053,30 +14098,24 @@ var PoDbWorkflowStoreService = class PoDbWorkflowStoreService {
14053
14098
  return new PoDbWorkflowStoreService(options);
14054
14099
  }
14055
14100
  async currentActivation(authorityId, owner) {
14056
- let byOwner = processActivations.get(this.db);
14057
- if (!byOwner) {
14058
- byOwner = /* @__PURE__ */ new Map();
14059
- processActivations.set(this.db, byOwner);
14060
- }
14061
14101
  const key = activationKey(authorityId, owner);
14062
- let activation = byOwner.get(key);
14102
+ let activation = this.activations.get(key);
14063
14103
  if (!activation) {
14064
14104
  const entry = { started: this.activateOwner(authorityId, owner) };
14065
14105
  activation = entry;
14066
- byOwner.set(key, entry);
14106
+ this.activations.set(key, entry);
14067
14107
  entry.started.then((fence) => {
14068
14108
  entry.fence = fence;
14069
14109
  }, () => {
14070
- if (byOwner.get(key) === entry) byOwner.delete(key);
14110
+ if (this.activations.get(key) === entry) this.activations.delete(key);
14071
14111
  });
14072
14112
  }
14073
14113
  return activation.started;
14074
14114
  }
14075
14115
  /** Drops the cached activation `fence` came from once something else replaced it. */
14076
14116
  forgetActivation(fence) {
14077
- const byOwner = processActivations.get(this.db);
14078
14117
  const key = activationKey(fence.authorityId, fence.owner);
14079
- if (byOwner?.get(key)?.fence?.token === fence.token) byOwner.delete(key);
14118
+ if (this.activations.get(key)?.fence?.token === fence.token) this.activations.delete(key);
14080
14119
  }
14081
14120
  transaction(work) {
14082
14121
  return this.db.database.transaction(work);
@@ -14110,7 +14149,12 @@ var PoDbWorkflowStoreService = class PoDbWorkflowStoreService {
14110
14149
  if (input.maxActive !== void 0) {
14111
14150
  if (((await tx.get("SELECT COUNT(*) AS count FROM workflow_runs WHERE authority_id = ? AND workspace_id = ? AND active = 1", input.authorityId, input.workspaceId))?.count ?? 0) >= input.maxActive) return reject("capacity");
14112
14151
  }
14113
- const latest = await tx.get("SELECT lineage_id, generation FROM workflow_runs WHERE authority_id = ? AND workspace_id = ? AND run_key = ? ORDER BY generation DESC LIMIT 1", input.authorityId, input.workspaceId, input.runKey);
14152
+ const latest = await tx.get("SELECT run_id, lineage_id, generation, lifecycle, tombstoned_at FROM workflow_runs WHERE authority_id = ? AND workspace_id = ? AND run_key = ? ORDER BY generation DESC LIMIT 1", input.authorityId, input.workspaceId, input.runKey);
14153
+ if (input.recovery) {
14154
+ const { resourceKey, claimId, previousRunId, fence } = input.recovery;
14155
+ if (latest?.run_id !== previousRunId || latest.lifecycle !== "failed" || latest.tombstoned_at !== null || fence.authorityId !== input.authorityId || !await this.fenceIsCurrent(tx, fence)) return reject("recovery-changed");
14156
+ if (!await tx.get("SELECT acquisition_id FROM workflow_claims WHERE authority_id = ? AND resource_key = ? AND acquisition_id = ? AND run_id = ? AND state = 'adopted' AND owner = ? AND fence = ?", input.authorityId, resourceKey, claimId, previousRunId, fence.owner, fence.fence)) return reject("recovery-changed");
14157
+ }
14114
14158
  const run = {
14115
14159
  runId: input.runId ?? this.id(),
14116
14160
  authorityId: input.authorityId,
@@ -16120,7 +16164,7 @@ var RunWorkflowService = class {
16120
16164
  const saved = input.recovery?.definition ?? input.definition;
16121
16165
  const pinned = input.recovery === void 0 && input.definition !== void 0;
16122
16166
  const path = (0, node_path.resolve)(this.runtime.cwd, input.workflowPath);
16123
- const adopts = input.recovery?.adoptDefinition === true || input.helpActive?.() === true;
16167
+ const adopts = input.authorizeRegistration === void 0 && (input.recovery?.adoptDefinition === true || input.helpActive?.() === true);
16124
16168
  const workflow = saved && (pinned || !adopts || !await this.pathExists(path)) ? structuredClone(saved) : await this.parser.parseWorkflowFile(path);
16125
16169
  this.assertRecoveryEdit(input, workflow);
16126
16170
  return this.admitAllocationForWorkflow(input, workflow);
@@ -16191,7 +16235,7 @@ var RunWorkflowService = class {
16191
16235
  let saved = input.recovery?.definition ?? input.definition;
16192
16236
  const pinned = input.recovery === void 0 && input.definition !== void 0;
16193
16237
  let adopting = input.recovery?.adoptDefinition === true;
16194
- const adopts = () => adopting || input.helpActive?.() === true;
16238
+ const adopts = () => input.authorizeRegistration === void 0 && (adopting || input.helpActive?.() === true);
16195
16239
  const readDefinition = async (path) => {
16196
16240
  if (saved && (pinned || !adopts() || !await this.pathExists(path))) return structuredClone(saved);
16197
16241
  const parsed = await this.parser.parseWorkflowFile(path);
@@ -16246,6 +16290,7 @@ var RunWorkflowService = class {
16246
16290
  revision: workflowDefinitionRevision(workflow)
16247
16291
  });
16248
16292
  let policyAuthorized = input.admission?.binding === void 0;
16293
+ let registrationAuthorized = input.authorizeRegistration === void 0 || dryRun;
16249
16294
  let progress;
16250
16295
  let result = null;
16251
16296
  let runError = null;
@@ -16323,37 +16368,50 @@ var RunWorkflowService = class {
16323
16368
  const workflowName = input.name ? baseName : `${baseName}-${this.parser.generateHumanReadableId()}-${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;
16324
16369
  const workflowId = (0, node_path.basename)(workflowPath, (0, node_path.extname)(workflowPath));
16325
16370
  if (dryRun && input.recovery) registryRun = await this.createRecoveryDryRunHandle(input, resolvedWorkspace);
16326
- else registryRun = await this.registry.createRun({
16327
- activeRepairId: input.recovery?.activeRepairId,
16328
- admission: input.admission,
16329
- configuration: configuration(),
16330
- continueOnError: input.continueOnError,
16331
- displayName: workflowName,
16332
- dryRun,
16333
- env: input.env,
16334
- inputs: input.inputs,
16335
- job: input.recovery ? input.recovery.originalJob : input.job,
16336
- launcher: this.launcherMetadata ?? await this.resolveLauncherMetadata(),
16337
- prompt: input.prompt,
16338
- recoveryClaimId: input.recovery?.claimId,
16339
- recoveries: input.recovery?.recoveries,
16340
- runner,
16341
- command: input.command,
16342
- choice: input.choice,
16343
- profile: input.profile,
16344
- allocation,
16345
- runDirectory: workflow["run-directory"],
16346
- secretFile: input.secretFile,
16347
- workflowPath,
16348
- workflowId,
16349
- workflowName: workflow.name ?? workflowId,
16350
- workflowWorkspace: workflow.workspace,
16351
- workspace: input.workspace
16352
- });
16353
- if (!dryRun && input.admission?.binding) {
16354
- const admitted = await this.registry.authorizeExecution(registryRun);
16355
- Object.assign(workflowEnv, admitted.admission?.environment);
16356
- policyAuthorized = true;
16371
+ else {
16372
+ const launch = {
16373
+ activeRepairId: input.recovery?.activeRepairId,
16374
+ admission: input.admission,
16375
+ configuration: configuration(),
16376
+ continueOnError: input.continueOnError,
16377
+ displayName: workflowName,
16378
+ dryRun,
16379
+ env: input.env,
16380
+ inputs: input.inputs,
16381
+ job: input.recovery ? input.recovery.originalJob : input.job,
16382
+ launcher: this.launcherMetadata ?? await this.resolveLauncherMetadata(),
16383
+ prompt: input.prompt,
16384
+ recoveryClaimId: input.recovery?.claimId,
16385
+ recoveryPreviousRunId: input.recovery?.previousRunId,
16386
+ recoveries: input.recovery?.recoveries,
16387
+ runner,
16388
+ command: input.command,
16389
+ choice: input.choice,
16390
+ profile: input.profile,
16391
+ ...input.authorizeRegistration ? { team: input.team } : {},
16392
+ allocation,
16393
+ runDirectory: workflow["run-directory"],
16394
+ secretFile: input.secretFile,
16395
+ workflowPath,
16396
+ workflowId,
16397
+ workflowName: workflow.name ?? workflowId,
16398
+ workflowWorkspace: workflow.workspace,
16399
+ workspace: input.workspace
16400
+ };
16401
+ const fingerprint = !dryRun && input.authorizeRegistration ? workflowLaunchFingerprint({
16402
+ ...launch,
16403
+ workspace: resolvedWorkspace
16404
+ }) : void 0;
16405
+ registryRun = await this.registry.createRun(launch);
16406
+ if (!dryRun && input.admission?.binding) {
16407
+ const admitted = await this.registry.authorizeExecution(registryRun);
16408
+ Object.assign(workflowEnv, admitted.admission?.environment);
16409
+ policyAuthorized = true;
16410
+ }
16411
+ if (fingerprint !== void 0 && input.authorizeRegistration) {
16412
+ await input.authorizeRegistration(registryRun.runId, fingerprint);
16413
+ registrationAuthorized = true;
16414
+ }
16357
16415
  }
16358
16416
  if (input.recovery?.activeRepairId && !dryRun) activeRepair = await this.repairService.readRepair(registryRun.runDir, input.recovery.activeRepairId);
16359
16417
  const runBinding = {
@@ -16880,7 +16938,7 @@ var RunWorkflowService = class {
16880
16938
  } else throw error;
16881
16939
  } finally {
16882
16940
  if (registryRun && !(dryRun && input.recovery)) await this.registry.markFinalizing(registryRun);
16883
- if (workflow.post && policyAuthorized && parkedWait === void 0) {
16941
+ if (workflow.post && policyAuthorized && registrationAuthorized && parkedWait === void 0) {
16884
16942
  this.stepRunner.resetInterruption();
16885
16943
  const settled = this.resolveRunOutcome(result, runError);
16886
16944
  workflowEnv[WORKFLOW_PHASE_ENV] = "post";
@@ -16895,6 +16953,7 @@ var RunWorkflowService = class {
16895
16953
  continueOnError,
16896
16954
  progress,
16897
16955
  workflowDir,
16956
+ runId: registryRun?.runId,
16898
16957
  ...noProfile
16899
16958
  }))) {
16900
16959
  this.logger.error(`\n${RED}${BOLD}${WORKFLOW_POST_FAILED_TEXT}${RESET}`);
@@ -17588,7 +17647,8 @@ function createServerLauncher(dependencies) {
17588
17647
  await telemetry?.recordWarning(RUN_STOP_FAILED_EVENT, error);
17589
17648
  }
17590
17649
  };
17591
- const runInProcess = async (input, helpActive) => {
17650
+ const runInProcess = async (input, host) => {
17651
+ if (dependencies.runtime.workflowHost.durable?.registerLaunchAuthority && !input.dryRun && !host.authorizeRegistration) throw new Error("A pinned profile workflow requires a verified enabling member.");
17592
17652
  const launchId = input.env?.[require_workflowServices.WORKFLOW_LAUNCH_ID_ENV];
17593
17653
  if (launchId === void 0) throw new Error("An in-process launch needs its launch id.");
17594
17654
  const log = createRunLog(dependencies.runtime, telemetry);
@@ -17604,7 +17664,8 @@ function createServerLauncher(dependencies) {
17604
17664
  const result = await service.run({
17605
17665
  ...input,
17606
17666
  ...runner === void 0 ? {} : { runner },
17607
- helpActive,
17667
+ helpActive: host.helpActive,
17668
+ authorizeRegistration: host.authorizeRegistration,
17608
17669
  onConfigChanged: (registration) => dependencies.onConfigChanged?.(registration, input),
17609
17670
  onRegistered: (registration) => {
17610
17671
  run.registration = registration;
@@ -17638,7 +17699,7 @@ function createServerLauncher(dependencies) {
17638
17699
  environment: dependencies.environment,
17639
17700
  activeRunCount: async () => active.size,
17640
17701
  ...dependencies.rejectRunner === void 0 ? {} : { rejectRunner: dependencies.rejectRunner },
17641
- runTool: { execute: (input) => runInProcess(input, host.helpActive) },
17702
+ runTool: { execute: (input) => runInProcess(input, host) },
17642
17703
  trackPendingRun: (pending) => pending,
17643
17704
  findLaunchedRun: async ({ launchId }) => {
17644
17705
  const registration = active.get(launchId)?.registration;
@@ -17683,6 +17744,7 @@ function createServerLauncher(dependencies) {
17683
17744
  },
17684
17745
  async recover(target, { helpActive, byOwner, ...options }) {
17685
17746
  if (closing) return textResult$1("The workflow session is closing.", true);
17747
+ if (dependencies.runtime.workflowHost.durable?.registerLaunchAuthority && !options.dryRun) return textResult$1("Pinned profile workflow recovery is unavailable.", true);
17686
17748
  const run = {
17687
17749
  interrupt: () => void 0,
17688
17750
  target,
@@ -17808,6 +17870,7 @@ const FIX_STATUS_KEY = "status";
17808
17870
  const FIX_TERMINAL_TARGET = "stop";
17809
17871
  const REPAIR_TRIAGE_JOB_NAME = "repair-triage";
17810
17872
  const PO_SESSION_ENV = "PO_SESSION_ID";
17873
+ const PINNED_RECOVERY_UNAVAILABLE = "Pinned profile workflow recovery is unavailable.";
17811
17874
  /**
17812
17875
  * RecoverWorkflowService reconstructs and replays failed workflow runs.
17813
17876
  */
@@ -17858,10 +17921,10 @@ var RecoverWorkflowService = class {
17858
17921
  source: "default"
17859
17922
  };
17860
17923
  }
17861
- async recoverClaimed(input, claimId, owner, record, editPolicy) {
17862
- const replay = await this.buildReplay(input, claimId, owner, record, editPolicy);
17924
+ async recoverClaimed(replay, authorizeRegistration) {
17863
17925
  return this.runner.run({
17864
17926
  ...replay,
17927
+ authorizeRegistration,
17865
17928
  onRegistered: (registration) => this.hooks.onRegistered?.(registration, replay),
17866
17929
  onConfigChanged: (registration) => this.hooks.onConfigChanged?.(registration, replay)
17867
17930
  });
@@ -17870,23 +17933,32 @@ var RecoverWorkflowService = class {
17870
17933
  const record = await this.registry.readRunByKey(input.workspace, ERROR_STAGE, input.runKey);
17871
17934
  if (this.hooks.expectedRunId !== void 0 && record.runId !== this.hooks.expectedRunId) throw new Error("Workflow recovery generation changed.");
17872
17935
  if (record.admission && ownerSessionId !== record.admission.ownerSessionId) throw new Error("Managed workflow recovery must run in its original owner session.");
17936
+ const durable = this.runtime.workflowHost.durable;
17937
+ const pinned = durable?.registerLaunchAuthority !== void 0;
17938
+ const prepareAuthority = pinned && ownerSessionId && durable?.prepareRecoveryAuthority ? (previous) => durable.prepareRecoveryAuthority(previous.runId, ownerSessionId, workflowLaunchFingerprint(previous), previous.wait) : void 0;
17939
+ if (pinned && !(input.dryRun ?? record.dryRun) && (!this.hooks.authorizePinnedCheckpoint || !this.hooks.expectedRunId || !prepareAuthority || record.dryRun || input.recoveryClaimId !== void 0 || input.runner !== void 0 || this.hooks.admission !== void 0)) throw new Error(PINNED_RECOVERY_UNAVAILABLE);
17873
17940
  const editPolicy = await this.editPolicy();
17874
- await this.runner.prepareAllocation(await this.buildReplay(input, void 0, ownerSessionId, record, editPolicy));
17875
- if (input.dryRun || record.dryRun) return await this.recoverClaimed(input, void 0, void 0, record, editPolicy);
17941
+ const preview = await this.buildReplay(input, void 0, ownerSessionId, record, editPolicy);
17942
+ await this.runner.prepareAllocation(preview);
17943
+ if (input.dryRun || record.dryRun) return await this.recoverClaimed(preview);
17876
17944
  const claim = input.recoveryClaimId ? await this.registry.adoptRunRecoveryClaim(record.workspace, record.runKey, input.recoveryClaimId) : await this.registry.claimRunRecovery(record.workspace, record.runKey, ownerSessionId);
17877
17945
  try {
17878
- if (!input.recoveryClaimId) await this.registry.adoptRunRecoveryClaim(record.workspace, record.runKey, claim.claimId);
17946
+ const adopted = input.recoveryClaimId ? claim : await this.registry.adoptRunRecoveryClaim(record.workspace, record.runKey, claim.claimId);
17879
17947
  const current = await this.registry.readRunByKey(record.workspace, ERROR_STAGE, record.runKey);
17880
- if (current.runId !== record.runId) throw new Error("Workflow recovery generation changed after claiming.");
17948
+ if (!current.runId || current.runId !== record.runId || current.runId !== adopted.runId) throw new Error("Workflow recovery generation changed after claiming.");
17881
17949
  if (current.admission?.settlement?.outcome === "abandoned") throw new Error(`Workflow run "${record.workspace}/${record.runKey}" was abandoned and cannot be recovered`);
17950
+ if (pinned && (!current.configuration || current.admission !== void 0 || current.allocation !== void 0 || current.wait !== void 0 && (current.wait.parkedRunId !== current.runId || current.wait.blocked !== void 0) || current.secretFile !== void 0 || current.activeRepairId !== void 0 || current.fixLoopCycle !== void 0 || durable?.interruptionReason?.(current.runKey) !== void 0 || this.hooks.authorizePinnedCheckpoint?.(current) !== true)) throw new Error(PINNED_RECOVERY_UNAVAILABLE);
17951
+ const authorizeRegistration = await prepareAuthority?.(current);
17952
+ const replayRecord = pinned ? current : {
17953
+ ...record,
17954
+ wait: current.wait
17955
+ };
17956
+ const replay = pinned ? await this.buildReplay(input, claim.claimId, claim.ownerSessionId, replayRecord, editPolicy) : void 0;
17882
17957
  const runDir = await this.registry.runDirectoryFor(record);
17883
17958
  const paneRefs = (await this.registry.readProgress(record.runId)).flatMap((event) => event.ref?.kind === "pane" ? [event.ref.id] : []);
17884
17959
  if (paneRefs.length) await new NativeTerminalService(this.runtime).killRunPanes(record.runId, paneRefs);
17885
17960
  await killRunServices(this.runtime, runDir);
17886
- return await this.recoverClaimed(input, claim.claimId, claim.ownerSessionId, {
17887
- ...record,
17888
- wait: current.wait
17889
- }, editPolicy);
17961
+ return await this.recoverClaimed(replay ?? await this.buildReplay(input, claim.claimId, claim.ownerSessionId, replayRecord, editPolicy), authorizeRegistration);
17890
17962
  } catch (error) {
17891
17963
  await this.registry.releaseRunRecoveryClaim(record.workspace, record.runKey, claim.claimId);
17892
17964
  throw error;
@@ -17907,6 +17979,8 @@ var RecoverWorkflowService = class {
17907
17979
  if (terminalFix.terminal) throw new Error(`Workflow run "${record.workspace}/${record.runKey}" has a terminal fix request and cannot be recovered`);
17908
17980
  if (record.admission?.settlement?.outcome === "abandoned") throw new Error(`Workflow run "${record.workspace}/${record.runKey}" was abandoned and cannot be recovered`);
17909
17981
  const fixRestartFrom = terminalFix.restartFrom;
17982
+ const pinned = this.runtime.workflowHost.durable?.registerLaunchAuthority !== void 0;
17983
+ if (pinned && recoveryClaimId !== void 0 && fixRestartFrom !== void 0) throw new Error(PINNED_RECOVERY_UNAVAILABLE);
17910
17984
  const recoveredJob = record.wait?.job ?? (activeRepair ? this.repairService.resolveRecoveryStart(activeRepair) : fixRestartFrom ?? record.failedJob);
17911
17985
  if (!recoveredJob) throw new Error(`Workflow run "${record.workspace}/${record.runKey}" does not include a recoverable failed job`);
17912
17986
  const runner = input.runner ?? record.runner ?? record.cliAgent;
@@ -17939,7 +18013,7 @@ var RecoverWorkflowService = class {
17939
18013
  } : void 0);
17940
18014
  if (record.admission && admission && (admission.ownerSessionId !== record.admission.ownerSessionId || admission.launcherSessionId !== record.admission.launcherSessionId || JSON.stringify(admission.binding?.association) !== JSON.stringify(record.admission.binding?.association))) throw new Error("Workflow recovery policy ownership changed.");
17941
18015
  const envOverrides = ownerSessionId ? { [PO_SESSION_ENV]: ownerSessionId } : void 0;
17942
- const byOwner = this.hooks.byOwner === true;
18016
+ const byOwner = !pinned && this.hooks.byOwner === true;
17943
18017
  const dryRun = input.dryRun ?? record.dryRun;
17944
18018
  const recoveries = (record.recoveries ?? 0) + (byOwner && !dryRun ? 1 : 0);
17945
18019
  const handed = record.admission !== void 0 && record.admission.ownerSessionId !== record.admission.launcherSessionId;
@@ -17967,10 +18041,11 @@ var RecoverWorkflowService = class {
17967
18041
  prompt: record.prompt,
17968
18042
  name: record.displayName,
17969
18043
  workspace: record.workspace,
17970
- helpActive: this.hooks.helpActive,
18044
+ helpActive: pinned ? void 0 : this.hooks.helpActive,
17971
18045
  recovery: {
17972
18046
  activeRepairId: activeRepair?.repairId,
17973
18047
  claimId: recoveryClaimId,
18048
+ ...recoveryClaimId === void 0 ? {} : { previousRunId: record.runId },
17974
18049
  originalJob,
17975
18050
  runKey: record.runKey,
17976
18051
  startJob: recoveredJob,
@@ -19861,6 +19936,11 @@ const RUN_TOOL = "workflow_run";
19861
19936
  const IN_PROCESS_ORIGIN = "http://po.local";
19862
19937
  /** A burst of job and step events is published once, this long after the first. */
19863
19938
  const RUNS_PUBLISH_DEBOUNCE_MS = 100;
19939
+ /**
19940
+ * A catalog read walks the session's directory tree, so a tool call schedules one at most this often
19941
+ * rather than walking per call. Opening the catalog still reads it fresh.
19942
+ */
19943
+ const CATALOG_PUBLISH_THROTTLE_MS = 3e4;
19864
19944
  /** A notification body's limit; a longer failure is cut to it. */
19865
19945
  const NOTICE_BODY_LIMIT = 4e3;
19866
19946
  /** A dry run only printed what it would do, so there is nothing to continue from. */
@@ -20330,6 +20410,16 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20330
20410
  }, RUNS_PUBLISH_DEBOUNCE_MS);
20331
20411
  runsTimer.unref?.();
20332
20412
  };
20413
+ let catalogTimer;
20414
+ /** One catalog publish per window, off the caller's path; a burst of tool calls walks the tree once. */
20415
+ const publishCatalogSoon = (executionContext) => {
20416
+ if (disposed || catalogTimer !== void 0) return;
20417
+ catalogTimer = setTimeout(() => {
20418
+ catalogTimer = void 0;
20419
+ publishCatalog(executionContext);
20420
+ }, CATALOG_PUBLISH_THROTTLE_MS);
20421
+ catalogTimer.unref?.();
20422
+ };
20333
20423
  const sessionService = serverHost.context.sessionService;
20334
20424
  const featureOptions = {
20335
20425
  identityWorkspaceId: serverHost.context.workspaceId,
@@ -20457,7 +20547,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20457
20547
  [require_workflowServices.WORKFLOW_LAUNCHER_SESSION_ENV]: source
20458
20548
  } }
20459
20549
  };
20460
- if (input.env?.[PUBLIC_LAUNCH_ENV] === PUBLIC_LAUNCH_ENABLED) {
20550
+ if (!input.dryRun && hostOptions.authorizeRegistration || input.env?.[PUBLIC_LAUNCH_ENV] === PUBLIC_LAUNCH_ENABLED) {
20461
20551
  const registration = await launcher.launchRegistered(resolved, hostOptions);
20462
20552
  if (disposed) throw new Error(RUNTIME_DISPOSED_MESSAGE);
20463
20553
  return {
@@ -20568,7 +20658,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20568
20658
  * A role-bound launch is admitted with its explicit allocation before it runs, so its answer is the
20569
20659
  * admission's. Undefined for any other launch, which runs directly.
20570
20660
  */
20571
- const admitRoleBound = async (parameters, where) => {
20661
+ const admitRoleBound = async (parameters, where, hostOptions) => {
20572
20662
  let input;
20573
20663
  let workflowPath;
20574
20664
  try {
@@ -20578,6 +20668,7 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20578
20668
  } catch {
20579
20669
  return;
20580
20670
  }
20671
+ if (hostOptions?.authorizeRegistration) return textResult("A pinned profile workflow cannot transfer launch authority to another session.", true);
20581
20672
  const active = launcher.activeRunCount();
20582
20673
  const ceiling = resolveMaxConcurrent(host.context.environment);
20583
20674
  if (active >= ceiling) return textResult(`Error: This session is at capacity: ${String(active)}/${String(ceiling)} workflows running.`, true);
@@ -20604,18 +20695,31 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
20604
20695
  * both still run in the session that owns them, never in one created for the run.
20605
20696
  */
20606
20697
  const launch = async (parameters, where, hostOptions) => {
20698
+ if (runtime.workflowHost.durable?.registerLaunchAuthority && !hostOptions?.authorizeRegistration) return textResult("A pinned profile workflow requires a verified enabling member.", true);
20607
20699
  const owner = launchOwner();
20608
- if (owner !== void 0) return launchIn(owner, parameters);
20609
- return (canHandOff() ? await admitRoleBound(parameters, where ?? host.context) : void 0) ?? launchHere(parameters, where, hostOptions);
20700
+ if (owner !== void 0) return hostOptions?.authorizeRegistration ? textResult("A pinned profile workflow cannot transfer launch authority to another session.", true) : launchIn(owner, parameters);
20701
+ return (canHandOff() ? await admitRoleBound(parameters, where ?? host.context, hostOptions) : void 0) ?? launchHere(parameters, where, hostOptions);
20610
20702
  };
20611
20703
  /**
20612
20704
  * A launch another session handed this one. A hand-off from a launcher
20613
20705
  * carries its stamp and runs here; any other, such as a dispatcher's, goes
20614
20706
  * through the same routing as a launch made here.
20615
20707
  */
20616
- const launchFromApi = async (parameters) => {
20708
+ const launchFromApi = async (parameters, enablingMember) => {
20709
+ const durable = runtime.workflowHost.durable;
20710
+ const register = durable?.registerLaunchAuthority?.bind(durable);
20711
+ if (register && !enablingMember) return {
20712
+ text: "A pinned profile workflow requires a verified enabling member.",
20713
+ isError: true
20714
+ };
20715
+ const hostOptions = register && enablingMember ? { authorizeRegistration: (runId, fingerprint) => register(runId, host.context.sessionId, enablingMember, fingerprint) } : void 0;
20617
20716
  const env = parameters.env;
20618
- const result = typeof env === "object" && env !== null && typeof env["PO_WORKFLOW_LAUNCHER_SESSION_ID"] === "string" ? await launchHere(parameters) : await launch(parameters);
20717
+ const handedOff = typeof env === "object" && env !== null && typeof env["PO_WORKFLOW_LAUNCHER_SESSION_ID"] === "string";
20718
+ if (handedOff && register) return {
20719
+ text: "A pinned profile workflow cannot transfer launch authority to another session.",
20720
+ isError: true
20721
+ };
20722
+ const result = handedOff ? await launchHere(parameters, void 0, hostOptions) : await launch(parameters, void 0, hostOptions);
20619
20723
  publishRunsSoon(host.context);
20620
20724
  return {
20621
20725
  text: result.content.map((item) => item.text).join("\n"),
@@ -21075,9 +21179,9 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
21075
21179
  reportFailure: reportLifecycleFailure
21076
21180
  });
21077
21181
  return {
21078
- api: [createWorkflowApi(runtime, async (parameters) => {
21182
+ api: [createWorkflowApi(runtime, async (parameters, enablingMember) => {
21079
21183
  await waitForReadiness();
21080
- return launchFromApi(parameters);
21184
+ return launchFromApi(parameters, enablingMember);
21081
21185
  }, async (sessionId) => {
21082
21186
  const root = await artifactStorage?.rootForSession(sessionId, environment);
21083
21187
  return root === void 0 ? void 0 : (0, node_path.join)(root, "workflow");
@@ -21350,7 +21454,9 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
21350
21454
  description: "Publish workflow runs and catalog updates and deliver completions after tool execution.",
21351
21455
  event: "tool_execution_end",
21352
21456
  handle: async (_event, executionContext) => {
21353
- await publishLifecycle(executionContext);
21457
+ await publishRuns(executionContext);
21458
+ await deliverCompletions();
21459
+ publishCatalogSoon(executionContext);
21354
21460
  }
21355
21461
  }),
21356
21462
  (0, _agimon_ai_po_core_extensionFile.defineHook)({
@@ -21601,6 +21707,8 @@ function createWorkflowServerRuntime(host, serverHost, runtime, resolveSecrets,
21601
21707
  if (runsTimer !== void 0) clearTimeout(runsTimer);
21602
21708
  runsTimer = void 0;
21603
21709
  runsAfter = void 0;
21710
+ if (catalogTimer !== void 0) clearTimeout(catalogTimer);
21711
+ catalogTimer = void 0;
21604
21712
  },
21605
21713
  ...[...launchers.values()].map((owned) => () => owned.dispose()),
21606
21714
  () => {