TypeScript
feat(server,web,mobile): thread links name their environment and never a title (#26239)
Julius Marmingec2fbf0a52454
diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsxindex 9b6371813d2..d097416b2ef 100644--- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx+++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx@@ -1,6 +1,6 @@import { Button } from "../../components/ui/Button";import { QuestionAttachments } from "./QuestionAttachments";-import type { RuntimeRequestId } from "@t3tools/contracts";+import type { EnvironmentId, RuntimeRequestId } from "@t3tools/contracts";import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";import { useRef } from "react";import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";@@ -23,6 +23,7 @@ import { cn } from "../../lib/cn";import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";import { useOpenPullRequest } from "../../native/useOpenPullRequest";import { useMarkdownPreviewStyles } from "../files/FileMarkdownPreview";+import { useLiveThreadLinkLabels } from "../../state/entities";import {isPendingUserInputOptionSelected,type PendingUserInput,@@ -30,6 +31,7 @@ import {} from "../../lib/threadActivity";export interface PendingUserInputCardProps {+ readonly environmentId: EnvironmentId;readonly canOperateThread: boolean;readonly pendingUserInput: PendingUserInput;readonly maxHeight: DerivedValue<number>;@@ -59,12 +61,13 @@ export interface PendingUserInputCardProps {/** Android cannot hit-test overlays beyond their parent's bounds; render its expanded card in-flow. */const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";-function QuestionText(props: { readonly markdown: string }) {+function QuestionText(props: { readonly markdown: string; readonly environmentId: EnvironmentId }) {const styles = useMarkdownPreviewStyles();+ const markdown = useLiveThreadLinkLabels(props.markdown, props.environmentId);const openLink = useOpenPullRequest();return (<SelectableMarkdownText- markdown={props.markdown}+ markdown={markdown}textStyle={styles.nativeTextStyle}onLinkPress={(href) => void openLink(href)}/>@@ -217,7 +220,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-foreground-muted">{question.header}</Text>- <QuestionText markdown={question.question} />+ <QuestionText markdown={question.question} environmentId={props.environmentId} /><View className="gap-2">{question.options.map((option) => {const optionValue = option.value ?? option.label.trim();diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsxindex 3500e6bb35a..a23f06abef2 100644--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx@@ -1513,6 +1513,7 @@ function ThreadDetailBody(props: ThreadDetailScreenProps) {) : null}{props.activePendingUserInput ? (<PendingUserInputCard+ environmentId={props.environmentId}canOperateThread={props.canOperateThread}pendingUserInput={props.activePendingUserInput}maxHeight={pendingUserInputMaxHeight}diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsxindex c4339faf2e4..f845d923f9a 100644--- a/apps/mobile/src/features/threads/ThreadFeed.tsx+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx@@ -56,7 +56,7 @@ import {} from "@t3tools/contracts";import { renderAssistantCitationsAsText } from "@t3tools/shared/assistantCitations";import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";-import { parseThreadLinkHref, resolveThreadLinkRef } from "@t3tools/shared/threadLinks";+import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";import { PROMPT_LINK_MAX_PROMPT_LENGTH } from "@t3tools/shared/promptLinks";import {parseComposerContextHref,@@ -239,6 +239,7 @@ import {WORKSPACE_BASENAME_LOOKUP_LIMIT,} from "@t3tools/client-runtime/workspace-basename-lookup";import {+ resolveThreadLink,useLiveThreadLinkLabels,useQuietThreadShell,useThreadChipIcons,@@ -2255,13 +2256,16 @@ export const ThreadFeed = memo(function ThreadFeed({});};const resolveLinkedThread = (href: string) => {- const linkedThreadId = parseThreadLinkHref(href);- if (!linkedThreadId) return null;- const source = scopeThreadRef(props.environmentId, linkedThreadId);- return (- resolveThreadLinkRef(source, appAtomRegistry.get(environmentThreadShells.threadRefsAtom)) ??- source+ const link = parseThreadLinkHref(href);+ if (!link) return null;+ const resolved = resolveThreadLink(+ (atom) => appAtomRegistry.get(atom),+ link,+ props.environmentId,);+ if (resolved !== null || link.environmentId !== null) return resolved;+ // A v1 link names no environment, so it falls back to this message's.+ return scopeThreadRef(props.environmentId, link.threadId);};const onMarkdownLinkPress = (href: string, imageEmbed = false) => {markdownLinkRequest.current?.abort();@@ -2273,12 +2277,14 @@ export const ThreadFeed = memo(function ThreadFeed({if (instructionsPath) openSkillInstructions(instructionsPath);return;}- const target = resolveLinkedThread(href);- if (target) {- openLinkedThread({- environmentId: String(target.environmentId),- threadId: String(target.threadId),- });+ if (parseThreadLinkHref(href)) {+ const target = resolveLinkedThread(href);+ if (target) {+ openLinkedThread({+ environmentId: String(target.environmentId),+ threadId: String(target.threadId),+ });+ }return;}const media = resolveMarkdownMediaPreview(href, {diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts b/apps/mobile/src/lib/enrichedLinkPresentation.test.tsindex 89155b11a3c..4a3b0174ff6 100644--- a/apps/mobile/src/lib/enrichedLinkPresentation.test.ts+++ b/apps/mobile/src/lib/enrichedLinkPresentation.test.ts@@ -51,10 +51,12 @@ describe("Enriched link presentation", () => {});it("presents thread links as thread chips and leaves other links alone", () => {- expect(enrichedThreadLinkPresentation("t3-thread://v1/thread%3Aproject%3A1")).toEqual({- accent: "#009c96",- icon: { kind: "chip", name: "messages-square" },- });+ for (const href of ["t3-thread://v1/thread%3Aproject%3A1", "t3-thread://v2/env/thread_1"]) {+ expect(enrichedThreadLinkPresentation(href), href).toEqual({+ accent: "#009c96",+ icon: { kind: "chip", name: "messages-square" },+ });+ }for (const href of ["https://github.com/example/repo/pull/7","https://example.com",@@ -70,7 +72,7 @@ describe("Enriched link presentation", () => {expect(threadChipTargets(here,- "See [A](t3-thread://v1/thread_a), [A again](t3-thread://v1/thread_a) and [B](t3-thread://v1/thread_b).",+ "See [A](t3-thread://v1/thread_a), [A again](t3-thread://v1/thread_a), [B](t3-thread://v1/thread_b) and [D](t3-thread://v2/env-there/thread_d).",[{version: 1,@@ -86,6 +88,12 @@ describe("Enriched link presentation", () => {).toEqual([{ href: "t3-thread://v1/thread_a", environmentId: here, threadId: "thread_a", link: true },{ href: "t3-thread://v1/thread_b", environmentId: here, threadId: "thread_b", link: true },+ {+ href: "t3-thread://v2/env-there/thread_d",+ environmentId: there,+ threadId: "thread_d",+ link: true,+ },{href: "t3-context://v1/thread/thr1",environmentId: there,diff --git a/apps/mobile/src/lib/enrichedLinkPresentation.ts b/apps/mobile/src/lib/enrichedLinkPresentation.tsindex b93841ad8f8..12859d2dc8b 100644--- a/apps/mobile/src/lib/enrichedLinkPresentation.ts+++ b/apps/mobile/src/lib/enrichedLinkPresentation.ts@@ -58,9 +58,16 @@ export function threadChipTargets(): ReadonlyArray<ThreadChipTarget> {const targets = new Map<string, ThreadChipTarget>();if (hasThreadLinks(markdown)) {- for (const [, href = ""] of markdown.matchAll(/\]\((t3-thread:\/\/v1\/[^\s)]+)\)/g)) {- const threadId = parseThreadLinkHref(href);- if (threadId) targets.set(href, { href, environmentId, threadId, link: true });+ for (const [, href = ""] of markdown.matchAll(/\]\((t3-thread:\/\/v[12]\/[^\s)]+)\)/g)) {+ const link = parseThreadLinkHref(href);+ if (link) {+ targets.set(href, {+ href,+ environmentId: link.environmentId ?? environmentId,+ threadId: link.threadId,+ link: true,+ });+ }}}for (const record of records ?? []) {diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.tsindex 43910e0f14a..c98c8a11488 100644--- a/apps/mobile/src/state/entities.ts+++ b/apps/mobile/src/state/entities.ts@@ -17,9 +17,13 @@ import {} from "@t3tools/contracts";import { scopeThreadRef } from "@t3tools/client-runtime/environment";import {+ guessThreadLinkRef,hasThreadLinks,+ parseThreadLinkHref,relabelThreadLinks,- resolveThreadLinkRef,+ threadLinkCandidates,+ threadLinkRefs,+ type ThreadLink,} from "@t3tools/shared/threadLinks";import * as Option from "effect/Option";import * as Schema from "effect/Schema";@@ -45,26 +49,35 @@ const EMPTY_SERVER_CONFIG_ATOM = Atom.make<ServerConfig | null>(null).pipe(const EMPTY_THREAD_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(Atom.withLabel("mobile-thread:empty"),);-const EMPTY_THREAD_TITLES: ReadonlyMap<ThreadId, string> = new Map();-const EMPTY_THREAD_TITLES_ATOM = Atom.make(EMPTY_THREAD_TITLES).pipe(- Atom.withLabel("mobile-thread-titles:empty"),+const EMPTY_THREAD_LINK_TITLES_ATOM = Atom.make<ReadonlyMap<string, string>>(new Map()).pipe(+ Atom.withLabel("mobile-thread-link-titles:empty"),);-const threadTitlesAtom = Atom.family((environmentId: EnvironmentId) => {- let previous = EMPTY_THREAD_TITLES;+const decodeThreadKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, ThreadId]));+const threadKey = (ref: ScopedThreadRef) => JSON.stringify([ref.environmentId, ref.threadId]);++// Null when this client doesn't know the thread. Keyed, so a link never walks an environment's threads.+const threadTitleAtom = Atom.family((key: string) => {+ const ref = scopeThreadRef(...decodeThreadKey(JSON.parse(key)));+ return Atom.make((get) => get(environmentThreadShells.threadShellAtom(ref))?.title ?? null).pipe(+ Atom.withLabel(`mobile-thread-title:${key}`),+ );+});++const decodeThreadKeys = Schema.decodeUnknownSync(Schema.Array(Schema.String));++const threadLinkTitlesAtom = Atom.family((key: string) => {+ const refKeys = decodeThreadKeys(JSON.parse(key));return Atom.make((get) => {- const index = get(environmentThreadShells.environmentThreadIndexAtom(environmentId));- const unchanged =- index.size === previous.size &&- Array.from(index).every(([threadId, shell]) => previous.get(threadId) === shell.title);- if (!unchanged) {- previous = new Map(Array.from(index, ([threadId, shell]) => [threadId, shell.title]));+ const titles = new Map<string, string>();+ for (const refKey of refKeys) {+ const title = get(threadTitleAtom(refKey));+ if (title !== null) titles.set(refKey, title);}- return previous;- }).pipe(Atom.withLabel(`mobile-thread-titles:${environmentId}`));+ return titles;+ }).pipe(Atom.withLabel(`mobile-thread-link-titles:${key}`));});-const decodeThreadKey = Schema.decodeUnknownSync(Schema.Tuple([EnvironmentId, ThreadId]));const decodeThreadChipTargets = Schema.decodeUnknownSync(Schema.Array(Schema.Struct({@@ -118,13 +131,11 @@ const threadChipIconsAtom = Atom.family((key: string) => {return Atom.make((get) => {const icons = new Map<string, string>();for (const target of targets) {- const source = scopeThreadRef(target.environmentId, target.threadId);- const ref = target.link- ? (resolveThreadLinkRef(source, get(environmentThreadShells.threadRefsAtom)) ?? source)- : source;- const icon = get(- threadProjectChipIconAtom(JSON.stringify([ref.environmentId, ref.threadId])),- );+ const link = target.link ? parseThreadLinkHref(target.href) : null;+ const ref =+ (link ? resolveThreadLink(get, link, target.environmentId) : null) ??+ scopeThreadRef(target.environmentId, target.threadId);+ const icon = get(threadProjectChipIconAtom(threadKey(ref)));if (icon) icons.set(target.href, icon);}return icons;@@ -190,11 +201,26 @@ export function useChildThreadInputs(ref: ScopedThreadRef) {export function useLiveThreadLinkLabels(markdown: string, environmentId: EnvironmentId): string {const titles = useAtomValue(- hasThreadLinks(markdown) ? threadTitlesAtom(environmentId) : EMPTY_THREAD_TITLES_ATOM,+ hasThreadLinks(markdown)+ ? threadLinkTitlesAtom(JSON.stringify(threadLinkRefs(markdown, environmentId).map(threadKey)))+ : EMPTY_THREAD_LINK_TITLES_ATOM,+ );+ return relabelThreadLinks(markdown, environmentId, (ref) => titles.get(threadKey(ref)));+}++/** Keyed reads; every thread is read only to place a v1 link its message's environment lacks. */+export function resolveThreadLink(+ read: <A>(atom: Atom.Atom<A>) => A,+ link: ThreadLink,+ messageEnvironmentId: EnvironmentId,+): ScopedThreadRef | null {+ const known = threadLinkCandidates(link, messageEnvironmentId).find(+ (ref) => read(threadTitleAtom(threadKey(ref))) !== null,);- return titles.size === 0- ? markdown- : relabelThreadLinks(markdown, (threadId) => titles.get(threadId));+ if (known) return known;+ return link.environmentId === null+ ? guessThreadLinkRef(link, read(environmentThreadShells.threadRefsAtom))+ : null;}export function useThreadChipIcons(diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex bb66e208c97..3681c457890 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -1,5 +1,6 @@import {CommandId,+ type EnvironmentId,type RunId,isProviderAvailable,MessageId,@@ -748,13 +749,14 @@ function threadPullRequests(}function listItemFromShell(+ environmentId: EnvironmentId,shell: OrchestrationV2ThreadShell,nowMs: number,): OrchestratorMcpThreadListItem {return {threadId: shell.id,title: shell.title,- link: formatThreadLink(shell.id, shell.title),+ link: formatThreadLink({ environmentId, threadId: shell.id }),createdBy: shell.createdBy,creationSource: shell.creationSource,status: shell.activityRunStatus ?? shell.status,@@ -776,6 +778,7 @@ function listItemFromShell(}function threadDetail(+ environmentId: EnvironmentId,projection: Pick<OrchestrationV2ThreadProjection, "thread" | "runs" | "runtimeRequests">,itemCount: number,shell: OrchestrationV2ThreadShell,@@ -787,7 +790,7 @@ function threadDetail(threadId: projection.thread.id,projectId: projection.thread.projectId,title: projection.thread.title,- link: formatThreadLink(projection.thread.id, projection.thread.title),+ link: formatThreadLink({ environmentId, threadId: projection.thread.id }),createdBy: projection.thread.createdBy,creationSource: projection.thread.creationSource,status: active?.status ?? latest?.status ?? "idle",@@ -1518,7 +1521,10 @@ const make = Effect.gen(function* () {const result = {taskId: task.id,childThreadId: task.childThreadId,- link: formatThreadLink(task.childThreadId, childControls.thread.title),+ link: formatThreadLink({+ environmentId: scope.environmentId,+ threadId: task.childThreadId,+ }),childRunId: childRun?.id ?? null,childNodeId: task.id,status,@@ -1674,7 +1680,9 @@ const make = Effect.gen(function* () {return {taskId: task.id,childThreadId: null,- ...(task.remoteChild === undefined ? {} : { remoteChild: task.remoteChild }),+ ...(task.remoteChild === undefined+ ? {}+ : { remoteChild: task.remoteChild, link: formatThreadLink(task.remoteChild) }),childRunId: null,childNodeId: task.id,status,@@ -2739,7 +2747,7 @@ const make = Effect.gen(function* () {);return {threadId,- link: formatThreadLink(threadId, projection.thread.title),+ link: formatThreadLink({ environmentId: scope.environmentId, threadId }),runId: run?.id ?? null,status: run?.status ?? "idle",title: projection.thread.title,@@ -2792,7 +2800,7 @@ const make = Effect.gen(function* () {return {projectId,currentThreadId: parent?.thread.id ?? null,- threads: page.map((shell) => listItemFromShell(shell, nowMs)),+ threads: page.map((shell) => listItemFromShell(scope.environmentId, shell, nowMs)),nextCursor,total: filtered.length,} satisfies OrchestratorMcpThreadListResult;@@ -2872,7 +2880,13 @@ const make = Effect.gen(function* () {}}return {- thread: threadDetail(target, timeline.totalItems, shell, yield* Clock.currentTimeMillis),+ thread: threadDetail(+ scope.environmentId,+ target,+ timeline.totalItems,+ shell,+ yield* Clock.currentTimeMillis,+ ),recentRuns: target.runs.toSorted((left, right) => right.ordinal - left.ordinal).slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)@@ -2931,7 +2945,7 @@ const make = Effect.gen(function* () {);return {threadId: input.threadId,- link: formatThreadLink(input.threadId, target.thread.title),+ link: formatThreadLink({ environmentId: scope.environmentId, threadId: input.threadId }),messageId,runId: result.run.id,...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }),diff --git a/apps/server/src/mcp/toolkits/project/handlers.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.tsindex 3e9fe6a21f9..4031654a8c8 100644--- a/apps/server/src/mcp/toolkits/project/handlers.test.ts+++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts@@ -185,7 +185,7 @@ it.effect(expect(belowCeiling.result).toMatchObject({projectId: belowCeiling.projectId,modelSelection: belowCeiling.modelSelection,- link: `[Fix](t3-thread://v1/${belowCeiling.launched[0]?.threadId})`,+ link: `<t3-thread://v2/environment/${belowCeiling.launched[0]?.threadId}>`,});expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required");expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined();diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.tsindex f5a67ae025a..950cb38c6c4 100644--- a/apps/server/src/mcp/toolkits/project/handlers.ts+++ b/apps/server/src/mcp/toolkits/project/handlers.ts@@ -240,7 +240,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {const run = result.projection.runs.find((run) => run.userMessageId === messageId);return {threadId: thread.id,- link: formatThreadLink(thread.id, thread.title),+ link: formatThreadLink({ environmentId: scope.environmentId, threadId: thread.id }),projectId: thread.projectId,modelSelection: thread.modelSelection,runId: run?.id ?? null,diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.tsindex 8d7d1359e8c..8ad9afa4351 100644--- a/apps/server/src/mcp/toolkits/thread/handlers.ts+++ b/apps/server/src/mcp/toolkits/thread/handlers.ts@@ -11,6 +11,7 @@ import * as Effect from "effect/Effect";import { modelSelectionCommandType } from "@t3tools/shared/model";import { formatThreadLink } from "@t3tools/shared/threadLinks";+import * as McpInvocationContext from "../../McpInvocationContext.ts";import * as McpToolAccess from "../../McpToolAccess.ts";import {dispatchFailure,@@ -103,9 +104,11 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {const { task, threadId } = yield* scheduler.runNow({ id: input.taskId }).pipe(Effect.mapError(unavailable));+ const { environmentId } = yield* McpInvocationContext.McpInvocationContext;return {taskId: task.id,threadId,+ ...(threadId === null ? {} : { link: formatThreadLink({ environmentId, threadId }) }),lastRunStatus: task.lastRunStatus,runCount: task.runCount,nextRunAt: task.nextRunAt,@@ -115,6 +118,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {t3_thread_search: McpToolAccess.reads((input) =>Effect.gen(function* () {const { caller } = yield* readCaller();+ const { environmentId } = yield* McpInvocationContext.McpInvocationContext;const threadSearch = yield* ThreadSearch.ThreadSearch;const { matches } = yield* threadSearch.searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId })@@ -122,7 +126,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {return {matches: matches.map((match) => ({...match,- link: formatThreadLink(match.threadId, match.title),+ link: formatThreadLink({ environmentId, threadId: match.threadId }),})),};}),diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.tsindex b14b1bd387f..4b566c44a69 100644--- a/apps/server/src/mcp/toolkits/thread/tools.ts+++ b/apps/server/src/mcp/toolkits/thread/tools.ts@@ -226,6 +226,7 @@ const ScheduledTaskRunTool = Tool.make("run_scheduled_task_now", {success: Schema.Struct({taskId: ScheduledTaskId,threadId: ScheduledTask.fields.threadId,+ link: Schema.optional(Schema.String),lastRunStatus: ScheduledTask.fields.lastRunStatus,runCount: NonNegativeInt,nextRunAt: ScheduledTask.fields.nextRunAt,diff --git a/apps/server/src/peer/RemoteDelegation.test.ts b/apps/server/src/peer/RemoteDelegation.test.tsindex 73c547546d1..a344f63c523 100644--- a/apps/server/src/peer/RemoteDelegation.test.ts+++ b/apps/server/src/peer/RemoteDelegation.test.ts@@ -759,6 +759,7 @@ const delegateToBox = (laptopEnv: Effect.Success<ReturnType<typeof makeLaptop>>)status: string;childThreadId: null;remoteChild: { environmentId: string; threadId: ThreadId; label: string };+ link?: string;};}),);@@ -807,6 +808,10 @@ it.effect("a task delegated to the box wakes the laptop's parent when it ends th});// The box launched it in the project with the same repository.expect(yield* Ref.get(thread.launched)).toBe(delegated.remoteChild.threadId);+ // Its link opens the thread there, so the parent can mention it like any other.+ expect(delegated.link).toBe(+ `<t3-thread://v2/${box.environmentId}/${delegated.remoteChild.threadId}>`,+ );// ...naming the parent here, so the thread there links back to it.expect(yield* Ref.get(thread.delegatedFrom)).toEqual({environmentId: laptop.environmentId,diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.jsonindex beec65c80d1..fdc39bc78bc 100644--- a/apps/server/src/provider/agentContextBudget.json+++ b/apps/server/src/provider/agentContextBudget.json@@ -1,5 +1,5 @@{- "claudeSystemAppendBytes": 5258,- "codexAdditionalContextBytes": 5810,+ "claudeSystemAppendBytes": 5135,+ "codexAdditionalContextBytes": 5687,"mcpToolListJsonBytes": 45861}diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex fc0489c0165..2ae3e8d9f97 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -1060,13 +1060,15 @@ const CHAT_MARKDOWN_COMPONENTS = {const text = use(ChatMarkdownTextContext);const citation = href ? parseAssistantCitationHref(href) : null;if (citation) return <AssistantCitationChip citation={citation} />;- const linkedThreadId = href ? parseThreadLinkHref(href) : null;- if (linkedThreadId) {- const label = hastPlainTextDeep(node) || linkedThreadId;+ const threadLink = href ? parseThreadLinkHref(href) : null;+ if (threadLink) {+ const written = hastPlainTextDeep(node);+ // An autolink's text is its own URL, which is no label.+ const label = written && parseThreadLinkHref(written) === null ? written : null;return environmentId ? (- <MarkdownThreadLink environmentId={environmentId} threadId={linkedThreadId} label={label} />+ <MarkdownThreadLink environmentId={environmentId} link={threadLink} label={label} />) : (- <span>{label}</span>+ <span>{label ?? "Thread"}</span>);}const contextReference = href ? parseComposerContextHref(href) : null;diff --git a/apps/web/src/components/chat/MarkdownThreadLink.tsx b/apps/web/src/components/chat/MarkdownThreadLink.tsxindex 8b32a541223..68ab4cd569e 100644--- a/apps/web/src/components/chat/MarkdownThreadLink.tsx+++ b/apps/web/src/components/chat/MarkdownThreadLink.tsx@@ -1,39 +1,41 @@import { scopeThreadRef } from "@t3tools/client-runtime/environment";-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import type { EnvironmentId } from "@t3tools/contracts";import {formatThreadLink,+ guessThreadLinkRef,percentDecodedThreadLinkId,- resolveThreadLinkRef,+ type ThreadLink,+ unknownThreadLinkLabel,} from "@t3tools/shared/threadLinks";import { useThreadRefs, useThreadShell } from "../../state/entities";+import { UnresolvedChip } from "../contextChipParts";import { ThreadContextChip } from "../ThreadContextChip";+/** `label` is the link's written text; an autolink has none. */export function MarkdownThreadLink(props: {readonly environmentId: EnvironmentId;- readonly threadId: ThreadId;- readonly label: string;+ readonly link: ThreadLink;+ readonly label: string | null;}) {- const decodedId = percentDecodedThreadLinkId(props.threadId);- const written = useThreadShell(scopeThreadRef(props.environmentId, props.threadId));+ const environmentId = props.link.environmentId ?? props.environmentId;+ const decodedId = percentDecodedThreadLinkId(props.link.threadId);+ const written = useThreadShell(scopeThreadRef(environmentId, props.link.threadId));const decoded = useThreadShell(- written === null && decodedId !== null ? scopeThreadRef(props.environmentId, decodedId) : null,+ written === null && decodedId !== null ? scopeThreadRef(environmentId, decodedId) : null,);const local = written ?? decoded;- const refs = useThreadRefs(local === null);- const remote = useThreadShell(- local === null- ? resolveThreadLinkRef(scopeThreadRef(props.environmentId, props.threadId), refs)- : null,- );+ const guess = local === null && props.link.environmentId === null;+ const refs = useThreadRefs(guess);+ const remote = useThreadShell(guess ? guessThreadLinkRef(props.link, refs) : null);const thread = local ?? remote;- const environmentId = thread?.environmentId ?? props.environmentId;- const threadId = thread?.id ?? props.threadId;- const title = thread?.title.trim() || props.label;+ if (thread === null) {+ const unknown = unknownThreadLinkLabel(props.link, props.environmentId);+ return <UnresolvedChip label={props.label ?? unknown} tooltip={unknown} />;+ }+ const ref = { environmentId: thread.environmentId, threadId: thread.id };+ const title = thread.title.trim() || props.label || "Untitled thread";return (- <ThreadContextChip- record={{ environmentId, threadId, title: props.label }}- copyMarkdown={formatThreadLink(threadId, title)}- />+ <ThreadContextChip record={{ ...ref, title }} copyMarkdown={formatThreadLink(ref, title)} />);}diff --git a/apps/web/src/components/chat/timelineMinimapItems.test.ts b/apps/web/src/components/chat/timelineMinimapItems.test.tsnew file mode 100644index 00000000000..20d4c75997b--- /dev/null+++ b/apps/web/src/components/chat/timelineMinimapItems.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from "vite-plus/test";++import { resolveTimelineMinimapPreview } from "./timelineMinimapItems";++describe("resolveTimelineMinimapPreview", () => {+ it("previews a thread autolink as prose, not its URL", () => {+ const preview = resolveTimelineMinimapPreview({+ id: "turn-1",+ rowIndex: 0,+ userText: null,+ assistantText:+ "Started <t3-thread://v2/env-1/thread-1> and [Fix CI](t3-thread://v2/env-1/t2).",+ });+ expect(preview?.assistantText).toBe("Started a thread and Fix CI.");+ });+});diff --git a/apps/web/src/components/chat/timelineMinimapItems.ts b/apps/web/src/components/chat/timelineMinimapItems.tsindex faf6af94154..099c58379cc 100644--- a/apps/web/src/components/chat/timelineMinimapItems.ts+++ b/apps/web/src/components/chat/timelineMinimapItems.ts@@ -1,3 +1,4 @@+import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";import type { Nodes } from "mdast";import remarkGfm from "remark-gfm";import remarkParse from "remark-parse";@@ -82,7 +83,9 @@ function markdownNodeText(node: Nodes): string {if (node.type === "image" || node.type === "imageReference") return node.alt ?? "";if (!("children" in node)) return "";const separator = INLINE_PARENT_TYPES.has(node.type) ? "" : " ";- return node.children.map(markdownNodeText).join(separator);+ const text = node.children.map(markdownNodeText).join(separator);+ // A thread autolink's only text is its URL.+ return node.type === "link" && parseThreadLinkHref(text) !== null ? "a thread" : text;}function compactMinimapPreview(text: string | null | undefined) {diff --git a/apps/web/src/pendingUserInput.test.ts b/apps/web/src/pendingUserInput.test.tsindex 521a249b000..69800be4b75 100644--- a/apps/web/src/pendingUserInput.test.ts+++ b/apps/web/src/pendingUserInput.test.ts@@ -27,7 +27,7 @@ describe("projectPendingUserInputAnswer", () => {it("sends thread chips as readable links with the actual thread ID", () => {const answer = `Compare ${formatInlineContextReference(threadContextReference(record))}`;expect(projectPendingUserInputAnswer(answer, [record])).toBe(- "Compare [Reference work](t3-thread://v1/reference-thread)",+ "Compare [Reference work](t3-thread://v2/env-answer/reference-thread)",);});diff --git a/apps/web/src/pendingUserInput.ts b/apps/web/src/pendingUserInput.tsindex 55817c3378b..f8f9d6d52b5 100644--- a/apps/web/src/pendingUserInput.ts+++ b/apps/web/src/pendingUserInput.ts@@ -12,7 +12,7 @@ export function projectPendingUserInputAnswer(const recordsById = new Map(threadContexts.map((record) => [record.contextId, record]));return replaceComposerContextReferences(answer, (reference) => {const record = reference.kind === "thread" ? recordsById.get(reference.contextId) : undefined;- return record ? formatThreadLink(record.threadId, reference.label) : reference.source;+ return record ? formatThreadLink(record, reference.label) : reference.source;});}diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.mdindex e41f42c8248..befaca4c077 100644--- a/docs/orchestration-v2/orchestrator-mcp-server.md+++ b/docs/orchestration-v2/orchestrator-mcp-server.md@@ -390,12 +390,15 @@ and `creationSource: "mcp"`; provider output uses `creationSource: "provider"`.Actor and ingress are separate so agent-authored user-role messages remaindistinguishable from human-authored messages.-Agents mention another thread as `[title](t3-thread://v1/<threadId>)`. Thread-results carry this ready-made as `link`, so agents never format the id. The-link carries only the id. Clients first resolve it in the message's environment,-then use a unique match in another enabled environment. Ambiguous matches stay-unresolved. Web and desktop show the resolved thread’s current title. Mobile-relabels local matches; cross-environment links can retain the written label.+Agents mention another thread by the `link` its result carries,+`<t3-thread://v2/<environmentId>/<threadId>>`, so they never format an id or+write a title, which goes stale when the user renames the thread. The+environment that owns the thread builds the link, so forwarded results and tasks+delegated to a linked environment name that environment. Clients open only that+environment's thread and show its current title; a link to a thread they do not+know renders as a label that opens nothing. Older `t3-thread://v1/<threadId>`+links name no environment: clients resolve them in the message's environment,+then by a unique match in another enabled environment.List and read results report `snoozed` and `snoozedUntil`, and`t3_thread_list` filters on `snoozed`. The server's `isSnoozed` follows thediff --git a/evals/mcp-tool-use/cases/orchestration.ndjson b/evals/mcp-tool-use/cases/orchestration.ndjsonindex fae66d64431..dc79eb774df 100644--- a/evals/mcp-tool-use/cases/orchestration.ndjson+++ b/evals/mcp-tool-use/cases/orchestration.ndjson@@ -13,9 +13,10 @@{"id": "debate-drops-second-model", "area": "orchestration", "kind": "bad", "pattern": "missed requested delegate; polling", "experience": "Asked to argue with GPT-6.1 Sol and Muse Wonder Full, the agent only delegated to Sol (twice), never mentioned Muse, and blocked the turn with 7 task_status and 3 t3_thread_wait calls.", "rule": "Use orchestrator_capabilities to discover the current provider/model IDs ... (intended: one delegate per requested model; end the turn after async delegates)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default", "task_status": "default", "t3_thread_wait": {"threadId": "44444444-4444-4444-8444-000000000001", "status": "running", "timedOut": true}, "WebSearch": "Hostco status page: Major outage. Deploys and new builds are unavailable in all regions. Started 17 hours ago. Running apps and databases are not affected. Next update in 60 minutes."}, "world": {"files": {"infra/README.md": "# Hosting\n\nProduction runs on Hostco: the web service, a worker, and managed Postgres, all in us-east. The app needs the database in the same region for latency.\n", "infra/hostco.yaml": "services:\n - name: web\n plan: standard\n - name: worker\n plan: starter\ndatabases:\n - name: main\n plan: pro-4gb\n"}}}, "prompt": "Our hosting provider has been down for SEVENTEEN HOURS and I can't deploy. The DB has to stay colocated with compute, probably on the same platform. Rethink our options and research more. Argue with GPT-6.1 Sol and Muse Wonder Full about it. Don't bother me until you actually understand what is going on and have a real plan.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "gpt-6.1-sol"}}, {"tool": "delegate_task", "args": {"target.model": "muse-wonder-full"}}], "order": ["orchestrator_capabilities", "delegate_task"], "maxCalls": {"t3_thread_wait": 0, "task_status": 1}}, "notes": "'Don't bother me until...' is the pressure toward blocking waits. Real model id replaced with the fixture 'muse-wonder-full'.", "maxSteps": 12}{"id": "file-watcher-after-async-delegates", "area": "orchestration", "kind": "bad", "pattern": "polling after async delegate_task (shell watcher)", "experience": "After async delegates, the agent ran background 'until [ -f file ]; do sleep 15; done' watchers. They caused empty wake turns ('That alert was the old plan-file watcher closing, so nothing changed').", "rule": "Keep polling/wait loops bounded, do not duplicate active work (intended: end the turn; completion wakes this thread)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default", "task_status": "default"}, "world": {"files": {"infra/README.md": "# Services\n\nweb (Node), worker (queue consumer), Postgres, Redis. All on Hostco in one region.\n", "infra/web.yaml": "name: web\nenv:\n DATABASE_URL: from-db\n REDIS_URL: from-redis\n", "infra/worker.yaml": "name: worker\nenv:\n DATABASE_URL: from-db\n REDIS_URL: from-redis\n"}}}, "prompt": "We're starting a new repo that helps people move off our current host after today's outages. Do these, all with subagents:\n1. Inventory the services in infra/ and how they connect. Write .research/01-inventory.md.\n2. Survey the other hosting options. Write .research/02-alternatives.md.\n3. When 1 and 2 are done, propose a migration plan for the best two options in .research/03-plan.md.", "expect": {"notCalls": ["Monitor", "ScheduleWakeup"], "callsMustNot": [{"tool": "Agent", "args": {"run_in_background": true}}], "shellMustNot": ["\\bsleep\\b", "until \\[", "while \\[ ! -f", "inotifywait|fswatch"], "maxCalls": {"task_status": 1, "t3_thread_wait": 0}}, "notes": "Step 3 depends on 1 and 2, which is what pushed the agent to watch for files. Expected: start 1 and 2 as delegates, end the turn, start 3 on the wake."}{"id": "worktree-add-for-parallel-pr-delegates", "area": "orchestration", "kind": "bad", "pattern": "worktree via git worktree add instead of isolation", "experience": "Asked for delegates that each make a separate PR, the agent ran git worktree add 12 times in the shell and told each delegate to work in its path.", "rule": "For a child task that needs a separate checkout, use delegate_task with isolation:\"worktree\" ... Asking an agent to run git worktree add or cd in its prompt does not update T3's thread binding.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "What's left before we can ship 1.0? Give me a short list of blockers."}, {"role": "assistant", "text": "Three release blockers:\n1. A deploy can drop a table without confirmation.\n2. Auth tokens are sent in WebSocket URLs.\n3. Admin sessions never expire.", "toolCalls": [{"tool": "Bash", "input": {"command": "rg -n \"dropTable\" src/deploy"}, "result": "src/deploy/migrate.ts:3: await db.dropTable(name); // no confirmation"}, {"tool": "Bash", "input": {"command": "rg -n \"token=\" src/ws"}, "result": "src/ws/client.ts:2: return new WebSocket(`${base}?token=${token}`);"}, {"tool": "Bash", "input": {"command": "rg -n \"expires\" src/admin"}, "result": "Exit code 1\n"}, {"tool": "Read", "input": {"file_path": "/home/user/.t3/worktrees/t3code/t3-f8cdd940/src/admin/session.ts"}, "result": " 1\texport function createAdminSession(userId: string) {\n 2\t return { userId, createdAt: Date.now() }; // no expiresAt\n 3\t}"}]}], "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "childRunId": "run-child-1", "status": "running", "workState": "working", "providerInstanceId": "claudeAgent", "model": "claude-sonnet-5-5"}}, "world": {"files": {"src/deploy/migrate.ts": "export async function applyMigration(m: Migration) {\n for (const name of m.dropTables) {\n await db.dropTable(name); // no confirmation\n }\n}\n", "src/ws/client.ts": "export function connect(base: string, token: string) {\n return new WebSocket(`${base}?token=${token}`);\n}\n", "src/admin/session.ts": "export function createAdminSession(userId: string) {\n return { userId, createdAt: Date.now() }; // no expiresAt\n}\n"}}}, "prompt": "Sounds reasonable. Start the work. Spin up delegates to work on each of these as separate PRs.", "expect": {"calls": [{"tool": "delegate_task", "args": {"isolation": "worktree"}}], "notCalls": ["t3_thread_launch", "create_threads"], "shellMustNot": ["git worktree add"], "callsMustNot": [{"tool": "delegate_task", "args": {"task": "~git worktree add"}}]}, "notes": "Also guards pattern 1: the 'independent implementation in its own worktree' launch section can pull toward t3_thread_launch, which the user did not ask for."}-{"id": "thread-id-not-read", "area": "orchestration", "kind": "bad", "pattern": "did not read a given thread id", "experience": "The user pasted a thread id and asked why 'this t3 code thread' kept mentioning pi. The agent answered from its own context. The user: 'Use the t3 code mcp to get that thread, that's the id lol'.", "rule": "Intended: read a given thread id with t3_thread_read, with a bounded size.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Is the Muse CLI just a fork or wrapper of the Pi agent?"}, {"role": "assistant", "text": "No. The installed Muse CLI is a native Rust binary built from its own source tree. I searched the provider code for 'pi' to check, and found only T3 Code's separate Pi provider docs.", "toolCalls": [{"tool": "Bash", "input": {"command": "rg -il '\\bpi\\b' src/providers"}, "result": "src/providers/pi/README.md"}, {"tool": "Bash", "input": {"command": "file \"$(which muse)\""}, "result": "/usr/local/bin/muse: ELF 64-bit LSB pie executable, x86-64, dynamically linked, Rust toolchain 1.91, stripped"}]}], "mocks": {"t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Muse CLI integration and ACP support", "link": "[Muse CLI integration and ACP support](t3-thread://v1/11111111-1111-4111-8111-111111111111)", "status": "idle"}, "items": [{"position": 494, "createdBy": "assistant", "text": "Pi already replays recorded transcripts in tests, so the Muse adapter copies that pattern."}], "nextPosition": 495, "hasMore": false}}, "world": {"files": {"src/providers/pi/README.md": "# Pi provider\n\nRuns the Pi agent through its RPC mode.\n", "src/providers/muse/adapter.ts": "export const museAdapter = makeAdapter({ binary: 'muse' });\n"}}}, "prompt": "11111111-1111-4111-8111-111111111111 why does this t3 code thread keep mentioning pi?", "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}]}, "notes": "The prior turn mentions pi, which is what let the agent think 'this thread' meant itself. The same thread then read with limit 100 and got an 85k-char result (see gaps)."}-{"id": "thread-mention-without-link-after-read", "area": "orchestration", "kind": "bad", "pattern": "thread mentioned without t3-thread link", "experience": "Asked to explain what went wrong in a given thread, the agent named it by id or title with no t3-thread:// link.", "rule": "To mention another thread to the user, link it as [title](t3-thread://v1/<threadId>) with its exact threadId.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Fix ultrafast pricing", "link": "[Fix ultrafast pricing](t3-thread://v1/11111111-1111-4111-8111-111111111111)", "status": "idle"}, "items": [{"position": 210, "createdBy": "assistant", "toolName": "t3_thread_send", "text": "t3_thread_send threadId=44444444-4444-4444-8444-000000000001 message='Round 2. Read only, as before...'"}, {"position": 214, "createdBy": "user", "text": "Use delegate_task please, this should not be a separate thread."}], "nextPosition": 215, "hasMore": false}}}, "prompt": "11111111-1111-4111-8111-111111111111 This thread used the wrong tool. Figure out why.", "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}], "textMust": ["t3-thread://v1/[^)\\s]*11111111-1111-4111-8111-111111111111"]}, "notes": "Real agent was Codex before the 10-21 untruncation fix, when the link rule often did not reach Codex. May pass on Claude today; keep as a regression check for the rewrite.", "maxSteps": 10}-{"id": "found-thread-mentioned-without-link", "area": "orchestration", "kind": "bad", "pattern": "thread mentioned without t3-thread link", "experience": "The agent found yesterday's thread by search and told the user where they left off, but did not link the thread.", "rule": "To mention another thread to the user, link it as [title](t3-thread://v1/<threadId>) with its exact threadId.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_thread_search": {"matches": [{"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "22222222-2222-4222-8222-222222222222", "title": "Fix macOS camera permission prompt", "snippet": "...the app never asks for camera permission on mac...", "messageCreatedAt": "2026-10-19T21:04:00Z"}]}, "t3_thread_list": {"threads": [{"threadId": "11111111-1111-4111-8111-111111111111", "title": "Fix macOS camera permission prompt", "status": "idle"}]}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Fix macOS camera permission prompt", "link": "[Fix macOS camera permission prompt](t3-thread://v1/11111111-1111-4111-8111-111111111111)", "status": "idle"}, "items": [{"position": 88, "createdBy": "assistant", "text": "The fix is committed locally on branch fix/camera-entitlement in another clone. No PR is open yet."}], "nextPosition": 89, "hasMore": false}}, "shellMocks": [{"match": "gh pr list", "output": ""}]}, "prompt": "Did I ever make a PR to fix the issue where the app couldn't request camera permission on mac? I had a thread about it yesterday and forgot where we left off.", "expect": {"textMust": ["t3-thread://v1/[^)\\s]*11111111-1111-4111-8111-111111111111"]}, "notes": "Also seen in another thread ('Found the prior audits (Jul 21, Sep 1, Oct 3 threads ...)' with no links). Original prompt also said 'get it fixed full stop'; dropped to keep the case small."}+{"id": "thread-id-not-read", "area": "orchestration", "kind": "bad", "pattern": "did not read a given thread id", "experience": "The user pasted a thread id and asked why 'this t3 code thread' kept mentioning pi. The agent answered from its own context. The user: 'Use the t3 code mcp to get that thread, that's the id lol'.", "rule": "Intended: read a given thread id with t3_thread_read, with a bounded size.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Is the Muse CLI just a fork or wrapper of the Pi agent?"}, {"role": "assistant", "text": "No. The installed Muse CLI is a native Rust binary built from its own source tree. I searched the provider code for 'pi' to check, and found only T3 Code's separate Pi provider docs.", "toolCalls": [{"tool": "Bash", "input": {"command": "rg -il '\\bpi\\b' src/providers"}, "result": "src/providers/pi/README.md"}, {"tool": "Bash", "input": {"command": "file \"$(which muse)\""}, "result": "/usr/local/bin/muse: ELF 64-bit LSB pie executable, x86-64, dynamically linked, Rust toolchain 1.91, stripped"}]}], "mocks": {"t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Muse CLI integration and ACP support", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "status": "idle"}, "items": [{"position": 494, "createdBy": "assistant", "text": "Pi already replays recorded transcripts in tests, so the Muse adapter copies that pattern."}], "nextPosition": 495, "hasMore": false}}, "world": {"files": {"src/providers/pi/README.md": "# Pi provider\n\nRuns the Pi agent through its RPC mode.\n", "src/providers/muse/adapter.ts": "export const museAdapter = makeAdapter({ binary: 'muse' });\n"}}}, "prompt": "11111111-1111-4111-8111-111111111111 why does this t3 code thread keep mentioning pi?", "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}]}, "notes": "The prior turn mentions pi, which is what let the agent think 'this thread' meant itself. The same thread then read with limit 100 and got an 85k-char result (see gaps)."}+{"id": "thread-mention-without-link-after-read", "area": "orchestration", "kind": "bad", "pattern": "thread mentioned without t3-thread link", "experience": "Asked to explain what went wrong in a given thread, the agent named it by id or title with no t3-thread:// link.", "rule": "To mention another thread to the user, write its `link` verbatim: <t3-thread://v2/<environmentId>/<threadId>>, with no title.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Fix ultrafast pricing", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "status": "idle"}, "items": [{"position": 210, "createdBy": "assistant", "toolName": "t3_thread_send", "text": "t3_thread_send threadId=44444444-4444-4444-8444-000000000001 message='Round 2. Read only, as before...'"}, {"position": 214, "createdBy": "user", "text": "Use delegate_task please, this should not be a separate thread."}], "nextPosition": 215, "hasMore": false}}}, "prompt": "11111111-1111-4111-8111-111111111111 This thread used the wrong tool. Figure out why.", "expect": {"calls": [{"tool": "t3_thread_read", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}], "textMust": ["t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111"], "textMustNot": ["t3-thread://v1/"]}, "notes": "Real agent was Codex before the 10-21 untruncation fix, when the link rule often did not reach Codex. May pass on Claude today; keep as a regression check for the rewrite.", "maxSteps": 10}+{"id": "found-thread-mentioned-without-link", "area": "orchestration", "kind": "bad", "pattern": "thread mentioned without t3-thread link", "experience": "The agent found yesterday's thread by search and told the user where they left off, but did not link the thread.", "rule": "To mention another thread to the user, write its `link` verbatim: <t3-thread://v2/<environmentId>/<threadId>>, with no title.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_thread_search": {"matches": [{"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "22222222-2222-4222-8222-222222222222", "title": "Fix macOS camera permission prompt", "snippet": "...the app never asks for camera permission on mac...", "messageCreatedAt": "2026-10-19T21:04:00Z"}]}, "t3_thread_list": {"threads": [{"threadId": "11111111-1111-4111-8111-111111111111", "title": "Fix macOS camera permission prompt", "status": "idle"}]}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Fix macOS camera permission prompt", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "status": "idle"}, "items": [{"position": 88, "createdBy": "assistant", "text": "The fix is committed locally on branch fix/camera-entitlement in another clone. No PR is open yet."}], "nextPosition": 89, "hasMore": false}}, "shellMocks": [{"match": "gh pr list", "output": ""}]}, "prompt": "Did I ever make a PR to fix the issue where the app couldn't request camera permission on mac? I had a thread about it yesterday and forgot where we left off.", "expect": {"textMust": ["t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111"], "textMustNot": ["t3-thread://v1/"]}, "notes": "Also seen in another thread ('Found the prior audits (Jul 21, Sep 1, Oct 3 threads ...)' with no links). Original prompt also said 'get it fixed full stop'; dropped to keep the case small."}+{"id": "thread-link-rewritten-with-title", "area": "orchestration", "kind": "bad", "pattern": "thread link rewritten with a title", "experience": "Thread links carried the title the agent wrote, which went stale once the user renamed the thread. The app already shows each linked thread's current title, so maintainers asked that agents write only the stable link.", "rule": "To mention another thread to the user, write its `link` verbatim: <t3-thread://v2/<environmentId>/<threadId>>, with no title.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"t3_thread_list": {"threads": [{"threadId": "11111111-1111-4111-8111-111111111111", "title": "Fix flaky checkout test", "status": "running"}, {"threadId": "44444444-4444-4444-8444-000000000002", "title": "Upgrade Vite", "status": "idle"}]}}}, "prompt": "Which of my threads in this project are still running?", "expect": {"calls": [{"tool": "t3_thread_list"}], "textMust": ["<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>"], "textMustNot": ["\\]\\(t3-thread://", "t3-thread://v1/"]}, "notes": "Source: maintainer request with the v2 thread link change. The old instructions carried a titled [title](t3-thread://v1/<exact id>) template for threads without a link."}{"id": "cross-provider-delegates-with-options", "area": "orchestration", "kind": "guard", "pattern": "capabilities then cross-provider delegate_task with options", "experience": "Asked for Sol 'high' and Muse Wonder Full 'xhigh' delegates, the agent read capabilities and put effort in target.options.", "rule": "Read the selected model's descriptors from orchestrator_capabilities and put settings in target.options, not only in the prompt.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}}, "prompt": "I want this codebase reviewed by two different models. Spin up a delegate for GPT-6.1 Sol high in Codex and one for Muse Wonder Full at xhigh. Tell them both to explore the codebase and find interesting things, plus some easy wins.", "expect": {"order": ["orchestrator_capabilities", "delegate_task"], "calls": [{"tool": "delegate_task", "args": {"target.providerInstanceId": "codex", "target.model": "gpt-6.1-sol", "target.options.reasoningEffort": "high"}}, {"tool": "delegate_task", "args": {"target.providerInstanceId": "muse", "target.model": "muse-wonder-full", "target.options.reasoningEffort": "xhigh"}}], "notCalls": ["t3_thread_launch", "create_threads", "Agent"]}, "notes": "target.options may be an object or an [{id,value}] array. The runner must normalize arrays to an object before matching 'target.options.<id>'."}{"id": "same-provider-delegate-with-effort", "area": "orchestration", "kind": "guard", "pattern": "model options force delegate_task over native", "experience": "Asked for an Opus 5.5 (xhigh) delegate from a Claude parent, the agent used delegate_task with target.options effort xhigh.", "rule": "When model options are requested ... use delegate_task even for native-supported models. Native subagents cannot reliably apply T3 model options.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}}, "prompt": "Spin up an Opus 5.5 delegate in Claude Code on xhigh to research why the update flow spams 'connected successfully' toasts. Have it write up the causes in priority order.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.providerInstanceId": "claudeAgent", "target.model": "claude-opus-5-5", "target.options.effort": "xhigh"}}], "notCalls": ["Agent", "Workflow"]}, "notes": "A shorter text that drops the options rule could send this to the native Agent tool with model 'opus' and lose xhigh."}{"id": "async-delegate-then-end-turn", "area": "orchestration", "kind": "guard", "pattern": "async delegate then end turn", "experience": "After starting an async Sol review the agent said its completion would wake the thread and ended the turn.", "rule": "Prefer mode='async' for long work ... the task's completion still wakes this thread. (intended: end the turn; no sleep or task_status loops)", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default", "task_status": "default"}, "world": {"branch": "fix/session-stop", "commits": [{"sha": "3e8d1f0", "subject": "fix(server): stop clears an orphaned task row"}], "diff": "diff --git a/src/session.ts b/src/session.ts\n--- a/src/session.ts\n+++ b/src/session.ts\n@@ -10,1 +10,1 @@\n- if (task.status !== \"running\") return;\n+ if (task.status === \"cancelled\") return emitTaskRow(task);\n", "prs": [{"number": 123, "title": "fix(server): stop clears an orphaned task row", "headRefName": "fix/session-stop"}]}}, "prompt": "Have a GPT-6.1 Sol delegate review the diff on this branch (https://github.com/acme/app/pull/123) before I merge it.", "expect": {"calls": [{"tool": "delegate_task", "args": {"target.model": "gpt-6.1-sol"}}], "maxCalls": {"task_status": 0, "t3_thread_wait": 0}, "shellMustNot": ["\\bsleep\\b"]}, "notes": ""}@@ -24,7 +25,7 @@{"id": "opus-review-too-via-delegate", "area": "orchestration", "kind": "guard", "pattern": "same-provider review via delegate_task", "experience": "'Have Opus review the things too' from a Claude parent with no extra settings runs a native Opus subagent the parent waits for.", "rule": "Use your native tool when the child uses your provider, a model it offers, and no settings beyond yours, and you need it only in this turn.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Get a Sol review on https://github.com/acme/app/pull/123 before we file anything else."}, {"role": "assistant", "text": "Sol approved PR 123 after one fix to its description.", "toolCalls": [{"tool": "delegate_task", "input": {"title": "Sol review PR 123", "mode": "async", "clientRequestId": "sol-123-r1", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Review https://github.com/acme/app/pull/123. Read only."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "childRunId": "run-child-1", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "task_status", "input": {"taskId": "task-1"}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "status": "completed", "workState": "result_available", "summary": "APPROVE after S1 (description wording)."}}]}], "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}, "world": {"prs": [{"number": 123, "title": "fix(web): keep scroll position on thread switch", "headRefName": "fix/scroll"}]}, "harness": "claude"}, "prompt": "Have Opus review the things too, not just Sol", "expect": {"calls": [{"tool": "Agent", "args": {"model": "~opus"}}], "notCalls": ["delegate_task", "t3_thread_send"], "callsMustNot": [{"tool": "Agent", "args": {"run_in_background": true}}]}, "notes": "T3's 'prefer native for same-provider' line pulls toward the native Agent tool here; this stayed correct in the real thread."}{"id": "delegates-then-new-thread-with-model", "area": "orchestration", "kind": "guard", "pattern": "new thread asked: t3_thread_launch with model", "experience": "'Spin up 2 Opus delegates ... then start a new thread using Grok 4.7 to implement' gave 2 delegate_task calls and 1 t3_thread_launch on Grok.", "rule": "t3_thread_launch and create_threads ... Use them only when the user explicitly asks for separate/new/top-level threads.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Spin up 2 Opus 5.5 delegates to explore performance wins in this app."}, {"role": "assistant", "text": "Both Opus delegates are done.\n- Client: the thread list re-renders every row on each streamed token.\n- Server: each event write runs a full projection rebuild.", "toolCalls": [{"tool": "delegate_task", "input": {"title": "Opus: client performance", "mode": "wait", "clientRequestId": "perf-client", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Find concrete client performance wins. Read only."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "childRunId": "run-child-1", "status": "completed", "workState": "result_available", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5", "summary": "Client: the thread list re-renders every row on each streamed token. Memoize rows by thread id and select only the active thread's stream."}}, {"tool": "delegate_task", "input": {"title": "Opus: server performance", "mode": "wait", "clientRequestId": "perf-server", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Find concrete server performance wins. Read only."}, "result": {"taskId": "task-2", "childThreadId": "44444444-4444-4444-8444-000000000002", "childRunId": "run-child-2", "status": "completed", "workState": "result_available", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5", "summary": "Server: each event write runs a full projection rebuild. Apply events to the projection incrementally."}}]}], "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "t3_thread_launch": {"threadId": "11111111-1111-4111-8111-111111111111", "projectId": "22222222-2222-4222-8222-222222222222", "modelSelection": {"instanceId": "grok", "model": "grok-4.7"}, "status": "starting"}}}, "prompt": "Summarize their thoughts, then start a new thread using Grok 4.7 to implement your findings.", "expect": {"calls": [{"tool": "t3_thread_launch", "args": {"modelSelection.model": "~grok"}}], "notCalls": ["delegate_task", "create_threads"]}, "notes": "Pattern 2 (new thread asked but delegate used) had only 1-2 real cases in 40 asks, so this is a guard. Check the arg path against the current t3_thread_launch schema."}{"id": "subagent-ask-no-new-threads", "area": "orchestration", "kind": "guard", "pattern": "subagent asked: no t3_thread_launch/create_threads", "experience": "'Have Haiku 5.5 subagents do the exploration' must give child tasks, not top-level threads. 0 of 98 subagent asks went wrong, and the user still warns about it.", "rule": "Never use them merely because the user said \"subagent\" or requested parallel delegated work.", "privacy": "commit-safe", "setup": {"role": "top", "mocks": {"orchestrator_capabilities": {"parentThreadId": "33333333-3333-4333-8333-333333333333", "inheritedProviderInstanceId": "claudeAgent", "inheritedModel": "claude-sonnet-5-5", "inheritedOptions": [{"id": "effort", "value": "high"}], "runtimeMode": "full-access", "interactionMode": "default", "features": {"appOwnedSubagents": true, "asyncPolling": true, "cancellation": true, "batchThreadCreation": true, "threadManagement": true, "incrementalThreadRead": true, "scheduledTasks": true}, "providers": [{"providerInstanceId": "claudeAgent", "driverKind": "claudeAgent", "displayName": "Claude", "models": [{"id": "claude-opus-5-5", "label": "Claude Opus 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "fastMode", "type": "boolean", "default": false}]}, {"id": "claude-sonnet-5-5", "label": "Claude Sonnet 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}, {"id": "claude-haiku-5-5", "label": "Claude Haiku 5.5", "options": [{"id": "effort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "codex", "driverKind": "codex", "displayName": "Codex", "models": [{"id": "gpt-6.1-sol", "label": "GPT-6.1 Sol", "options": [{"id": "reasoningEffort", "values": ["low", "medium", "high", "xhigh", "max"], "default": "high"}, {"id": "serviceTier", "values": ["default", "priority"], "default": "default"}]}]}, {"providerInstanceId": "muse", "driverKind": "muse", "displayName": "Muse Code", "runtimeModes": ["approval-required", "full-access"], "models": [{"id": "muse-wonder-full", "label": "Muse Wonder Full", "options": [{"id": "reasoningEffort", "values": ["minimal", "low", "medium", "high", "xhigh", "max"], "default": "high"}]}]}, {"providerInstanceId": "grok", "driverKind": "grok", "displayName": "Grok", "models": [{"id": "grok-4.7", "label": "Grok 4.7", "options": []}]}]}, "delegate_task": "default"}, "world": {"files": {"package.json": "{\n \"name\": \"app\",\n \"private\": true,\n \"packageManager\": \"[email protected]\",\n \"scripts\": {\n \"dev\": \"turbo run dev\",\n \"build\": \"turbo run build\",\n \"test\": \"vitest run\",\n \"typecheck\": \"turbo run typecheck\"\n }\n}\n", "pnpm-workspace.yaml": "packages:\n - apps/*\n - packages/*\n", "turbo.json": "{\n \"tasks\": {\n \"build\": { \"outputs\": [\"dist/**\"] },\n \"typecheck\": {},\n \"dev\": { \"cache\": false }\n }\n}\n", "apps/web/package.json": "{ \"name\": \"@app/web\", \"scripts\": { \"dev\": \"vite\", \"build\": \"vite build\" } }\n", "apps/server/package.json": "{ \"name\": \"@app/server\", \"scripts\": { \"dev\": \"tsx watch src/index.ts\", \"build\": \"tsc\" } }\n", ".github/workflows/ci.yml": "name: ci\non: [push, pull_request]\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v4\n - run: pnpm install --frozen-lockfile\n - run: pnpm typecheck\n - run: pnpm test\n", "scripts/seed-dev-db.ts": "import { db } from '../apps/server/src/db';\n\n// Seeds the dev database with 20 fake users.\nfor (let i = 0; i < 20; i++) await db.insert('users', { name: `user${i}` });\n", "apps/web/src/main.tsx": "import { createRoot } from 'react-dom/client';\nimport { App } from './App';\n\ncreateRoot(document.getElementById('root')!).render(<App />);\n", "apps/web/src/App.tsx": "export function App() {\n return <ThreadList />;\n}\n", "apps/server/src/index.ts": "import { createServer } from './server';\n\ncreateServer().listen(Number(process.env.PORT ?? 3773));\n", "apps/server/src/db.ts": "import { Database } from 'better-sqlite3';\n\nexport const db = new Database(process.env.DB_PATH ?? 'dev.sqlite');\n"}}}, "prompt": "I want your honest thoughts on this project. Do a deep dive and really read through it so you know it well. Have Haiku 5.5 subagents do the exploration.", "expect": {"notCalls": ["t3_thread_launch", "create_threads"]}, "notes": "Narrow on purpose: native vs delegate is graded in the bad cases. The user's preemptive guard: 'Please don't make new threads with the T3 Code MCP, only create delegates, workflows, subagents etc.'."}-{"id": "thread-send-to-named-top-level-thread", "area": "orchestration", "kind": "guard", "pattern": "t3_thread_send to a top-level thread the user names", "experience": "Given another top-level thread id to talk to, the agent used t3_thread_send on it and linked it in the reply.", "rule": "To mention another thread to the user, link it as [title](t3-thread://v1/<threadId>).", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The other agent disagreed:\n\nTheirs is the better plan to execute. Mine is the wider survey. Start from theirs and graft three items from mine.\n\nTheir 5 points: 1) cache tsc output per package, 2) split the web typecheck into two projects, 3) drop the duplicate lint step in CI, 4) run typecheck only for changed packages in CI (memo), 5) measure before and after on main."}, {"role": "assistant", "text": "We now agree on almost everything. I accept points 1, 2, 3, and 5. I disagree with one detail of the memo in point 4: CI must also typecheck the packages that depend on a changed package, not only the changed ones. From my plan I would graft: project references, a warm tsc cache restored in CI, and a per-package timing report."}], "mocks": {"t3_thread_send": {"threadId": "11111111-1111-4111-8111-111111111111", "messageId": "msg-1", "runId": "run-1", "queued": true}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Faster type checking", "link": "[Faster type checking](t3-thread://v1/11111111-1111-4111-8111-111111111111)", "status": "idle"}, "items": [{"position": 41, "createdBy": "assistant", "text": "Plan: 1) cache tsc output per package, 2) split the web typecheck, 3) drop the duplicate lint step, 4) memo: typecheck only changed packages in CI, 5) measure on main."}, {"position": 42, "createdBy": "user", "text": "Another agent has a wider survey. I'll bring its answer back here."}], "nextPosition": 43, "hasMore": false}}}, "prompt": "That thread is on this machine, you can talk to it directly with t3 code: 11111111-1111-4111-8111-111111111111", "expect": {"calls": [{"tool": "t3_thread_send", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}], "notCalls": ["delegate_task", "t3_thread_launch"], "textMust": ["t3-thread://v1/[^)\\s]*11111111-1111-4111-8111-111111111111"]}, "notes": "Keeps a rewrite from over-banning t3_thread_send. The ban is only for delegated childThreadIds."}+{"id": "thread-send-to-named-top-level-thread", "area": "orchestration", "kind": "guard", "pattern": "t3_thread_send to a top-level thread the user names", "experience": "Given another top-level thread id to talk to, the agent used t3_thread_send on it and linked it in the reply.", "rule": "To mention another thread to the user, write its `link` verbatim: <t3-thread://v2/<environmentId>/<threadId>>, with no title.", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "The other agent disagreed:\n\nTheirs is the better plan to execute. Mine is the wider survey. Start from theirs and graft three items from mine.\n\nTheir 5 points: 1) cache tsc output per package, 2) split the web typecheck into two projects, 3) drop the duplicate lint step in CI, 4) run typecheck only for changed packages in CI (memo), 5) measure before and after on main."}, {"role": "assistant", "text": "We now agree on almost everything. I accept points 1, 2, 3, and 5. I disagree with one detail of the memo in point 4: CI must also typecheck the packages that depend on a changed package, not only the changed ones. From my plan I would graft: project references, a warm tsc cache restored in CI, and a per-package timing report."}], "mocks": {"t3_thread_send": {"threadId": "11111111-1111-4111-8111-111111111111", "messageId": "msg-1", "runId": "run-1", "queued": true}, "t3_thread_read": {"thread": {"threadId": "11111111-1111-4111-8111-111111111111", "title": "Faster type checking", "link": "<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>", "status": "idle"}, "items": [{"position": 41, "createdBy": "assistant", "text": "Plan: 1) cache tsc output per package, 2) split the web typecheck, 3) drop the duplicate lint step, 4) memo: typecheck only changed packages in CI, 5) measure on main."}, {"position": 42, "createdBy": "user", "text": "Another agent has a wider survey. I'll bring its answer back here."}], "nextPosition": 43, "hasMore": false}}}, "prompt": "That thread is on this machine, you can talk to it directly with t3 code: 11111111-1111-4111-8111-111111111111", "expect": {"calls": [{"tool": "t3_thread_send", "args": {"threadId": "11111111-1111-4111-8111-111111111111"}}], "notCalls": ["delegate_task", "t3_thread_launch"], "textMust": ["<t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>"]}, "notes": "Keeps a rewrite from over-banning t3_thread_send. The ban is only for delegated childThreadIds."}{"id": "too-many-delegates-cancel-extras", "area": "orchestration", "kind": "guard", "pattern": "volume complaint: cancel, do not add", "experience": "After 'You're doing too much man, we have like 6+ delegates going', the agent stopped the stale review tasks and made the next fix without a new round.", "rule": "none (task_cancel description covers the action)", "privacy": "commit-safe", "setup": {"role": "top", "priorTurns": [{"role": "user", "text": "Take over https://github.com/acme/app/pull/123. Have Sol and Opus delegates audit it hard."}, {"role": "assistant", "text": "Five audits are running on the PR: three Sol (error handling, concurrency, API surface) and two Opus (tests, migration safety).", "toolCalls": [{"tool": "delegate_task", "input": {"title": "Sol audit: error handling", "mode": "async", "clientRequestId": "pr123-sol-error", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Audit https://github.com/acme/app/pull/123 for error handling problems. Report each with file:line. Read only."}, "result": {"taskId": "task-1", "childThreadId": "44444444-4444-4444-8444-000000000001", "childRunId": "run-child-1", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "delegate_task", "input": {"title": "Sol audit: concurrency", "mode": "async", "clientRequestId": "pr123-sol-concurrency", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Audit https://github.com/acme/app/pull/123 for concurrency problems. Report each with file:line. Read only."}, "result": {"taskId": "task-2", "childThreadId": "44444444-4444-4444-8444-000000000002", "childRunId": "run-child-2", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "delegate_task", "input": {"title": "Sol audit: API surface", "mode": "async", "clientRequestId": "pr123-sol-api", "target": {"providerInstanceId": "codex", "model": "gpt-6.1-sol", "options": {"reasoningEffort": "high"}}, "task": "Audit https://github.com/acme/app/pull/123 for API surface problems. Report each with file:line. Read only."}, "result": {"taskId": "task-3", "childThreadId": "44444444-4444-4444-8444-000000000003", "childRunId": "run-child-3", "status": "running", "workState": "working", "providerInstanceId": "codex", "model": "gpt-6.1-sol"}}, {"tool": "delegate_task", "input": {"title": "Opus audit: tests", "mode": "async", "clientRequestId": "pr123-opus-tests", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Audit https://github.com/acme/app/pull/123 for tests problems. Report each with file:line. Read only."}, "result": {"taskId": "task-4", "childThreadId": "44444444-4444-4444-8444-000000000004", "childRunId": "run-child-4", "status": "running", "workState": "working", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}}, {"tool": "delegate_task", "input": {"title": "Opus audit: migration safety", "mode": "async", "clientRequestId": "pr123-opus-migration", "target": {"providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}, "task": "Audit https://github.com/acme/app/pull/123 for migration safety problems. Report each with file:line. Read only."}, "result": {"taskId": "task-5", "childThreadId": "44444444-4444-4444-8444-000000000005", "childRunId": "run-child-5", "status": "running", "workState": "working", "providerInstanceId": "claudeAgent", "model": "claude-opus-5-5"}}]}], "mocks": {"task_status": {"status": "running", "workState": "working"}, "task_cancel": {"status": "cancel_requested"}}, "world": {"prs": [{"number": 123, "title": "feat(server): resumable uploads", "headRefName": "feat/resumable-uploads"}]}}, "prompt": "You're doing too much man, we have like 6+ delegates going. We don't need to go that hard.", "expect": {"calls": [{"tool": "task_cancel"}], "maxCalls": {"delegate_task": 0}, "notCalls": ["t3_thread_interrupt"]}, "notes": "Pairs with review-round-per-bot-nit."}{"id": "control-new-thread-view-wording", "area": "orchestration", "kind": "control", "pattern": "'new thread' as product text", "experience": "A UI bug report that says 'new thread view' needs a code fix, not a new T3 thread or delegate.", "rule": "t3_thread_launch and create_threads ... only when the user explicitly asks for separate/new/top-level threads.", "privacy": "commit-safe", "setup": {"role": "top", "world": {"files": {"apps/mobile/src/Sidebar.tsx": "export function Sidebar() {\n return (\n <View style={styles.sidebar} pointerEvents={isFoldable ? 'box-none' : 'auto'}>\n <ThreadList onPress={openThread} />\n </View>\n );\n}\n", "apps/mobile/src/NewThreadView.tsx": "export function NewThreadView() {\n return <View style={StyleSheet.absoluteFill}>{/* composer */}</View>;\n}\n"}}}, "prompt": "On Android foldables the sidebar is visible but tapping threads does nothing in some places, like the new thread view or settings. It makes the sidebar feel broken. Fix it.", "expect": {"notCalls": ["t3_thread_launch", "create_threads", "delegate_task", "orchestrator_capabilities"]}, "notes": ""}{"id": "control-subagent-label-bug-wording", "area": "orchestration", "kind": "control", "pattern": "'subagent' as product text", "experience": "A bug report about how subagent models are labeled is a code task. It needs no delegation.", "rule": "none", "privacy": "commit-safe", "setup": {"role": "top", "world": {"commits": [{"sha": "61b0e9d", "subject": "fix(web): label subagent messages with the subagent's model"}], "files": {"apps/web/src/subagentLabel.ts": "export function subagentModelLabel(run: Run, parent: Thread) {\n return run.model ?? parent.model;\n}\n"}}}, "prompt": "I recently fixed a bug where models were labeled wrong inside subagents that run through Claude Code. I think it came back in a different form. A Sol subagent shows the parent's model name in the UI. Find the cause and fix it.", "expect": {"notCalls": ["delegate_task", "orchestrator_capabilities", "t3_thread_launch", "create_threads", "Workflow"]}, "notes": ""}diff --git a/evals/mcp-tool-use/run.test.ts b/evals/mcp-tool-use/run.test.tsindex 9cf9a6db484..b0a5ed0d51e 100644--- a/evals/mcp-tool-use/run.test.ts+++ b/evals/mcp-tool-use/run.test.ts@@ -104,7 +104,7 @@ it("passes a good run and names every rule a bad run breaks", () => {maxCalls: { task_status: 0 },endsTurnAfter: "delegate_task",shellMustNot: ["\\bsleep\\b"],- textMust: ["t3-thread://v1/"],+ textMust: ["t3-thread://v2/"],textMustNot: ["Paste .*token"],linked: ["~/pull/124"],};@@ -117,7 +117,7 @@ it("passes a good run and names every rule a bad run breaks", () => {input: { task: "Prior findings: ...", target: { options: { reasoningEffort: "max" } } },},],- text: "Started [Review](t3-thread://v1/11111111-1111-4111-8111-111111111111). Do not paste a token.",+ text: "Started <t3-thread://v2/eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee/11111111-1111-4111-8111-111111111111>. Do not paste a token.",stopReason: "end_turn",linked: ["https://github.com/acme/app/pull/124"],};@@ -146,7 +146,7 @@ it("passes a good run and names every rule a bad run breaks", () => {"maxCalls task_status <= 0","endsTurnAfter delegate_task","shellMustNot /\\bsleep\\b/",- "textMust /t3-thread://v1//",+ "textMust /t3-thread://v2//","textMustNot /Paste .*token/","linked ~/pull/124",]);diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.tsindex c1970086f77..af5a6455f50 100644--- a/evals/mcp-tool-use/run.ts+++ b/evals/mcp-tool-use/run.ts@@ -33,7 +33,7 @@ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";import { taskPrompt } from "../../apps/server/src/mcp/delegatedTaskModes.ts";import * as McpInvocationContext from "../../apps/server/src/mcp/McpInvocationContext.ts";import { advertisedJsonSchema } from "../../apps/server/src/mcp/advertisedJsonSchema.ts";-import { ORCHESTRATOR_MCP_RUNNING_TASK_NEXT } from "@t3tools/contracts";+import { EnvironmentId, ORCHESTRATOR_MCP_RUNNING_TASK_NEXT, ThreadId } from "@t3tools/contracts";import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences";import { formatThreadLink } from "@t3tools/shared/threadLinks";import { buildCodexAdditionalContext } from "../../apps/server/src/provider/CodexDeveloperInstructions.ts";@@ -893,14 +893,24 @@ const t3Default = (sample: Sample, name: string, input: Readonly<Record<string,}};+/** The machine the fake threads live on. */+const EVAL_ENVIRONMENT_ID = EnvironmentId.make("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee");+/** Fields T3 adds to real thread and task results, applied to mocks and defaults alike. */const withProductFields = (name: string, value: unknown, child: boolean): unknown => {if (!isRecord(value)) return value;const linked = (thread: unknown, idKey = "threadId") => {if (!isRecord(thread) || thread.link !== undefined) return thread;const id = thread[idKey] ?? thread.id;- const title = valueText(thread.title) || "Thread";- return typeof id === "string" ? { ...thread, link: formatThreadLink(id, title) } : thread;+ return typeof id === "string"+ ? {+ ...thread,+ link: formatThreadLink({+ environmentId: EVAL_ENVIRONMENT_ID,+ threadId: ThreadId.make(id),+ }),+ }+ : thread;};const listed = (key: string) =>Array.isArray(value[key]) ? { ...value, [key]: value[key].map((item) => linked(item)) } : value;@@ -915,6 +925,7 @@ const withProductFields = (name: string, value: unknown, child: boolean): unknowreturn { ...value, thread: linked(value.thread) };case "t3_thread_launch":case "t3_thread_send":+ case "run_scheduled_task_now":return linked(value);case "t3_thread_list":case "create_threads":diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.tsindex 5ce74766c40..6737fdea693 100644--- a/packages/provider-core/src/server/orchestrationInstructions.ts+++ b/packages/provider-core/src/server/orchestrationInstructions.ts@@ -15,7 +15,7 @@ Ordinary coding tasks need no T3 tools.- Given a thread id, \`t3_thread_read\` it before you answer about it.- Another machine: \`t3_environment_links\` lists linked ones. Pass its \`environmentId\` to a T3 tool to act there. Ids are then that machine's, so pass \`threadId\`.- A machine the user names that is not linked ("delegate this to my vps"): call \`t3_environment_link\` with a \`hint\` from their words. Never ask for a pairing code in chat.-- In your reply, a thread's first mention is its \`link\` verbatim. No \`link\`: \`[title](t3-thread://v1/<exact id>)\`. Never a plain title or bare id. A thread on a linked machine: its title and machine, not its link.+- In your reply, mention a thread by its \`link\`, verbatim. Never a plain title or bare id.- A secret: call \`request_secret\` yourself. Pass its \`secretRef\` to a T3 tool, or use \`delivery: "file"\` for a shell command. Never ask in chat or invent one. When asked only to schedule, \`schedule_task\` without running its prompt.- T3 tools may load late. Try the name once before you call it absent.`,`### Visuals and previewdiff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.tsindex e23195f693a..aa753e6303f 100644--- a/packages/shared/src/markdownPipeline.test.ts+++ b/packages/shared/src/markdownPipeline.test.ts@@ -12,7 +12,7 @@ it("preserves in-app thread links through the shared Markdown sanitizer", () =>.use(CHAT_MARKDOWN_REHYPE_PLUGINS);const tree = processor.runSync(processor.parse(- '[Open thread](t3-thread://v1/environment/thread)\n\n<a href="javascript:alert(1)">Unsafe</a>',+ '[Open thread](t3-thread://v1/thread)\n\n<t3-thread://v2/environment/thread:a%3A1>\n\n<a href="javascript:alert(1)">Unsafe</a>',),);expect(tree.children[0]).toMatchObject({@@ -20,11 +20,21 @@ it("preserves in-app thread links through the shared Markdown sanitizer", () =>children: [{tagName: "a",- properties: { href: "t3-thread://v1/environment/thread" },+ properties: { href: "t3-thread://v1/thread" },children: [{ type: "text", value: "Open thread" }],},],});+ expect(tree.children[2]).toMatchObject({+ tagName: "p",+ children: [+ {+ tagName: "a",+ properties: { href: "t3-thread://v2/environment/thread:a%3A1" },+ children: [{ type: "text", value: "t3-thread://v2/environment/thread:a%3A1" }],+ },+ ],+ });expect(JSON.stringify(tree)).not.toContain("javascript:");});diff --git a/packages/shared/src/threadLinks.test.ts b/packages/shared/src/threadLinks.test.tsindex a6c8eebc7e6..82d981f5982 100644--- a/packages/shared/src/threadLinks.test.ts+++ b/packages/shared/src/threadLinks.test.ts@@ -1,53 +1,69 @@import { describe, expect, it } from "vite-plus/test";-import { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";import {formatThreadLink,+ guessThreadLinkRef,parseThreadLinkHref,relabelThreadLinks,- resolveThreadLinkRef,+ threadLinkCandidates,+ threadLinkRefs,} from "./threadLinks.ts";const ref = (environmentId: string, threadId = "chat-1") => ({environmentId: EnvironmentId.make(environmentId),threadId: ThreadId.make(threadId),});+const v1 = (threadId: string) => ({ environmentId: null, threadId: ThreadId.make(threadId) });+const local = EnvironmentId.make("local");+const titlesIn =+ (titles: Record<string, Record<string, string>>) =>+ ({ environmentId, threadId }: ScopedThreadRef) =>+ titles[environmentId]?.[threadId];describe("thread link destinations", () => {- it("prefers the local literal id, then the local decoded id, over remote matches", () => {- const source = ref("local", "provider%3A1");- const decoded = ref("local", "provider:1");- const remote = ref("remote", "provider%3A1");- expect(resolveThreadLinkRef(source, [remote, decoded, source])).toEqual(source);- expect(resolveThreadLinkRef(source, [remote, decoded])).toEqual(decoded);+ it("names a v1 link's thread in the message's environment, as written and then decoded", () => {+ expect(threadLinkCandidates(v1("provider%3A1"), local)).toEqual([+ ref("local", "provider%3A1"),+ ref("local", "provider:1"),+ ]);});- it("opens the unique matching chat in another environment", () => {+ it("opens the unique matching chat in another environment for a v1 link", () => {const destination = ref("remote");- expect(resolveThreadLinkRef(ref("local"), [ref("local", "other-chat"), destination])).toEqual(+ expect(guessThreadLinkRef(v1("chat-1"), [ref("local", "other-chat"), destination])).toEqual(destination,);});+ it("opens a v2 link only in its own environment", () => {+ const there = ref("there", "a%3A1");+ expect(threadLinkCandidates(there, local)).toEqual([there, ref("there", "a:1")]);+ expect(guessThreadLinkRef(there, [ref("elsewhere", "a%3A1"), ref("elsewhere", "a:1")])).toBe(+ null,+ );+ });+it("leaves ambiguous or missing destinations unresolved", () => {- const source = ref("local", "provider%3A1");+ const link = v1("provider%3A1");const literal = ref("remote", "provider%3A1");const decoded = ref("remote", "provider:1");expect(- resolveThreadLinkRef(source, [literal, ref("other-remote", literal.threadId), decoded]),- ).toBeNull();- expect(- resolveThreadLinkRef(source, [decoded, ref("other-remote", decoded.threadId)]),+ guessThreadLinkRef(link, [literal, ref("other-remote", literal.threadId), decoded]),).toBeNull();- expect(resolveThreadLinkRef(source, [ref("remote", "other-chat")])).toBeNull();+ expect(guessThreadLinkRef(link, [decoded, ref("other-remote", decoded.threadId)])).toBeNull();+ expect(guessThreadLinkRef(link, [ref("remote", "other-chat")])).toBeNull();});});describe("thread links", () => {- it("takes the thread id verbatim, percent escapes included", () => {- expect(parseThreadLinkHref("t3-thread://v1/mcp:1234")).toBe("mcp:1234");- expect(parseThreadLinkHref("t3-thread://v1/thread:delegated-task:mcp%3A1")).toBe(- "thread:delegated-task:mcp%3A1",+ it("takes the ids verbatim, percent escapes included", () => {+ expect(parseThreadLinkHref("t3-thread://v1/mcp:1234")).toEqual(v1("mcp:1234"));+ expect(parseThreadLinkHref("t3-thread://v1/thread:delegated-task:mcp%3A1")).toEqual(+ v1("thread:delegated-task:mcp%3A1"),+ );+ expect(parseThreadLinkHref("t3-thread://v2/env-1/thread:a/b%3A1")).toEqual(+ ref("env-1", "thread:a/b%3A1"),);});@@ -55,59 +71,90 @@ describe("thread links", () => {expect(parseThreadLinkHref("https://t3.codes")).toBeNull();expect(parseThreadLinkHref("t3-thread://v1/")).toBeNull();expect(parseThreadLinkHref("t3-thread://v1/ ")).toBeNull();+ expect(parseThreadLinkHref("t3-thread://v2/env-1")).toBeNull();+ expect(parseThreadLinkHref("t3-thread://v2/env-1/")).toBeNull();+ expect(parseThreadLinkHref("t3-thread://v2//chat-1")).toBeNull();});it("resolves a percent-encoded id when the id as written names no thread", () => {- const titles = new Map([- ["thread:project:1", "Decoded"],- ["provider%3A1", "Literal escape"],- ]);+ const title = titlesIn({ local: { "thread:project:1": "Decoded", "provider%3A1": "Literal" } });expect(relabelThreadLinks("[a](t3-thread://v1/thread%3Aproject%3A1) [b](t3-thread://v1/provider%3A1)",- (threadId) => titles.get(threadId),+ local,+ title,),- ).toBe(- "[Decoded](t3-thread://v1/thread:project:1) [Literal escape](t3-thread://v1/provider%3A1)",+ ).toBe("[Decoded](t3-thread://v1/thread:project:1) [Literal](t3-thread://v1/provider%3A1)");+ const untitled = titlesIn({ local: { "a%3A1": "", "a:1": "Other" } });+ expect(relabelThreadLinks("[Kept](t3-thread://v1/a%3A1)", local, untitled)).toBe(+ "[Kept](t3-thread://v1/a%3A1)",);- const untitled = new Map([- ["a%3A1", ""],- ["a:1", "Other"],- ]);+ });++ it("titles a v2 link from its own environment and writes it with that title", () => {+ const title = titlesIn({ local: { t1: "Here" }, there: { t1: "There" } });+ expect(+ relabelThreadLinks(+ "<t3-thread://v2/there/t1> and [old](t3-thread://v2/local/t1)",+ local,+ title,+ ),+ ).toBe("[There](t3-thread://v2/there/t1) and [Here](t3-thread://v2/local/t1)");+ });++ it("turns a v2 link it cannot resolve into plain text, never the raw link", () => {expect(- relabelThreadLinks("[Kept](t3-thread://v1/a%3A1)", (threadId) => untitled.get(threadId)),- ).toBe("[Kept](t3-thread://v1/a%3A1)");+ relabelThreadLinks(+ "<t3-thread://v2/there/t1>, <t3-thread://v2/local/t1>, [Old title](t3-thread://v2/there/t1)",+ local,+ () => undefined,+ ),+ ).toBe("Thread on another machine, Thread no longer available, Old title");+ expect(relabelThreadLinks("[Old](t3-thread://v1/t1)", local, () => undefined)).toBe(+ "[Old](t3-thread://v1/t1)",+ );});it("leaves links inside code spans and fences as written", () => {const markdown = ["Live [old](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.","```md",- "[old](t3-thread://v1/t1)",+ "<t3-thread://v2/local/t1>","```",- "After [old](t3-thread://v1/t1)",+ "After <t3-thread://v2/local/t1>",].join("\n");- expect(relabelThreadLinks(markdown, () => "New")).toBe(+ expect(relabelThreadLinks(markdown, local, () => "New")).toBe(["Live [New](t3-thread://v1/t1), literal `[old](t3-thread://v1/t1)`.","```md",- "[old](t3-thread://v1/t1)",+ "<t3-thread://v2/local/t1>","```",- "After [New](t3-thread://v1/t1)",+ "After [New](t3-thread://v2/local/t1)",].join("\n"),);});- it("writes the thread id verbatim so the link opens that exact thread", () => {- const link = formatThreadLink("thread:delegated-task:mcp%3A1", "Fix");- expect(link).toBe("[Fix](t3-thread://v1/thread:delegated-task:mcp%3A1)");- expect(parseThreadLinkHref(link.slice(link.indexOf("](") + 2, -1))).toBe(- "thread:delegated-task:mcp%3A1",+ it("lists the threads a message's links can name, outside code", () => {+ expect(+ threadLinkRefs(+ "<t3-thread://v2/there/t1> [a](t3-thread://v1/t%3A2) `<t3-thread://v2/code/t3>`",+ local,+ ),+ ).toEqual([ref("there", "t1"), ref("local", "t%3A2"), ref("local", "t:2")]);+ });++ it("writes a titleless autolink that opens that exact thread", () => {+ const link = formatThreadLink(ref("env-1", "thread:delegated-task:mcp%3A1"));+ expect(link).toBe("<t3-thread://v2/env-1/thread:delegated-task:mcp%3A1>");+ expect(parseThreadLinkHref(link.slice(1, -1))).toEqual(+ ref("env-1", "thread:delegated-task:mcp%3A1"),);});it("formats a label that would otherwise break the Markdown link", () => {- expect(formatThreadLink("t1", "Fix [ci] \\ build")).toBe("[Fix ci build](t3-thread://v1/t1)");- expect(formatThreadLink("t1", " ] ")).toBe("[t1](t3-thread://v1/t1)");+ expect(formatThreadLink(ref("e", "t1"), "Fix [ci] \\ build")).toBe(+ "[Fix ci build](t3-thread://v2/e/t1)",+ );+ expect(formatThreadLink(ref("e", "t1"), " ] ")).toBe("<t3-thread://v2/e/t1>");});});diff --git a/packages/shared/src/threadLinks.ts b/packages/shared/src/threadLinks.tsindex 20c64e1ec1a..a71fe4489d6 100644--- a/packages/shared/src/threadLinks.ts+++ b/packages/shared/src/threadLinks.ts@@ -1,19 +1,36 @@-import { ThreadId, type ScopedThreadRef } from "@t3tools/contracts";+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";import * as Option from "effect/Option";import * as Schema from "effect/Schema";export const THREAD_LINK_PROTOCOL = "t3-thread";-const THREAD_LINK_HREF_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;+const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;+const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;// Code comes first in the alternation so a link written inside a code span or fence is skipped.const THREAD_LINK_OUTSIDE_CODE =- /(?<fence>(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(`+)[^\n]*?\4)|\[[^\]\n]*\]\((?<href>t3-thread:\/\/v1\/[^\s)]+)\)/g;+ /(?<fence>(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(`+)[^\n]*?\4)|\[(?<label>[^\]\n]*)\]\((?<href>t3-thread:\/\/v[12]\/[^\s)]+)\)|<(?<autolink>t3-thread:\/\/v[12]\/[^\s<>]+)>/g;const decodeThreadId = Schema.decodeUnknownOption(ThreadId);+const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);-/** The id as written. Thread ids can hold percent escapes of their own, so it is not decoded. */-export function parseThreadLinkHref(href: string): ThreadId | null {- if (!href.startsWith(THREAD_LINK_HREF_PREFIX)) return null;- return Option.getOrNull(decodeThreadId(href.slice(THREAD_LINK_HREF_PREFIX.length)));+/** A v1 link names no environment; the message's own, or a unique match, stands in. */+export interface ThreadLink {+ readonly environmentId: EnvironmentId | null;+ readonly threadId: ThreadId;+}++/** The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded. */+export function parseThreadLinkHref(href: string): ThreadLink | null {+ if (href.startsWith(V1_PREFIX)) {+ const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));+ return threadId === null ? null : { environmentId: null, threadId };+ }+ if (!href.startsWith(V2_PREFIX)) return null;+ const path = href.slice(V2_PREFIX.length);+ const slash = path.indexOf("/");+ if (slash < 0) return null;+ const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash)));+ const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1)));+ return environmentId === null || threadId === null ? null : { environmentId, threadId };}export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {@@ -25,19 +42,25 @@ export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null}}-export function resolveThreadLinkRef(- source: ScopedThreadRef,+/** The threads a link can name, in its own environment or else the message's: as written, then decoded. */+export function threadLinkCandidates(+ link: ThreadLink,+ messageEnvironmentId: EnvironmentId,+): ReadonlyArray<ScopedThreadRef> {+ const environmentId = link.environmentId ?? messageEnvironmentId;+ const decodedId = percentDecodedThreadLinkId(link.threadId);+ const written = { environmentId, threadId: link.threadId };+ return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }];+}++/** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */+export function guessThreadLinkRef(+ link: ThreadLink,refs: ReadonlyArray<ScopedThreadRef>,): ScopedThreadRef | null {- const decodedId = percentDecodedThreadLinkId(source.threadId);- const ids = decodedId === null ? [source.threadId] : [source.threadId, decodedId];- for (const threadId of ids) {- const local = refs.find(- (ref) => ref.environmentId === source.environmentId && ref.threadId === threadId,- );- if (local) return local;- }- for (const threadId of ids) {+ if (link.environmentId !== null) return null;+ const decodedId = percentDecodedThreadLinkId(link.threadId);+ for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) {let match: ScopedThreadRef | null = null;for (const ref of refs) {if (ref.threadId !== threadId) continue;@@ -49,34 +72,83 @@ export function resolveThreadLinkRef(return null;}-export function formatThreadLink(threadId: string, label: string): string {+function threadLinkHref(link: ThreadLink): string {+ return link.environmentId === null+ ? `${V1_PREFIX}${link.threadId}`+ : `${V2_PREFIX}${link.environmentId}/${link.threadId}`;+}++/** Without a label, an autolink: clients show the thread's current title. */+export function formatThreadLink(ref: ThreadLink, label?: string): string {const cleaned = label- .replace(/[[\]\\\r\n]/g, " ")+ ?.replace(/[[\]\\\r\n]/g, " ").replace(/\s+/g, " ").trim();- return `[${cleaned || threadId}](${THREAD_LINK_HREF_PREFIX}${threadId})`;+ return cleaned ? `[${cleaned}](${threadLinkHref(ref)})` : `<${threadLinkHref(ref)}>`;}export function hasThreadLinks(markdown: string): boolean {- return markdown.includes(`](${THREAD_LINK_HREF_PREFIX}`);+ return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`);}+/** Every thread the markdown's links can name, so their titles are keyed reads. */+export function threadLinkRefs(+ markdown: string,+ messageEnvironmentId: EnvironmentId,+): ReadonlyArray<ScopedThreadRef> {+ const refs = new Map<string, ScopedThreadRef>();+ for (const match of markdown.matchAll(THREAD_LINK_OUTSIDE_CODE)) {+ const href = match.groups?.href ?? match.groups?.autolink;+ const link = href === undefined ? null : parseThreadLinkHref(href);+ if (link === null) continue;+ for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {+ refs.set(`${ref.environmentId}/${ref.threadId}`, ref);+ }+ }+ return [...refs.values()];+}++export function unknownThreadLinkLabel(+ link: ThreadLink,+ messageEnvironmentId: EnvironmentId,+): string {+ return link.environmentId === null || link.environmentId === messageEnvironmentId+ ? "Thread no longer available"+ : "Thread on another machine";+}++/**+ * Writes each link with its thread's current title. A link `title` cannot resolve becomes plain+ * text, its written label or a neutral one, except a labeled v1 link, which may open elsewhere.+ */export function relabelThreadLinks(markdown: string,- title: (threadId: ThreadId) => string | undefined,+ messageEnvironmentId: EnvironmentId,+ title: (ref: ScopedThreadRef) => string | undefined,): string {if (!hasThreadLinks(markdown)) return markdown;return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {- const href = (args.at(-1) as { href?: string }).href;+ const groups = args.at(-1) as { href?: string; autolink?: string; label?: string };+ const href = groups.href ?? groups.autolink;if (href === undefined) return source;const written = parseThreadLinkHref(href);if (written === null) return source;- const decoded = percentDecodedThreadLinkId(written);+ const environmentId = written.environmentId ?? messageEnvironmentId;+ const decoded = percentDecodedThreadLinkId(written.threadId);const threadId =- title(written) === undefined && decoded !== null && title(decoded) !== undefined+ title({ environmentId, threadId: written.threadId }) === undefined &&+ decoded !== null &&+ title({ environmentId, threadId: decoded }) !== undefined? decoded- : written;- const label = title(threadId)?.trim();- return label ? formatThreadLink(threadId, label) : source;+ : written.threadId;+ const current = title({ environmentId, threadId });+ if (current === undefined) {+ if (groups.href !== undefined && written.environmentId === null) return source;+ return groups.label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);+ }+ return formatThreadLink(+ { environmentId: written.environmentId, threadId },+ current.trim() || groups.label || threadId,+ );});}