Open History to see the last commit
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 modelSelection,
216 runtimeMode: input.launch?.runtimeMode ?? defaults.defaultRuntimeMode,
217 interactionMode: input.launch?.interactionMode ?? "default",
218 workspaceStrategy: input.launch?.workspace ?? { type: "root" },
219 initialMessage: { messageId, text: input.prompt, attachments: [], ...outputSchema },
220 createdBy: "system",
221 creationSource: "server",
222 workflowRun: { environmentId: here, ...input.origin },
223 })
224 .pipe(Effect.mapError(failed("Could not start the thread")));
225 const run = launched.projection.runs.find(
226 (candidate) => candidate.userMessageId === messageId,
227 );
228 if (run === undefined) {
229 return yield* new WorkflowAgentError({
230 reason: `Thread ${launched.threadId} started without a turn for its first message.`,
231 });
232 }
233 yield* showIssue(input.issue, launched.threadId);
234 return { threadId: launched.threadId, turnId: run.id };
235 }),
236 result: Effect.fn("WorkflowAgentThreads.result")(function* (turn, options) {
237 const environment = elsewhere(turn.environment);
238 if (environment !== undefined) return yield* linked.result(turn, environment, options);
239 const threadId = ThreadId.make(turn.threadId);
240 const shell = yield* threads
241 .getThreadShell(threadId)
242 .pipe(Effect.mapError(failed("Could not read the thread")));
243 if (shell === null) {
244 return yield* new WorkflowAgentError({
245 reason: `Thread ${turn.threadId} no longer exists.`,
246 });
247 }
248 // The newest turn already seen to end without the result, so quiet is not restarted by it.
249 let quietSince = -1;
250 while (true) {
251 const waited = yield* threads
252 .waitForThread({
253 projectId: shell.projectId,
254 threadId,
255 runId: turn.turnId as RunId,
256 timeoutMs: Duration.toMillis(WAIT_SLICE),
257 })
258 .pipe(Effect.mapError(failed("Could not wait for the turn")));
259 let run = waited.run;
260 if (waited.timedOut || run === null) continue;
261 // The agent may have ended its turn to wait for something that will wake it.
262 const quiet = options?.quiet;
263 const owes = (candidate: NonNullable<typeof waited.run>) =>
264 candidate.status === "completed" &&
265 candidate.outputSchema !== undefined &&
266 candidate.output === undefined;
267 while (owes(run)) {
268 if (quiet === undefined) break;
269 const owed: ThreadManagement.ThreadManagementWaitResult = yield* threads
270 .waitForThread({
271 projectId: shell.projectId,
272 threadId,
273 runId: run.id,
274 untilOutput: true,
275 timeoutMs: Duration.toMillis(quiet),
276 })
277 .pipe(Effect.mapError(failed("Could not wait for the turn's result")));
278 if (owed.run === null) break;
279 run = owed.run;
280 if (!owed.timedOut) continue;
281 // Quiet is counted from the thread's last turn, so one under way is waited out first.
282 const latest = yield* threads
283 .waitForThread({
284 projectId: shell.projectId,
285 threadId,
286 timeoutMs: Duration.toMillis(WAIT_SLICE),
287 })
288 .pipe(Effect.mapError(failed("Could not wait for the thread")));
289 if (latest.run === null || latest.run.id === run.id) break;
290 if (!latest.timedOut && latest.run.ordinal <= quietSince) break;
291 quietSince = latest.timedOut ? quietSince : latest.run.ordinal;
292 }
293 yield* noteLinked(threadId, turn.startedAt);
294 if (run.status !== "completed") {
295 // Interrupted or cancelled is someone stopping it; the rest is the turn dying.
296 const ending = run.status === "failed" ? ("failed" as const) : ("stopped" as const);
297 return { ending, detail: run.status, reply: "" };
298 }
299 const records = yield* threads
300 .getThreadRecords(threadId, ["messages", "turnItems", "providerTurns"])
301 .pipe(Effect.mapError(failed("Could not read the turn's reply")));
302 return {
303 ending: "completed" as const,
304 detail: "",
305 reply: subagentResultForRun(records, run).text,
306 ...(run.output === undefined ? {} : { output: run.output.value }),
307 };
308 }
309 }),
310 interrupt: Effect.fn("WorkflowAgentThreads.interrupt")(function* (target) {
311 const environment = elsewhere(target.environment);
312 if (environment !== undefined)
313 return yield* linked.interrupt(target.threadId, environment, target.turnId);
314 const thread = target.threadId;
315 const threadId = ThreadId.make(thread);
316 const shell = yield* threads
317 .getThreadShell(threadId)
318 .pipe(Effect.mapError(failed("Could not read the thread")));
319 if (shell === null) return "ended" as const;
320 const stopped = yield* threads
321 .interruptThread({
322 projectId: shell.projectId,
323 threadId,
324 commandId: CommandId.make(
325 `workflow:interrupt:${thread}:${target.turnId ?? ""}:${yield* Clock.currentTimeMillis}`,
326 ),
327 reason: "Its workflow run was cancelled",
328 ...(target.turnId === undefined ? {} : { runId: target.turnId as RunId }),
329 })
330 .pipe(Effect.mapError(failed("Could not stop the thread")));
331 return stopped.type === "interrupt_requested" ? ("stopped" as const) : ("ended" as const);
332 }),
333 });
334 // Thread launches and sends are user work, not engine bookkeeping, so they are never sampled.
335 return WorkflowAgents.of({
336 start: Effect.fnUntraced(function* (input) {
337 return yield* withoutRoutineSpans(agents.start(input));
338 }),
339 result: Effect.fnUntraced(function* (turn, options) {
340 return yield* withoutRoutineSpans(agents.result(turn, options));
341 }),
342 interrupt: Effect.fnUntraced(function* (target) {
343 return yield* withoutRoutineSpans(agents.interrupt(target));
344 }),
345 });
346});
347
348export const layer = Layer.effect(WorkflowAgents, make);