The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { |
| 2 | AcpRegistryOperationError, |
| 3 | CommandId, |
| 4 | ThreadId, |
| 5 | type AcpRegistryImportSessionInput, |
| 6 | type AcpRegistryImportSessionResult, |
| 7 | type Project, |
| 8 | type ProjectId, |
| 9 | type ProviderDriverKind, |
| 10 | type ProviderInstanceId, |
| 11 | } from "@t3tools/contracts"; |
| 12 | import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator"; |
| 13 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 14 | import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; |
| 15 | import * as Context from "effect/Context"; |
| 16 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 17 | import * as Effect from "effect/Effect"; |
| 18 | import * as Layer from "effect/Layer"; |
| 19 | import * as Result from "effect/Result"; |
| 20 | import * as SqlClient from "effect/sql/SqlClient"; |
| 21 | |
| 22 | import * as ThreadLaunchService from "../orchestration-v2/ThreadLaunchService.ts"; |
| 23 | import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; |
| 24 | import * as AgentSessionImporter from "../project/AgentSessionImporter.ts"; |
| 25 | import * as ProjectService from "../project/ProjectService.ts"; |
| 26 | import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts"; |
| 27 | import * as ProviderInstanceRegistry from "./ProviderInstanceRegistry.ts"; |
| 28 | import * as ProviderRegistry from "./ProviderRegistry.ts"; |
| 29 | |
| 30 | export const importedThreadId = (input: { |
| 31 | readonly driver: ProviderDriverKind; |
| 32 | readonly instanceId: ProviderInstanceId; |
| 33 | readonly sessionId: string; |
| 34 | }) => |
| 35 | IdAllocator.deriveThreadFromProviderThread({ |
| 36 | driver: input.driver, |
| 37 | providerInstanceId: input.instanceId, |
| 38 | nativeThreadId: input.sessionId, |
| 39 | }); |
| 40 | |
| 41 | export class AcpRegistrySessions extends Context.Service< |
| 42 | AcpRegistrySessions, |
| 43 | { |
| 44 | readonly project: (projectId: ProjectId) => Effect.Effect<Project, AcpRegistryOperationError>; |
| 45 | readonly sessionManager: (instanceId: ProviderInstanceId) => Effect.Effect< |
| 46 | { |
| 47 | readonly instance: ProviderInstance; |
| 48 | readonly manager: NonNullable<ProviderInstance["acpSessionManagement"]>; |
| 49 | }, |
| 50 | AcpRegistryOperationError |
| 51 | >; |
| 52 | readonly findOwner: (input: { |
| 53 | readonly driver: ProviderDriverKind; |
| 54 | readonly instanceId: ProviderInstanceId; |
| 55 | readonly sessionId: string; |
| 56 | }) => Effect.Effect<ThreadId | null, AcpRegistryOperationError>; |
| 57 | /** |
| 58 | * Binds a native ACP session to a T3 thread and copies its history in. Importing a |
| 59 | * session whose thread still lacks its history repairs that thread instead. |
| 60 | */ |
| 61 | readonly importSession: ( |
| 62 | input: AcpRegistryImportSessionInput, |
| 63 | ) => Effect.Effect<AcpRegistryImportSessionResult, AcpRegistryOperationError>; |
| 64 | } |
| 65 | >()("t3/provider/AcpRegistrySessions") {} |
| 66 | |
| 67 | const make = Effect.gen(function* () { |
| 68 | const projectService = yield* ProjectService.ProjectService; |
| 69 | const providerInstances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; |
| 70 | const providerRegistry = yield* ProviderRegistry.ProviderRegistry; |
| 71 | const coordinator = yield* AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator; |
| 72 | const threadManagement = yield* ThreadManagementService.ThreadManagementService; |
| 73 | const threadLaunch = yield* ThreadLaunchService.ThreadLaunchService; |
| 74 | const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup; |
| 75 | const agentSessionImporter = yield* AgentSessionImporter.AgentSessionImporter; |
| 76 | const random = yield* SecureRandom.SecureRandom; |
| 77 | const sql = yield* SqlClient.SqlClient; |
| 78 | |
| 79 | const findOwner = Effect.fn("AcpRegistrySessions.findOwner")(function* (input: { |
| 80 | readonly driver: ProviderDriverKind; |
| 81 | readonly instanceId: ProviderInstanceId; |
| 82 | readonly sessionId: string; |
| 83 | }) { |
| 84 | const rows = yield* sql<{ readonly thread_id: string }>` |
| 85 | SELECT provider.thread_id |
| 86 | FROM orchestration_v2_projection_provider_threads AS provider |
| 87 | JOIN orchestration_v2_projection_threads AS thread ON thread.thread_id = provider.thread_id |
| 88 | WHERE provider.driver = ${input.driver} |
| 89 | AND provider.provider_instance_id = ${input.instanceId} |
| 90 | AND json_extract(provider.payload_json, '$.nativeThreadRef.nativeId') = ${input.sessionId} |
| 91 | AND thread.deleted_at IS NULL |
| 92 | ORDER BY thread.updated_at DESC |
| 93 | LIMIT 1 |
| 94 | `.pipe( |
| 95 | Effect.mapError( |
| 96 | (cause) => |
| 97 | new AcpRegistryOperationError({ |
| 98 | reason: "session_import_failed", |
| 99 | message: "Could not inspect ACP session ownership.", |
| 100 | cause, |
| 101 | }), |
| 102 | ), |
| 103 | ); |
| 104 | return rows[0] ? ThreadId.make(rows[0].thread_id) : null; |
| 105 | }); |
| 106 | |
| 107 | const project = Effect.fn("AcpRegistrySessions.project")(function* (projectId: ProjectId) { |
| 108 | const found = yield* projectService.getById(projectId).pipe( |
| 109 | Effect.mapError( |
| 110 | (cause) => |
| 111 | new AcpRegistryOperationError({ |
| 112 | reason: "project_not_found", |
| 113 | message: `Project ${projectId} is unavailable.`, |
| 114 | cause, |
| 115 | }), |
| 116 | ), |
| 117 | ); |
| 118 | return yield* Effect.fromOption( |
| 119 | found, |
| 120 | () => |
| 121 | new AcpRegistryOperationError({ |
| 122 | reason: "project_not_found", |
| 123 | message: `Project ${projectId} was not found.`, |
| 124 | }), |
| 125 | ); |
| 126 | }); |
| 127 | |
| 128 | const sessionManager = Effect.fn("AcpRegistrySessions.sessionManager")(function* ( |
| 129 | instanceId: ProviderInstanceId, |
| 130 | ) { |
| 131 | const instance = yield* providerInstances.getInstance(instanceId); |
| 132 | if (instance === undefined) { |
| 133 | return yield* new AcpRegistryOperationError({ |
| 134 | reason: "instance_not_found", |
| 135 | message: `Provider instance ${instanceId} was not found.`, |
| 136 | }); |
| 137 | } |
| 138 | if (instance.acpSessionManagement === undefined) { |
| 139 | return yield* new AcpRegistryOperationError({ |
| 140 | reason: "session_list_unsupported", |
| 141 | message: `Provider instance ${instanceId} does not expose ACP session management.`, |
| 142 | }); |
| 143 | } |
| 144 | return { instance, manager: instance.acpSessionManagement }; |
| 145 | }); |
| 146 | |
| 147 | const importSession = Effect.fn("AcpRegistrySessions.importSession")(function* ( |
| 148 | input: AcpRegistryImportSessionInput, |
| 149 | ) { |
| 150 | const { workspaceRoot } = yield* project(input.projectId); |
| 151 | const { instance } = yield* sessionManager(input.instanceId); |
| 152 | const providerSnapshot = yield* instance.snapshot.getSnapshot; |
| 153 | if ( |
| 154 | providerSnapshot.nativeSessions?.canLoad !== true && |
| 155 | providerSnapshot.nativeSessions?.canResume !== true |
| 156 | ) { |
| 157 | return yield* new AcpRegistryOperationError({ |
| 158 | reason: "session_resume_unsupported", |
| 159 | message: "The ACP agent cannot load or resume native sessions.", |
| 160 | }); |
| 161 | } |
| 162 | const threadId = importedThreadId({ |
| 163 | driver: instance.driverKind, |
| 164 | instanceId: input.instanceId, |
| 165 | sessionId: input.sessionId, |
| 166 | }); |
| 167 | const owner = yield* findOwner({ |
| 168 | driver: instance.driverKind, |
| 169 | instanceId: input.instanceId, |
| 170 | sessionId: input.sessionId, |
| 171 | }); |
| 172 | if (owner !== null && owner !== threadId) return { threadId: owner, imported: false } as const; |
| 173 | const existing = yield* threadManagement.getThreadShell(threadId).pipe( |
| 174 | Effect.mapError( |
| 175 | (cause) => |
| 176 | new AcpRegistryOperationError({ |
| 177 | reason: "session_import_failed", |
| 178 | message: "Could not inspect the imported ACP session mapping.", |
| 179 | cause, |
| 180 | }), |
| 181 | ), |
| 182 | ); |
| 183 | if (existing !== null) { |
| 184 | const repairing = AgentSessionImporter.isNativeHistoryPending({ |
| 185 | historyOrigin: existing.historyOrigin, |
| 186 | hasRun: existing.latestRunId !== null, |
| 187 | }); |
| 188 | yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( |
| 189 | Effect.mapError( |
| 190 | (cause) => |
| 191 | new AcpRegistryOperationError({ |
| 192 | reason: "session_import_failed", |
| 193 | message: "Could not import the ACP session history.", |
| 194 | cause, |
| 195 | }), |
| 196 | ), |
| 197 | ); |
| 198 | return { threadId, imported: repairing } as const; |
| 199 | } |
| 200 | |
| 201 | const provider = (yield* providerRegistry.getProviders).find( |
| 202 | (candidate) => candidate.instanceId === input.instanceId, |
| 203 | ); |
| 204 | const model = |
| 205 | provider?.models.find((candidate) => candidate.isDefault)?.slug ?? |
| 206 | provider?.models[0]?.slug ?? |
| 207 | "default"; |
| 208 | const commandId = CommandId.make(yield* random.uuidV4()); |
| 209 | const launched = yield* Effect.result( |
| 210 | startup.enqueueCommand( |
| 211 | threadLaunch.launch({ |
| 212 | commandId, |
| 213 | threadId, |
| 214 | projectId: input.projectId, |
| 215 | title: input.title ?? "Imported ACP session", |
| 216 | modelSelection: { instanceId: input.instanceId, model }, |
| 217 | runtimeMode: "approval-required", |
| 218 | interactionMode: "default", |
| 219 | workspaceStrategy: { type: "root" }, |
| 220 | importedNativeThread: { |
| 221 | ref: { |
| 222 | driver: instance.driverKind, |
| 223 | nativeId: input.sessionId, |
| 224 | strength: "strong", |
| 225 | }, |
| 226 | metadata: { |
| 227 | itemIdentityVersion: 2, |
| 228 | ...(input.title === undefined ? {} : { title: input.title }), |
| 229 | ...(input.updatedAt === undefined ? {} : { updatedAt: input.updatedAt }), |
| 230 | }, |
| 231 | }, |
| 232 | createdBy: "user", |
| 233 | creationSource: "web", |
| 234 | }), |
| 235 | ), |
| 236 | ); |
| 237 | if (Result.isFailure(launched)) { |
| 238 | const racedImport = yield* threadManagement.getThreadShell(threadId).pipe( |
| 239 | Effect.mapError( |
| 240 | (cause) => |
| 241 | new AcpRegistryOperationError({ |
| 242 | reason: "session_import_failed", |
| 243 | message: "Could not inspect the imported ACP session after launch failed.", |
| 244 | cause, |
| 245 | }), |
| 246 | ), |
| 247 | ); |
| 248 | if (racedImport !== null) return { threadId, imported: false } as const; |
| 249 | return yield* new AcpRegistryOperationError({ |
| 250 | reason: "session_import_failed", |
| 251 | message: "Could not create a T3 thread for the ACP session.", |
| 252 | cause: launched.failure, |
| 253 | }); |
| 254 | } |
| 255 | // The thread is usable without its history, so a failed read only logs. |
| 256 | yield* agentSessionImporter.importNativeHistory({ threadId, workspaceRoot }).pipe( |
| 257 | Effect.catch((cause) => |
| 258 | Effect.logWarning("Could not import ACP session history", { |
| 259 | instanceId: input.instanceId, |
| 260 | sessionId: input.sessionId, |
| 261 | cause, |
| 262 | }), |
| 263 | ), |
| 264 | ); |
| 265 | return { threadId, imported: true } as const; |
| 266 | }, coordinator.withSessionMutation); |
| 267 | |
| 268 | return AcpRegistrySessions.of({ project, sessionManager, findOwner, importSession }); |
| 269 | }); |
| 270 | |
| 271 | export const layer = Layer.effect(AcpRegistrySessions, make); |