diff --git a/FORK_CHANGES.md b/FORK_CHANGES.md index 9c9fc3317b840..56f533ca1d653 100644 --- a/FORK_CHANGES.md +++ b/FORK_CHANGES.md @@ -49,6 +49,7 @@ setting is missing here or a setting named here does not exist. | Model policy: the setting for which models (and efforts) agents may pick, per provider driver: off, advise or enforce, and the allowed rows. The server checks an agent's pick (`delegate_task`, `create_threads`, `t3_thread_launch`, `t3_thread_configure`, here, and both before and after it goes to linked machines): a model in no row, a call that names no model, or an effort off its row is refused in enforce, only noted in advise. A person's own pick is never refused; Settings marks one outside the rows. A bad hand edit, or a settings file that does not parse, refuses every agent pick (a warning if the value says advise). Settings offers the fork's start rows (Opus 5.5 and Fable 5.2) while none are saved. While it is on, a child whose call names its model keeps only the options it names. | Agents should use the models the person chose for each kind of work. | `server.modelPolicy` | off | [#268](https://github.com/scuttletoby/t3code/pull/268), [#731](https://github.com/scuttletoby/t3code/issues/731) | | Placement, part 1: the settings only. `placement` (off, advise or enforce; this machine's labels, an optional facts command, label groups that must never meet on one machine, and a weight per linked machine) and `placementNeeds` (labels a project's work needs). Person-only; a bad `placement` reads as off and a bad `placementNeeds` fits no machine, each kept as written. Nothing reads them yet. | Delegated work should go to a machine that has what it needs, and never where it must not run. | `server.placement`, `server.placementNeeds`, `projectOverride.placementNeeds` | off | [#134](https://github.com/scuttletoby/t3code/issues/134) | | Calm sidebar, part 1: the settings. `threadRoles` names the assistant thread and one orchestrator per project; the server refuses a role for a thread that is missing, deleted, a sub-agent, a side chat, delegated from a linked machine or in another project. `calmSidebarEnabled` is the per-device switch. Nothing shows them yet. | A short sidebar: the threads that matter on top, the rest folded. | `server.threadRoles`, `client.calmSidebarEnabled` | off | [#928](https://github.com/scuttletoby/t3code/pull/928) | +| Assistant setup: the switch `assistant.enabled` (off) offers **Make assistant** in Settings, which makes a thread in the Scratch project, names it `threadRoles.assistant` and picks for it the new built-in MCP profile `assistant` (no outside servers, no shell, file or web tools; T3 tool groups `orchestration`, `threads` and `projects`). Claude only. | One thread you talk to across projects, with only T3's tools. | `server.assistant`, `server.mcpProfiles` | off | [#953](https://github.com/scuttletoby/t3code/pull/953) | ## Repository, CI and releases diff --git a/apps/server/src/fork/mcpProfile.test.ts b/apps/server/src/fork/mcpProfile.test.ts index b6c41f96d0252..e58478666b804 100644 --- a/apps/server/src/fork/mcpProfile.test.ts +++ b/apps/server/src/fork/mcpProfile.test.ts @@ -79,7 +79,7 @@ describe("MCP profile resolver: old and empty state", () => { }); }); - it.each(["all", "t3-only"])( + it.each(["all", "t3-only", "assistant"])( "refuses %s when a hand edit put a profile of that name in the file", (name) => { const file = { @@ -662,6 +662,19 @@ describe('builtinTools "none" (assistant)', () => { ); }); + it("the built-in assistant: no servers or built-in tools, three groups; a child keeps it", () => { + const picked = fromFile({ mcpThreadProfiles: { a1: "assistant" } }); + const own = resolved(resolveMcpProfile(picked, [top("a1")])); + expect([own.name, own.source]).toEqual(["assistant", "thread-pick"]); + expect(own.profile).toEqual({ + servers: [], + t3Tools: ["orchestration", "threads", "projects"], + builtinTools: "none", + }); + const sub = resolved(resolveMcpProfile(picked, [child("c1"), top("a1")])); + expect(sub.profile).toEqual(own.profile); + }); + it.each([["some"], [false], [["Bash"]]])("refuses, never widens, builtinTools %j", (value) => { const broken = fromFile({ mcpProfiles: { odd: { servers: "all", t3Tools: "all", builtinTools: value } }, @@ -674,3 +687,60 @@ describe('builtinTools "none" (assistant)', () => { ); }); }); + +describe("the assistant thread is never wider than the assistant profile (#953)", () => { + const ASSISTANT_SET = { + servers: [], + t3Tools: ["orchestration", "threads", "projects"], + builtinTools: "none", + }; + const roles = { assistant: "a1", orchestrators: {} }; + + it("a managed policy that drops its pick: the defaults' all is cut down to assistant", () => { + // The policy owns mcpThreadProfiles as a whole and leaves the assistant's pick out. + const dropped = fromFile({ + mcpProfiles: PROFILES, + threadRoles: roles, + mcpThreadProfiles: { other: "docs" }, + }); + const own = resolved(resolveMcpProfile(dropped, [top("a1")])); + expect([own.name, own.source]).toEqual(["assistant", "assistant-role"]); + expect(own.profile).toEqual(ASSISTANT_SET); + // A project default and a wider pick are cut too; a child gets no more than its parent. + const project = resolved(resolveMcpProfile(dropped, [top("a1", { mcpProfile: "docs" })])); + expect(project.profile).toEqual(ASSISTANT_SET); + const wide = fromFile({ threadRoles: roles, mcpThreadProfiles: { a1: "all" } }); + expect(resolved(resolveMcpProfile(wide, [top("a1")])).profile).toEqual(ASSISTANT_SET); + expect(resolved(resolveMcpProfile(dropped, [child("c1"), top("a1")])).profile).toEqual( + ASSISTANT_SET, + ); + }); + + it("its own pick stands when it is within assistant; other threads are not touched", () => { + const settings = fromFile({ + mcpProfiles: { tiny: { servers: [], t3Tools: ["threads"], builtinTools: "none" } }, + threadRoles: roles, + mcpThreadProfiles: { a1: "tiny" }, + }); + const own = resolved(resolveMcpProfile(settings, [top("a1")])); + expect([own.name, own.source]).toEqual(["tiny", "thread-pick"]); + const picked = fromFile({ threadRoles: roles, mcpThreadProfiles: { a1: "assistant" } }); + expect(resolved(resolveMcpProfile(picked, [top("a1")])).source).toBe("thread-pick"); + const other = resolved(resolveMcpProfile(settings, [top("t2")])); + expect([other.name, isEveryMcpTool(other.profile)]).toEqual(["all", true]); + // No role: the thread that held the pick gets what any thread gets. + expect(isEveryMcpTool(resolved(resolveMcpProfile(fromFile({}), [top("a1")])).profile)).toBe( + true, + ); + }); + + it("refuses, never widens, when the built-in assistant cannot be read or the pick is broken", () => { + const shadowed = fromFile({ + mcpProfiles: { assistant: { servers: "all", t3Tools: "all" } }, + threadRoles: roles, + }); + expect(refused(resolveMcpProfile(shadowed, [top("a1")])).profileName).toBe("assistant"); + const missing = fromFile({ threadRoles: roles, mcpThreadProfiles: { a1: "gone" } }); + expect(refused(resolveMcpProfile(missing, [top("a1")])).problem).toBe("missing"); + }); +}); diff --git a/apps/server/src/fork/mcpProfileSettingsText.test.ts b/apps/server/src/fork/mcpProfileSettingsText.test.ts index 824f92b685622..0c02d6a415d68 100644 --- a/apps/server/src/fork/mcpProfileSettingsText.test.ts +++ b/apps/server/src/fork/mcpProfileSettingsText.test.ts @@ -243,3 +243,18 @@ describe("mcpProfileFileKeysOf (#681)", () => { ); }); }); + +describe("the assistant pointer counts as an MCP profile key (#953)", () => { + it("a file that does not decode still gives threadRoles.assistant, laid over a broken load", () => { + // `"theme": 5` makes the full decode fail; the text reader still gives the profile keys. + const keys = keysOf( + JSON.stringify({ theme: 5, threadRoles: { assistant: "thread:a", orchestrators: 3 } }), + ); + expect(keys.threadRoles).toEqual({ assistant: "thread:a", orchestrators: {} }); + const laid = withMcpProfileFileKeys(DEFAULT_SERVER_SETTINGS, keys); + expect(laid.threadRoles.assistant).toBe("thread:a"); + // A decoded file gives the same, so the keys last read keep it too. + const decoded = { ...DEFAULT_SERVER_SETTINGS, threadRoles: keys.threadRoles } as ServerSettings; + expect(mcpProfileFileKeysOf(decoded).threadRoles.assistant).toBe("thread:a"); + }); +}); diff --git a/apps/server/src/fork/mcpProfileSettingsText.ts b/apps/server/src/fork/mcpProfileSettingsText.ts index a38c1e383f2f5..101bd09278b49 100644 --- a/apps/server/src/fork/mcpProfileSettingsText.ts +++ b/apps/server/src/fork/mcpProfileSettingsText.ts @@ -14,10 +14,13 @@ import * as Schema from "effect/Schema"; import { parseSettingsFileText } from "../serverSettings.ts"; -/** The settings keys MCP profiles read from the file, besides `mcpCarriedProfiles`. */ +/** + * The settings keys MCP profiles read from the file, besides `mcpCarriedProfiles`. `threadRoles` + * too: the assistant thread is held within the `assistant` profile, so its pointer counts. + */ export type McpProfileFileKeys = Pick< ServerSettings, - "mcpProfiles" | "mcpProfile" | "mcpSubagentProfile" | "mcpThreadProfiles" + "mcpProfiles" | "mcpProfile" | "mcpSubagentProfile" | "mcpThreadProfiles" | "threadRoles" > & { /** Each project's two MCP profile keys, as written; a project left out has none. */ readonly projectSettingsOverrides: Readonly< @@ -49,6 +52,7 @@ const ServerKeys = Schema.Struct({ mcpProfile: ForkServerSettingsFields.mcpProfile, mcpSubagentProfile: ForkServerSettingsFields.mcpSubagentProfile, mcpThreadProfiles: ForkServerSettingsFields.mcpThreadProfiles, + threadRoles: ForkServerSettingsFields.threadRoles, }); const ProjectKeys = Schema.Struct({ mcpProfile: ForkProjectOverrideFields.mcpProfile, @@ -184,6 +188,7 @@ export function mcpProfileFileKeysOf(settings: ServerSettings): McpProfileFileKe mcpProfile: settings.mcpProfile, mcpSubagentProfile: settings.mcpSubagentProfile, mcpThreadProfiles: settings.mcpThreadProfiles, + threadRoles: settings.threadRoles, projectSettingsOverrides, }; } @@ -211,6 +216,7 @@ export function withMcpProfileFileKeys( mcpProfile: keys.mcpProfile, mcpSubagentProfile: keys.mcpSubagentProfile, mcpThreadProfiles: keys.mcpThreadProfiles, + threadRoles: keys.threadRoles, projectSettingsOverrides: projectSettingsOverrides as ServerSettings["projectSettingsOverrides"], }; diff --git a/apps/server/src/golive/forkReport.test.ts b/apps/server/src/golive/forkReport.test.ts index fbbeaddc8823e..d272407509d99 100644 --- a/apps/server/src/golive/forkReport.test.ts +++ b/apps/server/src/golive/forkReport.test.ts @@ -1142,6 +1142,7 @@ describe("__fork-report settings", () => { placementNeeds: "placement: settings only so far; nothing reads them yet (later placement rows)", threadRoles: "calm sidebar: settings only so far; nothing reads them yet", + assistant: "only offers Make assistant; the assistant is the threadRoles.assistant thread", }; it("counts every fork setting as a feature or names why it is not a switch", () => { diff --git a/apps/server/src/policy/forkManagedSettings.ts b/apps/server/src/policy/forkManagedSettings.ts index fd2202bcd2904..c4fab57507451 100644 --- a/apps/server/src/policy/forkManagedSettings.ts +++ b/apps/server/src/policy/forkManagedSettings.ts @@ -6,6 +6,7 @@ import type { ForkServerSettingKey } from "@t3tools/contracts"; const WHOLE_ONLY = [ + "assistant", "handoff", "mcpCarriedProfiles", "mcpProfile", diff --git a/apps/web/src/components/fork/mcpProfile/threadMcpProfile.logic.test.ts b/apps/web/src/components/fork/mcpProfile/threadMcpProfile.logic.test.ts index c114dca13b55d..5b3d547c99376 100644 --- a/apps/web/src/components/fork/mcpProfile/threadMcpProfile.logic.test.ts +++ b/apps/web/src/components/fork/mcpProfile/threadMcpProfile.logic.test.ts @@ -119,6 +119,8 @@ describe("the thread menu's MCP profile entry", () => { expect(item!.children!.map((child) => [child.id, child.checked ?? false])).toEqual([ ["mcp-profile:pick:all", false], ["mcp-profile:pick:t3-only", false], + // The built-in `assistant` is a choice for every thread: it only narrows and gives no role. + ["mcp-profile:pick:assistant", false], ["mcp-profile:pick:docs", false], ["mcp-profile:pick:narrow", true], ["mcp-profile:clear", false], diff --git a/apps/web/src/components/settings/fork/AssistantSettings.tsx b/apps/web/src/components/settings/fork/AssistantSettings.tsx new file mode 100644 index 0000000000000..be1cd71251524 --- /dev/null +++ b/apps/web/src/components/settings/fork/AssistantSettings.tsx @@ -0,0 +1,182 @@ +/** + * Fork (assistant): the switch `assistant.enabled` and "Make assistant", which makes a thread in the + * Scratch project and names it the assistant (`threadRoles.assistant`) with the built-in profile + * `assistant`. Server-wide, so a project screen does not show it. Every write is an ordinary settings + * save from the person at the screen; agents cannot change these keys. Docs: docs/fork/assistant.md. + */ +/* oxlint-disable t3code/no-untranslated-copy -- Fork: this panel is the fork's own and its text is English only; upstream's translation catalogs hold no fork keys. */ +import { + DEFAULT_PROVIDER_INTERACTION_MODE, + DEFAULT_RUNTIME_MODE, + type EnvironmentId, + type ScopedThreadRef, + type ServerSettingsPatch, +} from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { useNavigate } from "@tanstack/react-router"; +import { useRef, useState } from "react"; + +import { newThreadId } from "~/lib/utils"; +import { useScratchProject } from "../../../hooks/useScratchProject"; +import { appAtomRegistry } from "../../../rpc/atomRegistry"; +import { useThreadShells, waitForThreadShell } from "../../../state/entities"; +import { useEnvironmentProviders } from "../../../state/environments"; +import { environmentThreadShells, threadEnvironment } from "../../../state/threads"; +import { useAtomCommand } from "../../../state/use-atom-command"; +import { waitForAtomValue } from "../../../state/waitForAtomValue"; +import { buildThreadRouteParams } from "../../../threadRoutes"; +import { Button } from "../../ui/button"; +import { Switch } from "../../ui/switch"; +import { useSettingsScope } from "../SettingsScopeContext"; +import { SettingsSection } from "../settingsLayout"; +import { useSearchableSetting } from "../settingsSearch"; +import { useUpdateScopedSettings } from "../useScopedSettings"; +import { ForkRow } from "./ForkRow"; +import { + assistantModelSelection, + assistantThreadState, + assistantThreadText, + makeAssistantThread, +} from "./assistantSetup.logic"; + +/** True once this client holds no thread `ref` (deleted, or never made); false after 5 seconds. */ +const waitForThreadShellGone = (ref: ScopedThreadRef) => + waitForAtomValue({ + registry: appAtomRegistry, + atom: environmentThreadShells.threadShellAtom(ref), + predicate: (thread) => thread === null, + timeoutMs: 5_000, + }); + +export function AssistantSettings() { + const searchableSetting = useSearchableSetting(); + const updateSettings = useUpdateScopedSettings(); + const { targets } = useSettingsScope(); + const { openScratchProject } = useScratchProject(); + const createThread = useAtomCommand(threadEnvironment.create, { reportFailure: false }); + const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false }); + const providers = useEnvironmentProviders(); + const shells = useThreadShells(); + const navigate = useNavigate(); + const [busy, setBusy] = useState(false); + const running = useRef(false); + const [error, setError] = useState(null); + + const target = targets.length === 1 ? targets[0]! : null; + if (target === null) { + return ( + + + + ); + } + const environmentId: EnvironmentId = target.environmentId; + const enabled = target.settings.assistant.enabled; + const state = assistantThreadState( + target.settings.threadRoles.assistant, + shells.filter((thread) => thread.environmentId === environmentId), + ); + const modelSelection = assistantModelSelection(providers.get(environmentId) ?? []); + + // Resolves once the save settled: true when every target saved it. + const save = (patch: ServerSettingsPatch) => + new Promise((resolve) => + updateSettings(patch, { onFailed: () => resolve(false), onSaved: () => resolve(true) }), + ); + + const makeAssistant = () => { + // A ref, not only the state: a double click arrives before the disabled button re-renders. + if (modelSelection === null || running.current) return; + running.current = true; + setBusy(true); + setError(null); + // `makeAssistantThread` never rejects; `.finally` still leaves the busy state on any path. + void makeAssistantThread({ + openScratchProject: async () => (await openScratchProject(environmentId))?.id ?? null, + newThreadId, + save, + createThread: async (threadId, projectId) => + ( + await createThread({ + environmentId, + input: { + threadId, + projectId, + title: "Assistant", + modelSelection, + runtimeMode: DEFAULT_RUNTIME_MODE, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + }, + }) + )._tag !== "Failure", + waitForThread: (threadId) => waitForThreadShell(scopeThreadRef(environmentId, threadId)), + discardThread: async (threadId) => + (await deleteThread({ environmentId, input: { threadId, onlyIfUnused: true } }))._tag !== + "Failure" && (await waitForThreadShellGone(scopeThreadRef(environmentId, threadId))), + }) + .then((outcome) => { + if (outcome._tag === "Stopped") { + setError(outcome.error); + return; + } + const ref = scopeThreadRef(environmentId, outcome.threadId); + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }); + }) + .finally(() => { + running.current = false; + setBusy(false); + }); + }; + + return ( + + + updateSettings({ assistant: { enabled: Boolean(checked) } }) + } + aria-label="Offer Make assistant" + /> + } + /> + {enabled ? ( + makeAssistant()} + > + Make assistant + + } + /> + ) : null} + + ); +} diff --git a/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx b/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx index 5699f051206cf..b87255f52caf6 100644 --- a/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx +++ b/apps/web/src/components/settings/fork/ForkSettingsPanel.tsx @@ -11,6 +11,7 @@ import { useSettingsScope } from "../SettingsScopeContext"; import { SettingsPageContainer, SettingsRow, SettingsSection } from "../settingsLayout"; import { useSearchableSetting } from "../settingsSearch"; import { WaitsAndSlotsSettings } from "../WaitsAndSlotsSettings"; +import { AssistantSettings } from "./AssistantSettings"; import { forkFeatureStatuses } from "./forkStatus.logic"; import { HandoffSettings } from "./HandoffSettings"; import { McpProfileSettings } from "./McpProfileSettings"; @@ -49,6 +50,7 @@ export function ForkSettingsPanel() { + {isProjectScope ? null : } ); } diff --git a/apps/web/src/components/settings/fork/McpProfileSettings.tsx b/apps/web/src/components/settings/fork/McpProfileSettings.tsx index 0c1cc97512786..bb70b4fffd13f 100644 --- a/apps/web/src/components/settings/fork/McpProfileSettings.tsx +++ b/apps/web/src/components/settings/fork/McpProfileSettings.tsx @@ -274,6 +274,8 @@ export function McpProfileSettings({ isProjectScope }: { readonly isProjectScope const projectSettingsOverrides = useScopedSettings( (settings) => settings.projectSettingsOverrides, ); + // The assistant thread never runs wider than `assistant`, so a pick's effect depends on it too. + const threadRoles = useScopedSettings((settings) => settings.threadRoles); const threadShells = useThreadShells(); const projects = useProjects(); const { environment } = useSettingsScope(); @@ -373,7 +375,7 @@ export function McpProfileSettings({ isProjectScope }: { readonly isProjectScope const pickRows = mcpThreadPickRows(mcpThreadProfiles, labels.threads); // The threads of the environment these settings are for: a pick's effect depends on its parent. const shells = threadShells.filter((shell) => shell.environmentId === environment?.environmentId); - const threadSettings = { ...settings, mcpCarriedProfiles, projectSettingsOverrides }; + const threadSettings = { ...settings, mcpCarriedProfiles, projectSettingsOverrides, threadRoles }; const pickEffect = (threadId: string, name: string) => threadPickEffect(threadSettings, threadId, name, shells); const draftEffect = diff --git a/apps/web/src/components/settings/fork/assistantSetup.logic.test.ts b/apps/web/src/components/settings/fork/assistantSetup.logic.test.ts new file mode 100644 index 0000000000000..581dd5c81d2d7 --- /dev/null +++ b/apps/web/src/components/settings/fork/assistantSetup.logic.test.ts @@ -0,0 +1,207 @@ +import { + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ServerSettings, + ThreadId, + resolveMcpProfile, + type ServerProvider, +} from "@t3tools/contracts"; +import { forkSettingsWriteProblem } from "@t3tools/shared/forkSettingsPatch"; +import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { + type MakeAssistantSteps, + assistantModelSelection, + assistantPickRemovalPatch, + assistantProfilePatch, + assistantRolePatch, + assistantThreadState, + makeAssistantThread, +} from "./assistantSetup.logic"; + +const provider = ( + instanceId: string, + driver: string, + models: ReadonlyArray<{ slug: string; isDefault?: boolean }>, + extra: Partial = {}, +): ServerProvider => + ({ + instanceId: ProviderInstanceId.make(instanceId), + driver: ProviderDriverKind.make(driver), + enabled: true, + availability: "available", + models: models.map((model) => ({ ...model, name: model.slug, isCustom: false })), + ...extra, + }) as unknown as ServerProvider; + +describe("Make assistant", () => { + it("picks an on, available Claude instance (the default first) and Claude's default model", () => { + const providers = [ + provider("codex", "codex", [{ slug: "gpt" }]), + provider("claudeWork", "claudeAgent", [{ slug: "claude-x", isDefault: true }]), + provider("claudeAgent", "claudeAgent", [{ slug: "claude-x" }, { slug: "claude-opus-5-5" }]), + ]; + expect(assistantModelSelection(providers)).toEqual({ + instanceId: "claudeAgent", + model: "claude-opus-5-5", + }); + expect(assistantModelSelection(providers.slice(0, 2))).toEqual({ + instanceId: "claudeWork", + model: "claude-x", + }); + }); + + it("offers nothing without a usable Claude: no other provider can drop built-in tools", () => { + expect(assistantModelSelection([provider("codex", "codex", [{ slug: "gpt" }])])).toBeNull(); + const off = provider("claudeAgent", "claudeAgent", [{ slug: "c" }], { enabled: false }); + const gone = provider("claudeAgent", "claudeAgent", [{ slug: "c" }], { + availability: "unavailable", + } as Partial); + expect(assistantModelSelection([off, gone])).toBeNull(); + }); + + it("picks the profile first, before the thread exists, then names the assistant", () => { + const decode = Schema.decodeUnknownSync(ServerSettings); + const before = decode({ mcpThreadProfiles: { old: "t3-only" } }); + const thread = ThreadId.make("thread-new"); + // Saved before the thread is made: if setup stops here, no wide "Assistant" thread exists. + const picked = applyServerSettingsPatch(before, assistantProfilePatch(thread)); + expect(forkSettingsWriteProblem(before, picked)).toBeUndefined(); + expect(picked.threadRoles.assistant).toBeNull(); + const resolved = resolveMcpProfile(picked, [{ threadId: thread, delegated: false }]); + expect(resolved._tag === "Resolved" && resolved.profile.builtinTools).toBe("none"); + const named = applyServerSettingsPatch(picked, assistantRolePatch(thread)); + expect(forkSettingsWriteProblem(picked, named)).toBeUndefined(); + expect(named.threadRoles.assistant).toBe("thread-new"); + expect(named.mcpThreadProfiles).toEqual({ old: "t3-only", "thread-new": "assistant" }); + }); + + it("shows an assistant thread that is not active (archived or deleted) as none", () => { + const active = [{ id: "a", title: "Assistant" }]; + expect(assistantThreadState(null, active)).toEqual({ kind: "none" }); + expect(assistantThreadState("a", active)).toMatchObject({ kind: "ok", title: "Assistant" }); + expect(assistantThreadState("b", active)).toEqual({ kind: "inactive", threadId: "b" }); + }); +}); + +const decodeServerSettings = Schema.decodeSync(ServerSettings); + +describe("Make assistant's run (#953)", () => { + const NEW = ThreadId.make("thread-new"); + + /** Steps that log what they did; `overrides` make one fail, refuse or throw. */ + const stepsWith = (overrides: Partial = {}) => { + const log: Array = []; + const steps: MakeAssistantSteps = { + openScratchProject: async () => ProjectId.make("scratch"), + newThreadId: () => NEW, + save: async (patch) => { + log.push(`save ${JSON.stringify(patch)}`); + return true; + }, + createThread: async () => { + log.push("create"); + return true; + }, + waitForThread: async () => true, + discardThread: async () => { + log.push("discard"); + return true; + }, + ...overrides, + }; + return { steps, log }; + }; + const pick = `save ${JSON.stringify(assistantProfilePatch(NEW))}`; + const role = `save ${JSON.stringify(assistantRolePatch(NEW))}`; + const removal = `save ${JSON.stringify(assistantPickRemovalPatch(NEW))}`; + + it("saves the pick, makes the thread, then the role, and cleans up nothing", async () => { + const { steps, log } = stepsWith(); + expect(await makeAssistantThread(steps)).toEqual({ _tag: "Made", threadId: NEW }); + expect(log).toEqual([pick, "create", role]); + }); + + it("always ends with an outcome when a step throws or rejects, so the button leaves busy", async () => { + const throwing: ReadonlyArray> = [ + { openScratchProject: () => Promise.reject(new Error("scratch")) }, + { + save: () => { + throw new Error("save threw"); + }, + }, + { createThread: () => Promise.reject(new Error("rpc")) }, + { waitForThread: () => Promise.reject(new Error("wait")) }, + ]; + for (const overrides of throwing) { + const outcome = await makeAssistantThread(stepsWith(overrides).steps); + expect(outcome._tag).toBe("Stopped"); + expect(outcome._tag === "Stopped" ? outcome.error : null).toContain("Try again"); + } + }); + + it("a refused role removes the empty thread, then its pick, so retries leave no picks", async () => { + let first = true; + const { steps, log } = stepsWith({ + save: async (patch) => { + log.push(`save ${JSON.stringify(patch)}`); + if (patch.threadRoles === undefined) return true; + return (first = false); + }, + }); + const outcome = await makeAssistantThread(steps); + expect(outcome._tag).toBe("Stopped"); + expect(first).toBe(false); + expect(log).toEqual([pick, "create", role, "discard", removal]); + }); + + it("each stop after the pick cleans up; a refused pick has nothing to clean up", async () => { + const notMade = stepsWith({ createThread: async () => false }); + await makeAssistantThread(notMade.steps); + expect(notMade.log).toEqual([pick, "discard", removal]); + const notSeen = stepsWith({ waitForThread: async () => false }); + await makeAssistantThread(notSeen.steps); + expect(notSeen.log).toEqual([pick, "create", "discard", removal]); + const threw = stepsWith({ waitForThread: () => Promise.reject(new Error("wait")) }); + await makeAssistantThread(threw.steps); + expect(threw.log).toEqual([pick, "create", "discard", removal]); + const refused = stepsWith(); + refused.steps = { + ...refused.steps, + save: async (patch) => { + refused.log.push(`save ${JSON.stringify(patch)}`); + return false; + }, + }; + await makeAssistantThread(refused.steps); + expect(refused.log).toEqual([pick]); + }); + + it("a thread that stays (someone wrote in it, or the delete failed) keeps its narrow pick", async () => { + const kept = stepsWith({ + waitForThread: async () => false, + discardThread: async () => false, + }); + await makeAssistantThread(kept.steps); + expect(kept.log).toEqual([pick, "create"]); + // A clean-up that throws leaves the pick and still ends with the outcome. + const broken = stepsWith({ + waitForThread: async () => false, + discardThread: () => Promise.reject(new Error("delete")), + }); + expect((await makeAssistantThread(broken.steps))._tag).toBe("Stopped"); + expect(broken.log).toEqual([pick, "create"]); + }); + + it("the removal clears only this thread's pick", () => { + const settings = decodeServerSettings({ + mcpThreadProfiles: { [NEW]: "assistant", other: "assistant" }, + }); + expect( + applyServerSettingsPatch(settings, assistantPickRemovalPatch(NEW)).mcpThreadProfiles, + ).toEqual({ other: "assistant" }); + }); +}); diff --git a/apps/web/src/components/settings/fork/assistantSetup.logic.ts b/apps/web/src/components/settings/fork/assistantSetup.logic.ts new file mode 100644 index 0000000000000..7344e89811426 --- /dev/null +++ b/apps/web/src/components/settings/fork/assistantSetup.logic.ts @@ -0,0 +1,181 @@ +/** + * Fork (assistant): the pure parts of "Make assistant". The thread is made in the Scratch project and + * named the assistant by one settings save from the person at the screen; the server's role check + * (apps/server/src/fork/threadRoleTargets.ts) refuses a thread that cannot hold the role. + */ +/* oxlint-disable t3code/no-untranslated-copy -- Fork: the fork's own settings are English only; upstream's translation catalogs hold no fork keys. */ +import { + DEFAULT_MODEL_BY_PROVIDER, + MCP_PROFILE_ASSISTANT, + ProviderDriverKind, + type ModelSelection, + type ProjectId, + type ServerProvider, + type ServerSettingsPatch, + type ThreadId, +} from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; + +const CLAUDE = ProviderDriverKind.make("claudeAgent"); + +/** + * The assistant's model: a Claude instance that is on and available (the default one first), with + * Claude's default model when it offers it. Null when there is none: the assistant's profile has no + * built-in tools, which only Claude can apply, so any other provider would refuse its turns. + */ +export function assistantModelSelection( + providers: ReadonlyArray, + defaultInstanceId: string = CLAUDE, +): ModelSelection | null { + const usable = providers.filter( + (provider) => + provider.driver === CLAUDE && provider.enabled && provider.availability !== "unavailable", + ); + const pick = usable.find((provider) => provider.instanceId === defaultInstanceId) ?? usable[0]; + if (pick === undefined) return null; + const wanted = DEFAULT_MODEL_BY_PROVIDER[CLAUDE]; + const model = + pick.models.find((entry) => entry.slug === wanted) ?? + pick.models.find((entry) => entry.isDefault === true) ?? + pick.models[0]; + return model === undefined ? null : createModelSelection(pick.instanceId, model.slug); +} + +/** + * The first save: the thread's profile pick, made before the thread exists, so a thread named + * "Assistant" never runs with a wider profile, even when the setup stops half-way. + */ +export const assistantProfilePatch = (threadId: ThreadId): ServerSettingsPatch => ({ + mcpThreadProfiles: { [threadId]: MCP_PROFILE_ASSISTANT }, +}); + +/** The second save, once the thread exists: the role pointer (the server's role check decides). */ +export const assistantRolePatch = (threadId: ThreadId): ServerSettingsPatch => ({ + threadRoles: { assistant: threadId }, +}); + +/** + * The thread `threadRoles.assistant` names, as Settings shows it. The client's thread list holds + * active threads only, so an archived one reads as not active, like a deleted one. + */ +export type AssistantThreadState = + | { readonly kind: "none" } + | { readonly kind: "inactive"; readonly threadId: string } + | { readonly kind: "ok"; readonly threadId: string; readonly title: string }; + +/** Readers treat a deleted or archived assistant thread as no assistant (threadRoles docs). */ +export function assistantThreadState( + assistant: string | null, + activeThreads: ReadonlyArray<{ readonly id: string; readonly title: string }>, +): AssistantThreadState { + if (assistant === null) return { kind: "none" }; + const thread = activeThreads.find((candidate) => candidate.id === assistant); + return thread === undefined + ? { kind: "inactive", threadId: assistant } + : { kind: "ok", threadId: assistant, title: thread.title }; +} + +export function assistantThreadText(state: AssistantThreadState): string { + switch (state.kind) { + case "none": + return "No thread is the assistant yet."; + case "inactive": + return `The assistant was thread ${state.threadId}, which is archived, deleted or not on this server, so there is none. Unarchive it or make a new one.`; + case "ok": + return `The assistant is "${state.title}".`; + } +} + +/** Removes the first save's pick, once its thread is gone (or was never made). */ +export const assistantPickRemovalPatch = (threadId: ThreadId): ServerSettingsPatch => ({ + mcpThreadProfiles: { [threadId]: null }, +}); + +/** The steps "Make assistant" takes; the Settings row passes the app's own. */ +export interface MakeAssistantSteps { + /** The Scratch project's id, or null when there is none (the hook has said why). */ + readonly openScratchProject: () => Promise; + readonly newThreadId: () => ThreadId; + /** One settings save from the person at the screen: true when it saved. */ + readonly save: (patch: ServerSettingsPatch) => Promise; + /** Makes the thread "Assistant" in the project: true when the server took the command. */ + readonly createThread: (threadId: ThreadId, projectId: ProjectId) => Promise; + /** True once the new thread has reached this client. */ + readonly waitForThread: (threadId: ThreadId) => Promise; + /** + * Deletes the thread only if it has no message or run yet (`onlyIfUnused`): true only when the + * delete was taken and this client then sees no such thread. A thread someone wrote in stays. + */ + readonly discardThread: (threadId: ThreadId) => Promise; +} + +export type MakeAssistantOutcome = + | { readonly _tag: "Made"; readonly threadId: ThreadId } + /** Nothing named: `error` says why (null when the Scratch hook already said it). */ + | { readonly _tag: "Stopped"; readonly error: string | null }; + +const stopped = (error: string | null): MakeAssistantOutcome => ({ _tag: "Stopped", error }); + +/** + * A run that stopped after the pick: the empty thread is deleted, and only once it is gone is its + * pick removed, so retries leave no picks behind. A thread that stays (someone wrote in it, or the + * delete was not taken) keeps its narrow pick: removing it would give the thread the defaults. + */ +async function discardUnused(steps: MakeAssistantSteps, threadId: ThreadId): Promise { + try { + if (await steps.discardThread(threadId)) await steps.save(assistantPickRemovalPatch(threadId)); + } catch { + // The pick stays, which is harmless: a pick for a thread that does not exist does nothing. + } +} + +/** The run's steps in order; `run.picked` is set once a pick may have been saved. */ +async function makeAssistantSteps( + steps: MakeAssistantSteps, + run: { picked: ThreadId | null }, +): Promise { + const projectId = await steps.openScratchProject(); + if (projectId === null) return stopped(null); + const threadId = steps.newThreadId(); + // A save that throws may still have saved the pick, so the clean-up counts from here on. + run.picked = threadId; + if (!(await steps.save(assistantProfilePatch(threadId)))) { + // Refused: no pick was saved, so there is nothing to clean up. + run.picked = null; + return stopped("The server refused the assistant profile. Nothing was made."); + } + if (!(await steps.createThread(threadId, projectId))) { + return stopped("Could not make the assistant's thread. Try again."); + } + if (!(await steps.waitForThread(threadId))) { + return stopped("The assistant's thread was made, but it did not reach this client. Try again."); + } + if (!(await steps.save(assistantRolePatch(threadId)))) { + return stopped( + "The server refused to name the new thread the assistant. It is removed unless someone already wrote in it.", + ); + } + return { _tag: "Made", threadId }; +} + +/** + * "Make assistant": the pick first (a stop at any later point leaves no thread, or one already + * narrowed), then the thread, then the role. A run that stops after the pick cleans up + * ({@link discardUnused}). Never rejects: a step that throws stops the run with an error, so the + * caller always gets an outcome and leaves its busy state. + */ +export async function makeAssistantThread( + steps: MakeAssistantSteps, +): Promise { + const run: { picked: ThreadId | null } = { picked: null }; + let outcome: MakeAssistantOutcome; + try { + outcome = await makeAssistantSteps(steps, run); + } catch { + outcome = stopped( + "Something went wrong while making the assistant. Nothing was named. Try again.", + ); + } + if (outcome._tag === "Stopped" && run.picked !== null) await discardUnused(steps, run.picked); + return outcome; +} diff --git a/apps/web/src/components/settings/fork/mcpProfileSettings.logic.test.ts b/apps/web/src/components/settings/fork/mcpProfileSettings.logic.test.ts index d070433cc7fdb..991e9aecd776a 100644 --- a/apps/web/src/components/settings/fork/mcpProfileSettings.logic.test.ts +++ b/apps/web/src/components/settings/fork/mcpProfileSettings.logic.test.ts @@ -35,14 +35,15 @@ function serverSave(settings: ServerSettings, patch: unknown): ServerSettings { const LEAN = { servers: ["docs"], t3Tools: ["threads", "orchestration"] }; describe("MCP profile list", () => { - it("shows all and t3-only read-only from an old settings file, and nothing else", () => { + it("shows the built-ins read-only from an old settings file, and nothing else", () => { const old = fromFile({}); const rows = mcpProfileRows(old, null); expect(rows.map((row) => [row.name, row.kind, row.state])).toEqual([ ["all", "built-in", "ok"], ["t3-only", "built-in", "ok"], + ["assistant", "built-in", "ok"], ]); - expect(mcpProfileChoices(old)).toEqual(["all", "t3-only"]); + expect(mcpProfileChoices(old)).toEqual(["all", "t3-only", "assistant"]); // The default and the rule show as their defaults; nothing to write. expect(shownProfileRef(old.mcpProfile, "all")).toBe("all"); expect(shownProfileRef(old.mcpSubagentProfile, "inherit")).toBe("inherit"); @@ -144,7 +145,7 @@ describe("saving and deleting a profile", () => { it("refuses built-in names, inherit, bad names and a name taken", () => { const settings = fromFile({ mcpProfiles: { lean: LEAN } }); const draft = { servers: [] as string[], t3Tools: "all" as const }; - for (const name of ["all", "t3-only"]) { + for (const name of ["all", "t3-only", "assistant"]) { expect(saveMcpProfilePatch(settings, null, { ...draft, name })).toEqual({ problem: `"${name}" is a built-in profile; pick another name.`, }); diff --git a/apps/web/src/components/settings/fork/mcpProfileSettings.logic.ts b/apps/web/src/components/settings/fork/mcpProfileSettings.logic.ts index 8926de4803abe..ead14b4c931f6 100644 --- a/apps/web/src/components/settings/fork/mcpProfileSettings.logic.ts +++ b/apps/web/src/components/settings/fork/mcpProfileSettings.logic.ts @@ -6,8 +6,7 @@ /* oxlint-disable t3code/no-untranslated-copy -- Fork: the fork's own settings are English only; upstream's translation catalogs hold no fork keys. */ import { MCP_BUILTIN_TOOLS_NONE, - MCP_PROFILE_ALL, - MCP_PROFILE_T3_ONLY, + MCP_BUILT_IN_PROFILES, MCP_SUBAGENT_INHERIT, MCP_T3_TOOL_GROUPS, MCP_T3_UNGROUPED_TOOLS, @@ -66,11 +65,6 @@ export type McpProfileRow = readonly removable: boolean; }; -const BUILT_IN_SETS: ReadonlyArray = [ - [MCP_PROFILE_ALL, { servers: "all", t3Tools: "all" }], - [MCP_PROFILE_T3_ONLY, { servers: [], t3Tools: "all" }], -]; - const entriesOf = (profiles: unknown): ReadonlyArray => typeof profiles === "object" && profiles !== null && !Array.isArray(profiles) ? Object.entries(profiles) @@ -97,7 +91,7 @@ export function mcpProfileRows( knownServers: ReadonlyArray | null, ): ReadonlyArray { const entries = entriesOf(settings.mcpProfiles); - const builtIns = BUILT_IN_SETS.map(([name, profile]): McpProfileRow => { + const builtIns = Object.entries(MCP_BUILT_IN_PROFILES).map(([name, profile]): McpProfileRow => { // A save never writes one: a hand edit, and the resolver refuses the built-in while it stays. if (entries.some(([entryName]) => entryName === name)) { return { @@ -396,6 +390,7 @@ const SOURCE_TEXT = { "subagent-rule": "the sub-agent rule", project: "the project's default", environment: "the default profile", + "assistant-role": "the assistant thread's limit", } as const; /** One line on what a thread gets, from the resolver's result. */ diff --git a/apps/web/src/components/settings/forkSettingsSearchItems.ts b/apps/web/src/components/settings/forkSettingsSearchItems.ts index c26248bdf259c..7fda6e457ff90 100644 --- a/apps/web/src/components/settings/forkSettingsSearchItems.ts +++ b/apps/web/src/components/settings/forkSettingsSearchItems.ts @@ -249,4 +249,20 @@ export const FORK_SETTINGS_SEARCH_ITEMS = [ environmentOnly: true, scope: "environment-defaults", }, + { + id: "assistant", + title: "Assistant", + to: FORK_PAGE, + searchTerms: ["assistant personal one thread across projects"], + environmentOnly: true, + scope: "environment-defaults", + }, + { + id: "assistant-thread", + title: "Make assistant", + to: FORK_PAGE, + searchTerms: ["assistant thread role scratch make"], + environmentOnly: true, + scope: "environment-defaults", + }, ] as const; diff --git a/docs/fork/README.md b/docs/fork/README.md index 34287b10b6eb9..a6f347489afd2 100644 --- a/docs/fork/README.md +++ b/docs/fork/README.md @@ -67,6 +67,7 @@ no section below. "Off" means the default leaves the machine as upstream's would | [`server.mcpCarriedProfiles`](#servermcpcarriedprofiles) | `"apply"` | yes | [#640](https://github.com/scuttletoby/t3code/issues/640) | | [`server.handoff`](#serverhandoff) | `{"mode":"off"}` | yes | [#215](https://github.com/scuttletoby/t3code/issues/215) | | [`server.threadRoles`](#serverthreadroles) | `{"assistant":null,"orchestrators":{}}` | yes | [#138](https://github.com/scuttletoby/t3code/issues/138) | +| [`server.assistant`](#serverassistant) | `{"enabled":false}` | yes | [#879](https://github.com/scuttletoby/t3code/issues/879) | | [`projectOverride.waitChecks`](#projectoverridewaitchecks) | not set | yes | [#84](https://github.com/scuttletoby/t3code/issues/84) | | [`projectOverride.playtest`](#projectoverrideplaytest) | not set | yes | [#260](https://github.com/scuttletoby/t3code/issues/260) | | [`projectOverride.reviewRules`](#projectoverridereviewrules) | not set | yes | [#291](https://github.com/scuttletoby/t3code/issues/291) | @@ -788,8 +789,9 @@ Switch off in `settings.json`: `"headlessUsageRefreshInterval": 0`. ### `server.mcpProfiles` Named MCP profiles. A profile says which outside MCP servers (`servers`) and which groups of T3's -own tools (`t3Tools`) a thread gets; each is `"all"` or a list. Two profiles are built in: `all` -(everything, today's behaviour) and `t3-only` (no outside servers, every T3 tool); a profile cannot +own tools (`t3Tools`) a thread gets; each is `"all"` or a list. Three profiles are built in: `all` +(everything, today's behaviour), `t3-only` (no outside servers, every T3 tool) and `assistant` (see +[assistant.md](assistant.md): no outside servers or built-in tools, three T3 tool groups); a profile cannot take their names, and one written in by hand makes that built-in refuse threads until it is removed (a save may send `null` under a built-in name to remove it) or renamed. @@ -1047,7 +1049,7 @@ the owner set up so. { "mcpProfiles": { "lean": { "servers": [], "t3Tools": ["orchestration", "threads"] } } } ``` -In the app: **Settings → Fork**, section MCP profiles. It lists `all` and `t3-only` (read-only) +In the app: **Settings → Fork**, section MCP profiles. It lists the built-ins (read-only) and each named profile, and adds, edits and deletes named ones: `servers` is all or a list of names (the editor offers the names other profiles use and takes any other; no list of the machine's servers reaches the app yet), `t3Tools` all or a list of groups, and a "No built-in tools" box sets `builtinTools: "none"`. `request_secret`, @@ -1206,6 +1208,18 @@ file after the next save of any setting, since the save writes the settings as r } ``` +### `server.assistant` + +`enabled` offers **Make assistant** in **Settings → Fork**, section Assistant: it makes a thread in +the Scratch project, picks the built-in MCP profile `assistant` for it and points +`threadRoles.assistant` at it, in two saves from the person (the pick first, before the thread +exists). Off (the default): no such button; a +thread already named the assistant stays as it is. Only the person can change it. Anything but +`{"enabled": true}` in the file reads as off; a save with a bad value is refused. The thread +`threadRoles.assistant` names never gets more than the profile `assistant`, whatever its pick (a +managed policy that owns `mcpThreadProfiles` can drop the pick). More in +[assistant.md](assistant.md). + ### `projectOverride.waitChecks` A project's own list of wait checks. It replaces the server's list for that project as a whole (a @@ -1368,6 +1382,7 @@ switch. - [host-tools.md](host-tools.md): design for agents on a person's own computer (no code yet). - [playtest.md](playtest.md): the playtest adapter contract (steps, environment, exit codes). - [handoff.md](handoff.md): handoff instead of compaction (when, the quiet rule, the message). +- [assistant.md](assistant.md): the assistant thread (setup, its profile, what it cannot do yet). - [run-records.md](run-records.md): one record per agent run (usage, time, labels) and the weekly summary. - [`.github/fork-fleet.md`](../../.github/fork-fleet.md): the fleet runners and `CI_RUNNERS`. diff --git a/docs/fork/assistant.md b/docs/fork/assistant.md new file mode 100644 index 0000000000000..a8eda0ec7449e --- /dev/null +++ b/docs/fork/assistant.md @@ -0,0 +1,107 @@ +# The assistant + +Fork only. The assistant is one long thread you talk to across projects. It can read threads, and +start and message work in your projects. It has no shell, no file tools and no web of its own. Later pull +requests let it find each project's orchestrator by itself; mail and calendar come later as +simple tools ([#879](https://github.com/scuttletoby/t3code/issues/879)). + +## Making it + +1. **Settings → Fork**, section Assistant: switch on **Offer Make assistant** (`assistant.enabled`). +2. Press **Make assistant**. T3 first saves the MCP profile pick `assistant` for a new thread id + (`mcpThreadProfiles`), then makes a thread named "Assistant" with that id in the Scratch project + (the project with no folder), then names it the assistant (`threadRoles.assistant`). The app + opens it. The pick comes first so a thread called "Assistant" never runs with a wider profile, + even if setup stops half-way. + +The button needs exactly one environment selected at the top and a Claude provider that is on and +available. The thread gets Claude's default model; change it in the thread as usual. + +Only you can do this: both keys are person-only, so no agent's tool can name a thread the assistant +or give it a profile. The server checks the role as for any `threadRoles` save: the thread must +exist and be a top-level thread. If that save is refused, the new thread is removed again while it +is still empty. The button is locked while a managed policy owns `threadRoles` or +`mcpThreadProfiles`. + +## The profile `assistant` + +A built-in MCP profile, like `all` and `t3-only`: + +- `servers: []`: no outside MCP servers. +- `builtinTools: "none"`: no shell, file or web tools of the provider. Only Claude can apply this, so + a turn on any other provider is refused and says why. +- `t3Tools`: the groups `orchestration`, `threads` and `projects`, plus the tools every profile + keeps (`send_to_user`, `request_secret`, `tool_search`). The thread runs full-access, so it uses + every one of these without asking you. They are much more than reading and messaging: + - `orchestration`: list, read, message, wait for, interrupt and rename threads; delegate tasks + and make threads (`delegate_task`, `create_threads`); schedule, list, cancel and delete tasks; stop workflows (`t3_workflow_stop`); link and unlink + environments (`t3_environment_link`, `t3_environment_unlink`). + - `threads`: change another thread's model and settings (`t3_thread_configure`), transfer and + fork threads, search threads, organize them (pin, snooze, settle, archive), answer another + thread's pending questions (not permission requests), edit, reorder or cancel its queued + messages, and run a scheduled task now. + - `projects`: list and read projects, launch a thread in a project (`t3_thread_launch`), and also + create projects, clone a repository from the network onto disk (`t3_project_clone`), update + projects and delete them. A delete with `force: true` also deletes every thread of that + project, archived ones too, with their transcripts. Only Scratch cannot be deleted. + + Each of these keeps its own server checks (model policy, launch limits, person-only settings). + Profiles keep whole groups, so a single tool cannot be left out today (leaving out `projects` + also takes `t3_thread_launch`). Whether to split the groups into reading and starting work versus + the destructive tools is an open owner question, + [#954](https://github.com/scuttletoby/t3code/issues/954); this version keeps the three whole + groups. + +Any thread can pick it, not only the assistant (it only narrows a thread; the pick alone gives no +role). A sub-agent of the assistant gets at most the same. + +**The assistant thread never runs wider than this profile.** Whatever its pick says, the thread +`threadRoles.assistant` names gets at most `assistant`: a narrower pick stands, and anything wider +(no pick, so the project or server default, or a wider pick) is cut down to `assistant`, shown as +"the assistant thread's limit". This matters when a managed policy owns `mcpThreadProfiles`: it +replaces the whole map and drops the assistant's pick, and without this rule the thread would get +the default (by default `all`, with shell). If the built-in `assistant` cannot be read (see +below), the assistant thread is refused. +A profile in `mcpProfiles` under the name `assistant` makes the built-in refuse its threads until +you remove it (the rule for every built-in name). + +**Upgrading with your own profile called `assistant`:** before this version that was an ordinary +name. After it, every thread that picks it is refused until the entry is removed or renamed. When +you remove it, those threads get the built-in `assistant` instead, which may differ from yours, so +rename it and move their picks first. + +Not yet: the assistant cannot launch a thread into a project whose profile is wider than its own +(the launch check refuses a narrower thread starting a wider one). It can message threads there. +A later pull request settles how the assistant starts work. + +## When things change + +- **Made twice:** the second press makes a new thread and moves the pointer to it. The old thread + keeps its `assistant` profile pick and stays as it is; delete or archive it if you like. The + button is off while a setup runs, so a double click makes one thread. +- **Stops half-way:** after the pick only, nothing is made (a pick for a thread that does not exist + does nothing). After the thread is made but before the role, an "Assistant" thread is left in + Scratch with the `assistant` profile and no role; Settings still says there is no assistant. +- **A run that stops or fails after the pick** (thread not made, not seen by this client, role + refused, or an error): the new thread is deleted if nobody wrote in it yet, and once this client + sees it gone, its pick is removed, so retries do not pile up picks. A thread that stays (someone + wrote in it, or the delete or the check did not go through) keeps its narrow pick. +- **A managed policy owns `mcpThreadProfiles` or `threadRoles`:** the button is locked. A policy + that owns `mcpThreadProfiles` and leaves out the assistant's pick does not widen the assistant + (see above). A policy that owns `threadRoles` and moves or drops the pointer makes that thread an + ordinary one again: from then on it gets its pick, or the defaults if the policy dropped that too. +- **Its thread archived or deleted:** Settings says it is archived, deleted or not on this server + (the app's thread list holds active threads only), and readers treat it as no assistant. The + pointer and the profile pick stay in the file until a new Make assistant replaces the pointer. +- **Profile edited by hand:** an entry `mcpProfiles.assistant` makes the assistant's turns refused + (fail closed) until it is removed; the switch and pointer are not touched. +- **Settings unreadable:** a bad `assistant` value reads as off; a bad `threadRoles` as no roles; a + thread whose profile cannot be read is refused, never given every tool. +- **An older client or server:** an older fork server does not know the profile `assistant`, so + it refuses the first save (the pick) and nothing is made, and it refuses the turns of a thread + already set to it, never giving it more. An older client has no Assistant section and shows the pick as a + profile it does not know. +- **An older build saves the settings:** it knows `assistant` as `{ enabled }` only, so a save from + it writes back just `enabled` and drops any field a newer build added to `assistant`. Today + `enabled` is the only field, so nothing is lost; a later pull request that adds a field must keep + this in mind (read a missing field as its default). diff --git a/packages/contracts/src/assistant.test.ts b/packages/contracts/src/assistant.test.ts new file mode 100644 index 0000000000000..5b5450d1fd458 --- /dev/null +++ b/packages/contracts/src/assistant.test.ts @@ -0,0 +1,26 @@ +// Fork (assistant): the `assistant` settings block. Off in an old or bad file; a save is strict. +import * as Schema from "effect/Schema"; +import { describe, expect, it } from "vite-plus/test"; + +import { FORK_PERSON_ONLY_KEYS } from "./forkSettings.ts"; +import { ServerSettings, ServerSettingsPatch } from "./settings.ts"; + +const decodeServer = Schema.decodeUnknownSync(ServerSettings); +const decodePatch = Schema.decodeUnknownSync(ServerSettingsPatch); + +describe("assistant settings", () => { + it("reads an old file, or anything but enabled: true, as off; keeps the other settings", () => { + for (const assistant of [undefined, null, {}, { enabled: "yes" }, [true], true]) { + const settings = decodeServer({ assistant, enableAgentBrowserAccess: false }); + expect(settings.assistant).toEqual({ enabled: false }); + expect(settings.enableAgentBrowserAccess).toBe(false); + } + expect(decodeServer({ assistant: { enabled: true } }).assistant).toEqual({ enabled: true }); + }); + + it("takes a good save, refuses a bad one, and is person-only", () => { + expect(decodePatch({ assistant: { enabled: true } }).assistant).toEqual({ enabled: true }); + expect(() => decodePatch({ assistant: { enabled: "yes" } })).toThrow(); + expect(FORK_PERSON_ONLY_KEYS).toContain("assistant"); + }); +}); diff --git a/packages/contracts/src/assistant.ts b/packages/contracts/src/assistant.ts new file mode 100644 index 0000000000000..7b9e756dfafef --- /dev/null +++ b/packages/contracts/src/assistant.ts @@ -0,0 +1,37 @@ +/** + * Fork (assistant): the `assistant` settings block. `enabled` offers "Make assistant" in Settings; + * the assistant itself is the thread `threadRoles.assistant` names, run with the built-in MCP + * profile `assistant`. Off by default. Docs: docs/fork/assistant.md. + */ +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; +import * as SchemaTransformation from "effect/SchemaTransformation"; + +export const AssistantSettings = Schema.Struct({ + enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), +}); +export type AssistantSettings = typeof AssistantSettings.Type; + +const DEFAULT_ASSISTANT_SETTINGS: AssistantSettings = { enabled: false }; + +/** The settings file's `assistant`, read leniently: anything but `enabled: true` reads as off. */ +export const AssistantSettingsFromSettingsFile = Schema.Unknown.pipe( + Schema.decodeTo( + AssistantSettings, + SchemaTransformation.transform({ + decode: (raw: unknown): typeof AssistantSettings.Encoded => ({ + enabled: + typeof raw === "object" && + raw !== null && + (raw as { enabled?: unknown }).enabled === true, + }), + encode: (settings: typeof AssistantSettings.Encoded): unknown => settings, + }), + ), + Schema.withDecodingDefault(Effect.succeed(DEFAULT_ASSISTANT_SETTINGS)), +); + +/** A save's change: strict, so a bad value is refused; a field left out keeps its value. */ +export const AssistantSettingsPatch = Schema.Struct({ + enabled: Schema.optionalKey(Schema.Boolean), +}); diff --git a/packages/contracts/src/forkDefaults.ts b/packages/contracts/src/forkDefaults.ts index 75915a307c719..00a44d967c56f 100644 --- a/packages/contracts/src/forkDefaults.ts +++ b/packages/contracts/src/forkDefaults.ts @@ -220,6 +220,14 @@ export const FORK_SETTING_DEFAULTS: ReadonlyArray = [ reason: "No thread holds a role, so every thread is shown as upstream shows it.", decidedIn: "#138", }, + { + scope: "server", + key: "assistant", + default: { enabled: false }, + off: true, + reason: 'Settings offers no "Make assistant"; no thread is made.', + decidedIn: "#879", + }, { scope: "projectOverride", key: "mcpProfile", diff --git a/packages/contracts/src/forkSettings.ts b/packages/contracts/src/forkSettings.ts index 1e228209c4a16..9c81329c31946 100644 --- a/packages/contracts/src/forkSettings.ts +++ b/packages/contracts/src/forkSettings.ts @@ -43,6 +43,7 @@ import { ReviewRulesProjectPatch, } from "./reviewRules.ts"; import { ThreadRolesFromSettingsFile, ThreadRolesPatch } from "./threadRoles.ts"; +import { AssistantSettingsFromSettingsFile, AssistantSettingsPatch } from "./assistant.ts"; import { DEFAULT_USAGE_PACING_INSTANCE_SETTINGS, UsagePacingGateMode, @@ -59,6 +60,7 @@ import { WaitForSettingsPatch, } from "./waitFor.ts"; +export * from "./assistant.ts"; export * from "./forkFeatures.ts"; export * from "./handoff.ts"; export * from "./mcpProfile.ts"; @@ -138,6 +140,8 @@ export const ForkServerSettingsFields = { ), /** Which thread is the assistant and each project's orchestrator; none. A bad entry drops alone. */ threadRoles: ThreadRolesFromSettingsFile, + /** Offers "Make assistant"; off. A bad value reads as off. */ + assistant: AssistantSettingsFromSettingsFile, }; /** A key of {@link ForkServerSettingsFields}. */ @@ -183,6 +187,8 @@ export const ForkServerSettingsPatchFields = { placementNeeds: Schema.optionalKey(PlacementNeedsPatch), /** Strict ids; the server also refuses a pointer to a thread that cannot hold the role. */ threadRoles: Schema.optionalKey(ThreadRolesPatch), + /** Strict: a save refuses a bad value or an unknown field. */ + assistant: Schema.optionalKey(AssistantSettingsPatch), } satisfies Record; /** @@ -234,6 +240,7 @@ export const FORK_PATCH_RULES: { readonly [K in ForkServerSettingKey]: ForkPatch // One orchestrator per project entry, so two people setting different projects keep both; two // saves of the same project, the last one wins. threadRoles: { fields: { assistant: "replace", orchestrators: { replaceEntries: {} } } }, + assistant: "merge-fields", }; /** diff --git a/packages/contracts/src/mcpProfile.ts b/packages/contracts/src/mcpProfile.ts index 9d2eef040ca5a..43c0899d1e01d 100644 --- a/packages/contracts/src/mcpProfile.ts +++ b/packages/contracts/src/mcpProfile.ts @@ -13,8 +13,17 @@ import { TrimmedString } from "./baseSchemas.ts"; export const MCP_PROFILE_ALL = "all"; /** No outside servers, every T3 tool. */ export const MCP_PROFILE_T3_ONLY = "t3-only"; -/** The two profiles every build knows; `mcpProfiles` cannot redefine them. */ -const MCP_BUILT_IN_PROFILE_NAMES: ReadonlyArray = [MCP_PROFILE_ALL, MCP_PROFILE_T3_ONLY]; +/** + * The assistant's: no outside servers, no built-in tools, and the T3 groups `orchestration`, + * `threads` and `projects` (docs/fork/assistant.md lists what they can do). + */ +export const MCP_PROFILE_ASSISTANT = "assistant"; +/** The profiles every build knows; `mcpProfiles` cannot redefine them. */ +const MCP_BUILT_IN_PROFILE_NAMES: ReadonlyArray = [ + MCP_PROFILE_ALL, + MCP_PROFILE_T3_ONLY, + MCP_PROFILE_ASSISTANT, +]; /** * A profile's `builtinTools`: `none` starts the thread with no built-in tools of the provider (no * shell, files or web; only MCP tools). Only Claude applies it; a turn on any other driver is @@ -31,7 +40,7 @@ const MCP_PROFILE_NAME_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/u; export const McpProfileName = Schema.String.check(Schema.isPattern(MCP_PROFILE_NAME_PATTERN)); export type McpProfileName = typeof McpProfileName.Type; -/** True for `all` and `t3-only`. */ +/** True for a built-in profile's name: `all`, `t3-only` and `assistant`. */ export const isBuiltInMcpProfileName = (name: string): boolean => MCP_BUILT_IN_PROFILE_NAMES.includes(name); diff --git a/packages/contracts/src/mcpProfileResolve.ts b/packages/contracts/src/mcpProfileResolve.ts index 17f6336416a00..f598243d3b700 100644 --- a/packages/contracts/src/mcpProfileResolve.ts +++ b/packages/contracts/src/mcpProfileResolve.ts @@ -8,6 +8,7 @@ import { MCP_BUILTIN_TOOLS_NONE, MCP_CARRIED_PROFILES_REFUSE, MCP_PROFILE_ALL, + MCP_PROFILE_ASSISTANT, MCP_PROFILE_T3_ONLY, MCP_SUBAGENT_INHERIT, MCP_T3_TOOL_GROUPS, @@ -24,7 +25,13 @@ import type { ServerSettings } from "./settings.ts"; export type McpProfileSettings = Pick< ServerSettings, "mcpProfiles" | "mcpProfile" | "mcpSubagentProfile" | "mcpThreadProfiles" | "mcpCarriedProfiles" ->; +> & { + /** + * The role pointers; only `assistant` is read: that thread never gets more than the built-in + * `assistant` profile (see {@link resolveMcpProfile}). + */ + readonly threadRoles: { readonly assistant: string | null }; +}; /** One thread of a lineage, as the resolver needs it. */ export interface McpProfileThread { @@ -48,8 +55,16 @@ export interface McpProfileSet { readonly builtinTools?: typeof MCP_BUILTIN_TOOLS_NONE; } -/** Where a thread's profile came from. */ -export type McpProfileSource = "thread-pick" | "subagent-rule" | "project" | "environment"; +/** + * Where a thread's profile came from. `assistant-role`: the thread is `threadRoles.assistant` and + * what it would get otherwise keeps more than the built-in `assistant` profile, so it gets that. + */ +export type McpProfileSource = + | "thread-pick" + | "subagent-rule" + | "project" + | "environment" + | "assistant-role"; export interface McpProfileResolved { readonly _tag: "Resolved"; @@ -108,9 +123,15 @@ export type McpProfileResolution = McpProfileResolved | McpProfileCannotApply; /** Longer lineages are refused; real delegation chains are a few threads deep. */ export const MCP_PROFILE_MAX_LINEAGE = 64; -const BUILT_IN_PROFILES: Readonly> = { +/** What each built-in profile gives; Settings lists them from here. */ +export const MCP_BUILT_IN_PROFILES: Readonly> = { [MCP_PROFILE_ALL]: { servers: "all", t3Tools: "all" }, [MCP_PROFILE_T3_ONLY]: { servers: [], t3Tools: "all" }, + [MCP_PROFILE_ASSISTANT]: { + servers: [], + t3Tools: ["orchestration", "threads", "projects"], + builtinTools: MCP_BUILTIN_TOOLS_NONE, + }, }; const KNOWN_GROUPS: ReadonlySet = new Set(MCP_T3_TOOL_GROUPS); @@ -181,7 +202,9 @@ type Lookup = /** A named profile: a built-in, or an entry of `mcpProfiles` checked now. */ function lookUp(settings: McpProfileSettings, name: string): Lookup { const profiles: unknown = settings.mcpProfiles; - const builtIn = Object.hasOwn(BUILT_IN_PROFILES, name) ? BUILT_IN_PROFILES[name] : undefined; + const builtIn = Object.hasOwn(MCP_BUILT_IN_PROFILES, name) + ? MCP_BUILT_IN_PROFILES[name] + : undefined; if (builtIn !== undefined) { // A save never writes an entry under a built-in's name, so one is a hand edit. Which of the // two the owner meant is unknown, so neither is used. @@ -416,11 +439,38 @@ function cannotApply( }; } +/** + * The thread's profile, held within the built-in `assistant` for the `threadRoles.assistant` thread, + * so a managed policy that drops its pick cannot give it the wide defaults. Within stands; wider is + * cut to `assistant`; a broken `assistant` refuses. + */ function resolveAt( settings: McpProfileSettings, lineage: ReadonlyArray, index: number, carried: unknown, +): McpProfileResolution { + const thread = lineage[index]!; + const resolved = resolveOwnAt(settings, lineage, index, carried); + const roles: unknown = settings.threadRoles; + const assistant = isRecord(roles) ? roles.assistant : undefined; + if (resolved._tag === "CannotApply" || assistant !== thread.threadId) return resolved; + const bound = lookUp(settings, MCP_PROFILE_ASSISTANT); + if (!bound.ok) return cannotApply(bound.problem, thread, MCP_PROFILE_ASSISTANT, bound.issue); + if (isWithinMcpProfile(resolved.profile, bound.profile)) return resolved; + return { + ...resolved, + name: MCP_PROFILE_ASSISTANT, + source: "assistant-role", + profile: cutTo(resolved.profile, bound.profile), + }; +} + +function resolveOwnAt( + settings: McpProfileSettings, + lineage: ReadonlyArray, + index: number, + carried: unknown, ): McpProfileResolution { const thread = lineage[index]!; const choice = ownChoice(settings, thread); diff --git a/packages/shared/src/forkSettingsPatch.test.ts b/packages/shared/src/forkSettingsPatch.test.ts index 709be547c98bc..98550aafd0f00 100644 --- a/packages/shared/src/forkSettingsPatch.test.ts +++ b/packages/shared/src/forkSettingsPatch.test.ts @@ -303,6 +303,7 @@ describe("fork settings save check (MCP profile references)", () => { ["a built-in default", { mcpProfile: "t3-only" }], ["inherit as the sub-agent rule", { mcpSubagentProfile: "inherit" }], ["a pick of a built-in", { mcpThreadProfiles: { "thread-1": "all" } }], + ["a pick of the assistant's built-in", { mcpThreadProfiles: { "thread-1": "assistant" } }], [ "a default added in the same save", { mcpProfiles: { docs: { servers: ["docs"], t3Tools: "all" } }, mcpProfile: "docs" },