The best way to control Claude Code, Codex and more from any computer or phone

main
ts 266 lines 10.2 KB
Raw
1 import {
2 OrchestratorMcpEnvironmentTarget,
3 ScheduledTaskId,
4 ScheduledTask,
5 OrchestrationSearchThreadsInput,
6 OrchestrationThreadSearchMatch,
7 OrchestrationV2ThreadForkSourcePoint,
8 OrchestrationV2ContextTransfer,
9 TrimmedNonEmptyString,
10 ModelSelection,
11 RuntimeMode,
12 ProviderInteractionMode,
13 RuntimeRequestId,
14 ProviderUserInputAnswers,
15 IsoDateTime,
16 OrchestratorMcpFailure,
17 OrchestrationV2DispatchCommandResult,
18 ThreadId,
19 RunId,
20 NonNegativeInt,
21 ProjectId,
22 clampedPositiveInt,
23 } from "@t3tools/contracts";
24 import * as SecureRandom from "effect/crypto/SecureRandom";
25 import * as Schema from "effect/Schema";
26 import { McpSchema, Tool, Toolkit } from "effect/ai";
27
28 import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
29 import * as ScheduledTaskService from "../../../scheduledTasks/ScheduledTaskService.ts";
30 import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
31 import * as McpInvocationContext from "../../McpInvocationContext.ts";
32
33 const ThreadOrganizeTool = Tool.make("t3_thread_organize", {
34 description:
35 "Pin, snooze, settle, archive, or mark a thread unread. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active.",
36 parameters: Schema.Struct({
37 environmentId: OrchestratorMcpEnvironmentTarget,
38 threadId: Schema.optional(ThreadId),
39 action: Schema.Literals([
40 "pin",
41 "unpin",
42 "snooze",
43 "unsnooze",
44 "settle",
45 "unsettle",
46 "archive",
47 "unarchive",
48 "mark_unread",
49 ]),
50 snoozedUntil: Schema.optional(IsoDateTime),
51 }),
52 success: Schema.Union([
53 OrchestrationV2DispatchCommandResult,
54 Schema.Struct({ settlesWhenTurnEnds: Schema.Literal(true) }),
55 ]),
56 failure: OrchestratorMcpFailure,
57 failureMode: "return" as const,
58 dependencies: [
59 McpInvocationContext.McpInvocationContext,
60 ThreadManagementService.ThreadManagementService,
61 SecureRandom.SecureRandom,
62 ],
63 })
64 .annotate(Tool.Title, "Organize a thread")
65 .annotate(Tool.Strict, true)
66 .annotate(Tool.Destructive, true);
67
68 const commandTool = {
69 success: OrchestrationV2DispatchCommandResult,
70 failure: OrchestratorMcpFailure,
71 failureMode: "return" as const,
72 dependencies: [
73 McpInvocationContext.McpInvocationContext,
74 ThreadManagementService.ThreadManagementService,
75 SecureRandom.SecureRandom,
76 ],
77 };
78 const queueEntry = Schema.Struct({
79 queuedRunId: RunId,
80 text: Schema.String,
81 truncated: Schema.Boolean,
82 });
83 const QUEUE_READ_ACTIONS = ["list", "read"] as const;
84 const QueueTool = Tool.make("t3_queue", {
85 ...commandTool,
86 description:
87 "Manage a thread's queued messages. Omit `threadId` for this thread. list: send order, paged by `cursor` and `limit`. read: up to 16,000 chars of one. edit: replace its `text`; attachments stay. cancel. reorder: before `beforeRunId`, or to the end with null. promote_to_steer: send it now as steering to active `targetRunId`. Writes fail once the run is no longer queued.",
88 parameters: Schema.Struct({
89 action: Schema.Literals([
90 ...QUEUE_READ_ACTIONS,
91 "edit",
92 "cancel",
93 "reorder",
94 "promote_to_steer",
95 ]),
96 environmentId: OrchestratorMcpEnvironmentTarget,
97 threadId: Schema.optional(ThreadId),
98 queuedRunId: Schema.optional(RunId),
99 text: Schema.optional(Schema.String.check(Schema.isMaxLength(100000))),
100 beforeRunId: Schema.optional(Schema.NullOr(RunId)),
101 targetRunId: Schema.optional(RunId),
102 cursor: Schema.optional(NonNegativeInt),
103 limit: Schema.optional(clampedPositiveInt(100)),
104 }),
105 success: Schema.Union([
106 Schema.Struct({ items: Schema.Array(queueEntry), nextCursor: Schema.NullOr(NonNegativeInt) }),
107 queueEntry,
108 OrchestrationV2DispatchCommandResult,
109 ]),
110 }).annotate(Tool.Destructive, true);
111
112 const question = Schema.Struct({
113 id: Schema.String,
114 header: Schema.String,
115 question: Schema.String,
116 options: Schema.Array(
117 Schema.Struct({
118 label: Schema.String,
119 description: Schema.String,
120 value: Schema.optional(Schema.String),
121 preview: Schema.optional(Schema.String),
122 }),
123 ),
124 multiSelect: Schema.optional(Schema.Boolean),
125 allowCustomAnswer: Schema.optional(Schema.Boolean),
126 initialAnswer: Schema.optional(Schema.String),
127 required: Schema.optional(Schema.Boolean),
128 });
129 const PendingRequestTool = Tool.make("t3_pending_request", {
130 ...commandTool,
131 description:
132 "Pending user questions in a thread. Omit `threadId` for this thread. list: their ids; approvals are not listed. read: one by `requestId`. respond: answer one with `answers`; this cannot approve a permission request.",
133 parameters: Schema.Struct({
134 action: Schema.Literals(["list", "read", "respond"]),
135 environmentId: OrchestratorMcpEnvironmentTarget,
136 threadId: Schema.optional(ThreadId),
137 requestId: Schema.optional(RuntimeRequestId),
138 answers: Schema.optional(ProviderUserInputAnswers),
139 }),
140 success: Schema.Union([
141 Schema.Struct({ requestIds: Schema.Array(RuntimeRequestId) }),
142 Schema.Struct({ requestId: RuntimeRequestId, questions: Schema.Array(question) }),
143 OrchestrationV2DispatchCommandResult,
144 ]),
145 })
146 .annotate(Tool.Destructive, true)
147 .annotate(Tool.OpenWorld, true);
148
149 const threadConfiguration = Schema.Struct({
150 threadId: ThreadId,
151 modelSelection: ModelSelection,
152 runtimeMode: RuntimeMode,
153 interactionMode: ProviderInteractionMode,
154 });
155 const ThreadConfigureTool = Tool.make("t3_thread_configure", {
156 ...commandTool,
157 description:
158 "Read a thread's provider, model, and modes, or set its provider, model, and options with `modelSelection`. Omit `threadId` for this thread. Permission modes stay. Values from `orchestrator_capabilities`.",
159 parameters: Schema.Struct({
160 environmentId: OrchestratorMcpEnvironmentTarget,
161 threadId: Schema.optional(ThreadId),
162 modelSelection: Schema.optional(ModelSelection),
163 }),
164 success: Schema.Union([threadConfiguration, OrchestrationV2DispatchCommandResult]),
165 }).annotate(Tool.Destructive, true);
166
167 const ThreadTransferTool = Tool.make("t3_thread_transfer", {
168 ...commandTool,
169 description:
170 "Move context between threads. Omit `threadId` for this thread. fork: copy it from `sourcePoint` (default latest stable run) into a new thread with the same setup; no turn runs yet. merge_back: merge it from `sourcePoint` into a related `targetThreadId` in the same project. status: its context transfers.",
171 parameters: Schema.Struct({
172 action: Schema.Literals(["fork", "merge_back", "status"]),
173 environmentId: OrchestratorMcpEnvironmentTarget,
174 threadId: Schema.optional(ThreadId),
175 sourcePoint: Schema.optional(OrchestrationV2ThreadForkSourcePoint),
176 targetThreadId: Schema.optional(ThreadId),
177 title: Schema.optional(TrimmedNonEmptyString),
178 }),
179 success: Schema.Union([
180 Schema.Struct({ sequence: NonNegativeInt, targetThreadId: ThreadId }),
181 Schema.Struct({
182 transfers: Schema.Array(
183 Schema.Struct({
184 id: OrchestrationV2ContextTransfer.fields.id,
185 sourceThreadId: OrchestrationV2ContextTransfer.fields.sourceThreadId,
186 targetThreadId: OrchestrationV2ContextTransfer.fields.targetThreadId,
187 status: OrchestrationV2ContextTransfer.fields.status,
188 }),
189 ),
190 }),
191 ]),
192 }).annotate(Tool.Destructive, true);
193
194 const ThreadSearchTool = Tool.make("t3_thread_search", {
195 ...commandTool,
196 description:
197 "Search active threads by title, branch, PR, project, then message text. Skips subagent threads. `projectId`: one project, else yours, else all outside a thread. Not exhaustive.",
198 parameters: Schema.Struct({
199 environmentId: OrchestratorMcpEnvironmentTarget,
200 ...OrchestrationSearchThreadsInput.fields,
201 projectId: Schema.optional(ProjectId),
202 }),
203 success: Schema.Struct({
204 currentThreadId: Schema.optional(Schema.NullOr(ThreadId)),
205 matches: Schema.Array(
206 Schema.Struct({
207 threadId: OrchestrationThreadSearchMatch.fields.threadId,
208 projectId: OrchestrationThreadSearchMatch.fields.projectId,
209 title: Schema.String,
210 link: Schema.optional(Schema.String),
211 source: Schema.Literals(["title", "user", "assistant"]),
212 snippet: Schema.optional(OrchestrationThreadSearchMatch.fields.snippet),
213 messageCreatedAt: Schema.optional(OrchestrationThreadSearchMatch.fields.messageCreatedAt),
214 }),
215 ),
216 }),
217 dependencies: [...commandTool.dependencies, ThreadSearch.ThreadSearch],
218 })
219 .annotate(Tool.Readonly, true)
220 .annotate(Tool.Destructive, false);
221
222 const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {
223 ...commandTool,
224 description:
225 "Run one scheduled task now. Needs a full-access or default caller. Returns its thread, or null if not started. Success means started, not finished.",
226 parameters: Schema.Struct({
227 environmentId: OrchestratorMcpEnvironmentTarget,
228 taskId: ScheduledTaskId,
229 }),
230 success: Schema.Struct({
231 taskId: ScheduledTaskId,
232 threadId: ScheduledTask.fields.threadId,
233 link: Schema.optional(Schema.String),
234 lastRunStatus: ScheduledTask.fields.lastRunStatus,
235 lastRunError: ScheduledTask.fields.lastRunError,
236 runCount: NonNegativeInt,
237 nextRunAt: ScheduledTask.fields.nextRunAt,
238 }),
239 dependencies: [...commandTool.dependencies, ScheduledTaskService.ScheduledTaskService],
240 })
241 .annotate(Tool.Destructive, true)
242 .annotate(Tool.OpenWorld, true);
243
244 const SubmitOutputTool = Tool.make("t3_submit_output", {
245 ...commandTool,
246 description:
247 "Return this turn's result as data, when the message asked for one. `json`: JSON text matching the schema it gave. A rejection says what did not fit; fix it and call again.",
248 // Stored on the run, which every client of the thread holds.
249 parameters: Schema.Struct({ json: Schema.String.check(Schema.isMaxLength(200000)) }),
250 success: Schema.Struct({ runId: RunId }),
251 })
252 // It writes only the caller's own run, so a read-only or plan-mode agent can still answer.
253 .annotate(Tool.Readonly, true)
254 .annotate(Tool.Destructive, false)
255 .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients);
256
257 export const ThreadToolkit = Toolkit.make(
258 ScheduledTaskRunTool,
259 ThreadSearchTool,
260 ThreadConfigureTool,
261 ThreadTransferTool,
262 ThreadOrganizeTool,
263 PendingRequestTool,
264 QueueTool,
265 SubmitOutputTool,
266 );