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 afterPosition: number | undefined;
135 while (true) {
136 const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
137 threadId: turn.threadId,
138 view: "messages",
139 limit: 100,
140 ...(afterPosition === undefined ? {} : { afterPosition }),
141 });
142 last =
143 read.items.findLast(
144 (item) => item.type === "assistant_message" && item.runId === turn.turnId,
145 ) ?? last;
146 if (!read.hasMore || read.nextPosition === null) break;
147 afterPosition = read.nextPosition;
148 }
149 if (last === undefined) return "";
150 let text = last.text ?? "";
151 let textOffset = last.textTruncated ? (last.nextTextOffset ?? null) : null;
152 while (textOffset !== null) {
153 const rest = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
154 threadId: turn.threadId,
155 itemId: last.itemId,
156 textOffset,
157 maxCharsPerItem: 50_000,
158 });
159 const part = rest.items[0];
160 if (part === undefined) break;
161 text += part.text ?? "";
162 textOffset = part.textTruncated ? (part.nextTextOffset ?? null) : null;
163 }
164 return text;
165 });
166
167 const start = Effect.fn("WorkflowAgentLinks.start")(function* (
168 input: Parameters<Service["start"]>[0],
169 environment: string,
170 requestId: string,
171 here: EnvironmentId,
172 ) {
173 if (!(yield* links.enabled)) {
174 return yield* new WorkflowAgentError({
175 reason:
176 "Linked environments is off on this machine, so an agent step cannot run in another one. Turn it on in Settings → Labs.",
177 });
178 }
179 const outputSchema =
180 input.outputSchema === undefined ? {} : { outputSchema: input.outputSchema };
181 if (input.thread !== undefined) {
182 if (input.launch !== undefined) return yield* launchOnContinue;
183 const sent = yield* call(environment, "t3_thread_send", OrchestratorMcpThreadSendResult, {
184 threadId: input.thread,
185 message: input.prompt,
186 mode: "queue",
187 ...outputSchema,
188 clientRequestId: requestId,
189 });
190 return { threadId: sent.threadId, turnId: sent.runId, environment };
191 }
192 if (input.project === undefined) {
193 return yield* new WorkflowAgentError({
194 reason: "An agent step needs a `project` to start in, or a `thread` to continue.",
195 });
196 }
197 const projectId = isProjectPath(input.project)
198 ? yield* projectAt(environment, input.project)
199 : input.project;
200 const launched = yield* call(
201 environment,
202 "t3_thread_launch",
203 ProjectToolkit.tools.t3_thread_launch.successSchema,
204 {
205 projectId,
206 title: input.title,
207 ...(input.model === undefined ? {} : { modelSelection: input.model }),
208 ...(input.launch?.runtimeMode === undefined
209 ? {}
210 : { runtimeMode: input.launch.runtimeMode }),
211 ...(input.launch?.interactionMode === undefined
212 ? {}
213 : { interactionMode: input.launch.interactionMode }),
214 ...(input.launch?.workspace === undefined
215 ? {}
216 : { workspaceStrategy: input.launch.workspace }),
217 message: input.prompt,
218 ...outputSchema,
219 clientRequestId: requestId,
220 // The thread there says which run it is a step of, and where that run lives.
221 workflowRun: { environmentId: here, ...input.origin },
222 },
223 );
224 if (launched.runId === null) {
225 return yield* new WorkflowAgentError({
226 reason: `Thread ${launched.threadId} in ${environment} started without a turn for its first message.`,
227 });
228 }
229 return { threadId: launched.threadId, turnId: launched.runId, environment };
230 });
231
232 const result = Effect.fn("WorkflowAgentLinks.result")(function* (
233 turn: AgentTurn,
234 environment: string,
235 options?: { readonly quiet?: Duration.Duration | undefined },
236 ): Effect.fn.Return<AgentResult, WorkflowAgentError> {
237 const ended = new Set(["completed", "failed", "interrupted", "cancelled", "rolled_back"]);
238 /** The result a later turn submits, or nothing once the thread has been quiet. */
239 const owed = Effect.fn("WorkflowAgentLinks.owed")(function* (quiet: Duration.Duration) {
240 let left = Duration.toMillis(quiet);
241 // The newest turn already seen to end without the result, so quiet is not restarted by it.
242 let counted = turn.turnId;
243 while (true) {
244 const piece = Math.min(left, Duration.toMillis(WAIT_PIECE));
245 const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, {
246 threadId: turn.threadId,
247 runId: turn.turnId,
248 untilOutput: true,
249 timeoutMs: piece,
250 });
251 if (waited.output !== undefined) return Option.some(waited.output);
252 // An environment that does not know `untilOutput` answers at once: nothing to wait on.
253 if (!waited.timedOut) return Option.none<Schema.Json>();
254 left -= piece;
255 if (left > 0) continue;
256 const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
257 threadId: turn.threadId,
258 limit: 1,
259 runLimit: 1,
260 });
261 const latest = read.recentRuns[0];
262 if (latest === undefined || latest.runId === counted) return Option.none<Schema.Json>();
263 // Quiet is counted from the thread's last turn: one under way, or one not yet counted.
264 if (ended.has(latest.status)) counted = latest.runId;
265 left = Duration.toMillis(quiet);
266 }
267 });
268 while (true) {
269 const waited = yield* call(environment, "t3_thread_wait", OrchestratorMcpThreadWaitResult, {
270 threadId: turn.threadId,
271 runId: turn.turnId,
272 timeoutMs: Duration.toMillis(WAIT_PIECE),
273 });
274 if (waited.timedOut) continue;
275 const read = yield* call(environment, "t3_thread_read", OrchestratorMcpThreadReadResult, {
276 threadId: turn.threadId,
277 limit: 1,
278 runLimit: 50,
279 });
280 const status = read.recentRuns.find((run) => run.runId === turn.turnId)?.status;
281 if (status === undefined) {
282 return yield* new WorkflowAgentError({
283 reason: `Thread ${turn.threadId} in ${environment} no longer lists turn ${turn.turnId}.`,
284 });
285 }
286 if (status === "completed") {
287 const output =
288 waited.output !== undefined || options?.quiet === undefined
289 ? Option.fromUndefinedOr(waited.output)
290 : yield* owed(options.quiet);
291 return {
292 ending: "completed",
293 detail: "",
294 reply: yield* reply(turn, environment),
295 ...(Option.isNone(output) ? {} : { output: output.value }),
296 };
297 }
298 if (
299 status === "failed" ||
300 status === "interrupted" ||
301 status === "cancelled" ||
302 status === "rolled_back"
303 ) {
304 return { ending: status === "failed" ? "failed" : "stopped", detail: status, reply: "" };
305 }
306 // The wait answered for a turn that has not ended. Asking again at once would spin.
307 yield* Effect.sleep("5 seconds");
308 }
309 });
310
311 const interrupt = (threadId: string, environment: string, runId?: string) =>
312 Effect.map(
313 call(environment, "t3_thread_interrupt", OrchestratorMcpThreadInterruptResult, {
314 threadId,
315 ...(runId === undefined ? {} : { runId }),
316 reason: "Its workflow run was cancelled",
317 }),
318 (stopped): "stopped" | "ended" =>
319 stopped.status === "interrupt_requested" ? "stopped" : "ended",
320 );
321
322 return { start, result, interrupt };
323});