agents-relay 2.0.251 → 2.0.253

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.
@@ -1,23 +1,29 @@
1
- /**
2
- * One active execution per Job, irrespective of adapter or current reconciler.
3
- * A claimed QUEUED execution also occupies the slot; synchronous P0/self work
4
- * occupies it by its RUNNING state even though it has no execution UUID.
5
- */
1
+ /** A Coordinator is a durable Task but does not occupy a Worker execution slot.
2
+ * Legacy delegated Shortcut Workers preserve their original foreground semantics. */
3
+ function occupiesSlot(job, task) {
4
+ if (task.agentGraph && task.result?.data?.dag?.version === 1)
5
+ return false;
6
+ const shortcut = task.result?.data?.shortcut;
7
+ const delegatedWorker = job.executionMode === 'shortcut' && job.contentOnly === true && task.state === 'RUNNING'
8
+ && shortcut && typeof shortcut === 'object'
9
+ && Object.keys(shortcut.workerNodes ?? {}).length > 0;
10
+ const durableWait = job.executionMode === 'shortcut' && job.contentOnly === true && task.state === 'RUNNING'
11
+ && task.leaseOwner === null && shortcut && typeof shortcut === 'object'
12
+ && Object.keys(shortcut.waits ?? {}).length > 0;
13
+ return task.state !== 'AWAITING_DECISION' && !durableWait && !delegatedWorker &&
14
+ (task.state === 'RUNNING' || (task.executionId !== null && !['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state)));
15
+ }
16
+ function plannerOccupies(job, planId) {
17
+ return (job.plans ?? []).some(plan => plan.id !== planId && plan.executionId !== null && plan.status === 'PLANNING');
18
+ }
6
19
  export function jobHasActiveExecution(job, except = {}) {
7
- const worker = job.tasks.some(task => {
8
- if (task.id === except.taskId)
9
- return false;
10
- const shortcut = task.result?.data?.shortcut;
11
- const delegatedWorker = job.executionMode === 'shortcut' && job.contentOnly === true && task.state === 'RUNNING'
12
- && task.result?.data?.shortcut && typeof task.result.data.shortcut === 'object'
13
- && Object.keys(task.result.data.shortcut.workerNodes ?? {}).length > 0;
14
- const durableWait = job.executionMode === 'shortcut' && job.contentOnly === true && task.state === 'RUNNING'
15
- && task.leaseOwner === null && shortcut && typeof shortcut === 'object'
16
- && shortcut.waits
17
- && Object.keys(shortcut.waits).length > 0;
18
- return task.state !== 'AWAITING_DECISION' && !durableWait && !delegatedWorker && (task.state === 'RUNNING' || (task.executionId !== null && !['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state)));
19
- });
20
- const planner = (job.plans ?? []).some(plan => plan.id !== except.planId
21
- && plan.executionId !== null && plan.status === 'PLANNING');
22
- return worker || planner;
20
+ return job.tasks.some(task => task.id !== except.taskId && occupiesSlot(job, task)) || plannerOccupies(job, except.planId);
21
+ }
22
+ /** Only sibling DAG Tasks may execute concurrently; unrelated Tasks retain
23
+ * the existing one-active-execution-per-Job safety boundary. */
24
+ export function jobHasConflictingExecution(job, candidate) {
25
+ if (!candidate.dagNode)
26
+ return jobHasActiveExecution(job, { taskId: candidate.id });
27
+ return plannerOccupies(job) || job.tasks.some(task => task.id !== candidate.id && occupiesSlot(job, task) &&
28
+ task.dagNode?.parentTaskId !== candidate.dagNode?.parentTaskId);
23
29
  }
package/dist/pool.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { unifiedDAG } from './dag-task-runtime.js';
1
2
  import { listManagedGitHubJobs } from './store.js';
2
3
  import { eventFor } from './events.js';
3
4
  import { ReconcileCoordinator } from './reconcile-coordinator.js';
@@ -41,6 +42,8 @@ export function needsLifecycleReconciliation(job, now = Date.now()) {
41
42
  if (review.accepted && review.actions.some(action => action.id === 'review.create'))
42
43
  return true;
43
44
  }
45
+ if (job.tasks.some(task => unifiedDAG(job, task) && task.state === 'RUNNING'))
46
+ return true;
44
47
  if (job.tasks.some(task => (task.state === 'QUEUED' && task.executionId === null)
45
48
  || (task.state === 'RUNNING' && task.adapter === 'orchestrator' && task.executionId === null)
46
49
  || (task.state === 'DRAFT' && task.dependencies.length > 0)))
@@ -153,7 +156,7 @@ export class RepositoryWorkerPool {
153
156
  const outcome = await reconciler.applyEvent(signal.event);
154
157
  // The decision is durably applied before invoking the Shortcut CLI hook.
155
158
  // A replay can also wake a still-QUEUED Task without a new decision.
156
- if (signal.event.type === 'task.interactive_decision' &&
159
+ if (signal.event.type === 'task.interactive_decision' && !target.job.tasks.some(t => unifiedDAG(target.job, t)) &&
157
160
  ['task.interactive_decision.accepted', 'task.interactive_decision.duplicate'].includes(outcome.reason) &&
158
161
  await this.onShortcutDecision?.(jobId, signal.event.task_id))
159
162
  continue;
@@ -168,8 +171,8 @@ export class RepositoryWorkerPool {
168
171
  for (const job of jobs) {
169
172
  if (capacity <= 0)
170
173
  break;
171
- // Shortcut starts and review resumes are external CLI invocations, not normal Task dispatch.
172
- if (job.executionMode === 'shortcut')
174
+ // Legacy in-flight Shortcut Jobs retain their original foreground owner.
175
+ if (job.executionMode === 'shortcut' && !job.tasks.some(t => unifiedDAG(job, t)))
173
176
  continue;
174
177
  const store = await this.requireLocalStore(job.id);
175
178
  await store.hydrate?.(job);
@@ -1,3 +1,4 @@
1
+ import { dagCompletionError } from './dag-result-contract.js';
1
2
  import { dependencyRevisionStillCurrent } from './dependency-revision-execution.js';
2
3
  import { isFinalReviewAgent } from './final-review-role.js';
3
4
  import { handleWorkerLaunchFailure } from './worker-failure-recovery.js';
@@ -73,7 +74,7 @@ export class ReconcilerRuntimeBase {
73
74
  });
74
75
  }
75
76
  async applyHostInvocationEvent(event) { const result = await this.hostInvocations.applyEvent(event); const resumed = result.resumeWorker && result.decision ? await resumeInteractiveTask(this.store, result.decision.jobId, result.decision.taskId, result.decision.invocationId, result.decision.revision, result.decision.decision) : false; return { applied: result.outcome !== 'ignored', reconcile: resumed || result.outcome === 'accepted', reason: `task.interactive_decision.${result.outcome}` }; }
76
- bindInteractiveInvocation(jobId, task, executionId, invocationId, revision) { return this.hostInvocations.bind(jobId, task, executionId, invocationId, revision); }
77
+ bindInteractiveInvocation(jobId, task, executionId) { return this.hostInvocations.bind(jobId, task, executionId); }
77
78
  async applyJobEffectOutcomes(job, outcomes) {
78
79
  await applyJobEffectOutcomes(this.store, event => this.emit(event), job, outcomes);
79
80
  }
@@ -92,6 +93,13 @@ export class ReconcilerRuntimeBase {
92
93
  if (event.type === 'task.completed') {
93
94
  const latest = await this.store.load(event.job_id);
94
95
  const task = latest.tasks.find(item => item.id === event.task_id);
96
+ if (task?.dagNode) {
97
+ const projectPath = this.options.projectPathForJob ? await this.options.projectPathForJob(latest, task) : undefined;
98
+ const invalid = await dagCompletionError(task, projectPath);
99
+ if (invalid)
100
+ return this.applyTerminalEvent({ ...event, type: 'task.failed',
101
+ message: invalid, data: { ...event.data, reason: 'invalid_dag_result' } });
102
+ }
95
103
  // Source generation still goes through canonical Task terminal
96
104
  // correlation; convert stale verification into a safe supersede event.
97
105
  if (task?.revision && task.revision.kind !== 'targeted' && !dependencyRevisionStillCurrent(latest, task)) {
@@ -246,7 +254,7 @@ export class ReconcilerRuntimeBase {
246
254
  return true;
247
255
  const sourceId = eventSourceId(event);
248
256
  const expected = executionEventSource(jobId, task.id, task.executionId);
249
- if ((['codex', 'chatgpt', 'z'].includes(task.adapter)) && sourceId !== expected)
257
+ if ((['codex', 'chatgpt', 'z', 'script'].includes(task.adapter)) && sourceId !== expected)
250
258
  return false;
251
259
  if (afterCommit)
252
260
  claimTerminalExecution(expected);
@@ -403,7 +411,7 @@ export class ReconcilerRuntimeBase {
403
411
  const lifecycleEvent = event.type;
404
412
  const transition = await withExecutionBoundary(event.job_id, event.task_id, () => this.taskTransitions.apply(event.job_id, event.task_id, lifecycleEvent, {
405
413
  eligible: (_job, task) => {
406
- if (!['codex', 'chatgpt', 'z', 'orchestrator'].includes(task.adapter))
414
+ if (!['codex', 'chatgpt', 'z', 'script', 'orchestrator'].includes(task.adapter))
407
415
  return false;
408
416
  if (event.type === 'task.blocked' && (!trustedInternal || task.agentName !== 'troubleshooter'))
409
417
  return false;
@@ -416,7 +424,7 @@ export class ReconcilerRuntimeBase {
416
424
  return false;
417
425
  if (event.type === 'task.completed' && task.interactiveInvocation?.status !== undefined && task.interactiveInvocation.status !== 'approved')
418
426
  return false; // current interactive revision requires durable approval
419
- const modelBacked = ['codex', 'chatgpt', 'z'].includes(task.adapter);
427
+ const modelBacked = ['codex', 'chatgpt', 'z', 'script'].includes(task.adapter);
420
428
  if (!trustedInternal && modelBacked && !isCorrelatedWorkerEvent(task, event)) {
421
429
  const eventExecutionId = executionIdFromSource(eventSourceId(event), _job.id, task.id);
422
430
  const prior = eventExecutionId ? task.executionHistory?.find(item => item.id === eventExecutionId) : undefined;
@@ -432,7 +440,7 @@ export class ReconcilerRuntimeBase {
432
440
  return { recoverableExecution: isRecoverableWatchdogFailure(task) && freshEnough, awaitingInteractiveDecision: lifecycleEvent === 'task.interactive_waiting' && task.interactiveInvocation?.status === 'awaiting_decision' };
433
441
  },
434
442
  mutate: (job, task) => {
435
- const modelBacked = ['codex', 'chatgpt', 'z'].includes(task.adapter);
443
+ const modelBacked = ['codex', 'chatgpt', 'z', 'script'].includes(task.adapter);
436
444
  const acceptedExecutionId = task.executionId;
437
445
  const eventExecutionId = executionIdFromSource(eventSourceId(event), job.id, task.id);
438
446
  const terminalExecutionId = eventExecutionId ?? acceptedExecutionId;
@@ -29,7 +29,7 @@ import { CallbackWorkflowEffectHandler } from './workflow/effects.js';
29
29
  import { exhaustedTroubleshooterRecoveries, pendingTroubleshooterTasks, pendingTroubleshooterReopens, pendingTroubleshooterRetries, refreshTroubleshooterInput } from './troubleshooter.js';
30
30
  import { fallbackFailedTroubleshooters, escalateExhaustedTroubleshooters } from './troubleshooter-fallback.js';
31
31
  import { cleanupMergedJobWorktree } from './job-worktree-cleanup.js';
32
- import { jobHasActiveExecution } from './job-execution-slot.js';
32
+ import { jobHasConflictingExecution } from './job-execution-slot.js';
33
33
  import { requiresWorkerInactivityWatchdog } from './task-inactivity-watchdog.js';
34
34
  import { managedWorkerInput } from './managed-worker-input.js';
35
35
  import { launchShortcutEffect, resumeShortcutEffect, resumeShortcutEventWaits } from './reconciler-shortcut.js';
@@ -42,6 +42,8 @@ import { repairLegacyOrchestrators } from './legacy-orchestrator-repair.js';
42
42
  import { launchPlanExecution } from './planner-runtime.js';
43
43
  import { classifyFailure, errorMessage, observability, withObservabilityCorrelation } from './observability.js';
44
44
  import { recoverInteractiveDecisions } from './interactive-resume.js';
45
+ import { reconcileDAGSchedule, unifiedDAG } from './dag-task-runtime.js';
46
+ import { ScriptTaskAdapter } from './script-task-adapter.js';
45
47
  const PRIORITY_RANK = { P0: 0, P1: 1, P2: 2, P3: 3 };
46
48
  export function compareTaskPriority(a, b, jobPriority = 'P2') { const ar = PRIORITY_RANK[a.priority ?? jobPriority]; const br = PRIORITY_RANK[b.priority ?? jobPriority]; return ar - br || a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id); }
47
49
  export class Reconciler extends ReconcilerReviewBase {
@@ -62,9 +64,7 @@ export class Reconciler extends ReconcilerReviewBase {
62
64
  }
63
65
  async dispatchExecutableTasks(jobId) {
64
66
  const scheduled = refreshTaskDependencies(await this.store.load(jobId));
65
- // Ordinary daemon/queue never owns Shortcut Jobs, including recovery Tasks.
66
- // Only the explicit foreground runner may use existing Worker Adapters.
67
- if (scheduled.executionMode === 'shortcut' && !this.options.shortcutRunnerOwner)
67
+ if (scheduled.executionMode === 'shortcut' && !scheduled.tasks.some(t => unifiedDAG(scheduled, t)) && !this.options.shortcutRunnerOwner)
68
68
  return scheduled;
69
69
  if (scheduled.pause)
70
70
  return scheduled;
@@ -72,17 +72,15 @@ export class Reconciler extends ReconcilerReviewBase {
72
72
  this.detach(this.deliverContinuation(scheduled, task), scheduled.id, task.id, 'continuation');
73
73
  }
74
74
  const capacity = Math.max(0, (this.options.maxConcurrent ?? 4) - this.live.size - this.plannerLive.size);
75
- const dispatchable = (jobHasActiveExecution(scheduled) ? [] : scheduled.tasks)
76
- .filter(task => revisionRequestReady(scheduled, task) && task.state === 'QUEUED'
77
- && task.executionId === null
78
- && task.kind !== 'planner'
79
- && task.adapter !== 'orchestrator'
80
- && dependencyReady(task, new Map(scheduled.tasks.map(item => [item.id, item]))))
81
- .sort((a, b) => compareTaskPriority(a, b, scheduled.priority ?? 'P2'))
82
- .slice(0, Math.min(capacity, 1));
75
+ const ready = scheduled.tasks.filter(task => !unifiedDAG(scheduled, task) && revisionRequestReady(scheduled, task) &&
76
+ task.state === 'QUEUED' && task.executionId === null && task.kind !== 'planner' && task.adapter !== 'orchestrator' &&
77
+ dependencyReady(task, new Map(scheduled.tasks.map(item => [item.id, item]))) && !jobHasConflictingExecution(scheduled, task))
78
+ .sort((a, b) => compareTaskPriority(a, b, scheduled.priority ?? 'P2'));
79
+ const firstDAG = ready[0]?.dagNode?.parentTaskId;
80
+ const dispatchable = (firstDAG ? ready.filter(t => t.dagNode?.parentTaskId === firstDAG) : ready.slice(0, 1)).slice(0, capacity);
83
81
  for (const task of dispatchable) {
84
82
  const shortcut = task.result?.data?.shortcut;
85
- await transitionTaskEvent(task, 'dispatch', { dispatchable: true, shortcutExecution: scheduled.executionMode === 'shortcut' && scheduled.contentOnly === true && shortcut?.workerFallback !== true && Boolean(task.agentGraph), shortcutFallback: shortcut?.workerFallback === true, shortcutHasGraph: Boolean(task.agentGraph) }, async (actionId) => {
83
+ await transitionTaskEvent(task, 'dispatch', { dispatchable: true, shortcutExecution: scheduled.executionMode === 'shortcut' && scheduled.contentOnly === true && shortcut?.workerFallback !== true && Boolean(task.agentGraph) && !unifiedDAG(scheduled, task), shortcutFallback: shortcut?.workerFallback === true, shortcutHasGraph: Boolean(task.agentGraph) }, async (actionId) => {
86
84
  const outcomes = await this.workflowEffects.execute([actionId], { jobId: scheduled.id, taskId: task.id, transitionKey: `dispatch:${task.attempt}`, data: { attempt: task.attempt, ...(task.interactiveInvocation?.decidedAt ? { reviewInvocationId: task.interactiveInvocation.invocationId } : {}) } });
87
85
  await this.applyTaskEffectOutcomes(scheduled, task, outcomes);
88
86
  }, async () => { await this.store.saveTask(task); });
@@ -97,7 +95,7 @@ export class Reconciler extends ReconcilerReviewBase {
97
95
  let job = await this.store.load(jobId);
98
96
  // The same durable Job flag covers children, retries, and Troubleshooters.
99
97
  // Do not let a background Reconciler mutate or dispatch any of them.
100
- if (job.executionMode === 'shortcut' && !this.options.shortcutRunnerOwner)
98
+ if (job.executionMode === 'shortcut' && !job.tasks.some(t => unifiedDAG(job, t)) && !this.options.shortcutRunnerOwner)
101
99
  return job;
102
100
  await drainProductionWorkflowOutbox(this.store, this.options);
103
101
  await deliverPendingEscalations(this.store, jobId, this.options.escalationNotifier);
@@ -206,6 +204,7 @@ export class Reconciler extends ReconcilerReviewBase {
206
204
  scheduled = refreshTaskDependencies(await this.store.load(jobId));
207
205
  }
208
206
  scheduled = refreshTaskDependencies(await this.maybeCreatePlanner(scheduled));
207
+ scheduled = refreshTaskDependencies(await reconcileDAGSchedule({ store: this.store, jobId, job: scheduled, projectPathForTask: async (j, t) => j.shortcutRunnerContext?.projectPath ?? (this.options.projectPathForJob ? this.options.projectPathForJob(j, t) : t.routing?.cwd ?? process.cwd()), roots: this.options.executionContextRoots }));
209
208
  if (scheduled.state !== previousState || scheduled.updatedAt !== job.updatedAt)
210
209
  await this.store.saveJob(scheduled);
211
210
  scheduled = await this.dispatchExecutableTasks(jobId);
@@ -286,11 +285,11 @@ export class Reconciler extends ReconcilerReviewBase {
286
285
  emitFailed: async (task, reason) => { await this.emit(eventFor(job.id, task.id, task.parentTaskId, 'task.failed', 'failed', task.error ?? reason, 'user', { reason })); },
287
286
  };
288
287
  }
289
- async recoverLostExecutions(job, now) { if (job.executionMode !== 'shortcut' || this.options.shortcutRunnerOwner)
288
+ async recoverLostExecutions(job, now) { if (job.executionMode !== 'shortcut' || job.tasks.some(t => unifiedDAG(job, t)) || this.options.shortcutRunnerOwner)
290
289
  await recoverExpiredExecutions(job, now, this.executionRecoveryPorts(job)); }
291
290
  async recoverStartupOrphans(jobId) {
292
291
  const job = await this.store.load(jobId);
293
- if (job.state === 'ACTIVE' && (job.executionMode !== 'shortcut' || this.options.shortcutRunnerOwner === true)) {
292
+ if (job.state === 'ACTIVE' && (job.executionMode !== 'shortcut' || job.tasks.some(t => unifiedDAG(job, t)) || this.options.shortcutRunnerOwner === true)) {
294
293
  await recoverStartupExecutionOrphans(job, this.executionRecoveryPorts(job));
295
294
  }
296
295
  return this.store.load(jobId);
@@ -366,12 +365,12 @@ export class Reconciler extends ReconcilerReviewBase {
366
365
  return;
367
366
  if (freshTask.executionId !== null)
368
367
  return;
369
- if (jobHasActiveExecution(freshJob, { taskId: freshTask.id }))
368
+ if (jobHasConflictingExecution(freshJob, freshTask))
370
369
  return;
371
370
  if (isFinalReviewAgent(freshTask.agentName) && freshTask.planningDecisionId && freshTask.dependencies.length)
372
371
  await bindPlannedReviewHead(this.store, freshTask, await this.currentHeadSha(freshJob));
373
372
  const implementationThread = resolveImplementationTaskThreadDestination(freshJob, freshTask);
374
- if ((!freshTask.routing || ((implementationThread || (isFinalReviewAgent(freshTask.agentName) && resolveReviewerThreadDestination(freshJob, this.options.reviewer?.threadId))) && freshTask.adapter !== 'chatgpt')) && freshTask.adapter !== 'orchestrator') {
373
+ if (freshTask.adapter !== 'script' && (!freshTask.routing || ((implementationThread || (isFinalReviewAgent(freshTask.agentName) && resolveReviewerThreadDestination(freshJob, this.options.reviewer?.threadId))) && freshTask.adapter !== 'chatgpt')) && freshTask.adapter !== 'orchestrator') {
375
374
  const routed = await this.routeTaskForExecutionFailClosed(freshJob, freshTask);
376
375
  if (!routed)
377
376
  return;
@@ -456,7 +455,7 @@ export class Reconciler extends ReconcilerReviewBase {
456
455
  if (!reserved)
457
456
  throw new Error('already reserved launch attempt: reconcile existing generation');
458
457
  }
459
- const adapter = this.options.adapters.find(x => x.name === task.adapter);
458
+ const adapter = task.adapter === 'script' ? new ScriptTaskAdapter(event => this.options.eventBus ? this.emit(event) : this.handleEvent(event), this.options.executionContextRoots) : this.options.adapters.find(x => x.name === task.adapter);
460
459
  if (!adapter) {
461
460
  await this.failLaunch(job.id, task.id, task.executionId, 'No adapter ' + task.adapter);
462
461
  return;
@@ -464,7 +463,7 @@ export class Reconciler extends ReconcilerReviewBase {
464
463
  let executionContext;
465
464
  try {
466
465
  const role = isFinalReviewAgent(task.agentName) ? 'reviewer' : task.agentName === 'troubleshooter' ? 'troubleshooter' : task.parentTaskId ? 'nested-worker' : 'worker';
467
- const projectPath = this.options.projectPathForJob ? await this.options.projectPathForJob(job, task) : task.routing?.cwd ?? process.cwd();
466
+ const projectPath = task.dagNode && job.shortcutRunnerContext?.projectPath ? job.shortcutRunnerContext.projectPath : this.options.projectPathForJob ? await this.options.projectPathForJob(job, task) : task.routing?.cwd ?? process.cwd();
468
467
  executionContext = await this.resolvedContext(job, task, role, projectPath);
469
468
  }
470
469
  catch (error) {
@@ -478,7 +477,7 @@ export class Reconciler extends ReconcilerReviewBase {
478
477
  const sourceId = executionEventSource(job.id, task.id, durableExecutionId);
479
478
  let baseWorkerInput;
480
479
  try {
481
- baseWorkerInput = await managedWorkerInput(job, task, executionContext);
480
+ baseWorkerInput = task.adapter === 'script' ? task.input : await managedWorkerInput(job, task, executionContext);
482
481
  }
483
482
  catch (error) {
484
483
  await this.failLaunch(job.id, task.id, task.executionId, `Execution contract unavailable: ${error instanceof Error ? error.message : String(error)}`);
@@ -1,5 +1,5 @@
1
1
  import { submitTargetedRevisionRequest } from './review-revision-model.js';
2
- import { beginInteractiveReview, abortInteractiveReview, readyInteractiveReview, failInteractiveReview, interactiveWaitingEvent } from './interactive-request.js';
2
+ import { beginInteractiveReview, abortInteractiveReview, failInteractiveReview, interactiveWaitingEvent } from './interactive-request.js';
3
3
  import { localSourceHead, localWorkingHead } from './local-git-merge.js';
4
4
  import { appendTaskComment } from './task-comments.js';
5
5
  import { InMemoryStore } from './store.js';
@@ -81,23 +81,20 @@ export function createWorkspaceControl(deps) {
81
81
  if (command.startsWith('review.interactive.')) {
82
82
  const taskId = typeof body.taskId === 'string' ? body.taskId : '';
83
83
  const executionId = typeof body.executionId === 'string' ? body.executionId : '';
84
- const invocationId = typeof body.invocationId === 'string' ? body.invocationId : '';
85
84
  if (!taskId || !executionId)
86
85
  throw new Error('Interactive review requires taskId and executionId');
87
86
  if (command === 'review.interactive.begin')
88
87
  return await beginInteractiveReview(store, jobId, taskId, executionId);
89
- if (!invocationId)
90
- throw new Error('Interactive review requires invocationId');
91
88
  if (command === 'review.interactive.abort') {
92
- await abortInteractiveReview(store, jobId, taskId, executionId, invocationId);
89
+ await abortInteractiveReview(store, jobId, taskId, executionId);
93
90
  return { aborted: true };
94
91
  }
95
92
  if (command === 'review.interactive.wait') {
96
93
  const current = (await store.load(jobId)).tasks.find((t) => t.id === taskId);
97
- if (current?.state === 'AWAITING_DECISION' && current.interactiveInvocation?.invocationId === invocationId)
94
+ if (current?.state === 'AWAITING_DECISION' && current.interactiveInvocation?.executionId === executionId)
98
95
  return { waiting: true, taskState: 'AWAITING_DECISION' };
99
96
  if (current?.state !== 'RUNNING' || current.executionId !== executionId ||
100
- current.interactiveInvocation?.invocationId !== invocationId)
97
+ current.interactiveInvocation?.executionId !== executionId)
101
98
  throw new Error('Stale interactive waiting request');
102
99
  const reconciler = makeReconciler(store, concurrency);
103
100
  const event = interactiveWaitingEvent(jobId, taskId, current.parentTaskId, executionId);
@@ -119,10 +116,8 @@ export function createWorkspaceControl(deps) {
119
116
  await reconciler.close();
120
117
  }
121
118
  }
122
- if (command === 'review.interactive.ready')
123
- return await readyInteractiveReview(store, jobId, taskId, executionId, invocationId, typeof body.revision === 'string' ? body.revision : '');
124
119
  if (command === 'review.interactive.fail') {
125
- const result = await failInteractiveReview(store, jobId, taskId, executionId, invocationId, typeof body.reason === 'string' ? body.reason : 'Interactive review failed');
120
+ const result = await failInteractiveReview(store, jobId, taskId, executionId, typeof body.reason === 'string' ? body.reason : 'Interactive review failed');
126
121
  if (result.requeued)
127
122
  await pool.reconcileLocalJob(jobId, 'interactive.preview-failed');
128
123
  return result;
@@ -0,0 +1,118 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { once } from 'node:events';
3
+ import { dirname, isAbsolute } from 'node:path';
4
+ import { mkdir, writeFile } from 'node:fs/promises';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { eventFor } from './events.js';
7
+ import { executionEventSource } from './execution-event-identity.js';
8
+ import { discoverShortcut } from './agent-shortcut.js';
9
+ import { spawnOwnedProcess } from './owned-process.js';
10
+ const valid = (value) => {
11
+ if (!value || typeof value !== 'object' || Array.isArray(value))
12
+ return false;
13
+ const r = value;
14
+ return r.status === 'COMPLETED' && !!r.output && typeof r.output === 'object' && !Array.isArray(r.output)
15
+ && (!!r.artifacts && typeof r.artifacts === 'object');
16
+ };
17
+ async function runCommand(args, cwd, signal) {
18
+ if (!args.length || args.some(a => typeof a !== 'string' || !a))
19
+ throw Error('Script command requires an argv vector');
20
+ const child = spawnOwnedProcess(args[0], args.slice(1), { invocation: 'dag.script-command', signal, spawn: { cwd, stdio: ['ignore', 'pipe', 'pipe'] } });
21
+ let stdout = '', stderr = '';
22
+ child.stdout?.on('data', c => { stdout += String(c); });
23
+ child.stderr?.on('data', c => { stderr += String(c); });
24
+ const [code] = await once(child, 'close');
25
+ return { stdout, stderr, code: code ?? -1 };
26
+ }
27
+ /** Script is just another Task Worker Adapter. It publishes exactly the same
28
+ * execution-scoped Task lifecycle events as a Model Worker. */
29
+ export class ScriptTaskAdapter {
30
+ onEvent;
31
+ roots;
32
+ name = 'script';
33
+ id = 'script';
34
+ capabilities = ['script'];
35
+ constructor(onEvent, roots = {}) {
36
+ this.onEvent = onEvent;
37
+ this.roots = roots;
38
+ }
39
+ launch(task, signal, context = {}) {
40
+ const dag = task.dagNode;
41
+ if ((dag && dag.executor !== 'script') || !task.executionId || !task.jobId || !task.agentName)
42
+ throw Error('Script Adapter requires a leased Agent Task');
43
+ if (task.output?.kind !== 'file' || !isAbsolute(task.output.path))
44
+ throw Error('Script Task requires absolute file output');
45
+ const outputPath = task.output.path;
46
+ const executionId = task.executionId;
47
+ const executionAbort = new AbortController();
48
+ const forwardAbort = () => executionAbort.abort(signal.reason ?? new Error('Script Task cancelled'));
49
+ if (signal.aborted)
50
+ forwardAbort();
51
+ else
52
+ signal.addEventListener('abort', forwardAbort, { once: true });
53
+ const source = { id: executionEventSource(task.jobId, task.id, executionId), agent: task.agentName, component: 'agents-relay' };
54
+ const send = async (type, status, message, data = {}) => {
55
+ await this.onEvent(eventFor(task.jobId, task.id, task.parentTaskId, type, status, message, 'orchestrator', data, source));
56
+ };
57
+ const promise = (async () => {
58
+ let stage = 'running';
59
+ try {
60
+ let input;
61
+ if (dag) {
62
+ input = JSON.parse(task.input);
63
+ if (input.source !== 'relay-dag-task' || input.nodeId !== dag.nodeId || input.taskId && input.taskId !== task.id)
64
+ throw Error('Script Task is not bound to its declared DAG node');
65
+ }
66
+ else {
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(task.input);
70
+ }
71
+ catch { }
72
+ input = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : { taskInput: task.input };
73
+ input = { ...input, source: 'relay-agent-task', taskId: task.id, outputPath };
74
+ }
75
+ const projectPath = context.executionContext?.project.path ?? input.projectPath;
76
+ if (typeof projectPath !== 'string' || !isAbsolute(projectPath))
77
+ throw Error('No trusted Script Project context');
78
+ const script = await discoverShortcut(task.agentName, projectPath, this.roots.sharedRoot ?? undefined, this.roots.workspaceRoot ?? undefined, this.roots.globalRoot ?? undefined);
79
+ if (!script)
80
+ throw Error(`Declared Agent Shortcut is unavailable: ${task.agentName}`);
81
+ await send('task.started', 'running', 'Script Worker started');
82
+ const module = await import(pathToFileURL(script).href);
83
+ if (typeof module.run !== 'function')
84
+ throw Error('Agent Shortcut must export run(context)');
85
+ const invocation = task.interactiveInvocation;
86
+ const review = invocation?.decidedAt && ['approved', 'changes_requested'].includes(invocation.status)
87
+ ? { status: invocation.status, revision: invocation.revision, invocationId: invocation.invocationId, feedback: invocation.feedback, comments: invocation.comments } : undefined;
88
+ if (executionAbort.signal.aborted)
89
+ throw executionAbort.signal.reason;
90
+ const result = await Promise.race([module.run({ input: { ...input, jobId: task.jobId, taskId: task.id, executionId,
91
+ ...(review ? { reviewDecision: review } : {}) }, signal,
92
+ runCommand: (args, cwd) => runCommand(args, cwd, executionAbort.signal) }), new Promise((_resolve, reject) => {
93
+ if (executionAbort.signal.aborted)
94
+ reject(executionAbort.signal.reason);
95
+ else
96
+ executionAbort.signal.addEventListener('abort', () => reject(executionAbort.signal.reason), { once: true });
97
+ })]);
98
+ if (result && typeof result === 'object' && result.status === 'WAITING_REVIEW') {
99
+ stage = 'waiting';
100
+ return { summary: 'Script Task waiting for authorized human review' };
101
+ }
102
+ if (!valid(result))
103
+ throw Error('Script Worker did not return a completed artifact contract');
104
+ await mkdir(dirname(outputPath), { recursive: true, mode: 0o700 });
105
+ await writeFile(outputPath, JSON.stringify(result, null, 2) + '\n');
106
+ await send('task.completed', 'succeeded', 'Script Worker completed', { status: 'COMPLETED', output: result.output, artifacts: result.artifacts });
107
+ stage = 'completed';
108
+ return { summary: 'Script Task completed' };
109
+ }
110
+ catch (error) {
111
+ if (!executionAbort.signal.aborted && stage === 'running')
112
+ await send('task.failed', 'failed', error instanceof Error ? error.message : String(error), { reason: 'script_execution_failed' });
113
+ throw error;
114
+ }
115
+ })().finally(() => signal.removeEventListener('abort', forwardAbort));
116
+ return { id: randomUUID(), promise, cancel: () => executionAbort.abort(new Error('Script Task cancelled')) };
117
+ }
118
+ }
@@ -12,7 +12,7 @@ export async function runShortcutModelNode(options) {
12
12
  if (!/^[A-Za-z_][\w.-]*$/.test(node.id))
13
13
  throw new Error('Invalid shortcut model node ID');
14
14
  const review = node.reviewDecision;
15
- if (review && (!/^[a-f0-9]{40}$/.test(review.revision) || !/^[0-9a-f-]{36}$/i.test(review.invocationId)))
15
+ if (review && (review.revision !== review.invocationId))
16
16
  throw new Error('Invalid semantic Revision identity');
17
17
  const taskId = `shortcut-${parentTaskId}-${node.id}${review ? '-revision-' + review.invocationId : ''}`;
18
18
  const initial = await store.load(jobId);
@@ -18,7 +18,7 @@ export function eligibleShortcutReviewTask(job, taskId) {
18
18
  const cp = task.result?.data?.shortcut;
19
19
  const pending = Object.values(cp?.inFlight ?? {});
20
20
  if (pending.length !== 1 || !rev?.decidedAt || !['approved', 'changes_requested'].includes(rev.status) ||
21
- !/^[a-f0-9]{40}$/.test(rev.revision) || rev.executionId !== pending[0] || !rev.invocationId)
21
+ rev.revision !== rev.executionId || rev.executionId !== pending[0])
22
22
  return null;
23
23
  return task;
24
24
  }
@@ -41,6 +41,7 @@ export const WORKFLOW_EVENT_NAMES = [
41
41
  'task.started',
42
42
  'shortcut.waiting',
43
43
  'shortcut.completed',
44
+ 'content.completed',
44
45
  'shortcut.failed',
45
46
  'shortcut.result',
46
47
  'effect.launchShortcut.failed',
@@ -5,7 +5,7 @@ import { WORKFLOW_EFFECT_NAMES, WORKFLOW_EVENT_NAMES, WORKFLOW_MUTATION_NAMES, }
5
5
  const TASK_STATES = ['DRAFT', 'QUEUED', 'RUNNING', 'AWAITING_DECISION', 'BLOCKED', 'SUCCEEDED', 'FAILED', 'CANCELLED'];
6
6
  const JOB_STATES = ['DRAFT', 'ACTIVE', 'COMPLETED', 'CANCELLED'];
7
7
  const conditionRegistry = new ConditionRegistry([
8
- ...new Set(['dependenciesSatisfied', 'dependenciesUnsatisfied', 'runnable', 'dispatchable', 'recoverableExecution', 'troubleshooterRecovery', 'troubleshooterTask', 'awaitingInteractiveDecision', 'retryAvailable', 'notMerged', 'autoMerge', 'prOpen', 'reviewDisabled', 'implementationComplete', 'headAvailable', 'mergeCapable', 'localCompletionAllowed', 'localMergeReady', 'shortcutCompletionAllowed'])
8
+ ...new Set(['dependenciesSatisfied', 'dependenciesUnsatisfied', 'runnable', 'dispatchable', 'recoverableExecution', 'troubleshooterRecovery', 'troubleshooterTask', 'awaitingInteractiveDecision', 'retryAvailable', 'notMerged', 'autoMerge', 'prOpen', 'reviewDisabled', 'implementationComplete', 'headAvailable', 'mergeCapable', 'localCompletionAllowed', 'localMergeReady', 'shortcutCompletionAllowed', 'contentCompletionAllowed'])
9
9
  ].map(booleanCondition));
10
10
  const boolGuard = (name) => conditionRegistry.guard(name);
11
11
  export const lifecycleConditions = conditionRegistry;
@@ -64,6 +64,7 @@ export const jobLifecycleV2 = load('job-lifecycle', JOB_STATES, {
64
64
  && values.reviewHeadCurrent === true && values.mergeAttemptReady === true;
65
65
  },
66
66
  shortcutCompletionAllowed: facts => facts.durableFacts.shortcutCompletionAllowed === true,
67
+ contentCompletionAllowed: facts => facts.durableFacts.contentCompletionAllowed === true,
67
68
  });
68
69
  function topologyTargets(graph, from) {
69
70
  const source = [...graph.nodes.values()].find(node => node.kind === 'state' && node.semanticId === from);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-relay",
3
- "version": "2.0.251",
3
+ "version": "2.0.253",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,9 +16,9 @@
16
16
  "test": "npm run test:full",
17
17
  "test:chatgpt-temp-quality": "AGENTS_RELAY_RUN_CHATGPT_TEMP_QUALITY=1 sh -c \"npm run build && node test/quality/run-temporary-chat.mjs\"",
18
18
  "dev": "tsx src/cli.ts",
19
- "test:publish": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=1 --test-force-exit test/*.test.js test/verification/l3-shortcut-review.test.mjs",
20
- "test:l3:shortcut": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=1 test/verification/l3-shortcut-review.test.mjs",
21
- "test:shortcut:dags": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=1 test/verification/shortcut-dag-matrix.test.mjs test/verification/l3-shortcut-review.test.mjs test/agent-shortcut.test.js",
19
+ "test:publish": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=1 --test-force-exit test/*.test.js test/verification/l3-shortcut-review.test.mjs test/verification/l3-unified-dag.test.mjs",
20
+ "test:l3:shortcut": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=1 test/verification/l3-shortcut-review.test.mjs test/verification/l3-unified-dag.test.mjs",
21
+ "test:shortcut:dags": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=1 test/verification/shortcut-dag-matrix.test.mjs test/verification/l3-shortcut-review.test.mjs test/verification/l3-unified-dag.test.mjs test/agent-shortcut.test.js",
22
22
  "test:fast": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=2 test/workflow-lifecycle.test.js test/workflow-v2-lifecycle-parity.test.js test/workflow-effects.test.js test/relay-store.test.js test/local-authority.test.js test/local-jobid-routing.test.js test/interactive-request.test.js test/local-sqlite-jobid.test.js test/no-github.test.js test/reconcile-coordinator.test.js test/service-publication.test.js test/github-webhook.test.js test/verification/shortcut-dag-matrix.test.mjs",
23
23
  "test:full": "npm run build && node --import ./test/test-store-env.mjs --test --test-concurrency=1 test/*.test.js test/verification/shortcut-dag-matrix.test.mjs && npm run test:verification:l3",
24
24
  "test:verification:l1": "npm run build && node --test test/verification/harness.test.mjs test/verification/contract.test.mjs test/browser-worker-pool-graph.test.js test/verification/graph-inventory.test.mjs test/verification/dashboard-drilldown.test.mjs test/verification/evidence-matrix.test.mjs test/verification/task-resolution-classification.test.mjs test/verification/planner-contract.test.mjs test/verification/force-restate-validation.test.mjs test/planner-child-recovery.test.js",