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

threadAccess.ts

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