@devries-cameron20 / t3code Mirror · read-only
Fork 0

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, 03:37 UTC

main
ts 467 lines 18.4 KB
Raw
1 import { assert, it } from "@effect/vitest";
2 import {
3 MessageId,
4 type ModelSelection,
5 NodeId,
6 type OrchestrationV2ProviderThread,
7 type OrchestrationV2Run,
8 type OrchestrationV2ThreadProjection,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderSessionId,
13 ProviderThreadId,
14 ProviderTurnId,
15 RunAttemptId,
16 RunId,
17 ThreadId,
18 } from "@t3tools/contracts";
19 import * as DateTime from "effect/DateTime";
20 import * as Effect from "effect/Effect";
21 import * as Exit from "effect/Exit";
22 import * as Layer from "effect/Layer";
23 import * as Option from "effect/Option";
24 import * as Ref from "effect/Ref";
25 import * as Stream from "effect/Stream";
26
27 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
28 import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
29 import * as EventSink from "./EventSink.ts";
30 import * as ProjectionStore from "./ProjectionStore.ts";
31 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
32 import * as ProviderSessionManager from "./ProviderSessionManager.ts";
33 import * as ProviderTurnControlService from "./ProviderTurnControlService.ts";
34
35 const driver = ProviderDriverKind.make("codex");
36 const providerInstanceId = ProviderInstanceId.make("codex");
37 const modelSelection = {
38 instanceId: providerInstanceId,
39 model: "gpt-5.4",
40 } satisfies ModelSelection;
41
42 function makeProjection(input: {
43 readonly now: DateTime.Utc;
44 readonly threadId: ThreadId;
45 readonly providerThread: OrchestrationV2ProviderThread;
46 readonly providerTurnId: ProviderTurnId;
47 readonly attemptId: RunAttemptId;
48 }): OrchestrationV2ThreadProjection {
49 const runId = RunId.make("run:restart-session");
50 const nodeId = NodeId.make("node:restart-session");
51 return {
52 thread: {
53 createdBy: "user",
54 creationSource: "web",
55 id: input.threadId,
56 projectId: ProjectId.make("project:restart-session"),
57 title: "Restart session",
58 providerInstanceId,
59 modelSelection,
60 runtimeMode: "full-access",
61 interactionMode: "default",
62 branch: null,
63 worktreePath: "/workspace",
64 activeProviderThreadId: input.providerThread.id,
65 lineage: {
66 parentThreadId: null,
67 relationshipToParent: null,
68 rootThreadId: input.threadId,
69 },
70 forkedFrom: null,
71 createdAt: input.now,
72 updatedAt: input.now,
73 archivedAt: null,
74 settledOverride: null,
75 settledAt: null,
76 lastVisitedAt: null,
77 deletedAt: null,
78 },
79 runs: [],
80 attempts: [
81 {
82 id: input.attemptId,
83 runId,
84 attemptOrdinal: 1,
85 rootNodeId: nodeId,
86 providerInstanceId,
87 providerThreadId: input.providerThread.id,
88 providerTurnId: input.providerTurnId,
89 reason: "initial",
90 status: "superseded",
91 startedAt: input.now,
92 completedAt: input.now,
93 },
94 ],
95 nodes: [],
96 subagents: [],
97 providerSessions: [],
98 providerThreads: [input.providerThread],
99 providerTurns: [
100 {
101 id: input.providerTurnId,
102 providerThreadId: input.providerThread.id,
103 nodeId,
104 runAttemptId: input.attemptId,
105 nativeTurnRef: {
106 driver,
107 nativeId: "native-turn:restart-session",
108 strength: "strong",
109 },
110 ordinal: 1,
111 status: "running",
112 startedAt: input.now,
113 completedAt: null,
114 },
115 ],
116 runtimeRequests: [],
117 messages: [],
118 plans: [],
119 turnItems: [],
120 checkpointScopes: [],
121 checkpoints: [],
122 contextHandoffs: [],
123 contextTransfers: [],
124 visibleTurnItems: [],
125 updatedAt: input.now,
126 };
127 }
128
129 function layerProjectionStore(
130 getProviderControlContext: ProjectionStore.ProjectionStoreV2["Service"]["getProviderControlContext"],
131 ) {
132 return Layer.succeed(
133 ProjectionStore.ProjectionStoreV2,
134 ProjectionStore.ProjectionStoreV2.of({
135 apply: () => Effect.void,
136 getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"),
137 getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"),
138 getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"),
139 getAgentAwarenessSnapshot: () => Effect.die("unused awareness snapshot"),
140 getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
141 listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),
142 countThreads: () => Effect.die("unused countThreads"),
143 listActiveShellIndex: () => Effect.die("unused listActiveShellIndex"),
144 listActiveThreads: () => Effect.die("unused listActiveThreads"),
145 listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"),
146 readShellSnapshot: () => Effect.die("unused readShellSnapshot"),
147 getThreadShell: () => Effect.die("unused getThreadShell"),
148 getThreadTitles: () => Effect.die("unused getThreadTitles"),
149 getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"),
150 findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),
151 getThread: () => Effect.die("unused getThread"),
152 findThread: () => Effect.die("unused findThread"),
153 getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
154 getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
155 getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"),
156 getThreadProjection: () => Effect.die("control effects must not load transcript"),
157 getTurnStartContext: () => Effect.die("unused"),
158 getTurnStartHistory: () => Effect.die("unused"),
159 getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"),
160 getPlan: () => Effect.die("unused"),
161 hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"),
162 hasRunInterruptRequest: () => Effect.die("unused stop read"),
163 getRunProviderRecords: () => Effect.die("unused run provider read"),
164 getRunCardRecords: () => Effect.die("unused run card read"),
165 getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"),
166 searchThread: () => Effect.die("unused"),
167 searchThreadStream: () => Stream.empty,
168 getThreadHistoryPage: () => Effect.die("unused"),
169 getTimelinePage: () => Effect.die("Unused timeline read"),
170 getMessageCount: () => Effect.die("unused message count"),
171 getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"),
172 hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"),
173 getSubagentCount: () => Effect.die("unused subagent count"),
174 getRunCount: () => Effect.die("unused run count"),
175 listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"),
176 getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),
177 getTurnItem: () => Effect.die("unused turn item read"),
178 getMessagesById: () => Effect.die("unused getMessagesById"),
179 getThreadRecords: () => Effect.die("unused record read"),
180 getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"),
181 getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"),
182 getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"),
183 getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"),
184 getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"),
185 getProviderControlContext,
186 getCheckpointContext: () => Effect.die("not used"),
187 getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
188 getCheckpointCaptureContext: () => Effect.die("not used"),
189 getRunMessage: () => Effect.die("not used"),
190 getDelegatedChildControls: () => Effect.die("not used"),
191 getRun: () => Effect.die("not used"),
192 isNodeStored: () => Effect.die("not used"),
193 canStartQueuedRun: () => Effect.die("not used"),
194 getHeldQueuedRuns: () => Effect.die("not used"),
195 getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
196 getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
197 getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
198 getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"),
199 getPullRequestSnapshot: () => Effect.die("unused getPullRequestSnapshot"),
200 }),
201 );
202 }
203
204 function layerSessions(
205 liveSessionId: ProviderSessionId,
206 runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
207 ) {
208 return Layer.succeed(
209 ProviderSessionManager.ProviderSessionManagerV2,
210 ProviderSessionManager.ProviderSessionManagerV2.of({
211 shutdown: Effect.void,
212 open: () => Effect.die("unused open"),
213 get: (providerSessionId) =>
214 Effect.succeed(providerSessionId === liveSessionId ? Option.some(runtime) : Option.none()),
215 isLive: (providerSessionId) => Effect.succeed(providerSessionId === liveSessionId),
216 close: () => Effect.void,
217 closeInstance: () => Effect.void,
218 release: () => Effect.void,
219 detach: () => Effect.void,
220 otherWorkingThreads: () => Effect.succeed([]),
221 releaseUnlessBusy: () => Effect.succeed(true),
222 forgetLoadedProviderThread: () => Effect.void,
223 subscribePromptSuggestion: () => Stream.empty,
224 }),
225 );
226 }
227
228 it.effect(
229 "interrupts the historical session only for the exact committed restart replacement",
230 () =>
231 Effect.gen(function* () {
232 const now = yield* DateTime.now;
233 const threadId = ThreadId.make("thread:restart-session");
234 const oldSessionId = ProviderSessionId.make("provider-session:restart-session:old");
235 const replacementSessionId = ProviderSessionId.make(
236 "provider-session:restart-session:replacement",
237 );
238 const unrelatedSessionId = ProviderSessionId.make(
239 "provider-session:restart-session:unrelated",
240 );
241 const providerThreadId = ProviderThreadId.make("provider-thread:restart-session");
242 const providerTurnId = ProviderTurnId.make("provider-turn:restart-session");
243 const attemptId = RunAttemptId.make("run-attempt:restart-session");
244 const providerThread: OrchestrationV2ProviderThread = {
245 id: providerThreadId,
246 driver,
247 providerInstanceId,
248 providerSessionId: replacementSessionId,
249 appThreadId: threadId,
250 ownerNodeId: null,
251 nativeThreadRef: {
252 driver,
253 nativeId: "native-thread:restart-session",
254 strength: "strong",
255 },
256 nativeConversationHeadRef: null,
257 status: "not_loaded",
258 firstRunOrdinal: 1,
259 lastRunOrdinal: 1,
260 handoffIds: [],
261 forkedFrom: null,
262 createdAt: now,
263 updatedAt: now,
264 };
265 const projection = yield* Ref.make(
266 makeProjection({ now, threadId, providerThread, providerTurnId, attemptId }),
267 );
268 const interruptedThread = yield* Ref.make<OrchestrationV2ProviderThread | null>(null);
269 const providerSession = {
270 id: oldSessionId,
271 driver,
272 providerInstanceId,
273 status: "running" as const,
274 cwd: "/workspace",
275 model: modelSelection.model,
276 capabilities: CodexProviderCapabilitiesV2,
277 createdAt: now,
278 updatedAt: now,
279 lastError: null,
280 };
281 const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
282 instanceId: providerInstanceId,
283 driver,
284 providerSessionId: oldSessionId,
285 providerSession,
286 events: Stream.empty,
287 ensureThread: () => Effect.die("unused ensureThread"),
288 resumeThread: () => Effect.die("unused resumeThread"),
289 startTurn: () => Effect.die("unused startTurn"),
290 steerTurn: () => Effect.die("unused steerTurn"),
291 interruptTurn: ({ providerThread: target }) =>
292 Effect.all(
293 [
294 Ref.set(interruptedThread, target),
295 Ref.update(projection, (current) => ({
296 ...current,
297 providerTurns: current.providerTurns.map((turn) =>
298 turn.id === providerTurnId
299 ? { ...turn, status: "interrupted" as const, completedAt: now }
300 : turn,
301 ),
302 })),
303 ],
304 { discard: true },
305 ),
306 respondToRuntimeRequest: () => Effect.die("unused respondToRuntimeRequest"),
307 readThreadSnapshot: () => Effect.die("unused readThreadSnapshot"),
308 rollbackThread: () => Effect.die("unused rollbackThread"),
309 forkThread: () => Effect.die("unused forkThread"),
310 };
311 const layerProjection = layerProjectionStore((_threadId, target) =>
312 Ref.get(projection).pipe(
313 Effect.map((current) => ({
314 providerThread: current.providerThreads.find(
315 (thread) => thread.id === target.providerThreadId,
316 ),
317 providerTurn: current.providerTurns.find((turn) => turn.id === target.providerTurnId),
318 attempt: current.attempts.find((attempt) => attempt.id === target.attemptId),
319 message: undefined,
320 run: undefined,
321 })),
322 ),
323 );
324 const layerSessionManager = layerSessions(oldSessionId, runtime);
325 const layerControl = ProviderTurnControlService.layer.pipe(
326 Layer.provide(
327 Layer.mergeAll(
328 layerProjection,
329 layerSessionManager,
330 Layer.mock(EventSink.EventSinkV2)({}),
331 McpAppModelContext.layerEmpty,
332 ),
333 ),
334 );
335
336 const [ordinaryInterrupt, unrelatedRestart] = yield* Effect.gen(function* () {
337 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
338 const ordinary = yield* Effect.exit(
339 control.interrupt({
340 threadId,
341 providerSessionId: oldSessionId,
342 providerThreadId,
343 providerTurnId,
344 }),
345 );
346 const unrelated = yield* Effect.exit(
347 control.interruptAndAwaitTerminal({
348 threadId,
349 providerSessionId: oldSessionId,
350 replacementProviderSessionId: unrelatedSessionId,
351 providerThreadId,
352 providerTurnId,
353 interruptedAttemptId: attemptId,
354 }),
355 );
356 return [ordinary, unrelated] as const;
357 }).pipe(Effect.provide(layerControl));
358
359 assert.isTrue(Exit.isFailure(ordinaryInterrupt));
360 assert.isTrue(Exit.isFailure(unrelatedRestart));
361 assert.isNull(yield* Ref.get(interruptedThread));
362
363 yield* Effect.gen(function* () {
364 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
365 yield* control.interruptAndAwaitTerminal({
366 threadId,
367 providerSessionId: oldSessionId,
368 replacementProviderSessionId: replacementSessionId,
369 providerThreadId,
370 providerTurnId,
371 interruptedAttemptId: attemptId,
372 });
373 }).pipe(Effect.provide(layerControl));
374
375 const interrupted = yield* Ref.get(interruptedThread);
376 assert.isNotNull(interrupted);
377 assert.equal(interrupted?.providerSessionId, oldSessionId);
378 assert.equal(interrupted?.id, providerThreadId);
379 assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session");
380 }),
381 );
382
383 it.effect("steers a running turn with its sender and the thread's MCP app model context", () =>
384 Effect.gen(function* () {
385 const now = yield* DateTime.now;
386 const threadId = ThreadId.make("thread:steer-app-context");
387 const sessionId = ProviderSessionId.make("provider-session:steer-app-context");
388 const providerTurnId = ProviderTurnId.make("provider-turn:steer-app-context");
389 const attemptId = RunAttemptId.make("run-attempt:steer-app-context");
390 const providerThread = {
391 id: ProviderThreadId.make("provider-thread:steer-app-context"),
392 driver,
393 providerInstanceId,
394 providerSessionId: sessionId,
395 } as OrchestrationV2ProviderThread;
396 const projection = makeProjection({ now, threadId, providerThread, providerTurnId, attemptId });
397 const steered: Array<ProviderAdapter.ProviderAdapterV2SteerInput> = [];
398 const runtime = {
399 instanceId: providerInstanceId,
400 driver,
401 providerSessionId: sessionId,
402 steerTurn: (input: ProviderAdapter.ProviderAdapterV2SteerInput) =>
403 Effect.sync(() => void steered.push(input)),
404 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
405 const layerControl = ProviderTurnControlService.layer.pipe(
406 Layer.provide(
407 Layer.mergeAll(
408 layerProjectionStore(() =>
409 Effect.succeed({
410 providerThread,
411 providerTurn: projection.providerTurns[0],
412 attempt: projection.attempts[0],
413 message: {
414 id: MessageId.make("message:steer-app-context"),
415 text: "What did the app report?",
416 attachments: [],
417 createdBy: "agent",
418 creationSource: "mcp",
419 senderThreadId: ThreadId.make("thread:steer-sender"),
420 } as unknown as NonNullable<
421 ProjectionStore.ProjectionProviderControlContext["message"]
422 >,
423 run: {
424 id: RunId.make("run:steer-app-context"),
425 status: "running",
426 activeAttemptId: attemptId,
427 } as OrchestrationV2Run,
428 }),
429 ),
430 layerSessions(sessionId, runtime),
431 Layer.mock(EventSink.EventSinkV2)({}),
432 Layer.mock(McpAppModelContext.McpAppModelContext)({
433 forThread: () =>
434 Effect.succeed([
435 {
436 itemId: "turn-item:call-1",
437 server: "tools",
438 tool: "picker",
439 text: "Pressed: blue",
440 },
441 ]),
442 }),
443 ),
444 ),
445 );
446
447 yield* Effect.gen(function* () {
448 const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
449 yield* control.steer({
450 threadId,
451 providerSessionId: sessionId,
452 providerThreadId: providerThread.id,
453 providerTurnId,
454 messageId: MessageId.make("message:steer-app-context"),
455 });
456 }).pipe(Effect.provide(layerControl));
457
458 assert.equal(steered.length, 1);
459 assert.equal(
460 steered[0]!.message.text,
461 '[T3 Code: the agent in T3 thread "thread:steer-sender" sent this message, not the user.]\n\nWhat did the app report?',
462 );
463 assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [
464 { key: "mcp_app_turn-item_call-1", text: "Pressed: blue" },
465 ]);
466 }),
467 );