@jive-sh/workflow-platform 0.7.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (195) hide show
  1. package/README.md +70 -435
  2. package/component/_generated/api.ts +72 -0
  3. package/component/_generated/component.ts +629 -0
  4. package/component/_generated/dataModel.ts +60 -0
  5. package/component/_generated/server.ts +169 -0
  6. package/component/convex.config.ts +3 -0
  7. package/component/engine.ts +756 -0
  8. package/component/errors.ts +66 -0
  9. package/component/events.ts +17 -0
  10. package/component/notes.ts +19 -0
  11. package/component/places.ts +136 -0
  12. package/component/retention.ts +205 -0
  13. package/component/runEngine.ts +25 -0
  14. package/component/schema.ts +135 -0
  15. package/component/steps.ts +188 -0
  16. package/component/store.ts +513 -0
  17. package/component/tasks.ts +290 -0
  18. package/component/worker.ts +109 -0
  19. package/component/workflows.ts +83 -0
  20. package/dist/definition/agent-runner.js +9 -0
  21. package/dist/definition/agent-runner.js.map +1 -0
  22. package/dist/definition/file-store.js +9 -0
  23. package/dist/definition/file-store.js.map +1 -0
  24. package/dist/definition/program-build.js +10 -0
  25. package/dist/definition/program-build.js.map +1 -0
  26. package/dist/definition/step.js +1 -0
  27. package/dist/definition/step.js.map +1 -0
  28. package/dist/definition/task-schema.js +5 -0
  29. package/dist/definition/task-schema.js.map +1 -0
  30. package/dist/definition/tasks.js +9 -0
  31. package/dist/definition/tasks.js.map +1 -0
  32. package/dist/definition/workflow.js +117 -0
  33. package/dist/definition/workflow.js.map +1 -0
  34. package/dist/graph.js +310 -9
  35. package/dist/graph.js.map +1 -1
  36. package/dist/index.js +7 -196
  37. package/dist/index.js.map +1 -1
  38. package/package.json +9 -4
  39. package/src/definition/agent-runner.ts +59 -0
  40. package/src/definition/file-store.ts +20 -0
  41. package/src/definition/program-build.ts +30 -0
  42. package/src/definition/step.ts +106 -0
  43. package/src/definition/task-schema.ts +15 -0
  44. package/src/definition/tasks.ts +43 -0
  45. package/src/definition/workflow.ts +262 -0
  46. package/src/graph.ts +352 -19
  47. package/src/index.ts +8 -238
  48. package/worker/directory-file-store.ts +42 -0
  49. package/worker/index.ts +12 -0
  50. package/worker/platform-client.ts +144 -0
  51. package/worker/step-meter.ts +80 -0
  52. package/worker/worker-tasks.ts +27 -0
  53. package/worker/worker.test.ts +200 -0
  54. package/worker/worker.ts +240 -0
  55. package/dist/budget-states.js +0 -30
  56. package/dist/budget-states.js.map +0 -1
  57. package/dist/cpu-limit/limiter.js +0 -839
  58. package/dist/cpu-limit/limiter.js.map +0 -1
  59. package/dist/cpu-limit/use.js +0 -139
  60. package/dist/cpu-limit/use.js.map +0 -1
  61. package/dist/dashboard/agent-usage.js +0 -25
  62. package/dist/dashboard/agent-usage.js.map +0 -1
  63. package/dist/dashboard/dashboard.css +0 -148
  64. package/dist/dashboard/drilldown.js +0 -47
  65. package/dist/dashboard/drilldown.js.map +0 -1
  66. package/dist/dashboard/queue-lines.js +0 -44
  67. package/dist/dashboard/queue-lines.js.map +0 -1
  68. package/dist/dashboard/queue-table.js +0 -16
  69. package/dist/dashboard/queue-table.js.map +0 -1
  70. package/dist/dashboard/run-doing-words.js +0 -29
  71. package/dist/dashboard/run-doing-words.js.map +0 -1
  72. package/dist/dashboard/setting-words.js +0 -18
  73. package/dist/dashboard/setting-words.js.map +0 -1
  74. package/dist/dashboard/spending-words.js +0 -24
  75. package/dist/dashboard/spending-words.js.map +0 -1
  76. package/dist/failure.js +0 -35
  77. package/dist/failure.js.map +0 -1
  78. package/dist/keep-running.js +0 -79
  79. package/dist/keep-running.js.map +0 -1
  80. package/dist/outside-failure.js +0 -31
  81. package/dist/outside-failure.js.map +0 -1
  82. package/dist/pick-wakes.js +0 -125
  83. package/dist/pick-wakes.js.map +0 -1
  84. package/dist/project.js +0 -1
  85. package/dist/project.js.map +0 -1
  86. package/dist/queue-counts.js +0 -51
  87. package/dist/queue-counts.js.map +0 -1
  88. package/dist/reasons.js +0 -33
  89. package/dist/reasons.js.map +0 -1
  90. package/dist/retention.js +0 -59
  91. package/dist/retention.js.map +0 -1
  92. package/dist/settings.js +0 -88
  93. package/dist/settings.js.map +0 -1
  94. package/dist/spending-limit.js +0 -82
  95. package/dist/spending-limit.js.map +0 -1
  96. package/dist/step-files.js +0 -200
  97. package/dist/step-files.js.map +0 -1
  98. package/dist/step-meter.js +0 -97
  99. package/dist/step-meter.js.map +0 -1
  100. package/dist/step-times.js +0 -114
  101. package/dist/step-times.js.map +0 -1
  102. package/dist/step-usage.js +0 -19
  103. package/dist/step-usage.js.map +0 -1
  104. package/dist/steps.js +0 -1205
  105. package/dist/steps.js.map +0 -1
  106. package/dist/storage/agent-claims.js +0 -3
  107. package/dist/storage/agent-claims.js.map +0 -1
  108. package/dist/storage/budgets.js +0 -121
  109. package/dist/storage/budgets.js.map +0 -1
  110. package/dist/storage/engine-records.js +0 -91
  111. package/dist/storage/engine-records.js.map +0 -1
  112. package/dist/storage/engine-storage.js +0 -67
  113. package/dist/storage/engine-storage.js.map +0 -1
  114. package/dist/storage/input-records.js +0 -12
  115. package/dist/storage/input-records.js.map +0 -1
  116. package/dist/storage/move-store.js +0 -251
  117. package/dist/storage/move-store.js.map +0 -1
  118. package/dist/storage/sqlite-store.js +0 -901
  119. package/dist/storage/sqlite-store.js.map +0 -1
  120. package/dist/storage/step-records.js +0 -11
  121. package/dist/storage/step-records.js.map +0 -1
  122. package/dist/storage/storage-error.js +0 -19
  123. package/dist/storage/storage-error.js.map +0 -1
  124. package/dist/storage/task-store.js +0 -30
  125. package/dist/storage/task-store.js.map +0 -1
  126. package/dist/system-workflows.js +0 -54
  127. package/dist/system-workflows.js.map +0 -1
  128. package/dist/tasks.js +0 -500
  129. package/dist/tasks.js.map +0 -1
  130. package/dist/views/format.js +0 -37
  131. package/dist/views/format.js.map +0 -1
  132. package/dist/views/runs-now.js +0 -117
  133. package/dist/views/runs-now.js.map +0 -1
  134. package/dist/views/step-funnel.js +0 -98
  135. package/dist/views/step-funnel.js.map +0 -1
  136. package/dist/views/step-graph.js +0 -39
  137. package/dist/views/step-graph.js.map +0 -1
  138. package/dist/views/workflows-view.js +0 -236
  139. package/dist/views/workflows-view.js.map +0 -1
  140. package/src/budget-states.ts +0 -54
  141. package/src/cpu-limit/limiter.ts +0 -935
  142. package/src/cpu-limit/use.ts +0 -166
  143. package/src/dashboard/agent-usage-line.tsx +0 -28
  144. package/src/dashboard/agent-usage.ts +0 -48
  145. package/src/dashboard/dashboard.css +0 -148
  146. package/src/dashboard/drilldown.ts +0 -70
  147. package/src/dashboard/index.tsx +0 -4
  148. package/src/dashboard/limits-and-runs.tsx +0 -191
  149. package/src/dashboard/machine-controls.tsx +0 -53
  150. package/src/dashboard/queue-bar.tsx +0 -62
  151. package/src/dashboard/queue-chart.tsx +0 -149
  152. package/src/dashboard/queue-lines.ts +0 -87
  153. package/src/dashboard/queue-table.ts +0 -37
  154. package/src/dashboard/run-doing-words.ts +0 -41
  155. package/src/dashboard/setting-words.ts +0 -30
  156. package/src/dashboard/spending-limit-control.tsx +0 -47
  157. package/src/dashboard/spending-words.ts +0 -32
  158. package/src/dashboard/time-distribution.tsx +0 -61
  159. package/src/dashboard/workflow-dag.tsx +0 -322
  160. package/src/dashboard/workflow-drilldown.tsx +0 -31
  161. package/src/dashboard/workflows-dashboard.tsx +0 -532
  162. package/src/failure.ts +0 -36
  163. package/src/keep-running.ts +0 -85
  164. package/src/outside-failure.ts +0 -39
  165. package/src/pick-wakes.ts +0 -182
  166. package/src/project.ts +0 -127
  167. package/src/queue-counts.ts +0 -64
  168. package/src/reasons.ts +0 -30
  169. package/src/retention.ts +0 -90
  170. package/src/settings.ts +0 -171
  171. package/src/spending-limit.ts +0 -139
  172. package/src/step-files.ts +0 -208
  173. package/src/step-meter.ts +0 -120
  174. package/src/step-times.ts +0 -151
  175. package/src/step-usage.ts +0 -23
  176. package/src/steps.ts +0 -1616
  177. package/src/storage/agent-claims.ts +0 -63
  178. package/src/storage/budgets.ts +0 -152
  179. package/src/storage/engine-records.ts +0 -119
  180. package/src/storage/engine-storage.ts +0 -82
  181. package/src/storage/input-records.ts +0 -43
  182. package/src/storage/move-store.ts +0 -265
  183. package/src/storage/sqlite-store.ts +0 -1022
  184. package/src/storage/step-records.ts +0 -358
  185. package/src/storage/storage-error.ts +0 -35
  186. package/src/storage/task-store.ts +0 -235
  187. package/src/system-workflows.ts +0 -70
  188. package/src/tasks.ts +0 -586
  189. package/src/views/format.ts +0 -40
  190. package/src/views/runs-now.ts +0 -188
  191. package/src/views/step-funnel.ts +0 -163
  192. package/src/views/step-graph.ts +0 -77
  193. package/src/views/workflows-view.ts +0 -484
  194. package/src/workflow-dag.test.tsx +0 -89
  195. package/src/workflow-page.test.tsx +0 -170
package/src/index.ts CHANGED
@@ -1,238 +1,8 @@
1
- /**
2
- * @jive-sh/workflow-platform: durable workflows on effect/workflow, measured step by step.
3
- *
4
- * A project builds one platform with `createWorkflowPlatform(project, storage)`: its facts (`project.ts`) and where its
5
- * records live (`storage/`). The platform gives it the one way to define workflows and steps, the task queue, waiting
6
- * Picks and the trigger's plan.
7
- */
8
- import { Effect } from 'effect';
9
- import fs from 'node:fs';
10
- import path from 'node:path';
11
- import type { StorageError } from './storage/storage-error';
12
- import type { WorkflowProject } from './project';
13
- import { makePickWakes } from './pick-wakes';
14
- import { makeStepFiles } from './step-files';
15
- import { makeStepUsage } from './step-usage';
16
- import { keptRunningByItsBudget, makeSteps, runLimitOf, tasksAreRuns } from './steps';
17
- import { blockedReasons, makeTasks, needsAgentReasons } from './tasks';
18
- import { buildWorkflowFigures, buildWorkflowsView, type WorkflowFigures, type WorkflowsView, type WorkflowView } from './views/workflows-view';
19
- import { makeQueueCounts } from './queue-counts';
20
- import { makeStepTimes } from './step-times';
21
- import { makeSpendingLimit } from './spending-limit';
22
- import { makeRetention } from './retention';
23
- import { checkedSettings, RUNTIME_SETTINGS, settingValueRefusal, stepSetting, workflowSetting, type Effective, type SettingLevel, type SettingName, type SettingsTree, type SettingValues } from './settings';
24
-
25
- /** Every setting as resolved at one moment (`platform.settings.now`). */
26
- export interface SettingsNow {
27
- readonly ofStep: <N extends SettingName>(r: { readonly workflow: string; readonly step: string; readonly name: N }) => Effective<SettingValues[N]>;
28
- readonly ofWorkflow: <N extends SettingName>(r: { readonly workflow: string; readonly name: N }) => Effective<SettingValues[N]>;
29
- }
30
- import { makeSystemWorkflows } from './system-workflows';
31
- import { sqliteBudgets, type LimitStore } from './storage/budgets';
32
- import { sqliteEngineRecords, type EngineRecords } from './storage/engine-records';
33
- import { sqliteStore } from './storage/sqlite-store';
34
- import type { StepRecords } from './storage/step-records';
35
- import type { TaskStore } from './storage/task-store';
36
- import type { InputRecords } from './storage/input-records';
37
- import type { AgentClaims } from './storage/agent-claims';
38
-
39
- export * from './failure';
40
- export * from './outside-failure';
41
- export * from './project';
42
- export * from './budget-states';
43
- export * from './keep-running';
44
- export * from './pick-wakes';
45
- export * from './queue-counts';
46
- export * from './spending-limit';
47
- export * from './step-files';
48
- export * from './step-meter';
49
- export * from './steps';
50
- export * from './tasks';
51
- export * from './cpu-limit/use';
52
- export * from './cpu-limit/limiter';
53
- export * from './storage/budgets';
54
- export * from './storage/engine-records';
55
- export * from './storage/sqlite-store';
56
- export * from './storage/step-records';
57
- export * from './storage/input-records';
58
- export * from './storage/agent-claims';
59
- export * from './storage/storage-error';
60
- export * from './storage/move-store';
61
- export * from './storage/engine-storage';
62
- export * from './graph';
63
- export * from './reasons';
64
- export * from './views/runs-now';
65
- export * from './views/step-funnel';
66
- export * from './views/step-graph';
67
- export * from './step-times';
68
- export * from './settings';
69
- export * from './retention';
70
- export * from './system-workflows';
71
- export * from './views/workflows-view';
72
- export type { NewNote, TaskStore, TextChange } from './storage/task-store';
73
- export type { AgentUsage, UsageLimit } from './dashboard/agent-usage';
74
-
75
- /** Where a project's records live: each store an interface, so another database can stand behind any of them. */
76
- export interface WorkflowStorage {
77
- readonly stepRecords: StepRecords;
78
- readonly tasks: TaskStore;
79
- readonly inputs: InputRecords;
80
- readonly engine: EngineRecords;
81
- readonly budgets: LimitStore;
82
- /** Each run's claim on its top workflow's agents (`storage/agent-claims.ts`). */
83
- readonly claims: AgentClaims;
84
- }
85
-
86
- /**
87
- * The storage as SQLite files: the platform's one database (step records, tasks, input runs, the limits, and the schema the
88
- * project declares beside them), and the engine's own (`STORAGE.md` says why the engine keeps a file of its own). A test
89
- * may name other files for each.
90
- */
91
- export const sqliteStorage = (options: {
92
- readonly stepRecordsFile: () => string | null;
93
- readonly engineFile: () => string;
94
- readonly budgetsFile: () => string;
95
- readonly processes: WorkflowProject['processes'];
96
- /** The file the step records had of their own, read until they have moved (`storage/move-store.ts`). */
97
- readonly movedFrom?: () => string | null;
98
- /** Whether the store makes a missing file; the project's boot makes its own database (`sqliteStore` `creates`). */
99
- readonly creates?: (file: string) => boolean;
100
- }): WorkflowStorage => {
101
- const store = sqliteStore({ file: options.stepRecordsFile, processes: options.processes, ...(options.movedFrom === undefined ? {} : { movedFrom: options.movedFrom }), ...(options.creates === undefined ? {} : { creates: options.creates }) });
102
- return {
103
- stepRecords: store.stepRecords,
104
- tasks: store.tasks,
105
- inputs: store.inputs,
106
- claims: store.claims,
107
- engine: sqliteEngineRecords({ file: options.engineFile }),
108
- budgets: sqliteBudgets({ file: options.budgetsFile }),
109
- };
110
- };
111
-
112
- /**
113
- * ONE PROJECT'S PLATFORM. `R` is what its workflows' lists of work run under.
114
- */
115
- export const createWorkflowPlatform = <R>(input: {
116
- readonly project: WorkflowProject;
117
- readonly storage: WorkflowStorage;
118
- }) => {
119
- const { project, storage } = input;
120
- const wakes = makePickWakes();
121
- const stepFiles = makeStepFiles({ tree: project.tree, runLightNow: project.runLightNow });
122
- 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}`))); } });
123
- const tasks = makeTasks({ store: storage.tasks, engine: storage.engine, stepRecords: storage.stepRecords, wakes, texts: project.texts });
124
- const spending = makeSpendingLimit({ store: storage.budgets, usage: project.weekUsage === undefined ? null : project.weekUsage, wakes });
125
- // The app's platform-wide settings, checked where they enter: what every workflow and step inherits (`settings.ts`).
126
- const appSettings = checkedSettings({ what: "the app's settings", ...(project.settings ?? {}) });
127
- const { oneStepSystemWorkflow, ...steps } = makeSteps<R>({
128
- sourceRoot: project.sourceRoot, stepRecords: storage.stepRecords, engine: storage.engine, tasks, wakes, budgets: storage.budgets, stepFiles,
129
- CurrentStepUsage: stepUsage.CurrentStepUsage, isTransientFailure: project.isTransientFailure, thisProcess: project.processes.thisProcess, inputs: storage.inputs,
130
- queueChanged: (workflow) => queueCounts.changed(workflow),
131
- spendingHoldsAgents: spending.holdsAgents,
132
- claims: storage.claims,
133
- appSettings,
134
- });
135
- /** Whether a workflow's tasks are its runs (`steps.ts` `tasksAreRuns`), among the workflows declared now. */
136
- const runsAreTasks = (workflow: string): boolean => {
137
- const declared = steps.declaredWorkflows();
138
- const d = declared.find((x) => x.name === workflow);
139
- return d !== undefined && tasksAreRuns(d, declared);
140
- };
141
- const queueCounts = makeQueueCounts({
142
- store: storage.tasks, tasks, wakes,
143
- withQueues: () => steps.declaredWorkflows().filter((d) => d.item !== null || runsAreTasks(d.name)).map((d) => d.name),
144
- });
145
- /**
146
- * Every workflow's limits now, by name, in one read: what a page's controls show. Every workflow has a run limit
147
- * (`steps.ts` `runLimitOf`), none meaning no limit; only one its budget keeps going has an agents' limit. Empty where no
148
- * store is read (a test).
149
- */
150
- const limitsNow = (): Effect.Effect<Readonly<Record<string, NonNullable<WorkflowView['limits']>>>, StorageError> =>
151
- Effect.map(storage.budgets.storedLimits(), (stored) => (stored === null ? {} : Object.fromEntries(steps.declaredWorkflows().map((d) => {
152
- const limits = stored.get(d.name) ?? { agents: 0, runs: null };
153
- return [d.name, { agents: keptRunningByItsBudget(d) ? limits.agents : null, runs: runLimitOf(d, limits), runsSet: limits.runs !== null, agentsSet: stored.has(d.name) }] as const;
154
- }))));
155
-
156
- /** Each source file's text, read again only when the file changed: a page's links name the line a definition is on now. */
157
- const texts = new Map<string, { readonly changed: number; readonly text: string } | null>();
158
- const locate = (s: { readonly path: string; readonly anchor: string }): number | null => {
159
- const file = path.join(project.sourceRoot, s.path);
160
- try {
161
- const changed = fs.statSync(file).mtimeMs;
162
- if (texts.get(s.path)?.changed !== changed) texts.set(s.path, { changed, text: fs.readFileSync(file, 'utf8') });
163
- } catch {
164
- texts.set(s.path, null);
165
- }
166
- const text = texts.get(s.path)?.text;
167
- const at = text === undefined ? -1 : text.indexOf(s.anchor);
168
- return text === undefined || at < 0 ? null : text.slice(0, at).split('\n').length;
169
- };
170
-
171
- /**
172
- * Every workflow as a dashboard shows it before one is opened, read now (`views/workflows-view.ts` `buildWorkflowsView`).
173
- */
174
- const view = (r: { readonly now: number; readonly top: string }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
175
- const limits = yield* limitsNow();
176
- return yield* buildWorkflowsView({ declared: steps.declaredWorkflows(), app: appSettings, stored: yield* storage.budgets.storedSettings(), top: r.top, now: r.now, taskStore: storage.tasks, locate, limitsOf: (name) => limits[name] ?? null, spending: yield* spending.state(r.now) });
177
- });
178
-
179
- /** One workflow's figures over the `hours` before `now`, read from its own records (`buildWorkflowFigures`); none for one not declared. */
180
- const figures = (r: { readonly workflow: string; readonly now: number; readonly hours: number }): Effect.Effect<WorkflowFigures | null, StorageError> => {
181
- const declaration = steps.declaredWorkflows().find((d) => d.name === r.workflow);
182
- // The workflows whose runs start it as a step (`defineSubWorkflow`), and the step's name in each: their tasks pass through it.
183
- const asAStepOf = steps.declaredWorkflows().flatMap((p) => p.steps().flatMap((s) => (s.workflow === r.workflow && s.runsOnItsOwnTrigger !== true ? [{ workflow: p.name, step: s.name }] : [])));
184
- return declaration === undefined ? Effect.succeed(null) : buildWorkflowFigures({
185
- declaration, now: r.now, hours: r.hours, records: storage.stepRecords, engine: storage.engine, locate, asAStepOf,
186
- reasons: declaration.item === null && !runsAreTasks(r.workflow)
187
- ? Effect.succeed({ blocked: [], needingAnAgent: { reasons: [], passedOverBecause: null } })
188
- : Effect.map(Effect.all({ summaries: tasks.taskSummaries({ workflow: r.workflow }), noAgentFree: steps.whyNoAgentIsFree(r.workflow) }), ({ summaries, noAgentFree }) => ({
189
- blocked: blockedReasons(summaries),
190
- needingAnAgent: { reasons: needsAgentReasons(summaries), passedOverBecause: noAgentFree },
191
- })),
192
- });
193
- };
194
- /** Each step's time distribution over the current version of its workflow, held in memory (`step-times.ts`). */
195
- const stepTimes = makeStepTimes({
196
- records: storage.stepRecords, engine: storage.engine, versionOf: steps.versionOf,
197
- stepsOf: (workflow) => steps.declaredWorkflows().find((d) => d.name === workflow)?.steps().map((s) => s.name) ?? [],
198
- });
199
- /** Retention (`retention.ts`): what the platform's own workflow Retention runs to delete the records its workflows keep no longer. */
200
- const retention = makeRetention({
201
- declared: steps.declaredWorkflows, app: appSettings, stored: storage.budgets.storedSettings, records: storage.stepRecords, tasks: storage.tasks, engine: storage.engine,
202
- queueChanged: (workflow) => queueCounts.changed(workflow),
203
- });
204
- /**
205
- * THE PLATFORM'S OWN WORKFLOWS (`system-workflows.ts`), defined here, before the app defines any of its own: the app's
206
- * engine runs `system.layer`, and its scheduler starts each of `system.workflows` on its schedule.
207
- */
208
- const system = makeSystemWorkflows<R>({ define: oneStepSystemWorkflow, retention, schedules: project.systemSchedules });
209
- /** The settings every workflow and step inherits (`settings.ts`), over every workflow declared now and the app's. */
210
- const settings = {
211
- /** An agent step's model and where it is set: set in code alone, so read at once. */
212
- model: (r: { readonly workflow: string; readonly step: string }): Effective<string | null> =>
213
- stepSetting({ declared: steps.declaredWorkflows(), app: appSettings, stored: [] }, { ...r, name: 'model' }),
214
- /** Every setting now, the retention settings set while the app runs read from the store first. */
215
- now: (): Effect.Effect<SettingsNow, StorageError> => Effect.map(storage.budgets.storedSettings(), (stored): SettingsNow => {
216
- const tree: SettingsTree = { declared: steps.declaredWorkflows(), app: appSettings, stored };
217
- return { ofStep: (r) => stepSetting(tree, r), ofWorkflow: (r) => workflowSetting(tree, r) };
218
- }),
219
- /**
220
- * WHY A CHANGE A PAGE ASKS FOR IS REFUSED, none where the project may store it (`storage/budgets.ts`
221
- * `SET_WORKFLOW_SETTING_SQL`): a retention setting, at a level declared now, to a good value or none (the code's).
222
- */
223
- changeRefusal: (c: { readonly level: SettingLevel; readonly name: string; readonly value: number | null }): string | null => {
224
- const name = RUNTIME_SETTINGS.find((n) => n === c.name);
225
- if (name === undefined) return `${c.name} is no setting a page sets: only ${RUNTIME_SETTINGS.join(' and ')}`;
226
- if (c.level.kind !== 'app') {
227
- const { level } = c;
228
- const d = steps.declaredWorkflows().find((x) => x.name === level.workflow);
229
- if (d === undefined) return `no workflow ${level.workflow} is declared`;
230
- if (level.kind === 'step' && !d.steps().some((s) => s.name === level.step)) return `${d.name} has no step ${level.step}`;
231
- }
232
- return c.value === null ? null : settingValueRefusal(name, c.value);
233
- },
234
- };
235
- return { project, storage, wakes, stepFiles, stepUsage, tasks, steps, view, figures, limitsNow, queueCounts, spending, stepTimes, retention, system, settings };
236
- };
237
-
238
- export type WorkflowPlatform<R> = ReturnType<typeof createWorkflowPlatform<R>>;
1
+ export * as AgentRunner from "./definition/agent-runner"
2
+ export * as FileStore from "./definition/file-store"
3
+ export * as ProgramBuild from "./definition/program-build"
4
+ export * as Tasks from "./definition/tasks"
5
+ export * as TaskSchema from "./definition/task-schema"
6
+ export * as Workflow from "./definition/workflow"
7
+ export type * from "./definition/step"
8
+ export * from "./graph"
@@ -0,0 +1,42 @@
1
+ import { createHash } from "node:crypto"
2
+ import { Effect, FileSystem, Layer, Path, pipe } from "effect"
3
+ import { FileStore, FileStoreError, type IFileStore } from "../src/definition/file-store"
4
+ import type { TaskFile } from "../src/graph"
5
+
6
+ /** A file store in a directory every worker can reach. A file's reference is `<sha-256 of its bytes>/<name>`, so equal files are stored once. */
7
+ export class DirectoryFileStore implements IFileStore {
8
+ constructor(
9
+ private readonly fileSystem: FileSystem.FileSystem,
10
+ private readonly path: Path.Path,
11
+ private readonly root: string,
12
+ ) {}
13
+
14
+ *write(input: { readonly name: string; readonly bytes: Uint8Array }) {
15
+ const ref = `${createHash("sha256").update(input.bytes).digest("hex")}/${this.path.basename(input.name)}`
16
+ const target = this.path.join(this.root, ref)
17
+ yield* pipe(
18
+ this.fileSystem.makeDirectory(this.path.dirname(target), { recursive: true }),
19
+ Effect.andThen(this.fileSystem.writeFile(target, input.bytes)),
20
+ Effect.mapError((cause) => new FileStoreError({ file: input.name, cause })),
21
+ )
22
+ const file: TaskFile = { name: input.name, ref }
23
+ return file
24
+ }
25
+
26
+ *read(file: TaskFile) {
27
+ return yield* pipe(
28
+ this.fileSystem.readFile(this.path.join(this.root, file.ref)),
29
+ Effect.mapError((cause) => new FileStoreError({ file: file.name, cause })),
30
+ )
31
+ }
32
+ }
33
+
34
+ /** The directory file store as the `FileStore` an organization gives its workers; a relative root is resolved against the worker's working directory. */
35
+ export const directoryFileStoreLayer = (root: string): Layer.Layer<FileStore, never, FileSystem.FileSystem | Path.Path> =>
36
+ Layer.effect(
37
+ FileStore,
38
+ Effect.gen(function* () {
39
+ const path = yield* Path.Path
40
+ return new DirectoryFileStore(yield* FileSystem.FileSystem, path, path.resolve(root))
41
+ }),
42
+ )
@@ -0,0 +1,12 @@
1
+ export { DirectoryFileStore, directoryFileStoreLayer } from "./directory-file-store"
2
+ export {
3
+ ConvexWorkflowPlatformClient,
4
+ type IWorkflowPlatformClient,
5
+ PlatformCallFailed,
6
+ type CompleteInput,
7
+ type ReportedOtherWrite,
8
+ type TakenStep,
9
+ type WorkerFunctions,
10
+ WorkflowPlatformClient,
11
+ } from "./platform-client"
12
+ export { type ServicesOfWorkflows, WorkerLacksService, type WorkerOptions, type WorkerServices, type WorkResult, workForever, workOnce, workUntilIdle } from "./worker"
@@ -0,0 +1,144 @@
1
+ import type { ConvexHttpClient } from "convex/browser"
2
+ import type { FunctionReference } from "convex/server"
3
+ import { Context, Data, Effect, Schema } from "effect"
4
+ import type { FoundTask, TasksAt } from "../src/definition/tasks"
5
+ import type { StepMeasurements, TaskFile } from "../src/graph"
6
+
7
+ export class PlatformCallFailed extends Data.TaggedError("PlatformCallFailed")<{ readonly call: string; readonly cause: unknown }> {
8
+ override get message() {
9
+ return `${this.call} failed: ${String(this.cause)}`
10
+ }
11
+ }
12
+
13
+ const TaskNote = Schema.Struct({
14
+ workflow: Schema.String,
15
+ step: Schema.optionalKey(Schema.String),
16
+ note: Schema.String,
17
+ at: Schema.Number,
18
+ by: Schema.optionalKey(Schema.Struct({ workflow: Schema.String, step: Schema.String, task: Schema.String })),
19
+ })
20
+ const File = Schema.Struct({ name: Schema.String, ref: Schema.String })
21
+
22
+ const TakenStep = Schema.Struct({
23
+ run: Schema.String,
24
+ workflow: Schema.String,
25
+ step: Schema.String,
26
+ task: Schema.Struct({ id: Schema.String, fields: Schema.Unknown, files: Schema.Array(File), notes: Schema.Array(TaskNote) }),
27
+ lastFingerprint: Schema.optionalKey(Schema.String),
28
+ })
29
+ export type TakenStep = typeof TakenStep.Type
30
+ const decodeTaken = Schema.decodeUnknownEffect(Schema.NullOr(TakenStep))
31
+
32
+ const Found = Schema.Array(
33
+ Schema.Struct({
34
+ taskId: Schema.String,
35
+ workflow: Schema.String,
36
+ fields: Schema.Unknown,
37
+ files: Schema.Array(File),
38
+ notes: Schema.Array(TaskNote),
39
+ at: Schema.Union([Schema.Struct({ line: Schema.String }), Schema.Struct({ step: Schema.String }), Schema.Struct({ end: Schema.String })]),
40
+ }),
41
+ )
42
+ const decodeFound = Schema.decodeUnknownEffect(Found)
43
+
44
+ /** A write to another task as a worker reports it: its files already kept in the organization's file store. */
45
+ export interface ReportedOtherWrite {
46
+ readonly workflow: string
47
+ readonly task: string
48
+ readonly fields?: Readonly<Record<string, unknown>>
49
+ readonly files?: ReadonlyArray<TaskFile>
50
+ readonly note: string
51
+ }
52
+
53
+ export interface CompleteInput {
54
+ readonly run: string
55
+ readonly workflow: string
56
+ readonly endState: string
57
+ readonly fields?: Record<string, unknown>
58
+ readonly files?: ReadonlyArray<TaskFile>
59
+ readonly measurements: StepMeasurements
60
+ readonly note?: string
61
+ /** From a step that syncs a declared item list: every item on it, as encoded task fields. */
62
+ readonly listed?: ReadonlyArray<unknown>
63
+ /** Writes to other tasks, applied with the run's own result. */
64
+ readonly others?: ReadonlyArray<ReportedOtherWrite>
65
+ }
66
+
67
+ /** What a worker asks of the workflow platform in Convex: take a task, report on it, and read other tasks for its run. */
68
+ export interface IWorkflowPlatformClient {
69
+ take(input: { readonly worker: string; readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>; readonly leaseMs: number }): Effect.fn.Return<TakenStep | null, PlatformCallFailed>
70
+ complete(input: CompleteInput): Effect.fn.Return<void, PlatformCallFailed>
71
+ fail(input: { readonly workflow: string; readonly run: string; readonly error: string; readonly measurements: StepMeasurements }): Effect.fn.Return<void, PlatformCallFailed>
72
+ heartbeat(input: { readonly workflow: string; readonly run: string; readonly leaseMs: number }): Effect.fn.Return<void, PlatformCallFailed>
73
+ /** Tasks of `in` that the run `run` of `workflow` asks for; Convex refuses a workflow its step may not read. */
74
+ findTasks(input: {
75
+ readonly workflow: string
76
+ readonly run: string
77
+ readonly in: string
78
+ readonly where?: Readonly<Record<string, unknown>>
79
+ readonly at?: TasksAt
80
+ readonly limit: number
81
+ }): Effect.fn.Return<ReadonlyArray<FoundTask>, PlatformCallFailed>
82
+ }
83
+
84
+ export class WorkflowPlatformClient extends Context.Service<WorkflowPlatformClient, IWorkflowPlatformClient>()("WorkflowPlatformClient") {}
85
+
86
+ /** The workforce functions `workforceFunctions` defines, as the workforce app's generated `api` names them. */
87
+ export interface WorkerFunctions {
88
+ readonly take: FunctionReference<"mutation">
89
+ readonly complete: FunctionReference<"mutation">
90
+ readonly fail: FunctionReference<"mutation">
91
+ readonly heartbeat: FunctionReference<"mutation">
92
+ readonly findTasks: FunctionReference<"query">
93
+ }
94
+
95
+ export class ConvexWorkflowPlatformClient implements IWorkflowPlatformClient {
96
+ constructor(
97
+ private readonly client: ConvexHttpClient,
98
+ private readonly functions: WorkerFunctions,
99
+ ) {}
100
+
101
+ private call(name: Exclude<keyof WorkerFunctions, "findTasks">, args: Record<string, unknown>) {
102
+ return Effect.tryPromise({
103
+ try: (): Promise<unknown> => this.client.mutation(this.functions[name], args),
104
+ catch: (cause) => new PlatformCallFailed({ call: name, cause }),
105
+ })
106
+ }
107
+
108
+ *take(input: { readonly worker: string; readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>; readonly leaseMs: number }) {
109
+ const taken = yield* this.call("take", { ...input, steps: [...input.steps] })
110
+ return yield* Effect.mapError(decodeTaken(taken), (cause) => new PlatformCallFailed({ call: "take", cause }))
111
+ }
112
+
113
+ *complete(input: CompleteInput) {
114
+ yield* this.call("complete", {
115
+ ...input,
116
+ ...(input.files !== undefined ? { files: [...input.files] } : {}),
117
+ ...(input.listed !== undefined ? { listed: [...input.listed] } : {}),
118
+ ...(input.others !== undefined ? { others: input.others.map((other) => ({ ...other, ...(other.files !== undefined ? { files: [...other.files] } : {}) })) } : {}),
119
+ })
120
+ }
121
+
122
+ *fail(input: { readonly workflow: string; readonly run: string; readonly error: string; readonly measurements: StepMeasurements }) {
123
+ yield* this.call("fail", input)
124
+ }
125
+
126
+ *heartbeat(input: { readonly workflow: string; readonly run: string; readonly leaseMs: number }) {
127
+ yield* this.call("heartbeat", input)
128
+ }
129
+
130
+ *findTasks(input: {
131
+ readonly workflow: string
132
+ readonly run: string
133
+ readonly in: string
134
+ readonly where?: Readonly<Record<string, unknown>>
135
+ readonly at?: TasksAt
136
+ readonly limit: number
137
+ }) {
138
+ const found = yield* Effect.tryPromise({
139
+ try: (): Promise<unknown> => this.client.query(this.functions.findTasks, { ...input }),
140
+ catch: (cause) => new PlatformCallFailed({ call: "findTasks", cause }),
141
+ })
142
+ return yield* Effect.mapError(decodeFound(found), (cause) => new PlatformCallFailed({ call: "findTasks", cause }))
143
+ }
144
+ }
@@ -0,0 +1,80 @@
1
+ import { Effect, Option } from "effect"
2
+ import type { AgentRunInput, AgentRunResult, IAgentRunner } from "../src/definition/agent-runner"
3
+ import type { IProgramBuild, ProgramBuildResult } from "../src/definition/program-build"
4
+ import type { TaskFile } from "../src/graph"
5
+ import { noSpend, type StepMeasurements, type StepSpend } from "../src/graph"
6
+
7
+ /**
8
+ * Measures one step run on this worker: the worker process's CPU and memory while it ran, and the spend of every agent
9
+ * run it made through the metered `AgentRunner`. Steps that start processes or compile report those themselves.
10
+ */
11
+ export class StepMeter {
12
+ private spend: StepSpend = noSpend
13
+ private agent: string | undefined = undefined
14
+ private transcripts: Array<TaskFile> = []
15
+ private readonly cpuAtStart = process.cpuUsage()
16
+ private peakRssBytes = process.memoryUsage().rss
17
+
18
+ /** The organization's agent runner, with every run's spend and agent added to this meter. */
19
+ meteredAgentRunner(inner: IAgentRunner): IAgentRunner {
20
+ const meter = this
21
+ return {
22
+ *run(input: AgentRunInput) {
23
+ const result: AgentRunResult = yield* inner.run(input)
24
+ meter.addAgentRun(result)
25
+ return result
26
+ },
27
+ }
28
+ }
29
+
30
+ /** The organization's program build, with every build's compiled functions added to this meter's compiles. */
31
+ meteredProgramBuild(inner: IProgramBuild): IProgramBuild {
32
+ const meter = this
33
+ return {
34
+ *build(input: { readonly changedFunctions: ReadonlyArray<string> }) {
35
+ const result: ProgramBuildResult = yield* inner.build(input)
36
+ meter.spend = { ...meter.spend, compiles: meter.spend.compiles + result.functions.compiled }
37
+ return result
38
+ },
39
+ }
40
+ }
41
+
42
+ private addAgentRun(result: AgentRunResult) {
43
+ this.spend = {
44
+ fresh: this.spend.fresh + result.spend.fresh,
45
+ cacheWrite: this.spend.cacheWrite + result.spend.cacheWrite,
46
+ cacheRead: this.spend.cacheRead + result.spend.cacheRead,
47
+ output: this.spend.output + result.spend.output,
48
+ requests: this.spend.requests + result.spend.requests,
49
+ costUsd: this.spend.costUsd + result.spend.costUsd,
50
+ compiles: this.spend.compiles,
51
+ }
52
+ this.agent = result.agent
53
+ this.transcripts = [...this.transcripts, result.transcript]
54
+ }
55
+
56
+ /** The step's figures so far, with what the step itself reported about processes it started. */
57
+ measurements(input: {
58
+ readonly files: ReadonlyArray<string>
59
+ readonly reported: { readonly childCpuSeconds?: number; readonly compiles?: number }
60
+ readonly fingerprint: Option.Option<string>
61
+ }) {
62
+ return Effect.sync((): StepMeasurements => {
63
+ const cpu = process.cpuUsage(this.cpuAtStart)
64
+ this.peakRssBytes = Math.max(this.peakRssBytes, process.memoryUsage().rss)
65
+ return {
66
+ spend: { ...this.spend, compiles: this.spend.compiles + (input.reported.compiles ?? 0) },
67
+ used: {
68
+ ownCpuSeconds: (cpu.user + cpu.system) / 1_000_000,
69
+ childCpuSeconds: input.reported.childCpuSeconds ?? 0,
70
+ peakMemoryMb: this.peakRssBytes / (1024 * 1024),
71
+ filesWritten: input.files.length,
72
+ },
73
+ files: [...input.files],
74
+ transcripts: [...this.transcripts],
75
+ ...(Option.isSome(input.fingerprint) ? { fingerprint: input.fingerprint.value } : {}),
76
+ ...(this.agent !== undefined ? { agent: this.agent } : {}),
77
+ }
78
+ })
79
+ }
80
+ }
@@ -0,0 +1,27 @@
1
+ import { Effect } from "effect"
2
+ import { type ITasks, type TasksAt, TasksCallFailed } from "../src/definition/tasks"
3
+ import type { IWorkflowPlatformClient, TakenStep } from "./platform-client"
4
+
5
+ /** The `Tasks` a worker gives one run: every read goes to Convex as that run's, which checks the step may make it. */
6
+ export class RunTasks implements ITasks {
7
+ constructor(
8
+ private readonly client: IWorkflowPlatformClient,
9
+ private readonly taken: TakenStep,
10
+ ) {}
11
+
12
+ *find(input: { readonly workflow?: string; readonly where?: Readonly<Record<string, unknown>>; readonly at?: TasksAt; readonly limit: number }) {
13
+ return yield* Effect.mapError(
14
+ Effect.gen(() =>
15
+ this.client.findTasks({
16
+ workflow: this.taken.workflow,
17
+ run: this.taken.run,
18
+ in: input.workflow ?? this.taken.workflow,
19
+ limit: input.limit,
20
+ ...(input.where !== undefined ? { where: input.where } : {}),
21
+ ...(input.at !== undefined ? { at: input.at } : {}),
22
+ }),
23
+ ),
24
+ (cause) => new TasksCallFailed({ cause }),
25
+ )
26
+ }
27
+ }