diff --git a/apps/server/src/auth/settleActor.test.ts b/apps/server/src/auth/settleActor.test.ts new file mode 100644 index 0000000000000..250cba96ae064 --- /dev/null +++ b/apps/server/src/auth/settleActor.test.ts @@ -0,0 +1,59 @@ +import { AuthSessionId } from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; + +import { settleActorOf } from "./settleActor.ts"; + +const sessionId = AuthSessionId.make("settle-actor-session"); +const pairedBrowser = { + sessionId, + device: "Chrome", + deviceType: "desktop", + founder: null, +} as const; + +describe("settleActorOf", () => { + it("names a person's assigned client session as its founder", () => { + expect( + settleActorOf( + { sessionId, device: "Laptop", deviceType: "desktop", founder: "kameron" }, + "one-time-token", + true, + ), + ).toEqual({ kind: "founder", founder: "kameron", sessionId, client: "Laptop" }); + }); + + it("names the desktop app's own bootstrap session a founder before an owner is set", () => { + expect( + settleActorOf( + { sessionId, device: "", deviceType: "desktop", founder: null }, + "desktop-bootstrap", + true, + ).kind, + ).toBe("founder"); + }); + + it("names a bot's session as an agent, so a founder's inbox refuses its settle", () => { + expect( + settleActorOf({ sessionId, device: "", deviceType: "bot", founder: null }, "bot", false), + ).toEqual({ kind: "agent", founder: null, sessionId }); + }); + + it("names an unknown or failed sender read an agent", () => { + expect( + settleActorOf({ sessionId, device: "", deviceType: "unknown", founder: null }, "x", false) + .kind, + ).toBe("agent"); + expect( + settleActorOf( + { sessionId, device: "", deviceType: "unknown", founder: "kameron" }, + "desktop-bootstrap", + false, + ).kind, + ).toBe("agent"); + }); + + it("names an unassigned paired person session a founder unless founder identity is required", () => { + expect(settleActorOf(pairedBrowser, "one-time-token", false).kind).toBe("founder"); + expect(settleActorOf(pairedBrowser, "one-time-token", true).kind).toBe("agent"); + }); +}); diff --git a/apps/server/src/auth/settleActor.ts b/apps/server/src/auth/settleActor.ts new file mode 100644 index 0000000000000..1a97a94eddd69 --- /dev/null +++ b/apps/server/src/auth/settleActor.ts @@ -0,0 +1,23 @@ +import type { OrchestrationV2CommandActor, OrchestrationV2MessageSentBy } from "@t3tools/contracts"; + +const PERSON_DEVICES = new Set(["desktop", "mobile", "tablet"]); + +/** + * Settles as a founder only from a person's device type; an unknown or failed sender read settles + * as an agent, so a founder's inbox refuses it. Under `requireFounderIdentity` the session must + * also be enrolled: an assigned founder or the desktop app's own bootstrap session. + */ +export const settleActorOf = ( + sentBy: OrchestrationV2MessageSentBy, + sessionSubject: string, + requireFounderIdentity: boolean, +): OrchestrationV2CommandActor => ({ + kind: + PERSON_DEVICES.has(sentBy.deviceType) && + (!requireFounderIdentity || sentBy.founder !== null || sessionSubject === "desktop-bootstrap") + ? "founder" + : "agent", + founder: sentBy.founder, + sessionId: sentBy.sessionId, + ...(sentBy.device === "" ? {} : { client: sentBy.device }), +}); diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 099f0f15abf4a..9c3d82a98b891 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -701,6 +701,55 @@ it.effect("rejects an unknown organize target instead of archiving the calling t ); }); +it.effect("settles through organize as an agent, on its own thread or another", () => { + const settles: Array< + Parameters[0] + > = []; + return Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const settle = (invocation: McpInvocationContext.McpInvocationScope, target?: string) => + server + .callTool({ + name: "t3_thread_organize", + arguments: { action: "settle", ...(target === undefined ? {} : { threadId: target }) }, + }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + expect((yield* settle(scope)).isError).toBe(false); + expect((yield* settle(clientScope("full-access"), "other-thread")).isError).toBe(false); + expect(settles).toMatchObject([ + { threadId, byOwnAgent: true, actor: { kind: "agent", agentThreadId: threadId } }, + { + threadId: "other-thread", + byOwnAgent: false, + actor: { kind: "agent", client: "Claude Code" }, + }, + ]); + }).pipe( + Effect.provide( + layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide( + Layer.mock(ThreadManagement.ThreadManagementService)({ + getThreadShell: (id) => Effect.succeed(McpToolAccessTestkit.liveThreadShell(id)), + getProjectThreadRecords: ({ threadId: id }) => + Effect.succeed( + McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)), + ), + settleThread: (input) => { + settles.push(input); + return Effect.succeed({ sequence: 1 }); + }, + }), + ), + ), + ), + ); +}); + it.effect("keeps unexpected handler defects private through the production registration", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index fced6484e2bee..10743a48c7bf6 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -413,11 +413,20 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { ), t3_thread_organize: writesThread((input) => Effect.gen(function* () { - const { threads, projection, caller } = yield* readThread(input.threadId); + const { threads, projection, caller, scope } = yield* readThread(input.threadId); const common = { commandId: yield* newCommandId(), threadId: projection.thread.id }; if (input.action === "settle") { + // Every MCP caller is an agent, a linked environment's included. return yield* threads - .settleThread({ ...common, byOwnAgent: caller?.id === projection.thread.id }) + .settleThread({ + ...common, + byOwnAgent: caller?.id === projection.thread.id, + actor: { + kind: "agent", + ...(caller === undefined ? {} : { agentThreadId: caller.id }), + ...(scope.client === undefined ? {} : { client: scope.client.label }), + }, + }) .pipe(Effect.mapError(dispatchFailure)); } let command: OrchestrationV2Command; diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index b71a922a95a8a..b0117b7df562d 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -33,7 +33,7 @@ import * as McpInvocationContext from "../../McpInvocationContext.ts"; const ThreadOrganizeTool = Tool.make("t3_thread_organize", { description: - "Organize this thread by default. `snooze` needs `snoozedUntil`. Self-settle waits for turn end; failure or a queued message keeps it active.", + "Organize this thread by default. `snooze` needs `snoozedUntil`. Self-settle waits for turn end; failure or a queued message keeps it active. A thread in a founder or Shared inbox refuses settle: leave it for the founder.", parameters: Schema.Struct({ environmentId: OrchestratorMcpEnvironmentTarget, threadId: Schema.optional(ThreadId), diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 29063a75ddb61..055108f38e30b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -24,6 +24,7 @@ import { RuntimeRequestId, ThreadId, TurnItemId, + makeThreadInbox, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; @@ -2511,6 +2512,7 @@ it.effect.each(["thread.settle", "thread.auto-settle"] as const)( payload: { ...before, id: childId, + inbox: makeThreadInbox({ actor: null }), lineage: { parentThreadId: threadId, rootThreadId: threadId, @@ -2534,6 +2536,13 @@ it.effect.each(["thread.settle", "thread.auto-settle"] as const)( threadId, standing: null, }); + // A persona files the thread for the founders; only once it is back in Agents may it settle. + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("standing-root:to-agents"), + threadId, + inboxRouting: { owner: null, assignee: null, audience: "agent-only" }, + }); const retired = yield* projections.getThread(threadId); yield* orchestrator.dispatch({ type, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index aa2babc0b6341..8e958e4c47a92 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -9,6 +9,8 @@ import type { } from "@t3tools/contracts"; import { inboxAfterStandingSet, + founderInboxHolder, + founderInboxSettleRefusal, isStandingThreadRoot, makeThreadInbox, nextFounderSeenMessage, @@ -5622,6 +5624,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio "Standing role threads cannot be settled. Clear its standing persona before settling.", }); } + // Every settle path reaches here, a deferred settle-after-run included, so it re-checks now. + // Project decisionRequest through the shell when present so answered asks don't linger. + const projectedShell = + thread.inbox?.decisionRequest !== undefined + ? yield* projectionStore.getThreadShell(command.threadId).pipe(mapDispatchError(command)) + : null; + const inboxHolder = founderInboxHolder(projectedShell?.inbox ?? thread.inbox); + if (inboxHolder !== null && command.actor?.kind !== "founder") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: founderInboxSettleRefusal(inboxHolder), + }); + } const projection = yield* loadProjectionForCommand( command, ["runs", "runtimeRequests", "providerThreads", "turnItems"], @@ -6678,6 +6694,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio providerInstanceId: updatedThread.providerInstanceId, occurredAt: now, payload: updatedThread, + ...(command.type === "thread.settle" && command.actor !== undefined + ? { actor: command.actor } + : {}), }); // Archiving ends the guest share, so its waiting files go too. yield* releaseGuestAttachments(command, thread.guestShare, updatedThread.guestShare, effects); @@ -17676,6 +17695,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio type: "thread.settle", commandId: command.commandId, threadId: command.threadId, + actor: { kind: "server" }, ...(command.settledAt === undefined ? {} : { settledAt: command.settledAt }), }, events, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 2365a74894ff3..aa5473a9cbbe8 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -1,7 +1,10 @@ import * as SecureRandom from "effect/crypto/SecureRandom"; import { BACKGROUND_WAIT_STALE_MINUTES, + founderInboxHolder, + founderInboxSettleRefusal, isStandingThreadRoot, + type OrchestrationV2CommandActor, ThreadRedirectError, } from "@t3tools/contracts"; import { staleTimeoutMs } from "./waitStaleness.ts"; @@ -590,11 +593,15 @@ export interface ThreadManagementServiceShape { readonly projectId: ProjectId; readonly threadId: ThreadId; readonly runId: RunId; + /** Who asked; absent means the server. A founder inbox refuses any but a founder. */ + readonly actor?: OrchestrationV2CommandActor; }) => Effect.Effect; + /** Refuses at once when a founder's inbox holds the thread and `actor` is not a founder. */ readonly settleThread: (input: { readonly threadId: ThreadId; readonly commandId: CommandId; readonly byOwnAgent: boolean; + readonly actor: OrchestrationV2CommandActor; }) => Effect.Effect< { readonly sequence: number } | { readonly settlesWhenTurnEnds: true }, Orchestrator.OrchestratorV2Error | ThreadManagementProviderInstanceDisabledError @@ -1473,6 +1480,16 @@ const make = Effect.gen(function* () { ) ) return true; + // A founder's inbox took the thread while the turn ran; the dispatch would refuse it. + const projectedInbox = + records.thread.inbox?.decisionRequest !== undefined + ? (yield* orchestrator.getThreadShell(input.threadId))?.inbox + : undefined; + if ( + founderInboxHolder(projectedInbox ?? records.thread.inbox) !== null && + input.actor?.kind !== "founder" + ) + return true; const later = records.runs.filter((candidate) => candidate.ordinal > run.ordinal); const cancelledMessageIds = later .filter((candidate) => candidate.status === "cancelled") @@ -1536,6 +1553,7 @@ const make = Effect.gen(function* () { commandId: CommandId.make(`server:settle-after-run:${input.runId}:${sequence}`), threadId: input.threadId, expectedLatestRunId: latest.id, + actor: input.actor ?? { kind: "server" }, }).pipe( Effect.as(true), // A notification can start between the projection read and the guarded dispatch. @@ -1564,12 +1582,28 @@ const make = Effect.gen(function* () { const settleThread: ThreadManagementServiceShape["settleThread"] = Effect.fn( "orchestrationV2.threadManagement.settleThread", )(function* (input) { - const shell = input.byOwnAgent ? yield* orchestrator.getThreadShell(input.threadId) : null; - if (shell != null && shell.activeRunId !== null && !isStandingThreadRoot(shell)) { + const shell = yield* orchestrator.getThreadShell(input.threadId); + const inboxHolder = + shell != null && isStandingThreadRoot(shell) ? null : founderInboxHolder(shell?.inbox); + // Refuse before deferring, so an agent learns now instead of at a settle that never lands. + if (inboxHolder !== null && input.actor.kind !== "founder") { + return yield* new Orchestrator.OrchestratorDispatchError({ + commandId: input.commandId, + commandType: "thread.settle", + cause: founderInboxSettleRefusal(inboxHolder), + }); + } + if ( + input.byOwnAgent && + shell != null && + shell.activeRunId !== null && + !isStandingThreadRoot(shell) + ) { yield* settleAfterRun({ projectId: shell.projectId, threadId: shell.id, runId: shell.activeRunId, + actor: input.actor, }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(layerScope)); return { settlesWhenTurnEnds: true } as const; } @@ -1577,6 +1611,7 @@ const make = Effect.gen(function* () { type: "thread.settle", commandId: input.commandId, threadId: input.threadId, + actor: input.actor, }); return { sequence: result.sequence }; }); diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index d86583515ddad..554cad09c3d44 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -9,6 +9,7 @@ import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { CommandId, isDelegatedAppThread, + founderInboxHolder, isStandingThreadRoot, isOrchestrationV2WorkActive, type ThreadId, @@ -202,17 +203,13 @@ export function settlesFinishedAgentWork( return !agentBackgroundWorkPending(thread); } -const HUMAN_INBOX_AUDIENCES = new Set(["kameron", "jeff", "shared"]); - export function isAutoSettlementCandidate( thread: Omit, nowMs: number, ): boolean { if (thread.archivedAt !== null || thread.settledOverride !== null) return false; if (thread.pinnedAt != null || thread.autoSettleDisabledAt != null) return false; - if (thread.inbox?.audience !== undefined && HUMAN_INBOX_AUDIENCES.has(thread.inbox.audience)) { - return false; - } + if (founderInboxHolder(thread.inbox) !== null) return false; if (thread.inbox?.audience === "agent-only" && thread.status === "failed") return false; if (isStandingThreadRoot(thread)) return false; if (thread.pendingRuntimeRequest !== null) return false; diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 1484008ecbe2f..6eb35e9357ecb 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -30,6 +30,7 @@ import { CommandId, ContextTransferId, EnvironmentId, + AuthSessionId, EventId, IssueTrackerKind, MessageId, @@ -3909,6 +3910,12 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { standing: null, }); assert.isUndefined(shellOf(yield* orchestrator.getShellSnapshot()).standing ?? undefined); + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("runtime-layer-lifecycle-to-agents"), + threadId, + inboxRouting: { owner: null, assignee: null, audience: "agent-only" }, + }); const preAutoProjection = yield* orchestrator.getThreadProjection(threadId); const staleAutoSettle = yield* orchestrator @@ -9372,6 +9379,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { threadId, commandId: CommandId.make("runtime-layer-settle-after-run-settle"), byOwnAgent: true, + actor: { kind: "agent", agentThreadId: threadId }, }); assert.deepEqual(result, { settlesWhenTurnEnds: true }); assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); @@ -9389,10 +9397,186 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }, ], }); - yield* Fiber.join(settled); + const settledEvent = yield* Fiber.join(settled); const projection = yield* orchestrator.getThreadProjection(threadId); assert.equal(projection.thread.settledOverride, "settled"); + assert.deepEqual(Option.getOrThrow(settledEvent).event.actor, { + kind: "agent", + agentThreadId: threadId, + }); + }), + ); + + const startFounderInboxRun = Effect.fn(function* (name: string) { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projectId = ProjectId.make(`runtime-layer-${name}-project`); + const threadId = ThreadId.make(`runtime-layer-${name}-thread`); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-${name}-create`), + threadId, + projectId, + title: "Founder inbox settle", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: `/tmp/runtime-layer-${name}`, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make(`runtime-layer-${name}-message`), + threadId, + messageId: MessageId.make(`runtime-layer-${name}-message`), + text: "Work through this with me.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const fileForKameron = orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make(`runtime-layer-${name}-inbox`), + threadId, + inboxRouting: { audience: "kameron", reason: "conversation" }, + }); + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]; + if (run === undefined) return yield* Effect.die(new Error("Run missing.")); + const completeRun = Effect.gen(function* () { + const eventSink = yield* EventSink.EventSinkV2; + const now = yield* DateTime.now; + yield* eventSink.write({ + commandId: CommandId.make(`runtime-layer-${name}-completed`), + events: [ + { + id: EventId.make(`runtime-layer-${name}-completed`), + type: "run.updated", + threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: "completed", startedAt: now, completedAt: now }, + }, + ], + }); + }); + return { projectId, threadId, run, fileForKameron, completeRun }; + }); + + it.effect("refuses an agent settling its own thread in a founder's inbox", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const { threadId, fileForKameron } = yield* startFounderInboxRun("founder-self-settle"); + yield* fileForKameron; + + const refused = yield* threadManagement + .settleThread({ + threadId, + commandId: CommandId.make("mcp:runtime-layer-founder-self-settle"), + byOwnAgent: true, + actor: { kind: "agent", agentThreadId: threadId }, + }) + .pipe(Effect.flip); + assert.equal(refused._tag, "OrchestratorDispatchError"); + assert.equal( + refused._tag === "OrchestratorDispatchError" ? refused.cause : undefined, + "Thread is in kameron's inbox; only the founder settles it.", + ); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + }), + ); + + it.effect("refuses an agent settling another thread in a founder's inbox", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const { threadId, fileForKameron, completeRun } = + yield* startFounderInboxRun("founder-cross-settle"); + yield* fileForKameron; + yield* completeRun; + + const refused = yield* threadManagement + .settleThread({ + threadId, + commandId: CommandId.make("mcp:runtime-layer-founder-cross-settle"), + byOwnAgent: false, + actor: { kind: "agent", agentThreadId: ThreadId.make("some-other-agent-thread") }, + }) + .pipe(Effect.flip); + assert.equal(refused._tag, "OrchestratorDispatchError"); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + }), + ); + + it.effect("drops a settle-after-run once a founder's inbox holds the thread", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const threadManagement = yield* ThreadManagementService.ThreadManagementService; + const { projectId, threadId, run, fileForKameron, completeRun } = yield* startFounderInboxRun( + "founder-settle-after-run", + ); + + // Requested while the thread was still in Agents, then filed for Kameron mid-turn. + const deferred = yield* threadManagement + .settleAfterRun({ + projectId, + threadId, + runId: run.id, + actor: { kind: "agent", agentThreadId: threadId }, + }) + .pipe(Effect.forkChild); + yield* fileForKameron; + yield* completeRun; + yield* Fiber.join(deferred); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + + // The dispatch guard holds even when the deferred settle reaches it. + const refused = yield* orchestrator + .dispatch({ + type: "thread.settle", + commandId: CommandId.make(`server:settle-after-run:${run.id}:1`), + threadId, + expectedLatestRunId: run.id, + actor: { kind: "agent", agentThreadId: threadId }, + }) + .pipe(Effect.flip); + assert.equal(refused._tag, "OrchestratorDispatchError"); + assert.isNull((yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride); + }), + ); + + it.effect("lets a founder's client settle a thread in their inbox and records who did", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const { threadId, fileForKameron, completeRun } = + yield* startFounderInboxRun("founder-ui-settle"); + yield* fileForKameron; + yield* completeRun; + const actor = { + kind: "founder", + founder: "kameron", + sessionId: AuthSessionId.make("runtime-layer-founder-ui-session"), + client: "Kameron's laptop", + } as const; + + yield* orchestrator.dispatch({ + type: "thread.settle", + commandId: CommandId.make("runtime-layer-founder-ui-settle"), + threadId, + actor, + }); + assert.equal( + (yield* orchestrator.getThreadProjection(threadId)).thread.settledOverride, + "settled", + ); + const stored = yield* orchestrator + .streamStoredEventsFrom({ threadId, afterSequence: 0, eventType: "thread.settled" }) + .pipe(Stream.runHead); + assert.deepEqual(Option.getOrThrow(stored).event.actor, actor); }), ); diff --git a/apps/server/src/persistence/OrchestrationEventStore.ts b/apps/server/src/persistence/OrchestrationEventStore.ts index 69b1b7be06322..11e5e9b785925 100644 --- a/apps/server/src/persistence/OrchestrationEventStore.ts +++ b/apps/server/src/persistence/OrchestrationEventStore.ts @@ -207,6 +207,7 @@ function metadataForV2Event(event: OrchestrationV2DomainEvent): Record => + command.type === "thread.settle" + ? serverSettings.getSettings.pipe( + Effect.map((settings) => settings.requireFounderIdentity), + Effect.orElseSucceed(() => true), + Effect.flatMap((requireFounderIdentity) => + messageSender.pipe( + Effect.map((sentBy) => ({ + ...command, + actor: settleActorOf(sentBy, currentSession.subject, requireFounderIdentity), + })), + ), + ), + ) + : Effect.succeed(command); + const handlers = ServerWsRpcGroup.of({ [WS_METHODS.issuesList]: (input) => issues.list(input), [WS_METHODS.issuesDetail]: (input) => issues.detail(input), @@ -2224,6 +2244,7 @@ export const layerWsRpc = ( ).pipe( Effect.flatMap((sentBy) => fileUnderCreator(command).pipe( + Effect.flatMap(stampSettleActor), Effect.map((filed) => ({ filed, sentBy })), ), ), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6bf4ac46fa144..35182de25b9d4 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -193,6 +193,19 @@ export const OrchestrationV2MessageSentBy = Schema.Struct({ founder: Schema.NullOr(Founder), }); export type OrchestrationV2MessageSentBy = typeof OrchestrationV2MessageSentBy.Type; +/** + * Who issued a command, stamped by the server from the authenticated session or calling agent. + * A client never supplies it. Recorded on the event so a settle can be attributed later. + */ +export const OrchestrationV2CommandActor = Schema.Struct({ + kind: Schema.Literals(["founder", "agent", "server"]), + founder: Schema.optionalKey(Schema.NullOr(Founder)), + sessionId: Schema.optionalKey(AuthSessionId), + client: Schema.optionalKey(Schema.String), + /** The thread whose agent issued it. */ + agentThreadId: Schema.optionalKey(ThreadId), +}); +export type OrchestrationV2CommandActor = typeof OrchestrationV2CommandActor.Type; /** * The workflow run a thread is an agent step of, with the step's name. `environmentId` is where * the run lives, which is another environment for a step that runs through a link. @@ -2525,6 +2538,7 @@ const OrchestrationV2EventBase = Schema.Struct({ providerInstanceId: Schema.optional(ProviderInstanceId), rawEventId: Schema.optional(RawEventId), occurredAt: Schema.DateTimeUtc, + actor: Schema.optional(OrchestrationV2CommandActor), }); export const OrchestrationV2DomainEvent = Schema.Union([ @@ -3813,6 +3827,8 @@ export const OrchestrationV2Command = Schema.Union([ threadId: ThreadId, expectedLatestRunId: Schema.optional(RunId), settledAt: Schema.optional(Schema.DateTimeUtc), + /** Server-stamped; a client's value is replaced. A founder inbox refuses any but a founder. */ + actor: Schema.optional(OrchestrationV2CommandActor), }), /** Rejects changes since snapshotAt or any explicit settled override to preserve user actions. */ Schema.Struct({ diff --git a/packages/contracts/src/threadInbox.ts b/packages/contracts/src/threadInbox.ts index 69d3035140b42..d30fb53548525 100644 --- a/packages/contracts/src/threadInbox.ts +++ b/packages/contracts/src/threadInbox.ts @@ -94,6 +94,40 @@ export const ThreadInbox = Schema.Struct({ executorEnvironmentId: Schema.NullOr(EnvironmentId), }); export type ThreadInbox = typeof ThreadInbox.Type; +/** + * Whose inbox holds the thread: the founder it is filed for, assigned to, or waiting on via an + * open decision request, "shared", or null for Agents. Only a founder settles a thread a founder's + * inbox holds. + */ +export function founderInboxHolder( + inbox: + | (Pick & { + readonly decisionRequest?: ThreadDecisionRequest | undefined; + }) + | null + | undefined, +): Founder | "shared" | null { + if (inbox == null) return null; + if (inbox.audience !== "agent-only") return inbox.audience; + if (inbox.assignee?.kind === "human") return inbox.assignee.id; + if (inbox.decisionRequest !== undefined) { + const joint = jointSignOff(inbox.decisionRequest.signOff); + if (joint !== null) { + const unsigned = joint.filter((entry) => !entry.signed); + if (unsigned.length > 1) return "shared"; + if (unsigned.length === 1) return unsigned[0]!.founder; + } else { + return inbox.decisionRequest.founder; + } + } + return null; +} + +export function founderInboxSettleRefusal(holder: Founder | "shared"): string { + return holder === "shared" + ? "Thread is in the founders' shared inbox; only a founder settles it." + : `Thread is in ${holder}'s inbox; only the founder settles it.`; +} export const InboxView = Schema.Literals(["kameron", "jeff", "shared", "agents", "all"]); export type InboxView = typeof InboxView.Type; /** An inbox a thread can be filed into: every view except All. */