@jive-sh/workflow-platform 0.7.0 → 1.1.0
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 +70 -435
- package/component/_generated/api.ts +72 -0
- package/component/_generated/component.ts +629 -0
- package/component/_generated/dataModel.ts +60 -0
- package/component/_generated/server.ts +169 -0
- package/component/convex.config.ts +3 -0
- package/component/engine.ts +756 -0
- package/component/errors.ts +66 -0
- package/component/events.ts +17 -0
- package/component/notes.ts +19 -0
- package/component/places.ts +136 -0
- package/component/retention.ts +205 -0
- package/component/runEngine.ts +25 -0
- package/component/schema.ts +135 -0
- package/component/steps.ts +188 -0
- package/component/store.ts +513 -0
- package/component/tasks.ts +290 -0
- package/component/worker.ts +109 -0
- package/component/workflows.ts +83 -0
- package/dist/definition/agent-runner.js +9 -0
- package/dist/definition/agent-runner.js.map +1 -0
- package/dist/definition/file-store.js +9 -0
- package/dist/definition/file-store.js.map +1 -0
- package/dist/definition/program-build.js +10 -0
- package/dist/definition/program-build.js.map +1 -0
- package/dist/definition/step.js +1 -0
- package/dist/definition/step.js.map +1 -0
- package/dist/definition/task-schema.js +5 -0
- package/dist/definition/task-schema.js.map +1 -0
- package/dist/definition/tasks.js +9 -0
- package/dist/definition/tasks.js.map +1 -0
- package/dist/definition/workflow.js +117 -0
- package/dist/definition/workflow.js.map +1 -0
- package/dist/graph.js +310 -9
- package/dist/graph.js.map +1 -1
- package/dist/index.js +7 -196
- package/dist/index.js.map +1 -1
- package/package.json +9 -4
- package/src/definition/agent-runner.ts +59 -0
- package/src/definition/file-store.ts +20 -0
- package/src/definition/program-build.ts +30 -0
- package/src/definition/step.ts +106 -0
- package/src/definition/task-schema.ts +15 -0
- package/src/definition/tasks.ts +43 -0
- package/src/definition/workflow.ts +262 -0
- package/src/graph.ts +352 -19
- package/src/index.ts +8 -238
- package/worker/directory-file-store.ts +42 -0
- package/worker/index.ts +12 -0
- package/worker/platform-client.ts +144 -0
- package/worker/step-meter.ts +80 -0
- package/worker/worker-tasks.ts +27 -0
- package/worker/worker.test.ts +200 -0
- package/worker/worker.ts +240 -0
- package/dist/budget-states.js +0 -30
- package/dist/budget-states.js.map +0 -1
- package/dist/cpu-limit/limiter.js +0 -839
- package/dist/cpu-limit/limiter.js.map +0 -1
- package/dist/cpu-limit/use.js +0 -139
- package/dist/cpu-limit/use.js.map +0 -1
- package/dist/dashboard/agent-usage.js +0 -25
- package/dist/dashboard/agent-usage.js.map +0 -1
- package/dist/dashboard/dashboard.css +0 -148
- package/dist/dashboard/drilldown.js +0 -47
- package/dist/dashboard/drilldown.js.map +0 -1
- package/dist/dashboard/queue-lines.js +0 -44
- package/dist/dashboard/queue-lines.js.map +0 -1
- package/dist/dashboard/queue-table.js +0 -16
- package/dist/dashboard/queue-table.js.map +0 -1
- package/dist/dashboard/run-doing-words.js +0 -29
- package/dist/dashboard/run-doing-words.js.map +0 -1
- package/dist/dashboard/setting-words.js +0 -18
- package/dist/dashboard/setting-words.js.map +0 -1
- package/dist/dashboard/spending-words.js +0 -24
- package/dist/dashboard/spending-words.js.map +0 -1
- package/dist/failure.js +0 -35
- package/dist/failure.js.map +0 -1
- package/dist/keep-running.js +0 -79
- package/dist/keep-running.js.map +0 -1
- package/dist/outside-failure.js +0 -31
- package/dist/outside-failure.js.map +0 -1
- package/dist/pick-wakes.js +0 -125
- package/dist/pick-wakes.js.map +0 -1
- package/dist/project.js +0 -1
- package/dist/project.js.map +0 -1
- package/dist/queue-counts.js +0 -51
- package/dist/queue-counts.js.map +0 -1
- package/dist/reasons.js +0 -33
- package/dist/reasons.js.map +0 -1
- package/dist/retention.js +0 -59
- package/dist/retention.js.map +0 -1
- package/dist/settings.js +0 -88
- package/dist/settings.js.map +0 -1
- package/dist/spending-limit.js +0 -82
- package/dist/spending-limit.js.map +0 -1
- package/dist/step-files.js +0 -200
- package/dist/step-files.js.map +0 -1
- package/dist/step-meter.js +0 -97
- package/dist/step-meter.js.map +0 -1
- package/dist/step-times.js +0 -114
- package/dist/step-times.js.map +0 -1
- package/dist/step-usage.js +0 -19
- package/dist/step-usage.js.map +0 -1
- package/dist/steps.js +0 -1205
- package/dist/steps.js.map +0 -1
- package/dist/storage/agent-claims.js +0 -3
- package/dist/storage/agent-claims.js.map +0 -1
- package/dist/storage/budgets.js +0 -121
- package/dist/storage/budgets.js.map +0 -1
- package/dist/storage/engine-records.js +0 -91
- package/dist/storage/engine-records.js.map +0 -1
- package/dist/storage/engine-storage.js +0 -67
- package/dist/storage/engine-storage.js.map +0 -1
- package/dist/storage/input-records.js +0 -12
- package/dist/storage/input-records.js.map +0 -1
- package/dist/storage/move-store.js +0 -251
- package/dist/storage/move-store.js.map +0 -1
- package/dist/storage/sqlite-store.js +0 -901
- package/dist/storage/sqlite-store.js.map +0 -1
- package/dist/storage/step-records.js +0 -11
- package/dist/storage/step-records.js.map +0 -1
- package/dist/storage/storage-error.js +0 -19
- package/dist/storage/storage-error.js.map +0 -1
- package/dist/storage/task-store.js +0 -30
- package/dist/storage/task-store.js.map +0 -1
- package/dist/system-workflows.js +0 -54
- package/dist/system-workflows.js.map +0 -1
- package/dist/tasks.js +0 -500
- package/dist/tasks.js.map +0 -1
- package/dist/views/format.js +0 -37
- package/dist/views/format.js.map +0 -1
- package/dist/views/runs-now.js +0 -117
- package/dist/views/runs-now.js.map +0 -1
- package/dist/views/step-funnel.js +0 -98
- package/dist/views/step-funnel.js.map +0 -1
- package/dist/views/step-graph.js +0 -39
- package/dist/views/step-graph.js.map +0 -1
- package/dist/views/workflows-view.js +0 -236
- package/dist/views/workflows-view.js.map +0 -1
- package/src/budget-states.ts +0 -54
- package/src/cpu-limit/limiter.ts +0 -935
- package/src/cpu-limit/use.ts +0 -166
- package/src/dashboard/agent-usage-line.tsx +0 -28
- package/src/dashboard/agent-usage.ts +0 -48
- package/src/dashboard/dashboard.css +0 -148
- package/src/dashboard/drilldown.ts +0 -70
- package/src/dashboard/index.tsx +0 -4
- package/src/dashboard/limits-and-runs.tsx +0 -191
- package/src/dashboard/machine-controls.tsx +0 -53
- package/src/dashboard/queue-bar.tsx +0 -62
- package/src/dashboard/queue-chart.tsx +0 -149
- package/src/dashboard/queue-lines.ts +0 -87
- package/src/dashboard/queue-table.ts +0 -37
- package/src/dashboard/run-doing-words.ts +0 -41
- package/src/dashboard/setting-words.ts +0 -30
- package/src/dashboard/spending-limit-control.tsx +0 -47
- package/src/dashboard/spending-words.ts +0 -32
- package/src/dashboard/time-distribution.tsx +0 -61
- package/src/dashboard/workflow-dag.tsx +0 -322
- package/src/dashboard/workflow-drilldown.tsx +0 -31
- package/src/dashboard/workflows-dashboard.tsx +0 -532
- package/src/failure.ts +0 -36
- package/src/keep-running.ts +0 -85
- package/src/outside-failure.ts +0 -39
- package/src/pick-wakes.ts +0 -182
- package/src/project.ts +0 -127
- package/src/queue-counts.ts +0 -64
- package/src/reasons.ts +0 -30
- package/src/retention.ts +0 -90
- package/src/settings.ts +0 -171
- package/src/spending-limit.ts +0 -139
- package/src/step-files.ts +0 -208
- package/src/step-meter.ts +0 -120
- package/src/step-times.ts +0 -151
- package/src/step-usage.ts +0 -23
- package/src/steps.ts +0 -1616
- package/src/storage/agent-claims.ts +0 -63
- package/src/storage/budgets.ts +0 -152
- package/src/storage/engine-records.ts +0 -119
- package/src/storage/engine-storage.ts +0 -82
- package/src/storage/input-records.ts +0 -43
- package/src/storage/move-store.ts +0 -265
- package/src/storage/sqlite-store.ts +0 -1022
- package/src/storage/step-records.ts +0 -358
- package/src/storage/storage-error.ts +0 -35
- package/src/storage/task-store.ts +0 -235
- package/src/system-workflows.ts +0 -70
- package/src/tasks.ts +0 -586
- package/src/views/format.ts +0 -40
- package/src/views/runs-now.ts +0 -188
- package/src/views/step-funnel.ts +0 -163
- package/src/views/step-graph.ts +0 -77
- package/src/views/workflows-view.ts +0 -484
- package/src/workflow-dag.test.tsx +0 -89
- package/src/workflow-page.test.tsx +0 -170
package/dist/steps.js
DELETED
|
@@ -1,1205 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* THE ONE WAY TO DEFINE A WORKFLOW AND ITS STEPS.
|
|
3
|
-
*
|
|
4
|
-
* A workflow states its steps and the item it works on, and each step states
|
|
5
|
-
* whether it needs an agent; nothing else defines a step. Every run of every step goes through the same code here, which
|
|
6
|
-
* writes its one record (`storage/step-records.ts`): start, end, outcome, tokens, compiles, and a heartbeat while an agent
|
|
7
|
-
* works. A dashboard derives all it says from those records and these declarations.
|
|
8
|
-
*
|
|
9
|
-
* const PICK = defineStep({ name: 'Pick', runs: 'deterministic', description: '...', at: import.meta.path, success: Schema.Number });
|
|
10
|
-
* export const MyWorkflow = defineWorkflow({ description: '...', at: import.meta.path, steps: () => [PICK],
|
|
11
|
-
* graph: () => [{ from: RUN_STARTS, to: PICK.name, when: 'each run' }, { from: PICK.name, to: RUN_ENDS, when: 'always' }] })('My workflow', { payload, success, error, idempotencyKey });
|
|
12
|
-
* ... yield* PICK.run(Effect.gen(...)); a repeating step gives its number: PICK.run(body, { call: 2 })
|
|
13
|
-
*
|
|
14
|
-
* Its `graph` says which step can follow which, and when, in plain words (`StepEdge`): a dashboard draws it, and a run that
|
|
15
|
-
* takes an edge it does not declare fails in tests.
|
|
16
|
-
*
|
|
17
|
-
* A step can name the run's item from its result (`subject`), usually at Pick, and later steps inherit it. When the run
|
|
18
|
-
* ends the definer records each item's real outcome (`outcomes`). A workflow with an agent step and a list of work needs no
|
|
19
|
-
* trigger: the trigger (`keep-running.ts`) keeps its budget's number of runs of it going, so its payload is `{ run }`.
|
|
20
|
-
*
|
|
21
|
-
* AN ITEM IS TESTED BEFORE AN AGENT SEES IT. Alex, 2026-11-04: "work in the queue should probably undergo an initial round
|
|
22
|
-
* of testing before the work gets handed to an agent". A no-agent test step (`defineItemTest`) comes before a workflow's
|
|
23
|
-
* first agent step: an item that passes now is finished, with no agent and no tokens; one that fails gives the agent the
|
|
24
|
-
* exact failure as its input; one that cannot be tested says why.
|
|
25
|
-
*
|
|
26
|
-
* An agent call needs `AgentStep`, which only a step that runs agentically (`runs: 'agentic'`) provides, so it cannot compile anywhere else.
|
|
27
|
-
*
|
|
28
|
-
* A RUN CLAIMS ITS AGENTS FOR THE REST OF ITS RUN (`claimAgentsOrEnd`): a workflow with an agent step claims 1, or the
|
|
29
|
-
* number it declares (`agentsClaimed`), at a run's first agent step, against the agents' limit of the workflow at the top
|
|
30
|
-
* of the run, and holds it through every step until the run ends. A run that finds no claim free never waits: its task goes to the back of its
|
|
31
|
-
* queue, marked as needing an agent, and the run ends, so the next task can start. A sub-workflow step that keeps its agent
|
|
32
|
-
* until its run ends (`agentKeptUntilThisRunEnds`) has the claim its workflow's run takes held by the run of that step, so
|
|
33
|
-
* the step's next call finds it held, and no other run can take it between them.
|
|
34
|
-
*
|
|
35
|
-
* A RUN LIMIT ENDS THE RUNS PAST IT, NOT ONLY THE RUNS STARTED. Before each agent step, a run its workflow's budget has no
|
|
36
|
-
* room for ends: oldest runs keep their places, so with 10 going and a budget of 5 exactly the newest 5 end, and no two runs
|
|
37
|
-
* have to agree on anything. No agent call is cut off. The check is part of the step's activity, so a resumed run decides
|
|
38
|
-
* the same way. The step fails with `STOOD_DOWN`, and the run ends through its failure path, or through its normal one where
|
|
39
|
-
* it asks `isStoodDown`.
|
|
40
|
-
*
|
|
41
|
-
* EVERY ITEM IS A TASK, in one of four statuses read from its notes (`tasks.ts`). A Pick orders its own candidates through `pickOrder`, or
|
|
42
|
-
* takes its queue's head; a Pick that finds nothing waits for an event that can change that (`picked`, `pick-wakes.ts`),
|
|
43
|
-
* so a run never ends for want of an item.
|
|
44
|
-
*
|
|
45
|
-
* WHAT A STEP USES IS MEASURED, never reported (`step-meter.ts`): time, tokens, CPU, peak memory, files written and
|
|
46
|
-
* compiles, on its one record. A step working on items says which: `subject` names the run's one, `eachItem` gives a batch
|
|
47
|
-
* step one record per item, and a step whose work no one item owns declares `shared` rather than dividing it up.
|
|
48
|
-
*/
|
|
49
|
-
import { createHash } from 'node:crypto';
|
|
50
|
-
import fs from 'node:fs';
|
|
51
|
-
import path from 'node:path';
|
|
52
|
-
import { Cause, Context, Data, Duration, Effect, Exit, pipe, Result, Schedule, Schema, Semaphore } from 'effect';
|
|
53
|
-
import { Activity, DurableClock, Workflow, WorkflowEngine } from 'effect/workflow';
|
|
54
|
-
import { describeFailure, startAndEnd } from './failure';
|
|
55
|
-
import { oneLine, standardReason } from './reasons';
|
|
56
|
-
import { filesChanged } from './step-files';
|
|
57
|
-
import { edgeDeclared, RUN_ENDS, RUN_STARTS } from './graph';
|
|
58
|
-
import { meterClosed, meterOpened, StepMeter } from './step-meter';
|
|
59
|
-
import { runLimit } from './storage/budgets';
|
|
60
|
-
import { AGENT_BEAT_MS, noSpend } from './storage/step-records';
|
|
61
|
-
import { claimsCounting } from './storage/agent-claims';
|
|
62
|
-
import { checkedSettings, stepSetting } from './settings';
|
|
63
|
-
import { inPickOrder, listOf, queueOrder, STOOD_DOWN_OUTCOME } from './tasks';
|
|
64
|
-
export { A_STEP_FAILS, edgeDeclared, isRetry, RUN_ENDS, RUN_STARTS } from './graph';
|
|
65
|
-
/** Provided only inside a step that runs agentically; an agent call reports what it spent through it. */
|
|
66
|
-
export class AgentStep extends Context.Service()('AgentStep') {
|
|
67
|
-
}
|
|
68
|
-
/** The outcome of an item its test passed: finished, with no agent. */
|
|
69
|
-
export const CLEARED_BY_TEST = 'cleared by its test, no agent';
|
|
70
|
-
/** What an agent step fails with when its run is one too many for its workflow's budget. Stored as the step's result. */
|
|
71
|
-
export const STOOD_DOWN = 'stood down: its workflow has more runs going than its budget';
|
|
72
|
-
/**
|
|
73
|
-
* What a step waiting for work or for an agent fails with when its process hands its runs to the next one
|
|
74
|
-
* (`pick-wakes.ts` `releaseWaiting`): its run stands down untried, and the next process starts one.
|
|
75
|
-
*/
|
|
76
|
-
export const HANDED_OVER = 'stood down: its process is handing its runs to the next';
|
|
77
|
-
/**
|
|
78
|
-
* What a step of a run a sub-workflow step started fails with once the run above it has ended: nothing is left to read its
|
|
79
|
-
* result, so it does no more work. Two runs of Write C went on writing, an agent each, for ten minutes after the runs of
|
|
80
|
-
* Decompile above them had failed (2026-11-19).
|
|
81
|
-
*/
|
|
82
|
-
export const ABOVE_ENDED = 'stood down: the run above it has ended';
|
|
83
|
-
/**
|
|
84
|
-
* What a run fails with where it can claim no agent at its first agent step (`claimAgentsOrEnd`), or holds one that can no longer be
|
|
85
|
-
* used before its next agent call (`beforeAgentCall`): its task, where it has one, went to the back of its queue, marked
|
|
86
|
-
* as needing an agent, and the run gives its slot up.
|
|
87
|
-
*/
|
|
88
|
-
export const NEEDS_AN_AGENT_STOOD_DOWN = 'stood down: no agent was free, so its task went to the back of its queue, marked as needing one';
|
|
89
|
-
/**
|
|
90
|
-
* What an agent step fails with where no model is set on it or on any workflow above it (`settings.ts`): a fault in the
|
|
91
|
-
* declarations, not in its item, so its run stands down untried, and its task is neither charged a failed try nor blocked.
|
|
92
|
-
* As a plain failure it blocked three Decompile tasks for good (2026-11-21, 22:13 to 22:35 UTC): their inputs never change
|
|
93
|
-
* when a model is set, so "nothing new since its last failed try" never lapsed.
|
|
94
|
-
*/
|
|
95
|
-
export const NO_MODEL_STOOD_DOWN = 'stood down: no model is set on its agent step or on any workflow above it, so it took no agent';
|
|
96
|
-
export const isStoodDown = (failure) => failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN || failure === NO_MODEL_STOOD_DOWN;
|
|
97
|
-
/** Why no agent can be had at an agents' limit of 0, in words. */
|
|
98
|
-
export const AGENTS_LIMIT_ZERO = "its agents' limit is 0";
|
|
99
|
-
/** That every agent a limit allows is claimed, in words. Pure. */
|
|
100
|
-
const agentsInUse = (agents) => `its ${agents === 1 ? 'agent is' : `${agents} agents are`} in use`;
|
|
101
|
-
/** Whether a run is surplus: it is past the budget in the workflow's runs, oldest first. A run not listed is not counted. Pure. */
|
|
102
|
-
export const surplusRun = (oldestFirst, run, budget) => oldestFirst.indexOf(run) >= budget;
|
|
103
|
-
/**
|
|
104
|
-
/**
|
|
105
|
-
* WHAT A STEP IS, as a page says it in words. Alex, 2026-11-19: "there are different kinds of workflow steps. like a check,
|
|
106
|
-
* like a sub workflow."
|
|
107
|
-
*
|
|
108
|
-
* step does part of the work;
|
|
109
|
-
* check decides whether the work passes;
|
|
110
|
-
* sub-workflow a workflow used as a step of another workflow (`StepDeclaration.workflow` names it).
|
|
111
|
-
*/
|
|
112
|
-
export const STEP_KINDS = ['step', 'check', 'sub-workflow'];
|
|
113
|
-
/**
|
|
114
|
-
* HOW A STEP RUNS, a separate question from what it is. Alex, 2026-11-19: "rather than 'no ai' or 'agent' I think a step
|
|
115
|
-
* should be labeled as one of the following 'deterministic', 'agentic' or 'classification' where that third option allows
|
|
116
|
-
* for steps which use a separate classifier model".
|
|
117
|
-
*
|
|
118
|
-
* deterministic code only;
|
|
119
|
-
* agentic an agent does it, on the agent its run claimed as it started (`claimAgentsOrEnd`);
|
|
120
|
-
* classification a separate classifier model decides.
|
|
121
|
-
*
|
|
122
|
-
* A step or a check is any of the three. A sub-workflow step states none: its workflow's own steps state theirs.
|
|
123
|
-
*/
|
|
124
|
-
export const STEP_RUNS = ['deterministic', 'agentic', 'classification'];
|
|
125
|
-
/** A step's kind, from its declaration: the kind it states, a check where it is its workflow's test, a step otherwise. Pure. */
|
|
126
|
-
export const stepKindOf = (s) => s.kind ?? (s.test === true ? 'check' : 'step');
|
|
127
|
-
/** What the test said of an item: it passes now, the exact failure the agent gets, or why it cannot be tested. */
|
|
128
|
-
export const ItemTest = Schema.Union([
|
|
129
|
-
Schema.Struct({ result: Schema.Literal('passes'), detail: Schema.String }),
|
|
130
|
-
Schema.Struct({ result: Schema.Literal('fails'), failure: Schema.String }),
|
|
131
|
-
Schema.Struct({ result: Schema.Literal('cannot'), why: Schema.String }),
|
|
132
|
-
]);
|
|
133
|
-
/**
|
|
134
|
-
* HOW MANY AGENTS A RUN OF A WORKFLOW CLAIMS FOR ITS WHOLE RUN: the number it declares, else 1 where it has an agent step of
|
|
135
|
-
* its own, else none. A workflow whose agent steps are all under its sub-workflow steps claims none itself: each of those
|
|
136
|
-
* workflows claims its own. Pure.
|
|
137
|
-
*/
|
|
138
|
-
export const agentsClaimedBy = (d) => d.agentsClaimed ?? (d.steps().some((s) => s.runs === 'agentic') ? 1 : 0);
|
|
139
|
-
/** A run not started: its workflow's run limit was reached. What a start that waits for its result fails with. */
|
|
140
|
-
export class RunLimitReached extends Data.TaggedError('RunLimitReached') {
|
|
141
|
-
}
|
|
142
|
-
/** How often a workflow's refused starts are said, at most: a timer at 0 would say it every turn. */
|
|
143
|
-
const REFUSED_SAID_EVERY_MS = 10 * 60 * 1000;
|
|
144
|
-
/**
|
|
145
|
-
* A WORKFLOW'S RUN LIMIT, whatever starts it: for one its budget keeps going, its run limit or its agents' limit
|
|
146
|
-
* (`runLimit`); for any other its run limit, none meaning no limit. 0 starts nothing new. Pure.
|
|
147
|
-
*/
|
|
148
|
-
export const runLimitOf = (d, limits) => keptRunningByItsBudget(d) ? runLimit(limits) : limits.runs;
|
|
149
|
-
/** Whether a workflow declares a list, of either kind: it has tasks and a queue. Pure. */
|
|
150
|
-
export const hasAList = (d) => d.pending !== undefined || d.items !== undefined;
|
|
151
|
-
/** Whether a step uses an agent: it is an agent step, or a sub-workflow step whose workflow has one at any depth. Pure. */
|
|
152
|
-
export const stepUsesAnAgent = (s) => s.runs === 'agentic' || s.agentUnder?.() === true;
|
|
153
|
-
/** Whether a workflow's budget rules it: a declared list, and an agent step of its own or under a sub-workflow step. Pure. */
|
|
154
|
-
export const keptRunningByItsBudget = (d) => hasAList(d) && d.steps().some(stepUsesAnAgent);
|
|
155
|
-
/**
|
|
156
|
-
* The workflows a run of another starts as one of its steps (`defineSubWorkflow`): each of their runs is part of the run
|
|
157
|
-
* above it, which a count takes once, and they have no limit of their own. A step on its own trigger is not one. Pure.
|
|
158
|
-
*/
|
|
159
|
-
export const startedAsSteps = (declared) => new Set(declared.flatMap((d) => d.steps().flatMap((s) => (s.workflow === undefined || s.runsOnItsOwnTrigger === true ? [] : [s.workflow]))));
|
|
160
|
-
/**
|
|
161
|
-
* Whether every step of a workflow is another workflow on its own trigger: it starts no run of its own, and its runs, agents
|
|
162
|
-
* and costs are its steps', added up. Pure.
|
|
163
|
-
*/
|
|
164
|
-
export const isMadeOfWorkflows = (d) => {
|
|
165
|
-
const steps = d.steps();
|
|
166
|
-
return steps.length > 0 && steps.every((s) => s.runsOnItsOwnTrigger === true);
|
|
167
|
-
};
|
|
168
|
-
/**
|
|
169
|
-
* WHETHER A WORKFLOW'S TASKS ARE ITS RUNS, one task a run (`tasks.ts` `runStarted`): it works on no item, has runs of its
|
|
170
|
-
* own (it is not made of workflows), and runs on its own trigger, never as a step another workflow's run starts, whose
|
|
171
|
-
* tasks are that workflow's passing through it. Alex, 2026-11-21: "a workflow is a workflow". Pure.
|
|
172
|
-
*/
|
|
173
|
-
export const tasksAreRuns = (d, declared) => d.item === null && !isMadeOfWorkflows(d) && !startedAsSteps(declared).has(d.name);
|
|
174
|
-
const CurrentMeter = Context.Reference('CurrentStepMeter', { defaultValue: () => null });
|
|
175
|
-
/** The definer of one project's workflows and steps, on its stores. */
|
|
176
|
-
export const makeSteps = (deps) => {
|
|
177
|
-
const { stepRecords: records, stepFiles } = deps;
|
|
178
|
-
const DECLARED = new Map();
|
|
179
|
-
/** The platform's own workflows, by name (`system-workflows.ts`): defined before any of the app's. */
|
|
180
|
-
const SYSTEM = new Set();
|
|
181
|
-
/**
|
|
182
|
-
* AN APP CANNOT AMEND ONE OF THE PLATFORM'S OWN WORKFLOWS: a definition of the same name, or one holding it as a step,
|
|
183
|
-
* fails the app's start, naming what the app may set instead. Alex, 2026-11-22: "system workflows at the top level which
|
|
184
|
-
* can be configured but not amended without changing the platform itself".
|
|
185
|
-
*/
|
|
186
|
-
const refuseSystem = (name, what) => {
|
|
187
|
-
if (SYSTEM.has(name))
|
|
188
|
-
throw new Error(`${name} is one of the platform's own workflows, so ${what}: its schedule and run limit are the app's to set, and its steps change only with the platform`);
|
|
189
|
-
};
|
|
190
|
-
const PICKING = new Map();
|
|
191
|
-
const RUN_ENDED = new Set();
|
|
192
|
-
const undeclaredSaid = new Set();
|
|
193
|
-
/** Each workflow's run items a mark was refused for, said once (`markedAsNeedingAnAgent`). */
|
|
194
|
-
const offItsListSaid = new Set();
|
|
195
|
-
/**
|
|
196
|
-
* EACH RUN'S LAST STEP, as this process ran it, until the run ends. A run resumed from another process has none here, and
|
|
197
|
-
* the records of that process say; a record this process wrote for a run that has ended is no step of this one. Read from
|
|
198
|
-
* the records alone, a test that names no records file saw every step as a run's first, and two tests reusing a run's id
|
|
199
|
-
* saw the other's last step.
|
|
200
|
-
*/
|
|
201
|
-
const lastStepRan = new Map();
|
|
202
|
-
const lastStepBefore = (run) => {
|
|
203
|
-
const ran = lastStepRan.get(run);
|
|
204
|
-
if (ran !== undefined)
|
|
205
|
-
return Effect.succeed(ran);
|
|
206
|
-
return Effect.map(records.lastStepOf(run), (recorded) => {
|
|
207
|
-
const self = deps.thisProcess();
|
|
208
|
-
return recorded === null || (recorded.owner !== null && recorded.owner.pid === self.pid && recorded.owner.startedAt === self.startedAt) ? null : recorded;
|
|
209
|
-
});
|
|
210
|
-
};
|
|
211
|
-
/**
|
|
212
|
-
* A RECORD FAILING TO WRITE NEVER FAILS THE STEP IT MEASURES: what the store could not write is said, and the step goes
|
|
213
|
-
* on with none (`null`).
|
|
214
|
-
*/
|
|
215
|
-
const recorded = (what, write) => Effect.catchTag(write, 'StorageError', (e) => Effect.as(Effect.logError(`[step-runs] ${what}: ${e.reason}`), null));
|
|
216
|
-
/** The same from a callback outside any effect (a heartbeat, usage as it arrives): run at once, never waited for. */
|
|
217
|
-
const recordNow = (what, write) => { Effect.runFork(recorded(what, write)); };
|
|
218
|
-
/** A file's path relative to the project's source root, from its absolute path. */
|
|
219
|
-
const sourcePath = (absolute) => path.relative(deps.sourceRoot, absolute).split(path.sep).join('/');
|
|
220
|
-
/** Each file's code as this process loaded it (`codeOf`), by its absolute path. */
|
|
221
|
-
const CODE_OF_FILE = new Map();
|
|
222
|
-
/**
|
|
223
|
-
* A FILE'S CODE AS THIS PROCESS LOADED IT, read once, when the first definition naming it is made: its content's hash, and
|
|
224
|
-
* when it last changed. What a workflow's version is made of (`versionOf`). An unreadable file is code too: its hash says so.
|
|
225
|
-
*/
|
|
226
|
-
const codeOf = (file) => {
|
|
227
|
-
const known = CODE_OF_FILE.get(file);
|
|
228
|
-
if (known !== undefined)
|
|
229
|
-
return known;
|
|
230
|
-
let code;
|
|
231
|
-
try {
|
|
232
|
-
code = { hash: createHash('sha256').update(fs.readFileSync(file)).digest('hex').slice(0, 16), changed: fs.statSync(file).mtimeMs / 1000 };
|
|
233
|
-
}
|
|
234
|
-
catch {
|
|
235
|
-
code = { hash: 'unreadable', changed: 0 };
|
|
236
|
-
}
|
|
237
|
-
CODE_OF_FILE.set(file, code);
|
|
238
|
-
return code;
|
|
239
|
-
};
|
|
240
|
-
/** Each step's code (`defineStep`): the file that defines it, and an agent step's prompt file. */
|
|
241
|
-
const STEP_CODE = new WeakMap();
|
|
242
|
-
/** Each workflow's own file's code (`defineWorkflow`). */
|
|
243
|
-
const WORKFLOW_CODE = new Map();
|
|
244
|
-
const VERSIONS = new Map();
|
|
245
|
-
/**
|
|
246
|
-
* A WORKFLOW'S VERSION, THE CODE LOADED NOW: a hash of its own file and each of its steps' files (an agent step's prompt
|
|
247
|
-
* included), in their order; a step that is a workflow counts by that workflow's version, never its files inlined. `since`
|
|
248
|
-
* is when the newest of those files last changed. Read once per process, after every workflow is defined: a version
|
|
249
|
-
* changes only with the code a process loads. Every step record of a run carries its run's version
|
|
250
|
-
* (`StepRecords.openStepRun`).
|
|
251
|
-
*/
|
|
252
|
-
const versionOf = (workflow, under = new Set()) => {
|
|
253
|
-
const known = VERSIONS.get(workflow);
|
|
254
|
-
if (known !== undefined)
|
|
255
|
-
return known;
|
|
256
|
-
const d = DECLARED.get(workflow);
|
|
257
|
-
if (d === undefined || under.has(workflow))
|
|
258
|
-
return { version: 'undeclared', since: 0 };
|
|
259
|
-
const own = WORKFLOW_CODE.get(workflow) ?? { hash: 'unknown', changed: 0 };
|
|
260
|
-
let since = own.changed;
|
|
261
|
-
const parts = [own.hash, ...d.steps().map((s) => {
|
|
262
|
-
if (s.workflow !== undefined) {
|
|
263
|
-
const sub = versionOf(s.workflow, new Set([...under, workflow]));
|
|
264
|
-
since = Math.max(since, sub.since);
|
|
265
|
-
return `${s.name}>${sub.version}`;
|
|
266
|
-
}
|
|
267
|
-
const codes = STEP_CODE.get(s) ?? [];
|
|
268
|
-
for (const c of codes)
|
|
269
|
-
since = Math.max(since, c.changed);
|
|
270
|
-
return `${s.name}:${codes.map((c) => c.hash).join(',')}`;
|
|
271
|
-
})];
|
|
272
|
-
const version = { version: createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 12), since };
|
|
273
|
-
VERSIONS.set(workflow, version);
|
|
274
|
-
return version;
|
|
275
|
-
};
|
|
276
|
-
/** The runs of these workflows not finished now, oldest first. */
|
|
277
|
-
const runsOldestFirst = (workflows) => deps.engine.runsOldestFirst(workflows);
|
|
278
|
-
/** The runs of a workflow not finished now, by the id its step records carry. */
|
|
279
|
-
const runningRunIds = (workflow) => deps.engine.runsOldestFirst([workflow]);
|
|
280
|
-
/** Runs of a workflow not finished now. */
|
|
281
|
-
const runningRuns = (workflow) => deps.engine.runningRuns(workflow);
|
|
282
|
-
/**
|
|
283
|
-
* One item's part of a batch step: its own record under the step's, with its own time and CPU, and what it used added to
|
|
284
|
-
* the step's. Outside a step it just runs the work.
|
|
285
|
-
*/
|
|
286
|
-
const eachItem = (subject, work) => Effect.flatMap(CurrentMeter, (step) => {
|
|
287
|
-
if (step === null)
|
|
288
|
-
return work;
|
|
289
|
-
return Effect.acquireUseRelease(Effect.gen(function* () {
|
|
290
|
-
const id = step.record === null ? null : yield* recorded('open an item', records.openStepItem({ stepRun: step.record, subject }));
|
|
291
|
-
const meter = new StepMeter(step.record, false, step.writes, step);
|
|
292
|
-
meterOpened(meter);
|
|
293
|
-
return { id, meter };
|
|
294
|
-
}), ({ meter }) => pipe(work, Effect.provideService(deps.CurrentStepUsage, meter)), ({ id, meter }, exit) => Effect.gen(function* () {
|
|
295
|
-
meterClosed(meter);
|
|
296
|
-
if (id !== null)
|
|
297
|
-
yield* recorded('close an item', records.closeStepItem({ id, outcome: Exit.isSuccess(exit) ? 'success' : Cause.hasInterrupts(exit.cause) ? 'interrupted' : 'failure', used: meter.used() }));
|
|
298
|
-
}));
|
|
299
|
-
});
|
|
300
|
-
/**
|
|
301
|
-
* Whether this run should stand down before its next agent call, and whether its Pick, finding nothing it can claim, waits
|
|
302
|
-
* for work rather than ending its run. A test supplies others.
|
|
303
|
-
*/
|
|
304
|
-
/**
|
|
305
|
-
* A declared workflow's limits: its run limit (`runLimitOf`, none for no limit), and its agents' limit where its budget
|
|
306
|
-
* keeps it going (none for any other). None for one not declared, or with no store to read.
|
|
307
|
-
*/
|
|
308
|
-
const limitsOf = (workflow) => {
|
|
309
|
-
const d = DECLARED.get(workflow);
|
|
310
|
-
if (d === undefined)
|
|
311
|
-
return Effect.succeed(null);
|
|
312
|
-
return Effect.map(deps.budgets.limitsOf(workflow), (limits) => (limits === null ? null : { runs: runLimitOf(d, limits), agents: keptRunningByItsBudget(d) ? limits.agents : null }));
|
|
313
|
-
};
|
|
314
|
-
/** Whether a run is past the runs its workflow's run limit keeps, oldest first; never where it has no run limit. */
|
|
315
|
-
const pastItsRunLimit = (workflow, run) => Effect.flatMap(limitsOf(workflow), (w) => {
|
|
316
|
-
const runs = w === null ? null : w.runs;
|
|
317
|
-
return runs === null ? Effect.succeed(false) : Effect.map(runsOldestFirst([workflow]), (going) => surplusRun(going, run, runs));
|
|
318
|
-
});
|
|
319
|
-
/**
|
|
320
|
-
* LIMITS THAT CANNOT BE READ GIVE NO NEW AGENT: a run does not stand down and its Pick waits, each until the next wake reads
|
|
321
|
-
* them again, and a run that starts takes no claim and ends, saying why. Read as no limits, a store that failed would start
|
|
322
|
-
* agents at 0.
|
|
323
|
-
*/
|
|
324
|
-
const unreadLimits = (workflow, held) => (e) => Effect.as(Effect.logError(`[budget] ${workflow}: its limits could not be read (${e.reason}); its runs wait`), held(e.reason));
|
|
325
|
-
/**
|
|
326
|
-
* THE RUN AT THE TOP OF A RUN: itself, or, for a run a sub-workflow step started, the run at the top of those above it
|
|
327
|
-
* (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent claim counts
|
|
328
|
-
* against the agents' limit of the workflow at the top (`claimAgentsOrEnd`). Kept while the run goes: it never changes.
|
|
329
|
-
*/
|
|
330
|
-
const TOPS = new Map();
|
|
331
|
-
/** Each workflow's start with no run limit asked, by name: what a sub-workflow step starts it by (`defineSubWorkflow`). */
|
|
332
|
-
const STARTS_AS_A_STEP = new Map();
|
|
333
|
-
const topOf = (workflow, run) => {
|
|
334
|
-
const known = TOPS.get(run);
|
|
335
|
-
if (known !== undefined)
|
|
336
|
-
return Effect.succeed(known);
|
|
337
|
-
return Effect.map(records.rootOfRun(run), (root) => {
|
|
338
|
-
const top = root ?? { run, workflow };
|
|
339
|
-
TOPS.set(run, top);
|
|
340
|
-
return top;
|
|
341
|
-
});
|
|
342
|
-
};
|
|
343
|
-
/**
|
|
344
|
-
* THE AGENT CLAIMS THAT COUNT NOW, every workflow's: open, with the run at the top of each unfinished in the engine
|
|
345
|
-
* (`storage/agent-claims.ts` `claimsCounting`). The runs holding an agent, as a page shows them.
|
|
346
|
-
*/
|
|
347
|
-
const agentClaimsNow = () => Effect.map(Effect.all({ open: deps.claims.openAgentClaims(), live: deps.engine.unfinishedRuns() }), ({ open, live }) => claimsCounting(open, new Set(live.map((u) => u.run))));
|
|
348
|
-
/** How many agents the runs under `workflow`'s runs claim now, the claim of the run `besides` left out. */
|
|
349
|
-
const agentsClaimedAgainst = (r) => Effect.map(Effect.all({ open: deps.claims.openAgentClaims(), live: runsOldestFirst([r.workflow]) }), ({ open, live }) => claimsCounting(open.filter((c) => c.top.workflow === r.workflow && c.run !== r.besides), new Set(live)).reduce((n, c) => n + c.agents, 0));
|
|
350
|
-
const AgentBudgets = Context.Reference('AgentBudgets', {
|
|
351
|
-
defaultValue: () => ({
|
|
352
|
-
// Among its workflow's unfinished runs, oldest first, the run is past those its run limit keeps (`runLimit`). A run not
|
|
353
|
-
// listed is not counted. A run a sub-workflow step started stands down with the run at its top.
|
|
354
|
-
standsDown: (workflow, run) => pipe(topOf(workflow, run), Effect.flatMap((top) => Effect.zipWith(pastItsRunLimit(workflow, run), top.run === run ? Effect.succeed(false) : pastItsRunLimit(top.workflow, top.run), (own, above) => own || above)), Effect.catchTag('StorageError', unreadLimits(workflow, () => false))),
|
|
355
|
-
waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
|
|
356
|
-
// The agents the other runs under the workflow at its top claim (`agentsClaimedAgainst`), against that workflow's
|
|
357
|
-
// agents' limit: at 0 none is ever free, which no claim ending changes.
|
|
358
|
-
agentSlot: (workflow, run) => pipe(run === null ? Effect.succeed({ run: null, workflow }) : topOf(workflow, run), Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w) => {
|
|
359
|
-
const agents = w === null ? null : w.agents;
|
|
360
|
-
if (agents === null)
|
|
361
|
-
return Effect.succeed({ free: true });
|
|
362
|
-
if (agents === 0)
|
|
363
|
-
return Effect.succeed({ free: false, why: AGENTS_LIMIT_ZERO, unavailable: AGENTS_LIMIT_ZERO, inUse: null });
|
|
364
|
-
return Effect.map(agentsClaimedAgainst({ workflow: top.workflow, besides: run }), (held) => (held < agents ? { free: true, limit: agents } : { free: false, why: agentsInUse(agents), unavailable: null, inUse: agentsInUse(agents) }));
|
|
365
|
-
})), Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false, why: `its limits could not be read (${why})`, unavailable: null, inUse: null })))),
|
|
366
|
-
}),
|
|
367
|
-
});
|
|
368
|
-
/** The task a run at the top works on: its workflow's, where that workflow has a list, on the run's item; none otherwise. */
|
|
369
|
-
const taskOfTop = (top) => {
|
|
370
|
-
const d = DECLARED.get(top.workflow);
|
|
371
|
-
if (d === undefined || !hasAList(d))
|
|
372
|
-
return Effect.succeed(null);
|
|
373
|
-
return Effect.map(Effect.orElseSucceed(records.subjectOfRun(top.run), () => null), (item) => (item === null ? null : { workflow: top.workflow, item }));
|
|
374
|
-
};
|
|
375
|
-
/**
|
|
376
|
-
* Marks the task of the run at the top as needing an agent; whether it was marked (a run with no task, or no store, is not).
|
|
377
|
-
*
|
|
378
|
-
* ONLY A TASK ITS PICK READS IS MARKED (`tasks.ts` `readByItsPick`). A mark on any other passes over nothing: the run
|
|
379
|
-
* ends, the next takes the same work and ends the same way. Fix conflicts' runs named conflicts while its list named
|
|
380
|
-
* functions, and it took the same 3 names 907 times in 75 minutes (2026-11-20). Such a run is a fault in its workflow,
|
|
381
|
-
* which names its run's item differently from its list: in a test it fails the run, and live it is said once, and the
|
|
382
|
-
* run ends unmarked, as a run with no task does. A task whose state cannot be read is marked as before.
|
|
383
|
-
*/
|
|
384
|
-
const markedAsNeedingAnAgent = (top, step, why) => Effect.flatMap(taskOfTop(top), (task) => {
|
|
385
|
-
if (task === null)
|
|
386
|
-
return Effect.succeed(false);
|
|
387
|
-
return Effect.flatMap(Effect.orElseSucceed(deps.tasks.readByItsPick(task), () => true), (read) => {
|
|
388
|
-
if (read)
|
|
389
|
-
return deps.tasks.markNeedsAgent({ task, by: { workflow: top.workflow, run: top.run, step }, why });
|
|
390
|
-
const fault = `${top.workflow}: its run ${top.run} works on ${task.item}, which is not a task its Pick reads (not on its list, nor returned to its queue), so a mark at ${step} would pass over nothing; it ends unmarked`;
|
|
391
|
-
if (process.env.NODE_ENV === 'test')
|
|
392
|
-
return Effect.die(new Error(fault));
|
|
393
|
-
if (!offItsListSaid.has(`${top.workflow}\n${task.item}`)) {
|
|
394
|
-
offItsListSaid.add(`${top.workflow}\n${task.item}`);
|
|
395
|
-
console.error(`[agents] ${fault}`);
|
|
396
|
-
}
|
|
397
|
-
return Effect.succeed(false);
|
|
398
|
-
});
|
|
399
|
-
});
|
|
400
|
-
/**
|
|
401
|
-
* WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, until a limit or a reading changes, in words; none where one can: the
|
|
402
|
-
* spending limit holds, or its agents' limit is 0. While it says so and its Pick would pass over every task in its queue,
|
|
403
|
-
* no run of it starts, and a Pick that finds nothing ends its run (`whyNoRunCanTakeWork`).
|
|
404
|
-
*/
|
|
405
|
-
const agentsUnavailable = (workflow) => Effect.gen(function* () {
|
|
406
|
-
const held = yield* deps.spendingHoldsAgents();
|
|
407
|
-
if (held !== null)
|
|
408
|
-
return held;
|
|
409
|
-
const limits = yield* Effect.orElseSucceed(limitsOf(workflow), () => null);
|
|
410
|
-
return limits !== null && limits.agents === 0 ? AGENTS_LIMIT_ZERO : null;
|
|
411
|
-
});
|
|
412
|
-
/** Whether a run of a workflow may claim an agent now (`AgentSlot`): the spending limit first, then its top workflow's agents. */
|
|
413
|
-
const agentSlotNow = (workflow, run) => Effect.gen(function* () {
|
|
414
|
-
const held = yield* deps.spendingHoldsAgents();
|
|
415
|
-
if (held !== null)
|
|
416
|
-
return { free: false, why: held, unavailable: held, inUse: null };
|
|
417
|
-
return yield* (yield* AgentBudgets).agentSlot(workflow, run);
|
|
418
|
-
});
|
|
419
|
-
/**
|
|
420
|
-
* WHY NO AGENT IS FREE FOR A WORKFLOW'S PICK NOW, in words; none where one is, or its limits could not be read: none can be
|
|
421
|
-
* had (`agentsUnavailable`), or every agent its agents' limit allows is claimed. While it says so, its Pick passes over its
|
|
422
|
-
* tasks marked as needing an agent, and those with nothing new since their last run (`queueNow`, `pickOrder`, `tasks.ts`
|
|
423
|
-
* `passedOverWithoutAnAgent`): a run on one would only find no agent to claim again. It takes them in their queue's order
|
|
424
|
-
* once an agent is free, woken by a claim ending (`endClaims`). Taken while every agent was claimed, a marked task would be
|
|
425
|
-
* picked, marked and put back again at once, as Fix conflicts' 3 tasks were 907 times in 75 minutes (2026-11-20).
|
|
426
|
-
*/
|
|
427
|
-
const whyNoAgentIsFree = (workflow) => Effect.map(agentSlotNow(workflow, null), (slot) => (slot.free ? null : slot.unavailable !== null ? slot.unavailable : slot.inUse));
|
|
428
|
-
/** One claim taken at a time per top workflow in this process; the store's statement keeps processes apart (`takeAgentClaim`). */
|
|
429
|
-
const CLAIMING = new Map();
|
|
430
|
-
/**
|
|
431
|
-
* A RUN THAT CAN HAVE NO AGENT ENDS, AND NEVER WAITS: it marks its task as needing an agent, which puts it at the back of
|
|
432
|
-
* its queue (`tasks.ts` `markNeedsAgent`), and fails with `NEEDS_AN_AGENT_STOOD_DOWN`, giving its run slot to the next
|
|
433
|
-
* task. A run with no task, or no store to mark it in, ends the same way, and its next trigger tries again. Waiting, a few
|
|
434
|
-
* such runs filled every run slot of Decompile and nothing behind them moved: at 0 agents on 2026-11-20, and on 2026-11-21
|
|
435
|
-
* with 4 runs allowed and 1 agent, 3 runs waited inside Write C for hours. Alex, 2026-11-22: "i thought that if agent limit
|
|
436
|
-
* is 1 and 1 task is currently using the agent on a step, then the running task that gets blocked on needing an agent is
|
|
437
|
-
* marked as needing an agent then stopped and moved back to the queue's end".
|
|
438
|
-
*/
|
|
439
|
-
const endForWantOfAnAgent = (r) => Effect.flatMap(markedAsNeedingAnAgent(r.top, r.step, r.why), (marked) => {
|
|
440
|
-
console.log(`[agents] ${r.workflow} run ${r.run} ended at ${r.step}: no agent was free (${r.why}); ${marked ? 'its task goes to the back of its queue, marked as needing one' : 'it has no task to mark, and its next trigger tries again'}`);
|
|
441
|
-
return Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
|
|
442
|
-
});
|
|
443
|
-
/**
|
|
444
|
-
* THE RUN A CLAIM IS TAKEN FOR: the run itself, or, where a sub-workflow step that keeps its agent until its run ends
|
|
445
|
-
* started it (`StepDeclaration.agentKeptUntilThisRunEnds`), the run of that step, whose end ends the claim (`endClaims`).
|
|
446
|
-
* Where the run above cannot be read, the claim is the run's own, and that is said: it ends with the run, as before.
|
|
447
|
-
*/
|
|
448
|
-
const claimHolder = (workflow, run) => pipe(records.parentOfRun(run), Effect.map((parent) => {
|
|
449
|
-
const keeps = parent !== null && DECLARED.get(parent.workflow)?.steps().some((s) => s.name === parent.step && s.agentKeptUntilThisRunEnds === true) === true;
|
|
450
|
-
return keeps ? { run: parent.run, workflow: parent.workflow } : { run, workflow };
|
|
451
|
-
}), Effect.catchTag('StorageError', (e) => Effect.as(Effect.logError(`[agents] ${workflow} run ${run}: the run above it could not be read, so its agent claim is its own and ends with it: ${e.reason}`), { run, workflow })));
|
|
452
|
-
/**
|
|
453
|
-
* A RUN CLAIMS ITS AGENTS AS IT STARTS, AND HOLDS THEM UNTIL IT ENDS. Alex, 2026-11-22: "i think we should think about a
|
|
454
|
-
* workflow having a number of agents it claims. so a subworkflow write C claims one on decompiles agents so while that
|
|
455
|
-
* task's own workflow is doing all these different things, some are agentic steps and deterministic steps but as that's
|
|
456
|
-
* going on decompile is down one agent."
|
|
457
|
-
*
|
|
458
|
-
* A run of a workflow that claims agents (`agentsClaimedBy`) takes its claim at its first agent step, against the agents'
|
|
459
|
-
* limit of the workflow at the top of its run (`topOf`): Write C's against Decompile's. Its steps before it (a Pick, a
|
|
460
|
-
* Test with no agent) run with none, so a run at an agents' limit of 0 still finishes what needs no agent, and reaches its
|
|
461
|
-
* agent step with its task named, to mark. From then it holds the claim through every step, agent and deterministic, and
|
|
462
|
-
* through a handover or a restart, until it ends (`endClaims`). A workflow with no agent step of its own that declares
|
|
463
|
-
* agents claims as it starts. Its agent steps never wait
|
|
464
|
-
* for, or take, an agent of their own. A run resumed, or replayed by the engine, keeps the claim it holds; a run under a
|
|
465
|
-
* run that holds one takes none. With no claim free it ends (`endForWantOfAnAgent`). Where the claim is taken, a mark on
|
|
466
|
-
* its task as needing an agent has done its work and clears (`tasks.ts` `agentTaken`). A run that a sub-workflow step
|
|
467
|
-
* keeping its agent started (`agentKeptUntilThisRunEnds`) takes the claim for the run of that step (`claimHolder`), which
|
|
468
|
-
* holds it until it ends: that step's next call finds it held, and takes none.
|
|
469
|
-
*/
|
|
470
|
-
const claimAgentsOrEnd = (workflow, run, step) => Effect.gen(function* () {
|
|
471
|
-
const d = DECLARED.get(workflow);
|
|
472
|
-
const agents = d === undefined ? 0 : agentsClaimedBy(d);
|
|
473
|
-
if (agents === 0)
|
|
474
|
-
return;
|
|
475
|
-
// A read that fails takes no second claim: the run goes on as one that holds its own, and that is said.
|
|
476
|
-
const held = yield* Effect.catchTag(deps.claims.claimHeldAtOrAbove(run), 'StorageError', (e) => Effect.as(Effect.logError(`[agents] ${workflow} run ${run}: whether it holds an agent claim could not be read, so it goes on as one that does: ${e.reason}`), true));
|
|
477
|
-
if (held)
|
|
478
|
-
return;
|
|
479
|
-
const top = yield* Effect.orElseSucceed(topOf(workflow, run), () => ({ run, workflow }));
|
|
480
|
-
const lock = CLAIMING.get(top.workflow) ?? Semaphore.makeUnsafe(1);
|
|
481
|
-
CLAIMING.set(top.workflow, lock);
|
|
482
|
-
const why = yield* lock.withPermits(1)(Effect.gen(function* () {
|
|
483
|
-
const slot = yield* agentSlotNow(workflow, run);
|
|
484
|
-
if (!slot.free)
|
|
485
|
-
return slot.unavailable ?? slot.inUse ?? slot.why;
|
|
486
|
-
const limit = slot.limit ?? null;
|
|
487
|
-
const live = yield* Effect.orElseSucceed(runsOldestFirst([top.workflow]), () => [top.run]);
|
|
488
|
-
const holder = yield* claimHolder(workflow, run);
|
|
489
|
-
const taken = yield* Effect.catchTag(deps.claims.takeAgentClaim({ ...holder, top, agents, limit, liveTopRuns: live }), 'StorageError', (e) => Effect.as(Effect.logError(`[agents] ${workflow} run ${run}: its agent claim could not be recorded, so it goes on unrecorded: ${e.reason}`), 'not recorded'));
|
|
490
|
-
return taken === 'no room' ? agentsInUse(limit ?? agents) : null;
|
|
491
|
-
}));
|
|
492
|
-
if (why !== null)
|
|
493
|
-
return yield* endForWantOfAnAgent({ top, workflow, run, step, why });
|
|
494
|
-
const task = yield* taskOfTop(top);
|
|
495
|
-
if (task !== null)
|
|
496
|
-
yield* deps.tasks.agentTaken({ task, by: { workflow: top.workflow, run: top.run, step } });
|
|
497
|
-
});
|
|
498
|
-
/**
|
|
499
|
-
* BEFORE EACH AGENT CALL, A RUN THAT HOLDS ITS CLAIM ENDS WHERE NO AGENT CAN BE HAD NOW: the spending limit holds, or its
|
|
500
|
-
* top workflow's agents' limit was set to 0 (`AgentSlot` `unavailable`). The call before it finished; this one is not made,
|
|
501
|
-
* and the run gives its task back as one that could claim none (`endForWantOfAnAgent`). Every agent merely claimed ends no
|
|
502
|
-
* run, its own claim among them, and nor does a limit lowered to above 0: the claims held keep their agents to their ends.
|
|
503
|
-
*/
|
|
504
|
-
const beforeAgentCall = (instance, step) => Effect.gen(function* () {
|
|
505
|
-
const workflow = instance.workflow._tag;
|
|
506
|
-
const top = yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }));
|
|
507
|
-
const slot = yield* agentSlotNow(workflow, instance.executionId);
|
|
508
|
-
if (!slot.free && slot.unavailable !== null)
|
|
509
|
-
return yield* endForWantOfAnAgent({ top, workflow, run: instance.executionId, step, why: slot.unavailable });
|
|
510
|
-
});
|
|
511
|
-
/**
|
|
512
|
-
* A RUN'S CLAIMS END WITH IT, whatever its outcome, and its top workflow's Picks are woken: a task they pass over as needing
|
|
513
|
-
* an agent can be taken now. An interrupted run keeps them: it resumes, in this process or the next.
|
|
514
|
-
*/
|
|
515
|
-
const endClaims = (run, exit) => Effect.gen(function* () {
|
|
516
|
-
if (!Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause))
|
|
517
|
-
return;
|
|
518
|
-
const ended = yield* recorded('end its agent claims', deps.claims.endAgentClaims({ run, outcome: Exit.isSuccess(exit) ? 'success' : 'failure' }));
|
|
519
|
-
for (const top of new Set((ended ?? []).map((c) => c.top.workflow)))
|
|
520
|
-
deps.wakes.wakePicksOf(top, 'an agent claim ended');
|
|
521
|
-
});
|
|
522
|
-
/**
|
|
523
|
-
* A RUN OF A WORKFLOW WITH A LIST WORKS ON ONE OF ITS TASKS: the item its Pick named, which every later step inherits. A
|
|
524
|
-
* step naming another is the fault `markedAsNeedingAnAgent` guards against, caught where it is made: in tests it fails
|
|
525
|
-
* the run; live, it is said once.
|
|
526
|
-
*/
|
|
527
|
-
const checkItem = (workflow, run, step, item) => Effect.gen(function* () {
|
|
528
|
-
const d = DECLARED.get(workflow);
|
|
529
|
-
if (item === null || d === undefined || !hasAList(d))
|
|
530
|
-
return;
|
|
531
|
-
const named = yield* Effect.orElseSucceed(records.subjectOfRun(run), () => null);
|
|
532
|
-
if (named === null || named.toLowerCase() === item.toLowerCase())
|
|
533
|
-
return;
|
|
534
|
-
const fault = `${workflow}: its step ${step} names ${item}, while its run works on ${named}: a run of a workflow with a list works on one of its tasks`;
|
|
535
|
-
if (process.env.NODE_ENV === 'test')
|
|
536
|
-
throw new Error(fault);
|
|
537
|
-
if (!undeclaredSaid.has(fault)) {
|
|
538
|
-
undeclaredSaid.add(fault);
|
|
539
|
-
console.error(`[steps] ${fault}`);
|
|
540
|
-
}
|
|
541
|
-
});
|
|
542
|
-
/** Checks the move to `step` against its workflow's graph: in tests an undeclared one fails the run; live, it is said once. */
|
|
543
|
-
const checkEdge = (workflow, run, step) => Effect.gen(function* () {
|
|
544
|
-
const graph = DECLARED.get(workflow)?.graph?.();
|
|
545
|
-
if (graph === undefined)
|
|
546
|
-
return;
|
|
547
|
-
const read = yield* Effect.result(lastStepBefore(run));
|
|
548
|
-
// With its last step unread, the move cannot be checked; it is said, and the step goes on.
|
|
549
|
-
if (Result.isFailure(read))
|
|
550
|
-
return yield* Effect.logError(`[steps] ${workflow}: the move to ${step} was not checked: ${read.failure.reason}`);
|
|
551
|
-
const last = read.success;
|
|
552
|
-
if (edgeDeclared(graph, last, step))
|
|
553
|
-
return;
|
|
554
|
-
// A sub-workflow step run again as its workflow ends, after its run above was suspended, takes its own open record up
|
|
555
|
-
// again (`defineSubWorkflow`): that is no move. Read as one, every such resume of Decompile's Write C was said to be undeclared.
|
|
556
|
-
if (last !== null && !last.failed && last.step === step && DECLARED.get(workflow)?.steps().some((s) => s.name === step && s.kind === 'sub-workflow') === true)
|
|
557
|
-
return;
|
|
558
|
-
const move = `${workflow}: ${last === null ? RUN_STARTS : `${last.step}${last.failed ? ' (failed)' : ''}`} to ${step}`;
|
|
559
|
-
if (process.env.NODE_ENV === 'test')
|
|
560
|
-
throw new Error(`a run took an edge its workflow does not declare: ${move}`);
|
|
561
|
-
if (!undeclaredSaid.has(move)) {
|
|
562
|
-
undeclaredSaid.add(move);
|
|
563
|
-
console.error(`[steps] a run took an edge its workflow does not declare: ${move}`);
|
|
564
|
-
}
|
|
565
|
-
});
|
|
566
|
-
/** Runs `execute` as this step of the workflow it is in, and writes its record. */
|
|
567
|
-
const measured = (step, call, subject, subjectOf, reasonOf, mayWrite, execute, childRun = null) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => {
|
|
568
|
-
// A call's running sum is by request; its final figures replace it. `settled` is what finished calls reported.
|
|
569
|
-
const settled = noSpend();
|
|
570
|
-
const running = new Map();
|
|
571
|
-
const spendNow = () => {
|
|
572
|
-
const out = { ...settled };
|
|
573
|
-
for (const r of running.values()) {
|
|
574
|
-
out.fresh += r.fresh;
|
|
575
|
-
out.cacheWrite += r.cacheWrite;
|
|
576
|
-
out.cacheRead += r.cacheRead;
|
|
577
|
-
out.output += r.output;
|
|
578
|
-
out.requests += 1;
|
|
579
|
-
}
|
|
580
|
-
return out;
|
|
581
|
-
};
|
|
582
|
-
const usage = (message, model, u) => {
|
|
583
|
-
const was = running.get(message) ?? noSpend();
|
|
584
|
-
running.set(message, {
|
|
585
|
-
...was,
|
|
586
|
-
fresh: u.input_tokens ?? was.fresh,
|
|
587
|
-
cacheRead: u.cache_read_input_tokens ?? was.cacheRead,
|
|
588
|
-
cacheWrite: u.cache_creation_input_tokens ?? was.cacheWrite,
|
|
589
|
-
output: u.output_tokens ?? was.output,
|
|
590
|
-
});
|
|
591
|
-
if (recordId !== null)
|
|
592
|
-
recordNow('its spend so far', records.updateStepSpend({ id: recordId, spend: spendNow(), model }));
|
|
593
|
-
};
|
|
594
|
-
const report = (spent) => {
|
|
595
|
-
const requests = running.size;
|
|
596
|
-
running.clear();
|
|
597
|
-
for (const [k, v] of Object.entries(spent))
|
|
598
|
-
settled[k] += v ?? 0;
|
|
599
|
-
if (spent.requests === undefined)
|
|
600
|
-
settled.requests += requests;
|
|
601
|
-
};
|
|
602
|
-
const toolInputs = [];
|
|
603
|
-
let before = null;
|
|
604
|
-
let recordId = null;
|
|
605
|
-
let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
|
|
606
|
-
// Its model, where it runs on one: its own, or what its workflows above or the app set (`settings.ts`), in code alone.
|
|
607
|
-
const model = step.runs === 'agentic' ? stepSetting({ declared: [...DECLARED.values()], app: deps.appSettings, stored: [] }, { workflow: instance.workflow._tag, step: step.name, name: 'model' }).value : null;
|
|
608
|
-
return Effect.acquireUseRelease(Effect.flatMap(Effect.gen(function* () {
|
|
609
|
-
yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
|
|
610
|
-
yield* checkItem(instance.workflow._tag, instance.executionId, step.name, subject);
|
|
611
|
-
// A sub-workflow step is run again when its workflow has ended: it takes its open record up again, and names the run it started.
|
|
612
|
-
const id = yield* recorded('open its record', records.openStepRun({ workflow: instance.workflow._tag, run: instance.executionId, step: step.name, call, agent: (step.runs === 'agentic'), subject, version: versionOf(instance.workflow._tag).version, ...(childRun === null ? {} : { resume: true }) }));
|
|
613
|
-
if (id !== null && childRun !== null)
|
|
614
|
-
yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
|
|
615
|
-
const beat = (step.runs === 'agentic') && id !== null ? setInterval(() => recordNow('its heartbeat', records.beatStepRun(id)), AGENT_BEAT_MS) : null;
|
|
616
|
-
recordId = id;
|
|
617
|
-
meter = new StepMeter(id, (step.runs === 'agentic'), step.writes ?? [], null);
|
|
618
|
-
meterOpened(meter);
|
|
619
|
-
return { id, beat };
|
|
620
|
-
}), (opened) => (mayWrite === undefined
|
|
621
|
-
? Effect.succeed(opened)
|
|
622
|
-
: Effect.map(Effect.promise(async () => {
|
|
623
|
-
const hashes = await stepFiles.treeHashes();
|
|
624
|
-
if (opened.id !== null)
|
|
625
|
-
await stepFiles.snapshotTree(stepFiles.snapshotOf(opened.id), hashes);
|
|
626
|
-
return hashes;
|
|
627
|
-
}), (hashes) => {
|
|
628
|
-
before = hashes;
|
|
629
|
-
return opened;
|
|
630
|
-
}))), () => pipe(
|
|
631
|
-
// An agent step with no model set on it or above it stands down before it takes an agent (`NO_MODEL_STOOD_DOWN`).
|
|
632
|
-
(step.runs === 'agentic') && model === null ? Effect.andThen(Effect.logError(`[settings] ${instance.workflow._tag}: its agent step ${step.name} has no model set on it or on any workflow above it: set one with \`model\``), Effect.fail(NO_MODEL_STOOD_DOWN))
|
|
633
|
-
: (step.runs === 'agentic') ? Effect.andThen(claimAgentsOrEnd(instance.workflow._tag, instance.executionId, step.name), Effect.andThen(beforeAgentCall(instance, step.name), execute)) : execute,
|
|
634
|
-
// What it changed, on its record, and a change it named outside where it may write refuses the step.
|
|
635
|
-
Effect.tap(() => Effect.suspend(() => {
|
|
636
|
-
const earlier = before;
|
|
637
|
-
if (earlier === null || mayWrite === undefined)
|
|
638
|
-
return Effect.void;
|
|
639
|
-
return Effect.flatMap(Effect.promise(() => stepFiles.treeHashes()), (after) => Effect.gen(function* () {
|
|
640
|
-
const files = filesChanged(earlier, after, mayWrite, toolInputs);
|
|
641
|
-
const snapshot = recordId === null ? null : stepFiles.snapshotOf(recordId);
|
|
642
|
-
if (snapshot !== null)
|
|
643
|
-
stepFiles.keepWhatItChanged(snapshot, files.attributed);
|
|
644
|
-
if (recordId !== null)
|
|
645
|
-
yield* recorded('the files it changed', records.recordStepFiles({ id: recordId, files: JSON.stringify({ ...files, snapshot }) }));
|
|
646
|
-
// Refused here means undone here: a change that stayed would make the refusal decorative.
|
|
647
|
-
if (snapshot !== null)
|
|
648
|
-
stepFiles.undoFiles(snapshot, files.refused);
|
|
649
|
-
return files.refused.length === 0 ? yield* Effect.void : yield* Effect.fail(`refused: it changed ${files.refused.join(', ')}, outside ${mayWrite.join(', ') || 'nothing it may write'}`);
|
|
650
|
-
}));
|
|
651
|
-
})), Effect.provideService(CurrentMeter, meter), Effect.provideService(deps.CurrentStepUsage, meter), (step.runs === 'agentic' && model !== null) ? Effect.provideService(AgentStep, { usage, report, model, touched: (inputs) => { toolInputs.push(...inputs); }, waiting: (why) => { if (recordId !== null)
|
|
652
|
-
recordNow('say what it waits on', records.setStepWaiting({ id: recordId, waiting: why })); } }) : (e) => e), ({ id, beat }, exit) => Effect.gen(function* () {
|
|
653
|
-
if (beat !== null)
|
|
654
|
-
clearInterval(beat);
|
|
655
|
-
// An interrupted step is no move: the run does it again.
|
|
656
|
-
if (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause))
|
|
657
|
-
lastStepRan.set(instance.executionId, { step: step.name, failed: !Exit.isSuccess(exit) });
|
|
658
|
-
meterClosed(meter);
|
|
659
|
-
if (id === null)
|
|
660
|
-
return;
|
|
661
|
-
const spend = spendNow();
|
|
662
|
-
const used = meter.used();
|
|
663
|
-
const named = Exit.isSuccess(exit) ? subjectOf?.(exit.value) ?? null : null;
|
|
664
|
-
yield* checkItem(instance.workflow._tag, instance.executionId, step.name, named);
|
|
665
|
-
// A batch that started no process and recorded no item had none to do; one that worked outside `eachItem` stays undeclared.
|
|
666
|
-
const idleBatch = step.perItem === true && Exit.isSuccess(exit) && used.childCpuSeconds === 0 && used.compiles === 0;
|
|
667
|
-
const scope = meter.items > 0 ? 'functions' : step.shared === true ? 'shared' : idleBatch ? 'none due' : subjectOf !== undefined && Exit.isSuccess(exit) && named === null ? 'nothing' : 'undeclared';
|
|
668
|
-
if (Exit.isSuccess(exit))
|
|
669
|
-
yield* recorded('close its record', records.closeStepRun({ id, outcome: 'success', reason: (reasonOf ?? standardReason)(exit.value), error: null, spend, subject: named, used, scope }));
|
|
670
|
-
// A sub-workflow step whose run is suspended until its workflow ends is still in that step: its record stays open.
|
|
671
|
-
else if (Cause.hasInterrupts(exit.cause) && childRun !== null && instance.suspended)
|
|
672
|
-
yield* Effect.void;
|
|
673
|
-
else if (Cause.hasInterrupts(exit.cause))
|
|
674
|
-
yield* recorded('close its record', records.closeStepRun({ id, outcome: 'interrupted', reason: 'interrupted', error: null, spend, subject: null, used, scope }));
|
|
675
|
-
else
|
|
676
|
-
yield* recorded('close its record', records.closeStepRun({ id, outcome: 'failure', reason: oneLine(describeFailure(Cause.squash(exit.cause))), error: describeFailure(Cause.squash(exit.cause)), spend, subject: null, used, scope }));
|
|
677
|
-
}));
|
|
678
|
-
});
|
|
679
|
-
/**
|
|
680
|
-
* TAKES BACK WHAT THIS RUN'S AGENT STEP CHANGED, from that step's record: the one way a refused change leaves the tree. Run
|
|
681
|
-
* it as a step of its own, then rebuild, or the tree still holds what was refused.
|
|
682
|
-
*/
|
|
683
|
-
const undoAgentStep = (stepName) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => Effect.map(records.stepFilesOf({ run: instance.executionId, step: stepName }), (record) => {
|
|
684
|
-
if (record === null)
|
|
685
|
-
return { restored: [], conflicts: [] };
|
|
686
|
-
const { snapshot, attributed } = JSON.parse(record);
|
|
687
|
-
return snapshot === null ? { restored: [], conflicts: [] } : stepFiles.undoFiles(snapshot, attributed ?? []);
|
|
688
|
-
}));
|
|
689
|
-
/**
|
|
690
|
-
* A RUN PAST ITS WORKFLOW'S RUN LIMIT ENDS BEFORE IT TAKES ON MORE WORK, inside the step's activity. It fails with
|
|
691
|
-
* `STOOD_DOWN`. At a run limit of 0 every run is past it, so each run already going ends this way.
|
|
692
|
-
*
|
|
693
|
-
* A workflow its budget keeps going before an agent step, and nowhere else: a run past its limit still picks and
|
|
694
|
-
* (`keptRunningByItsBudget`) tests with no agent, so an item its test clears is finished at no cost, and its
|
|
695
|
-
* Pick ends its run where it finds nothing (`untilPicked`).
|
|
696
|
-
* Any other workflow before a Pick, before an agent step, and before the first step this process runs
|
|
697
|
-
* of it (a run the engine resumed after a restart): nothing else would end its run.
|
|
698
|
-
*
|
|
699
|
-
* A step between those goes on, so what an agent step just made is still checked and recorded.
|
|
700
|
-
*/
|
|
701
|
-
const standDownIfSurplus = (step) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) =>
|
|
702
|
-
// A run a sub-workflow step started is its top run's work: its steps stand down as that run's own would, by that
|
|
703
|
-
// workflow's budget. Asked of its own, a step with no agent stood the run above down where that run's own never would.
|
|
704
|
-
Effect.flatMap(Effect.orElseSucceed(topOf(instance.workflow._tag, instance.executionId), () => ({ run: instance.executionId, workflow: instance.workflow._tag })), (top) => Effect.flatMap(
|
|
705
|
-
// IT ENDS WITH THE RUN ABOVE IT. Once that run has ended (failed, or stopped), no step of this one starts: its result
|
|
706
|
-
// would be read by nothing. A read of the engine's records that fails stops no step.
|
|
707
|
-
top.run === instance.executionId ? Effect.succeed(false) : Effect.orElseSucceed(Effect.map(runsOldestFirst([top.workflow]), (unfinished) => !unfinished.includes(top.run)), () => false), (aboveEnded) => {
|
|
708
|
-
if (aboveEnded) {
|
|
709
|
-
console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: the ${top.workflow} run above it, ${top.run}, has ended`);
|
|
710
|
-
return Effect.fail(ABOVE_ENDED);
|
|
711
|
-
}
|
|
712
|
-
const declared = DECLARED.get(top.workflow);
|
|
713
|
-
const budgetKeepsIt = declared !== undefined && keptRunningByItsBudget(declared);
|
|
714
|
-
if (!step.agent && (budgetKeepsIt || (!step.picks && lastStepRan.has(instance.executionId))))
|
|
715
|
-
return Effect.void;
|
|
716
|
-
return Effect.flatMap(AgentBudgets, (budgets) => Effect.flatMap(budgets.standsDown(instance.workflow._tag, instance.executionId), (surplus) => {
|
|
717
|
-
if (!surplus)
|
|
718
|
-
return Effect.void;
|
|
719
|
-
console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: its workflow has more runs going than its run limit`);
|
|
720
|
-
return Effect.fail(STOOD_DOWN);
|
|
721
|
-
}));
|
|
722
|
-
})));
|
|
723
|
-
/**
|
|
724
|
-
* A RUN STARTS NO STEP IN A PROCESS HANDING ITS RUNS TO THE NEXT (`pick-wakes.ts` `releaseWaiting`): it suspends on a
|
|
725
|
-
* durable clock, which the process that takes its shard next delivers, and that process replays it from its records and
|
|
726
|
-
* runs the step. A step already running finishes where it is, an agent's call included. Left to the engine, the run was
|
|
727
|
-
* abandoned without a reply, and the wake its sub-workflow step's workflow had sent it waited on that reply for ever: the
|
|
728
|
-
* run's entity, and its shard, stayed in the old process until it was killed. Four runs of Decompile sat between steps so
|
|
729
|
-
* for 13 minutes after the reload at 22:10 UTC on 2026-11-21 (`handover.test.ts`). The clock's name is this process's, so
|
|
730
|
-
* a later handover at the same step suspends the run again. What it gives keeps the activity's name, which a workflow's
|
|
731
|
-
* graph may name the step by.
|
|
732
|
-
*/
|
|
733
|
-
const handedOverBeforeStep = (activity) => Object.assign(Effect.andThen(Effect.suspend(() => {
|
|
734
|
-
if (!deps.wakes.handingOver())
|
|
735
|
-
return Effect.void;
|
|
736
|
-
const self = deps.thisProcess();
|
|
737
|
-
return Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => Effect.andThen(Effect.sync(() => console.log(`[handover] ${instance.workflow._tag} run ${instance.executionId} suspended before ${activity.name}: the next process runs it`)), DurableClock.sleep({ name: `handed over by pid ${self.pid} started at ${self.startedAt}, before ${activity.name}`, duration: Duration.seconds(1), inMemoryThreshold: Duration.zero })));
|
|
738
|
-
}), activity), { name: activity.name });
|
|
739
|
-
/** One run of a workflow picks at a time: its choice is on its step record before the next reads what is taken. */
|
|
740
|
-
const pickingOneAtATime = (workflow, pick) => {
|
|
741
|
-
const lock = PICKING.get(workflow) ?? Semaphore.makeUnsafe(1);
|
|
742
|
-
PICKING.set(workflow, lock);
|
|
743
|
-
return lock.withPermits(1)(pick);
|
|
744
|
-
};
|
|
745
|
-
/** Why a Pick waits, on its open record: its queued tasks, none of which it can claim now, and what wakes it. */
|
|
746
|
-
const nothingToClaim = (workflow) => pipe(deps.tasks.taskSummaries({ workflow }), Effect.map((tasks) => {
|
|
747
|
-
const queued = queueOrder(tasks);
|
|
748
|
-
const needAnAgent = queued.filter((t) => deps.tasks.passedOverNow(t) !== null).length;
|
|
749
|
-
return `${queued.length} queued${queued.length === 0 ? '' : ', none it can claim now'}${needAnAgent === 0 ? '' : `, ${needAnAgent} of them passed over as needing an agent or with nothing new since their last run`}`;
|
|
750
|
-
}), Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)), Effect.map((queued) => `no task it can claim (${queued}); it waits for a task returned to its queue, a new item, an agent claim ending, a run ending or a limit change`));
|
|
751
|
-
/**
|
|
752
|
-
* A PICK THAT FINDS NOTHING IT CAN CLAIM WAITS FOR AN EVENT THAT CAN CHANGE THAT (`pick-wakes.ts`), and never polls: one
|
|
753
|
-
* open record, its `waiting` saying on what, and no new record while nothing changes. The run keeps its place in its
|
|
754
|
-
* workflow's count, and its record starts again when it found an item, since the wait was no work. It ends with nothing
|
|
755
|
-
* when its run is past the runs its run limit keeps (`runLimit`), or when no agent can be had and nothing in its queue
|
|
756
|
-
* can be taken without one (`whyNoRunCanTakeWork`): kept waiting there, 4 Decompile runs held their run slots for 51
|
|
757
|
-
* minutes on 2026-11-20 with each of its 751 queued tasks marked, and showed as running.
|
|
758
|
-
*/
|
|
759
|
-
const untilPicked = (picked, pick) => Effect.gen(function* () {
|
|
760
|
-
const instance = yield* WorkflowEngine.WorkflowInstance;
|
|
761
|
-
const workflow = instance.workflow._tag;
|
|
762
|
-
const budgets = yield* AgentBudgets;
|
|
763
|
-
const meter = yield* CurrentMeter;
|
|
764
|
-
const record = meter?.record ?? null;
|
|
765
|
-
let waited = false;
|
|
766
|
-
for (;;) {
|
|
767
|
-
const wakes = deps.wakes.pickWakesSoFar(workflow);
|
|
768
|
-
const began = performance.now();
|
|
769
|
-
const found = yield* pickingOneAtATime(workflow, pick);
|
|
770
|
-
if (waited)
|
|
771
|
-
deps.wakes.countRePick(workflow, performance.now() - began);
|
|
772
|
-
// With no agent to be had and nothing it can take, it ends rather than wait (`whyNoRunCanTakeWork`).
|
|
773
|
-
const noWork = picked(found) ? null : yield* noWorkByInputsLastRead(workflow);
|
|
774
|
-
if (noWork !== null)
|
|
775
|
-
console.log(`[agents] ${workflow} run ${instance.executionId} ended at its Pick: ${noWork}`);
|
|
776
|
-
if (picked(found) || noWork !== null || !(yield* budgets.waitsForWork(workflow, instance.executionId))) {
|
|
777
|
-
if (picked(found))
|
|
778
|
-
deps.queueChanged(workflow);
|
|
779
|
-
if (waited && record !== null) {
|
|
780
|
-
yield* recorded('end its wait', records.setStepWaiting({ id: record, waiting: null }));
|
|
781
|
-
yield* recorded('start its record again', records.restartStepRun(record));
|
|
782
|
-
}
|
|
783
|
-
return found;
|
|
784
|
-
}
|
|
785
|
-
if (record !== null)
|
|
786
|
-
yield* recorded('say what it waits on', records.setStepWaiting({ id: record, waiting: yield* nothingToClaim(workflow) }));
|
|
787
|
-
waited = true;
|
|
788
|
-
if ((yield* deps.wakes.untilPickWoken({ workflow, after: wakes })) === 'released')
|
|
789
|
-
return yield* Effect.fail(HANDED_OVER);
|
|
790
|
-
}
|
|
791
|
-
});
|
|
792
|
-
/** A step: its declaration, and `run`, the only way to run it. */
|
|
793
|
-
const defineStep = (d) => {
|
|
794
|
-
if (d.model !== undefined && d.runs !== 'agentic')
|
|
795
|
-
throw new Error(`${d.name} sets a model, and runs ${d.runs}: only an agent step runs on a model`);
|
|
796
|
-
const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
|
|
797
|
-
const declaration = {
|
|
798
|
-
name: d.name, runs: d.runs, description: d.description, ...(d.kind === undefined ? {} : { kind: d.kind }), ...(d.test === undefined ? {} : { test: true }), ...(d.shared === undefined ? {} : { shared: true }), ...(d.perItem === undefined ? {} : { perItem: true }), ...(d.picked === undefined ? {} : { picks: true }), ...(d.subject === undefined ? {} : { namesItem: true }),
|
|
799
|
-
...(writes.length === 0 ? {} : { writes }),
|
|
800
|
-
...checkedSettings({ what: d.name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
|
|
801
|
-
source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
|
|
802
|
-
};
|
|
803
|
-
const step = {
|
|
804
|
-
...declaration,
|
|
805
|
-
run: (execute, options) => handedOverBeforeStep(Activity.make({
|
|
806
|
-
name: options?.call === undefined ? d.name : `${d.name} ${options.call}`,
|
|
807
|
-
success: d.success,
|
|
808
|
-
error: Schema.String,
|
|
809
|
-
execute: pipe(standDownIfSurplus({ agent: d.runs === 'agentic', picks: d.picked !== undefined }), Effect.andThen(measured(declaration, options?.call ?? null, options?.subject ?? null, d.subject, d.reason, d.mayWrite, d.picked === undefined ? execute : untilPicked(d.picked, execute))), Effect.retry({ while: deps.isTransientFailure, times: 10, schedule: Schedule.spaced('3 seconds') }), Effect.mapError(describeFailure)),
|
|
810
|
-
})),
|
|
811
|
-
};
|
|
812
|
-
// Its code as loaded now, for its workflow's version (`versionOf`): its file, and an agent step's prompt file.
|
|
813
|
-
STEP_CODE.set(step, [codeOf(d.at), ...(d.prompt === undefined ? [] : [codeOf(path.join(deps.sourceRoot, d.prompt.path))])]);
|
|
814
|
-
return step;
|
|
815
|
-
};
|
|
816
|
-
/**
|
|
817
|
-
* "CLEARED" MEANS OFF THE LIST, by construction: a pass counts only if the list the workflow shows and Pick takes from no
|
|
818
|
-
* longer holds the item. One still on it is a fault, recorded and named, and its agent starts, told so.
|
|
819
|
-
*/
|
|
820
|
-
const heldToItsList = (test, subject) => Effect.gen(function* () {
|
|
821
|
-
const said = yield* test;
|
|
822
|
-
if (said.result !== 'passes')
|
|
823
|
-
return said;
|
|
824
|
-
const instance = yield* WorkflowEngine.WorkflowInstance;
|
|
825
|
-
const workflow = instance.workflow._tag;
|
|
826
|
-
const item = subject ?? (yield* recorded('read its item', records.subjectOfRun(instance.executionId)));
|
|
827
|
-
const pending = DECLARED.get(workflow)?.pending;
|
|
828
|
-
if (item === null || pending === undefined)
|
|
829
|
-
return said;
|
|
830
|
-
// Only a workflow with a list comes here, and those run under what its list reads.
|
|
831
|
-
const work = yield* Effect.exit(pending());
|
|
832
|
-
if (!Exit.isSuccess(work) || !listOf(work.value).some((i) => i.toLowerCase() === item.toLowerCase()))
|
|
833
|
-
return said;
|
|
834
|
-
yield* recorded('a pass its list still holds', records.recordClearedButListed({ workflow, run: instance.executionId, item, said: said.detail }));
|
|
835
|
-
return { result: 'cannot', why: `its test passed (${said.detail}), and it is still on this workflow's list, so it has not cleared` };
|
|
836
|
-
});
|
|
837
|
-
/** The no-agent test step of a workflow, before its first agent step. */
|
|
838
|
-
const defineItemTest = (d) => {
|
|
839
|
-
const step = defineStep({ name: 'Test', runs: 'deterministic', test: true, description: d.description, at: d.at, prompt: { path: sourcePath(d.at), anchor: 'defineItemTest(' }, success: ItemTest });
|
|
840
|
-
return { ...step, run: (test, options) => step.run(heldToItsList(test, options?.subject ?? null), options) };
|
|
841
|
-
};
|
|
842
|
-
/** The sub-workflows whose agent steps are being asked for now: a workflow that used itself as a step would ask for ever. */
|
|
843
|
-
const askingForAgents = new Set();
|
|
844
|
-
/**
|
|
845
|
-
* A SUB-WORKFLOW STEP: a workflow used as a step of another. Alex, 2026-11-19: "decompile is itself a workflow composed of
|
|
846
|
-
* other workflows. the long term goal of Jive is to be workflows all the way down".
|
|
847
|
-
*
|
|
848
|
-
* Running it starts `workflow` as a run of its own on `payload` and waits for it: the engine suspends the run above until
|
|
849
|
-
* it ends, across restarts, and then runs this step again, which reads the result. The step keeps ONE record in the
|
|
850
|
-
* workflow above, open while its workflow runs and naming that run, so:
|
|
851
|
-
*
|
|
852
|
-
* the page shows the run above in this step, and the workflow's own view shows its steps and what they cost;
|
|
853
|
-
* the workflow's steps work on the item the run above works on, with no code naming it (`StepRecords.openStepRun`);
|
|
854
|
-
* its agent claim counts against the agents' limit of the workflow at the top, and its steps stand down with its run (`topOf`).
|
|
855
|
-
*
|
|
856
|
-
* Its start is the step's, so no run limit of its own gates it: the run above is the one a limit lets start or not, and a
|
|
857
|
-
* limit on a workflow used only as a step would fail the steps of runs already going.
|
|
858
|
-
*/
|
|
859
|
-
const defineSubWorkflow = (d) => {
|
|
860
|
-
const child = d.workflow._tag;
|
|
861
|
-
refuseSystem(child, 'no workflow of the app has it as a step');
|
|
862
|
-
// What its workflow gave is what the step declares, or the step fails saying so: no result is taken on trust.
|
|
863
|
-
const isDeclared = Schema.is(d.success);
|
|
864
|
-
const given = (result) => (isDeclared(result) ? Effect.succeed(result) : Effect.fail(`${child} gave a result that is not what this step declares`));
|
|
865
|
-
const name = d.as ?? child;
|
|
866
|
-
const startAsAStep = (payload) => (STARTS_AS_A_STEP.get(child) ?? d.workflow.execute)(payload);
|
|
867
|
-
/**
|
|
868
|
-
* ITS WORKFLOW STARTED, AND WAITED FOR. In a process handing its runs to the next, the wait is cut: its workflow's run
|
|
869
|
-
* has gone to the next process, which this one's engine can no longer reach, so the call is interrupted. Left to the
|
|
870
|
-
* engine's activity, that interrupt was tried again 10 times and then failed the run above, while its workflow went on
|
|
871
|
-
* in the next process with a result nothing would read: two runs of Decompile ended so on 2026-11-19, their agents
|
|
872
|
-
* still writing. The run above is suspended instead, as it is whenever its workflow has not ended: the next process
|
|
873
|
-
* resumes it when that workflow ends, this step runs again there and reads the result, and its record stays the one.
|
|
874
|
-
*/
|
|
875
|
-
const startedAndWaitedFor = (payload) => pipe(startAsAStep(payload), Effect.sandbox, Effect.catch((cause) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => (Cause.hasInterruptsOnly(cause) && !instance.suspended && deps.wakes.handingOver() ? Workflow.suspend(instance) : Effect.failCause(cause)))));
|
|
876
|
-
const declaration = {
|
|
877
|
-
name, runs: null, kind: 'sub-workflow', workflow: child,
|
|
878
|
-
...(d.agentKeptUntilThisRunEnds === true ? { agentKeptUntilThisRunEnds: true } : {}),
|
|
879
|
-
...checkedSettings({ what: name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
|
|
880
|
-
description: DECLARED.get(child)?.description ?? `Runs ${child}.`,
|
|
881
|
-
source: DECLARED.get(child)?.source ?? { path: sourcePath(d.at), anchor: `'${child}'` },
|
|
882
|
-
agentUnder: () => {
|
|
883
|
-
if (askingForAgents.has(child))
|
|
884
|
-
return false;
|
|
885
|
-
askingForAgents.add(child);
|
|
886
|
-
try {
|
|
887
|
-
return DECLARED.get(child)?.steps().some(stepUsesAnAgent) === true;
|
|
888
|
-
}
|
|
889
|
-
finally {
|
|
890
|
-
askingForAgents.delete(child);
|
|
891
|
-
}
|
|
892
|
-
},
|
|
893
|
-
};
|
|
894
|
-
return {
|
|
895
|
-
...declaration,
|
|
896
|
-
run: (payload, options) => handedOverBeforeStep(Activity.make({
|
|
897
|
-
name: options?.call === undefined ? name : `${name} ${options.call}`,
|
|
898
|
-
success: d.success,
|
|
899
|
-
error: Schema.String,
|
|
900
|
-
execute: pipe(standDownIfSurplus({ agent: false, picks: false }), Effect.andThen(Effect.flatMap(d.workflow.executionId(payload), (childRun) => measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(startedAndWaitedFor(payload), given), childRun))), Effect.mapError(describeFailure)),
|
|
901
|
-
})),
|
|
902
|
-
};
|
|
903
|
-
};
|
|
904
|
-
/**
|
|
905
|
-
* A STEP THAT IS ANOTHER WORKFLOW, ON ITS OWN TRIGGER. Alex, 2026-11-21: "just one fucking workflow that has steps some
|
|
906
|
-
* of which can be other workflows". A workflow whose steps are workflows that start themselves (on their queues, their
|
|
907
|
-
* inputs, a timer) holds them as any workflow holds its steps: the project's top, and each part of it, is one. No run of
|
|
908
|
-
* it starts them, so it has no runs of its own: its runs, agents and costs are theirs, added up (`isMadeOfWorkflows`).
|
|
909
|
-
* Define `workflow` before the workflow that has it as a step.
|
|
910
|
-
*/
|
|
911
|
-
const defineWorkflowStep = (workflow) => {
|
|
912
|
-
refuseSystem(workflow, 'no workflow of the app has it as a step');
|
|
913
|
-
const d = DECLARED.get(workflow);
|
|
914
|
-
if (d === undefined)
|
|
915
|
-
throw new Error(`${workflow} is a step of a workflow defined before it: define ${workflow} first`);
|
|
916
|
-
return { name: workflow, runs: null, kind: 'sub-workflow', workflow, runsOnItsOwnTrigger: true, description: d.description, source: d.source, agentUnder: () => d.steps().some(stepUsesAnAgent) };
|
|
917
|
-
};
|
|
918
|
-
/** A workflow and every workflow under it, through each step that is a workflow. */
|
|
919
|
-
const withWorkflowsUnder = (name, seen = new Set()) => {
|
|
920
|
-
if (seen.has(name))
|
|
921
|
-
return seen;
|
|
922
|
-
seen.add(name);
|
|
923
|
-
for (const s of DECLARED.get(name)?.steps() ?? [])
|
|
924
|
-
if (s.workflow !== undefined)
|
|
925
|
-
withWorkflowsUnder(s.workflow, seen);
|
|
926
|
-
return seen;
|
|
927
|
-
};
|
|
928
|
-
/**
|
|
929
|
-
* THE STEP GRAPH OF A WORKFLOW MADE OF WORKFLOWS, from what feeds what (`WorkflowDeclaration.fedBy`): a step follows each
|
|
930
|
-
* of its fellow steps whose results become its tasks, at any depth under each; one none of them feeds is where work
|
|
931
|
-
* enters it, and one that feeds none of them is where its work leaves. The feeds are declared once, on the workflow fed.
|
|
932
|
-
*/
|
|
933
|
-
const graphOfFeeds = (steps) => {
|
|
934
|
-
const under = new Map(steps.map((s) => [s, withWorkflowsUnder(s)]));
|
|
935
|
-
const feeds = (from, to) => from !== to && [...under.get(to)].some((w) => (DECLARED.get(w)?.fedBy ?? []).some((f) => under.get(from).has(f)));
|
|
936
|
-
const edges = steps.flatMap((to) => steps.filter((from) => feeds(from, to)).map((from) => ({ from, to, when: `its results become ${to}'s tasks` })));
|
|
937
|
-
return [
|
|
938
|
-
...steps.filter((s) => !edges.some((e) => e.to === s)).map((s) => ({ from: RUN_STARTS, to: s, when: 'on its own trigger' })),
|
|
939
|
-
...edges,
|
|
940
|
-
...steps.filter((s) => !edges.some((e) => e.from === s)).map((s) => ({ from: s, to: RUN_ENDS, when: 'what it finishes leaves here' })),
|
|
941
|
-
];
|
|
942
|
-
};
|
|
943
|
-
/** Every workflow defined so far, in the order defined. */
|
|
944
|
-
const declaredWorkflows = () => [...DECLARED.values()];
|
|
945
|
-
/** Calls `listener` shortly after any run ends, when the engine has stored its end. */
|
|
946
|
-
const onRunEnded = (listener) => {
|
|
947
|
-
RUN_ENDED.add(listener);
|
|
948
|
-
};
|
|
949
|
-
const runEnded = () => {
|
|
950
|
-
for (const after of [1000, 5000]) {
|
|
951
|
-
for (const listener of RUN_ENDED)
|
|
952
|
-
setTimeout(listener, after);
|
|
953
|
-
}
|
|
954
|
-
};
|
|
955
|
-
/** A workflow's tasks' inputs now (`WorkflowDeclaration.taskInputs`), recorded for every summary of its tasks; none for one that declares none. */
|
|
956
|
-
const readTaskInputs = (workflow) => Effect.gen(function* () {
|
|
957
|
-
const d = DECLARED.get(workflow);
|
|
958
|
-
if (d?.taskInputs === undefined)
|
|
959
|
-
return null;
|
|
960
|
-
const read = yield* d.taskInputs();
|
|
961
|
-
const byItem = new Map([...read].map(([item, inputs]) => [item.toLowerCase(), inputs]));
|
|
962
|
-
deps.tasks.recordTaskInputs(workflow, byItem);
|
|
963
|
-
return byItem;
|
|
964
|
-
});
|
|
965
|
-
/** The step a Pick's notes are written by: every Pick is the step that reads its queue. */
|
|
966
|
-
const pickedBy = (input) => ({ workflow: input.workflow, run: input.run, step: 'Pick' });
|
|
967
|
-
/**
|
|
968
|
-
* A WORKFLOW'S QUEUE AS ITS PICK TAKES IT: first in, first out (`tasks.ts` `queueOrder`), another run's tasks left out.
|
|
969
|
-
* The Pick first reads what its tasks run on and settles its queue (`tasks.ts` `settleQueue`): a task a standard reason
|
|
970
|
-
* holds for is blocked, and a blocked one whose reason lapsed is back in the queue.
|
|
971
|
-
*/
|
|
972
|
-
const queueNow = (input) => Effect.gen(function* () {
|
|
973
|
-
yield* readTaskInputs(input.workflow);
|
|
974
|
-
const queue = queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
|
|
975
|
-
// While no agent is free, a task marked as needing one is passed over (`whyNoAgentIsFree`).
|
|
976
|
-
return (yield* whyNoAgentIsFree(input.workflow)) === null ? queue : queue.filter((t) => deps.tasks.passedOverNow(t) === null);
|
|
977
|
-
});
|
|
978
|
-
/**
|
|
979
|
-
* WHY NO RUN OF A WORKFLOW CAN TAKE WORK NOW, none where one can: no agent can be had for it (`agentsUnavailable`), and
|
|
980
|
-
* every task in its queue is one its Pick passes over meanwhile, marked as needing an agent or with nothing new since its
|
|
981
|
-
* last run (`tasks.ts` `passedOverWithoutAnAgent`), or its queue is empty. Then a run would only hold a run slot and show
|
|
982
|
-
* as running: its trigger starts none (`keep-running.ts` `planRunStarts`), and a Pick that found nothing ends its run
|
|
983
|
-
* rather than wait (`untilPicked`). An agent to be had (a limit lifted, the spending limit no longer holding), a mark
|
|
984
|
-
* cleared, new input or a new item lets runs start again. Only a workflow with a list and an agent step: one with no agent
|
|
985
|
-
* step needs none. Read where it cannot be, it says nothing, and runs start and wait as before. Every agent merely in use
|
|
986
|
-
* is not this: one frees when a run holding one ends, so runs start and do their work with no agent, a run that reaches
|
|
987
|
-
* its agent step with none free gives its task back, and a Pick with nothing it can take waits for a claim to end.
|
|
988
|
-
*/
|
|
989
|
-
const whyNoRunCanTakeWork = (workflow) => Effect.gen(function* () {
|
|
990
|
-
// Its tasks' inputs, a read of every task's, are read again only where the inputs its last Pick read leave no work.
|
|
991
|
-
if ((yield* noWorkByInputsLastRead(workflow)) === null)
|
|
992
|
-
return null;
|
|
993
|
-
yield* Effect.orElseSucceed(readTaskInputs(workflow), () => null);
|
|
994
|
-
return yield* noWorkByInputsLastRead(workflow);
|
|
995
|
-
});
|
|
996
|
-
/** `whyNoRunCanTakeWork` by its tasks' inputs as its last Pick read them: what a Pick that just read them asks. */
|
|
997
|
-
const noWorkByInputsLastRead = (workflow) => pipe(Effect.gen(function* () {
|
|
998
|
-
const d = DECLARED.get(workflow);
|
|
999
|
-
if (d === undefined || !keptRunningByItsBudget(d))
|
|
1000
|
-
return null;
|
|
1001
|
-
const unavailable = yield* agentsUnavailable(workflow);
|
|
1002
|
-
if (unavailable === null)
|
|
1003
|
-
return null;
|
|
1004
|
-
const queued = queueOrder(yield* deps.tasks.taskSummaries({ workflow }));
|
|
1005
|
-
if (queued.some((t) => deps.tasks.passedOverNow(t) === null))
|
|
1006
|
-
return null;
|
|
1007
|
-
return `no agent can be had (${unavailable}), and ${queued.length === 0 ? 'its queue is empty' : `each of its ${queued.length} queued tasks needs one or has nothing new since its last run`}`;
|
|
1008
|
-
}), Effect.orElseSucceed(() => null));
|
|
1009
|
-
/**
|
|
1010
|
-
* A workflow: what it states about itself, then `Workflow.make`'s own name and options. `system` is the platform defining
|
|
1011
|
-
* one of its own (`system-workflows.ts`); an app's definition of one of those names is refused (`refuseSystem`).
|
|
1012
|
-
*/
|
|
1013
|
-
const defineWorkflowAs = (system) => (d) => ((name, options) => {
|
|
1014
|
-
if (!system)
|
|
1015
|
-
refuseSystem(name, 'the app defines no workflow of its name');
|
|
1016
|
-
if (d.agentsClaimed !== undefined && !(Number.isInteger(d.agentsClaimed) && d.agentsClaimed >= 1))
|
|
1017
|
-
throw new Error(`${name} claims ${d.agentsClaimed} agents: a workflow claims a whole number of them, 1 or more, or states none`);
|
|
1018
|
-
// A main step is one of a workflow made of workflows, whose steps (`defineWorkflowStep`) are defined before it, so read now.
|
|
1019
|
-
if (d.mainStep !== undefined && !(isMadeOfWorkflows(d) && d.steps().some((s) => s.name === d.mainStep)))
|
|
1020
|
-
throw new Error(`${name}'s main step ${d.mainStep} is not one of its steps, each a workflow on its own trigger`);
|
|
1021
|
-
// The one place a workflow's own types do not matter: every workflow passes through here the same way.
|
|
1022
|
-
const workflow = Workflow.make(name, options);
|
|
1023
|
-
/**
|
|
1024
|
-
* EVERY START OF IT, WHATEVER CALLS IT (a timer, its inputs changing, its queue, a request), PASSES ITS RUN LIMIT: a new
|
|
1025
|
-
* run starts only while fewer of its runs are going than its limit. One already going, by the same execution id, is
|
|
1026
|
-
* joined as before. A start refused for the limit starts nothing: one that discards its run gets its id back, one that
|
|
1027
|
-
* waits for its result fails with `RunLimitReached`. Where the limit cannot be read, the run starts, and that is said.
|
|
1028
|
-
*/
|
|
1029
|
-
const execute = workflow.execute.bind(workflow);
|
|
1030
|
-
let refusedSaidAt = 0;
|
|
1031
|
-
const startAllowed = (payload) => Effect.gen(function* () {
|
|
1032
|
-
const limits = yield* deps.budgets.limitsOf(name);
|
|
1033
|
-
const limit = limits === null ? null : runLimitOf(d, limits);
|
|
1034
|
-
if (limit === null)
|
|
1035
|
-
return { allowed: true };
|
|
1036
|
-
const going = (yield* deps.engine.unfinishedRuns()).filter((u) => u.workflow === name).map((u) => u.run);
|
|
1037
|
-
if (going.length < limit)
|
|
1038
|
-
return { allowed: true };
|
|
1039
|
-
const id = yield* workflow.executionId(payload);
|
|
1040
|
-
return going.includes(id) ? { allowed: true } : { allowed: false, limit };
|
|
1041
|
-
}).pipe(Effect.catchTag('StorageError', (e) => Effect.as(Effect.logError(`[run limit] ${name}: its limit could not be read, so the run starts: ${e.reason}`), { allowed: true })));
|
|
1042
|
-
const gatedExecute = (payload, startOptions) => Effect.flatMap(startAllowed(payload), (gate) => {
|
|
1043
|
-
if (gate.allowed)
|
|
1044
|
-
return startOptions === undefined ? execute(payload) : execute(payload, startOptions);
|
|
1045
|
-
const say = Date.now() - refusedSaidAt < REFUSED_SAID_EVERY_MS ? Effect.void : Effect.sync(() => { refusedSaidAt = Date.now(); console.log(`[run limit] ${name}: not started, its run limit of ${gate.limit} is reached`); });
|
|
1046
|
-
return Effect.andThen(say, startOptions?.discard === true ? workflow.executionId(payload) : Effect.fail(new RunLimitReached({ workflow: name, limit: gate.limit })));
|
|
1047
|
-
});
|
|
1048
|
-
WORKFLOW_CODE.set(name, codeOf(d.at));
|
|
1049
|
-
DECLARED.set(name, {
|
|
1050
|
-
name, description: d.description, steps: d.steps,
|
|
1051
|
-
...(d.graph === undefined ? {} : { graph: d.graph }),
|
|
1052
|
-
source: { path: sourcePath(d.at), anchor: `'${name}'` },
|
|
1053
|
-
...(d.pending === undefined ? {} : { pending: d.pending }),
|
|
1054
|
-
...(d.items === undefined ? {} : { items: d.items }),
|
|
1055
|
-
...(d.picksQueueHead === undefined ? {} : { picksQueueHead: d.picksQueueHead }),
|
|
1056
|
-
...(d.fedBy === undefined ? {} : { fedBy: d.fedBy }),
|
|
1057
|
-
...(d.mainStep === undefined ? {} : { mainStep: d.mainStep }),
|
|
1058
|
-
...(d.inputs === undefined ? {} : { inputs: d.inputs }),
|
|
1059
|
-
...(d.taskInputs === undefined ? {} : { taskInputs: d.taskInputs }),
|
|
1060
|
-
...checkedSettings({ what: name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
|
|
1061
|
-
item: d.item,
|
|
1062
|
-
finishedWord: d.item === null ? null : d.finishedWord,
|
|
1063
|
-
gate: d.item === null ? null : (d.gate ?? null),
|
|
1064
|
-
start: (run) => gatedExecute({ run }, { discard: true }),
|
|
1065
|
-
startOn: (payload, options) => Effect.asVoid(options.wait ? gatedExecute(payload) : gatedExecute(payload, { discard: true })),
|
|
1066
|
-
executionIdOf: (payload) => workflow.executionId(payload),
|
|
1067
|
-
...(system ? { system: true } : {}),
|
|
1068
|
-
...(d.agentsClaimed === undefined ? {} : { agentsClaimed: d.agentsClaimed }),
|
|
1069
|
-
});
|
|
1070
|
-
if (system)
|
|
1071
|
-
SYSTEM.add(name);
|
|
1072
|
-
const toLayer = workflow.toLayer.bind(workflow);
|
|
1073
|
-
// Its start as a step of another workflow, which no run limit of its own gates (`defineSubWorkflow`).
|
|
1074
|
-
STARTS_AS_A_STEP.set(name, execute);
|
|
1075
|
-
Object.assign(workflow, { execute: gatedExecute });
|
|
1076
|
-
// Read when a run starts or ends, once every workflow is declared: whether this one's tasks are its runs.
|
|
1077
|
-
const runsAreTasks = () => { const me = DECLARED.get(name); return me !== undefined && tasksAreRuns(me, [...DECLARED.values()]); };
|
|
1078
|
-
// A run claims at its first agent step (`measured`); one with no agent step of its own that declares agents claims as it starts.
|
|
1079
|
-
const claimsAsItStarts = () => { const me = DECLARED.get(name); return me !== undefined && agentsClaimedBy(me) > 0 && !me.steps().some((s) => s.runs === 'agentic'); };
|
|
1080
|
-
// Every run of every workflow ends here: its items' outcomes are recorded, and the next run can start at once. A
|
|
1081
|
-
// workflow whose tasks are its runs gets its run's task as the run starts, and its outcome as it ends. A run of one
|
|
1082
|
-
// that claims agents takes its claim at its first agent step, or here where it has none, and ends it as it ends
|
|
1083
|
-
// (`claimAgentsOrEnd`, `endClaims`).
|
|
1084
|
-
return Object.assign(workflow, {
|
|
1085
|
-
toLayer: (execute) => toLayer((payload, executionId) => Effect.andThen(runsAreTasks() ? Effect.tap(deps.tasks.runStarted({ workflow: name, run: executionId }), () => Effect.sync(() => deps.queueChanged(name))) : Effect.void, Effect.onExit(Effect.andThen(claimsAsItStarts() ? claimAgentsOrEnd(name, executionId, name) : Effect.void, Effect.suspend(() => execute(payload, executionId))), (exit) => Effect.flatMap(
|
|
1086
|
-
// ITS TASK'S INPUTS AS THE RUN LEFT THEM go on its outcome: a run that changed what it ran on (a Test's trials)
|
|
1087
|
-
// left nothing new for the next. Taken when it picked, 490 Tests ran on 107 functions in 41 minutes (2026-11-14).
|
|
1088
|
-
!Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause) || d.item === null ? Effect.succeed(null) : Effect.orElseSucceed(readTaskInputs(name), () => null), (leftWith) => Effect.gen(function* () {
|
|
1089
|
-
const interrupted = !Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause);
|
|
1090
|
-
const me = DECLARED.get(name);
|
|
1091
|
-
// Its own claim, or one a sub-workflow step of it took for it (`agentKeptUntilThisRunEnds`), ends with it.
|
|
1092
|
-
if (me !== undefined && (agentsClaimedBy(me) > 0 || me.steps().some((s) => s.agentKeptUntilThisRunEnds === true)))
|
|
1093
|
-
yield* endClaims(executionId, exit);
|
|
1094
|
-
const runItem = yield* recorded('read its item', records.subjectOfRun(executionId));
|
|
1095
|
-
const inputsLeft = (subject) => {
|
|
1096
|
-
const item = subject ?? runItem;
|
|
1097
|
-
return item === null ? null : leftWith?.get(item.toLowerCase())?.fingerprint ?? null;
|
|
1098
|
-
};
|
|
1099
|
-
if (!interrupted && d.item !== null) {
|
|
1100
|
-
if (Exit.isSuccess(exit)) {
|
|
1101
|
-
for (const o of d.outcomes(exit.value))
|
|
1102
|
-
yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: o.subject ?? null, outcome: o.outcome, finished: o.finished || o.outcome === CLEARED_BY_TEST, inputs: inputsLeft(o.subject ?? null), blocked: o.blocked ?? null });
|
|
1103
|
-
}
|
|
1104
|
-
else {
|
|
1105
|
-
// With its cause, as its step's record has it: a bare "failed" sent whoever read it to the records for why.
|
|
1106
|
-
const failure = Cause.squash(exit.cause);
|
|
1107
|
-
const outcome = isStoodDown(failure) ? 'stood down' : `failed: ${startAndEnd(describeFailure(failure), { cap: 1000, end: 400, what: 'the failure' })}`;
|
|
1108
|
-
yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: null, outcome, finished: false, inputs: inputsLeft(null), blocked: null });
|
|
1109
|
-
}
|
|
1110
|
-
}
|
|
1111
|
-
// A RUN'S OWN TASK: done when it succeeds; blocked when it fails or stands down, with why in words the page
|
|
1112
|
-
// counts by (the step it failed at, or the stand-down's reason), the failure itself on the outcome note.
|
|
1113
|
-
if (!interrupted && runsAreTasks()) {
|
|
1114
|
-
const failure = Exit.isSuccess(exit) ? null : Cause.squash(exit.cause);
|
|
1115
|
-
const stoodDown = failure !== null && isStoodDown(failure);
|
|
1116
|
-
yield* deps.tasks.appendOutcome({
|
|
1117
|
-
workflow: name, run: executionId, subject: executionId, finished: failure === null, inputs: null,
|
|
1118
|
-
outcome: failure === null ? 'succeeded' : stoodDown ? STOOD_DOWN_OUTCOME : `failed: ${startAndEnd(describeFailure(failure), { cap: 1000, end: 400, what: 'the failure' })}`,
|
|
1119
|
-
blocked: failure === null ? null : stoodDown ? String(failure) : `failed at ${lastStepRan.get(executionId)?.step ?? 'its first step'}`,
|
|
1120
|
-
});
|
|
1121
|
-
}
|
|
1122
|
-
// What it ran on gave this result, which stands until its inputs change. Only a run its trigger started on its
|
|
1123
|
-
// inputs has a record to end.
|
|
1124
|
-
if (d.inputs !== undefined) {
|
|
1125
|
-
yield* Effect.catchTag(deps.inputs.recordEnd({
|
|
1126
|
-
run: executionId,
|
|
1127
|
-
outcome: Exit.isSuccess(exit) ? 'success' : Cause.hasInterrupts(exit.cause) ? 'interrupted' : 'failure',
|
|
1128
|
-
result: Exit.isSuccess(exit) ? JSON.stringify(exit.value) ?? null : null,
|
|
1129
|
-
}), 'StorageError', (e) => Effect.logError(`[inputs] ${name} run ${executionId}: its end could not be recorded: ${e.reason}`));
|
|
1130
|
-
}
|
|
1131
|
-
lastStepRan.delete(executionId);
|
|
1132
|
-
TOPS.delete(executionId);
|
|
1133
|
-
runEnded();
|
|
1134
|
-
// Its claim and its item are free now for its workflow's other runs, once the engine has stored its end. Only its
|
|
1135
|
-
// own: about 25 short runs end a minute, and waking every Pick on each re-read every task twice each time.
|
|
1136
|
-
setTimeout(() => deps.wakes.wakePicksOf(name, 'one of its runs ended'), 1000);
|
|
1137
|
-
}))))),
|
|
1138
|
-
});
|
|
1139
|
-
});
|
|
1140
|
-
const defineWorkflow = defineWorkflowAs(false);
|
|
1141
|
-
/**
|
|
1142
|
-
* RUNS A WORKFLOW ON `payload` ONLY WHEN ITS INPUTS CHANGED since its last successful run: it reads their fingerprint, and
|
|
1143
|
-
* when it is that run's, the result that run stored stands and nothing starts. Otherwise the run starts, recorded with the
|
|
1144
|
-
* fingerprint it ran on before it starts, so its end finds the record. A workflow that declares no inputs runs each time.
|
|
1145
|
-
* `wait` waits for the run to end.
|
|
1146
|
-
*/
|
|
1147
|
-
const runIfInputsChanged = (r) => Effect.gen(function* () {
|
|
1148
|
-
const d = DECLARED.get(r.workflow);
|
|
1149
|
-
if (d === undefined)
|
|
1150
|
-
return yield* Effect.fail(`no workflow ${r.workflow} is declared`);
|
|
1151
|
-
if (d.inputs !== undefined) {
|
|
1152
|
-
const inputs = yield* d.inputs.read();
|
|
1153
|
-
const last = yield* deps.inputs.lastSuccess(r.workflow);
|
|
1154
|
-
if (last !== null && last.inputs === inputs)
|
|
1155
|
-
return 'unchanged';
|
|
1156
|
-
const run = yield* d.executionIdOf(r.payload);
|
|
1157
|
-
yield* deps.inputs.recordStart({ workflow: r.workflow, inputs, run });
|
|
1158
|
-
}
|
|
1159
|
-
yield* d.startOn(r.payload, { wait: r.wait });
|
|
1160
|
-
return 'started';
|
|
1161
|
-
});
|
|
1162
|
-
/** The items a workflow's other unfinished runs are on, lower case, so a budget above 1 never puts two agents on one. */
|
|
1163
|
-
const itemsOfOtherRuns = (workflow, run) => Effect.flatMap(runningRunIds(workflow), (runs) => Effect.map(Effect.forEach(runs.filter((r) => r !== run), (r) => records.subjectOfRun(r)), (subjects) => new Set(subjects.flatMap((subject) => (subject === null ? [] : [subject.toLowerCase()])))));
|
|
1164
|
-
/**
|
|
1165
|
-
* The candidates of this run's Pick in the order it takes them (`tasks.ts` `inPickOrder`), its queue settled first as
|
|
1166
|
-
* `queueNow` settles it: none blocked, another run's left out. `fromItem` builds a candidate for a task a step or a person
|
|
1167
|
-
* returned to the queue that the candidates do not hold.
|
|
1168
|
-
*/
|
|
1169
|
-
const pickOrder = (input) => Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), noAgentFree: whyNoAgentIsFree(input.workflow) }), ({ tasks, noAgentFree }) => inPickOrder({
|
|
1170
|
-
candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }),
|
|
1171
|
-
// While no agent is free, a task marked as needing one is passed over (`whyNoAgentIsFree`).
|
|
1172
|
-
...(noAgentFree === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => deps.tasks.passedOverNow(t) !== null).map((t) => t.ref.item)) }),
|
|
1173
|
-
}));
|
|
1174
|
-
/**
|
|
1175
|
-
* A workflow of one code step, run each turn of its trigger: `run` waits for the run to finish (a heavy one, in line with
|
|
1176
|
-
* the other heavy jobs), `start` leaves it to the engine.
|
|
1177
|
-
*/
|
|
1178
|
-
const oneStepWorkflowAs = (system) => (
|
|
1179
|
-
// One step of the project's code: no agent, and no single item. `reason` is what its record says it did (`defineStep`).
|
|
1180
|
-
states, name, step, success, execute) => {
|
|
1181
|
-
const theStep = defineStep({ name: step, runs: 'deterministic', shared: true, description: states.stepDescription, at: states.at, success, ...(states.writes === undefined ? {} : { writes: states.writes }), ...(states.reason === undefined ? {} : { reason: states.reason }) });
|
|
1182
|
-
const workflow = defineWorkflowAs(system)({ description: states.description, at: states.at, steps: () => [theStep], item: null, ...(states.inputs === undefined ? {} : { inputs: states.inputs }),
|
|
1183
|
-
graph: () => [{ from: RUN_STARTS, to: step, when: 'each turn' }, { from: step, to: RUN_ENDS, when: 'always' }] })(name, {
|
|
1184
|
-
payload: { turn: Schema.Number },
|
|
1185
|
-
idempotencyKey: ({ turn }) => String(turn),
|
|
1186
|
-
success,
|
|
1187
|
-
error: Schema.String,
|
|
1188
|
-
});
|
|
1189
|
-
return {
|
|
1190
|
-
name, step, workflow, layer: workflow.toLayer(() => theStep.run(execute)),
|
|
1191
|
-
// Each turn of its trigger starts a run only when its inputs changed, where it declares them (`runIfInputsChanged`).
|
|
1192
|
-
run: (turn) => Effect.asVoid(runIfInputsChanged({ workflow: name, payload: { turn }, wait: true })),
|
|
1193
|
-
start: (turn) => Effect.asVoid(runIfInputsChanged({ workflow: name, payload: { turn }, wait: false })),
|
|
1194
|
-
};
|
|
1195
|
-
};
|
|
1196
|
-
const oneStepWorkflow = oneStepWorkflowAs(false);
|
|
1197
|
-
return {
|
|
1198
|
-
defineStep, defineItemTest, defineSubWorkflow, defineWorkflowStep, graphOfFeeds, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
|
|
1199
|
-
eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
|
|
1200
|
-
runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, whyNoAgentIsFree, whyNoRunCanTakeWork, versionOf, agentClaimsNow,
|
|
1201
|
-
/** The platform's own one-step workflows are defined by this (`system-workflows.ts`); `createWorkflowPlatform` keeps it from the app. */
|
|
1202
|
-
oneStepSystemWorkflow: oneStepWorkflowAs(true),
|
|
1203
|
-
};
|
|
1204
|
-
};
|
|
1205
|
-
//# sourceMappingURL=steps.js.map
|