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