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 992688cbb5761..583cb0db3532d 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -3,6 +3,7 @@ import * as NodeSqlite from "node:sqlite"; import { assert, it } from "@effect/vitest"; import { CommandId, + EnvironmentId, MessageId, EventId, founderInboxLane, @@ -22,6 +23,7 @@ import { RunAttemptId, RunId, RuntimeRequestId, + ScheduledTaskId, ThreadId, TurnItemId, } from "@t3tools/contracts"; @@ -43,6 +45,7 @@ import { orchestrationCommandDuration, orchestrationCommandsTotal, } from "../observability/Metrics.ts"; +import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; import * as SqlitePersistence from "../persistence/Sqlite.ts"; import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; import * as DelegatedTaskQuestionReactor from "./DelegatedTaskQuestionReactor.ts"; @@ -2459,6 +2462,81 @@ it.effect("replays a thread.create receipt without changing the thread", () => }).pipe(Effect.provide(layerTest)), ); +it.effect("keeps a standing laptop schedule in the original thread queue through resume", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const events = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("thread:standing-laptop"); + const messageId = MessageId.make("standing-laptop:occurrence"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("standing-laptop:create"), + threadId, + projectId: ProjectId.make("project:standing-laptop"), + title: "Product Designer", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "thread.standing.set", + commandId: CommandId.make("standing-laptop:persona"), + threadId, + standing: { name: "Product Designer", avatarId: "bolt", accent: "sky" }, + }); + const commandId = CommandId.make("standing-laptop:schedule"); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId, + threadId, + messageId, + scheduledTaskId: ScheduledTaskId.make("standing-laptop:job"), + text: "Scheduled occurrence", + attachments: [], + createdBy: "user", + creationSource: "web", + localExecution: true, + dispatchMode: { type: "start_immediately" }, + }); + const before = yield* projections.getThreadRecords(threadId, ["runs", "messages"]); + assert.lengthOf(before.runs, 1); + assert.equal(before.runs[0]?.status, "queued"); + assert.equal(before.runs[0]?.queueHeld, true); + assert.equal(before.messages[0]?.id, messageId); + assert.equal(before.messages[0]?.scheduledTaskId, ScheduledTaskId.make("standing-laptop:job")); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make("standing-laptop:resume"), + threadId, + }); + const after = yield* projections.getThreadRecords(threadId, ["runs", "messages"]); + assert.deepEqual(after.runs, before.runs); + assert.deepEqual(after.messages, before.messages); + assert.isFalse( + (yield* events.readByCommandId({ commandId }).pipe(Stream.runCollect)).some( + ({ event }) => event.type === "run.created" && event.payload.status === "starting", + ), + ); + }).pipe( + Effect.provide( + layerTest.pipe( + Layer.provide( + Layer.succeed(ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed( + EnvironmentId.make("2f360b2e-0386-498a-b9cd-62999f3525ba"), + ), + }), + ), + ), + ), + ), +); + it.effect("explicit settle clears snooze atomically and stays idempotent after re-snoozing", () => Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index a2b36016d4467..3c57689ec1bb4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -18,6 +18,11 @@ import { type ThreadInbox, } from "@t3tools/contracts"; import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; +import { + executionEnvironmentId, + logStandingExecution, + requiresRemoteStandingExecution, +} from "./standingExecution.ts"; import { latestExecutedRun, latestRootProviderFailure, @@ -1933,6 +1938,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const runtimePolicy = yield* RuntimePolicyV2; const threadForkService = yield* ThreadForkServiceV2; const threadDispatch = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const environmentId = yield* executionEnvironmentId; const messageIntake = yield* KeyedLock.make(); // Read once: the policy is fixed for the server's life, and dispatch takes it as an input. const { managedPolicy } = serverSettings; @@ -2857,7 +2863,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } if (projection.runtimeRequests.some((request) => request.status === "pending")) return; const expired = projection.runs.filter( - (run) => run.status === "queued" && deliveryExpired(run, checkedAt), + (run) => + run.status === "queued" && + run.standingExecutor === undefined && + deliveryExpired(run, checkedAt), ); if (expired.length > 0) { yield* writeSystemEvents( @@ -2926,6 +2935,41 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio if (storedQueuedRun === undefined) { return; } + if ( + requiresRemoteStandingExecution( + environmentId, + projection.thread, + storedQueuedRun.localExecution, + ) + ) { + const settings = yield* serverSettings.getSettings; + if ( + storedQueuedRun.queueHeld !== true && + settings.standingThreadExecutors[threadId] === undefined + ) { + yield* writeSystemEvents([ + { + type: "run.updated", + threadId, + runId: storedQueuedRun.id, + providerInstanceId: storedQueuedRun.providerInstanceId, + occurredAt: checkedAt, + payload: { + ...storedQueuedRun, + queueHeld: true, + standingExecutionHold: "executor-unavailable", + }, + }, + ]); + yield* logStandingExecution( + "held", + environmentId, + projection.thread, + storedQueuedRun, + ).pipe(Effect.ignore); + } + return; + } const queuedMessage = projection.messages.find( (candidate) => candidate.id === storedQueuedRun.userMessageId, ); @@ -8710,7 +8754,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio (yield* projectionStore.getMessageCount(command.threadId).pipe(mapDispatchError(command))) === 0 && !hasTitleSetBeforeFirstMessage(projection.thread, command.titleSeed); + const localExecution = + command.localExecution === true && + command.createdBy === "user" && + (command.creationSource === "web" || command.creationSource === "mobile") && + command.scheduledTaskId === undefined && + command.guestMessageId === undefined && + command.notification === undefined && + command.delegatedCompletion === undefined && + command.steerFollowUpOfRunId === undefined && + command.restartContinuationOfRunId === undefined && + command.usageLimitContinuationOfRunId === undefined && + command.manualContinuationOfRunId === undefined && + command.providerFailover === undefined + ? { localExecution: true as const } + : {}; + const remoteStandingExecution = requiresRemoteStandingExecution( + environmentId, + projection.thread, + localExecution.localExecution, + ); if ( + !remoteStandingExecution && !isNativeMaintenanceCommand(command) && (seedsUntitledThread || (command.createdBy === "user" && @@ -8778,6 +8843,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio attachments: command.attachments, }) : resolveMessageDispatchIntent(projection, requestedMode, requestedIntent); + if (remoteStandingExecution) dispatchMode = { type: "queue_after_active" }; if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; const target = projection.runs.find((run) => run.id === targetRunId); @@ -8901,6 +8967,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); if ( isLiveRun(target) && + !remoteStandingExecution && goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) && (targetMessage === undefined || !isNativeMaintenanceCommand(targetMessage)) && !(yield* stopReachedRun(command, command.threadId, target.id)) @@ -9261,7 +9328,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A digest never starts a turn, so on a thread with nothing running it waits for one. const holdDigest = deliveryClass === "digest" && queueBehindRun === undefined && startsOrQueuesRun; - const shouldQueue = (queueBehindRun !== undefined && startsOrQueuesRun) || holdDigest; + const shouldQueue = + (startsOrQueuesRun && (queueBehindRun !== undefined || remoteStandingExecution)) || + holdDigest; // 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. @@ -9296,7 +9365,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command.scheduledTaskId === undefined; const heldRunsToRelease = sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved - ? projection.runs.filter((run) => run.status === "queued" && run.queueHeld === true) + ? projection.runs.filter( + (run) => + run.status === "queued" && + run.queueHeld === true && + !requiresRemoteStandingExecution( + environmentId, + projection.thread, + run.localExecution, + ), + ) : []; const releasedAt = yield* DateTime.now; for (const held of heldRunsToRelease) { @@ -9315,7 +9393,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const coalesceKey = command.delivery?.coalesceKey; if (coalesceKey !== undefined) { for (const replaced of projection.runs.filter( - (run) => run.status === "queued" && run.delivery?.coalesceKey === coalesceKey, + (run) => + run.status === "queued" && + run.standingExecutor === undefined && + run.delivery?.coalesceKey === coalesceKey, )) { for (const event of queuedRunCancellationEvents(projection, replaced, releasedAt)) { projection = applyToProjection(projection, yield* emit(events, command)(event)); @@ -9337,7 +9418,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio : projection.providerThreads.find( (candidate) => candidate.id === queueBehindRun.providerThreadId, )); - if (queueProviderThread === undefined && !holdDigest) { + if (queueProviderThread === undefined && !holdDigest && !remoteStandingExecution) { return yield* new OrchestratorDispatchError({ commandId: command.commandId, commandType: command.type, @@ -9398,7 +9479,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const attemptId = idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }); const rootNodeId = idAllocator.derive.rootNode({ runId }); const checkpointScope = - holdDigest || queueBehindRun?.status === "preparing" || worktreeMissingRun !== undefined + holdDigest || + remoteStandingExecution || + queueBehindRun?.status === "preparing" || + worktreeMissingRun !== undefined ? null : yield* runtimePolicy.resolve({ thread: projection.thread, modelSelection }).pipe( Effect.flatMap((resolvedRuntimePolicy) => @@ -9425,8 +9509,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); const queueIsHeld = projection.runs.some( - (candidate) => candidate.status === "queued" && candidate.queueHeld === true, + (candidate) => + candidate.status === "queued" && + candidate.queueHeld === true && + candidate.standingExecutionHold === undefined, ); + const standingExecutorMissing = + remoteStandingExecution && + (yield* serverSettings.getSettings.pipe(mapDispatchError(command))).standingThreadExecutors[ + command.threadId + ] === undefined; // Buffered wakes need a T3 run for output the CLI already started producing. // Stop still holds wakes that arrive before the active run settles. const wakeSkipsHold = @@ -9473,6 +9565,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio rootNodeId, activeAttemptId: attemptId, status: "queued", + ...localExecution, ...(steerWhenReadyRunId === undefined ? {} : { steerWhenReadyRunId }), // A restart cancels its run; nobody knows whether the provider read the steer, so a person decides. ...(worktreeMissingRun !== undefined || @@ -9482,7 +9575,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio !wakeSkipsHold && queuedRunStop?.skipsHeldQueue !== true) ? { queueHeld: true } - : {}), + : standingExecutorMissing + ? { queueHeld: true, standingExecutionHold: "executor-unavailable" } + : {}), queuePosition: queuedRunStop !== undefined ? 1 @@ -9922,6 +10017,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio rootNodeId, activeAttemptId: attemptId, status: dispatchMode.type === "defer_start" ? "preparing" : "starting", + ...localExecution, queuePosition: null, requestedAt: now, startedAt: null, @@ -10758,6 +10854,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio rootNodeId, activeAttemptId: attemptId, status: "starting", + ...localExecution, queuePosition: null, requestedAt: now, startedAt: null, @@ -13537,6 +13634,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Queued run ${command.queuedRunId} is not queued.`, }); } + if ( + requiresRemoteStandingExecution(environmentId, projection.thread, queuedRun.localExecution) + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "This standing turn is held for remote execution.", + }); + } const queuedRootNode = queuedRun.rootNodeId === null ? undefined @@ -13892,6 +13998,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const queuedMessage = projection.messages.find( (candidate) => candidate.id === queuedRun.userMessageId, ); + if (queuedRun.standingExecutor !== undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "This standing turn is already assigned to a remote executor.", + }); + } const now = yield* DateTime.now; if (queuedMessage?.delegatedCompletion !== undefined) { yield* disposeDelegatedCompletionCohort({ @@ -13999,6 +14112,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Run ${command.runId} is not queued.`, }); } + if (queuedRun.standingExecutor !== undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "This standing turn is already assigned to a remote executor.", + }); + } const queuedMessage = projection.messages.find( (candidate) => candidate.id === queuedRun.userMessageId, ); @@ -17984,6 +18104,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio selectedRunId === undefined ? undefined : projection.runs.find((run) => run.id === selectedRunId && run.status === "queued"); + if ( + selectedRun !== undefined && + requiresRemoteStandingExecution( + environmentId, + projection.thread, + selectedRun.localExecution, + ) + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: "This standing turn is held for remote execution.", + }); + } if (selectedRunId !== undefined) { const selectedMessage = projection.messages.find( (message) => message.id === selectedRun?.userMessageId, @@ -18025,7 +18159,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } const now = yield* DateTime.now; - const queued = projection.runs.filter((run) => run.status === "queued"); + const queued = projection.runs.filter( + (run) => + run.status === "queued" && + !requiresRemoteStandingExecution(environmentId, projection.thread, run.localExecution), + ); for (const run of queued) { yield* emit( events, diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index de932c1d87500..e7e53e63af65a 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -8,6 +8,8 @@ import { expect, it, vi } from "vite-plus/test"; import { it as effectIt } from "@effect/vitest"; import { CheckpointScopeId, + CLOSURA_LAPTOP_ENVIRONMENT_ID, + CLOSURA_R720_ENVIRONMENT_ID, CommandId, ContextHandoffId, ContextTransferId, @@ -46,6 +48,7 @@ import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import * as ServerConfig from "../config.ts"; +import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts"; import * as PreviewAgentActivity from "../preview/PreviewAgentActivity.ts"; import * as CheckpointService from "./CheckpointService.ts"; @@ -88,6 +91,7 @@ import * as ProviderTurnStart from "./ProviderTurnStartService.ts"; import * as RunExecutionService from "./RunExecutionService.ts"; import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts"; import * as RuntimePolicy from "./RuntimePolicy.ts"; +import { layerStandingExecutionEvidence } from "./standingExecution.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; const isDomainEvent = Schema.is(OrchestrationV2DomainEvent); @@ -1769,6 +1773,107 @@ const enqueueStart = ( return { storedEffect: outbox.get("effect:failed-start").pipe(Effect.map(Option.getOrThrow)) }; }); +effectIt.effect.each([ + { environmentId: CLOSURA_LAPTOP_ENVIRONMENT_ID, localExecution: undefined, outcome: "held" }, + { + environmentId: CLOSURA_LAPTOP_ENVIRONMENT_ID, + localExecution: true as const, + outcome: "started", + }, + { environmentId: CLOSURA_R720_ENVIRONMENT_ID, localExecution: undefined, outcome: "started" }, + { + environmentId: CLOSURA_R720_ENVIRONMENT_ID, + localExecution: undefined, + outcome: "audit-failed", + }, +])( + "guards standing starts on $environmentId (explicit local $localExecution, $outcome)", + (input) => { + const harness = makeLocalCommandHarness({ + text: "Run the scheduled check", + previousTurn: { runStatus: "completed", turnStatus: "completed" }, + }); + return Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-standing-evidence-" }); + const auditFailed = input.outcome === "audit-failed"; + const logsDir = auditFailed ? path.join(tempDir, "blocked") : tempDir; + if (auditFailed) yield* fs.writeFileString(logsDir, ""); + const evidence = layerStandingExecutionEvidence.pipe( + Layer.provide( + Layer.mock(ServerConfig.ServerConfig)({ + logsDir, + } as ServerConfig.ServerConfig["Service"]), + ), + ); + const projection = harness.projection(); + const run = projection.runs.at(-1)!; + harness.setProjection({ + ...projection, + thread: { + ...projection.thread, + standing: { name: "CoS", avatarId: "bolt", accent: "sky" }, + }, + runs: [ + ...projection.runs.slice(0, -1), + { ...run, ...(input.localExecution === true ? { localExecution: true } : {}) }, + ], + }); + harness.startRootRun.mockImplementation(({ session, ...turn }) => + session.startTurn(turn as never).pipe(Effect.orDie), + ); + const open = harness.open.getMockImplementation()!; + harness.open.mockImplementation(() => + open().pipe( + Effect.map( + (session) => ({ ...(session as object), startTurn: harness.startTurn }) as never, + ), + ), + ); + const result = yield* harness.start.pipe(Effect.provide(evidence), Effect.result); + const started = input.outcome === "started"; + expect(harness.open).toHaveBeenCalledTimes(started ? 1 : 0); + expect(harness.startTurn).toHaveBeenCalledTimes(started ? 1 : 0); + expect(result._tag).toBe(auditFailed ? "Failure" : "Success"); + if (auditFailed) return; + expect(harness.projection().runs.find((candidate) => candidate.id === run.id)).toMatchObject( + started + ? { id: run.id, status: "running" } + : { id: run.id, status: "queued", queueHeld: true }, + ); + const file = yield* fs.readFileString(path.join(logsDir, "standing-execution.ndjson")); + const records = file + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + expect(records.map((record) => record.phase)).toEqual( + started + ? [ + "coverage-start", + "session-open-requested", + "turn-start-requested", + "turn-start-accepted", + ] + : ["coverage-start", "held"], + ); + for (const [sequence, record] of records.entries()) { + expect(record).toMatchObject({ + event: "t3.standing-execution", + environmentId: input.environmentId, + sequence, + streamId: records[0].streamId, + }); + } + }).pipe( + Effect.provide(NodeServices.layer), + Effect.provideService(ServerEnvironmentIdentity, { + getEnvironmentId: Effect.succeed(input.environmentId), + }), + ); + }, +); + effectIt.effect( "settles an exhausted start effect without claiming an external turn stopped", () => { diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 09a99b698af6f..65d07ac1d037c 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -98,6 +98,11 @@ import { UNTITLED_LAUNCH_REFUSAL, } from "./SessionSpendGuard.ts"; import * as TurnItemPositionStore from "./TurnItemPositionStore.ts"; +import { + executionEnvironmentId, + logStandingExecution, + requiresRemoteStandingExecution, +} from "./standingExecution.ts"; import { isRestartNoteContinuation, pendingRestartCancelledBackgroundWork, @@ -339,6 +344,7 @@ export const layer: Layer.Layer< const restoreMissingWorktree = yield* makeRestoreMissingWorktree; const worktreeRestore = yield* ThreadWorktreeRestore; const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2; + const environmentId = yield* executionEnvironmentId; // Build draining callbacks outside startup scope so they cannot retain full thread history. const makeRunControls = (input: { @@ -590,6 +596,49 @@ export const layer: Layer.Layer< if (run.status !== "starting") { return; } + if (requiresRemoteStandingExecution(environmentId, projection.thread, run.localExecution)) { + if (run.activeAttemptId === null) { + return yield* new ProviderTurnStartError({ + runId, + cause: "Cannot hold a starting run without its active attempt.", + }); + } + const currentSettings = yield* serverSettings.getSettings; + const executorMissing = + currentSettings.standingThreadExecutors[input.threadId] === undefined; + const held = yield* eventSink.writeIfRunCurrent({ + threadId: input.threadId, + runId, + activeAttemptId: run.activeAttemptId, + expectedStatus: "starting", + events: [ + { + id: yield* idAllocator.allocate.event({ threadId: input.threadId }), + type: "run.updated", + threadId: input.threadId, + runId, + providerInstanceId: run.providerInstanceId, + occurredAt: yield* DateTime.now, + payload: { + ...run, + status: "queued", + ...(executorMissing + ? { + queueHeld: true, + standingExecutionHold: "executor-unavailable" as const, + } + : {}), + }, + }, + ], + }); + if (held.committed) { + yield* logStandingExecution("held", environmentId, projection.thread, run).pipe( + Effect.ignore, + ); + } + return; + } captureStartingRun(run); const rootNode = projection.nodes.find((candidate) => candidate.id === run.rootNodeId); const attempt = projection.attempts.find((candidate) => candidate.id === run.activeAttemptId); @@ -1098,6 +1147,7 @@ export const layer: Layer.Layer< brokenNativeThread && providerThread.nativeThreadRef !== null && !(yield* providerSessions.isLive(providerSessionId)); + yield* logStandingExecution("session-open-requested", environmentId, projection.thread, run); const sessionResult = yield* Effect.result( providerSessions.open({ threadId: projection.thread.id, @@ -1132,7 +1182,43 @@ export const layer: Layer.Layer< }); return; } - const session = sessionResult.success; + const nativeSession = sessionResult.success; + const auditTurnStart = (start: Effect.Effect) => + logStandingExecution("turn-start-requested", environmentId, projection.thread, run).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterTurnStartError({ + driver: nativeSession.driver, + threadId: input.threadId, + providerThreadId: providerThread.id, + runId, + cause, + }), + ), + Effect.andThen(start), + Effect.tap(() => + logStandingExecution("turn-start-accepted", environmentId, projection.thread, run).pipe( + Effect.ignore, + ), + ), + ); + const session = { + ...nativeSession, + startTurn: (turn: Parameters[0]) => + auditTurnStart(nativeSession.startTurn(turn)), + ...(nativeSession.resumeTurn === undefined + ? {} + : { + resumeTurn: (turn: ProviderAdapter.ProviderAdapterV2ResumeTurnInput) => + auditTurnStart(nativeSession.resumeTurn!(turn)), + }), + ...(nativeSession.compactThread === undefined + ? {} + : { + compactThread: (turn: Parameters[0]) => + auditTurnStart(nativeSession.compactThread!(turn)), + }), + }; if (!(yield* isCurrentAttemptInStatus("starting"))) return; const loadFromProvider = Effect.fn("ProviderTurnStartService.loadFromProvider")(function* ( load: Effect.Effect, diff --git a/apps/server/src/orchestration-v2/standingExecution.ts b/apps/server/src/orchestration-v2/standingExecution.ts new file mode 100644 index 0000000000000..6f3d63eb2ea3e --- /dev/null +++ b/apps/server/src/orchestration-v2/standingExecution.ts @@ -0,0 +1,173 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeCrypto from "node:crypto"; +import { + CLOSURA_LAPTOP_ENVIRONMENT_ID, + CLOSURA_R720_ENVIRONMENT_ID, + CLOSURA_ASUS_ENVIRONMENT_ID, + type EnvironmentId, + type OrchestrationV2AppThread, + type OrchestrationV2Run, +} from "@t3tools/contracts"; +import { makeAsyncRotatingFileSink } from "@t3tools/shared/logging"; +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 Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as Result from "effect/Result"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; +import { buildCommit, ServerConfig } from "../config.ts"; +import { ServerEnvironmentIdentity } from "../environment/ServerEnvironment.ts"; + +const roleNames = new Map([ + ["cos", "cos"], + ["chief of staff", "cos"], + ["cto", "cto"], + ["chief technology officer", "cto"], + ["ceo", "ceo"], + ["chief executive officer", "ceo"], + ["cfo", "cfo"], + ["chief financial officer", "cfo"], + ["product designer", "product-designer"], +] as const); + +const hostNames = new Map([ + [CLOSURA_LAPTOP_ENVIRONMENT_ID, "laptop"], + [CLOSURA_R720_ENVIRONMENT_ID, "r720"], + [CLOSURA_ASUS_ENVIRONMENT_ID, "asus"], +]); + +type StandingThread = Pick; + +function standingExecutionRole(thread: StandingThread) { + if (thread.lineage.parentThreadId !== null) return undefined; + // Older role roots predate standing personas. Match their exact titles only. + const role = thread.standing?.role?.trim().toLowerCase(); + const name = thread.standing?.name.trim().toLowerCase(); + const title = thread.title?.trim().toLowerCase(); + return ( + (role === undefined ? undefined : roleNames.get(role)) ?? + (name === undefined ? undefined : roleNames.get(name)) ?? + (title === undefined ? undefined : roleNames.get(title)) + ); +} + +export const executionEnvironmentId = Effect.serviceOption(ServerEnvironmentIdentity).pipe( + Effect.flatMap((identity) => + Option.isSome(identity) ? identity.value.getEnvironmentId : Effect.succeed(null), + ), +); + +class StandingExecutionEvidenceError extends Schema.TaggedError()( + "StandingExecutionEvidenceError", + { cause: Schema.Defect() }, +) {} + +class StandingExecutionEvidence extends Context.Service< + StandingExecutionEvidence, + { readonly append: (event: object) => Effect.Effect } +>()("t3/orchestration-v2/standingExecution/StandingExecutionEvidence") {} + +const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown)); + +export const layerStandingExecutionEvidence = Layer.effect( + StandingExecutionEvidence, + Effect.gen(function* () { + const { logsDir } = yield* ServerConfig; + const { join } = yield* Path.Path; + const environmentId = yield* (yield* ServerEnvironmentIdentity).getEnvironmentId; + const host = hostNames.get(environmentId); + if (host === undefined) return { append: () => Effect.void }; + const streamId = NodeCrypto.randomUUID(); + const lock = yield* Semaphore.make(1); + const opened = yield* makeAsyncRotatingFileSink({ + filePath: join(logsDir, "standing-execution.ndjson"), + maxBytes: 256 * 1024, + maxFiles: 3, + sync: true, + }).pipe(Effect.result); + if (Result.isFailure(opened)) { + return { + append: () => Effect.fail(new StandingExecutionEvidenceError({ cause: opened.failure })), + }; + } + const sink = opened.success; + let sequence = 0; + const write = Effect.fn("StandingExecutionEvidence.write")( + function* (event: object) { + const line = yield* encodeRecord({ + ...event, + event: "t3.standing-execution", + version: 1, + host, + environmentId, + sourceRevision: buildCommit ?? null, + streamId, + sequence: sequence++, + at: DateTime.formatIso(yield* DateTime.now), + }); + yield* sink.write(`${line}\n`); + }, + Effect.mapError((cause) => new StandingExecutionEvidenceError({ cause })), + ); + + const boundary = yield* write({ phase: "coverage-start" }).pipe(Effect.result); + const append = Effect.fn("StandingExecutionEvidence.append")(function* (event: object) { + if (Result.isFailure(boundary)) return yield* boundary.failure; + yield* lock.withPermit(write(event)); + }); + return { append }; + }), +); + +export function requiresRemoteStandingExecution( + environmentId: EnvironmentId | null, + thread: StandingThread, + localExecution?: true, +) { + return ( + environmentId === CLOSURA_LAPTOP_ENVIRONMENT_ID && + localExecution !== true && + standingExecutionRole(thread) !== undefined + ); +} + +export function logStandingExecution( + phase: + | "session-open-requested" + | "turn-start-requested" + | "turn-start-accepted" + | "held" + | "candidate", + environmentId: EnvironmentId | null, + thread: StandingThread, + run: Pick, + candidate?: { environmentId: EnvironmentId; outcome: string }, +) { + const role = standingExecutionRole(thread); + if (role === undefined) return Effect.void; + const event = { + phase, + host: environmentId === null ? null : (hostNames.get(environmentId) ?? null), + environmentId, + sourceRevision: buildCommit ?? null, + role, + threadId: thread.id, + runId: run.id, + attemptId: run.activeAttemptId, + localExecution: run.localExecution === true, + ...(candidate === undefined + ? {} + : { + candidateEnvironmentId: candidate.environmentId, + candidateOutcome: candidate.outcome, + }), + }; + return Effect.gen(function* () { + const evidence = yield* Effect.serviceOption(StandingExecutionEvidence); + if (Option.isSome(evidence)) yield* evidence.value.append(event); + yield* Effect.logInfo("t3.standing-execution").pipe(Effect.annotateLogs(event)); + }); +} diff --git a/apps/server/src/peer/StandingThreadExecution.test.ts b/apps/server/src/peer/StandingThreadExecution.test.ts new file mode 100644 index 0000000000000..98f3ac2c7ec72 --- /dev/null +++ b/apps/server/src/peer/StandingThreadExecution.test.ts @@ -0,0 +1,191 @@ +import { assert, it } from "@effect/vitest"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { + CLOSURA_ASUS_ENVIRONMENT_ID, + CLOSURA_R720_ENVIRONMENT_ID, + CommandId, + EventId, + MessageId, + OrchestratorMcpFailure, + ProjectId, + ProviderInstanceId, + RunAttemptId, + RunId, + ThreadId, + type EnvironmentId, + type OrchestrationV2Run, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; +import * as RemoteDelegation from "./RemoteDelegation.ts"; +import { makeSweep } from "./StandingThreadExecution.ts"; + +const source = ThreadId.make("standing:cos"); +const r720 = ThreadId.make("standing:cos:r720"); +const asus = ThreadId.make("standing:cos:asus"); +const projectId = ProjectId.make("project:standing"); +const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }; +const fixtureTime = DateTime.makeUnsafe("2026-12-01T00:00:00Z"); +const initialRun = { + id: RunId.make("source-run"), + activeAttemptId: RunAttemptId.make("source-attempt"), + userMessageId: MessageId.make("source-message"), + threadId: source, + ordinal: 1, + queuePosition: 1, + modelSelection, + providerInstanceId: modelSelection.instanceId, + status: "queued", + requestedAt: fixtureTime, +} as OrchestrationV2Run; + +it.effect.each([ + { r720Up: true, asusUp: true, expected: CLOSURA_R720_ENVIRONMENT_ID }, + { r720Up: false, asusUp: true, expected: CLOSURA_ASUS_ENVIRONMENT_ID }, + { r720Up: false, asusUp: false, expected: undefined }, +])("uses R720 then ASUS or keeps the same queued run ($r720Up, $asusUp)", (input) => { + let run = initialRun; + let r720Up = input.r720Up; + let asusUp = input.asusUp; + const calls: Array<{ host: EnvironmentId; key: unknown }> = []; + const intents = new Map(); + const lostReply = new OrchestratorMcpFailure({ + code: "orchestration_error", + message: "disconnected", + }); + const shell = { + id: source, + title: "CoS", + lineage: { parentThreadId: null }, + archivedAt: null, + deletedAt: null, + worktreePath: null, + projectId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + } as OrchestrationV2ThreadShell; + + return Effect.gen(function* () { + const sweep = yield* makeSweep; + yield* sweep(); + assert.equal(run.id, initialRun.id); + assert.equal(run.status, "queued"); + assert.deepEqual( + calls.map(({ host }) => host), + input.expected ? [input.expected] : [], + ); + if (input.expected === undefined) { + assert.isUndefined(run.standingExecutor); + assert.isTrue(run.queueHeld); + assert.equal(run.standingExecutionHold, "executor-unavailable"); + asusUp = true; + yield* sweep(); + assert.equal(calls[0]?.host, CLOSURA_ASUS_ENVIRONMENT_ID); + assert.equal(run.id, initialRun.id); + assert.isFalse(run.queueHeld); + return; + } + assert.equal(run.standingExecutor?.environmentId, input.expected); + assert.isUndefined(run.standingExecutor?.runId); + r720Up = true; + asusUp = true; + yield* sweep(); + assert.deepEqual( + calls.map(({ host }) => host), + [input.expected, input.expected], + ); + assert.equal(calls[0]?.key, calls[1]?.key); + yield* sweep(); + assert.equal(run.status, "completed"); + }).pipe( + Effect.provide( + Layer.mergeAll( + NodeCrypto.layer, + ThreadCommandExecutor.layer, + ServerSettings.layerTest({ standingThreadExecutors: { [source]: { r720, asus } } }), + Layer.mock(IdAllocator.IdAllocatorV2)({ + allocate: { event: () => Effect.succeed(EventId.make("event:standing-test")) } as never, + derive: {} as never, + }), + Layer.mock(EventSink.EventSinkV2)({ + writeIfRunCurrent: ({ events }) => + Effect.sync(() => { + const event = events[0]; + if (event?.type === "run.updated") run = event.payload; + return { committed: true, storedEvents: [] }; + }), + }), + Layer.mock(ProjectionStore.ProjectionStoreV2)({ + getThreadShell: () => Effect.succeed(shell), + getThreadRecords: (() => Effect.succeed({ runs: [run], runtimeRequests: [] })) as never, + getMessagesById: (() => + Effect.succeed( + new Map([[run.userMessageId, { text: "Wake", attachments: [] }]]), + )) as never, + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + bindIntent: ({ commandId, value }) => + Effect.sync(() => { + if (!intents.has(commandId)) intents.set(commandId, value); + return intents.get(commandId)!; + }), + intentOf: (commandId) => + Effect.sync(() => Option.fromUndefinedOr(intents.get(commandId))), + }), + Layer.mock(PeerLinks.PeerLinks)({ + enabled: Effect.succeed(true), + session: () => Effect.succeedSome("test-link"), + }), + Layer.mock(RemoteDelegation.RemoteDelegation)({ + admit: (_, proposal) => + Effect.succeed({ + environmentId: proposal.candidateEnvironmentIds[0]!, + projectId, + reason: "capacity", + resumed: false, + }), + }), + Layer.mock(PeerMcpClient.PeerMcpClient)({ + call: ({ environmentId, tool, arguments: args }) => { + const up = environmentId === CLOSURA_R720_ENVIRONMENT_ID ? r720Up : asusUp; + if (!up) return Effect.fail(lostReply); + const runId = RunId.make("remote-run"); + if (tool === "t3_thread_read") { + return Effect.succeed({ + thread: { + ...shell, + threadId: args.threadId, + archived: false, + snoozed: false, + parentThreadId: null, + model: modelSelection.model, + providerInstanceId: modelSelection.instanceId, + }, + } as never); + } + if (tool === "t3_thread_send") { + calls.push({ host: environmentId, key: args.clientRequestId }); + return calls.length === 1 + ? Effect.fail(lostReply) + : Effect.succeed({ threadId: args.threadId, runId } as never); + } + return Effect.succeed({ threadId: args.threadId, runId, status: "completed" } as never); + }, + }), + ), + ), + ); +}); diff --git a/apps/server/src/peer/StandingThreadExecution.ts b/apps/server/src/peer/StandingThreadExecution.ts new file mode 100644 index 0000000000000..1719786ecde1f --- /dev/null +++ b/apps/server/src/peer/StandingThreadExecution.ts @@ -0,0 +1,358 @@ +import { + CLOSURA_ASUS_ENVIRONMENT_ID, + CLOSURA_LAPTOP_ENVIRONMENT_ID, + CLOSURA_R720_ENVIRONMENT_ID, + CommandId, + OrchestratorMcpThreadReadResult, + OrchestratorMcpThreadSendResult, + OrchestratorMcpThreadWaitResult, + ThreadId, + type OrchestrationV2Run, + type ServerSettings as Settings, +} from "@t3tools/contracts"; +import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import * as DateTime from "effect/DateTime"; +import * as Digest from "effect/crypto/Digest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Result from "effect/Result"; +import * as Schedule from "effect/Schedule"; +import * as Schema from "effect/Schema"; + +import * as EventSink from "../orchestration-v2/EventSink.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import { queuedRunsInDeliveryOrder } from "../orchestration-v2/QueuedRunOrder.ts"; +import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts"; +import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts"; +import { + executionEnvironmentId, + logStandingExecution, + requiresRemoteStandingExecution, +} from "../orchestration-v2/standingExecution.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as PeerLinks from "./PeerLinks.ts"; +import * as PeerMcpClient from "./PeerMcpClient.ts"; +import * as RemoteDelegation from "./RemoteDelegation.ts"; + +type Route = Settings["standingThreadExecutors"][ThreadId]; + +const encodeBinding = Schema.encodeEffect( + Schema.fromJsonString(Schema.Tuple([Schema.String, Schema.String, Schema.String])), +); + +const order = [ + ["r720", CLOSURA_R720_ENVIRONMENT_ID], + ["asus", CLOSURA_ASUS_ENVIRONMENT_ID], +] as const; + +export const makeSweep = Effect.gen(function* () { + const here = CLOSURA_LAPTOP_ENVIRONMENT_ID; + const settings = yield* ServerSettings.ServerSettingsService; + const threads = yield* ThreadManagement.ThreadManagementService; + const projection = yield* ProjectionStore.ProjectionStoreV2; + const events = yield* EventSink.EventSinkV2; + const ids = yield* IdAllocator.IdAllocatorV2; + const locks = yield* ThreadCommandExecutor.ThreadCommandExecutor; + const peers = yield* PeerMcpClient.PeerMcpClient; + const links = yield* PeerLinks.PeerLinks; + const placement = yield* RemoteDelegation.RemoteDelegation; + const digest = yield* Digest.Digest; + + const updateQueuedRun = Effect.fn("StandingThreadExecution.updateQueuedRun")(function* ( + run: OrchestrationV2Run, + patch: Partial, + ) { + if (run.activeAttemptId === null) return false; + const { committed } = yield* events.writeIfRunCurrent({ + threadId: run.threadId, + runId: run.id, + activeAttemptId: run.activeAttemptId, + expectedStatus: "queued", + events: [ + { + id: yield* ids.allocate.event({ threadId: run.threadId }), + type: "run.updated", + threadId: run.threadId, + runId: run.id, + providerInstanceId: run.providerInstanceId, + occurredAt: yield* DateTime.now, + payload: { ...run, ...patch }, + }, + ], + }); + return committed; + }); + + const processQueue = Effect.fn("StandingThreadExecution.processQueue")(function* ( + threadId: ThreadId, + route: Route, + ) { + const shell = yield* projection.getThreadShell(threadId); + if ( + shell === null || + shell.archivedAt !== null || + shell.deletedAt !== null || + shell.replacedByThreadId != null || + !requiresRemoteStandingExecution(here, shell) + ) { + return; + } + const { runs, runtimeRequests } = yield* projection.getThreadRecords(threadId, [ + "runs", + "runtimeRequests", + ]); + const queue = queuedRunsInDeliveryOrder({ runs, messages: [] }); + const boundRun = queue.find((run) => run.standingExecutor !== undefined); + const now = yield* DateTime.now; + const run = + boundRun ?? + queue.find( + (run) => + (run.queueHeld !== true || run.standingExecutionHold === "executor-unavailable") && + run.localExecution !== true && + run.delivery?.class !== "digest" && + (run.delivery?.expiresAt === undefined || + DateTime.isGreaterThan(run.delivery.expiresAt, now)), + ); + if (run === undefined || run.activeAttemptId === null) return; + const message = (yield* projection.getMessagesById(threadId, [run.userMessageId])).get( + run.userMessageId, + ); + if (message === undefined) return; + if (boundRun === undefined) { + if ( + (shell.snoozedUntil != null && DateTime.isGreaterThan(shell.snoozedUntil, now)) || + runs.some(ThreadManagement.isActiveRun) || + runtimeRequests.some((request) => request.status === "pending") + ) { + return; + } + // These turns refer to state on the owner. Keep them there until a peer can restore it. + if ( + shell.worktreePath !== null || + message.attachments.length > 0 || + message.context !== undefined || + message.notification !== undefined || + message.delegatedCompletion !== undefined || + run.manualContinuationOfRunId !== undefined || + run.restartContinuationOfRunId !== undefined || + run.usageLimitContinuationOfRunId !== undefined || + run.providerFailoverOfRunId !== undefined + ) { + if ( + yield* updateQueuedRun(run, { + queueHeld: true, + standingExecutionHold: "unsupported-payload", + }) + ) { + yield* logStandingExecution("held", here, shell, run); + } + return; + } + } + + const limits = { runtimeMode: shell.runtimeMode, interactionMode: shell.interactionMode }; + const modelSelection = message.followsThreadSelection + ? shell.modelSelection + : run.modelSelection; + const key = yield* digest.digestHex( + Digest.sha256, + new TextEncoder().encode(`${here}\0${threadId}\0${run.id}`), + ); + const commandId = CommandId.make(`standing-placement:${key}`); + const incarnationId = CommandId.make(`standing-placement-link:${key}`); + let target = run.standingExecutor; + if (target === undefined) { + const recordCandidate = (environmentId: (typeof order)[number][1], outcome: string) => + logStandingExecution("candidate", here, shell, run, { environmentId, outcome }); + // Validate the admitted counterpart before binding. Nothing sent during preflight can start work. + for (const [host, environmentId] of order) { + const remoteThreadId = route[host]; + if (remoteThreadId === undefined) { + yield* recordCandidate(environmentId, "missing-counterpart"); + continue; + } + const remote = yield* peers + .call({ + environmentId, + tool: "t3_thread_read", + arguments: { threadId: remoteThreadId, limit: 1, runLimit: 1, maxCharsPerItem: 1 }, + limits, + success: OrchestratorMcpThreadReadResult, + }) + .pipe(Effect.option); + if (Option.isNone(remote)) { + yield* recordCandidate(environmentId, "preflight-failed"); + continue; + } + if ( + remote.value.thread.threadId !== remoteThreadId || + remote.value.thread.archived || + remote.value.thread.parentThreadId !== null || + remote.value.thread.snoozed || + remote.value.thread.model !== modelSelection.model || + remote.value.thread.providerInstanceId !== modelSelection.instanceId || + remote.value.thread.runtimeMode !== limits.runtimeMode || + remote.value.thread.interactionMode !== limits.interactionMode + ) { + yield* recordCandidate(environmentId, "counterpart-ineligible"); + continue; + } + const admitted = yield* placement + .admit( + { sessionId: `standing-execution:${here}`, stillAuthorized: links.enabled }, + { + commandId, + threadId, + projectId: shell.projectId, + modelSelection, + ...limits, + candidateEnvironmentIds: [environmentId], + here: Effect.succeed({ resources: null, modelAvailable: false }), + }, + ) + .pipe(Effect.result); + if (Result.isFailure(admitted)) { + yield* recordCandidate(environmentId, `placement-${admitted.failure.reason}`); + continue; + } + // A crash between admission and the queued-run update can replay another peer's binding. + if ( + admitted.success.environmentId !== environmentId || + admitted.success.projectId !== remote.value.thread.projectId + ) { + yield* recordCandidate(environmentId, "placement-mismatch"); + continue; + } + target = { environmentId, threadId: remoteThreadId }; + const incarnation = yield* links.session(environmentId); + if (Option.isNone(incarnation)) { + yield* recordCandidate(environmentId, "link-unavailable"); + return; + } + const binding = yield* encodeBinding([ + target.environmentId, + target.threadId, + incarnation.value, + ]); + const held = yield* threads.bindIntent({ + commandId: incarnationId, + threadId, + value: binding, + }); + if (held !== binding) { + yield* recordCandidate(environmentId, "link-binding-mismatch"); + return; + } + if ( + !(yield* updateQueuedRun(run, { + standingExecutor: target, + queueHeld: false, + standingExecutionHold: undefined, + })) + ) + return; + yield* recordCandidate(environmentId, "bound"); + break; + } + } + if (target === undefined) { + if ( + run.standingExecutionHold !== "executor-unavailable" && + (yield* updateQueuedRun(run, { + queueHeld: true, + standingExecutionHold: "executor-unavailable", + })) + ) { + yield* logStandingExecution("held", here, shell, run); + } + return; + } + const incarnation = yield* links.session(target.environmentId); + if (Option.isNone(incarnation)) return; + const held = yield* threads.intentOf(incarnationId); + if ( + Option.isNone(held) || + held.value !== + (yield* encodeBinding([target.environmentId, target.threadId, incarnation.value])) + ) { + return; + } + const peerCall = { + environmentId: target.environmentId, + limits, + expectedIncarnation: incarnation.value, + }; + if (target.runId === undefined) { + const sent = yield* peers.call({ + ...peerCall, + tool: "t3_thread_send", + arguments: { + threadId: target.threadId, + message: message.text, + mode: "queue", + clientRequestId: `standing:${key}`, + freshContext: run.freshContext === true, + ...(run.delivery?.expiresAt === undefined + ? {} + : { expiresAt: DateTime.formatIso(run.delivery.expiresAt) }), + ...(run.outputSchema === undefined ? {} : { outputSchema: run.outputSchema }), + }, + sender: { environmentId: here, threadId, title: shell.title }, + success: OrchestratorMcpThreadSendResult, + }); + if (sent.threadId === target.threadId) { + yield* updateQueuedRun(run, { + standingExecutor: { ...target, runId: sent.runId }, + queueHeld: false, + standingExecutionHold: undefined, + }); + } + return; + } + const done = yield* peers.call({ + ...peerCall, + tool: "t3_thread_wait", + arguments: { threadId: target.threadId, runId: target.runId, timeoutMs: 50 }, + success: OrchestratorMcpThreadWaitResult, + }); + if ( + done.threadId === target.threadId && + done.runId === target.runId && + done.status !== "idle" && + ThreadManagement.isTerminalRunStatus(done.status) + ) { + yield* updateQueuedRun(run, { + status: done.status, + completedAt: yield* DateTime.now, + queuePosition: null, + queueHeld: false, + }); + } + }); + + return Effect.fn("StandingThreadExecution.sweep")(function* () { + const { standingThreadExecutors } = yield* settings.getSettings; + yield* Effect.forEach( + Object.entries(standingThreadExecutors), + ([id, route]) => { + const threadId = ThreadId.make(id); + return locks.withLock(threadId, processQueue(threadId, route)).pipe(Effect.ignore); + }, + { concurrency: 4, discard: true }, + ); + }); +}); + +export const layer = Layer.effectDiscard( + Effect.gen(function* () { + if ((yield* executionEnvironmentId) !== CLOSURA_LAPTOP_ENVIRONMENT_ID) return; + const sweep = yield* makeSweep; + yield* sweep().pipe( + Effect.ignore, + Effect.repeat(Schedule.spaced("10 seconds")), + Effect.forkScoped, + ); + }), +); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index b1927fab540bf..c66118f4bc1c4 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -108,6 +108,7 @@ import * as PeerLinkRenewal from "./peer/PeerLinkRenewal.ts"; import * as PeerLinks from "./peer/PeerLinks.ts"; import * as PeerMcpClient from "./peer/PeerMcpClient.ts"; import * as PeerThreadRelay from "./peer/PeerThreadRelay.ts"; +import * as StandingThreadExecution from "./peer/StandingThreadExecution.ts"; import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as DeviceService from "./device/DeviceService.ts"; @@ -239,6 +240,8 @@ import * as CursorUsageAccounts from "@t3tools/provider-cursor/server/CursorUsag import * as UsageService from "./usage/UsageService.ts"; import * as CodexUsageHistory from "./usage/CodexUsageHistory.ts"; import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts"; +import * as ThreadCommandExecutor from "./orchestration-v2/ThreadCommandExecutor.ts"; +import { layerStandingExecutionEvidence } from "./orchestration-v2/standingExecution.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; import * as ThreadViewers from "./orchestration-v2/ThreadViewers.ts"; import * as WorkflowForge from "./workflows/WorkflowForge.ts"; @@ -846,7 +849,9 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( ReplayMarkers.layer, Layer.effectDiscard(ProjectSettingsOverrideSweep.sweep), ).pipe( - Layer.provideMerge(layerOrchestrationApplication), + Layer.provideMerge( + layerOrchestrationApplication.pipe(Layer.provideMerge(layerStandingExecutionEvidence)), + ), // One hub, which the feeders above and the workflow store inside the runtime publish to. Layer.provideMerge(MilestoneHub.layer), Layer.provideMerge(Layer.merge(layerTaskFolders, LayoutCommandApprovalWrites.layer)), @@ -999,6 +1004,16 @@ const layerMakeRoutes = Layer.mergeAll( Layer.effectDiscard( RemoteDelegation.RemoteDelegation.pipe(Effect.flatMap((remote) => remote.start())), ), + StandingThreadExecution.layer.pipe( + Layer.provide( + Layer.mergeAll( + ProjectionStoreV2.layer, + RuntimeLayer.layerEventSink, + IdAllocator.layer, + ThreadCommandExecutor.layer, + ), + ), + ), // Tells the watcher thread, here or on a linked machine, when a run here ran a fallback model. Layer.effectDiscard( ModelAlertReactor.ModelAlertReactor.pipe(Effect.flatMap((reactor) => reactor.start())), diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6bf4ac46fa144..1a36630edaba1 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -996,6 +996,19 @@ export const OrchestrationV2Run = Schema.Struct({ status: OrchestrationV2RunStatus, queuePosition: Schema.optional(Schema.NullOr(PositiveInt)), queueHeld: Schema.optional(Schema.Boolean), + /** This individual human-requested turn must execute on the thread's own environment. */ + localExecution: Schema.optional(Schema.Literal(true)), + standingExecutionHold: Schema.optional( + Schema.Literals(["executor-unavailable", "unsupported-payload"]), + ), + /** The durable destination for a dispatched standing turn. Reconcile there after an uncertain send. */ + standingExecutor: Schema.optional( + Schema.Struct({ + environmentId: EnvironmentId, + threadId: ThreadId, + runId: Schema.optional(RunId), + }), + ), steerWhenReadyRunId: Schema.optional(RunId), requestedAt: Schema.DateTimeUtc, startedAt: Schema.NullOr(Schema.DateTimeUtc), @@ -4056,6 +4069,8 @@ export const OrchestrationV2Command = Schema.Union([ notification: Schema.optional(OrchestrationV2Notification), /** Sends this pending guest message; the server uses the guest's text, not `text`. */ guestMessageId: Schema.optional(GuestMessageId), + /** Explicitly run this human submission on the thread's own environment. */ + localExecution: Schema.optional(Schema.Literal(true)), ...OrchestrationV2CreationFields, scheduledTaskId: Schema.optional(ScheduledTaskId), senderThreadId: Schema.optional(ThreadId), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 64b6152aef34a..4b34e93e506ce 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1227,13 +1227,23 @@ export const ModelAlertWatcher = Schema.Struct({ }); export type ModelAlertWatcher = typeof ModelAlertWatcher.Type; -// Closura: Kameron's CoS thread on the laptop hears every machine's alerts (the old CoS thread -// retired on 2026-11-20). Moving the watcher means changing this one value (or `modelAlertWatcher` -// on each machine). +export const CLOSURA_LAPTOP_ENVIRONMENT_ID = EnvironmentId.make( + "2f360b2e-0386-498a-b9cd-62999f3525ba", +); +export const CLOSURA_R720_ENVIRONMENT_ID = EnvironmentId.make( + "5cd73d78-08c9-47d4-8381-a53e008340d4", +); +export const CLOSURA_ASUS_ENVIRONMENT_ID = EnvironmentId.make( + "26cc7088-9c9e-4e60-87dc-51af42d30424", +); + +// Closura: Kameron's CoS thread hears every machine's alerts. It moved from the laptop to R720 on +// 2026-12-03 so no standing bot runs on the laptop. Moving the watcher means changing this one value +// (or `modelAlertWatcher` on each machine). const DEFAULT_MODEL_ALERT_WATCHER: ModelAlertWatcher = { - environmentId: EnvironmentId.make("2f360b2e-0386-498a-b9cd-62999f3525ba"), + environmentId: CLOSURA_R720_ENVIRONMENT_ID, threadId: ThreadId.make( - "mcp:launch:4c07a2ef8bc6157f99fbae20642807c05a8a57c53eaec25dd4abfa16bc5b242e", + "mcp:launch:bb84e8fe904e8d300c5d00ece7178771e3b2beccc1169983fe96e90c518b3e7b", ), }; @@ -1495,12 +1505,12 @@ export type AutomaticPlacementHost = typeof AutomaticPlacementHost.Type; export const DEFAULT_AUTOMATIC_PLACEMENT_HOSTS: ReadonlyArray = [ { - environmentId: EnvironmentId.make("5cd73d78-08c9-47d4-8381-a53e008340d4"), + environmentId: CLOSURA_R720_ENVIRONMENT_ID, maxLanes: 4, minAvailableMemoryGiB: 4, }, { - environmentId: EnvironmentId.make("26cc7088-9c9e-4e60-87dc-51af42d30424"), + environmentId: CLOSURA_ASUS_ENVIRONMENT_ID, maxLanes: 1, minAvailableMemoryGiB: 4, }, @@ -1510,7 +1520,7 @@ export const DEFAULT_AUTOMATIC_PLACEMENT_HOSTS: ReadonlyArray, + options: Omit & { readonly sync?: boolean }, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -246,9 +246,13 @@ export const makeAsyncRotatingFileSink = Effect.fnUntraced(function* ( const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk; if (buffer.length === 0) return; if (currentSize > 0 && currentSize + buffer.length > options.maxBytes) yield* rotate; - yield* fs - .writeFile(options.filePath, buffer, { flag: "a" }) - .pipe(Effect.mapError(failure("write"))); + const append = options.sync + ? fs.open(options.filePath, { flag: "a" }).pipe( + Effect.flatMap((file) => file.writeAll(buffer).pipe(Effect.andThen(file.sync))), + Effect.scoped, + ) + : fs.writeFile(options.filePath, buffer, { flag: "a" }); + yield* append.pipe(Effect.mapError(failure("write"))); currentSize += buffer.length; }).pipe( Effect.tapError(() =>