@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
@@ -0,0 +1,290 @@
1
+ import { v } from "convex/values"
2
+ import { Option } from "effect"
3
+ import {
4
+ createsTasks,
5
+ noteWriterValidator,
6
+ inputPlacesOf,
7
+ parentRefValidator,
8
+ placeAtStartOf,
9
+ placeRefValidator,
10
+ skippedOtherValidator,
11
+ stepSpendValidator,
12
+ stepUsedValidator,
13
+ taskFileValidator,
14
+ taskNoteValidator,
15
+ } from "../src/graph"
16
+ import { mutation, query } from "./_generated/server"
17
+ import * as Engine from "./engine"
18
+ import { runEngine } from "./runEngine"
19
+ import { notesOf } from "./notes"
20
+
21
+ /** A task arrives: through the workflow's task event, or through a named request event. Fields are already encoded by the task schema. */
22
+ export const create = mutation({
23
+ args: {
24
+ workflow: v.string(),
25
+ event: v.optional(v.string()),
26
+ fields: v.any(),
27
+ files: v.optional(v.array(taskFileValidator)),
28
+ parent: v.optional(parentRefValidator),
29
+ },
30
+ returns: v.id("tasks"),
31
+ handler: (ctx, args) =>
32
+ runEngine(
33
+ ctx,
34
+ Engine.createTask({
35
+ workflow: args.workflow,
36
+ event: Option.fromNullishOr(args.event),
37
+ fields: args.fields,
38
+ files: args.files ?? [],
39
+ parent: Option.fromNullishOr(args.parent),
40
+ }),
41
+ ),
42
+ })
43
+
44
+ /** Replaces a task's fields (and files, when given); every change event watching a field that changed starts a flow. */
45
+ export const setFields = mutation({
46
+ args: { task: v.id("tasks"), fields: v.any(), files: v.optional(v.array(taskFileValidator)) },
47
+ returns: v.null(),
48
+ handler: async (ctx, args) => {
49
+ await runEngine(ctx, Engine.setTaskFields({ task: args.task, fields: args.fields, files: Option.fromNullishOr(args.files) }))
50
+ return null
51
+ },
52
+ })
53
+
54
+ const stepRunValidator = v.object({
55
+ step: v.string(),
56
+ status: v.string(),
57
+ worker: v.optional(v.string()),
58
+ startedAt: v.number(),
59
+ endedAt: v.optional(v.number()),
60
+ endState: v.optional(v.string()),
61
+ error: v.optional(v.string()),
62
+ call: v.number(),
63
+ version: v.string(),
64
+ spend: stepSpendValidator,
65
+ used: stepUsedValidator,
66
+ agent: v.optional(v.string()),
67
+ files: v.array(v.string()),
68
+ note: v.optional(v.string()),
69
+ transcripts: v.array(taskFileValidator),
70
+ skippedOthers: v.optional(v.array(skippedOtherValidator)),
71
+ })
72
+
73
+ /** A task as it is now: its fields, files, every place its flows are, and the record of every step it went through. */
74
+ export const get = query({
75
+ // Any string, so a task id that came from outside, such as another task's run writing to it, reads as no task.
76
+ args: { task: v.string() },
77
+ returns: v.union(
78
+ v.null(),
79
+ v.object({
80
+ id: v.id("tasks"),
81
+ workflow: v.string(),
82
+ fields: v.any(),
83
+ files: v.array(taskFileValidator),
84
+ endedAs: v.optional(v.string()),
85
+ parent: v.optional(parentRefValidator),
86
+ places: v.array(v.object({ startedBy: v.string(), place: v.string() })),
87
+ stepRuns: v.array(stepRunValidator),
88
+ }),
89
+ ),
90
+ handler: async (ctx, args) => {
91
+ const task = await (async () => {
92
+ const id = ctx.db.normalizeId("tasks", args.task)
93
+ return id === null ? null : await ctx.db.get(id)
94
+ })()
95
+ if (task === null) return null
96
+ const flows = await ctx.db.query("flows").withIndex("by_task_started_by", (q) => q.eq("task", task._id)).collect()
97
+ const runs = await ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", task._id)).collect()
98
+ return {
99
+ id: task._id,
100
+ workflow: task.workflow,
101
+ fields: task.fields,
102
+ files: task.files,
103
+ ...(task.endedAs !== undefined ? { endedAs: task.endedAs } : {}),
104
+ ...(task.parent !== undefined ? { parent: task.parent } : {}),
105
+ places: flows.map((flow) => ({ startedBy: flow.startedBy, place: flow.place })),
106
+ stepRuns: runs.map((run) => ({
107
+ step: run.step,
108
+ status: run.status,
109
+ call: run.call,
110
+ version: run.version,
111
+ spend: run.spend,
112
+ used: run.used,
113
+ files: run.files,
114
+ transcripts: run.transcripts,
115
+ ...(run.agent !== undefined ? { agent: run.agent } : {}),
116
+ startedAt: run.startedAt,
117
+ ...(run.worker !== undefined ? { worker: run.worker } : {}),
118
+ ...(run.endedAt !== undefined ? { endedAt: run.endedAt } : {}),
119
+ ...(run.endState !== undefined ? { endState: run.endState } : {}),
120
+ ...(run.error !== undefined ? { error: run.error } : {}),
121
+ ...(run.note !== undefined ? { note: run.note } : {}),
122
+ ...(run.skippedOthers !== undefined ? { skippedOthers: run.skippedOthers } : {}),
123
+ })),
124
+ }
125
+ },
126
+ })
127
+
128
+ /** The tasks a flow of this task waits on in a sub-workflow step, by list entry; their fields live in the sub-workflow's component. */
129
+ export const subWorkflowTasks = query({
130
+ args: { task: v.id("tasks") },
131
+ returns: v.array(v.object({ entryIndex: v.number(), workflow: v.string(), task: v.optional(v.string()), endedAs: v.optional(v.string()) })),
132
+ handler: async (ctx, args) => {
133
+ const flows = await ctx.db.query("flows").withIndex("by_task_started_by", (q) => q.eq("task", args.task)).collect()
134
+ const rows = []
135
+ for (const flow of flows) {
136
+ rows.push(...(await ctx.db.query("subWorkflowTasks").withIndex("by_flow_entry", (q) => q.eq("flow", flow._id)).collect()))
137
+ }
138
+ return rows.map((row) => ({
139
+ entryIndex: row.entryIndex,
140
+ workflow: row.workflow,
141
+ ...(row.task !== undefined ? { task: row.task } : {}),
142
+ ...(row.endedAs !== undefined ? { endedAs: row.endedAs } : {}),
143
+ }))
144
+ },
145
+ })
146
+
147
+ /** The workforce created the sub-workflow task for one entry of a flow waiting here. */
148
+ export const recordSubWorkflowTask = mutation({
149
+ args: { flow: v.id("flows"), entryIndex: v.number(), task: v.string() },
150
+ returns: v.null(),
151
+ handler: async (ctx, args) => {
152
+ await runEngine(ctx, Engine.recordSubWorkflowTask(args))
153
+ return null
154
+ },
155
+ })
156
+
157
+ /** The workforce relays that a sub-workflow task of a flow waiting here ended, with that task's fields. */
158
+ export const subWorkflowTaskEnded = mutation({
159
+ args: { flow: v.id("flows"), entryIndex: v.number(), endState: v.string(), fields: v.any() },
160
+ returns: v.null(),
161
+ handler: async (ctx, args) => {
162
+ await runEngine(ctx, Engine.subWorkflowTaskEnded(args))
163
+ return null
164
+ },
165
+ })
166
+
167
+ /**
168
+ * Sends a task back through a task or request event of its workflow, with new fields when given and `note` kept as
169
+ * why: from the end state it stopped at onto that event's line. Fields are already encoded by the task schema.
170
+ */
171
+ export const requeue = mutation({
172
+ args: { task: v.id("tasks"), event: v.string(), fields: v.optional(v.any()), note: v.string() },
173
+ returns: v.null(),
174
+ handler: async (ctx, args) => {
175
+ await runEngine(ctx, Engine.requeue({ task: args.task, event: args.event, fields: Option.fromNullishOr(args.fields), note: args.note }))
176
+ return null
177
+ },
178
+ })
179
+
180
+ /** Everything said about a task, oldest first: its step runs' notes and the reasons calls sent it back. */
181
+ export const notes = query({
182
+ args: { task: v.id("tasks") },
183
+ returns: v.array(taskNoteValidator),
184
+ handler: async (ctx, args) => {
185
+ const task = await ctx.db.get(args.task)
186
+ if (task === null) return []
187
+ const runs = await ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", task._id)).collect()
188
+ const left = await ctx.db.query("taskNotes").withIndex("by_task", (q) => q.eq("task", task._id)).collect()
189
+ return notesOf({ task, runs, left })
190
+ },
191
+ })
192
+
193
+ /** Where a task is, as `find` reports it: the place of the flow that brought it in. */
194
+ const taskPlaceValidator = v.union(v.object({ line: v.string() }), v.object({ step: v.string() }), v.object({ end: v.string() }))
195
+
196
+ /**
197
+ * Tasks of the workflow whose fields equal every value of `where` (compared as stored), narrowed by `at` to those
198
+ * waiting in front of a step, in a step, at an end state or on one line; at most `limit`. Each comes with its fields,
199
+ * files, notes and where it is now. The workforce checks that the asking step may read this workflow.
200
+ */
201
+ export const find = query({
202
+ args: { workflow: v.string(), where: v.optional(v.any()), at: v.optional(placeRefValidator), limit: v.number() },
203
+ returns: v.array(
204
+ v.object({ taskId: v.id("tasks"), fields: v.any(), files: v.array(taskFileValidator), notes: v.array(taskNoteValidator), at: taskPlaceValidator }),
205
+ ),
206
+ handler: async (ctx, args) => {
207
+ const workflow = await ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", args.workflow)).unique()
208
+ if (workflow === null) return []
209
+ const graph = workflow.graph
210
+ const arrivalEvents = new Set(graph.events.filter(createsTasks).map((event) => event.id))
211
+ const where: Record<string, unknown> = typeof args.where === "object" && args.where !== null ? args.where : {}
212
+ const matches = (fields: Record<string, unknown>) => Object.entries(where).every(([field, value]) => JSON.stringify(fields[field]) === JSON.stringify(value))
213
+ const at = args.at
214
+ const places =
215
+ at === undefined
216
+ ? undefined
217
+ : "inFrontOf" in at
218
+ ? inputPlacesOf(graph, at.inFrontOf)
219
+ : "step" in at
220
+ ? [`step:${at.step}`]
221
+ : "end" in at
222
+ ? [`end:${at.end}`]
223
+ : graph.lines.filter((line) => line.id === at.line).map(placeAtStartOf)
224
+ const candidates =
225
+ places === undefined
226
+ ? await ctx.db.query("tasks").withIndex("by_workflow", (q) => q.eq("workflow", args.workflow)).collect()
227
+ : await (async () => {
228
+ const tasks = []
229
+ for (const place of places) {
230
+ const flows = await ctx.db.query("flows").withIndex("by_workflow_place_entered", (q) => q.eq("workflow", args.workflow).eq("place", place)).collect()
231
+ for (const flow of flows.filter((candidate) => arrivalEvents.has(candidate.startedBy))) {
232
+ const task = await ctx.db.get(flow.task)
233
+ if (task !== null) tasks.push(task)
234
+ }
235
+ }
236
+ return tasks
237
+ })()
238
+ const found = []
239
+ for (const task of candidates) {
240
+ if (found.length >= args.limit) break
241
+ if (!matches(task.fields)) continue
242
+ const flows = await ctx.db.query("flows").withIndex("by_task_started_by", (q) => q.eq("task", task._id)).collect()
243
+ const arrival = flows.find((flow) => arrivalEvents.has(flow.startedBy))
244
+ if (arrival === undefined) continue
245
+ const place = arrival.place
246
+ const runs = await ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", task._id)).collect()
247
+ const left = await ctx.db.query("taskNotes").withIndex("by_task", (q) => q.eq("task", task._id)).collect()
248
+ found.push({
249
+ taskId: task._id,
250
+ fields: task.fields,
251
+ files: task.files,
252
+ notes: notesOf({ task, runs, left }),
253
+ at: place.startsWith("step:") ? { step: place.slice(5) } : place.startsWith("end:") ? { end: place.slice(4) } : { line: place.slice(5) },
254
+ })
255
+ }
256
+ return found
257
+ },
258
+ })
259
+
260
+ /**
261
+ * Another task's run writes to one of this workflow's tasks, inside the workforce mutation completing that run. Returns
262
+ * why the write was skipped, or null once it is applied (`Engine.writeOther`). Fields are already encoded and checked.
263
+ */
264
+ export const writeOther = mutation({
265
+ args: { task: v.string(), fields: v.optional(v.any()), files: v.optional(v.array(taskFileValidator)), note: v.string(), by: noteWriterValidator },
266
+ returns: v.union(v.null(), v.string()),
267
+ handler: async (ctx, args) => {
268
+ const task = ctx.db.normalizeId("tasks", args.task)
269
+ if (task === null) return "there is no such task"
270
+ const skipped = await runEngine(
271
+ ctx,
272
+ Engine.writeOther({ task, fields: Option.fromNullishOr(args.fields), files: Option.fromNullishOr(args.files), note: args.note, by: args.by }),
273
+ )
274
+ return Option.getOrNull(skipped)
275
+ },
276
+ })
277
+
278
+ /**
279
+ * Moves these tasks to the front of the queues they wait in, in this order, with `note` as why (`Engine.moveToFront`):
280
+ * those in a step, ended, or of another workflow are named as not waiting.
281
+ */
282
+ export const moveToFront = mutation({
283
+ args: { workflow: v.string(), tasks: v.array(v.string()), note: v.string() },
284
+ returns: v.object({ moved: v.array(v.string()), notWaiting: v.array(v.string()) }),
285
+ handler: async (ctx, args) => {
286
+ const tasks = args.tasks.map((id) => ({ id, task: Option.fromNullishOr(ctx.db.normalizeId("tasks", id)) }))
287
+ const result = await runEngine(ctx, Engine.moveToFront({ workflow: args.workflow, tasks, note: args.note }))
288
+ return { moved: [...result.moved], notWaiting: [...result.notWaiting] }
289
+ },
290
+ })
@@ -0,0 +1,109 @@
1
+ import { v } from "convex/values"
2
+ import { Option } from "effect"
3
+ import { skippedOtherValidator, stepMeasurementsValidator, taskFileValidator, taskNoteValidator } from "../src/graph"
4
+ import { internalMutation, mutation, query } from "./_generated/server"
5
+ import * as Engine from "./engine"
6
+ import { runEngine } from "./runEngine"
7
+
8
+ /** Takes the task that has waited longest in front of any of the given steps whose workflow budget has room, or null. */
9
+ export const take = mutation({
10
+ args: {
11
+ worker: v.string(),
12
+ steps: v.array(v.object({ workflow: v.string(), step: v.string() })),
13
+ leaseMs: v.number(),
14
+ },
15
+ returns: v.union(
16
+ v.null(),
17
+ v.object({
18
+ run: v.id("stepRuns"),
19
+ workflow: v.string(),
20
+ step: v.string(),
21
+ task: v.object({ id: v.id("tasks"), fields: v.any(), files: v.array(taskFileValidator), notes: v.array(taskNoteValidator) }),
22
+ lastFingerprint: v.optional(v.string()),
23
+ }),
24
+ ),
25
+ handler: async (ctx, args) => {
26
+ const maybeTaken = await runEngine(ctx, Engine.take(args))
27
+ return Option.getOrNull(maybeTaken)
28
+ },
29
+ })
30
+
31
+ /** Reports a step's end state, with the task's new fields and files when the step changed them. */
32
+ export const complete = mutation({
33
+ args: {
34
+ run: v.id("stepRuns"),
35
+ workflow: v.string(),
36
+ endState: v.string(),
37
+ fields: v.optional(v.any()),
38
+ files: v.optional(v.array(taskFileValidator)),
39
+ measurements: v.optional(stepMeasurementsValidator),
40
+ note: v.optional(v.string()),
41
+ /** From a step that syncs a declared item list: every item on it, as encoded task fields. */
42
+ listed: v.optional(v.array(v.any())),
43
+ /** Writes to other tasks the workforce could not apply, each with why. */
44
+ skippedOthers: v.optional(v.array(skippedOtherValidator)),
45
+ },
46
+ returns: v.null(),
47
+ handler: async (ctx, args) => {
48
+ await runEngine(
49
+ ctx,
50
+ Engine.complete({
51
+ run: args.run,
52
+ workflow: args.workflow,
53
+ endState: args.endState,
54
+ fields: Option.fromNullishOr(args.fields),
55
+ files: Option.fromNullishOr(args.files),
56
+ measurements: Option.fromNullishOr(args.measurements),
57
+ note: Option.fromNullishOr(args.note),
58
+ listed: Option.fromNullishOr(args.listed),
59
+ skippedOthers: args.skippedOthers ?? [],
60
+ }),
61
+ )
62
+ return null
63
+ },
64
+ })
65
+
66
+ export const fail = mutation({
67
+ args: { run: v.id("stepRuns"), error: v.string(), measurements: v.optional(stepMeasurementsValidator) },
68
+ returns: v.null(),
69
+ handler: async (ctx, args) => {
70
+ await runEngine(ctx, Engine.fail({ run: args.run, error: args.error, measurements: Option.fromNullishOr(args.measurements) }))
71
+ return null
72
+ },
73
+ })
74
+
75
+ export const heartbeat = mutation({
76
+ args: { run: v.id("stepRuns"), leaseMs: v.number() },
77
+ returns: v.null(),
78
+ handler: async (ctx, args) => {
79
+ await runEngine(ctx, Engine.heartbeat(args))
80
+ return null
81
+ },
82
+ })
83
+
84
+ export const expireLease = internalMutation({
85
+ args: { run: v.id("stepRuns") },
86
+ returns: v.null(),
87
+ handler: async (ctx, args) => {
88
+ await runEngine(ctx, Engine.expireLease(args))
89
+ return null
90
+ },
91
+ })
92
+
93
+ /** When the task `take` would give entered its queue, or null; read inside the workforce's `take` transaction. */
94
+ export const oldestTakeable = mutation({
95
+ args: { steps: v.array(v.object({ workflow: v.string(), step: v.string() })) },
96
+ returns: v.union(v.null(), v.number()),
97
+ handler: async (ctx, args) => Option.getOrNull(await runEngine(ctx, Engine.oldestTakeable(args))),
98
+ })
99
+
100
+ /** Which step a run is of, its task, and whether it is still running; the workforce reads it to check the step's access. */
101
+ export const runOf = query({
102
+ args: { run: v.string() },
103
+ returns: v.union(v.null(), v.object({ workflow: v.string(), step: v.string(), task: v.id("tasks"), status: v.string() })),
104
+ handler: async (ctx, args) => {
105
+ const id = ctx.db.normalizeId("stepRuns", args.run)
106
+ const run = id === null ? null : await ctx.db.get(id)
107
+ return run === null ? null : { workflow: run.workflow, step: run.step, task: run.task, status: run.status }
108
+ },
109
+ })
@@ -0,0 +1,83 @@
1
+ import { v } from "convex/values"
2
+ import { Option } from "effect"
3
+ import { budgetsValidator, graphValidator, workforceHooksValidator } from "../src/graph"
4
+ import { mutation, query } from "./_generated/server"
5
+ import * as Engine from "./engine"
6
+ import { runEngine } from "./runEngine"
7
+
8
+ /** Registers a workflow, or replaces its graph; tasks already in it keep their places. Its budgets stay as they were. */
9
+ export const register = mutation({
10
+ args: { graph: graphValidator, hooks: v.optional(workforceHooksValidator) },
11
+ returns: v.null(),
12
+ handler: async (ctx, args) => {
13
+ await runEngine(ctx, Engine.register({ graph: args.graph, hooks: Option.fromNullishOr(args.hooks) }))
14
+ return null
15
+ },
16
+ })
17
+
18
+ export const setBudgets = mutation({
19
+ args: { workflow: v.string(), budgets: budgetsValidator },
20
+ returns: v.null(),
21
+ handler: async (ctx, args) => {
22
+ await runEngine(ctx, Engine.setBudgets(args))
23
+ return null
24
+ },
25
+ })
26
+
27
+ /** The graph a workflow runs now, with its `version` (the one every new step run records) and its budgets; null if not registered. */
28
+ export const get = query({
29
+ args: { workflow: v.string() },
30
+ returns: v.union(v.null(), v.object({ graph: graphValidator, version: v.string(), budgets: budgetsValidator })),
31
+ handler: async (ctx, args) => {
32
+ const workflow = await ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", args.workflow)).unique()
33
+ return workflow === null ? null : { graph: workflow.graph, version: workflow.version, budgets: workflow.budgets }
34
+ },
35
+ })
36
+
37
+ /**
38
+ * The number of tasks at every place of a workflow: on each line, in each step, at each end state. A line out of an
39
+ * end state counts the tasks waiting at that end state, since they are its queue.
40
+ */
41
+ export const counts = query({
42
+ args: { workflow: v.string() },
43
+ returns: v.object({
44
+ lines: v.array(v.object({ line: v.string(), tasks: v.number() })),
45
+ steps: v.array(v.object({ step: v.string(), tasks: v.number() })),
46
+ ends: v.array(v.object({ end: v.string(), tasks: v.number() })),
47
+ budgets: v.object({ agents: v.object({ inUse: v.number(), limit: v.number() }), cpu: v.object({ inUse: v.number(), limit: v.number() }) }),
48
+ }),
49
+ handler: async (ctx, args) => {
50
+ const workflow = await ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", args.workflow)).unique()
51
+ if (workflow === null) throw new Error(`workflow ${args.workflow} is not registered`)
52
+ const flows = await ctx.db.query("flows").withIndex("by_workflow_place_entered", (q) => q.eq("workflow", args.workflow)).collect()
53
+ const tasksAt = (place: string) => flows.filter((flow) => flow.place === place).length
54
+ const running = (budget: "agents" | "cpu") =>
55
+ ctx.db
56
+ .query("stepRuns")
57
+ .withIndex("by_workflow_budget_status", (q) => q.eq("workflow", args.workflow).eq("budget", budget).eq("status", "running"))
58
+ .collect()
59
+ return {
60
+ lines: workflow.graph.lines.map((line) => ({
61
+ line: line.id,
62
+ tasks: "end" in line.from ? tasksAt(`end:${line.from.end}`) : "end" in line.to ? 0 : tasksAt(`line:${line.id}`),
63
+ })),
64
+ steps: workflow.graph.steps.map((step) => ({ step: step.id, tasks: tasksAt(`step:${step.id}`) })),
65
+ ends: workflow.graph.endStates.map((end) => ({ end, tasks: tasksAt(`end:${end}`) })),
66
+ budgets: {
67
+ agents: { inUse: (await running("agents")).length, limit: workflow.budgets.agents },
68
+ cpu: { inUse: (await running("cpu")).length, limit: workflow.budgets.cpu },
69
+ },
70
+ }
71
+ },
72
+ })
73
+
74
+
75
+ /** Deletes a workflow with all its tasks and records. Tasks of its sub-workflows stay in their own workflows. */
76
+ export const remove = mutation({
77
+ args: { workflow: v.string() },
78
+ returns: v.null(),
79
+ handler: async (ctx, args) => {
80
+ await runEngine(ctx, Engine.remove(args))
81
+ return null
82
+ },
83
+ })
@@ -0,0 +1,9 @@
1
+ import { Context, Data } from "effect";
2
+ export class AgentRunFailed extends Data.TaggedError("AgentRunFailed") {
3
+ get message() {
4
+ return `the agent run failed: ${String(this.cause)}`;
5
+ }
6
+ }
7
+ export class AgentRunner extends Context.Service()("AgentRunner") {
8
+ }
9
+ //# sourceMappingURL=agent-runner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-runner.js","sourceRoot":"","sources":["../../../../src/definition/agent-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAe,MAAM,QAAQ,CAAA;AAGnD,MAAM,OAAO,cAAe,SAAQ,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAA8B;IACjG,IAAa,OAAO;QAClB,OAAO,yBAAyB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAA;IACtD,CAAC;CACF;AAmDD,MAAM,OAAO,WAAY,SAAQ,OAAO,CAAC,OAAO,EAA6B,CAAC,aAAa,CAAC;CAAG"}
@@ -0,0 +1,9 @@
1
+ import { Context, Data } from "effect";
2
+ export class FileStoreError extends Data.TaggedError("FileStoreError") {
3
+ get message() {
4
+ return `file ${this.file} could not be stored or read: ${String(this.cause)}`;
5
+ }
6
+ }
7
+ export class FileStore extends Context.Service()("FileStore") {
8
+ }
9
+ //# sourceMappingURL=file-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-store.js","sourceRoot":"","sources":["../../../../src/definition/file-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAe,MAAM,QAAQ,CAAA;AAGnD,MAAM,OAAO,cAAe,SAAQ,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAqD;IACxH,IAAa,OAAO;QAClB,OAAO,QAAQ,IAAI,CAAC,IAAI,iCAAiC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAA;IAC/E,CAAC;CACF;AAWD,MAAM,OAAO,SAAU,SAAQ,OAAO,CAAC,OAAO,EAAyB,CAAC,WAAW,CAAC;CAAG"}
@@ -0,0 +1,10 @@
1
+ import { Context, Data } from "effect";
2
+ /** The build could not run at all, such as when the toolchain is missing. A build that runs and fails is a result. */
3
+ export class ProgramBuildFailed extends Data.TaggedError("ProgramBuildFailed") {
4
+ get message() {
5
+ return `the program build failed: ${String(this.cause)}`;
6
+ }
7
+ }
8
+ export class ProgramBuild extends Context.Service()("ProgramBuild") {
9
+ }
10
+ //# sourceMappingURL=program-build.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"program-build.js","sourceRoot":"","sources":["../../../../src/definition/program-build.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAA4B,MAAM,QAAQ,CAAA;AAEhE,sHAAsH;AACtH,MAAM,OAAO,kBAAmB,SAAQ,IAAI,CAAC,WAAW,CAAC,oBAAoB,CAA8B;IACzG,IAAa,OAAO;QAClB,OAAO,6BAA6B,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAA;IAC1D,CAAC;CACF;AAsBD,MAAM,OAAO,YAAa,SAAQ,OAAO,CAAC,OAAO,EAA+B,CAAC,cAAc,CAAC;CAAG"}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=step.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"step.js","sourceRoot":"","sources":["../../../../src/definition/step.ts"],"names":[],"mappings":""}
@@ -0,0 +1,5 @@
1
+ export const make = (input) => ({
2
+ fields: input.fields,
3
+ files: input.files ?? [],
4
+ });
5
+ //# sourceMappingURL=task-schema.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"task-schema.js","sourceRoot":"","sources":["../../../../src/definition/task-schema.ts"],"names":[],"mappings":"AAWA,MAAM,CAAC,MAAM,IAAI,GAAG,CAA8B,KAA0E,EAAsB,EAAE,CAAC,CAAC;IACpJ,MAAM,EAAE,KAAK,CAAC,MAAM;IACpB,KAAK,EAAE,KAAK,CAAC,KAAK,IAAI,EAAE;CACzB,CAAC,CAAA"}
@@ -0,0 +1,9 @@
1
+ import { Context, Data } from "effect";
2
+ export class TasksCallFailed extends Data.TaggedError("TasksCallFailed") {
3
+ get message() {
4
+ return `reading tasks failed: ${String(this.cause)}`;
5
+ }
6
+ }
7
+ export class Tasks extends Context.Service()("Tasks") {
8
+ }
9
+ //# sourceMappingURL=tasks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tasks.js","sourceRoot":"","sources":["../../../../src/definition/tasks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAe,MAAM,QAAQ,CAAA;AAGnD,MAAM,OAAO,eAAgB,SAAQ,IAAI,CAAC,WAAW,CAAC,iBAAiB,CAA8B;IACnG,IAAa,OAAO;QAClB,OAAO,yBAAyB,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAA;IACtD,CAAC;CACF;AAmCD,MAAM,OAAO,KAAM,SAAQ,OAAO,CAAC,OAAO,EAAiB,CAAC,OAAO,CAAC;CAAG"}