@praudent/dagma 0.0.0-stage → 0.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 (177) hide show
  1. package/dist/admin-ui/assets/index-CHJ8lsZp.js +120 -0
  2. package/dist/admin-ui/assets/index-XyqtD-IA.css +1 -0
  3. package/dist/admin-ui/index.html +12 -0
  4. package/dist/blueprint/agent.d.ts +148 -0
  5. package/dist/blueprint/agent.js +1 -0
  6. package/dist/blueprint/declaration-site.d.ts +7 -0
  7. package/dist/blueprint/declaration-site.js +8 -0
  8. package/dist/blueprint/declared-structure.d.ts +145 -0
  9. package/dist/blueprint/declared-structure.js +213 -0
  10. package/dist/blueprint/define-run-state.d.ts +79 -0
  11. package/dist/blueprint/define-run-state.js +89 -0
  12. package/dist/blueprint/load-blueprint.d.ts +28 -0
  13. package/dist/blueprint/load-blueprint.js +85 -0
  14. package/dist/blueprint/outcomes.d.ts +76 -0
  15. package/dist/blueprint/outcomes.js +10 -0
  16. package/dist/blueprint/phase.d.ts +153 -0
  17. package/dist/blueprint/phase.js +1 -0
  18. package/dist/blueprint/places.d.ts +26 -0
  19. package/dist/blueprint/places.js +37 -0
  20. package/dist/blueprint/prompt-file.d.ts +81 -0
  21. package/dist/blueprint/prompt-file.js +131 -0
  22. package/dist/blueprint/reply-reader.d.ts +36 -0
  23. package/dist/blueprint/reply-reader.js +38 -0
  24. package/dist/blueprint/run-settings.d.ts +38 -0
  25. package/dist/blueprint/run-settings.js +1 -0
  26. package/dist/blueprint/serializer.d.ts +14 -0
  27. package/dist/blueprint/serializer.js +4 -0
  28. package/dist/blueprint/write-scope.d.ts +39 -0
  29. package/dist/blueprint/write-scope.js +106 -0
  30. package/dist/command.d.ts +2 -0
  31. package/dist/command.js +148 -0
  32. package/dist/commands/calls-answering.d.ts +16 -0
  33. package/dist/commands/calls-answering.js +63 -0
  34. package/dist/commands/json-file.d.ts +6 -0
  35. package/dist/commands/json-file.js +19 -0
  36. package/dist/commands/run-command.d.ts +23 -0
  37. package/dist/commands/run-command.js +172 -0
  38. package/dist/commands/typed-answers.d.ts +10 -0
  39. package/dist/commands/typed-answers.js +43 -0
  40. package/dist/config.d.ts +27 -0
  41. package/dist/config.js +20 -0
  42. package/dist/devtool-server/app-pages.d.ts +12 -0
  43. package/dist/devtool-server/app-pages.js +68 -0
  44. package/dist/devtool-server/blueprint-description.d.ts +21 -0
  45. package/dist/devtool-server/blueprint-description.js +27 -0
  46. package/dist/devtool-server/connected-runs.d.ts +36 -0
  47. package/dist/devtool-server/connected-runs.js +201 -0
  48. package/dist/devtool-server/devtool-server.d.ts +17 -0
  49. package/dist/devtool-server/devtool-server.js +294 -0
  50. package/dist/devtool-server/devtool-shapes.d.ts +312 -0
  51. package/dist/devtool-server/devtool-shapes.js +24 -0
  52. package/dist/devtool-server/listed-runs.d.ts +17 -0
  53. package/dist/devtool-server/listed-runs.js +42 -0
  54. package/dist/devtool-server/print-blueprint.d.ts +1 -0
  55. package/dist/devtool-server/print-blueprint.js +36 -0
  56. package/dist/example/added-species.d.ts +21 -0
  57. package/dist/example/added-species.js +19 -0
  58. package/dist/example/cover.d.ts +21 -0
  59. package/dist/example/cover.js +67 -0
  60. package/dist/example/cross-references.d.ts +21 -0
  61. package/dist/example/cross-references.js +77 -0
  62. package/dist/example/entry-drafts.d.ts +21 -0
  63. package/dist/example/entry-drafts.js +63 -0
  64. package/dist/example/entry-merge.d.ts +108 -0
  65. package/dist/example/entry-merge.js +284 -0
  66. package/dist/example/field-guide.d.ts +26 -0
  67. package/dist/example/field-guide.js +40 -0
  68. package/dist/example/guide-page.d.ts +21 -0
  69. package/dist/example/guide-page.js +15 -0
  70. package/dist/example/missing-species.d.ts +21 -0
  71. package/dist/example/missing-species.js +59 -0
  72. package/dist/example/run-state.d.ts +803 -0
  73. package/dist/example/run-state.js +58 -0
  74. package/dist/example/serializers.d.ts +32 -0
  75. package/dist/example/serializers.js +42 -0
  76. package/dist/example/species-list.d.ts +47 -0
  77. package/dist/example/species-list.js +93 -0
  78. package/dist/index.d.ts +35 -0
  79. package/dist/index.js +25 -0
  80. package/dist/inference/anthropic-api.d.ts +37 -0
  81. package/dist/inference/anthropic-api.js +197 -0
  82. package/dist/inference/anthropic-prices.d.ts +18 -0
  83. package/dist/inference/anthropic-prices.js +39 -0
  84. package/dist/inference/anthropic-request.d.ts +51 -0
  85. package/dist/inference/anthropic-request.js +208 -0
  86. package/dist/inference/bedrock-api.d.ts +45 -0
  87. package/dist/inference/bedrock-api.js +242 -0
  88. package/dist/inference/bedrock-prices.d.ts +22 -0
  89. package/dist/inference/bedrock-prices.js +79 -0
  90. package/dist/inference/bedrock-request.d.ts +27 -0
  91. package/dist/inference/bedrock-request.js +193 -0
  92. package/dist/inference/call-queue-shapes.d.ts +273 -0
  93. package/dist/inference/call-queue-shapes.js +82 -0
  94. package/dist/inference/call-queue.d.ts +109 -0
  95. package/dist/inference/call-queue.js +408 -0
  96. package/dist/inference/gemini-api.d.ts +44 -0
  97. package/dist/inference/gemini-api.js +191 -0
  98. package/dist/inference/gemini-prices.d.ts +19 -0
  99. package/dist/inference/gemini-prices.js +33 -0
  100. package/dist/inference/gemini-request.d.ts +25 -0
  101. package/dist/inference/gemini-request.js +126 -0
  102. package/dist/inference/inference.d.ts +84 -0
  103. package/dist/inference/inference.js +9 -0
  104. package/dist/inference/openai-api.d.ts +29 -0
  105. package/dist/inference/openai-api.js +138 -0
  106. package/dist/inference/openai-prices.d.ts +12 -0
  107. package/dist/inference/openai-prices.js +25 -0
  108. package/dist/inference/openai-request.d.ts +50 -0
  109. package/dist/inference/openai-request.js +100 -0
  110. package/dist/inference/own-worker.d.ts +6 -0
  111. package/dist/inference/own-worker.js +16 -0
  112. package/dist/inference/scripted.d.ts +146 -0
  113. package/dist/inference/scripted.js +67 -0
  114. package/dist/run/assignments/agent-call.d.ts +32 -0
  115. package/dist/run/assignments/agent-call.js +218 -0
  116. package/dist/run/assignments/agent-phase.d.ts +14 -0
  117. package/dist/run/assignments/agent-phase.js +243 -0
  118. package/dist/run/assignments/assignment-memory.d.ts +42 -0
  119. package/dist/run/assignments/assignment-memory.js +52 -0
  120. package/dist/run/assignments/assignment.d.ts +17 -0
  121. package/dist/run/assignments/assignment.js +252 -0
  122. package/dist/run/assignments/model-settings.d.ts +39 -0
  123. package/dist/run/assignments/model-settings.js +57 -0
  124. package/dist/run/assignments/prepared-call.d.ts +28 -0
  125. package/dist/run/assignments/prepared-call.js +115 -0
  126. package/dist/run/assignments/tool-call.d.ts +26 -0
  127. package/dist/run/assignments/tool-call.js +108 -0
  128. package/dist/run/blueprint-mistake.d.ts +8 -0
  129. package/dist/run/blueprint-mistake.js +14 -0
  130. package/dist/run/code-phase.d.ts +11 -0
  131. package/dist/run/code-phase.js +59 -0
  132. package/dist/run/create-run.d.ts +36 -0
  133. package/dist/run/create-run.js +119 -0
  134. package/dist/run/execute-run.d.ts +7 -0
  135. package/dist/run/execute-run.js +158 -0
  136. package/dist/run/record/apply-event.d.ts +13 -0
  137. package/dist/run/record/apply-event.js +256 -0
  138. package/dist/run/record/events.d.ts +187 -0
  139. package/dist/run/record/events.js +1 -0
  140. package/dist/run/record/postgres-run-store.d.ts +13 -0
  141. package/dist/run/record/postgres-run-store.js +189 -0
  142. package/dist/run/record/progress-projection.d.ts +83 -0
  143. package/dist/run/record/progress-projection.js +167 -0
  144. package/dist/run/record/progress.d.ts +207 -0
  145. package/dist/run/record/progress.js +63 -0
  146. package/dist/run/record/run-store.d.ts +74 -0
  147. package/dist/run/record/run-store.js +1 -0
  148. package/dist/run/record/run-summary.d.ts +8 -0
  149. package/dist/run/record/run-summary.js +19 -0
  150. package/dist/run/record/run-types.d.ts +95 -0
  151. package/dist/run/record/run-types.js +1 -0
  152. package/dist/run/record/state-changes.d.ts +42 -0
  153. package/dist/run/record/state-changes.js +157 -0
  154. package/dist/run/resume-run.d.ts +25 -0
  155. package/dist/run/resume-run.js +99 -0
  156. package/dist/run/run-endings.d.ts +20 -0
  157. package/dist/run/run-endings.js +20 -0
  158. package/dist/run/run-option-shapes.d.ts +176 -0
  159. package/dist/run/run-option-shapes.js +47 -0
  160. package/dist/run/run-session.d.ts +144 -0
  161. package/dist/run/run-session.js +278 -0
  162. package/dist/worker/answer-queued-call.d.ts +19 -0
  163. package/dist/worker/answer-queued-call.js +100 -0
  164. package/dist/worker/launchers/claude-code.d.ts +7 -0
  165. package/dist/worker/launchers/claude-code.js +156 -0
  166. package/dist/worker/launchers/codex.d.ts +6 -0
  167. package/dist/worker/launchers/codex.js +141 -0
  168. package/dist/worker/launchers/launch.d.ts +31 -0
  169. package/dist/worker/launchers/launch.js +6 -0
  170. package/dist/worker/launchers/program-run.d.ts +30 -0
  171. package/dist/worker/launchers/program-run.js +92 -0
  172. package/dist/worker/launchers/tool-server.d.ts +26 -0
  173. package/dist/worker/launchers/tool-server.js +90 -0
  174. package/dist/worker/worker.d.ts +13 -0
  175. package/dist/worker/worker.js +170 -0
  176. package/package.json +43 -4
  177. package/README.md +0 -3
@@ -0,0 +1,176 @@
1
+ import { z } from 'zod';
2
+ /** The shapes of what a person chooses when starting or resuming a run, as the command and the
3
+ * devtool both read them. */
4
+ export declare const CallsAnsweredBySchema: z.ZodEnum<["codex", "claude-code", "openai-api", "anthropic-api", "bedrock-api", "gemini-api", "scripted"]>;
5
+ export declare const QuestionsAnsweredBySchema: z.ZodEnum<["person", "recommendation"]>;
6
+ export declare const ModelSettingsSchema: z.ZodObject<{
7
+ effort: z.ZodOptional<z.ZodEnum<["none", "low", "medium", "high"]>>;
8
+ model: z.ZodOptional<z.ZodObject<{
9
+ codex: z.ZodOptional<z.ZodString>;
10
+ 'claude-code': z.ZodOptional<z.ZodString>;
11
+ 'openai-api': z.ZodOptional<z.ZodString>;
12
+ 'anthropic-api': z.ZodOptional<z.ZodString>;
13
+ 'bedrock-api': z.ZodOptional<z.ZodString>;
14
+ 'gemini-api': z.ZodOptional<z.ZodString>;
15
+ }, "strict", z.ZodTypeAny, {
16
+ codex?: string | undefined;
17
+ 'claude-code'?: string | undefined;
18
+ 'openai-api'?: string | undefined;
19
+ 'anthropic-api'?: string | undefined;
20
+ 'bedrock-api'?: string | undefined;
21
+ 'gemini-api'?: string | undefined;
22
+ }, {
23
+ codex?: string | undefined;
24
+ 'claude-code'?: string | undefined;
25
+ 'openai-api'?: string | undefined;
26
+ 'anthropic-api'?: string | undefined;
27
+ 'bedrock-api'?: string | undefined;
28
+ 'gemini-api'?: string | undefined;
29
+ }>>;
30
+ }, "strict", z.ZodTypeAny, {
31
+ model?: {
32
+ codex?: string | undefined;
33
+ 'claude-code'?: string | undefined;
34
+ 'openai-api'?: string | undefined;
35
+ 'anthropic-api'?: string | undefined;
36
+ 'bedrock-api'?: string | undefined;
37
+ 'gemini-api'?: string | undefined;
38
+ } | undefined;
39
+ effort?: "none" | "low" | "medium" | "high" | undefined;
40
+ }, {
41
+ model?: {
42
+ codex?: string | undefined;
43
+ 'claude-code'?: string | undefined;
44
+ 'openai-api'?: string | undefined;
45
+ 'anthropic-api'?: string | undefined;
46
+ 'bedrock-api'?: string | undefined;
47
+ 'gemini-api'?: string | undefined;
48
+ } | undefined;
49
+ effort?: "none" | "low" | "medium" | "high" | undefined;
50
+ }>;
51
+ /** A run's own model settings, each for every call, one phase or one agent. */
52
+ export declare const ModelOverridesSchema: z.ZodArray<z.ZodObject<{
53
+ phase: z.ZodOptional<z.ZodString>;
54
+ agent: z.ZodOptional<z.ZodString>;
55
+ modelSettings: z.ZodObject<{
56
+ effort: z.ZodOptional<z.ZodEnum<["none", "low", "medium", "high"]>>;
57
+ model: z.ZodOptional<z.ZodObject<{
58
+ codex: z.ZodOptional<z.ZodString>;
59
+ 'claude-code': z.ZodOptional<z.ZodString>;
60
+ 'openai-api': z.ZodOptional<z.ZodString>;
61
+ 'anthropic-api': z.ZodOptional<z.ZodString>;
62
+ 'bedrock-api': z.ZodOptional<z.ZodString>;
63
+ 'gemini-api': z.ZodOptional<z.ZodString>;
64
+ }, "strict", z.ZodTypeAny, {
65
+ codex?: string | undefined;
66
+ 'claude-code'?: string | undefined;
67
+ 'openai-api'?: string | undefined;
68
+ 'anthropic-api'?: string | undefined;
69
+ 'bedrock-api'?: string | undefined;
70
+ 'gemini-api'?: string | undefined;
71
+ }, {
72
+ codex?: string | undefined;
73
+ 'claude-code'?: string | undefined;
74
+ 'openai-api'?: string | undefined;
75
+ 'anthropic-api'?: string | undefined;
76
+ 'bedrock-api'?: string | undefined;
77
+ 'gemini-api'?: string | undefined;
78
+ }>>;
79
+ }, "strict", z.ZodTypeAny, {
80
+ model?: {
81
+ codex?: string | undefined;
82
+ 'claude-code'?: string | undefined;
83
+ 'openai-api'?: string | undefined;
84
+ 'anthropic-api'?: string | undefined;
85
+ 'bedrock-api'?: string | undefined;
86
+ 'gemini-api'?: string | undefined;
87
+ } | undefined;
88
+ effort?: "none" | "low" | "medium" | "high" | undefined;
89
+ }, {
90
+ model?: {
91
+ codex?: string | undefined;
92
+ 'claude-code'?: string | undefined;
93
+ 'openai-api'?: string | undefined;
94
+ 'anthropic-api'?: string | undefined;
95
+ 'bedrock-api'?: string | undefined;
96
+ 'gemini-api'?: string | undefined;
97
+ } | undefined;
98
+ effort?: "none" | "low" | "medium" | "high" | undefined;
99
+ }>;
100
+ }, "strict", z.ZodTypeAny, {
101
+ modelSettings: {
102
+ model?: {
103
+ codex?: string | undefined;
104
+ 'claude-code'?: string | undefined;
105
+ 'openai-api'?: string | undefined;
106
+ 'anthropic-api'?: string | undefined;
107
+ 'bedrock-api'?: string | undefined;
108
+ 'gemini-api'?: string | undefined;
109
+ } | undefined;
110
+ effort?: "none" | "low" | "medium" | "high" | undefined;
111
+ };
112
+ phase?: string | undefined;
113
+ agent?: string | undefined;
114
+ }, {
115
+ modelSettings: {
116
+ model?: {
117
+ codex?: string | undefined;
118
+ 'claude-code'?: string | undefined;
119
+ 'openai-api'?: string | undefined;
120
+ 'anthropic-api'?: string | undefined;
121
+ 'bedrock-api'?: string | undefined;
122
+ 'gemini-api'?: string | undefined;
123
+ } | undefined;
124
+ effort?: "none" | "low" | "medium" | "high" | undefined;
125
+ };
126
+ phase?: string | undefined;
127
+ agent?: string | undefined;
128
+ }>, "many">;
129
+ export declare const GivenAnswerSchema: z.ZodObject<{
130
+ questionId: z.ZodString;
131
+ answer: z.ZodString;
132
+ }, "strict", z.ZodTypeAny, {
133
+ questionId: string;
134
+ answer: string;
135
+ }, {
136
+ questionId: string;
137
+ answer: string;
138
+ }>;
139
+ /** What is written to an executing run's input, one JSON value per line: Stop, or an answer. */
140
+ export declare const RunInputLineSchema: z.ZodUnion<[z.ZodObject<{
141
+ stop: z.ZodLiteral<true>;
142
+ }, "strict", z.ZodTypeAny, {
143
+ stop: true;
144
+ }, {
145
+ stop: true;
146
+ }>, z.ZodObject<{
147
+ answer: z.ZodObject<{
148
+ questionId: z.ZodString;
149
+ answer: z.ZodString;
150
+ }, "strict", z.ZodTypeAny, {
151
+ questionId: string;
152
+ answer: string;
153
+ }, {
154
+ questionId: string;
155
+ answer: string;
156
+ }>;
157
+ }, "strict", z.ZodTypeAny, {
158
+ answer: {
159
+ questionId: string;
160
+ answer: string;
161
+ };
162
+ }, {
163
+ answer: {
164
+ questionId: string;
165
+ answer: string;
166
+ };
167
+ }>]>;
168
+ /** The first line an executing run prints when it prints its events: which run it is. Every
169
+ * later line is one events line. */
170
+ export declare const RunNamedLineSchema: z.ZodObject<{
171
+ runId: z.ZodString;
172
+ }, "strict", z.ZodTypeAny, {
173
+ runId: string;
174
+ }, {
175
+ runId: string;
176
+ }>;
@@ -0,0 +1,47 @@
1
+ import { z } from 'zod';
2
+ /** The shapes of what a person chooses when starting or resuming a run, as the command and the
3
+ * devtool both read them. */
4
+ export const CallsAnsweredBySchema = z.enum([
5
+ 'codex',
6
+ 'claude-code',
7
+ 'openai-api',
8
+ 'anthropic-api',
9
+ 'bedrock-api',
10
+ 'gemini-api',
11
+ 'scripted',
12
+ ]);
13
+ export const QuestionsAnsweredBySchema = z.enum(['person', 'recommendation']);
14
+ export const ModelSettingsSchema = z
15
+ .object({
16
+ effort: z.enum(['none', 'low', 'medium', 'high']).optional(),
17
+ model: z
18
+ .object({
19
+ codex: z.string().optional(),
20
+ 'claude-code': z.string().optional(),
21
+ 'openai-api': z.string().optional(),
22
+ 'anthropic-api': z.string().optional(),
23
+ 'bedrock-api': z.string().optional(),
24
+ 'gemini-api': z.string().optional(),
25
+ })
26
+ .strict()
27
+ .optional(),
28
+ })
29
+ .strict();
30
+ /** A run's own model settings, each for every call, one phase or one agent. */
31
+ export const ModelOverridesSchema = z
32
+ .object({
33
+ phase: z.string().optional(),
34
+ agent: z.string().optional(),
35
+ modelSettings: ModelSettingsSchema,
36
+ })
37
+ .strict()
38
+ .array();
39
+ export const GivenAnswerSchema = z.object({ questionId: z.string(), answer: z.string() }).strict();
40
+ /** What is written to an executing run's input, one JSON value per line: Stop, or an answer. */
41
+ export const RunInputLineSchema = z.union([
42
+ z.object({ stop: z.literal(true) }).strict(),
43
+ z.object({ answer: GivenAnswerSchema }).strict(),
44
+ ]);
45
+ /** The first line an executing run prints when it prints its events: which run it is. Every
46
+ * later line is one events line. */
47
+ export const RunNamedLineSchema = z.object({ runId: z.string() }).strict();
@@ -0,0 +1,144 @@
1
+ import type { Answer, Artifact, ArtifactReader, Change, Question } from '../blueprint/outcomes.js';
2
+ import type { Blueprint } from '../blueprint/phase.js';
3
+ import type { PromptFile } from '../blueprint/prompt-file.js';
4
+ import type { QuestionsAnsweredBy } from '../blueprint/run-settings.js';
5
+ import type { Infer } from '../inference/inference.js';
6
+ import type { ChangeEntry, RunEvent, RunHappening, SavedArtifact, SavedQuestion } from './record/events.js';
7
+ import { type ProgressDelta, type ProgressSnapshot } from './record/progress-projection.js';
8
+ import type { Checkpoint, RunProgress } from './record/progress.js';
9
+ import type { RunStore } from './record/run-store.js';
10
+ import type { CallFile } from './record/run-types.js';
11
+ export type RunEventObserver = (event: RunEvent, delta: ProgressDelta) => void | Promise<void>;
12
+ /** One run while a process executes it: its store, its progress, and the rules every part of the
13
+ * run shares (events in order, one change at a time, questions, artifacts, Stop). */
14
+ export declare class RunSession<State = unknown, Services = any> {
15
+ readonly runId: string;
16
+ readonly store: RunStore;
17
+ readonly blueprint: Blueprint<State, any, Services>;
18
+ readonly promptFiles: {
19
+ [agentName: string]: PromptFile;
20
+ };
21
+ readonly infer: Infer;
22
+ readonly services: Services;
23
+ /** How long to wait before the second and third attempt of a call whose connection failed. */
24
+ readonly retryWaitsMs: number[];
25
+ progress: RunProgress;
26
+ private readonly start;
27
+ private readonly events;
28
+ private readonly onEvent?;
29
+ private readonly stopController;
30
+ private readonly drainController;
31
+ private readonly callFiles;
32
+ private lastSnapshot;
33
+ private appending;
34
+ private notifying;
35
+ private turn;
36
+ private answerListeners;
37
+ private changeListeners;
38
+ private lastIdNumber;
39
+ constructor(options: {
40
+ runId: string;
41
+ store: RunStore;
42
+ blueprint: Blueprint<State, any, Services>;
43
+ promptFiles: {
44
+ [agentName: string]: PromptFile;
45
+ };
46
+ infer: Infer;
47
+ services?: Services;
48
+ retryWaitsMs?: number[];
49
+ start: Checkpoint;
50
+ events: RunEvent[];
51
+ /** Called with each event and progress delta in strict `seq` order once persisted. */
52
+ onEvent?: RunEventObserver;
53
+ });
54
+ get state(): State;
55
+ get questionsAnsweredBy(): QuestionsAnsweredBy;
56
+ /** The signal that Stop, or the run's first failure, triggers. */
57
+ get stopSignal(): AbortSignal;
58
+ /** The signal that a graceful drain triggers: in-flight calls finish, no new work starts. */
59
+ get drainSignal(): AbortSignal;
60
+ /** Current serializable progress snapshot for this run. */
61
+ currentProgressSnapshot(): ProgressSnapshot;
62
+ /** A new id for a call, an assignment, a question or an artifact's owner. No two are alike in
63
+ * one run, also when several are made in the same moment and after Resume. */
64
+ newId({ prefix }: {
65
+ prefix: string;
66
+ }): string;
67
+ /** Ends the work in progress. With a `RunStopped` reason the run is left stopped; with any
68
+ * other error it is the run's first failure cancelling the rest. */
69
+ endWorkInProgress({ reason }: {
70
+ reason: Error;
71
+ }): void;
72
+ /** Stops starting new work while letting calls already in progress finish and save their
73
+ * outcomes before the run stops. */
74
+ drain({ reason }: {
75
+ reason: Error;
76
+ }): void;
77
+ /** Adds one event to the run's store and applies it to the run's progress. The progress is
78
+ * current as soon as this is called; the returned promise settles once persisted and after any
79
+ * async `onEvent` observer finishes in strict `seq` order. */
80
+ record(happening: RunHappening): Promise<RunEvent>;
81
+ /** Runs work that reads the state and may change it, one piece at a time across the whole run,
82
+ * each to its end. A reply is therefore always judged against the latest state. */
83
+ inTurn<Result>(work: () => Promise<Result> | Result): Promise<Result>;
84
+ /** The run state as it stood after an events line. */
85
+ stateAt({ seq }: {
86
+ seq: number;
87
+ }): State;
88
+ /** Works out a change against the state as it stands, checks it, and writes the artifacts'
89
+ * bytes. Returns what the events line that makes them count must carry. Call it inside
90
+ * `inTurn`, and record that line before the turn ends. */
91
+ writeArtifactsAndCheckChange({ change, artifacts, madeBy, }: {
92
+ change?: Change<State>;
93
+ artifacts?: Artifact[];
94
+ /** What makes the writes, for the message when the change is a mistake. */
95
+ madeBy: string;
96
+ }): Promise<{
97
+ change?: ChangeEntry[];
98
+ artifacts?: SavedArtifact[];
99
+ }>;
100
+ readonly artifacts: ArtifactReader;
101
+ /** Gives new questions their ids. The events line that asks them carries the result. */
102
+ newQuestions({ questions, askedBy, }: {
103
+ questions: Question[];
104
+ /** What asks, for the message when it asked nothing. */
105
+ askedBy: string;
106
+ }): SavedQuestion[];
107
+ /** In a run answered by the recommendation, answers at once each of these questions that has
108
+ * one. Returns whether all of them are now answered. */
109
+ answerByRecommendation({ questions }: {
110
+ questions: SavedQuestion[];
111
+ }): Promise<boolean>;
112
+ /** Why an answer cannot be recorded; undefined when it can. */
113
+ answerProblem({ questionId }: {
114
+ questionId: string;
115
+ }): string | undefined;
116
+ /** Records the answer to a waiting question. Only the process executing the run calls it. */
117
+ recordAnswer({ questionId, answer, answeredBy, }: {
118
+ questionId: string;
119
+ answer: string;
120
+ answeredBy: 'person' | 'run';
121
+ }): Promise<void>;
122
+ /** Settles when the next answer is recorded. */
123
+ nextAnswer(): Promise<void>;
124
+ /** Settles when the run state next changes. */
125
+ nextChange(): Promise<void>;
126
+ /** The questions in the list that are answered, each with its answer, in the order given. */
127
+ answersTo({ questionIds }: {
128
+ questionIds: string[];
129
+ }): Answer[];
130
+ /** The record of a call this process started, or read from the store for one an earlier run did. */
131
+ callFile({ callId }: {
132
+ callId: string;
133
+ }): Promise<CallFile>;
134
+ /** Saves a call's record as it now stands. */
135
+ saveCallFile(call: CallFile): Promise<void>;
136
+ /** Saves what the Runs table shows: a copy of what the events say. */
137
+ saveSummary({ input }?: {
138
+ input?: unknown;
139
+ }): Promise<void>;
140
+ /** The checkpoint of the run as it stands, for the phase that just finished. */
141
+ checkpointNow({ phase }: {
142
+ phase: string;
143
+ }): Checkpoint;
144
+ }
@@ -0,0 +1,278 @@
1
+ import { BlueprintMistake } from './blueprint-mistake.js';
2
+ import { applyEvent, progressFromEvents } from './record/apply-event.js';
3
+ import { progressDeltaFromSnapshots, progressSnapshot, } from './record/progress-projection.js';
4
+ import { summaryOfProgress } from './record/run-summary.js';
5
+ import { checkedChangeEntries, deepFreeze } from './record/state-changes.js';
6
+ /** One run while a process executes it: its store, its progress, and the rules every part of the
7
+ * run shares (events in order, one change at a time, questions, artifacts, Stop). */
8
+ export class RunSession {
9
+ runId;
10
+ store;
11
+ blueprint;
12
+ promptFiles;
13
+ infer;
14
+ services;
15
+ /** How long to wait before the second and third attempt of a call whose connection failed. */
16
+ retryWaitsMs;
17
+ progress;
18
+ start;
19
+ events;
20
+ onEvent;
21
+ stopController = new AbortController();
22
+ drainController = new AbortController();
23
+ callFiles = Object.create(null);
24
+ lastSnapshot;
25
+ appending = Promise.resolve();
26
+ notifying = Promise.resolve();
27
+ turn = Promise.resolve();
28
+ answerListeners = [];
29
+ changeListeners = [];
30
+ lastIdNumber;
31
+ constructor(options) {
32
+ this.runId = options.runId;
33
+ this.store = options.store;
34
+ this.blueprint = options.blueprint;
35
+ this.promptFiles = options.promptFiles;
36
+ this.infer = options.infer;
37
+ this.services = options.services;
38
+ this.retryWaitsMs = options.retryWaitsMs ?? [30_000, 60_000];
39
+ this.start = options.start;
40
+ this.events = [...options.events];
41
+ this.onEvent = options.onEvent;
42
+ this.progress = progressFromEvents({ start: options.start, events: this.events });
43
+ this.lastSnapshot = progressSnapshot({ progress: this.progress, blueprint: this.blueprint });
44
+ // One line can carry several ids, so the numbers run ahead of the lines: new ids start past
45
+ // every number already used.
46
+ const { calls, questionIds, assignmentIds, artifacts } = this.progress;
47
+ const usedIds = [
48
+ ...Object.keys(calls),
49
+ ...questionIds,
50
+ ...assignmentIds,
51
+ ...Object.values(artifacts).map((saved) => saved.id),
52
+ ];
53
+ this.lastIdNumber = Math.max(this.progress.seq, ...usedIds.map((id) => Number.parseInt(id.slice(1)) || 0));
54
+ }
55
+ get state() {
56
+ return this.progress.state;
57
+ }
58
+ get questionsAnsweredBy() {
59
+ return this.progress.questionsAnsweredBy ?? 'person';
60
+ }
61
+ /** The signal that Stop, or the run's first failure, triggers. */
62
+ get stopSignal() {
63
+ return this.stopController.signal;
64
+ }
65
+ /** The signal that a graceful drain triggers: in-flight calls finish, no new work starts. */
66
+ get drainSignal() {
67
+ return this.drainController.signal;
68
+ }
69
+ /** Current serializable progress snapshot for this run. */
70
+ currentProgressSnapshot() {
71
+ return this.lastSnapshot;
72
+ }
73
+ /** A new id for a call, an assignment, a question or an artifact's owner. No two are alike in
74
+ * one run, also when several are made in the same moment and after Resume. */
75
+ newId({ prefix }) {
76
+ this.lastIdNumber = Math.max(this.lastIdNumber, this.progress.seq) + 1;
77
+ return `${prefix}${this.lastIdNumber}`;
78
+ }
79
+ /** Ends the work in progress. With a `RunStopped` reason the run is left stopped; with any
80
+ * other error it is the run's first failure cancelling the rest. */
81
+ endWorkInProgress({ reason }) {
82
+ if (!this.stopController.signal.aborted)
83
+ this.stopController.abort(reason);
84
+ }
85
+ /** Stops starting new work while letting calls already in progress finish and save their
86
+ * outcomes before the run stops. */
87
+ drain({ reason }) {
88
+ if (!this.drainController.signal.aborted)
89
+ this.drainController.abort(reason);
90
+ }
91
+ /** Adds one event to the run's store and applies it to the run's progress. The progress is
92
+ * current as soon as this is called; the returned promise settles once persisted and after any
93
+ * async `onEvent` observer finishes in strict `seq` order. */
94
+ async record(happening) {
95
+ const event = {
96
+ seq: this.progress.seq + 1,
97
+ at: new Date().toISOString(),
98
+ ...happening,
99
+ };
100
+ const previousSnapshot = this.lastSnapshot;
101
+ applyEvent({ progress: this.progress, event });
102
+ this.events.push(event);
103
+ const nextSnapshot = progressSnapshot({ progress: this.progress, blueprint: this.blueprint });
104
+ const delta = progressDeltaFromSnapshots({
105
+ previous: previousSnapshot,
106
+ next: nextSnapshot,
107
+ event,
108
+ });
109
+ this.lastSnapshot = nextSnapshot;
110
+ if ('change' in happening && happening.change?.length)
111
+ for (const listener of this.changeListeners.splice(0))
112
+ listener();
113
+ const appended = this.appending.then(() => this.store.appendEvent({ runId: this.runId, event }));
114
+ this.appending = appended;
115
+ appended.catch(() => undefined);
116
+ await appended;
117
+ if (this.onEvent) {
118
+ const notify = this.notifying.then(() => this.onEvent(event, delta));
119
+ this.notifying = notify.catch(() => undefined);
120
+ await notify;
121
+ }
122
+ return event;
123
+ }
124
+ /** Runs work that reads the state and may change it, one piece at a time across the whole run,
125
+ * each to its end. A reply is therefore always judged against the latest state. */
126
+ inTurn(work) {
127
+ const result = this.turn.then(work);
128
+ this.turn = result.catch(() => undefined);
129
+ return result;
130
+ }
131
+ /** The run state as it stood after an events line. */
132
+ stateAt({ seq }) {
133
+ const then = progressFromEvents({ start: this.start, events: this.events, upToSeq: seq });
134
+ // After Resume the schema may hold defaults an earlier state was saved without.
135
+ const fitted = this.blueprint.runStateSchema.safeParse(then.state);
136
+ return (fitted.success ? deepFreeze(fitted.data) : then.state);
137
+ }
138
+ /** Works out a change against the state as it stands, checks it, and writes the artifacts'
139
+ * bytes. Returns what the events line that makes them count must carry. Call it inside
140
+ * `inTurn`, and record that line before the turn ends. */
141
+ async writeArtifactsAndCheckChange({ change, artifacts, madeBy, }) {
142
+ const writes = {};
143
+ if (change) {
144
+ const entries = checkedChangeEntries({
145
+ state: this.state,
146
+ change,
147
+ schema: this.blueprint.runStateSchema,
148
+ madeBy,
149
+ });
150
+ if (entries.length)
151
+ writes.change = entries;
152
+ }
153
+ if (artifacts?.length) {
154
+ const ownerId = this.newId({ prefix: 'w' });
155
+ writes.artifacts = [];
156
+ for (const [index, artifact] of artifacts.entries())
157
+ writes.artifacts.push(await this.store.writeArtifact({
158
+ runId: this.runId,
159
+ id: `${ownerId}-${index + 1}`,
160
+ artifact,
161
+ }));
162
+ }
163
+ return writes;
164
+ }
165
+ artifacts = {
166
+ read: async ({ name }) => {
167
+ const saved = this.progress.artifacts[name];
168
+ if (!saved)
169
+ throw new Error(`The run has no artifact named ${name}.`);
170
+ return this.store.readArtifact({ runId: saved.sourceRunId ?? this.runId, saved });
171
+ },
172
+ };
173
+ /** Gives new questions their ids. The events line that asks them carries the result. */
174
+ newQuestions({ questions, askedBy, }) {
175
+ if (!questions.length)
176
+ throw new BlueprintMistake(`${askedBy} asked the person with no questions.`);
177
+ return questions.map((question) => ({ id: this.newId({ prefix: 'q' }), question }));
178
+ }
179
+ /** In a run answered by the recommendation, answers at once each of these questions that has
180
+ * one. Returns whether all of them are now answered. */
181
+ async answerByRecommendation({ questions }) {
182
+ if (this.questionsAnsweredBy !== 'recommendation')
183
+ return false;
184
+ for (const saved of questions)
185
+ if (saved.question.recommended && this.progress.questions[saved.id]?.answer === undefined)
186
+ await this.recordAnswer({
187
+ questionId: saved.id,
188
+ answer: saved.question.recommended.choice,
189
+ answeredBy: 'run',
190
+ });
191
+ return questions.every((saved) => this.progress.questions[saved.id]?.answer !== undefined);
192
+ }
193
+ /** Why an answer cannot be recorded; undefined when it can. */
194
+ answerProblem({ questionId }) {
195
+ const question = this.progress.questions[questionId];
196
+ if (!question)
197
+ return `The run has no question ${questionId}.`;
198
+ if (question.answer !== undefined)
199
+ return `Question ${questionId} is already answered.`;
200
+ return undefined;
201
+ }
202
+ /** Records the answer to a waiting question. Only the process executing the run calls it. */
203
+ async recordAnswer({ questionId, answer, answeredBy, }) {
204
+ const problem = this.answerProblem({ questionId });
205
+ if (problem)
206
+ throw new Error(problem);
207
+ await this.record({ kind: 'question-answered', questionId, answer, answeredBy });
208
+ for (const listener of this.answerListeners.splice(0))
209
+ listener();
210
+ }
211
+ /** Settles when the next answer is recorded. */
212
+ nextAnswer() {
213
+ return new Promise((resolve) => this.answerListeners.push(resolve));
214
+ }
215
+ /** Settles when the run state next changes. */
216
+ nextChange() {
217
+ return new Promise((resolve) => this.changeListeners.push(resolve));
218
+ }
219
+ /** The questions in the list that are answered, each with its answer, in the order given. */
220
+ answersTo({ questionIds }) {
221
+ return questionIds
222
+ .map((id) => this.progress.questions[id])
223
+ .filter((question) => question.answer !== undefined)
224
+ .map((question) => ({ question: question.question, answer: question.answer }));
225
+ }
226
+ /** The record of a call this process started, or read from the store for one an earlier run did. */
227
+ async callFile({ callId }) {
228
+ if (!this.callFiles[callId]) {
229
+ const loaded = await this.store.readCall({ runId: this.runId, callId });
230
+ if (!loaded)
231
+ throw new Error(`Call ${callId} was not found in run ${this.runId}.`);
232
+ this.callFiles[callId] = loaded;
233
+ }
234
+ return this.callFiles[callId];
235
+ }
236
+ /** Saves a call's record as it now stands. */
237
+ async saveCallFile(call) {
238
+ this.callFiles[call.callId] = call;
239
+ await this.store.writeCall({ runId: this.runId, call });
240
+ }
241
+ /** Saves what the Runs table shows: a copy of what the events say. */
242
+ async saveSummary({ input } = {}) {
243
+ await this.store.writeRunSummary({
244
+ runId: this.runId,
245
+ summary: summaryOfProgress({
246
+ runId: this.runId,
247
+ blueprintName: this.blueprint.name,
248
+ progress: this.progress,
249
+ }),
250
+ ...(input !== undefined ? { input } : {}),
251
+ });
252
+ }
253
+ /** The checkpoint of the run as it stands, for the phase that just finished. */
254
+ checkpointNow({ phase }) {
255
+ const { progress } = this;
256
+ return {
257
+ number: progress.checkpointsSaved + 1,
258
+ phase,
259
+ state: progress.state,
260
+ artifacts: Object.fromEntries(Object.entries(progress.artifacts).map(([name, saved]) => [
261
+ name,
262
+ // A run started from this checkpoint reads the artifacts from their originating run.
263
+ { ...saved, sourceRunId: saved.sourceRunId ?? this.runId },
264
+ ])),
265
+ sideLineVisits: progress.sideLineVisits,
266
+ ...(progress.openVisit
267
+ ? {
268
+ openVisit: {
269
+ sideLine: progress.openVisit.sideLine,
270
+ visit: progress.openVisit.visit,
271
+ during: progress.openVisit.during,
272
+ },
273
+ }
274
+ : {}),
275
+ finishedAssignments: progress.finishedAssignments,
276
+ };
277
+ }
278
+ }
@@ -0,0 +1,19 @@
1
+ import type { QueuedCall, WorkerFailure, WorkerReply } from '../inference/call-queue-shapes.js';
2
+ /**
3
+ * Answers one queued call with Codex or Claude Code on this computer, in a temporary folder that is deleted
4
+ * afterwards. The call's pictures go to the program with the prompt, and the model's tool calls are forwarded
5
+ * through `callTool`.
6
+ */
7
+ export declare function answerQueuedCall({ call, callTool, signal, }: {
8
+ call: QueuedCall;
9
+ /** Forwards one tool call to the run, which answers it. */
10
+ callTool: (toolCall: {
11
+ name: string;
12
+ args: unknown;
13
+ }) => Promise<unknown>;
14
+ signal: AbortSignal;
15
+ }): Promise<{
16
+ reply: WorkerReply;
17
+ } | {
18
+ failure: WorkerFailure;
19
+ }>;