agents-relay 2.0.208 → 2.0.210

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/adapters.js +2 -1
  2. package/dist/agent-shortcut.js +113 -41
  3. package/dist/browser-worker-runtime.js +7 -2
  4. package/dist/chatgpt-platform-fallback.js +30 -0
  5. package/dist/cli-help.js +10 -4
  6. package/dist/cli-prompt.js +2 -1
  7. package/dist/cli-revision.js +49 -0
  8. package/dist/cli-shortcut-local.js +49 -0
  9. package/dist/cli-shortcut.js +81 -19
  10. package/dist/cli-worker-task.js +15 -0
  11. package/dist/cli.js +19 -5
  12. package/dist/dashboard-html.js +2 -2
  13. package/dist/dependency-revision-execution.js +152 -0
  14. package/dist/dependency-validity.js +17 -0
  15. package/dist/final-review-role.js +17 -0
  16. package/dist/force-restate-validation.js +6 -3
  17. package/dist/job-execution-slot.js +4 -1
  18. package/dist/job-pr-number-migration.js +2 -1
  19. package/dist/managed-worker-input.js +2 -1
  20. package/dist/model-routing.js +8 -0
  21. package/dist/planner-agent-roles.js +18 -0
  22. package/dist/planner-runtime.js +7 -1
  23. package/dist/planner-task-ids.js +1 -0
  24. package/dist/planner.js +11 -6
  25. package/dist/reconciler-review.js +110 -109
  26. package/dist/reconciler-runtime.js +56 -58
  27. package/dist/reconciler.js +33 -13
  28. package/dist/relay-job-snapshot-reads.js +5 -2
  29. package/dist/relay-store.js +2 -0
  30. package/dist/relay-workflow-operations.js +1 -1
  31. package/dist/relayd-control.js +31 -0
  32. package/dist/review-evidence.js +44 -0
  33. package/dist/review-generation-fence.js +2 -1
  34. package/dist/review-revision-execution.js +86 -0
  35. package/dist/review-revision-merge.js +15 -0
  36. package/dist/review-revision-model.js +191 -0
  37. package/dist/review-revision-policy.js +49 -0
  38. package/dist/review-revision-settlement.js +54 -0
  39. package/dist/review-revision-stale.js +57 -0
  40. package/dist/reviewer-thread.js +41 -1
  41. package/dist/runtime-status.js +24 -8
  42. package/dist/shortcut-node-worker.js +128 -0
  43. package/dist/shortcut-stage-contract.js +50 -0
  44. package/dist/shortcut-worker-runner.js +73 -0
  45. package/dist/single-job-task-control.js +1 -1
  46. package/dist/task-actions.js +4 -13
  47. package/dist/task-context.js +3 -2
  48. package/dist/task-inactivity-watchdog.js +7 -0
  49. package/dist/terminal-event-recovery.js +13 -0
  50. package/dist/worker-failure-recovery.js +90 -0
  51. package/dist/workflow/contracts.js +4 -0
  52. package/dist/workflow/definitions-v2.js +2 -0
  53. package/dist/workflow/dependency-revision-v2.js +16 -0
  54. package/dist/workflow/entity-creation.js +2 -0
  55. package/dist/workflow/review-v2.js +6 -2
  56. package/dist/workflow/revision-v2.js +32 -0
  57. package/dist/workflow/runtime.js +30 -0
  58. package/dist/workflow/task-reconcile.js +3 -0
  59. package/dist/workflow/task-resolution.js +1 -4
  60. package/package.json +4 -3
  61. package/skills/agents-relay/agents/job-acceptance-reviewer.agent.md +41 -0
  62. package/skills/agents-relay/agents/planner.agent.md +18 -5
  63. package/skills/agents-relay/agents/reviewer.agent.md +2 -0
  64. package/skills/agents-relay/contracts/event-contract.md +7 -0
  65. package/skills/agents-relay/contracts/orchestrator-workflows.md +6 -0
  66. package/skills/agents-relay/contracts/task-job-contract.md +10 -0
  67. package/workflow/dependency-revision.mmd +30 -0
  68. package/workflow/force-restate-validation.mmd +1 -1
  69. package/workflow/review-lifecycle.mmd +41 -10
  70. package/workflow/revision-lifecycle.mmd +68 -0
  71. package/workflow/task-lifecycle.mmd +13 -12
  72. package/workflow/task-resolution.mmd +1 -6
package/dist/adapters.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { terminalRecoveryPrompt } from './terminal-event-recovery.js';
1
2
  import { access, readFile, realpath } from 'node:fs/promises';
2
3
  import { relative, resolve, sep, basename } from 'node:path';
3
4
  import { DEFAULT_PROMPT_REFERENCE_DIRECTORY } from './agent-prompt-builder.js';
@@ -298,7 +299,7 @@ function browserWorkerRunner() {
298
299
  } : { message, temporary: false } }),
299
300
  recover: async (threadId) => ({
300
301
  thread_id: threadId, mode: 'sync',
301
- message: `[Relay Browser Worker recovery: ${request.execution?.executionId ?? 'unknown'}]\nInspect this Task's authoritative Neo events and durable outputs. If an original correlated terminal event exists, report it without duplicating. If the output is complete and verified, publish task.completed using the ORIGINAL execution identity. Otherwise continue the remaining work with task.progress, or publish task.failed with a real reason. Do not claim completion without evidence.`,
302
+ message: terminalRecoveryPrompt(request.execution?.executionId ?? 'unknown'),
302
303
  }),
303
304
  }, signal);
304
305
  };
@@ -1,15 +1,16 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { existsSync } from 'node:fs';
3
3
  import { readFile } from 'node:fs/promises';
4
- import { resolve, relative, isAbsolute, sep } from 'node:path';
4
+ import { resolve, relative, isAbsolute, sep, dirname } from 'node:path';
5
5
  import { realpath } from 'node:fs/promises';
6
6
  import { once } from 'node:events';
7
7
  import { pathToFileURL } from 'node:url';
8
8
  import { spawnOwnedProcess } from './owned-process.js';
9
+ import { validateShortcutStageGate } from './shortcut-stage-contract.js';
9
10
  import { parseAgentGraph } from './agent-graph.js';
10
11
  import { DurableTaskTransitionRuntime } from './workflow/durable-transition.js';
11
12
  import { dispatchJobLifecycleSync } from './workflow/lifecycle.js';
12
- import { dependencyReady } from './task-transitions.js';
13
+ import { dependencyReady, tryTransitionTaskEvent } from './task-transitions.js';
13
14
  const digest = (value) => createHash('sha256').update(value).digest('hex');
14
15
  const digestBytes = (value) => createHash('sha256').update(value).digest('hex');
15
16
  function canonical(value) {
@@ -116,7 +117,25 @@ async function discoverShortcut(agent, projectPath, neoRoot) {
116
117
  throw new Error('Shared shortcut symlink escapes shortcut root');
117
118
  return actual;
118
119
  }
120
+ export async function missingShortcutNodes(agentGraph, projectPath, neoRoot) {
121
+ const graph = parseAgentGraph(agentGraph);
122
+ const result = await Promise.all(graph.nodes.map(async (node) => ({
123
+ id: node.id, available: Boolean(await discoverShortcut(node.agent, projectPath, neoRoot)),
124
+ })));
125
+ return result.filter(item => !item.available).map(item => item.id);
126
+ }
119
127
  function inside(root, path) { const rel = relative(root, path); return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); }
128
+ function raceAbort(work, signal) {
129
+ if (signal.aborted)
130
+ return Promise.reject(signal.reason ?? new Error('Shortcut execution interrupted'));
131
+ let rejectAbort;
132
+ const aborted = new Promise((_resolve, reject) => {
133
+ rejectAbort = () => reject(signal.reason ?? new Error('Shortcut execution interrupted'));
134
+ signal.addEventListener('abort', rejectAbort, { once: true });
135
+ });
136
+ return Promise.race([work, aborted]).finally(() => { if (rejectAbort)
137
+ signal.removeEventListener('abort', rejectAbort); });
138
+ }
120
139
  // Only Vlog's Visioner evidence follows the source-manifest/index artifact schema.
121
140
  // Distribution Visioner has a separate domain contract and cannot reuse it.
122
141
  function requiresVlogVisionerEvidence(agent) {
@@ -144,10 +163,10 @@ async function validateVisionerResult(result, projectRoot) {
144
163
  artifactFiles.set(name, { bytes, parsed: parsed });
145
164
  }
146
165
  const evidenceFile = artifactFiles.get('vision-evidence.json'), indexFile = artifactFiles.get('vision-segment-index.json'), metadataFile = artifactFiles.get('metadata.json');
147
- if (evidence.vision_segment_index_sha256 !== digestBytes(indexFile.bytes) || evidence.manifest_hash !== index.manifest_hash
148
- || evidence.markcut_metadata_sha256 !== index.markcut_metadata_sha256 || index.markcut_metadata_sha256 !== digestBytes(metadataFile.bytes)
149
- || evidenceFile.parsed.status !== 'EVIDENCE_READY_UNREVIEWED')
150
- throw new Error('Visioner evidence hashes or artifact contents do not match');
166
+ // Stage authority is the source-linked structure and original media IDs, not repeated checksum validation.
167
+ if (evidenceFile.parsed.status !== 'EVIDENCE_READY_UNREVIEWED' || indexFile.parsed.status !== 'SOURCE_LINKED_UNREVIEWED'
168
+ || !metadataFile.parsed)
169
+ throw new Error('Visioner structured evidence does not satisfy the Stage contract');
151
170
  }
152
171
  export async function runAgentShortcut(options) {
153
172
  const { store, job, task, projectPath, neoRoot } = options;
@@ -177,6 +196,10 @@ export async function runAgentShortcut(options) {
177
196
  throw new Error('Shortcut invocation Task snapshot is stale; reload the durable Task before execution or receipt consumption');
178
197
  if (currentJob.executionMode !== 'shortcut' || currentJob.contentOnly !== true)
179
198
  throw new Error('Shortcut execution requires durable shortcut and content-only Job policy');
199
+ if (currentJob.shortcutExecutionDeadlineAt && !Number.isFinite(Date.parse(currentJob.shortcutExecutionDeadlineAt)))
200
+ throw new Error('Shortcut execution budget metadata is invalid');
201
+ if (currentJob.shortcutExecutionStartedAt && !Number.isFinite(Date.parse(currentJob.shortcutExecutionStartedAt)))
202
+ throw new Error('Shortcut execution budget metadata is invalid');
180
203
  const existingShortcut = currentTask.result?.data?.shortcut;
181
204
  if (existingShortcut?.workerFallback === true)
182
205
  throw new Error('Task is durably routed to the original Worker; shortcut execution is not authorized');
@@ -185,6 +208,13 @@ export async function runAgentShortcut(options) {
185
208
  if (currentTask.state === 'QUEUED' && !dependencyReady(currentTask, new Map(currentJob.tasks.map(item => [item.id, item]))))
186
209
  throw new Error(`Task ${task.id} dependencies are not satisfied`);
187
210
  let state = checkpoint(currentTask);
211
+ // A Task Lifecycle-authorized retry retains verified completed nodes and
212
+ // execution history, but its previous attempt's terminal verdict must not
213
+ // contaminate the new run's eventual success receipt.
214
+ if (currentTask.state === 'QUEUED' && currentTask.attempt > 0 &&
215
+ currentTask.executionId === null && currentTask.leaseOwner === null &&
216
+ 'terminal' in state)
217
+ delete state.terminal;
188
218
  if (state.graphHash && (state.version !== 1 || state.graphHash !== graphHash || state.inputHash !== inputHash || state.shortcutHash !== shortcutHash))
189
219
  throw new Error('Shortcut checkpoint fingerprint changed; refusing to reuse prior node output');
190
220
  state.version = 1;
@@ -218,6 +248,9 @@ export async function runAgentShortcut(options) {
218
248
  throw new Error(`Checkpoint artifact has no completed node: ${nodeId}`);
219
249
  }
220
250
  if (currentTask.state === 'QUEUED') {
251
+ const launch = tryTransitionTaskEvent(currentTask, 'dispatch', { dispatchable: true, shortcutExecution: true, shortcutFallback: false, shortcutHasGraph: true, shortcutDirectInvocation: true });
252
+ if (!launch.accepted || !launch.actions.includes('effect.launchShortcut'))
253
+ throw new Error('Task Lifecycle graph did not select direct shortcut execution');
221
254
  await store.mutateJob(job.id, fresh => {
222
255
  const t = fresh.tasks.find(item => item.id === task.id);
223
256
  if (fresh.state !== 'ACTIVE' || fresh.pause || !t || t.state !== 'QUEUED' || t.executionId !== null || t.agentGraph !== task.agentGraph || t.input !== task.input
@@ -227,6 +260,10 @@ export async function runAgentShortcut(options) {
227
260
  t.executionId = randomUUID();
228
261
  t.leaseOwner = owner;
229
262
  t.leaseExpiresAt = new Date(Date.now() + leaseMs).toISOString();
263
+ if (!fresh.shortcutExecutionStartedAt)
264
+ fresh.shortcutExecutionStartedAt = new Date().toISOString();
265
+ if (!fresh.shortcutExecutionDeadlineAt)
266
+ fresh.shortcutExecutionDeadlineAt = new Date(Date.parse(fresh.shortcutExecutionStartedAt) + 20 * 60 * 1000).toISOString();
230
267
  t.executionHistory = [...(t.executionHistory ?? []), { id: t.executionId, attempt: t.attempt, startedAt: new Date().toISOString() }].slice(-8);
231
268
  return fresh;
232
269
  });
@@ -285,6 +322,8 @@ export async function runAgentShortcut(options) {
285
322
  const nodeAgent = graph.nodes.find(node => node.id === nodeId)?.agent;
286
323
  if (requiresVlogVisionerEvidence(nodeAgent?.toLowerCase()))
287
324
  await validateVisionerResult(output, projectReal);
325
+ if (nodeAgent && task.output?.kind === 'file')
326
+ await validateShortcutStageGate({ projectPath: projectReal, agent: nodeAgent, runPath: dirname(task.output.path), execute: (args, cwd) => runCommand(args, cwd, new AbortController().signal) });
288
327
  state.nodes[nodeId] = structuredClone(output);
289
328
  state.artifactHashes[nodeId] = artifactHashes;
290
329
  delete state.waits[nodeId];
@@ -292,7 +331,28 @@ export async function runAgentShortcut(options) {
292
331
  }
293
332
  if (Object.keys(state.nodes).length > Object.keys(checkpoint(currentTask).nodes).length)
294
333
  await persist(state);
334
+ currentJob = await store.load(job.id);
335
+ if (!currentJob.shortcutExecutionStartedAt)
336
+ throw new Error('Direct shortcut Job has no durable first-execution timestamp; refusing to start or reset its budget');
337
+ const startedAt = Date.parse(currentJob.shortcutExecutionStartedAt);
338
+ const deadlineAt = currentJob.shortcutExecutionDeadlineAt ? Date.parse(currentJob.shortcutExecutionDeadlineAt) : startedAt + 20 * 60 * 1000;
339
+ if (!Number.isFinite(startedAt) || !Number.isFinite(deadlineAt) || deadlineAt !== startedAt + 20 * 60 * 1000)
340
+ throw new Error('Shortcut execution budget metadata is invalid');
341
+ if (!currentJob.shortcutExecutionDeadlineAt) {
342
+ await store.mutateJob(job.id, fresh => {
343
+ if (fresh.shortcutExecutionStartedAt !== currentJob.shortcutExecutionStartedAt)
344
+ throw new Error('Shortcut execution budget origin changed');
345
+ fresh.shortcutExecutionDeadlineAt = new Date(deadlineAt).toISOString();
346
+ return fresh;
347
+ });
348
+ }
295
349
  const executionAbort = new AbortController();
350
+ const abortFromCaller = () => executionAbort.abort(options.signal?.reason ?? new Error('Shortcut execution interrupted'));
351
+ if (options.signal?.aborted)
352
+ abortFromCaller();
353
+ else
354
+ options.signal?.addEventListener('abort', abortFromCaller, { once: true });
355
+ const budgetTimer = setTimeout(() => executionAbort.abort(new Error('Shortcut execution budget exceeded (20 minutes)')), Math.max(0, deadlineAt - Date.now()));
296
356
  let leaseHeartbeatError;
297
357
  let heartbeatInFlight = false;
298
358
  const heartbeat = setInterval(() => {
@@ -309,18 +369,17 @@ export async function runAgentShortcut(options) {
309
369
  }).catch(error => { leaseHeartbeatError = error; executionAbort.abort(error); }).finally(() => { heartbeatInFlight = false; });
310
370
  }, heartbeatMs);
311
371
  heartbeat.unref();
312
- const stopHeartbeat = () => clearInterval(heartbeat);
313
- let effectsStarted = false;
314
- let shortcutModuleEntered = false;
372
+ const stopHeartbeat = () => { clearInterval(heartbeat); clearTimeout(budgetTimer); options.signal?.removeEventListener('abort', abortFromCaller); };
373
+ const emit = (event) => options.onNodeEvent?.({ ...event, timestamp: new Date().toISOString() });
315
374
  try {
316
- // Shortcut execution is a whole-Graph optimization, not a per-node Worker scheduler.
317
- // Check complete coverage BEFORE importing or invoking any shortcut. Otherwise a
318
- // missing later role can strand earlier side effects in Troubleshooter recovery.
319
- // The existing durable shortcut.failed transition safely routes an untouched Graph
320
- // to its original Worker; a previously checkpointed partial run still fails closed.
375
+ if (Date.now() >= deadlineAt)
376
+ return await fail('Shortcut execution budget exceeded (20 minutes)');
377
+ // The existing Graph executor owns node readiness for both code and model
378
+ // nodes. Model nodes execute using Relay's existing durable Worker adapter,
379
+ // never by routing the entire Agent Graph to one Worker.
321
380
  const missing = shortcuts.filter(item => !item.path);
322
- if (missing.length)
323
- return await fallback(`Incomplete Agent Graph shortcut coverage: ${missing.map(item => item.nodeId).join(', ')}; use the original Worker`);
381
+ if (missing.length && !options.runModelNode)
382
+ return await fail(`Incomplete Agent Graph shortcut coverage: ${missing.map(item => item.nodeId).join(', ')}`);
324
383
  const incoming = new Map(graph.nodes.map(node => [node.id, graph.edges.filter(edge => edge.to === node.id).map(edge => edge.from)]));
325
384
  const max = Math.max(1, Math.min(8, options.concurrency ?? 4));
326
385
  const shortcutByNode = new Map(shortcuts.map(item => [item.nodeId, item.path]));
@@ -328,27 +387,29 @@ export async function runAgentShortcut(options) {
328
387
  const ready = wave.filter(id => !state.nodes[id] && !state.waits[id] && (incoming.get(id) ?? []).every(parent => Boolean(state.nodes[parent])));
329
388
  for (let offset = 0; offset < ready.length; offset += max) {
330
389
  const batch = ready.slice(offset, offset + max);
331
- for (const id of batch)
332
- if (shortcutByNode.get(id))
333
- state.inFlight[id] = currentTask.executionId;
334
- if (batch.some(id => Boolean(shortcutByNode.get(id))))
390
+ for (const id of batch) {
391
+ state.inFlight[id] = currentTask.executionId;
392
+ emit({ nodeId: id, type: 'started', data: { executionId: currentTask.executionId, agent: graph.nodes.find(node => node.id === id)?.agent } });
393
+ }
394
+ if (batch.length)
335
395
  await persist(state);
336
396
  const outcomes = await Promise.all(batch.map(async (id) => {
337
397
  const node = graph.nodes.find(item => item.id === id);
338
398
  const shortcut = shortcutByNode.get(id) ?? null;
339
- if (!shortcut)
340
- return { id, value: null };
341
399
  try {
342
- shortcutModuleEntered = true;
343
- const module = await import(pathToFileURL(shortcut).href);
344
400
  const predecessorOutputs = Object.fromEntries((incoming.get(id) ?? []).map(parent => [parent, state.nodes[parent]?.output]));
345
401
  const trackedRunCommand = async (args, cwd) => {
346
402
  if (executionAbort.signal.aborted)
347
403
  throw new Error(`Shortcut execution was cancelled: ${String(leaseHeartbeatError ?? 'lease lost')}`);
348
- effectsStarted = true;
349
404
  return runCommand(args, cwd, executionAbort.signal);
350
405
  };
351
- const raw = await module.run({ input: { ...taskShortcutInput(task.input), projectPath, jobId: job.id, taskId: task.id, nodeId: id, agent: node.agent, predecessorOutputs }, signal: executionAbort.signal, runCommand: trackedRunCommand });
406
+ emit({ nodeId: id, type: 'progress', data: { phase: shortcut ? 'shortcut.invoke' : 'worker.invoke' } });
407
+ const raw = await raceAbort(shortcut
408
+ ? (async () => {
409
+ const module = await import(pathToFileURL(shortcut).href);
410
+ return module.run({ input: { ...taskShortcutInput(task.input), projectPath, jobId: job.id, taskId: task.id, nodeId: id, agent: node.agent, predecessorOutputs }, signal: executionAbort.signal, runCommand: trackedRunCommand });
411
+ })()
412
+ : options.runModelNode({ id, agent: node.agent, predecessorOutputs, executionId: currentTask.executionId, signal: executionAbort.signal }), executionAbort.signal);
352
413
  if (leaseHeartbeatError)
353
414
  throw new Error(`Shortcut lease renewal failed: ${String(leaseHeartbeatError)}`);
354
415
  if (!raw || typeof raw !== 'object')
@@ -367,6 +428,8 @@ export async function runAgentShortcut(options) {
367
428
  const projectReal = await realpath(projectPath);
368
429
  if (requiresVlogVisionerEvidence(node.agent.toLowerCase()))
369
430
  await validateVisionerResult(result, projectReal);
431
+ if (task.output?.kind === 'file')
432
+ await validateShortcutStageGate({ projectPath: projectReal, agent: node.agent, runPath: dirname(task.output.path), execute: trackedRunCommand });
370
433
  const artifactHashes = {};
371
434
  for (const artifact of artifactPaths) {
372
435
  if (!artifact)
@@ -390,26 +453,33 @@ export async function runAgentShortcut(options) {
390
453
  return { id, value: null, error: error instanceof Error ? error.message : String(error) };
391
454
  }
392
455
  }));
456
+ const failed = outcomes.find(result => !result.value);
393
457
  for (const result of outcomes) {
394
- if (!result.value)
395
- return await fallback(`No valid shortcut for ${result.id}${result.error ? `: ${result.error}` : ''}`);
458
+ if (!result.value) {
459
+ delete state.inFlight[result.id];
460
+ continue;
461
+ }
396
462
  if (result.value.status === 'WAITING_EVENT') {
397
463
  const evt = result.value.event;
398
464
  if (evt.kind !== 'nonhuman_result')
399
- return await fallback('Shortcut event wait must be a nonhuman result; human approval must use Relay hostInvocation');
465
+ return await fail('Shortcut event wait must be a nonhuman result; human approval must use Relay hostInvocation');
400
466
  if (typeof evt.id !== 'string' || typeof evt.revision !== 'string' || typeof evt.contentHash !== 'string'
401
467
  || (evt.nodeId !== undefined && evt.nodeId !== result.id) || !/^[0-9a-f]{64}$/i.test(evt.contentHash))
402
- return await fallback(`Invalid event wait from ${result.id}`);
468
+ return await fail(`Invalid event wait from ${result.id}`);
403
469
  delete state.inFlight[result.id];
404
470
  state.waits[result.id] = { kind: 'nonhuman_result', id: evt.id, revision: evt.revision, contentHash: evt.contentHash, executionId: currentTask.executionId };
471
+ emit({ nodeId: result.id, type: 'waiting', data: { waitId: evt.id, revision: evt.revision, executionId: currentTask.executionId } });
405
472
  }
406
473
  else {
407
474
  delete state.inFlight[result.id];
408
475
  state.nodes[result.id] = result.value;
409
476
  state.artifactHashes[result.id] = result.artifactHashes ?? {};
477
+ emit({ nodeId: result.id, type: 'completed', data: { executionId: currentTask.executionId, output: result.value.output } });
410
478
  }
411
479
  }
412
480
  await persist(state);
481
+ if (failed)
482
+ return await fail(`Shortcut node ${failed.id} failed: ${failed.error ?? 'no valid result'}`);
413
483
  }
414
484
  }
415
485
  if (Object.keys(state.waits).length) {
@@ -456,25 +526,27 @@ export async function runAgentShortcut(options) {
456
526
  }
457
527
  async function findTask() { const fresh = await store.load(job.id); const found = fresh.tasks.find(item => item.id === task.id); if (!found)
458
528
  throw new Error('Task disappeared'); return found; }
459
- async function fallback(reason) {
460
- const safe = !effectsStarted && !shortcutModuleEntered && Object.keys(state.inFlight ?? {}).length === 0 && Object.keys(state.nodes).length === 0;
529
+ async function fail(reason) {
530
+ const timedOut = reason.includes('budget exceeded') || Date.now() >= deadlineAt;
531
+ const interrupted = options.signal?.aborted === true && !timedOut;
532
+ const failure = timedOut ? `Shortcut execution timed out after 20 minutes: ${reason}` : interrupted ? `Shortcut execution interrupted: ${reason}` : reason;
533
+ for (const nodeId of Object.keys(state.inFlight ?? {}))
534
+ emit({ nodeId, type: 'failed', data: { executionId: currentTask.executionId, reason: failure } });
461
535
  stopHeartbeat();
462
536
  const result = await transitions.apply(job.id, task.id, 'shortcut.failed', {
463
537
  eligible: (_j, t) => t.state === 'RUNNING' && t.leaseOwner === owner,
464
- facts: () => ({ shortcutEffectsSafe: safe }),
465
- mutate: (_j, t, decision) => {
466
- const workerFallback = decision.actions.includes('mutation.markShortcutWorkerFallback');
467
- const failure = workerFallback ? reason : `Shortcut stopped after possible partial effects; Troubleshooter recovery required: ${reason}`;
538
+ mutate: (_j, t) => {
468
539
  t.error = failure;
540
+ t.leaseOwner = null;
541
+ t.leaseExpiresAt = null;
542
+ t.executionId = null;
469
543
  const prior = t.result ?? { summary: 'Shortcut execution failed', data: {} };
470
- t.result = { ...prior, data: { ...(prior.data ?? {}), shortcut: { ...state, ...(workerFallback ? { workerFallback: true } : {}) } } };
544
+ t.result = { ...prior, summary: failure, data: { ...(prior.data ?? {}), shortcut: { ...state, terminal: { status: timedOut ? 'TIMED_OUT' : interrupted ? 'INTERRUPTED' : 'FAILED', reason: failure, at: new Date().toISOString(), executionId: currentTask.executionId } } } };
471
545
  },
472
546
  });
473
547
  if (!result?.decision.accepted)
474
- throw new Error(`Task lifecycle graph rejected shortcut failure: ${reason}`);
475
- const workerFallback = result.decision.actions.includes('mutation.markShortcutWorkerFallback');
476
- const failure = result.task.error ?? reason;
477
- return { outcome: { status: 'FAILED', reason: failure }, task: await findTask(), fallback: workerFallback };
548
+ throw new Error(`Task lifecycle graph rejected shortcut failure: ${failure}`);
549
+ return { outcome: { status: 'FAILED', reason: failure }, task: await findTask(), fallback: false };
478
550
  }
479
551
  }
480
552
  export function shortcutResumeEvent(_value) {
@@ -1,5 +1,6 @@
1
1
  import { join } from 'node:path';
2
2
  import { homedir } from 'node:os';
3
+ import { terminalRecoveryEligible } from './terminal-event-recovery.js';
3
4
  import { spawnOwnedProcess } from './owned-process.js';
4
5
  import { BrowserWorkerPoolManager, BrowserPoolAdmissionError } from './browser-worker-pool.js';
5
6
  import { monitorPoolDecision, progressPoolDecision } from './browser-worker-pool-graph.js';
@@ -179,8 +180,12 @@ export function pooledWebHelmRun(request, signal) {
179
180
  // after its last_used_at expires without falsely freeing the Relay slot.
180
181
  void stop().catch(() => { });
181
182
  };
183
+ const canRecoverTerminal = () => terminalRecoveryEligible({
184
+ hasSession: !!sessionId, hasThread: !!threadId, terminalObserved: false, recoveryAttempts: recoveries,
185
+ outcomeUncertain: recoveryOutcomeUncertain, cancelled: stopped || released || uncertain,
186
+ });
182
187
  const sendRecovery = async () => {
183
- if (stopped || released || uncertain || recoveryOutcomeUncertain || !sessionId || !threadId || !request.recover || recoveries >= 2)
188
+ if (!request.recover || !sessionId || !threadId || !canRecoverTerminal())
184
189
  return;
185
190
  recoveries++;
186
191
  const cfg = await request.recover(threadId);
@@ -225,7 +230,7 @@ export function pooledWebHelmRun(request, signal) {
225
230
  await request.onActivity?.('Browser Worker produced new assistant output');
226
231
  }
227
232
  const due = now - observedAt >= Math.max(request.recoveryMinMs ?? 60_000, Math.round(request.timeoutMs * .6)) &&
228
- !observation.state?.generating && !recoveryOutcomeUncertain && recoveries < 2 && !!request.recover && !!threadId;
233
+ !observation.state?.generating && canRecoverTerminal() && !!request.recover;
229
234
  if (monitorPoolDecision(due) === 'recoverTurn' && request.recover && threadId) {
230
235
  // Count before the send. An ambiguous response must never cause automatic retransmission.
231
236
  observedAt = now;
@@ -1,5 +1,6 @@
1
1
  import { eligibleWorkerCandidates, workerCandidates } from './worker-routing.js';
2
2
  import { routeExecution } from './execution-routing.js';
3
+ import { configuredCodexDefault } from './model-routing.js';
3
4
  import { eventFor } from './events.js';
4
5
  export function codexFallbackRouting(task, adapters, registered, usage) {
5
6
  const requirements = task.workerRequirements ?? { capabilities: [] };
@@ -54,3 +55,32 @@ export function persistChatGptPlatformFailure(task, original, executionId, class
54
55
  }];
55
56
  }
56
57
  }
58
+ /** One deterministic, verified configured-default Codex route for an
59
+ * unstarted failed ChatGPT/Z Worker generation. Never use catalog defaults. */
60
+ export async function codexNoStartFallbackRoute(task, adapters, registered, usage) {
61
+ if ((!['chatgpt', 'z'].includes(task.adapter) && !task.noStartFallback) || task.chatgptThreadDelivery)
62
+ return null;
63
+ const configured = await configuredCodexDefault();
64
+ if (!configured)
65
+ return null;
66
+ const requirements = task.workerRequirements ?? { capabilities: [] };
67
+ const { candidates, excludedRoutes } = codexFallbackRouting(task, adapters, registered, usage);
68
+ if (!candidates.length)
69
+ return null;
70
+ try {
71
+ const decision = await routeExecution(candidates, requirements, {
72
+ registered, usage, excludedRoutes, decisionMode: 'off',
73
+ routingConstraints: { provider: configured.provider, model: configured.model },
74
+ taskFacts: { task: { id: task.id, fallback: 'no-start' } },
75
+ });
76
+ if (decision.candidate.adapter !== 'codex'
77
+ || decision.candidate.routing.provider !== configured.provider
78
+ || decision.candidate.routing.model !== configured.model
79
+ || decision.model.profile !== undefined)
80
+ return null;
81
+ return decision;
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
package/dist/cli-help.js CHANGED
@@ -9,7 +9,7 @@ Usage:
9
9
 
10
10
  Commands:
11
11
  job create|update|show|list|run|shortcut-receipt|merge|unblock|cancel|pause|resume Manage SQLite-authoritative jobs with optional GitHub PRs
12
- task create|update|show|list|classify|complete|retry|unblock|cancel Manage durable tasks
12
+ task create|update|show|list|revise|classify|complete|retry|unblock|cancel Manage durable tasks
13
13
  review request Request graph-owned review (optional thread override)
14
14
  artifact validate Check a JSON artifact against a project-owned JSON Schema
15
15
  plan Invoke the Planner for an existing managed Job
@@ -164,13 +164,14 @@ Returns the same summary used by the dashboard header plus a running array with
164
164
  task: `Manage durable tasks.
165
165
 
166
166
  Usage:
167
- npx agents-relay task <create|update|show|events|list|retry|unblock|cancel> [options]
167
+ npx agents-relay task <create|update|show|events|list|revise|retry|unblock|cancel> [options]
168
168
 
169
169
  Actions:
170
170
  create Create one durable Task under an existing Job
171
171
  update Update mutable Task fields
172
172
  show Show one Task
173
173
  list List Tasks for a Job
174
+ revise Submit an immutable-head targeted reviewer fix request
174
175
  retry Retry a FAILED Task
175
176
  unblock Authoritatively invalidate a BLOCKED decision
176
177
  complete Complete an orchestrator-owned Task
@@ -178,7 +179,7 @@ Actions:
178
179
  'task create': `Create one durable Task under an existing Job.
179
180
 
180
181
  Required: normal Job storage options plus --input-file PATH|- (preferred) or --input MARKDOWN, and --output task-pr|file. --input and --input-file are mutually exclusive.
181
- Common: --task-id ID (optional; Relay auto-assigns a global increasing integer Task ID), --title TITLE (optional; otherwise derived from the first non-empty input line), --idempotency-key KEY, --priority P0|P1|P2|P3, --story-size S|M|L, --agent NAME, --agent-graph-file PATH|-, --deps a,b, --parent ID, --draft. Normal model-backed Tasks omit adapter/provider/model so Relay runs one Execution Router decision over complete worker+model routes. New Tasks are worker-routed; legacy adapter=orchestrator records are recovery-only and cannot be created or manually executed.\nTasks with dependencies start DRAFT; tasks without dependencies start QUEUED unless --draft is given.
182
+ Common: --task-id ID (optional; Relay auto-assigns a global increasing integer Task ID), --title TITLE (optional; otherwise derived from the first non-empty input line), --idempotency-key KEY, --priority P0|P1|P2|P3, --story-size S|M|L, --agent NAME, --agent-graph-file PATH|-, --deps a,b, --dependency-validity JSON, --parent ID, --draft. The JSON maps declared dependency Task IDs to order-only, revalidate, or rerun. Normal model-backed Tasks omit adapter/provider/model so Relay runs one Execution Router decision over complete worker+model routes. New Tasks are worker-routed; legacy adapter=orchestrator records are recovery-only and cannot be created or manually executed.\nTasks with dependencies start DRAFT; tasks without dependencies start QUEUED unless --draft is given.
182
183
  Directly-created Tasks are not wrapped in a synthetic Plan. Planner-generated Tasks are created internally by Relay from planner output.
183
184
 
184
185
  Example:
@@ -186,12 +187,17 @@ Example:
186
187
  'task update': `Update mutable durable Task fields in place.
187
188
 
188
189
  Required: --id JOB_ID --task-id ID. Optional --repo OWNER/REPO fences the Job identity.
189
- Mutable while not RUNNING/SUCCEEDED/CANCELLED: --title, --adapter, --priority, --story-size, --input-file PATH|- or --input MARKDOWN, --project, --agent, --agent-graph-file PATH|-, --parent, --deps, --capabilities, --timeout (inactivity window), --max-attempts, --provider, --model, --profile, --reasoning, --cwd, --chatgpt-project, --chatgpt-tab-close-policy, --draft, --queue.
190
+ Mutable while not RUNNING/SUCCEEDED/CANCELLED: --title, --adapter, --priority, --story-size, --input-file PATH|- or --input MARKDOWN, --project, --agent, --agent-graph-file PATH|-, --parent, --deps, --dependency-validity JSON, --capabilities, --timeout (inactivity window), --max-attempts, --provider, --model, --profile, --reasoning, --cwd, --chatgpt-project, --chatgpt-tab-close-policy, --draft, --queue.
190
191
  Accepted task.started and newer current-execution task.progress events reset --timeout.
191
192
  Use --clear-routing to remove routing metadata.
192
193
 
193
194
  Example:
194
195
  npx agents-relay task update --repo OWNER/REPO --pr 12 --id 101 --task-id build --adapter chatgpt --provider chatgpt --model gpt-5.6-sol --reasoning high`,
196
+ 'task revise': `Authenticated immutable-head targeted revision request from the active Final Reviewer.
197
+
198
+ Required: --repo OWNER/REPO --id JOB --task-id ORIGINAL --review-task-id FINAL_REVIEW --execution-id CURRENT_REVIEW_EXECUTION --head-sha EXACT_SHA --request-id STABLE_ID --findings-file PATH. The findings file contains a nonempty JSON array [{"id":"F-1","summary":"...","evidence":"..."}].
199
+
200
+ The Relay service verifies the current Reviewer generation and local Git head, atomically records immutable owner feedback and a semantic child revision. Repeating an identical request ID is idempotent; it does not finish a Reviewer or revision Task. Reviewer must subsequently report its canonical changes-required verdict.`,
195
201
  'task comment': `Append an immutable Task comment. Does not retry or change Task state.
196
202
 
197
203
  Required: --repo OWNER/REPO --id JOB_ID --task-id TASK_ID and --message TEXT or --message-file FILE.`,
@@ -1,3 +1,4 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
1
2
  import { readFile, writeFile } from 'node:fs/promises';
2
3
  import { plannerInput } from './planner.js';
3
4
  import { arg, storeFor } from './cli-support.js';
@@ -89,7 +90,7 @@ export async function runPromptCommand(args) {
89
90
  throw new Error(`Task ${taskId} not found in Job ${job.id}`);
90
91
  if (!task.executionId)
91
92
  throw new Error(`Task ${taskId} has no execution ID`);
92
- const context = await resolveExecutionContext(projectPath, task.agentName === 'troubleshooter' ? 'troubleshooter' : task.agentName === 'reviewer' ? 'reviewer' : 'worker');
93
+ const context = await resolveExecutionContext(projectPath, task.agentName === 'troubleshooter' ? 'troubleshooter' : isFinalReviewAgent(task.agentName) ? 'reviewer' : 'worker');
93
94
  prompt = await managedWorkerInput(job, { ...task, adapter }, context);
94
95
  }
95
96
  const output = arg(args, '--output');
@@ -0,0 +1,49 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { arg, relayControlCommand } from './cli-support.js';
3
+ /** Reviewer-controlled file intake; findings are structured immutable evidence. */
4
+ export function parseRevisionFindings(source) {
5
+ let value;
6
+ try {
7
+ value = JSON.parse(source);
8
+ }
9
+ catch {
10
+ throw new Error('findings-file must contain a JSON array of {id,summary,evidence?}');
11
+ }
12
+ if (!Array.isArray(value) || !value.length || value.length > 200)
13
+ throw new Error('findings-file requires 1..200 identified findings');
14
+ const findings = value.map((item, index) => {
15
+ if (!item || typeof item !== 'object' || Array.isArray(item))
16
+ throw new Error(`finding ${index} must be an object`);
17
+ const entry = item;
18
+ if (typeof entry.id !== 'string' || !entry.id.trim() || entry.id.length > 160
19
+ || typeof entry.summary !== 'string' || !entry.summary.trim() || entry.summary.length > 4000
20
+ || (entry.evidence !== undefined && (typeof entry.evidence !== 'string' || entry.evidence.length > 10000))) {
21
+ throw new Error(`finding ${index} requires valid id, summary, optional evidence`);
22
+ }
23
+ if (Object.keys(entry).some(key => !['id', 'summary', 'evidence'].includes(key)))
24
+ throw new Error(`finding ${index} contains unsupported fields`);
25
+ return { id: entry.id.trim(), summary: entry.summary.trim(), ...(typeof entry.evidence === 'string' ? { evidence: entry.evidence } : {}) };
26
+ });
27
+ if (new Set(findings.map(item => item.id)).size !== findings.length)
28
+ throw new Error('findings-file contains duplicate IDs');
29
+ return findings;
30
+ }
31
+ export async function runTaskReviseCommand(args) {
32
+ const jobId = arg(args, '--id');
33
+ const repository = arg(args, '--repo');
34
+ const taskId = arg(args, '--task-id');
35
+ const reviewTaskId = arg(args, '--review-task-id');
36
+ const reviewExecutionId = arg(args, '--execution-id');
37
+ const headSha = arg(args, '--head-sha');
38
+ const requestId = arg(args, '--request-id');
39
+ const findingsFile = arg(args, '--findings-file');
40
+ if ([jobId, repository, taskId, reviewTaskId, reviewExecutionId, headSha, requestId, findingsFile].some(value => !value || value.startsWith('--')))
41
+ throw new Error('task revise requires --repo --id --task-id --review-task-id --execution-id --head-sha --request-id --findings-file');
42
+ const findings = parseRevisionFindings(await readFile(findingsFile, 'utf8'));
43
+ const response = await relayControlCommand(args, {
44
+ command: 'task.revise', jobId, repository, taskId, reviewTaskId, reviewExecutionId, headSha, requestId, findings,
45
+ });
46
+ if (!response.request || response.request.requestId !== requestId || response.request.originalTaskId !== taskId || !response.request.revisionTaskId)
47
+ throw new Error('Relay targeted revision receipt has unexpected request or Task identity');
48
+ console.log(JSON.stringify({ status: 'durable', ...response }, null, 2));
49
+ }
@@ -0,0 +1,49 @@
1
+ import { DisabledGitHubClient } from './no-github.js';
2
+ import { ensureManagedGitHubJob } from './cli-job-create.js';
3
+ import { workerTaskFromArgs } from './cli-worker-task.js';
4
+ import { arg, hasArg, repository, storeFor, textOption } from './cli-support.js';
5
+ import { relayStoreDirectory } from './relay-store.js';
6
+ /** Private foreground shortcut bootstrap. This must never contact relayd.
7
+ * Only content-only Shortcut Jobs use this path; the conventional CLI stays
8
+ * daemon-owned. Atomic SQLite records remain authoritative for both paths. */
9
+ export async function runLocalShortcutBinding(kind, action, args) {
10
+ if (kind === 'job' && action === 'create') {
11
+ if (!hasArg(args, '--shortcut-execution') || hasArg(args, '--initial-plan'))
12
+ throw new Error('local shortcut create requires --shortcut-execution without --initial-plan');
13
+ const objective = await textOption(args, '--objective', '--objective-file');
14
+ if (!objective.trim())
15
+ throw new Error('local shortcut create requires objective');
16
+ const { job } = await ensureManagedGitHubJob(new DisabledGitHubClient(), repository(args), new Set(), {
17
+ title: arg(args, '--title') || undefined, objective,
18
+ projectPath: arg(args, '--project-path') || undefined,
19
+ executionMode: 'shortcut', storeDirectory: arg(args, '--store-dir') || relayStoreDirectory(),
20
+ noGitHub: true,
21
+ });
22
+ console.log(JSON.stringify({ repository: job.repository, job: job.id, state: job.state }));
23
+ return;
24
+ }
25
+ if (kind === 'job' && action === 'show' || kind === 'task' && action === 'list') {
26
+ const { job } = await storeFor(args);
27
+ if (job.repository !== repository(args) || job.executionMode !== 'shortcut' || job.contentOnly !== true)
28
+ throw new Error('local shortcut Job identity mismatch');
29
+ console.log(JSON.stringify(kind === 'job' ? job : job.tasks, null, 2));
30
+ return;
31
+ }
32
+ if (kind === 'task' && action === 'create') {
33
+ const { store, job, localFile } = await storeFor(args);
34
+ if (localFile !== null || !store.mutateJob || job.repository !== repository(args) || job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'DRAFT')
35
+ throw new Error('local shortcut Task creation requires a DRAFT content-only SQLite Job');
36
+ const task = await workerTaskFromArgs(job, args, new Date().toISOString());
37
+ if (task.id !== arg(args, '--task-id') || !task.agentGraph || task.output?.kind !== 'file')
38
+ throw new Error('local shortcut Task must have explicit ID, Agent Graph and file output');
39
+ await store.mutateJob(job.id, current => {
40
+ if (current.state !== 'DRAFT' || current.tasks.some(existing => existing.id === task.id))
41
+ throw new Error('local shortcut Task already exists or Job is no longer DRAFT');
42
+ current.tasks.push(structuredClone(task));
43
+ return current;
44
+ });
45
+ console.log(JSON.stringify(task, null, 2));
46
+ return;
47
+ }
48
+ throw new Error('unsupported local shortcut command; only create, show and list bindings are allowed');
49
+ }