agents-relay 2.0.247 → 2.0.248

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.
package/dist/pool.js CHANGED
@@ -9,7 +9,6 @@ import { pendingTroubleshooterTasks, pendingTroubleshooterReopens, pendingTroubl
9
9
  import { reviewPlanReady, reviewWorkSettled } from './review-replan.js';
10
10
  import { decideReviewLifecycle } from './workflow/review-v2.js';
11
11
  import { isFinalReviewAgent } from './final-review-role.js';
12
- import { shortcutAutoResumeTask } from './shortcut-auto-resume.js';
13
12
  const RANK = { P0: 0, P1: 1, P2: 2, P3: 3 };
14
13
  export function compareJobPriority(a, b) { return RANK[a.priority ?? 'P2'] - RANK[b.priority ?? 'P2'] || a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id); }
15
14
  export function runnableManagedJobs(items) { return items.filter(item => item.job.state === 'ACTIVE' || item.job.projectionRecovery?.status === 'repairing').map(item => item.job).sort(compareJobPriority); }
@@ -59,21 +58,19 @@ export class RepositoryWorkerPool {
59
58
  makeReconciler;
60
59
  localInventory;
61
60
  resolveLocalJob;
62
- resumeShortcut;
61
+ onShortcutDecision;
63
62
  running = false;
64
63
  pending = false;
65
64
  reconcileLocks = new Map();
66
65
  coordinator;
67
66
  dispatchTail = Promise.resolve();
68
67
  watchedBus;
69
- shortcutResumes = new Set();
70
- shortcutResumeFailures = new Map();
71
- constructor(concurrency, makeReconciler, localInventory, resolveLocalJob, resumeShortcut) {
68
+ constructor(concurrency, makeReconciler, localInventory, resolveLocalJob, onShortcutDecision) {
72
69
  this.concurrency = concurrency;
73
70
  this.makeReconciler = makeReconciler;
74
71
  this.localInventory = localInventory;
75
72
  this.resolveLocalJob = resolveLocalJob;
76
- this.resumeShortcut = resumeShortcut;
73
+ this.onShortcutDecision = onShortcutDecision;
77
74
  const reportCoordinatorError = (error, signal) => {
78
75
  observability().record({
79
76
  stage: 'reconcile', event: 'reconcile.coordinator_failed', level: 'error', outcome: 'failed',
@@ -154,42 +151,26 @@ export class RepositoryWorkerPool {
154
151
  if (signal.event.type === 'github.webhook')
155
152
  continue;
156
153
  const outcome = await reconciler.applyEvent(signal.event);
157
- // A host may commit an accepted decision to SQLite before publishing its
158
- // durable EventBus wake. Its replay is idempotently ignored by the Task
159
- // reducer, but the shared Pool must still inspect QUEUED Shortcut work.
160
- shouldReconcile ||= outcome.reconcile || signal.event.type === 'task.interactive_decision';
154
+ // The decision is durably applied before invoking the Shortcut CLI hook.
155
+ // A replay can also wake a still-QUEUED Task without a new decision.
156
+ if (signal.event.type === 'task.interactive_decision' &&
157
+ ['task.interactive_decision.accepted', 'task.interactive_decision.duplicate'].includes(outcome.reason) &&
158
+ await this.onShortcutDecision?.(jobId, signal.event.task_id))
159
+ continue;
160
+ shouldReconcile ||= outcome.reconcile;
161
161
  }
162
162
  if (shouldReconcile)
163
163
  await this.reconcileLocalJob(jobId, 'local.signal');
164
164
  }
165
165
  async reconcileDiscovered(discovered) {
166
166
  const jobs = runnableManagedJobs(discovered);
167
- let capacity = Math.max(0, this.concurrency - jobs.filter(job => jobHasActiveExecution(job)).length - this.shortcutResumes.size);
167
+ let capacity = Math.max(0, this.concurrency - jobs.filter(job => jobHasActiveExecution(job)).length);
168
168
  for (const job of jobs) {
169
169
  if (capacity <= 0)
170
170
  break;
171
- // The shared Pool resumes only previously launched human-reviewed
172
- // Shortcut Tasks. A Shortcut created but never explicitly run is inert.
173
- if (job.executionMode === 'shortcut') {
174
- const resume = shortcutAutoResumeTask(job);
175
- if (resume && this.resumeShortcut && !this.shortcutResumes.has(job.id)) {
176
- const invocationId = resume.interactiveInvocation.invocationId;
177
- const old = this.shortcutResumeFailures.get(job.id);
178
- const previous = old?.invocationId === invocationId ? old : undefined;
179
- if (!previous || (previous.attempts < 3 && previous.retryAfter <= Date.now())) {
180
- this.shortcutResumes.add(job.id);
181
- void this.resumeShortcut(job, resume).then(() => this.shortcutResumeFailures.delete(job.id)).catch(error => {
182
- const attempts = (previous?.attempts ?? 0) + 1;
183
- this.shortcutResumeFailures.set(job.id, { invocationId, attempts, retryAfter: Date.now() + Math.min(120000, 10000 * 2 ** (attempts - 1)) });
184
- observability().record({ stage: 'reconcile', event: 'shortcut.resume_failed', level: 'warn', outcome: 'failed',
185
- message: 'Shortcut automatic resume failed (' + attempts + '/3): ' + errorMessage(error),
186
- correlation: { jobId: job.id, repository: job.repository, taskId: resume.id } });
187
- }).finally(() => this.shortcutResumes.delete(job.id));
188
- capacity--;
189
- }
190
- }
171
+ // Shortcut starts and review resumes are external CLI invocations, not normal Task dispatch.
172
+ if (job.executionMode === 'shortcut')
191
173
  continue;
192
- }
193
174
  const store = await this.requireLocalStore(job.id);
194
175
  await store.hydrate?.(job);
195
176
  const ready = job.tasks.filter(task => (task.state === 'QUEUED' && task.executionId === null) || (task.state === 'DRAFT' && task.dependencies.length > 0)).length;
package/dist/relayd.js CHANGED
@@ -10,7 +10,7 @@ import { ZAdapter } from './z-adapter.js';
10
10
  import { CodexThreadContinuation, CommandContinuation, WebhookContinuation } from './continuation.js';
11
11
  import { serveDashboard } from './dashboard.js';
12
12
  import { RepositoryWorkerPool } from './pool.js';
13
- import { resumeShortcutInOwnedProcess } from './shortcut-auto-resume-process.js';
13
+ import { createShortcutReviewWake } from './shortcut-review-wake.js';
14
14
  import { Reconciler } from './reconciler.js';
15
15
  import { dashboardManagedJobs, GitHubStore, InMemoryStore, resolvePullRequest } from './store.js';
16
16
  import { GitHubProjectionWriter } from './projected-store.js';
@@ -392,7 +392,8 @@ export async function runDaemon(argv) {
392
392
  })();
393
393
  return githubBindingSyncInFlight;
394
394
  };
395
- const pool = new RepositoryWorkerPool(concurrency, makeReconciler, inventoryFromLocal, localJobBinding, resumeShortcutInOwnedProcess);
395
+ const shortcutReviewWake = createShortcutReviewWake(async (jobId) => (await localJobBinding(jobId))?.job ?? null);
396
+ const pool = new RepositoryWorkerPool(concurrency, makeReconciler, inventoryFromLocal, localJobBinding, shortcutReviewWake);
396
397
  const initial = cachedOverviews;
397
398
  const fallback = initial[0]?.job;
398
399
  const dashboardStore = fallback ? (await requireLocalJobBinding(fallback.id)).store : new InMemoryStore();
@@ -0,0 +1,64 @@
1
+ import { once } from 'node:events';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { spawnOwnedProcess } from './owned-process.js';
4
+ import { errorMessage, observability } from './observability.js';
5
+ /** The interactive decision has already been applied by the canonical Relay
6
+ * handler. Invoke the *same* CLI a human would run, once per in-flight Job.
7
+ * No Shortcut scheduler, queue, or normal-Job Worker Pool dispatch required.
8
+ */
9
+ export function eligibleShortcutReviewTask(job, taskId) {
10
+ if (job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'ACTIVE' || job.pause ||
11
+ !job.shortcutExecutionStartedAt || !job.shortcutRunnerContext?.projectPath ||
12
+ !job.shortcutRunnerContext.workspaceRoot)
13
+ return null;
14
+ const task = job.tasks.find(t => t.id === taskId);
15
+ if (!task?.agentGraph || task.state !== 'QUEUED' || task.executionId !== null || task.leaseOwner !== null)
16
+ return null;
17
+ const rev = task.interactiveInvocation;
18
+ const cp = task.result?.data?.shortcut;
19
+ const pending = Object.values(cp?.inFlight ?? {});
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)
22
+ return null;
23
+ return task;
24
+ }
25
+ export async function launchShortcutReviewCLI(job, task) {
26
+ const ctx = job.shortcutRunnerContext;
27
+ if (!ctx)
28
+ throw Error('Missing trusted original Shortcut launch context');
29
+ const args = [fileURLToPath(new URL('./cli.js', import.meta.url)),
30
+ 'job', 'run', '--mode', 'shortcut', '--repo', job.repository, '--id', job.id, '--task-id', task.id,
31
+ '--project-path', ctx.projectPath, '--workspace-root', ctx.workspaceRoot,
32
+ ...(ctx.sharedRoot ? ['--shared-root', ctx.sharedRoot] : []),
33
+ ...(ctx.globalRoot ? ['--global-root', ctx.globalRoot] : []),
34
+ ...(ctx.noGitHub ? ['--no-github'] : [])];
35
+ const child = spawnOwnedProcess(process.execPath, args, { invocation: 'shortcut.review-resume',
36
+ correlation: { jobId: job.id, repository: job.repository, taskId: task.id },
37
+ spawn: { cwd: ctx.projectPath, stdio: ['ignore', 'pipe', 'pipe'], env: process.env } });
38
+ const stderr = [];
39
+ child.stderr?.on('data', chunk => { if (stderr.join('').length < 4000)
40
+ stderr.push(String(chunk).slice(0, 500)); });
41
+ child.stdout?.resume();
42
+ const [code, signal] = await once(child, 'close');
43
+ if (signal || (code !== 0 && code !== 3))
44
+ throw Error(`Shortcut CLI exited (${signal ?? code}): ${stderr.join('').slice(-1500)}`);
45
+ }
46
+ export function createShortcutReviewWake(loadJob, run = launchShortcutReviewCLI) {
47
+ const running = new Set();
48
+ return async (jobId, taskId) => {
49
+ const job = await loadJob(jobId);
50
+ if (!job || job.executionMode !== 'shortcut')
51
+ return false;
52
+ const task = eligibleShortcutReviewTask(job, taskId);
53
+ if (!task || running.has(jobId))
54
+ return true;
55
+ running.add(jobId);
56
+ // Return immediately to the event consumer: the CLI may wait on an Agent.
57
+ void run(job, task).catch(error => {
58
+ observability().record({ stage: 'reconcile', event: 'shortcut.review_resume_failed', level: 'error', outcome: 'failed',
59
+ message: 'Shortcut review CLI failed: ' + errorMessage(error),
60
+ correlation: { jobId, repository: job.repository, taskId } });
61
+ }).finally(() => running.delete(jobId));
62
+ return true;
63
+ };
64
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-relay",
3
- "version": "2.0.247",
3
+ "version": "2.0.248",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",
@@ -58,7 +58,7 @@ Job/Task/Execution source identity.
58
58
  Relay checks the pending invocation, persists RUNNING -> AWAITING_DECISION,
59
59
  clears the execution lease, and releases the Worker. This is a non-failure
60
60
  handoff and is not a Task completion or a Troubleshooter block.
61
- For Shortcut modules, a host-wrapped `markcut.preview` call uses the **original Shortcut Task identity**, not a reviewer child. The module returns `WAITING_REVIEW` only after the host has durably transitioned that Task to `AWAITING_DECISION`. The foreground runner exits with waiting status, keeping the in-flight node as a durable replay fence. After an authenticated accepted decision, the lifecycle requeues that same Task. The existing Relay Worker Pool automatically re-enters the trusted Shortcut Runner only for Jobs with a prior explicit launch and an exact accepted review/in-flight execution. It never auto-starts draft or unlaunched Shortcut Jobs and does not add a separate Scheduler. On `changes_requested`, a Script node invokes its Agent's normal durable model Worker to revise existing Artifacts, then re-verifies and opens a new human Preview. `approved` continues the Graph. Nonhuman `WAITING_EVENT` receipts are a different mechanism.
61
+ For Shortcut modules, a host-wrapped `markcut.preview` call uses the **original Shortcut Task identity**, not a reviewer child. The module returns `WAITING_REVIEW` only after the host has durably transitioned that Task to `AWAITING_DECISION`. The foreground runner exits with waiting status, keeping the in-flight node as a durable replay fence. After an authenticated accepted decision, the lifecycle requeues that same Task. The interactive decision event listener calls the same trusted Shortcut Runner CLI used for manual execution, immediately after Relay durably accepts the decision and requeues the original Task. It does not schedule Shortcuts through the normal Worker Pool. It never auto-starts draft or unlaunched Shortcut Jobs and does not add a separate Scheduler. On `changes_requested`, a Script node invokes its Agent's normal durable model Worker to revise existing Artifacts, then re-verifies and opens a new human Preview. `approved` continues the Graph. Nonhuman `WAITING_EVENT` receipts are a different mechanism.
62
62
 
63
63
  The Job stays ACTIVE; the Task does not requeue until a matching
64
64
  `task.interactive_decision` is durably accepted and the Task Graph selects
@@ -1,27 +0,0 @@
1
- import { once } from 'node:events';
2
- import { fileURLToPath } from 'node:url';
3
- import { spawnOwnedProcess } from './owned-process.js';
4
- /** The shared Scheduler launches only the trusted current Relay CLI. Paths are
5
- * bound during the first explicit Shortcut run, never parsed from Task text. */
6
- export async function resumeShortcutInOwnedProcess(job, task) {
7
- const ctx = job.shortcutRunnerContext;
8
- if (!ctx?.projectPath || !ctx.workspaceRoot)
9
- throw Error('Unbound Shortcut launch context');
10
- const args = [fileURLToPath(new URL('./cli.js', import.meta.url)),
11
- 'job', 'run', '--mode', 'shortcut', '--repo', job.repository, '--id', job.id, '--task-id', task.id,
12
- '--project-path', ctx.projectPath, '--workspace-root', ctx.workspaceRoot,
13
- ...(ctx.sharedRoot ? ['--shared-root', ctx.sharedRoot] : []),
14
- ...(ctx.globalRoot ? ['--global-root', ctx.globalRoot] : []),
15
- ...(ctx.noGitHub ? ['--no-github', '--shortcut-local'] : [])];
16
- const child = spawnOwnedProcess(process.execPath, args, { invocation: 'shortcut.auto-resume',
17
- correlation: { jobId: job.id, repository: job.repository, taskId: task.id },
18
- spawn: { cwd: ctx.projectPath, stdio: ['ignore', 'pipe', 'pipe'], env: process.env } });
19
- const errors = [];
20
- child.stderr?.on('data', chunk => { const text = String(chunk); if (errors.join('').length < 4000)
21
- errors.push(text.slice(0, 500)); });
22
- child.stdout?.resume();
23
- const [code, signal] = await once(child, 'close');
24
- // Exit 3 is a persisted WAITING_REVIEW/WAITING_EVENT, not worker failure.
25
- if (signal || (code !== 0 && code !== 3))
26
- throw Error(`Shortcut runner stopped (${signal ?? code}): ${errors.join('').slice(-1500)}`);
27
- }
@@ -1,24 +0,0 @@
1
- /** The first Shortcut launch is ALWAYS explicit. Only a previously suspended,
2
- * human-decided node may be auto-resumed through the shared Relay Worker Pool.
3
- * No separate queue, timer, or scheduler owns these Task transitions.
4
- */
5
- export function shortcutAutoResumeTask(job) {
6
- if (job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'ACTIVE' ||
7
- job.pause || !job.shortcutRunnerContext || !job.shortcutRunnerContext.projectPath || !job.shortcutRunnerContext.workspaceRoot ||
8
- !job.shortcutExecutionStartedAt || !Number.isFinite(Date.parse(job.shortcutExecutionStartedAt)))
9
- return null;
10
- for (const task of job.tasks) {
11
- if (!task.agentGraph || task.state !== 'QUEUED' || task.executionId !== null || task.leaseOwner !== null)
12
- continue;
13
- const review = task.interactiveInvocation;
14
- const cp = task.result?.data?.shortcut;
15
- const pending = Object.entries(cp?.inFlight ?? {});
16
- if (pending.length !== 1 || !review?.decidedAt ||
17
- !['approved', 'changes_requested'].includes(review.status) ||
18
- review.executionId !== pending[0][1] || !/^[a-f0-9]{40}$/.test(review.revision) ||
19
- typeof review.invocationId !== 'string' || !review.invocationId)
20
- continue;
21
- return task;
22
- }
23
- return null;
24
- }