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 | CheckpointId, |
| 3 | CheckpointScopeId, |
| 4 | CommandId, |
| 5 | ContextHandoffId, |
| 6 | ContextTransferId, |
| 7 | EventId, |
| 8 | MessageId, |
| 9 | NodeId, |
| 10 | PlanId, |
| 11 | ProjectId, |
| 12 | ProviderDriverKind, |
| 13 | ProviderInstanceId, |
| 14 | ProviderSessionId, |
| 15 | ProviderThreadId, |
| 16 | ProviderTurnId, |
| 17 | RawEventId, |
| 18 | RunAttemptId, |
| 19 | RunId, |
| 20 | RuntimeRequestId, |
| 21 | ThreadId, |
| 22 | TurnItemId, |
| 23 | } from "@t3tools/contracts"; |
| 24 | // @effect-diagnostics-next-line nodeBuiltinImport:off -- derive ids are synchronous, so the hash must be too. |
| 25 | import * as NodeCrypto from "node:crypto"; |
| 26 | |
| 27 | import * as Context from "effect/Context"; |
| 28 | import * as Effect from "effect/Effect"; |
| 29 | import * as Layer from "effect/Layer"; |
| 30 | import * as Schema from "effect/Schema"; |
| 31 | |
| 32 | import { randomUuidV4 } from "./randomUuid.ts"; |
| 33 | |
| 34 | export const IdAllocatorV2Kind = Schema.Literals([ |
| 35 | "command", |
| 36 | "event", |
| 37 | "raw_event", |
| 38 | "project", |
| 39 | "thread", |
| 40 | "message", |
| 41 | "run", |
| 42 | "run_attempt", |
| 43 | "node", |
| 44 | "provider_session", |
| 45 | "provider_thread", |
| 46 | "provider_turn", |
| 47 | "runtime_request", |
| 48 | "turn_item", |
| 49 | "checkpoint_scope", |
| 50 | "checkpoint", |
| 51 | "context_handoff", |
| 52 | "context_transfer", |
| 53 | "plan", |
| 54 | ]); |
| 55 | export type IdAllocatorV2Kind = typeof IdAllocatorV2Kind.Type; |
| 56 | |
| 57 | export class IdAllocatorV2AllocationError extends Schema.TaggedError<IdAllocatorV2AllocationError>()( |
| 58 | "IdAllocatorV2AllocationError", |
| 59 | { |
| 60 | kind: IdAllocatorV2Kind, |
| 61 | input: Schema.optional(Schema.Unknown), |
| 62 | cause: Schema.optional(Schema.Defect()), |
| 63 | }, |
| 64 | ) { |
| 65 | override get message(): string { |
| 66 | return `Failed to allocate orchestration ${this.kind} id.`; |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | export const IdAllocatorV2Error = Schema.Union([IdAllocatorV2AllocationError]); |
| 71 | export type IdAllocatorV2Error = typeof IdAllocatorV2Error.Type; |
| 72 | |
| 73 | export interface IdAllocatorV2Allocate { |
| 74 | readonly command: (input: { |
| 75 | readonly fixtureName: string; |
| 76 | readonly commandName: string; |
| 77 | }) => Effect.Effect<CommandId, IdAllocatorV2Error>; |
| 78 | readonly event: (input: { |
| 79 | readonly threadId?: ThreadId; |
| 80 | readonly commandId?: CommandId; |
| 81 | readonly providerSessionId?: ProviderSessionId; |
| 82 | }) => Effect.Effect<EventId, IdAllocatorV2Error>; |
| 83 | readonly rawEvent: (input: { |
| 84 | readonly providerSessionId: ProviderSessionId; |
| 85 | readonly method: string | null; |
| 86 | }) => Effect.Effect<RawEventId, IdAllocatorV2Error>; |
| 87 | readonly project: (input: { |
| 88 | readonly fixtureName: string; |
| 89 | }) => Effect.Effect<ProjectId, IdAllocatorV2Error>; |
| 90 | readonly thread: (input: { |
| 91 | readonly fixtureName?: string; |
| 92 | readonly projectId?: ProjectId; |
| 93 | }) => Effect.Effect<ThreadId, IdAllocatorV2Error>; |
| 94 | readonly message: (input: { |
| 95 | readonly threadId: ThreadId; |
| 96 | readonly ordinal: number; |
| 97 | }) => Effect.Effect<MessageId, IdAllocatorV2Error>; |
| 98 | readonly providerSession: (input: { |
| 99 | readonly providerInstanceId: ProviderInstanceId; |
| 100 | readonly threadId: ThreadId; |
| 101 | }) => Effect.Effect<ProviderSessionId, IdAllocatorV2Error>; |
| 102 | readonly runtimeRequest: (input: { |
| 103 | readonly driver: ProviderDriverKind; |
| 104 | readonly providerTurnId?: ProviderTurnId; |
| 105 | readonly nativeRequestId?: string; |
| 106 | }) => Effect.Effect<RuntimeRequestId, IdAllocatorV2Error>; |
| 107 | readonly checkpointScope: (input: { |
| 108 | readonly threadId: ThreadId; |
| 109 | readonly name: string; |
| 110 | }) => Effect.Effect<CheckpointScopeId, IdAllocatorV2Error>; |
| 111 | readonly checkpoint: (input: { |
| 112 | readonly checkpointScopeId: CheckpointScopeId; |
| 113 | readonly name: string; |
| 114 | }) => Effect.Effect<CheckpointId, IdAllocatorV2Error>; |
| 115 | readonly contextHandoff: (input: { |
| 116 | readonly threadId: ThreadId; |
| 117 | readonly fromProviderInstanceId: ProviderInstanceId; |
| 118 | readonly toProviderInstanceId: ProviderInstanceId; |
| 119 | }) => Effect.Effect<ContextHandoffId, IdAllocatorV2Error>; |
| 120 | readonly contextTransfer: (input: { |
| 121 | readonly sourceThreadId: ThreadId; |
| 122 | readonly targetThreadId: ThreadId; |
| 123 | readonly type: string; |
| 124 | }) => Effect.Effect<ContextTransferId, IdAllocatorV2Error>; |
| 125 | readonly plan: (input: { |
| 126 | readonly threadId: ThreadId; |
| 127 | readonly runId?: RunId; |
| 128 | readonly driver: ProviderDriverKind; |
| 129 | }) => Effect.Effect<PlanId, IdAllocatorV2Error>; |
| 130 | } |
| 131 | |
| 132 | export interface IdAllocatorV2Derive { |
| 133 | readonly providerSession: (input: { |
| 134 | readonly providerInstanceId: ProviderInstanceId; |
| 135 | }) => ProviderSessionId; |
| 136 | readonly delegatedTaskNode: (input: { readonly commandId: CommandId }) => NodeId; |
| 137 | readonly delegatedTaskThread: (input: { readonly commandId: CommandId }) => ThreadId; |
| 138 | readonly delegatedTaskMessage: (input: { readonly commandId: CommandId }) => MessageId; |
| 139 | readonly delegatedTaskTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId; |
| 140 | readonly createdThreadTurnItem: (input: { readonly commandId: CommandId }) => TurnItemId; |
| 141 | readonly threadFromProviderThread: (input: { |
| 142 | readonly driver: ProviderDriverKind; |
| 143 | readonly nativeThreadId: string; |
| 144 | readonly providerInstanceId?: ProviderInstanceId; |
| 145 | }) => ThreadId; |
| 146 | readonly subagentThread: (input: { |
| 147 | readonly driver: ProviderDriverKind; |
| 148 | readonly nativeThreadId: string; |
| 149 | readonly providerInstanceId?: ProviderInstanceId; |
| 150 | }) => ThreadId; |
| 151 | readonly run: (input: { readonly threadId: ThreadId; readonly ordinal: number }) => RunId; |
| 152 | readonly runAttempt: (input: { |
| 153 | readonly runId: RunId; |
| 154 | readonly attemptOrdinal: number; |
| 155 | }) => RunAttemptId; |
| 156 | readonly rootNode: (input: { readonly runId: RunId }) => NodeId; |
| 157 | readonly rootNodeAttempt: (input: { |
| 158 | readonly runId: RunId; |
| 159 | readonly attemptOrdinal: number; |
| 160 | }) => NodeId; |
| 161 | readonly userTurnItem: (input: { readonly messageId: MessageId }) => TurnItemId; |
| 162 | readonly runSignalTurnItem: (input: { |
| 163 | readonly runId: RunId; |
| 164 | readonly signal: string; |
| 165 | }) => TurnItemId; |
| 166 | readonly providerThread: (input: { |
| 167 | readonly driver: ProviderDriverKind; |
| 168 | readonly nativeThreadId: string; |
| 169 | readonly providerInstanceId?: ProviderInstanceId; |
| 170 | }) => ProviderThreadId; |
| 171 | readonly providerTurn: (input: { |
| 172 | readonly driver: ProviderDriverKind; |
| 173 | readonly nativeTurnId: string; |
| 174 | }) => ProviderTurnId; |
| 175 | readonly nodeFromProviderItem: (input: { |
| 176 | readonly driver: ProviderDriverKind; |
| 177 | readonly nativeItemId: string; |
| 178 | }) => NodeId; |
| 179 | readonly messageFromProviderItem: (input: { |
| 180 | readonly driver: ProviderDriverKind; |
| 181 | readonly nativeItemId: string; |
| 182 | }) => MessageId; |
| 183 | readonly turnItemFromProviderItem: (input: { |
| 184 | readonly driver: ProviderDriverKind; |
| 185 | readonly nativeItemId: string; |
| 186 | }) => TurnItemId; |
| 187 | readonly approvalNode: (input: { readonly requestId: RuntimeRequestId }) => NodeId; |
| 188 | readonly approvalTurnItem: (input: { readonly requestId: RuntimeRequestId }) => TurnItemId; |
| 189 | } |
| 190 | |
| 191 | export class IdAllocatorV2 extends Context.Service< |
| 192 | IdAllocatorV2, |
| 193 | { |
| 194 | readonly allocate: IdAllocatorV2Allocate; |
| 195 | readonly derive: IdAllocatorV2Derive; |
| 196 | } |
| 197 | >()("@t3tools/provider-core/server/IdAllocator/IdAllocatorV2") {} |
| 198 | |
| 199 | const encodePart = (part: string | number): string => encodeURIComponent(String(part)); |
| 200 | |
| 201 | const joinId = (prefix: string, ...parts: ReadonlyArray<string | number>): string => |
| 202 | [prefix, ...parts.map(encodePart)].join(":"); |
| 203 | |
| 204 | export function deriveThreadFromProviderThread(input: { |
| 205 | readonly driver: ProviderDriverKind; |
| 206 | readonly providerInstanceId?: ProviderInstanceId; |
| 207 | readonly nativeThreadId: string; |
| 208 | }): ThreadId { |
| 209 | return ThreadId.make( |
| 210 | joinId( |
| 211 | "thread", |
| 212 | "provider", |
| 213 | input.driver, |
| 214 | ...(input.providerInstanceId === undefined |
| 215 | ? [] |
| 216 | : ["provider-instance", input.providerInstanceId]), |
| 217 | "native-thread", |
| 218 | input.nativeThreadId, |
| 219 | ), |
| 220 | ); |
| 221 | } |
| 222 | |
| 223 | // Agents quote subagent thread ids back to thread tools, and the native id often |
| 224 | // nests the parent's encoded ids, so hash it to a short stable id instead. Adapters |
| 225 | // re-derive child ids on resume, so a child stored under its legacy id keeps it. |
| 226 | const makeDeriveSubagentThread = |
| 227 | (legacyThreadIds: ReadonlySet<string>): IdAllocatorV2Derive["subagentThread"] => |
| 228 | (input) => { |
| 229 | const legacy = deriveThreadFromProviderThread(input); |
| 230 | if (legacyThreadIds.has(legacy)) return legacy; |
| 231 | const digest = NodeCrypto.createHash("sha256").update(legacy).digest("hex").slice(0, 16); |
| 232 | return ThreadId.make(`thread:subagent:${digest}`); |
| 233 | }; |
| 234 | |
| 235 | export function deriveProviderThread(input: { |
| 236 | readonly driver: ProviderDriverKind; |
| 237 | readonly providerInstanceId?: ProviderInstanceId; |
| 238 | readonly nativeThreadId: string; |
| 239 | }): ProviderThreadId { |
| 240 | return ProviderThreadId.make( |
| 241 | joinId( |
| 242 | "provider-thread", |
| 243 | "provider", |
| 244 | input.driver, |
| 245 | ...(input.providerInstanceId === undefined |
| 246 | ? [] |
| 247 | : ["provider-instance", input.providerInstanceId]), |
| 248 | "native-thread", |
| 249 | input.nativeThreadId, |
| 250 | ), |
| 251 | ); |
| 252 | } |
| 253 | |
| 254 | const randomId = |
| 255 | <Id, Input>(input: { |
| 256 | readonly kind: IdAllocatorV2Kind; |
| 257 | readonly prefix: string; |
| 258 | readonly parts: ReadonlyArray<string | number>; |
| 259 | readonly make: (value: string) => Id; |
| 260 | }) => |
| 261 | (allocationInput: Input): Effect.Effect<Id, IdAllocatorV2Error> => |
| 262 | randomUuidV4.pipe( |
| 263 | Effect.map((uuid) => input.make(joinId(input.prefix, ...input.parts, uuid))), |
| 264 | Effect.mapError( |
| 265 | (cause) => |
| 266 | new IdAllocatorV2AllocationError({ |
| 267 | kind: input.kind, |
| 268 | input: allocationInput, |
| 269 | cause, |
| 270 | }), |
| 271 | ), |
| 272 | ); |
| 273 | |
| 274 | const DELEGATED_TASK_THREAD_PREFIX = joinId("thread", "delegated-task", ""); |
| 275 | |
| 276 | export const isDelegatedTaskThread = (threadId: ThreadId): boolean => |
| 277 | threadId.startsWith(DELEGATED_TASK_THREAD_PREFIX); |
| 278 | |
| 279 | export const derive: IdAllocatorV2Derive = { |
| 280 | providerSession: (input) => |
| 281 | ProviderSessionId.make( |
| 282 | joinId("provider-session", "provider-instance", input.providerInstanceId, "shared"), |
| 283 | ), |
| 284 | delegatedTaskNode: (input) => NodeId.make(joinId("node", "delegated-task", input.commandId)), |
| 285 | delegatedTaskThread: (input) => |
| 286 | ThreadId.make(`${DELEGATED_TASK_THREAD_PREFIX}${encodePart(input.commandId)}`), |
| 287 | delegatedTaskMessage: (input) => |
| 288 | MessageId.make(joinId("message", "delegated-task", input.commandId)), |
| 289 | delegatedTaskTurnItem: (input) => |
| 290 | TurnItemId.make(joinId("turn-item", "delegated-task", input.commandId)), |
| 291 | createdThreadTurnItem: (input) => |
| 292 | TurnItemId.make(joinId("turn-item", "created-thread", input.commandId)), |
| 293 | threadFromProviderThread: deriveThreadFromProviderThread, |
| 294 | subagentThread: makeDeriveSubagentThread(new Set()), |
| 295 | run: (input) => RunId.make(joinId("run", "thread", input.threadId, "ordinal", input.ordinal)), |
| 296 | runAttempt: (input) => |
| 297 | RunAttemptId.make(joinId("run-attempt", "run", input.runId, "attempt", input.attemptOrdinal)), |
| 298 | rootNode: (input) => NodeId.make(joinId("node", "run", input.runId, "root")), |
| 299 | rootNodeAttempt: (input) => |
| 300 | NodeId.make(joinId("node", "run", input.runId, "attempt", input.attemptOrdinal, "root")), |
| 301 | userTurnItem: (input) => TurnItemId.make(joinId("turn-item", "message", input.messageId)), |
| 302 | runSignalTurnItem: (input) => |
| 303 | TurnItemId.make(joinId("turn-item", "run", input.runId, "signal", input.signal)), |
| 304 | providerThread: deriveProviderThread, |
| 305 | providerTurn: (input) => |
| 306 | ProviderTurnId.make( |
| 307 | joinId("provider-turn", "provider", input.driver, "native-turn", input.nativeTurnId), |
| 308 | ), |
| 309 | nodeFromProviderItem: (input) => |
| 310 | NodeId.make(joinId("node", "provider", input.driver, "native-item", input.nativeItemId)), |
| 311 | messageFromProviderItem: (input) => |
| 312 | MessageId.make(joinId("message", "provider", input.driver, "native-item", input.nativeItemId)), |
| 313 | turnItemFromProviderItem: (input) => |
| 314 | TurnItemId.make( |
| 315 | joinId("turn-item", "provider", input.driver, "native-item", input.nativeItemId), |
| 316 | ), |
| 317 | approvalNode: (input) => NodeId.make(joinId("node", "runtime-request", input.requestId)), |
| 318 | approvalTurnItem: (input) => |
| 319 | TurnItemId.make(joinId("turn-item", "runtime-request", input.requestId)), |
| 320 | }; |
| 321 | |
| 322 | export const layer: Layer.Layer<IdAllocatorV2> = Layer.succeed( |
| 323 | IdAllocatorV2, |
| 324 | IdAllocatorV2.of({ |
| 325 | allocate: { |
| 326 | command: (input) => |
| 327 | randomId<CommandId, typeof input>({ |
| 328 | kind: "command", |
| 329 | prefix: "command", |
| 330 | parts: ["fixture", input.fixtureName, input.commandName], |
| 331 | make: CommandId.make, |
| 332 | })(input), |
| 333 | event: (input) => |
| 334 | randomId<EventId, typeof input>({ |
| 335 | kind: "event", |
| 336 | prefix: "event", |
| 337 | parts: [ |
| 338 | ...(input.threadId === undefined ? [] : ["thread", input.threadId]), |
| 339 | ...(input.commandId === undefined ? [] : ["command", input.commandId]), |
| 340 | ...(input.providerSessionId === undefined |
| 341 | ? [] |
| 342 | : ["provider-session", input.providerSessionId]), |
| 343 | ], |
| 344 | make: EventId.make, |
| 345 | })(input), |
| 346 | rawEvent: (input) => |
| 347 | randomId<RawEventId, typeof input>({ |
| 348 | kind: "raw_event", |
| 349 | prefix: "raw-event", |
| 350 | parts: [ |
| 351 | "provider-session", |
| 352 | input.providerSessionId, |
| 353 | ...(input.method === null ? [] : ["method", input.method]), |
| 354 | ], |
| 355 | make: RawEventId.make, |
| 356 | })(input), |
| 357 | project: (input) => |
| 358 | randomId<ProjectId, typeof input>({ |
| 359 | kind: "project", |
| 360 | prefix: "project", |
| 361 | parts: ["fixture", input.fixtureName], |
| 362 | make: ProjectId.make, |
| 363 | })(input), |
| 364 | thread: (input) => |
| 365 | randomId<ThreadId, typeof input>({ |
| 366 | kind: "thread", |
| 367 | prefix: "thread", |
| 368 | parts: [ |
| 369 | ...(input.fixtureName === undefined ? [] : ["fixture", input.fixtureName]), |
| 370 | ...(input.projectId === undefined ? [] : ["project", input.projectId]), |
| 371 | ], |
| 372 | make: ThreadId.make, |
| 373 | })(input), |
| 374 | message: (input) => |
| 375 | randomId<MessageId, typeof input>({ |
| 376 | kind: "message", |
| 377 | prefix: "message", |
| 378 | parts: ["thread", input.threadId, "ordinal", input.ordinal], |
| 379 | make: MessageId.make, |
| 380 | })(input), |
| 381 | providerSession: (input) => |
| 382 | randomId<ProviderSessionId, typeof input>({ |
| 383 | kind: "provider_session", |
| 384 | prefix: "provider-session", |
| 385 | parts: ["provider-instance", input.providerInstanceId, "thread", input.threadId], |
| 386 | make: ProviderSessionId.make, |
| 387 | })(input), |
| 388 | runtimeRequest: (input) => |
| 389 | randomId<RuntimeRequestId, typeof input>({ |
| 390 | kind: "runtime_request", |
| 391 | prefix: "runtime-request", |
| 392 | parts: [ |
| 393 | "provider", |
| 394 | input.driver, |
| 395 | ...(input.providerTurnId === undefined ? [] : ["provider-turn", input.providerTurnId]), |
| 396 | ...(input.nativeRequestId === undefined |
| 397 | ? [] |
| 398 | : ["native-request", input.nativeRequestId]), |
| 399 | ], |
| 400 | make: RuntimeRequestId.make, |
| 401 | })(input), |
| 402 | checkpointScope: (input) => |
| 403 | Effect.succeed( |
| 404 | CheckpointScopeId.make( |
| 405 | joinId("checkpoint-scope", "thread", input.threadId, "name", input.name), |
| 406 | ), |
| 407 | ), |
| 408 | checkpoint: (input) => |
| 409 | Effect.succeed( |
| 410 | CheckpointId.make( |
| 411 | joinId("checkpoint", "scope", input.checkpointScopeId, "name", input.name), |
| 412 | ), |
| 413 | ), |
| 414 | contextHandoff: (input) => |
| 415 | randomId<ContextHandoffId, typeof input>({ |
| 416 | kind: "context_handoff", |
| 417 | prefix: "context-handoff", |
| 418 | parts: [ |
| 419 | "thread", |
| 420 | input.threadId, |
| 421 | "from-provider-instance", |
| 422 | input.fromProviderInstanceId, |
| 423 | "to-provider-instance", |
| 424 | input.toProviderInstanceId, |
| 425 | ], |
| 426 | make: ContextHandoffId.make, |
| 427 | })(input), |
| 428 | contextTransfer: (input) => |
| 429 | randomId<ContextTransferId, typeof input>({ |
| 430 | kind: "context_transfer", |
| 431 | prefix: "context-transfer", |
| 432 | parts: [ |
| 433 | "type", |
| 434 | input.type, |
| 435 | "source-thread", |
| 436 | input.sourceThreadId, |
| 437 | "target-thread", |
| 438 | input.targetThreadId, |
| 439 | ], |
| 440 | make: ContextTransferId.make, |
| 441 | })(input), |
| 442 | plan: (input) => |
| 443 | randomId<PlanId, typeof input>({ |
| 444 | kind: "plan", |
| 445 | prefix: "plan", |
| 446 | parts: [ |
| 447 | "thread", |
| 448 | input.threadId, |
| 449 | "provider", |
| 450 | input.driver, |
| 451 | ...(input.runId === undefined ? [] : ["run", input.runId]), |
| 452 | ], |
| 453 | make: PlanId.make, |
| 454 | })(input), |
| 455 | }, |
| 456 | derive, |
| 457 | }), |
| 458 | ); |
| 459 | |
| 460 | /** For adapters: subagent threads already stored under a legacy derived id keep that id. */ |
| 461 | export const layerWithLegacySubagentThreads = ( |
| 462 | legacyThreadIds: ReadonlySet<string>, |
| 463 | ): Layer.Layer<IdAllocatorV2> => |
| 464 | Layer.effect( |
| 465 | IdAllocatorV2, |
| 466 | Effect.gen(function* () { |
| 467 | const base = yield* IdAllocatorV2; |
| 468 | return IdAllocatorV2.of({ |
| 469 | allocate: base.allocate, |
| 470 | derive: { ...base.derive, subagentThread: makeDeriveSubagentThread(legacyThreadIds) }, |
| 471 | }); |
| 472 | }), |
| 473 | ).pipe(Layer.provide(layer)); |