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

handlers.ts

303 lines10.8 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 readMutationCaller,
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 ThreadToolkitHandlersLive = ThreadToolkit.toLayer({
79 run_scheduled_task_now: (input) =>
80 Effect.gen(function* () {
81 const { caller } = yield* readMutationCaller();
82 if (
83 caller.archivedAt !== null ||
84 caller.runtimeMode !== "full-access" ||
85 caller.interactionMode !== "default"
86 )
87 return yield* new OrchestratorMcpFailure({
88 code: "capability_denied",
89 message: "Running a scheduled task requires a live full-access/default thread.",
90 });
91 const scheduler = yield* ScheduledTasks.ScheduledTaskService;
92 const { tasks } = yield* scheduler.list().pipe(Effect.mapError(unavailable));
93 if (!tasks.some((task) => task.id === input.taskId && task.projectId === caller.projectId))
94 return yield* new OrchestratorMcpFailure({
95 code: "invalid_request",
96 message: "The task was not found in the calling project.",
97 });
98 const { task } = yield* scheduler
99 .runNow({ id: input.taskId })
100 .pipe(Effect.mapError(unavailable));
101 return {
102 taskId: task.id,
103 threadId: task.threadId,
104 lastRunStatus: task.lastRunStatus,
105 runCount: task.runCount,
106 nextRunAt: task.nextRunAt,
107 };
108 }),
109 t3_thread_search: (input) =>
110 Effect.gen(function* () {
111 const { caller } = yield* readCaller();
112 const threadSearch = yield* ThreadSearch.ThreadSearch;
113 const result = yield* threadSearch.search(input).pipe(Effect.mapError(unavailable));
114 return { matches: result.matches.filter((match) => match.projectId === caller.projectId) };
115 }),
116 t3_thread_fork: (input) =>
117 Effect.gen(function* () {
118 const { threads, projection } = yield* readWritableThread();
119 const commandId = yield* newCommandId();
120 const targetThreadId = ThreadId.make(`${commandId}:fork`);
121 const result = yield* threads
122 .dispatch({
123 type: "thread.fork",
124 commandId,
125 sourceThreadId: projection.thread.id,
126 targetThreadId,
127 sourcePoint: input.sourcePoint,
128 ...(input.title === undefined ? {} : { title: input.title }),
129 createdBy: "agent",
130 creationSource: "mcp",
131 })
132 .pipe(Effect.mapError(unavailable));
133 return { sequence: result.sequence, targetThreadId };
134 }),
135 t3_thread_merge_back: (input) =>
136 Effect.gen(function* () {
137 const { threads, caller } = yield* readWritableThread(input.targetThreadId);
138 const result = yield* threads
139 .dispatch({
140 type: "thread.merge_back",
141 commandId: yield* newCommandId(),
142 sourceThreadId: caller.id,
143 targetThreadId: input.targetThreadId,
144 sourcePoint: input.sourcePoint,
145 createdBy: "agent",
146 creationSource: "mcp",
147 })
148 .pipe(Effect.mapError(unavailable));
149 return { sequence: result.sequence, targetThreadId: input.targetThreadId };
150 }),
151 t3_thread_transfers: (input) =>
152 Effect.gen(function* () {
153 const { projection } = yield* readThread(input.threadId, ["contextTransfers"]);
154 return {
155 transfers: projection.contextTransfers.map(
156 ({ id, sourceThreadId, targetThreadId, status }) => ({
157 id,
158 sourceThreadId,
159 targetThreadId,
160 status,
161 }),
162 ),
163 };
164 }),
165 t3_thread_configuration: (input) =>
166 Effect.gen(function* () {
167 const {
168 projection: { thread },
169 } = yield* readThread(input.threadId);
170 return {
171 threadId: thread.id,
172 modelSelection: thread.modelSelection,
173 runtimeMode: thread.runtimeMode,
174 interactionMode: thread.interactionMode,
175 };
176 }),
177 t3_thread_configure: (input) =>
178 Effect.gen(function* () {
179 const {
180 threads,
181 projection: { thread },
182 } = yield* readWritableThread();
183 const type = modelSelectionCommandType(thread.providerInstanceId, input.modelSelection);
184 const result = yield* threads
185 .dispatch({
186 type,
187 threadId: thread.id,
188 commandId: yield* newCommandId(),
189 modelSelection: input.modelSelection,
190 })
191 .pipe(Effect.mapError(unavailable));
192 return { sequence: result.sequence };
193 }),
194 t3_pending_request_list: (input) =>
195 Effect.gen(function* () {
196 const { projection } = yield* readThread(input.threadId, ["runtimeRequests"]);
197 return {
198 requestIds: projection.runtimeRequests
199 .filter((request) => request.kind === "user_input" && request.status === "pending")
200 .map((request) => request.id),
201 };
202 }),
203 t3_pending_request_read: (input) =>
204 Effect.gen(function* () {
205 const { item } = yield* readQuestion(input);
206 return { requestId: input.requestId, questions: item.questions };
207 }),
208 t3_pending_request_respond: (input) =>
209 Effect.gen(function* () {
210 const { threads, projection } = yield* readQuestion(input, true);
211 const result = yield* threads
212 .dispatch({
213 type: "runtime-request.respond",
214 threadId: projection.thread.id,
215 commandId: yield* newCommandId(),
216 requestId: input.requestId,
217 answers: input.answers,
218 })
219 .pipe(Effect.mapError(unavailable));
220 return { sequence: result.sequence };
221 }),
222 t3_queue_list: (input) =>
223 Effect.gen(function* () {
224 const { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
225 const runs = queuedRunsInDeliveryOrder(projection);
226 const cursor = input.cursor ?? 0;
227 const end = cursor + (input.limit ?? 20);
228 return {
229 items: runs.slice(cursor, end).flatMap((run) => {
230 const entry = queueEntry(projection, run.id, 1000);
231 return entry === undefined ? [] : [entry];
232 }),
233 nextCursor: end < runs.length ? end : null,
234 };
235 }),
236 t3_queue_read: (input) =>
237 Effect.gen(function* () {
238 const { projection } = yield* readThread(input.threadId, ["runs", "messages"]);
239 const entry = queueEntry(projection, input.queuedRunId, 16000);
240 return (
241 entry ??
242 (yield* new OrchestratorMcpFailure({
243 code: "invalid_request",
244 message: "The queued message was not found.",
245 }))
246 );
247 }),
248 t3_queue_edit: (input) =>
249 dispatch(input.threadId, (common) => ({
250 ...common,
251 type: "queued-run.edit",
252 runId: input.queuedRunId,
253 text: input.text,
254 })),
255 t3_queue_cancel: (input) =>
256 dispatch(input.threadId, (common) => ({
257 ...common,
258 type: "queued-run.cancel",
259 runId: input.queuedRunId,
260 })),
261 t3_queue_reorder: (input) =>
262 dispatch(input.threadId, (common) => ({
263 ...common,
264 type: "queued-run.reorder",
265 runId: input.queuedRunId,
266 beforeRunId: input.beforeRunId,
267 })),
268 t3_queue_promote_to_steer: (input) =>
269 dispatch(input.threadId, (common) => ({
270 ...common,
271 type: "queued-message.promote-to-steer",
272 queuedRunId: input.queuedRunId,
273 targetRunId: input.targetRunId,
274 })),
275 t3_thread_organize: (input) =>
276 Effect.gen(function* () {
277 const { threads, projection } = yield* readWritableThread(input.threadId);
278 const common = { commandId: yield* newCommandId(), threadId: projection.thread.id };
279 let command: OrchestrationV2Command;
280 switch (input.action) {
281 case "snooze":
282 if (input.snoozedUntil === undefined) {
283 return yield* new OrchestratorMcpFailure({
284 code: "invalid_request",
285 message: "snooze requires snoozedUntil.",
286 });
287 }
288 command = { ...common, type: "thread.snooze", snoozedUntil: input.snoozedUntil };
289 break;
290 case "unsnooze":
291 case "unsettle":
292 command = { ...common, type: `thread.${input.action}`, reason: "user" };
293 break;
294 case "mark_unread":
295 command = { ...common, type: "thread.mark-unread" };
296 break;
297 default:
298 command = { ...common, type: `thread.${input.action}` };
299 }
300 const result = yield* threads.dispatch(command).pipe(Effect.mapError(unavailable));
301 return { sequence: result.sequence };
302 }),
303});