@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.
- package/dist/admin-ui/assets/index-CHJ8lsZp.js +120 -0
- package/dist/admin-ui/assets/index-XyqtD-IA.css +1 -0
- package/dist/admin-ui/index.html +12 -0
- package/dist/blueprint/agent.d.ts +148 -0
- package/dist/blueprint/agent.js +1 -0
- package/dist/blueprint/declaration-site.d.ts +7 -0
- package/dist/blueprint/declaration-site.js +8 -0
- package/dist/blueprint/declared-structure.d.ts +145 -0
- package/dist/blueprint/declared-structure.js +213 -0
- package/dist/blueprint/define-run-state.d.ts +79 -0
- package/dist/blueprint/define-run-state.js +89 -0
- package/dist/blueprint/load-blueprint.d.ts +28 -0
- package/dist/blueprint/load-blueprint.js +85 -0
- package/dist/blueprint/outcomes.d.ts +76 -0
- package/dist/blueprint/outcomes.js +10 -0
- package/dist/blueprint/phase.d.ts +153 -0
- package/dist/blueprint/phase.js +1 -0
- package/dist/blueprint/places.d.ts +26 -0
- package/dist/blueprint/places.js +37 -0
- package/dist/blueprint/prompt-file.d.ts +81 -0
- package/dist/blueprint/prompt-file.js +131 -0
- package/dist/blueprint/reply-reader.d.ts +36 -0
- package/dist/blueprint/reply-reader.js +38 -0
- package/dist/blueprint/run-settings.d.ts +38 -0
- package/dist/blueprint/run-settings.js +1 -0
- package/dist/blueprint/serializer.d.ts +14 -0
- package/dist/blueprint/serializer.js +4 -0
- package/dist/blueprint/write-scope.d.ts +39 -0
- package/dist/blueprint/write-scope.js +106 -0
- package/dist/command.d.ts +2 -0
- package/dist/command.js +148 -0
- package/dist/commands/calls-answering.d.ts +16 -0
- package/dist/commands/calls-answering.js +63 -0
- package/dist/commands/json-file.d.ts +6 -0
- package/dist/commands/json-file.js +19 -0
- package/dist/commands/run-command.d.ts +23 -0
- package/dist/commands/run-command.js +172 -0
- package/dist/commands/typed-answers.d.ts +10 -0
- package/dist/commands/typed-answers.js +43 -0
- package/dist/config.d.ts +27 -0
- package/dist/config.js +20 -0
- package/dist/devtool-server/app-pages.d.ts +12 -0
- package/dist/devtool-server/app-pages.js +68 -0
- package/dist/devtool-server/blueprint-description.d.ts +21 -0
- package/dist/devtool-server/blueprint-description.js +27 -0
- package/dist/devtool-server/connected-runs.d.ts +36 -0
- package/dist/devtool-server/connected-runs.js +201 -0
- package/dist/devtool-server/devtool-server.d.ts +17 -0
- package/dist/devtool-server/devtool-server.js +294 -0
- package/dist/devtool-server/devtool-shapes.d.ts +312 -0
- package/dist/devtool-server/devtool-shapes.js +24 -0
- package/dist/devtool-server/listed-runs.d.ts +17 -0
- package/dist/devtool-server/listed-runs.js +42 -0
- package/dist/devtool-server/print-blueprint.d.ts +1 -0
- package/dist/devtool-server/print-blueprint.js +36 -0
- package/dist/example/added-species.d.ts +21 -0
- package/dist/example/added-species.js +19 -0
- package/dist/example/cover.d.ts +21 -0
- package/dist/example/cover.js +67 -0
- package/dist/example/cross-references.d.ts +21 -0
- package/dist/example/cross-references.js +77 -0
- package/dist/example/entry-drafts.d.ts +21 -0
- package/dist/example/entry-drafts.js +63 -0
- package/dist/example/entry-merge.d.ts +108 -0
- package/dist/example/entry-merge.js +284 -0
- package/dist/example/field-guide.d.ts +26 -0
- package/dist/example/field-guide.js +40 -0
- package/dist/example/guide-page.d.ts +21 -0
- package/dist/example/guide-page.js +15 -0
- package/dist/example/missing-species.d.ts +21 -0
- package/dist/example/missing-species.js +59 -0
- package/dist/example/run-state.d.ts +803 -0
- package/dist/example/run-state.js +58 -0
- package/dist/example/serializers.d.ts +32 -0
- package/dist/example/serializers.js +42 -0
- package/dist/example/species-list.d.ts +47 -0
- package/dist/example/species-list.js +93 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +25 -0
- package/dist/inference/anthropic-api.d.ts +37 -0
- package/dist/inference/anthropic-api.js +197 -0
- package/dist/inference/anthropic-prices.d.ts +18 -0
- package/dist/inference/anthropic-prices.js +39 -0
- package/dist/inference/anthropic-request.d.ts +51 -0
- package/dist/inference/anthropic-request.js +208 -0
- package/dist/inference/bedrock-api.d.ts +45 -0
- package/dist/inference/bedrock-api.js +242 -0
- package/dist/inference/bedrock-prices.d.ts +22 -0
- package/dist/inference/bedrock-prices.js +79 -0
- package/dist/inference/bedrock-request.d.ts +27 -0
- package/dist/inference/bedrock-request.js +193 -0
- package/dist/inference/call-queue-shapes.d.ts +273 -0
- package/dist/inference/call-queue-shapes.js +82 -0
- package/dist/inference/call-queue.d.ts +109 -0
- package/dist/inference/call-queue.js +408 -0
- package/dist/inference/gemini-api.d.ts +44 -0
- package/dist/inference/gemini-api.js +191 -0
- package/dist/inference/gemini-prices.d.ts +19 -0
- package/dist/inference/gemini-prices.js +33 -0
- package/dist/inference/gemini-request.d.ts +25 -0
- package/dist/inference/gemini-request.js +126 -0
- package/dist/inference/inference.d.ts +84 -0
- package/dist/inference/inference.js +9 -0
- package/dist/inference/openai-api.d.ts +29 -0
- package/dist/inference/openai-api.js +138 -0
- package/dist/inference/openai-prices.d.ts +12 -0
- package/dist/inference/openai-prices.js +25 -0
- package/dist/inference/openai-request.d.ts +50 -0
- package/dist/inference/openai-request.js +100 -0
- package/dist/inference/own-worker.d.ts +6 -0
- package/dist/inference/own-worker.js +16 -0
- package/dist/inference/scripted.d.ts +146 -0
- package/dist/inference/scripted.js +67 -0
- package/dist/run/assignments/agent-call.d.ts +32 -0
- package/dist/run/assignments/agent-call.js +218 -0
- package/dist/run/assignments/agent-phase.d.ts +14 -0
- package/dist/run/assignments/agent-phase.js +243 -0
- package/dist/run/assignments/assignment-memory.d.ts +42 -0
- package/dist/run/assignments/assignment-memory.js +52 -0
- package/dist/run/assignments/assignment.d.ts +17 -0
- package/dist/run/assignments/assignment.js +252 -0
- package/dist/run/assignments/model-settings.d.ts +39 -0
- package/dist/run/assignments/model-settings.js +57 -0
- package/dist/run/assignments/prepared-call.d.ts +28 -0
- package/dist/run/assignments/prepared-call.js +115 -0
- package/dist/run/assignments/tool-call.d.ts +26 -0
- package/dist/run/assignments/tool-call.js +108 -0
- package/dist/run/blueprint-mistake.d.ts +8 -0
- package/dist/run/blueprint-mistake.js +14 -0
- package/dist/run/code-phase.d.ts +11 -0
- package/dist/run/code-phase.js +59 -0
- package/dist/run/create-run.d.ts +36 -0
- package/dist/run/create-run.js +119 -0
- package/dist/run/execute-run.d.ts +7 -0
- package/dist/run/execute-run.js +158 -0
- package/dist/run/record/apply-event.d.ts +13 -0
- package/dist/run/record/apply-event.js +256 -0
- package/dist/run/record/events.d.ts +187 -0
- package/dist/run/record/events.js +1 -0
- package/dist/run/record/postgres-run-store.d.ts +13 -0
- package/dist/run/record/postgres-run-store.js +189 -0
- package/dist/run/record/progress-projection.d.ts +83 -0
- package/dist/run/record/progress-projection.js +167 -0
- package/dist/run/record/progress.d.ts +207 -0
- package/dist/run/record/progress.js +63 -0
- package/dist/run/record/run-store.d.ts +74 -0
- package/dist/run/record/run-store.js +1 -0
- package/dist/run/record/run-summary.d.ts +8 -0
- package/dist/run/record/run-summary.js +19 -0
- package/dist/run/record/run-types.d.ts +95 -0
- package/dist/run/record/run-types.js +1 -0
- package/dist/run/record/state-changes.d.ts +42 -0
- package/dist/run/record/state-changes.js +157 -0
- package/dist/run/resume-run.d.ts +25 -0
- package/dist/run/resume-run.js +99 -0
- package/dist/run/run-endings.d.ts +20 -0
- package/dist/run/run-endings.js +20 -0
- package/dist/run/run-option-shapes.d.ts +176 -0
- package/dist/run/run-option-shapes.js +47 -0
- package/dist/run/run-session.d.ts +144 -0
- package/dist/run/run-session.js +278 -0
- package/dist/worker/answer-queued-call.d.ts +19 -0
- package/dist/worker/answer-queued-call.js +100 -0
- package/dist/worker/launchers/claude-code.d.ts +7 -0
- package/dist/worker/launchers/claude-code.js +156 -0
- package/dist/worker/launchers/codex.d.ts +6 -0
- package/dist/worker/launchers/codex.js +141 -0
- package/dist/worker/launchers/launch.d.ts +31 -0
- package/dist/worker/launchers/launch.js +6 -0
- package/dist/worker/launchers/program-run.d.ts +30 -0
- package/dist/worker/launchers/program-run.js +92 -0
- package/dist/worker/launchers/tool-server.d.ts +26 -0
- package/dist/worker/launchers/tool-server.js +90 -0
- package/dist/worker/worker.d.ts +13 -0
- package/dist/worker/worker.js +170 -0
- package/package.json +43 -4
- package/README.md +0 -3
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { hasAnthropicPrice } from '../../inference/anthropic-prices.js';
|
|
2
|
+
import { hasBedrockPrice } from '../../inference/bedrock-prices.js';
|
|
3
|
+
import { hasGeminiPrice } from '../../inference/gemini-prices.js';
|
|
4
|
+
import { hasOpenAiPrice } from '../../inference/openai-prices.js';
|
|
5
|
+
const merged = ({ lower, higher }) => ({
|
|
6
|
+
...lower,
|
|
7
|
+
...higher,
|
|
8
|
+
model: { ...lower.model, ...higher?.model },
|
|
9
|
+
});
|
|
10
|
+
/** Resolves the worker type name and optional definition for one agent in one phase. */
|
|
11
|
+
export function resolvedWorkerFor({ workers, phase, agent, }) {
|
|
12
|
+
const worker = agent.worker ?? phase.worker ?? 'default';
|
|
13
|
+
const definition = workers && Object.hasOwn(workers, worker) ? workers[worker] : undefined;
|
|
14
|
+
return { worker, definition };
|
|
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 function modelSettingsFor({ blueprint, workers, phase, agent, overrides, }) {
|
|
20
|
+
const applies = (override) => (!override.phase || override.phase === phase.name) &&
|
|
21
|
+
(!override.agent || override.agent === agent.name);
|
|
22
|
+
const specificity = (override) => (override.agent ? 2 : 0) + (override.phase ? 1 : 0);
|
|
23
|
+
const { definition } = resolvedWorkerFor({ workers, phase, agent });
|
|
24
|
+
const declared = merged({
|
|
25
|
+
lower: merged({
|
|
26
|
+
lower: merged({ lower: blueprint, higher: definition?.modelSettings }),
|
|
27
|
+
higher: phase.modelSettings,
|
|
28
|
+
}),
|
|
29
|
+
higher: agent.modelSettings,
|
|
30
|
+
});
|
|
31
|
+
return overrides
|
|
32
|
+
.filter(applies)
|
|
33
|
+
.sort((one, other) => specificity(one) - specificity(other))
|
|
34
|
+
.reduce((settings, override) => merged({ lower: settings, higher: override.modelSettings }), declared);
|
|
35
|
+
}
|
|
36
|
+
/** Why a run answered this way cannot use these settings; undefined when it can. A scripted run
|
|
37
|
+
* needs no model or effort. */
|
|
38
|
+
export function modelSettingsProblem({ settings, callsAnsweredBy, }) {
|
|
39
|
+
if (callsAnsweredBy === 'scripted' || callsAnsweredBy === 'custom')
|
|
40
|
+
return undefined;
|
|
41
|
+
const model = settings.model?.[callsAnsweredBy];
|
|
42
|
+
if (!model)
|
|
43
|
+
return `has no model for ${callsAnsweredBy}`;
|
|
44
|
+
if (callsAnsweredBy === 'openai-api' && !hasOpenAiPrice({ model }))
|
|
45
|
+
return `names the model ${model}, which has no price on the OpenAI API`;
|
|
46
|
+
if (callsAnsweredBy === 'anthropic-api' && !hasAnthropicPrice({ model }))
|
|
47
|
+
return `names the model ${model}, which has no price on the Anthropic API`;
|
|
48
|
+
if (callsAnsweredBy === 'bedrock-api' && !hasBedrockPrice({ model }))
|
|
49
|
+
return `names the model ${model}, which has no price on the AWS Bedrock API`;
|
|
50
|
+
if (callsAnsweredBy === 'gemini-api' && !hasGeminiPrice({ model }))
|
|
51
|
+
return `names the model ${model}, which has no price on the Gemini API`;
|
|
52
|
+
if (!settings.effort)
|
|
53
|
+
return 'has no effort';
|
|
54
|
+
if (settings.effort === 'none' && callsAnsweredBy === 'claude-code')
|
|
55
|
+
return 'has effort none, which Claude Code cannot be given';
|
|
56
|
+
return undefined;
|
|
57
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { AgentInChain } from '../../blueprint/agent.js';
|
|
2
|
+
import type { CallsAnsweredBy, ModelSettings } from '../../blueprint/run-settings.js';
|
|
3
|
+
import type { InferenceCall } from '../../inference/inference.js';
|
|
4
|
+
import type { AssignmentProgress } from '../record/progress.js';
|
|
5
|
+
import type { CallFile } from '../record/run-types.js';
|
|
6
|
+
import type { RunSession } from '../run-session.js';
|
|
7
|
+
import { type AssignmentMemory } from './assignment-memory.js';
|
|
8
|
+
export declare const byteLength: (text: string) => number;
|
|
9
|
+
/** One call made ready: its prompt built from the state as it stands, its file as first saved,
|
|
10
|
+
* and the call as whatever answers it receives it. Nothing is saved or recorded here. */
|
|
11
|
+
export declare function preparedCall<State>({ session, assignment, agent, memory, callsAnsweredBy, worker, workerLabel, settings, }: {
|
|
12
|
+
session: RunSession<State>;
|
|
13
|
+
assignment: AssignmentProgress;
|
|
14
|
+
agent: AgentInChain<State, never>;
|
|
15
|
+
memory: AssignmentMemory<State>;
|
|
16
|
+
callsAnsweredBy: CallsAnsweredBy;
|
|
17
|
+
worker: string;
|
|
18
|
+
workerLabel?: string;
|
|
19
|
+
/** The agent's model settings, after the worker's, phase's, blueprint's and run's overrides. */
|
|
20
|
+
settings: ModelSettings;
|
|
21
|
+
}): Promise<{
|
|
22
|
+
callId: string;
|
|
23
|
+
attempt: number;
|
|
24
|
+
stateAtPrompt: State;
|
|
25
|
+
stateSeq: number;
|
|
26
|
+
callFile: CallFile;
|
|
27
|
+
call: InferenceCall;
|
|
28
|
+
}>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
2
|
+
import { renderPrompt } from '../../blueprint/prompt-file.js';
|
|
3
|
+
import { blueprintCode } from '../blueprint-mistake.js';
|
|
4
|
+
import { assignmentReads } from './assignment-memory.js';
|
|
5
|
+
export const byteLength = (text) => new TextEncoder().encode(text).length;
|
|
6
|
+
/** One call made ready: its prompt built from the state as it stands, its file as first saved,
|
|
7
|
+
* and the call as whatever answers it receives it. Nothing is saved or recorded here. */
|
|
8
|
+
export async function preparedCall({ session, assignment, agent, memory, callsAnsweredBy, worker, workerLabel, settings, }) {
|
|
9
|
+
const promptFile = session.promptFiles[agent.name];
|
|
10
|
+
const model = callsAnsweredBy === 'scripted' || callsAnsweredBy === 'custom'
|
|
11
|
+
? undefined
|
|
12
|
+
: settings.model?.[callsAnsweredBy];
|
|
13
|
+
const tools = agent.tools.map((tool) => ({
|
|
14
|
+
name: tool.name,
|
|
15
|
+
description: tool.description,
|
|
16
|
+
inputSchema: zodToJsonSchema(tool.input, { $refStrategy: 'none' }),
|
|
17
|
+
...(tool.annotations ? { annotations: tool.annotations } : {}),
|
|
18
|
+
}));
|
|
19
|
+
/** How many calls this agent has had answered for this lane's subject and repeat in the whole run.
|
|
20
|
+
* A call counts once it failed, asked, or its reply was judged. */
|
|
21
|
+
const answeredCallsBefore = () => Object.values(session.progress.calls).filter((call) => {
|
|
22
|
+
const its = session.progress.assignments[call.assignmentId];
|
|
23
|
+
const answered = call.status === 'failed' || call.status === 'asked' || call.outcome !== undefined;
|
|
24
|
+
return (call.agent === agent.name &&
|
|
25
|
+
its.phase === assignment.phase &&
|
|
26
|
+
its.lane === assignment.lane &&
|
|
27
|
+
its.key === assignment.key &&
|
|
28
|
+
its.repeat === assignment.repeat &&
|
|
29
|
+
answered);
|
|
30
|
+
}).length;
|
|
31
|
+
const reads = assignmentReads({ session, assignment, memory });
|
|
32
|
+
const stateAtPrompt = session.state;
|
|
33
|
+
const stateSeq = session.progress.seq;
|
|
34
|
+
const inputTexts = Object.create(null);
|
|
35
|
+
for (const [placeholder, input] of Object.entries(agent.inputs))
|
|
36
|
+
inputTexts[placeholder] = blueprintCode({
|
|
37
|
+
what: `${agent.name}'s input ${placeholder}`,
|
|
38
|
+
run: () => input.serializer.render(input.from(reads)),
|
|
39
|
+
});
|
|
40
|
+
const rendered = renderPrompt({ promptFile, inputTexts });
|
|
41
|
+
const imageNames = agent.attachedImages
|
|
42
|
+
? blueprintCode({
|
|
43
|
+
what: `${agent.name}'s attached images`,
|
|
44
|
+
run: () => agent.attachedImages.images(reads),
|
|
45
|
+
})
|
|
46
|
+
: [];
|
|
47
|
+
const images = [];
|
|
48
|
+
for (const name of imageNames)
|
|
49
|
+
images.push(await session.artifacts.read({ name }));
|
|
50
|
+
const callId = session.newId({ prefix: 'c' });
|
|
51
|
+
const attempt = (assignment.attempts[agent.name] ?? 0) + 1;
|
|
52
|
+
const callFile = {
|
|
53
|
+
callId,
|
|
54
|
+
assignmentId: assignment.id,
|
|
55
|
+
phase: assignment.phase,
|
|
56
|
+
lane: assignment.lane,
|
|
57
|
+
subjectKey: assignment.key,
|
|
58
|
+
repeat: assignment.repeat,
|
|
59
|
+
agent: agent.name,
|
|
60
|
+
placeInChain: assignment.placeInChain,
|
|
61
|
+
attempt,
|
|
62
|
+
answeredBy: callsAnsweredBy,
|
|
63
|
+
...(model ? { model } : {}),
|
|
64
|
+
...(settings.effort ? { effort: settings.effort } : {}),
|
|
65
|
+
promptFile: { path: promptFile.path, text: promptFile.text, templates: promptFile.templates },
|
|
66
|
+
prompt: rendered.prompt,
|
|
67
|
+
inputs: Object.entries(agent.inputs).map(([placeholder, input]) => ({
|
|
68
|
+
placeholder,
|
|
69
|
+
description: input.description,
|
|
70
|
+
serializer: input.serializer.name,
|
|
71
|
+
sizeInBytes: byteLength(inputTexts[placeholder]),
|
|
72
|
+
ranges: rendered.inputs.find((entry) => entry.placeholder === placeholder)?.ranges ?? [],
|
|
73
|
+
})),
|
|
74
|
+
templates: rendered.templates,
|
|
75
|
+
attachedImages: imageNames.map((name) => ({
|
|
76
|
+
name,
|
|
77
|
+
artifactId: session.progress.artifacts[name].id,
|
|
78
|
+
})),
|
|
79
|
+
tools,
|
|
80
|
+
startedAt: new Date().toISOString(),
|
|
81
|
+
toolCalls: [],
|
|
82
|
+
reasoning: [],
|
|
83
|
+
};
|
|
84
|
+
const phase = session.blueprint.trunk
|
|
85
|
+
.concat(session.blueprint.sideLines.flatMap((line) => line.phases))
|
|
86
|
+
.find((candidate) => candidate.name === assignment.phase || assignment.phase.endsWith(`.${candidate.name}`));
|
|
87
|
+
const activityLabel = phase?.label ?? phase?.name ?? assignment.phase;
|
|
88
|
+
const subjectLabel = assignment.key !== 'once' ? assignment.label : undefined;
|
|
89
|
+
const resolvedModels = settings.model && Object.keys(settings.model).length > 0 ? { ...settings.model } : undefined;
|
|
90
|
+
const call = {
|
|
91
|
+
callId,
|
|
92
|
+
agent: agent.name,
|
|
93
|
+
phase: assignment.phase,
|
|
94
|
+
lane: assignment.lane,
|
|
95
|
+
subjectKey: assignment.key,
|
|
96
|
+
activityLabel,
|
|
97
|
+
...(subjectLabel ? { subjectLabel } : {}),
|
|
98
|
+
...(agent.role ? { role: agent.role } : {}),
|
|
99
|
+
worker,
|
|
100
|
+
...(workerLabel ? { workerLabel } : {}),
|
|
101
|
+
repeat: assignment.repeat,
|
|
102
|
+
attempt,
|
|
103
|
+
callNumber: answeredCallsBefore() + 1,
|
|
104
|
+
prompt: rendered.prompt,
|
|
105
|
+
...(rendered.promptBlocks.some((block) => block.cache)
|
|
106
|
+
? { promptBlocks: rendered.promptBlocks }
|
|
107
|
+
: {}),
|
|
108
|
+
images: images.map(({ mediaType, bytes }) => ({ mediaType, bytes })),
|
|
109
|
+
tools,
|
|
110
|
+
...(model ? { model } : {}),
|
|
111
|
+
...(resolvedModels ? { models: resolvedModels } : {}),
|
|
112
|
+
...(settings.effort ? { effort: settings.effort } : {}),
|
|
113
|
+
};
|
|
114
|
+
return { callId, attempt, stateAtPrompt, stateSeq, callFile, call };
|
|
115
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { AgentInChain } from '../../blueprint/agent.js';
|
|
2
|
+
import type { AssignmentProgress } from '../record/progress.js';
|
|
3
|
+
import type { CallFile } from '../record/run-types.js';
|
|
4
|
+
import type { RunSession } from '../run-session.js';
|
|
5
|
+
import { type AssignmentMemory } from './assignment-memory.js';
|
|
6
|
+
/** Answers one tool call of a model, where the tool's handler runs, and saves it. Returns what
|
|
7
|
+
* goes back to the model. `askedPerson` is set when the tool asked a question that now waits,
|
|
8
|
+
* which ends the call. Any error of a handler goes back to the model as the tool call's result.
|
|
9
|
+
* Throws when the call ended while the handler worked, and when what the handler returned cannot
|
|
10
|
+
* be saved, which fails the run. */
|
|
11
|
+
export declare function answerToolCall<State>({ session, assignment, agent, memory, callFile, callSignal, toolCall: { name, args }, }: {
|
|
12
|
+
session: RunSession<State>;
|
|
13
|
+
assignment: AssignmentProgress;
|
|
14
|
+
agent: AgentInChain<State, never>;
|
|
15
|
+
memory: AssignmentMemory<State>;
|
|
16
|
+
callFile: CallFile;
|
|
17
|
+
/** Triggered when the call ends for any reason: Stop or a failure. */
|
|
18
|
+
callSignal: AbortSignal;
|
|
19
|
+
toolCall: {
|
|
20
|
+
name: string;
|
|
21
|
+
args: unknown;
|
|
22
|
+
};
|
|
23
|
+
}): Promise<{
|
|
24
|
+
result: unknown;
|
|
25
|
+
askedPerson?: true;
|
|
26
|
+
}>;
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { writeScopeViolations } from '../../blueprint/write-scope.js';
|
|
2
|
+
import { BlueprintMistake, blueprintCode } from '../blueprint-mistake.js';
|
|
3
|
+
import { fittedNextState } from '../record/state-changes.js';
|
|
4
|
+
import { assignmentReads } from './assignment-memory.js';
|
|
5
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
6
|
+
/** Answers one tool call of a model, where the tool's handler runs, and saves it. Returns what
|
|
7
|
+
* goes back to the model. `askedPerson` is set when the tool asked a question that now waits,
|
|
8
|
+
* which ends the call. Any error of a handler goes back to the model as the tool call's result.
|
|
9
|
+
* Throws when the call ended while the handler worked, and when what the handler returned cannot
|
|
10
|
+
* be saved, which fails the run. */
|
|
11
|
+
export async function answerToolCall({ session, assignment, agent, memory, callFile, callSignal, toolCall: { name, args }, }) {
|
|
12
|
+
const started = performance.now();
|
|
13
|
+
const tool = agent.tools.find((candidate) => candidate.name === name);
|
|
14
|
+
/** Saves the tool call in the call's file and as an events line carrying what it wrote. */
|
|
15
|
+
const save = async ({ toolCall, writes = {}, }) => {
|
|
16
|
+
const durationMs = Math.round(performance.now() - started);
|
|
17
|
+
const saved = { tool: name, arguments: args, durationMs, ...toolCall };
|
|
18
|
+
callFile.toolCalls.push(saved);
|
|
19
|
+
await session.saveCallFile(callFile);
|
|
20
|
+
await session.record({
|
|
21
|
+
kind: 'tool-call-finished',
|
|
22
|
+
callId: callFile.callId,
|
|
23
|
+
tool: name,
|
|
24
|
+
durationMs,
|
|
25
|
+
status: toolCall.status,
|
|
26
|
+
...writes,
|
|
27
|
+
});
|
|
28
|
+
return saved;
|
|
29
|
+
};
|
|
30
|
+
const failed = async (error) => {
|
|
31
|
+
await save({ toolCall: { status: 'failed', error } });
|
|
32
|
+
return { result: { error } };
|
|
33
|
+
};
|
|
34
|
+
if (!tool)
|
|
35
|
+
return failed(`There is no tool named ${name}.`);
|
|
36
|
+
const parsed = tool.input.safeParse(args);
|
|
37
|
+
// Arguments that fail the tool's input never reach its handler.
|
|
38
|
+
if (!parsed.success)
|
|
39
|
+
return failed(parsed.error.issues
|
|
40
|
+
.map((issue) => `${issue.path.join('.') || 'arguments'}: ${issue.message}`)
|
|
41
|
+
.join('; '));
|
|
42
|
+
const reads = assignmentReads({ session, assignment, memory });
|
|
43
|
+
let outcome;
|
|
44
|
+
try {
|
|
45
|
+
outcome = await tool.handle({
|
|
46
|
+
args: parsed.data,
|
|
47
|
+
state: session.state,
|
|
48
|
+
questionsAnsweredBy: session.questionsAnsweredBy,
|
|
49
|
+
subject: reads.subject,
|
|
50
|
+
earlier: reads.earlier,
|
|
51
|
+
stopSignal: callSignal,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (callSignal.aborted)
|
|
56
|
+
throw error;
|
|
57
|
+
return failed(messageOf(error));
|
|
58
|
+
}
|
|
59
|
+
// From here on a failure is the run's, not the tool's answer: what the handler returned could
|
|
60
|
+
// not be saved.
|
|
61
|
+
if ('outcome' in outcome) {
|
|
62
|
+
if (!tool.asks)
|
|
63
|
+
throw new BlueprintMistake(`The tool ${name} asked the person and declares no asks.`);
|
|
64
|
+
const questions = session.newQuestions({
|
|
65
|
+
questions: outcome.questions,
|
|
66
|
+
askedBy: `The tool ${name}`,
|
|
67
|
+
});
|
|
68
|
+
const saved = await save({ toolCall: { status: 'asked' }, writes: { questions } });
|
|
69
|
+
if (!(await session.answerByRecommendation({ questions })))
|
|
70
|
+
return { result: { waiting: 'The person has been asked.' }, askedPerson: true };
|
|
71
|
+
saved.result = { answers: session.answersTo({ questionIds: questions.map(({ id }) => id) }) };
|
|
72
|
+
await session.saveCallFile(callFile);
|
|
73
|
+
return { result: saved.result };
|
|
74
|
+
}
|
|
75
|
+
const { result, change, artifacts } = outcome;
|
|
76
|
+
return session.inTurn(async () => {
|
|
77
|
+
const before = session.state;
|
|
78
|
+
if (change && agent.mayChange.length) {
|
|
79
|
+
const after = fittedNextState({
|
|
80
|
+
state: before,
|
|
81
|
+
change,
|
|
82
|
+
schema: session.blueprint.runStateSchema,
|
|
83
|
+
madeBy: `The tool ${name}`,
|
|
84
|
+
});
|
|
85
|
+
const violations = blueprintCode({
|
|
86
|
+
what: `${agent.name}'s write scope`,
|
|
87
|
+
run: () => writeScopeViolations({
|
|
88
|
+
before,
|
|
89
|
+
after,
|
|
90
|
+
rules: agent.mayChange,
|
|
91
|
+
state: before,
|
|
92
|
+
subject: reads.subject,
|
|
93
|
+
}),
|
|
94
|
+
});
|
|
95
|
+
if (violations.length)
|
|
96
|
+
return failed(violations.join('\n'));
|
|
97
|
+
}
|
|
98
|
+
const writes = await session.writeArtifactsAndCheckChange({
|
|
99
|
+
change,
|
|
100
|
+
artifacts,
|
|
101
|
+
madeBy: `The tool ${name}`,
|
|
102
|
+
});
|
|
103
|
+
if (writes.change)
|
|
104
|
+
memory.stateBeforeFirstChange ??= before;
|
|
105
|
+
await save({ toolCall: { status: 'returned', result }, writes });
|
|
106
|
+
return { result };
|
|
107
|
+
});
|
|
108
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** A mistake in the blueprint's own code, as opposed to a model's reply. It fails the run. */
|
|
2
|
+
export declare class BlueprintMistake extends Error {
|
|
3
|
+
}
|
|
4
|
+
/** Runs blueprint code. Anything it throws is a mistake in the blueprint, named by `what`. */
|
|
5
|
+
export declare function blueprintCode<Result>({ what, run }: {
|
|
6
|
+
what: string;
|
|
7
|
+
run: () => Result;
|
|
8
|
+
}): Result;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** A mistake in the blueprint's own code, as opposed to a model's reply. It fails the run. */
|
|
2
|
+
export class BlueprintMistake extends Error {
|
|
3
|
+
}
|
|
4
|
+
/** Runs blueprint code. Anything it throws is a mistake in the blueprint, named by `what`. */
|
|
5
|
+
export function blueprintCode({ what, run }) {
|
|
6
|
+
try {
|
|
7
|
+
return run();
|
|
8
|
+
}
|
|
9
|
+
catch (error) {
|
|
10
|
+
if (error instanceof BlueprintMistake)
|
|
11
|
+
throw error;
|
|
12
|
+
throw new BlueprintMistake(`${what} threw: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { CodePhase } from '../blueprint/phase.js';
|
|
2
|
+
import type { RunSession } from './run-session.js';
|
|
3
|
+
/** Runs a code phase: its function, once, and again each time the person has
|
|
4
|
+
* answered what it asked. Its change and artifacts are saved by one events line, and a code
|
|
5
|
+
* phase whose result is saved is not run again. */
|
|
6
|
+
export declare function runCodePhase<State, Services = unknown>({ session, phase, place, }: {
|
|
7
|
+
session: RunSession<State, Services>;
|
|
8
|
+
phase: CodePhase<State, Services>;
|
|
9
|
+
/** The place the phase runs at: its own name on the trunk. */
|
|
10
|
+
place: string;
|
|
11
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { BlueprintMistake } from './blueprint-mistake.js';
|
|
2
|
+
import { allAnswered } from './record/progress.js';
|
|
3
|
+
import { RunWaitsForPerson } from './run-endings.js';
|
|
4
|
+
/** Runs a code phase: its function, once, and again each time the person has
|
|
5
|
+
* answered what it asked. Its change and artifacts are saved by one events line, and a code
|
|
6
|
+
* phase whose result is saved is not run again. */
|
|
7
|
+
export async function runCodePhase({ session, phase, place, }) {
|
|
8
|
+
const standing = () => (session.progress.codePhases[place] ??= { questionIds: [], accepted: false });
|
|
9
|
+
while (!standing().accepted) {
|
|
10
|
+
session.stopSignal.throwIfAborted();
|
|
11
|
+
session.drainSignal.throwIfAborted();
|
|
12
|
+
const { questionIds } = standing();
|
|
13
|
+
if (!allAnswered({ progress: session.progress, questionIds }))
|
|
14
|
+
throw new RunWaitsForPerson();
|
|
15
|
+
const started = performance.now();
|
|
16
|
+
let outcome;
|
|
17
|
+
try {
|
|
18
|
+
outcome = await phase.run({
|
|
19
|
+
state: session.state,
|
|
20
|
+
questionsAnsweredBy: session.questionsAnsweredBy,
|
|
21
|
+
artifacts: session.artifacts,
|
|
22
|
+
stopSignal: session.stopSignal,
|
|
23
|
+
answers: session.answersTo({ questionIds }),
|
|
24
|
+
services: session.services,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
if (session.stopSignal.aborted)
|
|
29
|
+
throw session.stopSignal.reason;
|
|
30
|
+
throw new BlueprintMistake(`The code phase ${phase.name} threw: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
31
|
+
}
|
|
32
|
+
if (outcome.outcome === 'asked' && !phase.asks)
|
|
33
|
+
throw new BlueprintMistake(`The code phase ${phase.name} asked the person and declares no asks.`);
|
|
34
|
+
const asked = await session.inTurn(async () => {
|
|
35
|
+
const writes = await session.writeArtifactsAndCheckChange({
|
|
36
|
+
change: outcome.change,
|
|
37
|
+
artifacts: outcome.artifacts,
|
|
38
|
+
madeBy: `The code phase ${phase.name}`,
|
|
39
|
+
});
|
|
40
|
+
const questions = outcome.outcome === 'asked'
|
|
41
|
+
? session.newQuestions({
|
|
42
|
+
questions: outcome.questions,
|
|
43
|
+
askedBy: `The code phase ${phase.name}`,
|
|
44
|
+
})
|
|
45
|
+
: [];
|
|
46
|
+
await session.record({
|
|
47
|
+
kind: 'code-phase-ended',
|
|
48
|
+
phase: place,
|
|
49
|
+
outcome: outcome.outcome,
|
|
50
|
+
durationMs: Math.round(performance.now() - started),
|
|
51
|
+
...writes,
|
|
52
|
+
...(questions.length ? { questions } : {}),
|
|
53
|
+
});
|
|
54
|
+
return questions;
|
|
55
|
+
});
|
|
56
|
+
if (asked.length)
|
|
57
|
+
await session.answerByRecommendation({ questions: asked });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type LoadedBlueprint } from '../blueprint/load-blueprint.js';
|
|
2
|
+
import type { Blueprint } from '../blueprint/phase.js';
|
|
3
|
+
import type { CallsAnsweredBy, QuestionsAnsweredBy } from '../blueprint/run-settings.js';
|
|
4
|
+
import type { Infer } from '../inference/inference.js';
|
|
5
|
+
import type { ModelOverride } from './record/events.js';
|
|
6
|
+
import type { RunStore } from './record/run-store.js';
|
|
7
|
+
import { RunSession, type RunEventObserver } from './run-session.js';
|
|
8
|
+
/** Why a run answered this way cannot start: each agent without the model settings it needs. */
|
|
9
|
+
export declare function modelSettingsProblems({ loaded, callsAnsweredBy, overrides, }: {
|
|
10
|
+
loaded: LoadedBlueprint;
|
|
11
|
+
callsAnsweredBy: CallsAnsweredBy;
|
|
12
|
+
overrides: ModelOverride[];
|
|
13
|
+
}): string[];
|
|
14
|
+
/** Creates a run in `store`: its initial summary, starting checkpoint, and first event.
|
|
15
|
+
* Accepts either a `Blueprint` value directly or a `LoadedBlueprint`. Nothing is executed yet. */
|
|
16
|
+
export declare function createRun<State = unknown, Input = unknown, Services = unknown>({ blueprint: blueprintInput, store, input, from, stopAfter, callsAnsweredBy, scriptedRepliesFile, questionsAnsweredBy, overrides, infer, services, promptFolder, readPrompt, retryWaitsMs, onEvent, }: {
|
|
17
|
+
blueprint: Blueprint<State, Input, Services> | LoadedBlueprint;
|
|
18
|
+
store: RunStore;
|
|
19
|
+
input?: Input;
|
|
20
|
+
from?: {
|
|
21
|
+
runId: string;
|
|
22
|
+
checkpoint: string;
|
|
23
|
+
};
|
|
24
|
+
stopAfter?: string;
|
|
25
|
+
callsAnsweredBy?: CallsAnsweredBy;
|
|
26
|
+
/** The replies file of a scripted run, saved so Resume finds it again. */
|
|
27
|
+
scriptedRepliesFile?: string;
|
|
28
|
+
questionsAnsweredBy: QuestionsAnsweredBy;
|
|
29
|
+
overrides?: ModelOverride[];
|
|
30
|
+
infer: Infer;
|
|
31
|
+
services?: Services;
|
|
32
|
+
promptFolder?: string;
|
|
33
|
+
readPrompt?: (path: string) => string;
|
|
34
|
+
retryWaitsMs?: number[];
|
|
35
|
+
onEvent?: RunEventObserver;
|
|
36
|
+
}): Promise<RunSession<State, Services>>;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { isLoadedBlueprint, prepareBlueprint, } from '../blueprint/load-blueprint.js';
|
|
2
|
+
import { declaredPhases, phaseAtPlace } from '../blueprint/places.js';
|
|
3
|
+
import { modelSettingsFor, modelSettingsProblem } from './assignments/model-settings.js';
|
|
4
|
+
import { blueprintCode } from './blueprint-mistake.js';
|
|
5
|
+
import { stateFittedToSchema } from './record/state-changes.js';
|
|
6
|
+
import { RunSession } from './run-session.js';
|
|
7
|
+
/** Why a run answered this way cannot start: each agent without the model settings it needs. */
|
|
8
|
+
export function modelSettingsProblems({ loaded, callsAnsweredBy, overrides, }) {
|
|
9
|
+
if (callsAnsweredBy === 'custom')
|
|
10
|
+
return [];
|
|
11
|
+
const problems = [];
|
|
12
|
+
for (const phase of declaredPhases({ blueprint: loaded.blueprint })) {
|
|
13
|
+
if (phase.kind !== 'agents')
|
|
14
|
+
continue;
|
|
15
|
+
for (const agent of phase.lanes.flatMap((lane) => lane.chain)) {
|
|
16
|
+
const problem = modelSettingsProblem({
|
|
17
|
+
settings: modelSettingsFor({
|
|
18
|
+
blueprint: loaded.blueprint.modelSettings,
|
|
19
|
+
workers: loaded.blueprint.workers,
|
|
20
|
+
phase,
|
|
21
|
+
agent,
|
|
22
|
+
overrides,
|
|
23
|
+
}),
|
|
24
|
+
callsAnsweredBy,
|
|
25
|
+
});
|
|
26
|
+
if (problem)
|
|
27
|
+
problems.push(`${agent.name} in ${phase.name} ${problem}`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return [...new Set(problems)];
|
|
31
|
+
}
|
|
32
|
+
/** Creates a run in `store`: its initial summary, starting checkpoint, and first event.
|
|
33
|
+
* Accepts either a `Blueprint` value directly or a `LoadedBlueprint`. Nothing is executed yet. */
|
|
34
|
+
export async function createRun({ blueprint: blueprintInput, store, input, from, stopAfter, callsAnsweredBy = 'custom', scriptedRepliesFile, questionsAnsweredBy, overrides = [], infer, services, promptFolder, readPrompt, retryWaitsMs, onEvent, }) {
|
|
35
|
+
const loaded = isLoadedBlueprint(blueprintInput)
|
|
36
|
+
? blueprintInput
|
|
37
|
+
: prepareBlueprint({ blueprint: blueprintInput, promptFolder, readPrompt });
|
|
38
|
+
const blueprint = loaded.blueprint;
|
|
39
|
+
const isDeclared = (name) => !!phaseAtPlace({ blueprint, name });
|
|
40
|
+
if (stopAfter && !isDeclared(stopAfter))
|
|
41
|
+
throw new Error(`The blueprint has no phase named ${stopAfter} to stop after.`);
|
|
42
|
+
const problems = modelSettingsProblems({ loaded, callsAnsweredBy, overrides });
|
|
43
|
+
if (problems.length)
|
|
44
|
+
throw new Error(`The run cannot start on ${callsAnsweredBy}:\n- ${problems.join('\n- ')}`);
|
|
45
|
+
let start;
|
|
46
|
+
let savedInput;
|
|
47
|
+
if (from) {
|
|
48
|
+
const checkpoint = await store.readCheckpoint({ runId: from.runId, name: from.checkpoint });
|
|
49
|
+
if (!checkpoint)
|
|
50
|
+
throw new Error(`Run ${from.runId} has no checkpoint named ${from.checkpoint}.`);
|
|
51
|
+
if (checkpoint.phase && !isDeclared(checkpoint.phase))
|
|
52
|
+
throw new Error(`The checkpoint's phase ${checkpoint.phase} is no longer in the blueprint.`);
|
|
53
|
+
const state = stateFittedToSchema({
|
|
54
|
+
state: checkpoint.state,
|
|
55
|
+
schema: blueprint.runStateSchema,
|
|
56
|
+
madeBy: `The checkpoint ${from.checkpoint}`,
|
|
57
|
+
});
|
|
58
|
+
start = { ...checkpoint, number: 0, state };
|
|
59
|
+
savedInput = await store.readInput({ runId: from.runId });
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
const parsed = blueprint.input.safeParse(input);
|
|
63
|
+
if (!parsed.success)
|
|
64
|
+
throw new Error(`The input does not fit the blueprint's input shape: ${parsed.error.issues
|
|
65
|
+
.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`)
|
|
66
|
+
.join('; ')}`);
|
|
67
|
+
const state = blueprintCode({
|
|
68
|
+
what: `${blueprint.name}'s startingState`,
|
|
69
|
+
run: () => blueprint.startingState.from({ input: parsed.data }),
|
|
70
|
+
});
|
|
71
|
+
start = {
|
|
72
|
+
number: 0,
|
|
73
|
+
state: stateFittedToSchema({
|
|
74
|
+
state: JSON.parse(JSON.stringify(state)),
|
|
75
|
+
schema: blueprint.runStateSchema,
|
|
76
|
+
madeBy: 'startingState',
|
|
77
|
+
}),
|
|
78
|
+
artifacts: {},
|
|
79
|
+
sideLineVisits: {},
|
|
80
|
+
finishedAssignments: {},
|
|
81
|
+
};
|
|
82
|
+
savedInput = input;
|
|
83
|
+
}
|
|
84
|
+
const runId = await store.createRunId();
|
|
85
|
+
const session = new RunSession({
|
|
86
|
+
runId,
|
|
87
|
+
store,
|
|
88
|
+
blueprint,
|
|
89
|
+
promptFiles: loaded.promptFiles,
|
|
90
|
+
infer,
|
|
91
|
+
services,
|
|
92
|
+
retryWaitsMs,
|
|
93
|
+
start,
|
|
94
|
+
events: [],
|
|
95
|
+
onEvent,
|
|
96
|
+
});
|
|
97
|
+
// Insert the parent run row before writing checkpoints, structures, and events.
|
|
98
|
+
await session.saveSummary({ input: savedInput });
|
|
99
|
+
await store.writeCheckpoint({ runId, checkpoint: start });
|
|
100
|
+
const structureFile = await store.writeStructure({
|
|
101
|
+
runId,
|
|
102
|
+
number: 1,
|
|
103
|
+
structure: loaded.structure,
|
|
104
|
+
});
|
|
105
|
+
await session.record({
|
|
106
|
+
kind: 'run-started',
|
|
107
|
+
blueprint: blueprint.name,
|
|
108
|
+
blueprintHash: loaded.hash,
|
|
109
|
+
structureFile,
|
|
110
|
+
callsAnsweredBy,
|
|
111
|
+
...(scriptedRepliesFile ? { scriptedRepliesFile } : {}),
|
|
112
|
+
questionsAnsweredBy,
|
|
113
|
+
overrides,
|
|
114
|
+
...(from ? { startedFrom: from } : {}),
|
|
115
|
+
...(stopAfter ? { stopAfter } : {}),
|
|
116
|
+
});
|
|
117
|
+
await session.saveSummary();
|
|
118
|
+
return session;
|
|
119
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { RunStatus } from './record/progress.js';
|
|
2
|
+
import type { RunSession } from './run-session.js';
|
|
3
|
+
/** Executes a run from where it stands until it finishes, waits for the person, is stopped or
|
|
4
|
+
* fails. Returns the status it ended with. */
|
|
5
|
+
export declare function executeRun<State, Services = unknown>({ session, }: {
|
|
6
|
+
session: RunSession<State, Services>;
|
|
7
|
+
}): Promise<RunStatus>;
|