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

threadAccess.ts

284 lines10.9 KB

1import type {
2 ProjectionRecordField,
3 ProjectionRecordFilter,
4} from "../orchestration-v2/ProjectionStore.ts";
5import {
6 CommandId,
7 type EnvironmentId,
8 OrchestratorMcpFailure,
9 type ProjectId,
10 type ProviderInstanceId,
11 type ProviderInteractionMode,
12 type RuntimeMode,
13 ThreadId,
14 type OrchestrationV2ThreadShell,
15} from "@t3tools/contracts";
16import {
17 hasThreadLinks,
18 parseThreadLinkHref,
19 threadLinkCandidates,
20 threadLinkRefs,
21} from "@t3tools/shared/threadLinks";
22import * as SecureRandom from "effect/crypto/SecureRandom";
23import * as Effect from "effect/Effect";
24​
25import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts";
26import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
27import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";
28import { fencingLinkOrigin } from "./linkOrigin.ts";
29import * as McpInvocationContext from "./McpInvocationContext.ts";
30​
31const delegatedTaskPrefix = "thread:delegated-task:";
32​
33const suggestedThreadId = (threadId: ThreadId) => {
34 if (!threadId.startsWith(delegatedTaskPrefix)) return ThreadId.make(`mcp:${threadId}`);
35 const rest = threadId.slice(delegatedTaskPrefix.length);
36 // encodeURIComponent throws on lone surrogates, which a JSON string can carry.
37 if (!rest.isWellFormed()) return null;
38 const encoded = encodeURIComponent(rest);
39 return encoded === rest ? null : ThreadId.make(`${delegatedTaskPrefix}${encoded}`);
40};
41​
42// A pasted link (bare, Markdown, or hosted) names its thread; only this environment's can be read here.
43const candidateThreadIds = (threadId: ThreadId, environmentId: EnvironmentId) => {
44 if (!hasThreadLinks(threadId)) {
45 const suggested = suggestedThreadId(threadId);
46 return suggested === null ? [] : [suggested];
47 }
48 const link = parseThreadLinkHref(threadId);
49 const refs =
50 link === null
51 ? threadLinkRefs(threadId, environmentId)
52 : threadLinkCandidates(link, environmentId);
53 return refs.filter((ref) => ref.environmentId === environmentId).map((ref) => ref.threadId);
54};
55​
56/**
57 * Agents paste bare uuids for `mcp:<uuid>` threads, unencoded delegated-task ids, and thread links.
58 * The id is never rewritten, so permission checks keyed on it still hold; the miss
59 * only names a live thread the caller could read by its full id. Ids from another
60 * machine miss here too. The link hint is static: listing links probes peers.
61 */
62export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* (
63 threads: Pick<ThreadManagement.ThreadManagementService["Service"], "getThreadShell">,
64 scope: McpInvocationContext.McpInvocationScope,
65 threadId: ThreadId,
66 message: string,
67) {
68 let suggested: ThreadId | null = null;
69 for (const candidate of candidateThreadIds(threadId, scope.environmentId)) {
70 const shell = yield* threads.getThreadShell(candidate).pipe(Effect.orElseSucceed(() => null));
71 if (shell !== null && shell.deletedAt === null) {
72 suggested = candidate;
73 break;
74 }
75 }
76 if (suggested !== null && hasThreadLinks(threadId)) {
77 return yield* new OrchestratorMcpFailure({
78 code: "thread_not_found",
79 message: `\`${threadId}\` is a thread link, not a thread id. Pass \`${suggested}\` instead.`,
80 });
81 }
82 const mcpHint = suggested === null ? "" : ` Did you mean \`${suggested}\`?`;
83 const caller =
84 scope.thread === undefined
85 ? null
86 : yield* threads.getThreadShell(scope.thread.threadId).pipe(Effect.orElseSucceed(() => null));
87 // A peer link's caller would be pointed at this machine's links, and a fenced one may not use them.
88 const linksHint =
89 scope.linkedEnvironments === false ||
90 scope.client?.linked === true ||
91 fencingLinkOrigin({ scope, caller: caller ?? undefined }) !== undefined
92 ? ""
93 : " Thread ids belong to one environment: for a thread on a linked one, find it with `t3_environment_links` and pass its `environmentId` to a tool that takes one.";
94 return yield* new OrchestratorMcpFailure({
95 code: "thread_not_found",
96 message: `${message}${mcpHint}${linksHint}`,
97 });
98});
99​
100export const unavailable = () =>
101 new OrchestratorMcpFailure({
102 code: "orchestration_error",
103 message: "The operation could not be completed.",
104 });
105​
106export const dispatchFailure = (
107 error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
108) =>
109 error._tag === "ThreadManagementProviderInstanceDisabledError" ||
110 error._tag === "OrchestratorRuntimeModeAboveCeilingError" ||
111 error._tag === "OrchestratorProviderSelectionBusyError"
112 ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
113 : (error._tag === "OrchestratorDispatchError" ||
114 error._tag === "OrchestratorCommandRejectedError") &&
115 typeof error.cause === "string" &&
116 error.cause.length > 0
117 ? new OrchestratorMcpFailure({
118 code: "orchestration_error",
119 message: Array.from(error.cause).slice(0, 1000).join(""),
120 })
121 : unavailable();
122​
123export interface CallerLimits {
124 readonly runtimeMode: RuntimeMode;
125 readonly interactionMode: ProviderInteractionMode;
127​
128export interface Caller {
129 readonly scope: McpInvocationContext.McpInvocationScope;
130 readonly threads: ThreadManagement.ThreadManagementService["Service"];
131 readonly caller: OrchestrationV2ThreadShell | undefined;
132 readonly limits: CallerLimits;
134​
135export const readCaller = Effect.fn("mcp.readCaller")(function* () {
136 const scope = yield* McpInvocationContext.McpInvocationContext;
137 if (!scope.capabilities.has("orchestration")) {
138 return yield* new OrchestratorMcpFailure({
139 code: "capability_denied",
140 message: "This credential cannot control threads.",
141 });
142 }
143 return yield* loadCaller();
144});
145​
146export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
147 const scope = yield* McpInvocationContext.McpInvocationContext;
148 const threads = yield* ThreadManagement.ThreadManagementService;
149 if (scope.thread === undefined) {
150 return {
151 scope,
152 threads,
153 caller: undefined,
154 limits: McpInvocationContext.clientModeCeiling(scope.client),
155 } satisfies Caller;
156 }
157 const caller = yield* threads
158 .getThreadShell(scope.thread.threadId)
159 .pipe(Effect.mapError(unavailable));
160 if (caller === null || caller.deletedAt !== null) {
161 return yield* new OrchestratorMcpFailure({
162 code: "thread_not_found",
163 message: "The calling thread was not found.",
164 });
165 }
166 return {
167 scope,
168 threads,
169 caller,
170 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
171 } satisfies Caller;
172});
173​
174export const assertTargetWithinLimits = (
175 limits: CallerLimits,
176 target: Pick<OrchestrationV2ThreadShell, "id" | "runtimeMode" | "interactionMode">,
177) =>
178 resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
179 Effect.andThen(resolveInteractionMode(limits.interactionMode, target.interactionMode)),
180 Effect.asVoid,
181 Effect.mapError(
182 (error) =>
183 new OrchestratorMcpFailure({
184 code: error.code,
185 message: `Thread "${target.id}" runs in ${target.runtimeMode}/${target.interactionMode}, above this caller's ${limits.runtimeMode}/${limits.interactionMode} limit. For linked calls, this limit is also capped by the link's approved access. This call does not create an approval request. Have the user act directly in the target thread through an authorized client.`,
186 }),
187 ),
188 );
189​
190/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */
191export const isLiveCallerShell = (
192 shell: Pick<
193 OrchestrationV2ThreadShell,
194 "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"
195 > | null,
196 providerInstanceId: ProviderInstanceId | undefined,
197) =>
198 shell !== null &&
199 shell.archivedAt === null &&
200 shell.providerInstanceId === providerInstanceId &&
201 (shell.activeRunId !== null ||
202 (shell.pendingBackgroundTasks?.some(
203 (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,
204 ) ??
205 false));
206​
207/** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */
208export function assertLiveCaller({ caller, scope }: Caller) {
209 if (caller === undefined) return Effect.void;
210 return isLiveCallerShell(caller, scope.thread?.providerInstanceId)
211 ? Effect.void
212 : Effect.fail(
213 new OrchestratorMcpFailure({
214 code: "parent_not_active",
215 message: "The calling provider no longer owns an active thread run.",
216 }),
217 );
219​
220export const assertFullAccess = (context: Caller, message: string) =>
221 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
222 ? Effect.void
223 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
224​
225export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
226 projectId !== undefined
227 ? Effect.succeed(projectId)
228 : context.caller !== undefined
229 ? Effect.succeed(context.caller.projectId)
230 : Effect.fail(
231 new OrchestratorMcpFailure({
232 code: "target_required",
233 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
234 }),
235 );
236​
237const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
238 threadId !== undefined
239 ? Effect.succeed(threadId)
240 : context.caller !== undefined
241 ? Effect.succeed(context.caller.id)
242 : Effect.fail(
243 new OrchestratorMcpFailure({
244 code: "target_required",
245 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
246 }),
247 );
248​
249export const readThread = Effect.fn("mcp.readThread")(function* <
250 K extends ProjectionRecordField = never,
251>(threadId?: ThreadId, fields: ReadonlyArray<K> = [], filter?: ProjectionRecordFilter) {
252 const context = yield* readCaller();
253 const targetId = yield* resolveThreadId(context, threadId);
254 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
255 if (shell === null || shell.deletedAt !== null) {
256 return yield* threadNotFound(
257 context.threads,
258 context.scope,
259 targetId,
260 "The thread was not found.",
261 );
262 }
263 const projection = yield* context.threads
264 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
265 turnItemTypes: ["user_input_request"],
266 ...filter,
267 })
268 .pipe(
269 Effect.mapError((error) =>
270 error._tag === "ThreadManagementThreadNotFoundError"
271 ? new OrchestratorMcpFailure({
272 code: "thread_not_found",
273 message: "The thread was not found.",
274 })
275 : unavailable(),
276 ),
277 );
278 return { ...context, projection };
279});
280​
281export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
282 const random = yield* SecureRandom.SecureRandom;
283 return CommandId.make(`mcp:${yield* random.uuidV4()}`);
284});