@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.3
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 +18 -0
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
- package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-6L5KCQWJ.mjs} +99 -21
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-QNU2YE4G.mjs} +45 -13
- package/build/backend-worker.mjs +48 -7
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/index.js +72 -10
- package/dist/backend/claude/subagents.js +30 -9
- package/dist/backend/fake/index.js +36 -6
- package/dist/backend/pi/index.js +34 -2
- package/dist/backend/pi/state.js +16 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/worker/claude-state.js +22 -0
- package/dist/backend/worker/entry.js +25 -6
- package/dist/backend/worker/index.js +30 -5
- package/dist/backend/worker/protocol.js +1 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -7
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/client/reduce.js +29 -3
- package/dist/client/subagent-tree.js +49 -0
- package/dist/daemon/git.js +10 -7
- package/dist/daemon/host.js +226 -26
- package/dist/daemon/runtime.js +71 -3
- package/dist/daemon/server.js +3 -0
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder.js +36 -11
- package/dist/daemon/workflow-environment.js +191 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +9 -6
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +382 -300
- package/dist/daemon/workflow-routes.js +39 -0
- package/dist/daemon/workflow-schedule-driver.js +247 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +341 -0
- package/dist/isolation/sandbox.js +30 -14
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/protocol/events.js +2 -0
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/tui/render.js +7 -1
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +1 -1
- package/dist/workflows/graph.js +78 -4
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +124 -8
- package/dist/workflows/recovery.js +37 -1
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +351 -92
- package/dist/workflows/schedules.js +129 -0
- package/dist/workflows/schema.js +2 -0
- package/dist/workflows/store.js +110 -11
- package/package.json +2 -1
- package/web/dist/assets/index-BGu3YSP7.css +2 -0
- package/web/dist/assets/index-Miy2nveb.js +40 -0
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-Vf_fCXyE.js} +1 -1
- package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
- package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
- package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
- package/web/dist/index.html +4 -3
- package/web/dist/assets/index-DRfeO6GJ.js +0 -40
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
|
@@ -1,10 +1,48 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { deriveResultSchema } from "../workflows/calls.js";
|
|
1
3
|
import { validSecretName } from "../protocol/secrets.js";
|
|
2
4
|
import { validateDefinition } from "../workflows/graph.js";
|
|
5
|
+
export function workflowCatalogue(workflows) {
|
|
6
|
+
const entries = [];
|
|
7
|
+
const errors = [];
|
|
8
|
+
for (const definition of workflows.listDefinitions()) {
|
|
9
|
+
try {
|
|
10
|
+
entries.push({ id: definition.id, name: definition.name, backend: definition.backend, projectId: definition.projectId, contract: { inputSchema: definition.inputSchema, outputSchema: deriveResultSchema(definition) } });
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
errors.push({ id: definition.id, name: definition.name, message: 'Saved Workflow Definition is invalid' });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return { workflows: entries, errors };
|
|
17
|
+
}
|
|
18
|
+
function validateWorkflowContracts(definition, workflows) {
|
|
19
|
+
let original;
|
|
20
|
+
try {
|
|
21
|
+
original = workflows.getDefinition(definition.id);
|
|
22
|
+
}
|
|
23
|
+
catch { }
|
|
24
|
+
const catalogue = workflowCatalogue(workflows).workflows;
|
|
25
|
+
for (const step of definition.steps) {
|
|
26
|
+
if (step.kind !== 'workflow')
|
|
27
|
+
continue;
|
|
28
|
+
const retained = original?.steps.find((candidate) => candidate.id === step.id && candidate.kind === 'workflow');
|
|
29
|
+
if (retained?.workflowId === step.workflowId && isDeepStrictEqual(retained.contract, step.contract))
|
|
30
|
+
continue;
|
|
31
|
+
const selected = catalogue.find(item => item.id === step.workflowId && item.backend === definition.backend);
|
|
32
|
+
if (!selected || !isDeepStrictEqual(selected.contract, step.contract))
|
|
33
|
+
throw new Error(`Workflow step ${step.name} requires a saved host-derived contract`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
3
36
|
export function workflowRequestError(error, redact = message => message) {
|
|
4
37
|
// Redact before truncation: a credential containing ':' must not leak its prefix.
|
|
5
38
|
return error instanceof Error && error.name !== 'ZodError' && error.name !== 'SyntaxError' && error.message ? redact(error.message).split(':')[0] : 'Invalid workflow request';
|
|
6
39
|
}
|
|
7
40
|
export async function workflowRoutes(request, response, pathname, workflows, secrets, executions) {
|
|
41
|
+
if (pathname === '/api/workflow-catalogue') {
|
|
42
|
+
response.writeHead(!workflows ? 404 : request.method === 'GET' ? 200 : 405, { 'content-type': 'application/json' });
|
|
43
|
+
response.end(JSON.stringify(!workflows ? { error: 'Not available' } : request.method === 'GET' ? workflowCatalogue(workflows) : { error: 'Method not allowed' }));
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
8
46
|
const match = /^\/api\/(workflows|secrets)(?:\/(.*))?$/.exec(pathname);
|
|
9
47
|
if (!match)
|
|
10
48
|
return false;
|
|
@@ -81,6 +119,7 @@ export async function workflowRoutes(request, response, pathname, workflows, sec
|
|
|
81
119
|
let definition;
|
|
82
120
|
try {
|
|
83
121
|
definition = validateDefinition(body).definition;
|
|
122
|
+
validateWorkflowContracts(definition, workflows);
|
|
84
123
|
executions?.validateDefinitionCredentials(definition);
|
|
85
124
|
if (definition.id !== id)
|
|
86
125
|
throw new Error();
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { removeOwnedSandbox, sandboxUnavailable } from "../isolation/sandbox.js";
|
|
5
|
+
import { isActiveOccurrence, projectExecution } from "../workflows/schedules.js";
|
|
6
|
+
import { ScheduledExecutionStarted } from "./workflow-schedules.js";
|
|
7
|
+
import { resolveWorkflowCalls } from "../workflows/calls.js";
|
|
8
|
+
import { ScheduleValidationError } from "../workflows/schedule-errors.js";
|
|
9
|
+
import { includedProjects } from "./projects.js";
|
|
10
|
+
import { isClean, localBranches, planWorktree, removeMergedBranch, removeWorktree, run, GIT_WRITE_TIMEOUT_MS } from "./git.js";
|
|
11
|
+
export function scheduleDriver(options) {
|
|
12
|
+
const { host, config, workflows, executions, schedules, transcripts } = options;
|
|
13
|
+
const repositories = new Map();
|
|
14
|
+
const provisioning = new Set();
|
|
15
|
+
function current(occurrence) {
|
|
16
|
+
const owner = `occurrence-${occurrence.id}`;
|
|
17
|
+
return occurrence.executionId ? workflows.getExecution(owner, occurrence.executionId) : workflows.listExecutions(owner)[0];
|
|
18
|
+
}
|
|
19
|
+
function definition(id) {
|
|
20
|
+
try {
|
|
21
|
+
return workflows.getDefinition(id);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error.code === 'ENOENT')
|
|
25
|
+
throw new ScheduleValidationError('Select an available Workflow Definition');
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function validate(settings) {
|
|
30
|
+
const projects = includedProjects(config.rawProjectRoot(), config.projectInclude());
|
|
31
|
+
const project = projects.find(project => project.path === settings.projectId && !project.missing);
|
|
32
|
+
if (!project || realpathSync(project.path) !== settings.projectId)
|
|
33
|
+
throw new ScheduleValidationError('Select an available opted-in Project');
|
|
34
|
+
host.scheduledConnections(settings.mcpConnectionIds);
|
|
35
|
+
const selected = definition(settings.workflowId);
|
|
36
|
+
const manifest = resolveWorkflowCalls(selected, definition);
|
|
37
|
+
for (const candidate of Object.values(manifest)) {
|
|
38
|
+
executions.validateDefinitionCredentials(candidate);
|
|
39
|
+
for (const step of candidate.steps)
|
|
40
|
+
if (step.kind === 'mcp' && !settings.mcpConnectionIds.includes(step.tool.connectionId))
|
|
41
|
+
throw new ScheduleValidationError('Workflow MCP connection must be selected');
|
|
42
|
+
}
|
|
43
|
+
if (settings.worktree) {
|
|
44
|
+
const branches = await localBranches(settings.projectId);
|
|
45
|
+
if (!branches.ok)
|
|
46
|
+
throw new Error('Local branch inspection is unavailable');
|
|
47
|
+
if (!branches.value.includes(settings.worktree.from))
|
|
48
|
+
throw new ScheduleValidationError('Select an existing local base branch');
|
|
49
|
+
}
|
|
50
|
+
await executions.validateScheduledAgents(selected, settings.input, settings.projectId);
|
|
51
|
+
}
|
|
52
|
+
async function reclaimEnvironment(occurrence) {
|
|
53
|
+
const path = join(workflows.ownerPath(`occurrence-${occurrence.id}`), 'sandbox.json');
|
|
54
|
+
if (!existsSync(path))
|
|
55
|
+
return;
|
|
56
|
+
const support = host.sandboxSupport();
|
|
57
|
+
if (!support?.supported)
|
|
58
|
+
throw sandboxUnavailable();
|
|
59
|
+
await removeOwnedSandbox(support.provider, path, `flow-occurrence-${occurrence.id}`);
|
|
60
|
+
}
|
|
61
|
+
async function reclaimWorktree(occurrence) {
|
|
62
|
+
const worktree = occurrence.worktree;
|
|
63
|
+
if (!worktree)
|
|
64
|
+
return true;
|
|
65
|
+
const preserve = (warning) => { schedules.saveCleanupWarning(occurrence, warning); return false; };
|
|
66
|
+
const retry = (warning) => {
|
|
67
|
+
schedules.saveCleanupWarning(occurrence, warning);
|
|
68
|
+
throw new Error('Workflow Occurrence Git cleanup is unavailable. Owned work is retained for retry.');
|
|
69
|
+
};
|
|
70
|
+
const from = occurrence.settings.worktree?.from;
|
|
71
|
+
if (!from)
|
|
72
|
+
return preserve('Worktree preserved: saved base unavailable. Manual review required.');
|
|
73
|
+
const baseRef = `refs/heads/${from}`, branchRef = `refs/heads/${worktree.branch}`;
|
|
74
|
+
const base = await run(worktree.repo, ['show-ref', '--verify', '--quiet', baseRef], 10_000);
|
|
75
|
+
if (!base.ok)
|
|
76
|
+
return base.failure.code === 1 ? preserve('Worktree preserved: saved base unavailable. Manual review required.') : retry('Saved base inspection failed. Cleanup will be retried.');
|
|
77
|
+
const presentPath = existsSync(worktree.path);
|
|
78
|
+
if (presentPath) {
|
|
79
|
+
const clean = await isClean(worktree.path);
|
|
80
|
+
if (!clean.ok)
|
|
81
|
+
return retry('Worktree inspection failed. Cleanup will be retried.');
|
|
82
|
+
if (!clean.value)
|
|
83
|
+
return preserve('Worktree preserved: dirty. Manual review required.');
|
|
84
|
+
const branch = await run(worktree.path, ['symbolic-ref', '--quiet', 'HEAD'], 10_000);
|
|
85
|
+
if (!branch.ok)
|
|
86
|
+
return branch.failure.code === 1 ? preserve('Worktree preserved: detached. Manual review required.') : retry('Worktree branch inspection failed. Cleanup will be retried.');
|
|
87
|
+
if (branch.value.trim() !== branchRef)
|
|
88
|
+
return preserve('Worktree preserved: changed branch. Manual review required.');
|
|
89
|
+
const head = await run(worktree.path, ['rev-parse', 'HEAD'], 10_000);
|
|
90
|
+
if (!head.ok)
|
|
91
|
+
return retry('Worktree HEAD inspection failed. Cleanup will be retried.');
|
|
92
|
+
const merged = await run(worktree.repo, ['merge-base', '--is-ancestor', head.value.trim(), baseRef], 10_000);
|
|
93
|
+
if (!merged.ok)
|
|
94
|
+
return merged.failure.code === 1 ? preserve('Worktree preserved: unmerged. Manual review required.') : retry('Worktree merge inspection failed. Cleanup will be retried.');
|
|
95
|
+
if (!(await removeWorktree(worktree)).ok)
|
|
96
|
+
retry('Worktree removal failed. Cleanup will be retried.');
|
|
97
|
+
}
|
|
98
|
+
const present = await run(worktree.repo, ['show-ref', '--verify', '--quiet', branchRef], 10_000);
|
|
99
|
+
if (!present.ok)
|
|
100
|
+
return present.failure.code === 1 ? true : retry('Branch inspection failed. Cleanup will be retried.');
|
|
101
|
+
const merged = await run(worktree.repo, ['merge-base', '--is-ancestor', branchRef, baseRef], 10_000);
|
|
102
|
+
if (!merged.ok)
|
|
103
|
+
return merged.failure.code === 1 ? preserve('Branch preserved: unmerged. Manual review required.') : retry('Branch merge inspection failed. Cleanup will be retried.');
|
|
104
|
+
if (!(await removeMergedBranch(worktree.repo, worktree.branch, from)).ok)
|
|
105
|
+
retry('Branch removal failed. Cleanup will be retried.');
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
async function cleanupResources(occurrence) {
|
|
109
|
+
await executions.expireScheduled(occurrence.id);
|
|
110
|
+
await reclaimEnvironment(occurrence);
|
|
111
|
+
const session = occurrence.sessionId ? transcripts.readMeta(occurrence.sessionId) : undefined;
|
|
112
|
+
const reclaimed = session?.scheduledOccurrenceId === occurrence.id || await reclaimWorktree(occurrence);
|
|
113
|
+
workflows.deleteOwner({ kind: 'occurrence', occurrenceId: occurrence.id });
|
|
114
|
+
if (reclaimed)
|
|
115
|
+
schedules.clearCleanupWarning(occurrence.id);
|
|
116
|
+
}
|
|
117
|
+
async function cleanupUnstarted(initial) {
|
|
118
|
+
const occurrence = schedules.getOccurrence(initial.id);
|
|
119
|
+
if (provisioning.has(occurrence.id) || !['interrupted', 'cancelled', 'launch-failed'].includes(occurrence.status)
|
|
120
|
+
|| occurrence.executionId || occurrence.sessionId || occurrence.association
|
|
121
|
+
|| workflows.listExecutions(`occurrence-${occurrence.id}`).length)
|
|
122
|
+
return;
|
|
123
|
+
await cleanupResources(occurrence);
|
|
124
|
+
}
|
|
125
|
+
const attachment = (id) => async () => {
|
|
126
|
+
let occurrence = schedules.getOccurrence(id);
|
|
127
|
+
const sessionId = occurrence.sessionId ?? randomUUID();
|
|
128
|
+
// Intent is durable before host creation. The host also writes its occurrence association
|
|
129
|
+
// before backend creation; retries always reuse this identity, never a second session.
|
|
130
|
+
if (!occurrence.sessionId) {
|
|
131
|
+
occurrence = { ...occurrence, sessionId, association: 'pending' };
|
|
132
|
+
schedules.saveOccurrence(occurrence);
|
|
133
|
+
}
|
|
134
|
+
if (!occurrence.scope)
|
|
135
|
+
throw new Error('Occurrence Scope unavailable');
|
|
136
|
+
const definition = workflows.listExecutions(`occurrence-${id}`)[0]?.definition;
|
|
137
|
+
if (!definition)
|
|
138
|
+
throw new Error('Retained execution unavailable');
|
|
139
|
+
try {
|
|
140
|
+
const result = await host.attachScheduled({ scope: occurrence.scope, backend: definition.backend, mcpConnectionIds: occurrence.settings.mcpConnectionIds,
|
|
141
|
+
scheduled: { id: sessionId, occurrenceId: id, ...(occurrence.worktree ? { worktree: occurrence.worktree } : {}) } });
|
|
142
|
+
schedules.saveOccurrence({ ...schedules.getOccurrence(id), association: 'attached' });
|
|
143
|
+
return result;
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
schedules.saveOccurrence({ ...schedules.getOccurrence(id), association: 'failed', outcome: 'Agent Session attachment failed. Restore backend availability and retry attachment; the workflow will not replay automatically.' });
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
return {
|
|
151
|
+
validate,
|
|
152
|
+
current,
|
|
153
|
+
async launch(initial, signal) {
|
|
154
|
+
provisioning.add(initial.id);
|
|
155
|
+
try {
|
|
156
|
+
signal?.throwIfAborted();
|
|
157
|
+
await validate(initial.settings);
|
|
158
|
+
signal?.throwIfAborted();
|
|
159
|
+
let occurrence = schedules.getOccurrence(initial.id);
|
|
160
|
+
let scope = occurrence.settings.projectId;
|
|
161
|
+
if (occurrence.settings.worktree) {
|
|
162
|
+
const repo = scope;
|
|
163
|
+
const previous = repositories.get(repo) ?? Promise.resolve();
|
|
164
|
+
const provision = previous.catch(() => { }).then(async () => {
|
|
165
|
+
signal?.throwIfAborted();
|
|
166
|
+
const from = occurrence.settings.worktree.from;
|
|
167
|
+
const planned = await planWorktree({ repo, from, branch: `flow/schedule-${occurrence.id}`, under: transcripts.worktreesRoot() });
|
|
168
|
+
if (!planned.ok)
|
|
169
|
+
throw new Error('Could not plan worktree');
|
|
170
|
+
signal?.throwIfAborted();
|
|
171
|
+
occurrence = { ...occurrence, worktree: { ...planned.value, repo } };
|
|
172
|
+
schedules.saveOccurrence(occurrence);
|
|
173
|
+
const created = await run(repo, ['worktree', 'add', '-b', planned.value.branch, planned.value.path, `refs/heads/${from}`], GIT_WRITE_TIMEOUT_MS);
|
|
174
|
+
if (!created.ok)
|
|
175
|
+
throw new Error('Could not create worktree');
|
|
176
|
+
scope = realpathSync(planned.value.path);
|
|
177
|
+
});
|
|
178
|
+
repositories.set(repo, provision);
|
|
179
|
+
try {
|
|
180
|
+
await provision;
|
|
181
|
+
}
|
|
182
|
+
finally {
|
|
183
|
+
if (repositories.get(repo) === provision)
|
|
184
|
+
repositories.delete(repo);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
signal?.throwIfAborted();
|
|
188
|
+
occurrence = { ...occurrence, scope };
|
|
189
|
+
schedules.saveOccurrence(occurrence);
|
|
190
|
+
try {
|
|
191
|
+
const view = await executions.startScheduled({ occurrenceId: occurrence.id, definition: workflows.getDefinition(occurrence.settings.workflowId), input: occurrence.settings.input, scope, projectId: occurrence.settings.projectId, mcpConnectionIds: occurrence.settings.mcpConnectionIds, attach: attachment(occurrence.id), signal });
|
|
192
|
+
const saved = schedules.getOccurrence(occurrence.id);
|
|
193
|
+
schedules.saveOccurrence(projectExecution(saved, current(saved) ?? view.execution, Date.now()));
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
const record = workflows.listExecutions(`occurrence-${occurrence.id}`)[0];
|
|
197
|
+
if (!record)
|
|
198
|
+
throw error;
|
|
199
|
+
throw new ScheduledExecutionStarted(record.id, { cause: error });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
provisioning.delete(initial.id);
|
|
204
|
+
}
|
|
205
|
+
},
|
|
206
|
+
async reconcile(occurrence) {
|
|
207
|
+
// A checkpoint can have reached disk before occurrence metadata. Recover by durable owner,
|
|
208
|
+
// never by re-launching an ambiguous provisioning claim.
|
|
209
|
+
const records = workflows.listExecutions(`occurrence-${occurrence.id}`);
|
|
210
|
+
const record = records[0];
|
|
211
|
+
if (!record) {
|
|
212
|
+
const saved = schedules.getOccurrence(occurrence.id);
|
|
213
|
+
if (isActiveOccurrence(saved))
|
|
214
|
+
schedules.saveOccurrence({ ...saved, status: 'interrupted', finishedAt: Date.now(), outcome: 'Session Host stopped during provisioning; this occurrence will not be replayed.' });
|
|
215
|
+
await cleanupUnstarted(saved);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const current = executions.scheduler.get(`occurrence-${occurrence.id}`, record.id);
|
|
219
|
+
executions.restoreScheduled(current, occurrence.settings.mcpConnectionIds, attachment(occurrence.id));
|
|
220
|
+
if (!current.sessionId && current.status === 'recovery-required') {
|
|
221
|
+
try {
|
|
222
|
+
const sessionId = await attachment(occurrence.id)();
|
|
223
|
+
executions.scheduler.associate(occurrence.id, current.id, sessionId);
|
|
224
|
+
current.sessionId = sessionId;
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
schedules.saveOccurrence({ ...schedules.getOccurrence(occurrence.id), executionId: current.id, status: 'recovery-required', outcome: 'Agent Session attachment failed. Restore backend availability and restart the Session Host to reconcile.' });
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
const status = current.status;
|
|
232
|
+
schedules.saveOccurrence({ ...schedules.getOccurrence(occurrence.id), executionId: current.id, ...(current.sessionId ? { sessionId: current.sessionId } : {}), status,
|
|
233
|
+
...(status === 'running' || status === 'recovery-required' ? {} : { finishedAt: current.finishedAt ?? Date.now() }) });
|
|
234
|
+
if (current.sessionId && status === 'recovery-required')
|
|
235
|
+
host.workflowWake(current.sessionId, current.id, (await import("../workflows/recovery.js")).recoveryRevision(current));
|
|
236
|
+
},
|
|
237
|
+
async cancel(occurrence) {
|
|
238
|
+
if (occurrence.executionId)
|
|
239
|
+
await executions.cancel(`occurrence-${occurrence.id}`, occurrence.executionId);
|
|
240
|
+
const saved = schedules.getOccurrence(occurrence.id);
|
|
241
|
+
if (['provisioning', 'running', 'recovery-required'].includes(saved.status))
|
|
242
|
+
schedules.saveOccurrence({ ...saved, status: 'cancelled', finishedAt: Date.now() });
|
|
243
|
+
},
|
|
244
|
+
cleanup: cleanupResources,
|
|
245
|
+
cleanupUnstarted,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { scheduleSettingsValidator, occurrenceSettings, storageId, timingValidator, nextOccurrence } from "../workflows/schedules.js";
|
|
3
|
+
import { ScheduleRecordNotFound, ScheduleRevisionConflict } from "../workflows/schedule-store.js";
|
|
4
|
+
import { ScheduleValidationError } from "../workflows/schedule-errors.js";
|
|
5
|
+
import { WorkflowInvocationNotFound } from "../workflows/invocations.js";
|
|
6
|
+
import { WorkflowConflict, WorkflowValidationError } from "./workflow-execution-values.js";
|
|
7
|
+
class BodyTooLarge extends Error {
|
|
8
|
+
}
|
|
9
|
+
const revision = z.number().int().positive();
|
|
10
|
+
const createBody = z.object({ settings: scheduleSettingsValidator, enabled: z.boolean().default(false) }).strict();
|
|
11
|
+
const editBody = createBody.extend({ revision });
|
|
12
|
+
function requestValue(schema, value) {
|
|
13
|
+
const parsed = schema.safeParse(value);
|
|
14
|
+
if (!parsed.success)
|
|
15
|
+
throw new ScheduleValidationError('Invalid request value');
|
|
16
|
+
return parsed.data;
|
|
17
|
+
}
|
|
18
|
+
async function body(request) {
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let size = 0;
|
|
21
|
+
for await (const chunk of request) {
|
|
22
|
+
const bytes = Buffer.from(chunk);
|
|
23
|
+
size += bytes.length;
|
|
24
|
+
if (size > 1_000_000)
|
|
25
|
+
throw new BodyTooLarge();
|
|
26
|
+
chunks.push(bytes);
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
return chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {};
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
throw new ScheduleValidationError('Invalid request body');
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function requestId(value) {
|
|
36
|
+
let decoded;
|
|
37
|
+
try {
|
|
38
|
+
decoded = decodeURIComponent(value);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
throw new ScheduleValidationError('Invalid route identity');
|
|
42
|
+
}
|
|
43
|
+
return requestValue(storageId, decoded);
|
|
44
|
+
}
|
|
45
|
+
export async function workflowScheduleRoutes(request, response, url, service, executions) {
|
|
46
|
+
if (!/^\/api\/workflow-(schedules|occurrences)(?:\/|$)/.test(url.pathname))
|
|
47
|
+
return false;
|
|
48
|
+
const reply = (status, value) => { response.writeHead(status, { 'content-type': 'application/json' }); response.end(JSON.stringify(value)); };
|
|
49
|
+
if (!service || !executions) {
|
|
50
|
+
reply(404, { error: 'Schedules unavailable' });
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const match = /^\/api\/workflow-(schedules|occurrences)(?:\/([^/]+)(?:\/(enable|pause|history|execution|activity|cancel|retry-attachment))?)?$/.exec(url.pathname);
|
|
55
|
+
if (!match)
|
|
56
|
+
throw new ScheduleValidationError('Invalid route');
|
|
57
|
+
const kind = match[1], id = match[2] === undefined ? undefined : requestId(match[2]), action = match[3];
|
|
58
|
+
const method = request.method;
|
|
59
|
+
const allowed = action === 'history' || kind === 'occurrences' && !id ? ['scheduleId', 'before', 'limit'] : action === 'execution' ? ['invocationId'] : action === 'activity' ? ['invocationId', 'stepId', 'attempt', 'after', 'before', 'latest', 'limit'] : [];
|
|
60
|
+
for (const key of url.searchParams.keys())
|
|
61
|
+
if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1)
|
|
62
|
+
throw new ScheduleValidationError('Invalid query');
|
|
63
|
+
if (kind === 'schedules' && id === 'preview' && method === 'POST') {
|
|
64
|
+
const { timing } = requestValue(z.object({ timing: timingValidator }).strict(), await body(request));
|
|
65
|
+
reply(200, { nextDue: nextOccurrence(timing, Date.now()) });
|
|
66
|
+
}
|
|
67
|
+
else if (kind === 'schedules' && !id && method === 'GET')
|
|
68
|
+
reply(200, { schedules: service.store.listSchedules(), cleanupWarnings: service.store.cleanupWarnings() });
|
|
69
|
+
else if (kind === 'schedules' && !id && method === 'POST') {
|
|
70
|
+
const input = requestValue(createBody, await body(request));
|
|
71
|
+
reply(201, { schedule: await service.create(input.settings, input.enabled) });
|
|
72
|
+
}
|
|
73
|
+
else if (kind === 'schedules' && id && !action && method === 'GET')
|
|
74
|
+
reply(200, { schedule: service.store.getSchedule(id) });
|
|
75
|
+
else if (kind === 'schedules' && id && !action && method === 'PUT') {
|
|
76
|
+
const input = requestValue(editBody, await body(request));
|
|
77
|
+
reply(200, { schedule: await service.update(id, input.revision, input.settings, input.enabled) });
|
|
78
|
+
}
|
|
79
|
+
else if (kind === 'schedules' && id && !action && method === 'DELETE') {
|
|
80
|
+
const input = requestValue(z.object({ revision }).strict(), await body(request));
|
|
81
|
+
await service.delete(id, input.revision);
|
|
82
|
+
reply(200, { deleted: true });
|
|
83
|
+
}
|
|
84
|
+
else if (kind === 'schedules' && id && (action === 'enable' || action === 'pause') && method === 'POST') {
|
|
85
|
+
const input = requestValue(z.object({ revision }).strict(), await body(request));
|
|
86
|
+
const schedule = service.store.getSchedule(id);
|
|
87
|
+
reply(200, { schedule: action === 'pause' ? await service.pause(id, input.revision) : await service.update(id, input.revision, occurrenceSettings(schedule), true) });
|
|
88
|
+
}
|
|
89
|
+
else if (method === 'GET' && (kind === 'schedules' && action === 'history' || kind === 'occurrences' && !id)) {
|
|
90
|
+
const query = url.searchParams;
|
|
91
|
+
reply(200, service.store.page({ ...(kind === 'schedules' ? { scheduleId: id } : query.has('scheduleId') ? { scheduleId: requestValue(storageId, query.get('scheduleId')) } : {}), ...(query.has('before') ? { before: requestValue(storageId, query.get('before')) } : {}), limit: requestValue(z.coerce.number().int().min(1).max(200), query.get('limit') ?? 50) }));
|
|
92
|
+
}
|
|
93
|
+
else if (kind === 'occurrences' && id) {
|
|
94
|
+
const occurrence = service.store.getOccurrence(id);
|
|
95
|
+
if (method === 'GET' && !action)
|
|
96
|
+
reply(200, { occurrence });
|
|
97
|
+
else if (method === 'POST' && action === 'retry-attachment') {
|
|
98
|
+
requestValue(z.object({}).strict(), await body(request));
|
|
99
|
+
await service.retryAttachment(id);
|
|
100
|
+
reply(200, { occurrence: service.store.getOccurrence(id) });
|
|
101
|
+
}
|
|
102
|
+
else if (method === 'POST' && action === 'cancel') {
|
|
103
|
+
requestValue(z.object({}).strict(), await body(request));
|
|
104
|
+
await service.cancel(id);
|
|
105
|
+
reply(200, { occurrence: service.store.getOccurrence(id) });
|
|
106
|
+
}
|
|
107
|
+
else if (method === 'GET' && (action === 'execution' || action === 'activity')) {
|
|
108
|
+
if (!occurrence.executionId)
|
|
109
|
+
throw new ScheduleRecordNotFound('Execution not found');
|
|
110
|
+
const owner = `occurrence-${id}`, executionId = occurrence.executionId;
|
|
111
|
+
const query = url.searchParams;
|
|
112
|
+
if (action === 'execution')
|
|
113
|
+
reply(200, executions.view(owner, executionId, query.has('invocationId') ? requestValue(storageId, query.get('invocationId')) : undefined));
|
|
114
|
+
else {
|
|
115
|
+
const number = (name) => requestValue(z.coerce.number().int().min(name === 'after' ? 0 : 1).safe(), query.get(name));
|
|
116
|
+
if (query.has('latest') && query.get('latest') !== 'true' || query.has('after') && (query.has('before') || query.has('latest')))
|
|
117
|
+
throw new ScheduleValidationError('Invalid activity cursor');
|
|
118
|
+
reply(200, await executions.activity(owner, executionId, { ...(query.has('invocationId') ? { invocationId: requestValue(storageId, query.get('invocationId')) } : {}), ...(query.has('stepId') ? { stepId: query.get('stepId') } : {}), ...(query.has('attempt') ? { attempt: number('attempt') } : {}), ...(query.has('after') ? { after: number('after') } : {}), ...(query.has('before') ? { before: number('before') } : {}), ...(query.has('latest') ? { latest: true } : {}), ...(query.has('limit') ? { limit: number('limit') } : {}) }));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
else
|
|
122
|
+
reply(405, { error: 'Method not allowed or execution unavailable' });
|
|
123
|
+
}
|
|
124
|
+
else
|
|
125
|
+
reply(405, { error: 'Method not allowed' });
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
const status = error instanceof ScheduleRevisionConflict || error instanceof WorkflowConflict ? 409
|
|
129
|
+
: error instanceof ScheduleRecordNotFound || error instanceof WorkflowInvocationNotFound ? 404
|
|
130
|
+
: error instanceof BodyTooLarge ? 413
|
|
131
|
+
: error instanceof ScheduleValidationError || error instanceof WorkflowValidationError ? 400 : 500;
|
|
132
|
+
if (status === 500)
|
|
133
|
+
console.error('Workflow Schedule request failed. An internal operation is unavailable.');
|
|
134
|
+
reply(status, { error: status === 409 ? 'Schedule or Workflow changed; reload before editing' : status === 404 ? 'Schedule, occurrence or execution not found' : status === 413 ? 'Body too large' : status === 500 ? 'Schedule operation unavailable. Check Session Host diagnostics.' : 'Invalid schedule request. Check timing, inputs, Project, local branch and MCP selection.' });
|
|
135
|
+
}
|
|
136
|
+
return true;
|
|
137
|
+
}
|