Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

commands.ts

651 lines21.8 KB

1import {
2 CommandId,
3 ORCHESTRATION_V2_WS_METHODS,
4 OrchestrationV2CheckpointUnavailableError,
5 WS_METHODS,
6 type ChatAttachment,
7 type MessageId,
8 type ModelSelection,
9 type OrchestrationV2Command,
10 type OrchestrationV2CreationSource,
11 type PlanId,
12 type ProjectId,
13 type ProjectScript,
14 type ProviderApprovalDecision,
15 type ProviderInteractionMode,
16 type ProviderUserInputAnswers,
17 type RunId,
18 type RuntimeMode,
19 type RuntimeRequestId,
20 type ThreadId,
21 type UploadChatAttachment,
22} from "@t3tools/contracts";
23import * as Crypto from "effect/Crypto";
24import * as Effect from "effect/Effect";
25​
26import { request } from "../rpc/client.ts";
27​
28interface CommandMetadata {
29 readonly commandId?: CommandId;
30 readonly createdAt?: string;
31 readonly creationSource?: OrchestrationV2CreationSource;
33​
34export interface CreateProjectInput extends CommandMetadata {
35 readonly projectId: ProjectId;
36 readonly title: string;
37 readonly workspaceRoot: string;
38 readonly createWorkspaceRootIfMissing?: boolean;
39 readonly defaultModelSelection?: ModelSelection | null;
40 readonly scripts?: ReadonlyArray<ProjectScript>;
42​
43export interface UpdateProjectInput extends CommandMetadata {
44 readonly projectId: ProjectId;
45 readonly title?: string;
46 readonly workspaceRoot?: string;
47 readonly defaultModelSelection?: ModelSelection | null;
48 readonly scripts?: ReadonlyArray<ProjectScript>;
50​
51export interface DeleteProjectInput extends CommandMetadata {
52 readonly projectId: ProjectId;
53 readonly force?: boolean;
55​
56export interface CreateThreadInput extends CommandMetadata {
57 readonly threadId: ThreadId;
58 readonly projectId: ProjectId;
59 readonly title: string;
60 readonly modelSelection: ModelSelection;
61 readonly runtimeMode: RuntimeMode;
62 readonly interactionMode: ProviderInteractionMode;
63 readonly branch: string | null;
64 readonly worktreePath: string | null;
66​
67export interface ThreadCommandInput extends CommandMetadata {
68 readonly threadId: ThreadId;
70​
71export type DeleteThreadInput = ThreadCommandInput;
72export type ArchiveThreadInput = ThreadCommandInput;
73export type UnarchiveThreadInput = ThreadCommandInput;
74​
75export interface UpdateThreadMetadataInput extends ThreadCommandInput {
76 readonly title?: string;
77 readonly modelSelection?: ModelSelection;
78 readonly branch?: string | null;
79 readonly worktreePath?: string | null;
81​
82export interface SetThreadRuntimeModeInput extends ThreadCommandInput {
83 readonly runtimeMode: RuntimeMode;
85​
86export interface SetThreadInteractionModeInput extends ThreadCommandInput {
87 readonly interactionMode: ProviderInteractionMode;
89​
90interface StartThreadBootstrap {
91 readonly createThread?: {
92 readonly projectId: ProjectId;
93 readonly title: string;
94 readonly modelSelection: ModelSelection;
95 readonly runtimeMode: RuntimeMode;
96 readonly interactionMode: ProviderInteractionMode;
97 readonly branch: string | null;
98 readonly worktreePath: string | null;
99 readonly createdAt: string;
100 };
101 readonly prepareWorktree?: {
102 readonly projectCwd: string;
103 readonly baseBranch: string;
104 readonly branch?: string;
105 readonly startFromOrigin?: boolean;
106 };
107 readonly runSetupScript?: boolean;
109​
110export interface StartThreadTurnInput extends ThreadCommandInput {
111 readonly message: {
112 readonly messageId: MessageId;
113 readonly role: "user";
114 readonly text: string;
115 readonly attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>;
116 };
117 readonly modelSelection?: ModelSelection;
118 readonly titleSeed?: string;
119 readonly runtimeMode: RuntimeMode;
120 readonly interactionMode: ProviderInteractionMode;
121 readonly bootstrap?: StartThreadBootstrap;
122 readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId };
123 readonly dispatchMode?: "auto" | "queue" | "steer" | "restart";
125​
126export interface InterruptThreadTurnInput extends ThreadCommandInput {
127 readonly runId?: RunId;
128 /** Temporary caller compatibility while UI naming moves from turns to runs. */
129 readonly turnId?: string;
131​
132export interface RespondToThreadApprovalInput extends ThreadCommandInput {
133 readonly requestId: RuntimeRequestId;
134 readonly decision: ProviderApprovalDecision;
136​
137export interface RespondToThreadUserInputInput extends ThreadCommandInput {
138 readonly requestId: RuntimeRequestId;
139 readonly answers: ProviderUserInputAnswers;
141​
142export interface RevertThreadCheckpointInput extends ThreadCommandInput {
143 readonly checkpointId?: string;
144 readonly scopeId?: string;
145 readonly turnCount?: number;
147​
148export type StopThreadSessionInput = ThreadCommandInput;
149​
150export interface ForkThreadFromRunInput extends CommandMetadata {
151 readonly sourceThreadId: ThreadId;
152 readonly targetThreadId: ThreadId;
153 readonly runId: RunId;
154 readonly title?: string;
156​
157export interface MergeThreadBackInput extends CommandMetadata {
158 readonly sourceThreadId: ThreadId;
159 readonly targetThreadId: ThreadId;
160 readonly runId: RunId;
162​
163export interface ReorderQueuedRunInput extends ThreadCommandInput {
164 readonly runId: RunId;
165 readonly beforeRunId: RunId | null;
167​
168export interface PromoteQueuedRunInput extends ThreadCommandInput {
169 readonly queuedRunId: RunId;
170 readonly targetRunId: RunId;
172​
173const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
174 input: CommandMetadata,
175) {
176 if (input.commandId !== undefined) return input.commandId;
177 const crypto = yield* Crypto.Crypto;
178 return CommandId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie));
179});
180​
181const dispatch = (command: OrchestrationV2Command) =>
182 request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command);
183​
184const getProjection = (threadId: ThreadId) =>
185 request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
186​
187const persistAttachments = Effect.fn("EnvironmentCommands.persistAttachments")(function* (
188 threadId: ThreadId,
189 messageId: MessageId,
190 attachments: ReadonlyArray<ChatAttachment | UploadChatAttachment>,
191) {
192 const stored = attachments.filter(
193 (attachment): attachment is ChatAttachment => "id" in attachment,
194 );
195 const uploads = attachments.filter(
196 (attachment): attachment is UploadChatAttachment => "dataUrl" in attachment,
197 );
198 if (uploads.length === 0) return stored;
199 const result = yield* request(WS_METHODS.assetsPersistChatAttachments, {
200 threadId,
201 messageId,
202 attachments: uploads,
203 });
204 if (stored.length === 0) return result.attachments;
205 const byUpload = new Map(
206 uploads.map((attachment, index) => [attachment, result.attachments[index]]),
207 );
208 return attachments.flatMap((attachment) => {
209 if ("id" in attachment) return [attachment];
210 const persisted = byUpload.get(attachment);
211 return persisted === undefined ? [] : [persisted];
212 });
213});
214​
215const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* (
216 mutation:
217 | {
218 readonly type: "project.create";
219 readonly commandId: CommandId;
220 readonly projectId: ProjectId;
221 readonly title: string;
222 readonly workspaceRoot: string;
223 readonly createWorkspaceRootIfMissing?: boolean;
224 readonly defaultModelSelection?: ModelSelection | null;
225 readonly scripts?: ReadonlyArray<ProjectScript>;
226 }
227 | {
228 readonly type: "project.update";
229 readonly commandId: CommandId;
230 readonly projectId: ProjectId;
231 readonly title?: string;
232 readonly workspaceRoot?: string;
233 readonly defaultModelSelection?: ModelSelection | null;
234 readonly scripts?: ReadonlyArray<ProjectScript>;
235 }
236 | {
237 readonly type: "project.delete";
238 readonly commandId: CommandId;
239 readonly projectId: ProjectId;
240 readonly force?: boolean;
241 },
242) {
243 return yield* request(WS_METHODS.projectsMutate, mutation);
244});
245​
246export const createProject = Effect.fn("EnvironmentCommands.createProject")(function* (
247 input: CreateProjectInput,
248) {
249 return yield* mutateProject({
250 type: "project.create",
251 commandId: yield* allocateCommandId(input),
252 projectId: input.projectId,
253 title: input.title,
254 workspaceRoot: input.workspaceRoot,
255 ...(input.createWorkspaceRootIfMissing === undefined
256 ? {}
257 : { createWorkspaceRootIfMissing: input.createWorkspaceRootIfMissing }),
258 ...(input.defaultModelSelection === undefined
259 ? {}
260 : { defaultModelSelection: input.defaultModelSelection }),
261 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
262 });
263});
264​
265export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(function* (
266 input: UpdateProjectInput,
267) {
268 return yield* mutateProject({
269 type: "project.update",
270 commandId: yield* allocateCommandId(input),
271 projectId: input.projectId,
272 ...(input.title === undefined ? {} : { title: input.title }),
273 ...(input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot }),
274 ...(input.defaultModelSelection === undefined
275 ? {}
276 : { defaultModelSelection: input.defaultModelSelection }),
277 ...(input.scripts === undefined ? {} : { scripts: input.scripts }),
278 });
279});
280​
281export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* (
282 input: DeleteProjectInput,
283) {
284 return yield* mutateProject({
285 type: "project.delete",
286 commandId: yield* allocateCommandId(input),
287 projectId: input.projectId,
288 ...(input.force === undefined ? {} : { force: input.force }),
289 });
290});
291​
292export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* (
293 input: CreateThreadInput,
294) {
295 return yield* dispatch({
296 type: "thread.create",
297 commandId: yield* allocateCommandId(input),
298 createdBy: "user",
299 creationSource: input.creationSource ?? "web",
300 threadId: input.threadId,
301 projectId: input.projectId,
302 title: input.title,
303 modelSelection: input.modelSelection,
304 runtimeMode: input.runtimeMode,
305 interactionMode: input.interactionMode,
306 branch: input.branch,
307 worktreePath: input.worktreePath,
308 });
309});
310​
311function simpleThreadCommand(
312 type: "thread.delete" | "thread.archive" | "thread.unarchive",
313 input: ThreadCommandInput,
314) {
315 return allocateCommandId(input).pipe(
316 Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })),
317 );
319​
320export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
321 input: DeleteThreadInput,
322) {
323 return yield* simpleThreadCommand("thread.delete", input);
324});
325​
326export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
327 input: ArchiveThreadInput,
328) {
329 return yield* simpleThreadCommand("thread.archive", input);
330});
331​
332export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* (
333 input: UnarchiveThreadInput,
334) {
335 return yield* simpleThreadCommand("thread.unarchive", input);
336});
337​
338export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
339 function* (input: UpdateThreadMetadataInput) {
340 const commandId = yield* allocateCommandId(input);
341 let result = null;
342 if (
343 input.title !== undefined ||
344 input.branch !== undefined ||
345 input.worktreePath !== undefined
346 ) {
347 result = yield* dispatch({
348 type: "thread.metadata.update",
349 commandId,
350 threadId: input.threadId,
351 ...(input.title === undefined ? {} : { title: input.title }),
352 ...(input.branch === undefined ? {} : { branch: input.branch }),
353 ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
354 });
355 }
356 if (input.modelSelection !== undefined) {
357 const projection = yield* getProjection(input.threadId);
358 const type =
359 projection.thread.providerInstanceId === input.modelSelection.instanceId
360 ? ("thread.model-selection.set" as const)
361 : ("provider.switch" as const);
362 result = yield* dispatch({
363 type,
364 commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`),
365 threadId: input.threadId,
366 modelSelection: input.modelSelection,
367 });
368 }
369 return result ?? { sequence: 0 };
370 },
371);
372​
373export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")(
374 function* (input: SetThreadRuntimeModeInput) {
375 return yield* dispatch({
376 type: "thread.runtime-mode.set",
377 commandId: yield* allocateCommandId(input),
378 threadId: input.threadId,
379 runtimeMode: input.runtimeMode,
380 });
381 },
382);
383​
384export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")(
385 function* (input: SetThreadInteractionModeInput) {
386 return yield* dispatch({
387 type: "thread.interaction-mode.set",
388 commandId: yield* allocateCommandId(input),
389 threadId: input.threadId,
390 interactionMode: input.interactionMode,
391 });
392 },
393);
394​
395export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* (
396 input: StartThreadTurnInput,
397) {
398 const commandId = yield* allocateCommandId(input);
399 const attachments = yield* persistAttachments(
400 input.threadId,
401 input.message.messageId,
402 input.message.attachments,
403 );
404 const bootstrap = input.bootstrap?.createThread;
405 const prepareWorktree = input.bootstrap?.prepareWorktree;
406 if (bootstrap !== undefined || prepareWorktree !== undefined) {
407 const existingProjection =
408 bootstrap === undefined ? yield* getProjection(input.threadId) : null;
409 const thread = bootstrap ?? existingProjection!.thread;
410 const workspaceStrategy =
411 prepareWorktree !== undefined
412 ? {
413 type: "worktree" as const,
414 baseRef: prepareWorktree.baseBranch,
415 ...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }),
416 ...(prepareWorktree.startFromOrigin === undefined
417 ? {}
418 : { startFromOrigin: prepareWorktree.startFromOrigin }),
419 }
420 : bootstrap?.worktreePath
421 ? {
422 type: "existing_worktree" as const,
423 worktreePath: bootstrap.worktreePath,
424 ...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }),
425 }
426 : {
427 type: "root" as const,
428 ...(bootstrap?.branch === null || bootstrap?.branch === undefined
429 ? {}
430 : { branch: bootstrap.branch }),
431 };
432 return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
433 commandId,
434 creationSource: input.creationSource ?? "web",
435 threadId: input.threadId,
436 ...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
437 projectId: thread.projectId,
438 title: thread.title,
439 modelSelection: input.modelSelection ?? thread.modelSelection,
440 runtimeMode: input.runtimeMode,
441 interactionMode: input.interactionMode,
442 workspaceStrategy,
443 initialMessage: {
444 messageId: input.message.messageId,
445 text: input.message.text,
446 attachments,
447 },
448 });
449 }
450​
451 const projection = yield* getProjection(input.threadId);
452 const activeRun = projection.runs.findLast(
453 (run) =>
454 run.status === "preparing" ||
455 run.status === "starting" ||
456 run.status === "running" ||
457 run.status === "waiting",
458 );
459 const requestedMode = input.dispatchMode ?? "auto";
460 const activeProviderThread =
461 activeRun === undefined
462 ? undefined
463 : projection.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
464 const activeProviderSession =
465 activeProviderThread?.providerSessionId === null ||
466 activeProviderThread?.providerSessionId === undefined
467 ? undefined
468 : projection.providerSessions.find(
469 (session) => session.id === activeProviderThread.providerSessionId,
470 );
471 const turnCapabilities = activeProviderSession?.capabilities.turns;
472 const dispatchMode =
473 activeRun === undefined
474 ? ({ type: "start_immediately" } as const)
475 : requestedMode === "steer"
476 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
477 : requestedMode === "restart"
478 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
479 : requestedMode === "queue"
480 ? ({ type: "queue_after_active" } as const)
481 : turnCapabilities?.supportsActiveSteering === true
482 ? ({ type: "steer_active", targetRunId: activeRun.id } as const)
483 : turnCapabilities?.supportsQueuedMessages === true
484 ? ({ type: "queue_after_active" } as const)
485 : turnCapabilities?.supportsSteeringByInterruptRestart === true
486 ? ({ type: "restart_active", targetRunId: activeRun.id } as const)
487 : ({ type: "queue_after_active" } as const);
488 return yield* dispatch({
489 type: "message.dispatch",
490 commandId,
491 createdBy: "user",
492 creationSource: input.creationSource ?? "web",
493 threadId: input.threadId,
494 messageId: input.message.messageId,
495 text: input.message.text,
496 attachments,
497 ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
498 ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
499 dispatchMode,
500 });
501});
502​
503export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
504 input: InterruptThreadTurnInput,
505) {
506 const projection = yield* getProjection(input.threadId);
507 const runId =
508 input.runId ??
509 (input.turnId as RunId | undefined) ??
510 projection.runs.findLast(
511 (run) =>
512 run.status === "preparing" ||
513 run.status === "starting" ||
514 run.status === "running" ||
515 run.status === "waiting",
516 )?.id;
517 if (runId === undefined) return { sequence: 0 };
518 return yield* dispatch({
519 type: "run.interrupt",
520 commandId: yield* allocateCommandId(input),
521 threadId: input.threadId,
522 runId,
523 });
524});
525​
526export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
527 function* (input: RespondToThreadApprovalInput) {
528 return yield* dispatch({
529 type: "runtime-request.respond",
530 commandId: yield* allocateCommandId(input),
531 threadId: input.threadId,
532 requestId: input.requestId,
533 decision: input.decision,
534 });
535 },
536);
537​
538export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
539 function* (input: RespondToThreadUserInputInput) {
540 return yield* dispatch({
541 type: "runtime-request.respond",
542 commandId: yield* allocateCommandId(input),
543 threadId: input.threadId,
544 requestId: input.requestId,
545 answers: input.answers,
546 });
547 },
548);
549​
550export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
551 function* (input: RevertThreadCheckpointInput) {
552 const projection = yield* getProjection(input.threadId);
553 const checkpoint =
554 projection.checkpoints.find(
555 (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
556 ) ??
557 projection.checkpoints.findLast((candidate) =>
558 input.turnCount === 0
559 ? candidate.ordinalWithinScope === 0 && candidate.appRunOrdinal === null
560 : candidate.appRunOrdinal === input.turnCount,
561 );
562 if (checkpoint === undefined || checkpoint.status !== "ready") {
563 const target =
564 input.checkpointId === undefined
565 ? `run ordinal ${input.turnCount ?? "unknown"}`
566 : `checkpoint ${input.checkpointId}`;
567 return yield* new OrchestrationV2CheckpointUnavailableError({
568 threadId: input.threadId,
569 target,
570 });
571 }
572 return yield* dispatch({
573 type: "checkpoint.rollback",
574 commandId: yield* allocateCommandId(input),
575 threadId: input.threadId,
576 scopeId: checkpoint.scopeId,
577 checkpointId: checkpoint.id,
578 });
579 },
580);
581​
582export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
583 input: StopThreadSessionInput,
584) {
585 const projection = yield* getProjection(input.threadId);
586 const commandId = yield* allocateCommandId(input);
587 let result = { sequence: 0 };
588 for (const session of projection.providerSessions) {
589 result = yield* dispatch({
590 type: "provider-session.detach",
591 commandId: CommandId.make(`${commandId}:detach:${session.id}`),
592 threadId: input.threadId,
593 providerSessionId: session.id,
594 reason: "client-requested",
595 });
596 }
597 return result;
598});
599​
600export const forkThreadFromRun = Effect.fn("EnvironmentCommands.forkThreadFromRun")(function* (
601 input: ForkThreadFromRunInput,
602) {
603 return yield* dispatch({
604 type: "thread.fork",
605 commandId: yield* allocateCommandId(input),
606 createdBy: "user",
607 creationSource: input.creationSource ?? "web",
608 sourceThreadId: input.sourceThreadId,
609 targetThreadId: input.targetThreadId,
610 sourcePoint: { type: "run", runId: input.runId },
611 ...(input.title === undefined ? {} : { title: input.title }),
612 });
613});
614​
615export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(function* (
616 input: MergeThreadBackInput,
617) {
618 return yield* dispatch({
619 type: "thread.merge_back",
620 commandId: yield* allocateCommandId(input),
621 createdBy: "user",
622 creationSource: input.creationSource ?? "web",
623 sourceThreadId: input.sourceThreadId,
624 targetThreadId: input.targetThreadId,
625 sourcePoint: { type: "run", runId: input.runId },
626 });
627});
628​
629export const reorderQueuedRun = Effect.fn("EnvironmentCommands.reorderQueuedRun")(function* (
630 input: ReorderQueuedRunInput,
631) {
632 return yield* dispatch({
633 type: "queued-run.reorder",
634 commandId: yield* allocateCommandId(input),
635 threadId: input.threadId,
636 runId: input.runId,
637 beforeRunId: input.beforeRunId,
638 });
639});
640​
641export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* (
642 input: PromoteQueuedRunInput,
643) {
644 return yield* dispatch({
645 type: "queued-message.promote-to-steer",
646 commandId: yield* allocateCommandId(input),
647 threadId: input.threadId,
648 queuedRunId: input.queuedRunId,
649 targetRunId: input.targetRunId,
650 });
651});