agents-relay 2.0.247 → 2.0.249

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.
@@ -137,6 +137,7 @@ export async function buildRelayWorkPrompt(input) {
137
137
  `Task: ${input.taskId}`,
138
138
  `Execution: ${input.executionId}`,
139
139
  '', '## User Assignment',
140
+ ...(input.suggestedSkills?.length ? [`Suggested skills (optional, use only when relevant and available): ${input.suggestedSkills.join(', ')}`] : []),
140
141
  ...(input.taskTitle?.trim() ? [`Assigned ${input.agentName === 'planner' ? 'Plan' : 'Task'} title (locator): ${JSON.stringify(input.taskTitle)}`] : []),
141
142
  ...(input.agentName === 'planner' ? [
142
143
  'Read the full authoritative Plan Context through the matching Relay CLI. Apply the actual Plan, not merely its context lookup.',
@@ -138,6 +138,9 @@ async function agentFiles(root, source, skills) {
138
138
  description: fields.description || undefined,
139
139
  capabilities: listValue(fields.capabilities),
140
140
  runtime: fields.runtime || listValue(fields.runtimes)[0] || undefined,
141
+ suggestedSkills: listValue(fields.skills),
142
+ preferredModel: fields.model || undefined,
143
+ preferredReasoning: fields.reasoning || undefined,
141
144
  trustDomains: listValue(fields.trustDomains ?? fields.trust_domains ?? fields.trust),
142
145
  delegation: listValue(fields.delegation),
143
146
  restrictions: listValue(fields.restrictions ?? fields.boundaries),
@@ -203,6 +206,9 @@ export async function resolveExecutionContext(projectPath, role, options = {}) {
203
206
  description: fields.description,
204
207
  capabilities: listValue(fields.capabilities),
205
208
  runtime: fields.runtime || listValue(fields.runtimes)[0] || undefined,
209
+ suggestedSkills: listValue(fields.skills),
210
+ preferredModel: fields.model || undefined,
211
+ preferredReasoning: fields.reasoning || undefined,
206
212
  trustDomains: listValue(fields.trustDomains ?? fields.trust_domains ?? fields.trust),
207
213
  delegation: listValue(fields.delegation),
208
214
  restrictions: listValue(fields.restrictions ?? fields.boundaries),
@@ -235,6 +241,18 @@ export async function resolveExecutionContext(projectPath, role, options = {}) {
235
241
  delegation: { mode: 'relay-child-task', parentTaskIdRequired: role === 'nested-worker' },
236
242
  };
237
243
  }
244
+ /** Resolve just the selected Agent's optional model advice without scanning
245
+ * every Agent/Skill in the project before routing. This is a read-only lookup. */
246
+ export async function resolveAgentModelPreference(projectPath, agentName, options = {}) {
247
+ const workspaceRoot = await resolveWorkspaceRoot(options.workspaceRoot);
248
+ const globalRoot = configuredGlobalRoot(options.globalRoot);
249
+ const configuredSharedRoot = options.sharedRoot !== undefined ? options.sharedRoot : process.env.AGENTS_RELAY_SHARED_ROOT;
250
+ const sharedRoot = configuredSharedRoot ? resolve(configuredSharedRoot) : null;
251
+ const agent = await resolveAgentMarkdown(agentName, BUNDLED_AGENTS_ROOT, projectPath, sharedRoot, agentSourceLayers(projectPath, { workspaceRoot, globalRoot, sharedRoot }));
252
+ const model = agent.metadata.model || undefined;
253
+ const reasoning = agent.metadata.reasoning || undefined;
254
+ return model || reasoning ? { model, reasoning } : undefined;
255
+ }
238
256
  export async function resolveAgentContract(context, agentName) {
239
257
  const agent = context.agents.find(candidate => candidate.name === agentName);
240
258
  if (!agent)
@@ -2,7 +2,7 @@ import { makeExecutionDecisionAudit, recentExecutionRouteResults } from './decis
2
2
  import { discoverModelCandidates } from './model-routing.js';
3
3
  import { loadExecutionRouterRules, loadRoutingPolicy, policyAllows } from './routing-policy.js';
4
4
  import { DEFAULT_CHATGPT_PREFERRED_CONCURRENCY } from './worker-routing.js';
5
- import { appendRoutingInstruction } from './router-rules.js';
5
+ import { appendRoutingInstruction, appendAgentModelPreference } from './router-rules.js';
6
6
  export function executionTaskShape(taskFacts = {}) {
7
7
  const nestedTask = taskFacts.task && typeof taskFacts.task === 'object' ? taskFacts.task : undefined;
8
8
  const raw = taskFacts.storySize ?? nestedTask?.storySize;
@@ -324,7 +324,7 @@ export async function routeExecution(workers, requirements, options = {}) {
324
324
  },
325
325
  recent_route_results: recentRouteResults,
326
326
  }));
327
- const question = appendRoutingInstruction('User routing instructions have highest priority over default preferences, task size, runtime and resource signals. Candidate order is arbitrary and conveys no priority, ranking or preference. Do not favor earlier choices. Select an offered route that obeys the user instructions.\nUser routing instructions:\n' + routingInstruction, 'Use recent_route_results (up to the last 10 confirmed execution outcomes) to weigh route reliability, including success, failure and the recorded reason. Distinguish provider/runtime faults from task-specific failures and cancellations; historical failures are evidence, not automatic hard exclusions. For vision, image generation, visual review, and final review tasks, prefer ChatGPT Worker when available and within capacity; for coding, CLI and filesystem tasks, prefer Codex. These are soft preferences subordinate to user rules. Choose exactly one listed route; do not invent routes.');
327
+ const question = appendAgentModelPreference(appendRoutingInstruction('User routing instructions have highest priority over default preferences, task size, runtime and resource signals. Candidate order is arbitrary and conveys no priority, ranking or preference. Do not favor earlier choices. Select an offered route that obeys the user instructions.\nUser routing instructions:\n' + routingInstruction, 'Use recent_route_results (up to the last 10 confirmed execution outcomes) to weigh route reliability, including success, failure and the recorded reason. Distinguish provider/runtime faults from task-specific failures and cancellations; historical failures are evidence, not automatic hard exclusions. For vision, image generation, visual review, and final review tasks, prefer ChatGPT Worker when available and within capacity; for coding, CLI and filesystem tasks, prefer Codex. These are soft preferences subordinate to user rules. Choose exactly one listed route; do not invent routes.'), options.modelPreference);
328
328
  let selected = fallback;
329
329
  let evidence = { mode: options.decisionMode ?? 'off', fallback: true };
330
330
  const decisionStages = [];
@@ -37,6 +37,7 @@ export async function managedWorkerInput(job, task, context, mode = 'production'
37
37
  const eventProtocol = eventSkill ? join(dirname(eventSkill.path), 'references/protocol.md') : undefined;
38
38
  return buildRelayWorkPrompt({
39
39
  agentName,
40
+ suggestedSkills: selected.agent.suggestedSkills,
40
41
  agentContent: agent,
41
42
  adapter,
42
43
  contracts: [
package/dist/planner.js CHANGED
@@ -503,7 +503,7 @@ export async function buildPlannerExecutionPrompt(context, agentFile = DEFAULT_P
503
503
  if (!context.planExecution)
504
504
  throw new Error('Planner execution is missing its durable Plan and execution identity');
505
505
  const ctx = context.executionContext, selected = ctx ? await resolveAgentMarkdown('planner', BUNDLED_AGENTS_ROOT, ctx.project.path, ctx.project.sharedRoot, agentSourceLayers(ctx.project.path, ctx.project)) : undefined;
506
- return buildRelayWorkPrompt({ agentName: 'planner', agentContent: selected?.content ?? await readFile(agentFile, 'utf8'), adapter,
506
+ return buildRelayWorkPrompt({ agentName: 'planner', agentContent: selected?.content ?? await readFile(agentFile, 'utf8'), suggestedSkills: ctx?.agents.find(agent => agent.name === 'planner')?.suggestedSkills, adapter,
507
507
  contracts: [join(dirname(fileURLToPath(import.meta.url)), '..', 'skills/agents-relay/contracts/task-job-contract.md'),
508
508
  join(dirname(fileURLToPath(import.meta.url)), '..', 'skills/agents-relay/contracts/blocker-job-recovery.md'),
509
509
  ...(ctx?.skills.find(skill => skill.name === 'ponytail')?.path ? [ctx.skills.find(skill => skill.name === 'ponytail').path] : [])],
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;
@@ -1,4 +1,23 @@
1
- import { resolveExecutionContext } from './execution-context.js';
1
+ import { resolveExecutionContext, resolveAgentModelPreference } from './execution-context.js';
2
+ /**
3
+ * Agent model guidance is advisory. A missing/malformed Agent or unavailable
4
+ * context must never turn a previously routable Task into a routing failure.
5
+ */
6
+ export async function agentModelPreferenceForJob(options, job, agentName, task) {
7
+ if (!agentName)
8
+ return undefined;
9
+ try {
10
+ // Do not call projectPathForJob here: production providers may create a
11
+ // worktree or mutate Job state when that execution locator is evaluated.
12
+ const projectPath = options.agentPreferenceContextPathForJob
13
+ ? await options.agentPreferenceContextPathForJob(job, task)
14
+ : task?.routing?.cwd;
15
+ return projectPath ? await resolveAgentModelPreference(projectPath, agentName, options.executionContextRoots ?? {}) : undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
2
21
  export async function resolveTaskContext(store, options, job, task, role, projectPathOverride) {
3
22
  const projectPath = projectPathOverride ?? (options.projectPathForJob ? await options.projectPathForJob(job) : task.routing?.cwd ?? process.cwd());
4
23
  return resolveExecutionContext(projectPath, role, {
@@ -21,6 +21,7 @@ import { reviewGenerationMatches } from './review-generation-fence.js';
21
21
  import { targetedRequestsForReview, targetedRequestsCoverReview } from './review-revision-model.js';
22
22
  import { reviewFindingFingerprint } from './review-revision-policy.js';
23
23
  import { codexNoStartFallbackRoute, quarantineUnavailableCodexFallback } from './chatgpt-platform-fallback.js';
24
+ import { agentModelPreferenceForJob } from './reconciler-context.js';
24
25
  export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
25
26
  async currentHeadSha(job) {
26
27
  // Tests may replace the external Git effect entirely; in that case its
@@ -108,7 +109,7 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
108
109
  const now = new Date().toISOString();
109
110
  const reviewGateTasks = implementationTasks(job);
110
111
  const reviewThread = resolveReviewerThreadDestination(job, this.options.reviewer?.threadId);
111
- const reviewerRouting = await this.selectReviewer(reviewGateTasks, reviewThread ? chatgptThreadRequirements(this.options.reviewer?.requirements) : undefined);
112
+ const reviewerRouting = await this.selectReviewer(reviewGateTasks, reviewThread ? chatgptThreadRequirements(this.options.reviewer?.requirements) : undefined, job);
112
113
  const chatgptThreadDelivery = prepareReviewerThreadDelivery(job, {
113
114
  id, agentName: FINAL_REVIEW_AGENT, reviewHeadSha: headSha, routing: reviewerRouting.candidate.routing,
114
115
  }, this.options.reviewer?.threadId);
@@ -190,7 +191,7 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
190
191
  const ready = refreshTaskDependencies(await this.store.load(job.id));
191
192
  await this.store.saveJob(ready);
192
193
  }
193
- async selectReviewer(implementationTasks, requirementsOverride) {
194
+ async selectReviewer(implementationTasks, requirementsOverride, job) {
194
195
  const configured = this.options.reviewer;
195
196
  const registered = await this.store.listAgents();
196
197
  const usage = this.options.usageSnapshotProvider ? await this.options.usageSnapshotProvider() : undefined;
@@ -230,6 +231,7 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
230
231
  decisionEngine: this.options.decisionEngine,
231
232
  decisionMode: this.options.decisionMode,
232
233
  taskFacts,
234
+ modelPreference: job ? await agentModelPreferenceForJob(this.options, job, FINAL_REVIEW_AGENT) : undefined,
233
235
  usage,
234
236
  registered,
235
237
  chatgptRunning: runtimeSummary?.chatgptRunning ?? 0,
@@ -294,6 +296,7 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
294
296
  decisionEngine: this.options.decisionEngine,
295
297
  decisionMode: this.options.decisionMode,
296
298
  taskFacts: { ...taskFacts, recovery: task.recoveryContext ?? null, recovery_parent_failed_route: excludedRoutes[0] ?? null },
299
+ modelPreference: await agentModelPreferenceForJob(this.options, job, task.agentName ?? 'implementation', task),
297
300
  usage,
298
301
  registered,
299
302
  chatgptRunning: runtimeSummary?.chatgptRunning ?? 0,
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';
@@ -156,7 +156,7 @@ export async function runDaemon(argv) {
156
156
  return limitHistory ? dashboardManagedJobs(visible) : visible;
157
157
  };
158
158
  cachedOverviews = await inventoryFromLocal();
159
- const makeReconciler = (store, maxConcurrent) => new Reconciler(store, { noGitHub, owner: `relayd-${process.pid}`, maxConcurrent, leaseMs: Number(value(argv, '--lease-ms', '300000')), adapters: [new CodexAdapter(value(argv, '--codex', 'codex')), new ChatGptAdapter(), new ZAdapter()], continuations: [new CodexThreadContinuation(value(argv, '--codex', 'codex')), new CommandContinuation(), new WebhookContinuation()], planner: runtimePlanner(argv), usageSnapshotProvider: () => usageRegistry.snapshot(), runtimeSummaryProvider: () => ({ chatgptRunning: summarizeRuntime(cachedOverviews.map(item => item.job)).workers.chatgpt }), decisionEngine: executionDecisionEngine(), decisionMode: decisionMode(), decisionAuditStore, eventBus: bus, escalationNotifier: escalationNotifierFromEnvironment(), reviewer: runtimeReviewer(argv), executionContextRoots: { workspaceRoot }, projectPathForJob: async (job, task) => {
159
+ const makeReconciler = (store, maxConcurrent) => new Reconciler(store, { noGitHub, owner: `relayd-${process.pid}`, maxConcurrent, leaseMs: Number(value(argv, '--lease-ms', '300000')), adapters: [new CodexAdapter(value(argv, '--codex', 'codex')), new ChatGptAdapter(), new ZAdapter()], continuations: [new CodexThreadContinuation(value(argv, '--codex', 'codex')), new CommandContinuation(), new WebhookContinuation()], planner: runtimePlanner(argv), usageSnapshotProvider: () => usageRegistry.snapshot(), runtimeSummaryProvider: () => ({ chatgptRunning: summarizeRuntime(cachedOverviews.map(item => item.job)).workers.chatgpt }), decisionEngine: executionDecisionEngine(), decisionMode: decisionMode(), decisionAuditStore, eventBus: bus, escalationNotifier: escalationNotifierFromEnvironment(), reviewer: runtimeReviewer(argv), executionContextRoots: { workspaceRoot }, agentPreferenceContextPathForJob: async (job) => resolveRepositoryProjectPath(repositoryPaths.get(job.repository) ?? await resolveManagedProjectPath(job.repository, explicitProjectPath, workspaceRoot), job.projectPath), projectPathForJob: async (job, task) => {
160
160
  const canonical = repositoryPaths.get(job.repository) ?? await resolveManagedProjectPath(job.repository, explicitProjectPath, workspaceRoot);
161
161
  if (!(task ? taskRequiresManagedWorktree(job, task) : Boolean(job.localMerge?.sourceRef)))
162
162
  return resolveRepositoryProjectPath(canonical, job.projectPath);
@@ -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();
@@ -66,6 +66,17 @@ export function appendRoutingInstruction(question, instruction) {
66
66
  return question;
67
67
  return question + '\n\n' + instruction;
68
68
  }
69
+ /** Optional Agent metadata belongs to Router advice, not candidate discovery. */
70
+ export function appendAgentModelPreference(question, preference) {
71
+ if (!preference?.model && !preference?.reasoning)
72
+ return question;
73
+ return appendRoutingInstruction(question, [
74
+ 'Agent model preference (advisory only; lower priority than user routing instructions and all hard constraints):',
75
+ ...(preference.model ? [`Prefer model: ${preference.model}`] : []),
76
+ ...(preference.reasoning ? [`Prefer reasoning: ${preference.reasoning}`] : []),
77
+ 'Choose only among the existing eligible routes. Do not invent or enable a route to satisfy this preference.',
78
+ ].join('\n'));
79
+ }
69
80
  export function parseRouterRules(text) {
70
81
  const choices = [];
71
82
  const seen = new Set();
@@ -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.249",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,6 +31,8 @@ Read `contracts/task-job-contract.md` before authoring or changing Jobs or Tasks
31
31
 
32
32
  Usually let `job create --initial-plan` establish the first Planner round; use `plan` for an existing create-only Job. Direct `task create` is for deliberately orchestrator-authored work. Tasks describe verifiable outcomes, **not shell commands**. Declare exactly one durable result (`task_pr` or `file`), meaningful dependencies, and `storySize`; Relay chooses worker/model routes unless the task truly needs a specific capability.
33
33
 
34
+ Agent frontmatter `skills` suggests Worker skills; `model` and `reasoning` suggest a Router preference. None are mandatory.
35
+
34
36
  An assigned **execution Prompt** pins a specific Skill version and supplies Role, Bootstrap, Contracts, Contexts, and Task/Plan identity. Preserve these references. Resolve the matching CLI as `../../dist/cli.js` relative to the pinned Skill directory; do **not** substitute an unrelated globally installed CLI. Before acting, load the exact execution-bound context:
35
37
 
36
38
  ```sh
@@ -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
- }