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

threadAccess.ts

210 lines7.7 KB

1import type { ProjectionRecordField } from "../orchestration-v2/ProjectionStore.ts";
2import {
3 CommandId,
4 OrchestratorMcpFailure,
5 type ProjectId,
6 type ProviderInstanceId,
7 type ProviderInteractionMode,
8 type RuntimeMode,
9 ThreadId,
10 type OrchestrationV2ThreadShell,
11} from "@t3tools/contracts";
12import * as Crypto from "effect/Crypto";
13import * as Effect from "effect/Effect";
14​
15import type { OrchestratorV2Error } from "../orchestration-v2/Orchestrator.ts";
16import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
17import { resolveInteractionMode, resolveRuntimeMode } from "./delegatedTaskModes.ts";
18import * as McpInvocationContext from "./McpInvocationContext.ts";
19​
20/**
21 * Threads an agent starts over MCP are `mcp:<uuid>`, and agents often paste the
22 * bare uuid. The id is never rewritten, so permission checks keyed on it still
23 * hold; the miss only names a live thread the caller could read by its full id.
24 */
25export const threadNotFound = Effect.fn("OrchestratorMcpService.threadNotFound")(function* (
26 threads: Pick<ThreadManagement.ThreadManagementService["Service"], "getThreadShell">,
27 threadId: ThreadId,
28 message: string,
29) {
30 const prefixed = ThreadId.make(`mcp:${threadId}`);
31 const shell = yield* threads.getThreadShell(prefixed).pipe(Effect.orElseSucceed(() => null));
32 return yield* new OrchestratorMcpFailure({
33 code: "thread_not_found",
34 message:
35 shell === null || shell.deletedAt !== null
36 ? message
37 : `${message} Did you mean \`${prefixed}\`?`,
38 });
39});
40​
41export const unavailable = () =>
42 new OrchestratorMcpFailure({
43 code: "orchestration_error",
44 message: "The operation could not be completed.",
45 });
46​
47export const dispatchFailure = (
48 error: OrchestratorV2Error | ThreadManagement.ThreadManagementProviderInstanceDisabledError,
49) =>
50 error._tag === "ThreadManagementProviderInstanceDisabledError"
51 ? new OrchestratorMcpFailure({ code: "invalid_request", message: error.message })
52 : (error._tag === "OrchestratorDispatchError" ||
53 error._tag === "OrchestratorCommandRejectedError") &&
54 typeof error.cause === "string" &&
55 error.cause.length > 0
56 ? new OrchestratorMcpFailure({
57 code: "orchestration_error",
58 message: Array.from(error.cause).slice(0, 1000).join(""),
59 })
60 : unavailable();
61​
62export interface CallerLimits {
63 readonly runtimeMode: RuntimeMode;
64 readonly interactionMode: ProviderInteractionMode;
66​
67export interface Caller {
68 readonly scope: McpInvocationContext.McpInvocationScope;
69 readonly threads: ThreadManagement.ThreadManagementService["Service"];
70 readonly caller: OrchestrationV2ThreadShell | undefined;
71 readonly limits: CallerLimits;
73​
74export const readCaller = Effect.fn("mcp.readCaller")(function* () {
75 const scope = yield* McpInvocationContext.McpInvocationContext;
76 if (!scope.capabilities.has("orchestration")) {
77 return yield* new OrchestratorMcpFailure({
78 code: "capability_denied",
79 message: "This credential cannot control threads.",
80 });
81 }
82 return yield* loadCaller();
83});
84​
85export const loadCaller = Effect.fn("mcp.loadCaller")(function* () {
86 const scope = yield* McpInvocationContext.McpInvocationContext;
87 const threads = yield* ThreadManagement.ThreadManagementService;
88 if (scope.thread === undefined) {
89 return {
90 scope,
91 threads,
92 caller: undefined,
93 limits: McpInvocationContext.clientModeCeiling(scope.client),
94 } satisfies Caller;
95 }
96 const caller = yield* threads
97 .getThreadShell(scope.thread.threadId)
98 .pipe(Effect.mapError(unavailable));
99 if (caller === null || caller.deletedAt !== null) {
100 return yield* new OrchestratorMcpFailure({
101 code: "thread_not_found",
102 message: "The calling thread was not found.",
103 });
104 }
105 return {
106 scope,
107 threads,
108 caller,
109 limits: { runtimeMode: caller.runtimeMode, interactionMode: caller.interactionMode },
110 } satisfies Caller;
111});
112​
113export const assertTargetWithinLimits = (
114 limits: CallerLimits,
115 target: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
116) =>
117 resolveRuntimeMode(limits.runtimeMode, target.runtimeMode).pipe(
118 Effect.andThen(resolveInteractionMode(limits.interactionMode, target.interactionMode)),
119 Effect.asVoid,
120 );
121​
122/** Background subagents retain credentials until provider exit; archived threads and other instances cannot act. */
123export const isLiveCallerShell = (
124 shell: Pick<
125 OrchestrationV2ThreadShell,
126 "archivedAt" | "activeRunId" | "providerInstanceId" | "pendingBackgroundTasks"
127 > | null,
128 providerInstanceId: ProviderInstanceId | undefined,
129) =>
130 shell !== null &&
131 shell.archivedAt === null &&
132 shell.providerInstanceId === providerInstanceId &&
133 (shell.activeRunId !== null ||
134 (shell.pendingBackgroundTasks?.some(
135 (task) => task.kind === "subagent" && task.providerInstanceId === providerInstanceId,
136 ) ??
137 false));
138​
139/** Thread callers need a live run or its background subagent in an unarchived thread. OAuth clients rely on their session and ceiling. */
140export function assertLiveCaller({ caller, scope }: Caller) {
141 if (caller === undefined) return Effect.void;
142 return isLiveCallerShell(caller, scope.thread?.providerInstanceId)
143 ? Effect.void
144 : Effect.fail(
145 new OrchestratorMcpFailure({
146 code: "parent_not_active",
147 message: "The calling provider no longer owns an active thread run.",
148 }),
149 );
151​
152export const assertFullAccess = (context: Caller, message: string) =>
153 context.limits.runtimeMode === "full-access" && context.limits.interactionMode === "default"
154 ? Effect.void
155 : Effect.fail(new OrchestratorMcpFailure({ code: "capability_denied", message }));
156​
157export const resolveProjectId = (context: Caller, projectId: ProjectId | undefined) =>
158 projectId !== undefined
159 ? Effect.succeed(projectId)
160 : context.caller !== undefined
161 ? Effect.succeed(context.caller.projectId)
162 : Effect.fail(
163 new OrchestratorMcpFailure({
164 code: "target_required",
165 message: "Pass projectId: this MCP client is not running inside a T3 thread.",
166 }),
167 );
168​
169const resolveThreadId = (context: Caller, threadId: ThreadId | undefined) =>
170 threadId !== undefined
171 ? Effect.succeed(threadId)
172 : context.caller !== undefined
173 ? Effect.succeed(context.caller.id)
174 : Effect.fail(
175 new OrchestratorMcpFailure({
176 code: "target_required",
177 message: "Pass threadId: this MCP client is not running inside a T3 thread.",
178 }),
179 );
180​
181export const readThread = Effect.fn("mcp.readThread")(function* <
182 K extends ProjectionRecordField = never,
183>(threadId?: ThreadId, fields: ReadonlyArray<K> = []) {
184 const context = yield* readCaller();
185 const targetId = yield* resolveThreadId(context, threadId);
186 const shell = yield* context.threads.getThreadShell(targetId).pipe(Effect.mapError(unavailable));
187 if (shell === null || shell.deletedAt !== null) {
188 return yield* threadNotFound(context.threads, targetId, "The thread was not found.");
189 }
190 const projection = yield* context.threads
191 .getProjectThreadRecords({ projectId: shell.projectId, threadId: targetId }, fields, {
192 turnItemTypes: ["user_input_request"],
193 })
194 .pipe(
195 Effect.mapError((error) =>
196 error._tag === "ThreadManagementThreadNotFoundError"
197 ? new OrchestratorMcpFailure({
198 code: "thread_not_found",
199 message: "The thread was not found.",
200 })
201 : unavailable(),
202 ),
203 );
204 return { ...context, projection };
205});
206​
207export const newCommandId = Effect.fn("mcp.newCommandId")(function* () {
208 const crypto = yield* Crypto.Crypto;
209 return CommandId.make(`mcp:${yield* crypto.randomUUIDv4().pipe(Effect.orDie)}`);
210});