feat(orchestrator): introduce new orchestrator #2829
Mergedjuliusmarmingemerged 250+ commits into
main fromrefs/pull/2829/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
- apps/server/src/orchestration-v2/EventStore.ts lines 146 to 221OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +201,21 @@201+ }202+ return yield* rowToStoredEvent(row).pipe(203+ Effect.mapError(204+ (cause) =>205+ new EventStoreAppendEventsError({206+ eventCount: input.events.length,207+ cause,208+ }),209+ ),210+ );211+ }),212+ { concurrency: 1 },213+ ).pipe(214+ Effect.mapError(215+ (cause) =>216+ new EventStoreAppendEventsError({217+ eventCount: input.events.length,218+ cause,219+ }),220+ ),221+ );apps/server/src/orchestration-v2/ProviderAdapterRegistry.ts lines 356 to 359OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +339,21 @@339+ if (existing !== undefined && entryEqual(existing.entry, entry)) {340+ nextEntries.set(instanceId, existing);341+ continue;342+ }343+344+ const nextEntry = yield* createAdapterEntryFromConfigEntry({345+ driversById,346+ parentScope,347+ instanceId,348+ entry,349+ });350+ nextEntries.set(instanceId, nextEntry);351+ if (existing !== undefined) {352+ staleEntries.push(existing);353+ }354+ }355+356+ for (const [instanceId, existing] of previous) {357+ if (!nextIds.has(instanceId)) {358+ staleEntries.push(existing);359+ }@@ -0,0 +100,21 @@100+ if (firstRecord.type !== "transcript_start") {101+ entries.push(firstRecord);102+ }103+104+ for (const { line, lineNumber } of lines.slice(1)) {105+ const record = yield* parseReplayRecord(line, lineNumber);106+ if (record.type === "transcript_start") {107+ return yield* new ProviderReplayNdjsonLineParseError({108+ lineNumber,109+ line,110+ cause: "transcript_start is only valid as the first replay record",111+ });112+ }113+ entries.push(record);114+ }115+116+ return decodeTranscript({117+ ...metadata,118+ entries,119+ });120+ });packages/client-runtime/src/wsRpcClient.ts line 323OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -308,3 +320,4 @@308320 { ...options, tag: ORCHESTRATION_WS_METHODS.subscribeThread },309321 ),310322 },323+ orchestrationV2: {apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts lines 1384 to 1388OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +715,21 @@715+ providerSessionId: input.providerSessionId,716+ event,717+ },718+ input.threadId,719+ )720+ .pipe(Effect.ignore);721+}722+723+export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer<724+ CodexAppServerClientFactory,725+ never,726+ ChildProcessSpawner.ChildProcessSpawner | ServerConfig727+> = Layer.effect(728+ CodexAppServerClientFactory,729+ Effect.gen(function* () {730+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;731+ const { providerEventLogPath } = yield* ServerConfig;732+ const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {733+ stream: "native",734+ });735+apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts lines 717 to 728OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +708,21 @@708+ },709+ },710+ }).pipe(711+ Layer.provide(makeClaudeAgentSdkReplayLayer(transcript)),712+ Layer.provide(idAllocatorLayer),713+ Layer.provide(NodeServices.layer),714+ );715+}716+717+export async function replayClaudeAgentSdkTranscript(input: {718+ readonly transcript: ClaudeAgentSdkReplayTranscript;719+ readonly prompts: ReadonlyArray<string>;720+ readonly modelSelection: ModelSelection;721+ readonly cwd?: string;722+}): Promise<ReadonlyArray<SDKMessage>> {723+ return input.transcript.entries.flatMap((entry) =>724+ entry.type === "emit_inbound" && isClaudeSdkReplayMessage(entry.frame)725+ ? [sdkMessageFromReplayFrame(entry.frame)]726+ : [],727+ );728+}
- apps/server/src/orchestration-v2/RunExecutionService.ts lines 1267 to 1326OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +340,21 @@340+ Ref.get(latestProviderThread).pipe(341+ Effect.flatMap((providerThread) =>342+ writeFinalRunEvents({343+ run: input.run,344+ rootNode: input.rootNode,345+ checkpointScope: input.checkpointScope,346+ providerThread,347+ attempt: input.attempt,348+ status: "failed",349+ runtimePolicy: input.runtimePolicy,350+ }),351+ ),352+ Effect.mapError(353+ (writeCause) =>354+ new RunExecutionIngestError({355+ runId: input.run.id,356+ cause: { ingest: cause, write: writeCause },357+ }),358+ ),359+ ),360+ ),
- apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts line 1610OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +864,21 @@864+}865+866+export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): ProviderAdapterV2Shape {867+ const { clientFactory, fileSystem, idAllocator, serverConfig } = adapterOptions;868+869+ return ProviderAdapterV2.of({870+ instanceId: adapterOptions.instanceId,871+ provider: CODEX_PROVIDER,872+ getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),873+ openSession: (input) =>874+ Effect.gen(function* () {875+ const client = yield* clientFactory.open({876+ instanceId: adapterOptions.instanceId,877+ threadId: input.threadId,878+ providerSessionId: input.providerSessionId,879+ runtimePolicy: input.runtimePolicy,880+ settings: adapterOptions.settings,881+ environment: adapterOptions.environment,882+ });883+ const initialized = yield* Ref.make(false);884+ const ensureInitialized = Effect.gen(function* () {apps/server/src/orchestration-v2/RunExecutionService.ts line 1328OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +349,21 @@349+ rootNode: input.rootNode,350+ checkpointScope: input.checkpointScope,351+ providerThread,352+ attempt: input.attempt,353+ ...(input.shouldFinalizeRun === undefined354+ ? {}355+ : { shouldFinalizeRun: input.shouldFinalizeRun }),356+ status: "failed",357+ runtimePolicy: input.runtimePolicy,358+ }),359+ ),360+ Effect.mapError(361+ (writeCause) =>362+ new RunExecutionIngestError({363+ runId: input.run.id,364+ cause: { ingest: cause, write: writeCause },365+ }),366+ ),367+ ),368+ ),369+ Effect.forkDetach,
juliusmarminge changed the title
- apps/server/src/orchestration-v2/RunExecutionService.ts line 571OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +108,21 @@108+ RunExecutionServiceV2,109+ Effect.gen(function* () {110+ const checkpointService = yield* CheckpointServiceV2;111+ const eventSink = yield* EventSinkV2;112+ const idAllocator = yield* IdAllocatorV2;113+ const providerEventIngestor = yield* ProviderEventIngestorV2;114+115+ const writeFinalRunEvents = (input: {116+ readonly run: OrchestrationV2Run;117+ readonly rootNode: OrchestrationV2ExecutionNode;118+ readonly checkpointScope: OrchestrationV2CheckpointScope;119+ readonly providerThread: OrchestrationV2ProviderThread;120+ readonly attempt: OrchestrationV2RunAttempt;121+ readonly shouldFinalizeRun?: () => Effect.Effect<boolean, never>;122+ readonly status: Extract<123+ OrchestrationV2Run["status"],124+ "completed" | "interrupted" | "failed" | "cancelled"125+ >;126+ readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;127+ }) =>128+ Effect.gen(function* () {@@ -0,0 +108,21 @@108+ ) =>109+ Effect.gen(function* () {110+ const threadId = payloadInput.threadId ?? input.threadId;111+ const eventId = yield* idAllocator.allocate.event({112+ threadId,113+ providerSessionId: input.providerSessionId,114+ });115+ const occurredAt = yield* DateTime.now;116+ return yield* Schema.decodeUnknownEffect(OrchestrationV2DomainEvent)(117+ compactUndefined({118+ id: eventId,119+ type: payloadInput.type,120+ threadId,121+ runId: payloadInput.runId ?? input.runId,122+ nodeId: payloadInput.nodeId ?? input.nodeId,123+ provider: input.event.provider,124+ rawEventId: input.rawEventId,125+ occurredAt,126+ payload: payloadInput.payload,127+ }),128+ );apps/server/src/orchestration-v2/Orchestrator.ts lines 9260 to 9262OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +3365,21 @@3365+ case "run.interrupt":3366+ yield* dispatchRunInterrupt(command, events);3367+ break;3368+ case "queued-message.promote-to-steer":3369+ yield* dispatchQueuedMessagePromoteToSteer(command, events);3370+ break;3371+ case "queued-run.reorder":3372+ yield* dispatchQueuedRunReorder(command, events);3373+ break;3374+ case "checkpoint.rollback":3375+ yield* dispatchCheckpointRollback(command, events);3376+ break;3377+ case "thread.fork":3378+ yield* dispatchThreadFork(command, events);3379+ break;3380+ case "thread.merge_back":3381+ yield* dispatchThreadMergeBack(command, events);3382+ break;3383+ default:3384+ return yield* dispatchUnsupported(command);3385+ }apps/web/src/routes/debug.orchestration-v2.tsx lines 3482 to 3483OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +3463,21 @@3463+ );3464+ }3465+3466+ case "reasoning":3467+ return (3468+ <ChatBubbleRow side="left">3469+ <details className="max-w-[92%] min-w-0 rounded-md border border-dashed border-border bg-muted/40 px-3 py-1.5 text-muted-foreground open:pb-2.5">3470+ <summary className="flex cursor-pointer list-none items-center gap-2 text-xs font-medium tracking-wide uppercase hover:text-foreground">3471+ <span>Reasoning</span>3472+ {item.streaming ? <StreamingDot /> : null}3473+ </summary>3474+ <p className="mt-1.5 wrap-break-word whitespace-pre-wrap text-base italic sm:text-sm">3475+ {item.text}3476+ </p>3477+ </details>3478+ <ChatMeta side="left">3479+ <ChatStatusPill status={item.status} />3480+ <ChatClock iso={timestamp} nowMs={nowMs} />3481+ </ChatMeta>3482+ wrap-break-word3483+ </ChatBubbleRow>apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 7038OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +2845,21 @@2845+ const currentTurn = yield* Ref.get(activeTurn);2846+ if (currentTurn?.providerTurnId !== turnInput.providerTurnId) {2847+ return yield* new ProviderAdapterProtocolError({2848+ provider: CLAUDE_PROVIDER,2849+ detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`,2850+ });2851+ }2852+ yield* Ref.update(interruptedTurns, (current) => {2853+ const next = new Set(current);2854+ next.add(turnInput.providerTurnId);2855+ return next;2856+ });2857+ yield* existing.query.interrupt;2858+ yield* existing.query.close.pipe(Effect.ignore);2859+ const closed = yield* Deferred.await(existing.closed).pipe(2860+ Effect.timeoutOption("10 seconds"),2861+ );2862+ if (Option.isSome(closed)) {2863+ return;2864+ }2865+
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts line 2295OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1877,21 @@1877+1878+async function recordInterruptedClaudeQuery(input: {1879+ readonly scenario: string;1880+ readonly prompt: string;1881+ readonly modelSelection: ModelSelection;1882+ readonly cwd: string;1883+ readonly sessionId: string;1884+ readonly resume: boolean;1885+ readonly entries: Array<ProviderReplayEntry>;1886+ readonly queryOpenLabel: string;1887+ readonly promptOfferLabel: string;1888+ readonly interruptLabel: string;1889+ readonly interruptAfter?: "prompt_offer" | "tool_use";1890+ readonly enableTools?: boolean;1891+ readonly tools?: ClaudeAgentSdkQueryTools;1892+ readonly permissionMode?: ClaudeAgentSdkQueryOptions["permissionMode"];1893+ readonly allowedTools?: ReadonlyArray<string>;1894+ readonly disallowedTools?: ReadonlyArray<string>;1895+ readonly allowDangerouslySkipPermissions?: boolean;1896+}): Promise<void> {1897+ const promptQueue = new RecordingPromptQueue();
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts lines 1877 to 1886OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1257,21 @@1257+ return pattern === undefined || pattern.trim().length === 0 ? [] : [pattern];1258+}1259+1260+function webSearchResultsFromClaudeOutput(1261+ output: ClaudeNativeToolOutput,1262+): ReadonlyArray<OrchestrationV2WebSearchResult> {1263+ const value = claudeNativeToolOutputValue(output);1264+ if (!isClaudeWebSearchOutput(value)) {1265+ return [];1266+ }1267+1268+ return value.results.flatMap((result) => {1269+ if (typeof result === "string") {1270+ return [];1271+ }1272+ return result.content.map((content) => ({1273+ title: content.title,1274+ url: content.url,1275+ }));1276+ });1277+}
- apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts lines 767 to 768OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +513,21 @@513+ const effort =514+ input.runtimePolicy.reasoningEffort === undefined515+ ? undefined516+ : yield* decodeTurnReasoningEffort(input.runtimePolicy.reasoningEffort);517+ const collaborationMode: CodexSchema.ClientRequest__CollaborationMode | undefined =518+ input.runtimePolicy.interactionMode === "plan"519+ ? {520+ mode: "plan",521+ settings: {522+ model: input.model,523+ reasoning_effort: effort ?? "medium",524+ developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,525+ },526+ }527+ : undefined;528+529+ return yield* Schema.decodeUnknownEffect(CodexTurnStartParamsWithCollaborationMode)({530+ threadId: input.nativeThreadId,531+ input: input.codexInput,532+ ...(approvalPolicy === undefined ? {} : { approvalPolicy }),533+ ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }),
- apps/server/src/orchestration-v2/ProviderSessionManager.ts line 679OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +659,21 @@659+ releaseEntry({660+ providerSessionId: entry.runtime.providerSessionId,661+ reason: "server_shutdown",662+ }).pipe(663+ Effect.catchCause((cause) =>664+ Effect.logWarning("orchestration-v2.provider-session.shutdown-release-failed", {665+ providerSessionId: entry.runtime.providerSessionId,666+ cause,667+ }),668+ ),669+ ),670+ { discard: true },671+ );672+ }),673+ );674+675+ return ProviderSessionManagerV2.of({676+ open: (input) =>677+ Effect.gen(function* () {678+ const key = sessionKey(input.providerSessionId);679+ const existing = (yield* Ref.get(sessions)).get(key);apps/server/src/orchestration-v2/Orchestrator.ts lines 2289 to 2304OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +2284,21 @@2284+ ordinal: ordinal * 100 - 1,2285+ status: "completed",2286+ title:2287+ portableForkHandoff !== null2288+ ? "Fork context"2289+ : providerSwitchHandoff !== null2290+ ? "Provider handoff"2291+ : "Merge-back context",2292+ startedAt: now,2293+ completedAt: now,2294+ updatedAt: now,2295+ type: "handoff",2296+ contextHandoffId: activeHandoff.id,2297+ fromProviderThreadIds: activeHandoff.fromProviderThreadIds,2298+ toProviderThreadId: activeHandoff.toProviderThreadId,2299+ fromProviders:2300+ portableForkHandoff !== null2301+ ? sourceRun === null2302+ ? []2303+ : [sourceRun.provider]2304+ : providerSwitchHandoff === null
- apps/server/src/mcp/OrchestratorMcpService.ts line 655OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +635,21 @@635+ scope: McpInvocationScope,636+ taskId: NodeId,637+ waitTimedOut = false,638+ ): Effect.Effect<OrchestratorMcpDelegateTaskResult, OrchestratorMcpFailure> =>639+ Effect.gen(function* () {640+ yield* requireCapability(scope);641+ const parentProjection = yield* loadProjection(scope.threadId);642+ const task = parentProjection.subagents.find(643+ (candidate) =>644+ candidate.id === taskId &&645+ candidate.origin === "app_owned" &&646+ candidate.threadId === scope.threadId,647+ );648+ if (task === undefined || task.childThreadId === null) {649+ return yield* failure(650+ "task_not_found",651+ `Delegated task ${taskId} does not belong to thread ${scope.threadId}.`,652+ );653+ }654+ const childProjection = yield* loadProjection(task.childThreadId);655+ const childRun = childProjection.runs[0];apps/server/src/ws.ts line 822OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -798,3 +813,10 @@798813 .refreshStatus(cwd)799814 .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid);800815816+ const subscribeOrchestrationV2Thread = Effect.fn("ws.orchestrationV2.subscribeThread")(817+ function* (input: { readonly threadId: ThreadId }) {818+ yield* Effect.annotateCurrentSpan({819+ "orchestration_v2.thread_id": input.threadId,820+ });821+822+ const projection = yield* threadManagement.getThreadProjection(input.threadId).pipe(@@ -0,0 +251,21 @@251+ return [];252+ }253+ return [254+ {255+ type: "http",256+ name: "t3-code",257+ url: session.endpoint,258+ headers: [259+ {260+ name: "Authorization",261+ value: session.authorizationHeader,262+ },263+ ],264+ },265+ ];266+}267+268+function nativeThreadId(provider: ProviderKind, thread: OrchestrationV2ProviderThread): string {269+ const id = thread.nativeThreadRef?.nativeId;270+ if (id === null || id === undefined || id.trim().length === 0) {271+ throw new ProviderAdapterProtocolError({
- apps/server/src/orchestration-v2/EffectWorker.ts line 341OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +321,21 @@321+ drain: (maxEffects = Number.MAX_SAFE_INTEGER) =>322+ Effect.gen(function* () {323+ let completed = 0;324+ while (completed < maxEffects && (yield* runOnce)) {325+ completed += 1;326+ }327+ return completed;328+ }),329+ });330+ }),331+ );332+333+export const layer = layerWithOptions();334+335+export const daemonLayer: Layer.Layer<never, never, OrchestrationEffectWorkerV2> =336+ Layer.effectDiscard(337+ Effect.gen(function* () {338+ const worker = yield* OrchestrationEffectWorkerV2;339+ yield* Effect.forever(340+ worker.runOnce.pipe(341+ Effect.catchCause((cause) =>@@ -0,0 +186,21 @@186+ unsupported(187+ input,188+ "queued_messages",189+ "providerInstanceId does not support app-owned queued turns",190+ ),191+ );192+193+const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {194+ if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {195+ return Effect.succeed("active_steering");196+ }197+ if (198+ input.capabilities.turns.supportsInterrupt &&199+ input.capabilities.turns.supportsSteeringByInterruptRestart200+ ) {201+ return Effect.succeed("interrupt_restart");202+ }203+ return Effect.fail(204+ unsupported(205+ input,206+ input.capabilities.turns.supportsInterrupt ? "interrupt_restart_steering" : "active_steering",apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts line 4916OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +3090,21 @@3090+ runtimeRequest: artifacts.request,3091+ });3092+ yield* emitProviderEvent({3093+ type: "turn_item.updated",3094+ driver: CODEX_PROVIDER,3095+ turnItem: artifacts.turnItem,3096+ });3097+3098+ const resolved = yield* Deferred.await(answers).pipe(3099+ Effect.ensuring(3100+ Ref.update(pendingRuntimeRequests, (current) => {3101+ const updated = new Map(current);3102+ updated.delete(String(artifacts.request.id));3103+ return updated;3104+ }),3105+ ),3106+ );3107+ return {3108+ answers: toCodexUserInputAnswers(3109+ resolved,3110+ new Set(payload.questions.map((question) => question.id)),apps/server/src/persistence/Migrations/035_OrchestrationV2Foundation.ts lines 87 to 87OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +67,21 @@67+ yield* sql`CREATE INDEX orchestration_v2_projection_provider_sessions_instance_status_idx ON orchestration_v2_projection_provider_sessions(provider_instance_id, status)`;68+69+ yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN driver TEXT`;70+ yield* sql`ALTER TABLE orchestration_v2_projection_provider_threads ADD COLUMN provider_instance_id TEXT`;71+ yield* sql`72+ UPDATE orchestration_v2_projection_provider_threads73+ SET74+ driver = COALESCE(json_extract(payload_json, '$.driver'), provider),75+ provider_instance_id = COALESCE(76+ json_extract(payload_json, '$.providerInstanceId'),77+ provider78+ )79+ `;80+ yield* sql`CREATE INDEX orchestration_v2_projection_provider_threads_instance_status_idx ON orchestration_v2_projection_provider_threads(provider_instance_id, status)`;81+82+ yield* sql`ALTER TABLE orchestration_v2_projection_subagents ADD COLUMN driver TEXT`;83+ yield* sql`ALTER TABLE orchestration_v2_projection_subagents ADD COLUMN provider_instance_id TEXT`;84+ yield* sql`85+ UPDATE orchestration_v2_projection_subagents86+ SET87+ driver = json_extract(payload_json, '$.driver'),apps/server/src/orchestration-v2/Orchestrator.ts line 1683OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1663,21 @@1663+ runId,1664+ nodeId: rootNodeId,1665+ role: "user",1666+ text: command.text,1667+ attachments: command.attachments,1668+ streaming: false,1669+ createdAt: now,1670+ updatedAt: now,1671+ };1672+ const turnItem: OrchestrationV2TurnItem = {1673+ createdBy: command.createdBy,1674+ creationSource: command.creationSource,1675+ id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),1676+ threadId: command.threadId,1677+ runId,1678+ nodeId: rootNodeId,1679+ providerThreadId: queueProviderThread.id,1680+ providerTurnId: null,1681+ nativeItemRef: null,1682+ parentItemId: null,1683+ ordinal: ordinal * 100,
- apps/server/src/orchestration-v2/testkit/fixtures/shared.ts lines 475 to 476OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +456,21 @@456+ break;457+ case "queue_message":458+ messageIndex += 1;459+ pushDispatch(460+ dispatchMessageCommand({461+ commandId: yield* idAllocator.allocate.command({462+ fixtureName: input.scenario,463+ commandName: `queue-message-${messageIndex}`,464+ }),465+ ids,466+ modelSelection: input.modelSelection,467+ messageId: yield* idAllocator.allocate.message({468+ threadId: ids.threadId,469+ ordinal: messageIndex,470+ }),471+ text: step.text,472+ ...(step.attachments === undefined ? {} : { attachments: step.attachments }),473+ }),474+ );475+ steps.push({ type: "await", key: `run:${messageIndex - 1}` });476+ steps.push({ type: "await_thread_idle", threadId: ids.threadId });apps/server/src/orchestration-v2/RunExecutionService.ts line 1267OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +512,21 @@512+ return;513+ }514+ const providerThread = yield* Ref.get(latestProviderThread);515+ yield* writeFinalRunEvents({516+ run: input.run,517+ rootNode: input.rootNode,518+ checkpointScope: input.checkpointScope,519+ providerThread,520+ attempt: input.attempt,521+ ...(input.shouldFinalizeRun === undefined522+ ? {}523+ : { shouldFinalizeRun: input.shouldFinalizeRun }),524+ status,525+ }).pipe(526+ Effect.mapError(527+ (cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),528+ ),529+ );530+ }),531+ ),532+ Effect.catchCause((cause) =>
- apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts lines 1008 to 1012OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +992,21 @@992+export const CodexAdapterV2Driver: ProviderAdapterDriver<CodexSettings, CodexAdapterV2DriverEnv> = {993+ driverKind: CODEX_DRIVER_KIND,994+ configSchema: CodexSettings,995+ defaultConfig: (): CodexSettings => DEFAULT_CODEX_SETTINGS,996+ create: ({ instanceId, environment, enabled, config }) =>997+ Effect.gen(function* () {998+ const clientFactory = yield* CodexAppServerClientFactory;999+ const fileSystem = yield* FileSystem.FileSystem;1000+ const hostEnvironment = yield* HostProcessEnvironment;1001+ const idAllocator = yield* IdAllocatorV2;1002+ const serverConfig = yield* ServerConfig;1003+ const homeLayout = yield* resolveCodexHomeLayout(config);1004+1005+ yield* materializeCodexShadowHome(homeLayout).pipe(1006+ Effect.mapError(1007+ (cause) =>1008+ new ProviderAdapterDriverCreateError({1009+ driver: CODEX_DRIVER_KIND,1010+ instanceId,1011+ detail: cause.message,1012+ cause,
- apps/server/scripts/acp-replay-agent.ts lines 95 to 102Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +79,21 @@79+ }80+ return JSON.stringify(value);81+}82+83+function expandExpectedString(value: string): string {84+ return value.replaceAll("<workspace>", replayWorkspace);85+}86+87+function matchesExpected(expected: unknown, actual: unknown): boolean {88+ if (expected === "<any>") return true;89+ if (typeof expected === "string" && typeof actual === "string") {90+ const expanded = expandExpectedString(expected);91+ if (!expanded.includes("<any>")) return expanded === actual;92+ const parts = expanded.split("<any>");93+ let offset = 0;94+ for (const part of parts) {95+ const index = actual.indexOf(part, offset);96+ if (index === -1) return false;97+ offset = index + part.length;98+ }99+ return true;apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts lines 450 to 450OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +430,21 @@430+ const recovered = yield* Effect.result(431+ recoverWithPolicy({432+ operation: resume,433+ classify: classifier.classify,434+ connectivity,435+ maxAttempts: recoveryPolicy.maxAttempts,436+ idempotent: true,437+ }),438+ );439+ if (recovered._tag === "Failure") {440+ const terminalizedRuns = yield* terminalize(441+ projection,442+ `Unable to resume provider session ${session.id}.`,443+ );444+ return { resumedSessions, terminalizedRuns };445+ }446+ resumedSessions += 1;447+ }448+ if (449+ resumedSessions === 0 &&450+ projection.runs.some((run) => run.status === "running" || run.status === "waiting")
- apps/web/src/components/ChatView.tsx line 2040OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2017,4 +2037,4 @@20172037 }20182038 return [...serverMessagesWithPreviewHandoff, ...pendingMessages];20192039 }, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]);2020- const timelineEntries = useMemo(2040+ const serverTimelineEntries = useMemo(apps/mobile/src/lib/threadActivity.ts lines 910 to 912Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -964,16 +252,9 @@964252 const start = Date.parse(startIso);965253 const end = Date.parse(endIso);966- if (!Number.isFinite(start) || !Number.isFinite(end)) {967- return null;968- }969- return Math.max(0, end - start);254+ return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;970255 }971256972-function maxIsoTimestamp(a: string | null, b: string | null): string | null {973- if (a === null) return b;974- if (b === null) return a;975- const aMs = Date.parse(a);976- const bMs = Date.parse(b);977- if (!Number.isFinite(aMs)) return b;978- if (!Number.isFinite(bMs)) return a;979- return bMs > aMs ? b : a;257+function maxIsoTimestamp(left: string | null, right: string | null): string | null {258+ if (left === null) return right;259+ if (right === null) return left;260+ return Date.parse(right) > Date.parse(left) ? right : left;
- @@ -0,0 +2270,21 @@2270+ effect.pipe(2271+ Effect.mapError(2272+ (cause) =>2273+ new ProviderAdapterEnsureThreadError({2274+ driver: CURSOR_PROVIDER,2275+ threadId: threadInput.threadId,2276+ cause,2277+ }),2278+ ),2279+ ),2280+ ),2281+ resumeThread: Effect.fn("CursorAdapterV2.resumeThread")(2282+ function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {2283+ const agentId = nativeThreadId(threadInput.providerThread);2284+ yield* openAgent({2285+ operation: "resume",2286+ agentId,2287+ threadId: threadInput.providerThread.appThreadId ?? input.threadId,2288+ modelSelection: input.modelSelection,2289+ runtimePolicy: input.runtimePolicy,2290+ });packages/client-runtime/src/state/models.ts lines 673 to 676OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -40,4 +658,19 @@658+export function presentThread(40659 environmentId: EnvironmentId,41- thread: OrchestrationThread,660+ projection: OrchestrationV2ThreadProjection,42661 ): EnvironmentThread {43- return { ...thread, environmentId };662+ const shell = presentThreadShell(environmentId, {663+ ...projection.thread,664+ latestRunId:665+ projection.runs.reduce<(typeof projection.runs)[number] | null>(666+ (latest, candidate) =>667+ latest === null || candidate.ordinal > latest.ordinal ? candidate : latest,668+ null,669+ )?.id ?? null,670+ activeRunId:671+ projection.runs.findLast(672+ (run) =>673+ run.status === "preparing" ||674+ run.status === "starting" ||675+ run.status === "running" ||676+ run.status === "waiting",apps/web/src/components/chat/MessagesTimeline.tsx line 893OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -657,0 +873,21 @@873+ return {874+ label: "Run interrupted",875+ detail: item.message,876+ tone: "danger",877+ icon: XIcon,878+ };879+ case "handoff":880+ return {881+ label: "Context handoff",882+ detail:883+ item.summary ??884+ `${item.fromProviderInstanceIds.join(", ")} → ${item.toProviderInstanceId}`,885+ tone: item.status === "failed" ? "danger" : "muted",886+ icon: ZapIcon,887+ };888+ case "fork":889+ return {890+ label: "Conversation fork",891+ detail: `Continues in ${item.targetThreadId}`,892+ tone: "muted",893+ icon: HammerIcon,
- @@ -351,0 +418,21 @@418+ unexpectedThreadCount: verification.unexpectedThreadIds.length,419+ unreadableThreadCount: verification.unreadableThreadIds.length,420+ },421+ ),422+ ),423+ ),424+ ),425+ rebuild: runStartupPhase(426+ "orchestration-v2.projections.rebuild",427+ projectionMaintenance.rebuild,428+ ),429+ recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),430+ startEffectWorker: runStartupPhase(431+ "orchestration-v2.effect-worker.start",432+ Effect.gen(function* () {433+ const workerFiber = yield* EffectWorker.runDaemon.pipe(Effect.forkScoped);434+ yield* Ref.set(effectWorkerFiber, workerFiber);435+ yield* agentAwarenessRelay.start();436+ }),437+ ),438+ autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
- apps/web/src/components/chat/ThreadRelationshipsControl.tsx line 81OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +61,21 @@61+ const archivedShells = archived.snapshots.find(62+ (entry) => entry.environmentId === props.environmentId,63+ )?.snapshot.threads;64+ const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [65+ ...activeShells.map((thread) => thread.source),66+ ...(archivedShells ?? []),67+ ];68+ const graph = deriveThreadRelationshipGraph({ threads: shells, projection });69+ const navigate = useNavigate();70+ const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun);71+ const mergeBack = useAtomCommand(threadEnvironment.mergeBack);72+ const stopSession = useAtomCommand(threadEnvironment.stopSession);73+ const [busyAction, setBusyAction] = useState<"fork" | "merge" | "detach" | null>(null);74+ const latestCompletedRun = projection?.runs.findLast((run) => run.status === "completed") ?? null;75+ const sourceProviderThread =76+ latestCompletedRun?.providerThreadId == null77+ ? null78+ : (projection?.providerThreads.find(79+ (thread) => thread.id === latestCompletedRun.providerThreadId,80+ ) ?? null);81+ const capabilities =apps/web/src/lib/threadRelationships.ts lines 159 to 179OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +150,21 @@150+export function immediateThreadRelationships(151+ graph: ThreadRelationshipGraph,152+ threadId: ThreadId,153+): ReadonlyArray<ThreadRelationshipWalkRow> {154+ const visited = new Set<ThreadId>();155+ const rows: ThreadRelationshipWalkRow[] = [];156+157+ for (const edge of graph.edges) {158+ const relatedId =159+ edge.sourceThreadId === threadId160+ ? edge.targetThreadId161+ : edge.targetThreadId === threadId162+ ? edge.sourceThreadId163+ : null;164+ if (relatedId === null || visited.has(relatedId)) continue;165+ visited.add(relatedId);166+ rows.push({ threadId: relatedId, fromThreadId: threadId, depth: 1, edge });167+ }168+169+ return rows;170+}@@ -150,0 +191,21 @@191+ * Applies a real right-panel mutation and its thread-panel transition atomically.192+ * This is the only path real panel actions use, so visibility never has to be193+ * reconciled after the fact in React.194+ */195+const updateThread = (196+ state: RightPanelStoreData,197+ ref: ScopedThreadRef,198+ updater: (current: ThreadRightPanelState) => ThreadRightPanelState,199+): RightPanelStoreData => {200+ const threadKey = scopedThreadKey(ref);201+ const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;202+ const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);203+ const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;204+ let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;205+206+ if (!current.isOpen && next.isOpen) {207+ threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(208+ threadPanelVisibilityByThreadKey,209+ threadKey,210+ (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),211+ );
- @@ -849,5 +862,4 @@849862 // Context window850863 // ------------------------------------------------------------------851864 const activeContextWindow = useMemo(852- () => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),853- [activeThreadActivities],865+ () => deriveLatestContextWindowSnapshot(activeThreadWorkEntries ?? []),
- apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts line 184Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +128,21 @@128+ }),129+ ),130+ Effect.flatMap((status) => {131+ if (132+ status.failure === undefined &&133+ status.cursor === transcript.entries.length &&134+ status.total === transcript.entries.length135+ ) {136+ return Effect.void;137+ }138+ return Effect.fail(139+ new EffectAcpErrors.AcpTransportError({140+ detail: `ACP replay did not consume all frames for ${transcript.scenario}`,141+ cause: status,142+ }),143+ );144+ }),145+ );146+}147+148+export function makeAcpReplayRuntime(input: {apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts lines 2044 to 2046OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1565,21 @@1565+}1566+1567+function claudeToolResultBlocksFromUserMessage(1568+ message: SDKMessage,1569+): ReadonlyArray<ClaudeToolResultContentBlock> {1570+ if (message.type !== "user" || typeof message.message.content === "string") {1571+ return [];1572+ }1573+ return message.message.content.filter(isClaudeUserToolResultContentBlock);1574+}1575+1576+function claudeToolResultEntriesFromMessage(message: SDKMessage): ReadonlyArray<{1577+ readonly toolResult: ClaudeToolResultContentBlock;1578+ readonly output: ClaudeNativeToolOutput;1579+}> {1580+ const assistantResults = claudeToolResultBlocksFromAssistantMessage(message).map(1581+ (toolResult) => ({ toolResult, output: claudeNativeToolOutputFromToolResult(toolResult) }),1582+ );1583+ const userResults = claudeToolResultBlocksFromUserMessage(message);1584+ const structuredOutput =1585+ message.type === "user" && userResults.length === 1 ? message.tool_use_result : undefined;@@ -0,0 +94,21 @@94+ ? Sources95+ : never96+ : never;97+ readonly sandboxEnabled?: boolean;98+ readonly enableAgentRetries?: boolean;99+ readonly hasCustomTools?: boolean;100+ };101+ readonly agents?: ReadonlyArray<string>;102+}103+104+export interface CursorAgentSdkLoggedSendOptions {105+ readonly model?: SendOptions["model"];106+ readonly mode?: SendOptions["mode"];107+ readonly local?: {108+ readonly force?: boolean;109+ readonly hasCustomTools?: boolean;110+ };111+ readonly idempotencyKey?: string;112+}113+114+export type CursorAgentSdkProtocolLogEvent =@@ -0,0 +92,21 @@92+ EffectAcpErrors.AcpError,93+ Scope.Scope94+ >;95+ readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;96+}97+98+export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({99+ runtime,100+ requestUserInput,101+}) =>102+ Effect.forEach(103+ ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,104+ (method) =>105+ runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params) => {106+ const identity = extractXAiAskUserQuestionIdentity(params);107+ const questions = extractXAiAskUserQuestions(params).map((question) => ({108+ id: question.id,109+ header: question.header,110+ question: question.question,111+ options: [...question.options],112+ }));apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts lines 1151 to 1153OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +884,21 @@884+ if (target.providerTurn.providerThreadId !== input.providerThread.id) {885+ return yield* new ProviderAdapterRollbackThreadError({886+ driver: CLAUDE_PROVIDER,887+ providerThreadId: input.providerThread.id,888+ cause: `Cannot roll back Claude thread ${input.providerThread.id} to provider turn ${target.providerTurn.id}: target turn belongs to provider thread ${target.providerTurn.providerThreadId}.`,889+ });890+ }891+892+ const nativeTurnRef = target.providerTurn.nativeTurnRef;893+ if (894+ nativeTurnRef !== null &&895+ nativeTurnRef.driver === CLAUDE_PROVIDER &&896+ nativeTurnRef.nativeId !== null &&897+ !isSyntheticClaudeTurnId(nativeTurnRef.nativeId)898+ ) {899+ return nativeTurnRef.nativeId;900+ }901+902+ const providerTurnsAfterTarget = input.providerThreadTurns.filter(903+ (turn) => turn.ordinal > target.providerTurn.ordinal && isTerminalProviderTurn(turn),904+ );apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts lines 2435 to 2448OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1704,21 @@1704+ providerTurnId: input.providerTurnId,1705+ nativeItemRef,1706+ runtimeRequestId: null,1707+ checkpointScopeId: null,1708+ startedAt: input.startedAt,1709+ completedAt: input.completedAt,1710+ },1711+ message: {1712+ createdBy: "agent",1713+ creationSource: "provider",1714+ id: messageId,1715+ threadId: input.turnInput.threadId,1716+ runId: input.turnInput.runId,1717+ nodeId,1718+ role: "assistant",1719+ text: input.text,1720+ attachments: [],1721+ streaming: false,1722+ createdAt: input.completedAt,1723+ updatedAt: input.completedAt,1724+ },apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts line 563OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +518,21 @@518+ | { readonly status: "success"; readonly value: Value }519+ | { readonly status: "error"; readonly error: unknown }520+ | undefined {521+ const result = unknownRecord(rawResult);522+ if (result === undefined) {523+ return undefined;524+ }525+ const success = unknownRecord(result.success);526+ if (success !== undefined) {527+ return {528+ status: "success",529+ value: mapSuccess(success),530+ };531+ }532+ return {533+ status: "error",534+ error: result.error ?? result.permissionDenied ?? result,535+ };536+}537+538+function nestedGrepWorkspaceResults(success: Record<string, unknown>): Record<string, unknown> {apps/server/scripts/record-codex-app-server-replay-fixture.ts lines 918 to 919OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +899,21 @@899+ return input.records;900+ }901+ const initializeRequest = input.records.find(902+ (record) => record.type === "expect_outbound" && record.label === "initialize",903+ );904+ const initializeResponse = input.records.find(905+ (record) => record.type === "emit_inbound" && record.label === "initialize",906+ );907+ const initializedNotification = input.records.find(908+ (record) => record.type === "expect_outbound" && record.label === "initialized",909+ );910+ if (911+ initializeRequest === undefined ||912+ initializeResponse === undefined ||913+ initializedNotification === undefined914+ ) {915+ throw new Error(`Scenario ${input.scenario} is missing initialization records.`);916+ }917+918+ let nextRequestId = 1;919+ let forkSessionOrdinal = 0;@@ -0,0 +460,21 @@460+ return result.output.counts.map((entry) => ({461+ fileName: entry.file,462+ preview: `${entry.count} matches`,463+ }));464+ }465+ return result.output.matches.map((entry) => ({466+ fileName: entry.file,467+ ...(entry.lineNumber === undefined ? {} : { line: entry.lineNumber }),468+ preview: entry.line,469+ }));470+ });471+ case "semSearch":472+ return [473+ {474+ fileName: "semantic-search",475+ preview: toolCall.result.value.results,476+ },477+ ];478+ default:479+ return [];480+ }@@ -0,0 +514,21 @@514+ readonly nativeThreadId: string;515+ readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;516+ readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;517+ readonly modelSelection: ModelSelection;518+}) {519+ return Effect.gen(function* () {520+ const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);521+ const approvalPolicy =522+ input.runtimePolicy.approvalPolicy === undefined523+ ? runtimeModeDefaults.approvalPolicy524+ : yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy);525+ const sandboxPolicy =526+ input.runtimePolicy.sandboxPolicy === undefined527+ ? runtimeModeDefaults.sandboxPolicy528+ : yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy);529+ const selectedEffort = getModelSelectionStringOptionValue(530+ input.modelSelection,531+ "reasoningEffort",532+ );533+ const effort =534+ selectedEffort === undefined ? undefined : yield* decodeTurnReasoningEffort(selectedEffort);apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 628OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +502,21 @@502+ direction: "outgoing",503+ stage: "decoded",504+ payload: {505+ type: "query.open",506+ options: loggedClaudeQueryOptions(input.options),507+ },508+ });509+510+ return {511+ messages: Stream.fromAsyncIterable(queryRuntime, (cause) =>512+ queryRunnerError(cause, "fromAsyncIterable"),513+ ).pipe(514+ Stream.tap((message) =>515+ logProtocolEvent({516+ direction: "incoming",517+ stage: "decoded",518+ payload: message,519+ }),520+ ),521+ ),522+ offer: (message) =>@@ -0,0 +534,21 @@534+ })),535+ ];536+537+ if (requiresApproval) {538+ rules.push({ permission: "*", pattern: "*", action: "ask" });539+ for (const permission of OPENCODE_RESTRICTED_PERMISSIONS) {540+ rules.push({ permission, pattern: "*", action: "ask" });541+ }542+ }543+544+ rules.push(545+ ...OPENCODE_ALWAYS_ALLOWED_PERMISSIONS.map((permission) => ({546+ permission,547+ pattern: "*",548+ action: "allow" as const,549+ })),550+ );551+552+ if (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite") {553+ rules.push({ permission: "edit", pattern: "*", action: "allow" });554+ }
- apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 637OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +617,21 @@617+618+export function makeClaudeQueryOptions(input: {619+ readonly modelSelection: ModelSelection;620+ readonly nativeThreadId: string;621+ readonly resume: boolean;622+ readonly resumeSessionAt?: string;623+ readonly cwd: string | null;624+ readonly settings?: ClaudeSettings;625+ readonly sdkSettings?: string | ClaudeSdkSettings;626+ readonly environment?: NodeJS.ProcessEnv;627+ readonly mcpServers?: ClaudeQueryOptions["mcpServers"];628+ readonly tools?: ClaudeAgentSdkQueryTools;629+ readonly allowedTools?: ReadonlyArray<string>;630+ readonly disallowedTools?: ReadonlyArray<string>;631+ readonly permissionMode?: PermissionMode;632+ readonly canUseTool?: CanUseTool;633+ readonly allowDangerouslySkipPermissions?: boolean;634+}): ClaudeAgentSdkQueryOptions {635+ const compiledSelection = compileClaudeModelSelection(input.modelSelection);636+ const extraArgs =637+ input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags;apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts line 243OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +223,21 @@223+} satisfies OrchestrationV2ProviderCapabilities;224+225+function negotiatedCapabilities(226+ base: OrchestrationV2ProviderCapabilities,227+ started: AcpSessionRuntimeStartResult,228+): OrchestrationV2ProviderCapabilities {229+ const agent = started.initializeResult.agentCapabilities ?? {};230+ const session = agent.sessionCapabilities;231+ const setup = started.sessionSetupResult;232+ const hasModelConfig =233+ setup.configOptions?.some((option) => option.category === "model") === true;234+ const hasModeConfig = setup.configOptions?.some((option) => option.category === "mode") === true;235+ const supportsMcp = agent.mcpCapabilities?.http === true || agent.mcpCapabilities?.sse === true;236+ const canLoad = agent.loadSession === true;237+ const canFork = session?.fork != null;238+ return {239+ ...base,240+ sessions: {241+ ...base.sessions,242+ supportsModelSwitchInSession: setup.models != null || hasModelConfig,243+ supportsRuntimeModeSwitchInSession: setup.modes != null || hasModeConfig,apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 2385OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1641,21 @@1641+ OrchestrationV2ProviderTurn["status"],1642+ "completed" | "interrupted" | "failed" | "cancelled"1643+> {1644+ if (message.subtype === "success") {1645+ return "completed";1646+ }1647+ const errorText = message.errors.join("\n").toLowerCase();1648+ if (errorText.includes("interrupt")) {1649+ return "interrupted";1650+ }1651+ if (errorText.includes("cancel")) {1652+ return "cancelled";1653+ }1654+ return "failed";1655+}1656+1657+function isClaudeActiveSteeringAbortResult(message: SDKResultMessage): boolean {1658+ return message.terminal_reason === "aborted_streaming";1659+}1660+1661+function buildAssistantArtifacts(input: {apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts line 100OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +80,21 @@80+function readArgValue(name: string): string | undefined {81+ const index = process.argv.indexOf(name);82+ return index === -1 ? undefined : process.argv[index + 1];83+}84+85+function encodeTranscriptNdjson(86+ transcript: Awaited<ReturnType<typeof recordCursorAgentSdkReplayTranscript>>,87+): string {88+ const { entries, ...metadata } = transcript;89+ return [90+ encodeUnknownJsonString({ type: "transcript_start", ...metadata }),91+ ...entries.map((entry) => encodeUnknownJsonString(entry)),92+ "",93+ ].join("\n");94+}95+96+const runFileSystem = <A, E>(97+ effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,98+): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));99+100+async function prepareWorkspace(scenario: RecordingName): Promise<{@@ -106,15 +99,4 @@10699 return emptyDiff;107100 }108101109- const threadContext = yield* projectionSnapshotQuery110- .getThreadCheckpointContext(input.threadId)111- .pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));112- if (Option.isNone(threadContext)) {113- return yield* new CheckpointThreadNotFoundError({114- operation,115- threadId: input.threadId,116- });117- }118-119- const maxTurnCount = threadContext.value.checkpoints.reduce(120- (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),102+ const projection = yield* threads.getThreadProjection(input.threadId).pipe(apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts line 920OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +661,21 @@661+ }),662+ ...threadIdentity,663+ ...(input.resumeSessionAt === undefined ? {} : { resumeSessionAt: input.resumeSessionAt }),664+ ...(input.allowedTools === undefined ? {} : { allowedTools: [...input.allowedTools] }),665+ ...(input.disallowedTools === undefined ? {} : { disallowedTools: [...input.disallowedTools] }),666+ ...(input.canUseTool === undefined ? {} : { canUseTool: input.canUseTool }),667+ ...(input.allowDangerouslySkipPermissions === true668+ ? { allowDangerouslySkipPermissions: true }669+ : {}),670+ ...(querySettings === undefined ? {} : { settings: querySettings }),671+ ...(input.settings?.binaryPath672+ ? { pathToClaudeCodeExecutable: input.settings.binaryPath }673+ : {}),674+ ...(input.environment === undefined ? {} : { env: input.environment }),675+ ...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }),676+ ...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),677+ };678+ return input.cwd === null ? options : { ...options, cwd: input.cwd };679+}680+681+export function claudeMcpQueryOverrides(input: {apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts lines 1276 to 1284OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +993,21 @@993+ options: CodexClient.CodexAppServerClientOptions & {994+ readonly command: string;995+ readonly args?: ReadonlyArray<string>;996+ readonly cwd?: string;997+ readonly env?: NodeJS.ProcessEnv;998+ },999+): Layer.Layer<CodexAppServerClientFactory, never, ChildProcessSpawner.ChildProcessSpawner> =>1000+ Layer.effect(1001+ CodexAppServerClientFactory,1002+ Effect.gen(function* () {1003+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;1004+ return CodexAppServerClientFactory.of({1005+ open: (input) =>1006+ Effect.gen(function* () {1007+ const scope = yield* Scope.Scope;1008+ const command = yield* makeCodexAppServerSpawnCommand({1009+ command: options.command,1010+ args: [...(options.args ?? [])],1011+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),1012+ ...(options.env === undefined ? {} : { env: options.env, extendEnv: true }),1013+ });apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts lines 772 to 778OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +736,21 @@736+ return value;737+ }738+ const direct =739+ nestedString(value, ["text"]) ??740+ nestedString(value, ["message", "text"]) ??741+ nestedString(value, ["userMessage", "text"]) ??742+ nestedString(value, ["assistantMessage", "text"]);743+ if (direct !== undefined) {744+ return direct;745+ }746+ const content = unknownRecord(value)?.content;747+ if (!Array.isArray(content)) {748+ return "";749+ }750+ return content751+ .flatMap((part) => {752+ const text = unknownRecord(part)?.text;753+ return typeof text === "string" ? [text] : [];754+ })755+ .join("");756+}@@ -0,0 +367,21 @@367+ run: (input) => RunId.make(joinId("run", "thread", input.threadId, "ordinal", input.ordinal)),368+ runAttempt: (input) =>369+ RunAttemptId.make(370+ joinId("run-attempt", "run", input.runId, "attempt", input.attemptOrdinal),371+ ),372+ rootNode: (input) => NodeId.make(joinId("node", "run", input.runId, "root")),373+ rootNodeAttempt: (input) =>374+ NodeId.make(joinId("node", "run", input.runId, "attempt", input.attemptOrdinal, "root")),375+ userTurnItem: (input) => TurnItemId.make(joinId("turn-item", "message", input.messageId)),376+ runSignalTurnItem: (input) =>377+ TurnItemId.make(joinId("turn-item", "run", input.runId, "signal", input.signal)),378+ providerThread: (input) =>379+ ProviderThreadId.make(380+ joinId(381+ "provider-thread",382+ "provider",383+ input.driver,384+ "native-thread",385+ input.nativeThreadId,386+ ),387+ ),apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts lines 424 to 424OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +404,21 @@404+405+export function loggedClaudeQueryOptions(406+ options: ClaudeAgentSdkQueryOptions,407+): ClaudeAgentSdkLoggedQueryOptions {408+ return {409+ model: options.model,410+ tools: options.tools,411+ permissionMode: options.permissionMode,412+ ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),413+ ...(options.resume === undefined ? {} : { resume: options.resume }),414+ ...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),415+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),416+ ...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),417+ ...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),418+ ...(options.settings === undefined ? {} : { settings: options.settings }),419+ ...(options.effort === undefined ? {} : { effort: options.effort }),420+ ...(options.includePartialMessages === true ? { includePartialMessages: true } : {}),421+ ...(options.pathToClaudeCodeExecutable === undefined422+ ? {}423+ : { pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable }),424+ ...(options.extraArgs === undefined ? {} : { extraArgs: options.extraArgs }),@@ -0,0 +426,21 @@426+ normalized === "edit" ||427+ normalized.includes("write") ||428+ normalized.includes("patch") ||429+ normalizedTool.includes("edit") ||430+ normalizedTool.includes("write") ||431+ normalizedTool.includes("patch")432+ ) {433+ return "file-change";434+ }435+ if (436+ normalized === "read" ||437+ normalized === "glob" ||438+ normalized === "grep" ||439+ normalized === "lsp" ||440+ normalized === "external_directory" ||441+ normalizedTool === "read" ||442+ normalizedTool.includes("glob") ||443+ normalizedTool.includes("grep") ||444+ normalizedTool.includes("search")445+ ) {446+ return "file-read";
Sign in to join this conversation.
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.