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