Open History to see the last commit
1// Agent steps in a linked environment: the same three operations, as that environment's T3 tools.
2import {
3 type EnvironmentId,
4 OrchestratorMcpFailure,
5 OrchestratorMcpThreadInterruptResult,
6 OrchestratorMcpThreadReadResult,
7 OrchestratorMcpThreadSendResult,
8 OrchestratorMcpThreadWaitResult,
9} from "@t3tools/contracts";
10import {
11 fileBasename,
12 isWindowsDrivePath,
13 normalizeProjectPathForComparison,
14} from "@t3tools/shared/path";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Option from "effect/Option";
18import * as Result from "effect/Result";
19import * as Schedule from "effect/Schedule";
20import type * as Schema from "effect/Schema";
21
22import { ProjectToolkit } from "../mcp/toolkits/project/tools.ts";
23import * as PeerLinks from "../peer/PeerLinks.ts";
24import * as PeerMcpClient from "../peer/PeerMcpClient.ts";
25import {
26 type AgentResult,
27 type AgentTurn,
28 isProjectPath,
29 launchOnContinue,
30 WorkflowAgentError,
31 type WorkflowAgents,
32} from "./WorkflowAgents.ts";
33
34// A run acts for whoever owns this environment, not for an agent with modes of its own, so the
35// only ceiling on what it starts there is the access the link was paired with.
36const LIMITS = { runtimeMode: "full-access", interactionMode: "default" } as const;
37
38// T3 Connect's edge drops a request that is idle for about 100 s, so a wait goes out in pieces.
39const WAIT_PIECE = Duration.seconds(50);
40
41/** The link is gone or the thread is: asking again cannot help. */
42const isFinal = (error: OrchestratorMcpFailure) =>
43 error.code === "capability_denied" ||
44 error.code === "thread_not_found" ||
45 error.code === "run_not_found" ||
46 error.code === "invalid_request";
47
48// The other machine asleep or a dropped route is worth a few more tries before the run pauses.
49const retried = {
50 schedule: Schedule.exponential("2 seconds"),
51 times: 5,
52 while: (error: OrchestratorMcpFailure) => !isFinal(error),
53};
54
55type Service = WorkflowAgents["Service"];
56
57export const make = Effect.gen(function* () {
58 const peers = yield* PeerMcpClient.PeerMcpClient;
59 const links = yield* PeerLinks.PeerLinks;
60
61 const callPeer = <S extends Schema.Decoder<unknown>>(
62 environment: string,
63 tool: string,
64 success: S,
65 args: Record<string, unknown>,
66 ) =>
67 peers.call({
68 environmentId: environment as EnvironmentId,
69 tool,
70 arguments: args,
71 limits: LIMITS,
72 success,
73 });
74
75 const refused = (environment: string, tool: string, error: OrchestratorMcpFailure) =>
76 `Environment ${environment} refused ${tool}: ${error.message}`;
77
78 const call = <S extends Schema.Decoder<unknown>>(
79 environment: string,
80 tool: string,
81 success: S,
82 args: Record<string, unknown>,
83 ) =>
84 callPeer(environment, tool, success, args).pipe(
85 Effect.retry(retried),
86 Effect.mapError(
87 (error) => new WorkflowAgentError({ reason: refused(environment, tool, error) }),
88 ),
89 );
90
91 const listed = Effect.fn("WorkflowAgentLinks.listed")(function* (
92 environment: string,
93 path: string,
94 ) {
95 const target = normalizeProjectPathForComparison(path);
96 let cursor: number | null = 0;
97 while (cursor !== null) {
98 const page: Schema.Schema.Type<typeof ProjectToolkit.tools.t3_project_list.successSchema> =
99 yield* call(
100 environment,
101 "t3_project_list",
102 ProjectToolkit.tools.t3_project_list.successSchema,
103 { cursor, limit: 100 },
104 );
105 const found = page.projects.find(
106 (project) => normalizeProjectPathForComparison(project.workspaceRoot) === target,
107 );
108 if (found !== undefined) return found.id;
109 cursor = page.nextCursor;
110 }
111 return undefined;
112 });
113
114 /**
115 * The project at a folder there. A machine made for one run has the folder and no project yet,
116 * so a folder that is not one is registered. Two steps may do that at once; the one that is
117 * refused finds the other's.
118 */
119 const projectAt = Effect.fn("WorkflowAgentLinks.projectAt")(function* (
120 environment: string,
121 path: string,
122 ) {
123 const known = yield* listed(environment, path);
124 if (known !== undefined) return known;
125 const title = isWindowsDrivePath(path)
126 ? fileBasename(path)
127 : (path.split("/").findLast((part) => part.length > 0) ?? path);
128 const created = yield* call(
129 environment,
130 "t3_project_create",
131 ProjectToolkit.tools.t3_project_create.successSchema,
132 { title, workspaceRoot: path },
133 ).pipe(Effect.result);
134 if (Result.isSuccess(created)) return created.success.id;
135 return (yield* listed(environment, path)) ?? (yield* created.failure);
136 });
137
138 /** The whole text of the run's last assistant message. */
139 const reply = Effect.fn("WorkflowAgentLinks.reply")(function* (
140 turn: AgentTurn,
141 environment: string,
142 ) {
143 let last: OrchestratorMcpThreadReadResult["items"][number] | undefined;
144 let cursor: { beforePosition?: number; afterPosition?: number } = {};
145 while (true) {
146 const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
147 threadId: turn.threadId,
148 view: "messages",
149 limit: 100,
150 ...cursor,
151 });
152 last =
153 read.items.findLast(
154 (item) => item.type === "assistant_message" && item.runId === turn.turnId,
155 ) ?? last;
156 const { earlierPosition, nextPosition, hasMore } = read;
157 // Backward pages are chronological too, and hasMore points toward newer items.
158 if (cursor.afterPosition === undefined && earlierPosition != null) {
159 if (last !== undefined || earlierPosition >= (cursor.beforePosition ?? Infinity)) break;
160 cursor = { beforePosition: earlierPosition };
161 continue;
162 }
163 if (
164 cursor.beforePosition !== undefined ||
165 !hasMore ||
166 nextPosition === null ||
167 nextPosition <= (cursor.afterPosition ?? -1)
168 )
169 break;
170 cursor = { afterPosition: nextPosition };
171 }
172 if (last === undefined) return "";
173 let text = last.text ?? "";
174 let textOffset = last.textTruncated ? (last.nextTextOffset ?? null) : null;
175 while (textOffset !== null) {
176 const rest = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
177 threadId: turn.threadId,
178 itemId: last.itemId,
179 textOffset,
180 maxCharsPerItem: 50_000,
181 });
182 const part = rest.items[0];
183 if (part === undefined) break;
184 text += part.text ?? "";
185 textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null;
186 }
187 return text;
188 });
189
190 const start = Effect.fn("WorkflowAgentLinks.start")(function* (
191 input: Parameters<Service["start"]>[0],
192 environment: string,
193 requestId: string,
194 here: EnvironmentId,
195 ) {
196 if (!(yield* links.enabled)) {
197 return yield* new WorkflowAgentError({
198 reason:
199 "Linked environments is off on this machine, so an agent step cannot run in another one. Turn it on in Settings → Labs.",
200 });
201 }
202 const outputSchema =
203 input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema };
204 if (input.thread !== undefined) {
205 if (input.launch !== undefined) return yield* launchOnContinue;
206 const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendResult, {
207 threadId: input.thread,
208 message: input.prompt,
209 mode: "queue",
210 ...outputSchema,
211 clientRequestId: requestId,
212 });
213 return { threadId: sent.threadId, turnId: sent.runId, environment };
214 }
215 if (input.project === undefined) {
216 return yield* new WorkflowAgentError({
217 reason: "An agent step needs a `project` to start in, or a `thread` to continue.",
218 });
219 }
220 const projectId = isProjectPath(input.project)
221 ? yield* projectAt(environment, input.project)
222 : input.project;
223 const launched = yield* call(
224 environment,
225 "t3_thread_launch",
226 ProjectToolkit.tools.t3_thread_launch.successSchema,
227 {
228 projectId,
229 title: input.title,
230 ...(input.model === undefined ? {} : { modelSelection: input.model }),
231 ...(input.launch?.runtimeMode === undefined
232 ? {}
233 : { runtimeMode: input.launch.runtimeMode }),
234 ...(input.launch?.interactionMode === undefined
235 ? {}
236 : { interactionMode: input.launch.interactionMode }),
237 ...(input.launch?.workspace === undefined
238 ? {}
239 : { workspaceStrategy: input.launch.workspace }),
240 message: input.prompt,
241 ...outputSchema,
242 clientRequestId: requestId,
243 // The thread there says which run it is a step of, and where that run lives.
244 workflowRun: { environmentId: here, ...input.origin },
245 },
246 );
247 if (launched.runId === null) {
248 return yield* new WorkflowAgentError({
249 reason: `Thread ${launched.threadId} in ${environment} started without a turn for its first message.`,
250 });
251 }
252 return { threadId: launched.threadId, turnId: launched.runId, environment };
253 });
254
255 const result = Effect.fn("WorkflowAgentLinks.result")(function* (
256 turn: AgentTurn,
257 environment: string,
258 options?: { readonly quiet?: Duration.Duration | undefined },
259 ): Effect.fn.Return<AgentResult, WorkflowAgentError> {
260 const ended = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]);
261 /** The result a later turn submits, or nothing once the thread has been quiet. */
262 const owed = Effect.fn("WorkflowAgentLinks.owed")(function* (
263 turnId: string,
264 quiet: Duration.Duration,
265 ) {
266 let left = Duration.toMillis(quiet);
267 // The newest turn already seen to end without the result, so quiet is not restarted by it.
268 let counted = turnId;
269 while (true) {
270 const piece = Math.min(left, Duration.toMillis(WAIT_PIECE));
271 const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, {
272 threadId: turn.threadId,
273 runId: turnId,
274 untilOutput: true,
275 timeoutMs: piece,
276 });
277 if (waited.output !== undefined) return Option.some(waited.output);
278 // An environment that does not know `untilOutput` answers at once: nothing to wait on.
279 if (!waited.timedOut) return Option.none<Schema.Json>();
280 left -= piece;
281 if (left > 0) continue;
282 const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
283 threadId: turn.threadId,
284 limit: 1,
285 runLimit: 1,
286 });
287 const latest = read.recentRuns[0];
288 if (latest === undefined || latest.runId === counted) return Option.none<Schema.Json>();
289 // Quiet is counted from the thread's last turn: one under way, or one not yet counted.
290 if (ended.has(latest.status)) counted = latest.runId;
291 left = Duration.toMillis(quiet);
292 }
293 });
294 while (true) {
295 const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, {
296 threadId: turn.threadId,
297 runId: turn.turnId,
298 timeoutMs: Duration.toMillis(WAIT_PIECE),
299 });
300 if (waited.timedOut) continue;
301 // The wait follows restart continuations, so the run it names may be a later one.
302 const turnId = waited.runId ?? turn.turnId;
303 const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
304 threadId: turn.threadId,
305 limit: 1,
306 runLimit: 50,
307 });
308 const status = read.recentRuns.find((run) => run.runId === turnId)?.status;
309 if (status === undefined) {
310 return yield* new WorkflowAgentError({
311 reason: `Thread ${turn.threadId} in ${environment} no longer lists turn ${turnId}.`,
312 });
313 }
314 if (status === "completed") {
315 const output =
316 waited.output !== undefined || options?.quiet === undefined
317 ? Option.fromUndefinedOr(waited.output)
318 : yield* owed(turnId, options.quiet);
319 return {
320 ending: "completed",
321 detail: "",
322 reply: yield* reply({ ...turn, turnId }, environment),
323 ...(Option.isNone(output) ? {} : { output: output.value }),
324 };
325 }
326 if (
327 status === "failed" ||
328 status === "interrupted" ||
329 status === "cancelled" ||
330 status === "rolled_back"
331 ) {
332 return { ending: status === "failed" ? "failed" : "stopped", detail: status, reply: "" };
333 }
334 // The wait answered for a turn that has not ended. Asking again at once would spin.
335 yield* Effect.sleep("5 seconds");
336 }
337 });
338
339 const interrupt = (
340 threadId: string,
341 environment: string,
342 runId?: string,
343 options?: Parameters<Service["interrupt"]>[1],
344 ) => {
345 const tool = "t3_thread_interrupt";
346 const request = callPeer(environment, tool, OrchestratorMcpThreadInterruptResult, {
347 threadId,
348 ...(runId === undefined ? {} : { runId }),
349 reason: "Its workflow run was cancelled",
350 });
351 return (options?.once ? request : request.pipe(Effect.retry(retried))).pipe(
352 Effect.map((stopped): "stopped" | "ended" =>
353 stopped.status === "interrupt_requested" ? "stopped" : "ended",
354 ),
355 Effect.catch((error) =>
356 error.code === "thread_not_found" || error.code === "run_not_found"
357 ? Effect.succeed("ended" as const)
358 : Effect.fail(
359 new WorkflowAgentError({
360 reason: refused(environment, tool, error),
361 final: isFinal(error),
362 }),
363 ),
364 ),
365 );
366 };
367
368 return { start, result, interrupt };
369});