@jive-sh/workflow-platform 0.5.2 → 0.6.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 +50 -5
- package/dist/dashboard/queue-table.js +10 -2
- package/dist/dashboard/queue-table.js.map +1 -1
- package/dist/dashboard/spending-words.js +32 -0
- package/dist/dashboard/spending-words.js.map +1 -0
- package/dist/index.js +13 -4
- package/dist/index.js.map +1 -1
- package/dist/project.js +0 -4
- package/dist/project.js.map +1 -1
- package/dist/queue-counts.js +7 -1
- package/dist/queue-counts.js.map +1 -1
- package/dist/spending-limit.js +87 -0
- package/dist/spending-limit.js.map +1 -0
- package/dist/steps.js +125 -14
- package/dist/steps.js.map +1 -1
- package/dist/storage/budgets.js +27 -2
- package/dist/storage/budgets.js.map +1 -1
- package/dist/storage/sqlite-store.js +13 -2
- package/dist/storage/sqlite-store.js.map +1 -1
- package/dist/storage/task-store.js +10 -1
- package/dist/storage/task-store.js.map +1 -1
- package/dist/tasks.js +35 -5
- package/dist/tasks.js.map +1 -1
- package/dist/views/format.js +2 -0
- package/dist/views/format.js.map +1 -1
- package/dist/views/runs-now.js +12 -0
- package/dist/views/runs-now.js.map +1 -1
- package/dist/views/workflows-view.js +9 -2
- package/dist/views/workflows-view.js.map +1 -1
- package/package.json +1 -1
- package/src/dashboard/dashboard.css +5 -0
- package/src/dashboard/queue-bar.tsx +5 -5
- package/src/dashboard/queue-table.ts +17 -3
- package/src/dashboard/spending-limit-control.tsx +50 -0
- package/src/dashboard/spending-words.ts +50 -0
- package/src/dashboard/workflow-dag.tsx +1 -1
- package/src/dashboard/workflow-drilldown.tsx +5 -5
- package/src/dashboard/workflows-dashboard.tsx +28 -3
- package/src/index.ts +13 -4
- package/src/project.ts +35 -0
- package/src/queue-counts.ts +8 -1
- package/src/spending-limit.ts +155 -0
- package/src/steps.ts +140 -19
- package/src/storage/budgets.ts +34 -2
- package/src/storage/sqlite-store.ts +14 -3
- package/src/storage/task-store.ts +17 -1
- package/src/tasks.ts +43 -5
- package/src/views/format.ts +3 -0
- package/src/views/runs-now.ts +4 -0
- package/src/views/workflows-view.ts +27 -4
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE SPENDING LIMIT: ONE SETTING FOR THE WHOLE ACCOUNT, "AGENTS STOP AT X% OF THE WEEK". Alex, 2026-11-20: "ideally the
|
|
3
|
+
* workflow platform offers a configurable spending limit", and, of this design, "yes to building the spending limit".
|
|
4
|
+
*
|
|
5
|
+
* While the project's newest good reading of its week (`WorkflowProject.weekUsage`) is at or past X, every agent step of
|
|
6
|
+
* every workflow waits before its agent call, as it waits at an agents' limit of 0 (`steps.ts` `untilAgentSlot`), its record
|
|
7
|
+
* saying why in words (`spendingWait`). An agent call already going is never cut off. The steps go on by themselves once a
|
|
8
|
+
* reading is below X, which the week's reset brings: the project tells the platform of each reading it takes
|
|
9
|
+
* (`readingTaken`), and a verdict that changed wakes every waiting step. None is set: X is 95 (`DEFAULT_SPENDING_LIMIT_PERCENT`).
|
|
10
|
+
*
|
|
11
|
+
* IT JUDGES THE ACCOUNT'S WEEK, NOT A COUNT OF TOKENS, because the week is the one figure that also counts spending the
|
|
12
|
+
* platform cannot see: agent threads run by hand, outside any workflow, which no step record holds. They were 73% of the
|
|
13
|
+
* spending of the week that ran out on 2026-11-01, 57 hours before its reset (the first project's `usage/pace.ts`).
|
|
14
|
+
*
|
|
15
|
+
* A READING THAT FAILS OR GROWS OLD NEVER LIFTS IT. The rule judges the newest good reading, however old, so a hold stands
|
|
16
|
+
* until a good reading below X, and a page says the reading is stale and why. That holds past the reset the reading named
|
|
17
|
+
* too: with every read failing, agents wait until one succeeds, rather than spend on a week nobody can see. A reading that
|
|
18
|
+
* cannot be read at all holds every agent step, as limits that cannot be read hold their runs. With no good reading yet
|
|
19
|
+
* there is nothing to judge, and nothing is held. A project that reads no week has no spending limit.
|
|
20
|
+
*/
|
|
21
|
+
import { Effect, pipe, Result } from 'effect';
|
|
22
|
+
import type { PickWakes } from './pick-wakes';
|
|
23
|
+
import type { WeekUsage, WeekUsageNow, WeekUsageReading } from './project';
|
|
24
|
+
import { SET_SPENDING_LIMIT_SQL, type LimitStore, type StoredSpendingLimit } from './storage/budgets';
|
|
25
|
+
import type { StorageError } from './storage/storage-error';
|
|
26
|
+
import { percentCut } from './views/format';
|
|
27
|
+
|
|
28
|
+
/** The percent of the week at which agents stop where none is set. */
|
|
29
|
+
export const DEFAULT_SPENDING_LIMIT_PERCENT = 95;
|
|
30
|
+
|
|
31
|
+
/** The spending limit against the newest reading of the week, for a page and for the rule. */
|
|
32
|
+
export interface SpendingLimitState {
|
|
33
|
+
/** The percent of the week at which agents stop. */
|
|
34
|
+
readonly limitPercent: number;
|
|
35
|
+
/** When it was set, unix seconds; none while it is the default. */
|
|
36
|
+
readonly setAt: number | null;
|
|
37
|
+
/** The newest good reading, which the verdict rests on; none before the first. */
|
|
38
|
+
readonly reading: WeekUsageReading | null;
|
|
39
|
+
/** The newest read, where it failed after that one. */
|
|
40
|
+
readonly failedSince: WeekUsageNow['failedSince'];
|
|
41
|
+
/** Whether the reading is stale: a read failed since, or it is older than the project's time between readings allows. */
|
|
42
|
+
readonly stale: boolean;
|
|
43
|
+
/** Whether every agent step waits now. */
|
|
44
|
+
readonly holds: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** What every agent step's record says while the limit holds it. */
|
|
48
|
+
export const spendingWait = (r: { readonly usedPercent: number; readonly limitPercent: number }): string =>
|
|
49
|
+
`waits: the week's use is ${percentCut(r.usedPercent)}, at or past the spending limit of ${r.limitPercent}%`;
|
|
50
|
+
|
|
51
|
+
/** How every wait the spending limit gives starts, its unreadable one included. */
|
|
52
|
+
const SPENDING_WAIT_START = "waits: the week's use ";
|
|
53
|
+
|
|
54
|
+
/** Whether what a step waits on is the spending limit: what a page counts its waiting steps by. Pure. */
|
|
55
|
+
export const isSpendingLimitWait = (why: string): boolean => why.startsWith(SPENDING_WAIT_START);
|
|
56
|
+
|
|
57
|
+
/** The limit against the week now. Pure. */
|
|
58
|
+
export const judgeSpending = (input: {
|
|
59
|
+
readonly limit: StoredSpendingLimit | null;
|
|
60
|
+
readonly usage: WeekUsageNow;
|
|
61
|
+
readonly staleAfterSeconds: number;
|
|
62
|
+
readonly now: number;
|
|
63
|
+
}): SpendingLimitState => {
|
|
64
|
+
const limitPercent = input.limit === null ? DEFAULT_SPENDING_LIMIT_PERCENT : input.limit.weekPercent;
|
|
65
|
+
const good = input.usage.good;
|
|
66
|
+
return {
|
|
67
|
+
limitPercent,
|
|
68
|
+
setAt: input.limit === null ? null : input.limit.changedAt,
|
|
69
|
+
reading: good,
|
|
70
|
+
failedSince: input.usage.failedSince,
|
|
71
|
+
stale: good !== null && (input.usage.failedSince !== null || input.now - good.readAt > input.staleAfterSeconds),
|
|
72
|
+
holds: good !== null && good.usedPercent >= limitPercent,
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* What the limit does to an agent step now. `why` is what its record says (`spendingWait`); `unavailable`, in words, is why
|
|
78
|
+
* no agent can be had until a reading or the limit changes, the reason a run with a task ends and marks it as needing an
|
|
79
|
+
* agent (`steps.ts` `untilAgentSlot`). An unreadable week has none: the step waits, since the next read may well succeed.
|
|
80
|
+
*/
|
|
81
|
+
export interface SpendingHold {
|
|
82
|
+
readonly why: string;
|
|
83
|
+
readonly unavailable: string | null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export interface SpendingLimit {
|
|
87
|
+
/** What the limit does to an agent step now; none while it holds nothing. */
|
|
88
|
+
readonly holdsAgents: () => Effect.Effect<SpendingHold | null>;
|
|
89
|
+
/** The limit against the newest reading, for a page; none for a project that reads no week. */
|
|
90
|
+
readonly state: (now: number) => Effect.Effect<SpendingLimitState | null, StorageError>;
|
|
91
|
+
/**
|
|
92
|
+
* The project took a reading of its week. Where the verdict changed since the last one, or a step found the week
|
|
93
|
+
* unreadable since, every waiting step is woken to judge it again: a reading below the limit lets them go.
|
|
94
|
+
*/
|
|
95
|
+
readonly readingTaken: () => Effect.Effect<void>;
|
|
96
|
+
/**
|
|
97
|
+
* THE ONE WAY TO SET IT, for the project's route: checks the percent asked, stores it with the platform's statement
|
|
98
|
+
* through the project's `write`, wakes every waiting step (relayed to the process its runs wait in), and says in the log
|
|
99
|
+
* who asked (`from`), as the routes that set a workflow's limits do. A refused one changes nothing.
|
|
100
|
+
*/
|
|
101
|
+
readonly set: <E>(r: {
|
|
102
|
+
readonly weekPercent: unknown;
|
|
103
|
+
readonly from: string;
|
|
104
|
+
readonly write: (statement: { readonly sql: string; readonly params: ReadonlyArray<number> }) => Effect.Effect<unknown, E>;
|
|
105
|
+
}) => Effect.Effect<{ readonly ok: true; readonly weekPercent: number } | { readonly ok: false; readonly error: string }, E>;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export const makeSpendingLimit = (deps: { readonly store: LimitStore; readonly usage: WeekUsage | null; readonly wakes: PickWakes }): SpendingLimit => {
|
|
109
|
+
const { usage } = deps;
|
|
110
|
+
const state = (now: number): Effect.Effect<SpendingLimitState | null, StorageError> =>
|
|
111
|
+
usage === null ? Effect.succeed(null) : Effect.map(
|
|
112
|
+
Effect.all({ limit: deps.store.spendingLimit(), week: usage.now() }),
|
|
113
|
+
({ limit, week }) => judgeSpending({ limit, usage: week, staleAfterSeconds: usage.staleAfterSeconds, now }),
|
|
114
|
+
);
|
|
115
|
+
/** What the last reading told held, in this process; none before the first. */
|
|
116
|
+
let heldAtLastReading: boolean | null = null;
|
|
117
|
+
/** A step found the week unreadable since the last reading, so it waits for a wake that a changed verdict alone may not bring. */
|
|
118
|
+
let unreadSinceLastReading = false;
|
|
119
|
+
return {
|
|
120
|
+
holdsAgents: () => pipe(
|
|
121
|
+
state(Date.now() / 1000),
|
|
122
|
+
Effect.map((s): SpendingHold | null => (s === null || !s.holds || s.reading === null ? null : {
|
|
123
|
+
why: spendingWait({ usedPercent: s.reading.usedPercent, limitPercent: s.limitPercent }),
|
|
124
|
+
unavailable: `the week's use is ${percentCut(s.reading.usedPercent)}, at or past the spending limit of ${s.limitPercent}%`,
|
|
125
|
+
})),
|
|
126
|
+
Effect.catchTag('StorageError', (e) => Effect.sync((): SpendingHold => {
|
|
127
|
+
unreadSinceLastReading = true;
|
|
128
|
+
return { why: `waits: the week's use could not be read (${e.reason}), so the spending limit holds every agent step`, unavailable: null };
|
|
129
|
+
})),
|
|
130
|
+
),
|
|
131
|
+
state,
|
|
132
|
+
readingTaken: () => Effect.gen(function* () {
|
|
133
|
+
const judged = yield* Effect.result(state(Date.now() / 1000));
|
|
134
|
+
if (Result.isFailure(judged)) return yield* Effect.logError(`[spending limit] a reading was taken and could not be judged: ${judged.failure.reason}`);
|
|
135
|
+
const holds = judged.success !== null && judged.success.holds;
|
|
136
|
+
if (holds === heldAtLastReading && !unreadSinceLastReading) return;
|
|
137
|
+
if (holds !== heldAtLastReading && judged.success !== null) {
|
|
138
|
+
yield* Effect.log(`[spending limit] ${holds ? 'holds every agent step' : 'holds nothing'}: the week's use is ${judged.success.reading === null ? 'not read yet' : percentCut(judged.success.reading.usedPercent)}, the limit ${judged.success.limitPercent}%`);
|
|
139
|
+
}
|
|
140
|
+
heldAtLastReading = holds;
|
|
141
|
+
unreadSinceLastReading = false;
|
|
142
|
+
deps.wakes.wakeEveryPick(holds ? 'a reading at or past the spending limit' : 'a reading below the spending limit');
|
|
143
|
+
}),
|
|
144
|
+
set: (r) => Effect.gen(function* () {
|
|
145
|
+
const weekPercent = r.weekPercent;
|
|
146
|
+
if (typeof weekPercent !== 'number' || !Number.isInteger(weekPercent) || weekPercent < 0 || weekPercent > 100) {
|
|
147
|
+
return { ok: false as const, error: 'weekPercent must be a whole number from 0 to 100' };
|
|
148
|
+
}
|
|
149
|
+
yield* r.write({ sql: SET_SPENDING_LIMIT_SQL, params: [weekPercent, Date.now() / 1000] });
|
|
150
|
+
deps.wakes.wakeEveryPick('the spending limit set');
|
|
151
|
+
yield* Effect.log(`[spending limit] ${weekPercent}%, from ${r.from}`);
|
|
152
|
+
return { ok: true as const, weekPercent };
|
|
153
|
+
}),
|
|
154
|
+
};
|
|
155
|
+
};
|
package/src/steps.ts
CHANGED
|
@@ -54,7 +54,8 @@ import type { EngineRecords } from './storage/engine-records';
|
|
|
54
54
|
import { AGENT_BEAT_MS, noSpend, type StepRecords, type StepScope, type StepSpend } from './storage/step-records';
|
|
55
55
|
import type { InputRecords } from './storage/input-records';
|
|
56
56
|
import type { StorageError } from './storage/storage-error';
|
|
57
|
-
import
|
|
57
|
+
import type { SpendingHold } from './spending-limit';
|
|
58
|
+
import { inPickOrder, listOf, queueOrder, type PendingWork, type TaskInputs, type TaskRef, type Tasks, type TaskSummary } from './tasks';
|
|
58
59
|
|
|
59
60
|
export { A_STEP_FAILS, edgeDeclared, isRetry, RUN_ENDS, RUN_STARTS, type StepEdge } from './graph';
|
|
60
61
|
|
|
@@ -100,7 +101,23 @@ export const HANDED_OVER = 'stood down: its process is handing its runs to the n
|
|
|
100
101
|
* Decompile above them had failed (2026-11-19).
|
|
101
102
|
*/
|
|
102
103
|
export const ABOVE_ENDED = 'stood down: the run above it has ended';
|
|
103
|
-
|
|
104
|
+
/**
|
|
105
|
+
* What an agent step of a run with a task fails with where no agent can be had (`untilAgentSlot`): its task went to the
|
|
106
|
+
* back of its queue, marked as needing an agent, and the run gives its slot up untried.
|
|
107
|
+
*/
|
|
108
|
+
export const NEEDS_AN_AGENT_STOOD_DOWN = 'stood down: no agent can be had, so its task went to the back of its queue, marked as needing one';
|
|
109
|
+
export const isStoodDown = (failure: unknown): boolean =>
|
|
110
|
+
failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN;
|
|
111
|
+
|
|
112
|
+
/** Why no agent can be had at an agents' limit of 0, in words. */
|
|
113
|
+
export const AGENTS_LIMIT_ZERO = "its agents' limit is 0";
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Whether an agent step may take an agent now. Where not, `why` is what its record says, and `unavailable`, in words, is why
|
|
117
|
+
* none can be had until a limit or a reading changes (an agents' limit of 0, the spending limit); none where one may free
|
|
118
|
+
* when another run's agent step ends, or the limits could not be read.
|
|
119
|
+
*/
|
|
120
|
+
export type AgentSlot = { readonly free: true } | { readonly free: false; readonly why: string; readonly unavailable: string | null };
|
|
104
121
|
|
|
105
122
|
/** 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. */
|
|
106
123
|
export const surplusRun = (oldestFirst: ReadonlyArray<string>, run: string, budget: number): boolean => oldestFirst.indexOf(run) >= budget;
|
|
@@ -155,6 +172,8 @@ export interface StepDeclaration {
|
|
|
155
172
|
readonly perItem?: boolean;
|
|
156
173
|
/** Whether it picks its run's work, waiting while there is none. */
|
|
157
174
|
readonly picks?: boolean;
|
|
175
|
+
/** Whether its result names the item its run works on (`subject`), which later steps inherit. */
|
|
176
|
+
readonly namesItem?: boolean;
|
|
158
177
|
/** The paths, from the project's root, whose changed files are counted to it: where it may write and where it writes. */
|
|
159
178
|
readonly writes?: ReadonlyArray<string>;
|
|
160
179
|
}
|
|
@@ -301,7 +320,7 @@ export interface AgentBudgetRules {
|
|
|
301
320
|
readonly standsDown: (workflow: string, run: string) => Effect.Effect<boolean>;
|
|
302
321
|
readonly waitsForWork: (workflow: string, run: string) => Effect.Effect<boolean>;
|
|
303
322
|
/** Its workflow's other runs in an agent step now are fewer than its agents' limit; why not, when they are not. */
|
|
304
|
-
readonly agentSlot: (workflow: string, run: string) => Effect.Effect<
|
|
323
|
+
readonly agentSlot: (workflow: string, run: string) => Effect.Effect<AgentSlot>;
|
|
305
324
|
}
|
|
306
325
|
|
|
307
326
|
/** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
|
|
@@ -328,6 +347,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
328
347
|
readonly inputs: InputRecords;
|
|
329
348
|
/** A workflow's queue changed with no wake of its Picks: one of them claimed an item (`queue-counts.ts`). */
|
|
330
349
|
readonly queueChanged: (workflow: string) => void;
|
|
350
|
+
/** What the spending limit does to an agent step now; none while it holds nothing (`spending-limit.ts`). */
|
|
351
|
+
readonly spendingHoldsAgents: () => Effect.Effect<SpendingHold | null>;
|
|
331
352
|
}) => {
|
|
332
353
|
const { stepRecords: records, stepFiles } = deps;
|
|
333
354
|
type Declaration = WorkflowDeclaration<Phase, R>;
|
|
@@ -335,6 +356,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
335
356
|
const PICKING = new Map<string, Semaphore.Semaphore>();
|
|
336
357
|
const RUN_ENDED = new Set<() => void>();
|
|
337
358
|
const undeclaredSaid = new Set<string>();
|
|
359
|
+
/** Each workflow's run items a mark was refused for, said once (`markedAsNeedingAnAgent`). */
|
|
360
|
+
const offItsListSaid = new Set<string>();
|
|
338
361
|
/**
|
|
339
362
|
* EACH RUN'S LAST STEP, as this process ran it, until the run ends. A run resumed from another process has none here, and
|
|
340
363
|
* 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
|
|
@@ -448,39 +471,95 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
448
471
|
),
|
|
449
472
|
waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
|
|
450
473
|
// The other runs of the workflow at its top that an agent works for, a waiting one not counted, against that
|
|
451
|
-
// workflow's agents' limit: at 0 none is ever free,
|
|
474
|
+
// workflow's agents' limit: at 0 none is ever free, which no agent ending changes.
|
|
452
475
|
agentSlot: (workflow, run) => pipe(
|
|
453
476
|
topOf(workflow, run),
|
|
454
|
-
Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<
|
|
477
|
+
Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<AgentSlot, StorageError> => {
|
|
455
478
|
const agents = w === null ? null : w.agents;
|
|
456
479
|
if (agents === null) return Effect.succeed({ free: true });
|
|
457
|
-
if (agents === 0) return Effect.succeed({ free: false, why:
|
|
458
|
-
return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }) => {
|
|
480
|
+
if (agents === 0) return Effect.succeed({ free: false, why: `waits for an agent: ${AGENTS_LIMIT_ZERO}`, unavailable: AGENTS_LIMIT_ZERO });
|
|
481
|
+
return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }): AgentSlot => {
|
|
459
482
|
const going = new Set(runs);
|
|
460
483
|
const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
|
|
461
|
-
return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use
|
|
484
|
+
return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use`, unavailable: null };
|
|
462
485
|
});
|
|
463
486
|
})),
|
|
464
|
-
Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false
|
|
487
|
+
Effect.catchTag('StorageError', unreadLimits(workflow, (why): AgentSlot => ({ free: false, why: `waits for an agent: its limits could not be read (${why})`, unavailable: null }))),
|
|
465
488
|
),
|
|
466
489
|
}),
|
|
467
490
|
});
|
|
468
491
|
|
|
492
|
+
/** 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. */
|
|
493
|
+
const taskOfTop = (top: { readonly run: string; readonly workflow: string }): Effect.Effect<TaskRef | null> => {
|
|
494
|
+
const d = DECLARED.get(top.workflow);
|
|
495
|
+
if (d === undefined || !hasAList(d)) return Effect.succeed(null);
|
|
496
|
+
return Effect.map(Effect.orElseSucceed(records.subjectOfRun(top.run), () => null), (item) => (item === null ? null : { workflow: top.workflow, item }));
|
|
497
|
+
};
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* 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).
|
|
501
|
+
*
|
|
502
|
+
* ONLY A TASK ITS PICK READS IS MARKED (`tasks.ts` `readByItsPick`). A mark on any other passes over nothing: the run
|
|
503
|
+
* ends, the next takes the same work and ends the same way. Fix conflicts' runs named conflicts while its list named
|
|
504
|
+
* 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
|
+
* 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 waits for an agent as a run with no task does. A task whose state cannot be read is marked as before.
|
|
507
|
+
*/
|
|
508
|
+
const markedAsNeedingAnAgent = (top: { readonly run: string; readonly workflow: string }, step: string, why: string): Effect.Effect<boolean> =>
|
|
509
|
+
Effect.flatMap(taskOfTop(top), (task) => {
|
|
510
|
+
if (task === null) return Effect.succeed(false);
|
|
511
|
+
return Effect.flatMap(Effect.orElseSucceed(deps.tasks.readByItsPick(task), () => true), (read) => {
|
|
512
|
+
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 waits for an agent instead`;
|
|
514
|
+
if (process.env.NODE_ENV === 'test') return Effect.die(new Error(fault));
|
|
515
|
+
if (!offItsListSaid.has(`${top.workflow}\n${task.item}`)) {
|
|
516
|
+
offItsListSaid.add(`${top.workflow}\n${task.item}`);
|
|
517
|
+
console.error(`[agents] ${fault}`);
|
|
518
|
+
}
|
|
519
|
+
return Effect.succeed(false);
|
|
520
|
+
});
|
|
521
|
+
});
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, in words; none where one can: the spending limit holds, or its
|
|
525
|
+
* agents' limit is 0. While it says so, its Pick passes over its tasks marked as needing an agent (`queueNow`,
|
|
526
|
+
* `pickOrder`), and takes them in their queue's order again once an agent can be had. A limit that cannot be read passes
|
|
527
|
+
* over none.
|
|
528
|
+
*/
|
|
529
|
+
const agentsUnavailable = (workflow: string): Effect.Effect<string | null> => Effect.gen(function* () {
|
|
530
|
+
const held = yield* deps.spendingHoldsAgents();
|
|
531
|
+
if (held !== null && held.unavailable !== null) return held.unavailable;
|
|
532
|
+
const limits = yield* Effect.orElseSucceed(limitsOf(workflow), () => null);
|
|
533
|
+
return limits !== null && limits.agents === 0 ? AGENTS_LIMIT_ZERO : null;
|
|
534
|
+
});
|
|
535
|
+
|
|
469
536
|
/**
|
|
470
537
|
* AN AGENT STEP TAKES AN AGENT SLOT FIRST: with its workflow's agents' limit in use by its other runs it waits, its record
|
|
471
538
|
* saying so, until an agent step ends or a limit changes (`pick-wakes.ts`), and never polls. Its record starts again when
|
|
472
539
|
* it has a slot, since the wait was no work. A limit lowered meanwhile to 0 agents, or below its run, stands it down.
|
|
540
|
+
* While the spending limit holds (`spending-limit.ts`) every agent step waits the same way, in every workflow, until a
|
|
541
|
+
* reading below it or a new limit wakes it.
|
|
542
|
+
*
|
|
543
|
+
* A RUN WITH A TASK DOES NOT WAIT WHERE NO AGENT CAN BE HAD (its workflow's agents' limit is 0, or the spending limit
|
|
544
|
+
* holds): it marks its task as needing an agent, which puts it at the back of its queue (`tasks.ts` `markNeedsAgent`),
|
|
545
|
+
* and ends, giving its run slot to work that needs none. Its Pick passes over such tasks while no agent is available
|
|
546
|
+
* (`agentsUnavailable`). Waiting, a few such runs filled every run slot of Decompile and nothing behind them moved
|
|
547
|
+
* (2026-11-20). A run with no task, or one waiting for an agent another run holds, still waits here.
|
|
548
|
+
*
|
|
549
|
+
* A step that gets past it took an agent, and clears its task's mark when it ends (`measured`, `agentStepRan`).
|
|
473
550
|
*/
|
|
474
|
-
const untilAgentSlot = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, record: () => number | null) => Effect.gen(function* () {
|
|
551
|
+
const untilAgentSlot = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, step: string, record: () => number | null) => Effect.gen(function* () {
|
|
475
552
|
const rules = yield* AgentBudgets;
|
|
476
553
|
const workflow = instance.workflow._tag;
|
|
477
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.
|
|
478
|
-
const
|
|
555
|
+
const top = yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }));
|
|
556
|
+
const heardOn = top.workflow;
|
|
479
557
|
let waited = false;
|
|
480
558
|
for (;;) {
|
|
481
559
|
const wakes = deps.wakes.pickWakesSoFar(heardOn);
|
|
482
560
|
if (yield* rules.standsDown(workflow, instance.executionId)) return yield* Effect.fail(STOOD_DOWN);
|
|
483
|
-
const
|
|
561
|
+
const spendingHeld = yield* deps.spendingHoldsAgents();
|
|
562
|
+
const slot: AgentSlot = spendingHeld !== null ? { free: false, why: spendingHeld.why, unavailable: spendingHeld.unavailable } : yield* rules.agentSlot(workflow, instance.executionId);
|
|
484
563
|
const id = record();
|
|
485
564
|
if (slot.free) {
|
|
486
565
|
if (waited && id !== null) {
|
|
@@ -489,12 +568,34 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
489
568
|
}
|
|
490
569
|
return;
|
|
491
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
|
+
}
|
|
492
575
|
if (id !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
|
|
493
576
|
waited = true;
|
|
494
577
|
if ((yield* deps.wakes.untilPickWoken({ workflow: heardOn, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
|
|
495
578
|
}
|
|
496
579
|
});
|
|
497
580
|
|
|
581
|
+
/**
|
|
582
|
+
* 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
|
|
583
|
+
* step naming another is the fault `markedAsNeedingAnAgent` guards against, caught where it is made: in tests it fails
|
|
584
|
+
* the run; live, it is said once.
|
|
585
|
+
*/
|
|
586
|
+
const checkItem = (workflow: string, run: string, step: string, item: string | null): Effect.Effect<void> => Effect.gen(function* () {
|
|
587
|
+
const d = DECLARED.get(workflow);
|
|
588
|
+
if (item === null || d === undefined || !hasAList(d)) return;
|
|
589
|
+
const named = yield* Effect.orElseSucceed(records.subjectOfRun(run), () => null);
|
|
590
|
+
if (named === null || named.toLowerCase() === item.toLowerCase()) return;
|
|
591
|
+
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`;
|
|
592
|
+
if (process.env.NODE_ENV === 'test') throw new Error(fault);
|
|
593
|
+
if (!undeclaredSaid.has(fault)) {
|
|
594
|
+
undeclaredSaid.add(fault);
|
|
595
|
+
console.error(`[steps] ${fault}`);
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
|
|
498
599
|
/** Checks the move to `step` against its workflow's graph: in tests an undeclared one fails the run; live, it is said once. */
|
|
499
600
|
const checkEdge = (workflow: string, run: string, step: string): Effect.Effect<void> => Effect.gen(function* () {
|
|
500
601
|
const graph = DECLARED.get(workflow)?.graph?.();
|
|
@@ -546,9 +647,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
546
647
|
let before: TreeHashes | null = null;
|
|
547
648
|
let recordId: number | null = null;
|
|
548
649
|
let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
|
|
650
|
+
/** Whether this agent step took an agent: past its slot, its task's mark as needing one clears when it ends. */
|
|
651
|
+
let tookAnAgent = false;
|
|
549
652
|
return Effect.acquireUseRelease(
|
|
550
653
|
Effect.flatMap(Effect.gen(function* () {
|
|
551
654
|
yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
|
|
655
|
+
yield* checkItem(instance.workflow._tag, instance.executionId, step.name, subject);
|
|
552
656
|
// 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.
|
|
553
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 }) }));
|
|
554
658
|
if (id !== null && childRun !== null) yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
|
|
@@ -568,7 +672,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
568
672
|
return opened;
|
|
569
673
|
}))),
|
|
570
674
|
() => pipe(
|
|
571
|
-
(step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, () => recordId), execute) : execute,
|
|
675
|
+
(step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, step.name, () => recordId), Effect.andThen(Effect.sync(() => { tookAnAgent = true; }), execute)) : execute,
|
|
572
676
|
// What it changed, on its record, and a change it named outside where it may write refuses the step.
|
|
573
677
|
Effect.tap(() => Effect.suspend(() => {
|
|
574
678
|
const earlier = before;
|
|
@@ -589,6 +693,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
589
693
|
) as Effect.Effect<A, E, Exclude<R2, AgentStep>>,
|
|
590
694
|
({ id, beat }, exit) => Effect.gen(function* () {
|
|
591
695
|
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
|
+
}
|
|
592
702
|
// Its agent slot is free for its workflow's next run waiting on one.
|
|
593
703
|
if ((step.runs === 'agentic')) deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
|
|
594
704
|
// An interrupted step is no move: the run does it again.
|
|
@@ -598,6 +708,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
598
708
|
const spend = spendNow();
|
|
599
709
|
const used = meter.used();
|
|
600
710
|
const named = Exit.isSuccess(exit) ? subjectOf?.(exit.value) ?? null : null;
|
|
711
|
+
yield* checkItem(instance.workflow._tag, instance.executionId, step.name, named);
|
|
601
712
|
// A batch that started no process and recorded no item had none to do; one that worked outside `eachItem` stays undeclared.
|
|
602
713
|
const idleBatch = step.perItem === true && Exit.isSuccess(exit) && used.childCpuSeconds === 0 && used.compiles === 0;
|
|
603
714
|
const scope: StepScope = meter.items > 0 ? 'functions' : step.shared === true ? 'shared' : idleBatch ? 'none due' : subjectOf !== undefined && Exit.isSuccess(exit) && named === null ? 'nothing' : 'undeclared';
|
|
@@ -666,7 +777,11 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
666
777
|
/** Why a Pick waits, on its open record: its queued tasks, none of which it can claim now, and what wakes it. */
|
|
667
778
|
const nothingToClaim = (workflow: string): Effect.Effect<string> => pipe(
|
|
668
779
|
deps.tasks.taskSummaries({ workflow }),
|
|
669
|
-
Effect.map((tasks) =>
|
|
780
|
+
Effect.map((tasks) => {
|
|
781
|
+
const queued = queueOrder(tasks);
|
|
782
|
+
const needAnAgent = queued.filter((t) => t.needsAgent !== null).length;
|
|
783
|
+
return `${queued.length} queued${queued.length === 0 ? '' : ', none it can claim now'}${needAnAgent === 0 ? '' : `, ${needAnAgent} of them passed over as needing an agent`}`;
|
|
784
|
+
}),
|
|
670
785
|
Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)),
|
|
671
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`),
|
|
672
787
|
);
|
|
@@ -739,7 +854,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
739
854
|
}) => {
|
|
740
855
|
const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
|
|
741
856
|
const declaration: StepDeclaration = {
|
|
742
|
-
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 }),
|
|
857
|
+
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 }),
|
|
743
858
|
...(writes.length === 0 ? {} : { writes }),
|
|
744
859
|
source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
|
|
745
860
|
};
|
|
@@ -897,7 +1012,9 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
897
1012
|
*/
|
|
898
1013
|
const queueNow = (input: { readonly workflow: string; readonly run: string }): Effect.Effect<ReadonlyArray<TaskSummary>, unknown, R> => Effect.gen(function* () {
|
|
899
1014
|
yield* readTaskInputs(input.workflow);
|
|
900
|
-
|
|
1015
|
+
const queue = queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
|
|
1016
|
+
// While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
|
|
1017
|
+
return (yield* agentsUnavailable(input.workflow)) === null ? queue : queue.filter((t) => t.needsAgent === null);
|
|
901
1018
|
});
|
|
902
1019
|
|
|
903
1020
|
/** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
|
|
@@ -1045,8 +1162,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1045
1162
|
* returned to the queue that the candidates do not hold.
|
|
1046
1163
|
*/
|
|
1047
1164
|
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> =>
|
|
1048
|
-
Effect.map(deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), (tasks) =>
|
|
1049
|
-
inPickOrder({
|
|
1165
|
+
Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), unavailable: agentsUnavailable(input.workflow) }), ({ tasks, unavailable }) =>
|
|
1166
|
+
inPickOrder({
|
|
1167
|
+
candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }),
|
|
1168
|
+
// While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
|
|
1169
|
+
...(unavailable === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => t.status === 'queued' && t.needsAgent !== null).map((t) => t.ref.item)) }),
|
|
1170
|
+
}));
|
|
1050
1171
|
|
|
1051
1172
|
/**
|
|
1052
1173
|
* 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
|
|
@@ -1076,7 +1197,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
|
|
|
1076
1197
|
return {
|
|
1077
1198
|
defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
|
|
1078
1199
|
eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
|
|
1079
|
-
runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs,
|
|
1200
|
+
runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, agentsUnavailable,
|
|
1080
1201
|
};
|
|
1081
1202
|
};
|
|
1082
1203
|
|
package/src/storage/budgets.ts
CHANGED
|
@@ -3,8 +3,9 @@
|
|
|
3
3
|
*
|
|
4
4
|
* runs how many runs it keeps going, and nothing else does. None stored means the default: its agents' limit.
|
|
5
5
|
* agents how many of its runs may be in an agent step at once: its budget, as its owner sets it. A run at an agent step
|
|
6
|
-
*
|
|
7
|
-
* 0 is the owner's decision and no fault: nothing gets past a first agent step
|
|
6
|
+
* whose agents are all in use waits there for one (`steps.ts` `agentSlot`), its task kept and no CPU used.
|
|
7
|
+
* 0 is the owner's decision and no fault: nothing gets past a first agent step, and a run with a task ends there,
|
|
8
|
+
* its task marked as needing an agent (`steps.ts` `untilAgentSlot`).
|
|
8
9
|
*
|
|
9
10
|
* Alex, 2026-11-14: "there was supposed to be a number of runs concurrently allowed setting per workflow and also a number
|
|
10
11
|
* of concurrent agents allowed per workflow setting". One number did both until 2026-11-12; until 2026-11-14 the default
|
|
@@ -26,6 +27,23 @@ export const SET_WORKFLOW_BUDGET_SQL =
|
|
|
26
27
|
export const SET_WORKFLOW_RUNS_SQL =
|
|
27
28
|
'INSERT INTO workflow_budgets(workflow, budget, runs, changed_at) VALUES (?, 0, ?, ?) ON CONFLICT(workflow) DO UPDATE SET runs = excluded.runs, changed_at = excluded.changed_at';
|
|
28
29
|
|
|
30
|
+
/**
|
|
31
|
+
* THE ONE SPENDING LIMIT (`spending-limit.ts`): a table of one row beside `workflow_budgets`, since it is the account's and
|
|
32
|
+
* no workflow's: `spending_limit(id INTEGER PRIMARY KEY CHECK (id = 1), week_percent INTEGER NOT NULL, changed_at REAL NOT
|
|
33
|
+
* NULL)`. None stored is the default. As with `workflow_budgets`, the project makes the table and writes it through the
|
|
34
|
+
* statement below.
|
|
35
|
+
*/
|
|
36
|
+
export const SPENDING_LIMIT_SQL = 'SELECT week_percent, changed_at FROM spending_limit WHERE id = 1';
|
|
37
|
+
/** Sets the spending limit: the percent of the week at which agents stop. */
|
|
38
|
+
export const SET_SPENDING_LIMIT_SQL =
|
|
39
|
+
'INSERT INTO spending_limit(id, week_percent, changed_at) VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET week_percent = excluded.week_percent, changed_at = excluded.changed_at';
|
|
40
|
+
|
|
41
|
+
/** The spending limit as stored: the percent of the week at which agents stop, and when it was set, unix seconds. */
|
|
42
|
+
export interface StoredSpendingLimit {
|
|
43
|
+
readonly weekPercent: number;
|
|
44
|
+
readonly changedAt: number;
|
|
45
|
+
}
|
|
46
|
+
|
|
29
47
|
export interface WorkflowBudgetRow {
|
|
30
48
|
readonly workflow: string;
|
|
31
49
|
/** The agents' limit. */
|
|
@@ -46,6 +64,8 @@ export interface LimitStore {
|
|
|
46
64
|
readonly limitsOf: (workflow: string) => Effect.Effect<WorkflowLimits | null, StorageError>;
|
|
47
65
|
/** Every stored workflow's limits, by name, in one read: one with none stored is absent. None where there is no store. */
|
|
48
66
|
readonly storedLimits: () => Effect.Effect<ReadonlyMap<string, WorkflowLimits> | null, StorageError>;
|
|
67
|
+
/** The spending limit as set; none where none was set or there is no store, which is the default. */
|
|
68
|
+
readonly spendingLimit: () => Effect.Effect<StoredSpendingLimit | null, StorageError>;
|
|
49
69
|
}
|
|
50
70
|
|
|
51
71
|
/**
|
|
@@ -78,4 +98,16 @@ export const sqliteBudgets = (options: { readonly file: () => string }): LimitSt
|
|
|
78
98
|
db.close();
|
|
79
99
|
}
|
|
80
100
|
}),
|
|
101
|
+
spendingLimit: () => storeCall('limits: spendingLimit', () => {
|
|
102
|
+
const file = options.file();
|
|
103
|
+
if (!fs.existsSync(file)) return null;
|
|
104
|
+
const db = new Database(file, { readonly: true });
|
|
105
|
+
try {
|
|
106
|
+
if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'spending_limit'`).get() === null) return null;
|
|
107
|
+
const row = db.query(SPENDING_LIMIT_SQL).get() as { week_percent: number; changed_at: number } | null;
|
|
108
|
+
return row === null ? null : { weekPercent: row.week_percent, changedAt: row.changed_at };
|
|
109
|
+
} finally {
|
|
110
|
+
db.close();
|
|
111
|
+
}
|
|
112
|
+
}),
|
|
81
113
|
});
|
|
@@ -11,7 +11,7 @@ import {
|
|
|
11
11
|
stepErrorKept, type FunnelStepRecord, type ItemCost, type ItemHistoryRow, type LastStepNow, type NewestStepRecord, type RunCost, type RunOutcomeRow, type StepEdgeTaken,
|
|
12
12
|
type StepFileCount, type StepRecords, type StepRunRow, type UndeclaredWrites, type WorkStep, AGENT_LIVE_SECONDS,
|
|
13
13
|
} from './step-records';
|
|
14
|
-
import { LISTED_AGAIN, MOVED_TO_FRONT, STATUS_KINDS, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS, type Listed, type ListedWait, type NewNote, type QueueCount, type ReturnedBetween, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './task-store';
|
|
14
|
+
import { AGENT_STEP_RAN, LISTED_AGAIN, MOVED_TO_FRONT, NEEDS_AN_AGENT, STATUS_KINDS, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS, type Listed, type ListedWait, type NewNote, type QueueCount, type ReturnedBetween, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './task-store';
|
|
15
15
|
import type { InputRecords, InputRun } from './input-records';
|
|
16
16
|
import { storeCall, storeCalls } from './storage-error';
|
|
17
17
|
|
|
@@ -291,12 +291,19 @@ const quoted = (kinds: ReadonlyArray<string>): string => kinds.map((k) => `'${k.
|
|
|
291
291
|
const IS_STATUS_NOTE = `((n.kind = 'outcome' AND n.why <> '${STOOD_DOWN_OUTCOME}') OR n.kind IN (${quoted(Object.keys(STATUS_KINDS))}))`;
|
|
292
292
|
/** A note after which a task's failed tries are counted again: its final check passing, or a return to its queue. */
|
|
293
293
|
const STARTS_TRIES_AGAIN = `((n.kind = 'outcome' AND n.finished = 1) OR n.kind IN (${quoted(TRIES_START_AGAIN_KINDS)}))`;
|
|
294
|
+
/**
|
|
295
|
+
* A note `c` that clears task `t`'s `needs an agent` mark (`task-store.ts` `TaskState.needsAgent`): something new from outside
|
|
296
|
+
* its workflow (a return to its queue, a move to the front, any note by a person or by another workflow), an agent step that
|
|
297
|
+
* ran on it, or its final check passing.
|
|
298
|
+
*/
|
|
299
|
+
const CLEARS_NEEDS_AN_AGENT = `(c.kind IN (${quoted([...TRIES_START_AGAIN_KINDS, MOVED_TO_FRONT, AGENT_STEP_RAN])}) OR (c.kind = 'outcome' AND c.finished = 1)
|
|
300
|
+
OR c.by_workflow IS NULL OR c.by_workflow <> t.workflow)`;
|
|
294
301
|
|
|
295
302
|
interface StateRow {
|
|
296
303
|
readonly id: number; readonly workflow: string; readonly item: string; readonly listed: string | null; readonly created_at: number;
|
|
297
304
|
readonly note: number | null; readonly front: number | null; readonly kind: string | null; readonly why: string | null; readonly at: number | null;
|
|
298
305
|
readonly finished: number | null; readonly inputs: string | null; readonly about_workflow: string | null; readonly about_item: string | null;
|
|
299
|
-
readonly tries: number; readonly changes: number; readonly start_kind: string | null;
|
|
306
|
+
readonly tries: number; readonly changes: number; readonly start_kind: string | null; readonly needs_agent: string | null;
|
|
300
307
|
}
|
|
301
308
|
|
|
302
309
|
/**
|
|
@@ -310,10 +317,13 @@ const statesWhere = (db: Database, where: string, params: ReadonlyArray<string |
|
|
|
310
317
|
SELECT t.id AS id,
|
|
311
318
|
(SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${IS_STATUS_NOTE}) AS note,
|
|
312
319
|
(SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${STARTS_TRIES_AGAIN}) AS start,
|
|
313
|
-
(SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${MOVED_TO_FRONT}') AS front
|
|
320
|
+
(SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${MOVED_TO_FRONT}') AS front,
|
|
321
|
+
(SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${NEEDS_AN_AGENT}') AS mark
|
|
314
322
|
FROM tasks t WHERE ${where})
|
|
315
323
|
SELECT t.id, t.workflow, t.item, t.listed, t.created_at, s.note, s.front, n.kind, n.why, n.at, n.finished, n.inputs,
|
|
316
324
|
a.workflow AS about_workflow, a.item AS about_item,
|
|
325
|
+
CASE WHEN s.mark IS NULL OR EXISTS (SELECT 1 FROM task_notes c WHERE c.task = t.id AND c.id > s.mark AND ${CLEARS_NEEDS_AN_AGENT}) THEN NULL
|
|
326
|
+
ELSE (SELECT m.why FROM task_notes m WHERE m.id = s.mark) END AS needs_agent,
|
|
317
327
|
(SELECT COUNT(*) FROM task_notes o WHERE o.task = t.id AND o.kind = 'outcome' AND o.finished = 0 AND o.why <> '${STOOD_DOWN_OUTCOME}' AND o.id > COALESCE(s.start, 0)) AS tries,
|
|
318
328
|
(SELECT COUNT(*) FROM task_notes c WHERE c.task = t.id AND c.before_sha IS NOT NULL) AS changes,
|
|
319
329
|
(SELECT k.kind FROM task_notes k WHERE k.id = s.start) AS start_kind
|
|
@@ -327,6 +337,7 @@ const statesWhere = (db: Database, where: string, params: ReadonlyArray<string |
|
|
|
327
337
|
about: r.about_workflow === null || r.about_item === null ? null : { workflow: r.about_workflow, item: r.about_item },
|
|
328
338
|
changes: r.changes,
|
|
329
339
|
returned: r.start_kind !== null && TRIES_START_AGAIN_KINDS.includes(r.start_kind),
|
|
340
|
+
needsAgent: r.needs_agent,
|
|
330
341
|
}));
|
|
331
342
|
|
|
332
343
|
/**
|
|
@@ -76,9 +76,19 @@ export type Listed =
|
|
|
76
76
|
*/
|
|
77
77
|
export type NotedStatus = 'queued' | 'blocked' | 'done' | 'removed';
|
|
78
78
|
|
|
79
|
+
/**
|
|
80
|
+
* THE KIND THE ENGINE WRITES WHEN A RUN ENDS AT AN AGENT STEP NO AGENT CAN BE HAD FOR (`steps.ts` `untilAgentSlot`): its task
|
|
81
|
+
* goes to the back of its queue, marked as needing an agent, with why in words. Alex, 2026-11-20: "if a workflow run is
|
|
82
|
+
* paused because it needs an agent it should probably go to the back of the queue and the task gets marked for needing an
|
|
83
|
+
* agent such that the workflow dequeuing logic can skip over functions which need an agent when the agentic budget is zero."
|
|
84
|
+
*/
|
|
85
|
+
export const NEEDS_AN_AGENT = 'needs an agent';
|
|
86
|
+
/** The kind the engine writes on a marked task after an agent step ran on it: it may need no agent now, so the mark clears. */
|
|
87
|
+
export const AGENT_STEP_RAN = 'an agent step ran';
|
|
88
|
+
|
|
79
89
|
/** The note kinds a status is read from, and what each leaves a task as. A run that stood down wrote no such note. */
|
|
80
90
|
export const STATUS_KINDS: Readonly<Record<string, NotedStatus>> = {
|
|
81
|
-
queued: 'queued', unblocked: 'queued', 'listed again': 'queued', blocked: 'blocked', removed: 'removed',
|
|
91
|
+
queued: 'queued', unblocked: 'queued', 'listed again': 'queued', blocked: 'blocked', removed: 'removed', [NEEDS_AN_AGENT]: 'queued',
|
|
82
92
|
// Kinds written before 2026-11-19, read as what they did: each put its task back in its queue, or held it out.
|
|
83
93
|
reopened: 'queued', 'new input': 'queued', resumed: 'queued', released: 'queued', held: 'blocked', 'waits on': 'blocked',
|
|
84
94
|
};
|
|
@@ -117,6 +127,12 @@ export interface TaskState {
|
|
|
117
127
|
readonly returned: boolean;
|
|
118
128
|
/** Notes on it that changed its text: what the flipping rule reads only where there are enough to flip. */
|
|
119
129
|
readonly changes: number;
|
|
130
|
+
/**
|
|
131
|
+
* WHY IT NEEDS AN AGENT, from its newest `needs an agent` note, while that mark stands; none otherwise. Something new from
|
|
132
|
+
* outside its workflow clears it (a return to its queue, a move to the front, any note by a person or another workflow),
|
|
133
|
+
* and so do an agent step that ran on it and its final check passing (`AGENT_STEP_RAN`, a finished outcome).
|
|
134
|
+
*/
|
|
135
|
+
readonly needsAgent: string | null;
|
|
120
136
|
}
|
|
121
137
|
|
|
122
138
|
/** How many of a workflow's tasks stood in one status from `at` on, unix seconds. */
|