@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
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@jive-sh/workflow-platform",
3
- "version": "0.7.0",
3
+ "version": "1.0.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
- "description": "Durable workflows on effect/workflow: steps, step records, task queues, waiting picks, budgets, the trigger that keeps runs going, and a dashboard of them.",
6
+ "description": "Durable workflows in Convex: one workflow primitive with a task schema, queues on every line, workflow budgets, named end states, events and sub-workflows; worker processes run the steps.",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/jive-sh/workflow-platform.git"
@@ -16,14 +16,19 @@
16
16
  "types": "./src/index.ts",
17
17
  "import": "./dist/index.js"
18
18
  },
19
- "./README.md": "./README.md"
19
+ "./README.md": "./README.md",
20
+ "./component/*": "./component/*",
21
+ "./worker/*": "./worker/*"
20
22
  },
21
23
  "files": [
22
24
  "README.md",
25
+ "component",
26
+ "worker",
23
27
  "dist",
24
28
  "src"
25
29
  ],
26
30
  "peerDependencies": {
27
- "effect": "^4.0.0"
31
+ "convex": "^1.51.0",
32
+ "effect": "^4.1.7"
28
33
  }
29
34
  }
@@ -0,0 +1,59 @@
1
+ import { Context, Data, type Effect } from "effect"
2
+ import type { TaskFile } from "../graph"
3
+
4
+ export class AgentRunFailed extends Data.TaggedError("AgentRunFailed")<{ readonly cause: unknown }> {
5
+ override get message() {
6
+ return `the agent run failed: ${String(this.cause)}`
7
+ }
8
+ }
9
+
10
+ /**
11
+ * What one agent run produced: its final answer, which agent (provider and model) ran it, and what it spent. Input
12
+ * tokens are split the way providers price them; `requests` counts the API calls it made, and `costUsd` is what they
13
+ * cost in US dollars at the prices of the agent that ran them: the runner knows the model, so it prices the run.
14
+ */
15
+ export interface AgentRunResult {
16
+ readonly output: string
17
+ readonly agent: string
18
+ /** The run's whole transcript, kept through the organization's `FileStore`; the step's record lists it. */
19
+ readonly transcript: TaskFile
20
+ /** Whether the run stopped at its `maxTurns` before it answered; `output` is then empty, and its spend still counts. */
21
+ readonly stoppedAtTurnLimit: boolean
22
+ readonly spend: { readonly fresh: number; readonly cacheWrite: number; readonly cacheRead: number; readonly output: number; readonly requests: number; readonly costUsd: number }
23
+ }
24
+
25
+ /**
26
+ * What an agent run may do besides answer. `none` (the default) answers in one turn with no tools. `reading` reads the
27
+ * files of `folder` (read, search, list) for up to `maxTurns` turns and changes nothing. `working` also edits, writes
28
+ * and runs commands there, with git refused; it may change only the files matching one of `mayWrite`, globs relative
29
+ * to `folder`.
30
+ */
31
+ export type AgentTools =
32
+ | { readonly kind: "none" }
33
+ | { readonly kind: "reading"; readonly folder: string; readonly maxTurns: number }
34
+ | { readonly kind: "working"; readonly folder: string; readonly maxTurns: number; readonly mayWrite: ReadonlyArray<string> }
35
+
36
+ /** What a step asks of one agent run. */
37
+ export interface AgentRunInput {
38
+ readonly instructions?: string
39
+ /**
40
+ * Text that stays the same from run to run, such as a function's disassembly and its notes on a second try, sent after
41
+ * the instructions so the provider reads it from its cache rather than charging for it fresh.
42
+ */
43
+ readonly cached?: string
44
+ readonly prompt: string
45
+ readonly files: ReadonlyArray<TaskFile>
46
+ readonly tools?: AgentTools
47
+ }
48
+
49
+ /**
50
+ * The interface a workflow's agent steps use to run an agent; the organization provides the implementation (which
51
+ * model or provider, which machine, which credentials). The step says what the agent is told to be (`instructions`, its
52
+ * system prompt), what it is asked, which of the task's files it may read, and which tools it may use where. The worker
53
+ * adds every run's spend and transcript to the step's record.
54
+ */
55
+ export interface IAgentRunner {
56
+ run(input: AgentRunInput): Effect.fn.Return<AgentRunResult, AgentRunFailed>
57
+ }
58
+
59
+ export class AgentRunner extends Context.Service<AgentRunner, IAgentRunner>()("AgentRunner") {}
@@ -0,0 +1,20 @@
1
+ import { Context, Data, type Effect } from "effect"
2
+ import type { TaskFile } from "../graph"
3
+
4
+ export class FileStoreError extends Data.TaggedError("FileStoreError")<{ readonly file: string; readonly cause: unknown }> {
5
+ override get message() {
6
+ return `file ${this.file} could not be stored or read: ${String(this.cause)}`
7
+ }
8
+ }
9
+
10
+ /**
11
+ * The interface a workflow uses to save and read its task files; the organization provides the implementation. Convex
12
+ * keeps only each file's reference (`TaskFile.ref`), so large files never reach the Convex bill.
13
+ */
14
+ export interface IFileStore {
15
+ write(input: { readonly name: string; readonly bytes: Uint8Array }): Effect.fn.Return<TaskFile, FileStoreError>
16
+ read(file: TaskFile): Effect.fn.Return<Uint8Array, FileStoreError>
17
+ }
18
+
19
+ export class FileStore extends Context.Service<FileStore, IFileStore>()("FileStore") {}
20
+
@@ -0,0 +1,30 @@
1
+ import { Context, Data, type Effect, type Option } from "effect"
2
+
3
+ /** The build could not run at all, such as when the toolchain is missing. A build that runs and fails is a result. */
4
+ export class ProgramBuildFailed extends Data.TaggedError("ProgramBuildFailed")<{ readonly cause: unknown }> {
5
+ override get message() {
6
+ return `the program build failed: ${String(this.cause)}`
7
+ }
8
+ }
9
+
10
+ /** What one build of the program produced. */
11
+ export interface ProgramBuildResult {
12
+ /** Whether the compiled functions linked into one runnable program. */
13
+ readonly linked: boolean
14
+ /** Functions in the program, compiled by this build, still failing to compile, and left out because they refused the link. */
15
+ readonly functions: { readonly total: number; readonly compiled: number; readonly failing: number; readonly excluded: number }
16
+ /** Why it didn't link, when it didn't. */
17
+ readonly failure: Option.Option<string>
18
+ }
19
+
20
+ /**
21
+ * The interface a workflow's build step uses to build the program it works on: compile what changed, link it, and
22
+ * publish the result where the organization serves it. The organization provides the implementation (which toolchain,
23
+ * which machine, where the program and its output live). `changedFunctions` names what the step knows changed; an
24
+ * implementation may find more by itself. The worker records `functions.compiled` as the step's compiles.
25
+ */
26
+ export interface IProgramBuild {
27
+ build(input: { readonly changedFunctions: ReadonlyArray<string> }): Effect.fn.Return<ProgramBuildResult, ProgramBuildFailed>
28
+ }
29
+
30
+ export class ProgramBuild extends Context.Service<ProgramBuild, IProgramBuild>()("ProgramBuild") {}
@@ -0,0 +1,106 @@
1
+ import type { Context, Effect, Option } from "effect"
2
+ import type { Retention, Retries, SubWorkflow, TaskFile, TaskNote } from "../graph"
3
+ import type { Tasks } from "./tasks"
4
+
5
+ export interface StepInput<Fields> {
6
+ readonly taskId: string
7
+ readonly fields: Fields
8
+ readonly files: ReadonlyArray<TaskFile>
9
+ /**
10
+ * Everything said about the task so far, oldest first: its own step runs' notes, the reasons calls sent it back, and
11
+ * the notes on the tasks above it whose sub-workflow steps made it. An agent step puts what it needs of them in its
12
+ * prompt.
13
+ */
14
+ readonly notes: ReadonlyArray<TaskNote>
15
+ /** For an inputs gate (`inputsChanged`): the fingerprint its last settled turn recorded. */
16
+ readonly lastFingerprint: Option.Option<string>
17
+ }
18
+
19
+ /**
20
+ * A write a step's run makes to another task: fields (as stored, encoded by that task's workflow's schema) laid over its
21
+ * own, files added to its own, and a note saying what was done. `workflow` is the step's own when absent.
22
+ */
23
+ export interface OtherTaskWrite {
24
+ readonly workflow?: string
25
+ readonly taskId: string
26
+ readonly fields?: Readonly<Record<string, unknown>>
27
+ readonly files?: ReadonlyArray<{ readonly name: string; readonly bytes: Uint8Array }>
28
+ readonly note: string
29
+ }
30
+
31
+ /** What a step reports: one of its end states, and the fields and files it changed (omitted ones stay as they were). */
32
+ export interface StepOutcome<EndState extends string, Fields> {
33
+ readonly endState: EndState
34
+ readonly fields?: Partial<Fields>
35
+ readonly files?: ReadonlyArray<{ readonly name: string; readonly bytes: Uint8Array }>
36
+ /** What the step measured of processes it started, which the worker cannot see. */
37
+ readonly used?: { readonly childCpuSeconds?: number; readonly compiles?: number }
38
+ /** What the step has to say about the task, such as why it matched or what blocked it; kept on the step's run. */
39
+ readonly note?: string
40
+ /** What the step read of its inputs, as one fingerprint; the step's next run is given it as `lastFingerprint`. */
41
+ readonly fingerprint?: string
42
+ /** From a step that syncs a declared item list (`syncList`): every item on it now, each as its task's fields. */
43
+ readonly listed?: ReadonlyArray<Fields>
44
+ /**
45
+ * Writes to other tasks, of workflows the step's `access.tasks.write` lists, applied with this outcome in one
46
+ * transaction. A task in a step at that moment is skipped, and the run records it with why. A run that fails writes none.
47
+ */
48
+ readonly others?: ReadonlyArray<OtherTaskWrite>
49
+ }
50
+
51
+ /** A service a step can be given: the platform's (`AgentRunner`, `FileStore`, `ProgramBuild`) or one of the organization's. */
52
+ export type ServiceKey = Context.Key<any, any>
53
+
54
+ /** The workflows whose tasks a step may read through `Tasks` and write through `others`, its own included only if listed. */
55
+ export interface TasksGrant {
56
+ readonly read: ReadonlyArray<string>
57
+ readonly write: ReadonlyArray<string>
58
+ }
59
+
60
+ /**
61
+ * What a step's code may use. Nothing listed grants nothing: the step sees only its own task. The worker gives a run
62
+ * only these services, and Convex refuses a read or write of tasks outside `tasks`.
63
+ */
64
+ export interface StepAccess<Services extends ReadonlyArray<ServiceKey>, Grant extends TasksGrant | undefined> {
65
+ readonly services?: Services
66
+ readonly tasks?: Grant
67
+ }
68
+
69
+ /** The requirements a step with this access may have: its listed services, and `Tasks` when it lists any tasks. */
70
+ export type Granted<Services extends ReadonlyArray<ServiceKey>, Grant extends TasksGrant | undefined> =
71
+ | Context.Service.Identifier<Services[number]>
72
+ | (Grant extends TasksGrant ? Tasks : never)
73
+
74
+ /**
75
+ * A step a worker runs: code, or an agent. An agent step takes one unit of its workflow's agent budget, a code step one
76
+ * of its CPU budget. `Services` are what its `run` requires, which its `access` declares.
77
+ */
78
+ export interface RunnableStep<Fields, EndState extends string, Services = never> {
79
+ readonly kind: "code" | "agent"
80
+ readonly endStates: ReadonlyArray<EndState>
81
+ readonly run: (input: StepInput<Fields>) => Effect.fn.Return<StepOutcome<EndState, Fields>, unknown, Services>
82
+ /** What the step declared it uses; the worker provides exactly these services. */
83
+ readonly access: { readonly services: ReadonlyArray<ServiceKey>; readonly tasks?: TasksGrant }
84
+ /** How a failed run is tried again; absent tries it again at once, however often it fails. */
85
+ readonly retries?: Retries & { readonly giveUp: EndState }
86
+ /** Set on an inputs gate: the workflow end states whose turns settle a fingerprint (`inputsChanged`). */
87
+ readonly inputsSettledBy?: ReadonlyArray<string>
88
+ /** Set on a list sync (`syncList`): the id of the `list` event whose tasks it keeps in step with the list. */
89
+ readonly syncs?: string
90
+ /** What its records keep, over its workflow's (`retentionOf`). */
91
+ readonly retention?: Retention
92
+ }
93
+
94
+ /** A step that is another workflow; it runs inside Convex and takes none of its own workflow's budget. */
95
+ export interface SubWorkflowStep<EndState extends string> {
96
+ readonly kind: "workflow"
97
+ readonly endStates: ReadonlyArray<EndState>
98
+ readonly workflow: SubWorkflow
99
+ }
100
+
101
+ export type AnyStep<Fields> = RunnableStep<Fields, string, any> | SubWorkflowStep<string>
102
+
103
+ /** The services the code and agent steps of `Steps` require, together. */
104
+ export type ServicesOfSteps<Steps> = {
105
+ [K in keyof Steps]: Steps[K] extends RunnableStep<any, any, infer Services> ? Services : never
106
+ }[keyof Steps]
@@ -0,0 +1,15 @@
1
+ import type { Schema } from "effect"
2
+
3
+ /** A schema of a task's attribute fields: an object, encoded to JSON-safe values for Convex. */
4
+ export type FieldsSchema = Schema.Codec<Record<string, any>, Record<string, any>>
5
+
6
+ /** A workflow's task: attribute fields stored in Convex, and the names of the files it carries in the workflow's file store. */
7
+ export interface TaskSchema<Fields extends FieldsSchema> {
8
+ readonly fields: Fields
9
+ readonly files: ReadonlyArray<string>
10
+ }
11
+
12
+ export const make = <Fields extends FieldsSchema>(input: { readonly fields: Fields; readonly files?: ReadonlyArray<string> }): TaskSchema<Fields> => ({
13
+ fields: input.fields,
14
+ files: input.files ?? [],
15
+ })
@@ -0,0 +1,43 @@
1
+ import { Context, Data, type Effect } from "effect"
2
+ import type { TaskFile, TaskNote } from "../graph"
3
+
4
+ export class TasksCallFailed extends Data.TaggedError("TasksCallFailed")<{ readonly cause: unknown }> {
5
+ override get message() {
6
+ return `reading tasks failed: ${String(this.cause)}`
7
+ }
8
+ }
9
+
10
+ /** Where a task is now: waiting on a line, in a step, or at an end state, as the workflow's diagram names them. */
11
+ export type TaskPlace = { readonly line: string } | { readonly step: string } | { readonly end: string }
12
+
13
+ /** Which tasks to look at: those waiting in front of a step, in a step, at an end state, or on one line. */
14
+ export type TasksAt = { readonly inFrontOf: string } | { readonly step: string } | { readonly end: string } | { readonly line: string }
15
+
16
+ /** One task another step's run found: its fields as stored (encoded by its workflow's task schema), files, notes and place. */
17
+ export interface FoundTask {
18
+ readonly taskId: string
19
+ readonly workflow: string
20
+ readonly fields: unknown
21
+ readonly files: ReadonlyArray<TaskFile>
22
+ readonly notes: ReadonlyArray<TaskNote>
23
+ readonly at: TaskPlace
24
+ }
25
+
26
+ /**
27
+ * Other tasks a step's run can read, of the workflows its `access.tasks.read` lists. It writes to them through its
28
+ * outcome's `others`, which Convex applies with the run's own result.
29
+ */
30
+ export interface ITasks {
31
+ /**
32
+ * Tasks of `workflow` (by default the step's own) whose fields equal every value in `where`, compared as stored,
33
+ * narrowed to one place by `at`; at most `limit` of them, in no set order.
34
+ */
35
+ find(input: {
36
+ readonly workflow?: string
37
+ readonly where?: Readonly<Record<string, unknown>>
38
+ readonly at?: TasksAt
39
+ readonly limit: number
40
+ }): Effect.fn.Return<ReadonlyArray<FoundTask>, TasksCallFailed>
41
+ }
42
+
43
+ export class Tasks extends Context.Service<Tasks, ITasks>()("Tasks") {}
@@ -0,0 +1,255 @@
1
+ import { Cause, Effect, Exit, Option, Schema } from "effect"
2
+ import {
3
+ type Budgets,
4
+ everySubWorkflowTaskEnded,
5
+ type GraphEvent,
6
+ type GraphStep,
7
+ lineIdOf,
8
+ type Retention,
9
+ type StepAccessGraph,
10
+ type WorkflowGraph,
11
+ } from "../graph"
12
+ import type {
13
+ AnyStep,
14
+ Granted,
15
+ RunnableStep,
16
+ ServiceKey,
17
+ ServicesOfSteps,
18
+ StepAccess,
19
+ StepInput,
20
+ StepOutcome,
21
+ SubWorkflowStep,
22
+ TasksGrant,
23
+ } from "./step"
24
+ import type { FieldsSchema, TaskSchema } from "./task-schema"
25
+
26
+ /**
27
+ * One workflow: its task schema, the steps tasks go through, the lines between them, the events that start flows,
28
+ * the end states it names and its budget defaults. `graph` is the form the Convex component runs; `runnableSteps` is
29
+ * what workers run, and `Services` what its steps require of the worker running them.
30
+ */
31
+ export interface WorkflowDefinition<Fields extends FieldsSchema = FieldsSchema, EndState extends string = string, Services = any> {
32
+ readonly name: string
33
+ readonly task: TaskSchema<Fields>
34
+ readonly endStates: ReadonlyArray<EndState>
35
+ readonly graph: WorkflowGraph
36
+ readonly runnableSteps: Readonly<Record<string, RunnableStep<Fields["Type"], string, Services>>>
37
+ }
38
+
39
+ export type EventDefinition<Fields> =
40
+ | { readonly kind: "task" }
41
+ | { readonly kind: "change"; readonly field: keyof Fields & string; readonly resumes?: string }
42
+ /**
43
+ * A turn every `everyMs`: a new task whose fields are what the task schema decodes from `{}`, so every field of a
44
+ * workflow a timer starts needs a default. One that has none is refused when the workflow is registered.
45
+ */
46
+ | { readonly kind: "timer"; readonly everyMs: number }
47
+ | { readonly kind: "request" }
48
+ /**
49
+ * A declared item list, kept as tasks by the step that syncs it (`syncList`): each item's task arrives here, keyed by its
50
+ * string field `key`, and one whose item leaves the list before it ends ends in `leftAs`, one of the workflow's end states.
51
+ */
52
+ | { readonly kind: "list"; readonly key: StringFieldOf<Fields>; readonly leftAs: string }
53
+
54
+ /** The fields of `Fields` that hold a string. */
55
+ type StringFieldOf<Fields> = { [K in keyof Fields]: Fields[K] extends string ? K : never }[keyof Fields] & string
56
+
57
+ /** The list fields of `Fields` whose entries are tasks of a workflow with `Entry` fields. */
58
+ type ListFieldOf<Fields, Entry> = { [K in keyof Fields]: Fields[K] extends ReadonlyArray<Entry> ? K : never }[keyof Fields] & string
59
+
60
+ /** A step's code: what it may use (`access`), and its `run`, which may require only that. */
61
+ interface RunnableStepInput<Fields, EndState extends string, Services extends ReadonlyArray<ServiceKey>, Grant extends TasksGrant | undefined> {
62
+ readonly endStates: ReadonlyArray<EndState>
63
+ readonly access?: StepAccess<Services, Grant>
64
+ readonly run: (input: StepInput<Fields>) => Effect.fn.Return<StepOutcome<NoInfer<EndState>, Fields>, unknown, NoInfer<Granted<Services, Grant>>>
65
+ readonly retries?: { readonly limit: number; readonly delayMs: number; readonly giveUp: NoInfer<EndState> }
66
+ /** What this step's records keep, over its workflow's. */
67
+ readonly retention?: Retention
68
+ }
69
+
70
+ export interface StepBuilder<Fields> {
71
+ code<const EndState extends string, const Services extends ReadonlyArray<ServiceKey> = [], const Grant extends TasksGrant | undefined = undefined>(
72
+ input: RunnableStepInput<Fields, EndState, Services, Grant>,
73
+ ): RunnableStep<Fields, EndState, Granted<Services, Grant>>
74
+ agent<const EndState extends string, const Services extends ReadonlyArray<ServiceKey> = [], const Grant extends TasksGrant | undefined = undefined>(
75
+ input: RunnableStepInput<Fields, EndState, Services, Grant>,
76
+ ): RunnableStep<Fields, EndState, Granted<Services, Grant>>
77
+ /** One task of `workflow` with this task's fields; the step ends with the end state that task reaches. */
78
+ workflow<ChildFields extends FieldsSchema, ChildEnd extends string>(input: {
79
+ readonly workflow: WorkflowDefinition<ChildFields, ChildEnd>
80
+ }): SubWorkflowStep<ChildEnd>
81
+ /**
82
+ * An inputs gate: `read` fingerprints what the workflow works from (files, records), and the step ends "changed" when
83
+ * that differs from the fingerprint of the last turn that settled one, or when none has, and "unchanged" otherwise. A
84
+ * turn settles its fingerprint when its task ends in one of `settledBy`, the workflow's success end states, as
85
+ * decomp-service's `runIfInputsChanged` compares with its last successful run. A turn that saw a change and then
86
+ * failed settles nothing, so the next one does the work again. Put first in a workflow a timer starts, it lets a turn
87
+ * do its work only when its inputs changed.
88
+ */
89
+ inputsChanged<const Services extends ReadonlyArray<ServiceKey> = [], const Grant extends TasksGrant | undefined = undefined>(input: {
90
+ readonly access?: StepAccess<Services, Grant>
91
+ readonly read: (input: StepInput<Fields>) => Effect.fn.Return<string, unknown, NoInfer<Granted<Services, Grant>>>
92
+ readonly settledBy: ReadonlyArray<string>
93
+ }): RunnableStep<Fields, "changed" | "unchanged", Granted<Services, Grant>>
94
+ /**
95
+ * Reads a declared item list, the `list` event `list`: `read` returns every item on it now, each as its task's fields,
96
+ * and the step ends "synced" once the list's tasks are in step with it (each new item a task, each item gone from it
97
+ * ended in the event's `leftAs`). Put in a workflow a timer starts, it keeps the list's tasks in step as it changes.
98
+ */
99
+ syncList<const Services extends ReadonlyArray<ServiceKey> = [], const Grant extends TasksGrant | undefined = undefined>(input: {
100
+ readonly access?: StepAccess<Services, Grant>
101
+ readonly list: string
102
+ readonly read: (input: StepInput<Fields>) => Effect.fn.Return<ReadonlyArray<Fields>, unknown, NoInfer<Granted<Services, Grant>>>
103
+ }): RunnableStep<Fields, "synced", Granted<Services, Grant>>
104
+ /**
105
+ * One task of `workflow` per entry of the list field `each`; the step ends with `ended` once all of them have.
106
+ * With `collect`, each one that ends in `collect.endState` has its fields appended to the list field `collect.into`.
107
+ */
108
+ each<ChildFields extends FieldsSchema, ChildEnd extends string>(input: {
109
+ readonly workflow: WorkflowDefinition<ChildFields, ChildEnd>
110
+ readonly each: ListFieldOf<Fields, ChildFields["Type"]>
111
+ readonly collect?: { readonly endState: NoInfer<ChildEnd>; readonly into: ListFieldOf<Fields, ChildFields["Type"]> }
112
+ }): SubWorkflowStep<typeof everySubWorkflowTaskEnded>
113
+ }
114
+
115
+ type LineStartOf<Steps extends Record<string, AnyStep<any>>, Events, EndState extends string> =
116
+ | { readonly event: keyof Events & string }
117
+ | { [K in keyof Steps & string]: { readonly step: K; readonly endState: Steps[K]["endStates"][number] } }[keyof Steps & string]
118
+ | { readonly end: EndState }
119
+
120
+ type LineEndOf<Steps, EndState extends string> = { readonly step: keyof Steps & string } | { readonly end: EndState }
121
+
122
+ export interface LineDefinition<Steps extends Record<string, AnyStep<any>>, Events, EndState extends string> {
123
+ readonly from: LineStartOf<Steps, Events, EndState>
124
+ readonly to: LineEndOf<Steps, EndState>
125
+ }
126
+
127
+ /** A step's declared access as its runnable form keeps it: nothing declared is nothing granted. */
128
+ const accessOf = (access: { readonly services?: ReadonlyArray<ServiceKey>; readonly tasks?: TasksGrant | undefined } | undefined) => ({
129
+ services: [...(access?.services ?? [])],
130
+ ...(access?.tasks !== undefined ? { tasks: { read: [...access.tasks.read], write: [...access.tasks.write] } } : {}),
131
+ })
132
+
133
+ const stepBuilder = <Fields>(): StepBuilder<Fields> => ({
134
+ syncList: (input) => ({
135
+ kind: "code",
136
+ endStates: ["synced"],
137
+ access: accessOf(input.access),
138
+ syncs: input.list,
139
+ run: function* (task) {
140
+ return { endState: "synced" as const, listed: yield* input.read(task) }
141
+ },
142
+ }),
143
+ inputsChanged: (input) => ({
144
+ kind: "code",
145
+ endStates: ["changed", "unchanged"],
146
+ access: accessOf(input.access),
147
+ inputsSettledBy: [...input.settledBy],
148
+ run: function* (task) {
149
+ const fingerprint = yield* input.read(task)
150
+ const unchanged = Option.isSome(task.lastFingerprint) && task.lastFingerprint.value === fingerprint
151
+ return { endState: unchanged ? ("unchanged" as const) : ("changed" as const), fingerprint }
152
+ },
153
+ }),
154
+ code: (input) => ({
155
+ kind: "code",
156
+ endStates: input.endStates,
157
+ access: accessOf(input.access),
158
+ run: input.run,
159
+ ...(input.retries !== undefined ? { retries: input.retries } : {}),
160
+ ...(input.retention !== undefined ? { retention: input.retention } : {}),
161
+ }),
162
+ agent: (input) => ({
163
+ kind: "agent",
164
+ endStates: input.endStates,
165
+ access: accessOf(input.access),
166
+ run: input.run,
167
+ ...(input.retries !== undefined ? { retries: input.retries } : {}),
168
+ ...(input.retention !== undefined ? { retention: input.retention } : {}),
169
+ }),
170
+ workflow: (input) => ({ kind: "workflow", endStates: input.workflow.endStates, workflow: { name: input.workflow.name } }),
171
+ each: (input) => ({
172
+ kind: "workflow",
173
+ endStates: [everySubWorkflowTaskEnded],
174
+ workflow: { name: input.workflow.name, each: input.each, ...(input.collect !== undefined ? { collect: input.collect } : {}) },
175
+ }),
176
+ })
177
+
178
+ /** A timer's turn task: what the task schema decodes from `{}`, encoded as Convex stores it, or why it cannot be made. */
179
+ const turnFieldsOf = (fields: FieldsSchema): { readonly fields: unknown } | { readonly fieldsProblem: string } => {
180
+ const decoded = Schema.decodeUnknownExit(fields)({})
181
+ if (Exit.isFailure(decoded)) return { fieldsProblem: `its task schema cannot make a task from {}, so some field has no default: ${Cause.pretty(decoded.cause)}` }
182
+ const encoded = Schema.encodeUnknownExit(fields)(decoded.value)
183
+ if (Exit.isFailure(encoded)) return { fieldsProblem: `the task its schema makes from {} cannot be encoded: ${Cause.pretty(encoded.cause)}` }
184
+ return { fields: encoded.value }
185
+ }
186
+
187
+ export const make = <
188
+ Fields extends FieldsSchema,
189
+ const EndState extends string,
190
+ const Events extends Record<string, EventDefinition<Fields["Type"]>>,
191
+ const Steps extends Record<string, AnyStep<Fields["Type"]>>,
192
+ >(input: {
193
+ readonly name: string
194
+ readonly task: TaskSchema<Fields>
195
+ readonly endStates: ReadonlyArray<EndState>
196
+ readonly budgets: Budgets
197
+ /** How long its records are kept, unless a step sets its own: 7 days and the newest 10,000 runs by default. */
198
+ readonly retention?: Retention
199
+ /**
200
+ * At most `limit` tasks in progress at once, or of each value of the field `per`: a lock held from a task's first step to
201
+ * its end, such as one on each function that every workflow touching it goes through as a sub-workflow step.
202
+ */
203
+ readonly inProgress?: { readonly limit: number; readonly per?: keyof Fields["Type"] & string }
204
+ readonly events: Events
205
+ readonly steps: (step: StepBuilder<Fields["Type"]>) => Steps
206
+ readonly lines: ReadonlyArray<LineDefinition<NoInfer<Steps>, NoInfer<Events>, NoInfer<EndState>>>
207
+ }): WorkflowDefinition<Fields, EndState, ServicesOfSteps<Steps>> => {
208
+ const steps = input.steps(stepBuilder<Fields["Type"]>())
209
+ const events: Array<GraphEvent> = Object.entries(input.events).map(([id, event]): GraphEvent =>
210
+ event.kind === "timer"
211
+ ? { id, kind: "timer", everyMs: event.everyMs, ...turnFieldsOf(input.task.fields) }
212
+ : event.kind === "change"
213
+ ? { id, kind: "change", field: event.field, ...(event.resumes !== undefined ? { resumes: event.resumes } : {}) }
214
+ : event.kind === "list"
215
+ ? { id, kind: "list", key: event.key, leftAs: event.leftAs }
216
+ : { id, kind: event.kind },
217
+ )
218
+ const graphSteps: Array<GraphStep> = Object.entries(steps).map(([id, step]): GraphStep => {
219
+ if (step.kind === "workflow") return { id, kind: "workflow", endStates: [...step.endStates], workflow: step.workflow }
220
+ const access: StepAccessGraph = {
221
+ services: step.access.services.map((service) => service.key),
222
+ ...(step.access.tasks !== undefined ? { tasks: { read: [...step.access.tasks.read], write: [...step.access.tasks.write] } } : {}),
223
+ }
224
+ return {
225
+ id,
226
+ kind: step.kind,
227
+ endStates: [...step.endStates],
228
+ access,
229
+ ...(step.retries !== undefined ? { retries: { ...step.retries } } : {}),
230
+ ...(step.inputsSettledBy !== undefined ? { inputsSettledBy: [...step.inputsSettledBy] } : {}),
231
+ ...(step.syncs !== undefined ? { syncs: step.syncs } : {}),
232
+ ...(step.retention !== undefined ? { retention: { ...step.retention } } : {}),
233
+ }
234
+ })
235
+ const runnableSteps: Record<string, RunnableStep<Fields["Type"], string, ServicesOfSteps<Steps>>> = {}
236
+ for (const [id, step] of Object.entries(steps)) {
237
+ if (step.kind !== "workflow") runnableSteps[id] = step
238
+ }
239
+ return {
240
+ name: input.name,
241
+ task: input.task,
242
+ endStates: input.endStates,
243
+ runnableSteps,
244
+ graph: {
245
+ name: input.name,
246
+ endStates: [...input.endStates],
247
+ events,
248
+ steps: graphSteps,
249
+ lines: input.lines.map((line) => ({ id: lineIdOf(line), from: line.from, to: line.to })),
250
+ budgets: input.budgets,
251
+ ...(input.retention !== undefined ? { retention: { ...input.retention } } : {}),
252
+ ...(input.inProgress !== undefined ? { inProgress: { ...input.inProgress } } : {}),
253
+ },
254
+ }
255
+ }