agents-relay 2.0.195 → 2.0.196
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters.js +10 -6
- package/dist/agent-content-resolver.js +28 -1
- package/dist/agent-prompt-builder.js +73 -3
- package/dist/browser-worker-runtime.js +40 -22
- package/dist/cli-help.js +20 -5
- package/dist/cli-prompt.js +132 -0
- package/dist/cli-shutdown.js +3 -0
- package/dist/cli-support.js +47 -5
- package/dist/cli.js +19 -30
- package/dist/events-bus-runtime.js +58 -8
- package/dist/local-job-registry.js +9 -5
- package/dist/managed-worker-input.js +48 -74
- package/dist/planner.js +16 -10
- package/dist/reconciler.js +3 -7
- package/dist/troubleshooter.js +2 -2
- package/dist/z-adapter.js +16 -8
- package/package.json +3 -1
- package/skills/agents-relay/SKILL.md +82 -30
- package/skills/agents-relay/agents/implementation.agent.md +1 -2
- package/skills/agents-relay/agents/planner.agent.md +12 -12
- package/skills/agents-relay/agents/reviewer.agent.md +1 -1
- package/skills/agents-relay/agents/troubleshooter.agent.md +6 -6
- package/skills/agents-relay/contracts/event-contract.md +6 -3
- package/skills/agents-relay/contracts/orchestrator-workflows.md +6 -4
- package/skills/agents-relay/contracts/task-job-contract.md +23 -20
- package/skills/agents-relay/contracts/task-recovery-flows.md +15 -35
package/dist/adapters.js
CHANGED
|
@@ -281,8 +281,9 @@ export async function ensureChatGptWebHelmReady(command = process.env.AGENTS_REL
|
|
|
281
281
|
function browserWorkerRunner() {
|
|
282
282
|
return (_definition, request, _route, signal, context) => {
|
|
283
283
|
const delivery = request.thread;
|
|
284
|
-
const message = request.files?.length
|
|
285
|
-
|
|
284
|
+
const message = request.files?.length && !request.prompt.startsWith('# Role')
|
|
285
|
+
&& !request.prompt.startsWith('[Relay agent:')
|
|
286
|
+
? `${request.prompt}\n\nTask file paths (read with Neo MCP):\n${request.files.map(file => `- ${JSON.stringify(file)}`).join('\n')}`
|
|
286
287
|
: request.prompt;
|
|
287
288
|
return pooledWebHelmRun({
|
|
288
289
|
provider: 'chatgpt', executionId: request.execution?.executionId ?? randomUUID(),
|
|
@@ -291,7 +292,7 @@ function browserWorkerRunner() {
|
|
|
291
292
|
build: async () => ({ action: delivery ? 'new-turn' : 'new-thread', config: delivery ? {
|
|
292
293
|
project_id: delivery.projectId ?? _route.projectId ?? null,
|
|
293
294
|
thread_id: delivery.threadId,
|
|
294
|
-
message:
|
|
295
|
+
message: request.prompt,
|
|
295
296
|
mode: 'sync', idempotency_key: delivery.requestId,
|
|
296
297
|
} : { message, temporary: false } }),
|
|
297
298
|
recover: async (threadId) => ({
|
|
@@ -372,7 +373,10 @@ export class ChatGptAdapter {
|
|
|
372
373
|
const policy = chatGptTabClosePolicy(task.chatgptTabClosePolicy, this.tabClosePolicy);
|
|
373
374
|
const submit = async () => {
|
|
374
375
|
const references = await accessiblePromptReferences(task.input);
|
|
375
|
-
|
|
376
|
+
// The Graph Action owns immutable Prompt bytes; legacy Task prose alone
|
|
377
|
+
// uses the compatibility new-turn wrapper.
|
|
378
|
+
const graphPrompt = task.input.startsWith('# Role') || task.input.startsWith('[Relay agent:');
|
|
379
|
+
let prompt = task.chatgptThreadDelivery?.repository && task.chatgptThreadDelivery.executionId && !graphPrompt
|
|
376
380
|
? taskReferencePrompt(task.chatgptThreadDelivery.repository, task.chatgptThreadDelivery.jobId, task.id, task.chatgptThreadDelivery.executionId, task.input) : task.input;
|
|
377
381
|
const referencePrompt = task.chatgptThreadDelivery && references.length
|
|
378
382
|
? `\n\n[Inline immutable local reference snapshots]\nThese complete verified snapshots are included in this message because this thread delivery does not attach local files. Follow their contents according to their declared roles.\n${references.map(reference => `\n--- ${reference.role}: ${reference.path} (sha256:${reference.sha256}) ---\n${reference.content}\n--- end snapshot ---`).join('\n')}`
|
|
@@ -383,10 +387,10 @@ export class ChatGptAdapter {
|
|
|
383
387
|
const unresolved = declaredPromptReferences(task.input)
|
|
384
388
|
.map(item => item.path).filter(path => !references.some(reference => reference.path === path));
|
|
385
389
|
if (unresolved.length)
|
|
386
|
-
|
|
390
|
+
throw new Error(`Agent Contract snapshot unavailable or corrupt: ${unresolved.join(', ')}`);
|
|
387
391
|
}
|
|
388
392
|
return (this.runner ?? browserWorkerRunner())(definition, {
|
|
389
|
-
prompt: prompt + referencePrompt,
|
|
393
|
+
prompt: graphPrompt ? prompt : prompt + referencePrompt,
|
|
390
394
|
...((task.attachments?.length || references.length && !task.chatgptThreadDelivery) ? { files: [...new Set([...(task.attachments ?? []), ...references.map(reference => reference.path)])] } : {}),
|
|
391
395
|
...(task.chatgptThreadDelivery ? { thread: task.chatgptThreadDelivery } : {}),
|
|
392
396
|
tabClosePolicy: policy,
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { readFile, realpath } from 'node:fs/promises';
|
|
3
|
-
import { join } from 'node:path';
|
|
3
|
+
import { dirname, join, resolve } from 'node:path';
|
|
4
4
|
const parseList = (raw) => raw.trim().replace(/^\[/, '').replace(/\]$/, '').split(',').map(s => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean);
|
|
5
5
|
/** Restrict the frontmatter grammar to the explicitly supported scalar/list fields. */
|
|
6
6
|
function parseDocument(raw) {
|
|
@@ -35,6 +35,32 @@ function parseDocument(raw) {
|
|
|
35
35
|
}
|
|
36
36
|
return { body: raw.slice(match[0].length).trim(), name, extendsAgent, mode, replace: sections.replace, extend: sections.extend };
|
|
37
37
|
}
|
|
38
|
+
/** A cached merged Agent has no useful directory for source-relative links.
|
|
39
|
+
* Canonicalize link destinations in each layer BEFORE merging, preserving the
|
|
40
|
+
* real source file's link base without inlining the linked document. */
|
|
41
|
+
function absoluteAgentLinks(body, sourcePath) {
|
|
42
|
+
let fence;
|
|
43
|
+
return body.split('\n').map(line => {
|
|
44
|
+
const open = /^\s*(`{3,}|~{3,})/.exec(line)?.[1];
|
|
45
|
+
if (open) {
|
|
46
|
+
if (!fence)
|
|
47
|
+
fence = open[0];
|
|
48
|
+
else if (fence === open[0])
|
|
49
|
+
fence = undefined;
|
|
50
|
+
return line;
|
|
51
|
+
}
|
|
52
|
+
if (fence)
|
|
53
|
+
return line;
|
|
54
|
+
return line.replace(/(\]\()([^\s)]+)(\))/g, (full, prefix, destination, suffix) => {
|
|
55
|
+
if (destination.startsWith('/') || destination.startsWith('#') || /^[a-z][a-z0-9+.-]*:/i.test(destination))
|
|
56
|
+
return full;
|
|
57
|
+
const hash = destination.search(/[?#]/);
|
|
58
|
+
const pathname = hash === -1 ? destination : destination.slice(0, hash);
|
|
59
|
+
const fragment = hash === -1 ? '' : destination.slice(hash);
|
|
60
|
+
return `${prefix}${resolve(dirname(sourcePath), pathname)}${fragment}${suffix}`;
|
|
61
|
+
});
|
|
62
|
+
}).join('\n');
|
|
63
|
+
}
|
|
38
64
|
function indexSections(lines) {
|
|
39
65
|
const sections = new Map();
|
|
40
66
|
const stack = [];
|
|
@@ -106,6 +132,7 @@ export async function resolveAgentMarkdown(name, builtinsRoot, contextRoot, neoR
|
|
|
106
132
|
throw new Error('Agent file escapes context root');
|
|
107
133
|
const raw = await readFile(canonical, 'utf8');
|
|
108
134
|
const source = parseDocument(raw);
|
|
135
|
+
source.body = absoluteAgentLinks(source.body, canonical);
|
|
109
136
|
if (source.name && source.name !== name)
|
|
110
137
|
throw new Error(`Agent name mismatch ${source.name} != ${name}`);
|
|
111
138
|
return { ...source, path: canonical, metadata: Object.fromEntries(raw.match(/^---\r?\n([\s\S]*?)\r?\n---/m)?.[1].split(/\r?\n/).flatMap(line => {
|
|
@@ -63,17 +63,87 @@ export async function buildReferenceFirstPrompt(input) {
|
|
|
63
63
|
reference = await snapshotAgentInstructions(input.system, referenceDirectory);
|
|
64
64
|
}
|
|
65
65
|
catch (error) {
|
|
66
|
-
if (error instanceof Error && error.message === 'Prompt snapshot digest mismatch')
|
|
66
|
+
if (input.strictReference || (error instanceof Error && error.message === 'Prompt snapshot digest mismatch'))
|
|
67
67
|
throw error;
|
|
68
68
|
return buildAgentPrompt(input);
|
|
69
69
|
}
|
|
70
|
-
if (!await isPromptReferenceAccessible(reference.path))
|
|
70
|
+
if (!await isPromptReferenceAccessible(reference.path)) {
|
|
71
|
+
if (input.strictReference)
|
|
72
|
+
throw new Error(`Immutable Agent Contract unavailable: ${reference.path}`);
|
|
71
73
|
return buildAgentPrompt(input);
|
|
74
|
+
}
|
|
72
75
|
return buildAgentPrompt({
|
|
73
76
|
role: input.role,
|
|
74
77
|
system: (input.bootstrap ? input.bootstrap.trim() + '\n' : '') +
|
|
75
78
|
'After the required execution startup action, read the referenced immutable Agent Contract snapshot and follow it. Relay owns snapshot integrity and version identity; do not compute a hash of the source .agent.md or compare it to the snapshot. If the snapshot is unreadable, report a concrete failure; never guess its instructions.',
|
|
76
79
|
user: input.user,
|
|
77
|
-
references: [reference],
|
|
80
|
+
references: [reference, ...(input.contextRefs ?? [])],
|
|
78
81
|
});
|
|
79
82
|
}
|
|
83
|
+
/** The one Graph dispatch / CLI action for production worker-facing instructions.
|
|
84
|
+
* Only an Agent can be resolved/merged; contracts and project contexts remain
|
|
85
|
+
* independent files, listed from base to higher-precedence project instructions.
|
|
86
|
+
*/
|
|
87
|
+
export async function buildRelayWorkPrompt(input) {
|
|
88
|
+
if (!input.jobId || !input.taskId || !input.executionId)
|
|
89
|
+
throw new Error('Relay prompt requires a full execution binding');
|
|
90
|
+
const reference = await snapshotAgentInstructions(input.agentContent, process.env.AGENTS_RELAY_PROMPT_REFERENCE_DIR ?? DEFAULT_PROMPT_REFERENCE_DIRECTORY);
|
|
91
|
+
const contracts = await Promise.all(input.contracts.map(path => promptFileReference(path, 'context')));
|
|
92
|
+
// Global AGENTS is Bootstrap-owned and README is human documentation.
|
|
93
|
+
// The calling Role Action selects context intentionally, not by a directory dump.
|
|
94
|
+
const ranks = { neo: 0, project: 1 };
|
|
95
|
+
const orderedContext = input.contexts.filter(item => (item.source === 'neo' || item.source === 'project') && item.path.endsWith('/AGENTS.md'))
|
|
96
|
+
.sort((a, b) => (ranks[a.source] ?? 0) - (ranks[b.source] ?? 0));
|
|
97
|
+
const contexts = await Promise.all(orderedContext.map(item => promptFileReference(item.path, 'context')));
|
|
98
|
+
const global = input.adapter === 'codex'
|
|
99
|
+
? input.contexts.find(item => item.source === 'global' && item.path.endsWith('/AGENTS.md'))
|
|
100
|
+
: undefined;
|
|
101
|
+
const globalReference = global ? await promptFileReference(global.path, 'context') : undefined;
|
|
102
|
+
const bootstrap = input.adapter === 'codex'
|
|
103
|
+
? [
|
|
104
|
+
`Use Codex CLI with project cwd: ${input.projectPath}. Codex -C loads directory AGENTS.md instructions.`,
|
|
105
|
+
...(globalReference ? [`Read global Neo rules once if they are not already loaded: ${globalReference.path} (sha256:${globalReference.sha256}).`] : []),
|
|
106
|
+
'Use local shell and files for referenced contracts and the Relay CLI. Do not call neo bootstrap.',
|
|
107
|
+
]
|
|
108
|
+
: input.adapter === 'chatgpt'
|
|
109
|
+
? [
|
|
110
|
+
'Account Default Instructions already initialize the Neo/XChat Harness.',
|
|
111
|
+
'Use the connected Neo MCP fs/shell tools to read the listed Neo Master files and execute Relay CLI. Do not run neo bootstrap again.',
|
|
112
|
+
]
|
|
113
|
+
: [
|
|
114
|
+
'The Z runtime supplies a one-hour Neo OAuth access token (never the operator or refresh token). Do not ask the user to copy a token.',
|
|
115
|
+
'Use the same Z interactive bootstrap entry: https://neoy.qili2.com/files/z-chat/bootstrap.md.',
|
|
116
|
+
'Run Neo MCP through authenticated HTTPS. The Z cloud filesystem is not Neo Master. Continue the assigned Task after bootstrap; do not wait for another user message.',
|
|
117
|
+
];
|
|
118
|
+
const skill = await promptFileReference(input.skillPath, 'context');
|
|
119
|
+
const lines = [
|
|
120
|
+
'# Role',
|
|
121
|
+
`You are ${input.agentName} with responsibility at ${reference.path} (sha256:${reference.sha256}).`,
|
|
122
|
+
'', '## Bootstrap',
|
|
123
|
+
...bootstrap,
|
|
124
|
+
'', '## Contracts',
|
|
125
|
+
...(input.agentName === 'planner'
|
|
126
|
+
? ['MANDATORY: Read the listed Plan/Task contract before planning. A Plan does not publish Task events.']
|
|
127
|
+
: ['MANDATORY: Read every listed Task and Events contract before execution.']),
|
|
128
|
+
'Read independently, in order. Later, more specific contracts take precedence over general rules.',
|
|
129
|
+
...contracts.map((ref, i) => `${i + 1}. ${ref.path} (sha256:${ref.sha256})`),
|
|
130
|
+
...(input.agentName === 'planner' ? [
|
|
131
|
+
'Planner lifecycle: use the execution-bound `plan context` from the matching Relay CLI described by the Skill. Run the returned same-version `apply_cli`, and return the exact PLAN_APPLIED receipt. Do not emit Task events for a Plan.',
|
|
132
|
+
] : [
|
|
133
|
+
`EVENT SOURCE (exact): job/${input.jobId}/task/${input.taskId}/execution/${input.executionId}`,
|
|
134
|
+
'START: After Bootstrap and the minimal event-contract preflight, publish `task.started` through the canonical events-bus before beginning Task work. Verify the publish response.',
|
|
135
|
+
'PROGRESS: Publish `task.progress` with concrete progress/evidence during long-running work and before the inactivity timeout. Progress is not completion.',
|
|
136
|
+
'TERMINAL: After verifying durable output, publish exactly ONE `task.completed`; if you cannot fulfill the Task, publish `task.failed` with phase, reason and evidence. Do not silently exit or treat a process/browser receipt as completion.',
|
|
137
|
+
'Every event MUST use the exact source above. Do not publish `task.blocked` or `task.unblocked`; those are Relay-owned states. Relay must accept the correlated event.',
|
|
138
|
+
]),
|
|
139
|
+
'', '## Contexts',
|
|
140
|
+
...(contexts.length ? ['Read only these additional role-relevant rules. Bootstrap and inherited Agent rules are not duplicated here.', ...contexts.map((ref, i) => `${i + 1}. [${orderedContext[i].source}] ${ref.path} (sha256:${ref.sha256})`)] : ['None required at startup. Read files only when selected by the Agent contract or the current Task.']),
|
|
141
|
+
'', '## Task',
|
|
142
|
+
`Use the agents-relay skill at ${skill.path} (sha256:${skill.sha256}) to read authoritative Job and Task/Plan details via the Relay CLI.`,
|
|
143
|
+
'All Relay state reads and operations use that version-matched CLI. Publish only required Task events through the separately listed Neo events-bus protocol; never inspect Relay backing storage or HTTP APIs.',
|
|
144
|
+
`Job: ${input.jobId}`,
|
|
145
|
+
`Task: ${input.taskId}`,
|
|
146
|
+
`Execution: ${input.executionId}`,
|
|
147
|
+
];
|
|
148
|
+
return lines.join('\n');
|
|
149
|
+
}
|
|
@@ -85,35 +85,43 @@ export function pooledWebHelmRun(request, signal) {
|
|
|
85
85
|
let stopped = false;
|
|
86
86
|
let monitor;
|
|
87
87
|
let completionRecoveryTimer;
|
|
88
|
+
let pendingProbe, pendingCompletionRecovery;
|
|
89
|
+
let stopping;
|
|
88
90
|
let browserKeepAliveAt = 0, observedAt = Date.now(), lastFingerprint = '', sampled = false;
|
|
89
91
|
let recoveries = 0, monitoring = false, threadId;
|
|
90
92
|
let submissionAttempted = false, verifiedSubmitted = false, uncertain = false, recoveryOutcomeUncertain = false;
|
|
91
93
|
let providerPreflightFailed = false;
|
|
92
|
-
const stop =
|
|
93
|
-
if (
|
|
94
|
-
return;
|
|
94
|
+
const stop = () => {
|
|
95
|
+
if (stopping)
|
|
96
|
+
return stopping;
|
|
95
97
|
stopped = true;
|
|
96
98
|
if (monitor)
|
|
97
99
|
clearInterval(monitor);
|
|
98
100
|
if (completionRecoveryTimer)
|
|
99
101
|
clearTimeout(completionRecoveryTimer);
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
102
|
+
stopping = (async () => {
|
|
103
|
+
// Clearing the interval does not cancel an already running WebHelm
|
|
104
|
+
// command. Drain it before closing the session or releasing the slot.
|
|
105
|
+
await Promise.allSettled([pendingProbe, pendingCompletionRecovery]);
|
|
106
|
+
if (!lease)
|
|
107
|
+
return;
|
|
108
|
+
if (uncertain) {
|
|
109
|
+
pool.quarantine(lease);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (!sessionId) {
|
|
113
|
+
pool.release(lease);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
await cliCommand(['session', 'stop', sessionId]);
|
|
118
|
+
pool.release(lease);
|
|
119
|
+
}
|
|
120
|
+
catch {
|
|
121
|
+
pool.quarantine(lease);
|
|
122
|
+
}
|
|
123
|
+
})();
|
|
124
|
+
return stopping;
|
|
117
125
|
};
|
|
118
126
|
const release = async () => { released = true; if (lease)
|
|
119
127
|
await stop(); };
|
|
@@ -238,10 +246,20 @@ export function pooledWebHelmRun(request, signal) {
|
|
|
238
246
|
// Completion proof is independent of CDP polling. Give the worker time to emit
|
|
239
247
|
// its correlated terminal event; the terminal event closes this lease before recovery.
|
|
240
248
|
if (receipt.status === 'completed' && request.recover) {
|
|
241
|
-
completionRecoveryTimer = setTimeout(() => {
|
|
249
|
+
completionRecoveryTimer = setTimeout(() => {
|
|
250
|
+
pendingCompletionRecovery = sendRecovery().catch(() => { });
|
|
251
|
+
}, request.completionRecoveryGraceMs ?? 12_000);
|
|
242
252
|
completionRecoveryTimer.unref();
|
|
243
253
|
}
|
|
244
|
-
monitor = setInterval(() => {
|
|
254
|
+
monitor = setInterval(() => {
|
|
255
|
+
if (monitoring || stopped)
|
|
256
|
+
return;
|
|
257
|
+
const running = probe();
|
|
258
|
+
pendingProbe = running;
|
|
259
|
+
void running.then(() => { if (pendingProbe === running)
|
|
260
|
+
pendingProbe = undefined; }, () => { if (pendingProbe === running)
|
|
261
|
+
pendingProbe = undefined; });
|
|
262
|
+
}, request.monitorIntervalMs ?? 30_000);
|
|
245
263
|
monitor.unref();
|
|
246
264
|
return JSON.stringify(receipt);
|
|
247
265
|
}
|
package/dist/cli-help.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const usage = 'agents-relay <job|task|review|artifact|plan|blocker|projection|escalation|context|init|record|agent-register|agent-discover|status|reconcile|serve> [options]';
|
|
1
|
+
export const usage = 'agents-relay <job|task|review|artifact|plan|prompt|blocker|projection|escalation|context|init|record|agent-register|agent-discover|status|reconcile|serve> [options]';
|
|
2
2
|
const help = {
|
|
3
3
|
root: `Agents Relay coordinates durable asynchronous agent jobs through local SQLite and workflow graphs.
|
|
4
4
|
|
|
@@ -14,6 +14,8 @@ Commands:
|
|
|
14
14
|
artifact validate Check a JSON artifact against a project-owned JSON Schema
|
|
15
15
|
plan Invoke the Planner for an existing managed Job
|
|
16
16
|
plan apply Submit a validated Task Tree within one active Plan
|
|
17
|
+
plan context Read execution-bound Planner context from SQLite
|
|
18
|
+
prompt Print raw Planner/Worker prompt from the production Builder
|
|
17
19
|
blocker add|resolve|show Manage cross-Job blocker dependencies
|
|
18
20
|
projection conflicts|resolve Inspect and repair deterministic GitHub projection conflicts
|
|
19
21
|
escalation Run the canonical escalation graph and Neo escalation executor
|
|
@@ -51,6 +53,16 @@ Common options:
|
|
|
51
53
|
|
|
52
54
|
Example:
|
|
53
55
|
npx agents-relay job show --repo OWNER/REPO --pr 12 --id 101`,
|
|
56
|
+
prompt: `Read-only exact PromptBuilder output for a durable Plan or Task.
|
|
57
|
+
|
|
58
|
+
agents-relay prompt --id JOB --plan-id PLAN --adapter codex|chatgpt|z [--output FILE]
|
|
59
|
+
agents-relay prompt --id JOB --task-id TASK --adapter codex|chatgpt|z [--output FILE]
|
|
60
|
+
|
|
61
|
+
Raw worker-facing text on stdout, no profile wrapper. --repo selects local SQLite,
|
|
62
|
+
not GitHub. Old completed Plans are reconstructed from recorded IDs and prior
|
|
63
|
+
Task history; their original historical prompt bytes are not persisted. Only
|
|
64
|
+
Codex currently has production Planner dispatch. Web Planner variants show the
|
|
65
|
+
same Builder message targeting the other transports, not a live delivery.`,
|
|
54
66
|
review: `Use review run for an Agent-owned outcome review, or request for the SHA-bound final review.
|
|
55
67
|
|
|
56
68
|
Outcome: agents-relay review run --prompt-file PATH --agents video-director,market --project-path DIR [--output PATH]
|
|
@@ -128,7 +140,7 @@ Returns the same summary used by the dashboard header plus a running array with
|
|
|
128
140
|
task: `Manage durable tasks.
|
|
129
141
|
|
|
130
142
|
Usage:
|
|
131
|
-
npx agents-relay task <create|update|show|list|retry|unblock|cancel> [options]
|
|
143
|
+
npx agents-relay task <create|update|show|events|list|retry|unblock|cancel> [options]
|
|
132
144
|
|
|
133
145
|
Actions:
|
|
134
146
|
create Create one durable Task under an existing Job
|
|
@@ -149,7 +161,7 @@ Example:
|
|
|
149
161
|
npx agents-relay task create --repo OWNER/REPO --id j-5-owner-repo-1 --output file --output-path story.md --input-file task.md`,
|
|
150
162
|
'task update': `Update mutable durable Task fields in place.
|
|
151
163
|
|
|
152
|
-
Required: --task-id ID
|
|
164
|
+
Required: --id JOB_ID --task-id ID. Optional --repo OWNER/REPO fences the Job identity.
|
|
153
165
|
Mutable while not RUNNING/SUCCEEDED/CANCELLED: --title, --adapter, --priority, --story-size, --input-file PATH|- or --input MARKDOWN, --project, --agent, --agent-graph-file PATH|-, --parent, --deps, --capabilities, --timeout (inactivity window), --max-attempts, --provider, --model, --profile, --reasoning, --cwd, --chatgpt-project, --chatgpt-tab-close-policy, --draft, --queue.
|
|
154
166
|
Accepted task.started and newer current-execution task.progress events reset --timeout.
|
|
155
167
|
Use --clear-routing to remove routing metadata.
|
|
@@ -161,10 +173,13 @@ Example:
|
|
|
161
173
|
Required: --repo OWNER/REPO --id JOB_ID --task-id TASK_ID and --message TEXT or --message-file FILE.`,
|
|
162
174
|
'task comments': `List append-only Task comments.
|
|
163
175
|
|
|
164
|
-
Required: --
|
|
176
|
+
Required: --id JOB_ID --task-id TASK_ID. Optional --repo OWNER/REPO fences the Job identity.`,
|
|
165
177
|
'task context': `Read the authoritative execution-scoped Task contract.
|
|
166
178
|
|
|
167
|
-
Required: --
|
|
179
|
+
Required: --id JOB_ID --task-id TASK_ID --execution-id EXECUTION_ID. Optional --repo OWNER/REPO fences the Job identity. Fails closed on stale execution.`,
|
|
180
|
+
'task events': `Read the latest Task-scoped lifecycle events via Relay.
|
|
181
|
+
|
|
182
|
+
Required: --id JOB_ID --task-id TASK_ID. Optional --repo, --limit 1..60 (default 60), --order asc|desc (default desc), --after CURSOR (for asc). To read full history: start with --order asc --after 0, then repeat with nextCursor until a page has fewer than --limit events. Failure to retrieve history is not success.`,
|
|
168
183
|
'task show': `Show one durable Task.
|
|
169
184
|
|
|
170
185
|
Required: --task-id ID and the normal Job storage options.`,
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { writeFile } from 'node:fs/promises';
|
|
2
|
+
import { plannerInput } from './planner.js';
|
|
3
|
+
import { arg, storeFor } from './cli-support.js';
|
|
4
|
+
import { resolveExecutionContext } from './execution-context.js';
|
|
5
|
+
import { buildPlannerExecutionPrompt } from './planner.js';
|
|
6
|
+
import { managedWorkerInput } from './managed-worker-input.js';
|
|
7
|
+
import { resolveManagedProjectPath, resolveRepositoryProjectPath } from './workspace.js';
|
|
8
|
+
import { taskExecutionContext } from './task-context.js';
|
|
9
|
+
import { eventsBusHistoryPage } from './events-bus-runtime.js';
|
|
10
|
+
/** Print the actual prompt emitted by the same production Builder entry point.
|
|
11
|
+
* This is read-only: it does not start an adapter, create a Plan or mutate a Task.
|
|
12
|
+
*/
|
|
13
|
+
export async function runPromptCommand(args) {
|
|
14
|
+
const adapter = arg(args, '--adapter', 'codex');
|
|
15
|
+
if (!['codex', 'chatgpt', 'z'].includes(adapter))
|
|
16
|
+
throw new Error('prompt --adapter must be codex|chatgpt|z');
|
|
17
|
+
const planId = arg(args, '--plan-id'), taskId = arg(args, '--task-id');
|
|
18
|
+
if (!!planId === !!taskId)
|
|
19
|
+
throw new Error('prompt requires exactly one of --plan-id or --task-id');
|
|
20
|
+
const { job } = await storeFor(args, true);
|
|
21
|
+
const projectPath = arg(args, '--project-path') || resolveRepositoryProjectPath(await resolveManagedProjectPath(job.repository), job.projectPath);
|
|
22
|
+
let prompt;
|
|
23
|
+
if (planId) {
|
|
24
|
+
const plan = job.plans?.find(item => item.id === planId);
|
|
25
|
+
if (!plan)
|
|
26
|
+
throw new Error(`Plan ${planId} not found in Job ${job.id}`);
|
|
27
|
+
const executionId = plan.executionId || plan.appliedExecutionId;
|
|
28
|
+
if (!executionId)
|
|
29
|
+
throw new Error(`Plan ${planId} has no recorded execution identity`);
|
|
30
|
+
// An immutable historical Planner input is not persisted. Exclude tasks
|
|
31
|
+
// and plans written AFTER the selected planning round to avoid injecting
|
|
32
|
+
// future results as though the Planner had already observed them.
|
|
33
|
+
const boundary = plan.createdAt;
|
|
34
|
+
const historicalTasks = job.tasks.filter(task => task.createdAt < boundary);
|
|
35
|
+
const historicalPlans = (job.plans ?? []).filter(item => item.round <= plan.round).map(item => item.id === plan.id ? { ...item, status: 'PLANNING', executionId, appliedExecutionId: undefined, generatedTaskIds: [] } : item);
|
|
36
|
+
const historicalJob = { ...job, tasks: historicalTasks, plans: historicalPlans };
|
|
37
|
+
const context = await resolveExecutionContext(projectPath, 'planner');
|
|
38
|
+
const planner = {
|
|
39
|
+
job: historicalJob, tasks: historicalTasks,
|
|
40
|
+
objective: job.objective ?? job.description ?? job.title,
|
|
41
|
+
previousPlannerTaskId: plan.previousPlanId,
|
|
42
|
+
planExecution: { planId, executionId },
|
|
43
|
+
trigger: plan.trigger, guidance: plan.guidance,
|
|
44
|
+
retryFeedback: plan.retryFeedback, forceRestate: plan.forceRestate,
|
|
45
|
+
restateTaskIds: plan.restateTaskIds, executionContext: context,
|
|
46
|
+
};
|
|
47
|
+
prompt = await buildPlannerExecutionPrompt(planner, undefined, adapter);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
const task = job.tasks.find(item => item.id === taskId);
|
|
51
|
+
if (!task)
|
|
52
|
+
throw new Error(`Task ${taskId} not found in Job ${job.id}`);
|
|
53
|
+
if (!task.executionId)
|
|
54
|
+
throw new Error(`Task ${taskId} has no execution ID`);
|
|
55
|
+
const context = await resolveExecutionContext(projectPath, task.agentName === 'troubleshooter' ? 'troubleshooter' : task.agentName === 'reviewer' ? 'reviewer' : 'worker');
|
|
56
|
+
prompt = await managedWorkerInput(job, { ...task, adapter }, context);
|
|
57
|
+
}
|
|
58
|
+
const output = arg(args, '--output');
|
|
59
|
+
if (output)
|
|
60
|
+
await writeFile(output, prompt + '\n', { mode: 0o600 });
|
|
61
|
+
else
|
|
62
|
+
console.log(prompt);
|
|
63
|
+
}
|
|
64
|
+
/** Authorized active Plan Context retrieval, like `task context`, from SQLite.
|
|
65
|
+
* Read-only; a stale or completed Plan cannot claim a current execution.
|
|
66
|
+
*/
|
|
67
|
+
export async function runPlanContextCommand(args) {
|
|
68
|
+
const planId = arg(args, '--plan-id'), executionId = arg(args, '--execution-id');
|
|
69
|
+
if (!planId || !executionId)
|
|
70
|
+
throw new Error('plan context requires --plan-id and --execution-id');
|
|
71
|
+
const { job } = await storeFor(args, true);
|
|
72
|
+
const plan = job.plans?.find(p => p.id === planId);
|
|
73
|
+
if (!plan || plan.status !== 'PLANNING' || plan.executionId !== executionId)
|
|
74
|
+
throw new Error(`Stale Plan execution ${planId}/${executionId}; current state ${plan?.status ?? 'not-found'}`);
|
|
75
|
+
const projectPath = arg(args, '--project-path') || resolveRepositoryProjectPath(await resolveManagedProjectPath(job.repository), job.projectPath);
|
|
76
|
+
const context = await resolveExecutionContext(projectPath, 'planner');
|
|
77
|
+
const input = { job, tasks: job.tasks, objective: job.objective ?? job.description ?? job.title,
|
|
78
|
+
previousPlannerTaskId: plan.previousPlanId, planExecution: { planId, executionId },
|
|
79
|
+
trigger: plan.trigger, executionContext: context, retryFeedback: plan.retryFeedback,
|
|
80
|
+
guidance: plan.guidance, forceRestate: plan.forceRestate, restateTaskIds: plan.restateTaskIds };
|
|
81
|
+
console.log(plannerInput(input));
|
|
82
|
+
}
|
|
83
|
+
/** Read-only Task Context Action; no HTTP service, GitHub or mutable state. */
|
|
84
|
+
export async function runTaskContextCommand(args) {
|
|
85
|
+
const id = arg(args, '--task-id');
|
|
86
|
+
if (!id)
|
|
87
|
+
throw new Error('task context requires --task-id');
|
|
88
|
+
const { job } = await storeFor(args, true);
|
|
89
|
+
console.log(JSON.stringify(taskExecutionContext(job, id, arg(args, '--execution-id')), null, 2));
|
|
90
|
+
}
|
|
91
|
+
/** Read Task-scoped event history via the Relay CLI; never require workers to query backing services directly. */
|
|
92
|
+
export async function runTaskEventsCommand(args) {
|
|
93
|
+
const id = arg(args, '--task-id');
|
|
94
|
+
if (!id)
|
|
95
|
+
throw new Error('task events requires --task-id');
|
|
96
|
+
const { job } = await storeFor(args, true);
|
|
97
|
+
if (!job.tasks.some(task => task.id === id))
|
|
98
|
+
throw new Error(`Task ${id} not found in Job ${job.id}`);
|
|
99
|
+
for (const flag of ['--limit', '--order', '--after']) {
|
|
100
|
+
if (args.filter(value => value === flag).length > 1)
|
|
101
|
+
throw new Error(`task events ${flag} may not be repeated`);
|
|
102
|
+
if (args.includes(flag) && (!arg(args, flag) || arg(args, flag).startsWith('--')))
|
|
103
|
+
throw new Error(`task events ${flag} requires a value`);
|
|
104
|
+
}
|
|
105
|
+
const requested = Number(arg(args, '--limit', '60'));
|
|
106
|
+
if (!Number.isInteger(requested) || requested < 1 || requested > 60)
|
|
107
|
+
throw new Error('task events --limit must be an integer from 1 to 60');
|
|
108
|
+
const order = arg(args, '--order', 'desc');
|
|
109
|
+
if (order !== 'asc' && order !== 'desc')
|
|
110
|
+
throw new Error('task events --order must be asc or desc');
|
|
111
|
+
const afterRaw = arg(args, '--after', '0');
|
|
112
|
+
const after = Number(afterRaw);
|
|
113
|
+
if (!Number.isSafeInteger(after) || after < 0)
|
|
114
|
+
throw new Error('task events --after must be a non-negative integer cursor');
|
|
115
|
+
if (args.includes('--after') && order !== 'asc')
|
|
116
|
+
throw new Error('task events --after requires --order asc');
|
|
117
|
+
const page = await eventsBusHistoryPage(job.id, id, requested, { order, after });
|
|
118
|
+
const events = page.events; // Source validates Job/Task identity and cursor before exposing evidence.
|
|
119
|
+
console.log(JSON.stringify({ jobId: job.id, taskId: id, order: order === 'asc' ? 'oldest-first' : 'newest-first',
|
|
120
|
+
...(order === 'asc' ? { nextCursor: page.nextCursor, morePossible: events.length === requested } : {}), events }, null, 2));
|
|
121
|
+
}
|
|
122
|
+
/** Read-only Task details/comments. ID-only lookup uses the immutable local Job index. */
|
|
123
|
+
export async function runTaskReadCommand(action, args) {
|
|
124
|
+
const id = arg(args, '--task-id');
|
|
125
|
+
if (!id)
|
|
126
|
+
throw new Error(`task ${action} requires --task-id`);
|
|
127
|
+
const { job } = await storeFor(args, true);
|
|
128
|
+
const task = job.tasks.find(item => item.id === id);
|
|
129
|
+
if (!task)
|
|
130
|
+
throw new Error(`Task ${id} not found in Job ${job.id}`);
|
|
131
|
+
console.log(JSON.stringify(action === 'show' ? task : task.comments ?? [], null, 2));
|
|
132
|
+
}
|
package/dist/cli-shutdown.js
CHANGED
|
@@ -8,6 +8,9 @@ export async function runCliEntrypoint(main, options = {}) {
|
|
|
8
8
|
console.error(error instanceof Error ? error.message : String(error));
|
|
9
9
|
exitCode = 1;
|
|
10
10
|
}
|
|
11
|
+
// A successful main() may intentionally set a non-zero status (for example,
|
|
12
|
+
// a read-only validation returning FAIL). Never overwrite that status with 0.
|
|
13
|
+
exitCode = Math.max(exitCode, Number(process.exitCode ?? 0) || 0);
|
|
11
14
|
process.exitCode = exitCode;
|
|
12
15
|
if (options.serve)
|
|
13
16
|
return;
|
package/dist/cli-support.js
CHANGED
|
@@ -3,8 +3,9 @@ import { InMemoryStore, GitHubStore } from './store.js';
|
|
|
3
3
|
import { githubAuthContext } from './github-auth.js';
|
|
4
4
|
import { noGitHubMode } from './no-github.js';
|
|
5
5
|
import { basename } from 'node:path';
|
|
6
|
-
import { createJobIdRegistryResolver } from './local-job-registry.js';
|
|
6
|
+
import { createJobIdRegistryResolver, findJobIdSnapshot } from './local-job-registry.js';
|
|
7
7
|
import { relayStoreDirectory } from './relay-store.js';
|
|
8
|
+
import { normalizeRelayJob } from './relay-job-snapshot-reads.js';
|
|
8
9
|
import { NatsEventBus, eventFor } from './events.js';
|
|
9
10
|
import { parseJobTagJson } from './task-tag.js';
|
|
10
11
|
import { resolveEventsBusRuntime } from './events-bus-runtime.js';
|
|
@@ -61,19 +62,60 @@ export function pullRequest(args) { const value = Number(arg(args, '--pr')); if
|
|
|
61
62
|
throw new Error('--pr is required for GitHub-backed operation'); return value; }
|
|
62
63
|
async function localStore(file) { const parsed = JSON.parse(await readFile(file, 'utf8')); const store = new InMemoryStore(parsed); return { store, job: await store.load(parsed.id) }; }
|
|
63
64
|
export async function githubStore(args) { const auth = await githubAuthContext(args); return new GitHubStore(auth.client, repository(args), pullRequest(args), auth.trustedAuthors); }
|
|
64
|
-
|
|
65
|
+
/** The public read-only commands must fail closed on ambiguous Job bindings. */
|
|
66
|
+
function validateReadOnlyJobBinding(args) {
|
|
67
|
+
for (const flag of ['--id', '--repo', '--pr', '--file', '--store-dir', '--task-id', '--plan-id', '--execution-id']) {
|
|
68
|
+
const count = args.filter(value => value === flag).length;
|
|
69
|
+
if (count > 1)
|
|
70
|
+
throw new Error(`${flag} may not be repeated`);
|
|
71
|
+
if (count === 1 && (!arg(args, flag) || arg(args, flag).startsWith('--')))
|
|
72
|
+
throw new Error(`${flag} requires a value`);
|
|
73
|
+
}
|
|
74
|
+
if (!hasArg(args, '--id'))
|
|
75
|
+
throw new Error('--id is required for read-only Relay commands');
|
|
76
|
+
if (hasArg(args, '--pr')) {
|
|
77
|
+
const pr = Number(arg(args, '--pr'));
|
|
78
|
+
if (!Number.isSafeInteger(pr) || pr <= 0)
|
|
79
|
+
throw new Error('--pr must be a positive integer');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
export async function storeFor(args, allowIdOnly = false) {
|
|
83
|
+
if (allowIdOnly)
|
|
84
|
+
validateReadOnlyJobBinding(args);
|
|
65
85
|
const file = arg(args, '--file');
|
|
66
86
|
if (file) {
|
|
67
87
|
const loaded = await localStore(file);
|
|
88
|
+
if (allowIdOnly) {
|
|
89
|
+
const requestedId = arg(args, '--id'), requestedRepo = arg(args, '--repo');
|
|
90
|
+
if (requestedId !== loaded.job.id)
|
|
91
|
+
throw new Error('Local --file Job ID binding mismatch');
|
|
92
|
+
if (requestedRepo && loaded.job.repository !== requestedRepo)
|
|
93
|
+
throw new Error('Local --file repository binding mismatch');
|
|
94
|
+
const boundPr = loaded.job.prNumber > 0 ? loaded.job.prNumber : 0;
|
|
95
|
+
if (hasArg(args, '--pr') && boundPr !== Number(arg(args, '--pr')))
|
|
96
|
+
throw new Error('Local --file PR binding mismatch');
|
|
97
|
+
}
|
|
68
98
|
return { ...loaded, localFile: file };
|
|
69
99
|
}
|
|
70
|
-
const repo = noGitHubMode(args) ? repository(args) : arg(args, '--repo');
|
|
100
|
+
const repo = allowIdOnly ? arg(args, '--repo') : noGitHubMode(args) ? repository(args) : arg(args, '--repo');
|
|
71
101
|
const jobId = arg(args, '--id');
|
|
72
|
-
if (!
|
|
102
|
+
if (!jobId || (!repo && !allowIdOnly))
|
|
73
103
|
throw new Error('Local Job requires --repo and --id (or explicit --file)');
|
|
74
104
|
const directory = arg(args, '--store-dir') || relayStoreDirectory();
|
|
105
|
+
if (allowIdOnly) {
|
|
106
|
+
// Read-only CLI must not initialize SQLiteRelayStore: its constructor
|
|
107
|
+
// runs migrations and reclaims processing outbox actions.
|
|
108
|
+
const selected = await findJobIdSnapshot(directory, jobId);
|
|
109
|
+
if (!selected || (repo && selected.job.repository !== repo))
|
|
110
|
+
throw new Error('Immutable local Job not found for repository: ' + jobId);
|
|
111
|
+
const job = normalizeRelayJob(JSON.stringify(selected.job));
|
|
112
|
+
const suppliedPr = arg(args, '--pr');
|
|
113
|
+
if (suppliedPr && (job.prNumber > 0 ? job.prNumber : 0) !== Number(suppliedPr))
|
|
114
|
+
throw new Error('Local Job/PR binding mismatch');
|
|
115
|
+
return { store: new InMemoryStore(job), job, localFile: null };
|
|
116
|
+
}
|
|
75
117
|
const binding = await createJobIdRegistryResolver(directory, new Map())(jobId);
|
|
76
|
-
if (!binding || binding.job.repository !== repo)
|
|
118
|
+
if (!binding || (repo && binding.job.repository !== repo))
|
|
77
119
|
throw new Error('Immutable local Job not found for repository: ' + jobId);
|
|
78
120
|
const suppliedPr = arg(args, '--pr');
|
|
79
121
|
const boundPr = binding.job.prNumber > 0 ? binding.job.prNumber : 0;
|