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