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

threadAccess.ts

300 lines11.7 KB

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