@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,243 @@
1
+ import { BlueprintMistake, blueprintCode } from '../blueprint-mistake.js';
2
+ import { allAnswered, assignmentIdentity, partsOfAssignmentIdentity, } from '../record/progress.js';
3
+ import { RunFailed, RunWaitsForPerson } from '../run-endings.js';
4
+ import { runAssignment } from './assignment.js';
5
+ /** The subject key of a lane that runs once. */
6
+ const ONCE_KEY = 'once';
7
+ /** Runs an agent phase at one place: creates each lane's assignments, starts each when it may and
8
+ * its lane has a free slot, and goes on until every one has finished. Lanes run interleaved. After
9
+ * Resume it continues the place's saved assignments. */
10
+ export async function runAgentPhase({ session, phase, place, whenNothingCanRun, }) {
11
+ const running = Object.create(null);
12
+ const memories = Object.create(null);
13
+ /** The subjects each lane returned last, by key, and their keys in the order returned. */
14
+ const latestSubjects = Object.create(null);
15
+ /** How many of the phase's assignments had finished when the lanes' subjects were last read. */
16
+ let finishedWhenSubjectsWereRead = -1;
17
+ let failure;
18
+ const laneNamed = (name) => phase.lanes.find((lane) => lane.name === name);
19
+ const reads = () => ({ state: session.state, questionsAnsweredBy: session.questionsAnsweredBy });
20
+ const mustNotGoOn = () => !!failure || session.stopSignal.aborted || session.drainSignal.aborted;
21
+ const ofThisPhase = () => session.progress.assignmentIds
22
+ .map((id) => session.progress.assignments[id])
23
+ .filter((assignment) => assignment.phase === place);
24
+ /** What has finished at this place, also in the run this one started from. */
25
+ const finished = () => session.progress.finishedAssignments[place] ?? {};
26
+ const finishedCount = () => ofThisPhase().filter((assignment) => assignment.status === 'finished').length;
27
+ /** A finished assignment may have changed what the lanes' subjects are, so they are read again
28
+ * before anything else starts. */
29
+ const subjectsAreCurrent = () => finishedWhenSubjectsWereRead === finishedCount();
30
+ /** Creates the assignments one lane now calls for and drops unstarted ones it no longer does. */
31
+ const syncLane = async (lane) => {
32
+ const { assignments } = lane;
33
+ const existing = ofThisPhase().filter((assignment) => assignment.lane === lane.name);
34
+ const add = ({ key, label, repeat }) => session.record({
35
+ kind: 'assignment-added',
36
+ assignmentId: session.newId({ prefix: 'a' }),
37
+ phase: place,
38
+ lane: lane.name,
39
+ key,
40
+ label,
41
+ repeat,
42
+ });
43
+ if (assignments === 'once') {
44
+ const wanted = !lane.onlyWhen ||
45
+ blueprintCode({
46
+ what: `${lane.name}'s onlyWhen`,
47
+ run: () => lane.onlyWhen.test(reads()),
48
+ });
49
+ const identity = assignmentIdentity({ lane: lane.name, key: ONCE_KEY, repeat: 1 });
50
+ // Work that runs once is decided when its phase starts, not again after Resume, and not
51
+ // again in a run started from a checkpoint taken after it finished.
52
+ if (!existing.length && wanted && !finished()[identity])
53
+ await add({ key: ONCE_KEY, label: lane.name, repeat: 1 });
54
+ return;
55
+ }
56
+ const entries = blueprintCode({
57
+ what: `${lane.name}'s subjects`,
58
+ run: () => assignments.forEach.subjects(reads()),
59
+ });
60
+ const byKey = Object.create(null);
61
+ for (const entry of entries) {
62
+ if (Object.hasOwn(byKey, entry.key))
63
+ throw new BlueprintMistake(`${lane.name} returned the subject key ${entry.key} twice.`);
64
+ byKey[entry.key] = entry;
65
+ }
66
+ latestSubjects[lane.name] = { byKey, keysInOrder: entries.map((entry) => entry.key) };
67
+ for (const entry of entries)
68
+ for (let repeat = 1; repeat <= (assignments.repeats ?? 1); repeat++) {
69
+ const alreadyHere = existing.some((assignment) => assignment.key === entry.key &&
70
+ assignment.repeat === repeat &&
71
+ assignment.status !== 'dropped');
72
+ const identity = assignmentIdentity({ lane: lane.name, key: entry.key, repeat });
73
+ if (!alreadyHere && !finished()[identity])
74
+ await add({ key: entry.key, label: entry.label, repeat });
75
+ }
76
+ for (const assignment of existing)
77
+ if (assignment.status === 'waiting-to-start' && !Object.hasOwn(byKey, assignment.key))
78
+ await session.record({ kind: 'assignment-dropped', assignmentId: assignment.id });
79
+ };
80
+ /** The keys of a lane whose assignments have all finished. */
81
+ const finishedKeys = (lane) => {
82
+ const repeats = lane.assignments === 'once' ? 1 : (lane.assignments.repeats ?? 1);
83
+ const keys = [];
84
+ for (const identity of Object.keys(finished())) {
85
+ const { lane: itsLane, key } = partsOfAssignmentIdentity(identity);
86
+ if (itsLane !== lane.name || keys.includes(key))
87
+ continue;
88
+ const everyRepeat = Array.from({ length: repeats }, (_, index) => assignmentIdentity({ lane: lane.name, key, repeat: index + 1 }));
89
+ if (everyRepeat.every((each) => finished()[each]))
90
+ keys.push(key);
91
+ }
92
+ return keys;
93
+ };
94
+ const run = (assignment) => {
95
+ running[assignment.id] = runAssignment({
96
+ session,
97
+ phase,
98
+ lane: laneNamed(assignment.lane),
99
+ assignment,
100
+ memories,
101
+ })
102
+ .then(() => undefined)
103
+ .catch((error) => {
104
+ failure ??= error;
105
+ session.endWorkInProgress({
106
+ reason: error instanceof Error ? error : new Error(String(error)),
107
+ });
108
+ })
109
+ .then(() => {
110
+ delete running[assignment.id];
111
+ });
112
+ };
113
+ const hasFreeSlot = (lane) => {
114
+ const limit = lane.assignments === 'once' ? 1 : lane.assignments.concurrency;
115
+ const inLane = Object.keys(running).filter((id) => session.progress.assignments[id].lane === lane.name);
116
+ return inLane.length < limit;
117
+ };
118
+ /** Continues work a stop or an answered question interrupted, records each waiting assignment
119
+ * whose start condition now holds, then starts those in the order their lane lists them while
120
+ * the lane has a free slot. It returns early whenever the subjects have to be read again. */
121
+ const startWhatMayStart = async () => {
122
+ if (mustNotGoOn())
123
+ return;
124
+ const notRunning = () => ofThisPhase().filter((assignment) => !Object.hasOwn(running, assignment.id));
125
+ for (const assignment of notRunning()) {
126
+ if (mustNotGoOn())
127
+ return;
128
+ const interrupted = assignment.status === 'running' || assignment.status === 'waiting-for-person';
129
+ const answered = !assignment.pendingAsk ||
130
+ allAnswered({ progress: session.progress, questionIds: assignment.pendingAsk.questionIds });
131
+ if (interrupted && answered && hasFreeSlot(laneNamed(assignment.lane)))
132
+ run(assignment);
133
+ }
134
+ const waiting = () => notRunning()
135
+ .filter((assignment) => assignment.status === 'waiting-to-start')
136
+ .map((assignment) => {
137
+ const lane = laneNamed(assignment.lane);
138
+ const latest = latestSubjects[lane.name];
139
+ return {
140
+ assignment,
141
+ lane,
142
+ subject: latest?.byKey[assignment.key]?.subject,
143
+ place: latest?.keysInOrder.indexOf(assignment.key) ?? 0,
144
+ };
145
+ });
146
+ for (const { assignment, lane, subject } of waiting()) {
147
+ if (mustNotGoOn() || !subjectsAreCurrent())
148
+ return;
149
+ if (assignment.mayStart)
150
+ continue;
151
+ const may = lane.assignments === 'once' ||
152
+ !lane.assignments.startsWhen ||
153
+ blueprintCode({
154
+ what: `${lane.name}'s startsWhen`,
155
+ run: () => lane.assignments.startsWhen.test({
156
+ ...reads(),
157
+ subject: subject,
158
+ finishedKeys: finishedKeys(lane),
159
+ }),
160
+ });
161
+ if (may)
162
+ await session.record({ kind: 'assignment-may-start', assignmentId: assignment.id });
163
+ }
164
+ const inLaneOrder = waiting().sort((one, other) => one.place - other.place);
165
+ for (const { assignment, lane, subject } of inLaneOrder) {
166
+ if (mustNotGoOn() || !subjectsAreCurrent())
167
+ return;
168
+ if (!assignment.mayStart || !hasFreeSlot(lane))
169
+ continue;
170
+ for (const agent of lane.chain) {
171
+ const parsed = agent.subject?.safeParse(subject);
172
+ if (parsed && !parsed.success)
173
+ throw new BlueprintMistake(`${lane.name} gave ${agent.name} a subject of another shape (${assignment.label}): ${parsed.error.issues
174
+ .map((issue) => `${issue.path.join('.') || 'subject'}: ${issue.message}`)
175
+ .join('; ')}`);
176
+ }
177
+ await session.record({
178
+ kind: 'assignment-started',
179
+ assignmentId: assignment.id,
180
+ subject: subject ?? null,
181
+ agents: lane.chain.map((agent) => agent.name),
182
+ });
183
+ run(assignment);
184
+ }
185
+ };
186
+ const draining = session.drainSignal.aborted
187
+ ? Promise.resolve()
188
+ : new Promise((resolve) => session.drainSignal.addEventListener('abort', () => resolve(), { once: true }));
189
+ while (!mustNotGoOn())
190
+ try {
191
+ if (!subjectsAreCurrent()) {
192
+ finishedWhenSubjectsWereRead = finishedCount();
193
+ // Work that has not started in a lane the phase no longer declares is dropped.
194
+ for (const assignment of ofThisPhase())
195
+ if (assignment.status === 'waiting-to-start' &&
196
+ !phase.lanes.some((lane) => lane.name === assignment.lane))
197
+ await session.record({ kind: 'assignment-dropped', assignmentId: assignment.id });
198
+ for (const lane of phase.lanes)
199
+ await syncLane(lane);
200
+ // An assignment that finished while the subjects were read has them read again.
201
+ continue;
202
+ }
203
+ // Taken before the pass, so an answer or a change recorded during it still wakes the wait
204
+ // below: a wait may read the state, which changes in the middle of another's chain.
205
+ const answered = session.nextAnswer();
206
+ const changed = session.nextChange();
207
+ await startWhatMayStart();
208
+ if (mustNotGoOn() || !subjectsAreCurrent())
209
+ continue;
210
+ const inProgress = Object.values(running);
211
+ if (inProgress.length) {
212
+ await Promise.race([...inProgress, answered, changed, draining]);
213
+ continue;
214
+ }
215
+ const unfinished = ofThisPhase().filter((assignment) => assignment.status !== 'finished' && assignment.status !== 'dropped');
216
+ if (unfinished.some((assignment) => assignment.status === 'waiting-for-person'))
217
+ throw new RunWaitsForPerson();
218
+ if (await whenNothingCanRun?.()) {
219
+ finishedWhenSubjectsWereRead = -1;
220
+ continue;
221
+ }
222
+ if (!unfinished.length)
223
+ break;
224
+ throw new RunFailed({
225
+ message: `${phase.name} has assignments that may never start: ${unfinished
226
+ .map((assignment) => assignment.label)
227
+ .join(', ')}.`,
228
+ });
229
+ }
230
+ catch (error) {
231
+ failure ??= error;
232
+ // Whatever is still running ends before the run's own last line is written.
233
+ if (!(error instanceof RunWaitsForPerson))
234
+ session.endWorkInProgress({
235
+ reason: error instanceof Error ? error : new Error(String(error)),
236
+ });
237
+ }
238
+ await Promise.all(Object.values(running));
239
+ if (failure)
240
+ throw failure;
241
+ session.stopSignal.throwIfAborted();
242
+ session.drainSignal.throwIfAborted();
243
+ }
@@ -0,0 +1,42 @@
1
+ import type { FromReads } from '../../blueprint/agent.js';
2
+ import type { AssignmentProgress } from '../record/progress.js';
3
+ import type { RunSession } from '../run-session.js';
4
+ /** What an unfinished assignment keeps in memory beyond its saved progress: the values its
5
+ * agents' functions are handed. */
6
+ export type AssignmentMemory<State> = {
7
+ /** Each earlier agent's accepted reply with the state before its first change and after its last. */
8
+ accepted: {
9
+ [agent: string]: {
10
+ reply: unknown;
11
+ stateBefore: State;
12
+ stateAfter: State;
13
+ };
14
+ };
15
+ /** The reply last sent back to the current agent, as the model wrote it. */
16
+ rejectedReplyText?: string;
17
+ /** A reply whose outcome asked the person; it is judged again once the answers are in. */
18
+ replyAwaitingAnswers?: {
19
+ callId: string;
20
+ reply: unknown;
21
+ stateAtPrompt: State;
22
+ };
23
+ /** The state before the current agent's first change. */
24
+ stateBeforeFirstChange?: State;
25
+ };
26
+ /** Rebuilds what an assignment that an earlier process left unfinished keeps in memory, from the
27
+ * call files and the events. Replies are read again by their agents' readers. */
28
+ export declare function rebuiltAssignmentMemory<State>({ session, assignment, readReply, }: {
29
+ session: RunSession<State>;
30
+ assignment: AssignmentProgress;
31
+ /** Reads an agent's saved reply text with that agent's reader. */
32
+ readReply: (reads: {
33
+ agent: string;
34
+ replyText: string;
35
+ }) => unknown;
36
+ }): Promise<AssignmentMemory<State>>;
37
+ /** What an agent's `from`, `attachedImages` and tools read about its assignment. */
38
+ export declare function assignmentReads<State>({ session, assignment, memory, }: {
39
+ session: RunSession<State>;
40
+ assignment: AssignmentProgress;
41
+ memory: AssignmentMemory<State>;
42
+ }): FromReads<State, never>;
@@ -0,0 +1,52 @@
1
+ import { BlueprintMistake } from '../blueprint-mistake.js';
2
+ /** Rebuilds what an assignment that an earlier process left unfinished keeps in memory, from the
3
+ * call files and the events. Replies are read again by their agents' readers. */
4
+ export async function rebuiltAssignmentMemory({ session, assignment, readReply, }) {
5
+ const memory = { accepted: Object.create(null) };
6
+ for (const place of assignment.finishedPlaces) {
7
+ if (place.callFailed)
8
+ continue;
9
+ const { replyText = '' } = await session.callFile({ callId: place.callId });
10
+ memory.accepted[place.agent] = {
11
+ reply: readReply({ agent: place.agent, replyText }),
12
+ stateBefore: session.stateAt({ seq: place.stateBeforeSeq }),
13
+ stateAfter: session.stateAt({ seq: place.stateAfterSeq }),
14
+ };
15
+ }
16
+ if (assignment.lastCorrection) {
17
+ const rejected = await session.callFile({ callId: assignment.lastCorrection.callId });
18
+ memory.rejectedReplyText = rejected.replyText;
19
+ }
20
+ if (assignment.firstChangeSeq !== undefined)
21
+ memory.stateBeforeFirstChange = session.stateAt({ seq: assignment.firstChangeSeq });
22
+ if (assignment.pendingAsk?.by === 'outcome') {
23
+ const { callId } = assignment.pendingAsk;
24
+ const { replyText = '', agent } = await session.callFile({ callId });
25
+ memory.replyAwaitingAnswers = {
26
+ callId,
27
+ reply: readReply({ agent, replyText }),
28
+ stateAtPrompt: session.stateAt({ seq: session.progress.calls[callId].stateSeq }),
29
+ };
30
+ }
31
+ return memory;
32
+ }
33
+ /** What an agent's `from`, `attachedImages` and tools read about its assignment. */
34
+ export function assignmentReads({ session, assignment, memory, }) {
35
+ const earlier = ({ agent }) => {
36
+ const accepted = memory.accepted[agent.name];
37
+ if (!accepted)
38
+ throw new BlueprintMistake(`${agent.name} has no accepted reply earlier in this assignment's chain.`);
39
+ return accepted;
40
+ };
41
+ return {
42
+ state: session.state,
43
+ questionsAnsweredBy: session.questionsAnsweredBy,
44
+ subject: assignment.subject,
45
+ repeat: assignment.repeat,
46
+ earlier,
47
+ correction: assignment.lastCorrection && memory.rejectedReplyText !== undefined
48
+ ? { rejectedReply: memory.rejectedReplyText, text: assignment.lastCorrection.text }
49
+ : undefined,
50
+ answers: session.answersTo({ questionIds: assignment.questionIds }),
51
+ };
52
+ }
@@ -0,0 +1,17 @@
1
+ import type { AgentPhase, Lane } from '../../blueprint/phase.js';
2
+ import { type AssignmentProgress } from '../record/progress.js';
3
+ import type { RunSession } from '../run-session.js';
4
+ import { type AssignmentMemory } from './assignment-memory.js';
5
+ /** Runs one assignment's chain from where it stands: each agent in turn until its reply is
6
+ * accepted. Returns `waiting` when it must wait for the person; it is run again once the
7
+ * answers are in. */
8
+ export declare function runAssignment<State>({ session, phase, lane, assignment, memories, }: {
9
+ session: RunSession<State>;
10
+ phase: AgentPhase<State>;
11
+ lane: Lane<State>;
12
+ assignment: AssignmentProgress;
13
+ /** What each unfinished assignment of the phase keeps in memory, by assignment id. */
14
+ memories: {
15
+ [assignmentId: string]: AssignmentMemory<State>;
16
+ };
17
+ }): Promise<'finished' | 'waiting' | 'draining'>;
@@ -0,0 +1,252 @@
1
+ import { isSentBack } from '../../blueprint/outcomes.js';
2
+ import { writeScopeViolations } from '../../blueprint/write-scope.js';
3
+ import { BlueprintMistake, blueprintCode } from '../blueprint-mistake.js';
4
+ import { allAnswered } from '../record/progress.js';
5
+ import { fittedNextState } from '../record/state-changes.js';
6
+ import { RunFailed } from '../run-endings.js';
7
+ import { callAgent } from './agent-call.js';
8
+ import { assignmentReads, rebuiltAssignmentMemory, } from './assignment-memory.js';
9
+ /** Runs one assignment's chain from where it stands: each agent in turn until its reply is
10
+ * accepted. Returns `waiting` when it must wait for the person; it is run again once the
11
+ * answers are in. */
12
+ export async function runAssignment({ session, phase, lane, assignment, memories, }) {
13
+ const chain = lane.chain;
14
+ memories[assignment.id] ??= await rebuiltAssignmentMemory({
15
+ session,
16
+ assignment,
17
+ readReply: ({ agent, replyText }) => chain.find((candidate) => candidate.name === agent).replyReader.read({ replyText }),
18
+ });
19
+ const memory = memories[assignment.id];
20
+ const waitsForAnswers = () => !!assignment.pendingAsk &&
21
+ !allAnswered({ progress: session.progress, questionIds: assignment.pendingAsk.questionIds });
22
+ while (assignment.placeInChain < chain.length) {
23
+ const step = { session, assignment, agent: chain[assignment.placeInChain], memory };
24
+ const { agent } = step;
25
+ if (waitsForAnswers())
26
+ return 'waiting';
27
+ session.stopSignal.throwIfAborted();
28
+ if (session.drainSignal.aborted)
29
+ return 'draining';
30
+ // A reply whose outcome asked is judged again with the answers; no call is made.
31
+ let read = assignment.pendingAsk?.by === 'outcome' ? memory.replyAwaitingAnswers : undefined;
32
+ if (!read) {
33
+ const call = await callAgent({ session, phase, assignment, agent, memory });
34
+ if (call.ended === 'draining')
35
+ return 'draining';
36
+ if (call.ended === 'asked')
37
+ return 'waiting';
38
+ if (call.ended === 'failed') {
39
+ await acceptFailedCall({ ...step, callId: call.callId, failure: call.failure });
40
+ continue;
41
+ }
42
+ const reply = blueprintCode({
43
+ what: `${agent.name}'s reply reader`,
44
+ run: () => agent.replyReader.read({ replyText: call.replyText }),
45
+ });
46
+ if (isSentBack(reply)) {
47
+ await sendReplyBack({ ...step, callId: call.callId, correction: reply.correction });
48
+ continue;
49
+ }
50
+ read = { callId: call.callId, reply, stateAtPrompt: call.stateAtPrompt };
51
+ }
52
+ await judgeReply({ ...step, read });
53
+ }
54
+ await session.record({ kind: 'assignment-finished', assignmentId: assignment.id });
55
+ delete memories[assignment.id];
56
+ return 'finished';
57
+ }
58
+ /** Sends a reply back to its agent with a correction. The reply after the agent's last allowed
59
+ * correction fails the assignment and the run. */
60
+ async function sendReplyBack({ session, assignment, agent, memory, callId, correction, replyParsed, failedChecks, }) {
61
+ const callFile = await session.callFile({ callId });
62
+ const usedUp = assignment.correctionsInARow >= agent.maxCorrections;
63
+ callFile.correction = correction;
64
+ if (replyParsed !== undefined)
65
+ callFile.replyParsed = replyParsed;
66
+ memory.rejectedReplyText = callFile.replyText;
67
+ delete memory.replyAwaitingAnswers;
68
+ await session.saveCallFile(callFile);
69
+ await session.record({
70
+ kind: 'reply-judged',
71
+ callId,
72
+ assignmentId: assignment.id,
73
+ outcome: 'sent-back',
74
+ correction,
75
+ ...(failedChecks?.length ? { failedChecks } : {}),
76
+ });
77
+ if (usedUp)
78
+ throw new RunFailed({
79
+ message: `${agent.name} used up its ${agent.maxCorrections} corrections for ${assignment.label}.`,
80
+ assignmentId: assignment.id,
81
+ });
82
+ }
83
+ /** Has the agent's checks and outcome decide about a reply, against the state as it stands, and
84
+ * saves what it decides. Outcomes run one at a time across the whole run. */
85
+ function judgeReply({ session, assignment, agent, memory, read, }) {
86
+ return session.inTurn(async () => {
87
+ const before = session.state;
88
+ const { subject, repeat, earlier, answers, questionsAnsweredBy } = assignmentReads({
89
+ session,
90
+ assignment,
91
+ memory,
92
+ });
93
+ const decideReads = {
94
+ reply: read.reply,
95
+ state: before,
96
+ stateAtPrompt: read.stateAtPrompt,
97
+ questionsAnsweredBy,
98
+ subject,
99
+ repeat,
100
+ earlier,
101
+ answers,
102
+ correctionsLeft: agent.maxCorrections - assignment.correctionsInARow,
103
+ };
104
+ if (agent.checks.length) {
105
+ const failed = [];
106
+ for (const rule of agent.checks) {
107
+ const messages = blueprintCode({
108
+ what: `${agent.name}'s check ${rule.name}`,
109
+ run: () => rule.check(decideReads),
110
+ });
111
+ if (messages.length)
112
+ failed.push({ name: rule.name, messages });
113
+ }
114
+ if (failed.length) {
115
+ await sendReplyBack({
116
+ session,
117
+ assignment,
118
+ agent,
119
+ memory,
120
+ callId: read.callId,
121
+ correction: failed
122
+ .flatMap(({ name, messages }) => messages.map((message) => `[${name}] ${message}`))
123
+ .join('\n'),
124
+ replyParsed: read.reply,
125
+ failedChecks: failed.map(({ name }) => name),
126
+ });
127
+ return;
128
+ }
129
+ }
130
+ const outcome = blueprintCode({
131
+ what: `${agent.name}'s outcome`,
132
+ run: () => agent.replyOutcome.decide(decideReads),
133
+ });
134
+ if (outcome.outcome === 'sentBack') {
135
+ await sendReplyBack({
136
+ session,
137
+ assignment,
138
+ agent,
139
+ memory,
140
+ callId: read.callId,
141
+ correction: outcome.correction,
142
+ replyParsed: read.reply,
143
+ });
144
+ return;
145
+ }
146
+ if (outcome.outcome === 'asked' && !agent.asks)
147
+ throw new BlueprintMistake(`${agent.name}'s outcome asked the person and the agent declares no asks.`);
148
+ if (outcome.change && agent.mayChange.length) {
149
+ const after = fittedNextState({
150
+ state: before,
151
+ change: outcome.change,
152
+ schema: session.blueprint.runStateSchema,
153
+ madeBy: `${agent.name}'s outcome`,
154
+ });
155
+ const violations = blueprintCode({
156
+ what: `${agent.name}'s write scope`,
157
+ run: () => writeScopeViolations({
158
+ before,
159
+ after,
160
+ rules: agent.mayChange,
161
+ state: before,
162
+ subject,
163
+ }),
164
+ });
165
+ if (violations.length) {
166
+ await sendReplyBack({
167
+ session,
168
+ assignment,
169
+ agent,
170
+ memory,
171
+ callId: read.callId,
172
+ correction: violations.join('\n'),
173
+ replyParsed: read.reply,
174
+ failedChecks: ['may-change'],
175
+ });
176
+ return;
177
+ }
178
+ }
179
+ const writes = await session.writeArtifactsAndCheckChange({
180
+ change: outcome.change,
181
+ artifacts: outcome.artifacts,
182
+ madeBy: `${agent.name}'s outcome`,
183
+ });
184
+ if (writes.change)
185
+ memory.stateBeforeFirstChange ??= before;
186
+ const callFile = await session.callFile({ callId: read.callId });
187
+ callFile.replyParsed = read.reply;
188
+ await session.saveCallFile(callFile);
189
+ if (outcome.outcome === 'asked') {
190
+ const questions = session.newQuestions({
191
+ questions: outcome.questions,
192
+ askedBy: `${agent.name}'s outcome`,
193
+ });
194
+ memory.replyAwaitingAnswers = read;
195
+ await session.record({
196
+ kind: 'reply-judged',
197
+ callId: read.callId,
198
+ assignmentId: assignment.id,
199
+ outcome: 'asked',
200
+ ...writes,
201
+ questions,
202
+ });
203
+ await session.answerByRecommendation({ questions });
204
+ return;
205
+ }
206
+ await session.record({
207
+ kind: 'reply-judged',
208
+ callId: read.callId,
209
+ assignmentId: assignment.id,
210
+ outcome: 'accepted',
211
+ ...writes,
212
+ });
213
+ memory.accepted[agent.name] = {
214
+ reply: read.reply,
215
+ stateBefore: memory.stateBeforeFirstChange ?? before,
216
+ stateAfter: session.state,
217
+ };
218
+ delete memory.stateBeforeFirstChange;
219
+ delete memory.replyAwaitingAnswers;
220
+ delete memory.rejectedReplyText;
221
+ });
222
+ }
223
+ /** For an agent whose failed call must not fail the run: saves what its `whenCallFails` decides
224
+ * in place of a reply, and the assignment goes on to its next agent. */
225
+ function acceptFailedCall({ session, assignment, agent, memory, callId, failure, }) {
226
+ return session.inTurn(async () => {
227
+ const { subject, repeat } = assignmentReads({ session, assignment, memory });
228
+ const accepted = blueprintCode({
229
+ what: `${agent.name}'s whenCallFails`,
230
+ run: () => agent.whenCallFails.decide({
231
+ failure,
232
+ state: session.state,
233
+ questionsAnsweredBy: session.questionsAnsweredBy,
234
+ subject,
235
+ repeat,
236
+ }),
237
+ });
238
+ const writes = await session.writeArtifactsAndCheckChange({
239
+ change: accepted.change,
240
+ artifacts: accepted.artifacts,
241
+ madeBy: `${agent.name}'s whenCallFails`,
242
+ });
243
+ await session.record({
244
+ kind: 'failed-call-accepted',
245
+ callId,
246
+ assignmentId: assignment.id,
247
+ ...writes,
248
+ });
249
+ delete memory.stateBeforeFirstChange;
250
+ delete memory.rejectedReplyText;
251
+ });
252
+ }
@@ -0,0 +1,39 @@
1
+ import type { BlueprintWorkers, CallsAnsweredBy, ModelSettings } from '../../blueprint/run-settings.js';
2
+ import type { ModelOverride } from '../record/events.js';
3
+ /** Resolves the worker type name and optional definition for one agent in one phase. */
4
+ export declare function resolvedWorkerFor({ workers, phase, agent, }: {
5
+ workers?: BlueprintWorkers;
6
+ phase: {
7
+ worker?: string;
8
+ };
9
+ agent: {
10
+ worker?: string;
11
+ };
12
+ }): {
13
+ worker: string;
14
+ definition: import("../../blueprint/run-settings.js").WorkerDefinition | undefined;
15
+ };
16
+ /** The model settings one agent's calls use in a run: the agent's value wins over the phase's,
17
+ * the phase's over the worker type's, and the worker type's over the blueprint's; the run's
18
+ * overrides win over all, the most specific last. */
19
+ export declare function modelSettingsFor({ blueprint, workers, phase, agent, overrides, }: {
20
+ blueprint: ModelSettings;
21
+ workers?: BlueprintWorkers;
22
+ phase: {
23
+ name: string;
24
+ worker?: string;
25
+ modelSettings?: ModelSettings;
26
+ };
27
+ agent: {
28
+ name: string;
29
+ worker?: string;
30
+ modelSettings: ModelSettings;
31
+ };
32
+ overrides: ModelOverride[];
33
+ }): ModelSettings;
34
+ /** Why a run answered this way cannot use these settings; undefined when it can. A scripted run
35
+ * needs no model or effort. */
36
+ export declare function modelSettingsProblem({ settings, callsAnsweredBy, }: {
37
+ settings: ModelSettings;
38
+ callsAnsweredBy: CallsAnsweredBy;
39
+ }): string | undefined;