Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorkflowAgentLinks.ts

313 lines11.7 KB

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