@jive-sh/workflow-platform 0.5.2 → 0.6.1

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.
Files changed (57) hide show
  1. package/README.md +50 -5
  2. package/dist/cpu-limit/limiter.js +2 -2
  3. package/dist/cpu-limit/limiter.js.map +1 -1
  4. package/dist/dashboard/dashboard.css +134 -0
  5. package/dist/dashboard/queue-table.js +10 -2
  6. package/dist/dashboard/queue-table.js.map +1 -1
  7. package/dist/dashboard/spending-words.js +32 -0
  8. package/dist/dashboard/spending-words.js.map +1 -0
  9. package/dist/index.js +13 -4
  10. package/dist/index.js.map +1 -1
  11. package/dist/keep-running.js +12 -2
  12. package/dist/keep-running.js.map +1 -1
  13. package/dist/project.js +0 -5
  14. package/dist/project.js.map +1 -1
  15. package/dist/queue-counts.js +7 -1
  16. package/dist/queue-counts.js.map +1 -1
  17. package/dist/spending-limit.js +88 -0
  18. package/dist/spending-limit.js.map +1 -0
  19. package/dist/steps.js +163 -17
  20. package/dist/steps.js.map +1 -1
  21. package/dist/storage/budgets.js +27 -2
  22. package/dist/storage/budgets.js.map +1 -1
  23. package/dist/storage/sqlite-store.js +17 -2
  24. package/dist/storage/sqlite-store.js.map +1 -1
  25. package/dist/storage/task-store.js +10 -1
  26. package/dist/storage/task-store.js.map +1 -1
  27. package/dist/tasks.js +55 -5
  28. package/dist/tasks.js.map +1 -1
  29. package/dist/views/format.js +2 -0
  30. package/dist/views/format.js.map +1 -1
  31. package/dist/views/runs-now.js +12 -0
  32. package/dist/views/runs-now.js.map +1 -1
  33. package/dist/views/workflows-view.js +9 -2
  34. package/dist/views/workflows-view.js.map +1 -1
  35. package/package.json +3 -2
  36. package/src/cpu-limit/limiter.ts +2 -2
  37. package/src/dashboard/dashboard.css +5 -0
  38. package/src/dashboard/queue-bar.tsx +5 -5
  39. package/src/dashboard/queue-table.ts +17 -3
  40. package/src/dashboard/spending-limit-control.tsx +50 -0
  41. package/src/dashboard/spending-words.ts +50 -0
  42. package/src/dashboard/workflow-dag.tsx +1 -1
  43. package/src/dashboard/workflow-drilldown.tsx +5 -5
  44. package/src/dashboard/workflows-dashboard.tsx +28 -3
  45. package/src/index.ts +13 -4
  46. package/src/keep-running.ts +14 -3
  47. package/src/project.ts +35 -0
  48. package/src/queue-counts.ts +8 -1
  49. package/src/spending-limit.ts +156 -0
  50. package/src/steps.ts +179 -23
  51. package/src/storage/budgets.ts +34 -2
  52. package/src/storage/sqlite-store.ts +18 -3
  53. package/src/storage/task-store.ts +24 -1
  54. package/src/tasks.ts +62 -5
  55. package/src/views/format.ts +3 -0
  56. package/src/views/runs-now.ts +4 -0
  57. package/src/views/workflows-view.ts +27 -4
@@ -8,6 +8,12 @@
8
8
  * the runs going, as soon as a run ends and otherwise on a fallback timer. There is no sharing between workflows, no order,
9
9
  * no cap per item and no check of usage: a run with nothing to pick waits for an item (`steps.ts` `untilPicked`), and the
10
10
  * blocking a Pick runs and the queue's order keep a run off what it cannot finish. A run limit of 0 holds one workflow.
11
+ *
12
+ * NO RUN STARTS THAT COULD TAKE NO WORK: while no agent can be had for a workflow and its Pick would pass over every task
13
+ * in its queue (`steps.ts` `whyNoRunCanTakeWork`), it starts none, and a run waiting in its Pick ends. Alex, relayed on 2026-11-20:
14
+ * "if the number of queued tasks that require agents is all of them, and if there is no remaining agentic budget or all
15
+ * agents are in use, then the workflow runner doesn't just continually cycle picking up tasks and moving them to the back
16
+ * of the queue again". The next turn after an agent can be had, a mark clears or new input lands starts runs again.
11
17
  */
12
18
  import { keptRunningByItsBudget } from './steps';
13
19
  import { runLimit } from './storage/budgets';
@@ -24,10 +30,14 @@ export const budgetedWorkflows = (declared) => declared.filter(keptRunningByItsB
24
30
  * no part: at 0 agents its runs wait at their first agent step. Pure.
25
31
  */
26
32
  export const runsToStart = (w) => Math.max(w.kept - w.running, 0);
27
- /** One turn's plan: for each budgeted workflow, the runs going and how many to start. Pure but for the reads it is given. */
33
+ /**
34
+ * One turn's plan: for each budgeted workflow, the runs going and how many to start; none where no run could take work
35
+ * (`noWork`, from `steps.ts` `whyNoRunCanTakeWork`), which says why. Pure but for the reads it is given.
36
+ */
28
37
  export const planRunStarts = (input) => budgetedWorkflows(input.declared).map((d) => {
29
38
  const running = input.runningRuns(d.name);
30
- return { declaration: d, running, start: runsToStart({ kept: runLimit(input.limitsOf(d.name)), running }) };
39
+ const noWork = input.noWork(d.name);
40
+ return { declaration: d, running, noWork, start: noWork !== null ? 0 : runsToStart({ kept: runLimit(input.limitsOf(d.name)), running }) };
31
41
  });
32
42
  /**
33
43
  * ONE TURN AT A TIME, AND NO TURN HOLDS THE NEXT UP FOR LONG. A call during a turn shares its result and asks for one more
@@ -1 +1 @@
1
- {"version":3,"file":"keep-running.js","sourceRoot":"","sources":["../../../src/keep-running.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,sBAAsB,EAA4B,MAAM,SAAS,CAAC;AAC3E,OAAO,EAAE,QAAQ,EAAuB,MAAM,mBAAmB,CAAC;AAElE,kEAAkE;AAClE,MAAM,CAAC,MAAM,0BAA0B,GAAG,EAAE,CAAC;AAC7C,0HAA0H;AAC1H,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC;AACpC,yCAAyC;AACzC,MAAM,CAAC,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAEtC,0EAA0E;AAC1E,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAsF,QAA0B,EAAoB,EAAE,CACrK,QAAQ,CAAC,MAAM,CAAC,sBAAsB,CAAC,CAAC;AAE1C;;;GAGG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAsD,EAAU,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;AAE/H,6HAA6H;AAC7H,MAAM,CAAC,MAAM,aAAa,GAAG,CAA+F,KAI3H,EAAgG,EAAE,CACjG,iBAA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E,MAAM,EAAE,EAAE;YAC7C,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,6CAA6C,OAAO,GAAG,IAAI,IAAI,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;QACxH,CAAC,CAAC,CAAC;QACH,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,OAAO,KAAK,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,EAAE;YACvE,YAAY,CAAC,KAAK,CAAC,CAAC;YACpB,OAAO,IAAI,CAAC,CAAC;YACb,KAAK,GAAG,IAAI,CAAC;YACb,IAAI,KAAK,EAAE,CAAC;gBAAC,KAAK,GAAG,KAAK,CAAC;gBAAC,KAAK,OAAO,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;YAAC,CAAC;QACtE,CAAC,CAAC,CAAC;QACH,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IACF,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAEF,iGAAiG;AACjG,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,EAAE,CAAC"}
package/dist/project.js CHANGED
@@ -1,6 +1 @@
1
- /**
2
- * WHAT A PROJECT TELLS THE PLATFORM ABOUT ITSELF: the facts no generic code can know. Everything else (how a step is
3
- * measured, how a task is queued, when a waiting Pick wakes) is the platform's.
4
- */
5
- export {};
6
1
  //# sourceMappingURL=project.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"project.js","sourceRoot":"","sources":["../../../src/project.ts"],"names":[],"mappings":"AAAA;;;GAGG"}
1
+ {"version":3,"file":"project.js","sourceRoot":"","sources":["../../../src/project.ts"],"names":[],"mappings":""}
@@ -13,10 +13,16 @@ import { Effect } from 'effect';
13
13
  import { statusCounts } from './tasks';
14
14
  /** How long after a queue's first change it is counted: every change in that time is in the one count. */
15
15
  export const COUNT_AFTER_MS = 5_000;
16
+ /**
17
+ * The count recorded beside the four statuses: how many queued tasks are marked as needing an agent (`tasks.ts`
18
+ * `TaskSummary.needsAgent`). Part of `queued`, never an addend of its own: a page shows it beside that row.
19
+ */
20
+ export const QUEUED_NEEDING_AN_AGENT = 'queued, needing an agent';
16
21
  export const makeQueueCounts = (deps) => {
17
22
  /** Counts one workflow's queue now and records it. */
18
23
  const count = (workflow) => Effect.gen(function* () {
19
- const counts = statusCounts(yield* deps.tasks.taskSummaries({ workflow }));
24
+ const summaries = yield* deps.tasks.taskSummaries({ workflow });
25
+ const counts = { ...statusCounts(summaries), [QUEUED_NEEDING_AN_AGENT]: summaries.filter((t) => t.status === 'queued' && t.needsAgent !== null).length };
20
26
  yield* deps.store.recordQueueCounts({ at: Date.now() / 1000, counts: Object.entries(counts).map(([bucket, tasks]) => ({ workflow, bucket, tasks })) });
21
27
  });
22
28
  let countSoon = () => undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"queue-counts.js","sourceRoot":"","sources":["../../../src/queue-counts.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAIhC,OAAO,EAAE,YAAY,EAAc,MAAM,SAAS,CAAC;AAEnD,0GAA0G;AAC1G,MAAM,CAAC,MAAM,cAAc,GAAG,KAAK,CAAC;AAEpC,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,IAQ/B,EAAE,EAAE;IACH,sDAAsD;IACtD,MAAM,KAAK,GAAG,CAAC,QAAgB,EAAqC,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,QAA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CAAC,YAAY,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;YAC3J,CAAC,EAAE,IAAI,CAAC,YAAY,IAAI,cAAc,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QACpD,CAAC,CAAC;QACF,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,GAAG,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC;YAAE,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3I,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,UAAU,EAAE;YAAE,SAAS,CAAC,QAAQ,CAAC,CAAC;IAChE,CAAC,CAAC;IAEF,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,QAAgB,EAAQ,EAAE,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;AACrF,CAAC,CAAC"}
@@ -0,0 +1,88 @@
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 { SET_SPENDING_LIMIT_SQL } from './storage/budgets';
23
+ import { percentCut } from './views/format';
24
+ /** The percent of the week at which agents stop where none is set. */
25
+ export const DEFAULT_SPENDING_LIMIT_PERCENT = 95;
26
+ /** What every agent step's record says while the limit holds it. */
27
+ export const spendingWait = (r) => `waits: the week's use is ${percentCut(r.usedPercent)}, at or past the spending limit of ${r.limitPercent}%`;
28
+ /** How every wait the spending limit gives starts, its unreadable one included. */
29
+ const SPENDING_WAIT_START = "waits: the week's use ";
30
+ /** Whether what a step waits on is the spending limit: what a page counts its waiting steps by. Pure. */
31
+ export const isSpendingLimitWait = (why) => why.startsWith(SPENDING_WAIT_START);
32
+ /** The limit against the week now. Pure. */
33
+ export const judgeSpending = (input) => {
34
+ const limitPercent = input.limit === null ? DEFAULT_SPENDING_LIMIT_PERCENT : input.limit.weekPercent;
35
+ const good = input.usage.good;
36
+ return {
37
+ limitPercent,
38
+ setAt: input.limit === null ? null : input.limit.changedAt,
39
+ reading: good,
40
+ failedSince: input.usage.failedSince,
41
+ stale: good !== null && (input.usage.failedSince !== null || input.now - good.readAt > input.staleAfterSeconds),
42
+ holds: good !== null && good.usedPercent >= limitPercent,
43
+ };
44
+ };
45
+ export const makeSpendingLimit = (deps) => {
46
+ const { usage } = deps;
47
+ const state = (now) => usage === null ? Effect.succeed(null) : Effect.map(Effect.all({ limit: deps.store.spendingLimit(), week: usage.now() }), ({ limit, week }) => judgeSpending({ limit, usage: week, staleAfterSeconds: usage.staleAfterSeconds, now }));
48
+ /** What the last reading told held, in this process; none before the first. */
49
+ let heldAtLastReading = null;
50
+ /** A step found the week unreadable since the last reading, so it waits for a wake that a changed verdict alone may not bring. */
51
+ let unreadSinceLastReading = false;
52
+ return {
53
+ holdsAgents: () => pipe(state(Date.now() / 1000), Effect.map((s) => (s === null || !s.holds || s.reading === null ? null : {
54
+ why: spendingWait({ usedPercent: s.reading.usedPercent, limitPercent: s.limitPercent }),
55
+ unavailable: `the week's use is ${percentCut(s.reading.usedPercent)}, at or past the spending limit of ${s.limitPercent}%`,
56
+ })), Effect.catchTag('StorageError', (e) => Effect.sync(() => {
57
+ unreadSinceLastReading = true;
58
+ return { why: `waits: the week's use could not be read (${e.reason}), so the spending limit holds every agent step`, unavailable: null };
59
+ }))),
60
+ state,
61
+ readingTaken: () => Effect.gen(function* () {
62
+ const judged = yield* Effect.result(state(Date.now() / 1000));
63
+ if (Result.isFailure(judged))
64
+ return yield* Effect.logError(`[spending limit] a reading was taken and could not be judged: ${judged.failure.reason}`);
65
+ const holds = judged.success !== null && judged.success.holds;
66
+ if (holds === heldAtLastReading && !unreadSinceLastReading)
67
+ return;
68
+ if (holds !== heldAtLastReading && judged.success !== null) {
69
+ 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}%`);
70
+ }
71
+ heldAtLastReading = holds;
72
+ unreadSinceLastReading = false;
73
+ // It changes whether any run can take work (`steps.ts` `whyNoRunCanTakeWork`): the run planner plans again too.
74
+ deps.wakes.runPlanChanged({ workflow: null, source: holds ? 'a reading at or past the spending limit' : 'a reading below the spending limit' });
75
+ }),
76
+ set: (r) => Effect.gen(function* () {
77
+ const weekPercent = r.weekPercent;
78
+ if (typeof weekPercent !== 'number' || !Number.isInteger(weekPercent) || weekPercent < 0 || weekPercent > 100) {
79
+ return { ok: false, error: 'weekPercent must be a whole number from 0 to 100' };
80
+ }
81
+ yield* r.write({ sql: SET_SPENDING_LIMIT_SQL, params: [weekPercent, Date.now() / 1000] });
82
+ deps.wakes.runPlanChanged({ workflow: null, source: 'the spending limit set' });
83
+ yield* Effect.log(`[spending limit] ${weekPercent}%, from ${r.from}`);
84
+ return { ok: true, weekPercent };
85
+ }),
86
+ };
87
+ };
88
+ //# sourceMappingURL=spending-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spending-limit.js","sourceRoot":"","sources":["../../../src/spending-limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AACH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAG9C,OAAO,EAAE,sBAAsB,EAA6C,MAAM,mBAAmB,CAAC;AAEtG,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,sEAAsE;AACtE,MAAM,CAAC,MAAM,8BAA8B,GAAG,EAAE,CAAC;AAkBjD,oEAAoE;AACpE,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAkE,EAAU,EAAE,CACzG,4BAA4B,UAAU,CAAC,CAAC,CAAC,WAAW,CAAC,sCAAsC,CAAC,CAAC,YAAY,GAAG,CAAC;AAE/G,mFAAmF;AACnF,MAAM,mBAAmB,GAAG,wBAAwB,CAAC;AAErD,yGAAyG;AACzG,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,GAAW,EAAW,EAAE,CAAC,GAAG,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAAC;AAEjG,4CAA4C;AAC5C,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,KAK7B,EAAsB,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AG,CAAC,IAAI,WAAW,GAAG,GAAG,EAAE,CAAC;gBAC9G,OAAO,EAAE,EAAE,EAAE,KAAc,EAAE,KAAK,EAAE,kDAAkD,EAAE,CAAC;YAC3F,CAAC;YACD,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,EAAE,GAAG,EAAE,sBAAsB,EAAE,MAAM,EAAE,CAAC,WAAW,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;YAC1F,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,wBAAwB,EAAE,CAAC,CAAC;YAChF,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,oBAAoB,WAAW,WAAW,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YACtE,OAAO,EAAE,EAAE,EAAE,IAAa,EAAE,WAAW,EAAE,CAAC;QAC5C,CAAC,CAAC;KACH,CAAC;AACJ,CAAC,CAAC"}
package/dist/steps.js CHANGED
@@ -69,7 +69,14 @@ export const HANDED_OVER = 'stood down: its process is handing its runs to the n
69
69
  * Decompile above them had failed (2026-11-19).
70
70
  */
71
71
  export const ABOVE_ENDED = 'stood down: the run above it has ended';
72
- export const isStoodDown = (failure) => failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED;
72
+ /**
73
+ * What an agent step of a run with a task fails with where no agent can be had (`untilAgentSlot`): its task went to the
74
+ * back of its queue, marked as needing an agent, and the run gives its slot up untried.
75
+ */
76
+ 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';
77
+ export const isStoodDown = (failure) => failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN;
78
+ /** Why no agent can be had at an agents' limit of 0, in words. */
79
+ export const AGENTS_LIMIT_ZERO = "its agents' limit is 0";
73
80
  /** 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. */
74
81
  export const surplusRun = (oldestFirst, run, budget) => oldestFirst.indexOf(run) >= budget;
75
82
  /**
@@ -126,6 +133,8 @@ export const makeSteps = (deps) => {
126
133
  const PICKING = new Map();
127
134
  const RUN_ENDED = new Set();
128
135
  const undeclaredSaid = new Set();
136
+ /** Each workflow's run items a mark was refused for, said once (`markedAsNeedingAnAgent`). */
137
+ const offItsListSaid = new Set();
129
138
  /**
130
139
  * EACH RUN'S LAST STEP, as this process ran it, until the run ends. A run resumed from another process has none here, and
131
140
  * 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
@@ -224,37 +233,94 @@ export const makeSteps = (deps) => {
224
233
  standsDown: (workflow, run) => pipe(topOf(workflow, run), Effect.flatMap((top) => Effect.zipWith(pastItsRunLimit(workflow, run), top.run === run ? Effect.succeed(false) : pastItsRunLimit(top.workflow, top.run), (own, above) => own || above)), Effect.catchTag('StorageError', unreadLimits(workflow, () => false))),
225
234
  waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
226
235
  // The other runs of the workflow at its top that an agent works for, a waiting one not counted, against that
227
- // workflow's agents' limit: at 0 none is ever free, and its runs wait at their first agent step until the limit is raised.
236
+ // workflow's agents' limit: at 0 none is ever free, which no agent ending changes.
228
237
  agentSlot: (workflow, run) => pipe(topOf(workflow, run), Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w) => {
229
238
  const agents = w === null ? null : w.agents;
230
239
  if (agents === null)
231
240
  return Effect.succeed({ free: true });
232
241
  if (agents === 0)
233
- return Effect.succeed({ free: false, why: 'waits for an agent: its agents\x27 limit is 0' });
242
+ return Effect.succeed({ free: false, why: `waits for an agent: ${AGENTS_LIMIT_ZERO}`, unavailable: AGENTS_LIMIT_ZERO });
234
243
  return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }) => {
235
244
  const going = new Set(runs);
236
245
  const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
237
- return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use` };
246
+ return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use`, unavailable: null };
238
247
  });
239
- })), Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false, why: `waits for an agent: its limits could not be read (${why})` })))),
248
+ })), Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false, why: `waits for an agent: its limits could not be read (${why})`, unavailable: null })))),
240
249
  }),
241
250
  });
251
+ /** 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. */
252
+ const taskOfTop = (top) => {
253
+ const d = DECLARED.get(top.workflow);
254
+ if (d === undefined || !hasAList(d))
255
+ return Effect.succeed(null);
256
+ return Effect.map(Effect.orElseSucceed(records.subjectOfRun(top.run), () => null), (item) => (item === null ? null : { workflow: top.workflow, item }));
257
+ };
258
+ /**
259
+ * 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).
260
+ *
261
+ * ONLY A TASK ITS PICK READS IS MARKED (`tasks.ts` `readByItsPick`). A mark on any other passes over nothing: the run
262
+ * ends, the next takes the same work and ends the same way. Fix conflicts' runs named conflicts while its list named
263
+ * 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,
264
+ * 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
265
+ * run waits for an agent as a run with no task does. A task whose state cannot be read is marked as before.
266
+ */
267
+ const markedAsNeedingAnAgent = (top, step, why) => Effect.flatMap(taskOfTop(top), (task) => {
268
+ if (task === null)
269
+ return Effect.succeed(false);
270
+ return Effect.flatMap(Effect.orElseSucceed(deps.tasks.readByItsPick(task), () => true), (read) => {
271
+ if (read)
272
+ return deps.tasks.markNeedsAgent({ task, by: { workflow: top.workflow, run: top.run, step }, why });
273
+ 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`;
274
+ if (process.env.NODE_ENV === 'test')
275
+ return Effect.die(new Error(fault));
276
+ if (!offItsListSaid.has(`${top.workflow}\n${task.item}`)) {
277
+ offItsListSaid.add(`${top.workflow}\n${task.item}`);
278
+ console.error(`[agents] ${fault}`);
279
+ }
280
+ return Effect.succeed(false);
281
+ });
282
+ });
283
+ /**
284
+ * WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, in words; none where one can: the spending limit holds, or its
285
+ * agents' limit is 0. While it says so, its Pick passes over its tasks marked as needing an agent, and those with nothing
286
+ * new since their last run (`queueNow`, `pickOrder`, `tasks.ts` `passedOverWithoutAnAgent`), and takes them in their
287
+ * queue's order again once an agent can be had. A limit that cannot be read passes over none.
288
+ */
289
+ const agentsUnavailable = (workflow) => Effect.gen(function* () {
290
+ const held = yield* deps.spendingHoldsAgents();
291
+ if (held !== null && held.unavailable !== null)
292
+ return held.unavailable;
293
+ const limits = yield* Effect.orElseSucceed(limitsOf(workflow), () => null);
294
+ return limits !== null && limits.agents === 0 ? AGENTS_LIMIT_ZERO : null;
295
+ });
242
296
  /**
243
297
  * AN AGENT STEP TAKES AN AGENT SLOT FIRST: with its workflow's agents' limit in use by its other runs it waits, its record
244
298
  * saying so, until an agent step ends or a limit changes (`pick-wakes.ts`), and never polls. Its record starts again when
245
299
  * it has a slot, since the wait was no work. A limit lowered meanwhile to 0 agents, or below its run, stands it down.
300
+ * While the spending limit holds (`spending-limit.ts`) every agent step waits the same way, in every workflow, until a
301
+ * reading below it or a new limit wakes it.
302
+ *
303
+ * 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
304
+ * holds): it marks its task as needing an agent, which puts it at the back of its queue (`tasks.ts` `markNeedsAgent`),
305
+ * and ends, giving its run slot to work that needs none. Its Pick passes over such tasks while no agent is available
306
+ * (`agentsUnavailable`). Waiting, a few such runs filled every run slot of Decompile and nothing behind them moved
307
+ * (2026-11-20). A run with no task, or one waiting for an agent another run holds, still waits here.
308
+ *
309
+ * A step that gets past it took an agent, and clears its task's mark when it ends (`measured`, `agentStepRan`).
246
310
  */
247
- const untilAgentSlot = (instance, record) => Effect.gen(function* () {
311
+ const untilAgentSlot = (instance, step, record) => Effect.gen(function* () {
248
312
  const rules = yield* AgentBudgets;
249
313
  const workflow = instance.workflow._tag;
250
314
  // 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.
251
- const heardOn = (yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }))).workflow;
315
+ const top = yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }));
316
+ const heardOn = top.workflow;
252
317
  let waited = false;
253
318
  for (;;) {
254
319
  const wakes = deps.wakes.pickWakesSoFar(heardOn);
255
320
  if (yield* rules.standsDown(workflow, instance.executionId))
256
321
  return yield* Effect.fail(STOOD_DOWN);
257
- const slot = yield* rules.agentSlot(workflow, instance.executionId);
322
+ const spendingHeld = yield* deps.spendingHoldsAgents();
323
+ const slot = spendingHeld !== null ? { free: false, why: spendingHeld.why, unavailable: spendingHeld.unavailable } : yield* rules.agentSlot(workflow, instance.executionId);
258
324
  const id = record();
259
325
  if (slot.free) {
260
326
  if (waited && id !== null) {
@@ -263,6 +329,10 @@ export const makeSteps = (deps) => {
263
329
  }
264
330
  return;
265
331
  }
332
+ if (slot.unavailable !== null && (yield* markedAsNeedingAnAgent(top, step, slot.unavailable))) {
333
+ 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`);
334
+ return yield* Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
335
+ }
266
336
  if (id !== null)
267
337
  yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
268
338
  waited = true;
@@ -270,6 +340,26 @@ export const makeSteps = (deps) => {
270
340
  return yield* Effect.fail(HANDED_OVER);
271
341
  }
272
342
  });
343
+ /**
344
+ * 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
345
+ * step naming another is the fault `markedAsNeedingAnAgent` guards against, caught where it is made: in tests it fails
346
+ * the run; live, it is said once.
347
+ */
348
+ const checkItem = (workflow, run, step, item) => Effect.gen(function* () {
349
+ const d = DECLARED.get(workflow);
350
+ if (item === null || d === undefined || !hasAList(d))
351
+ return;
352
+ const named = yield* Effect.orElseSucceed(records.subjectOfRun(run), () => null);
353
+ if (named === null || named.toLowerCase() === item.toLowerCase())
354
+ return;
355
+ 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`;
356
+ if (process.env.NODE_ENV === 'test')
357
+ throw new Error(fault);
358
+ if (!undeclaredSaid.has(fault)) {
359
+ undeclaredSaid.add(fault);
360
+ console.error(`[steps] ${fault}`);
361
+ }
362
+ });
273
363
  /** Checks the move to `step` against its workflow's graph: in tests an undeclared one fails the run; live, it is said once. */
274
364
  const checkEdge = (workflow, run, step) => Effect.gen(function* () {
275
365
  const graph = DECLARED.get(workflow)?.graph?.();
@@ -330,8 +420,11 @@ export const makeSteps = (deps) => {
330
420
  let before = null;
331
421
  let recordId = null;
332
422
  let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
423
+ /** Whether this agent step took an agent: past its slot, its task's mark as needing one clears when it ends. */
424
+ let tookAnAgent = false;
333
425
  return Effect.acquireUseRelease(Effect.flatMap(Effect.gen(function* () {
334
426
  yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
427
+ yield* checkItem(instance.workflow._tag, instance.executionId, step.name, subject);
335
428
  // 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.
336
429
  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 }) }));
337
430
  if (id !== null && childRun !== null)
@@ -351,7 +444,7 @@ export const makeSteps = (deps) => {
351
444
  }), (hashes) => {
352
445
  before = hashes;
353
446
  return opened;
354
- }))), () => pipe((step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, () => recordId), execute) : execute,
447
+ }))), () => pipe((step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, step.name, () => recordId), Effect.andThen(Effect.sync(() => { tookAnAgent = true; }), execute)) : execute,
355
448
  // What it changed, on its record, and a change it named outside where it may write refuses the step.
356
449
  Effect.tap(() => Effect.suspend(() => {
357
450
  const earlier = before;
@@ -373,6 +466,13 @@ export const makeSteps = (deps) => {
373
466
  recordNow('say what it waits on', records.setStepWaiting({ id: recordId, waiting: why })); } }) : (e) => e), ({ id, beat }, exit) => Effect.gen(function* () {
374
467
  if (beat !== null)
375
468
  clearInterval(beat);
469
+ // An agent step that ran on a task marked as needing an agent clears the mark: it may need none now.
470
+ if (tookAnAgent && (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause))) {
471
+ const top = TOPS.get(instance.executionId) ?? { run: instance.executionId, workflow: instance.workflow._tag };
472
+ const task = yield* taskOfTop(top);
473
+ if (task !== null)
474
+ yield* deps.tasks.agentStepRan({ task, by: { workflow: top.workflow, run: top.run, step: step.name } });
475
+ }
376
476
  // Its agent slot is free for its workflow's next run waiting on one.
377
477
  if ((step.runs === 'agentic'))
378
478
  deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
@@ -385,6 +485,7 @@ export const makeSteps = (deps) => {
385
485
  const spend = spendNow();
386
486
  const used = meter.used();
387
487
  const named = Exit.isSuccess(exit) ? subjectOf?.(exit.value) ?? null : null;
488
+ yield* checkItem(instance.workflow._tag, instance.executionId, step.name, named);
388
489
  // A batch that started no process and recorded no item had none to do; one that worked outside `eachItem` stays undeclared.
389
490
  const idleBatch = step.perItem === true && Exit.isSuccess(exit) && used.childCpuSeconds === 0 && used.compiles === 0;
390
491
  const scope = meter.items > 0 ? 'functions' : step.shared === true ? 'shared' : idleBatch ? 'none due' : subjectOf !== undefined && Exit.isSuccess(exit) && named === null ? 'nothing' : 'undeclared';
@@ -450,12 +551,18 @@ export const makeSteps = (deps) => {
450
551
  return lock.withPermits(1)(pick);
451
552
  };
452
553
  /** Why a Pick waits, on its open record: its queued tasks, none of which it can claim now, and what wakes it. */
453
- const nothingToClaim = (workflow) => pipe(deps.tasks.taskSummaries({ workflow }), Effect.map((tasks) => `${queueOrder(tasks).length} queued${queueOrder(tasks).length === 0 ? '' : ', none it can claim now'}`), Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)), Effect.map((queued) => `no task it can claim (${queued}); it waits for a task returned to its queue, a new item, a run ending or a limit change`));
554
+ const nothingToClaim = (workflow) => pipe(deps.tasks.taskSummaries({ workflow }), Effect.map((tasks) => {
555
+ const queued = queueOrder(tasks);
556
+ const needAnAgent = queued.filter((t) => deps.tasks.passedOverNow(t) !== null).length;
557
+ 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`}`;
558
+ }), Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)), Effect.map((queued) => `no task it can claim (${queued}); it waits for a task returned to its queue, a new item, a run ending or a limit change`));
454
559
  /**
455
560
  * A PICK THAT FINDS NOTHING IT CAN CLAIM WAITS FOR AN EVENT THAT CAN CHANGE THAT (`pick-wakes.ts`), and never polls: one
456
561
  * open record, its `waiting` saying on what, and no new record while nothing changes. The run keeps its place in its
457
562
  * workflow's count, and its record starts again when it found an item, since the wait was no work. It ends with nothing
458
- * only when its run is past the runs its run limit keeps (`runLimit`).
563
+ * when its run is past the runs its run limit keeps (`runLimit`), or when no agent can be had and nothing in its queue
564
+ * can be taken without one (`whyNoRunCanTakeWork`): kept waiting there, 4 Decompile runs held their run slots for 51
565
+ * minutes on 2026-11-20 with each of its 751 queued tasks marked, and showed as running.
459
566
  */
460
567
  const untilPicked = (picked, pick) => Effect.gen(function* () {
461
568
  const instance = yield* WorkflowEngine.WorkflowInstance;
@@ -470,7 +577,11 @@ export const makeSteps = (deps) => {
470
577
  const found = yield* pickingOneAtATime(workflow, pick);
471
578
  if (waited)
472
579
  deps.wakes.countRePick(workflow, performance.now() - began);
473
- if (picked(found) || !(yield* budgets.waitsForWork(workflow, instance.executionId))) {
580
+ // With no agent to be had and nothing it can take, it ends rather than wait (`whyNoRunCanTakeWork`).
581
+ const noWork = picked(found) ? null : yield* noWorkByInputsLastRead(workflow);
582
+ if (noWork !== null)
583
+ console.log(`[agents] ${workflow} run ${instance.executionId} ended at its Pick: ${noWork}`);
584
+ if (picked(found) || noWork !== null || !(yield* budgets.waitsForWork(workflow, instance.executionId))) {
474
585
  if (picked(found))
475
586
  deps.queueChanged(workflow);
476
587
  if (waited && record !== null) {
@@ -490,7 +601,7 @@ export const makeSteps = (deps) => {
490
601
  const defineStep = (d) => {
491
602
  const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
492
603
  const declaration = {
493
- 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 }),
604
+ 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 }),
494
605
  ...(writes.length === 0 ? {} : { writes }),
495
606
  source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
496
607
  };
@@ -620,8 +731,39 @@ export const makeSteps = (deps) => {
620
731
  */
621
732
  const queueNow = (input) => Effect.gen(function* () {
622
733
  yield* readTaskInputs(input.workflow);
623
- return queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
734
+ const queue = queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
735
+ // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
736
+ return (yield* agentsUnavailable(input.workflow)) === null ? queue : queue.filter((t) => deps.tasks.passedOverNow(t) === null);
624
737
  });
738
+ /**
739
+ * WHY NO RUN OF A WORKFLOW CAN TAKE WORK NOW, none where one can: no agent can be had for it (`agentsUnavailable`), and
740
+ * every task in its queue is one its Pick passes over meanwhile, marked as needing an agent or with nothing new since its
741
+ * last run (`tasks.ts` `passedOverWithoutAnAgent`), or its queue is empty. Then a run would only hold a run slot and show
742
+ * as running: its trigger starts none (`keep-running.ts` `planRunStarts`), and a Pick that found nothing ends its run
743
+ * rather than wait (`untilPicked`). An agent to be had (a limit lifted, the spending limit no longer holding), a mark
744
+ * 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
745
+ * step needs none. Read where it cannot be, it says nothing, and runs start and wait as before.
746
+ */
747
+ const whyNoRunCanTakeWork = (workflow) => Effect.gen(function* () {
748
+ // Its tasks' inputs, a read of every task's, are read again only where the inputs its last Pick read leave no work.
749
+ if ((yield* noWorkByInputsLastRead(workflow)) === null)
750
+ return null;
751
+ yield* Effect.orElseSucceed(readTaskInputs(workflow), () => null);
752
+ return yield* noWorkByInputsLastRead(workflow);
753
+ });
754
+ /** `whyNoRunCanTakeWork` by its tasks' inputs as its last Pick read them: what a Pick that just read them asks. */
755
+ const noWorkByInputsLastRead = (workflow) => pipe(Effect.gen(function* () {
756
+ const d = DECLARED.get(workflow);
757
+ if (d === undefined || !keptRunningByItsBudget(d))
758
+ return null;
759
+ const unavailable = yield* agentsUnavailable(workflow);
760
+ if (unavailable === null)
761
+ return null;
762
+ const queued = queueOrder(yield* deps.tasks.taskSummaries({ workflow }));
763
+ if (queued.some((t) => deps.tasks.passedOverNow(t) === null))
764
+ return null;
765
+ return `no agent can be had (${unavailable}), and ${queued.length === 0 ? 'its queue is empty' : `each of its ${queued.length} queued tasks needs one or has nothing new since its last run`}`;
766
+ }), Effect.orElseSucceed(() => null));
625
767
  /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
626
768
  const defineWorkflow = (d) => ((name, options) => {
627
769
  // The one place a workflow's own types do not matter: every workflow passes through here the same way.
@@ -636,7 +778,7 @@ export const makeSteps = (deps) => {
636
778
  let refusedSaidAt = 0;
637
779
  const startAllowed = (payload) => Effect.gen(function* () {
638
780
  const limits = yield* deps.budgets.limitsOf(name);
639
- const limit = limits === null ? null : runLimitOf({ pending: d.pending, items: d.items, steps: d.steps }, limits);
781
+ const limit = limits === null ? null : runLimitOf(d, limits);
640
782
  if (limit === null)
641
783
  return { allowed: true };
642
784
  const going = (yield* deps.engine.unfinishedRuns()).filter((u) => u.workflow === name).map((u) => u.run);
@@ -742,7 +884,11 @@ export const makeSteps = (deps) => {
742
884
  * `queueNow` settles it: none blocked, another run's left out. `fromItem` builds a candidate for a task a step or a person
743
885
  * returned to the queue that the candidates do not hold.
744
886
  */
745
- const pickOrder = (input) => Effect.map(deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), (tasks) => inPickOrder({ candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }) }));
887
+ const pickOrder = (input) => Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), unavailable: agentsUnavailable(input.workflow) }), ({ tasks, unavailable }) => inPickOrder({
888
+ candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }),
889
+ // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
890
+ ...(unavailable === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => deps.tasks.passedOverNow(t) !== null).map((t) => t.ref.item)) }),
891
+ }));
746
892
  /**
747
893
  * 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
748
894
  * the other heavy jobs), `start` leaves it to the engine.
@@ -768,7 +914,7 @@ export const makeSteps = (deps) => {
768
914
  return {
769
915
  defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
770
916
  eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
771
- runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs,
917
+ runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, agentsUnavailable, whyNoRunCanTakeWork,
772
918
  };
773
919
  };
774
920
  //# sourceMappingURL=steps.js.map