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/agent-shortcut.js
DELETED
|
@@ -1,587 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
-
import { resolve, relative, isAbsolute, sep, dirname, basename, join } from 'node:path';
|
|
4
|
-
import { once } from 'node:events';
|
|
5
|
-
import { runShortcutRevisionNode } from './shortcut-node-revision.js';
|
|
6
|
-
import { spawnOwnedProcess } from './owned-process.js';
|
|
7
|
-
import { validateShortcutStageGate } from './shortcut-stage-contract.js';
|
|
8
|
-
import { parseAgentGraph } from './agent-graph.js';
|
|
9
|
-
import { agentSourceLayers, resolveAgentMarkdown } from './agent-content-resolver.js';
|
|
10
|
-
import { homedir } from 'node:os';
|
|
11
|
-
import { BUNDLED_AGENTS_ROOT } from './execution-context.js';
|
|
12
|
-
import { DurableTaskTransitionRuntime } from './workflow/durable-transition.js';
|
|
13
|
-
import { dispatchJobLifecycleSync } from './workflow/lifecycle.js';
|
|
14
|
-
import { dependencyReady, tryTransitionTaskEvent } from './task-transitions.js';
|
|
15
|
-
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
16
|
-
const digestBytes = (value) => createHash('sha256').update(value).digest('hex');
|
|
17
|
-
function canonical(value) {
|
|
18
|
-
if (Array.isArray(value))
|
|
19
|
-
return `[${value.map(canonical).join(',')}]`;
|
|
20
|
-
if (value && typeof value === 'object')
|
|
21
|
-
return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(',')}}`;
|
|
22
|
-
return JSON.stringify(value) ?? 'null';
|
|
23
|
-
}
|
|
24
|
-
function checkpoint(task) {
|
|
25
|
-
const data = task.result?.data?.shortcut;
|
|
26
|
-
return data && typeof data === 'object' ? structuredClone(data) : { version: 1, graphHash: '', inputHash: '', shortcutHash: '', nodes: {}, waits: {}, artifactHashes: {} };
|
|
27
|
-
}
|
|
28
|
-
function validOutput(value) {
|
|
29
|
-
return Boolean(value && typeof value === 'object' && !Array.isArray(value) && value.status === 'COMPLETED'
|
|
30
|
-
&& value.output && typeof value.output === 'object'
|
|
31
|
-
&& !Array.isArray(value.output)
|
|
32
|
-
&& ((Array.isArray(value.artifacts) && value.artifacts.every(item => typeof item === 'string'))
|
|
33
|
-
|| (Boolean(value.artifacts) && typeof value.artifacts === 'object' && !Array.isArray(value.artifacts))));
|
|
34
|
-
}
|
|
35
|
-
export function shortcutContentSha256(output) { return digest(canonical(output)); }
|
|
36
|
-
export async function recordShortcutReceipt(store, identity) {
|
|
37
|
-
if (!store.mutateJob)
|
|
38
|
-
throw new Error('Shortcut receipts require atomic Relay SQLite mutation');
|
|
39
|
-
if (!validOutput(identity.output))
|
|
40
|
-
throw new Error('Shortcut receipt output must satisfy the completed shortcut result contract');
|
|
41
|
-
if (!/^[0-9a-f]{64}$/i.test(identity.contentSha256) || shortcutContentSha256(identity.output) !== identity.contentSha256.toLowerCase())
|
|
42
|
-
throw new Error('Shortcut receipt content SHA256 does not match output');
|
|
43
|
-
const receipt = { jobId: identity.jobId, taskId: identity.taskId, nodeId: identity.nodeId, waitId: identity.waitId,
|
|
44
|
-
revision: identity.revision, executionId: identity.executionId, contentSha256: identity.contentSha256.toLowerCase(),
|
|
45
|
-
output: structuredClone(identity.output), recordedAt: new Date().toISOString() };
|
|
46
|
-
await store.mutateJob(identity.jobId, job => {
|
|
47
|
-
const task = job.tasks.find(item => item.id === identity.taskId);
|
|
48
|
-
const checkpoint = task?.result?.data?.shortcut;
|
|
49
|
-
const wait = checkpoint?.waits?.[identity.nodeId];
|
|
50
|
-
if (job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'ACTIVE' || job.pause || !task || !checkpoint || task.state !== 'RUNNING'
|
|
51
|
-
|| task.leaseOwner !== null || task.executionId !== identity.executionId || wait?.kind !== 'nonhuman_result'
|
|
52
|
-
|| wait.id !== identity.waitId || wait.revision !== identity.revision || wait.contentHash !== identity.contentSha256.toLowerCase()
|
|
53
|
-
|| wait.executionId !== identity.executionId)
|
|
54
|
-
throw new Error('Shortcut receipt does not match an active persisted wait and execution');
|
|
55
|
-
checkpoint.receipts ??= {};
|
|
56
|
-
const existing = checkpoint.receipts[identity.nodeId];
|
|
57
|
-
if (existing) {
|
|
58
|
-
if (existing.jobId === receipt.jobId && existing.taskId === receipt.taskId && existing.nodeId === receipt.nodeId && existing.waitId === receipt.waitId
|
|
59
|
-
&& existing.revision === receipt.revision && existing.executionId === receipt.executionId && existing.contentSha256 === receipt.contentSha256
|
|
60
|
-
&& canonical(existing.output) === canonical(receipt.output))
|
|
61
|
-
return job;
|
|
62
|
-
throw new Error('Conflicting shortcut receipt already exists for this wait');
|
|
63
|
-
}
|
|
64
|
-
if (checkpoint.nodes?.[identity.nodeId])
|
|
65
|
-
throw new Error('Shortcut wait result was already consumed');
|
|
66
|
-
checkpoint.receipts[identity.nodeId] = receipt;
|
|
67
|
-
return job;
|
|
68
|
-
});
|
|
69
|
-
return receipt;
|
|
70
|
-
}
|
|
71
|
-
function taskShortcutInput(input) {
|
|
72
|
-
try {
|
|
73
|
-
const parsed = JSON.parse(input);
|
|
74
|
-
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
|
|
75
|
-
return parsed;
|
|
76
|
-
}
|
|
77
|
-
catch { /* plain Task text remains available */ }
|
|
78
|
-
return { taskInput: input };
|
|
79
|
-
}
|
|
80
|
-
/** Task input is untrusted; only Relay may inject accepted review provenance. */
|
|
81
|
-
function safeShortcutTaskInput(input) {
|
|
82
|
-
const data = taskShortcutInput(input);
|
|
83
|
-
delete data.reviewDecision;
|
|
84
|
-
return data;
|
|
85
|
-
}
|
|
86
|
-
function shortcutJobCompletionAllowed(job) {
|
|
87
|
-
const graphs = job.tasks.filter(task => task.agentGraph);
|
|
88
|
-
return job.state === 'ACTIVE' && job.executionMode === 'shortcut' && job.contentOnly === true && job.prNumber === 0 && !job.localMerge && job.autoMerge === false
|
|
89
|
-
&& job.reviewEnabled === false && !job.review && !(job.plans?.length) && job.tasks.length > 0 && graphs.length > 0
|
|
90
|
-
&& job.tasks.every(task => task.state === 'SUCCEEDED')
|
|
91
|
-
&& graphs.every(task => {
|
|
92
|
-
const run = task.result?.data?.shortcut;
|
|
93
|
-
return Boolean(run && run.graphHash && Object.keys(run.waits).length === 0 && Object.keys(run.nodes).length === parseAgentGraph(task.agentGraph).nodes.length);
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
async function runCommand(args, cwd, signal) {
|
|
97
|
-
if (!Array.isArray(args) || args.length === 0 || args.some(item => typeof item !== 'string'))
|
|
98
|
-
throw new Error('runCommand requires a non-empty argument array');
|
|
99
|
-
const child = spawnOwnedProcess(args[0], args.slice(1), { invocation: 'shortcut.run-command', signal, spawn: { cwd, stdio: ['ignore', 'pipe', 'pipe'] } });
|
|
100
|
-
let stdout = '', stderr = '';
|
|
101
|
-
child.stdout?.setEncoding('utf8');
|
|
102
|
-
child.stderr?.setEncoding('utf8');
|
|
103
|
-
child.stdout?.on('data', chunk => { stdout += String(chunk); });
|
|
104
|
-
child.stderr?.on('data', chunk => { stderr += String(chunk); });
|
|
105
|
-
const [code] = await once(child, 'close');
|
|
106
|
-
return { stdout, stderr, code: code ?? -1 };
|
|
107
|
-
}
|
|
108
|
-
/** A Shortcut belongs to an Agent source, not to an independent name search.
|
|
109
|
-
* Only explicit Agent inheritance permits falling back to a parent's Shortcut. */
|
|
110
|
-
export async function discoverShortcut(agent, projectPath, sharedRoot, workspaceRoot, globalRoot) {
|
|
111
|
-
let sources;
|
|
112
|
-
try {
|
|
113
|
-
({ sources } = await resolveAgentMarkdown(agent, BUNDLED_AGENTS_ROOT, projectPath, sharedRoot, agentSourceLayers(projectPath, { sharedRoot, workspaceRoot, globalRoot: globalRoot ?? process.env.AGENTS_HOME ?? join(homedir(), '.agents') })));
|
|
114
|
-
}
|
|
115
|
-
catch (error) {
|
|
116
|
-
if (error instanceof Error && error.message === `Unknown agent ${agent}`)
|
|
117
|
-
return null;
|
|
118
|
-
throw error;
|
|
119
|
-
}
|
|
120
|
-
for (const source of [...sources].reverse()) {
|
|
121
|
-
const agentDir = dirname(source);
|
|
122
|
-
const name = basename(source).replace(/(?:\.agent)?\.md$/, '');
|
|
123
|
-
const shortcutDir = join(agentDir, '.shortcut');
|
|
124
|
-
let shortcutRoot;
|
|
125
|
-
try {
|
|
126
|
-
shortcutRoot = await realpath(shortcutDir);
|
|
127
|
-
}
|
|
128
|
-
catch (error) {
|
|
129
|
-
if (error.code === 'ENOENT')
|
|
130
|
-
continue;
|
|
131
|
-
throw error;
|
|
132
|
-
}
|
|
133
|
-
if (shortcutRoot !== shortcutDir)
|
|
134
|
-
throw new Error(`Agent shortcut directory symlink escapes Agent source: ${shortcutDir}`);
|
|
135
|
-
const candidate = join(shortcutDir, `${name}.agent.mjs`);
|
|
136
|
-
let actual;
|
|
137
|
-
try {
|
|
138
|
-
actual = await realpath(candidate);
|
|
139
|
-
}
|
|
140
|
-
catch (error) {
|
|
141
|
-
if (error.code === 'ENOENT')
|
|
142
|
-
continue;
|
|
143
|
-
throw error;
|
|
144
|
-
}
|
|
145
|
-
if (dirname(actual) !== shortcutRoot)
|
|
146
|
-
throw new Error(`Agent shortcut symlink escapes source directory: ${candidate}`);
|
|
147
|
-
if (!(await stat(actual)).isFile())
|
|
148
|
-
throw new Error(`Agent shortcut is not a regular file: ${candidate}`);
|
|
149
|
-
return actual;
|
|
150
|
-
}
|
|
151
|
-
return null;
|
|
152
|
-
}
|
|
153
|
-
export async function missingShortcutNodes(agentGraph, projectPath, sharedRoot, workspaceRoot, globalRoot) {
|
|
154
|
-
const graph = parseAgentGraph(agentGraph);
|
|
155
|
-
const result = await Promise.all(graph.nodes.map(async (node) => ({
|
|
156
|
-
id: node.id, available: Boolean(await discoverShortcut(node.agent, projectPath, sharedRoot, workspaceRoot, globalRoot)),
|
|
157
|
-
})));
|
|
158
|
-
return result.filter(item => !item.available).map(item => item.id);
|
|
159
|
-
}
|
|
160
|
-
function inside(root, path) { const rel = relative(root, path); return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)); }
|
|
161
|
-
function raceAbort(work, signal) {
|
|
162
|
-
if (signal.aborted)
|
|
163
|
-
return Promise.reject(signal.reason ?? new Error('Shortcut execution interrupted'));
|
|
164
|
-
let rejectAbort;
|
|
165
|
-
const aborted = new Promise((_resolve, reject) => {
|
|
166
|
-
rejectAbort = () => reject(signal.reason ?? new Error('Shortcut execution interrupted'));
|
|
167
|
-
signal.addEventListener('abort', rejectAbort, { once: true });
|
|
168
|
-
});
|
|
169
|
-
return Promise.race([work, aborted]).finally(() => { if (rejectAbort)
|
|
170
|
-
signal.removeEventListener('abort', rejectAbort); });
|
|
171
|
-
}
|
|
172
|
-
export async function runAgentShortcut(options) {
|
|
173
|
-
const { store, job, task, projectPath, sharedRoot, workspaceRoot, globalRoot } = options;
|
|
174
|
-
if (!store.mutateJob)
|
|
175
|
-
throw new Error('Shortcut execution requires atomic Relay SQLite mutation');
|
|
176
|
-
const leaseMs = options.leaseMs ?? 300_000, heartbeatMs = options.heartbeatMs ?? 30_000;
|
|
177
|
-
if (!Number.isSafeInteger(leaseMs) || leaseMs < 100 || !Number.isSafeInteger(heartbeatMs) || heartbeatMs < 10 || heartbeatMs >= leaseMs)
|
|
178
|
-
throw new Error('Shortcut lease heartbeat must be positive and shorter than its lease');
|
|
179
|
-
if (!task.agentGraph)
|
|
180
|
-
throw new Error(`Task ${task.id} has no Agent Graph`);
|
|
181
|
-
const graph = parseAgentGraph(task.agentGraph);
|
|
182
|
-
const graphHash = digest(task.agentGraph);
|
|
183
|
-
const inputHash = digest(task.input);
|
|
184
|
-
const projectReal = await realpath(projectPath);
|
|
185
|
-
const shortcuts = await Promise.all(graph.nodes.map(async (node) => {
|
|
186
|
-
const path = await discoverShortcut(node.agent, projectReal, sharedRoot, workspaceRoot, globalRoot);
|
|
187
|
-
return { nodeId: node.id, path, hash: path ? digestBytes(await readFile(path)) : 'missing' };
|
|
188
|
-
}));
|
|
189
|
-
const shortcutHash = digest(canonical(shortcuts.map(item => [item.nodeId, item.path, item.hash])));
|
|
190
|
-
const transitions = new DurableTaskTransitionRuntime(store);
|
|
191
|
-
const owner = `shortcut-${process.pid}-${randomUUID()}`;
|
|
192
|
-
let currentJob = await store.load(job.id);
|
|
193
|
-
let currentTask = currentJob.tasks.find(item => item.id === task.id);
|
|
194
|
-
if (!currentTask)
|
|
195
|
-
throw new Error(`Task ${task.id} not found`);
|
|
196
|
-
if (currentTask.agentGraph !== task.agentGraph || currentTask.input !== task.input)
|
|
197
|
-
throw new Error('Shortcut invocation Task snapshot is stale; reload the durable Task before execution or receipt consumption');
|
|
198
|
-
if (currentJob.executionMode !== 'shortcut' || currentJob.contentOnly !== true)
|
|
199
|
-
throw new Error('Shortcut execution requires durable shortcut and content-only Job policy');
|
|
200
|
-
if (currentJob.shortcutExecutionStartedAt && !Number.isFinite(Date.parse(currentJob.shortcutExecutionStartedAt)))
|
|
201
|
-
throw new Error('Shortcut execution start metadata is invalid');
|
|
202
|
-
const existingShortcut = currentTask.result?.data?.shortcut;
|
|
203
|
-
if (existingShortcut?.workerFallback === true)
|
|
204
|
-
throw new Error('Task is durably routed to the original Worker; shortcut execution is not authorized');
|
|
205
|
-
if (currentJob.state !== 'ACTIVE' || currentJob.pause)
|
|
206
|
-
throw new Error(`Job ${job.id} is not runnable (${currentJob.state}${currentJob.pause ? ' paused' : ''})`);
|
|
207
|
-
if (currentTask.state === 'QUEUED' && !dependencyReady(currentTask, new Map(currentJob.tasks.map(item => [item.id, item]))))
|
|
208
|
-
throw new Error(`Task ${task.id} dependencies are not satisfied`);
|
|
209
|
-
let state = checkpoint(currentTask);
|
|
210
|
-
// A Task Lifecycle-authorized retry retains verified completed nodes and
|
|
211
|
-
// execution history, but its previous attempt's terminal verdict must not
|
|
212
|
-
// contaminate the new run's eventual success receipt.
|
|
213
|
-
if (currentTask.state === 'QUEUED' && currentTask.attempt > 0 &&
|
|
214
|
-
currentTask.executionId === null && currentTask.leaseOwner === null &&
|
|
215
|
-
'terminal' in state)
|
|
216
|
-
delete state.terminal;
|
|
217
|
-
if (state.graphHash && (state.version !== 1 || state.graphHash !== graphHash || state.inputHash !== inputHash || state.shortcutHash !== shortcutHash))
|
|
218
|
-
throw new Error('Shortcut checkpoint fingerprint changed; refusing to reuse prior node output');
|
|
219
|
-
state.version = 1;
|
|
220
|
-
state.graphHash = graphHash;
|
|
221
|
-
state.inputHash = inputHash;
|
|
222
|
-
state.shortcutHash = shortcutHash;
|
|
223
|
-
for (const [nodeId, receipt] of Object.entries(state.receipts ?? {})) {
|
|
224
|
-
const wait = state.waits[nodeId];
|
|
225
|
-
if (!wait || receipt.jobId !== job.id || receipt.taskId !== task.id || receipt.nodeId !== nodeId || receipt.waitId !== wait.id
|
|
226
|
-
|| receipt.revision !== wait.revision || receipt.executionId !== currentTask.executionId || receipt.executionId !== wait.executionId
|
|
227
|
-
|| receipt.contentSha256 !== wait.contentHash || shortcutContentSha256(receipt.output) !== receipt.contentSha256 || !validOutput(receipt.output))
|
|
228
|
-
throw new Error(`Durable shortcut receipt ${nodeId} no longer matches its wait, execution, or content fingerprint`);
|
|
229
|
-
}
|
|
230
|
-
state.inFlight ??= {};
|
|
231
|
-
// An accepted human invocation authorizes replay of only its in-flight node.
|
|
232
|
-
let resumedReview = null;
|
|
233
|
-
if (currentTask.state === 'QUEUED' && Object.keys(state.inFlight).length > 0) {
|
|
234
|
-
const pending = Object.entries(state.inFlight);
|
|
235
|
-
const inv = currentTask.interactiveInvocation;
|
|
236
|
-
if (pending.length !== 1 || !inv?.decidedAt || !['approved', 'changes_requested'].includes(inv.status) ||
|
|
237
|
-
inv.executionId !== pending[0][1] || inv.revision !== inv.executionId)
|
|
238
|
-
throw new Error('Shortcut checkpoint contains an interrupted module execution; refusing automatic replay');
|
|
239
|
-
resumedReview = { nodeId: pending[0][0], status: inv.status,
|
|
240
|
-
revision: inv.revision, invocationId: inv.invocationId, feedback: inv.feedback, comments: inv.comments };
|
|
241
|
-
delete state.inFlight[pending[0][0]];
|
|
242
|
-
}
|
|
243
|
-
state.artifactHashes ??= {};
|
|
244
|
-
for (const [nodeId, hashes] of Object.entries(state.artifactHashes ?? {}))
|
|
245
|
-
for (const [artifact, expected] of Object.entries(hashes)) {
|
|
246
|
-
const actualPath = resolve(projectReal, artifact);
|
|
247
|
-
let actual;
|
|
248
|
-
try {
|
|
249
|
-
actual = await realpath(actualPath);
|
|
250
|
-
}
|
|
251
|
-
catch {
|
|
252
|
-
throw new Error(`Checkpoint artifact is missing: ${artifact}`);
|
|
253
|
-
}
|
|
254
|
-
if (!inside(projectReal, actual) || digestBytes(await readFile(actual)) !== expected)
|
|
255
|
-
throw new Error(`Checkpoint artifact changed or escaped project: ${artifact}`);
|
|
256
|
-
if (!state.nodes[nodeId])
|
|
257
|
-
throw new Error(`Checkpoint artifact has no completed node: ${nodeId}`);
|
|
258
|
-
}
|
|
259
|
-
if (currentTask.state === 'QUEUED') {
|
|
260
|
-
const launch = tryTransitionTaskEvent(currentTask, 'dispatch', { dispatchable: true, shortcutExecution: true, shortcutFallback: false, shortcutHasGraph: true, shortcutDirectInvocation: true });
|
|
261
|
-
if (!launch.accepted || !launch.actions.includes('effect.launchShortcut'))
|
|
262
|
-
throw new Error('Task Lifecycle graph did not select direct shortcut execution');
|
|
263
|
-
await store.mutateJob(job.id, fresh => {
|
|
264
|
-
const t = fresh.tasks.find(item => item.id === task.id);
|
|
265
|
-
if (fresh.state !== 'ACTIVE' || fresh.pause || !t || t.state !== 'QUEUED' || t.executionId !== null || t.agentGraph !== task.agentGraph || t.input !== task.input
|
|
266
|
-
|| !dependencyReady(t, new Map(fresh.tasks.map(item => [item.id, item]))))
|
|
267
|
-
throw new Error('Task is not available for shortcut claim or its input changed');
|
|
268
|
-
t.attempt += 1;
|
|
269
|
-
t.executionId = randomUUID();
|
|
270
|
-
t.leaseOwner = owner;
|
|
271
|
-
t.leaseExpiresAt = new Date(Date.now() + leaseMs).toISOString();
|
|
272
|
-
if (!fresh.shortcutExecutionStartedAt)
|
|
273
|
-
fresh.shortcutExecutionStartedAt = new Date().toISOString();
|
|
274
|
-
t.executionHistory = [...(t.executionHistory ?? []), { id: t.executionId, attempt: t.attempt, startedAt: new Date().toISOString() }].slice(-8);
|
|
275
|
-
return fresh;
|
|
276
|
-
});
|
|
277
|
-
currentTask = (await store.load(job.id)).tasks.find(item => item.id === task.id);
|
|
278
|
-
}
|
|
279
|
-
else if (currentTask.state !== 'RUNNING')
|
|
280
|
-
throw new Error(`Task ${task.id} cannot run shortcuts from ${currentTask.state}`);
|
|
281
|
-
if (currentTask.state === 'QUEUED') {
|
|
282
|
-
if (!currentTask.executionId || !currentTask.leaseOwner || !store.reserveWorkflowLaunch)
|
|
283
|
-
throw new Error('Shortcut execution requires the durable Graph-authorized launch claim');
|
|
284
|
-
const reserved = await store.reserveWorkflowLaunch({ jobId: job.id, taskId: task.id, executionId: currentTask.executionId, attempt: currentTask.attempt, leaseOwner: currentTask.leaseOwner });
|
|
285
|
-
if (!reserved)
|
|
286
|
-
throw new Error('Shortcut launch was already reserved; refusing duplicate execution');
|
|
287
|
-
const started = await transitions.apply(job.id, task.id, 'task.started', { eligible: (_j, t) => t.state === 'QUEUED' && t.leaseOwner === owner });
|
|
288
|
-
if (!started?.decision.accepted || !currentTask.executionId || await store.verifyWorkflowLaunch?.(job.id, task.id, currentTask.executionId) !== 'Verified')
|
|
289
|
-
throw new Error('Shortcut Task start did not verify against the durable launch claim');
|
|
290
|
-
}
|
|
291
|
-
else if (currentTask.leaseOwner && currentTask.leaseOwner !== owner) {
|
|
292
|
-
throw new Error(`Task ${task.id} has an active or unreconciled execution lease`);
|
|
293
|
-
}
|
|
294
|
-
else if (!currentTask.leaseOwner) {
|
|
295
|
-
if (!currentTask.executionId || !state.waits || !Object.keys(state.waits).some(nodeId => state.receipts?.[nodeId]))
|
|
296
|
-
throw new Error('Only a persisted wait with a durable receipt can resume an unleased RUNNING Task');
|
|
297
|
-
if (options.resumeReceiptSelected !== true)
|
|
298
|
-
throw new Error('Shortcut receipt consumption must be selected by the Task Lifecycle graph');
|
|
299
|
-
await store.mutateJob(job.id, fresh => {
|
|
300
|
-
const t = fresh.tasks.find(item => item.id === task.id);
|
|
301
|
-
if (fresh.state !== 'ACTIVE' || fresh.pause || !t || t.state !== 'RUNNING' || t.executionId !== currentTask.executionId || t.leaseOwner !== null)
|
|
302
|
-
throw new Error('Shortcut wait claim was fenced by another execution');
|
|
303
|
-
if (t.agentGraph !== task.agentGraph || t.input !== task.input)
|
|
304
|
-
throw new Error('Shortcut Task input changed before receipt claim');
|
|
305
|
-
t.leaseOwner = owner;
|
|
306
|
-
t.leaseExpiresAt = new Date(Date.now() + leaseMs).toISOString();
|
|
307
|
-
return fresh;
|
|
308
|
-
});
|
|
309
|
-
}
|
|
310
|
-
for (const [nodeId, receipt] of Object.entries(state.receipts ?? {})) {
|
|
311
|
-
const wait = state.waits[nodeId];
|
|
312
|
-
if (!wait)
|
|
313
|
-
throw new Error(`Durable shortcut receipt ${nodeId} has no persisted wait`);
|
|
314
|
-
if (state.nodes[nodeId])
|
|
315
|
-
throw new Error(`Shortcut receipt ${nodeId} was already consumed`);
|
|
316
|
-
const artifactHashes = {};
|
|
317
|
-
const output = receipt.output;
|
|
318
|
-
const artifactPaths = Array.isArray(output.artifacts) ? output.artifacts : Object.entries(output.artifacts).map(([name, value]) => {
|
|
319
|
-
if (!(name in output.output) || typeof output.output[name] !== 'string' || !value || typeof value !== 'object')
|
|
320
|
-
throw new Error(`shortcut artifact ${name} lacks a structured artifact and output path`);
|
|
321
|
-
return output.output[name];
|
|
322
|
-
});
|
|
323
|
-
for (const artifact of artifactPaths) {
|
|
324
|
-
const actual = await realpath(isAbsolute(artifact) ? resolve(artifact) : resolve(projectReal, artifact));
|
|
325
|
-
if (!inside(projectReal, actual))
|
|
326
|
-
throw new Error(`shortcut artifact outside project: ${artifact}`);
|
|
327
|
-
artifactHashes[relative(projectReal, actual)] = digestBytes(await readFile(actual));
|
|
328
|
-
}
|
|
329
|
-
const nodeAgent = graph.nodes.find(node => node.id === nodeId)?.agent;
|
|
330
|
-
if (nodeAgent && task.output?.kind === 'file')
|
|
331
|
-
await validateShortcutStageGate({ projectPath: projectReal, agent: nodeAgent, runPath: dirname(task.output.path), execute: (args, cwd) => runCommand(args, cwd, new AbortController().signal) });
|
|
332
|
-
state.nodes[nodeId] = structuredClone(output);
|
|
333
|
-
state.artifactHashes[nodeId] = artifactHashes;
|
|
334
|
-
delete state.waits[nodeId];
|
|
335
|
-
delete state.receipts?.[nodeId];
|
|
336
|
-
}
|
|
337
|
-
if (Object.keys(state.nodes).length > Object.keys(checkpoint(currentTask).nodes).length)
|
|
338
|
-
await persist(state);
|
|
339
|
-
currentJob = await store.load(job.id);
|
|
340
|
-
// Keep the first execution timestamp for progress/optimization metrics only.
|
|
341
|
-
// Twenty minutes is an orchestrator target, never an execution deadline.
|
|
342
|
-
if (!currentJob.shortcutExecutionStartedAt || !Number.isFinite(Date.parse(currentJob.shortcutExecutionStartedAt)))
|
|
343
|
-
throw new Error('Direct shortcut Job has no durable first-execution timestamp');
|
|
344
|
-
const executionAbort = new AbortController();
|
|
345
|
-
const abortFromCaller = () => executionAbort.abort(options.signal?.reason ?? new Error('Shortcut execution interrupted'));
|
|
346
|
-
if (options.signal?.aborted)
|
|
347
|
-
abortFromCaller();
|
|
348
|
-
else
|
|
349
|
-
options.signal?.addEventListener('abort', abortFromCaller, { once: true });
|
|
350
|
-
let leaseHeartbeatError;
|
|
351
|
-
let heartbeatInFlight = false;
|
|
352
|
-
const heartbeat = setInterval(() => {
|
|
353
|
-
if (heartbeatInFlight || executionAbort.signal.aborted)
|
|
354
|
-
return;
|
|
355
|
-
heartbeatInFlight = true;
|
|
356
|
-
void store.mutateJob(job.id, fresh => {
|
|
357
|
-
const t = fresh.tasks.find(item => item.id === task.id);
|
|
358
|
-
// A managed Preview has already suspended this exact Task and released
|
|
359
|
-
// its lease. Do not reinterpret that authorized handoff as lease loss.
|
|
360
|
-
if (t?.state === 'AWAITING_DECISION' && t.interactiveInvocation?.status === 'awaiting_decision' &&
|
|
361
|
-
t.interactiveInvocation.executionId === currentTask.executionId)
|
|
362
|
-
return fresh;
|
|
363
|
-
if (fresh.state !== 'ACTIVE' || fresh.pause || !t || t.state !== 'RUNNING' || t.executionId !== currentTask.executionId || t.leaseOwner !== owner) {
|
|
364
|
-
throw new Error('Shortcut execution lease was fenced during module execution');
|
|
365
|
-
}
|
|
366
|
-
t.leaseExpiresAt = new Date(Date.now() + leaseMs).toISOString();
|
|
367
|
-
return fresh;
|
|
368
|
-
}).catch(error => { leaseHeartbeatError = error; executionAbort.abort(error); }).finally(() => { heartbeatInFlight = false; });
|
|
369
|
-
}, heartbeatMs);
|
|
370
|
-
heartbeat.unref();
|
|
371
|
-
const stopHeartbeat = () => { clearInterval(heartbeat); options.signal?.removeEventListener('abort', abortFromCaller); };
|
|
372
|
-
const emit = (event) => options.onNodeEvent?.({ ...event, timestamp: new Date().toISOString() });
|
|
373
|
-
try {
|
|
374
|
-
// Graph executor runs Script and model nodes through their respective adapters.
|
|
375
|
-
const missing = shortcuts.filter(item => !item.path);
|
|
376
|
-
if (missing.length && !options.runModelNode)
|
|
377
|
-
return await fail(`Incomplete Agent Graph shortcut coverage: ${missing.map(item => item.nodeId).join(', ')}`);
|
|
378
|
-
const incoming = new Map(graph.nodes.map(node => [node.id, graph.edges.filter(edge => edge.to === node.id).map(edge => edge.from)]));
|
|
379
|
-
const max = Math.max(1, Math.min(8, options.concurrency ?? 4));
|
|
380
|
-
const shortcutByNode = new Map(shortcuts.map(item => [item.nodeId, item.path]));
|
|
381
|
-
for (const wave of graph.waves) {
|
|
382
|
-
const ready = wave.filter(id => !state.nodes[id] && !state.waits[id] && (incoming.get(id) ?? []).every(parent => Boolean(state.nodes[parent])));
|
|
383
|
-
for (let offset = 0; offset < ready.length; offset += max) {
|
|
384
|
-
const batch = ready.slice(offset, offset + max);
|
|
385
|
-
for (const id of batch) {
|
|
386
|
-
state.inFlight[id] = currentTask.executionId;
|
|
387
|
-
emit({ nodeId: id, type: 'started', data: { executionId: currentTask.executionId, agent: graph.nodes.find(node => node.id === id)?.agent } });
|
|
388
|
-
}
|
|
389
|
-
if (batch.length)
|
|
390
|
-
await persist(state);
|
|
391
|
-
const outcomes = await Promise.all(batch.map(async (id) => {
|
|
392
|
-
const node = graph.nodes.find(item => item.id === id);
|
|
393
|
-
const shortcut = shortcutByNode.get(id) ?? null;
|
|
394
|
-
try {
|
|
395
|
-
const predecessorOutputs = Object.fromEntries((incoming.get(id) ?? []).map(parent => [parent, state.nodes[parent]?.output]));
|
|
396
|
-
const trackedRunCommand = async (args, cwd) => {
|
|
397
|
-
if (executionAbort.signal.aborted)
|
|
398
|
-
throw new Error(`Shortcut execution was cancelled: ${String(leaseHeartbeatError ?? 'lease lost')}`);
|
|
399
|
-
return runCommand(args, cwd, executionAbort.signal);
|
|
400
|
-
};
|
|
401
|
-
emit({ nodeId: id, type: 'progress', data: { phase: shortcut ? 'shortcut.invoke' : 'worker.invoke' } });
|
|
402
|
-
const review = resumedReview?.nodeId === id ? resumedReview : null;
|
|
403
|
-
const raw = await raceAbort(shortcut
|
|
404
|
-
? runShortcutRevisionNode({ path: shortcut, signal: executionAbort.signal,
|
|
405
|
-
input: { ...safeShortcutTaskInput(task.input), projectPath, jobId: job.id, taskId: task.id, nodeId: id,
|
|
406
|
-
agent: node.agent, predecessorOutputs }, runCommand: trackedRunCommand,
|
|
407
|
-
modelNode: { id, agent: node.agent, predecessorOutputs, executionId: currentTask.executionId, signal: executionAbort.signal },
|
|
408
|
-
review, runModelNode: options.runModelNode, validOutput })
|
|
409
|
-
: options.runModelNode({ id, agent: node.agent, predecessorOutputs, executionId: currentTask.executionId, signal: executionAbort.signal }), executionAbort.signal);
|
|
410
|
-
if (leaseHeartbeatError)
|
|
411
|
-
throw new Error(`Shortcut lease renewal failed: ${String(leaseHeartbeatError)}`);
|
|
412
|
-
if (!raw || typeof raw !== 'object')
|
|
413
|
-
throw new Error('shortcut result must be an object');
|
|
414
|
-
const result = raw;
|
|
415
|
-
if (result.status === 'WAITING_EVENT' && result.event && typeof result.event === 'object')
|
|
416
|
-
return { id, value: result };
|
|
417
|
-
if (result.status === 'WAITING_REVIEW')
|
|
418
|
-
return { id, value: result };
|
|
419
|
-
if (!validOutput(result))
|
|
420
|
-
throw new Error('shortcut returned an invalid COMPLETED result contract');
|
|
421
|
-
const artifactPaths = Array.isArray(result.artifacts) ? result.artifacts
|
|
422
|
-
: Object.entries(result.artifacts).map(([name, value]) => {
|
|
423
|
-
if (!(name in result.output) || typeof result.output[name] !== 'string' || !value || typeof value !== 'object')
|
|
424
|
-
throw new Error(`shortcut artifact ${name} lacks a structured artifact and output path`);
|
|
425
|
-
return result.output[name];
|
|
426
|
-
});
|
|
427
|
-
const projectReal = await realpath(projectPath);
|
|
428
|
-
if (task.output?.kind === 'file')
|
|
429
|
-
await validateShortcutStageGate({ projectPath: projectReal, agent: node.agent, runPath: dirname(task.output.path), execute: trackedRunCommand });
|
|
430
|
-
const artifactHashes = {};
|
|
431
|
-
// Project-local Shortcut nodes use project-relative paths. Managed
|
|
432
|
-
// Project Run Workers may instead return paths relative to their
|
|
433
|
-
// canonical Run; both must stay inside the Project and remain
|
|
434
|
-
// unambiguous before hashing bytes.
|
|
435
|
-
const runRoot = task.output?.kind === 'file' ? await realpath(dirname(task.output.path)) : null;
|
|
436
|
-
const checkedRunRoot = runRoot && inside(projectReal, runRoot) ? runRoot : null;
|
|
437
|
-
for (const artifact of artifactPaths) {
|
|
438
|
-
if (!artifact || typeof artifact !== 'string')
|
|
439
|
-
throw new Error('shortcut artifact path cannot be empty');
|
|
440
|
-
const candidates = isAbsolute(artifact)
|
|
441
|
-
? [resolve(artifact)]
|
|
442
|
-
: [...new Set([resolve(projectReal, artifact), ...(checkedRunRoot ? [resolve(checkedRunRoot, artifact)] : [])])];
|
|
443
|
-
const found = [];
|
|
444
|
-
for (const candidate of candidates) {
|
|
445
|
-
// Never follow a symlink from outside the Project into it.
|
|
446
|
-
if (!inside(projectReal, candidate))
|
|
447
|
-
continue;
|
|
448
|
-
try {
|
|
449
|
-
const actual = await realpath(candidate);
|
|
450
|
-
if (inside(projectReal, actual) && !found.includes(actual))
|
|
451
|
-
found.push(actual);
|
|
452
|
-
}
|
|
453
|
-
catch { /* Check the alternate canonical Run location. */ }
|
|
454
|
-
}
|
|
455
|
-
if (found.length === 0)
|
|
456
|
-
throw new Error(`shortcut artifact missing or outside project: ${artifact}`);
|
|
457
|
-
// A copied project asset may exist at both paths. Identical bytes
|
|
458
|
-
// are unambiguous; prefer the Run copy, but fail closed on a diff.
|
|
459
|
-
const contents = await Promise.all(found.map(path => readFile(path)));
|
|
460
|
-
const hashes = contents.map(digestBytes);
|
|
461
|
-
if (new Set(hashes).size > 1)
|
|
462
|
-
throw new Error(`shortcut artifact ambiguous between project and run: ${artifact}`);
|
|
463
|
-
const selected = checkedRunRoot ? found.findIndex(path => inside(checkedRunRoot, path)) : -1;
|
|
464
|
-
const index = selected >= 0 ? selected : 0;
|
|
465
|
-
artifactHashes[relative(projectReal, found[index])] = hashes[index];
|
|
466
|
-
}
|
|
467
|
-
return { id, value: result, artifactHashes };
|
|
468
|
-
}
|
|
469
|
-
catch (error) {
|
|
470
|
-
return { id, value: null, error: error instanceof Error ? error.message : String(error) };
|
|
471
|
-
}
|
|
472
|
-
}));
|
|
473
|
-
const reviewWait = outcomes.find(result => result.value?.status === 'WAITING_REVIEW');
|
|
474
|
-
if (reviewWait) {
|
|
475
|
-
// The wrapper already persisted RUNNING -> AWAITING_DECISION and
|
|
476
|
-
// released the lease. Keep inFlight as a durable fence until the
|
|
477
|
-
// approved/changes-requested invocation requeues this same Task.
|
|
478
|
-
if (batch.length !== 1)
|
|
479
|
-
return await fail('Interactive Shortcut Review requires a single in-flight node');
|
|
480
|
-
const durable = await findTask();
|
|
481
|
-
if (durable.state !== 'AWAITING_DECISION' || durable.interactiveInvocation?.status !== 'awaiting_decision' ||
|
|
482
|
-
durable.interactiveInvocation.executionId !== currentTask.executionId)
|
|
483
|
-
return await fail('Shortcut Review did not bind the current Task through hostInvocation');
|
|
484
|
-
emit({ nodeId: reviewWait.id, type: 'waiting', data: { invocationId: durable.interactiveInvocation.invocationId,
|
|
485
|
-
executionId: durable.interactiveInvocation.executionId } });
|
|
486
|
-
stopHeartbeat();
|
|
487
|
-
return { outcome: { status: 'WAITING_REVIEW', nodeId: reviewWait.id,
|
|
488
|
-
invocationId: durable.interactiveInvocation.invocationId }, task: durable, fallback: false };
|
|
489
|
-
}
|
|
490
|
-
const failed = outcomes.find(result => !result.value);
|
|
491
|
-
for (const result of outcomes) {
|
|
492
|
-
if (!result.value) {
|
|
493
|
-
delete state.inFlight[result.id];
|
|
494
|
-
continue;
|
|
495
|
-
}
|
|
496
|
-
if (result.value.status === 'WAITING_EVENT') {
|
|
497
|
-
const evt = result.value.event;
|
|
498
|
-
if (evt.kind !== 'nonhuman_result')
|
|
499
|
-
return await fail('Shortcut event wait must be a nonhuman result; human approval must use Relay hostInvocation');
|
|
500
|
-
if (typeof evt.id !== 'string' || typeof evt.revision !== 'string' || typeof evt.contentHash !== 'string'
|
|
501
|
-
|| (evt.nodeId !== undefined && evt.nodeId !== result.id) || !/^[0-9a-f]{64}$/i.test(evt.contentHash))
|
|
502
|
-
return await fail(`Invalid event wait from ${result.id}`);
|
|
503
|
-
delete state.inFlight[result.id];
|
|
504
|
-
state.waits[result.id] = { kind: 'nonhuman_result', id: evt.id, revision: evt.revision, contentHash: evt.contentHash, executionId: currentTask.executionId };
|
|
505
|
-
emit({ nodeId: result.id, type: 'waiting', data: { waitId: evt.id, revision: evt.revision, executionId: currentTask.executionId } });
|
|
506
|
-
}
|
|
507
|
-
else {
|
|
508
|
-
delete state.inFlight[result.id];
|
|
509
|
-
state.nodes[result.id] = result.value;
|
|
510
|
-
state.artifactHashes[result.id] = result.artifactHashes ?? {};
|
|
511
|
-
emit({ nodeId: result.id, type: 'completed', data: { executionId: currentTask.executionId, output: result.value.output } });
|
|
512
|
-
}
|
|
513
|
-
}
|
|
514
|
-
await persist(state);
|
|
515
|
-
if (failed)
|
|
516
|
-
return await fail(`Shortcut node ${failed.id} failed: ${failed.error ?? 'no valid result'}`);
|
|
517
|
-
}
|
|
518
|
-
}
|
|
519
|
-
if (Object.keys(state.waits).length) {
|
|
520
|
-
const released = await transitions.apply(job.id, task.id, 'shortcut.waiting', { eligible: (_j, t) => t.state === 'RUNNING' && t.leaseOwner === owner });
|
|
521
|
-
if (!released?.decision.accepted)
|
|
522
|
-
throw new Error('Task lifecycle graph rejected shortcut.waiting');
|
|
523
|
-
stopHeartbeat();
|
|
524
|
-
const nodeId = Object.keys(state.waits)[0];
|
|
525
|
-
return { outcome: { status: 'WAITING_EVENT', event: { nodeId, ...state.waits[nodeId] } }, task: await findTask(), fallback: false };
|
|
526
|
-
}
|
|
527
|
-
const finalResult = { summary: `Shortcut Agent Graph completed (${graph.nodes.length} nodes)`, data: { shortcut: state } };
|
|
528
|
-
const done = await transitions.apply(job.id, task.id, 'task.completed', {
|
|
529
|
-
eligible: (_j, t) => t.state === 'RUNNING' && t.leaseOwner === owner,
|
|
530
|
-
mutate: (_j, t) => { t.result = finalResult; t.leaseOwner = null; t.leaseExpiresAt = null; t.executionId = null; }
|
|
531
|
-
});
|
|
532
|
-
if (!done?.decision.accepted)
|
|
533
|
-
throw new Error('Task lifecycle graph rejected task.completed');
|
|
534
|
-
stopHeartbeat();
|
|
535
|
-
await store.mutateJob(job.id, current => {
|
|
536
|
-
const allowed = shortcutJobCompletionAllowed(current);
|
|
537
|
-
dispatchJobLifecycleSync(current, 'shortcut.completed', { shortcutCompletionAllowed: allowed });
|
|
538
|
-
return current;
|
|
539
|
-
});
|
|
540
|
-
return { outcome: { status: 'COMPLETED', output: { nodes: state.nodes }, artifacts: Object.values(state.nodes).flatMap(node => {
|
|
541
|
-
if (Array.isArray(node.artifacts))
|
|
542
|
-
return node.artifacts;
|
|
543
|
-
const output = node.output;
|
|
544
|
-
return output && typeof output === 'object' ? Object.values(output).filter((value) => typeof value === 'string') : [];
|
|
545
|
-
}) }, task: await findTask(), fallback: false };
|
|
546
|
-
}
|
|
547
|
-
finally {
|
|
548
|
-
stopHeartbeat();
|
|
549
|
-
}
|
|
550
|
-
async function persist(next) {
|
|
551
|
-
await store.mutateJob(job.id, fresh => {
|
|
552
|
-
const t = fresh.tasks.find(item => item.id === task.id);
|
|
553
|
-
if (fresh.state !== 'ACTIVE' || fresh.pause || !t || t.state !== 'RUNNING' || t.leaseOwner !== owner || !t.executionId)
|
|
554
|
-
throw new Error('Shortcut checkpoint fenced by execution lease');
|
|
555
|
-
const previous = t.result ?? { summary: 'Shortcut execution in progress', data: {} };
|
|
556
|
-
t.result = { ...previous, data: { ...(previous.data ?? {}), shortcut: structuredClone(next) } };
|
|
557
|
-
t.leaseExpiresAt = new Date(Date.now() + leaseMs).toISOString();
|
|
558
|
-
return fresh;
|
|
559
|
-
});
|
|
560
|
-
}
|
|
561
|
-
async function findTask() { const fresh = await store.load(job.id); const found = fresh.tasks.find(item => item.id === task.id); if (!found)
|
|
562
|
-
throw new Error('Task disappeared'); return found; }
|
|
563
|
-
async function fail(reason) {
|
|
564
|
-
const interrupted = options.signal?.aborted === true;
|
|
565
|
-
const failure = interrupted ? `Shortcut execution interrupted: ${reason}` : reason;
|
|
566
|
-
for (const nodeId of Object.keys(state.inFlight ?? {}))
|
|
567
|
-
emit({ nodeId, type: 'failed', data: { executionId: currentTask.executionId, reason: failure } });
|
|
568
|
-
stopHeartbeat();
|
|
569
|
-
const result = await transitions.apply(job.id, task.id, 'shortcut.failed', {
|
|
570
|
-
eligible: (_j, t) => t.state === 'RUNNING' && t.leaseOwner === owner,
|
|
571
|
-
mutate: (_j, t) => {
|
|
572
|
-
t.error = failure;
|
|
573
|
-
t.leaseOwner = null;
|
|
574
|
-
t.leaseExpiresAt = null;
|
|
575
|
-
t.executionId = null;
|
|
576
|
-
const prior = t.result ?? { summary: 'Shortcut execution failed', data: {} };
|
|
577
|
-
t.result = { ...prior, summary: failure, data: { ...(prior.data ?? {}), shortcut: { ...state, terminal: { status: interrupted ? 'INTERRUPTED' : 'FAILED', reason: failure, at: new Date().toISOString(), executionId: currentTask.executionId } } } };
|
|
578
|
-
},
|
|
579
|
-
});
|
|
580
|
-
if (!result?.decision.accepted)
|
|
581
|
-
throw new Error(`Task lifecycle graph rejected shortcut failure: ${failure}`);
|
|
582
|
-
return { outcome: { status: 'FAILED', reason: failure }, task: await findTask(), fallback: false };
|
|
583
|
-
}
|
|
584
|
-
}
|
|
585
|
-
export function shortcutResumeEvent(_value) {
|
|
586
|
-
throw new Error('--event-json is disabled: manual JSON cannot authenticate a human approval or durable event receipt');
|
|
587
|
-
}
|
|
@@ -1,50 +0,0 @@
|
|
|
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
|
-
legacyShortcutBootstrap: true, 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, false, kind === 'job');
|
|
27
|
-
const requestedRepo = kind === 'job' ? arg(args, '--repo') : repository(args);
|
|
28
|
-
if ((requestedRepo && job.repository !== requestedRepo) || job.executionMode !== 'shortcut' || job.contentOnly !== true)
|
|
29
|
-
throw new Error('local shortcut Job identity mismatch');
|
|
30
|
-
console.log(JSON.stringify(kind === 'job' ? job : job.tasks, null, 2));
|
|
31
|
-
return;
|
|
32
|
-
}
|
|
33
|
-
if (kind === 'task' && action === 'create') {
|
|
34
|
-
const { store, job, localFile } = await storeFor(args);
|
|
35
|
-
if (localFile !== null || !store.mutateJob || job.repository !== repository(args) || job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'DRAFT')
|
|
36
|
-
throw new Error('local shortcut Task creation requires a DRAFT content-only SQLite Job');
|
|
37
|
-
const task = await workerTaskFromArgs(job, args, new Date().toISOString());
|
|
38
|
-
if (task.id !== arg(args, '--task-id') || !task.agentGraph || task.output?.kind !== 'file')
|
|
39
|
-
throw new Error('local shortcut Task must have explicit ID, Agent Graph and file output');
|
|
40
|
-
await store.mutateJob(job.id, current => {
|
|
41
|
-
if (current.state !== 'DRAFT' || current.tasks.some(existing => existing.id === task.id))
|
|
42
|
-
throw new Error('local shortcut Task already exists or Job is no longer DRAFT');
|
|
43
|
-
current.tasks.push(structuredClone(task));
|
|
44
|
-
return current;
|
|
45
|
-
});
|
|
46
|
-
console.log(JSON.stringify(task, null, 2));
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
throw new Error('unsupported local shortcut command; only create, show and list bindings are allowed');
|
|
50
|
-
}
|