agents-relay 2.0.255 → 2.0.257
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/README.md +26 -13
- package/dist/agent-script-discovery.js +56 -0
- package/dist/cli-coordinator.js +71 -0
- package/dist/cli-help.js +36 -30
- package/dist/cli-job-create.js +37 -4
- package/dist/cli.js +21 -12
- package/dist/dag-result-contract.js +2 -2
- package/dist/{shortcut-stage-contract.js → dag-stage-contract.js} +1 -1
- package/dist/dag-task-runtime.js +4 -33
- package/dist/dashboard-jel.js +8 -12
- package/dist/job-execution-slot.js +3 -11
- package/dist/pool.js +28 -15
- package/dist/reconciler.js +5 -28
- package/dist/relay-job-snapshot-reads.js +2 -5
- package/dist/relay-workflow-operations.js +2 -3
- package/dist/relayd-control.js +5 -0
- package/dist/relayd.js +1 -3
- package/dist/runtime-status.js +0 -33
- package/dist/script-task-adapter.js +2 -2
- package/dist/task-inactivity-watchdog.js +3 -6
- package/dist/worker-failure-recovery.js +1 -1
- package/dist/workflow/action-ledger.js +1 -1
- package/dist/workflow/contracts.js +0 -28
- package/dist/workflow/definitions-v2.js +1 -8
- package/dist/workflow/runtime.js +0 -9
- package/package.json +6 -6
- package/skills/agents-relay/SKILL.md +41 -14
- package/skills/agents-relay/contracts/event-contract.md +4 -5
- package/skills/agents-relay/contracts/task-job-contract.md +35 -1
- package/workflow/job-lifecycle.mmd +0 -8
- package/workflow/task-lifecycle.mmd +1 -26
- package/dist/agent-shortcut.js +0 -587
- package/dist/cli-shortcut-local.js +0 -50
- package/dist/cli-shortcut.js +0 -267
- package/dist/reconciler-shortcut.js +0 -74
- package/dist/shortcut-node-revision.js +0 -21
- package/dist/shortcut-node-worker.js +0 -144
- package/dist/shortcut-review-wake.js +0 -64
- package/dist/shortcut-worker-runner.js +0 -64
package/dist/cli-shortcut.js
DELETED
|
@@ -1,267 +0,0 @@
|
|
|
1
|
-
import { createHash } from 'node:crypto';
|
|
2
|
-
import { readFile } from 'node:fs/promises';
|
|
3
|
-
import { missingShortcutNodes, recordShortcutReceipt, runAgentShortcut, shortcutResumeEvent } from './agent-shortcut.js';
|
|
4
|
-
import { parseAgentGraph } from './agent-graph.js';
|
|
5
|
-
import { tryTransitionTaskEvent } from './task-transitions.js';
|
|
6
|
-
import { dispatchJobLifecycleSync } from './workflow/lifecycle.js';
|
|
7
|
-
import { runShortcutModelNode } from './shortcut-node-worker.js';
|
|
8
|
-
import { noGitHubMode } from './no-github.js';
|
|
9
|
-
import { resolveManagedProjectPath, resolveRepositoryProjectPath, resolveWorkspaceRoot } from './workspace.js';
|
|
10
|
-
import { arg, hasArg, integerArg, publishWake, saveLocal, storeFor, textOption, withEventBus } from './cli-support.js';
|
|
11
|
-
function assertSqliteShortcutArgs(args) {
|
|
12
|
-
if (args.some(value => value === '--file' || value.startsWith('--file=')))
|
|
13
|
-
throw new Error('Shortcut commands require the authoritative SQLite Relay store; --file is unsupported');
|
|
14
|
-
}
|
|
15
|
-
/** Apply the canonical Job Graph activate edge before the first direct run.
|
|
16
|
-
* The Job is created DRAFT so creation alone cannot launch any work. */
|
|
17
|
-
export async function activateShortcutJobForDirectRun(store, jobId) {
|
|
18
|
-
if (!store.mutateJob)
|
|
19
|
-
throw new Error('Shortcut activation requires atomic SQLite Job mutation');
|
|
20
|
-
await store.mutateJob(jobId, current => {
|
|
21
|
-
if (current.executionMode !== 'shortcut' || current.contentOnly !== true)
|
|
22
|
-
throw new Error('Only a content-only Shortcut Job may be activated by direct run');
|
|
23
|
-
if (current.state === 'DRAFT') {
|
|
24
|
-
const decision = dispatchJobLifecycleSync(current, 'activate');
|
|
25
|
-
if (!decision.accepted || decision.target !== 'ACTIVE')
|
|
26
|
-
throw new Error('Job Lifecycle graph rejected shortcut activation');
|
|
27
|
-
}
|
|
28
|
-
else if (current.state !== 'ACTIVE') {
|
|
29
|
-
throw new Error(`Shortcut Job ${jobId} is not runnable (${current.state})`);
|
|
30
|
-
}
|
|
31
|
-
return current;
|
|
32
|
-
});
|
|
33
|
-
}
|
|
34
|
-
export async function runShortcutJobCommand(args, id, makeRunner) {
|
|
35
|
-
assertSqliteShortcutArgs(args);
|
|
36
|
-
if (arg(args, '--mode') && arg(args, '--mode') !== 'shortcut')
|
|
37
|
-
throw new Error('job run no longer selects an execution mode');
|
|
38
|
-
const loaded = await storeFor(args, false, true);
|
|
39
|
-
if (loaded.localFile !== null || !loaded.store.mutateJob || !loaded.store.reserveWorkflowLaunch)
|
|
40
|
-
throw new Error('Shortcut execution requires the authoritative SQLite Relay store');
|
|
41
|
-
const job = loaded.job;
|
|
42
|
-
// An explicit graph start is an ordinary Job activation. Historical in-flight
|
|
43
|
-
// direct Shortcut checkpoints alone continue through the archived runner below.
|
|
44
|
-
const taskId = arg(args, '--task-id');
|
|
45
|
-
if (!taskId)
|
|
46
|
-
throw new Error('job run requires --task-id');
|
|
47
|
-
let task = job.tasks.find(item => item.id === taskId);
|
|
48
|
-
if (!task)
|
|
49
|
-
throw new Error(`Task ${taskId} not found`);
|
|
50
|
-
const legacy = hasArg(args, '--legacy-shortcut-runtime') || Boolean(task.result?.data?.shortcut);
|
|
51
|
-
if (!legacy) {
|
|
52
|
-
if (hasArg(args, '--event-json'))
|
|
53
|
-
throw new Error('Normal Job activation does not accept a Shortcut runner event');
|
|
54
|
-
const graphOverride = hasArg(args, '--agent-graph-file') ? await textOption(args, '--agent-graph', '--agent-graph-file') : undefined;
|
|
55
|
-
if (graphOverride)
|
|
56
|
-
parseAgentGraph(graphOverride);
|
|
57
|
-
const effectiveGraph = task.agentGraph ?? graphOverride;
|
|
58
|
-
if (!effectiveGraph)
|
|
59
|
-
throw new Error('job run requires a Task with an Agent Graph');
|
|
60
|
-
const workspaceRoot = await resolveWorkspaceRoot(arg(args, '--workspace-root') || undefined);
|
|
61
|
-
const projectRoot = await resolveManagedProjectPath(noGitHubMode(args) ? undefined : job.repository, arg(args, '--project-path') || job.projectPath || '', workspaceRoot);
|
|
62
|
-
const projectPath = resolveRepositoryProjectPath(projectRoot, job.projectPath);
|
|
63
|
-
const globalRoot = arg(args, '--global-root') || process.env.AGENTS_HOME || undefined;
|
|
64
|
-
const sharedRoot = arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined;
|
|
65
|
-
await loaded.store.mutateJob(id, current => {
|
|
66
|
-
const root = current.tasks.find(t => t.id === taskId);
|
|
67
|
-
if (!root)
|
|
68
|
-
throw Error('Graph Task disappeared');
|
|
69
|
-
if (root.agentGraph && root.agentGraph !== effectiveGraph)
|
|
70
|
-
throw Error('Graph Task changed since activation');
|
|
71
|
-
if (root.state !== 'QUEUED' && root.state !== 'RUNNING' && root.state !== 'DRAFT')
|
|
72
|
-
throw Error('Graph Task is not startable: ' + root.state);
|
|
73
|
-
if (!root.agentGraph) {
|
|
74
|
-
if (root.state !== 'QUEUED' && root.state !== 'DRAFT')
|
|
75
|
-
throw Error('Graph cannot be replaced after Task started');
|
|
76
|
-
root.agentGraph = effectiveGraph;
|
|
77
|
-
}
|
|
78
|
-
if (root.state === 'DRAFT') {
|
|
79
|
-
if (root.dependencies.length)
|
|
80
|
-
throw Error('Graph root has unmet dependencies');
|
|
81
|
-
const queued = tryTransitionTaskEvent(root, 'queue', { dependenciesSatisfied: true });
|
|
82
|
-
if (!queued.accepted || queued.target !== 'QUEUED')
|
|
83
|
-
throw Error('Task Lifecycle rejected Graph root queue');
|
|
84
|
-
}
|
|
85
|
-
const ctx = { projectPath, workspaceRoot, ...(sharedRoot ? { sharedRoot } : {}), ...(globalRoot ? { globalRoot } : {}), noGitHub: noGitHubMode(args) };
|
|
86
|
-
const existing = current.graphStartContext;
|
|
87
|
-
if (existing && ['projectPath', 'workspaceRoot', 'sharedRoot', 'globalRoot', 'noGitHub'].some(k => existing[k] !== ctx[k]))
|
|
88
|
-
throw Error('Graph start context changed from first authorized invocation');
|
|
89
|
-
if (!existing)
|
|
90
|
-
current.graphStartContext = ctx;
|
|
91
|
-
if (current.state === 'DRAFT') {
|
|
92
|
-
const decision = dispatchJobLifecycleSync(current, 'activate');
|
|
93
|
-
if (!decision.accepted || decision.target !== 'ACTIVE')
|
|
94
|
-
throw Error('Job Lifecycle rejected activation');
|
|
95
|
-
}
|
|
96
|
-
else if (current.state !== 'ACTIVE')
|
|
97
|
-
throw Error('Job is not runnable: ' + current.state);
|
|
98
|
-
return current;
|
|
99
|
-
});
|
|
100
|
-
const scheduled = await loaded.store.load(id);
|
|
101
|
-
await withEventBus(args, bus => publishWake(bus, scheduled, taskId, 'Graph Job activated; ordinary Scheduler owns execution'));
|
|
102
|
-
console.log(JSON.stringify({ jobId: id, taskId, scheduled: true, state: scheduled.state, graphRuntime: 'tasks',
|
|
103
|
-
message: 'Job activated; Relay Scheduler owns DAG Tasks, Reviews and recovery' }, null, 2));
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
if (job.executionMode !== 'shortcut' || job.contentOnly !== true)
|
|
107
|
-
throw new Error('Legacy Shortcut runner requires its original archived Job policy');
|
|
108
|
-
if (hasArg(args, '--event-json'))
|
|
109
|
-
shortcutResumeEvent(arg(args, '--event-json'));
|
|
110
|
-
if (!task.agentGraph && !hasArg(args, '--agent-graph-file'))
|
|
111
|
-
throw new Error(`Task ${taskId} has no Agent Graph; set it on the Task or pass --agent-graph-file`);
|
|
112
|
-
let resumeReceiptSelected = false;
|
|
113
|
-
if (task.state === 'RUNNING' && task.leaseOwner === null && task.executionId !== null) {
|
|
114
|
-
const checkpoint = task.result?.data?.shortcut;
|
|
115
|
-
if (Object.keys(checkpoint?.receipts ?? {}).length > 0) {
|
|
116
|
-
const decision = tryTransitionTaskEvent(task, 'shortcut.result', { shortcutResultCorrelated: true });
|
|
117
|
-
if (!decision.accepted || !decision.actions.includes('effect.resumeShortcut'))
|
|
118
|
-
throw new Error('Task Lifecycle graph did not select direct receipt resumption');
|
|
119
|
-
resumeReceiptSelected = true;
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
const graphOverride = hasArg(args, '--agent-graph-file') ? await textOption(args, '--agent-graph', '--agent-graph-file') : undefined;
|
|
123
|
-
if (graphOverride) {
|
|
124
|
-
parseAgentGraph(graphOverride);
|
|
125
|
-
if (!loaded.store.mutateJob)
|
|
126
|
-
throw new Error('Persisting an Agent Graph override requires atomic SQLite mutation');
|
|
127
|
-
await loaded.store.mutateJob(id, current => {
|
|
128
|
-
const durable = current.tasks.find(item => item.id === taskId);
|
|
129
|
-
if (!durable)
|
|
130
|
-
throw new Error(`Task ${taskId} not found`);
|
|
131
|
-
if (durable.agentGraph && durable.agentGraph !== graphOverride)
|
|
132
|
-
throw new Error('Cannot replace a durable Task Agent Graph');
|
|
133
|
-
if (!durable.agentGraph && durable.state !== 'QUEUED')
|
|
134
|
-
throw new Error('Agent Graph must be persisted before Task execution starts');
|
|
135
|
-
durable.agentGraph = graphOverride;
|
|
136
|
-
return current;
|
|
137
|
-
});
|
|
138
|
-
loaded.job = await loaded.store.load(id);
|
|
139
|
-
task = loaded.job.tasks.find(item => item.id === taskId);
|
|
140
|
-
if (!task)
|
|
141
|
-
throw new Error(`Task ${taskId} disappeared`);
|
|
142
|
-
}
|
|
143
|
-
await activateShortcutJobForDirectRun(loaded.store, id);
|
|
144
|
-
loaded.job = await loaded.store.load(id);
|
|
145
|
-
const workspaceRoot = await resolveWorkspaceRoot(arg(args, '--workspace-root') || undefined);
|
|
146
|
-
const projectRoot = await resolveManagedProjectPath(noGitHubMode(args) ? undefined : loaded.job.repository, arg(args, '--project-path') || loaded.job.projectPath || '', workspaceRoot);
|
|
147
|
-
const projectPath = resolveRepositoryProjectPath(projectRoot, loaded.job.projectPath);
|
|
148
|
-
const globalRoot = arg(args, '--global-root') || process.env.AGENTS_HOME || undefined;
|
|
149
|
-
const sharedRoot = arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined;
|
|
150
|
-
// The first trusted *explicit* invocation binds only resolved directories,
|
|
151
|
-
// not a command. Daemon recovery must never guess a Project path or execute
|
|
152
|
-
// argv serialized by an untrusted Task.
|
|
153
|
-
if (!loaded.store.mutateJob)
|
|
154
|
-
throw new Error('Shortcut Runner requires atomic context binding');
|
|
155
|
-
await loaded.store.mutateJob(id, current => {
|
|
156
|
-
if (current.executionMode !== 'shortcut' || current.state !== 'ACTIVE')
|
|
157
|
-
throw Error('Cannot bind context to an inactive Shortcut');
|
|
158
|
-
const ctx = { projectPath, workspaceRoot, ...(sharedRoot ? { sharedRoot } : {}), ...(globalRoot ? { globalRoot } : {}), noGitHub: noGitHubMode(args) };
|
|
159
|
-
const old = current.shortcutRunnerContext;
|
|
160
|
-
if (old && (old.projectPath !== ctx.projectPath || old.workspaceRoot !== ctx.workspaceRoot ||
|
|
161
|
-
old.sharedRoot !== ctx.sharedRoot || old.globalRoot !== ctx.globalRoot || old.noGitHub !== ctx.noGitHub))
|
|
162
|
-
throw Error('Shortcut context changed from its original trusted launch; refusing inconsistent resume');
|
|
163
|
-
if (!old)
|
|
164
|
-
current.shortcutRunnerContext = ctx;
|
|
165
|
-
return current;
|
|
166
|
-
});
|
|
167
|
-
// Shortcut is an explicit activation point, not a separate Task engine.
|
|
168
|
-
// Previously launched, in-flight Shortcut checkpoints retain their legacy
|
|
169
|
-
// foreground owner; new Jobs use the ordinary Reconciler/DAG Task path.
|
|
170
|
-
const oldCheckpoint = task.result?.data?.shortcut;
|
|
171
|
-
const dagCheckpoint = task.result?.data?.dag;
|
|
172
|
-
const unified = dagCheckpoint?.version === 1 || (!hasArg(args, '--legacy-shortcut-runtime') && !oldCheckpoint && !job.shortcutExecutionStartedAt);
|
|
173
|
-
if (unified) {
|
|
174
|
-
if (!loaded.store.mutateJob)
|
|
175
|
-
throw Error('Unified DAG activation requires SQLite');
|
|
176
|
-
const hash = createHash('sha256').update(task.agentGraph).digest('hex');
|
|
177
|
-
await loaded.store.mutateJob(id, current => {
|
|
178
|
-
const root = current.tasks.find(t => t.id === taskId);
|
|
179
|
-
if (current.state !== 'ACTIVE' || !root || !root.agentGraph || root.agentGraph !== task.agentGraph)
|
|
180
|
-
throw Error('DAG activation Task identity changed');
|
|
181
|
-
if (root.state !== 'QUEUED' && root.state !== 'RUNNING')
|
|
182
|
-
throw Error('DAG Task cannot start from ' + root.state);
|
|
183
|
-
const prior = root.result?.data?.dag;
|
|
184
|
-
if (prior && (prior.version !== 1 || prior.graphHash !== hash))
|
|
185
|
-
throw Error('DAG runtime identity changed');
|
|
186
|
-
if (!prior)
|
|
187
|
-
root.result = { summary: 'DAG ready', data: { ...(root.result?.data ?? {}), dag: { version: 1, graphHash: hash } } };
|
|
188
|
-
if (!current.shortcutExecutionStartedAt)
|
|
189
|
-
current.shortcutExecutionStartedAt = new Date().toISOString();
|
|
190
|
-
return current;
|
|
191
|
-
});
|
|
192
|
-
const scheduled = await loaded.store.load(id);
|
|
193
|
-
await withEventBus(args, bus => publishWake(bus, scheduled, taskId, 'Shortcut DAG activation (normal Task scheduler)'));
|
|
194
|
-
console.log(JSON.stringify({ jobId: id, taskId, mode: 'shortcut', scheduled: true, state: scheduled.state,
|
|
195
|
-
graphRuntime: 'tasks', message: 'Task scheduling and Review are owned by the ordinary Relay Reconciler' }, null, 2));
|
|
196
|
-
return;
|
|
197
|
-
}
|
|
198
|
-
const missing = await missingShortcutNodes(task.agentGraph, projectPath, sharedRoot, workspaceRoot, globalRoot);
|
|
199
|
-
const previous = task.result?.data?.shortcut;
|
|
200
|
-
if (previous?.workerFallback === true)
|
|
201
|
-
throw new Error('Legacy whole-Graph Worker fallback is not compatible with per-node Shortcut execution; retain its original recovery ownership');
|
|
202
|
-
const controller = new AbortController();
|
|
203
|
-
const onInterrupt = () => controller.abort(new Error('Interrupted by operator'));
|
|
204
|
-
process.once('SIGINT', onInterrupt);
|
|
205
|
-
process.once('SIGTERM', onInterrupt);
|
|
206
|
-
const execute = async (bus) => {
|
|
207
|
-
const hasSemanticRevision = task?.state === 'QUEUED' && task.interactiveInvocation?.status === 'changes_requested' &&
|
|
208
|
-
Boolean(task.interactiveInvocation.decidedAt) &&
|
|
209
|
-
Object.values(task.result?.data?.shortcut?.inFlight ?? {}).includes(task.interactiveInvocation.executionId);
|
|
210
|
-
const workerReconciler = (missing.length || hasSemanticRevision) && bus && makeRunner ? makeRunner(loaded.store, bus) : undefined;
|
|
211
|
-
const unwatch = workerReconciler ? await workerReconciler.watch(id) : undefined;
|
|
212
|
-
try {
|
|
213
|
-
const result = await runAgentShortcut({ store: loaded.store, job: loaded.job, task, projectPath,
|
|
214
|
-
sharedRoot,
|
|
215
|
-
workspaceRoot, globalRoot,
|
|
216
|
-
concurrency: integerArg(args, '--concurrency', 4), signal: controller.signal,
|
|
217
|
-
...(resumeReceiptSelected ? { resumeReceiptSelected: true } : {}),
|
|
218
|
-
...((missing.length || hasSemanticRevision) ? { runModelNode: node => {
|
|
219
|
-
if (!workerReconciler)
|
|
220
|
-
throw new Error('Model-backed node requires a reachable EventBus and existing Relay Worker Adapter');
|
|
221
|
-
return runShortcutModelNode({ store: loaded.store, reconciler: workerReconciler, jobId: id, parentTaskId: task.id, node });
|
|
222
|
-
} } : {}),
|
|
223
|
-
onNodeEvent: event => process.stderr.write(`shortcut.node ${JSON.stringify(event)}\n`) });
|
|
224
|
-
console.log(JSON.stringify({ outcome: result.outcome, fallbackQueued: false, task: result.task }, null, 2));
|
|
225
|
-
if (result.outcome.status === 'FAILED') {
|
|
226
|
-
const checkpoint = result.task.result?.data?.shortcut;
|
|
227
|
-
process.exitCode = checkpoint?.terminal?.status === 'TIMED_OUT' ? 4 : checkpoint?.terminal?.status === 'INTERRUPTED' ? 5 : 1;
|
|
228
|
-
}
|
|
229
|
-
else if (result.outcome.status === 'WAITING_EVENT' || result.outcome.status === 'WAITING_REVIEW')
|
|
230
|
-
process.exitCode = 3;
|
|
231
|
-
}
|
|
232
|
-
finally {
|
|
233
|
-
await unwatch?.();
|
|
234
|
-
await workerReconciler?.close();
|
|
235
|
-
}
|
|
236
|
-
};
|
|
237
|
-
try {
|
|
238
|
-
if (missing.length || (task?.state === 'QUEUED' && task.interactiveInvocation?.status === 'changes_requested' && Boolean(task.interactiveInvocation.decidedAt)))
|
|
239
|
-
await withEventBus(args, execute);
|
|
240
|
-
else
|
|
241
|
-
await execute(undefined);
|
|
242
|
-
}
|
|
243
|
-
finally {
|
|
244
|
-
process.removeListener('SIGINT', onInterrupt);
|
|
245
|
-
process.removeListener('SIGTERM', onInterrupt);
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
export async function recordShortcutReceiptCommand(args, id) {
|
|
249
|
-
assertSqliteShortcutArgs(args);
|
|
250
|
-
const taskId = arg(args, '--task-id'), nodeId = arg(args, '--node-id'), waitId = arg(args, '--wait-id');
|
|
251
|
-
const revision = arg(args, '--revision'), executionId = arg(args, '--execution-id'), outputFile = arg(args, '--output-file');
|
|
252
|
-
const contentSha256 = arg(args, '--content-sha256');
|
|
253
|
-
if (!taskId || !nodeId || !waitId || !revision || !executionId || !outputFile || !contentSha256)
|
|
254
|
-
throw new Error('job shortcut-receipt requires --task-id --node-id --wait-id --revision --execution-id --output-file --content-sha256');
|
|
255
|
-
if (outputFile === '-')
|
|
256
|
-
throw new Error('--output-file requires a local file path');
|
|
257
|
-
const { store, localFile } = await storeFor(args, false, true);
|
|
258
|
-
if (localFile !== null || !store.mutateJob || !store.reserveWorkflowLaunch)
|
|
259
|
-
throw new Error('Shortcut receipts require the authoritative SQLite Relay store');
|
|
260
|
-
const bytes = await readFile(outputFile);
|
|
261
|
-
const output = JSON.parse(bytes.toString('utf8'));
|
|
262
|
-
const receipt = await recordShortcutReceipt(store, { jobId: id, taskId, nodeId, waitId, revision, executionId, contentSha256, output });
|
|
263
|
-
const updated = await store.load(id);
|
|
264
|
-
await saveLocal(localFile, updated);
|
|
265
|
-
await withEventBus(args, bus => publishWake(bus, updated, taskId, 'Shortcut receipt recorded in Relay SQLite'));
|
|
266
|
-
console.log(JSON.stringify({ receipt: { ...receipt, output: undefined }, jobId: id, taskId }, null, 2));
|
|
267
|
-
}
|
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
import { eventFor } from './events.js';
|
|
2
|
-
import { runAgentShortcut } from './agent-shortcut.js';
|
|
3
|
-
import { applyTaskRetryAction } from './task-actions.js';
|
|
4
|
-
import { resolveExecutionContext } from './execution-context.js';
|
|
5
|
-
async function executeShortcut(store, options, job, task, emit) {
|
|
6
|
-
const projectPath = options.projectPathForJob ? await options.projectPathForJob(job, task) : task.routing?.cwd ?? process.cwd();
|
|
7
|
-
const context = await resolveExecutionContext(projectPath, 'worker', options.executionContextRoots ?? {});
|
|
8
|
-
const result = await runAgentShortcut({ store, job, task, projectPath, sharedRoot: context.project.sharedRoot ?? undefined, workspaceRoot: context.project.workspaceRoot, globalRoot: context.project.globalRoot, concurrency: options.maxConcurrent,
|
|
9
|
-
...(task.state === 'RUNNING' && task.leaseOwner === null ? { resumeReceiptSelected: true } : {}) });
|
|
10
|
-
if (result.fallback) {
|
|
11
|
-
await applyTaskRetryAction(result.task);
|
|
12
|
-
await store.saveTask(result.task);
|
|
13
|
-
}
|
|
14
|
-
else if (result.outcome.status === 'FAILED') {
|
|
15
|
-
const message = 'Shortcut stopped after possible effects; reconcile its durable Troubleshooter recovery';
|
|
16
|
-
await emit(eventFor(job.id, task.id, task.parentTaskId, 'job.wake', 'queued', message, 'orchestrator', { failureReason: 'shortcut_requires_recovery' }));
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
export async function launchShortcutEffect(store, options, jobId, taskId, emit) {
|
|
20
|
-
if (!taskId)
|
|
21
|
-
throw new Error('Shortcut launch requires a Task ID');
|
|
22
|
-
const job = await store.load(jobId);
|
|
23
|
-
const task = job.tasks.find(item => item.id === taskId);
|
|
24
|
-
if (!task || task.state !== 'QUEUED' || task.executionId !== null)
|
|
25
|
-
return;
|
|
26
|
-
if (!task.agentGraph)
|
|
27
|
-
throw new Error('Task Graph selected shortcut launch without a persisted Agent Graph');
|
|
28
|
-
await executeShortcut(store, options, job, task, emit);
|
|
29
|
-
}
|
|
30
|
-
export async function resumeShortcutEffect(store, options, jobId, taskId, _data, emit) {
|
|
31
|
-
if (!taskId)
|
|
32
|
-
throw new Error('Shortcut result action requires a Task ID');
|
|
33
|
-
const job = await store.load(jobId);
|
|
34
|
-
const task = job.tasks.find(item => item.id === taskId);
|
|
35
|
-
if (!task)
|
|
36
|
-
throw new Error(`Task ${taskId} not found`);
|
|
37
|
-
// The runner reads only the atomically persisted receipt from this Task's SQLite checkpoint.
|
|
38
|
-
if (task.state !== 'RUNNING' || task.leaseOwner !== null)
|
|
39
|
-
return;
|
|
40
|
-
try {
|
|
41
|
-
await executeShortcut(store, options, job, task, emit);
|
|
42
|
-
}
|
|
43
|
-
catch (error) {
|
|
44
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
45
|
-
if (message === 'Shortcut wait claim was fenced by another execution' || message === `Task ${task.id} has an active or unreconciled execution lease`)
|
|
46
|
-
return;
|
|
47
|
-
// Two reconcilers may observe the same SQLite receipt. If the first has
|
|
48
|
-
// already committed the Task's terminal success, the later callback is
|
|
49
|
-
// a stale wake-up, not an execution failure. Never overwrite the result.
|
|
50
|
-
if (message === `Job ${jobId} is not runnable (COMPLETED)`) {
|
|
51
|
-
const current = await store.load(jobId);
|
|
52
|
-
if (current.state === 'COMPLETED' && current.tasks.some(candidate => candidate.id === task.id && candidate.state === 'SUCCEEDED'))
|
|
53
|
-
return;
|
|
54
|
-
}
|
|
55
|
-
throw error;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
export async function resumeShortcutEventWaits(store, _options, jobId, dispatchResume, _emit) {
|
|
59
|
-
const job = await store.load(jobId);
|
|
60
|
-
if (job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'ACTIVE' || job.pause)
|
|
61
|
-
return;
|
|
62
|
-
for (const task of job.tasks.filter(item => item.state === 'RUNNING' && item.leaseOwner === null && item.executionId !== null)) {
|
|
63
|
-
const checkpoint = task.result?.data?.shortcut;
|
|
64
|
-
for (const [nodeId, wait] of Object.entries(checkpoint?.waits ?? {})) {
|
|
65
|
-
const receipt = checkpoint?.receipts?.[nodeId];
|
|
66
|
-
if (!receipt || wait.kind !== 'nonhuman_result' || !wait.id || !wait.revision || !wait.contentHash || wait.executionId !== task.executionId
|
|
67
|
-
|| receipt.nodeId !== nodeId || receipt.waitId !== wait.id || receipt.revision !== wait.revision || receipt.contentSha256 !== wait.contentHash
|
|
68
|
-
|| receipt.executionId !== task.executionId)
|
|
69
|
-
continue;
|
|
70
|
-
await dispatchResume(job, task, receipt);
|
|
71
|
-
break;
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
}
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { pathToFileURL } from 'node:url';
|
|
2
|
-
/** Preserve Script determinism: semantic owner feedback is resolved by its
|
|
3
|
-
* existing Agent Worker before the Script validates and requests re-review. */
|
|
4
|
-
export async function runShortcutRevisionNode(options) {
|
|
5
|
-
const { review } = options;
|
|
6
|
-
const module = await import(pathToFileURL(options.path).href);
|
|
7
|
-
let revisionWork;
|
|
8
|
-
if (review?.status === 'changes_requested') {
|
|
9
|
-
if (!options.runModelNode)
|
|
10
|
-
throw Error('Request Changes requires a bound Agent Worker; Shortcut script cannot perform a semantic revision');
|
|
11
|
-
revisionWork = await options.runModelNode({ ...options.modelNode, reviewDecision: { status: 'changes_requested',
|
|
12
|
-
revision: review.revision, invocationId: review.invocationId, feedback: review.feedback, comments: review.comments } });
|
|
13
|
-
if (!options.validOutput(revisionWork))
|
|
14
|
-
throw Error('Revision Worker did not return a completed Artifact result');
|
|
15
|
-
}
|
|
16
|
-
return module.run({ input: { ...options.input,
|
|
17
|
-
...(review ? { reviewDecision: { status: review.status, revision: review.revision, invocationId: review.invocationId,
|
|
18
|
-
feedback: review.feedback, comments: review.comments } } : {}),
|
|
19
|
-
...(revisionWork ? { reviewRevision: revisionWork } : {}) },
|
|
20
|
-
signal: options.signal, runCommand: options.runCommand });
|
|
21
|
-
}
|
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
import { mkdir, readFile } from 'node:fs/promises';
|
|
2
|
-
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
3
|
-
import { createTaskEntity } from './workflow/entity-creation.js';
|
|
4
|
-
import { taskOverallTimeoutMs } from './types.js';
|
|
5
|
-
/** A model node stays within its original Shortcut Job. Its durable child Task
|
|
6
|
-
* uses the existing Relay Worker adapter, lifecycle Graph and Troubleshooter.
|
|
7
|
-
* The parent Shortcut Graph, not the Worker Reconciler, selects DAG readiness. */
|
|
8
|
-
export async function runShortcutModelNode(options) {
|
|
9
|
-
const { store, reconciler, jobId, parentTaskId, node } = options;
|
|
10
|
-
if (!store.mutateJob)
|
|
11
|
-
throw new Error('Model nodes require the durable Relay SQLite store');
|
|
12
|
-
if (!/^[A-Za-z_][\w.-]*$/.test(node.id))
|
|
13
|
-
throw new Error('Invalid shortcut model node ID');
|
|
14
|
-
const review = node.reviewDecision;
|
|
15
|
-
if (review && (review.revision !== review.invocationId))
|
|
16
|
-
throw new Error('Invalid semantic Revision identity');
|
|
17
|
-
const taskId = `shortcut-${parentTaskId}-${node.id}${review ? '-revision-' + review.invocationId : ''}`;
|
|
18
|
-
const initial = await store.load(jobId);
|
|
19
|
-
const parent = initial.tasks.find(t => t.id === parentTaskId);
|
|
20
|
-
if (!parent || parent.state !== 'RUNNING' || parent.executionId !== node.executionId || !parent.leaseOwner)
|
|
21
|
-
throw new Error('Model node parent execution is not leased by Shortcut Runner');
|
|
22
|
-
if (parent.output?.kind !== 'file' || !isAbsolute(parent.output.path))
|
|
23
|
-
throw new Error('Model nodes require a canonical absolute Task output directory');
|
|
24
|
-
if (review) {
|
|
25
|
-
const recorded = parent.interactiveInvocation;
|
|
26
|
-
if (!recorded?.decidedAt || recorded.status !== 'changes_requested' ||
|
|
27
|
-
recorded.invocationId !== review.invocationId || recorded.revision !== review.revision)
|
|
28
|
-
throw new Error('Revision Worker requires the actual accepted Relay review');
|
|
29
|
-
}
|
|
30
|
-
const runRoot = dirname(parent.output.path);
|
|
31
|
-
const declaredRun = parent.input.match(/^- Canonical run:\s*(\/[^\r\n]+)$/m)?.[1]?.trim();
|
|
32
|
-
if (declaredRun && resolve(declaredRun) !== resolve(runRoot))
|
|
33
|
-
throw new Error('Shortcut Worker declared canonical run does not match the bound parent Task output directory');
|
|
34
|
-
const sourceRef = parent.input.match(/^- Private input evidence:\s*(\/[^\r\n]+)$/m)?.[1]?.trim();
|
|
35
|
-
if (sourceRef && (!declaredRun || dirname(resolve(sourceRef)) !== resolve(runRoot)))
|
|
36
|
-
throw new Error('Shortcut Worker source evidence is not confined to the declared canonical run');
|
|
37
|
-
const outputPath = join(runRoot, '.shortcut-node-results', `${taskId}.json`);
|
|
38
|
-
// No wall-clock cutoff. Child Workers use their standard progress-renewed
|
|
39
|
-
// inactivity watchdog; the foreground Shortcut parent keeps its lease live.
|
|
40
|
-
const started = initial.shortcutExecutionStartedAt && Date.parse(initial.shortcutExecutionStartedAt);
|
|
41
|
-
if (!started || !Number.isFinite(started))
|
|
42
|
-
throw new Error('Model node has no Shortcut start record');
|
|
43
|
-
await mkdir(dirname(outputPath), { recursive: true, mode: 0o700 });
|
|
44
|
-
await store.mutateJob(jobId, current => {
|
|
45
|
-
const active = current.tasks.find(t => t.id === parentTaskId);
|
|
46
|
-
if (current.state !== 'ACTIVE' || current.executionMode !== 'shortcut' || current.contentOnly !== true || current.pause ||
|
|
47
|
-
!active || active.executionId !== node.executionId || active.state !== 'RUNNING' || !active.leaseOwner)
|
|
48
|
-
throw new Error('Shortcut model worker claim invalidated by Job lifecycle');
|
|
49
|
-
const cp = active.result?.data?.shortcut;
|
|
50
|
-
if (!cp || typeof cp !== 'object')
|
|
51
|
-
throw new Error('Shortcut model worker requires a persisted Graph checkpoint');
|
|
52
|
-
const state = cp;
|
|
53
|
-
if (state.nodes?.[node.id] || state.inFlight?.[node.id] !== node.executionId)
|
|
54
|
-
throw new Error('Model node is no longer pending in the current Graph execution');
|
|
55
|
-
state.workerNodes ??= {};
|
|
56
|
-
const workerKey = review ? `${node.id}:revision:${review.invocationId}` : node.id;
|
|
57
|
-
if (state.workerNodes[workerKey] && state.workerNodes[workerKey] !== taskId)
|
|
58
|
-
throw new Error('Conflicting durable Worker node mapping');
|
|
59
|
-
state.workerNodes[workerKey] = taskId;
|
|
60
|
-
const existing = current.tasks.find(t => t.id === taskId);
|
|
61
|
-
if (existing) {
|
|
62
|
-
if (existing.parentTaskId !== parentTaskId || existing.agentName !== node.agent || existing.output?.kind !== 'file' || existing.output.path !== outputPath)
|
|
63
|
-
throw new Error('Durable Worker node identity mismatch');
|
|
64
|
-
}
|
|
65
|
-
else {
|
|
66
|
-
const now = new Date().toISOString();
|
|
67
|
-
const body = JSON.stringify({
|
|
68
|
-
source: 'shortcut-graph-node', jobId, parentTaskId, nodeId: node.id, agent: node.agent,
|
|
69
|
-
predecessorOutputs: node.predecessorOutputs,
|
|
70
|
-
...(review ? { reviewDecision: review, revisionOf: { nodeId: node.id, commitSha: review.revision } } : {}),
|
|
71
|
-
originalInput: active.input,
|
|
72
|
-
...(declaredRun ? { canonicalRunPath: declaredRun } : {}),
|
|
73
|
-
...(sourceRef ? { sourceEvidencePath: sourceRef } : {}),
|
|
74
|
-
requiredResult: { status: 'COMPLETED', output: {}, artifacts: [] },
|
|
75
|
-
outputPath,
|
|
76
|
-
instruction: review ? 'Revise only the existing Stage Artifact according to the human feedback within the Agent role, preserving source provenance; never invent evidence, approve, or publish. The parent Shortcut re-verifies and re-previews.' : 'Execute only this Agent role for this DAG node. The ONLY structured DAG predecessor values are predecessorOutputs; never infer an undeclared sibling dependency. If canonicalRunPath is declared, read the authorized original source manifest and prior stage artifact files there as required by the project Agent/Stage contract; inspect and validate their real contents, source provenance, hashes and use rights. These files are allowed canonical run evidence, not an alternative DAG predecessor result and not proof of human approval. Do not claim they are absent merely because they are not repeated in predecessorOutputs. Write {status:"COMPLETED",output:{...},artifacts:[]} to outputPath only after meeting stage acceptance and send a correlated task.completed event. If a real prerequisite is unavailable, report the specific verified blocker and task.failed; do not fabricate, publish, approve or infer new permissions.'
|
|
77
|
-
});
|
|
78
|
-
current.tasks.push(createTaskEntity(current, {
|
|
79
|
-
jobId, id: taskId, title: `Shortcut model node ${node.id}`, kind: 'work', parentTaskId,
|
|
80
|
-
agentName: node.agent, dependencies: [], capabilities: ['model'], workerRequirements: { capabilities: ['model'] },
|
|
81
|
-
adapter: 'codex', input: body, output: { kind: 'file', path: outputPath },
|
|
82
|
-
attempt: 0, maxAttempts: 3, leaseOwner: null, leaseExpiresAt: null, executionId: null, threadId: null,
|
|
83
|
-
result: null, error: null, timeoutMs: taskOverallTimeoutMs('L'), createdAt: now, updatedAt: now,
|
|
84
|
-
}));
|
|
85
|
-
}
|
|
86
|
-
return current;
|
|
87
|
-
});
|
|
88
|
-
while (true) {
|
|
89
|
-
if (node.signal.aborted)
|
|
90
|
-
throw node.signal.reason ?? new Error('Shortcut Worker node interrupted');
|
|
91
|
-
const current = await store.load(jobId);
|
|
92
|
-
if (current.state !== 'ACTIVE' || current.pause)
|
|
93
|
-
throw new Error('Shortcut Job cancelled/paused while Worker node was pending');
|
|
94
|
-
const task = current.tasks.find(t => t.id === taskId);
|
|
95
|
-
if (!task)
|
|
96
|
-
throw new Error('Worker node disappeared from the durable Job');
|
|
97
|
-
if (task.state === 'SUCCEEDED') {
|
|
98
|
-
const buffer = await readFile(outputPath);
|
|
99
|
-
const value = JSON.parse(buffer.toString('utf8'));
|
|
100
|
-
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
101
|
-
throw new Error('Worker Task reported success without contract-valid node output');
|
|
102
|
-
const record = value;
|
|
103
|
-
if (record.status !== 'COMPLETED' || !record.output || typeof record.output !== 'object' || Array.isArray(record.output))
|
|
104
|
-
throw new Error('Worker Task reported success without contract-valid node output');
|
|
105
|
-
// Some Workers report {path,kind:"human-readable description"}.
|
|
106
|
-
// Only the checked on-disk path is an artifact identity; `kind` is not
|
|
107
|
-
// a declared filesystem type or authorization claim.
|
|
108
|
-
// Convert ONLY exact file records to the Shortcut contract's path list;
|
|
109
|
-
// the Graph executor still verifies realpath containment and SHA-256.
|
|
110
|
-
if (Array.isArray(record.artifacts)) {
|
|
111
|
-
const files = record.artifacts.map((item) => {
|
|
112
|
-
if (typeof item === 'string' && item.trim())
|
|
113
|
-
return item;
|
|
114
|
-
if (item && typeof item === 'object' && !Array.isArray(item)) {
|
|
115
|
-
const ref = item;
|
|
116
|
-
const fields = Object.keys(ref);
|
|
117
|
-
// A Worker may naturally produce a path-only file record. Accept
|
|
118
|
-
// EXACTLY {path} (no unrecognized metadata), then let the Graph
|
|
119
|
-
// executor verify realpath confinement and SHA-256 as usual.
|
|
120
|
-
if (fields.length === 1 && fields[0] === 'path'
|
|
121
|
-
&& typeof ref.path === 'string' && ref.path.trim())
|
|
122
|
-
return ref.path;
|
|
123
|
-
if (fields.length === 2 && fields.includes('path')
|
|
124
|
-
&& ((fields.includes('type') && ref.type === 'file') ||
|
|
125
|
-
(fields.includes('kind') && typeof ref.kind === 'string' && ref.kind.trim()))
|
|
126
|
-
&& typeof ref.path === 'string' && ref.path.trim())
|
|
127
|
-
return ref.path;
|
|
128
|
-
}
|
|
129
|
-
throw new Error('Worker node returned unsupported artifact entry; expected a file path, {path}, {type:"file",path} or {kind:"description",path}');
|
|
130
|
-
});
|
|
131
|
-
return { ...record, artifacts: files };
|
|
132
|
-
}
|
|
133
|
-
if (!record.artifacts || typeof record.artifacts !== 'object')
|
|
134
|
-
throw new Error('Worker Task reported success without contract-valid artifact output');
|
|
135
|
-
return record;
|
|
136
|
-
}
|
|
137
|
-
if (task.state === 'CANCELLED')
|
|
138
|
-
throw new Error('Worker node cancelled');
|
|
139
|
-
if (task.state === 'BLOCKED')
|
|
140
|
-
throw new Error(`Worker node requires escalation: ${task.failureReason ?? task.error ?? task.id}`);
|
|
141
|
-
await reconciler.reconcile(jobId);
|
|
142
|
-
await new Promise(resolve => setTimeout(resolve, 100));
|
|
143
|
-
}
|
|
144
|
-
}
|
|
@@ -1,64 +0,0 @@
|
|
|
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
|
-
rev.revision !== rev.executionId || rev.executionId !== pending[0])
|
|
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
|
-
}
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { dispatchJobLifecycleSync } from './workflow/lifecycle.js';
|
|
2
|
-
/** One foreground owner drives all Worker fallback and Troubleshooter Tasks.
|
|
3
|
-
* No background scheduler may mutate a Shortcut Job. */
|
|
4
|
-
export async function driveShortcutWorkers(options) {
|
|
5
|
-
const { store, jobId, reconciler, taskId } = options;
|
|
6
|
-
if (!store.mutateJob)
|
|
7
|
-
throw new Error('Foreground Worker fallback requires atomic Relay SQLite');
|
|
8
|
-
await store.mutateJob(jobId, job => {
|
|
9
|
-
if (job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'ACTIVE')
|
|
10
|
-
throw new Error('Not an active Shortcut Job');
|
|
11
|
-
if (!job.tasks.find(task => task.id === taskId))
|
|
12
|
-
throw new Error('Shortcut parent Task missing');
|
|
13
|
-
if (!job.shortcutExecutionStartedAt)
|
|
14
|
-
job.shortcutExecutionStartedAt = new Date().toISOString();
|
|
15
|
-
if (!Number.isFinite(Date.parse(job.shortcutExecutionStartedAt)))
|
|
16
|
-
throw new Error('Invalid original Shortcut start time');
|
|
17
|
-
return job;
|
|
18
|
-
});
|
|
19
|
-
const last = new Map();
|
|
20
|
-
const stopWatching = await reconciler.watch(jobId);
|
|
21
|
-
const observe = (job) => {
|
|
22
|
-
for (const task of job.tasks) {
|
|
23
|
-
const key = `${task.state}:${task.attempt}:${task.error ?? ''}`;
|
|
24
|
-
if (last.get(task.id) !== key) {
|
|
25
|
-
last.set(task.id, key);
|
|
26
|
-
options.onTask?.(task);
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
try {
|
|
31
|
-
while (true) {
|
|
32
|
-
if (options.signal?.aborted)
|
|
33
|
-
return { status: 'INTERRUPTED', job: await store.load(jobId) };
|
|
34
|
-
await reconciler.reconcile(jobId);
|
|
35
|
-
let job = await store.load(jobId);
|
|
36
|
-
observe(job);
|
|
37
|
-
if (job.state === 'COMPLETED')
|
|
38
|
-
return { status: 'COMPLETED', job };
|
|
39
|
-
if (job.state === 'CANCELLED')
|
|
40
|
-
return { status: 'FAILED', job };
|
|
41
|
-
if (job.tasks.every(task => task.state === 'SUCCEEDED')) {
|
|
42
|
-
job = await store.mutateJob(jobId, current => {
|
|
43
|
-
if (current.state !== 'ACTIVE' || !current.tasks.length || !current.tasks.every(task => task.state === 'SUCCEEDED')
|
|
44
|
-
|| current.prNumber !== 0 || current.localMerge || current.autoMerge !== false || current.reviewEnabled !== false || current.review || current.plans?.length)
|
|
45
|
-
throw new Error('Shortcut completion requires all durable Tasks and content-only policy');
|
|
46
|
-
const decision = dispatchJobLifecycleSync(current, 'shortcut.completed', { shortcutCompletionAllowed: true });
|
|
47
|
-
if (!decision.accepted || decision.target !== 'COMPLETED')
|
|
48
|
-
throw new Error('Job Graph rejected Shortcut completion');
|
|
49
|
-
return current;
|
|
50
|
-
});
|
|
51
|
-
return { status: 'COMPLETED', job };
|
|
52
|
-
}
|
|
53
|
-
if (job.tasks.some(task => task.state === 'BLOCKED' || task.state === 'AWAITING_DECISION'))
|
|
54
|
-
return { status: 'WAITING_EVENT', job };
|
|
55
|
-
if (job.tasks.some(task => task.agentName === 'troubleshooter' && task.state === 'FAILED' && task.attempt >= task.maxAttempts))
|
|
56
|
-
return { status: 'FAILED', job };
|
|
57
|
-
await new Promise(resolve => setTimeout(resolve, 350));
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
finally {
|
|
61
|
-
await stopWatching();
|
|
62
|
-
await reconciler.close();
|
|
63
|
-
}
|
|
64
|
-
}
|