Harden referenced thread reads
This commit is contained in:
1 parent
e51be69219
commit
dba8c741ab
4 files changed
+189
-29
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
@@ -14,7 +15,11 @@ import { McpSchema, McpServer } from "effect/unstable/ai";
|
||||
|
||||
import * as McpInvocationContext from "../../McpInvocationContext.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { buildThreadReferencePage, ThreadReferenceToolkitHandlersLive } from "./handlers.ts";
|
||||
import {
|
||||
buildThreadReferencePage,
|
||||
hasUserThreadReference,
|
||||
ThreadReferenceToolkitHandlersLive,
|
||||
} from "./handlers.ts";
|
||||
import { ThreadReferenceToolkit } from "./tools.ts";
|
||||
|
||||
const TestLayer = McpServer.toolkit(ThreadReferenceToolkit).pipe(
|
||||
@@ -22,9 +27,13 @@ const TestLayer = McpServer.toolkit(ThreadReferenceToolkit).pipe(
|
||||
Layer.provideMerge(McpServer.McpServer.layer),
|
||||
);
|
||||
|
||||
const makeMessage = (id: string, text: string): OrchestrationMessage => ({
|
||||
const makeMessage = (
|
||||
id: string,
|
||||
text: string,
|
||||
role: OrchestrationMessage["role"] = "user",
|
||||
): OrchestrationMessage => ({
|
||||
id: MessageId.make(id),
|
||||
role: "user",
|
||||
role,
|
||||
text,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
@@ -32,12 +41,53 @@ const makeMessage = (id: string, text: string): OrchestrationMessage => ({
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
const currentThreadId = ThreadId.make("thread-current");
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
const thread = {
|
||||
id: ThreadId.make("thread-referenced"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Referenced work",
|
||||
messages: [makeMessage("message-1", "abcdef"), makeMessage("message-2", "ghijkl")],
|
||||
} as unknown as OrchestrationThread;
|
||||
const currentThread = {
|
||||
...thread,
|
||||
id: currentThreadId,
|
||||
messages: [
|
||||
makeMessage(
|
||||
"message-reference",
|
||||
`[Referenced work](t3-thread:///${environmentId}/${thread.id})`,
|
||||
),
|
||||
],
|
||||
} as OrchestrationThread;
|
||||
const invocation = {
|
||||
environmentId,
|
||||
threadId: currentThreadId,
|
||||
providerSessionId: "provider-session-1",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["thread-reference"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
};
|
||||
const mcpServerClient = {
|
||||
clientId: 1,
|
||||
initializePayload: {
|
||||
protocolVersion: "2025-03-26",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "test", version: "1" },
|
||||
},
|
||||
getClient: Effect.die("unused"),
|
||||
};
|
||||
const projectionQueryFor = (sourceThread: OrchestrationThread) =>
|
||||
({
|
||||
getThreadDetailById: (threadId: ThreadId) =>
|
||||
Effect.succeed(
|
||||
threadId === sourceThread.id
|
||||
? Option.some(sourceThread)
|
||||
: threadId === thread.id
|
||||
? Option.some(thread)
|
||||
: Option.none(),
|
||||
),
|
||||
}) as never;
|
||||
|
||||
it("paginates within a message without losing transcript text", () => {
|
||||
const first = buildThreadReferencePage(thread, {
|
||||
@@ -67,6 +117,67 @@ it("paginates within a message without losing transcript text", () => {
|
||||
expect(longSecond.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("continues pagination across an empty message at a page boundary", () => {
|
||||
const emptyMessageThread = {
|
||||
...thread,
|
||||
messages: [
|
||||
makeMessage("message-full", "a".repeat(1_000)),
|
||||
makeMessage("message-empty", ""),
|
||||
makeMessage("message-tail", "tail"),
|
||||
],
|
||||
};
|
||||
const first = buildThreadReferencePage(emptyMessageThread, {
|
||||
threadId: thread.id,
|
||||
maxChars: 1_000,
|
||||
});
|
||||
if ("_tag" in first) throw new Error("unexpected cursor error");
|
||||
expect(first.nextCursor).toBe("1:0");
|
||||
|
||||
const second = buildThreadReferencePage(emptyMessageThread, {
|
||||
threadId: thread.id,
|
||||
cursor: first.nextCursor!,
|
||||
maxChars: 1_000,
|
||||
});
|
||||
if ("_tag" in second) throw new Error("unexpected cursor error");
|
||||
expect(second.messages.map(({ text }) => text)).toEqual(["", "tail"]);
|
||||
expect(second.nextCursor).toBeNull();
|
||||
});
|
||||
|
||||
it("only authorizes user-supplied references from the invoking environment", () => {
|
||||
expect(hasUserThreadReference(currentThread, environmentId, thread.id)).toBe(true);
|
||||
expect(
|
||||
hasUserThreadReference(
|
||||
{
|
||||
...currentThread,
|
||||
messages: [
|
||||
makeMessage(
|
||||
"message-assistant-reference",
|
||||
`[Referenced work](t3-thread:///${environmentId}/${thread.id})`,
|
||||
"assistant",
|
||||
),
|
||||
],
|
||||
},
|
||||
environmentId,
|
||||
thread.id,
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
hasUserThreadReference(
|
||||
{
|
||||
...currentThread,
|
||||
messages: [
|
||||
makeMessage(
|
||||
"message-other-environment",
|
||||
`[Referenced work](t3-thread:///environment-2/${thread.id})`,
|
||||
),
|
||||
],
|
||||
},
|
||||
environmentId,
|
||||
thread.id,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it.effect("reads a referenced thread through the MCP toolkit", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
@@ -81,27 +192,31 @@ it.effect("reads a referenced thread through the MCP toolkit", () =>
|
||||
totalMessages: 2,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, {
|
||||
environmentId: "environment-1" as never,
|
||||
threadId: ThreadId.make("thread-current"),
|
||||
providerSessionId: "provider-session-1",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
capabilities: new Set(["thread-reference"] as const),
|
||||
issuedAt: 1,
|
||||
expiresAt: Number.MAX_SAFE_INTEGER,
|
||||
}),
|
||||
Effect.provideService(McpSchema.McpServerClient, {
|
||||
clientId: 1,
|
||||
initializePayload: {
|
||||
protocolVersion: "2025-03-26",
|
||||
capabilities: {},
|
||||
clientInfo: { name: "test", version: "1" },
|
||||
},
|
||||
getClient: Effect.die("unused"),
|
||||
}),
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getThreadDetailById: () => Effect.succeed(Option.some(thread)),
|
||||
} as never),
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, mcpServerClient),
|
||||
Effect.provideService(ProjectionSnapshotQuery, projectionQueryFor(currentThread)),
|
||||
Effect.provide(TestLayer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects a thread that was not referenced by the invoking user", () =>
|
||||
Effect.gen(function* () {
|
||||
const server = yield* McpServer.McpServer;
|
||||
const result = yield* server.callTool({
|
||||
name: "thread_read",
|
||||
arguments: { threadId: thread.id },
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
}).pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.provideService(McpSchema.McpServerClient, mcpServerClient),
|
||||
Effect.provideService(
|
||||
ProjectionSnapshotQuery,
|
||||
projectionQueryFor({
|
||||
...currentThread,
|
||||
messages: [makeMessage("message-without-reference", "No thread reference here.")],
|
||||
}),
|
||||
),
|
||||
Effect.provide(TestLayer),
|
||||
),
|
||||
);
|
||||
@@ -6,8 +6,11 @@ import {
|
||||
type ThreadReferenceReadResult,
|
||||
type ThreadReferenceTranscriptMessage,
|
||||
ThreadReferenceUnavailableError,
|
||||
type EnvironmentId,
|
||||
type OrchestrationThread,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { collectComposerThreadReferences } from "@t3tools/shared/composerInlineTokens";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
@@ -35,7 +38,7 @@ function decodeCursor(
|
||||
!Number.isSafeInteger(textOffset) ||
|
||||
messageIndex < 0 ||
|
||||
textOffset < 0 ||
|
||||
(!validEndCursor && (!message || textOffset >= message.text.length))
|
||||
(!validEndCursor && (!message || textOffset > message.text.length))
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
@@ -96,6 +99,21 @@ export function buildThreadReferencePage(
|
||||
};
|
||||
}
|
||||
|
||||
export function hasUserThreadReference(
|
||||
sourceThread: OrchestrationThread,
|
||||
environmentId: EnvironmentId,
|
||||
targetThreadId: ThreadId,
|
||||
): boolean {
|
||||
return sourceThread.messages.some(
|
||||
(message) =>
|
||||
message.role === "user" &&
|
||||
collectComposerThreadReferences(message.text).some(
|
||||
(reference) =>
|
||||
reference.environmentId === environmentId && reference.threadId === targetThreadId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const threadRead = Effect.fn("ThreadReferenceToolkit.threadRead")(function* (
|
||||
input: ThreadReferenceReadInput,
|
||||
) {
|
||||
@@ -104,6 +122,15 @@ const threadRead = Effect.fn("ThreadReferenceToolkit.threadRead")(function* (
|
||||
return yield* new ThreadReferenceUnavailableError({ threadId: input.threadId });
|
||||
}
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const sourceThreadOption = yield* snapshotQuery
|
||||
.getThreadDetailById(invocation.threadId)
|
||||
.pipe(Effect.mapError(() => new ThreadReferenceUnavailableError({ threadId: input.threadId })));
|
||||
if (
|
||||
Option.isNone(sourceThreadOption) ||
|
||||
!hasUserThreadReference(sourceThreadOption.value, invocation.environmentId, input.threadId)
|
||||
) {
|
||||
return yield* new ThreadReferenceUnavailableError({ threadId: input.threadId });
|
||||
}
|
||||
const threadOption = yield* snapshotQuery
|
||||
.getThreadDetailById(input.threadId)
|
||||
.pipe(Effect.mapError(() => new ThreadReferenceUnavailableError({ threadId: input.threadId })));
|
||||
|
||||
@@ -96,4 +96,17 @@ describe("collectComposerInlineTokens", () => {
|
||||
it("ignores malformed thread links", () => {
|
||||
expect(collectComposerInlineTokens("Read [chat](t3-thread:///missing) first")).toEqual([]);
|
||||
});
|
||||
|
||||
it("collects a complete thread reference at the end of the prompt", () => {
|
||||
expect(
|
||||
collectComposerInlineTokens("Read [chat](t3-thread:///environment-1/thread-1)"),
|
||||
).toMatchObject([
|
||||
{
|
||||
type: "thread",
|
||||
environmentId: "environment-1",
|
||||
threadId: "thread-1",
|
||||
title: "chat",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -30,15 +30,20 @@ export interface CollectComposerInlineTokensOptions {
|
||||
readonly preserveTrailingFrom?: ReadonlyArray<ComposerInlineToken>;
|
||||
}
|
||||
|
||||
type ComposerThreadInlineToken = Extract<ComposerInlineToken, { type: "thread" }>;
|
||||
|
||||
const SKILL_TOKEN_REGEX = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s)/g;
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g;
|
||||
const FILE_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)(?=\s)/g;
|
||||
const THREAD_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\((t3-thread:\/\/\/[^)\s]+)\)(?=\s)/g;
|
||||
const THREAD_LINK_TOKEN_REGEX =
|
||||
/(^|\s)\[((?:\\.|[^\]\\])*)\]\((t3-thread:\/\/\/[^)\s]+)\)(?=\s|$)/g;
|
||||
const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/;
|
||||
const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/;
|
||||
|
||||
function collectThreadTokens(text: string): ComposerInlineToken[] {
|
||||
const matches: ComposerInlineToken[] = [];
|
||||
export function collectComposerThreadReferences(
|
||||
text: string,
|
||||
): ReadonlyArray<ComposerThreadInlineToken> {
|
||||
const matches: ComposerThreadInlineToken[] = [];
|
||||
|
||||
for (const match of text.matchAll(THREAD_LINK_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
@@ -122,7 +127,7 @@ export function collectComposerInlineTokens(
|
||||
text: string,
|
||||
options: CollectComposerInlineTokensOptions = {},
|
||||
): ReadonlyArray<ComposerInlineToken> {
|
||||
const matches = [...collectMentionTokens(text), ...collectThreadTokens(text)];
|
||||
const matches = [...collectMentionTokens(text), ...collectComposerThreadReferences(text)];
|
||||
|
||||
for (const match of text.matchAll(SKILL_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
|
||||
Reference in new issue
Block a user