@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,213 @@
1
+ import { declaredPhases } from './places.js';
2
+ import { describeWriteScopeRule } from './write-scope.js';
3
+ /** Every agent a blueprint's lanes name, each once, in order of first use. */
4
+ export function blueprintAgents({ blueprint }) {
5
+ const agents = [];
6
+ for (const phase of declaredPhases({ blueprint }))
7
+ if (phase.kind === 'agents')
8
+ for (const lane of phase.lanes)
9
+ for (const agent of lane.chain)
10
+ if (!agents.includes(agent))
11
+ agents.push(agent);
12
+ return agents;
13
+ }
14
+ /** What is wrong with a blueprint as declared, apart from its prompt files: phase, side line, lane
15
+ * and agent names that are not unique, a side line beside no trunk phase, two presentations under one
16
+ * serializer name, two tools under one tool name. Empty when nothing is. */
17
+ export function blueprintProblems({ blueprint }) {
18
+ const problems = [];
19
+ const serializers = Object.create(null);
20
+ const tools = Object.create(null);
21
+ const agentNames = [];
22
+ const phaseNames = [];
23
+ const hasDot = (name) => name.includes('.');
24
+ for (const phase of blueprint.trunk)
25
+ if (blueprint.trunk.indexOf(phase) !== blueprint.trunk.lastIndexOf(phase))
26
+ problems.push(`${phase.name} stands on the trunk twice.`);
27
+ for (const phase of declaredPhases({ blueprint })) {
28
+ if (phaseNames.includes(phase.name))
29
+ problems.push(`Two phases are named ${phase.name}.`);
30
+ if (hasDot(phase.name))
31
+ problems.push(`The phase name ${phase.name} holds a dot.`);
32
+ phaseNames.push(phase.name);
33
+ if (phase.kind !== 'agents')
34
+ continue;
35
+ if (phase.worker &&
36
+ phase.worker !== 'default' &&
37
+ !Object.hasOwn(blueprint.workers ?? {}, phase.worker))
38
+ problems.push(`The phase ${phase.name} names unknown worker ${phase.worker}.`);
39
+ const laneNames = phase.lanes.map((lane) => lane.name);
40
+ for (const name of laneNames)
41
+ if (laneNames.indexOf(name) !== laneNames.lastIndexOf(name))
42
+ problems.push(`Two lanes of ${phase.name} are named ${name}.`);
43
+ }
44
+ blueprint.sideLines.forEach((sideLine, place) => {
45
+ const { name, beside, phases, atMost } = sideLine;
46
+ if (blueprint.sideLines.findIndex((each) => each.name === name) !== place)
47
+ problems.push(`Two side lines are named ${name}.`);
48
+ if (hasDot(name))
49
+ problems.push(`The side line name ${name} holds a dot.`);
50
+ if (!phases.length)
51
+ problems.push(`The side line ${name} has no phases.`);
52
+ if (phases.some((phase) => phases.indexOf(phase) !== phases.lastIndexOf(phase)))
53
+ problems.push(`A phase stands on the side line ${name} twice.`);
54
+ if (!beside.length)
55
+ problems.push(`The side line ${name} names no trunk phase it runs beside.`);
56
+ for (const phase of beside)
57
+ if (!blueprint.trunk.some((each) => each.name === phase))
58
+ problems.push(`The side line ${name} runs beside ${phase}, which is not on the trunk.`);
59
+ if (!Number.isInteger(atMost) || atMost < 1)
60
+ problems.push(`The side line ${name} must allow at least one visit.`);
61
+ });
62
+ for (const agent of blueprintAgents({ blueprint })) {
63
+ if (agentNames.includes(agent.name))
64
+ problems.push(`Two different agents are named ${agent.name}.`);
65
+ agentNames.push(agent.name);
66
+ if (agent.worker &&
67
+ agent.worker !== 'default' &&
68
+ !Object.hasOwn(blueprint.workers ?? {}, agent.worker))
69
+ problems.push(`The agent ${agent.name} names unknown worker ${agent.worker}.`);
70
+ for (const [placeholder, input] of Object.entries(agent.inputs)) {
71
+ const { name } = input.serializer;
72
+ if (Object.hasOwn(serializers, name) && serializers[name] !== input.serializer)
73
+ problems.push(`Two different serializers are named ${name} (${agent.name}.${placeholder}).`);
74
+ serializers[name] = input.serializer;
75
+ }
76
+ for (const tool of agent.tools) {
77
+ if (Object.hasOwn(tools, tool.name) && tools[tool.name] !== tool)
78
+ problems.push(`Two different tools are named ${tool.name} (${agent.name}).`);
79
+ tools[tool.name] = tool;
80
+ }
81
+ const checkNames = [];
82
+ for (const check of agent.checks) {
83
+ if (checkNames.includes(check.name))
84
+ problems.push(`Two checks of ${agent.name} are named ${check.name}.`);
85
+ checkNames.push(check.name);
86
+ }
87
+ }
88
+ return [...new Set(problems)];
89
+ }
90
+ /** The blueprint as plain data. */
91
+ export function declaredStructure({ blueprint, promptFiles, readFile, }) {
92
+ const agents = blueprintAgents({ blueprint });
93
+ const serializers = Object.create(null);
94
+ const tools = Object.create(null);
95
+ const templates = Object.create(null);
96
+ // Every declared template is listed, also one no prompt places yet.
97
+ for (const [name, path] of Object.entries(blueprint.templates))
98
+ templates[name] = { name, path, text: readFile(path).trim(), usedBy: [] };
99
+ for (const agent of agents) {
100
+ for (const input of Object.values(agent.inputs)) {
101
+ const { name, description, declaredAt } = input.serializer;
102
+ serializers[name] ??= { name, description, declaredAt, usedBy: [] };
103
+ if (!serializers[name].usedBy.includes(agent.name))
104
+ serializers[name].usedBy.push(agent.name);
105
+ }
106
+ for (const tool of agent.tools) {
107
+ const { name, description, declaredAt, annotations, asks } = tool;
108
+ tools[name] ??= {
109
+ name,
110
+ description,
111
+ declaredAt,
112
+ ...(annotations ? { annotations } : {}),
113
+ ...(asks ? { asks } : {}),
114
+ usedBy: [],
115
+ };
116
+ tools[name].usedBy.push(agent.name);
117
+ }
118
+ for (const name of promptFiles[agent.name].templates)
119
+ templates[name].usedBy.push(agent.name);
120
+ }
121
+ return {
122
+ name: blueprint.name,
123
+ description: blueprint.description,
124
+ declaredAt: blueprint.declaredAt,
125
+ startingStateDescription: blueprint.startingState.description,
126
+ modelSettings: blueprint.modelSettings,
127
+ workers: blueprint.workers,
128
+ phases: declaredPhases({ blueprint }).map((phase) => declaredPhase({ phase })),
129
+ trunk: blueprint.trunk.map((phase) => phase.name),
130
+ sideLines: blueprint.sideLines.map((sideLine) => ({
131
+ name: sideLine.name,
132
+ description: sideLine.description,
133
+ declaredAt: sideLine.declaredAt,
134
+ beside: sideLine.beside,
135
+ entersWhenDescription: sideLine.entersWhen.description,
136
+ atMost: sideLine.atMost,
137
+ phases: sideLine.phases.map((phase) => phase.name),
138
+ })),
139
+ agents: agents.map((agent) => declaredAgent({ agent, promptFile: promptFiles[agent.name] })),
140
+ tools: Object.values(tools),
141
+ serializers: Object.values(serializers),
142
+ templates: Object.values(templates),
143
+ };
144
+ }
145
+ function declaredAgent({ agent, promptFile, }) {
146
+ return {
147
+ name: agent.name,
148
+ description: agent.description,
149
+ declaredAt: agent.declaredAt,
150
+ prompt: { path: promptFile.path, text: promptFile.text, templates: promptFile.templates },
151
+ inputs: Object.entries(agent.inputs).map(([placeholder, input]) => ({
152
+ placeholder,
153
+ description: input.description,
154
+ serializer: input.serializer.name,
155
+ })),
156
+ ...(agent.attachedImages
157
+ ? { attachedImagesDescription: agent.attachedImages.description }
158
+ : {}),
159
+ replyReaderDescription: agent.replyReader.description,
160
+ ...(agent.replyReader.schema ? { replySchema: agent.replyReader.schema } : {}),
161
+ checks: agent.checks.map(({ name, description }) => ({ name, description })),
162
+ mayChange: agent.mayChange.map((rule) => ({
163
+ path: rule.path,
164
+ description: describeWriteScopeRule(rule),
165
+ })),
166
+ replyOutcomeDescription: agent.replyOutcome.description,
167
+ maxCorrections: agent.maxCorrections,
168
+ ...(agent.whenCallFails ? { whenCallFailsDescription: agent.whenCallFails.description } : {}),
169
+ tools: agent.tools.map((tool) => tool.name),
170
+ ...(agent.asks ? { asks: agent.asks } : {}),
171
+ ...(agent.worker ? { worker: agent.worker } : {}),
172
+ modelSettings: agent.modelSettings,
173
+ };
174
+ }
175
+ function declaredPhase({ phase }) {
176
+ const basics = {
177
+ name: phase.name,
178
+ description: phase.description,
179
+ declaredAt: phase.declaredAt,
180
+ };
181
+ if (phase.kind === 'code')
182
+ return { ...basics, kind: 'code', ...(phase.asks ? { asks: phase.asks } : {}) };
183
+ return {
184
+ ...basics,
185
+ kind: 'agents',
186
+ ...(phase.worker ? { worker: phase.worker } : {}),
187
+ ...(phase.modelSettings ? { modelSettings: phase.modelSettings } : {}),
188
+ lanes: phase.lanes.map((lane) => declaredLane({ lane })),
189
+ };
190
+ }
191
+ function declaredLane({ lane }) {
192
+ const { assignments } = lane;
193
+ return {
194
+ name: lane.name,
195
+ declaredAt: lane.declaredAt,
196
+ assignments: assignments === 'once'
197
+ ? {
198
+ kind: 'once',
199
+ ...(lane.onlyWhen ? { onlyWhenDescription: lane.onlyWhen.description } : {}),
200
+ }
201
+ : {
202
+ kind: 'forEach',
203
+ description: assignments.forEach.description,
204
+ subjectName: assignments.forEach.subjectName,
205
+ repeats: assignments.repeats ?? 1,
206
+ concurrency: assignments.concurrency,
207
+ ...(assignments.startsWhen
208
+ ? { startsWhenDescription: assignments.startsWhen.description }
209
+ : {}),
210
+ },
211
+ chain: lane.chain.map((agent) => agent.name),
212
+ };
213
+ }
@@ -0,0 +1,79 @@
1
+ import type { z } from 'zod';
2
+ import type { Agent, AgentInputs, AttachedImages, DecideReads, HandleReads, ReplyCheck, Tool, WhenCallFails } from './agent.js';
3
+ import type { Accepted, Artifact, AskParts, Change, ReplyOutcome, ToolOutcome } from './outcomes.js';
4
+ import type { AgentPhaseDeclaration, Blueprint, CodePhaseDeclaration, Lane, LaneDeclaration, Phase, SideLine, SideLineDeclaration } from './phase.js';
5
+ import type { ReplyReader } from './reply-reader.js';
6
+ import type { BlueprintWorkers, ModelSettings } from './run-settings.js';
7
+ import type { WriteScopeRule } from './write-scope.js';
8
+ /** Where a blueprint starts: the shape of its run state. Returns the define functions and the
9
+ * `accept` and `ask` outcomes, all typed to that state. */
10
+ export declare function defineRunState<State, Services = unknown>({ schema, }: {
11
+ schema: z.ZodType<State, z.ZodTypeDef, unknown>;
12
+ }): {
13
+ defineBlueprint: <Input>(blueprint: {
14
+ name: string;
15
+ description: string;
16
+ input: z.ZodType<Input, z.ZodTypeDef, unknown>;
17
+ startingState: {
18
+ description: string;
19
+ from: (reads: {
20
+ input: Input;
21
+ }) => State;
22
+ };
23
+ promptFolder: string;
24
+ templates?: {
25
+ [name: string]: string;
26
+ };
27
+ modelSettings: ModelSettings;
28
+ workers?: BlueprintWorkers;
29
+ trunk: readonly Phase<State, Services>[];
30
+ sideLines?: readonly SideLine<State, Services>[];
31
+ }) => Blueprint<State, Input, Services>;
32
+ defineSideLine: (sideLine: SideLineDeclaration<State, Services>) => SideLine<State, Services>;
33
+ defineAgentPhase: <Subject>(phase: AgentPhaseDeclaration<State, Subject>) => Phase<State, Services>;
34
+ defineLane: <Subject>(lane: LaneDeclaration<State, Subject>) => Lane<State>;
35
+ defineCodePhase: (phase: CodePhaseDeclaration<State, Services>) => Phase<State, Services>;
36
+ defineAgent: <Reply, Subject = unknown, SerializerArguments extends {
37
+ [placeholder: string]: unknown;
38
+ } = {}>(agent: {
39
+ name: string;
40
+ label?: string;
41
+ role?: string;
42
+ description: string;
43
+ subject?: z.ZodType<Subject, z.ZodTypeDef, unknown>;
44
+ prompt: string;
45
+ inputs: AgentInputs<State, Subject, SerializerArguments>;
46
+ attachedImages?: AttachedImages<State, Subject>;
47
+ replyReader: ReplyReader<Reply>;
48
+ checks?: ReplyCheck<State, Subject, Reply>[];
49
+ mayChange?: WriteScopeRule<State, Subject>[];
50
+ replyOutcome: {
51
+ description: string;
52
+ decide: (reads: DecideReads<State, Subject, Reply>) => ReplyOutcome<State>;
53
+ };
54
+ maxCorrections: number;
55
+ whenCallFails?: WhenCallFails<State, Subject>;
56
+ tools?: Tool<State, NoInfer<Subject>>[];
57
+ asks?: string;
58
+ worker?: string;
59
+ modelSettings?: ModelSettings;
60
+ }) => Agent<State, Subject, Reply>;
61
+ defineTool: <Arguments, Subject = unknown>(tool: {
62
+ name: string;
63
+ description: string;
64
+ input: z.ZodType<Arguments, z.ZodTypeDef, unknown>;
65
+ subject?: z.ZodType<Subject, z.ZodTypeDef, unknown>;
66
+ annotations?: {
67
+ [hint: string]: unknown;
68
+ };
69
+ asks?: string;
70
+ handle: (reads: HandleReads<State, Subject, Arguments>) => ToolOutcome<State> | Promise<ToolOutcome<State>>;
71
+ }) => Tool<State, Subject>;
72
+ accept: (writes?: {
73
+ change?: Change<State>;
74
+ artifacts?: Artifact[];
75
+ }) => Accepted<State>;
76
+ ask: <Asks extends AskParts<State>>(asks: Asks & { [Part in Exclude<keyof Asks, keyof AskParts<State>>]: never; }) => {
77
+ outcome: "asked";
78
+ } & Asks;
79
+ };
@@ -0,0 +1,89 @@
1
+ import { declarationSiteOfCaller } from './declaration-site.js';
2
+ /** Where a blueprint starts: the shape of its run state. Returns the define functions and the
3
+ * `accept` and `ask` outcomes, all typed to that state. */
4
+ export function defineRunState({ schema, }) {
5
+ /** The reply, or the code phase's work, is accepted. `change` and `artifacts` may be left out. */
6
+ function accept(writes = {}) {
7
+ return { outcome: 'accepted', ...writes };
8
+ }
9
+ /** The person is asked. With questions alone it is what a tool may return; with a change or
10
+ * artifacts it is what only a reply outcome or a code phase may return. The result keeps
11
+ * exactly the parts it was given, so a tool's `handle` can refuse a change and artifacts, and a
12
+ * part under a misspelled name is refused. */
13
+ function ask(asks) {
14
+ return { outcome: 'asked', ...asks };
15
+ }
16
+ function defineTool(tool) {
17
+ return { ...tool, declaredAt: declarationSiteOfCaller() };
18
+ }
19
+ function defineAgent(agent) {
20
+ return {
21
+ ...agent,
22
+ checks: agent.checks ?? [],
23
+ mayChange: agent.mayChange ?? [],
24
+ tools: agent.tools ?? [],
25
+ modelSettings: agent.modelSettings ?? {},
26
+ declaredAt: declarationSiteOfCaller(),
27
+ };
28
+ }
29
+ /** One lane of a phase that has several. Declaring it on its own gives its agents the lane's
30
+ * own subject type. */
31
+ function defineLane(lane) {
32
+ return { ...lane, declaredAt: declarationSiteOfCaller() };
33
+ }
34
+ function defineAgentPhase(phase) {
35
+ const declaredAt = declarationSiteOfCaller();
36
+ const { name, label, description, worker, modelSettings } = phase;
37
+ // A phase declared without lanes has one, named for the phase.
38
+ const lanes = phase.lanes ?? [
39
+ {
40
+ name,
41
+ ...(label ? { label } : {}),
42
+ declaredAt,
43
+ assignments: phase.assignments,
44
+ chain: phase.chain,
45
+ onlyWhen: phase.onlyWhen,
46
+ },
47
+ ];
48
+ return {
49
+ kind: 'agents',
50
+ name,
51
+ ...(label ? { label } : {}),
52
+ description,
53
+ ...(worker ? { worker } : {}),
54
+ ...(modelSettings ? { modelSettings } : {}),
55
+ lanes: lanes,
56
+ declaredAt,
57
+ };
58
+ }
59
+ function defineCodePhase(phase) {
60
+ return { ...phase, kind: 'code', declaredAt: declarationSiteOfCaller() };
61
+ }
62
+ /** A line of phases beside the trunk, for work a trunk phase finds is still needed. */
63
+ function defineSideLine(sideLine) {
64
+ return { atMost: 1, ...sideLine, declaredAt: declarationSiteOfCaller() };
65
+ }
66
+ function defineBlueprint(blueprint) {
67
+ const workers = Object.assign(Object.create(null), blueprint.workers);
68
+ workers.default ??= { modelSettings: blueprint.modelSettings };
69
+ return {
70
+ ...blueprint,
71
+ workers,
72
+ sideLines: blueprint.sideLines ?? [],
73
+ templates: Object.assign(Object.create(null), blueprint.templates),
74
+ runStateSchema: schema,
75
+ declaredAt: declarationSiteOfCaller(),
76
+ };
77
+ }
78
+ return {
79
+ defineBlueprint,
80
+ defineSideLine,
81
+ defineAgentPhase,
82
+ defineLane,
83
+ defineCodePhase,
84
+ defineAgent,
85
+ defineTool,
86
+ accept,
87
+ ask,
88
+ };
89
+ }
@@ -0,0 +1,28 @@
1
+ import { type DeclaredStructure } from './declared-structure.js';
2
+ import type { Blueprint } from './phase.js';
3
+ import { type PromptFile } from './prompt-file.js';
4
+ /** A blueprint read from its file, with its prompt files read and checked. */
5
+ export type LoadedBlueprint = {
6
+ blueprint: Blueprint;
7
+ promptFiles: {
8
+ [agentName: string]: PromptFile;
9
+ };
10
+ structure: DeclaredStructure;
11
+ /** A short code that changes whenever the declared structure, a description, a prompt or a
12
+ * template changes. */
13
+ hash: string;
14
+ };
15
+ /** Prepares an in-memory `Blueprint` value by reading and validating its prompt files and templates. */
16
+ export declare function prepareBlueprint({ blueprint, promptFolder: givenPromptFolder, readPrompt, }: {
17
+ blueprint: Blueprint<any, any, any>;
18
+ promptFolder?: string;
19
+ readPrompt?: (path: string) => string;
20
+ }): LoadedBlueprint;
21
+ /** Whether a value is already a `LoadedBlueprint` rather than a raw `Blueprint`. */
22
+ export declare function isLoadedBlueprint(value: Blueprint<any, any, any> | LoadedBlueprint): value is LoadedBlueprint;
23
+ /** Reads a blueprint file (its default export is the blueprint) and every prompt file its agents
24
+ * name, and checks them against each other, before any call. Throws one error listing everything
25
+ * that keeps the blueprint from being used. */
26
+ export declare function loadBlueprint({ file }: {
27
+ file: string;
28
+ }): Promise<LoadedBlueprint>;
@@ -0,0 +1,85 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync } from 'node:fs';
3
+ import { dirname, join, relative, resolve } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { blueprintAgents, blueprintProblems, declaredStructure, } from './declared-structure.js';
6
+ import { PROMPT_PATH, promptInputProblems, readPromptFile } from './prompt-file.js';
7
+ /** What is wrong with the blueprint's templates: a path outside the prompt folder's rule, a file
8
+ * that cannot be read, an empty file. */
9
+ function templateProblems({ blueprint, readFile, }) {
10
+ const problems = [];
11
+ for (const [name, path] of Object.entries(blueprint.templates))
12
+ try {
13
+ if (!PROMPT_PATH.test(path))
14
+ throw new Error(`Invalid template path: ${path}`);
15
+ if (!readFile(path).trim())
16
+ throw new Error(`${path} is empty.`);
17
+ }
18
+ catch (error) {
19
+ problems.push(`The template ${name}: ${error instanceof Error ? error.message : String(error)}`);
20
+ }
21
+ return problems;
22
+ }
23
+ /** Reads every agent's prompt file. Returns them by agent name, with what is wrong between each
24
+ * and its agent's inputs. */
25
+ function readAgentPromptFiles({ blueprint, readFile, }) {
26
+ const promptFiles = Object.create(null);
27
+ const problems = [];
28
+ for (const agent of blueprintAgents({ blueprint }))
29
+ try {
30
+ const promptFile = readPromptFile({
31
+ readFile,
32
+ path: agent.prompt,
33
+ templates: blueprint.templates,
34
+ });
35
+ promptFiles[agent.name] = promptFile;
36
+ problems.push(...promptInputProblems({ promptFile, inputNames: Object.keys(agent.inputs) }).map((problem) => `${agent.name}: ${problem}`));
37
+ }
38
+ catch (error) {
39
+ problems.push(`${agent.name}: ${error instanceof Error ? error.message : String(error)}`);
40
+ }
41
+ return { promptFiles, problems };
42
+ }
43
+ /** Prepares an in-memory `Blueprint` value by reading and validating its prompt files and templates. */
44
+ export function prepareBlueprint({ blueprint, promptFolder: givenPromptFolder, readPrompt, }) {
45
+ const baseDir = dirname(blueprint.declaredAt.file);
46
+ const promptFolder = givenPromptFolder ?? resolve(baseDir, blueprint.promptFolder);
47
+ const readFile = readPrompt ?? ((promptPath) => readFileSync(join(promptFolder, promptPath), 'utf8'));
48
+ const ofTemplates = templateProblems({ blueprint, readFile });
49
+ if (ofTemplates.length)
50
+ throw new Error(`The blueprint ${blueprint.name} cannot be used:\n- ${ofTemplates.join('\n- ')}`);
51
+ const { promptFiles, problems } = readAgentPromptFiles({ blueprint, readFile });
52
+ const allProblems = [...blueprintProblems({ blueprint }), ...problems];
53
+ if (allProblems.length)
54
+ throw new Error(`The blueprint ${blueprint.name} cannot be used:\n- ${allProblems.join('\n- ')}`);
55
+ const structure = declaredStructure({ blueprint, promptFiles, readFile });
56
+ const blueprintFolder = dirname(structure.declaredAt.file);
57
+ // Files are written relative to the blueprint's own, so the same blueprint in another folder
58
+ // has the same hash.
59
+ const hashed = JSON.stringify(structure, (key, value) => {
60
+ if (key !== 'declaredAt')
61
+ return value;
62
+ const { file, line } = value;
63
+ return { file: relative(blueprintFolder, file), line };
64
+ });
65
+ const hash = createHash('sha256').update(hashed).digest('hex').slice(0, 16);
66
+ return { blueprint, promptFiles, structure, hash };
67
+ }
68
+ /** Whether a value is already a `LoadedBlueprint` rather than a raw `Blueprint`. */
69
+ export function isLoadedBlueprint(value) {
70
+ return 'blueprint' in value && 'promptFiles' in value && 'structure' in value;
71
+ }
72
+ /** Reads a blueprint file (its default export is the blueprint) and every prompt file its agents
73
+ * name, and checks them against each other, before any call. Throws one error listing everything
74
+ * that keeps the blueprint from being used. */
75
+ export async function loadBlueprint({ file }) {
76
+ const path = resolve(file);
77
+ const module = (await import(pathToFileURL(path).href));
78
+ const blueprint = module.default;
79
+ if (!blueprint || !Array.isArray(blueprint.trunk) || typeof blueprint.name !== 'string')
80
+ throw new Error(`${path} must export a blueprint as its default export.`);
81
+ return prepareBlueprint({
82
+ blueprint,
83
+ promptFolder: resolve(dirname(path), blueprint.promptFolder),
84
+ });
85
+ }
@@ -0,0 +1,76 @@
1
+ /** A file a run writes that is not part of the run state. */
2
+ export type Artifact = {
3
+ name: string;
4
+ mediaType: string;
5
+ bytes: Uint8Array;
6
+ };
7
+ /** Reads an artifact by name: the newest of that name in this run or the run it started from. */
8
+ export type ArtifactReader = {
9
+ read: (reads: {
10
+ name: string;
11
+ }) => Promise<Artifact>;
12
+ };
13
+ /** Text for the person, with optional choices and an optional recommended choice. */
14
+ export type Question = {
15
+ text: string;
16
+ choices?: string[];
17
+ recommended?: {
18
+ choice: string;
19
+ reason: string;
20
+ };
21
+ };
22
+ /** A question that was asked, with the answer given: one of its choices or typed text. */
23
+ export type Answer = {
24
+ question: Question;
25
+ answer: string;
26
+ };
27
+ /** The reply that was sent back, as the model wrote it, and the correction text sent with it. */
28
+ export type Correction = {
29
+ rejectedReply: string;
30
+ text: string;
31
+ };
32
+ /** A change to the run state: a function from the state as it stands to the next state. */
33
+ export type Change<State> = (state: State) => State;
34
+ export type Accepted<State> = {
35
+ outcome: 'accepted';
36
+ change?: Change<State>;
37
+ artifacts?: Artifact[];
38
+ };
39
+ export type SentBack = {
40
+ outcome: 'sentBack';
41
+ correction: string;
42
+ };
43
+ export type Asked<State> = {
44
+ outcome: 'asked';
45
+ questions: Question[];
46
+ change?: Change<State>;
47
+ artifacts?: Artifact[];
48
+ };
49
+ /** What `ask` is given by a reply outcome or a code phase. */
50
+ export type AskParts<State> = {
51
+ questions: Question[];
52
+ change?: Change<State>;
53
+ artifacts?: Artifact[];
54
+ };
55
+ /** The only form of `ask` a tool may return: questions alone. */
56
+ export type AskedByTool = {
57
+ outcome: 'asked';
58
+ questions: Question[];
59
+ change?: undefined;
60
+ artifacts?: undefined;
61
+ };
62
+ /** What blueprint code decides about a reply. */
63
+ export type ReplyOutcome<State> = Accepted<State> | SentBack | Asked<State>;
64
+ export type CodePhaseOutcome<State> = Accepted<State> | Asked<State>;
65
+ /** A tool's result for the model, with an optional change and artifacts saved before the result
66
+ * goes back; or a question for the person, which ends the call. */
67
+ export type ToolOutcome<State> = {
68
+ result: unknown;
69
+ change?: Change<State>;
70
+ artifacts?: Artifact[];
71
+ } | AskedByTool;
72
+ /** The reply is not accepted: the same agent is called again with this correction. */
73
+ export declare function sendBack({ correction }: {
74
+ correction: string;
75
+ }): SentBack;
76
+ export declare function isSentBack(value: unknown): value is SentBack;
@@ -0,0 +1,10 @@
1
+ /** The reply is not accepted: the same agent is called again with this correction. */
2
+ export function sendBack({ correction }) {
3
+ return { outcome: 'sentBack', correction };
4
+ }
5
+ export function isSentBack(value) {
6
+ return (typeof value === 'object' &&
7
+ value !== null &&
8
+ value.outcome === 'sentBack' &&
9
+ typeof value.correction === 'string');
10
+ }