Open History to see the last commit
1import {
2 OrchestratorMcpCapabilitiesInput,
3 OrchestratorMcpCapabilitiesResult,
4 OrchestrationV2StopWorkflowInput,
5 OrchestratorMcpCreateThreadsInput,
6 OrchestratorMcpCreateThreadsResult,
7 OrchestratorMcpDelegateTaskInput,
8 OrchestratorMcpDelegateTaskResult,
9 OrchestratorMcpDeleteScheduledTaskInput,
10 OrchestratorMcpDeleteScheduledTaskResult,
11 OrchestratorMcpRequestSecretInput,
12 OrchestratorMcpRequestSecretResult,
13 OrchestratorMcpFailure,
14 OrchestratorMcpListScheduledTasksInput,
15 OrchestratorMcpListScheduledTasksResult,
16 OrchestratorMcpScheduleTaskInput,
17 OrchestratorMcpScheduleTaskResult,
18 OrchestratorMcpTaskCancelInput,
19 OrchestratorMcpTaskCancelResult,
20 OrchestratorMcpUpdateScheduledTaskInput,
21 OrchestratorMcpTaskStatusInput,
22 OrchestratorMcpThreadInterruptInput,
23 OrchestratorMcpThreadInterruptResult,
24 OrchestratorMcpThreadListInput,
25 OrchestratorMcpThreadListResult,
26 OrchestratorMcpThreadReadInput,
27 OrchestratorMcpThreadReadResult,
28 OrchestratorMcpThreadSendInput,
29 OrchestratorMcpThreadSendResult,
30 OrchestratorMcpThreadWaitInput,
31 OrchestratorMcpThreadWaitResult,
32 ThreadMetadataMcpUpdateInput,
33 ThreadMetadataMcpUpdateResult,
34 TrimmedNonEmptyString,
35} from "@t3tools/contracts";
36import { Tool, Toolkit } from "effect/ai";
37import * as Schema from "effect/Schema";
38
39import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
40import * as McpInvocationContext from "../../McpInvocationContext.ts";
41import * as OrchestratorMcpService from "../../OrchestratorMcpService.ts";
42import * as ThreadMetadataMcpService from "../../ThreadMetadataMcpService.ts";
43
44const dependencies = [
45 McpInvocationContext.McpInvocationContext,
46 ThreadManagementService.ThreadManagementService,
47 OrchestratorMcpService.OrchestratorMcpService,
48];
49const threadMetadataDependencies = [
50 McpInvocationContext.McpInvocationContext,
51 ThreadManagementService.ThreadManagementService,
52 ThreadMetadataMcpService.ThreadMetadataMcpService,
53];
54
55const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
56 description:
57 "List the V2 provider instances, a short list of their models from the same live catalog as the composer, inherited runtime settings, and app-owned orchestration features available to this caller. The list has the user's favorite and custom models, your own model, every current Codex, Claude, Muse and Grok model, and the first 8 current models of other providers. Other legacy models are left out. omittedModels counts models left out; pass search, such as 'sonnet 4.6', to find them. delegate_task accepts any catalog model, listed or not. For a separate top-level thread in a new or existing worktree, use t3_thread_launch with workspaceStrategy.",
58 parameters: OrchestratorMcpCapabilitiesInput,
59 success: OrchestratorMcpCapabilitiesResult,
60 failure: OrchestratorMcpFailure,
61 failureMode: "return",
62 dependencies,
63})
64 .annotate(Tool.Title, "Get orchestration capabilities")
65 .annotate(Tool.Readonly, true)
66 .annotate(Tool.Destructive, false)
67 .annotate(Tool.Idempotent, true);
68
69const DelegateTaskTool = Tool.make("delegate_task", {
70 description:
71 "Needs an agent running inside a T3 thread. Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Choose providers and models from orchestrator_capabilities, which uses the same live catalog as the composer. Prefer native subagent tools for same-provider work only when they support the chosen model and no model options are requested or inherited. Use this for any model missing from the native tool, including same-provider work, for cross-provider work, or for explicitly T3-owned child tasks. For independent T3 delegated review rounds, call delegate_task again with the original brief, prior findings, responses, and unresolved objections in the task prompt. Track each round by its own taskId and use a distinct clientRequestId per round, stable across retries of that round. For a follow-up that needs the same child's conversation, use t3_thread_send on its childThreadId. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Use delegate_task when model options are requested or the child keeps the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities, even for native-supported models. Native subagents cannot reliably apply T3 model options. Set target.options using advertised IDs: Claude {effort: 'max', fastMode: true}; Codex {reasoningEffort: 'max', serviceTier: 'priority'}. Check providerInstanceId, model, and options in the result. Provider/model and modes inherit unless overridden. Options inherit only for the same instance and model; explicit entries override individual values and [] or {} clears them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, a pending approval, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. If pendingApproval is set, read the fresh full request in childThreadId before responding: the record can outlive its provider callback. It grants no approval authority; decisions remain with the child's existing approval holder, and pending request tools answer questions only. The child keeps running and its completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
72 parameters: OrchestratorMcpDelegateTaskInput,
73 success: OrchestratorMcpDelegateTaskResult,
74 failure: OrchestratorMcpFailure,
75 failureMode: "return",
76 dependencies,
77})
78 .annotate(Tool.Title, "Delegate a child task")
79 .annotate(Tool.Destructive, true)
80 .annotate(Tool.OpenWorld, true);
81
82const TaskStatusTool = Tool.make("task_status", {
83 description:
84 "Needs an agent running inside a T3 thread. Read a T3-owned delegated task created by this parent thread. childRunId identifies the original delegated run. workState distinguishes working, waiting_for_children, and result_available; a completed turn with live nested work is not a completed task. summary is the final task result, including provider errors on failure, and remains stable after publication. hasPendingChildRuns reports later queued or executing turns in the backing child thread, even after the task is terminal; it does not reopen the task, and task_cancel stops those turns too. Turns held in a stopped queue wait for the user and do not count. latestTerminal* provides later non-monitor turn results; latestTerminalSummary and latestTerminalResultContextTransferId are independently null when they exactly repeat summary and resultContextTransferId, respectively. pendingApproval identifies the oldest pending live approval for this task's own unfinished work. Read the fresh full request in childThreadId before responding: the record can outlive its provider callback and grants no approval authority. Decisions remain with the child's existing approval holder. Reading a terminal result acknowledges its automatic parent delivery.",
85 parameters: OrchestratorMcpTaskStatusInput,
86 success: OrchestratorMcpDelegateTaskResult,
87 failure: OrchestratorMcpFailure,
88 failureMode: "return",
89 dependencies,
90})
91 .annotate(Tool.Title, "Get delegated task status")
92 .annotate(Tool.Readonly, false)
93 .annotate(Tool.Destructive, false)
94 .annotate(Tool.Idempotent, true);
95
96const TaskCancelTool = Tool.make("task_cancel", {
97 description:
98 "Needs an agent running inside a T3 thread. Stop a T3-owned delegated task and dispose its automatic parent delivery. Its child thread stops like a user Stop: the running turn is interrupted, other queued turns are held, pull request watches end, and the tasks it delegated stop too. The task's own queued turn is cancelled, including when held in a stopped queue. This includes later child-thread runs, even after the task is terminal. A terminal task returns its existing status, and published task results remain available.",
99 parameters: OrchestratorMcpTaskCancelInput,
100 success: OrchestratorMcpTaskCancelResult,
101 failure: OrchestratorMcpFailure,
102 failureMode: "return",
103 dependencies,
104})
105 .annotate(Tool.Title, "Cancel delegated task")
106 .annotate(Tool.Destructive, true);
107
108const WorkflowStopTool = Tool.make("t3_workflow_stop", {
109 description:
110 "Stop one running Claude workflow in a T3 thread. Use the workflow coordinator's subagentId returned by t3_thread_read with view='activity'. Stops the whole workflow, including its phases and agents. Does not stop the parent thread or other workflows. Individual workflow phases and agents cannot be stopped separately.",
111 parameters: OrchestrationV2StopWorkflowInput,
112 success: Schema.Struct({}),
113 failure: OrchestratorMcpFailure,
114 failureMode: "return",
115 dependencies,
116})
117 .annotate(Tool.Title, "Stop a workflow")
118 .annotate(Tool.Destructive, true);
119
120const BackgroundWaitTool = Tool.make("t3_background_wait", {
121 description:
122 "Keep this thread in the user's Working list and out of their inbox while you wait for background work. Start a background command or Monitor first. Call this before you end your turn if you will act on its result when it wakes you. In taskIds, give the ID shown when the task started. The thread stays in Working until the task ends. The user is not told the work is done. Do not mark work you leave running, such as a dev server or watcher. Unmarked commands and monitors never keep the thread in Working. Pass waiting=false to remove the mark. This does not stop the task. IDs that are not running return in unmatched and change nothing. Only Claude threads support this tool. Other providers return an error.",
123 parameters: Schema.Struct({
124 taskIds: Schema.Array(TrimmedNonEmptyString).check(
125 Schema.isMinLength(1),
126 Schema.isMaxLength(20),
127 ),
128 waiting: Schema.optional(Schema.Boolean),
129 }),
130 success: Schema.Struct({
131 matched: Schema.Array(Schema.String),
132 unmatched: Schema.Array(Schema.String),
133 }),
134 failure: OrchestratorMcpFailure,
135 failureMode: "return",
136 dependencies,
137}).annotate(Tool.Title, "Wait on background work");
138
139const ScheduleTaskTool = Tool.make("schedule_task", {
140 description:
141 "Create persistent work in the app scheduler that runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text. Timers: {type:'interval', everyMs:3600000} is hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} is weekday mornings; report the returned nextRunAt. Webhook dedupe accepts replayKey and coalesceKey templates with coalesceWindowSeconds (10–3600, default 120); replay keys expire after 7 days and coalescing keeps the latest payload in a window measured from its first delivery. Webhooks: {type:'webhook'} runs once per request to a generated URL. The run sees the request ONLY through prompt placeholders: {{body.path}} (e.g. {{body.action}}, {{body.release.tag_name}}), {{headers.name}}, {{query.name}}, {{body}}, or {{request}} (method, headers with credentials redacted, and body). Each value arrives framed as untrusted request data, and $skill, @file or /command mentions inside it do not act; without a signature, anyone with the URL can trigger a run. For a sender that signs requests, first call request_secret so the user enters the secret privately (never ask for it in chat or invent one), then set signature with the returned secretRef, e.g. GitHub: {type:'webhook', signature:{header:'x-hub-signature-256', encoding:'hex', prefix:'sha256=', secretRef}}. To run only for some requests, add filters, all of which must match, e.g. filters:[{path:'headers.x-github-event', op:'equals', value:'pull_request'}, {path:'body.action', op:'in', value:['opened','reopened']}]; ops are equals, notEquals, in, startsWith and exists. A path segment ending in [] fans out over an array: {path:'body.issue.labels[].name', op:'equals', value:'needs more info'} matches when any label has that name, and notEquals only when none does. The result's webhookUrl is the public URL to give the user; if it is absent, this environment has no T3 Connect managed tunnel, so tell the user to enable T3 Connect remote access rather than sharing a path. Omit projectId for this thread's project. In this thread's project, runs post into THIS thread by default (bindToCurrentThread=true), which suits an orchestrator that sees every trigger, delegates work, and can dedupe against what is in flight; use false only when the user wants a fresh top-level thread per run. Elsewhere each run launches a fresh thread. Provider, model, and runtime settings inherit from this thread, or from the project default when there is no calling thread.",
142 parameters: OrchestratorMcpScheduleTaskInput,
143 success: OrchestratorMcpScheduleTaskResult,
144 failure: OrchestratorMcpFailure,
145 failureMode: "return",
146 dependencies,
147})
148 .annotate(Tool.Title, "Schedule a recurring task")
149 .annotate(Tool.Destructive, true)
150 .annotate(Tool.OpenWorld, true);
151
152const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", {
153 parameters: OrchestratorMcpListScheduledTasksInput,
154 description:
155 "List recurring scheduled tasks in a project (omit projectId for the calling thread's project, or every project when there is no calling thread), including their id, schedule, prompt, enabled state, bound thread, next run time, and last run status. Use the returned scheduledTaskId with update_scheduled_task or delete_scheduled_task.",
156 success: OrchestratorMcpListScheduledTasksResult,
157 failure: OrchestratorMcpFailure,
158 failureMode: "return",
159 dependencies,
160})
161 .annotate(Tool.Title, "List scheduled tasks")
162 .annotate(Tool.Readonly, true)
163 .annotate(Tool.Destructive, false)
164 .annotate(Tool.Idempotent, true);
165
166const UpdateScheduledTaskTool = Tool.make("update_scheduled_task", {
167 description:
168 "Update an existing scheduled task by scheduledTaskId (from list_scheduled_tasks). Webhook schedule dedupe accepts replayKey, coalesceKey, and coalesceWindowSeconds (10–3600, default 120) to suppress replays for 7 days and retain the latest payload in each fixed window. Only the provided fields change; omit a field to leave it as-is. Use enabled=false to pause a task without deleting it. Set bindToCurrentThread to move the task between posting into this thread and launching a fresh thread per run. A webhook schedule without filters keeps the stored filters; pass filters to replace them, or filters:[] to clear them.",
169 parameters: OrchestratorMcpUpdateScheduledTaskInput,
170 success: OrchestratorMcpScheduleTaskResult,
171 failure: OrchestratorMcpFailure,
172 failureMode: "return",
173 dependencies,
174})
175 .annotate(Tool.Title, "Update a scheduled task")
176 .annotate(Tool.Destructive, true);
177
178const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
179 description:
180 "Permanently delete a scheduled task by scheduledTaskId (from list_scheduled_tasks). The task stops running immediately. To keep it but stop runs, use update_scheduled_task with enabled=false instead.",
181 parameters: OrchestratorMcpDeleteScheduledTaskInput,
182 success: OrchestratorMcpDeleteScheduledTaskResult,
183 failure: OrchestratorMcpFailure,
184 failureMode: "return",
185 dependencies,
186})
187 .annotate(Tool.Title, "Delete a scheduled task")
188 .annotate(Tool.Destructive, true);
189
190const RequestSecretTool = Tool.make("request_secret", {
191 description:
192 "Ask the user for a secret (a token, API key, signing secret, password) through a private card in this thread, and wait for them to answer. The value is kept by the app and NEVER returned to you or shown in the transcript. When saved, the result carries a secretRef: pass it to a tool that accepts one (e.g. schedule_task's signature.secretRef). It works once. Never ask for secrets in chat, and never invent one.",
193 parameters: OrchestratorMcpRequestSecretInput,
194 success: OrchestratorMcpRequestSecretResult,
195 failure: OrchestratorMcpFailure,
196 failureMode: "return",
197 dependencies,
198})
199 .annotate(Tool.Title, "Request a secret from the user")
200 .annotate(Tool.Destructive, false);
201
202const CreateThreadsTool = Tool.make("create_threads", {
203 description:
204 "Needs an agent running inside a T3 thread. Create one or more ORDINARY TOP-LEVEL T3 conversations. This is not delegation and does not create child agents/subagents. For delegated work, choose models from orchestrator_capabilities. Prefer native subagents only when they support the chosen model and no model options are requested or inherited; otherwise call delegate_task, including for same-provider work. This includes keeping the parent's provider instance and model with nonempty inheritedOptions from orchestrator_capabilities. Use create_threads for a batch of separate top-level threads sharing this checkout. Prefer t3_thread_launch for a single thread. Both require the user to request separate/new/top-level threads or conversations. Each entry may override provider, model, options, runtime mode, and interaction mode; omitted settings inherit. Project, branch, and worktree always inherit and cannot be overridden here. For independent implementation or a PR stack in its own worktree, use t3_thread_launch with workspaceStrategy instead of asking the agent to create a worktree in its prompt.",
205 parameters: OrchestratorMcpCreateThreadsInput,
206 success: OrchestratorMcpCreateThreadsResult,
207 failure: OrchestratorMcpFailure,
208 failureMode: "return",
209 dependencies,
210})
211 .annotate(Tool.Title, "Create T3 threads")
212 .annotate(Tool.Destructive, true)
213 .annotate(Tool.OpenWorld, true);
214
215const ThreadListTool = Tool.make("t3_thread_list", {
216 description:
217 "List T3 threads in a project, newest first. Omit projectId for the calling thread's project. Filter by durable run status, title, or settled state (settled=true lists threads the user or auto-settlement moved out of the active list), or snoozed state, and paginate with the returned cursor. A snoozed thread wakes early only when it asks for something or fails after snoozing; completed runs and background wakes keep it snoozed. pullRequests lists every pull request linked to each thread; linkedPullRequest is a legacy single link and can be null while pullRequests still has entries. To link a thread for the user, write `[title](t3-thread://v1/<threadId>)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread's current title.",
218 parameters: OrchestratorMcpThreadListInput,
219 success: OrchestratorMcpThreadListResult,
220 failure: OrchestratorMcpFailure,
221 failureMode: "return",
222 dependencies,
223})
224 .annotate(Tool.Title, "List T3 threads")
225 .annotate(Tool.Readonly, true)
226 .annotate(Tool.Destructive, false)
227 .annotate(Tool.Idempotent, true);
228
229const ThreadReadTool = Tool.make("t3_thread_read", {
230 description:
231 "Read durable state and a paginated timeline from any T3 thread in this environment. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Reading an untruncated terminal assistant result from this parent thread's direct app-owned child acknowledges that child's automatic completion delivery. Continue with afterPosition=nextPosition. Recover long item text with itemId and textOffset=nextTextOffset until nextTextOffset is null; offsets count UTF-16 code units. The thread also reports its snooze state and, in pullRequests, every linked pull request; linkedPullRequest is a legacy single link and can be null while pullRequests still has entries. To link a thread for the user, write `[title](t3-thread://v1/<threadId>)` with the threadId exactly as returned, not URL-encoded; T3 Code shows the thread's current title.",
232 parameters: OrchestratorMcpThreadReadInput,
233 success: OrchestratorMcpThreadReadResult,
234 failure: OrchestratorMcpFailure,
235 failureMode: "return",
236 dependencies,
237})
238 .annotate(Tool.Title, "Read a T3 thread")
239 .annotate(Tool.Strict, true)
240 .annotate(Tool.Readonly, false)
241 .annotate(Tool.Destructive, false)
242 .annotate(Tool.Idempotent, true);
243
244const ThreadUpdateTool = Tool.make("t3_thread_update", {
245 description:
246 "Update metadata for a thread. Omit threadId to update this thread. Use action='rename' with title, action='regenerate_title' with no extra field, action='link_pull_request' with pullRequest, or action='unlink_pull_request'. Workspace and branch changes are intentionally not supported. clientRequestId makes retries idempotent.",
247 parameters: ThreadMetadataMcpUpdateInput,
248 success: ThreadMetadataMcpUpdateResult,
249 failure: OrchestratorMcpFailure,
250 failureMode: "return",
251 dependencies: threadMetadataDependencies,
252})
253 .annotate(Tool.Title, "Update T3 thread metadata")
254 .annotate(Tool.Destructive, true)
255 .annotate(Tool.Idempotent, false);
256
257const ThreadSendTool = Tool.make("t3_thread_send", {
258 description:
259 "Send a message to any T3 thread in this environment. The target cannot have broader permission modes than the caller. Use delegate_task with the full review context and a new clientRequestId for independent review rounds. For a follow-up that needs the same child's conversation, send to its childThreadId. After the original task completes, a requested follow-up creates a fresh task in that child thread and returns taskId when it starts a turn or restarts a turn without its own task; its completion notifies the parent, and the original result stays unchanged. A steer that joins a running turn returns that turn's task, if it has one. mode='auto' starts an idle thread, steers a fully active turn, or queues behind a turn that is not yet steerable. Use queue for a separate follow-up turn, steer for an in-flight update, or restart to interrupt-and-restart the active turn. clientRequestId makes retries idempotent.",
260 parameters: OrchestratorMcpThreadSendInput,
261 success: OrchestratorMcpThreadSendResult,
262 failure: OrchestratorMcpFailure,
263 failureMode: "return",
264 dependencies,
265})
266 .annotate(Tool.Title, "Send to a T3 thread")
267 .annotate(Tool.Destructive, true)
268 .annotate(Tool.OpenWorld, true);
269
270const ThreadWaitTool = Tool.make("t3_thread_wait", {
271 description:
272 "Wait for a T3 thread run to reach a terminal durable state. Without runId, the latest run at call time is selected; an idle thread returns immediately. Timeout does not interrupt work, so call again or use t3_thread_read/list after timedOut=true. Waiting reports status only and does not acknowledge a delegated result.",
273 parameters: OrchestratorMcpThreadWaitInput,
274 success: OrchestratorMcpThreadWaitResult,
275 failure: OrchestratorMcpFailure,
276 failureMode: "return",
277 dependencies,
278})
279 .annotate(Tool.Title, "Wait for a T3 thread")
280 .annotate(Tool.Readonly, true)
281 .annotate(Tool.Destructive, false)
282 .annotate(Tool.Idempotent, true);
283
284const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
285 description:
286 "Request interruption of a running turn in any T3 thread in this environment. Without runId, the newest interruptible run is selected. Terminal runs and threads without an active turn return without another side effect. clientRequestId makes retries idempotent.",
287 parameters: OrchestratorMcpThreadInterruptInput,
288 success: OrchestratorMcpThreadInterruptResult,
289 failure: OrchestratorMcpFailure,
290 failureMode: "return",
291 dependencies,
292})
293 .annotate(Tool.Title, "Interrupt a T3 thread")
294 .annotate(Tool.Destructive, true);
295
296export const OrchestratorToolkit = Toolkit.make(
297 OrchestratorCapabilitiesTool,
298 DelegateTaskTool,
299 TaskStatusTool,
300 TaskCancelTool,
301 WorkflowStopTool,
302 BackgroundWaitTool,
303 ScheduleTaskTool,
304 ListScheduledTasksTool,
305 UpdateScheduledTaskTool,
306 DeleteScheduledTaskTool,
307 RequestSecretTool,
308 CreateThreadsTool,
309 ThreadListTool,
310 ThreadReadTool,
311 ThreadUpdateTool,
312 ThreadSendTool,
313 ThreadWaitTool,
314 ThreadInterruptTool,
315);