feat(droid): add Factory Droid as a provider #7993
Closedfactory-ain3sh(GitHub profile, opens in a new tab)wants to merge 74 commits into
main fromrefs/pull/7993/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/provider/Layers/DroidAdapter.ts line 1934Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1217,21 @@1217+ session,1218+ scope: sessionScope,1219+ rpc,1220+ pendingApprovals: new Map(),1221+ pendingUserInputs: new Map(),1222+ turns:1223+ initialized.kind === "loaded"1224+ ? droidLoadedTurns(initialized.result.session.messages)1225+ : [],1226+ activeTurnId: undefined,1227+ interruptedTurnIds: new Set(),1228+ pendingTurnMessageIds: new Set(),1229+ persistedPendingTurnMessageIds: new Set(),1230+ openItemIds: new Set(),1231+ childSessions: new Map(),1232+ specSuccessorSessionId: undefined,1233+ lastCallTokenUsage:1234+ initialized.kind === "loaded" ? initialized.result.lastCallTokenUsage : undefined,1235+ currentModelId: requestedModelId,1236+ currentReasoningEffort: requestedEffort,1237+ currentInteractionMode: "auto",apps/server/src/provider/Layers/DroidAdapter.ts line 1260OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +1240,21 @@1240+1241+ yield* Stream.runDrain(1242+ Stream.mapEffect(rpc.notifications, (envelope) =>1243+ Effect.gen(function* () {1244+ const notification = envelope.notification;1245+ // The envelope session id is the rewind guard: only the live1246+ // droid session's notifications reach turn handling. Known1247+ // child sessions become task lifecycles; a spec handoff's1248+ // implementation successor streams into the same t3 turn.1249+ if (envelope.sessionId !== undefined && envelope.sessionId !== ctx.droidSessionId) {1250+ if (ctx.childSessions.has(envelope.sessionId)) {1251+ return yield* handleChildSessionNotification(1252+ ctx,1253+ envelope.sessionId,1254+ notification,1255+ );1256+ }1257+ const isSpecSuccessor =1258+ ctx.activeTurnId !== undefined &&1259+ ctx.currentInteractionMode === "spec" &&1260+ (ctx.specSuccessorSessionId === undefined ||apps/server/src/textGeneration/DroidTextGeneration.ts lines 217 to 241OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +221,21 @@221+222+ const generated = yield* runDroidJson({223+ operation: "generateBranchName",224+ cwd: input.cwd,225+ prompt,226+ outputSchemaJson: outputSchema,227+ modelSelection: input.modelSelection,228+ });229+230+ return {231+ branch: sanitizeBranchFragment(generated.branch),232+ };233+ });234+235+ const generateThreadTitle: TextGeneration.TextGeneration["Service"]["generateThreadTitle"] =236+ Effect.fn("DroidTextGeneration.generateThreadTitle")(function* (input) {237+ const { prompt, outputSchema } = buildThreadTitlePrompt({238+ message: input.message,239+ previousTitle: input.previousTitle,240+ attachments: input.attachments,241+ });apps/server/src/provider/droid/DroidRpcClient.ts line 545OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +525,21 @@525+ const splitter = splitNdjsonChunks();526+ const handleLine = (line: string) => {527+ const parsed = parseJsonRpcLine(line);528+ return parsed._tag === "Invalid"529+ ? publishDiagnostic({530+ level: "warning",531+ message: `Unable to parse Droid JSON-RPC line: ${parsed.error}`,532+ line,533+ })534+ : handleMessage(parsed.message);535+ };536+537+ const stdoutFiber = yield* child.stdout.pipe(538+ Stream.decodeText(),539+ Stream.runForEach((chunk) =>540+ Effect.forEach(splitter.push(chunk), handleLine, {541+ discard: true,542+ }),543+ ),544+ Effect.andThen(545+ Effect.forEach(splitter.end(), handleLine, {apps/server/src/provider/Layers/ProviderService.ts line 355OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -337,3 +337,19 @@337337 });338338 });339339340+ // Adapters can change their resume cursor mid-session (droid compaction and341+ // rewind mint successor sessions). Re-persisting the snapshot when a turn342+ // settles keeps the durable binding pointing at the live conversation.343+ const persistSessionSnapshot = (344+ adapter: ProviderAdapterShape<ProviderAdapterError>,345+ instanceId: ProviderInstanceId,346+ threadId: ThreadId,347+ ) =>348+ adapter.listSessions().pipe(349+ Effect.flatMap((activeSessions) => {350+ const live = activeSessions.find((session) => session.threadId === threadId);351+ return live352+ ? upsertSessionBinding({ ...live, providerInstanceId: instanceId }, threadId)353+ : Effect.void;354+ }),355+ Effect.catchCause((cause) =>apps/server/src/provider/droid/DroidRpcClient.ts lines 740 to 742OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +722,21 @@722+ ),723+ );724+ }),725+ );726+ return yield* writeEnvelope({727+ jsonrpc: "2.0",728+ type: "request",729+ factoryApiVersion: "1.0.0",730+ id: requestId,731+ method,732+ params,733+ }).pipe(734+ Effect.andThen(result),735+ Effect.ensuring(736+ SynchronizedRef.update(lifecycle, (state) => {737+ if (state._tag === "Exited") {738+ return state;739+ }740+ const entry = state.pending.get(requestId);741+ if (entry === undefined || entry._tag !== "Pending" || entry.deferred !== deferred) {742+ return state;apps/server/src/provider/Layers/DroidAdapter.ts line 1194OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1174,21 @@1174+ interactionMode: "auto",1175+ ...(requestedModelId ? { modelId: requestedModelId } : {}),1176+ ...(requestedEffort ? { reasoningEffort: requestedEffort } : {}),1177+ ...(input.title ? { title: input.title } : {}),1178+ ...mcpServers,1179+ }),1180+ "droid.initialize_session",1181+ ),1182+ };1183+ const droidSessionId =1184+ initialized.kind === "loaded" ? initialized.sessionId : initialized.result.sessionId;1185+1186+ // A loaded session keeps its persisted settings; re-assert the1187+ // t3-side mode and any requested model so resume behaves like the1188+ // thread the user left.1189+ if (initialized.kind === "loaded") {1190+ yield* requestSession("droid.update_session_settings", {1191+ autonomyLevel,1192+ ...(requestedModelId ? { modelId: requestedModelId } : {}),1193+ ...(requestedEffort ? { reasoningEffort: requestedEffort } : {}),1194+ }).pipe(Effect.ignore);apps/server/src/provider/Layers/DroidProvider.ts lines 107 to 109OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +89,21 @@89+ label: effort,90+ ...(model.defaultReasoningEffort === effort ? { isDefault: true } : {}),91+ })),92+ }),93+ ],94+ });95+}96+97+export function buildDroidDiscoveredModels(98+ models: ReadonlyArray<DroidModelInfo>,99+): ReadonlyArray<ServerProviderModel> {100+ const seen = new Set<string>();101+ return models102+ .filter((model) => model.disabled !== true)103+ .map((model): ServerProviderModel | undefined => {104+ const slug = model.id.trim();105+ if (!slug || seen.has(slug)) return undefined;106+ seen.add(slug);107+ return {108+ slug,109+ name: model.displayName?.trim() || slug,apps/server/src/provider/Layers/DroidAdapter.ts line 332OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +312,21 @@312+313+/**314+ * Recover rewind anchors from a loaded session's durable messages. This315+ * adapter uses the droid user-message id as the t3 turn id, so resumed316+ * threads keep 1:1 rollback anchoring with the turns t3 checkpointed.317+ */318+export function droidLoadedTurns(319+ messages: ReadonlyArray<unknown>,320+): Array<{ id: TurnId; items: Array<unknown> }> {321+ const turns: Array<{ id: TurnId; items: Array<unknown> }> = [];322+ for (const message of messages) {323+ if (!isRecord(message)) continue;324+ const role =325+ typeof message.role === "string"326+ ? message.role327+ : typeof message.type === "string"328+ ? message.type329+ : undefined;330+ if (role !== "user" && role !== "user_message") continue;331+ if (typeof message.id !== "string" || !message.id.trim()) continue;332+ turns.push({ id: TurnId.make(message.id), items: [] });
- apps/server/src/provider/droid/DroidRpcClient.ts lines 44 to 57OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +37,21 @@37+38+export interface DroidProcessExit {39+ readonly code: number | null;40+ readonly signal?: string;41+ readonly description: string;42+}43+44+export class DroidRpcSpawnError extends Data.TaggedError("DroidRpcSpawnError")<{45+ readonly command: string;46+ readonly cause: unknown;47+}> {}48+49+export class DroidRpcError extends Data.TaggedError("DroidRpcError")<{50+ readonly kind: "encode" | "write" | "timeout" | "rpc" | "process-exit" | "duplicate-response";51+ readonly message: string;52+ readonly method?: string;53+ readonly requestId?: string;54+ readonly code?: number;55+ readonly data?: unknown;56+ readonly cause?: unknown;57+}> {}apps/server/src/provider/Layers/DroidAdapter.ts lines 1639 to 1648OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1628,21 @@1628+ });1629+ }1630+ const rewound = yield* decodeExecuteRewindResult(1631+ yield* requestViaRpc(ctx, "droid.execute_rewind", {1632+ sessionId: ctx.droidSessionId,1633+ messageId: String(anchor.id),1634+ filesToRestore: [],1635+ filesToDelete: [],1636+ forkTitle: "T3 Code checkpoint revert",1637+ }),1638+ ).pipe(1639+ Effect.catchTag("SchemaError", (cause) =>1640+ Effect.fail(1641+ new ProviderAdapterRequestError({1642+ provider: PROVIDER,1643+ method: "droid.execute_rewind",1644+ detail: "Failed to decode Droid rewind result.",1645+ cause,1646+ }),1647+ ),1648+ ),
- apps/web/src/components/Icons.tsx lines 217 to 218OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -214,3 +214,5 @@214214 </svg>215215 );216216217+export const DroidIcon: Icon = (props) => (218+ <svg {...props} viewBox="100 90 700 700" fill="currentColor">
- apps/server/src/provider/Layers/DroidAdapter.ts line 902OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +882,21 @@882+ ...(yield* makeEventStamp()),883+ provider: PROVIDER,884+ threadId: ctx.threadId,885+ turnId: ctx.activeTurnId,886+ payload: {887+ taskId: RuntimeTaskId.make(sessionId),888+ status:889+ outcome.state === "completed"890+ ? "completed"891+ : outcome.state === "cancelled"892+ ? "stopped"893+ : "failed",894+ summary: child.description,895+ },896+ });897+ ctx.childSessions.delete(sessionId);898+ }899+ });900+901+ // tool_result carries no tool name; remember tool_call names per session.902+ const toolUseNames = new Map<string, string>();apps/server/src/provider/Layers/DroidProvider.ts lines 127 to 127OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +107,21 @@107+ if (!slug || seen.has(slug)) return undefined;108+ seen.add(slug);109+ return {110+ slug,111+ name: model.displayName?.trim() || slug,112+ ...(model.shortDisplayName?.trim() ? { shortName: model.shortDisplayName.trim() } : {}),113+ isCustom: model.isCustom === true,114+ capabilities: reasoningEffortCapabilities(model),115+ };116+ })117+ .filter((model): model is ServerProviderModel => model !== undefined);118+}119+120+export function buildDroidSlashCommands(121+ commands: ReadonlyArray<DroidCommandInfo>,122+): ReadonlyArray<ServerProviderSlashCommand> {123+ const seen = new Set<string>();124+ const slashCommands: ServerProviderSlashCommand[] = [];125+ for (const command of commands) {126+ const name = command.name.trim();127+ if (!name || seen.has(name)) continue;apps/server/src/provider/Layers/DroidAdapter.ts line 912Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +558,21 @@558+559+ /**560+ * Terminal settlement for a turn. Emits exactly one turn.completed; late561+ * completions for interrupted or already-settled turns are dropped.562+ */563+ const settleTurn = (ctx: DroidSessionContext, turnId: TurnId, outcome: DroidTurnOutcome) =>564+ Effect.gen(function* () {565+ // A pre-marked interrupt outranks any non-cancelled terminal: consume566+ // the mark and drop the notification so the pending cancellation567+ // settles the turn instead. Cancelled outcomes pass through; the568+ // active-turn guard below still prevents a second terminal event.569+ if (ctx.interruptedTurnIds.has(turnId) && outcome.state !== "cancelled") {570+ ctx.interruptedTurnIds.delete(turnId);571+ return;572+ }573+ if (ctx.activeTurnId !== turnId && ctx.session.activeTurnId !== turnId) {574+ // Late cancelled terminal for an already-settled turn retires its mark.575+ if (outcome.state === "cancelled") ctx.interruptedTurnIds.delete(turnId);576+ return;577+ }578+ ctx.pendingTurnMessageIds.clear();
- apps/server/src/provider/Layers/DroidAdapter.ts line 244OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +224,21 @@224+ */225+export function selectDroidPermissionOutcome(226+ options: ReadonlyArray<DroidPermissionOption>,227+ decision: Exclude<ProviderApprovalDecision, "cancel">,228+): string | undefined {229+ const outcomes = options230+ .map((option) => option.outcome.trim())231+ .filter((outcome): outcome is string => Boolean(outcome));232+ const preference =233+ decision === "acceptForSession"234+ ? ["proceed_always", "proceed_always_file", "proceed_always_tools", "proceed_always_server"]235+ : decision === "accept"236+ ? ["proceed_once"]237+ : ["cancel"];238+ for (const preferred of preference) {239+ if (outcomes.includes(preferred)) return preferred;240+ }241+ if (decision === "decline") return outcomes.includes("cancel") ? "cancel" : undefined;242+ // Approvals with bespoke outcome sets (spec exit, autonomy raises) still243+ // proceed on the first non-cancel option droid offered.244+ return outcomes.find((outcome) => outcome !== "cancel");apps/server/src/provider/Layers/DroidAdapter.ts line 1155OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1135,21 @@1135+ ...(yield* makeEventStamp()),1136+ provider: PROVIDER,1137+ threadId: ctx.threadId,1138+ payload: { exitKind: "graceful" },1139+ });1140+ });1141+1142+ const startSession: DroidAdapterShape["startSession"] = (input) =>1143+ Effect.suspend(() => {1144+ if (closing) {1145+ return Effect.fail(1146+ new ProviderAdapterValidationError({1147+ provider: PROVIDER,1148+ operation: "startSession",1149+ issue: "Droid adapter is stopping; cannot start a new session.",1150+ }),1151+ );1152+ }1153+ startingThreads.add(input.threadId);1154+ return startSessionLocked(input).pipe(1155+ Effect.ensuring(Effect.sync(() => startingThreads.delete(input.threadId))),
- apps/server/src/provider/Layers/DroidAdapter.ts line 1696Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1113,21 @@1113+ Effect.catchCause((cause) =>1114+ Effect.logWarning("Droid server request handling failed.", {1115+ cause,1116+ method: request.method,1117+ }).pipe(1118+ Effect.andThen(1119+ request.fail(-32603, "t3-code failed to process the request.").pipe(Effect.ignore),1120+ ),1121+ ),1122+ ),1123+ Effect.forkIn(ctx.scope),1124+ );1125+ };1126+1127+ const stopSessionInternal = (ctx: DroidSessionContext) =>1128+ Effect.gen(function* () {1129+ if (ctx.stopped) return;1130+ ctx.stopped = true;1131+ yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);1132+ yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);1133+ yield* Effect.ignore(Scope.close(ctx.scope, Exit.void));apps/server/src/provider/Layers/DroidAdapter.ts line 1684OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1664,21 @@1664+ }1665+ }),1666+ );1667+ });1668+1669+ const respondToRequest: DroidAdapterShape["respondToRequest"] = (1670+ threadId,1671+ requestId,1672+ decision,1673+ ) =>1674+ Effect.gen(function* () {1675+ const ctx = yield* requireSession(threadId);1676+ const pending = ctx.pendingApprovals.get(requestId);1677+ if (!pending) {1678+ return yield* new ProviderAdapterRequestError({1679+ provider: PROVIDER,1680+ method: "droid.request_permission",1681+ detail: `Unknown pending approval request: ${requestId}`,1682+ });1683+ }1684+ yield* Deferred.succeed(pending.decision, decision);
- apps/server/src/provider/Drivers/DroidDriver.ts lines 170 to 170OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +150,21 @@150+ getSettings: snapshotSettings.getSettings,151+ streamSettings: snapshotSettings.streamSettings,152+ haveSettingsChanged: haveProviderSnapshotSettingsChanged,153+ initialSnapshot: (settings) =>154+ buildInitialDroidProviderSnapshot(settings.provider).pipe(Effect.map(stampIdentity)),155+ checkProvider,156+ enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>157+ enrichDroidSnapshot({158+ snapshot: currentSnapshot,159+ maintenanceCapabilities,160+ enableProviderUpdateChecks: settings.enableProviderUpdateChecks,161+ publishSnapshot,162+ httpClient,163+ }),164+ }).pipe(165+ Effect.mapError(166+ (cause) =>167+ new ProviderDriverError({168+ driver: DRIVER_KIND,169+ instanceId,170+ detail: `Failed to build Droid snapshot: ${cause.message ?? String(cause)}`,
- apps/server/src/provider/Layers/DroidAdapter.ts lines 994 to 1001OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +981,21 @@981+982+ // tool_result carries no tool name; remember tool_call names per session.983+ const rememberToolUse = (ctx: DroidSessionContext, toolUse: DroidToolUse) => {984+ ctx.toolUseNames.set(toolUse.id, toolUse.name);985+ };986+987+ const handlePermissionRequest = (988+ ctx: DroidSessionContext,989+ request: Extract<DroidServerRequest, { method: "droid.request_permission" }>,990+ ) =>991+ Effect.gen(function* () {992+ const params = request.params;993+ yield* logNative(ctx.threadId, "droid.request_permission", request.rawParams);994+ const primaryToolUse = params.toolUses[0];995+ if (primaryToolUse) rememberToolUse(ctx, primaryToolUse.toolUse);996+ const requestId = ApprovalRequestId.make(yield* randomUUIDv4);997+ const runtimeRequestId = RuntimeRequestId.make(requestId);998+ const decision = yield* Deferred.make<ProviderApprovalDecision>();999+ const turnId = ctx.activeTurnId;1000+ ctx.pendingApprovals.set(requestId, { decision });1001+ const requestType = droidCanonicalRequestType(primaryToolUse?.details.type);
- apps/server/src/provider/Layers/DroidAdapter.ts lines 1382 to 1393OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +1373,21 @@1373+ // implementation successor streams into the same t3 turn.1374+ if (envelope.sessionId !== undefined && envelope.sessionId !== ctx.droidSessionId) {1375+ if (ctx.childSessions.has(envelope.sessionId)) {1376+ return yield* handleChildSessionNotification(1377+ ctx,1378+ envelope.sessionId,1379+ notification,1380+ );1381+ }1382+ const isSpecSuccessor =1383+ ctx.activeTurnId !== undefined &&1384+ ctx.currentInteractionMode === "spec" &&1385+ (ctx.specSuccessorSessionId === undefined ||1386+ ctx.specSuccessorSessionId === envelope.sessionId);1387+ if (!isSpecSuccessor) {1388+ return yield* Effect.logDebug(1389+ "Dropped Droid notification from an abandoned session.",1390+ { sessionId: envelope.sessionId, type: notification.type },1391+ );1392+ }1393+ ctx.specSuccessorSessionId = envelope.sessionId;
- apps/server/src/provider/droid/DroidRpcClient.ts line 172OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +512,21 @@512+ });513+514+ const handleMessage = (message: ParsedJsonRpcMessage): Effect.Effect<void> => {515+ switch (message.type) {516+ case "request":517+ return handleServerRequest(message);518+ case "notification":519+ return handleNotification(message);520+ case "response":521+ return resolveResponse(message);522+ }523+ };524+525+ const handleLine = (line: string) => {526+ const parsed = parseJsonRpcLine(line);527+ return parsed._tag === "Invalid"528+ ? publishDiagnostic(`Unable to parse Droid JSON-RPC line: ${parsed.error}`, { line })529+ : handleMessage(parsed.message);530+ };531+532+ const stdoutFiber = yield* child.stdout.pipe(
- apps/server/src/provider/droid/DroidProtocol.ts line 283OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +263,21 @@263+ type: Schema.Literal("tool_progress_update"),264+ toolUseId: Schema.String,265+ toolName: Schema.String,266+ update: Schema.Struct({267+ status: Schema.optional(Schema.String),268+ details: Schema.optional(Schema.String),269+ text: Schema.optional(Schema.String),270+ error: Schema.optional(Schema.String),271+ valueSnippet: Schema.optional(Schema.String),272+ subagentSessionId: Schema.optional(Schema.String),273+ }),274+});275+276+const CreateMessage = Schema.Struct({277+ type: Schema.Literal("create_message"),278+ message: Schema.Unknown,279+});280+281+export const DroidAgentTurnCompleted = Schema.Struct({282+ type: Schema.Literal("agent_turn_completed"),283+ reason: Schema.Literals([
- apps/server/src/provider/Layers/ProviderService.ts line 316OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -312,3 +313,4 @@312313 ),313314 );314315316+ const persistedResumeCursors = yield* Ref.make(
- apps/server/src/textGeneration/DroidTextGeneration.ts line 120Resolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +104,21 @@104+ case "agent_turn_completed":105+ return Deferred.succeed(turnDone, notification.reason).pipe(Effect.asVoid);106+ default:107+ return Effect.void;108+ }109+ }),110+ ).pipe(Effect.forkScoped);111+112+ const reasoningEffort = getModelSelectionStringOptionValue(modelSelection, "reasoningEffort");113+ yield* rpc114+ .request(115+ "droid.initialize_session",116+ {117+ machineId: "default",118+ cwd,119+ autonomyLevel: "off",120+ interactionMode: "auto",121+ // Text generation must never touch the workspace.122+ // Droid treats an empty restriction as unrestricted; an unknown123+ // non-empty id collapses the tool allowlist to zero.124+ restrictToolIds: ["t3_text_generation"],
- apps/server/src/provider/droid/DroidProtocol.ts line 362OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +342,21 @@342+ ToolCall,343+ ToolResult,344+ ToolProgressUpdate,345+ CreateMessage,346+ DroidAgentTurnCompleted,347+ SessionTokenUsageChanged,348+ ErrorNotification,349+ LlmRetry,350+ SessionTitleUpdated,351+ ChildSessionAvailable,352+ Schema.Struct({ type: Schema.Literal("tool_execution_phase_changed") }),353+ Schema.Struct({ type: Schema.Literal("droid_working_state_changed") }),354+ Schema.Struct({ type: Schema.Literal("session_compacted") }),355+ Schema.Struct({ type: Schema.Literal("permission_resolved") }),356+ Schema.Struct({ type: Schema.Literal("queued_messages_discarded") }),357+ Schema.Struct({ type: Schema.Literal("mcp_status_changed") }),358+ Schema.Struct({ type: Schema.Literal("settings_updated") }),359+ Schema.Struct({ type: Schema.Literal("structured_output") }),360+]);361+362+const knownNotificationTypes = new Set([
- apps/server/src/provider/Layers/DroidAdapter.ts line 110OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +90,21 @@90+91+interface ThreadLockEntry {92+ readonly semaphore: Semaphore.Semaphore;93+ readonly references: number;94+}95+96+interface PendingApproval {97+ readonly decision: Deferred.Deferred<ProviderApprovalDecision>;98+}99+100+type PendingUserInputResolution =101+ | { readonly _tag: "answered"; readonly answers: ProviderUserInputAnswers }102+ | { readonly _tag: "cancelled" };103+104+interface PendingUserInput {105+ readonly resolution: Deferred.Deferred<PendingUserInputResolution>;106+}107+108+interface DroidSessionContext {109+ readonly threadId: ThreadId;110+ /** Mutable: rewind/compact mint a successor session id. */
- apps/server/src/provider/Layers/DroidAdapter.test.ts line 482Resolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +291,21 @@291+ );292+293+ it.effect("reaps thread locks after session teardown and failed startup", () =>294+ Effect.gen(function* () {295+ const { adapter, readDebugState } = yield* makeDroidScenario();296+ const { adapter: failingAdapter, readDebugState: readFailingDebugState } =297+ yield* makeDroidScenario({ T3_DROID_MOCK_FAIL_INIT: "1" });298+ const threadId = ThreadId.make("droid-thread-lock-reaped");299+ const failedThreadId = ThreadId.make("droid-failed-thread-lock-reaped");300+301+ yield* startDroidSession(adapter, threadId, "full-access");302+ assert.equal((yield* readDebugState(threadId)).threadLockCount, 1);303+ yield* adapter.stopSession(threadId);304+ assert.equal((yield* readDebugState(threadId)).threadLockCount, 0);305+306+ yield* Effect.flip(startDroidSession(failingAdapter, failedThreadId, "full-access"));307+ assert.equal((yield* readFailingDebugState(failedThreadId)).threadLockCount, 0);308+ }),309+ );310+311+ it.effect("waits for every same-thread start before stopAll returns", () =>
- apps/server/src/provider/Layers/ProviderService.ts line 1192OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -1103,3 +1190,3 @@11031190 "provider.rollback_turns": input.numTurns,11041191 });11051192 yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
- apps/server/src/provider/Layers/DroidAdapter.ts line 1690OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +1670,21 @@1670+ }1671+ return { _tag: "Proceed" as const, interruptedTurnId };1672+ });1673+ if (observed._tag === "Ignore") return;1674+1675+ yield* withThreadLock(1676+ threadId,1677+ Effect.gen(function* () {1678+ const ctx = yield* requireSession(threadId);1679+ const activeTurnId = ctx.activeTurnId ?? ctx.session.activeTurnId;1680+ const interruptedTurnId = observed.interruptedTurnId ?? activeTurnId;1681+ if (1682+ interruptedTurnId !== undefined &&1683+ activeTurnId !== undefined &&1684+ activeTurnId !== interruptedTurnId1685+ ) {1686+ return;1687+ }1688+ yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals);1689+ yield* settlePendingUserInputsAsCancelled(ctx.pendingUserInputs);1690+ yield* Effect.ignore(requestViaRpc(ctx, "droid.interrupt_session", {}));
- apps/server/src/provider/droid/DroidRpcClient.ts line 272OutdatedResolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +252,21 @@252+ });253+ }254+ return new DroidRpcError({255+ kind: "rpc",256+ method,257+ requestId,258+ data: error,259+ });260+}261+262+export const makeDroidRpcClient = (263+ input: DroidRpcSpawnInput,264+): Effect.Effect<265+ DroidRpcClient,266+ DroidRpcSpawnError,267+ ChildProcessSpawner.ChildProcessSpawner | Scope.Scope268+> =>269+ Effect.gen(function* () {270+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;271+ const runtimeScope = yield* Scope.Scope;272+ const outgoing = yield* Queue.unbounded<string, Cause.Done<void>>();
- apps/server/src/provider/Errors.ts lines 159 to 160OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -152,4 +156,5 @@152156 },153157 ) {154158 override get message(): string {155- return `Provider driver '${this.driver}' failed to create instance '${this.instanceId}': ${this.detail}`;159+ const causeDetail = this.cause === undefined ? "" : ` Cause: ${formatDefect(this.cause)}`;160+ return `Provider driver '${this.driver}' failed to create instance '${this.instanceId}': ${this.detail}${causeDetail}`;
- apps/server/src/provider/Layers/DroidAdapter.ts line 2042Resolvedby factory-ain3sh(GitHub profile, opens in a new tab)@@ -0,0 +1475,21 @@1475+1476+ // handleServerRequest forks each HITL exchange and answers the RPC1477+ // on failure, so draining the request stream itself cannot fail.1478+ yield* Stream.runDrain(1479+ Stream.mapEffect(rpc.serverRequests, (request) =>1480+ Effect.asVoid(handleServerRequest(ctx, request)),1481+ ),1482+ ).pipe(Effect.forkIn(ctx.scope));1483+1484+ // Unexpected process death fails the active turn and tears the1485+ // session down so the UI never waits on a corpse.1486+ yield* rpc.exits.pipe(1487+ Effect.flatMap((exit) =>1488+ withThreadLock(1489+ input.threadId,1490+ Effect.gen(function* () {1491+ // Identity check, not a session-id compare: rewind mints a1492+ // successor droid session id on this same process, and a1493+ // stale watcher must not tear down a replacement session.1494+ const live = sessions.get(input.threadId);1495+ if (live !== ctx || live.stopped) return;apps/server/src/provider/Layers/ProviderService.ts line 349OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -337,3 +338,12 @@337338 });338339 });339340341+ const persistEventResumeCursor = (342+ source: {343+ readonly instanceId: ProviderInstanceId;344+ readonly provider: ProviderDriverKind;345+ },346+ event: ProviderRuntimeEvent,347+ ) =>348+ event.type === "turn.completed" && event.payload?.resumeCursor !== undefined349+ ? directory.upsert({apps/server/src/provider/droid/DroidRpcClient.ts line 501OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +481,21 @@481+ return;482+ }483+ if (message.error !== undefined) {484+ yield* Deferred.fail(485+ requestState.deferred,486+ jsonRpcErrorFromMessage(message.error, requestState.method, requestId),487+ );488+ return;489+ }490+ yield* Deferred.succeed(requestState.deferred, message.result);491+ });492+493+ const makeServerRequestBase = (id: string, method: string, sessionId: string | undefined) =>494+ Effect.gen(function* () {495+ const answered = yield* Ref.make(false);496+ const answerOnce = (497+ result:498+ | { readonly _tag: "Success"; readonly value: unknown }499+ | { readonly _tag: "Failure"; readonly code: number; readonly message: string },500+ ) =>501+ Ref.getAndSet(answered, true).pipe(apps/server/src/provider/Layers/CodexAdapter.ts line 1885OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1875,7 +1871,15 @@1875- issue: "numTurns must be an integer >= 1.",1876- }),1877- );1878- }1879-1871+ const rollbackThread: CodexAdapterShape["rollbackThread"] = (threadId, target) => {18801872 return requireSession(threadId).pipe(1881- Effect.flatMap((session) => session.runtime.rollbackThread(numTurns)),1873+ Effect.flatMap((session) =>1874+ Effect.gen(function* () {1875+ const snapshot = yield* session.runtime.readThread;1876+ if (snapshot.turns.length < target.turnIds.length) {1877+ return yield* new ProviderAdapterValidationError({1878+ provider: PROVIDER,1879+ operation: "rollbackThread",1880+ issue: `Cannot roll back to ${target.turnIds.length} turns from ${snapshot.turns.length}.`,1881+ });1882+ }1883+ return snapshot.turns.length === target.turnIds.length1884+ ? snapshot1885+ : yield* session.runtime.rollbackThread(snapshot.turns.length - target.turnIds.length);apps/server/src/provider/droid/DroidRpcClient.ts line 616OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +596,21 @@596+ });597+598+ const handleNotification = (message: ParsedJsonRpcMessage): Effect.Effect<void> =>599+ Effect.gen(function* () {600+ if (message.method !== "droid.session_notification") {601+ return;602+ }603+ if (!Predicate.isObject(message.params)) {604+ yield* publishDiagnostic("Ignoring Droid session notification with invalid params");605+ return;606+ }607+ const decoded = yield* decodeNotification(message.params.notification).pipe(Effect.result);608+ if (decoded._tag === "Failure") {609+ yield* publishDiagnostic("Unable to decode Droid session notification", {610+ cause: decoded.failure,611+ });612+ return;613+ }614+ const sessionId =615+ typeof message.params.sessionId === "string" ? message.params.sessionId : undefined;616+ yield* Queue.offer(notificationPubSub, {apps/server/src/provider/droid/DroidRpcClient.ts line 540OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +520,21 @@520+ value: result,521+ }),522+ fail: (code: number, message: string) =>523+ answerOnce({524+ _tag: "Failure",525+ code,526+ message,527+ }),528+ };529+ });530+531+ const publishServerRequest = (request: DroidServerRequest) =>532+ Queue.offer(serverRequestPubSub, request).pipe(Effect.asVoid);533+534+ const handleServerRequest = (message: ParsedJsonRpcMessage): Effect.Effect<void> =>535+ Effect.gen(function* () {536+ if (message.id === undefined || message.id === null || typeof message.method !== "string") {537+ yield* publishDiagnostic("Ignoring malformed server-initiated Droid request");538+ return;539+ }540+ const id = String(message.id);apps/server/src/provider/Layers/ClaudeAdapter.ts lines 4502 to 4502OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -4485,7 +4490,13 @@44854490 );4486449144874492 const rollbackThread: ClaudeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(4488- function* (threadId, numTurns) {4493+ function* (threadId, target) {44894494 const context = yield* requireSession(threadId);4490- const nextLength = Math.max(0, context.turns.length - numTurns);4491- context.turns.splice(nextLength);4495+ if (context.turns.length < target.turnIds.length) {4496+ return yield* new ProviderAdapterValidationError({4497+ provider: PROVIDER,4498+ operation: "rollbackThread",4499+ issue: `Cannot roll back to ${target.turnIds.length} turns from ${context.turns.length}.`,4500+ });4501+ }4502+ context.turns.splice(target.turnIds.length);
- apps/server/src/orchestration/Layers/CheckpointReactor.ts line 768OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -689,0 +748,21 @@748+ providerSessionDirectory.updateRuntimePayloadIfOwned({749+ threadId: intent.threadId,750+ providerInstanceId: intent.providerInstanceId,751+ sessionLease: intent.sessionLease,752+ runtimePayload: { checkpointRevertIntent: intent },753+ });754+755+ const clearCheckpointRevertIntent = (intent: CheckpointRevertIntent, resumeCursor?: unknown) =>756+ providerSessionDirectory.getBinding(intent.threadId).pipe(757+ Effect.map(Option.getOrUndefined),758+ Effect.flatMap((binding) => {759+ if (760+ binding?.providerInstanceId !== intent.providerInstanceId ||761+ binding.sessionLease === null ||762+ binding.sessionLease === undefined763+ ) {764+ return Effect.succeed(false);765+ }766+ const providerInstanceId = binding.providerInstanceId;767+ const sessionLease = binding.sessionLease;768+ return providerSessionDirectoryapps/server/src/provider/droid/DroidRpcClient.ts line 781OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +761,21 @@761+ const finalizeTransportExit = (exit: DroidProcessExit) =>762+ Effect.gen(function* () {763+ yield* Queue.end(outgoing);764+ const finalExit = yield* finishProcessExit(exit);765+ if (finalExit === undefined) return;766+ yield* Effect.all([Queue.end(notificationPubSub), Queue.end(serverRequestPubSub)], {767+ discard: true,768+ });769+ yield* Deferred.succeed(exitDeferred, finalExit);770+ });771+772+ const stdoutFiber = yield* child.stdout.pipe(773+ Stream.decodeText(),774+ splitJsonRpcLines,775+ Stream.filter((line) => line.trim().length > 0),776+ Stream.runForEach(handleLine),777+ Effect.matchCauseEffect({778+ onFailure: (cause) =>779+ publishDiagnostic("Droid stdout stream failed", { cause }).pipe(780+ Effect.andThen(781+ finalizeTransportExit({apps/server/src/provider/Layers/GrokAdapter.ts line 1397OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1403,13 +1384,14 @@14031384 return { threadId, turns: ctx.turns };14041385 });140513861406- const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, numTurns) =>1387+ const rollbackThread: GrokAdapterShape["rollbackThread"] = (threadId, target) =>14071388 Effect.gen(function* () {1408- yield* requireSession(threadId);1409- if (!Number.isInteger(numTurns) || numTurns < 1) {1389+ const ctx = yield* requireSession(threadId);1390+ if (!rollbackTargetMatchesTurnPrefix(ctx.turns, target)) {14101391 return yield* new ProviderAdapterValidationError({14111392 provider: PROVIDER,14121393 operation: "rollbackThread",1413- issue: "numTurns must be an integer >= 1.",1394+ issue: "Rollback target does not match the current thread history.",14141395 });14151396 }1397+ if (ctx.turns.length === target.turnIds.length) {
Sign in to join this conversation.
📝 Walkthrough
Walkthrough#
Factory Droid support is added across contracts, JSON-RPC transport, provider sessions, discovery, text generation, interfaces, tests, and documentation. Approval handling supports plan requests. Rollback uses explicit turn identifiers and persists resume cursors.
Changes#
Factory Droid integration
packages/contracts/src/*,apps/server/src/provider/droid/*,apps/server/scripts/droid-mock-agent.tsapps/server/src/provider/Drivers/DroidDriver.ts,apps/server/src/provider/Layers/*,apps/server/src/provider/builtInDrivers.tsapps/server/src/provider/Services/*,apps/server/src/orchestration/Layers/*,apps/web/src/session-logic.ts,apps/mobile/src/lib/threadActivity.tsapps/server/src/textGeneration/*,apps/web/src/*,apps/mobile/src/*README.md,docs/*,**/*test*Estimated code review effort: 5 (Critical) | ~120 minutes
Merge Risk: 🟠 High · up to
689c6The PR adds a disabled-by-default provider that launches a local executable and supports session resume and checkpoint rollback. Current behavior can leave workspace and provider history out of sync, resume from stale session state after a persistence failure, reject newer approval requests, and expose users to an unverified installer path; enabling the provider also grants the configured executable the server user's access. These issues create significant merge-readiness risk and should be fixed or explicitly accepted before merge.
Suggested reviewers:
juliusmarminge,t3dotgg🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
Full details: Docstring Coverage
Explanation
Docstring coverage is 4.17% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 96 functions across 80 files. (13 skipped: 8 unsupported, 5 over the file limit.)
Full details: Description check
Explanation
The description provides detailed what, why, implementation, UI evidence, testing, risk, rollout, and scope information. It does not use the template's exact section headings and omits the checklist, but it is substantially complete and directly related to the changes.
✨ Finishing Touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands.