@jive-sh/workflow-platform 0.7.0 → 1.0.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 +66 -435
  2. package/component/_generated/api.ts +72 -0
  3. package/component/_generated/component.ts +621 -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 +755 -0
  8. package/component/errors.ts +66 -0
  9. package/component/events.ts +17 -0
  10. package/component/notes.ts +13 -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 +132 -0
  15. package/component/steps.ts +188 -0
  16. package/component/store.ts +512 -0
  17. package/component/tasks.ts +289 -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 +111 -0
  33. package/dist/definition/workflow.js.map +1 -0
  34. package/dist/graph.js +301 -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 +255 -0
  46. package/src/graph.ts +341 -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 +138 -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
@@ -0,0 +1,240 @@
1
+ import { Cause, Context, Data, Duration, Effect, Exit, Option, pipe, Result, Schedule, Schema } from "effect"
2
+ import { AgentRunner } from "../src/definition/agent-runner"
3
+ import { FileStore } from "../src/definition/file-store"
4
+ import { ProgramBuild } from "../src/definition/program-build"
5
+ import { Tasks } from "../src/definition/tasks"
6
+ import type { WorkflowDefinition } from "../src/definition/workflow"
7
+ import { nothingUsed, noSpend, type StepMeasurements, type TaskFile } from "../src/graph"
8
+ import { type PlatformCallFailed, type ReportedOtherWrite, type TakenStep, WorkflowPlatformClient } from "./platform-client"
9
+ import { StepMeter } from "./step-meter"
10
+ import { RunTasks } from "./worker-tasks"
11
+
12
+ /**
13
+ * What a worker needs around it: the platform to take tasks from, the file store it keeps steps' files in, and the
14
+ * organization's implementations of every service its workflows' steps declare. `Tasks` it makes itself, per run.
15
+ */
16
+ export type WorkerServices<Services = never> = WorkflowPlatformClient | FileStore | Exclude<Services, Tasks>
17
+
18
+ /** The services the steps of `Workflows` declare, together. */
19
+ export type ServicesOfWorkflows<Workflows extends ReadonlyArray<WorkflowDefinition<any, any, any>>> =
20
+ Workflows[number] extends WorkflowDefinition<any, any, infer Services> ? Services : never
21
+
22
+ export interface WorkerOptions<Workflows extends ReadonlyArray<WorkflowDefinition<any, any, any>> = ReadonlyArray<WorkflowDefinition<any, any, any>>> {
23
+ /** Recorded on every step run this worker takes. */
24
+ readonly worker: string
25
+ /** Every code and agent step of these workflows is one this worker can run. */
26
+ readonly workflows: Workflows
27
+ /** How long a taken task stays this worker's without a heartbeat before Convex gives it to another. */
28
+ readonly leaseMs: number
29
+ }
30
+
31
+ /** A worker refuses to start when a step it serves declares a service it was not given. */
32
+ export class WorkerLacksService extends Data.TaggedError("WorkerLacksService")<{ readonly workflow: string; readonly step: string; readonly service: string }> {
33
+ override get message() {
34
+ return `this worker cannot run step ${this.step} of ${this.workflow}: the step uses ${this.service}, which the worker was not given`
35
+ }
36
+ }
37
+
38
+ /** What one attempt to take a task did. */
39
+ export type WorkResult = { readonly _tag: "Idle" } | { readonly _tag: "Ran"; readonly taken: TakenStep; readonly outcome: "completed" | "failed" | "unreported" }
40
+
41
+ /** Fails with the first step of `workflows` whose declared services `context` lacks. */
42
+ const checkServices = function* (input: { readonly workflows: ReadonlyArray<WorkflowDefinition<any, any, any>>; readonly context: Context.Context<never> }): Effect.fn.Return<void, WorkerLacksService> {
43
+ for (const workflow of input.workflows) {
44
+ for (const [step, definition] of Object.entries(workflow.runnableSteps)) {
45
+ for (const service of definition.access.services) {
46
+ if (Option.isNone(Context.getOption(input.context, service))) {
47
+ return yield* Effect.fail(new WorkerLacksService({ workflow: workflow.name, step, service: service.key }))
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Takes one task from Convex, runs its step with only the services the step declares, and reports the end state with
56
+ * the task's changed fields and files and the step's writes to other tasks. A step that fails or dies is reported as
57
+ * failed, and Convex puts its task back at the front of its queue.
58
+ */
59
+ export const workOnce = function* <const Workflows extends ReadonlyArray<WorkflowDefinition<any, any, any>>>(
60
+ options: WorkerOptions<Workflows>,
61
+ ): Effect.fn.Return<WorkResult, unknown, WorkerServices<ServicesOfWorkflows<Workflows>>> {
62
+ const context = yield* Effect.context<WorkerServices<ServicesOfWorkflows<Workflows>>>()
63
+ yield* checkServices({ workflows: options.workflows, context })
64
+ return yield* runOnce({ options, context })
65
+ }
66
+
67
+ const runOnce = function* <Services>(input: {
68
+ readonly options: WorkerOptions
69
+ readonly context: Context.Context<WorkerServices<Services>>
70
+ }): Effect.fn.Return<WorkResult, unknown, WorkerServices<Services>> {
71
+ const options = input.options
72
+ const client = yield* WorkflowPlatformClient
73
+ const steps = options.workflows.flatMap((workflow) => Object.keys(workflow.runnableSteps).map((step) => ({ workflow: workflow.name, step })))
74
+ // Workers racing for one queue head can exhaust Convex's own retries; the loser asks again after a jittered wait,
75
+ // for about 5 seconds in all, since a loaded machine can take a second over each take.
76
+ const taken = yield* pipe(
77
+ Effect.gen(() => client.take({ worker: options.worker, steps, leaseMs: options.leaseMs })),
78
+ Effect.retry({ schedule: Schedule.jittered(Schedule.exponential(Duration.millis(20))), times: 8 }),
79
+ )
80
+ if (taken === null) return { _tag: "Idle" }
81
+
82
+ const workflow = options.workflows.find((candidate) => candidate.name === taken.workflow)
83
+ const step = workflow?.runnableSteps[taken.step]
84
+ if (workflow === undefined || step === undefined) {
85
+ const reported = yield* reportFailure({
86
+ taken,
87
+ error: `worker ${options.worker} has no code for step ${taken.step} of ${taken.workflow}`,
88
+ measurements: { spend: noSpend, used: nothingUsed, files: [], transcripts: [] },
89
+ })
90
+ return { _tag: "Ran", taken, outcome: reported ? "failed" : "unreported" }
91
+ }
92
+ const fileStore = yield* FileStore
93
+ const meter = yield* Effect.sync(() => new StepMeter())
94
+
95
+ // The run sees only what its step declared: those services (the agent runner and program build metered), and its
96
+ // own `Tasks` when it declared tasks to read or write.
97
+ let granted = Context.pick(...step.access.services)(input.context)
98
+ const maybeAgentRunner = Context.getOption(granted, AgentRunner)
99
+ if (Option.isSome(maybeAgentRunner)) granted = Context.add(granted, AgentRunner, meter.meteredAgentRunner(maybeAgentRunner.value))
100
+ const maybeProgramBuild = Context.getOption(granted, ProgramBuild)
101
+ if (Option.isSome(maybeProgramBuild)) granted = Context.add(granted, ProgramBuild, meter.meteredProgramBuild(maybeProgramBuild.value))
102
+ if (step.access.tasks !== undefined) granted = Context.add(granted, Tasks, new RunTasks(client, taken))
103
+ const stepContext = granted
104
+
105
+ // The lease taken with the task covers the first interval, so the first heartbeat waits a third of it.
106
+ const heartbeatEvery = Duration.millis(Math.max(1, Math.floor(options.leaseMs / 3)))
107
+ const heartbeats = pipe(
108
+ Effect.sleep(heartbeatEvery),
109
+ Effect.andThen(Effect.gen(() => client.heartbeat({ workflow: taken.workflow, run: taken.run, leaseMs: options.leaseMs }))),
110
+ Effect.repeat(Schedule.spaced(heartbeatEvery)),
111
+ )
112
+ const exit = yield* pipe(
113
+ Effect.gen(function* () {
114
+ const fields = yield* Schema.decodeUnknownEffect(workflow.task.fields)(taken.task.fields)
115
+ const outcome = yield* pipe(
116
+ Effect.gen(() =>
117
+ step.run({
118
+ taskId: taken.task.id,
119
+ fields,
120
+ files: taken.task.files,
121
+ notes: taken.task.notes,
122
+ lastFingerprint: Option.fromNullishOr(taken.lastFingerprint),
123
+ }),
124
+ ),
125
+ Effect.updateContext(() => stepContext),
126
+ )
127
+ const encodedFields =
128
+ outcome.fields === undefined ? undefined : yield* Schema.encodeUnknownEffect(workflow.task.fields)({ ...fields, ...outcome.fields })
129
+ const encodeItem = Schema.encodeUnknownEffect(workflow.task.fields)
130
+ const listed = outcome.listed === undefined ? undefined : yield* Effect.forEach(outcome.listed, (item) => encodeItem(item))
131
+ const written: Array<TaskFile> = []
132
+ for (const file of outcome.files ?? []) written.push(yield* fileStore.write(file))
133
+ const files =
134
+ written.length === 0
135
+ ? undefined
136
+ : taken.task.files.filter((file) => !written.some((newFile) => newFile.name === file.name)).concat(written)
137
+ const others: Array<ReportedOtherWrite> = []
138
+ for (const other of outcome.others ?? []) {
139
+ const otherFiles: Array<TaskFile> = []
140
+ for (const file of other.files ?? []) otherFiles.push(yield* fileStore.write(file))
141
+ others.push({
142
+ workflow: other.workflow ?? taken.workflow,
143
+ task: other.taskId,
144
+ note: other.note,
145
+ ...(other.fields !== undefined ? { fields: other.fields } : {}),
146
+ ...(otherFiles.length > 0 ? { files: otherFiles } : {}),
147
+ })
148
+ }
149
+ const measurements = yield* meter.measurements({
150
+ files: [...written, ...others.flatMap((other) => other.files ?? [])].map((file) => file.name),
151
+ reported: outcome.used ?? {},
152
+ fingerprint: Option.fromNullishOr(outcome.fingerprint),
153
+ })
154
+ return { endState: outcome.endState, encodedFields, files, measurements, note: outcome.note, listed, others }
155
+ }),
156
+ Effect.raceFirst(Effect.andThen(heartbeats, Effect.never)),
157
+ Effect.exit,
158
+ )
159
+ if (Exit.isFailure(exit)) {
160
+ const measurements = yield* meter.measurements({ files: [], reported: {}, fingerprint: Option.none() })
161
+ const reported = yield* reportFailure({ taken, error: Cause.pretty(exit.cause), measurements })
162
+ return { _tag: "Ran", taken, outcome: reported ? "failed" : "unreported" }
163
+ }
164
+ const completed = yield* reportedWithRetries(() =>
165
+ client.complete({
166
+ run: taken.run,
167
+ workflow: workflow.name,
168
+ endState: exit.value.endState,
169
+ measurements: exit.value.measurements,
170
+ ...(exit.value.encodedFields !== undefined ? { fields: exit.value.encodedFields } : {}),
171
+ ...(exit.value.files !== undefined ? { files: exit.value.files } : {}),
172
+ ...(exit.value.note !== undefined ? { note: exit.value.note } : {}),
173
+ ...(exit.value.listed !== undefined ? { listed: exit.value.listed } : {}),
174
+ ...(exit.value.others.length > 0 ? { others: exit.value.others } : {}),
175
+ }),
176
+ )
177
+ if (Result.isSuccess(completed)) return { _tag: "Ran", taken, outcome: "completed" }
178
+ // Convex refused the end state, or never answered: the run fails with why, so its task is tried again.
179
+ const reported = yield* reportFailure({
180
+ taken,
181
+ error: `its end state ${exit.value.endState} could not be reported: ${completed.failure.message}`,
182
+ measurements: exit.value.measurements,
183
+ })
184
+ return { _tag: "Ran", taken, outcome: reported ? "failed" : "unreported" }
185
+ }
186
+
187
+ /**
188
+ * A report to Convex, tried again a few times: a mutation that timed out was rolled back, so trying it again is safe,
189
+ * and a busy machine can take over a second for one.
190
+ */
191
+ const reportedWithRetries = <A>(report: () => Effect.fn.Return<A, PlatformCallFailed>) =>
192
+ pipe(
193
+ Effect.gen(report),
194
+ Effect.retry({ schedule: Schedule.jittered(Schedule.exponential(Duration.millis(100))), times: 4 }),
195
+ Effect.result,
196
+ )
197
+
198
+ /**
199
+ * Reports a failed run. When even that cannot reach Convex, the run is left to its lease, which fails it once this
200
+ * worker stops heartbeating, and the worker carries on with other tasks. Says whether the report got through.
201
+ */
202
+ const reportFailure = function* (input: {
203
+ readonly taken: TakenStep
204
+ readonly error: string
205
+ readonly measurements: StepMeasurements
206
+ }): Effect.fn.Return<boolean, never, WorkflowPlatformClient> {
207
+ const client = yield* WorkflowPlatformClient
208
+ const failed = yield* reportedWithRetries(() => client.fail({ workflow: input.taken.workflow, run: input.taken.run, error: input.error, measurements: input.measurements }))
209
+ if (Result.isSuccess(failed)) return true
210
+ yield* Effect.logWarning(`run ${input.taken.run} of ${input.taken.workflow} step ${input.taken.step} could not be reported, so it is left to its lease: ${failed.failure.message}`)
211
+ return false
212
+ }
213
+
214
+ /** Works until no step this worker can run has a task it may take, and returns what it ran. */
215
+ export const workUntilIdle = function* <const Workflows extends ReadonlyArray<WorkflowDefinition<any, any, any>>>(
216
+ options: WorkerOptions<Workflows>,
217
+ ): Effect.fn.Return<ReadonlyArray<WorkResult>, unknown, WorkerServices<ServicesOfWorkflows<Workflows>>> {
218
+ const context = yield* Effect.context<WorkerServices<ServicesOfWorkflows<Workflows>>>()
219
+ yield* checkServices({ workflows: options.workflows, context })
220
+ const results: Array<WorkResult> = []
221
+ while (true) {
222
+ const result = yield* runOnce({ options, context })
223
+ if (result._tag === "Idle") return results
224
+ results.push(result)
225
+ }
226
+ }
227
+
228
+ /** Works forever, waiting `idleMs` whenever there is nothing to take. It refuses to start without every service its steps declare. */
229
+ export const workForever = function* <const Workflows extends ReadonlyArray<WorkflowDefinition<any, any, any>>>(
230
+ options: WorkerOptions<Workflows> & { readonly idleMs: number },
231
+ ): Effect.fn.Return<never, unknown, WorkerServices<ServicesOfWorkflows<Workflows>>> {
232
+ const context = yield* Effect.context<WorkerServices<ServicesOfWorkflows<Workflows>>>()
233
+ yield* checkServices({ workflows: options.workflows, context })
234
+ while (true) {
235
+ // Convex unreachable even after `take`'s retries: the loop waits and asks again rather than ending.
236
+ const attempt = yield* Effect.result(Effect.gen(() => runOnce({ options, context })))
237
+ if (Result.isFailure(attempt)) yield* Effect.logWarning(`worker ${options.worker} could not take a task: ${String(attempt.failure)}`)
238
+ if (Result.isFailure(attempt) || attempt.success._tag === "Idle") yield* Effect.sleep(Duration.millis(options.idleMs))
239
+ }
240
+ }
@@ -1,30 +0,0 @@
1
- /** WHAT EACH BUDGETED WORKFLOW'S LIMITS ASK FOR AGAINST WHAT IT HAS, for a dashboard and the route that sets a limit. Pure. */
2
- import { runLimit } from './storage/budgets';
3
- export const workflowBudgetStates = (workflows, budgets, work, assigned) => workflows.map((w) => {
4
- const row = budgets.find((b) => b.workflow === w.name);
5
- const runs = assigned.filter((a) => a.workflow === w.name);
6
- const limits = { agents: row?.budget ?? 0, runs: row?.runs ?? null };
7
- return {
8
- workflow: w.name, budget: limits.agents, runs: runLimit(limits),
9
- changedAt: row?.changed_at ?? 0, running: runs.length,
10
- items: work.find((x) => x.workflow === w.name)?.items ?? 0,
11
- newestStart: runs.length === 0 ? null : Math.max(...runs.map((r) => r.started)),
12
- };
13
- });
14
- /** Fewer runs going than its run limit: a run with nothing to pick waits for an item, so work or none, it is a fault. */
15
- export const belowBudget = (w) => w.running < w.runs;
16
- /**
17
- * Whether the trigger started a run above the run limit. Every run going now had started by the newest one's start, so that
18
- * many were going then; if the limit was already this one, that start went over it. Runs above a limit lowered after they
19
- * started are finishing their call, and end before the next.
20
- */
21
- export const startedAboveBudget = (w) => w.running > w.runs && w.newestStart !== null && w.newestStart > w.changedAt;
22
- /** Why the route refuses a limit, with its status; null when it takes it. `budgeted` is every workflow with limits. */
23
- export const budgetRefusal = (workflow, asked, budget, budgeted) => {
24
- if (workflow === null)
25
- return { status: 404, error: `no workflow ${asked}` };
26
- if (!budgeted.includes(workflow))
27
- return { status: 409, error: `${workflow} has no agent step and no list of work, so it has no budget` };
28
- return typeof budget === 'number' && Number.isInteger(budget) && budget >= 0 ? null : { status: 400, error: 'budget must be a whole number, 0 or more' };
29
- };
30
- //# sourceMappingURL=budget-states.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"budget-states.js","sourceRoot":"","sources":["../../../src/budget-states.ts"],"names":[],"mappings":"AAAA,+HAA+H;AAC/H,OAAO,EAAE,QAAQ,EAA0B,MAAM,mBAAmB,CAAC;AAkBrE,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,SAAmD,EACnD,OAAyC,EACzC,IAA0E,EAC1E,QAAgF,EAC5C,EAAE,CACtC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE;IAClB,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC;IACvD,MAAM,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC;IACrE,OAAO;QACL,QAAQ,EAAE,CAAC,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,IAAI,EAAE,QAAQ,CAAC,MAAM,CAAC;QAC/D,SAAS,EAAE,GAAG,EAAE,UAAU,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,MAAM;QACrD,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,IAAI,CAAC;QAC1D,WAAW,EAAE,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;KAChF,CAAC;AACJ,CAAC,CAAC,CAAC;AAEL,yHAAyH;AACzH,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,CAAgD,EAAW,EAAE,CAAC,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,IAAI,CAAC;AAE7G;;;;GAIG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAA8E,EAAW,EAAE,CAC5H,CAAC,CAAC,OAAO,GAAG,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,WAAW,KAAK,IAAI,IAAI,CAAC,CAAC,WAAW,GAAG,CAAC,CAAC,SAAS,CAAC;AAE9E,uHAAuH;AACvH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC,QAAuB,EAAE,KAAa,EAAE,MAAe,EAAE,QAA+B,EAA8D,EAAE;IACpL,IAAI,QAAQ,KAAK,IAAI;QAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,eAAe,KAAK,EAAE,EAAE,CAAC;IAC7E,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC;QAAE,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,QAAQ,6DAA6D,EAAE,CAAC;IAC1I,OAAO,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,0CAA0C,EAAE,CAAC;AAC3J,CAAC,CAAC"}