-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathagent-cron.ts
More file actions
231 lines (185 loc) · 8.33 KB
/
Copy pathagent-cron.ts
File metadata and controls
231 lines (185 loc) · 8.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { createAgentCronJob, deleteAgentCronJobs, listCronJobs, checkCronToolAvailable } from "./gateway-api.js";
import type { WorkflowSpec } from "./types.js";
import { resolveAntfarmCli } from "./paths.js";
import { getDb } from "../db.js";
const DEFAULT_EVERY_MS = 300_000; // 5 minutes
const DEFAULT_AGENT_TIMEOUT_SECONDS = 30 * 60; // 30 minutes
function prefixThinkingDirective(thinking: string | undefined, body: string): string {
if (!thinking) return body;
return `/think ${thinking}
${body}`;
}
function buildAgentPrompt(workflowId: string, agentId: string): string {
const fullAgentId = `${workflowId}_${agentId}`;
const cli = resolveAntfarmCli();
return `You are an Antfarm workflow agent. Check for pending work and execute it.
⚠️ CRITICAL: You MUST call "step complete" or "step fail" before ending your session. If you don't, the workflow will be stuck forever. This is non-negotiable.
Step 1 — Check for pending work:
\`\`\`
node ${cli} step claim "${fullAgentId}"
\`\`\`
If output is "NO_WORK", reply HEARTBEAT_OK and stop.
Step 2 — If JSON is returned, it contains: {"stepId": "...", "runId": "...", "input": "..."}
Save the stepId — you'll need it to report completion.
The "input" field contains your FULLY RESOLVED task instructions. Read it carefully and DO the work.
Step 3 — Do the work described in the input. Format your output with KEY: value lines as specified.
Step 4 — MANDATORY: Report completion (do this IMMEDIATELY after finishing the work):
\`\`\`
cat <<'ANTFARM_EOF' > /tmp/antfarm-step-output.txt
STATUS: done
CHANGES: what you did
TESTS: what tests you ran
ANTFARM_EOF
cat /tmp/antfarm-step-output.txt | node ${cli} step complete "<stepId>"
\`\`\`
If the work FAILED:
\`\`\`
node ${cli} step fail "<stepId>" "description of what went wrong"
\`\`\`
RULES:
1. NEVER end your session without calling step complete or step fail
2. Write output to a file first, then pipe via stdin (shell escaping breaks direct args)
3. If you're unsure whether to complete or fail, call step fail with an explanation
The workflow cannot advance until you report. Your session ending without reporting = broken pipeline.`;
}
export function buildWorkPrompt(workflowId: string, agentId: string, thinking?: string): string {
const fullAgentId = `${workflowId}_${agentId}`;
const cli = resolveAntfarmCli();
const body = `You are an Antfarm workflow agent. Execute the pending work below.
⚠️ CRITICAL: You MUST call "step complete" or "step fail" before ending your session. If you don't, the workflow will be stuck forever. This is non-negotiable.
The claimed step JSON is provided below. It contains: {"stepId": "...", "runId": "...", "input": "..."}
Save the stepId — you'll need it to report completion.
The "input" field contains your FULLY RESOLVED task instructions. Read it carefully and DO the work.
Do the work described in the input. Format your output with KEY: value lines as specified.
MANDATORY: Report completion (do this IMMEDIATELY after finishing the work):
\`\`\`
cat <<'ANTFARM_EOF' > /tmp/antfarm-step-output.txt
STATUS: done
CHANGES: what you did
TESTS: what tests you ran
ANTFARM_EOF
cat /tmp/antfarm-step-output.txt | node ${cli} step complete "<stepId>"
\`\`\`
If the work FAILED:
\`\`\`
node ${cli} step fail "<stepId>" "description of what went wrong"
\`\`\`
RULES:
1. NEVER end your session without calling step complete or step fail
2. Write output to a file first, then pipe via stdin (shell escaping breaks direct args)
3. If you're unsure whether to complete or fail, call step fail with an explanation
The workflow cannot advance until you report. Your session ending without reporting = broken pipeline.`;
return prefixThinkingDirective(thinking, body);
}
const DEFAULT_POLLING_TIMEOUT_SECONDS = 120;
const DEFAULT_POLLING_MODEL = "default";
export function buildPollingPrompt(
workflowId: string,
agentId: string,
workModel?: string,
workThinking?: string,
pollingThinking?: string,
): string {
const fullAgentId = `${workflowId}_${agentId}`;
const cli = resolveAntfarmCli();
const model = workModel ?? "default";
const workPrompt = buildWorkPrompt(workflowId, agentId, workThinking);
const body = `Step 1 — Quick check for pending work (lightweight, no side effects):
\`\`\`
node ${cli} step peek "${fullAgentId}"
\`\`\`
If output is "NO_WORK", reply HEARTBEAT_OK and stop immediately. Do NOT run step claim.
Step 2 — If "HAS_WORK", claim the step:
\`\`\`
node ${cli} step claim "${fullAgentId}"
\`\`\`
If output is "NO_WORK", reply HEARTBEAT_OK and stop.
If JSON is returned, parse it to extract stepId, runId, and input fields.
Then call sessions_spawn with these parameters:
- agentId: "${fullAgentId}"
- model: "${model}"
- task: The full work prompt below, followed by "\\n\\nCLAIMED STEP JSON:\\n" and the exact JSON output from step claim.
Full work prompt to include in the spawned task:
---START WORK PROMPT---
${workPrompt}
---END WORK PROMPT---
Reply with a short summary of what you spawned.`;
return prefixThinkingDirective(pollingThinking, body);
}
export async function setupAgentCrons(workflow: WorkflowSpec): Promise<void> {
const agents = workflow.agents;
// Allow per-workflow cron interval via cron.interval_ms in workflow.yml
const everyMs = (workflow as any).cron?.interval_ms ?? DEFAULT_EVERY_MS;
// Resolve polling model: per-agent > workflow-level > default
const workflowPollingModel = workflow.polling?.model ?? DEFAULT_POLLING_MODEL;
const workflowPollingThinking = workflow.polling?.thinking;
const workflowPollingTimeout = workflow.polling?.timeoutSeconds ?? DEFAULT_POLLING_TIMEOUT_SECONDS;
for (let i = 0; i < agents.length; i++) {
const agent = agents[i];
const anchorMs = i * 60_000; // stagger by 1 minute each
const cronName = `antfarm/${workflow.id}/${agent.id}`;
const agentId = `${workflow.id}_${agent.id}`;
// Two-phase: Phase 1 uses cheap polling model + minimal prompt
const pollingModel = agent.pollingModel ?? workflowPollingModel;
const workModel = agent.model; // Phase 2 model (passed to sessions_spawn via prompt)
const prompt = buildPollingPrompt(workflow.id, agent.id, workModel, agent.thinking, workflowPollingThinking);
const timeoutSeconds = workflowPollingTimeout;
const result = await createAgentCronJob({
name: cronName,
schedule: { kind: "every", everyMs, anchorMs },
sessionTarget: "isolated",
agentId,
payload: { kind: "agentTurn", message: prompt, model: pollingModel, timeoutSeconds },
delivery: { mode: "none" },
enabled: true,
});
if (!result.ok) {
throw new Error(`Failed to create cron job for agent "${agent.id}": ${result.error}`);
}
}
}
export async function removeAgentCrons(workflowId: string): Promise<void> {
await deleteAgentCronJobs(`antfarm/${workflowId}/`);
}
// ── Run-scoped cron lifecycle ───────────────────────────────────────
/**
* Count active (running) runs for a given workflow.
*/
function countActiveRuns(workflowId: string): number {
const db = getDb();
const row = db.prepare(
"SELECT COUNT(*) as cnt FROM runs WHERE workflow_id = ? AND status = 'running'"
).get(workflowId) as { cnt: number };
return row.cnt;
}
/**
* Check if crons already exist for a workflow.
*/
async function workflowCronsExist(workflowId: string): Promise<boolean> {
const result = await listCronJobs();
if (!result.ok || !result.jobs) return false;
const prefix = `antfarm/${workflowId}/`;
return result.jobs.some((j) => j.name.startsWith(prefix));
}
/**
* Start crons for a workflow when a run begins.
* No-ops if crons already exist (another run of the same workflow is active).
*/
export async function ensureWorkflowCrons(workflow: WorkflowSpec): Promise<void> {
if (await workflowCronsExist(workflow.id)) return;
// Preflight: verify cron tool is accessible before attempting to create jobs
const preflight = await checkCronToolAvailable();
if (!preflight.ok) {
throw new Error(preflight.error!);
}
await setupAgentCrons(workflow);
}
/**
* Tear down crons for a workflow when a run ends.
* Only removes if no other active runs exist for this workflow.
*/
export async function teardownWorkflowCronsIfIdle(workflowId: string): Promise<void> {
const active = countActiveRuns(workflowId);
if (active > 0) return;
await removeAgentCrons(workflowId);
}