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

handlers.ts

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