@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.
- package/README.md +50 -5
- package/dist/cpu-limit/limiter.js +2 -2
- package/dist/cpu-limit/limiter.js.map +1 -1
- package/dist/dashboard/dashboard.css +134 -0
- 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/keep-running.js +12 -2
- package/dist/keep-running.js.map +1 -1
- package/dist/project.js +0 -5
- 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 +88 -0
- package/dist/spending-limit.js.map +1 -0
- package/dist/steps.js +163 -17
- 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 +17 -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 +55 -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 +3 -2
- package/src/cpu-limit/limiter.ts +2 -2
- 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/keep-running.ts +14 -3
- package/src/project.ts +35 -0
- package/src/queue-counts.ts +8 -1
- package/src/spending-limit.ts +156 -0
- package/src/steps.ts +179 -23
- package/src/storage/budgets.ts +34 -2
- package/src/storage/sqlite-store.ts +18 -3
- package/src/storage/task-store.ts +24 -1
- package/src/tasks.ts +62 -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,50 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* THE SPENDING LIMIT ON THE PAGE (`spending-limit.ts`): what it is set to with − and +, the week's reading against it, whether
|
|
5
|
+
* it holds every agent step, whether the reading is stale, and which agent steps wait on it, each in words
|
|
6
|
+
* (`spending-words.ts`). A click shows at once, as asked, until the page's next reading says the same; a failed one says why.
|
|
7
|
+
*/
|
|
8
|
+
import { useEffect, useState } from 'react';
|
|
9
|
+
import type { SpendingLimitState } from '../spending-limit';
|
|
10
|
+
import { heldStepsWords, spendingSettingWords, spendingStaleWords, spendingVerdictWords, type HeldStep } from './spending-words';
|
|
11
|
+
|
|
12
|
+
export interface SpendingLimitControlProps {
|
|
13
|
+
readonly spending: SpendingLimitState;
|
|
14
|
+
readonly held: ReadonlyArray<HeldStep>;
|
|
15
|
+
readonly now: number;
|
|
16
|
+
/** Stores a new limit, a whole percent from 0 to 100; with none the limit shows without buttons. */
|
|
17
|
+
readonly setSpendingLimit?: (weekPercent: number) => Promise<void>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const WHY = 'While the newest good reading of the week is at or past this percent, every agent step of every workflow waits before its agent call. A failed or late reading never lifts it.';
|
|
21
|
+
|
|
22
|
+
export function SpendingLimitControl({ spending, held, now, setSpendingLimit }: SpendingLimitControlProps) {
|
|
23
|
+
const [asked, setAsked] = useState<number | null>(null);
|
|
24
|
+
const [failed, setFailed] = useState<string | null>(null);
|
|
25
|
+
useEffect(() => {
|
|
26
|
+
if (asked !== null && asked === spending.limitPercent && spending.setAt !== null) setAsked(null);
|
|
27
|
+
}, [asked, spending.limitPercent, spending.setAt]);
|
|
28
|
+
const shown = asked === null ? spending.limitPercent : asked;
|
|
29
|
+
const set = (to: number) => {
|
|
30
|
+
if (setSpendingLimit === undefined) return;
|
|
31
|
+
setAsked(to);
|
|
32
|
+
setFailed(null);
|
|
33
|
+
setSpendingLimit(to).catch((e: unknown) => { setAsked(null); setFailed(e instanceof Error ? e.message : String(e)); });
|
|
34
|
+
};
|
|
35
|
+
const stale = spendingStaleWords(spending, now);
|
|
36
|
+
const waiting = heldStepsWords(spending, held);
|
|
37
|
+
return (
|
|
38
|
+
<div className="wp-spending">
|
|
39
|
+
<span className="wp-limit" title={WHY}>
|
|
40
|
+
{setSpendingLimit === undefined ? null : <button type="button" aria-label="Lower the spending limit" disabled={shown <= 0} onClick={() => set(shown - 1)}>−</button>}
|
|
41
|
+
<span>{spendingSettingWords({ limitPercent: shown, setAt: asked === null ? spending.setAt : now })}</span>
|
|
42
|
+
{setSpendingLimit === undefined ? null : <button type="button" aria-label="Raise the spending limit" disabled={shown >= 100} onClick={() => set(shown + 1)}>+</button>}
|
|
43
|
+
{failed === null ? null : <span className="wp-bad">not saved: {failed}</span>}
|
|
44
|
+
</span>
|
|
45
|
+
<p className={spending.holds ? 'wp-line wp-bad' : 'wp-line'}>{spendingVerdictWords(spending, now)}</p>
|
|
46
|
+
{stale === null ? null : <p className="wp-line wp-bad">{stale}</p>}
|
|
47
|
+
{waiting === null ? null : <p className={held.length > 0 ? 'wp-line wp-bad' : 'wp-line wp-mut'}>{waiting}</p>}
|
|
48
|
+
</div>
|
|
49
|
+
);
|
|
50
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE SPENDING LIMIT IN WORDS (`spending-limit.ts`): what it is set to, the week's reading against it, whether it holds, and
|
|
3
|
+
* which agent steps wait on it. Each state is said in words, first in its line; a colour on the page only repeats it. Pure,
|
|
4
|
+
* with no React and no JSX, so a test reads it without a page.
|
|
5
|
+
*/
|
|
6
|
+
import type { SpendingLimitState } from '../spending-limit';
|
|
7
|
+
import type { PhaseRunsNow } from '../views/runs-now';
|
|
8
|
+
import { percentCut, whenAgo } from '../views/format';
|
|
9
|
+
|
|
10
|
+
/** One agent step the limit holds runs at, and how many. */
|
|
11
|
+
export interface HeldStep {
|
|
12
|
+
readonly workflow: string;
|
|
13
|
+
readonly step: string;
|
|
14
|
+
readonly runs: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Every agent step the limit holds a run at now, from where runs are now. */
|
|
18
|
+
export const heldSteps = (runsNow: ReadonlyArray<PhaseRunsNow>): ReadonlyArray<HeldStep> =>
|
|
19
|
+
runsNow.flatMap((p) => p.workflows.flatMap((w) => w.steps.filter((s) => s.heldBySpendingLimit > 0).map((s) => ({ workflow: w.workflow, step: s.step, runs: s.heldBySpendingLimit }))));
|
|
20
|
+
|
|
21
|
+
/** What the limit is set to: "agents stop at 95% of the week (the default)". */
|
|
22
|
+
export const spendingSettingWords = (s: Pick<SpendingLimitState, 'limitPercent' | 'setAt'>): string =>
|
|
23
|
+
`Spending limit: agents stop at ${s.limitPercent}% of the week${s.setAt === null ? ' (the default)' : ''}`;
|
|
24
|
+
|
|
25
|
+
/** The week's reading against the limit, and whether it holds every agent step. */
|
|
26
|
+
export const spendingVerdictWords = (s: SpendingLimitState, now: number): string => {
|
|
27
|
+
if (s.reading === null) {
|
|
28
|
+
return s.failedSince === null
|
|
29
|
+
? "Holds nothing: there is no reading of the week's use yet."
|
|
30
|
+
: `Holds nothing: there is no good reading of the week's use yet; the newest read failed at ${whenAgo(s.failedSince.at, now)}: ${s.failedSince.error}`;
|
|
31
|
+
}
|
|
32
|
+
const reading = `the week's use is ${percentCut(s.reading.usedPercent)}, read ${whenAgo(s.reading.readAt, now)}`;
|
|
33
|
+
return s.holds
|
|
34
|
+
? `Holding every agent step: ${reading}, at or past the limit. Each waits before its agent call until a reading is below ${s.limitPercent}%.`
|
|
35
|
+
: `Holds nothing: ${reading}, below the limit.`;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Why the reading is stale and what the limit does meanwhile; none while it is current. */
|
|
39
|
+
export const spendingStaleWords = (s: SpendingLimitState, now: number): string | null => {
|
|
40
|
+
if (!s.stale) return null;
|
|
41
|
+
return s.failedSince === null
|
|
42
|
+
? "The reading is stale: none came since. The limit keeps that reading's verdict until a new one."
|
|
43
|
+
: `The reading is stale: the newest read failed at ${whenAgo(s.failedSince.at, now)} (${s.failedSince.error}). The limit keeps the last good reading's verdict until a read succeeds.`;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Which agent steps wait on it; none to say while it holds nothing and nothing waits. */
|
|
47
|
+
export const heldStepsWords = (s: Pick<SpendingLimitState, 'holds'>, held: ReadonlyArray<HeldStep>): string | null => {
|
|
48
|
+
if (held.length === 0) return s.holds ? 'No agent step has reached it yet.' : null;
|
|
49
|
+
return `Waiting on it: ${held.map((h) => `${h.workflow}, step ${h.step} (${h.runs} run${h.runs === 1 ? '' : 's'})`).join('; ')}.`;
|
|
50
|
+
};
|
|
@@ -96,7 +96,7 @@ function Node({ w, nodeStatus, href, style }: { readonly w: WorkflowView; readon
|
|
|
96
96
|
return (
|
|
97
97
|
<div data-workflow={w.name} className="wp-node" style={style}>
|
|
98
98
|
<a className="wp-node-name" href={href} title={`Open ${w.name}: ${w.description}`}>{w.name} ›</a>
|
|
99
|
-
{w.queue === null ? null : <QueueBar queue={w.queue} />}
|
|
99
|
+
{w.queue === null ? null : <QueueBar queue={w.queue} queuedNeedingAnAgent={w.queuedNeedingAnAgent} />}
|
|
100
100
|
<div className="wp-node-status">{nodeStatus(w)}</div>
|
|
101
101
|
</div>
|
|
102
102
|
);
|
|
@@ -8,7 +8,7 @@ import { Fragment, type ReactNode } from 'react';
|
|
|
8
8
|
import type { StepRunsNow, WorkflowRunsNow } from '../views/runs-now';
|
|
9
9
|
import type { StepSummary, WorkflowView } from '../views/workflows-view';
|
|
10
10
|
import { kindWords, type Crumb } from './drilldown';
|
|
11
|
-
import { queueSum } from './queue-table';
|
|
11
|
+
import { addendLabel, queueSum } from './queue-table';
|
|
12
12
|
|
|
13
13
|
/** The path opened, top first: every part but the last a link to its level, the last the page's title; `after` follows it. */
|
|
14
14
|
export function Breadcrumb({ crumbs, hrefOf, after }: { readonly crumbs: ReadonlyArray<Crumb>; readonly hrefOf: (path: ReadonlyArray<string>) => string; readonly after?: ReactNode }) {
|
|
@@ -26,9 +26,9 @@ export function Breadcrumb({ crumbs, hrefOf, after }: { readonly crumbs: Readonl
|
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
/** A sub-workflow's tasks on one line, as an addition: every category, then their total. */
|
|
29
|
-
const tasksLine = (queue: NonNullable<WorkflowView['queue']
|
|
30
|
-
const sum = queueSum(queue);
|
|
31
|
-
return `${sum.addends.map((a) => `${a.text} ${a
|
|
29
|
+
const tasksLine = (queue: NonNullable<WorkflowView['queue']>, queuedNeedingAnAgent: WorkflowView['queuedNeedingAnAgent']): string => {
|
|
30
|
+
const sum = queueSum(queue, queuedNeedingAnAgent);
|
|
31
|
+
return `${sum.addends.map((a) => `${a.text} ${addendLabel(a)}`).join(' + ')} = ${sum.totalText}`;
|
|
32
32
|
};
|
|
33
33
|
|
|
34
34
|
/** A sub-workflow's runs now against its run limit, in words. */
|
|
@@ -77,7 +77,7 @@ export function StepList({ steps, path, hrefOf, workflowOf, runsOf, runs, groupO
|
|
|
77
77
|
<span className="wp-kind">{kindWords(s)}</span>
|
|
78
78
|
</div>
|
|
79
79
|
<div className="wp-drill-what wp-mut">{s.description}</div>
|
|
80
|
-
{sub === undefined || sub.queue === null ? null : <div className="wp-drill-figures">{tasksLine(sub.queue)}</div>}
|
|
80
|
+
{sub === undefined || sub.queue === null ? null : <div className="wp-drill-figures">{tasksLine(sub.queue, sub.queuedNeedingAnAgent)}</div>}
|
|
81
81
|
{sub === undefined ? null : <div className="wp-drill-figures wp-mut">{runsLine(sub, runsOf(sub.name))}</div>}
|
|
82
82
|
{inStep === null ? null : <div className="wp-drill-figures">{inStep}</div>}
|
|
83
83
|
</li>
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* an addition (queued + in progress + blocked + done), its runs and limits, its tasks over time, its own steps with their
|
|
7
7
|
* kinds, and, read from its own records while it is open, why its blocked tasks are blocked, what its steps cost, its step
|
|
8
8
|
* graph and where its runs stopped. At the top it also shows what the project gives of its machine and its agents'
|
|
9
|
-
* account: the CPU limit, the stop of everything, and usage. It reads the platform's two readings
|
|
9
|
+
* account: the CPU limit, the stop of everything, and usage; and on every level the spending limit (`spending-limit-control.tsx`). It reads the platform's two readings
|
|
10
10
|
* (`views/workflows-view.ts`) and runs now (`views/runs-now.ts`). Uses React, which the host page brings.
|
|
11
11
|
*/
|
|
12
12
|
import { Fragment, useEffect, useState, type ReactNode } from 'react';
|
|
@@ -24,6 +24,8 @@ import { WorkflowDag } from './workflow-dag';
|
|
|
24
24
|
import { AgentUsageLine } from './agent-usage-line';
|
|
25
25
|
import type { AgentUsage } from './agent-usage';
|
|
26
26
|
import { MachineControls } from './machine-controls';
|
|
27
|
+
import { SpendingLimitControl } from './spending-limit-control';
|
|
28
|
+
import { heldSteps } from './spending-words';
|
|
27
29
|
|
|
28
30
|
/** What the page is given at each poll, all of it read at the request: every workflow, and where runs are now. */
|
|
29
31
|
export interface WorkflowsPageData {
|
|
@@ -79,6 +81,8 @@ export interface WorkflowsDashboardProps {
|
|
|
79
81
|
/** Stops everything the project runs, and resumes it; with neither, no button shows. */
|
|
80
82
|
readonly stopEverything?: () => Promise<void>;
|
|
81
83
|
readonly resume?: () => Promise<void>;
|
|
84
|
+
/** Stores a new spending limit, a whole percent of the week; with none the limit shows without buttons (`spending-limit-control.tsx`). */
|
|
85
|
+
readonly setSpendingLimit?: (weekPercent: number) => Promise<void>;
|
|
82
86
|
/**
|
|
83
87
|
* THE DRILL-DOWN (`drilldown.ts`): the sub-workflow steps opened below the top workflow, top first, and each level's
|
|
84
88
|
* address, which the host page routes back here as `path`.
|
|
@@ -279,6 +283,12 @@ function WorkflowStatus({ workflow, runs, limits, setLimit }: { readonly workflo
|
|
|
279
283
|
);
|
|
280
284
|
}
|
|
281
285
|
|
|
286
|
+
/** What its Pick does with its tasks marked as needing an agent, in words. */
|
|
287
|
+
const needingAnAgentLine = (passedOverBecause: string | null): string =>
|
|
288
|
+
passedOverBecause === null
|
|
289
|
+
? 'Each ended a run at an agent step when no agent could be had. An agent can be had now, so its Pick takes them in their queue\'s order again.'
|
|
290
|
+
: `Each ended a run at an agent step when no agent could be had. Its Pick passes over them now, because ${passedOverBecause}, and takes them in their queue's order once an agent can be had.`;
|
|
291
|
+
|
|
282
292
|
/** How often an open workflow's figures are read again. */
|
|
283
293
|
const FIGURES_EVERY_MS = 15_000;
|
|
284
294
|
|
|
@@ -305,6 +315,17 @@ function WorkflowDetail({ workflow, runs, now, figuresUrl, hrefOfWorkflow }: { r
|
|
|
305
315
|
</table>
|
|
306
316
|
</>
|
|
307
317
|
)}
|
|
318
|
+
{figures.needingAnAgent.reasons.length === 0 ? null : (
|
|
319
|
+
<>
|
|
320
|
+
<h4 className="wp-h4">Queued, needing an agent</h4>
|
|
321
|
+
<p className={figures.needingAnAgent.passedOverBecause === null ? 'wp-line' : 'wp-line wp-bad'}>{needingAnAgentLine(figures.needingAnAgent.passedOverBecause)}</p>
|
|
322
|
+
<table className="wp-reasons">
|
|
323
|
+
<tbody>
|
|
324
|
+
{figures.needingAnAgent.reasons.map((b) => <tr key={b.why}><td className="wp-r">{b.tasks.toLocaleString("en-US")}</td><td>{b.why}</td></tr>)}
|
|
325
|
+
</tbody>
|
|
326
|
+
</table>
|
|
327
|
+
</>
|
|
328
|
+
)}
|
|
308
329
|
{workflow.item === null ? null : <p className="wp-line">{yieldLine(figures, workflow.finishedWord)}</p>}
|
|
309
330
|
<p className="wp-line">{runCostLine(figures)}</p>
|
|
310
331
|
<StepsTable workflow={figures} usesAgents={workflow.usesAgents} runs={runs} now={now} />
|
|
@@ -341,7 +362,7 @@ function DrillLevelView({ data, path, hrefOf, now, figuresUrl, sourceHref, phase
|
|
|
341
362
|
{level.notFound === null ? null : <p className="wp-line wp-bad">{level.name} has no sub-workflow step named {level.notFound}.</p>}
|
|
342
363
|
<p className="wp-line">{level.description}</p>
|
|
343
364
|
{w === null ? null : <p className="wp-line wp-mut">{startsLine(w)}</p>}
|
|
344
|
-
{w === null || w.queue === null ? null : <QueueBar queue={w.queue} />}
|
|
365
|
+
{w === null || w.queue === null ? null : <QueueBar queue={w.queue} queuedNeedingAnAgent={w.queuedNeedingAnAgent} />}
|
|
345
366
|
{w === null ? null : <div className="wp-node-status wp-drill-status"><WorkflowStatus workflow={w} runs={runs} limits={w.limits} setLimit={setLimit} /></div>}
|
|
346
367
|
{/* Its tasks over time: at the top a row for each step that has tasks; below it, the workflow opened and each such step of its own. */}
|
|
347
368
|
<QueueChart view={data.view} level={path.join("/")} rowWord={w === null ? "step" : "workflow"}
|
|
@@ -364,7 +385,7 @@ function DrillLevelView({ data, path, hrefOf, now, figuresUrl, sourceHref, phase
|
|
|
364
385
|
);
|
|
365
386
|
}
|
|
366
387
|
|
|
367
|
-
export function WorkflowsDashboard({ data, error, figuresUrl, sourceHref, header, phaseLabel, setLimit, setCpuLimit, stopEverything, resume, path, hrefOf }: WorkflowsDashboardProps) {
|
|
388
|
+
export function WorkflowsDashboard({ data, error, figuresUrl, sourceHref, header, phaseLabel, setLimit, setCpuLimit, stopEverything, resume, setSpendingLimit, path, hrefOf }: WorkflowsDashboardProps) {
|
|
368
389
|
const now = Date.now() / 1000;
|
|
369
390
|
const atTheTop = path.length === 0;
|
|
370
391
|
return (
|
|
@@ -374,6 +395,10 @@ export function WorkflowsDashboard({ data, error, figuresUrl, sourceHref, header
|
|
|
374
395
|
{error !== null ? `The workflows could not be read: ${error}` : data === null ? 'Reading the workflows…' : `Read from the records ${whenAgo(data.view.at, now)}.`}
|
|
375
396
|
</p>
|
|
376
397
|
{data === null ? null : <p className={data.cpu.use !== null && data.cpu.use.cores > data.cpu.limit ? 'wp-line wp-bad' : 'wp-line'}>{cpuLine(data.cpu, now)}</p>}
|
|
398
|
+
{/* The spending limit holds agent steps at every level, so every level says where it stands. */}
|
|
399
|
+
{data === null || data.view.spending === null ? null : (
|
|
400
|
+
<SpendingLimitControl spending={data.view.spending} held={heldSteps(data.runsNow)} now={now} {...(setSpendingLimit === undefined ? {} : { setSpendingLimit })} />
|
|
401
|
+
)}
|
|
377
402
|
{/* Nothing a level decides is drawn before the first read: a server draws one page for every level's address. */}
|
|
378
403
|
{data === null || !atTheTop ? null : (
|
|
379
404
|
<>
|
package/src/index.ts
CHANGED
|
@@ -14,9 +14,10 @@ import { makePickWakes } from './pick-wakes';
|
|
|
14
14
|
import { makeStepFiles } from './step-files';
|
|
15
15
|
import { makeStepUsage } from './step-usage';
|
|
16
16
|
import { keptRunningByItsBudget, makeSteps, runLimitOf } from './steps';
|
|
17
|
-
import { blockedReasons, makeTasks } from './tasks';
|
|
17
|
+
import { blockedReasons, makeTasks, needsAgentReasons } from './tasks';
|
|
18
18
|
import { buildWorkflowFigures, buildWorkflowsView, type WorkflowFigures, type WorkflowsView, type WorkflowView } from './views/workflows-view';
|
|
19
19
|
import { makeQueueCounts } from './queue-counts';
|
|
20
|
+
import { makeSpendingLimit } from './spending-limit';
|
|
20
21
|
import { sqliteBudgets, type LimitStore } from './storage/budgets';
|
|
21
22
|
import { sqliteEngineRecords, type EngineRecords } from './storage/engine-records';
|
|
22
23
|
import { sqliteStore } from './storage/sqlite-store';
|
|
@@ -30,6 +31,7 @@ export * from './budget-states';
|
|
|
30
31
|
export * from './keep-running';
|
|
31
32
|
export * from './pick-wakes';
|
|
32
33
|
export * from './queue-counts';
|
|
34
|
+
export * from './spending-limit';
|
|
33
35
|
export * from './step-files';
|
|
34
36
|
export * from './step-meter';
|
|
35
37
|
export * from './steps';
|
|
@@ -100,10 +102,12 @@ export const createWorkflowPlatform = <Phase extends string, R>(input: {
|
|
|
100
102
|
const stepFiles = makeStepFiles({ tree: project.tree, runLightNow: project.runLightNow });
|
|
101
103
|
const stepUsage = makeStepUsage({ variable: project.stepRecordVariable, addStepCompile: (record) => { Effect.runFork(Effect.catchTag(storage.stepRecords.addStepCompile(record), 'StorageError', (e) => Effect.logError(`[step-runs] a compile of step record ${record}: ${e.reason}`))); } });
|
|
102
104
|
const tasks = makeTasks({ store: storage.tasks, engine: storage.engine, stepRecords: storage.stepRecords, wakes, texts: project.texts });
|
|
105
|
+
const spending = makeSpendingLimit({ store: storage.budgets, usage: project.weekUsage === undefined ? null : project.weekUsage, wakes });
|
|
103
106
|
const steps = makeSteps<Phase, R>({
|
|
104
107
|
sourceRoot: project.sourceRoot, stepRecords: storage.stepRecords, engine: storage.engine, tasks, wakes, budgets: storage.budgets, stepFiles,
|
|
105
108
|
CurrentStepUsage: stepUsage.CurrentStepUsage, isTransientFailure: project.isTransientFailure, thisProcess: project.processes.thisProcess, inputs: storage.inputs,
|
|
106
109
|
queueChanged: (workflow) => queueCounts.changed(workflow),
|
|
110
|
+
spendingHoldsAgents: spending.holdsAgents,
|
|
107
111
|
});
|
|
108
112
|
const queueCounts = makeQueueCounts({
|
|
109
113
|
store: storage.tasks, tasks, wakes,
|
|
@@ -141,7 +145,7 @@ export const createWorkflowPlatform = <Phase extends string, R>(input: {
|
|
|
141
145
|
*/
|
|
142
146
|
const view = (r: { readonly now: number; readonly phases: ReadonlyArray<string>; readonly top: { readonly name: string; readonly description: string } }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
|
|
143
147
|
const limits = yield* limitsNow();
|
|
144
|
-
return yield* buildWorkflowsView({ declared: steps.declaredWorkflows(), phases: r.phases, top: r.top, now: r.now, taskStore: storage.tasks, locate, limitsOf: (name) => limits[name] ?? null });
|
|
148
|
+
return yield* buildWorkflowsView({ declared: steps.declaredWorkflows(), phases: r.phases, top: r.top, now: r.now, taskStore: storage.tasks, locate, limitsOf: (name) => limits[name] ?? null, spending: yield* spending.state(r.now) });
|
|
145
149
|
});
|
|
146
150
|
|
|
147
151
|
/** One workflow's figures over the `hours` before `now`, read from its own records (`buildWorkflowFigures`); none for one not declared. */
|
|
@@ -149,10 +153,15 @@ export const createWorkflowPlatform = <Phase extends string, R>(input: {
|
|
|
149
153
|
const declaration = steps.declaredWorkflows().find((d) => d.name === r.workflow);
|
|
150
154
|
return declaration === undefined ? Effect.succeed(null) : buildWorkflowFigures({
|
|
151
155
|
declaration, now: r.now, hours: r.hours, records: storage.stepRecords, engine: storage.engine, locate,
|
|
152
|
-
|
|
156
|
+
reasons: declaration.item === null
|
|
157
|
+
? Effect.succeed({ blocked: [], needingAnAgent: { reasons: [], passedOverBecause: null } })
|
|
158
|
+
: Effect.map(Effect.all({ summaries: tasks.taskSummaries({ workflow: r.workflow }), unavailable: steps.agentsUnavailable(r.workflow) }), ({ summaries, unavailable }) => ({
|
|
159
|
+
blocked: blockedReasons(summaries),
|
|
160
|
+
needingAnAgent: { reasons: needsAgentReasons(summaries), passedOverBecause: unavailable },
|
|
161
|
+
})),
|
|
153
162
|
});
|
|
154
163
|
};
|
|
155
|
-
return { project, storage, wakes, stepFiles, stepUsage, tasks, steps, view, figures, limitsNow, queueCounts };
|
|
164
|
+
return { project, storage, wakes, stepFiles, stepUsage, tasks, steps, view, figures, limitsNow, queueCounts, spending };
|
|
156
165
|
};
|
|
157
166
|
|
|
158
167
|
export type WorkflowPlatform<Phase extends string, R> = ReturnType<typeof createWorkflowPlatform<Phase, R>>;
|
package/src/keep-running.ts
CHANGED
|
@@ -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, type WorkflowDeclaration } from './steps';
|
|
13
19
|
import { runLimit, type WorkflowLimits } from './storage/budgets';
|
|
@@ -29,15 +35,20 @@ export const budgetedWorkflows = <D extends Pick<WorkflowDeclaration<string, unk
|
|
|
29
35
|
*/
|
|
30
36
|
export const runsToStart = (w: { readonly kept: number; readonly running: number }): number => Math.max(w.kept - w.running, 0);
|
|
31
37
|
|
|
32
|
-
/**
|
|
38
|
+
/**
|
|
39
|
+
* One turn's plan: for each budgeted workflow, the runs going and how many to start; none where no run could take work
|
|
40
|
+
* (`noWork`, from `steps.ts` `whyNoRunCanTakeWork`), which says why. Pure but for the reads it is given.
|
|
41
|
+
*/
|
|
33
42
|
export const planRunStarts = <D extends Pick<WorkflowDeclaration<string, unknown>, 'name' | 'pending' | 'items' | 'steps'>>(input: {
|
|
34
43
|
readonly declared: ReadonlyArray<D>;
|
|
35
44
|
readonly limitsOf: (workflow: string) => WorkflowLimits;
|
|
36
45
|
readonly runningRuns: (workflow: string) => number;
|
|
37
|
-
|
|
46
|
+
readonly noWork: (workflow: string) => string | null;
|
|
47
|
+
}): ReadonlyArray<{ readonly declaration: D; readonly running: number; readonly start: number; readonly noWork: string | null }> =>
|
|
38
48
|
budgetedWorkflows(input.declared).map((d) => {
|
|
39
49
|
const running = input.runningRuns(d.name);
|
|
40
|
-
|
|
50
|
+
const noWork = input.noWork(d.name);
|
|
51
|
+
return { declaration: d, running, noWork, start: noWork !== null ? 0 : runsToStart({ kept: runLimit(input.limitsOf(d.name)), running }) };
|
|
41
52
|
});
|
|
42
53
|
|
|
43
54
|
/**
|
package/src/project.ts
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
* WHAT A PROJECT TELLS THE PLATFORM ABOUT ITSELF: the facts no generic code can know. Everything else (how a step is
|
|
3
3
|
* measured, how a task is queued, when a waiting Pick wakes) is the platform's.
|
|
4
4
|
*/
|
|
5
|
+
import type { Effect } from 'effect';
|
|
6
|
+
import type { StorageError } from './storage/storage-error';
|
|
5
7
|
|
|
6
8
|
/** A process, by its pid and the second it started (as `ps` reports it), so a reused pid is never taken for it. */
|
|
7
9
|
export interface ProcessIdentity {
|
|
@@ -58,6 +60,34 @@ export interface CpuLimit {
|
|
|
58
60
|
readonly newestUse: () => { readonly at: number; readonly cores: number; readonly held: number; readonly waiting: number } | null;
|
|
59
61
|
}
|
|
60
62
|
|
|
63
|
+
/** One good reading of the week the project's agents spend from, as its account reports it. */
|
|
64
|
+
export interface WeekUsageReading {
|
|
65
|
+
/** How much of the week is used, in percent. */
|
|
66
|
+
readonly usedPercent: number;
|
|
67
|
+
/** When it was read, unix seconds. */
|
|
68
|
+
readonly readAt: number;
|
|
69
|
+
/** When the week starts again, unix seconds; none where the account does not say. */
|
|
70
|
+
readonly resetsAt: number | null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** What the project knows of its week now: its newest good reading, and a read that failed after it. */
|
|
74
|
+
export interface WeekUsageNow {
|
|
75
|
+
/** The newest reading that succeeded, however old; none before the first. */
|
|
76
|
+
readonly good: WeekUsageReading | null;
|
|
77
|
+
/** The newest read, where it failed after that one: when, and why in words. */
|
|
78
|
+
readonly failedSince: { readonly at: number; readonly error: string } | null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* THE WEEK THE PROJECT'S AGENTS SPEND FROM, as the project reads it: the one figure the spending limit judges
|
|
83
|
+
* (`spending-limit.ts`). The project reads it however it reads its account; the platform never asks the account itself.
|
|
84
|
+
*/
|
|
85
|
+
export interface WeekUsage {
|
|
86
|
+
readonly now: () => Effect.Effect<WeekUsageNow, StorageError>;
|
|
87
|
+
/** How old a good reading may be before a page calls it stale: the project's time between readings, and its margin. */
|
|
88
|
+
readonly staleAfterSeconds: number;
|
|
89
|
+
}
|
|
90
|
+
|
|
61
91
|
export interface WorkflowProject {
|
|
62
92
|
/** The folder a workflow's or step's source link is relative to. */
|
|
63
93
|
readonly sourceRoot: string;
|
|
@@ -77,4 +107,9 @@ export interface WorkflowProject {
|
|
|
77
107
|
/** A failure that says nothing about the work and is waited out: a step retries on it (a locked database). */
|
|
78
108
|
readonly isTransientFailure: (failure: unknown) => boolean;
|
|
79
109
|
readonly cpu: CpuLimit;
|
|
110
|
+
/**
|
|
111
|
+
* The week its agents spend from, where it reads one: the spending limit holds its agent steps by it
|
|
112
|
+
* (`spending-limit.ts`). A project that gives none has no spending limit.
|
|
113
|
+
*/
|
|
114
|
+
readonly weekUsage?: WeekUsage;
|
|
80
115
|
}
|
package/src/queue-counts.ts
CHANGED
|
@@ -18,6 +18,12 @@ import { statusCounts, type Tasks } from './tasks';
|
|
|
18
18
|
/** How long after a queue's first change it is counted: every change in that time is in the one count. */
|
|
19
19
|
export const COUNT_AFTER_MS = 5_000;
|
|
20
20
|
|
|
21
|
+
/**
|
|
22
|
+
* The count recorded beside the four statuses: how many queued tasks are marked as needing an agent (`tasks.ts`
|
|
23
|
+
* `TaskSummary.needsAgent`). Part of `queued`, never an addend of its own: a page shows it beside that row.
|
|
24
|
+
*/
|
|
25
|
+
export const QUEUED_NEEDING_AN_AGENT = 'queued, needing an agent';
|
|
26
|
+
|
|
21
27
|
export const makeQueueCounts = (deps: {
|
|
22
28
|
readonly store: Pick<TaskStore, 'recordQueueCounts'>;
|
|
23
29
|
readonly tasks: Pick<Tasks, 'taskSummaries'>;
|
|
@@ -29,7 +35,8 @@ export const makeQueueCounts = (deps: {
|
|
|
29
35
|
}) => {
|
|
30
36
|
/** Counts one workflow's queue now and records it. */
|
|
31
37
|
const count = (workflow: string): Effect.Effect<void, StorageError> => Effect.gen(function* () {
|
|
32
|
-
const
|
|
38
|
+
const summaries = yield* deps.tasks.taskSummaries({ workflow });
|
|
39
|
+
const counts = { ...statusCounts(summaries), [QUEUED_NEEDING_AN_AGENT]: summaries.filter((t) => t.status === 'queued' && t.needsAgent !== null).length };
|
|
33
40
|
yield* deps.store.recordQueueCounts({ at: Date.now() / 1000, counts: Object.entries(counts).map(([bucket, tasks]) => ({ workflow, bucket, tasks })) });
|
|
34
41
|
});
|
|
35
42
|
|
|
@@ -0,0 +1,156 @@
|
|
|
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
|
+
// It changes whether any run can take work (`steps.ts` `whyNoRunCanTakeWork`): the run planner plans again too.
|
|
143
|
+
deps.wakes.runPlanChanged({ workflow: null, source: holds ? 'a reading at or past the spending limit' : 'a reading below the spending limit' });
|
|
144
|
+
}),
|
|
145
|
+
set: (r) => Effect.gen(function* () {
|
|
146
|
+
const weekPercent = r.weekPercent;
|
|
147
|
+
if (typeof weekPercent !== 'number' || !Number.isInteger(weekPercent) || weekPercent < 0 || weekPercent > 100) {
|
|
148
|
+
return { ok: false as const, error: 'weekPercent must be a whole number from 0 to 100' };
|
|
149
|
+
}
|
|
150
|
+
yield* r.write({ sql: SET_SPENDING_LIMIT_SQL, params: [weekPercent, Date.now() / 1000] });
|
|
151
|
+
deps.wakes.runPlanChanged({ workflow: null, source: 'the spending limit set' });
|
|
152
|
+
yield* Effect.log(`[spending limit] ${weekPercent}%, from ${r.from}`);
|
|
153
|
+
return { ok: true as const, weekPercent };
|
|
154
|
+
}),
|
|
155
|
+
};
|
|
156
|
+
};
|