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

handlers.ts

306 lines10.9 KB

1import {
2 type CommandId,
3 type RuntimeRequestId,
4 ThreadId,
5 type OrchestrationV2ThreadProjection,
6 type RunId,
7 OrchestratorMcpFailure,
8 type OrchestrationV2Command,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import { modelSelectionCommandType } from "@t3tools/shared/model";
12​
13import {
14 newCommandId,
15 readCaller,
16 readFullAccessCaller,
17 readThread,
18 readWritableThread,
19 unavailable,
20} from "../../threadAccess.ts";
21import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
22import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts";
23import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts";
24import { ThreadToolkit } from "./tools.ts";
25​
26function queueEntry(
27 projection: Pick<OrchestrationV2ThreadProjection, "runs" | "messages">,
28 runId: RunId,
29 limit: number,
30) {
31 const run = projection.runs.find((run) => run.id === runId && run.status === "queued");
32 const message = projection.messages.find((message) => message.id === run?.userMessageId);
33 if (run === undefined || message === undefined) return undefined;
34 const characters = Array.from(message.text);
35 return {
36 queuedRunId: run.id,
37 text: characters.slice(0, limit).join(""),
38 truncated: characters.length > limit,
39 };
41const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* (
42 threadId: ThreadId | undefined,
43 command: (common: { commandId: CommandId; threadId: ThreadId }) => OrchestrationV2Command,
44) {
45 const { threads, projection } = yield* readWritableThread(threadId);
46 const result = yield* threads
47 .dispatch(command({ commandId: yield* newCommandId(), threadId: projection.thread.id }))
48 .pipe(Effect.mapError(unavailable));
49 return { sequence: result.sequence };
50});
51​
52const readQuestion = Effect.fn("mcp.readQuestion")(function* (
53 input: {
54 threadId?: ThreadId | undefined;
55 requestId: RuntimeRequestId;
56 },
57 writable = false,
58) {
59 const context = yield* writable
60 ? readWritableThread(input.threadId, ["runtimeRequests", "turnItems"])
61 : readThread(input.threadId, ["runtimeRequests", "turnItems"]);
62 const request = context.projection.runtimeRequests.find(
63 (request) =>
64 request.id === input.requestId &&
65 request.kind === "user_input" &&
66 request.status === "pending",
67 );
68 const item = context.projection.turnItems.find(
69 (item) => item.type === "user_input_request" && item.requestId === input.requestId,
70 );
71 if (request === undefined || item?.type !== "user_input_request")
72 return yield* new OrchestratorMcpFailure({
73 code: "invalid_request",
74 message: "The pending user-input request was not found.",
75 });
76 return { ...context, request, item };
77});
78export const layer = ThreadToolkit.toLayer({
79 run_scheduled_task_now: (input) =>
80 Effect.gen(function* () {
81 yield* readFullAccessCaller(
82 "Running a scheduled task requires a live full-access/default thread or a full-access client.",
83 );
84 const scheduler = yield* ScheduledTasks.ScheduledTaskService;
85 const { tasks } = yield* scheduler.list().pipe(Effect.mapError(unavailable));
86 if (!tasks.some((task) => task.id === input.taskId))
87 return yield* new OrchestratorMcpFailure({
88 code: "invalid_request",
89 message: "The scheduled task was not found.",
90 });
91 const { task } = yield* scheduler
92 .runNow({ id: input.taskId })
93 .pipe(Effect.mapError(unavailable));
94 return {
95 taskId: task.id,
96 threadId: task.threadId,
97 lastRunStatus: task.lastRunStatus,
98 runCount: task.runCount,
99 nextRunAt: task.nextRunAt,
100 };
101 }),
102 t3_thread_search: (input) =>
103 Effect.gen(function* () {
104 const { caller } = yield* readCaller();
105 const { projectId: requested, ...query } = input;
106 // Like the other project tools, an omitted project means the caller's own; a client
107 // outside a thread searches every project.
108 const projectId = requested ?? caller?.projectId;
109 const threadSearch = yield* ThreadSearch.ThreadSearch;
110 const result = yield* threadSearch.search(query).pipe(Effect.mapError(unavailable));
111 return {
112 matches:
113 projectId === undefined
114 ? result.matches
115 : result.matches.filter((match) => match.projectId === projectId),
116 };
117 }),
118 t3_thread_fork: (input) =>
119 Effect.gen(function* () {
120 const { threads, projection } = yield* readWritableThread(input.threadId);
121 const commandId = yield* newCommandId();
122 const targetThreadId = ThreadId.make(`${commandId}:fork`);
123 const result = yield* threads
124 .dispatch({
125 type: "thread.fork",
126 commandId,
127 sourceThreadId: projection.thread.id,
128 targetThreadId,
129 sourcePoint: input.sourcePoint,
130 ...(input.title === undefined ? {} : { title: input.title }),
131 createdBy: "agent",
132 creationSource: "mcp",
133 })
134 .pipe(Effect.mapError(unavailable));
135 return { sequence: result.sequence, targetThreadId };
136 }),
137 t3_thread_merge_back: (input) =>
138 Effect.gen(function* () {
139 const context = yield* readWritableThread(input.targetThreadId);
140 const source = yield* readWritableThread(input.sourceThreadId);
141 const result = yield* context.threads
142 .dispatch({
143 type: "thread.merge_back",
144 commandId: yield* newCommandId(),
145 sourceThreadId: source.projection.thread.id,
146 targetThreadId: input.targetThreadId,
147 sourcePoint: input.sourcePoint,
148 createdBy: "agent",
149 creationSource: "mcp",
150 })
151 .pipe(Effect.mapError(unavailable));
152 return { sequence: result.sequence, targetThreadId: input.targetThreadId };
153 }),
154 t3_thread_transfers: (input) =>
155 Effect.gen(function* () {
156 const { projection } = yield* readThread(input.threadId, ["contextTransfers"]);
157 return {
158 transfers: projection.contextTransfers.map(
159 ({ id, sourceThreadId, targetThreadId, status }) => ({
160 id,
161 sourceThreadId,
162 targetThreadId,
163 status,
164 }),
165 ),
166 };
167 }),
168 t3_thread_configuration: (input) =>
169 Effect.gen(function* () {
170 const {
171 projection: { thread },
172 } = yield* readThread(input.threadId);
173 return {
174 threadId: thread.id,
175 modelSelection: thread.modelSelection,
176 runtimeMode: thread.runtimeMode,
177 interactionMode: thread.interactionMode,
178 };
179 }),
180 t3_thread_configure: (input) =>
181 Effect.gen(function* () {
182 const {
183 threads,
184 projection: { thread },
185 } = yield* readWritableThread(input.threadId);
186 const type = modelSelectionCommandType(thread.providerInstanceId, input.modelSelection);
187 const result = yield* threads
188 .dispatch({
189 type,
190 threadId: thread.id,
191 commandId: yield* newCommandId(),
192 modelSelection: input.modelSelection,
193 })
194 .pipe(Effect.mapError(unavailable));
195 return { sequence: result.sequence };
196 }),
197 t3_pending_request_list: (input) =>
198 Effect.gen(function* () {
199 const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
200 return {
201 requestIds: projection.runtimeRequests
202 .filter((request) => request.kind === "user_input" && request.status === "pending")
203 .map((request) => request.id),
204 };
205 }),
206 t3_pending_request_read: (input) =>
207 Effect.gen(function* () {
208 const { item } = yield* readQuestion(input);
209 return { requestId: input.requestId, questions: item.questions };
210 }),
211 t3_pending_request_respond: (input) =>
212 Effect.gen(function* () {
213 const { threads, projection } = yield* readQuestion(input, true);
214 const result = yield* threads
215 .dispatch({
216 type: "runtime-request.respond",
217 threadId: projection.thread.id,
218 commandId: yield* newCommandId(),
219 requestId: input.requestId,
220 answers: input.answers,
221 })
222 .pipe(Effect.mapError(unavailable));
223 return { sequence: result.sequence };
224 }),
225 t3_queue_list: (input) =>
226 Effect.gen(function* () {
227 const { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
228 const runs = queuedRunsInDeliveryOrder(projection);
229 const cursor = input.cursor ?? 0;
230 const end = cursor + (input.limit ?? 20);
231 return {
232 items: runs.slice(cursor, end).flatMap((run) => {
233 const entry = queueEntry(projection, run.id, 1000);
234 return entry === undefined ? [] : [entry];
235 }),
236 nextCursor: end < runs.length ? end : null,
237 };
238 }),
239 t3_queue_read: (input) =>
240 Effect.gen(function* () {
241 const { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
242 const entry = queueEntry(projection, input.queuedRunId, 16000);
243 return (
244 entry ??
245 (yield* new OrchestratorMcpFailure({
246 code: "invalid_request",
247 message: "The queued message was not found.",
248 }))
249 );
250 }),
251 t3_queue_edit: (input) =>
252 dispatch(input.threadId, (common) => ({
253 ...common,
254 type: "queued-run.edit",
255 runId: input.queuedRunId,
256 text: input.text,
257 })),
258 t3_queue_cancel: (input) =>
259 dispatch(input.threadId, (common) => ({
260 ...common,
261 type: "queued-run.cancel",
262 runId: input.queuedRunId,
263 })),
264 t3_queue_reorder: (input) =>
265 dispatch(input.threadId, (common) => ({
266 ...common,
267 type: "queued-run.reorder",
268 runId: input.queuedRunId,
269 beforeRunId: input.beforeRunId,
270 })),
271 t3_queue_promote_to_steer: (input) =>
272 dispatch(input.threadId, (common) => ({
273 ...common,
274 type: "queued-message.promote-to-steer",
275 queuedRunId: input.queuedRunId,
276 targetRunId: input.targetRunId,
277 })),
278 t3_thread_organize: (input) =>
279 Effect.gen(function* () {
280 const { threads, projection } = yield* readWritableThread(input.threadId);
281 const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
282 let command: OrchestrationV2Command;
283 switch (input.action) {
284 case "snooze":
285 if (input.snoozedUntil === undefined) {
286 return yield* new OrchestratorMcpFailure({
287 code: "invalid_request",
288 message: "snooze requires snoozedUntil.",
289 });
290 }
291 command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil };
292 break;
293 case "unsnooze":
294 case "unsettle":
295 command = { ...common, type: `thread.${input.action}`, reason: "user" };
296 break;
297 case "mark_unread":
298 command = { ...common, type: "thread.mark-unread" };
299 break;
300 default:
301 command = { ...common, type: `thread.${input.action}` };
302 }
303 const result = yield* threads.dispatch(command).pipe(Effect.mapError(unavailable));
304 return { sequence: result.sequence };
305 }),
306});