@ftrdotdev/pi-delegates 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/CHANGELOG.md +77 -0
- package/LICENSE +21 -0
- package/OPERATIONS.md +57 -0
- package/README.md +448 -2
- package/ROADMAP.md +158 -0
- package/TESTING.md +1061 -0
- package/agents.ts +8 -0
- package/examples/README.md +114 -0
- package/examples/gated.ts +28 -0
- package/index.ts +9 -0
- package/package.json +93 -4
- package/skills/pi-delegates/SKILL.md +147 -0
- package/skills/pi-delegates/references/control.md +159 -0
- package/skills/pi-delegates/references/definitions.md +163 -0
- package/skills/pi-delegates/references/gates.md +175 -0
- package/skills/pi-delegates/references/launch.md +156 -0
- package/src/domain/definitions.test.ts +41 -0
- package/src/domain/definitions.ts +161 -0
- package/src/domain/ids.ts +13 -0
- package/src/domain/names.ts +35 -0
- package/src/domain/orchestration/admission.ts +78 -0
- package/src/domain/orchestration/control.test.ts +1298 -0
- package/src/domain/orchestration/control.ts +436 -0
- package/src/domain/orchestration/fanout.test.ts +419 -0
- package/src/domain/orchestration/fanout.ts +334 -0
- package/src/domain/orchestration/gates.test.ts +686 -0
- package/src/domain/orchestration/gates.ts +360 -0
- package/src/domain/orchestration/launch.test.ts +173 -0
- package/src/domain/orchestration/launch.ts +581 -0
- package/src/domain/orchestration/requests.test.ts +700 -0
- package/src/domain/orchestration/requests.ts +769 -0
- package/src/domain/orchestration/review.test.ts +214 -0
- package/src/domain/orchestration/review.ts +168 -0
- package/src/domain/orchestration/run-wait.test.ts +262 -0
- package/src/domain/orchestration/run-wait.ts +256 -0
- package/src/domain/orchestration/workflow-section.test.ts +62 -0
- package/src/domain/orchestration/workflow-section.ts +99 -0
- package/src/domain/orchestration/workflow.test.ts +1425 -0
- package/src/domain/orchestration/workflow.ts +705 -0
- package/src/domain/run-records.test.ts +27 -0
- package/src/domain/run-records.ts +527 -0
- package/src/domain/shapes.test.ts +165 -0
- package/src/domain/skills.test.ts +466 -0
- package/src/domain/skills.ts +97 -0
- package/src/domain/tool-schema.test.ts +46 -0
- package/src/domain/tool-schema.ts +20 -0
- package/src/domain/toolkit.test.ts +201 -0
- package/src/domain/toolkit.ts +379 -0
- package/src/domain/view.test.ts +739 -0
- package/src/domain/view.ts +459 -0
- package/src/example.test.ts +15 -0
- package/src/extension/commands.test.ts +481 -0
- package/src/extension/commands.ts +227 -0
- package/src/extension/entry.test.ts +1118 -0
- package/src/extension/entry.ts +342 -0
- package/src/extension/gate-alerts.test.ts +235 -0
- package/src/extension/gate-alerts.ts +143 -0
- package/src/extension/guard.test.ts +48 -0
- package/src/extension/guard.ts +31 -0
- package/src/extension/host-signals.test.ts +20 -0
- package/src/extension/host-signals.ts +13 -0
- package/src/extension/inspector-command.test.ts +1191 -0
- package/src/extension/inspector-command.ts +638 -0
- package/src/extension/prompt.test.ts +110 -0
- package/src/extension/prompt.ts +50 -0
- package/src/extension/request-alerts.test.ts +183 -0
- package/src/extension/request-alerts.ts +181 -0
- package/src/extension/revocation.test.ts +81 -0
- package/src/extension/revocation.ts +84 -0
- package/src/extension/shortcut.test.ts +64 -0
- package/src/extension/shortcut.ts +105 -0
- package/src/extension/tools.test.ts +993 -0
- package/src/extension/tools.ts +505 -0
- package/src/extension/version.test.ts +123 -0
- package/src/extension/version.ts +97 -0
- package/src/harness-policy.test.ts +74 -0
- package/src/package-manifest.test.ts +157 -0
- package/src/presentation/actions.test.ts +221 -0
- package/src/presentation/actions.ts +85 -0
- package/src/presentation/activity.test.ts +387 -0
- package/src/presentation/activity.ts +66 -0
- package/src/presentation/close.test.ts +361 -0
- package/src/presentation/inspector.test.ts +679 -0
- package/src/presentation/inspector.ts +440 -0
- package/src/presentation/overlay.test.ts +555 -0
- package/src/presentation/overlay.ts +229 -0
- package/src/presentation/repaint.test.ts +329 -0
- package/src/presentation/shortcut.ts +2 -0
- package/src/presentation/snapshot.test.ts +530 -0
- package/src/presentation/snapshot.ts +306 -0
- package/src/presentation/strip.test.ts +196 -0
- package/src/presentation/strip.ts +74 -0
- package/src/presentation/wording.test.ts +238 -0
- package/src/presentation/wording.ts +222 -0
- package/src/runtime/bridge.test.ts +131 -0
- package/src/runtime/bridge.ts +134 -0
- package/src/runtime/config.test.ts +44 -0
- package/src/runtime/config.ts +87 -0
- package/src/runtime/context.test.ts +19 -0
- package/src/runtime/context.ts +9 -0
- package/src/runtime/execution-env.test.ts +35 -0
- package/src/runtime/execution-env.ts +15 -0
- package/src/runtime/extensions.test.ts +86 -0
- package/src/runtime/extensions.ts +140 -0
- package/src/runtime/log.test.ts +128 -0
- package/src/runtime/log.ts +68 -0
- package/src/runtime/mcp.test.ts +1453 -0
- package/src/runtime/mcp.ts +938 -0
- package/src/runtime/models.test.ts +145 -0
- package/src/runtime/models.ts +259 -0
- package/src/runtime/observe.test.ts +50 -0
- package/src/runtime/observe.ts +150 -0
- package/src/runtime/session.test.ts +359 -0
- package/src/runtime/session.ts +425 -0
- package/src/runtime/timers.test.ts +31 -0
- package/src/runtime/timers.ts +10 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { assert, it } from "@effect/vitest";
|
|
2
|
+
import { PROPERTY_RUNS } from "@ftrdotdev/pi-test-kit";
|
|
3
|
+
import { attemptListArbitrary } from "../../test-support/arbitraries.ts";
|
|
4
|
+
import { nextAttempt } from "./run-records.ts";
|
|
5
|
+
|
|
6
|
+
it.prop(
|
|
7
|
+
"attempt numbering is the next after every recorded one",
|
|
8
|
+
{
|
|
9
|
+
attempts: attemptListArbitrary,
|
|
10
|
+
},
|
|
11
|
+
({ attempts }) => {
|
|
12
|
+
const next = nextAttempt(attempts.map((attempt) => ({ attempt })));
|
|
13
|
+
assert.ok(next >= 1);
|
|
14
|
+
const highest = attempts.reduce((value, attempt) => Math.max(value, attempt), 0);
|
|
15
|
+
assert.strictEqual(next, highest + 1);
|
|
16
|
+
for (const attempt of attempts) assert.ok(next > attempt);
|
|
17
|
+
assert.strictEqual(
|
|
18
|
+
nextAttempt([...attempts.map((attempt) => ({ attempt })), { attempt: next }]),
|
|
19
|
+
next + 1,
|
|
20
|
+
);
|
|
21
|
+
},
|
|
22
|
+
{ arbitrary: { runs: PROPERTY_RUNS } },
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
it("an empty attempt list starts at one", () => {
|
|
26
|
+
assert.strictEqual(nextAttempt([]), 1);
|
|
27
|
+
});
|
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
import type { AssistantMessage, Message } from "@earendil-works/pi-ai";
|
|
2
|
+
import { MODEL_THINKING_LEVELS } from "@earendil-works/pi-ai/providers/model-schema";
|
|
3
|
+
import {
|
|
4
|
+
defineDoc,
|
|
5
|
+
defineDocFamily,
|
|
6
|
+
defineTask,
|
|
7
|
+
SubmissionSettled,
|
|
8
|
+
type JsonObject,
|
|
9
|
+
type RegistrySnapshot,
|
|
10
|
+
type RunningTask,
|
|
11
|
+
type TaskRecord,
|
|
12
|
+
type TaskRuntime,
|
|
13
|
+
type Tx,
|
|
14
|
+
} from "@earendil-works/pi-durable";
|
|
15
|
+
import { Effect, Option, Schema } from "effect";
|
|
16
|
+
import type { DelegatesConfig } from "../runtime/config.ts";
|
|
17
|
+
import { AgentDefinition } from "./definitions.ts";
|
|
18
|
+
import { available, liveCounts, type AdmissionHost } from "./orchestration/admission.ts";
|
|
19
|
+
import {
|
|
20
|
+
bindToolkit,
|
|
21
|
+
createBoundChild,
|
|
22
|
+
conversationNumber,
|
|
23
|
+
type McpServerTools,
|
|
24
|
+
type ToolkitResolver,
|
|
25
|
+
} from "./toolkit.ts";
|
|
26
|
+
import type { Context } from "@earendil-works/chord/context";
|
|
27
|
+
import { conversationId, taskId } from "./ids.ts";
|
|
28
|
+
import { reasonOf } from "../runtime/log.ts";
|
|
29
|
+
import type { SkillsService } from "./skills.ts";
|
|
30
|
+
import type { McpPresence } from "../runtime/mcp.ts";
|
|
31
|
+
import { GateDoc, GateIndexDoc, type GateRecord } from "./orchestration/gates.ts";
|
|
32
|
+
import { RequestDoc, RequestIndexDoc, type RequestRecord } from "./orchestration/requests.ts";
|
|
33
|
+
|
|
34
|
+
export const RunMode = Schema.Literals(["single", "fanout", "review", "workflow"]);
|
|
35
|
+
export type RunMode = typeof RunMode.Type;
|
|
36
|
+
|
|
37
|
+
export const RunMetadata = Schema.Struct({
|
|
38
|
+
definition: Schema.String,
|
|
39
|
+
mode: RunMode,
|
|
40
|
+
lane: Schema.String,
|
|
41
|
+
requestedAgent: Schema.String,
|
|
42
|
+
task: Schema.String,
|
|
43
|
+
requestId: Schema.String,
|
|
44
|
+
attempt: Schema.Finite,
|
|
45
|
+
childConversationId: Schema.NullOr(Schema.Finite),
|
|
46
|
+
taskId: Schema.NullOr(Schema.Finite),
|
|
47
|
+
gateRunId: Schema.String,
|
|
48
|
+
/** The run that launched this one: a fanout group or a workflow. `null` for a root run. */
|
|
49
|
+
parentRunId: Schema.NullOr(Schema.String),
|
|
50
|
+
childRunIds: Schema.Array(Schema.String),
|
|
51
|
+
diagnostics: Schema.Array(Schema.String),
|
|
52
|
+
});
|
|
53
|
+
export type RunMetadata = typeof RunMetadata.Type;
|
|
54
|
+
|
|
55
|
+
export interface RunDocSeed {
|
|
56
|
+
readonly definition: string;
|
|
57
|
+
/** Absent: `single`. */
|
|
58
|
+
readonly mode?: RunMode;
|
|
59
|
+
readonly lane: string;
|
|
60
|
+
/** Absent: a root run. */
|
|
61
|
+
readonly parentRunId?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const VERSION_WITH_MODE = 2;
|
|
65
|
+
|
|
66
|
+
/** One migration: version 1 may predate the run mode and the parent run id, or already carry them. */
|
|
67
|
+
export const migrateRun = (value: JsonObject, fromVersion: number): RunMetadata & JsonObject =>
|
|
68
|
+
({
|
|
69
|
+
...value,
|
|
70
|
+
...(fromVersion < VERSION_WITH_MODE
|
|
71
|
+
? { mode: value.mode ?? "single", parentRunId: value.parentRunId ?? null }
|
|
72
|
+
: {}),
|
|
73
|
+
}) as unknown as RunMetadata & JsonObject;
|
|
74
|
+
|
|
75
|
+
export const RunDoc = defineDocFamily<RunMetadata & JsonObject, RunDocSeed & JsonObject>({
|
|
76
|
+
kind: "delegates.run",
|
|
77
|
+
version: VERSION_WITH_MODE,
|
|
78
|
+
scope: "session",
|
|
79
|
+
family: true,
|
|
80
|
+
initial: (seed) => ({
|
|
81
|
+
definition: seed.definition,
|
|
82
|
+
mode: seed.mode ?? "single",
|
|
83
|
+
lane: seed.lane,
|
|
84
|
+
requestedAgent: "",
|
|
85
|
+
task: "",
|
|
86
|
+
requestId: "",
|
|
87
|
+
attempt: 1,
|
|
88
|
+
childConversationId: null,
|
|
89
|
+
taskId: null,
|
|
90
|
+
gateRunId: "",
|
|
91
|
+
parentRunId: seed.parentRunId ?? null,
|
|
92
|
+
childRunIds: [],
|
|
93
|
+
diagnostics: [],
|
|
94
|
+
}),
|
|
95
|
+
migrate: migrateRun,
|
|
96
|
+
checkpointWhen: () => true,
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
/** The session's run ids, in creation order; the only enumeration a viewer needs. */
|
|
100
|
+
export const RunIndexDoc = defineDoc<{ runIds: string[] } & JsonObject>({
|
|
101
|
+
kind: "delegates.run-index",
|
|
102
|
+
version: 1,
|
|
103
|
+
scope: "session",
|
|
104
|
+
initial: () => ({ runIds: [] }),
|
|
105
|
+
checkpointWhen: () => true,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
/** The stored host defaults; the levels are pi-ai's own runtime list, never a copy. */
|
|
109
|
+
export const HostDefaultsSchema = Schema.Struct({
|
|
110
|
+
model: Schema.Struct({ provider: Schema.String, modelId: Schema.String }),
|
|
111
|
+
thinkingLevel: Schema.Literals(MODEL_THINKING_LEVELS),
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
export const RunInputSchema = Schema.Struct({
|
|
115
|
+
runId: Schema.String,
|
|
116
|
+
/** The launch run that owns gates: the run id itself, or a fanout parent's id. */
|
|
117
|
+
gateRunId: Schema.String,
|
|
118
|
+
requestId: Schema.String,
|
|
119
|
+
attempt: Schema.Finite,
|
|
120
|
+
definition: AgentDefinition,
|
|
121
|
+
task: Schema.String,
|
|
122
|
+
host: HostDefaultsSchema,
|
|
123
|
+
lane: Schema.String,
|
|
124
|
+
maxTurns: Schema.Finite,
|
|
125
|
+
/** The key of this task's submission; a resume uses a fresh one so it continues the child. */
|
|
126
|
+
submissionKey: Schema.String,
|
|
127
|
+
});
|
|
128
|
+
export type RunInput = typeof RunInputSchema.Type;
|
|
129
|
+
|
|
130
|
+
export const RunResultSchema = Schema.Union([
|
|
131
|
+
Schema.Struct({ status: Schema.Literal("answered"), answer: Schema.String }),
|
|
132
|
+
Schema.Struct({ status: Schema.Literal("failed"), diagnostic: Schema.String }),
|
|
133
|
+
Schema.Struct({
|
|
134
|
+
status: Schema.Literal("denied"),
|
|
135
|
+
/** Names the request or gate that was refused, when one is known. */
|
|
136
|
+
diagnostic: Schema.optional(Schema.String),
|
|
137
|
+
}),
|
|
138
|
+
Schema.Struct({ status: Schema.Literal("stopped") }),
|
|
139
|
+
]);
|
|
140
|
+
export type RunResult = typeof RunResultSchema.Type;
|
|
141
|
+
|
|
142
|
+
/** A stored outcome result as the run result it claims to be; a malformed value reads as absent. */
|
|
143
|
+
export const runResultOf = (value: unknown): RunResult | undefined =>
|
|
144
|
+
Option.getOrUndefined(Schema.decodeUnknownOption(RunResultSchema)(value));
|
|
145
|
+
|
|
146
|
+
export type RunState =
|
|
147
|
+
| { readonly phase: "bind"; readonly input: RunInput }
|
|
148
|
+
| {
|
|
149
|
+
readonly phase: "submit";
|
|
150
|
+
readonly input: RunInput;
|
|
151
|
+
readonly childId: number;
|
|
152
|
+
}
|
|
153
|
+
| {
|
|
154
|
+
readonly phase: "settle";
|
|
155
|
+
readonly input: RunInput;
|
|
156
|
+
readonly childId: number;
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
type RunHooks = Record<never, never>;
|
|
160
|
+
|
|
161
|
+
/** The text of the last assistant answer in a context. */
|
|
162
|
+
export const answerText = (messages: readonly Message[]): string => {
|
|
163
|
+
const last = [...messages]
|
|
164
|
+
.reverse()
|
|
165
|
+
.find((message): message is AssistantMessage => message.role === "assistant");
|
|
166
|
+
return (last?.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("");
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
/** Resolves toolkit names against the phase's registry snapshot and the runtime's catalogue. */
|
|
170
|
+
export const resolverFor = (deps: {
|
|
171
|
+
readonly registry: RegistrySnapshot;
|
|
172
|
+
readonly skills: SkillsService;
|
|
173
|
+
/** The runtime's MCP presence; absent in a read-only viewer, which connects to nothing. */
|
|
174
|
+
readonly presence?: McpPresence;
|
|
175
|
+
}): ToolkitResolver => {
|
|
176
|
+
const installed = deps.registry.installed();
|
|
177
|
+
const tools = deps.registry.tools();
|
|
178
|
+
const availableTools = tools.map((entry) => entry.tool.name);
|
|
179
|
+
const mcpServers: McpServerTools[] = installed.flatMap((extension) => {
|
|
180
|
+
const namespace = extension.namespace;
|
|
181
|
+
// A server extension always has one namespace; a snapshot entry without it is not a server.
|
|
182
|
+
if (!extension.name.startsWith("mcp:") || namespace === undefined) return [];
|
|
183
|
+
return [
|
|
184
|
+
{
|
|
185
|
+
extension: extension.name,
|
|
186
|
+
namespace: namespace.name,
|
|
187
|
+
tools: (extension.tools ?? []).map((tool) => tool.name),
|
|
188
|
+
},
|
|
189
|
+
];
|
|
190
|
+
});
|
|
191
|
+
return {
|
|
192
|
+
availableExtensions: installed.map((extension) => extension.name),
|
|
193
|
+
availableTools,
|
|
194
|
+
availableSkills: deps.skills.all().map((skill) => skill.name),
|
|
195
|
+
extension: (name) => deps.registry.extension(name),
|
|
196
|
+
tool: (name) => tools.find((entry) => entry.tool.name === name)?.tool,
|
|
197
|
+
skill: deps.skills.find,
|
|
198
|
+
mcpServers,
|
|
199
|
+
// A codemode-exposed MCP tool is callable from scripts only, so `callers` names `tools`.
|
|
200
|
+
codemodeTools: tools
|
|
201
|
+
.filter((entry) => {
|
|
202
|
+
if (!entry.extension.name.startsWith("mcp:")) return false;
|
|
203
|
+
const callers = entry.tool.callers ?? ["model", "tools"];
|
|
204
|
+
return callers.includes("tools") && !callers.includes("model");
|
|
205
|
+
})
|
|
206
|
+
.map((entry) => entry.tool.name),
|
|
207
|
+
unconnected: deps.presence?.unconnected,
|
|
208
|
+
matchTools: (pattern) => {
|
|
209
|
+
const star = pattern.indexOf("*");
|
|
210
|
+
const prefix = pattern.slice(0, star);
|
|
211
|
+
const suffix = pattern.slice(star + 1);
|
|
212
|
+
return availableTools.filter((name) => name.startsWith(prefix) && name.endsWith(suffix));
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const failed = (diagnostic: string): RunResult => ({ status: "failed", diagnostic });
|
|
218
|
+
|
|
219
|
+
const bind = async (
|
|
220
|
+
task: RunningTask<RunInput, Extract<RunState, { phase: "bind" }>, RunResult>,
|
|
221
|
+
runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
|
|
222
|
+
context: Context,
|
|
223
|
+
admission: AdmissionHost,
|
|
224
|
+
skills: SkillsService,
|
|
225
|
+
mcpPresence: () => McpPresence | undefined,
|
|
226
|
+
): Promise<void> => {
|
|
227
|
+
const inspection = await admission.inspect();
|
|
228
|
+
const ownedTasks = await runtime.ownedTasks(context);
|
|
229
|
+
const counts = liveCounts(inspection, task.input.lane, {
|
|
230
|
+
excludeTaskId: runtime.taskId,
|
|
231
|
+
ownedTasks,
|
|
232
|
+
});
|
|
233
|
+
const caps = admission.caps();
|
|
234
|
+
if (available(caps.laneCap, counts.laneLive, caps.sessionCeiling, counts.sessionLive) <= 0) {
|
|
235
|
+
await runtime.commit(
|
|
236
|
+
() => ({
|
|
237
|
+
status: "sleeping",
|
|
238
|
+
until: runtime.now() + admission.pollMs,
|
|
239
|
+
checkpoint: task.state.checkpoint,
|
|
240
|
+
}),
|
|
241
|
+
context,
|
|
242
|
+
);
|
|
243
|
+
return;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Launch-time binding reads the live registry, not a snapshot: the task needs
|
|
247
|
+
// the phase's own view. A view builds one `registry.snapshot()` instead.
|
|
248
|
+
const presence = mcpPresence();
|
|
249
|
+
const resolver = resolverFor({
|
|
250
|
+
registry: runtime.registry,
|
|
251
|
+
skills,
|
|
252
|
+
...(presence === undefined ? {} : { presence }),
|
|
253
|
+
});
|
|
254
|
+
let bound;
|
|
255
|
+
try {
|
|
256
|
+
bound = await Effect.runPromise(bindToolkit(task.input.definition, resolver));
|
|
257
|
+
} catch (error) {
|
|
258
|
+
const diagnostic = reasonOf(error);
|
|
259
|
+
await runtime.commit(
|
|
260
|
+
() => ({
|
|
261
|
+
status: "terminal",
|
|
262
|
+
outcome: {
|
|
263
|
+
status: "failed",
|
|
264
|
+
error: { message: diagnostic },
|
|
265
|
+
result: failed(diagnostic),
|
|
266
|
+
},
|
|
267
|
+
}),
|
|
268
|
+
context,
|
|
269
|
+
);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
await runtime.commit(async (tx) => {
|
|
274
|
+
const seed = { definition: task.input.definition.name, lane: task.input.lane };
|
|
275
|
+
const doc = await tx.doc(RunDoc, task.input.runId, seed);
|
|
276
|
+
if (doc.childConversationId !== null) {
|
|
277
|
+
return {
|
|
278
|
+
status: "running",
|
|
279
|
+
checkpoint: { phase: "submit", input: task.input, childId: doc.childConversationId },
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
const child = await createBoundChild(
|
|
283
|
+
tx,
|
|
284
|
+
task.input.gateRunId,
|
|
285
|
+
task.input.runId,
|
|
286
|
+
runtime.taskId,
|
|
287
|
+
bound,
|
|
288
|
+
task.input.definition,
|
|
289
|
+
task.input.maxTurns,
|
|
290
|
+
);
|
|
291
|
+
doc.childConversationId = conversationNumber(child.id);
|
|
292
|
+
return {
|
|
293
|
+
status: "running",
|
|
294
|
+
checkpoint: { phase: "submit", input: task.input, childId: conversationNumber(child.id) },
|
|
295
|
+
};
|
|
296
|
+
}, context);
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
const submit = async (
|
|
300
|
+
task: RunningTask<RunInput, Extract<RunState, { phase: "submit" }>, RunResult>,
|
|
301
|
+
runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
|
|
302
|
+
context: Context,
|
|
303
|
+
): Promise<void> => {
|
|
304
|
+
const conversation = await runtime.conversation(
|
|
305
|
+
conversationId(task.state.checkpoint.childId),
|
|
306
|
+
context,
|
|
307
|
+
);
|
|
308
|
+
if (conversation === undefined) {
|
|
309
|
+
const diagnostic = "child conversation is missing";
|
|
310
|
+
await runtime.commit(
|
|
311
|
+
() => ({
|
|
312
|
+
status: "terminal",
|
|
313
|
+
outcome: {
|
|
314
|
+
status: "failed",
|
|
315
|
+
error: { message: diagnostic },
|
|
316
|
+
result: failed(diagnostic),
|
|
317
|
+
},
|
|
318
|
+
}),
|
|
319
|
+
context,
|
|
320
|
+
);
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
await conversation.submit(
|
|
324
|
+
{
|
|
325
|
+
type: "input",
|
|
326
|
+
content: task.input.task,
|
|
327
|
+
requestId: task.input.submissionKey,
|
|
328
|
+
notify: { taskId: runtime.taskId, key: task.input.submissionKey },
|
|
329
|
+
},
|
|
330
|
+
context,
|
|
331
|
+
);
|
|
332
|
+
await runtime.commit(
|
|
333
|
+
() => ({
|
|
334
|
+
status: "sleeping",
|
|
335
|
+
signals: [SubmissionSettled.key(task.input.submissionKey)],
|
|
336
|
+
checkpoint: { phase: "settle", input: task.input, childId: task.state.checkpoint.childId },
|
|
337
|
+
}),
|
|
338
|
+
context,
|
|
339
|
+
);
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* The newest request of one run, from the index. The `ask` tool wakes on a
|
|
344
|
+
* decline with an error; a child that then finishes would settle `answered`
|
|
345
|
+
* and hide the refusal, so a run whose newest request is declined settles
|
|
346
|
+
* `denied` with the request named, like a denied gate.
|
|
347
|
+
*/
|
|
348
|
+
const newestRequest = async (
|
|
349
|
+
runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
|
|
350
|
+
runId: string,
|
|
351
|
+
context: Context,
|
|
352
|
+
): Promise<RequestRecord | undefined> => {
|
|
353
|
+
const index = await runtime.snapshot(RequestIndexDoc, context);
|
|
354
|
+
let newest: RequestRecord | undefined;
|
|
355
|
+
for (const row of index?.rows ?? []) {
|
|
356
|
+
if (row.runId !== runId) continue;
|
|
357
|
+
const record = await runtime.snapshot(RequestDoc, row.key, context);
|
|
358
|
+
if (record === undefined) continue;
|
|
359
|
+
if (record.runId !== runId && record.childRunId !== runId) continue;
|
|
360
|
+
if (newest === undefined || record.requestedAt >= newest.requestedAt) newest = record;
|
|
361
|
+
}
|
|
362
|
+
return newest;
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
const declinedAtSettle = async (
|
|
366
|
+
runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
|
|
367
|
+
runId: string,
|
|
368
|
+
context: Context,
|
|
369
|
+
): Promise<boolean> => {
|
|
370
|
+
const newest = await newestRequest(runtime, runId, context);
|
|
371
|
+
return newest?.status === "cancelled" && newest.reason === "declined";
|
|
372
|
+
};
|
|
373
|
+
|
|
374
|
+
const settle = async (
|
|
375
|
+
task: RunningTask<RunInput, Extract<RunState, { phase: "settle" }>, RunResult>,
|
|
376
|
+
runtime: TaskRuntime<RunInput, RunState, RunResult, RunHooks>,
|
|
377
|
+
context: Context,
|
|
378
|
+
): Promise<void> => {
|
|
379
|
+
const signal = await runtime.readSignal(SubmissionSettled, task.input.submissionKey, context);
|
|
380
|
+
let result: RunResult;
|
|
381
|
+
if (signal === undefined || "expired" in signal) {
|
|
382
|
+
result = failed("missing_settlement");
|
|
383
|
+
} else {
|
|
384
|
+
const record = signal.value;
|
|
385
|
+
if (record.status === "done") {
|
|
386
|
+
if (await declinedAtSettle(runtime, task.input.runId, context)) {
|
|
387
|
+
const declined = await newestRequest(runtime, task.input.runId, context);
|
|
388
|
+
result = {
|
|
389
|
+
status: "denied",
|
|
390
|
+
...(declined === undefined
|
|
391
|
+
? {}
|
|
392
|
+
: { diagnostic: `request ${declined.requestId} was declined` }),
|
|
393
|
+
};
|
|
394
|
+
} else {
|
|
395
|
+
const view = await runtime.context(conversationId(task.state.checkpoint.childId), context);
|
|
396
|
+
result = { status: "answered", answer: answerText(view.messages) };
|
|
397
|
+
}
|
|
398
|
+
} else {
|
|
399
|
+
const gateIndex = await runtime.snapshot(GateIndexDoc, context);
|
|
400
|
+
const gates: GateRecord[] = [];
|
|
401
|
+
for (const key of gateIndex?.keys ?? []) {
|
|
402
|
+
const gate = await runtime.snapshot(GateDoc, key, context);
|
|
403
|
+
if (
|
|
404
|
+
gate !== undefined &&
|
|
405
|
+
gate.runId === task.input.gateRunId &&
|
|
406
|
+
(gate.childRunIds ?? []).includes(task.input.runId)
|
|
407
|
+
) {
|
|
408
|
+
gates.push(gate);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const last = gates.reduce<GateRecord | undefined>(
|
|
412
|
+
(latest, gate) =>
|
|
413
|
+
latest === undefined || gate.requestedAt >= latest.requestedAt ? gate : latest,
|
|
414
|
+
undefined,
|
|
415
|
+
);
|
|
416
|
+
result =
|
|
417
|
+
last?.status === "denied" ? { status: "denied" } : failed(record.reason ?? "unanswered");
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
await runtime.commit(
|
|
421
|
+
() =>
|
|
422
|
+
result.status === "failed"
|
|
423
|
+
? {
|
|
424
|
+
status: "terminal",
|
|
425
|
+
outcome: {
|
|
426
|
+
status: "failed",
|
|
427
|
+
error: { message: result.diagnostic },
|
|
428
|
+
result,
|
|
429
|
+
},
|
|
430
|
+
}
|
|
431
|
+
: { status: "terminal", outcome: { status: "completed", result } },
|
|
432
|
+
context,
|
|
433
|
+
);
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
export const createRunTask = (
|
|
437
|
+
admission: AdmissionHost,
|
|
438
|
+
skills: SkillsService,
|
|
439
|
+
/** The runtime's MCP presence, read at each bind; absent in a read-only runtime. */
|
|
440
|
+
mcpPresence: () => McpPresence | undefined = () => undefined,
|
|
441
|
+
) =>
|
|
442
|
+
defineTask<RunInput, RunState, RunResult, RunHooks>({
|
|
443
|
+
name: "delegates.run",
|
|
444
|
+
version: 1,
|
|
445
|
+
initial: (input) => ({ phase: "bind", input }),
|
|
446
|
+
phases: {
|
|
447
|
+
bind: (task, runtime, context) =>
|
|
448
|
+
bind(task, runtime, context, admission, skills, mcpPresence),
|
|
449
|
+
submit,
|
|
450
|
+
settle,
|
|
451
|
+
},
|
|
452
|
+
abort: async (_task, runtime, context) =>
|
|
453
|
+
runtime.commit(
|
|
454
|
+
() => ({
|
|
455
|
+
status: "terminal",
|
|
456
|
+
outcome: { status: "aborted", reason: "stopped", result: { status: "stopped" } },
|
|
457
|
+
}),
|
|
458
|
+
context,
|
|
459
|
+
),
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
export interface LaunchIndexAttempt {
|
|
463
|
+
readonly runId: string;
|
|
464
|
+
readonly attempt: number;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Session family: `requestId` → its committed attempts. */
|
|
468
|
+
export const LaunchIndexDoc = defineDocFamily<
|
|
469
|
+
{ attempts: LaunchIndexAttempt[] } & JsonObject,
|
|
470
|
+
{ readonly requestId: string } & JsonObject
|
|
471
|
+
>({
|
|
472
|
+
kind: "delegates.launch-index",
|
|
473
|
+
version: 1,
|
|
474
|
+
scope: "session",
|
|
475
|
+
family: true,
|
|
476
|
+
initial: () => ({ attempts: [] }),
|
|
477
|
+
checkpointWhen: () => true,
|
|
478
|
+
});
|
|
479
|
+
|
|
480
|
+
export interface LaunchClaim {
|
|
481
|
+
readonly runId: string;
|
|
482
|
+
readonly attempt: number;
|
|
483
|
+
readonly reuseTaskId?: number;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** The next attempt after every recorded one; pure, so it can be property-tested. */
|
|
487
|
+
export const nextAttempt = (attempts: readonly { readonly attempt: number }[]): number =>
|
|
488
|
+
attempts.reduce((highest, entry) => Math.max(highest, entry.attempt), 0) + 1;
|
|
489
|
+
|
|
490
|
+
const isReusable = (task: TaskRecord<unknown, unknown, unknown> | undefined): boolean =>
|
|
491
|
+
task !== undefined && task.state.status !== "terminal";
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Reuses an unfinished run for the same identity; otherwise returns the next attempt. A terminal
|
|
495
|
+
* run, failed included, never shadows a retry.
|
|
496
|
+
*/
|
|
497
|
+
export const claimLaunch = async (
|
|
498
|
+
tx: Tx,
|
|
499
|
+
identity: {
|
|
500
|
+
readonly requestId: string;
|
|
501
|
+
readonly definition: string;
|
|
502
|
+
readonly lane: string;
|
|
503
|
+
readonly seed: RunDocSeed & JsonObject;
|
|
504
|
+
},
|
|
505
|
+
): Promise<LaunchClaim> => {
|
|
506
|
+
const index = await tx.doc(LaunchIndexDoc, identity.requestId, {
|
|
507
|
+
requestId: identity.requestId,
|
|
508
|
+
});
|
|
509
|
+
for (const entry of [...index.attempts].reverse()) {
|
|
510
|
+
const doc = await tx.doc(RunDoc, entry.runId, identity.seed);
|
|
511
|
+
if (doc.taskId === null) continue;
|
|
512
|
+
const task = await tx.task(taskId(doc.taskId));
|
|
513
|
+
if (isReusable(task)) {
|
|
514
|
+
return { runId: entry.runId, attempt: entry.attempt, reuseTaskId: doc.taskId };
|
|
515
|
+
}
|
|
516
|
+
if (task !== undefined && task.state.status === "terminal") break;
|
|
517
|
+
}
|
|
518
|
+
const attempt = nextAttempt(index.attempts);
|
|
519
|
+
const runId = `${identity.requestId}#${attempt}`;
|
|
520
|
+
index.attempts.push({ runId, attempt });
|
|
521
|
+
return { runId, attempt };
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
/** The configuration the run task needs; kept beside the definitions for one import. */
|
|
525
|
+
export type RunConfig = Pick<DelegatesConfig, "maxTurns"> & { readonly cwd?: string };
|
|
526
|
+
|
|
527
|
+
export type { TaskRecord };
|