diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx index 58129ebc0cece..bf530881cd314 100644 --- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx +++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx @@ -5,6 +5,7 @@ import { queuedRunEditBlockedReason, } from "@t3tools/client-runtime/queued-run-edit"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { describeThreadFreeze } from "@t3tools/client-runtime/state/thread-workflows"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; import { Atom } from "effect/reactivity"; @@ -207,6 +208,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { contentContainerClassName="px-5 pb-6" contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 16) + 8 }} > + {workflow?.frozen != null ? ( + + {describeThreadFreeze(workflow.frozen)} + + ) : null} {workflow?.isHeld && queuedRuns.length > 0 ? ( Queue paused diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index c52fbde1a8a65..c9afb6de87fa6 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -22,6 +22,7 @@ import { } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; +import * as Hash from "effect/Hash"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; @@ -1991,3 +1992,99 @@ it.effect.each(["capability_denied", "invalid_request"] as const)( }).pipe(Effect.provide(layer)); }, ); + +it.effect( + "logs the connection of each call by its Mcp-Session-Id, over the real HTTP transport", + () => + Effect.scoped( + Effect.gen(function* () { + const entries: Array<{ readonly connection?: string | undefined }> = []; + const scope: McpInvocationContext.McpThreadInvocationScope = { + environmentId, + requestNamespace: "shared-token", + thread: { + threadId: ThreadId.make("thread-shared"), + providerSessionId: "provider-session", + providerInstanceId: ProviderInstanceId.make("codex"), + }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 1, + }; + const toolkit = Toolkit.make( + Tool.make("probe", { + success: Schema.Struct({}), + failure: OrchestratorMcpFailure, + failureMode: "return", + }), + ); + const serverLayer = McpHttpServer.layerMcpTransport( + McpHttpServer.toolkitRegistration( + toolkit, + McpToolAccess.toLayer(toolkit, { + probe: McpToolAccess.reads(() => Effect.succeed({})), + }), + ), + ).pipe( + Layer.provide(ServerSettings.layerTest()), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + Layer.provide( + Layer.mock(RequestLog.McpRequestLog)({ + record: (entry) => Effect.sync(() => void entries.push(entry)), + }), + ), + Layer.provide( + Layer.mock(McpSessionRegistry.McpSessionRegistry)({ + resolve: () => Effect.succeed(scope), + }), + ), + ); + yield* HttpRouter.serve(serverLayer, { disableListenLog: true, disableLogger: true }).pipe( + Layer.build, + ); + const httpClient = yield* HttpClient.HttpClient; + const headers = { + accept: "application/json, text/event-stream", + authorization: "Bearer shared-token", + }; + const connect = Effect.gen(function* () { + const initialize = yield* httpClient.post("/mcp", { + headers, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1.0.0"}}}`, + "application/json", + ), + }); + const sessionId = initialize.headers["mcp-session-id"]!; + const call = httpClient + .post("/mcp", { + headers: { + ...headers, + "mcp-session-id": sessionId, + "mcp-protocol-version": "2025-06-18", + }, + body: HttpBody.text( + `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"probe","arguments":{}}}`, + "application/json", + ), + }) + .pipe(Effect.flatMap((response) => response.text)); + return { sessionId, call }; + }); + // Two agents on one sign-in, each with its own MCP session; one makes parallel calls. + const first = yield* connect; + const second = yield* connect; + yield* Effect.all([first.call, first.call, second.call], { concurrency: "unbounded" }); + const [a1, a2, b1] = [...entries].toSorted((left, right) => + String(left.connection).localeCompare(String(right.connection)), + ); + expect(entries).toHaveLength(3); + expect(new Set(entries.map((entry) => entry.connection)).size).toBe(2); + expect(a1?.connection).toBeDefined(); + expect([a1, a2, b1].every((entry) => entry?.connection !== undefined)).toBe(true); + expect(new Set(entries.map((entry) => entry.connection))).toEqual( + new Set([first.sessionId, second.sessionId].map((id) => Hash.string(id).toString(16))), + ); + }), + ).pipe(Effect.provide(NodeHttpServer.layerTest)), +); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 71366fab53a93..f9a03e60c037f 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -6,6 +6,7 @@ import * as McpRequestLog from "../persistence/McpRequestLog.ts"; import * as McpBridgeMetrics from "./McpBridgeMetrics.ts"; import * as BridgeStatus from "../persistence/McpBridgeStatus.ts"; import * as ThreadLaunchMcp from "./ThreadLaunchMcpService.ts"; +import * as AgentRegistry from "../persistence/AgentRegistry.ts"; import * as McpClientThreads from "../persistence/McpClientThreads.ts"; import * as WorkLedger from "../persistence/WorkLedger.ts"; import { LedgerToolkit } from "./toolkits/ledger/tools.ts"; @@ -16,6 +17,7 @@ import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; +import * as Hash from "effect/Hash"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; @@ -324,7 +326,12 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { const limited = McpInvocationContext.withRuntimeModeCeiling(attributed, runtimeModeCeiling); const linkedEnvironments = yield* linksEnabled; if (limited.client?.linked === true && !linkedEnvironments) return linkedEnvironmentsOff; - return { ...limited, linkedEnvironments }; + const mcpSessionId = request.headers["mcp-session-id"]; + return { + ...limited, + linkedEnvironments, + ...(mcpSessionId === undefined ? {} : { connection: Hash.string(mcpSessionId).toString(16) }), + }; }); // Untraced: a span here would wrap the tool call; the HTTP server span already covers it. return Effect.fnUntraced(function* (httpEffect) { @@ -1219,6 +1226,7 @@ const withToolAnalytics = result, exit._tag === "Failure" ? exit.cause : undefined, ), + connection: scope.connection, }) .pipe(Effect.ignoreCause); } @@ -1560,4 +1568,5 @@ export const layer = Layer.merge( Layer.provide(McpClientThreads.layer), Layer.provide(McpBridgeMetrics.layer), Layer.provide(McpRequestLog.layer), + Layer.provide(AgentRegistry.layer), ); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index f6b59fce079ad..a75eae04db927 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -153,6 +153,8 @@ export interface McpInvocationScope { readonly client: McpClientCaller | undefined; /** False while the Linked environments beta is off here; `/mcp` reads it per request. */ readonly linkedEnvironments?: boolean; + /** Short digest of the request's `Mcp-Session-Id`: one agent's connection, kept for the request log. */ + readonly connection?: string; } export const messageSenderFor = (scope: McpInvocationScope) => { diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 59442dc012c60..8763ba7ade056 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -917,6 +917,7 @@ function threadDetail( archived: projection.thread.archivedAt !== null, ...threadSettlement(projection.thread), ...threadSnooze(shell, nowMs), + frozen: projection.thread.frozen ?? null, createdAt: DateTime.formatIso(projection.thread.createdAt), updatedAt: DateTime.formatIso(projection.thread.updatedAt), }; @@ -3482,6 +3483,8 @@ const make = Effect.gen(function* () { ...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }), status: result.run.status, delivery: result.delivery, + ...(result.run.queueHeld === true ? { held: true as const } : {}), + ...(target.thread.frozen == null ? {} : { frozen: true as const }), } satisfies OrchestratorMcpThreadSendResult; }), waitForThread: Effect.fn("OrchestratorMcpService.waitForThread")(function* (scope, input) { diff --git a/apps/server/src/mcp/threadFreeze.test.ts b/apps/server/src/mcp/threadFreeze.test.ts new file mode 100644 index 0000000000000..31d6abc6dad12 --- /dev/null +++ b/apps/server/src/mcp/threadFreeze.test.ts @@ -0,0 +1,155 @@ +import { expect, it } from "@effect/vitest"; +import { + EnvironmentId, + type OrchestrationV2Run, + type OrchestrationV2ServerCommand, + RunId, + ThreadId, +} from "@t3tools/contracts"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import { ThreadFreezeGate } from "../orchestration-v2/ThreadFreeze.ts"; +import * as McpInvocationContext from "./McpInvocationContext.ts"; +import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts"; +import { freezeThread, unfreezeThread } from "./threadFreeze.ts"; + +const target = ThreadId.make("thread:inbox"); +const queuedRun = { id: RunId.make("run:queued"), status: "queued" } as OrchestrationV2Run; +const longLabel = "x".repeat(300); + +const outside = (label = "Codex"): McpInvocationContext.McpInvocationScope => ({ + environmentId: EnvironmentId.make("env"), + requestNamespace: "ns", + issuedAt: 0, + capabilities: new Set(["orchestration"]), + thread: undefined, + client: { sessionId: "963da7fc-7a35-4939-b709-dfd27d40d323", label, access: "full-access" }, +}); +const asThread = ( + threadId: ThreadId, + subagent = false, +): McpInvocationContext.McpInvocationScope => ({ + ...outside(), + client: undefined, + thread: { + threadId, + providerSessionId: "provider-session", + providerInstanceId: McpToolAccessTestkit.liveThreadShell(threadId).providerInstanceId, + ...(subagent ? { subagent: true } : {}), + }, +}); + +const harness = (options: { + readonly frozen: boolean; + readonly runs: Array; +}) => { + const commands: Array = []; + const stopped: Array = []; + const gates: Array = []; + const shell = McpToolAccessTestkit.liveThreadShell(target); + const projection = McpToolAccessTestkit.idleThreadProjection(shell); + const layer = Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: () => + Effect.succeed({ + ...projection, + runs: options.runs, + thread: { + ...projection.thread, + ...(options.frozen + ? { frozen: { at: "t", by: { kind: "owner", label: "Chris" }, reason: "r" } } + : {}), + }, + }) as never, + dispatch: (command) => + Effect.gen(function* () { + commands.push(command); + gates.push(Option.getOrUndefined(yield* Effect.serviceOption(ThreadFreezeGate))); + return { sequence: 1, storedEvents: [], replayed: false } as never; + }), + stopDelegatedTasks: ({ threadId }) => Effect.sync(() => void stopped.push(threadId)), + }).pipe(Layer.provideMerge(NodeCrypto.layer)); + const run = ( + effect: Effect.Effect, + scope: McpInvocationContext.McpInvocationScope, + ) => + effect.pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, scope), + Effect.provide(layer), + ); + return { commands, gates, stopped, run }; +}; + +it.effect("freeze records the authenticated caller, then stops and holds", () => { + const { commands, gates, stopped, run } = harness({ frozen: false, runs: [queuedRun] }); + return Effect.gen(function* () { + const result = yield* run( + freezeThread({ threadId: target, reason: " misbehaving " }), + outside(longLabel), + ); + expect(result).toMatchObject({ frozen: true, queuedMessages: 1 }); + expect(commands.map((command) => command.type)).toEqual([ + "thread.metadata.update", + "thread.stop", + ]); + const marker = commands[0]; + expect(marker?.type === "thread.metadata.update" ? marker.frozen : undefined).toMatchObject({ + by: { kind: "outside-client", sessionId: "963da7fc", label: "x".repeat(128) }, + reason: "misbehaving", + }); + expect(gates).toEqual([{ op: "freeze" }, undefined]); + expect(stopped).toEqual([target]); + const missing = yield* run(freezeThread({ threadId: target, reason: " " }), outside()).pipe( + Effect.flip, + ); + expect(missing.code).toBe("invalid_request"); + }); +}); + +it.effect("a frozen thread or its delegate cannot unfreeze it", () => { + const { commands, run } = harness({ frozen: true, runs: [] }); + return Effect.gen(function* () { + for (const scope of [asThread(target), asThread(ThreadId.make("thread:child"), true)]) { + const refused = yield* run( + unfreezeThread({ threadId: target, freshContext: undefined }), + scope, + ).pipe(Effect.flip); + expect(refused.code).toBe("capability_denied"); + } + expect(commands).toEqual([]); + }); +}); + +it.effect("unfreeze resumes the queue, and freshContext waits for an empty queue", () => { + const queued = harness({ frozen: true, runs: [queuedRun] }); + const empty = harness({ frozen: true, runs: [] }); + return Effect.gen(function* () { + const refused = yield* queued + .run(unfreezeThread({ threadId: target, freshContext: true }), outside()) + .pipe(Effect.flip); + expect(refused.message).toContain("1 queued message"); + expect(queued.commands).toEqual([]); + + expect( + yield* queued.run(unfreezeThread({ threadId: target, freshContext: undefined }), outside()), + ).toMatchObject({ frozen: false, wasFrozen: true, queuedMessages: 1 }); + expect(queued.commands.map((command) => command.type)).toEqual(["queue.resume"]); + expect(queued.gates).toMatchObject([ + { + op: "unfreeze", + freshContext: false, + by: { kind: "outside-client", sessionId: "963da7fc" }, + }, + ]); + + expect( + yield* empty.run(unfreezeThread({ threadId: target, freshContext: true }), outside()), + ).toMatchObject({ frozen: false, freshContextNext: true }); + expect(empty.commands.map((command) => command.type)).toEqual(["queue.resume"]); + expect(empty.gates).toMatchObject([{ op: "unfreeze", freshContext: true }]); + }); +}); diff --git a/apps/server/src/mcp/threadFreeze.ts b/apps/server/src/mcp/threadFreeze.ts new file mode 100644 index 0000000000000..1151b3ad5150a --- /dev/null +++ b/apps/server/src/mcp/threadFreeze.ts @@ -0,0 +1,137 @@ +import { + CommandId, + OrchestratorMcpFailure, + type ThreadFreeze, + type ThreadFreezeActor, +} from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; + +import { ThreadFreezeGate } from "../orchestration-v2/ThreadFreeze.ts"; +import { type McpInvocationScope, messageSenderFor } from "./McpInvocationContext.ts"; +import { assertLiveCaller, dispatchFailure, newCommandId, readThread } from "./threadAccess.ts"; + +const invalid = (message: string) => + new OrchestratorMcpFailure({ code: "invalid_request", message }); + +/** The caller's identity from the authenticated scope, never from a tool argument. */ +const freezeActor = (scope: McpInvocationScope, label: string): ThreadFreezeActor => { + const sender = messageSenderFor(scope).senderClient; + if (sender !== undefined) { + return { + kind: sender.kind, + label: sender.clientLabel.slice(0, 128), + sessionId: sender.sessionId, + }; + } + return scope.thread === undefined + ? { kind: "unknown", label: label.slice(0, 128) } + : { kind: "agent", label: label.slice(0, 128), threadId: scope.thread.threadId }; +}; + +const nowIso = Effect.map(Clock.currentTimeMillis, (ms) => + DateTime.formatIso(DateTime.makeUnsafe(ms)), +); + +/** + * Freeze records the marker first, so nothing starts while the stop lands, then does what + * `t3_thread_interrupt` with `stop` does: interrupt the run, hold the queue, stop delegated tasks. + * It checks its caller as interrupt does. A thread may freeze itself, and then cannot lift it. + */ +export const freezeThread = Effect.fn("mcp.freezeThread")(function* (input: { + readonly threadId?: Parameters[0]; + readonly reason: string | undefined; +}) { + const reason = input.reason?.trim() ?? ""; + if (reason.length === 0) return yield* invalid("freeze needs a `reason`."); + const { projection, ...context } = yield* readThread(input.threadId, ["runs"]); + const { threads, scope, caller } = context; + yield* assertLiveCaller(context); + const threadId = projection.thread.id; + const queuedMessages = projection.runs.filter((run) => run.status === "queued").length; + const existing = projection.thread.frozen ?? null; + const freeze: ThreadFreeze = existing ?? { + at: yield* nowIso, + by: freezeActor(scope, caller?.title ?? "Unknown caller"), + reason: reason.slice(0, 500), + }; + const base = yield* newCommandId(); + if (existing === null) { + yield* threads + .dispatch({ type: "thread.metadata.update", commandId: base, threadId, frozen: freeze }) + .pipe( + Effect.provideService(ThreadFreezeGate, { op: "freeze" }), + Effect.mapError(dispatchFailure), + ); + } + const stopReason = `Frozen by ${freeze.by.label}: ${freeze.reason}`; + const stopId = CommandId.make(`${base}:stop`); + const stopped = yield* threads + .dispatch({ type: "thread.stop", commandId: stopId, threadId, reason: stopReason }) + .pipe(Effect.mapError(dispatchFailure)); + yield* threads + .stopDelegatedTasks({ threadId, commandId: stopId, reason: stopReason }) + .pipe(Effect.mapError(dispatchFailure)); + const interrupted = stopped.storedEvents.find( + ({ event }) => + (event.type === "run.updated" && event.payload.status === "interrupted") || + (event.type === "turn-item.updated" && + event.payload.type === "run_interrupt_request" && + event.payload.providerTurnId !== null), + )?.event.runId; + return { + frozen: true as const, + freeze, + interruptedRunId: interrupted ?? null, + queuedMessages, + }; +}); + +/** + * Unfreeze is one `queue.resume` that lifts the marker and releases the queue together, so a + * refused resume (a usage limit, say) leaves the thread frozen and the call can be repeated. + * The frozen thread or a delegate of it cannot call it. + */ +export const unfreezeThread = Effect.fn("mcp.unfreezeThread")(function* (input: { + readonly threadId?: Parameters[0]; + readonly freshContext: boolean | undefined; +}) { + const { projection, ...context } = yield* readThread(input.threadId, ["runs"]); + const { threads, scope, caller } = context; + yield* assertLiveCaller(context); + const threadId = projection.thread.id; + if (caller?.id === threadId || scope.thread?.subagent === true) { + return yield* new OrchestratorMcpFailure({ + code: "capability_denied", + message: + "A frozen thread or a delegate of it cannot unfreeze it; the operator or its coordinator must.", + }); + } + if (projection.thread.frozen == null) { + return { frozen: false as const, wasFrozen: false as const, queuedMessages: 0 }; + } + const held = projection.runs.filter((run) => run.status === "queued").length; + if (input.freshContext === true && held > 0) { + return yield* invalid( + `${held} queued message${held === 1 ? "" : "s"} would start first on the old context. Cancel them with t3_queue, or unfreeze without freshContext.`, + ); + } + yield* threads + .dispatch({ type: "queue.resume", commandId: yield* newCommandId(), threadId }) + .pipe( + Effect.provideService(ThreadFreezeGate, { + op: "unfreeze", + by: freezeActor(scope, caller?.title ?? "Unknown caller"), + at: yield* nowIso, + freshContext: input.freshContext === true, + }), + Effect.mapError(dispatchFailure), + ); + return { + frozen: false as const, + wasFrozen: true as const, + queuedMessages: held, + ...(input.freshContext === true ? { freshContextNext: true as const } : {}), + }; +}); diff --git a/apps/server/src/mcp/toolkits/bridge/handlers.ts b/apps/server/src/mcp/toolkits/bridge/handlers.ts index df7691d1910d7..1089ccc432dc9 100644 --- a/apps/server/src/mcp/toolkits/bridge/handlers.ts +++ b/apps/server/src/mcp/toolkits/bridge/handlers.ts @@ -2,6 +2,7 @@ import { OrchestratorMcpFailure } from "@t3tools/contracts"; import * as McpEvents from "../../McpEvents.ts"; import * as Effect from "effect/Effect"; import * as Invocation from "../../McpInvocationContext.ts"; +import * as AgentRegistry from "../../../persistence/AgentRegistry.ts"; import * as RequestLog from "../../../persistence/McpRequestLog.ts"; import * as Access from "../../McpToolAccess.ts"; import * as Bridge from "../../BridgeStatusService.ts"; @@ -13,6 +14,17 @@ export const layer = Access.toLayer(BridgeToolkit, { return yield* (yield* RequestLog.McpRequestLog).usage(input, scope.client?.sessionId); }), ), + agent_registry: Access.reads((input) => + Effect.gen(function* () { + const scope = yield* Invocation.McpInvocationContext; + const client = scope.client; + return yield* (yield* AgentRegistry.AgentRegistry).list(input, { + sessionId: client?.sessionId, + seesAll: + client === undefined || (client.access === "full-access" && client.linked !== true), + }); + }), + ), event_subscriptions: Access.reads(() => Effect.flatMap(McpEvents.McpEvents, (service) => service.listSubscriptions()).pipe( Effect.mapError( diff --git a/apps/server/src/mcp/toolkits/bridge/tools.ts b/apps/server/src/mcp/toolkits/bridge/tools.ts index d769fac04df6b..31b96f3082b2c 100644 --- a/apps/server/src/mcp/toolkits/bridge/tools.ts +++ b/apps/server/src/mcp/toolkits/bridge/tools.ts @@ -11,6 +11,7 @@ import { OrchestratorMcpFailure, } from "@t3tools/contracts"; import { Tool, Toolkit } from "effect/ai"; +import * as AgentRegistry from "../../../persistence/AgentRegistry.ts"; import * as RequestLog from "../../../persistence/McpRequestLog.ts"; import * as Bridge from "../../BridgeStatusService.ts"; import * as Invocation from "../../McpInvocationContext.ts"; @@ -37,6 +38,17 @@ export const BridgeToolkit = Toolkit.make( }) .annotate(Tool.Readonly, true) .annotate(Tool.Destructive, false), + Tool.make("agent_registry", { + description: + "List agents that called in 14 days, newest first: sign-ins, threads, scheduled tasks, delegates. 'shared, unattributable': a sign-in on overlapping MCP connections, so calls can't be tied to one agent. Others see only their own. Page with nextCursor.", + parameters: AgentRegistry.RegistryInput, + success: AgentRegistry.RegistryResult, + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [Invocation.McpInvocationContext, AgentRegistry.AgentRegistry], + }) + .annotate(Tool.Readonly, true) + .annotate(Tool.Destructive, false), Tool.make("event_subscriptions", { description: "List this caller's own event subscriptions by native id, thread, event, expiry and callbackGroup (one watch). Includes the inbox pin; notifyDerived distinguishes notify copies from explicit watches. Legacy origin is recovered by callback-group creation order. Callback URLs and secrets are omitted.", diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 1edac9c9b1e79..0d2a231e66d14 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -1,6 +1,7 @@ import { RuntimeModeChangeActor } from "../../orchestration-v2/DispatchModeLimit.ts"; import { CommandActor } from "../../orchestration-v2/CommandActor.ts"; import * as McpEvents from "../McpEvents.ts"; +import * as AgentRegistry from "../../persistence/AgentRegistry.ts"; import * as McpRequestLog from "../../persistence/McpRequestLog.ts"; import * as BridgeStatusService from "../BridgeStatusService.ts"; import { BridgeToolkit } from "./bridge/tools.ts"; @@ -220,6 +221,7 @@ it.effect( ).pipe( Layer.provide(Layer.mock(BridgeStatusService.BridgeStatusService)({})), Layer.provide(Layer.mock(McpEvents.McpEvents)({})), + Layer.provide(Layer.mock(AgentRegistry.AgentRegistry)({})), Layer.provideMerge(McpRequestLog.layer.pipe(Layer.provide(Sqlite.layerMemory))), Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), Layer.provideMerge(McpBridgeMetrics.layer), diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index a0955869db3b3..be06287c5aa3b 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -29,6 +29,7 @@ import * as ScratchThreadPromotion from "../../../project/ScratchThreadPromotion import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts"; import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts"; import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts"; +import { freezeThread, unfreezeThread } from "../../threadFreeze.ts"; import { ThreadToolkit } from "./tools.ts"; const isApprovalKind = Schema.is(ProviderRequestKind); @@ -430,6 +431,15 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { ), t3_thread_organize: writesThread((input, authorize) => Effect.gen(function* () { + if (input.action === "freeze") { + return yield* freezeThread({ threadId: input.threadId, reason: input.reason }); + } + if (input.action === "unfreeze") { + return yield* unfreezeThread({ + threadId: input.threadId, + freshContext: input.freshContext, + }); + } const { threads, projection, caller } = yield* readThread(input.threadId); if (input.action === "move") { const projectId = yield* required(input.projectId, "projectId"); diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index 9e815956cd4da..a8b11064d21a5 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -20,6 +20,7 @@ import { RunId, NonNegativeInt, ProjectId, + ThreadFreeze, } from "@t3tools/contracts"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Schema from "effect/Schema"; @@ -34,7 +35,7 @@ import * as PendingApproval from "../../PendingApprovalMcpService.ts"; const ThreadOrganizeTool = Tool.make("t3_thread_organize", { description: - "Pin, snooze, settle, archive, or mark unread. move: file an idle No project thread into existing `projectId`; keeps its folder. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active.", + "Pin, snooze, settle, archive, or mark unread. move: file an idle No project thread into existing `projectId`; keeps its folder. Omit `threadId` for this thread. `snooze` needs `snoozedUntil`. Settling this thread applies at turn end. A failed turn or queued message leaves it active. freeze (needs `reason`): stop the run, hold the queue and delegates, start nothing until unfreeze. unfreeze: resume; `freshContext` needs an empty queue.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId), @@ -49,14 +50,30 @@ const ThreadOrganizeTool = Tool.make("t3_thread_organize", { "unarchive", "mark_unread", "move", + "freeze", + "unfreeze", ]), snoozedUntil: Schema.optional(IsoDateTime), projectId: Schema.optional(ProjectId), + reason: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(500))), + freshContext: Schema.optional(Schema.Boolean), }), success: Schema.Union([ OrchestrationV2DispatchCommandResult, Schema.Struct({ moved: Schema.Literal(true), threadIds: Schema.Array(ThreadId) }), Schema.Struct({ settlesWhenTurnEnds: Schema.Literal(true) }), + Schema.Struct({ + frozen: Schema.Literal(true), + freeze: ThreadFreeze, + interruptedRunId: Schema.NullOr(RunId), + queuedMessages: NonNegativeInt, + }), + Schema.Struct({ + frozen: Schema.Literal(false), + wasFrozen: Schema.Boolean, + queuedMessages: NonNegativeInt, + freshContextNext: Schema.optional(Schema.Literal(true)), + }), ]), failure: OrchestratorMcpFailure, failureMode: "return" as const, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8e1b677fd60ed..fc42b54e27ed9 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -132,6 +132,15 @@ import { notificationTurnItem } from "@t3tools/provider-core/server/notification import { McpApprovalAnswerContext } from "../mcp/McpApprovalAnswerContext.ts"; import { CommandActor } from "./CommandActor.ts"; import { serverRunStop } from "./RunStop.ts"; +import { + FREEZE_GATE_REFUSAL, + ThreadFreezeGate, + frozenRefusal, + liftedThread, + liftsFreeze, + ownerActor, + threadFreezePatch, +} from "./ThreadFreeze.ts"; import { quoteUserInputAnswers } from "./userInputAnswerQuotes.ts"; import { cancelledBeforeStart, @@ -2239,6 +2248,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if ( projection.thread.archivedAt !== null || projection.thread.deletedAt !== null || + projection.thread.frozen != null || projection.runs.some(isActiveRun) ) { return; @@ -4105,6 +4115,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } } + if (command.type === "thread.metadata.update" && command.frozen !== undefined) { + const gate = yield* Effect.serviceOption(ThreadFreezeGate); + if (!(Option.isSome(gate) && gate.value.op === "freeze")) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: FREEZE_GATE_REFUSAL, + }); + } + } if ( command.type === "thread.metadata.update" && command.expectedWorktreePath !== undefined && @@ -4708,6 +4728,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio return { ...thread, ...(command.title === undefined ? {} : { title: command.title }), + ...threadFreezePatch(command), ...(command.limitRecovery === undefined ? {} : { limitRecovery }), ...(command.limitRecovery !== undefined && limitRecovery?.snooze === true && @@ -7094,7 +7115,63 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "start_immediately" }; } - const freshContext = command.freshContext === true; + // A frozen thread holds every send; only a paired owner client lifts the freeze by sending. + if (projection.thread.frozen != null && !command.postOnly) { + const actor = yield* Effect.serviceOption(CommandActor); + if (Option.isSome(actor) && liftsFreeze(actor.value.kind)) { + const liftedAt = yield* DateTime.now; + projection = { + ...projection, + thread: liftedThread(projection.thread, { + by: ownerActor(actor.value), + at: DateTime.formatIso(liftedAt), + freshContext: false, + }), + }; + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: yield* DateTime.now, + payload: projection.thread, + }); + } + } + const frozenHold = projection.thread.frozen != null && !command.postOnly; + // A compaction for a thread nobody is using would only sit in its held queue until unfreeze. + if (frozenHold && command.idleCompaction !== undefined) { + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: yield* DateTime.now, + payload: projection.thread, + }); + return; + } + const consumesFreshContext = + projection.thread.nextTurnFreshContext === true && + !frozenHold && + !command.postOnly && + command.delegatedCompletion === undefined && + command.notification === undefined; + const freshContext = command.freshContext === true || consumesFreshContext; + if (consumesFreshContext) { + projection = { ...projection, thread: { ...projection.thread, nextTurnFreshContext: false } }; + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: yield* DateTime.now, + payload: projection.thread, + }); + } if ( freshContext && (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") @@ -7271,6 +7348,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } } } + if (frozenHold) { + if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { + dispatchMode = { type: "queue_after_active" }; + } + queuedRunStop = undefined; + } const dispatchText = delegatedCompletion === undefined ? command.text @@ -7404,13 +7487,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection.thread.worktreePath === null ? latestRun : undefined; - const queueBehindRun = activeRun ?? worktreeMissingRun; + // A send to a frozen idle thread queues, held, behind the last run it executed, or with no + // provider thread yet when it never ran. + const queueBehindRun = + activeRun ?? worktreeMissingRun ?? (frozenHold ? (latestRun ?? undefined) : undefined); const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection); const startsOrQueuesRun = dispatchMode.type === "defer_start" || dispatchMode.type === "start_immediately" || dispatchMode.type === "queue_after_active"; - const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun; + const shouldQueue = (queueBehindRun !== undefined || frozenHold) && startsOrQueuesRun; // An explicit pick queued ahead reaches the thread only when its run starts. A goal or // restart command that stops the active run goes first, so nothing queued applies before it. // Buffered provider wakes drain output their own provider already produced. @@ -7435,7 +7521,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (command.creationSource === "web" || command.creationSource === "mobile") && command.scheduledTaskId === undefined; const heldRunsToRelease = - sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved + sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved && !frozenHold ? projection.runs.filter((run) => run.status === "queued" && run.queueHeld === true) : []; const releasedAt = yield* DateTime.now; @@ -7462,10 +7548,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } const queueProviderThread = activeProviderThread ?? - projection.providerThreads.find( - (candidate) => candidate.id === queueBehindRun.providerThreadId, - ); - if (queueProviderThread === undefined) { + (queueBehindRun === undefined + ? undefined + : projection.providerThreads.find( + (candidate) => candidate.id === queueBehindRun.providerThreadId, + )); + if (queueProviderThread === undefined && queueBehindRun !== undefined) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, @@ -7475,11 +7563,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const now = yield* DateTime.now; const ordinal = nextRunOrdinal(projection); const runId = idAllocator.derive.run({ threadId: command.threadId, ordinal }); - const targetProviderThread = freshContext - ? undefined - : modelSelection.instanceId === queueProviderThread.providerInstanceId - ? queueProviderThread - : rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0]; + const targetProviderThread = + freshContext || queueProviderThread === undefined + ? undefined + : modelSelection.instanceId === queueProviderThread.providerInstanceId + ? queueProviderThread + : rootProviderThreadsForProvider(projection, modelSelection.instanceId)[0]; const queuedAdapter = yield* providerAdapters .get(modelSelection.instanceId) .pipe(mapDispatchError(command)); @@ -7524,7 +7613,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }); const rootNodeId = idAllocator.derive.rootNode({ runId }); const checkpointScope = - queueBehindRun.status === "preparing" || worktreeMissingRun !== undefined + queueBehindRun?.status === "preparing" || worktreeMissingRun !== undefined ? null : yield* runtimePolicy.resolve({ thread: projection.thread, modelSelection }).pipe( Effect.flatMap((resolvedRuntimePolicy) => @@ -7607,6 +7696,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio status: "queued", ...(steerWhenReadyRunId === undefined ? {} : { steerWhenReadyRunId }), ...(worktreeMissingRun !== undefined || + frozenHold || (heldRunsToRelease.length === 0 && queueIsHeld && !wakeSkipsHold && @@ -15296,6 +15386,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} is not active.`, }); } + // Resuming a frozen thread lifts the freeze in the same command, so a refused resume + // changes nothing and can be retried. Only the gated unfreeze or a paired owner client may. + const frozen = projection.thread.frozen; + let resumedThread = projection.thread; + if (frozen != null) { + const gate = yield* Effect.serviceOption(ThreadFreezeGate); + const actor = yield* Effect.serviceOption(CommandActor); + const lift = + Option.isSome(gate) && gate.value.op === "unfreeze" + ? gate.value + : Option.isSome(actor) && liftsFreeze(actor.value.kind) + ? { + by: ownerActor(actor.value), + at: DateTime.formatIso(yield* DateTime.now), + freshContext: false, + } + : undefined; + if (lift === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: frozenRefusal(frozen), + }); + } + resumedThread = liftedThread(projection.thread, lift); + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: yield* DateTime.now, + payload: resumedThread, + }); + } const selectedRunId = command.type === "queued-run.start" ? command.runId : undefined; const selectedRun = selectedRunId === undefined @@ -15349,7 +15474,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...run, queueHeld: false }, }); } - if (queued.length === 0) { + if (queued.length === 0 && frozen == null) { yield* emit( events, command, diff --git a/apps/server/src/orchestration-v2/ThreadFreeze.test.ts b/apps/server/src/orchestration-v2/ThreadFreeze.test.ts new file mode 100644 index 0000000000000..76bd773a930fa --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadFreeze.test.ts @@ -0,0 +1,343 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + MessageId, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ScheduledTaskId, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as EventStore from "./EventStore.ts"; + +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as CommandReceiptStore from "./CommandReceiptStore.ts"; +import { CommandActor } from "./CommandActor.ts"; +import { ThreadFreezeGate } from "./ThreadFreeze.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as EffectOutbox from "./EffectOutbox.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ThreadManagementService from "./ThreadManagementService.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; + +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("Runs here never reach a provider"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = ThreadManagementService.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + EventStore.layer.pipe(Layer.provide(layerDatabase)), + EffectOutbox.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "thread-freeze" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + ), + ), + Layer.provideMerge(ServerSettings.layerTest()), + Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))), +); + +const threadId = (name: string) => ThreadId.make(`thread:freeze:${name}`); +const freezeRecord = { + at: "2026-11-13T00:00:00.000Z", + by: { kind: "outside-client", label: "Codex", sessionId: "963da7fc" }, + reason: "misbehaving inbox agent", +} as const; + +const create = (id: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${id}`), + threadId: id, + projectId: ProjectId.make("project:thread-freeze"), + title: id, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + }); + +const send = ( + id: ThreadId, + text: string, + options: { + readonly mode?: "start_immediately" | "queue_after_active"; + readonly by?: "user" | "agent"; + readonly deliveryIntent?: "auto" | "steer" | "restart"; + readonly freshContext?: boolean; + } = {}, +) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + return yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send:${id}:${text}`), + threadId: id, + messageId: MessageId.make(`message:${id}:${text}`), + text, + attachments: [], + dispatchMode: { type: options.mode ?? "start_immediately" }, + ...(options.deliveryIntent === undefined ? {} : { deliveryIntent: options.deliveryIntent }), + ...(options.freshContext === true ? { freshContext: true } : {}), + createdBy: options.by ?? "user", + creationSource: options.by === "agent" ? "mcp" : "web", + }); + }); + +const freeze = (id: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* orchestrator + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`freeze:${id}`), + threadId: id, + frozen: freezeRecord, + }) + .pipe(Effect.provideService(ThreadFreezeGate, { op: "freeze" })); + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make(`freeze-stop:${id}`), + threadId: id, + reason: "Frozen", + }); + }); + +const state = (id: ThreadId) => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projection = yield* orchestrator.getThreadProjection(id); + return { + frozen: projection.thread.frozen?.by.sessionId ?? null, + runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`), + projection, + }; + }); + +const asActor = (kind: "owner_client" | "agent", effect: Effect.Effect) => + Effect.provideService(effect, CommandActor, { kind }); +const asActorEffect = + (kind: "owner_client" | "agent") => + (effect: Effect.Effect) => + asActor(kind, effect); + +it.effect( + "a freeze stops the run, holds the queue and the delegates, and records who froze it", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const id = threadId("stop"); + yield* create(id); + yield* send(id, "first"); + yield* send(id, "second", { mode: "queue_after_active" }); + const parentRun = (yield* orchestrator.getThreadProjection(id)).runs[0]!; + yield* orchestrator.dispatch({ + type: "delegated_task.request", + commandId: CommandId.make("freeze:delegate"), + parentThreadId: id, + parentRunId: parentRun.id, + parentNodeId: parentRun.rootNodeId!, + task: "child task", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + completionWake: "always", + createdBy: "agent", + creationSource: "mcp", + }); + const childId = (yield* orchestrator.getThreadProjection(id)).subagents[0]!.childThreadId!; + + yield* freeze(id); + yield* threads.stopDelegatedTasks({ + threadId: id, + commandId: CommandId.make(`freeze-stop:${id}`), + }); + + const parent = yield* state(id); + assert.equal(parent.frozen, "963da7fc"); + assert.equal(parent.projection.thread.frozen?.reason, "misbehaving inbox agent"); + assert.deepEqual(parent.runs, ["interrupted", "queued:held"]); + assert.deepEqual((yield* state(childId)).runs, ["interrupted"]); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("a frozen thread holds every send; only an owner client lifts the freeze", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const id = threadId("sends"); + yield* create(id); + yield* send(id, "first"); + yield* freeze(id); + assert.deepEqual((yield* state(id)).runs, ["interrupted"]); + + // Idle and frozen: an agent's send and a restart-mode send queue held instead of starting. + yield* send(id, "agent", { by: "agent" }); + yield* send(id, "restart", { by: "agent", deliveryIntent: "restart" }); + assert.deepEqual((yield* state(id)).runs, ["interrupted", "queued:held", "queued:held"]); + + const resume = (key: string) => + orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make(`freeze:resume:${key}`), + threadId: id, + }); + const refused = yield* asActor("agent", resume("agent")).pipe(Effect.flip); + assert.include(String("cause" in refused ? refused.cause : refused), "frozen"); + const outside = yield* resume("outside").pipe(Effect.flip); + assert.include(String("cause" in outside ? outside.cause : outside), "frozen"); + assert.equal((yield* state(id)).frozen, "963da7fc"); + + // A raw command cannot set, replace or clear the marker. + const forged = yield* orchestrator + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("freeze:forge"), + threadId: id, + frozen: { ...freezeRecord, by: { kind: "owner", label: "Chris" } }, + }) + .pipe(asActorEffect("owner_client"), Effect.flip); + assert.include(String("cause" in forged ? forged.cause : forged), "t3_thread_organize"); + assert.equal((yield* state(id)).frozen, "963da7fc"); + + yield* asActor("owner_client", send(id, "human")); + const after = yield* state(id); + assert.equal(after.frozen, null); + assert.equal(after.projection.thread.unfrozen?.by.kind, "owner"); + assert.notInclude(after.runs.slice(1), "queued:held"); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("unfreeze with freshContext starts only the next message fresh", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const id = threadId("fresh"); + yield* create(id); + yield* send(id, "first"); + yield* freeze(id); + yield* orchestrator + .dispatch({ + type: "queue.resume", + commandId: CommandId.make("freeze:unfreeze"), + threadId: id, + }) + .pipe( + Effect.provideService(ThreadFreezeGate, { + op: "unfreeze", + by: { kind: "agent", label: "Coordinator" }, + at: "2026-11-13T01:00:00.000Z", + freshContext: true, + }), + ); + const lifted = yield* state(id); + assert.equal(lifted.frozen, null); + assert.equal(lifted.projection.thread.unfrozen?.by.label, "Coordinator"); + + yield* send(id, "next"); + yield* send(id, "later", { mode: "queue_after_active" }); + const { projection } = yield* state(id); + const byText = (text: string) => + projection.runs.find( + (run) => projection.messages.find((m) => m.id === run.userMessageId)?.text === text, + ); + assert.equal(byText("next")?.freshContext, true); + assert.equal(byText("later")?.freshContext, undefined); + assert.equal(projection.thread.nextTurnFreshContext, false); + }).pipe(Effect.provide(layerTest)), +); + +it.effect( + "repeat deliveries to a frozen thread are all held, and a never-run thread starts on unfreeze", + () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const id = threadId("held"); + yield* create(id); + yield* send(id, "first"); + yield* freeze(id); + // Each delivery carries its own content, so each is kept: sendToThread needs the message back. + for (const key of ["one", "two"]) { + const result = yield* threads.sendToThread({ + projectId: ProjectId.make("project:thread-freeze"), + commandId: CommandId.make(`webhook:${id}:${key}`), + threadId: id, + messageId: MessageId.make(`message:${id}:${key}`), + scheduledTaskId: ScheduledTaskId.make("task:webhook"), + text: `payload ${key}`, + attachments: [], + mode: "auto", + createdBy: "agent", + creationSource: "server", + }); + assert.equal(result.delivery, "queued"); + assert.equal(result.run.queueHeld, true); + } + assert.deepEqual((yield* state(id)).runs, ["interrupted", "queued:held", "queued:held"]); + + const never = threadId("never"); + yield* create(never); + yield* orchestrator + .dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("freeze:never"), + threadId: never, + frozen: freezeRecord, + }) + .pipe(Effect.provideService(ThreadFreezeGate, { op: "freeze" })); + const held = yield* threads.sendToThread({ + projectId: ProjectId.make("project:thread-freeze"), + commandId: CommandId.make("send:never:waiting"), + threadId: never, + messageId: MessageId.make("message:never:waiting"), + text: "waiting", + attachments: [], + mode: "auto", + createdBy: "agent", + creationSource: "mcp", + }); + assert.equal(held.delivery, "queued"); + assert.deepEqual((yield* state(never)).runs, ["queued:held"]); + + yield* orchestrator + .dispatch({ + type: "queue.resume", + commandId: CommandId.make("freeze:never:unfreeze"), + threadId: never, + }) + .pipe( + Effect.provideService(ThreadFreezeGate, { + op: "unfreeze", + by: { kind: "agent", label: "Coordinator" }, + at: "2026-11-13T01:00:00.000Z", + freshContext: false, + }), + ); + const started = yield* state(never); + assert.equal(started.frozen, null); + assert.notInclude(started.runs[0], "queued"); + }).pipe(Effect.provide(layerTest)), +); diff --git a/apps/server/src/orchestration-v2/ThreadFreeze.ts b/apps/server/src/orchestration-v2/ThreadFreeze.ts new file mode 100644 index 0000000000000..4d919b6b3c638 --- /dev/null +++ b/apps/server/src/orchestration-v2/ThreadFreeze.ts @@ -0,0 +1,61 @@ +import type { + OrchestrationV2AppThread, + OrchestrationV2Command, + ThreadFreeze, + ThreadFreezeActor, + UserInputAnsweredBy, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; + +/** + * Proof that the command comes from the gated `t3_thread_organize` action, which has checked its + * caller like `t3_thread_interrupt` does. A raw WebSocket command never carries it, so it cannot + * set or fake a freeze marker. + */ +export class ThreadFreezeGate extends Context.Service< + ThreadFreezeGate, + | { readonly op: "freeze" } + | { + readonly op: "unfreeze"; + readonly by: ThreadFreezeActor; + readonly at: string; + readonly freshContext: boolean; + } +>()("t3/orchestration-v2/ThreadFreeze/ThreadFreezeGate") {} + +/** Only a paired owner client lifts a freeze by acting; agents and outside sign-ins must unfreeze. */ +export const liftsFreeze = (actor: UserInputAnsweredBy | undefined): boolean => + actor === "owner_client"; + +export const frozenRefusal = (freeze: ThreadFreeze): string => + `This thread is frozen by ${freeze.by.label}${ + freeze.by.sessionId === undefined ? "" : ` (${freeze.by.sessionId})` + } since ${freeze.at}: ${freeze.reason}. Unfreeze it first.`; + +export const FREEZE_GATE_REFUSAL = "A freeze is set and lifted only through t3_thread_organize."; + +/** The thread after a freeze lifts: marker cleared, who lifted it, and a fresh next turn if asked. */ +export const liftedThread = ( + thread: OrchestrationV2AppThread, + lift: { readonly by: ThreadFreezeActor; readonly at: string; readonly freshContext: boolean }, +): OrchestrationV2AppThread => ({ + ...thread, + frozen: null, + unfrozen: { at: lift.at, by: lift.by }, + ...(lift.freshContext ? { nextTurnFreshContext: true } : {}), +}); + +/** The `thread.metadata.update` field that sets the freeze marker. */ +export const threadFreezePatch = ( + command: Extract, +): Partial> => + command.frozen === undefined ? {} : { frozen: command.frozen, unfrozen: null }; + +/** The recorded actor for a paired owner client, from the transport's command actor. */ +export const ownerActor = (actor: { + readonly client?: { readonly sessionId: string; readonly clientLabel: string } | undefined; +}): ThreadFreezeActor => ({ + kind: "owner", + label: (actor.client?.clientLabel ?? "owner").slice(0, 128), + ...(actor.client === undefined ? {} : { sessionId: actor.client.sessionId }), +}); diff --git a/apps/server/src/persistence/AgentRegistry.test.ts b/apps/server/src/persistence/AgentRegistry.test.ts new file mode 100644 index 0000000000000..5825502abe9cb --- /dev/null +++ b/apps/server/src/persistence/AgentRegistry.test.ts @@ -0,0 +1,150 @@ +import { expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as Registry from "./AgentRegistry.ts"; +import * as Log from "./McpRequestLog.ts"; +import * as Sqlite from "./Sqlite.ts"; + +const DAY = 24 * 60 * 60 * 1_000; +const now = 20 * DAY; +const shared = "963da7fc-7a35-4939-b709-dfd27d40d323"; +const reconnecting = "03857f09-0d4b-4d2f-8244-3171f050721f"; +const iso = (ms: number) => DateTime.formatIso(DateTime.makeUnsafe(ms)); + +it.effect( + "lists sign-ins and thread agents, flags a sign-in used at once, and pages by recency", + () => + Effect.gen(function* () { + const registry = yield* Registry.AgentRegistry; + const log = yield* Log.McpRequestLog; + const sql = yield* SqlClient.SqlClient; + yield* TestClock.setTime(now); + const call = ( + client: string, + tool: string, + startedAt: number, + options: { readonly session?: string; readonly connection?: string } = {}, + ) => + log.record({ + client, + session: options.session ?? client, + tool, + startedAt, + connection: options.connection, + durationMs: 1, + requestBytes: 1, + responseBytes: 1, + errorClass: null, + }); + // Two connections active over the same minutes behind one sign-in. + yield* call(shared, "t3_thread_send", now - 10, { connection: "1:1" }); + yield* call(shared, "t3_thread_read", now - 20, { connection: "1:2" }); + yield* call(shared, "t3_thread_read", now - 30, { connection: "1:1" }); + yield* call(shared, "t3_thread_read", now - 25, { connection: "1:2" }); + // One agent that reconnected: its connections never overlap. + yield* call(reconnecting, "ledger_query", now - 30_000, { connection: "1:3" }); + yield* call(reconnecting, "ledger_query", now - 5, { connection: "1:4" }); + const thread = (id: string, tool: string, at: number, session: string) => + call(id, tool, at, { session }); + yield* thread("thread:frozen", "t3_thread_read", now - 40, "provider-session-1"); + yield* thread("thread:child", "ledger_upsert", now - 50, "provider-session-2"); + yield* thread("thread:cron", "ledger_query", now - 60, "provider-session-3"); + yield* thread("thread:stale", "ledger_query", now - 3 * DAY, "provider-session-4"); + + for (const [id, label] of [ + [shared, "Codex"], + [reconnecting, "Jarvis"], + ] as const) { + yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, client_label, issued_at, expires_at) + VALUES (${id}, 'mcp-client', '[]', 'bearer-access-token', ${label}, ${iso(0)}, ${iso(now + DAY)})`; + yield* sql`INSERT INTO mcp_oauth_sessions (session_id, client_id, resource, access, peer_link, offline_access) + VALUES (${id}, 'client', 'resource', 'full-access', 0, 0)`; + } + const insertThread = (id: string, title: string, payload: object) => + sql`INSERT INTO orchestration_v2_projection_threads + (thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, created_at, updated_at, payload_json) + VALUES (${id}, 'project', ${title}, 'codex', 'full-access', 'default', ${iso(0)}, ${iso(0)}, ${JSON.stringify(payload)})`; + yield* insertThread("thread:frozen", "Inbox", { frozen: { reason: "x" } }); + yield* insertThread("thread:child", "Child", { + lineage: { relationshipToParent: "subagent" }, + }); + yield* insertThread("thread:cron", "Cron", {}); + yield* insertThread("thread:stale", "Stale", {}); + yield* sql`INSERT INTO scheduled_tasks (task_id, title, prompt, enabled, schedule_json, project_id, thread_id, + workspace_strategy_json, model_selection_json, runtime_mode, interaction_mode, created_by, creation_source, + created_at, updated_at, last_run_status, run_count) + VALUES ('task', 'Cron', 'p', 1, '{}', 'project', 'thread:cron', '{}', '{}', 'full-access', 'default', 'user', 'web', + ${iso(0)}, ${iso(0)}, 'idle', 0)`; + yield* sql`INSERT INTO mcp_client_threads (thread_id, session_id, client_label, created_at) + VALUES ('thread:frozen', ${shared}, 'Codex', ${iso(0)})`; + // A sign-in past the per-sign-in cap is flagged: its run count covers only the newest threads. + for (let index = 0; index < 201; index += 1) { + yield* sql`INSERT INTO mcp_client_threads (thread_id, session_id, client_label, created_at) + VALUES (${`thread:bulk:${index}`}, ${reconnecting}, 'Jarvis', ${iso(index)})`; + } + for (const [id, threadId, at, ordinal] of [ + ["r-recent", "thread:frozen", now - 1_000, 3], + ["r-cron", "thread:cron", now - 2_000, 2], + ["r-old", "thread:frozen", now - 2 * DAY, 1], + ] as const) { + yield* sql`INSERT INTO orchestration_v2_projection_runs + (run_id, thread_id, ordinal, provider, status, requested_at, payload_json) + VALUES (${id}, ${threadId}, ${ordinal}, 'codex', 'completed', ${iso(at)}, '{}')`; + } + + const everyone = { sessionId: undefined, seesAll: true }; + // Newest call first, by log order. + const first = yield* registry.list({ limit: 3 }, everyone); + expect(first.items.map((item) => [item.id, item.kind, item.frozen])).toEqual([ + ["thread:stale", "local_thread", false], + ["thread:cron", "scheduled_task", false], + ["thread:child", "delegate", false], + ]); + expect(first.items[0]?.calls24h).toBe(0); + // The cursor is a log row number: it names no agent or sign-in. + expect(first.nextCursor).toMatch(/^\d+$/); + const second = yield* registry.list( + { limit: 3, ...(first.nextCursor === null ? {} : { cursor: first.nextCursor }) }, + everyone, + ); + expect(second.items.map((item) => [item.id, item.kind])).toEqual([ + ["thread:frozen", "local_thread"], + ["03857f09", "outside_client"], + ["963da7fc", "outside_client"], + ]); + expect(second.nextCursor).toBeNull(); + expect(second.items[0]).toMatchObject({ + frozen: true, + sessionPrefix: "provider", + runs24h: 1, + }); + expect(second.items[2]).toMatchObject({ + label: "Codex", + lastTool: "t3_thread_read", + calls24h: 4, + runs24h: 1, + connections: 2, + attribution: "shared, unattributable", + frozen: null, + }); + expect(second.items[1]).toMatchObject({ + attribution: "attributed", + connections: 2, + truncated: true, + }); + expect(second.items[2]?.truncated).toBeUndefined(); + + const own = yield* registry.list({}, { sessionId: reconnecting, seesAll: false }); + expect(own).toMatchObject({ scope: "own", items: [{ id: "03857f09" }], nextCursor: null }); + const refused = yield* registry.list({ cursor: "garbage" }, everyone).pipe(Effect.flip); + expect(refused.code).toBe("invalid_request"); + }).pipe( + Effect.provide( + Registry.layer.pipe(Layer.provideMerge(Log.layer), Layer.provideMerge(Sqlite.layerMemory)), + ), + ), +); diff --git a/apps/server/src/persistence/AgentRegistry.ts b/apps/server/src/persistence/AgentRegistry.ts new file mode 100644 index 0000000000000..d11c138e181c9 --- /dev/null +++ b/apps/server/src/persistence/AgentRegistry.ts @@ -0,0 +1,284 @@ +import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +import { OrchestratorMcpFailure, ThreadId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; + +const DAY_MS = 24 * 60 * 60 * 1_000; +const LAUNCHED_CAP = 200; + +export const RegistryInput = Schema.Struct({ + cursor: Schema.optional(Schema.String.check(Schema.isMaxLength(300))), + limit: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 50 }))), +}); +export const RegistryItem = Schema.Struct({ + /** The sign-in's session prefix, or the thread id. */ + id: Schema.String, + kind: Schema.Literals([ + "outside_client", + "linked_agent", + "local_thread", + "scheduled_task", + "delegate", + ]), + label: Schema.String, + /** First eight characters of the sign-in or provider session. */ + sessionPrefix: Schema.String, + threadId: Schema.optional(ThreadId), + lastToolAt: Schema.Number, + lastTool: Schema.String, + calls24h: Schema.Number, + /** Runs started in the last 24 hours: in the thread, or in the threads a sign-in launched. */ + runs24h: Schema.Number, + /** Null for a sign-in: only threads freeze. */ + frozen: Schema.NullOr(Schema.Boolean), + attribution: Schema.Literals(["attributed", "shared, unattributable"]), + /** MCP connections a sign-in used in the last 24h, among calls logged since connections were recorded. */ + connections: Schema.optional(Schema.Number), + /** The sign-in launched more threads than the registry counts, so `runs24h` is partial. */ + truncated: Schema.optional(Schema.Literal(true)), +}); +export const RegistryResult = Schema.Struct({ + scope: Schema.Literals(["all", "own"]), + now: Schema.Number, + items: Schema.Array(RegistryItem), + nextCursor: Schema.NullOr(Schema.String), +}); +export type RegistryCaller = { + /** Set for an outside sign-in. */ + readonly sessionId: string | undefined; + /** A thread caller or a full-access, unlinked sign-in sees every agent; others see their own row. */ + readonly seesAll: boolean; +}; + +export class AgentRegistry extends Context.Service< + AgentRegistry, + { + readonly list: ( + input: typeof RegistryInput.Type, + caller: RegistryCaller, + ) => Effect.Effect; + } +>()("t3/persistence/AgentRegistry") {} + +const storage = () => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "Could not read the agent registry.", + }); + +// The cursor is the log row id of the last agent's latest call: it names no agent or sign-in. +const parseCursor = (cursor: string | undefined) => { + if (cursor === undefined) return undefined; + const id = Number(cursor); + return Number.isSafeInteger(id) && id > 0 ? id : undefined; +}; + +const make = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const list = Effect.fn("AgentRegistry.list")(function* ( + input: typeof RegistryInput.Type, + caller: RegistryCaller, + ) { + const now = yield* Clock.currentTimeMillis; + const day = now - DAY_MS; + const dayIso = DateTime.formatIso(DateTime.makeUnsafe(day)); + const limit = input.limit ?? 20; + const cursor = parseCursor(input.cursor); + if (input.cursor !== undefined && cursor === undefined) { + return yield* new OrchestratorMcpFailure({ + code: "invalid_request", + message: "The cursor is not one this tool returned.", + }); + } + if (!caller.seesAll && caller.sessionId === undefined) { + return yield* storage(); + } + return yield* sql + .withTransaction( + Effect.gen(function* () { + const own = caller.seesAll ? sql`` : sql`AND client = ${caller.sessionId ?? ""}`; + const page = yield* sql<{ + readonly client: string; + readonly lastId: number; + readonly lastAt: number; + readonly lastTool: string; + readonly session: string; + }>`SELECT client, last_id AS "lastId", last_at AS "lastAt", last_tool AS "lastTool", + last_session AS session + FROM mcp_agent_summary + WHERE last_id < ${cursor ?? Number.MAX_SAFE_INTEGER} ${own} + ORDER BY last_id DESC LIMIT ${limit + 1}`; + const rows = page.slice(0, limit); + if (rows.length === 0) { + return { + scope: caller.seesAll ? ("all" as const) : ("own" as const), + now, + items: [], + nextCursor: null, + }; + } + const clients = rows.map((row) => row.client); + const calls = new Map( + (yield* sql<{ readonly client: string; readonly calls: number }>` + SELECT client, COUNT(*) AS calls FROM mcp_request_log + WHERE started_at >= ${day} AND ${sql.in("client", clients)} GROUP BY client`).map( + (row) => [row.client, row.calls], + ), + ); + const signIns = new Map( + (yield* sql<{ + readonly sessionId: string; + readonly label: string | null; + readonly peerLink: number | null; + }>`SELECT a.session_id AS "sessionId", a.client_label AS label, o.peer_link AS "peerLink" + FROM auth_sessions a LEFT JOIN mcp_oauth_sessions o ON o.session_id = a.session_id + WHERE ${sql.in("a.session_id", clients)}`).map((row) => [row.sessionId, row]), + ); + const threadClients = clients.filter((client) => !signIns.has(client)); + const threads = new Map( + (threadClients.length === 0 + ? [] + : yield* sql<{ + readonly threadId: string; + readonly title: string; + readonly delegate: number; + readonly frozen: number; + readonly scheduled: number; + }>`SELECT t.thread_id AS "threadId", t.title, + COALESCE(json_extract(t.payload_json, '$.lineage.relationshipToParent') = 'subagent', 0) + OR json_extract(t.payload_json, '$.delegatedFrom') IS NOT NULL AS delegate, + json_extract(t.payload_json, '$.frozen') IS NOT NULL AS frozen, + EXISTS (SELECT 1 FROM scheduled_tasks s WHERE s.thread_id = t.thread_id) + OR COALESCE((SELECT m.payload_json LIKE '%"scheduledTaskId"%' + FROM orchestration_v2_projection_messages m + WHERE m.thread_id = t.thread_id AND m.role = 'user' + ORDER BY m.created_at LIMIT 1), 0) AS scheduled + FROM orchestration_v2_projection_threads t + WHERE ${sql.in("t.thread_id", threadClients)}` + ).map((row) => [row.threadId, row]), + ); + // Threads a sign-in launched, for its run count. + const signInIds = clients.filter((client) => signIns.has(client)); + const launched = new Map>(signInIds.map((id) => [id, new Set()])); + // Connection activity windows in the last 24h: overlapping windows are agents acting at once. + const windows = new Map>( + signInIds.map((id) => [id, []]), + ); + if (signInIds.length > 0) { + // The newest threads of each sign-in, capped per sign-in; a sign-in that hits the cap + // is flagged, since its run count then covers only those threads. + for (const row of yield* sql<{ readonly sessionId: string; readonly threadId: string }>` + SELECT session_id AS "sessionId", thread_id AS "threadId" FROM ( + SELECT session_id, thread_id, + ROW_NUMBER() OVER (PARTITION BY session_id ORDER BY created_at DESC) AS newest + FROM mcp_client_threads WHERE ${sql.in("session_id", signInIds)} + ) WHERE newest <= ${LAUNCHED_CAP}`) { + launched.get(row.sessionId)?.add(row.threadId); + } + for (const row of yield* sql<{ + readonly client: string; + readonly first: number; + readonly last: number; + }>`SELECT client, MIN(started_at) AS first, MAX(started_at) AS last FROM mcp_request_log + WHERE started_at >= ${day} AND connection IS NOT NULL AND ${sql.in("client", signInIds)} + GROUP BY client, connection`) { + windows.get(row.client)?.push([row.first, row.last]); + } + } + const runThreads = [ + ...new Set([...threadClients, ...[...launched.values()].flatMap((ids) => [...ids])]), + ]; + const runs = new Map( + (runThreads.length === 0 + ? [] + : yield* sql<{ readonly threadId: string; readonly runs: number }>` + SELECT thread_id AS "threadId", COUNT(*) AS runs FROM orchestration_v2_projection_runs + WHERE requested_at >= ${dayIso} AND ${sql.in("thread_id", runThreads)} + GROUP BY thread_id` + ).map((row) => [row.threadId, row.runs]), + ); + const items = rows.map((row) => { + const base = { + lastToolAt: row.lastAt, + lastTool: row.lastTool, + calls24h: calls.get(row.client) ?? 0, + }; + const signIn = signIns.get(row.client); + if (signIn !== undefined) { + const prefix = row.client.slice(0, 8); + const reached = launched.get(row.client) ?? new Set(); + const spans = windows.get(row.client) ?? []; + const concurrent = spans.some(([first, last], index) => + spans.some( + ([otherFirst, otherLast], other) => + other > index && otherFirst <= last && first <= otherLast, + ), + ); + return { + ...base, + id: prefix, + kind: + signIn.peerLink === 1 ? ("linked_agent" as const) : ("outside_client" as const), + label: signIn.label ?? "unlabelled sign-in", + sessionPrefix: prefix, + runs24h: [...reached].reduce((sum, id) => sum + (runs.get(id) ?? 0), 0), + frozen: null, + attribution: concurrent + ? ("shared, unattributable" as const) + : ("attributed" as const), + connections: spans.length, + ...(reached.size >= LAUNCHED_CAP ? { truncated: true as const } : {}), + }; + } + const thread = threads.get(row.client); + // A sign-in logs under its own session id, so a miss in both tables is a removed sign-in. + if (thread === undefined && row.client === row.session) { + return { + ...base, + id: row.client.slice(0, 8), + kind: "outside_client" as const, + label: "removed sign-in", + sessionPrefix: row.client.slice(0, 8), + runs24h: 0, + frozen: null, + attribution: "attributed" as const, + }; + } + return { + ...base, + id: row.client, + kind: + thread === undefined + ? ("local_thread" as const) + : thread.scheduled === 1 + ? ("scheduled_task" as const) + : thread.delegate === 1 + ? ("delegate" as const) + : ("local_thread" as const), + label: thread?.title ?? "removed thread", + sessionPrefix: row.session.slice(0, 8), + threadId: ThreadId.make(row.client), + runs24h: runs.get(row.client) ?? 0, + frozen: thread === undefined ? false : thread.frozen === 1, + attribution: "attributed" as const, + }; + }); + const last = rows.at(-1)!; + return { + scope: caller.seesAll ? ("all" as const) : ("own" as const), + now, + items, + nextCursor: page.length > limit ? String(last.lastId) : null, + }; + }), + ) + .pipe(NodeSqliteClient.readOnly, Effect.mapError(storage)); + }); + return AgentRegistry.of({ list }); +}); +export const layer = Layer.effect(AgentRegistry, make); diff --git a/apps/server/src/persistence/ForkMigrations.ts b/apps/server/src/persistence/ForkMigrations.ts index 271f0fb4b53b8..7361ae531ac2f 100644 --- a/apps/server/src/persistence/ForkMigrations.ts +++ b/apps/server/src/persistence/ForkMigrations.ts @@ -15,6 +15,7 @@ import ForkMigration0010 from "./ForkMigrations/010_WorkLedgerPortfolio.ts"; import ForkMigration0011 from "./ForkMigrations/011_ForkRunExclusions.ts"; import ForkMigration0012 from "./ForkMigrations/012_WorkLedgerApproval.ts"; import ForkMigration0013 from "./ForkMigrations/013_WorkLedgerHygiene.ts"; +import ForkMigration0014 from "./ForkMigrations/014_McpRequestLogConnection.ts"; // Fork-only migrations, recorded in their own table so upstream keeps every id in // effect_sql_migrations. They run after all upstream migrations. Add new ones here, never in // Migrations.ts, and never rename one: the repair below finds old rows by name. See FORK.md. @@ -32,6 +33,7 @@ const forkMigrationEntries = [ [11, "ForkRunExclusions", ForkMigration0011], [12, "WorkLedgerApproval", ForkMigration0012], [13, "WorkLedgerHygiene", ForkMigration0013], + [14, "McpRequestLogConnection", ForkMigration0014], ] as const; export const FORK_MIGRATIONS_TABLE = "t3_fork_migrations"; diff --git a/apps/server/src/persistence/ForkMigrations/014_McpRequestLogConnection.ts b/apps/server/src/persistence/ForkMigrations/014_McpRequestLogConnection.ts new file mode 100644 index 0000000000000..122491d3370d3 --- /dev/null +++ b/apps/server/src/persistence/ForkMigrations/014_McpRequestLogConnection.ts @@ -0,0 +1,20 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + // The MCP session (a digest of Mcp-Session-Id) a call arrived on, so several agents behind one + // sign-in can be told apart. + yield* sql`ALTER TABLE mcp_request_log ADD COLUMN connection TEXT`; + // One row per caller with its latest call, so the agent registry pages without grouping the log. + yield* sql`CREATE TABLE mcp_agent_summary ( + client TEXT PRIMARY KEY, last_id INTEGER NOT NULL, last_at INTEGER NOT NULL, + last_tool TEXT NOT NULL, last_session TEXT NOT NULL + )`; + yield* sql`CREATE INDEX mcp_agent_summary_last ON mcp_agent_summary(last_id)`; + yield* sql`INSERT INTO mcp_agent_summary (client, last_id, last_at, last_tool, last_session) + SELECT client, id, started_at, tool, session FROM ( + SELECT client, id, started_at, tool, session, + ROW_NUMBER() OVER (PARTITION BY client ORDER BY id DESC) AS newest + FROM mcp_request_log + ) WHERE newest = 1`; +}); diff --git a/apps/server/src/persistence/McpRequestLog.ts b/apps/server/src/persistence/McpRequestLog.ts index 5ba01e4835177..acbd93a688969 100644 --- a/apps/server/src/persistence/McpRequestLog.ts +++ b/apps/server/src/persistence/McpRequestLog.ts @@ -39,6 +39,8 @@ interface RequestEntry { readonly requestBytes: number; readonly responseBytes: number; readonly errorClass: string | null; + /** The MCP connection of the call, when the transport has one. */ + readonly connection?: string | undefined; } export class McpRequestLog extends Context.Service< McpRequestLog, @@ -60,14 +62,19 @@ const make = Effect.gen(function* () { const prune = Effect.fn("McpRequestLog.prune")(function* () { const now = yield* Clock.currentTimeMillis; yield* sql`DELETE FROM mcp_request_log WHERE started_at < ${now - RETENTION_MS}`; + yield* sql`DELETE FROM mcp_agent_summary WHERE last_at < ${now - RETENTION_MS}`; yield* sql`DELETE FROM mcp_request_log WHERE id <= (SELECT MAX(id) - ${MAX_ROWS} FROM mcp_request_log)`; }); const record = Effect.fn("McpRequestLog.record")((entry: RequestEntry) => sql .withTransaction( Effect.gen(function* () { - yield* sql`INSERT INTO mcp_request_log (client, session, tool, started_at, duration_ms, request_bytes, response_bytes, error_class) - VALUES (${entry.client}, ${entry.session}, ${entry.tool}, ${entry.startedAt}, ${entry.durationMs}, ${entry.requestBytes}, ${entry.responseBytes}, ${entry.errorClass})`; + yield* sql`INSERT INTO mcp_request_log (client, session, tool, started_at, duration_ms, request_bytes, response_bytes, error_class, connection) + VALUES (${entry.client}, ${entry.session}, ${entry.tool}, ${entry.startedAt}, ${entry.durationMs}, ${entry.requestBytes}, ${entry.responseBytes}, ${entry.errorClass}, ${entry.connection ?? null})`; + yield* sql`INSERT INTO mcp_agent_summary (client, last_id, last_at, last_tool, last_session) + VALUES (${entry.client}, last_insert_rowid(), ${entry.startedAt}, ${entry.tool}, ${entry.session}) + ON CONFLICT(client) DO UPDATE SET last_id = excluded.last_id, last_at = excluded.last_at, + last_tool = excluded.last_tool, last_session = excluded.last_session`; yield* prune(); }), ) diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index 2341b4da9dd7b..0f7f98e867247 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -2,6 +2,7 @@ import * as Sqlite from "../persistence/Sqlite.ts"; import * as McpEvents from "../mcp/McpEvents.ts"; import * as McpBridgeMetrics from "../mcp/McpBridgeMetrics.ts"; import * as McpClientThreads from "../persistence/McpClientThreads.ts"; +import * as AgentRegistry from "../persistence/AgentRegistry.ts"; import * as McpRequestLog from "../persistence/McpRequestLog.ts"; import * as WorkLedger from "../persistence/WorkLedger.ts"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; @@ -62,6 +63,7 @@ const toolHandlerServices = Layer.mergeAll( Layer.mock(McpClientThreads.McpClientThreads)({}), Layer.mock(WorkLedger.WorkLedger)({}), Layer.mock(McpRequestLog.McpRequestLog)({}), + Layer.mock(AgentRegistry.AgentRegistry)({}), Layer.mock(AssetSigner)({}), Layer.mock(DeviceService)({}), Layer.mock(DocumentText)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index ce6d27233f0ef..a31ea110412d0 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 5597, "codexAdditionalContextBytes": 7327, - "mcpToolListJsonBytes": 57258 + "mcpToolListJsonBytes": 57928 } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index fc14ff4a6baa1..237366432d56a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -364,7 +364,11 @@ import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark"; import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers"; import { ChatRightPanel } from "./chat/ChatRightPanel"; import { useDraftEnvironmentRouting } from "./chat/useDraftEnvironmentRouting"; -import { branchMismatchBannerItem, extensionStatusBannerItem } from "./chat/ThreadActivityBanners"; +import { + branchMismatchBannerItem, + extensionStatusBannerItem, + frozenBannerItem, +} from "./chat/ThreadActivityBanners"; import { ThreadNow } from "./chat/ThreadNow"; import type { ThreadStructure } from "@t3tools/client-runtime/state/shell"; import { useDelayedStatus } from "../hooks/useDelayedStatus"; @@ -2606,6 +2610,8 @@ export default function ChatView(props: ChatViewProps) { deriveProviderExtensionStatuses(serverProjection), ); const extensionStatusItems = extensionStatusBanner === null ? [] : [extensionStatusBanner]; + const frozen = serverProjection?.thread.frozen; + const frozenItems = frozen == null ? [] : [frozenBannerItem(frozen)]; const usageLimitsItems = usageLimitsBanner === null ? [] : [usageLimitsBanner]; const projectCloneItems = projectCloneBannerItem === null ? [] : [projectCloneBannerItem]; // An approval's feedback goes to that approval; the armed session waits for the next message. @@ -2615,6 +2621,7 @@ export default function ChatView(props: ChatViewProps) { : []; if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) { return [ + ...frozenItems, ...feedbackBannerItems, ...fallbackItems, ...limitRecoveryItems, @@ -2626,6 +2633,7 @@ export default function ChatView(props: ChatViewProps) { ]; } return [ + ...frozenItems, ...feedbackBannerItems, ...fallbackItems, ...limitRecoveryItems, diff --git a/apps/web/src/components/chat/ThreadActivityBanners.tsx b/apps/web/src/components/chat/ThreadActivityBanners.tsx index b12a6d1ae63b4..3edc98346988a 100644 --- a/apps/web/src/components/chat/ThreadActivityBanners.tsx +++ b/apps/web/src/components/chat/ThreadActivityBanners.tsx @@ -3,9 +3,11 @@ import type { OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderGoal, OrchestrationV2ProviderSession, + ThreadFreeze, ThreadId, } from "@t3tools/contracts"; import type { EnvironmentThreadShell, ThreadStructure } from "@t3tools/client-runtime/state/shell"; +import { describeThreadFreeze } from "@t3tools/client-runtime/state/thread-workflows"; import { presentPendingBackgroundWork, presentProviderGoal, @@ -33,6 +35,16 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import type { ComposerBannerStackItem } from "./ComposerBannerStack"; import type { ThreadNowItem } from "./ThreadNow"; +export function frozenBannerItem(freeze: ThreadFreeze): ComposerBannerStackItem { + return { + id: "thread-frozen", + variant: "warning", + icon: , + title: {describeThreadFreeze(freeze)}, + description: "Nothing runs until it is unfrozen. Sending a message here lifts the freeze.", + }; +} + export function extensionStatusBannerItem( statuses: NonNullable, ): ComposerBannerStackItem | null { diff --git a/docs/jarvis/GLOSSARY.md b/docs/jarvis/GLOSSARY.md index 2f172377a523d..a6a9f54da6575 100644 --- a/docs/jarvis/GLOSSARY.md +++ b/docs/jarvis/GLOSSARY.md @@ -48,3 +48,9 @@ The one set of questions an agent asks Chris before a task starts. His answers a **completion supervisor**: The scheduled task that re-drives idle ledger work every 30 minutes and posts a digest to Jarvis's inbox. + +**frozen thread**: +A thread an operator has stopped and held: its run is interrupted, its queue and delegates are held, and it starts nothing until it is unfrozen or its owner acts. + +**shared, unattributable**: +A sign-in whose calls arrive on overlapping MCP sessions, so several agents are acting through it at once and its calls cannot be tied to one. diff --git a/docs/jarvis/decisions/0018-freeze-and-agent-registry.md b/docs/jarvis/decisions/0018-freeze-and-agent-registry.md new file mode 100644 index 0000000000000..68d44c17f1fa1 --- /dev/null +++ b/docs/jarvis/decisions/0018-freeze-and-agent-registry.md @@ -0,0 +1,34 @@ +# Freeze a thread and list the agents + +Accepted 2026-11-13. Builds on [0013](0013-server-recorded-message-senders.md), [0015](0015-server-verified-approvals.md) and the MCP visibility record in [visibility-and-fleet](visibility-and-fleet.md). + +## Decision + +**Freeze.** `t3_thread_organize` takes `freeze` (with a `reason`) and `unfreeze`. + +- Freeze records a marker on the thread (`frozen`: time, who, reason), then does what `t3_thread_interrupt` with `stop` already does: interrupt the run, hold the queue, stop delegated tasks. `t3_thread_read` returns the marker and clients show it. "Who" comes from the authenticated caller, never from an argument: the outside sign-in's label and session prefix, or the calling thread. +- The marker is set and lifted only through the gated action. It runs the same caller checks as interrupt (write access to the target within the caller's mode limits, and a live calling thread) and passes a `ThreadFreezeGate` to the orchestrator. A raw `thread.metadata.update` carrying `frozen`, from any WebSocket session including a bot session, is refused, so nobody can clear a marker or fake who set it. +- A frozen thread starts nothing. Queued messages stay and stay held. A new send from an agent, scheduled task, webhook, notification, delegated result or restart-mode send is queued held, behind the last executed run, or with no provider thread yet when the thread never ran. Every delivery is kept, since each carries its own content; only idle compaction is dropped. Starting a queued run is refused while the marker is set. +- Unfreeze is one `queue.resume` that lifts the marker and releases the queue together. A refused resume (a usage limit, say) changes nothing, so the call can be repeated. The thread records who lifted it (`unfrozen`) until its next freeze. +- Who may lift it: the operator's paired owner client, by sending or pressing Resume (the transport's command actor `owner_client`, which a client cannot claim; a `t3 auth session` bot is not one), or another thread or sign-in through `unfreeze`. A frozen thread cannot unfreeze itself and a delegate cannot unfreeze its parent. A thread may freeze itself; only its coordinator or the operator can then lift it. The upstream desktop app has no frozen indicator, so its owner needs the way out through a send. +- `freshContext` on unfreeze makes the next message that starts a run use a fresh provider context. It is refused while messages are queued, because they would start first on the old context; cancel them with `t3_queue`. + +**Registry.** `agent_registry` lists the agents that called this server in the last 14 days, from `mcp_request_log`, sign-ins, threads and scheduled tasks. Each row has kind (`outside_client`, `linked_agent`, `local_thread`, `scheduled_task`, `delegate`), label, session prefix, last tool and time, calls and runs in 24 hours, and whether the thread is frozen. A small `mcp_agent_summary` table (one row per caller, kept by the request log) gives the pages, so a page never aggregates the log. The cursor is a log row number and names no agent. + +- Each call records its MCP connection: a digest of the `Mcp-Session-Id` the transport assigns at initialize and the client echoes. A sign-in whose calls arrive on two or more connections active in overlapping time is `shared, unattributable`: several agents act through it at once, so its calls cannot be tied to one. Parallel calls on one session count once; a sequential reconnect does not overlap. Calls logged before the connection migration have no connection, so the flag fills in after the update. +- Full-access sign-ins and thread callers see every agent; other sign-ins see only their own row. Session prefixes only, no ids, secrets or bodies. + +## Alternatives + +- A new `thread.freeze` command and event: touches every command and event switch for no gain over the existing `thread.metadata.update` event. +- Freeze state in a fork table: simpler to merge, but clients would not see it without a new feed. +- Refuse sends to a frozen thread: loses delegated results and scheduled runs; held queueing keeps them. +- Count the threads a sign-in reaches as sharing: it flagged a coordinator that drives many threads and missed the shared Codex sign-in. The MCP client id the transport gives each request does not name a connection either, so it is not the key. + +## Why + +Containing one misbehaving inbox agent took four calls, because a send in restart mode did not interrupt the running turn and the queue had to be reordered first. Nobody could tell which agent was acting: its messages came through a Codex sign-in that several agents share. One call now stops the thread durably and records who did it, and the registry shows which sign-ins several agents share, so a containment can name its target. + +## Limits + +A full-access agent on the host can still send a bot WebSocket session's `queue.resume`, which an agent cannot lift a freeze with, but it can run the gated tool as itself; 0015 records the same residual for approvals. `queued-message.promote-to-steer` is not gated: it needs an active run, and freeze stops it. diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index 74012f436318b..85a873c48a0d7 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -98,6 +98,7 @@ function queueWorkflowStatesEqual( return ( left.activeRun === right.activeRun && left.isHeld === right.isHeld && + left.frozen === right.frozen && left.canSendNow === right.canSendNow && left.canPromoteToSteer === right.canPromoteToSteer && left.promoteSkipsCompaction === right.promoteSkipsCompaction && diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index c96090427c4fd..91c683d050b47 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -3,6 +3,7 @@ import { isCompactionCommandMessage, type OrchestrationV2ProjectedTurnItem, type OrchestrationV2ProviderCapabilities, + type ThreadFreeze, } from "@t3tools/contracts"; import { copySorted } from "@t3tools/shared/Array"; @@ -31,10 +32,19 @@ export interface QueuedThreadRun { readonly message?: Message; } +/** One line for the frozen indicator, shared by web and mobile. */ +export function describeThreadFreeze(freeze: ThreadFreeze): string { + return `Frozen by ${freeze.by.label}${ + freeze.by.sessionId === undefined ? "" : ` (${freeze.by.sessionId})` + }: ${freeze.reason}`; +} + export interface ThreadQueueWorkflowState { readonly activeRun: Run | null; readonly queuedRuns: ReadonlyArray; readonly isHeld: boolean; + /** Set while the thread is frozen: nothing starts until it is unfrozen or the owner resumes. */ + readonly frozen: ThreadFreeze | null; readonly canPromoteToSteer: boolean; /** The active run is a compaction, so promoting a queued message stops it instead of steering. */ readonly promoteSkipsCompaction: boolean; @@ -173,6 +183,7 @@ export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQu activeRun, queuedRuns, isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true), + frozen: projection.thread.frozen ?? null, canSendNow: activeRun === null && projection.thread.archivedAt == null && diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 7fe7455d56dd2..3d37729ec3d2f 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -75,4 +75,5 @@ export * from "./secretReference.ts"; export * from "./settingsSecretValue.ts"; export * from "./clientRpcPermissions.ts"; +export * from "./threadFreeze.ts"; export * from "./workLedger.ts"; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 5e2cc81d19d1b..7e386baf1d6d0 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1,5 +1,6 @@ import { OrchestrationMessageContext } from "./composerContext.ts"; import { withRecordIdTable } from "./orchestrationV2IdTable.ts"; +import { ThreadFreeze, ThreadUnfreeze } from "./threadFreeze.ts"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -528,6 +529,12 @@ export const OrchestrationV2AppThread = Schema.Struct({ }), ), ), + /** Set while an operator has frozen the thread: no run starts until it is lifted. */ + frozen: Schema.optional(Schema.NullOr(ThreadFreeze)), + /** Who lifted the last freeze. */ + unfrozen: Schema.optional(Schema.NullOr(ThreadUnfreeze)), + /** Set by an unfreeze: the next message that starts a run starts on a fresh provider context. */ + nextTurnFreshContext: Schema.optional(Schema.Boolean), deletedAt: Schema.NullOr(Schema.DateTimeUtc), }); export type OrchestrationV2AppThread = typeof OrchestrationV2AppThread.Type; @@ -3255,6 +3262,8 @@ export const OrchestrationV2Command = Schema.Union([ limitRecovery: Schema.optional(Schema.NullOr(OrchestrationV2LimitRecoveryUpdate)), /** Link (object) or unlink (null) a pull request; absent leaves it unchanged. */ linkedPullRequest: Schema.optional(Schema.NullOr(ThreadLinkedPullRequest)), + /** Freeze the thread. Only `t3_thread_organize` may set it; lifting goes through `queue.resume`. */ + frozen: Schema.optional(ThreadFreeze), }), Schema.Struct({ type: Schema.Literal("thread.pull-request.link"), diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index 4a2706f09d4cf..1a906ea560381 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -35,6 +35,7 @@ import { } from "./threadPullRequest.ts"; import { secretRequestPageUrl } from "./secretRequest.ts"; import { hasOnlyPairedSurrogates } from "./threadMetadataMcp.ts"; +import { ThreadFreeze } from "./threadFreeze.ts"; import { ThreadTitleRegeneration } from "./threadTitle.ts"; import { OrchestrationV2SenderClient, @@ -473,6 +474,8 @@ export const OrchestratorMcpThreadDetail = Schema.Struct({ settledAt: Schema.NullOr(IsoDateTime), snoozed: Schema.Boolean, snoozedUntil: Schema.NullOr(IsoDateTime), + /** Set while the thread is frozen. Omitted by an environment on an older build. */ + frozen: Schema.optional(Schema.NullOr(ThreadFreeze)), createdAt: IsoDateTime, updatedAt: IsoDateTime, }); @@ -609,6 +612,10 @@ export const OrchestratorMcpThreadSendResult = Schema.Struct({ taskId: Schema.optional(NodeId), status: OrchestrationV2RunStatus, delivery: Schema.Literals(["started", "queued", "steered", "restarted"]), + /** Set when the queued message is held: it starts only after the thread is unfrozen or resumed. */ + held: Schema.optional(Schema.Literal(true)), + /** Set when a freeze holds the send. */ + frozen: Schema.optional(Schema.Literal(true)), }); export type OrchestratorMcpThreadSendResult = typeof OrchestratorMcpThreadSendResult.Type; diff --git a/packages/contracts/src/threadFreeze.ts b/packages/contracts/src/threadFreeze.ts new file mode 100644 index 0000000000000..3cc5aa3126c6d --- /dev/null +++ b/packages/contracts/src/threadFreeze.ts @@ -0,0 +1,23 @@ +import * as Schema from "effect/Schema"; + +import { IsoDateTime, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** Who froze a thread, from the authenticated caller and never from a tool argument. */ +export const ThreadFreezeActor = Schema.Struct({ + kind: Schema.Literals(["owner", "outside-client", "linked-agent", "agent", "unknown"]), + label: Schema.String.check(Schema.isMaxLength(128)), + /** First eight characters of the sign-in session, as in a message's `senderClient`. */ + sessionId: Schema.optional(Schema.String.check(Schema.isMaxLength(8))), + threadId: Schema.optional(ThreadId), +}); +export type ThreadFreezeActor = typeof ThreadFreezeActor.Type; + +export const ThreadFreeze = Schema.Struct({ + at: IsoDateTime, + by: ThreadFreezeActor, + reason: TrimmedNonEmptyString.check(Schema.isMaxLength(500)), +}); +export type ThreadFreeze = typeof ThreadFreeze.Type; + +/** Who lifted the last freeze, kept on the thread until the next one. */ +export const ThreadUnfreeze = Schema.Struct({ at: IsoDateTime, by: ThreadFreezeActor });