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