Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkflowAgentThreads.ts

349 lines14.7 KB

1// Agent steps as threads: a step's turn is an ordinary thread turn that was asked for a result.
2import {
3 CommandId,
4 MessageId,
5 type ModelSelection,
6 ProjectId,
7 ProviderInstanceId,
8 type RunId,
9 ThreadId,
10} from "@t3tools/contracts";
11import { subagentResultForRun } from "@t3tools/provider-core/server/subagentProjection";
12import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
13import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits";
14import * as Digest from "effect/crypto/Digest";
15import * as Clock from "effect/Clock";
16import * as DateTime from "effect/DateTime";
17import * as Duration from "effect/Duration";
18import * as Effect from "effect/Effect";
19import * as Hex from "effect/encoding/Hex";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22​
23import * as ThreadIssueService from "../orchestration-v2/ThreadIssueService.ts";
24import * as ThreadLaunch from "../orchestration-v2/ThreadLaunchService.ts";
25import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
26import * as ProjectService from "../project/ProjectService.ts";
27import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
28import * as ServerSettings from "../serverSettings.ts";
29import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
30import * as WorkflowAgentLinks from "./WorkflowAgentLinks.ts";
31import {
32 isProjectPath,
33 launchOnContinue,
34 WorkflowAgentError,
35 WorkflowAgents,
36} from "./WorkflowAgents.ts";
37import { noteReference } from "./runReferences.ts";
38import { type IssueAddress, linkedPullRequestReferences, WorkflowForge } from "./WorkflowForge.ts";
39import { withoutRoutineSpans } from "@t3tools/shared/observability";
40​
41// A turn can run for hours. Each look is bounded so a wait that lost its event is asked again.
42const WAIT_SLICE = Duration.minutes(10);
43​
44const failed = (reason: string) => (cause: unknown) =>
45 new WorkflowAgentError({
46 reason: `${reason}: ${cause instanceof Error ? cause.message : String(cause)}`,
47 });
48​
49const make = Effect.gen(function* () {
50 const threads = yield* ThreadManagement.ThreadManagementService;
51 const launches = yield* ThreadLaunch.ThreadLaunchService;
52 const projects = yield* ProjectService.ProjectService;
53 const providers = yield* ProviderRegistry.ProviderRegistry;
54 const settings = yield* ServerSettings.ServerSettingsService;
55 const digest = yield* Digest.Digest;
56 const linked = yield* WorkflowAgentLinks.make;
57 const forge = yield* WorkflowForge;
58 const threadIssues = yield* ThreadIssueService.ThreadIssueService;
59 // A tracker that is down must not cost the step its agent.
60 const showIssue = (issue: IssueAddress | undefined, threadId: string) =>
61 issue === undefined
62 ? Effect.void
63 : forge.issues.read(issue).pipe(
64 Effect.flatMap((detail) =>
65 threadIssues.link({
66 threadId: ThreadId.make(threadId),
67 ref: {
68 projectId: detail.projectId,
69 tracker: detail.tracker,
70 host: detail.host,
71 scope: detail.scope,
72 key: detail.key,
73 },
74 url: detail.url,
75 displayKey: detail.displayKey,
76 title: detail.title,
77 source: "agent",
78 }),
79 ),
80 Effect.catch((error) =>
81 Effect.logWarning("Could not link a workflow agent's thread to its issue", {
82 threadId,
83 reason: error.message,
84 }),
85 ),
86 );
87 // What the agent opened or linked while it worked is part of what its step touched.
88 const noteLinked = (threadId: ThreadId, sinceMillis: number | undefined) =>
89 threads.getThreadShell(threadId).pipe(
90 Effect.flatMap((shell) =>
91 shell === null
92 ? Effect.void
93 : Effect.forEach(linkedPullRequestReferences(shell, sinceMillis), noteReference, {
94 discard: true,
95 }),
96 ),
97 Effect.ignore,
98 );
99 const here = yield* ServerEnvironment.ServerEnvironment.pipe(
100 Effect.flatMap((environment) => environment.getEnvironmentId),
101 );
102 /** The linked environment a step names, or nothing when it names this one. */
103 const elsewhere = (environment: string | undefined) =>
104 environment === here ? undefined : environment;
105​
106 // Thread, message and command ids all derive from the step's key, so a start that is asked for
107 // again after a crash finds the turn it already started.
108 const idOf = Effect.fn("WorkflowAgentThreads.idOf")(function* (key: string) {
109 const hash = yield* digest
110 .digest(Digest.sha256, new TextEncoder().encode(key))
111 .pipe(Effect.mapError(failed("Could not derive the turn's id")));
112 return `workflow:${Hex.encode(hash)}`;
113 });
114​
115 const projectDefaults = Effect.fn("WorkflowAgentThreads.projectDefaults")(function* (
116 projectId: ProjectId,
117 ) {
118 const project = yield* projects
119 .getById(projectId)
120 .pipe(Effect.mapError(failed("Could not read the project")));
121 if (Option.isNone(project)) {
122 return yield* new WorkflowAgentError({ reason: `Project ${projectId} was not found.` });
123 }
124 const current = yield* settings.getSettings.pipe(
125 Effect.mapError(failed("Could not read settings")),
126 );
127 return resolveProjectSettings(current, projectId, project.value).settings;
128 });
129​
130 const projectIdOf = Effect.fn("WorkflowAgentThreads.projectIdOf")(function* (project: string) {
131 if (!isProjectPath(project)) return ProjectId.make(project);
132 const found = yield* projects
133 .getByWorkspaceRoot(project)
134 .pipe(Effect.mapError(failed("Could not read the project")));
135 if (Option.isNone(found)) {
136 return yield* new WorkflowAgentError({
137 reason: `No project is registered at ${project}.`,
138 });
139 }
140 return found.value.id;
141 });
142​
143 const agents = WorkflowAgents.of({
144 start: Effect.fn("WorkflowAgentThreads.start")(function* (input) {
145 const id = yield* idOf(input.key);
146 const environment = elsewhere(input.environment);
147 if (environment !== undefined) return yield* linked.start(input, environment, id, here);
148 const commandId = CommandId.make(id);
149 const messageId = MessageId.make(id);
150 const outputSchema =
151 input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema };
152​
153 if (input.thread !== undefined) {
154 if (input.launch !== undefined) return yield* launchOnContinue;
155 const threadId = ThreadId.make(input.thread);
156 const shell = yield* threads
157 .getThreadShell(threadId)
158 .pipe(Effect.mapError(failed("Could not read the thread to continue")));
159 if (shell === null || shell.deletedAt !== null) {
160 return yield* new WorkflowAgentError({
161 reason: `Thread ${input.thread} no longer exists, so it cannot be continued.`,
162 });
163 }
164 const sent = yield* threads
165 .sendToThread({
166 projectId: shell.projectId,
167 commandId,
168 threadId,
169 messageId,
170 text: input.prompt,
171 attachments: [],
172 mode: "queue",
173 ...outputSchema,
174 createdBy: "system",
175 creationSource: "server",
176 })
177 .pipe(Effect.mapError(failed("Could not send to the thread")));
178 yield* showIssue(input.issue, threadId);
179 return { threadId, turnId: sent.run.id };
180 }
181​
182 if (input.project === undefined) {
183 return yield* new WorkflowAgentError({
184 reason: "An agent step needs a `project` to start in, or a `thread` to continue.",
185 });
186 }
187 const projectId = yield* projectIdOf(input.project);
188 const defaults = yield* projectDefaults(projectId);
189 const modelSelection: ModelSelection | undefined =
190 input.model === undefined
191 ? (resolveNewThreadModelSelection({
192 defaultSelection: defaults.defaultModelSelection,
193 fallbackSelection: defaults.fallbackModelSelection,
194 providers: yield* providers.getProviders,
195 settings: defaults,
196 projectId,
197 now: DateTime.toEpochMillis(yield* DateTime.now),
198 }).selection ?? undefined)
199 : {
200 instanceId: ProviderInstanceId.make(input.model.instanceId),
201 model: input.model.model,
202 ...(input.model.options === undefined ? {} : { options: input.model.options }),
203 };
204 if (modelSelection === undefined) {
205 return yield* new WorkflowAgentError({
206 reason: `Project ${input.project} has no default model. Give the agent step a \`model\`.`,
207 });
208 }
209 const launched = yield* launches
210 .launch({
211 commandId,
212 threadId: ThreadId.make(id),
213 projectId,
214 title: input.title,
215 titleRenamed: true,
216 modelSelection,
217 runtimeMode: input.launch?.runtimeMode ?? defaults.defaultRuntimeMode,
218 interactionMode: input.launch?.interactionMode ?? "default",
219 workspaceStrategy: input.launch?.workspace ?? { type: "root" },
220 initialMessage: { messageId, text: input.prompt, attachments: [], ...outputSchema },
221 createdBy: "system",
222 creationSource: "server",
223 workflowRun: { environmentId: here, ...input.origin },
224 })
225 .pipe(Effect.mapError(failed("Could not start the thread")));
226 const run = launched.projection.runs.find(
227 (candidate) => candidate.userMessageId === messageId,
228 );
229 if (run === undefined) {
230 return yield* new WorkflowAgentError({
231 reason: `Thread ${launched.threadId} started without a turn for its first message.`,
232 });
233 }
234 yield* showIssue(input.issue, launched.threadId);
235 return { threadId: launched.threadId, turnId: run.id };
236 }),
237 result: Effect.fn("WorkflowAgentThreads.result")(function* (turn, options) {
238 const environment = elsewhere(turn.environment);
239 if (environment !== undefined) return yield* linked.result(turn, environment, options);
240 const threadId = ThreadId.make(turn.threadId);
241 const shell = yield* threads
242 .getThreadShell(threadId)
243 .pipe(Effect.mapError(failed("Could not read the thread")));
244 if (shell === null) {
245 return yield* new WorkflowAgentError({
246 reason: `Thread ${turn.threadId} no longer exists.`,
247 });
248 }
249 // The newest turn already seen to end without the result, so quiet is not restarted by it.
250 let quietSince = -1;
251 while (true) {
252 const waited = yield* threads
253 .waitForThread({
254 projectId: shell.projectId,
255 threadId,
256 runId: turn.turnId as RunId,
257 timeoutMs: Duration.toMillis(WAIT_SLICE),
258 })
259 .pipe(Effect.mapError(failed("Could not wait for the turn")));
260 let run = waited.run;
261 if (waited.timedOut || run === null) continue;
262 // The agent may have ended its turn to wait for something that will wake it.
263 const quiet = options?.quiet;
264 const owes = (candidate: NonNullable<typeof waited.run>) =>
265 candidate.status === "completed" &&
266 candidate.outputSchema !== undefined &&
267 candidate.output === undefined;
268 while (owes(run)) {
269 if (quiet === undefined) break;
270 const owed: ThreadManagement.ThreadManagementWaitResult = yield* threads
271 .waitForThread({
272 projectId: shell.projectId,
273 threadId,
274 runId: run.id,
275 untilOutput: true,
276 timeoutMs: Duration.toMillis(quiet),
277 })
278 .pipe(Effect.mapError(failed("Could not wait for the turn's result")));
279 if (owed.run === null) break;
280 run = owed.run;
281 if (!owed.timedOut) continue;
282 // Quiet is counted from the thread's last turn, so one under way is waited out first.
283 const latest = yield* threads
284 .waitForThread({
285 projectId: shell.projectId,
286 threadId,
287 timeoutMs: Duration.toMillis(WAIT_SLICE),
288 })
289 .pipe(Effect.mapError(failed("Could not wait for the thread")));
290 if (latest.run === null || latest.run.id === run.id) break;
291 if (!latest.timedOut && latest.run.ordinal <= quietSince) break;
292 quietSince = latest.timedOut ? quietSince : latest.run.ordinal;
293 }
294 yield* noteLinked(threadId, turn.startedAt);
295 if (run.status !== "completed") {
296 // Interrupted or cancelled is someone stopping it; the rest is the turn dying.
297 const ending = run.status === "failed" ? ("failed" as const) : ("stopped" as const);
298 return { ending, detail: run.status, reply: "" };
299 }
300 const records = yield* threads
301 .getThreadRecords(threadId, ["messages", "turnItems", "providerTurns"])
302 .pipe(Effect.mapError(failed("Could not read the turn's reply")));
303 return {
304 ending: "completed" as const,
305 detail: "",
306 reply: subagentResultForRun(records, run).text,
307 ...(run.output === undefined ? {} : { output: run.output.value }),
308 };
309 }
310 }),
311 interrupt: Effect.fn("WorkflowAgentThreads.interrupt")(function* (target) {
312 const environment = elsewhere(target.environment);
313 if (environment !== undefined)
314 return yield* linked.interrupt(target.threadId, environment, target.turnId);
315 const thread = target.threadId;
316 const threadId = ThreadId.make(thread);
317 const shell = yield* threads
318 .getThreadShell(threadId)
319 .pipe(Effect.mapError(failed("Could not read the thread")));
320 if (shell === null) return "ended" as const;
321 const stopped = yield* threads
322 .interruptThread({
323 projectId: shell.projectId,
324 threadId,
325 commandId: CommandId.make(
326 `workflow:interrupt:${thread}:${target.turnId ?? ""}:${yield* Clock.currentTimeMillis}`,
327 ),
328 reason: "Its workflow run was cancelled",
329 ...(target.turnId === undefined ? {} : { runId: target.turnId as RunId }),
330 })
331 .pipe(Effect.mapError(failed("Could not stop the thread")));
332 return stopped.type === "interrupt_requested" ? ("stopped" as const) : ("ended" as const);
333 }),
334 });
335 // Thread launches and sends are user work, not engine bookkeeping, so they are never sampled.
336 return WorkflowAgents.of({
337 start: Effect.fnUntraced(function* (input) {
338 return yield* withoutRoutineSpans(agents.start(input));
339 }),
340 result: Effect.fnUntraced(function* (turn, options) {
341 return yield* withoutRoutineSpans(agents.result(turn, options));
342 }),
343 interrupt: Effect.fnUntraced(function* (target) {
344 return yield* withoutRoutineSpans(agents.interrupt(target));
345 }),
346 });
347});
348​
349export const layer = Layer.effect(WorkflowAgents, make);