@jive-sh/workflow-platform 0.6.3 → 0.7.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 +182 -42
- package/dist/budget-states.js +1 -1
- package/dist/budget-states.js.map +1 -1
- package/dist/dashboard/dashboard.css +42 -28
- package/dist/dashboard/drilldown.js +35 -4
- package/dist/dashboard/drilldown.js.map +1 -1
- package/dist/dashboard/run-doing-words.js +29 -0
- package/dist/dashboard/run-doing-words.js.map +1 -0
- package/dist/dashboard/setting-words.js +18 -0
- package/dist/dashboard/setting-words.js.map +1 -0
- package/dist/dashboard/spending-words.js +2 -10
- package/dist/dashboard/spending-words.js.map +1 -1
- package/dist/index.js +76 -13
- package/dist/index.js.map +1 -1
- package/dist/keep-running.js +4 -2
- package/dist/keep-running.js.map +1 -1
- package/dist/pick-wakes.js +2 -2
- package/dist/retention.js +59 -0
- package/dist/retention.js.map +1 -0
- package/dist/settings.js +88 -0
- package/dist/settings.js.map +1 -0
- package/dist/spending-limit.js +15 -21
- package/dist/spending-limit.js.map +1 -1
- package/dist/step-times.js +114 -0
- package/dist/step-times.js.map +1 -0
- package/dist/steps.js +399 -114
- package/dist/steps.js.map +1 -1
- package/dist/storage/agent-claims.js +3 -0
- package/dist/storage/agent-claims.js.map +1 -0
- package/dist/storage/budgets.js +40 -4
- package/dist/storage/budgets.js.map +1 -1
- package/dist/storage/engine-records.js +26 -10
- package/dist/storage/engine-records.js.map +1 -1
- package/dist/storage/sqlite-store.js +198 -20
- package/dist/storage/sqlite-store.js.map +1 -1
- package/dist/storage/task-store.js +11 -5
- package/dist/storage/task-store.js.map +1 -1
- package/dist/system-workflows.js +54 -0
- package/dist/system-workflows.js.map +1 -0
- package/dist/tasks.js +49 -24
- package/dist/tasks.js.map +1 -1
- package/dist/views/runs-now.js +80 -38
- package/dist/views/runs-now.js.map +1 -1
- package/dist/views/step-graph.js +6 -1
- package/dist/views/step-graph.js.map +1 -1
- package/dist/views/workflows-view.js +29 -23
- package/dist/views/workflows-view.js.map +1 -1
- package/package.json +1 -1
- package/src/budget-states.ts +2 -3
- package/src/dashboard/dashboard.css +42 -28
- package/src/dashboard/drilldown.ts +32 -5
- package/src/dashboard/index.tsx +1 -1
- package/src/dashboard/limits-and-runs.tsx +191 -0
- package/src/dashboard/queue-bar.tsx +30 -11
- package/src/dashboard/queue-chart.tsx +1 -2
- package/src/dashboard/run-doing-words.ts +41 -0
- package/src/dashboard/setting-words.ts +30 -0
- package/src/dashboard/spending-limit-control.tsx +5 -8
- package/src/dashboard/spending-words.ts +5 -23
- package/src/dashboard/time-distribution.tsx +61 -0
- package/src/dashboard/workflow-dag.tsx +247 -129
- package/src/dashboard/workflow-drilldown.tsx +13 -71
- package/src/dashboard/workflows-dashboard.tsx +345 -227
- package/src/index.ts +86 -16
- package/src/keep-running.ts +6 -4
- package/src/pick-wakes.ts +2 -2
- package/src/project.ts +12 -0
- package/src/retention.ts +90 -0
- package/src/settings.ts +171 -0
- package/src/spending-limit.ts +25 -42
- package/src/step-times.ts +151 -0
- package/src/steps.ts +512 -135
- package/src/storage/agent-claims.ts +63 -0
- package/src/storage/budgets.ts +43 -4
- package/src/storage/engine-records.ts +28 -11
- package/src/storage/sqlite-store.ts +225 -32
- package/src/storage/step-records.ts +59 -7
- package/src/storage/task-store.ts +29 -29
- package/src/system-workflows.ts +70 -0
- package/src/tasks.ts +49 -24
- package/src/views/runs-now.ts +119 -51
- package/src/views/step-graph.ts +11 -2
- package/src/views/workflows-view.ts +80 -39
- package/src/workflow-dag.test.tsx +89 -0
- package/src/workflow-page.test.tsx +170 -0
- package/dist/views/workflow-flows.js +0 -53
- package/dist/views/workflow-flows.js.map +0 -1
- package/src/dashboard/step-graph.tsx +0 -106
- package/src/views/workflow-flows.ts +0 -97
package/src/steps.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* THE ONE WAY TO DEFINE A WORKFLOW AND ITS STEPS.
|
|
3
3
|
*
|
|
4
|
-
* A workflow states its
|
|
4
|
+
* A workflow states its steps and the item it works on, and each step states
|
|
5
5
|
* whether it needs an agent; nothing else defines a step. Every run of every step goes through the same code here, which
|
|
6
6
|
* writes its one record (`storage/step-records.ts`): start, end, outcome, tokens, compiles, and a heartbeat while an agent
|
|
7
7
|
* works. A dashboard derives all it says from those records and these declarations.
|
|
8
8
|
*
|
|
9
9
|
* const PICK = defineStep({ name: 'Pick', runs: 'deterministic', description: '...', at: import.meta.path, success: Schema.Number });
|
|
10
|
-
* export const MyWorkflow = defineWorkflow({
|
|
10
|
+
* export const MyWorkflow = defineWorkflow({ description: '...', at: import.meta.path, steps: () => [PICK],
|
|
11
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
12
|
* ... yield* PICK.run(Effect.gen(...)); a repeating step gives its number: PICK.run(body, { call: 2 })
|
|
13
13
|
*
|
|
@@ -25,7 +25,14 @@
|
|
|
25
25
|
*
|
|
26
26
|
* An agent call needs `AgentStep`, which only a step that runs agentically (`runs: 'agentic'`) provides, so it cannot compile anywhere else.
|
|
27
27
|
*
|
|
28
|
-
* A
|
|
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
|
|
29
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
|
|
30
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
|
|
31
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,9 +46,11 @@
|
|
|
39
46
|
* compiles, on its one record. A step working on items says which: `subject` names the run's one, `eachItem` gives a batch
|
|
40
47
|
* step one record per item, and a step whose work no one item owns declares `shared` rather than dividing it up.
|
|
41
48
|
*/
|
|
49
|
+
import { createHash } from 'node:crypto';
|
|
50
|
+
import fs from 'node:fs';
|
|
42
51
|
import path from 'node:path';
|
|
43
|
-
import { Cause, Context, Data, Effect, Exit, pipe, Result, Schedule, Schema, Semaphore } from 'effect';
|
|
44
|
-
import { Activity, Workflow, WorkflowEngine } from 'effect/workflow';
|
|
52
|
+
import { Cause, Context, Data, Duration, Effect, Exit, pipe, Result, Schedule, Schema, Semaphore } from 'effect';
|
|
53
|
+
import { Activity, DurableClock, Workflow, WorkflowEngine } from 'effect/workflow';
|
|
45
54
|
import { describeFailure, startAndEnd } from './failure';
|
|
46
55
|
import { oneLine, standardReason } from './reasons';
|
|
47
56
|
import type { ProcessIdentity, UsageSink } from './project';
|
|
@@ -54,8 +63,9 @@ import type { EngineRecords } from './storage/engine-records';
|
|
|
54
63
|
import { AGENT_BEAT_MS, noSpend, type StepRecords, type StepScope, type StepSpend } from './storage/step-records';
|
|
55
64
|
import type { InputRecords } from './storage/input-records';
|
|
56
65
|
import type { StorageError } from './storage/storage-error';
|
|
57
|
-
import type
|
|
58
|
-
import {
|
|
66
|
+
import { claimsCounting, type AgentClaim, type AgentClaims, type RunOf } from './storage/agent-claims';
|
|
67
|
+
import { checkedSettings, stepSetting, type InheritedSettings } from './settings';
|
|
68
|
+
import { inPickOrder, listOf, queueOrder, STOOD_DOWN_OUTCOME, type PendingWork, type TaskInputs, type TaskRef, type Tasks, type TaskSummary } from './tasks';
|
|
59
69
|
|
|
60
70
|
export { A_STEP_FAILS, edgeDeclared, isRetry, RUN_ENDS, RUN_STARTS, type StepEdge } from './graph';
|
|
61
71
|
|
|
@@ -81,6 +91,8 @@ export class AgentStep extends Context.Service<AgentStep, {
|
|
|
81
91
|
readonly report: (spent: Partial<StepSpend>) => void;
|
|
82
92
|
/** What the agent asked its tools to do, which attributes the files it changed. */
|
|
83
93
|
readonly touched: (toolInputs: ReadonlyArray<string>) => void;
|
|
94
|
+
/** The model it runs on: its own, or what its workflows above set (`settings.ts`). */
|
|
95
|
+
readonly model: string;
|
|
84
96
|
/** What the step waits on that is not its agent, on its record; null once it no longer waits. */
|
|
85
97
|
readonly waiting: (why: string | null) => void;
|
|
86
98
|
}>()('AgentStep') {}
|
|
@@ -102,22 +114,35 @@ export const HANDED_OVER = 'stood down: its process is handing its runs to the n
|
|
|
102
114
|
*/
|
|
103
115
|
export const ABOVE_ENDED = 'stood down: the run above it has ended';
|
|
104
116
|
/**
|
|
105
|
-
* What
|
|
106
|
-
*
|
|
117
|
+
* 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
|
|
118
|
+
* used before its next agent call (`beforeAgentCall`): its task, where it has one, went to the back of its queue, marked
|
|
119
|
+
* as needing an agent, and the run gives its slot up.
|
|
120
|
+
*/
|
|
121
|
+
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';
|
|
122
|
+
/**
|
|
123
|
+
* 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
|
|
124
|
+
* declarations, not in its item, so its run stands down untried, and its task is neither charged a failed try nor blocked.
|
|
125
|
+
* As a plain failure it blocked three Decompile tasks for good (2026-11-21, 22:13 to 22:35 UTC): their inputs never change
|
|
126
|
+
* when a model is set, so "nothing new since its last failed try" never lapsed.
|
|
107
127
|
*/
|
|
108
|
-
export const
|
|
128
|
+
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';
|
|
109
129
|
export const isStoodDown = (failure: unknown): boolean =>
|
|
110
|
-
failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN;
|
|
130
|
+
failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN || failure === NO_MODEL_STOOD_DOWN;
|
|
111
131
|
|
|
112
132
|
/** Why no agent can be had at an agents' limit of 0, in words. */
|
|
113
133
|
export const AGENTS_LIMIT_ZERO = "its agents' limit is 0";
|
|
114
134
|
|
|
115
135
|
/**
|
|
116
|
-
* Whether
|
|
117
|
-
*
|
|
118
|
-
*
|
|
136
|
+
* Whether a run may claim an agent now (`claimAgentsOrEnd`). Where it may, `limit` is the agents' limit its claim must still
|
|
137
|
+
* fit under as it is taken (`AgentClaims.takeAgentClaim`), none for no limit. Where not, `why` is what its task's mark says,
|
|
138
|
+
* and in words one of two reasons, or neither where the limits could not be read: `unavailable`, why none can be had until
|
|
139
|
+
* a limit or a reading changes (an agents' limit of 0, the spending limit); `inUse`, that every agent its limit allows is
|
|
140
|
+
* claimed by other runs, so one frees when one of their claims ends.
|
|
119
141
|
*/
|
|
120
|
-
export type AgentSlot = { readonly free: true } | { readonly free: false; readonly why: string; readonly unavailable: string | null };
|
|
142
|
+
export type AgentSlot = { readonly free: true; readonly limit?: number } | { readonly free: false; readonly why: string; readonly unavailable: string | null; readonly inUse: string | null };
|
|
143
|
+
|
|
144
|
+
/** That every agent a limit allows is claimed, in words. Pure. */
|
|
145
|
+
const agentsInUse = (agents: number): string => `its ${agents === 1 ? 'agent is' : `${agents} agents are`} in use`;
|
|
121
146
|
|
|
122
147
|
/** 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. */
|
|
123
148
|
export const surplusRun = (oldestFirst: ReadonlyArray<string>, run: string, budget: number): boolean => oldestFirst.indexOf(run) >= budget;
|
|
@@ -139,7 +164,7 @@ export type StepKind = (typeof STEP_KINDS)[number];
|
|
|
139
164
|
* for steps which use a separate classifier model".
|
|
140
165
|
*
|
|
141
166
|
* deterministic code only;
|
|
142
|
-
* agentic an agent does it
|
|
167
|
+
* agentic an agent does it, on the agent its run claimed as it started (`claimAgentsOrEnd`);
|
|
143
168
|
* classification a separate classifier model decides.
|
|
144
169
|
*
|
|
145
170
|
* A step or a check is any of the three. A sub-workflow step states none: its workflow's own steps state theirs.
|
|
@@ -150,7 +175,11 @@ export type StepRuns = (typeof STEP_RUNS)[number];
|
|
|
150
175
|
/** A step's kind, from its declaration: the kind it states, a check where it is its workflow's test, a step otherwise. Pure. */
|
|
151
176
|
export const stepKindOf = (s: Pick<StepDeclaration, 'test' | 'kind'>): StepKind => s.kind ?? (s.test === true ? 'check' : 'step');
|
|
152
177
|
|
|
153
|
-
|
|
178
|
+
/**
|
|
179
|
+
* A STEP AS IT STATES ITSELF. What it sets of the settings a workflow tree inherits (`settings.ts`) is its own: an agent
|
|
180
|
+
* step's model, how long its records are kept, and, for a sub-workflow step, what every step under it inherits.
|
|
181
|
+
*/
|
|
182
|
+
export interface StepDeclaration extends InheritedSettings {
|
|
154
183
|
readonly name: string;
|
|
155
184
|
/** How it runs; none for a sub-workflow step. */
|
|
156
185
|
readonly runs: StepRuns | null;
|
|
@@ -160,6 +189,20 @@ export interface StepDeclaration {
|
|
|
160
189
|
readonly workflow?: string;
|
|
161
190
|
/** For a sub-workflow step: whether its workflow has an agent step, at any depth under it. */
|
|
162
191
|
readonly agentUnder?: () => boolean;
|
|
192
|
+
/**
|
|
193
|
+
* For a sub-workflow step: its workflow runs on its own trigger (its queue, its inputs, a timer), and no run of this one
|
|
194
|
+
* starts it (`defineWorkflowStep`). Its runs and limits are its own; absent, a run of this one starts it and waits.
|
|
195
|
+
*/
|
|
196
|
+
readonly runsOnItsOwnTrigger?: true;
|
|
197
|
+
/**
|
|
198
|
+
* For a sub-workflow step: the agent claim its workflow's run takes (`claimAgentsOrEnd`) is held by the run of this step's
|
|
199
|
+
* workflow, from that claim until that run ends, not until the sub-workflow's run ends. Its next call, and the steps
|
|
200
|
+
* between, keep the agent: no other run can take it in between. The default in effect since 2026-11-24, which Alex can
|
|
201
|
+
* overrule: Decompile's run keeps the agent its Write C took through each Byte check, so a function goes on to its next
|
|
202
|
+
* round rather than to the back of the queue, losing the refusal that round was to act on. Of 752 functions with a Write C
|
|
203
|
+
* round in the week to 2026-11-22, 309 went to a second, with about 6 Byte checks between rounds each.
|
|
204
|
+
*/
|
|
205
|
+
readonly agentKeptUntilThisRunEnds?: true;
|
|
163
206
|
/** Whether this is the no-agent test an item goes through before any agent sees it. */
|
|
164
207
|
readonly test?: boolean;
|
|
165
208
|
/** One line on what it does, for its hover. */
|
|
@@ -232,10 +275,12 @@ export interface WorkflowInputs<R> {
|
|
|
232
275
|
readonly read: () => Effect.Effect<string, unknown, R>;
|
|
233
276
|
}
|
|
234
277
|
|
|
235
|
-
/**
|
|
236
|
-
|
|
278
|
+
/**
|
|
279
|
+
* A workflow as it states itself. `R` is what its list of work runs under. What it sets of the settings a workflow tree
|
|
280
|
+
* inherits (`settings.ts`), every step under it inherits, unless a step sets its own.
|
|
281
|
+
*/
|
|
282
|
+
export interface WorkflowDeclaration<R = never> extends InheritedSettings {
|
|
237
283
|
readonly name: string;
|
|
238
|
-
readonly phase: Phase;
|
|
239
284
|
readonly description: string;
|
|
240
285
|
readonly source: SourceRef;
|
|
241
286
|
readonly steps: () => ReadonlyArray<StepDeclaration>;
|
|
@@ -256,10 +301,15 @@ export interface WorkflowDeclaration<Phase extends string = string, R = never> {
|
|
|
256
301
|
/** Its Pick takes the first task of its queue it can claim (`tasks.ts` `queueOrder`), so a dashboard lists that queue. */
|
|
257
302
|
readonly picksQueueHead?: true;
|
|
258
303
|
/**
|
|
259
|
-
* The workflows whose results become its tasks: the
|
|
260
|
-
* used as a step of another needs none: it is drawn inside that one.
|
|
304
|
+
* The workflows whose results become its tasks: the edges between them in the step graph of a workflow made of
|
|
305
|
+
* workflows (`graphOfFeeds`). A workflow used as a step of another needs none: it is drawn inside that one.
|
|
261
306
|
*/
|
|
262
307
|
readonly fedBy?: ReadonlyArray<string>;
|
|
308
|
+
/**
|
|
309
|
+
* For a workflow made of workflows (`isMadeOfWorkflows`), the step that does its main work: the one whose tasks its box
|
|
310
|
+
* shows, counted under that step's own workflow. None, and its box shows no tasks.
|
|
311
|
+
*/
|
|
312
|
+
readonly mainStep?: string;
|
|
263
313
|
/** Its step graph (`StepEdge`); none until it declares one. */
|
|
264
314
|
readonly graph?: () => ReadonlyArray<StepEdge>;
|
|
265
315
|
/** What it runs on (`WorkflowInputs`); none until it declares them, and it runs whenever its trigger says. */
|
|
@@ -273,8 +323,23 @@ export interface WorkflowDeclaration<Phase extends string = string, R = never> {
|
|
|
273
323
|
readonly startOn: (payload: object, options: { readonly wait: boolean }) => Effect.Effect<void, unknown, WorkflowEngine.WorkflowEngine>;
|
|
274
324
|
/** The engine's id for the run on `payload`: what its step records and its end carry. */
|
|
275
325
|
readonly executionIdOf: (payload: object) => Effect.Effect<string>;
|
|
326
|
+
/**
|
|
327
|
+
* One of the platform's own workflows (`system-workflows.ts`), which every app has and none defines: its steps change
|
|
328
|
+
* only with the platform, and it is no step of an app's workflow.
|
|
329
|
+
*/
|
|
330
|
+
readonly system?: true;
|
|
331
|
+
/** How many agents each of its runs claims, where it declares more than its agent step's one (`agentsClaimedBy`). */
|
|
332
|
+
readonly agentsClaimed?: number;
|
|
276
333
|
}
|
|
277
334
|
|
|
335
|
+
/**
|
|
336
|
+
* 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
|
|
337
|
+
* its own, else none. A workflow whose agent steps are all under its sub-workflow steps claims none itself: each of those
|
|
338
|
+
* workflows claims its own. Pure.
|
|
339
|
+
*/
|
|
340
|
+
export const agentsClaimedBy = (d: Pick<WorkflowDeclaration<unknown>, 'agentsClaimed' | 'steps'>): number =>
|
|
341
|
+
d.agentsClaimed ?? (d.steps().some((s) => s.runs === 'agentic') ? 1 : 0);
|
|
342
|
+
|
|
278
343
|
/** A run not started: its workflow's run limit was reached. What a start that waits for its result fails with. */
|
|
279
344
|
export class RunLimitReached extends Data.TaggedError('RunLimitReached')<{ readonly workflow: string; readonly limit: number }> {}
|
|
280
345
|
|
|
@@ -285,24 +350,61 @@ const REFUSED_SAID_EVERY_MS = 10 * 60 * 1000;
|
|
|
285
350
|
* A WORKFLOW'S RUN LIMIT, whatever starts it: for one its budget keeps going, its run limit or its agents' limit
|
|
286
351
|
* (`runLimit`); for any other its run limit, none meaning no limit. 0 starts nothing new. Pure.
|
|
287
352
|
*/
|
|
288
|
-
export const runLimitOf = (d: Pick<WorkflowDeclaration<
|
|
353
|
+
export const runLimitOf = (d: Pick<WorkflowDeclaration<unknown>, 'pending' | 'items' | 'steps'>, limits: WorkflowLimits): number | null =>
|
|
289
354
|
keptRunningByItsBudget(d) ? runLimit(limits) : limits.runs;
|
|
290
355
|
|
|
291
356
|
/** Whether a workflow declares a list, of either kind: it has tasks and a queue. Pure. */
|
|
292
|
-
export const hasAList = (d: Pick<WorkflowDeclaration<
|
|
357
|
+
export const hasAList = (d: Pick<WorkflowDeclaration<unknown>, 'pending' | 'items'>): boolean => d.pending !== undefined || d.items !== undefined;
|
|
293
358
|
|
|
294
359
|
/** Whether a step uses an agent: it is an agent step, or a sub-workflow step whose workflow has one at any depth. Pure. */
|
|
295
360
|
export const stepUsesAnAgent = (s: Pick<StepDeclaration, 'runs' | 'agentUnder'>): boolean => s.runs === 'agentic' || s.agentUnder?.() === true;
|
|
296
361
|
|
|
297
362
|
/** Whether a workflow's budget rules it: a declared list, and an agent step of its own or under a sub-workflow step. Pure. */
|
|
298
|
-
export const keptRunningByItsBudget = (d: Pick<WorkflowDeclaration<
|
|
363
|
+
export const keptRunningByItsBudget = (d: Pick<WorkflowDeclaration<unknown>, 'pending' | 'items' | 'steps'>): boolean =>
|
|
299
364
|
hasAList(d) && d.steps().some(stepUsesAnAgent);
|
|
300
365
|
|
|
301
366
|
|
|
367
|
+
/**
|
|
368
|
+
* The workflows a run of another starts as one of its steps (`defineSubWorkflow`): each of their runs is part of the run
|
|
369
|
+
* 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.
|
|
370
|
+
*/
|
|
371
|
+
export const startedAsSteps = (declared: ReadonlyArray<{ readonly steps: () => ReadonlyArray<Pick<StepDeclaration, 'workflow' | 'runsOnItsOwnTrigger'>> }>): ReadonlySet<string> =>
|
|
372
|
+
new Set(declared.flatMap((d) => d.steps().flatMap((s) => (s.workflow === undefined || s.runsOnItsOwnTrigger === true ? [] : [s.workflow]))));
|
|
373
|
+
|
|
374
|
+
/**
|
|
375
|
+
* Whether every step of a workflow is another workflow on its own trigger: it starts no run of its own, and its runs, agents
|
|
376
|
+
* and costs are its steps', added up. Pure.
|
|
377
|
+
*/
|
|
378
|
+
export const isMadeOfWorkflows = (d: { readonly steps: () => ReadonlyArray<Pick<StepDeclaration, 'runsOnItsOwnTrigger'>> }): boolean => {
|
|
379
|
+
const steps = d.steps();
|
|
380
|
+
return steps.length > 0 && steps.every((s) => s.runsOnItsOwnTrigger === true);
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* WHETHER A WORKFLOW'S TASKS ARE ITS RUNS, one task a run (`tasks.ts` `runStarted`): it works on no item, has runs of its
|
|
385
|
+
* own (it is not made of workflows), and runs on its own trigger, never as a step another workflow's run starts, whose
|
|
386
|
+
* tasks are that workflow's passing through it. Alex, 2026-11-21: "a workflow is a workflow". Pure.
|
|
387
|
+
*/
|
|
388
|
+
export const tasksAreRuns = (
|
|
389
|
+
d: { readonly name: string; readonly item: string | null; readonly steps: () => ReadonlyArray<Pick<StepDeclaration, 'workflow' | 'runsOnItsOwnTrigger'>> },
|
|
390
|
+
declared: ReadonlyArray<{ readonly steps: () => ReadonlyArray<Pick<StepDeclaration, 'workflow' | 'runsOnItsOwnTrigger'>> }>,
|
|
391
|
+
): boolean => d.item === null && !isMadeOfWorkflows(d) && !startedAsSteps(declared).has(d.name);
|
|
392
|
+
|
|
393
|
+
/** A file's code as a process loaded it: its content's hash, and when it last changed, unix seconds. */
|
|
394
|
+
export interface FileCode {
|
|
395
|
+
readonly hash: string;
|
|
396
|
+
readonly changed: number;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** A workflow's version (`makeSteps` `versionOf`): the hash of its code loaded now, and when the newest of it changed. */
|
|
400
|
+
export interface WorkflowVersion {
|
|
401
|
+
readonly version: string;
|
|
402
|
+
readonly since: number;
|
|
403
|
+
}
|
|
404
|
+
|
|
302
405
|
/** An unfinished run of a workflow with an agent step. */
|
|
303
|
-
export interface AssignedRun
|
|
406
|
+
export interface AssignedRun {
|
|
304
407
|
readonly workflow: string;
|
|
305
|
-
readonly phase: Phase | 'upkeep';
|
|
306
408
|
readonly run: string;
|
|
307
409
|
readonly step: string;
|
|
308
410
|
readonly subject: string | null;
|
|
@@ -319,8 +421,11 @@ const CurrentMeter = Context.Reference<StepMeter | null>('CurrentStepMeter', { d
|
|
|
319
421
|
export interface AgentBudgetRules {
|
|
320
422
|
readonly standsDown: (workflow: string, run: string) => Effect.Effect<boolean>;
|
|
321
423
|
readonly waitsForWork: (workflow: string, run: string) => Effect.Effect<boolean>;
|
|
322
|
-
/**
|
|
323
|
-
|
|
424
|
+
/**
|
|
425
|
+
* The agents the other runs under its top workflow claim now are fewer than that workflow's agents' limit; why not, when
|
|
426
|
+
* they are not. With no run (`null`), whether a run of the workflow, such as one its Pick would start work for, could claim one.
|
|
427
|
+
*/
|
|
428
|
+
readonly agentSlot: (workflow: string, run: string | null) => Effect.Effect<AgentSlot>;
|
|
324
429
|
}
|
|
325
430
|
|
|
326
431
|
/** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
|
|
@@ -332,7 +437,7 @@ interface RunnableWorkflow {
|
|
|
332
437
|
}
|
|
333
438
|
|
|
334
439
|
/** The definer of one project's workflows and steps, on its stores. */
|
|
335
|
-
export const makeSteps = <
|
|
440
|
+
export const makeSteps = <R>(deps: {
|
|
336
441
|
readonly sourceRoot: string;
|
|
337
442
|
readonly stepRecords: StepRecords;
|
|
338
443
|
readonly engine: EngineRecords;
|
|
@@ -347,12 +452,26 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
347
452
|
readonly inputs: InputRecords;
|
|
348
453
|
/** A workflow's queue changed with no wake of its Picks: one of them claimed an item (`queue-counts.ts`). */
|
|
349
454
|
readonly queueChanged: (workflow: string) => void;
|
|
350
|
-
/**
|
|
351
|
-
readonly spendingHoldsAgents: () => Effect.Effect<
|
|
455
|
+
/** Why the spending limit withholds every agent now, in words; none while it holds nothing (`spending-limit.ts`). */
|
|
456
|
+
readonly spendingHoldsAgents: () => Effect.Effect<string | null>;
|
|
457
|
+
/** Each run's claim on its top workflow's agents (`storage/agent-claims.ts`). */
|
|
458
|
+
readonly claims: AgentClaims;
|
|
459
|
+
/** What the app sets above every workflow (`WorkflowProject.settings`): an agent step's model where nothing below sets one. */
|
|
460
|
+
readonly appSettings: InheritedSettings;
|
|
352
461
|
}) => {
|
|
353
462
|
const { stepRecords: records, stepFiles } = deps;
|
|
354
|
-
type Declaration = WorkflowDeclaration<
|
|
463
|
+
type Declaration = WorkflowDeclaration<R>;
|
|
355
464
|
const DECLARED = new Map<string, Declaration>();
|
|
465
|
+
/** The platform's own workflows, by name (`system-workflows.ts`): defined before any of the app's. */
|
|
466
|
+
const SYSTEM = new Set<string>();
|
|
467
|
+
/**
|
|
468
|
+
* AN APP CANNOT AMEND ONE OF THE PLATFORM'S OWN WORKFLOWS: a definition of the same name, or one holding it as a step,
|
|
469
|
+
* fails the app's start, naming what the app may set instead. Alex, 2026-11-22: "system workflows at the top level which
|
|
470
|
+
* can be configured but not amended without changing the platform itself".
|
|
471
|
+
*/
|
|
472
|
+
const refuseSystem = (name: string, what: string): void => {
|
|
473
|
+
if (SYSTEM.has(name)) 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`);
|
|
474
|
+
};
|
|
356
475
|
const PICKING = new Map<string, Semaphore.Semaphore>();
|
|
357
476
|
const RUN_ENDED = new Set<() => void>();
|
|
358
477
|
const undeclaredSaid = new Set<string>();
|
|
@@ -386,6 +505,58 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
386
505
|
/** A file's path relative to the project's source root, from its absolute path. */
|
|
387
506
|
const sourcePath = (absolute: string) => path.relative(deps.sourceRoot, absolute).split(path.sep).join('/');
|
|
388
507
|
|
|
508
|
+
/** Each file's code as this process loaded it (`codeOf`), by its absolute path. */
|
|
509
|
+
const CODE_OF_FILE = new Map<string, FileCode>();
|
|
510
|
+
/**
|
|
511
|
+
* A FILE'S CODE AS THIS PROCESS LOADED IT, read once, when the first definition naming it is made: its content's hash, and
|
|
512
|
+
* when it last changed. What a workflow's version is made of (`versionOf`). An unreadable file is code too: its hash says so.
|
|
513
|
+
*/
|
|
514
|
+
const codeOf = (file: string): FileCode => {
|
|
515
|
+
const known = CODE_OF_FILE.get(file);
|
|
516
|
+
if (known !== undefined) return known;
|
|
517
|
+
let code: FileCode;
|
|
518
|
+
try {
|
|
519
|
+
code = { hash: createHash('sha256').update(fs.readFileSync(file)).digest('hex').slice(0, 16), changed: fs.statSync(file).mtimeMs / 1000 };
|
|
520
|
+
} catch {
|
|
521
|
+
code = { hash: 'unreadable', changed: 0 };
|
|
522
|
+
}
|
|
523
|
+
CODE_OF_FILE.set(file, code);
|
|
524
|
+
return code;
|
|
525
|
+
};
|
|
526
|
+
/** Each step's code (`defineStep`): the file that defines it, and an agent step's prompt file. */
|
|
527
|
+
const STEP_CODE = new WeakMap<object, ReadonlyArray<FileCode>>();
|
|
528
|
+
/** Each workflow's own file's code (`defineWorkflow`). */
|
|
529
|
+
const WORKFLOW_CODE = new Map<string, FileCode>();
|
|
530
|
+
const VERSIONS = new Map<string, WorkflowVersion>();
|
|
531
|
+
/**
|
|
532
|
+
* 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
|
|
533
|
+
* included), in their order; a step that is a workflow counts by that workflow's version, never its files inlined. `since`
|
|
534
|
+
* is when the newest of those files last changed. Read once per process, after every workflow is defined: a version
|
|
535
|
+
* changes only with the code a process loads. Every step record of a run carries its run's version
|
|
536
|
+
* (`StepRecords.openStepRun`).
|
|
537
|
+
*/
|
|
538
|
+
const versionOf = (workflow: string, under: ReadonlySet<string> = new Set()): WorkflowVersion => {
|
|
539
|
+
const known = VERSIONS.get(workflow);
|
|
540
|
+
if (known !== undefined) return known;
|
|
541
|
+
const d = DECLARED.get(workflow);
|
|
542
|
+
if (d === undefined || under.has(workflow)) return { version: 'undeclared', since: 0 };
|
|
543
|
+
const own = WORKFLOW_CODE.get(workflow) ?? { hash: 'unknown', changed: 0 };
|
|
544
|
+
let since = own.changed;
|
|
545
|
+
const parts = [own.hash, ...d.steps().map((s) => {
|
|
546
|
+
if (s.workflow !== undefined) {
|
|
547
|
+
const sub = versionOf(s.workflow, new Set([...under, workflow]));
|
|
548
|
+
since = Math.max(since, sub.since);
|
|
549
|
+
return `${s.name}>${sub.version}`;
|
|
550
|
+
}
|
|
551
|
+
const codes = STEP_CODE.get(s) ?? [];
|
|
552
|
+
for (const c of codes) since = Math.max(since, c.changed);
|
|
553
|
+
return `${s.name}:${codes.map((c) => c.hash).join(',')}`;
|
|
554
|
+
})];
|
|
555
|
+
const version = { version: createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 12), since };
|
|
556
|
+
VERSIONS.set(workflow, version);
|
|
557
|
+
return version;
|
|
558
|
+
};
|
|
559
|
+
|
|
389
560
|
/** The runs of these workflows not finished now, oldest first. */
|
|
390
561
|
const runsOldestFirst = (workflows: ReadonlyArray<string>): Effect.Effect<ReadonlyArray<string>, StorageError> => deps.engine.runsOldestFirst(workflows);
|
|
391
562
|
/** The runs of a workflow not finished now, by the id its step records carry. */
|
|
@@ -436,16 +607,17 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
436
607
|
});
|
|
437
608
|
|
|
438
609
|
/**
|
|
439
|
-
* LIMITS THAT CANNOT BE READ
|
|
440
|
-
*
|
|
610
|
+
* 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
|
|
611
|
+
* them again, and a run that starts takes no claim and ends, saying why. Read as no limits, a store that failed would start
|
|
612
|
+
* agents at 0.
|
|
441
613
|
*/
|
|
442
614
|
const unreadLimits = <A>(workflow: string, held: (why: string) => A) => (e: StorageError): Effect.Effect<A> =>
|
|
443
615
|
Effect.as(Effect.logError(`[budget] ${workflow}: its limits could not be read (${e.reason}); its runs wait`), held(e.reason));
|
|
444
616
|
|
|
445
617
|
/**
|
|
446
618
|
* 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
|
|
447
|
-
* (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent
|
|
448
|
-
* against the agents' limit of the workflow at the top. Kept while the run goes: it never changes.
|
|
619
|
+
* (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent claim counts
|
|
620
|
+
* against the agents' limit of the workflow at the top (`claimAgentsOrEnd`). Kept while the run goes: it never changes.
|
|
449
621
|
*/
|
|
450
622
|
const TOPS = new Map<string, { readonly run: string; readonly workflow: string }>();
|
|
451
623
|
/** Each workflow's start with no run limit asked, by name: what a sub-workflow step starts it by (`defineSubWorkflow`). */
|
|
@@ -460,6 +632,17 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
460
632
|
});
|
|
461
633
|
};
|
|
462
634
|
|
|
635
|
+
/**
|
|
636
|
+
* THE AGENT CLAIMS THAT COUNT NOW, every workflow's: open, with the run at the top of each unfinished in the engine
|
|
637
|
+
* (`storage/agent-claims.ts` `claimsCounting`). The runs holding an agent, as a page shows them.
|
|
638
|
+
*/
|
|
639
|
+
const agentClaimsNow = (): Effect.Effect<ReadonlyArray<AgentClaim>, StorageError> =>
|
|
640
|
+
Effect.map(Effect.all({ open: deps.claims.openAgentClaims(), live: deps.engine.unfinishedRuns() }), ({ open, live }) => claimsCounting(open, new Set(live.map((u) => u.run))));
|
|
641
|
+
/** How many agents the runs under `workflow`'s runs claim now, the claim of the run `besides` left out. */
|
|
642
|
+
const agentsClaimedAgainst = (r: { readonly workflow: string; readonly besides: string | null }): Effect.Effect<number, StorageError> =>
|
|
643
|
+
Effect.map(Effect.all({ open: deps.claims.openAgentClaims(), live: runsOldestFirst([r.workflow]) }), ({ open, live }) =>
|
|
644
|
+
claimsCounting(open.filter((c) => c.top.workflow === r.workflow && c.run !== r.besides), new Set(live)).reduce((n, c) => n + c.agents, 0));
|
|
645
|
+
|
|
463
646
|
const AgentBudgets = Context.Reference<AgentBudgetRules>('AgentBudgets', {
|
|
464
647
|
defaultValue: () => ({
|
|
465
648
|
// Among its workflow's unfinished runs, oldest first, the run is past those its run limit keeps (`runLimit`). A run not
|
|
@@ -470,21 +653,18 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
470
653
|
Effect.catchTag('StorageError', unreadLimits(workflow, () => false)),
|
|
471
654
|
),
|
|
472
655
|
waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
|
|
473
|
-
// The other runs
|
|
474
|
-
//
|
|
656
|
+
// The agents the other runs under the workflow at its top claim (`agentsClaimedAgainst`), against that workflow's
|
|
657
|
+
// agents' limit: at 0 none is ever free, which no claim ending changes.
|
|
475
658
|
agentSlot: (workflow, run) => pipe(
|
|
476
|
-
topOf(workflow, run),
|
|
477
|
-
Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<AgentSlot, StorageError> => {
|
|
659
|
+
run === null ? Effect.succeed({ run: null, workflow }) : topOf(workflow, run),
|
|
660
|
+
Effect.flatMap((top: { readonly run: string | null; readonly workflow: string }) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<AgentSlot, StorageError> => {
|
|
478
661
|
const agents = w === null ? null : w.agents;
|
|
479
662
|
if (agents === null) return Effect.succeed({ free: true });
|
|
480
|
-
if (agents === 0) return Effect.succeed({ free: false, why:
|
|
481
|
-
return Effect.map(
|
|
482
|
-
|
|
483
|
-
const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
|
|
484
|
-
return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use`, unavailable: null };
|
|
485
|
-
});
|
|
663
|
+
if (agents === 0) return Effect.succeed({ free: false, why: AGENTS_LIMIT_ZERO, unavailable: AGENTS_LIMIT_ZERO, inUse: null });
|
|
664
|
+
return Effect.map(agentsClaimedAgainst({ workflow: top.workflow, besides: run }), (held): AgentSlot =>
|
|
665
|
+
(held < agents ? { free: true, limit: agents } : { free: false, why: agentsInUse(agents), unavailable: null, inUse: agentsInUse(agents) }));
|
|
486
666
|
})),
|
|
487
|
-
Effect.catchTag('StorageError', unreadLimits(workflow, (why): AgentSlot => ({ free: false, why: `
|
|
667
|
+
Effect.catchTag('StorageError', unreadLimits(workflow, (why): AgentSlot => ({ free: false, why: `its limits could not be read (${why})`, unavailable: null, inUse: null }))),
|
|
488
668
|
),
|
|
489
669
|
}),
|
|
490
670
|
});
|
|
@@ -503,14 +683,14 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
503
683
|
* ends, the next takes the same work and ends the same way. Fix conflicts' runs named conflicts while its list named
|
|
504
684
|
* 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,
|
|
505
685
|
* 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
|
|
506
|
-
* run
|
|
686
|
+
* run ends unmarked, as a run with no task does. A task whose state cannot be read is marked as before.
|
|
507
687
|
*/
|
|
508
688
|
const markedAsNeedingAnAgent = (top: { readonly run: string; readonly workflow: string }, step: string, why: string): Effect.Effect<boolean> =>
|
|
509
689
|
Effect.flatMap(taskOfTop(top), (task) => {
|
|
510
690
|
if (task === null) return Effect.succeed(false);
|
|
511
691
|
return Effect.flatMap(Effect.orElseSucceed(deps.tasks.readByItsPick(task), () => true), (read) => {
|
|
512
692
|
if (read) return deps.tasks.markNeedsAgent({ task, by: { workflow: top.workflow, run: top.run, step }, why });
|
|
513
|
-
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
|
|
693
|
+
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`;
|
|
514
694
|
if (process.env.NODE_ENV === 'test') return Effect.die(new Error(fault));
|
|
515
695
|
if (!offItsListSaid.has(`${top.workflow}\n${task.item}`)) {
|
|
516
696
|
offItsListSaid.add(`${top.workflow}\n${task.item}`);
|
|
@@ -521,61 +701,132 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
521
701
|
});
|
|
522
702
|
|
|
523
703
|
/**
|
|
524
|
-
* WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, in words; none where one can: the
|
|
525
|
-
* agents' limit is 0. While it says so
|
|
526
|
-
*
|
|
527
|
-
* queue's order again once an agent can be had. A limit that cannot be read passes over none.
|
|
704
|
+
* 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
|
|
705
|
+
* spending limit holds, or its agents' limit is 0. While it says so and its Pick would pass over every task in its queue,
|
|
706
|
+
* no run of it starts, and a Pick that finds nothing ends its run (`whyNoRunCanTakeWork`).
|
|
528
707
|
*/
|
|
529
708
|
const agentsUnavailable = (workflow: string): Effect.Effect<string | null> => Effect.gen(function* () {
|
|
530
709
|
const held = yield* deps.spendingHoldsAgents();
|
|
531
|
-
if (held !== null
|
|
710
|
+
if (held !== null) return held;
|
|
532
711
|
const limits = yield* Effect.orElseSucceed(limitsOf(workflow), () => null);
|
|
533
712
|
return limits !== null && limits.agents === 0 ? AGENTS_LIMIT_ZERO : null;
|
|
534
713
|
});
|
|
535
714
|
|
|
715
|
+
/** Whether a run of a workflow may claim an agent now (`AgentSlot`): the spending limit first, then its top workflow's agents. */
|
|
716
|
+
const agentSlotNow = (workflow: string, run: string | null): Effect.Effect<AgentSlot> => Effect.gen(function* () {
|
|
717
|
+
const held = yield* deps.spendingHoldsAgents();
|
|
718
|
+
if (held !== null) return { free: false, why: held, unavailable: held, inUse: null };
|
|
719
|
+
return yield* (yield* AgentBudgets).agentSlot(workflow, run);
|
|
720
|
+
});
|
|
721
|
+
|
|
536
722
|
/**
|
|
537
|
-
*
|
|
538
|
-
*
|
|
539
|
-
*
|
|
540
|
-
*
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
723
|
+
* 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
|
|
724
|
+
* had (`agentsUnavailable`), or every agent its agents' limit allows is claimed. While it says so, its Pick passes over its
|
|
725
|
+
* tasks marked as needing an agent, and those with nothing new since their last run (`queueNow`, `pickOrder`, `tasks.ts`
|
|
726
|
+
* `passedOverWithoutAnAgent`): a run on one would only find no agent to claim again. It takes them in their queue's order
|
|
727
|
+
* once an agent is free, woken by a claim ending (`endClaims`). Taken while every agent was claimed, a marked task would be
|
|
728
|
+
* picked, marked and put back again at once, as Fix conflicts' 3 tasks were 907 times in 75 minutes (2026-11-20).
|
|
729
|
+
*/
|
|
730
|
+
const whyNoAgentIsFree = (workflow: string): Effect.Effect<string | null> =>
|
|
731
|
+
Effect.map(agentSlotNow(workflow, null), (slot) => (slot.free ? null : slot.unavailable !== null ? slot.unavailable : slot.inUse));
|
|
732
|
+
|
|
733
|
+
/** One claim taken at a time per top workflow in this process; the store's statement keeps processes apart (`takeAgentClaim`). */
|
|
734
|
+
const CLAIMING = new Map<string, Semaphore.Semaphore>();
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* 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
|
|
738
|
+
* its queue (`tasks.ts` `markNeedsAgent`), and fails with `NEEDS_AN_AGENT_STOOD_DOWN`, giving its run slot to the next
|
|
739
|
+
* 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
|
|
740
|
+
* 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
|
|
741
|
+
* 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
|
|
742
|
+
* 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
|
|
743
|
+
* marked as needing an agent then stopped and moved back to the queue's end".
|
|
744
|
+
*/
|
|
745
|
+
const endForWantOfAnAgent = (r: { readonly top: { readonly run: string; readonly workflow: string }; readonly workflow: string; readonly run: string; readonly step: string; readonly why: string }): Effect.Effect<never, string> =>
|
|
746
|
+
Effect.flatMap(markedAsNeedingAnAgent(r.top, r.step, r.why), (marked) => {
|
|
747
|
+
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'}`);
|
|
748
|
+
return Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* THE RUN A CLAIM IS TAKEN FOR: the run itself, or, where a sub-workflow step that keeps its agent until its run ends
|
|
753
|
+
* started it (`StepDeclaration.agentKeptUntilThisRunEnds`), the run of that step, whose end ends the claim (`endClaims`).
|
|
754
|
+
* 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.
|
|
755
|
+
*/
|
|
756
|
+
const claimHolder = (workflow: string, run: string): Effect.Effect<RunOf> =>
|
|
757
|
+
pipe(
|
|
758
|
+
records.parentOfRun(run),
|
|
759
|
+
Effect.map((parent) => {
|
|
760
|
+
const keeps = parent !== null && DECLARED.get(parent.workflow)?.steps().some((s) => s.name === parent.step && s.agentKeptUntilThisRunEnds === true) === true;
|
|
761
|
+
return keeps ? { run: parent.run, workflow: parent.workflow } : { run, workflow };
|
|
762
|
+
}),
|
|
763
|
+
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 })),
|
|
764
|
+
);
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* 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
|
|
768
|
+
* workflow having a number of agents it claims. so a subworkflow write C claims one on decompiles agents so while that
|
|
769
|
+
* task's own workflow is doing all these different things, some are agentic steps and deterministic steps but as that's
|
|
770
|
+
* going on decompile is down one agent."
|
|
548
771
|
*
|
|
549
|
-
* A
|
|
772
|
+
* A run of a workflow that claims agents (`agentsClaimedBy`) takes its claim at its first agent step, against the agents'
|
|
773
|
+
* limit of the workflow at the top of its run (`topOf`): Write C's against Decompile's. Its steps before it (a Pick, a
|
|
774
|
+
* 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
|
|
775
|
+
* agent step with its task named, to mark. From then it holds the claim through every step, agent and deterministic, and
|
|
776
|
+
* through a handover or a restart, until it ends (`endClaims`). A workflow with no agent step of its own that declares
|
|
777
|
+
* agents claims as it starts. Its agent steps never wait
|
|
778
|
+
* 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
|
|
779
|
+
* run that holds one takes none. With no claim free it ends (`endForWantOfAnAgent`). Where the claim is taken, a mark on
|
|
780
|
+
* its task as needing an agent has done its work and clears (`tasks.ts` `agentTaken`). A run that a sub-workflow step
|
|
781
|
+
* keeping its agent started (`agentKeptUntilThisRunEnds`) takes the claim for the run of that step (`claimHolder`), which
|
|
782
|
+
* holds it until it ends: that step's next call finds it held, and takes none.
|
|
550
783
|
*/
|
|
551
|
-
const
|
|
552
|
-
const
|
|
784
|
+
const claimAgentsOrEnd = (workflow: string, run: string, step: string): Effect.Effect<void, string> => Effect.gen(function* () {
|
|
785
|
+
const d = DECLARED.get(workflow);
|
|
786
|
+
const agents = d === undefined ? 0 : agentsClaimedBy(d);
|
|
787
|
+
if (agents === 0) return;
|
|
788
|
+
// A read that fails takes no second claim: the run goes on as one that holds its own, and that is said.
|
|
789
|
+
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));
|
|
790
|
+
if (held) return;
|
|
791
|
+
const top = yield* Effect.orElseSucceed(topOf(workflow, run), () => ({ run, workflow }));
|
|
792
|
+
const lock = CLAIMING.get(top.workflow) ?? Semaphore.makeUnsafe(1);
|
|
793
|
+
CLAIMING.set(top.workflow, lock);
|
|
794
|
+
const why = yield* lock.withPermits(1)(Effect.gen(function* () {
|
|
795
|
+
const slot = yield* agentSlotNow(workflow, run);
|
|
796
|
+
if (!slot.free) return slot.unavailable ?? slot.inUse ?? slot.why;
|
|
797
|
+
const limit = slot.limit ?? null;
|
|
798
|
+
const live = yield* Effect.orElseSucceed(runsOldestFirst([top.workflow]), () => [top.run]);
|
|
799
|
+
const holder = yield* claimHolder(workflow, run);
|
|
800
|
+
const taken = yield* Effect.catchTag(deps.claims.takeAgentClaim({ ...holder, top, agents, limit, liveTopRuns: live }), 'StorageError', (e) =>
|
|
801
|
+
Effect.as(Effect.logError(`[agents] ${workflow} run ${run}: its agent claim could not be recorded, so it goes on unrecorded: ${e.reason}`), 'not recorded' as const));
|
|
802
|
+
return taken === 'no room' ? agentsInUse(limit ?? agents) : null;
|
|
803
|
+
}));
|
|
804
|
+
if (why !== null) return yield* endForWantOfAnAgent({ top, workflow, run, step, why });
|
|
805
|
+
const task = yield* taskOfTop(top);
|
|
806
|
+
if (task !== null) yield* deps.tasks.agentTaken({ task, by: { workflow: top.workflow, run: top.run, step } });
|
|
807
|
+
});
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* BEFORE EACH AGENT CALL, A RUN THAT HOLDS ITS CLAIM ENDS WHERE NO AGENT CAN BE HAD NOW: the spending limit holds, or its
|
|
811
|
+
* top workflow's agents' limit was set to 0 (`AgentSlot` `unavailable`). The call before it finished; this one is not made,
|
|
812
|
+
* and the run gives its task back as one that could claim none (`endForWantOfAnAgent`). Every agent merely claimed ends no
|
|
813
|
+
* run, its own claim among them, and nor does a limit lowered to above 0: the claims held keep their agents to their ends.
|
|
814
|
+
*/
|
|
815
|
+
const beforeAgentCall = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, step: string): Effect.Effect<void, string> => Effect.gen(function* () {
|
|
553
816
|
const workflow = instance.workflow._tag;
|
|
554
|
-
// An agent is freed, and a limit set, on the workflow at the top of this run: its wakes are the ones this wait hears.
|
|
555
817
|
const top = yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }));
|
|
556
|
-
const
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
}
|
|
569
|
-
return;
|
|
570
|
-
}
|
|
571
|
-
if (slot.unavailable !== null && (yield* markedAsNeedingAnAgent(top, step, slot.unavailable))) {
|
|
572
|
-
console.log(`[agents] ${workflow} run ${instance.executionId} ended at its agent step: no agent can be had (${slot.unavailable}); its task goes to the back of its queue, marked as needing one`);
|
|
573
|
-
return yield* Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
|
|
574
|
-
}
|
|
575
|
-
if (id !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
|
|
576
|
-
waited = true;
|
|
577
|
-
if ((yield* deps.wakes.untilPickWoken({ workflow: heardOn, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
|
|
578
|
-
}
|
|
818
|
+
const slot = yield* agentSlotNow(workflow, instance.executionId);
|
|
819
|
+
if (!slot.free && slot.unavailable !== null) return yield* endForWantOfAnAgent({ top, workflow, run: instance.executionId, step, why: slot.unavailable });
|
|
820
|
+
});
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* 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
|
|
824
|
+
* an agent can be taken now. An interrupted run keeps them: it resumes, in this process or the next.
|
|
825
|
+
*/
|
|
826
|
+
const endClaims = (run: string, exit: Exit.Exit<unknown, unknown>): Effect.Effect<void> => Effect.gen(function* () {
|
|
827
|
+
if (!Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause)) return;
|
|
828
|
+
const ended = yield* recorded('end its agent claims', deps.claims.endAgentClaims({ run, outcome: Exit.isSuccess(exit) ? 'success' : 'failure' }));
|
|
829
|
+
for (const top of new Set((ended ?? []).map((c) => c.top.workflow))) deps.wakes.wakePicksOf(top, 'an agent claim ended');
|
|
579
830
|
});
|
|
580
831
|
|
|
581
832
|
/**
|
|
@@ -605,6 +856,9 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
605
856
|
if (Result.isFailure(read)) return yield* Effect.logError(`[steps] ${workflow}: the move to ${step} was not checked: ${read.failure.reason}`);
|
|
606
857
|
const last = read.success;
|
|
607
858
|
if (edgeDeclared(graph, last, step)) return;
|
|
859
|
+
// A sub-workflow step run again as its workflow ends, after its run above was suspended, takes its own open record up
|
|
860
|
+
// again (`defineSubWorkflow`): that is no move. Read as one, every such resume of Decompile's Write C was said to be undeclared.
|
|
861
|
+
if (last !== null && !last.failed && last.step === step && DECLARED.get(workflow)?.steps().some((s) => s.name === step && s.kind === 'sub-workflow') === true) return;
|
|
608
862
|
const move = `${workflow}: ${last === null ? RUN_STARTS : `${last.step}${last.failed ? ' (failed)' : ''}`} to ${step}`;
|
|
609
863
|
if (process.env.NODE_ENV === 'test') throw new Error(`a run took an edge its workflow does not declare: ${move}`);
|
|
610
864
|
if (!undeclaredSaid.has(move)) {
|
|
@@ -647,14 +901,14 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
647
901
|
let before: TreeHashes | null = null;
|
|
648
902
|
let recordId: number | null = null;
|
|
649
903
|
let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
|
|
650
|
-
|
|
651
|
-
|
|
904
|
+
// Its model, where it runs on one: its own, or what its workflows above or the app set (`settings.ts`), in code alone.
|
|
905
|
+
const model = step.runs === 'agentic' ? stepSetting({ declared: [...DECLARED.values()], app: deps.appSettings, stored: [] }, { workflow: instance.workflow._tag, step: step.name, name: 'model' }).value : null;
|
|
652
906
|
return Effect.acquireUseRelease(
|
|
653
907
|
Effect.flatMap(Effect.gen(function* () {
|
|
654
908
|
yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
|
|
655
909
|
yield* checkItem(instance.workflow._tag, instance.executionId, step.name, subject);
|
|
656
910
|
// 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.
|
|
657
|
-
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, ...(childRun === null ? {} : { resume: true as const }) }));
|
|
911
|
+
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 as const }) }));
|
|
658
912
|
if (id !== null && childRun !== null) yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
|
|
659
913
|
const beat = (step.runs === 'agentic') && id !== null ? setInterval(() => recordNow('its heartbeat', records.beatStepRun(id)), AGENT_BEAT_MS) : null;
|
|
660
914
|
recordId = id;
|
|
@@ -672,7 +926,9 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
672
926
|
return opened;
|
|
673
927
|
}))),
|
|
674
928
|
() => pipe(
|
|
675
|
-
|
|
929
|
+
// An agent step with no model set on it or above it stands down before it takes an agent (`NO_MODEL_STOOD_DOWN`).
|
|
930
|
+
(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 as never))
|
|
931
|
+
: (step.runs === 'agentic') ? Effect.andThen(claimAgentsOrEnd(instance.workflow._tag, instance.executionId, step.name), Effect.andThen(beforeAgentCall(instance, step.name), execute)) : execute,
|
|
676
932
|
// What it changed, on its record, and a change it named outside where it may write refuses the step.
|
|
677
933
|
Effect.tap(() => Effect.suspend(() => {
|
|
678
934
|
const earlier = before;
|
|
@@ -689,18 +945,10 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
689
945
|
})),
|
|
690
946
|
Effect.provideService(CurrentMeter, meter),
|
|
691
947
|
Effect.provideService(deps.CurrentStepUsage, meter),
|
|
692
|
-
(step.runs === 'agentic') ? Effect.provideService(AgentStep, { usage, report, touched: (inputs) => { toolInputs.push(...inputs); }, waiting: (why) => { if (recordId !== null) recordNow('say what it waits on', records.setStepWaiting({ id: recordId, waiting: why })); } }) : (e) => e,
|
|
948
|
+
(step.runs === 'agentic' && model !== null) ? Effect.provideService(AgentStep, { usage, report, model, touched: (inputs) => { toolInputs.push(...inputs); }, waiting: (why) => { if (recordId !== null) recordNow('say what it waits on', records.setStepWaiting({ id: recordId, waiting: why })); } }) : (e) => e,
|
|
693
949
|
) as Effect.Effect<A, E, Exclude<R2, AgentStep>>,
|
|
694
950
|
({ id, beat }, exit) => Effect.gen(function* () {
|
|
695
951
|
if (beat !== null) clearInterval(beat);
|
|
696
|
-
// An agent step that ran on a task marked as needing an agent clears the mark: it may need none now.
|
|
697
|
-
if (tookAnAgent && (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause))) {
|
|
698
|
-
const top = TOPS.get(instance.executionId) ?? { run: instance.executionId, workflow: instance.workflow._tag };
|
|
699
|
-
const task = yield* taskOfTop(top);
|
|
700
|
-
if (task !== null) yield* deps.tasks.agentStepRan({ task, by: { workflow: top.workflow, run: top.run, step: step.name } });
|
|
701
|
-
}
|
|
702
|
-
// Its agent slot is free for its workflow's next run waiting on one.
|
|
703
|
-
if ((step.runs === 'agentic')) deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
|
|
704
952
|
// An interrupted step is no move: the run does it again.
|
|
705
953
|
if (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause)) lastStepRan.set(instance.executionId, { step: step.name, failed: !Exit.isSuccess(exit) });
|
|
706
954
|
meterClosed(meter);
|
|
@@ -767,6 +1015,25 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
767
1015
|
},
|
|
768
1016
|
)));
|
|
769
1017
|
|
|
1018
|
+
/**
|
|
1019
|
+
* A RUN STARTS NO STEP IN A PROCESS HANDING ITS RUNS TO THE NEXT (`pick-wakes.ts` `releaseWaiting`): it suspends on a
|
|
1020
|
+
* durable clock, which the process that takes its shard next delivers, and that process replays it from its records and
|
|
1021
|
+
* runs the step. A step already running finishes where it is, an agent's call included. Left to the engine, the run was
|
|
1022
|
+
* abandoned without a reply, and the wake its sub-workflow step's workflow had sent it waited on that reply for ever: the
|
|
1023
|
+
* run's entity, and its shard, stayed in the old process until it was killed. Four runs of Decompile sat between steps so
|
|
1024
|
+
* 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
|
|
1025
|
+
* a later handover at the same step suspends the run again. What it gives keeps the activity's name, which a workflow's
|
|
1026
|
+
* graph may name the step by.
|
|
1027
|
+
*/
|
|
1028
|
+
const handedOverBeforeStep = <S extends Schema.Constraint, E extends Schema.Constraint, R2>(activity: Activity.Activity<S, E, R2>) => Object.assign(Effect.andThen(Effect.suspend(() => {
|
|
1029
|
+
if (!deps.wakes.handingOver()) return Effect.void;
|
|
1030
|
+
const self = deps.thisProcess();
|
|
1031
|
+
return Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => Effect.andThen(
|
|
1032
|
+
Effect.sync(() => console.log(`[handover] ${instance.workflow._tag} run ${instance.executionId} suspended before ${activity.name}: the next process runs it`)),
|
|
1033
|
+
DurableClock.sleep({ name: `handed over by pid ${self.pid} started at ${self.startedAt}, before ${activity.name}`, duration: Duration.seconds(1), inMemoryThreshold: Duration.zero }),
|
|
1034
|
+
));
|
|
1035
|
+
}), activity), { name: activity.name });
|
|
1036
|
+
|
|
770
1037
|
/** One run of a workflow picks at a time: its choice is on its step record before the next reads what is taken. */
|
|
771
1038
|
const pickingOneAtATime = <A, E, R2>(workflow: string, pick: Effect.Effect<A, E, R2>): Effect.Effect<A, E, R2> => {
|
|
772
1039
|
const lock = PICKING.get(workflow) ?? Semaphore.makeUnsafe(1);
|
|
@@ -783,7 +1050,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
783
1050
|
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`}`;
|
|
784
1051
|
}),
|
|
785
1052
|
Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)),
|
|
786
|
-
Effect.map((queued) => `no task it can claim (${queued}); it waits for a task returned to its queue, a new item, a run ending or a limit change`),
|
|
1053
|
+
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`),
|
|
787
1054
|
);
|
|
788
1055
|
|
|
789
1056
|
/**
|
|
@@ -856,17 +1123,25 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
856
1123
|
readonly picked?: (a: A) => boolean;
|
|
857
1124
|
/** Why it ended as it did, from its result, in a line: what its outcomes are counted by. `standardReason` where absent. */
|
|
858
1125
|
readonly reason?: (a: A) => string | null;
|
|
1126
|
+
/** How many days its records are kept, where not what its workflow keeps (`settings.ts`). */
|
|
1127
|
+
readonly retentionDays?: number;
|
|
1128
|
+
/** How many of its newest runs keep their records however old, where not what is set above it (`settings.ts`). */
|
|
1129
|
+
readonly keepAtLeastRuns?: number;
|
|
1130
|
+
/** For an agent step: the model it runs on, where not its workflow's (`settings.ts`). */
|
|
1131
|
+
readonly model?: string;
|
|
859
1132
|
}) => {
|
|
1133
|
+
if (d.model !== undefined && d.runs !== 'agentic') throw new Error(`${d.name} sets a model, and runs ${d.runs}: only an agent step runs on a model`);
|
|
860
1134
|
const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
|
|
861
1135
|
const declaration: StepDeclaration = {
|
|
862
1136
|
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 }),
|
|
863
1137
|
...(writes.length === 0 ? {} : { writes }),
|
|
1138
|
+
...checkedSettings({ what: d.name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
|
|
864
1139
|
source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
|
|
865
1140
|
};
|
|
866
|
-
|
|
1141
|
+
const step = {
|
|
867
1142
|
...declaration,
|
|
868
1143
|
run: <E, R2>(execute: Effect.Effect<A, E, R2>, options?: { readonly call?: number; readonly subject?: string }) =>
|
|
869
|
-
Activity.make({
|
|
1144
|
+
handedOverBeforeStep(Activity.make({
|
|
870
1145
|
name: options?.call === undefined ? d.name : `${d.name} ${options.call}`,
|
|
871
1146
|
success: d.success,
|
|
872
1147
|
error: Schema.String,
|
|
@@ -876,8 +1151,11 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
876
1151
|
Effect.retry({ while: deps.isTransientFailure, times: 10, schedule: Schedule.spaced('3 seconds') }),
|
|
877
1152
|
Effect.mapError(describeFailure),
|
|
878
1153
|
),
|
|
879
|
-
}),
|
|
1154
|
+
})),
|
|
880
1155
|
};
|
|
1156
|
+
// Its code as loaded now, for its workflow's version (`versionOf`): its file, and an agent step's prompt file.
|
|
1157
|
+
STEP_CODE.set(step, [codeOf(d.at), ...(d.prompt === undefined ? [] : [codeOf(path.join(deps.sourceRoot, d.prompt.path))])]);
|
|
1158
|
+
return step;
|
|
881
1159
|
};
|
|
882
1160
|
|
|
883
1161
|
/**
|
|
@@ -918,7 +1196,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
918
1196
|
*
|
|
919
1197
|
* the page shows the run above in this step, and the workflow's own view shows its steps and what they cost;
|
|
920
1198
|
* the workflow's steps work on the item the run above works on, with no code naming it (`StepRecords.openStepRun`);
|
|
921
|
-
* its agent
|
|
1199
|
+
* its agent claim counts against the agents' limit of the workflow at the top, and its steps stand down with its run (`topOf`).
|
|
922
1200
|
*
|
|
923
1201
|
* 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
|
|
924
1202
|
* limit on a workflow used only as a step would fail the steps of runs already going.
|
|
@@ -931,8 +1209,17 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
931
1209
|
/** `import.meta.path`, for its link where its workflow is not defined yet. */
|
|
932
1210
|
readonly at: string;
|
|
933
1211
|
readonly success: Schema.Codec<A, unknown>;
|
|
1212
|
+
/** How many days the records of this step and of every step under it are kept, where not this workflow's (`settings.ts`). */
|
|
1213
|
+
readonly retentionDays?: number;
|
|
1214
|
+
/** How many of its newest runs keep their records however old, where not what is set above it (`settings.ts`). */
|
|
1215
|
+
readonly keepAtLeastRuns?: number;
|
|
1216
|
+
/** The model every agent step under it runs on, where not this workflow's (`settings.ts`). */
|
|
1217
|
+
readonly model?: string;
|
|
1218
|
+
/** The agent its workflow's run claims is held by this run until it ends (`StepDeclaration.agentKeptUntilThisRunEnds`). */
|
|
1219
|
+
readonly agentKeptUntilThisRunEnds?: true;
|
|
934
1220
|
}) => {
|
|
935
1221
|
const child = d.workflow._tag;
|
|
1222
|
+
refuseSystem(child, 'no workflow of the app has it as a step');
|
|
936
1223
|
// What its workflow gave is what the step declares, or the step fails saying so: no result is taken on trust.
|
|
937
1224
|
const isDeclared = Schema.is(d.success);
|
|
938
1225
|
const given = (result: unknown): Effect.Effect<A, string> => (isDeclared(result) ? Effect.succeed(result) : Effect.fail(`${child} gave a result that is not what this step declares`));
|
|
@@ -954,6 +1241,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
954
1241
|
);
|
|
955
1242
|
const declaration: StepDeclaration = {
|
|
956
1243
|
name, runs: null, kind: 'sub-workflow', workflow: child,
|
|
1244
|
+
...(d.agentKeptUntilThisRunEnds === true ? { agentKeptUntilThisRunEnds: true as const } : {}),
|
|
1245
|
+
...checkedSettings({ what: name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
|
|
957
1246
|
description: DECLARED.get(child)?.description ?? `Runs ${child}.`,
|
|
958
1247
|
source: DECLARED.get(child)?.source ?? { path: sourcePath(d.at), anchor: `'${child}'` },
|
|
959
1248
|
agentUnder: () => {
|
|
@@ -969,7 +1258,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
969
1258
|
return {
|
|
970
1259
|
...declaration,
|
|
971
1260
|
run: (payload: P, options?: { readonly call?: number }) =>
|
|
972
|
-
Activity.make({
|
|
1261
|
+
handedOverBeforeStep(Activity.make({
|
|
973
1262
|
name: options?.call === undefined ? name : `${name} ${options.call}`,
|
|
974
1263
|
success: d.success,
|
|
975
1264
|
error: Schema.String,
|
|
@@ -979,10 +1268,48 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
979
1268
|
measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(startedAndWaitedFor(payload), given), childRun))),
|
|
980
1269
|
Effect.mapError(describeFailure),
|
|
981
1270
|
),
|
|
982
|
-
}),
|
|
1271
|
+
})),
|
|
983
1272
|
};
|
|
984
1273
|
};
|
|
985
1274
|
|
|
1275
|
+
/**
|
|
1276
|
+
* A STEP THAT IS ANOTHER WORKFLOW, ON ITS OWN TRIGGER. Alex, 2026-11-21: "just one fucking workflow that has steps some
|
|
1277
|
+
* of which can be other workflows". A workflow whose steps are workflows that start themselves (on their queues, their
|
|
1278
|
+
* 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
|
|
1279
|
+
* it starts them, so it has no runs of its own: its runs, agents and costs are theirs, added up (`isMadeOfWorkflows`).
|
|
1280
|
+
* Define `workflow` before the workflow that has it as a step.
|
|
1281
|
+
*/
|
|
1282
|
+
const defineWorkflowStep = (workflow: string): StepDeclaration => {
|
|
1283
|
+
refuseSystem(workflow, 'no workflow of the app has it as a step');
|
|
1284
|
+
const d = DECLARED.get(workflow);
|
|
1285
|
+
if (d === undefined) throw new Error(`${workflow} is a step of a workflow defined before it: define ${workflow} first`);
|
|
1286
|
+
return { name: workflow, runs: null, kind: 'sub-workflow', workflow, runsOnItsOwnTrigger: true, description: d.description, source: d.source, agentUnder: () => d.steps().some(stepUsesAnAgent) };
|
|
1287
|
+
};
|
|
1288
|
+
|
|
1289
|
+
/** A workflow and every workflow under it, through each step that is a workflow. */
|
|
1290
|
+
const withWorkflowsUnder = (name: string, seen: Set<string> = new Set()): ReadonlySet<string> => {
|
|
1291
|
+
if (seen.has(name)) return seen;
|
|
1292
|
+
seen.add(name);
|
|
1293
|
+
for (const s of DECLARED.get(name)?.steps() ?? []) if (s.workflow !== undefined) withWorkflowsUnder(s.workflow, seen);
|
|
1294
|
+
return seen;
|
|
1295
|
+
};
|
|
1296
|
+
|
|
1297
|
+
/**
|
|
1298
|
+
* THE STEP GRAPH OF A WORKFLOW MADE OF WORKFLOWS, from what feeds what (`WorkflowDeclaration.fedBy`): a step follows each
|
|
1299
|
+
* of its fellow steps whose results become its tasks, at any depth under each; one none of them feeds is where work
|
|
1300
|
+
* enters it, and one that feeds none of them is where its work leaves. The feeds are declared once, on the workflow fed.
|
|
1301
|
+
*/
|
|
1302
|
+
const graphOfFeeds = (steps: ReadonlyArray<string>): ReadonlyArray<StepEdge> => {
|
|
1303
|
+
const under = new Map(steps.map((s) => [s, withWorkflowsUnder(s)]));
|
|
1304
|
+
const feeds = (from: string, to: string) => from !== to && [...under.get(to)!].some((w) => (DECLARED.get(w)?.fedBy ?? []).some((f) => under.get(from)!.has(f)));
|
|
1305
|
+
const edges = steps.flatMap((to) => steps.filter((from) => feeds(from, to)).map((from): StepEdge => ({ from, to, when: `its results become ${to}'s tasks` })));
|
|
1306
|
+
return [
|
|
1307
|
+
...steps.filter((s) => !edges.some((e) => e.to === s)).map((s): StepEdge => ({ from: RUN_STARTS, to: s, when: 'on its own trigger' })),
|
|
1308
|
+
...edges,
|
|
1309
|
+
...steps.filter((s) => !edges.some((e) => e.from === s)).map((s): StepEdge => ({ from: s, to: RUN_ENDS, when: 'what it finishes leaves here' })),
|
|
1310
|
+
];
|
|
1311
|
+
};
|
|
1312
|
+
|
|
986
1313
|
/** Every workflow defined so far, in the order defined. */
|
|
987
1314
|
const declaredWorkflows = (): ReadonlyArray<Declaration> => [...DECLARED.values()];
|
|
988
1315
|
|
|
@@ -1018,8 +1345,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1018
1345
|
const queueNow = (input: { readonly workflow: string; readonly run: string }): Effect.Effect<ReadonlyArray<TaskSummary>, unknown, R> => Effect.gen(function* () {
|
|
1019
1346
|
yield* readTaskInputs(input.workflow);
|
|
1020
1347
|
const queue = queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
|
|
1021
|
-
// While no agent
|
|
1022
|
-
return (yield*
|
|
1348
|
+
// While no agent is free, a task marked as needing one is passed over (`whyNoAgentIsFree`).
|
|
1349
|
+
return (yield* whyNoAgentIsFree(input.workflow)) === null ? queue : queue.filter((t) => deps.tasks.passedOverNow(t) === null);
|
|
1023
1350
|
});
|
|
1024
1351
|
|
|
1025
1352
|
/**
|
|
@@ -1029,7 +1356,9 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1029
1356
|
* as running: its trigger starts none (`keep-running.ts` `planRunStarts`), and a Pick that found nothing ends its run
|
|
1030
1357
|
* rather than wait (`untilPicked`). An agent to be had (a limit lifted, the spending limit no longer holding), a mark
|
|
1031
1358
|
* 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
|
|
1032
|
-
* step needs none. Read where it cannot be, it says nothing, and runs start and wait as before.
|
|
1359
|
+
* step needs none. Read where it cannot be, it says nothing, and runs start and wait as before. Every agent merely in use
|
|
1360
|
+
* 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
|
|
1361
|
+
* its agent step with none free gives its task back, and a Pick with nothing it can take waits for a claim to end.
|
|
1033
1362
|
*/
|
|
1034
1363
|
const whyNoRunCanTakeWork = (workflow: string): Effect.Effect<string | null, never, R> => Effect.gen(function* () {
|
|
1035
1364
|
// Its tasks' inputs, a read of every task's, are read again only where the inputs its last Pick read leave no work.
|
|
@@ -1052,9 +1381,11 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1052
1381
|
Effect.orElseSucceed(() => null),
|
|
1053
1382
|
);
|
|
1054
1383
|
|
|
1055
|
-
/**
|
|
1056
|
-
|
|
1057
|
-
|
|
1384
|
+
/**
|
|
1385
|
+
* A workflow: what it states about itself, then `Workflow.make`'s own name and options. `system` is the platform defining
|
|
1386
|
+
* one of its own (`system-workflows.ts`); an app's definition of one of those names is refused (`refuseSystem`).
|
|
1387
|
+
*/
|
|
1388
|
+
const defineWorkflowAs = (system: boolean) => <Result = never>(d: {
|
|
1058
1389
|
readonly description: string;
|
|
1059
1390
|
/** `import.meta.path`, for its link. */
|
|
1060
1391
|
readonly at: string;
|
|
@@ -1065,18 +1396,32 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1065
1396
|
readonly items?: () => Effect.Effect<ReadonlyArray<string>, unknown, R>;
|
|
1066
1397
|
readonly picksQueueHead?: true;
|
|
1067
1398
|
/**
|
|
1068
|
-
* The workflows whose results become its tasks: the
|
|
1399
|
+
* The workflows whose results become its tasks: what `graphOfFeeds` draws between the steps of a workflow made of workflows. A workflow
|
|
1069
1400
|
* used as a step of another needs none: it is drawn inside that one.
|
|
1070
1401
|
*/
|
|
1071
1402
|
readonly fedBy?: ReadonlyArray<string>;
|
|
1403
|
+
/** The step that does its main work, for a workflow made of workflows (`WorkflowDeclaration.mainStep`). */
|
|
1404
|
+
readonly mainStep?: string;
|
|
1072
1405
|
/** Its step graph: which step can follow which, and when. */
|
|
1073
1406
|
readonly graph?: () => ReadonlyArray<StepEdge>;
|
|
1074
1407
|
/** What it runs on: its trigger starts a run only when they changed (`runIfInputsChanged`). */
|
|
1075
1408
|
readonly inputs?: WorkflowInputs<R>;
|
|
1076
1409
|
/** What each of its tasks runs on (`WorkflowDeclaration.taskInputs`); its Pick reads its queue with them (`queueNow`). */
|
|
1077
1410
|
readonly taskInputs?: () => Effect.Effect<ReadonlyMap<string, TaskInputs>, unknown, R>;
|
|
1411
|
+
/** How many days its runs' records are kept, for every step under it that sets none (`settings.ts`); 7 at the top where none is set. */
|
|
1412
|
+
readonly retentionDays?: number;
|
|
1413
|
+
/** How many of its newest runs keep their records however old, where not what is set above it (`settings.ts`). */
|
|
1414
|
+
readonly keepAtLeastRuns?: number;
|
|
1415
|
+
/** The model every agent step under it runs on, where the step sets none (`settings.ts`). */
|
|
1416
|
+
readonly model?: string;
|
|
1417
|
+
/** How many agents each of its runs claims, held to its end, where more than its agent step's one (`agentsClaimedBy`). */
|
|
1418
|
+
readonly agentsClaimed?: number;
|
|
1078
1419
|
} & WorkflowItem<Result>): typeof Workflow.make =>
|
|
1079
1420
|
((name: string, options: Parameters<typeof Workflow.make>[1]) => {
|
|
1421
|
+
if (!system) refuseSystem(name, 'the app defines no workflow of its name');
|
|
1422
|
+
if (d.agentsClaimed !== undefined && !(Number.isInteger(d.agentsClaimed) && d.agentsClaimed >= 1)) throw new Error(`${name} claims ${d.agentsClaimed} agents: a workflow claims a whole number of them, 1 or more, or states none`);
|
|
1423
|
+
// A main step is one of a workflow made of workflows, whose steps (`defineWorkflowStep`) are defined before it, so read now.
|
|
1424
|
+
if (d.mainStep !== undefined && !(isMadeOfWorkflows(d) && d.steps().some((s) => s.name === d.mainStep))) throw new Error(`${name}'s main step ${d.mainStep} is not one of its steps, each a workflow on its own trigger`);
|
|
1080
1425
|
// The one place a workflow's own types do not matter: every workflow passes through here the same way.
|
|
1081
1426
|
const workflow: RunnableWorkflow = Workflow.make(name, options) as RunnableWorkflow;
|
|
1082
1427
|
/**
|
|
@@ -1101,36 +1446,52 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1101
1446
|
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`); });
|
|
1102
1447
|
return Effect.andThen(say, startOptions?.discard === true ? workflow.executionId(payload) : Effect.fail(new RunLimitReached({ workflow: name, limit: gate.limit })));
|
|
1103
1448
|
});
|
|
1449
|
+
WORKFLOW_CODE.set(name, codeOf(d.at));
|
|
1104
1450
|
DECLARED.set(name, {
|
|
1105
|
-
name,
|
|
1451
|
+
name, description: d.description, steps: d.steps,
|
|
1106
1452
|
...(d.graph === undefined ? {} : { graph: d.graph }),
|
|
1107
1453
|
source: { path: sourcePath(d.at), anchor: `'${name}'` },
|
|
1108
1454
|
...(d.pending === undefined ? {} : { pending: d.pending }),
|
|
1109
1455
|
...(d.items === undefined ? {} : { items: d.items }),
|
|
1110
1456
|
...(d.picksQueueHead === undefined ? {} : { picksQueueHead: d.picksQueueHead }),
|
|
1111
1457
|
...(d.fedBy === undefined ? {} : { fedBy: d.fedBy }),
|
|
1458
|
+
...(d.mainStep === undefined ? {} : { mainStep: d.mainStep }),
|
|
1112
1459
|
...(d.inputs === undefined ? {} : { inputs: d.inputs }),
|
|
1113
1460
|
...(d.taskInputs === undefined ? {} : { taskInputs: d.taskInputs }),
|
|
1461
|
+
...checkedSettings({ what: name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
|
|
1114
1462
|
item: d.item,
|
|
1115
1463
|
finishedWord: d.item === null ? null : d.finishedWord,
|
|
1116
1464
|
gate: d.item === null ? null : (d.gate ?? null),
|
|
1117
1465
|
start: (run) => gatedExecute({ run }, { discard: true }),
|
|
1118
1466
|
startOn: (payload, options) => Effect.asVoid(options.wait ? gatedExecute(payload) : gatedExecute(payload, { discard: true })),
|
|
1119
1467
|
executionIdOf: (payload) => workflow.executionId(payload),
|
|
1468
|
+
...(system ? { system: true as const } : {}),
|
|
1469
|
+
...(d.agentsClaimed === undefined ? {} : { agentsClaimed: d.agentsClaimed }),
|
|
1120
1470
|
});
|
|
1471
|
+
if (system) SYSTEM.add(name);
|
|
1121
1472
|
const toLayer = workflow.toLayer.bind(workflow);
|
|
1122
1473
|
// Its start as a step of another workflow, which no run limit of its own gates (`defineSubWorkflow`).
|
|
1123
1474
|
STARTS_AS_A_STEP.set(name, execute as (payload: unknown) => Effect.Effect<unknown, unknown, unknown>);
|
|
1124
1475
|
Object.assign(workflow, { execute: gatedExecute });
|
|
1125
|
-
//
|
|
1476
|
+
// Read when a run starts or ends, once every workflow is declared: whether this one's tasks are its runs.
|
|
1477
|
+
const runsAreTasks = (): boolean => { const me = DECLARED.get(name); return me !== undefined && tasksAreRuns(me, [...DECLARED.values()]); };
|
|
1478
|
+
// A run claims at its first agent step (`measured`); one with no agent step of its own that declares agents claims as it starts.
|
|
1479
|
+
const claimsAsItStarts = (): boolean => { const me = DECLARED.get(name); return me !== undefined && agentsClaimedBy(me) > 0 && !me.steps().some((s) => s.runs === 'agentic'); };
|
|
1480
|
+
// Every run of every workflow ends here: its items' outcomes are recorded, and the next run can start at once. A
|
|
1481
|
+
// 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
|
|
1482
|
+
// that claims agents takes its claim at its first agent step, or here where it has none, and ends it as it ends
|
|
1483
|
+
// (`claimAgentsOrEnd`, `endClaims`).
|
|
1126
1484
|
return Object.assign(workflow, {
|
|
1127
1485
|
toLayer: (execute: WorkflowBody) =>
|
|
1128
|
-
toLayer((payload, executionId) => Effect.onExit(execute(payload, executionId), (exit) => Effect.flatMap(
|
|
1486
|
+
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(
|
|
1129
1487
|
// 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)
|
|
1130
1488
|
// left nothing new for the next. Taken when it picked, 490 Tests ran on 107 functions in 41 minutes (2026-11-14).
|
|
1131
1489
|
!Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause) || d.item === null ? Effect.succeed(null) : Effect.orElseSucceed(readTaskInputs(name), () => null),
|
|
1132
1490
|
(leftWith) => Effect.gen(function* () {
|
|
1133
1491
|
const interrupted = !Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause);
|
|
1492
|
+
const me = DECLARED.get(name);
|
|
1493
|
+
// Its own claim, or one a sub-workflow step of it took for it (`agentKeptUntilThisRunEnds`), ends with it.
|
|
1494
|
+
if (me !== undefined && (agentsClaimedBy(me) > 0 || me.steps().some((s) => s.agentKeptUntilThisRunEnds === true))) yield* endClaims(executionId, exit);
|
|
1134
1495
|
const runItem = yield* recorded('read its item', records.subjectOfRun(executionId));
|
|
1135
1496
|
const inputsLeft = (subject: string | null): string | null => {
|
|
1136
1497
|
const item = subject ?? runItem;
|
|
@@ -1146,6 +1507,17 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1146
1507
|
yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: null, outcome, finished: false, inputs: inputsLeft(null), blocked: null });
|
|
1147
1508
|
}
|
|
1148
1509
|
}
|
|
1510
|
+
// A RUN'S OWN TASK: done when it succeeds; blocked when it fails or stands down, with why in words the page
|
|
1511
|
+
// counts by (the step it failed at, or the stand-down's reason), the failure itself on the outcome note.
|
|
1512
|
+
if (!interrupted && runsAreTasks()) {
|
|
1513
|
+
const failure = Exit.isSuccess(exit) ? null : Cause.squash(exit.cause);
|
|
1514
|
+
const stoodDown = failure !== null && isStoodDown(failure);
|
|
1515
|
+
yield* deps.tasks.appendOutcome({
|
|
1516
|
+
workflow: name, run: executionId, subject: executionId, finished: failure === null, inputs: null,
|
|
1517
|
+
outcome: failure === null ? 'succeeded' : stoodDown ? STOOD_DOWN_OUTCOME : `failed: ${startAndEnd(describeFailure(failure), { cap: 1000, end: 400, what: 'the failure' })}`,
|
|
1518
|
+
blocked: failure === null ? null : stoodDown ? String(failure) : `failed at ${lastStepRan.get(executionId)?.step ?? 'its first step'}`,
|
|
1519
|
+
});
|
|
1520
|
+
}
|
|
1149
1521
|
// What it ran on gave this result, which stands until its inputs change. Only a run its trigger started on its
|
|
1150
1522
|
// inputs has a record to end.
|
|
1151
1523
|
if (d.inputs !== undefined) {
|
|
@@ -1161,9 +1533,10 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1161
1533
|
// Its claim and its item are free now for its workflow's other runs, once the engine has stored its end. Only its
|
|
1162
1534
|
// own: about 25 short runs end a minute, and waking every Pick on each re-read every task twice each time.
|
|
1163
1535
|
setTimeout(() => deps.wakes.wakePicksOf(name, 'one of its runs ended'), 1000);
|
|
1164
|
-
})))),
|
|
1536
|
+
}))))),
|
|
1165
1537
|
});
|
|
1166
1538
|
}) as typeof Workflow.make;
|
|
1539
|
+
const defineWorkflow = defineWorkflowAs(false);
|
|
1167
1540
|
|
|
1168
1541
|
/**
|
|
1169
1542
|
* RUNS A WORKFLOW ON `payload` ONLY WHEN ITS INPUTS CHANGED since its last successful run: it reads their fingerprint, and
|
|
@@ -1197,24 +1570,24 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1197
1570
|
* returned to the queue that the candidates do not hold.
|
|
1198
1571
|
*/
|
|
1199
1572
|
const pickOrder = <C>(input: { readonly workflow: string; readonly run: string; readonly candidates: ReadonlyArray<C>; readonly subjectOf: (c: C) => string; readonly fromItem?: (item: string) => C | null }): Effect.Effect<ReadonlyArray<C>, StorageError> =>
|
|
1200
|
-
Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }),
|
|
1573
|
+
Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), noAgentFree: whyNoAgentIsFree(input.workflow) }), ({ tasks, noAgentFree }) =>
|
|
1201
1574
|
inPickOrder({
|
|
1202
1575
|
candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }),
|
|
1203
|
-
// While no agent
|
|
1204
|
-
...(
|
|
1576
|
+
// While no agent is free, a task marked as needing one is passed over (`whyNoAgentIsFree`).
|
|
1577
|
+
...(noAgentFree === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => deps.tasks.passedOverNow(t) !== null).map((t) => t.ref.item)) }),
|
|
1205
1578
|
}));
|
|
1206
1579
|
|
|
1207
1580
|
/**
|
|
1208
1581
|
* 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
|
|
1209
1582
|
* the other heavy jobs), `start` leaves it to the engine.
|
|
1210
1583
|
*/
|
|
1211
|
-
const
|
|
1212
|
-
// One step of the project's code: no agent, and no single item.
|
|
1213
|
-
states: { readonly
|
|
1584
|
+
const oneStepWorkflowAs = (system: boolean) => <A, E, R2>(
|
|
1585
|
+
// One step of the project's code: no agent, and no single item. `reason` is what its record says it did (`defineStep`).
|
|
1586
|
+
states: { readonly description: string; readonly stepDescription: string; readonly at: string; readonly writes?: ReadonlyArray<string>; readonly inputs?: WorkflowInputs<R>; readonly reason?: (a: A) => string | null },
|
|
1214
1587
|
name: string, step: string, success: Schema.Codec<A, unknown>, execute: Effect.Effect<A, E, R2>,
|
|
1215
1588
|
) => {
|
|
1216
|
-
const theStep = defineStep({ name: step, runs: 'deterministic', shared: true, description: states.stepDescription, at: states.at, success, ...(states.writes === undefined ? {} : { writes: states.writes }) });
|
|
1217
|
-
const workflow =
|
|
1589
|
+
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 }) });
|
|
1590
|
+
const workflow = defineWorkflowAs(system)({ description: states.description, at: states.at, steps: () => [theStep], item: null, ...(states.inputs === undefined ? {} : { inputs: states.inputs }),
|
|
1218
1591
|
graph: () => [{ from: RUN_STARTS, to: step, when: 'each turn' }, { from: step, to: RUN_ENDS, when: 'always' }] })(name, {
|
|
1219
1592
|
payload: { turn: Schema.Number },
|
|
1220
1593
|
idempotencyKey: ({ turn }) => String(turn),
|
|
@@ -1228,12 +1601,16 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1228
1601
|
start: (turn: number) => Effect.asVoid(runIfInputsChanged({ workflow: name, payload: { turn }, wait: false })),
|
|
1229
1602
|
};
|
|
1230
1603
|
};
|
|
1604
|
+
const oneStepWorkflow = oneStepWorkflowAs(false);
|
|
1231
1605
|
|
|
1232
1606
|
return {
|
|
1233
|
-
defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
|
|
1607
|
+
defineStep, defineItemTest, defineSubWorkflow, defineWorkflowStep, graphOfFeeds, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
|
|
1234
1608
|
eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
|
|
1235
|
-
runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs,
|
|
1609
|
+
runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, whyNoAgentIsFree, whyNoRunCanTakeWork, versionOf, agentClaimsNow,
|
|
1610
|
+
/** The platform's own one-step workflows are defined by this (`system-workflows.ts`); `createWorkflowPlatform` keeps it from the app. */
|
|
1611
|
+
oneStepSystemWorkflow: oneStepWorkflowAs(true),
|
|
1236
1612
|
};
|
|
1237
1613
|
};
|
|
1238
1614
|
|
|
1239
|
-
|
|
1615
|
+
/** The definer as an app has it: every way to define its own workflows, none to define the platform's. */
|
|
1616
|
+
export type Steps<R> = Omit<ReturnType<typeof makeSteps<R>>, 'oneStepSystemWorkflow'>;
|