Add plan interaction mode and user-input request handling

- Wire Codex plan mode through turn start, including collaboration settings
- Track and answer pending `requestUserInput` prompts instead of auto-empty responses
- Persist/project thread `interactionMode` (schema, migration, queries) and update tests/contracts
This commit is contained in:
Julius Marminge authored and Julius Marminge committed 2026-03-05 23:00:41 -08:00
1 parent 26f631b638
commit 12edc3455c
57 files changed
+4714 -730

No files matched your search

@@ -413,6 +413,12 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
})
: missingSessionEffect(provider, threadId);
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
@@ -475,6 +481,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -4,6 +4,7 @@ import path from "node:path";
import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
@@ -118,6 +119,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: harness.workspaceDir,
@@ -143,6 +145,7 @@ const startTurn = (input: {
attachments: [],
},
...(input.provider !== undefined ? { provider: input.provider } : {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
});
@@ -241,6 +244,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Thread",
model: "gpt-5.3-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: harness.workspaceDir,
@@ -257,6 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
text: "Reply with exactly ALPHA.",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: nowIso(),
});
@@ -283,6 +288,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
text: "Reply with exactly BETA.",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
});
@@ -1,5 +1,6 @@
import {
CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
TurnId,
@@ -43,6 +44,7 @@ function makeSnapshot(input: {
projectId: input.projectId,
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
+129 -1
View File
@@ -3,9 +3,11 @@ import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { ThreadId } from "@t3tools/contracts";
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
import {
buildCodexInitializeParams,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
CodexAppServerManager,
classifyCodexStderrLine,
isRecoverableThreadResumeError,
@@ -22,6 +24,7 @@ function createSendTurnHarness() {
provider: "codex",
status: "ready",
threadId: "thread_1",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
@@ -58,6 +61,7 @@ function createThreadControlHarness() {
provider: "codex",
status: "ready",
threadId: "thread_1",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
@@ -80,6 +84,46 @@ function createThreadControlHarness() {
return { manager, context, requireSession, sendRequest, updateSession };
}
function createPendingUserInputHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
sessionId: "sess_1",
provider: "codex",
status: "ready",
threadId: "thread_1",
resumeCursor: { threadId: "thread_1" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
pendingUserInputs: new Map([
[
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
jsonRpcId: 42,
threadId: asThreadId("thread_1"),
},
],
]),
};
const requireSession = vi
.spyOn(
manager as unknown as { requireSession: (sessionId: string) => unknown },
"requireSession",
)
.mockReturnValue(context);
const writeMessage = vi
.spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
.mockImplementation(() => {});
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
return { manager, context, requireSession, writeMessage, emitEvent };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -151,6 +195,19 @@ describe("isRecoverableThreadResumeError", () => {
});
describe("startSession", () => {
it("enables Codex experimental api capabilities during initialize", () => {
expect(buildCodexInitializeParams()).toEqual({
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
});
});
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
const manager = new CodexAppServerManager();
const events: Array<{ method: string; kind: string; message?: string }> = [];
@@ -207,6 +264,7 @@ describe("sendTurn", () => {
expect(result).toEqual({
threadId: "thread_1",
turnId: "turn_1",
resumeCursor: { threadId: "thread_1" },
});
expect(requireSession).toHaveBeenCalledWith("thread_1");
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
@@ -228,6 +286,7 @@ describe("sendTurn", () => {
expect(updateSession).toHaveBeenCalledWith(context, {
status: "running",
activeTurnId: "turn_1",
resumeCursor: { threadId: "thread_1" },
});
});
@@ -255,6 +314,36 @@ describe("sendTurn", () => {
});
});
it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
const { manager, context, sendRequest } = createSendTurnHarness();
await manager.sendTurn({
threadId: asThreadId("thread_1"),
input: "Plan the work",
interactionMode: "plan",
});
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
threadId: "thread_1",
input: [
{
type: "text",
text: "Plan the work",
text_elements: [],
},
],
model: "gpt-5.3-codex",
collaborationMode: {
mode: "plan",
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
},
});
});
it("rejects empty turn input", async () => {
const { manager } = createSendTurnHarness();
@@ -354,6 +443,45 @@ describe("thread checkpoint control", () => {
});
});
describe("respondToUserInput", () => {
it("serializes canonical answers to Codex native answer objects", async () => {
const { manager, context, requireSession, writeMessage, emitEvent } =
createPendingUserInputHarness();
await manager.respondToUserInput(
asThreadId("thread_1"),
ApprovalRequestId.makeUnsafe("req-user-input-1"),
{
scope: "All request methods",
compat: "Keep current envelope",
},
);
expect(requireSession).toHaveBeenCalledWith("thread_1");
expect(writeMessage).toHaveBeenCalledWith(context, {
id: 42,
result: {
answers: {
scope: { answers: ["All request methods"] },
compat: { answers: ["Keep current envelope"] },
},
},
});
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/tool/requestUserInput/answered",
payload: {
requestId: "req-user-input-1",
answers: {
scope: { answers: ["All request methods"] },
compat: { answers: ["Keep current envelope"] },
},
},
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it(
"keeps prior thread history when resuming with a changed runtime mode",
+281 -15
View File
@@ -8,6 +8,7 @@ import {
EventId,
ProviderItemId,
ProviderRequestKind,
type ProviderUserInputAnswers,
ThreadId,
TurnId,
normalizeModelSlug,
@@ -38,12 +39,25 @@ interface PendingApprovalRequest {
itemId?: ProviderItemId;
}
interface PendingUserInputRequest {
requestId: ApprovalRequestId;
jsonRpcId: string | number;
threadId: ThreadId;
turnId?: TurnId;
itemId?: ProviderItemId;
}
interface CodexUserInputAnswer {
answers: string[];
}
interface CodexSessionContext {
session: ProviderSession;
child: ChildProcessWithoutNullStreams;
output: readline.Interface;
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
nextRequestId: number;
stopping: boolean;
}
@@ -76,6 +90,7 @@ export interface CodexAppServerSendTurnInput {
readonly attachments?: ReadonlyArray<{ type: "image"; url: string }>;
readonly model?: string;
readonly effort?: string;
readonly interactionMode?: "default" | "plan";
}
export interface CodexThreadTurnSnapshot {
@@ -103,6 +118,127 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
## Mode rules (strict)
You are in **Plan Mode** until a developer message explicitly ends it.
Plan Mode is not changed by user intent, tone, or imperative language. If a user asks for execution while still in Plan Mode, treat it as a request to **plan the execution**, not perform it.
## Plan Mode vs update_plan tool
Plan Mode is a collaboration mode that can involve requesting user input and eventually issuing a \`<proposed_plan>\` block.
Separately, \`update_plan\` is a checklist/progress/TODOs tool; it does not enter or exit Plan Mode. Do not confuse it with Plan mode or try to use it while in Plan mode. If you try to use \`update_plan\` in Plan mode, it will return an error.
## Execution vs. mutation in Plan Mode
You may explore and execute **non-mutating** actions that improve the plan. You must not perform **mutating** actions.
### Allowed (non-mutating, plan-improving)
Actions that gather truth, reduce ambiguity, or validate feasibility without changing repo-tracked state. Examples:
* Reading or searching files, configs, schemas, types, manifests, and docs
* Static analysis, inspection, and repo exploration
* Dry-run style commands when they do not edit repo-tracked files
* Tests, builds, or checks that may write to caches or build artifacts (for example, \`target/\`, \`.cache/\`, or snapshots) so long as they do not edit repo-tracked files
### Not allowed (mutating, plan-executing)
Actions that implement the plan or change repo-tracked state. Examples:
* Editing or writing files
* Running formatters or linters that rewrite files
* Applying patches, migrations, or codegen that updates repo-tracked files
* Side-effectful commands whose purpose is to carry out the plan rather than refine it
When in doubt: if the action would reasonably be described as "doing the work" rather than "planning the work," do not do it.
## PHASE 1 - Ground in the environment (explore first, ask second)
Begin by grounding yourself in the actual environment. Eliminate unknowns in the prompt by discovering facts, not by asking the user. Resolve all questions that can be answered through exploration or inspection. Identify missing or ambiguous details only if they cannot be derived from the environment. Silent exploration between turns is allowed and encouraged.
Before asking the user any question, perform at least one targeted non-mutating exploration pass (for example: search relevant files, inspect likely entrypoints/configs, confirm current implementation shape), unless no local environment/repo is available.
Exception: you may ask clarifying questions about the user's prompt before exploring, ONLY if there are obvious ambiguities or contradictions in the prompt itself. However, if ambiguity might be resolved by exploring, always prefer exploring first.
Do not ask questions that can be answered from the repo or system (for example, "where is this struct?" or "which UI component should we use?" when exploration can make it clear). Only ask once you have exhausted reasonable non-mutating exploration.
## PHASE 2 - Intent chat (what they actually want)
* Keep asking until you can clearly state: goal + success criteria, audience, in/out of scope, constraints, current state, and the key preferences/tradeoffs.
* Bias toward questions over guessing: if any high-impact ambiguity remains, do NOT plan yet-ask.
## PHASE 3 - Implementation chat (what/how we'll build)
* Once intent is stable, keep asking until the spec is decision complete: approach, interfaces (APIs/schemas/I/O), data flow, edge cases/failure modes, testing + acceptance criteria, rollout/monitoring, and any migrations/compat constraints.
## Asking questions
Critical rules:
* Strongly prefer using the \`request_user_input\` tool to ask any questions.
* Offer only meaningful multiple-choice options; don't include filler choices that are obviously wrong or irrelevant.
* In rare cases where an unavoidable, important question can't be expressed with reasonable multiple-choice options (due to extreme ambiguity), you may ask it directly without the tool.
You SHOULD ask many questions, but each question must:
* materially change the spec/plan, OR
* confirm/lock an assumption, OR
* choose between meaningful tradeoffs.
* not be answerable by non-mutating commands.
Use the \`request_user_input\` tool only for decisions that materially change the plan, for confirming important assumptions, or for information that cannot be discovered via non-mutating exploration.
## Two kinds of unknowns (treat differently)
1. **Discoverable facts** (repo/system truth): explore first.
* Before asking, run targeted searches and check likely sources of truth (configs/manifests/entrypoints/schemas/types/constants).
* Ask only if: multiple plausible candidates; nothing found but you need a missing identifier/context; or ambiguity is actually product intent.
* If asking, present concrete candidates (paths/service names) + recommend one.
* Never ask questions you can answer from your environment (e.g., "where is this struct").
2. **Preferences/tradeoffs** (not discoverable): ask early.
* These are intent or implementation preferences that cannot be derived from exploration.
* Provide 2-4 mutually exclusive options + a recommended default.
* If unanswered, proceed with the recommended option and record it as an assumption in the final plan.
## Finalization rule
Only output the final plan when it is decision complete and leaves no decisions to the implementer.
When you present the official plan, wrap it in a \`<proposed_plan>\` block so the client can render it specially:
1) The opening tag must be on its own line.
2) Start the plan content on the next line (no text on the same line as the tag).
3) The closing tag must be on its own line.
4) Use Markdown inside the block.
5) Keep the tags exactly as \`<proposed_plan>\` and \`</proposed_plan>\` (do not translate or rename them), even if the plan content is in another language.
Example:
<proposed_plan>
plan content
</proposed_plan>
plan content should be human and agent digestible. The final plan must be plan-only and include:
* A clear title
* A brief summary section
* Important changes or additions to public APIs/interfaces/types
* Test cases and scenarios
* Explicit assumptions and defaults chosen where needed
Do not ask "should I proceed?" in the final output. The user can easily switch out of Plan mode and request implementation if you have included a \`<proposed_plan>\` block in your response. Alternatively, they can decide to stay in Plan mode and continue refining the plan.
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
</collaboration_mode>`;
function mapCodexRuntimeMode(runtimeMode: "approval-required" | "full-access"): {
readonly approvalPolicy: "on-request" | "never";
@@ -154,6 +290,80 @@ export function normalizeCodexModelSlug(
return normalized;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
function buildCodexCollaborationMode(input: {
readonly interactionMode?: "default" | "plan";
readonly model?: string;
readonly effort?: string;
}):
| {
mode: "plan";
settings: {
model: string;
reasoning_effort: string;
developer_instructions: string;
};
}
| undefined {
if (input.interactionMode !== "plan") {
return undefined;
}
const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
return {
mode: "plan",
settings: {
model,
reasoning_effort: input.effort ?? "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
},
};
}
function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
if (typeof value === "string") {
return { answers: [value] };
}
if (Array.isArray(value)) {
const answers = value.filter((entry): entry is string => typeof entry === "string");
if (answers.length > 0) {
return { answers };
}
}
if (value && typeof value === "object") {
const maybeAnswers = (value as { answers?: unknown }).answers;
if (Array.isArray(maybeAnswers)) {
const answers = maybeAnswers.filter((entry): entry is string => typeof entry === "string");
if (answers.length > 0) {
return { answers };
}
}
}
throw new Error("User input answers must be strings or arrays of strings.");
}
function toCodexUserInputAnswers(
answers: ProviderUserInputAnswers,
): Record<string, CodexUserInputAnswer> {
return Object.fromEntries(
Object.entries(answers).map(([questionId, value]) => [questionId, toCodexUserInputAnswer(value)]),
);
}
export function classifyCodexStderrLine(rawLine: string): { message: string } | null {
const line = rawLine.replaceAll(ANSI_ESCAPE_REGEX, "").trim();
if (!line) {
@@ -237,6 +447,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
output,
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -246,16 +457,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
this.emitLifecycleEvent(context, "session/connecting", "Starting codex app-server");
await this.sendRequest(context, "initialize", {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: false,
},
});
await this.sendRequest(context, "initialize", buildCodexInitializeParams());
this.writeMessage(context, { method: "initialized" });
@@ -423,17 +625,36 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
>;
model?: string;
effort?: string;
collaborationMode?: {
mode: "plan";
settings: {
model: string;
reasoning_effort: string;
developer_instructions: string;
};
};
} = {
threadId: providerThreadId,
input: turnInput,
};
const normalizedModel = normalizeCodexModelSlug(input.model);
const normalizedModel = normalizeCodexModelSlug(input.model ?? context.session.model);
if (normalizedModel) {
turnStartParams.model = normalizedModel;
}
if (input.effort) {
turnStartParams.effort = input.effort;
}
const collaborationMode = buildCodexCollaborationMode({
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
...(normalizedModel !== undefined ? { model: normalizedModel } : {}),
...(input.effort !== undefined ? { effort: input.effort } : {}),
});
if (collaborationMode) {
if (!turnStartParams.model) {
turnStartParams.model = collaborationMode.settings.model;
}
turnStartParams.collaborationMode = collaborationMode;
}
const response = await this.sendRequest(context, "turn/start", turnStartParams);
@@ -561,6 +782,43 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
});
}
async respondToUserInput(
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
): Promise<void> {
const context = this.requireSession(threadId);
const pendingRequest = context.pendingUserInputs.get(requestId);
if (!pendingRequest) {
throw new Error(`Unknown pending user input request: ${requestId}`);
}
context.pendingUserInputs.delete(requestId);
const codexAnswers = toCodexUserInputAnswers(answers);
this.writeMessage(context, {
id: pendingRequest.jsonRpcId,
result: {
answers: codexAnswers,
},
});
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
turnId: pendingRequest.turnId,
itemId: pendingRequest.itemId,
requestId: pendingRequest.requestId,
payload: {
requestId: pendingRequest.requestId,
answers: codexAnswers,
},
});
}
stopSession(threadId: ThreadId): void {
const context = this.sessions.get(threadId);
if (!context) {
@@ -575,6 +833,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
context.pending.clear();
context.pendingApprovals.clear();
context.pendingUserInputs.clear();
context.output.close();
@@ -792,6 +1051,17 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context.pendingApprovals.set(requestId, pendingRequest);
}
if (request.method === "item/tool/requestUserInput") {
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
context.pendingUserInputs.set(requestId, {
requestId,
jsonRpcId: request.id,
threadId: context.session.threadId,
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
});
}
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
kind: "request",
@@ -811,10 +1081,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (request.method === "item/tool/requestUserInput") {
this.writeMessage(context, {
id: request.id,
result: { answers: {} },
});
return;
}
@@ -6,6 +6,7 @@ import { execFileSync } from "node:child_process";
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
@@ -85,6 +86,7 @@ function createProviderServiceHarness(
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
@@ -286,6 +288,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: options?.threadWorktreePath ?? cwd,
@@ -601,6 +604,7 @@ describe("CheckpointReactor", () => {
text: "start turn",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
}),
@@ -1,6 +1,7 @@
import {
CheckpointRef,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
ProjectId,
ThreadId,
@@ -80,6 +81,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -97,6 +99,7 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt,
}),
@@ -132,6 +135,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "replay",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -193,7 +197,8 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "domain-stream",
model: "gpt-5-codex",
runtimeMode: "approval-required",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
@@ -237,6 +242,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -345,7 +351,8 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
model: "gpt-5-codex",
runtimeMode: "approval-required",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
@@ -361,6 +368,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -425,6 +433,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "atomic",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -442,6 +451,7 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required" as const,
createdAt,
};
@@ -558,6 +568,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "sync-before",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -602,6 +613,7 @@ describe("OrchestrationEngine", () => {
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now(),
}),
@@ -636,6 +648,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -652,7 +665,8 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "duplicate",
model: "gpt-5-codex",
runtimeMode: "approval-required",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
@@ -397,6 +397,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
title: event.payload.title,
model: event.payload.model,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
branch: event.payload.branch,
worktreePath: event.payload.worktreePath,
latestTurnId: null,
@@ -441,6 +442,21 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
return;
}
case "thread.interaction-mode-set": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
interactionMode: event.payload.interactionMode,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.deleted": {
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
const existingRow = yield* projectionThreadRepository.getById({
@@ -234,6 +234,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
projectId: asProjectId("project-1"),
title: "Thread 1",
model: "gpt-5-codex",
interactionMode: "default",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -154,6 +154,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
title,
model,
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
@@ -485,6 +486,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
title: row.title,
model: row.model,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
@@ -6,6 +6,7 @@ import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
@@ -139,6 +140,7 @@ describe("ProviderCommandReactor", () => {
);
const interruptTurn = vi.fn((_: unknown) => Effect.void);
const respondToRequest = vi.fn<ProviderServiceShape["respondToRequest"]>(() => Effect.void);
const respondToUserInput = vi.fn<ProviderServiceShape["respondToUserInput"]>(() => Effect.void);
const stopSession = vi.fn((input: unknown) =>
Effect.sync(() => {
const threadId =
@@ -180,6 +182,7 @@ describe("ProviderCommandReactor", () => {
sendTurn: sendTurn as ProviderServiceShape["sendTurn"],
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
stopSession: stopSession as ProviderServiceShape["stopSession"],
listSessions: () => Effect.succeed(runtimeSessions),
getCapabilities: (provider) =>
@@ -234,6 +237,7 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -247,6 +251,7 @@ describe("ProviderCommandReactor", () => {
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
renameBranch,
generateBranchName,
@@ -269,6 +274,7 @@ describe("ProviderCommandReactor", () => {
text: "hello reactor",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -289,6 +295,44 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("forwards plan interaction mode to the provider turn request", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.interaction-mode.set",
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"),
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-plan"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-plan"),
role: "user",
text: "plan this change",
attachments: [],
},
interactionMode: "plan",
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
});
});
it("starts first turn with requested provider when provider is specified", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -305,6 +349,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
provider: "claudeCode",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -341,6 +386,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
provider: "cursor",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -376,6 +422,7 @@ describe("ProviderCommandReactor", () => {
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -395,6 +442,7 @@ describe("ProviderCommandReactor", () => {
text: "second",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -422,6 +470,7 @@ describe("ProviderCommandReactor", () => {
},
provider: "cursor",
model: "composer-1.5",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -443,6 +492,7 @@ describe("ProviderCommandReactor", () => {
},
provider: "cursor",
model: "composer-1.5",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -470,6 +520,7 @@ describe("ProviderCommandReactor", () => {
},
provider: "cursor",
model: "gpt-5.3-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -491,6 +542,7 @@ describe("ProviderCommandReactor", () => {
},
provider: "cursor",
model: "composer-1.5",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -531,6 +583,7 @@ describe("ProviderCommandReactor", () => {
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
@@ -566,6 +619,7 @@ describe("ProviderCommandReactor", () => {
text: "second",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
@@ -604,6 +658,7 @@ describe("ProviderCommandReactor", () => {
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -624,6 +679,7 @@ describe("ProviderCommandReactor", () => {
attachments: [],
},
provider: "claudeCode",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -672,6 +728,7 @@ describe("ProviderCommandReactor", () => {
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
createdAt: now,
}),
@@ -746,7 +803,6 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.interruptTurn.mock.calls.length === 1);
expect(harness.interruptTurn.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
turnId: "turn-1",
});
});
@@ -791,6 +847,51 @@ describe("ProviderCommandReactor", () => {
});
});
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe("cmd-user-input-respond"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("user-input-request-1"),
answers: {
sandbox_mode: "workspace-write",
},
createdAt: now,
}),
);
await waitFor(() => harness.respondToUserInput.mock.calls.length === 1);
expect(harness.respondToUserInput.mock.calls[0]?.[0]).toEqual({
threadId: "thread-1",
requestId: "user-input-request-1",
answers: {
sandbox_mode: "workspace-write",
},
});
});
it("surfaces stale provider approval request failures without faking approval resolution", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -31,6 +31,7 @@ type ProviderIntentEvent = Extract<
| "thread.turn-start-requested"
| "thread.turn-interrupt-requested"
| "thread.approval-response-requested"
| "thread.user-input-response-requested"
| "thread.session-stop-requested";
}
>;
@@ -147,6 +148,7 @@ const make = Effect.gen(function* () {
| "provider.turn.start.failed"
| "provider.turn.interrupt.failed"
| "provider.approval.respond.failed"
| "provider.user-input.respond.failed"
| "provider.session.stop.failed";
readonly summary: string;
readonly detail: string;
@@ -320,6 +322,7 @@ const make = Effect.gen(function* () {
readonly provider?: ProviderKind;
readonly model?: string;
readonly effort?: string;
readonly interactionMode?: "default" | "plan";
readonly createdAt: string;
}) {
const thread = yield* resolveThread(input.threadId);
@@ -348,6 +351,7 @@ const make = Effect.gen(function* () {
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.effort !== undefined ? { effort: input.effort } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
});
@@ -461,6 +465,7 @@ const make = Effect.gen(function* () {
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
});
});
@@ -535,6 +540,50 @@ const make = Effect.gen(function* () {
);
});
const processUserInputResponseRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}
yield* providerService
.respondToUserInput({
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
})
.pipe(
Effect.catchCause((cause) =>
Effect.gen(function* () {
const error = Cause.squash(cause);
yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: toErrorMessage(error),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}),
),
);
});
const processSessionStopRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
) {
@@ -583,6 +632,9 @@ const make = Effect.gen(function* () {
case "thread.approval-response-requested":
yield* processApprovalResponseRequested(event);
return;
case "thread.user-input-response-requested":
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
@@ -617,6 +669,7 @@ const make = Effect.gen(function* () {
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.turn-interrupt-requested" &&
event.type !== "thread.approval-response-requested" &&
event.type !== "thread.user-input-response-requested" &&
event.type !== "thread.session-stop-requested"
) {
return Effect.void;
@@ -2,6 +2,7 @@ import type { OrchestrationReadModel, ProviderRuntimeEvent } from "@t3tools/cont
import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
@@ -59,6 +60,7 @@ function createProviderServiceHarness() {
sendTurn: () => unsupported(),
interruptTurn: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
@@ -163,6 +165,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -630,6 +633,112 @@ describe("ProviderRuntimeIngestion", () => {
expect(message?.streaming).toBe(false);
});
it("projects completed plan items into finalized proposed-plan assistant messages", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "item.completed",
eventId: asEventId("evt-plan-item-completed"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-final"),
itemId: asItemId("item-plan-final"),
payload: {
itemType: "plan",
status: "completed",
detail: "## Ship plan\n\n- wire projection\n- render follow-up",
},
});
const thread = await waitForThread(harness.engine, (entry) => {
const message = entry.messages.find(
(candidate: ProviderRuntimeTestMessage) => candidate.id === "assistant:item-plan-final",
);
return message?.streaming === false && message.text.includes("<proposed_plan>");
});
const message = thread.messages.find(
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-plan-final",
);
expect(message?.text).toBe(
"<proposed_plan>\n## Ship plan\n\n- wire projection\n- render follow-up\n</proposed_plan>",
);
expect(message?.streaming).toBe(false);
});
it("finalizes buffered plan deltas into a proposed-plan assistant message on turn completion", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-plan-buffer"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
});
await waitForThread(
harness.engine,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === "turn-plan-buffer",
);
harness.emit({
type: "content.delta",
eventId: asEventId("evt-plan-delta-1"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
itemId: asItemId("item-plan-buffer"),
payload: {
streamKind: "plan_text",
delta: "## Buffered plan\n\n- first",
},
});
harness.emit({
type: "content.delta",
eventId: asEventId("evt-plan-delta-2"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
itemId: asItemId("item-plan-buffer"),
payload: {
streamKind: "plan_text",
delta: "\n- second",
},
});
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-plan-buffer"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-plan-buffer"),
payload: {
state: "completed",
},
});
const thread = await waitForThread(harness.engine, (entry) => {
const message = entry.messages.find(
(candidate: ProviderRuntimeTestMessage) => candidate.id === "assistant:item-plan-buffer",
);
return message?.streaming === false && message.text.includes("<proposed_plan>");
});
const message = thread.messages.find(
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-plan-buffer",
);
expect(message?.text).toBe(
"<proposed_plan>\n## Buffered plan\n\n- first\n- second\n</proposed_plan>",
);
expect(message?.streaming).toBe(false);
});
it("buffers assistant deltas by default until completion", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -716,6 +825,7 @@ describe("ProviderRuntimeIngestion", () => {
attachments: [],
},
assistantDeliveryMode: "streaming",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
@@ -1217,6 +1327,160 @@ describe("ProviderRuntimeIngestion", () => {
expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated");
});
it("projects Codex task lifecycle chunks into thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "task.started",
eventId: asEventId("evt-task-started"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
payload: {
taskId: "turn-task-1",
taskType: "plan",
},
});
harness.emit({
type: "task.progress",
eventId: asEventId("evt-task-progress"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
payload: {
taskId: "turn-task-1",
description: "Comparing the desktop rollout chunks to the app-server stream.",
},
});
harness.emit({
type: "task.completed",
eventId: asEventId("evt-task-completed"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
payload: {
taskId: "turn-task-1",
status: "completed",
summary: "<proposed_plan>\n# Plan title\n</proposed_plan>",
},
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "task.completed",
),
);
const started = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-started",
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-progress",
);
const completed = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-completed",
);
const progressPayload =
progress?.payload && typeof progress.payload === "object"
? (progress.payload as Record<string, unknown>)
: undefined;
const completedPayload =
completed?.payload && typeof completed.payload === "object"
? (completed.payload as Record<string, unknown>)
: undefined;
expect(started?.kind).toBe("task.started");
expect(started?.summary).toBe("Plan task started");
expect(progress?.kind).toBe("task.progress");
expect(progressPayload?.detail).toBe(
"Comparing the desktop rollout chunks to the app-server stream.",
);
expect(completed?.kind).toBe("task.completed");
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
});
it("projects structured user input request and resolution as thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "user-input.requested",
eventId: asEventId("evt-user-input-requested"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
});
harness.emit({
type: "user-input.resolved",
eventId: asEventId("evt-user-input-resolved"),
provider: "codex",
createdAt: new Date().toISOString(),
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-user-input"),
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
answers: {
sandbox_mode: "workspace-write",
},
},
});
const thread = await waitForThread(
harness.engine,
(entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.requested",
) &&
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "user-input.resolved",
),
);
const requested = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-user-input-requested",
);
expect(requested?.kind).toBe("user-input.requested");
const resolved = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-user-input-resolved",
);
const resolvedPayload =
resolved?.payload && typeof resolved.payload === "object"
? (resolved.payload as Record<string, unknown>)
: undefined;
expect(resolved?.kind).toBe("user-input.resolved");
expect(resolvedPayload?.answers).toEqual({
sandbox_mode: "workspace-write",
});
});
it("continues processing runtime events after a single event handler failure", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -26,6 +26,8 @@ const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
const MESSAGE_STREAM_KIND_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
const MESSAGE_STREAM_KIND_BY_MESSAGE_ID_TTL = Duration.minutes(120);
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL = Duration.minutes(120);
const MAX_BUFFERED_ASSISTANT_CHARS = 24_000;
@@ -65,6 +67,14 @@ function truncateDetail(value: string, limit = 180): string {
return value.length > limit ? `${value.slice(0, limit - 3)}...` : value;
}
function wrapProposedPlanMessage(planMarkdown: string | undefined): string | undefined {
const trimmed = planMarkdown?.trim();
if (!trimmed) {
return undefined;
}
return `<proposed_plan>\n${trimmed}\n</proposed_plan>`;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
@@ -168,6 +178,9 @@ function runtimeEventToActivities(
})();
switch (event.type) {
case "request.opened": {
if (event.payload.requestType === "tool_user_input") {
return [];
}
const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);
return [
{
@@ -196,6 +209,9 @@ function runtimeEventToActivities(
}
case "request.resolved": {
if (event.payload.requestType === "tool_user_input") {
return [];
}
const requestKind = requestKindFromCanonicalRequestType(event.payload.requestType);
return [
{
@@ -273,6 +289,111 @@ function runtimeEventToActivities(
];
}
case "user-input.requested": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
...(event.requestId ? { requestId: event.requestId } : {}),
questions: event.payload.questions,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "user-input.resolved": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "user-input.resolved",
summary: "User input submitted",
payload: {
...(event.requestId ? { requestId: event.requestId } : {}),
answers: event.payload.answers,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "task.started": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "task.started",
summary:
event.payload.taskType === "plan"
? "Plan task started"
: event.payload.taskType
? `${event.payload.taskType} task started`
: "Task started",
payload: {
taskId: event.payload.taskId,
...(event.payload.taskType ? { taskType: event.payload.taskType } : {}),
...(event.payload.description ? { detail: truncateDetail(event.payload.description) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "task.progress": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "task.progress",
summary: "Reasoning update",
payload: {
taskId: event.payload.taskId,
detail: truncateDetail(event.payload.description),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "task.completed": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: event.payload.status === "failed" ? "error" : "info",
kind: "task.completed",
summary:
event.payload.status === "failed"
? "Task failed"
: event.payload.status === "stopped"
? "Task stopped"
: "Task completed",
payload: {
taskId: event.payload.taskId,
status: event.payload.status,
...(event.payload.summary ? { detail: truncateDetail(event.payload.summary) } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "item.updated": {
if (!isToolLifecycleItemType(event.payload.itemType)) {
return [];
@@ -359,6 +480,12 @@ const make = Effect.gen(function* () {
lookup: () => Effect.succeed(new Set<MessageId>()),
});
const messageStreamKindByMessageId = yield* Cache.make<MessageId, "assistant_text" | "plan_text">({
capacity: MESSAGE_STREAM_KIND_BY_MESSAGE_ID_CACHE_CAPACITY,
timeToLive: MESSAGE_STREAM_KIND_BY_MESSAGE_ID_TTL,
lookup: () => Effect.succeed("assistant_text"),
});
const bufferedAssistantTextByMessageId = yield* Cache.make<MessageId, string>({
capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
@@ -418,6 +545,16 @@ const make = Effect.gen(function* () {
const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
const rememberMessageStreamKind = (
messageId: MessageId,
streamKind: "assistant_text" | "plan_text",
) => Cache.set(messageStreamKindByMessageId, messageId, streamKind);
const getMessageStreamKind = (messageId: MessageId) =>
Cache.getOption(messageStreamKindByMessageId, messageId).pipe(
Effect.map((streamKind) => Option.getOrElse(streamKind, () => "assistant_text" as const)),
);
const appendBufferedAssistantText = (messageId: MessageId, delta: string) =>
Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe(
Effect.flatMap((existingText) =>
@@ -451,7 +588,10 @@ const make = Effect.gen(function* () {
Cache.invalidate(bufferedAssistantTextByMessageId, messageId);
const clearAssistantMessageState = (messageId: MessageId) =>
clearBufferedAssistantText(messageId);
Effect.all([
clearBufferedAssistantText(messageId),
Cache.invalidate(messageStreamKindByMessageId, messageId),
]).pipe(Effect.asVoid);
const finalizeAssistantMessage = (input: {
event: ProviderRuntimeEvent;
@@ -464,9 +604,20 @@ const make = Effect.gen(function* () {
fallbackText?: string;
}) =>
Effect.gen(function* () {
const messageStreamKind = yield* getMessageStreamKind(input.messageId);
const bufferedText = yield* takeBufferedAssistantText(input.messageId);
const bufferedFinalText =
bufferedText.length > 0
? messageStreamKind === "plan_text"
? (wrapProposedPlanMessage(bufferedText) ?? "")
: bufferedText
: "";
const text =
bufferedText.length > 0 ? bufferedText : (input.fallbackText?.trim().length ?? 0) > 0 ? input.fallbackText! : "";
bufferedFinalText.length > 0
? bufferedFinalText
: (input.fallbackText?.trim().length ?? 0) > 0
? input.fallbackText!
: "";
if (text.length > 0) {
yield* orchestrationEngine.dispatch({
@@ -617,7 +768,8 @@ const make = Effect.gen(function* () {
}
const assistantDelta =
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
event.type === "content.delta" &&
(event.payload.streamKind === "assistant_text" || event.payload.streamKind === "plan_text")
? event.payload.delta
: undefined;
@@ -626,9 +778,14 @@ const make = Effect.gen(function* () {
`assistant:${event.itemId ?? event.turnId ?? event.eventId}`,
);
const turnId = toTurnId(event.turnId);
const messageStreamKind =
event.type === "content.delta" && event.payload.streamKind === "plan_text"
? "plan_text"
: "assistant_text";
if (turnId) {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
yield* rememberMessageStreamKind(assistantMessageId, messageStreamKind);
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
if (assistantDeliveryMode === "buffered") {
@@ -658,12 +815,16 @@ const make = Effect.gen(function* () {
}
const assistantCompletion =
event.type === "item.completed" && event.payload.itemType === "assistant_message"
event.type === "item.completed" &&
(event.payload.itemType === "assistant_message" || event.payload.itemType === "plan")
? {
messageId: MessageId.makeUnsafe(`assistant:${event.itemId ?? event.turnId ?? event.eventId}`),
fallbackText: event.payload.detail,
fallbackText:
event.payload.itemType === "plan"
? wrapProposedPlanMessage(event.payload.detail)
: event.payload.detail,
}
: undefined;
: undefined;
if (assistantCompletion) {
const assistantMessageId = assistantCompletion.messageId;
+2
View File
@@ -5,6 +5,7 @@ import {
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -26,6 +27,7 @@ export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
MessageId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
type OrchestrationCommand,
@@ -50,6 +51,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.makeUnsafe("project-a"),
title: "Thread A",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -67,6 +69,7 @@ const readModel: OrchestrationReadModel = {
projectId: ProjectId.makeUnsafe("project-b"),
title: "Thread B",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -92,6 +95,7 @@ const messageSendCommand: OrchestrationCommand = {
text: "hello",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
};
@@ -139,6 +143,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.makeUnsafe("project-a"),
title: "new",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -159,6 +164,7 @@ describe("commandInvariants", () => {
projectId: ProjectId.makeUnsafe("project-a"),
title: "dup",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -1,4 +1,11 @@
import { CommandId, EventId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
@@ -130,6 +137,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
@@ -154,6 +162,7 @@ describe("decider project scripts", () => {
provider: "claudeCode",
model: "gpt-5",
effort: "high",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
},
@@ -225,6 +234,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -259,4 +269,83 @@ describe("decider project scripts", () => {
},
});
});
it("emits thread.interaction-mode-set from thread.interaction-mode.set", async () => {
const now = new Date().toISOString();
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create"),
aggregateKind: "project",
aggregateId: asProjectId("project-1"),
type: "project.created",
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-project-create"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-project-create"),
metadata: {},
payload: {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
);
const readModel = await Effect.runPromise(
projectEvent(withProject, {
sequence: 2,
eventId: asEventId("evt-thread-create"),
aggregateKind: "thread",
aggregateId: ThreadId.makeUnsafe("thread-1"),
type: "thread.created",
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-thread-create"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
metadata: {},
payload: {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
const result = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.interaction-mode.set",
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set"),
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
createdAt: now,
},
readModel,
}),
);
const singleResult = Array.isArray(result) ? null : result;
if (singleResult === null) {
throw new Error("Expected a single interaction-mode-set event.");
}
expect(singleResult).toMatchObject({
type: "thread.interaction-mode-set",
payload: {
threadId: ThreadId.makeUnsafe("thread-1"),
interactionMode: "plan",
},
});
});
});
+53
View File
@@ -158,6 +158,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
title: command.title,
model: command.model,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
branch: command.branch,
worktreePath: command.worktreePath,
createdAt: command.createdAt,
@@ -237,6 +238,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.interaction-mode.set": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
const occurredAt = nowIso();
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
}),
type: "thread.interaction-mode-set",
payload: {
threadId: command.threadId,
interactionMode: command.interactionMode,
updatedAt: occurredAt,
},
};
}
case "thread.turn.start": {
yield* requireThread({
readModel,
@@ -282,6 +306,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
runtimeMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
command.runtimeMode,
interactionMode:
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
command.interactionMode,
createdAt: command.createdAt,
},
};
@@ -336,6 +363,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.user-input.respond": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
metadata: {
requestId: command.requestId,
},
}),
type: "thread.user-input-response-requested",
payload: {
threadId: command.threadId,
requestId: command.requestId,
answers: command.answers,
createdAt: command.createdAt,
},
};
}
case "thread.checkpoint.revert": {
yield* requireThread({
readModel,
@@ -16,6 +16,7 @@ import {
ThreadActivityAppendedPayload,
ThreadCreatedPayload,
ThreadDeletedPayload,
ThreadInteractionModeSetPayload,
ThreadMetaUpdatedPayload,
ThreadRuntimeModeSetPayload,
ThreadRevertedPayload,
@@ -243,6 +244,7 @@ export function projectEvent(
title: payload.title,
model: payload.model,
runtimeMode: payload.runtimeMode,
interactionMode: payload.interactionMode,
branch: payload.branch,
worktreePath: payload.worktreePath,
latestTurn: null,
@@ -307,6 +309,22 @@ export function projectEvent(
})),
);
case "thread.interaction-mode-set":
return decodeForEvent(
ThreadInteractionModeSetPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
interactionMode: payload.interactionMode,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.message-sent":
return Effect.gen(function* () {
const payload = yield* decodeForEvent(
@@ -25,6 +25,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
title,
model,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
@@ -38,6 +39,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.title},
${row.model},
${row.runtimeMode},
${row.interactionMode},
${row.branch},
${row.worktreePath},
${row.latestTurnId},
@@ -51,6 +53,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
title = excluded.title,
model = excluded.model,
runtime_mode = excluded.runtime_mode,
interaction_mode = excluded.interaction_mode,
branch = excluded.branch,
worktree_path = excluded.worktree_path,
latest_turn_id = excluded.latest_turn_id,
@@ -71,6 +74,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
title,
model,
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
@@ -93,6 +97,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
title,
model,
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
@@ -23,6 +23,7 @@ import Migration0008 from "./Migrations/008_ProjectionThreadActivitySequence.ts"
import Migration0009 from "./Migrations/009_ProviderSessionRuntimeMode.ts";
import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
import { Effect } from "effect";
/**
@@ -47,6 +48,7 @@ const loader = Migrator.fromRecord({
"9_ProviderSessionRuntimeMode": Migration0009,
"10_ProjectionThreadsRuntimeMode": Migration0010,
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
"12_ProjectionThreadsInteractionMode": Migration0012,
});
/**
@@ -0,0 +1,11 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN interaction_mode TEXT NOT NULL DEFAULT 'default'
`;
});
@@ -6,7 +6,14 @@
*
* @module ProjectionThreadRepository
*/
import { IsoDateTime, ProjectId, RuntimeMode, ThreadId, TurnId } from "@t3tools/contracts";
import {
IsoDateTime,
ProjectId,
ProviderInteractionMode,
RuntimeMode,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
@@ -18,6 +25,7 @@ export const ProjectionThread = Schema.Struct({
title: Schema.String,
model: Schema.String,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
branch: Schema.NullOr(Schema.String),
worktreePath: Schema.NullOr(Schema.String),
latestTurnId: Schema.NullOr(TurnId),
@@ -1781,6 +1781,19 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
yield* Deferred.succeed(pending.decision, decision);
});
const respondToUserInput: ClaudeCodeAdapterShape["respondToUserInput"] = (
threadId,
requestId,
_answers,
) =>
Effect.fail(
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "item/tool/requestUserInput",
detail: `Claude Code does not yet support structured user-input responses for thread '${threadId}' and request '${requestId}'.`,
}),
);
const stopSession: ClaudeCodeAdapterShape["stopSession"] = (threadId) =>
Effect.gen(function* () {
const context = yield* requireSession(threadId);
@@ -1830,6 +1843,7 @@ function makeClaudeCodeAdapter(options?: ClaudeCodeAdapterLiveOptions) {
readThread,
rollbackThread,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -7,6 +7,7 @@ import {
type ProviderSession,
type ProviderSessionStartInput,
type ProviderTurnStartResult,
type ProviderUserInputAnswers,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -76,6 +77,14 @@ class FakeCodexManager extends CodexAppServerManager {
): Promise<void> => undefined,
);
public respondToUserInputImpl = vi.fn(
async (
_threadId: ThreadId,
_requestId: ApprovalRequestId,
_answers: ProviderUserInputAnswers,
): Promise<void> => undefined,
);
public stopAllImpl = vi.fn(() => undefined);
override startSession(input: ProviderSessionStartInput): Promise<ProviderSession> {
@@ -106,6 +115,14 @@ class FakeCodexManager extends CodexAppServerManager {
return this.respondToRequestImpl(threadId, requestId, decision);
}
override respondToUserInput(
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
): Promise<void> {
return this.respondToUserInputImpl(threadId, requestId, answers);
}
override stopSession(_threadId: ThreadId): void {}
override listSessions(): ProviderSession[] {
@@ -253,6 +270,46 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps completed plan items to canonical item.completed plan events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
const event: ProviderEvent = {
id: asEventId("evt-plan-complete"),
kind: "notification",
provider: "codex",
createdAt: new Date().toISOString(),
method: "item/completed",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
itemId: asItemId("plan_1"),
payload: {
item: {
type: "Plan",
id: "plan_1",
text: "## Final plan\n\n- one\n- two",
},
},
};
lifecycleManager.emit("event", event);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "item.completed");
if (firstEvent.value.type !== "item.completed") {
return;
}
assert.equal(firstEvent.value.itemId, "plan_1");
assert.equal(firstEvent.value.payload.itemType, "plan");
assert.equal(firstEvent.value.payload.detail, "## Final plan\n\n- one\n- two");
}),
);
it.effect("maps session/closed lifecycle events to canonical session.exited runtime events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
@@ -361,6 +418,182 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}
}),
);
it.effect("maps requestUserInput requests and answered notifications to canonical user-input events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 2)).pipe(
Effect.forkChild,
);
lifecycleManager.emit("event", {
id: asEventId("evt-user-input-requested"),
kind: "request",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput",
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-user-input-resolved"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "item/tool/requestUserInput/answered",
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
payload: {
answers: {
sandbox_mode: {
answers: ["workspace-write"],
},
},
},
} satisfies ProviderEvent);
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.equal(events[0]?.type, "user-input.requested");
if (events[0]?.type === "user-input.requested") {
assert.equal(events[0].requestId, "req-user-input-1");
assert.equal(events[0].payload.questions[0]?.id, "sandbox_mode");
}
assert.equal(events[1]?.type, "user-input.resolved");
if (events[1]?.type === "user-input.resolved") {
assert.equal(events[1].requestId, "req-user-input-1");
assert.deepEqual(events[1].payload.answers, {
sandbox_mode: "workspace-write",
});
}
}),
);
it.effect("maps Codex task and reasoning event chunks into canonical runtime events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const eventsFiber = yield* Stream.runCollect(Stream.take(adapter.streamEvents, 4)).pipe(
Effect.forkChild,
);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-started"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
id: "turn-structured-1",
msg: {
type: "task_started",
turn_id: "turn-structured-1",
collaboration_mode_kind: "plan",
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-agent-reasoning"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/agent_reasoning",
payload: {
id: "turn-structured-1",
msg: {
type: "agent_reasoning",
text: "Need to compare both transport layers before finalizing the plan.",
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-reasoning-delta"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/reasoning_content_delta",
payload: {
id: "turn-structured-1",
msg: {
type: "reasoning_content_delta",
turn_id: "turn-structured-1",
item_id: "rs_reasoning_1",
delta: "**Compare** transport boundaries",
summary_index: 0,
},
},
} satisfies ProviderEvent);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-task-complete"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_complete",
payload: {
id: "turn-structured-1",
msg: {
type: "task_complete",
turn_id: "turn-structured-1",
last_agent_message: "<proposed_plan>\n# Ship it\n</proposed_plan>",
},
},
} satisfies ProviderEvent);
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.equal(events[0]?.type, "task.started");
if (events[0]?.type === "task.started") {
assert.equal(events[0].turnId, "turn-structured-1");
assert.equal(events[0].payload.taskId, "turn-structured-1");
assert.equal(events[0].payload.taskType, "plan");
}
assert.equal(events[1]?.type, "task.progress");
if (events[1]?.type === "task.progress") {
assert.equal(events[1].payload.taskId, "turn-structured-1");
assert.equal(
events[1].payload.description,
"Need to compare both transport layers before finalizing the plan.",
);
}
assert.equal(events[2]?.type, "content.delta");
if (events[2]?.type === "content.delta") {
assert.equal(events[2].turnId, "turn-structured-1");
assert.equal(events[2].itemId, "rs_reasoning_1");
assert.equal(events[2].payload.streamKind, "reasoning_summary_text");
assert.equal(events[2].payload.summaryIndex, 0);
}
assert.equal(events[3]?.type, "task.completed");
if (events[3]?.type === "task.completed") {
assert.equal(events[3].turnId, "turn-structured-1");
assert.equal(events[3].payload.taskId, "turn-structured-1");
assert.equal(events[3].payload.summary, "<proposed_plan>\n# Ship it\n</proposed_plan>");
}
}),
);
});
afterAll(() => {
@@ -11,11 +11,14 @@ import {
type CanonicalRequestType,
type ProviderEvent,
type ProviderRuntimeEvent,
type ProviderUserInputAnswers,
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
ProviderApprovalDecision,
ProviderItemId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { Effect, FileSystem, Layer, Queue, Schema, ServiceMap, Stream } from "effect";
@@ -95,6 +98,10 @@ function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function asArray(value: unknown): unknown[] | undefined {
return Array.isArray(value) ? value : undefined;
}
function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
@@ -249,6 +256,88 @@ function toRequestTypeFromResolvedPayload(
return "unknown";
}
function toCanonicalUserInputAnswers(
answers: ProviderUserInputAnswers | undefined,
): ProviderUserInputAnswers {
if (!answers) {
return {};
}
return Object.fromEntries(
Object.entries(answers).flatMap(([questionId, value]) => {
if (typeof value === "string") {
return [[questionId, value] as const];
}
if (Array.isArray(value)) {
const normalized = value.filter((entry): entry is string => typeof entry === "string");
if (normalized.length === 0) {
return [];
}
return [[questionId, normalized.length === 1 ? normalized[0] : normalized] as const];
}
const answerObject = asObject(value);
const answerList = asArray(answerObject?.answers)?.filter(
(entry): entry is string => typeof entry === "string",
);
if (!answerList || answerList.length === 0) {
return [];
}
return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const];
}),
);
}
function toUserInputQuestions(payload: Record<string, unknown> | undefined) {
const questions = asArray(payload?.questions);
if (!questions) {
return undefined;
}
const parsedQuestions = questions
.map((entry) => {
const question = asObject(entry);
if (!question) return undefined;
const options = asArray(question.options)
?.map((option) => {
const optionRecord = asObject(option);
if (!optionRecord) return undefined;
const label = asString(optionRecord.label)?.trim();
const description = asString(optionRecord.description)?.trim();
if (!label || !description) {
return undefined;
}
return { label, description };
})
.filter((option): option is { label: string; description: string } => option !== undefined);
const id = asString(question.id)?.trim();
const header = asString(question.header)?.trim();
const prompt = asString(question.question)?.trim();
if (!id || !header || !prompt || !options || options.length === 0) {
return undefined;
}
return {
id,
header,
question: prompt,
options,
};
})
.filter(
(
question,
): question is {
id: string;
header: string;
question: string;
options: Array<{ label: string; description: string }>;
} => question !== undefined,
);
return parsedQuestions.length > 0 ? parsedQuestions : undefined;
}
function toThreadState(
value: unknown,
): "active" | "idle" | "archived" | "closed" | "compacted" | "error" {
@@ -304,6 +393,46 @@ function asRuntimeRequestId(requestId: string): RuntimeRequestId {
return RuntimeRequestId.makeUnsafe(requestId);
}
function asRuntimeTaskId(taskId: string): RuntimeTaskId {
return RuntimeTaskId.makeUnsafe(taskId);
}
function codexEventMessage(payload: Record<string, unknown> | undefined): Record<string, unknown> | undefined {
return asObject(payload?.msg);
}
function codexEventBase(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): Omit<ProviderRuntimeEvent, "type" | "payload"> {
const payload = asObject(event.payload);
const msg = codexEventMessage(payload);
const turnId = asString(msg?.turn_id) ?? asString(msg?.turnId);
const itemId = asString(msg?.item_id) ?? asString(msg?.itemId);
const requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
const base = runtimeEventBase(event, canonicalThreadId);
const providerRefs = base.providerRefs
? {
...base.providerRefs,
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
}
: {
...(turnId ? { providerTurnId: turnId } : {}),
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
...(requestId ? { providerRequestId: requestId } : {}),
};
return {
...base,
...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
};
}
function eventRawSource(event: ProviderEvent): NonNullable<ProviderRuntimeEvent["raw"]>["source"] {
return event.kind === "request" ? "codex.app-server.request" : "codex.app-server.notification";
}
@@ -404,6 +533,22 @@ function mapToRuntimeEvents(
}
if (event.kind === "request") {
if (event.method === "item/tool/requestUserInput") {
const questions = toUserInputQuestions(payload);
if (!questions) {
return [];
}
return [
{
...runtimeEventBase(event, canonicalThreadId),
type: "user-input.requested",
payload: {
questions,
},
},
];
}
const detail =
asString(payload?.command) ?? asString(payload?.reason) ?? asString(payload?.prompt);
return [
@@ -737,6 +882,102 @@ function mapToRuntimeEvents(
];
}
if (event.method === "item/tool/requestUserInput/answered") {
return [
{
...runtimeEventBase(event, canonicalThreadId),
type: "user-input.resolved",
payload: {
answers: toCanonicalUserInputAnswers(
asObject(event.payload)?.answers as ProviderUserInputAnswers | undefined,
),
},
},
];
}
if (event.method === "codex/event/task_started") {
const msg = codexEventMessage(payload);
const taskId = asString(payload?.id) ?? asString(msg?.turn_id);
if (!taskId) {
return [];
}
return [
{
...codexEventBase(event, canonicalThreadId),
type: "task.started",
payload: {
taskId: asRuntimeTaskId(taskId),
...(asString(msg?.collaboration_mode_kind)
? { taskType: asString(msg?.collaboration_mode_kind) }
: {}),
},
},
];
}
if (event.method === "codex/event/task_complete") {
const msg = codexEventMessage(payload);
const taskId = asString(payload?.id) ?? asString(msg?.turn_id);
if (!taskId) {
return [];
}
return [
{
...codexEventBase(event, canonicalThreadId),
type: "task.completed",
payload: {
taskId: asRuntimeTaskId(taskId),
status: "completed",
...(asString(msg?.last_agent_message)
? { summary: asString(msg?.last_agent_message) }
: {}),
},
},
];
}
if (event.method === "codex/event/agent_reasoning") {
const msg = codexEventMessage(payload);
const taskId = asString(payload?.id);
const description = asString(msg?.text);
if (!taskId || !description) {
return [];
}
return [
{
...codexEventBase(event, canonicalThreadId),
type: "task.progress",
payload: {
taskId: asRuntimeTaskId(taskId),
description,
},
},
];
}
if (event.method === "codex/event/reasoning_content_delta") {
const msg = codexEventMessage(payload);
const delta = asString(msg?.delta);
if (!delta) {
return [];
}
return [
{
...codexEventBase(event, canonicalThreadId),
type: "content.delta",
payload: {
streamKind:
asNumber(msg?.summary_index) !== undefined ? "reasoning_summary_text" : "reasoning_text",
delta,
...(asNumber(msg?.summary_index) !== undefined
? { summaryIndex: asNumber(msg?.summary_index) }
: {}),
},
},
];
}
if (event.method === "model/rerouted") {
return [
{
@@ -1034,6 +1275,9 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
...(input.input !== undefined ? { input: input.input } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.effort !== undefined ? { effort: input.effort } : {}),
...(input.interactionMode !== undefined
? { interactionMode: input.interactionMode }
: {}),
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
};
return manager.sendTurn(managerInput);
@@ -1096,6 +1340,16 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
catch: (cause) => toRequestError(threadId, "item/requestApproval/decision", cause),
});
const respondToUserInput: CodexAdapterShape["respondToUserInput"] = (
threadId,
requestId,
answers,
) =>
Effect.tryPromise({
try: () => manager.respondToUserInput(threadId, requestId, answers),
catch: (cause) => toRequestError(threadId, "item/tool/requestUserInput", cause),
});
const stopSession: CodexAdapterShape["stopSession"] = (threadId) =>
Effect.sync(() => {
manager.stopSession(threadId);
@@ -1163,6 +1417,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
readThread,
rollbackThread,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -1490,6 +1490,19 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
});
});
const respondToUserInput: CursorAdapterShape["respondToUserInput"] = (
threadId,
requestId,
_answers,
) =>
Effect.fail(
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "cursor/ask_question",
detail: `Cursor does not yet support structured user-input responses for thread '${threadId}' and request '${requestId}'.`,
}),
);
const stopSession: CursorAdapterShape["stopSession"] = (threadId) =>
Effect.gen(function* () {
const context = yield* requireSession(threadId);
@@ -1539,6 +1552,7 @@ function makeCursorAdapter(options?: CursorAdapterLiveOptions) {
readThread,
rollbackThread,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -19,6 +19,7 @@ const fakeCodexAdapter: CodexAdapterShape = {
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
@@ -35,6 +36,7 @@ const fakeClaudeAdapter: ClaudeCodeAdapterShape = {
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
@@ -51,6 +53,7 @@ const fakeCursorAdapter: CursorAdapterShape = {
sendTurn: vi.fn(),
interruptTurn: vi.fn(),
respondToRequest: vi.fn(),
respondToUserInput: vi.fn(),
stopSession: vi.fn(),
listSessions: vi.fn(),
hasSession: vi.fn(),
@@ -116,6 +116,14 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
): Effect.Effect<void, ProviderAdapterError> => Effect.void,
);
const respondToUserInput = vi.fn(
(
_threadId: ThreadId,
_requestId: string,
_answers: Record<string, unknown>,
): Effect.Effect<void, ProviderAdapterError> => Effect.void,
);
const stopSession = vi.fn(
(threadId: ThreadId): Effect.Effect<void, ProviderAdapterError> =>
Effect.sync(() => {
@@ -172,6 +180,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -192,6 +201,7 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
@@ -395,12 +405,12 @@ it.effect(
provider?: string;
cwd?: string;
resumeCursor?: unknown;
resumeThreadId?: string;
threadId?: string;
};
assert.equal(startPayload.provider, "codex");
assert.equal(startPayload.cwd, "/tmp/project");
assert.deepEqual(startPayload.resumeCursor, startedSession.resumeCursor);
assert.equal(startPayload.resumeThreadId, "thread-1");
assert.equal(startPayload.threadId, startedSession.threadId);
}
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
const rollbackCall = secondCodex.rollbackThread.mock.calls[0];
@@ -446,6 +456,23 @@ routing.layer("ProviderServiceLive routing", (it) => {
[session.threadId, asRequestId("req-1"), "accept"],
]);
yield* provider.respondToUserInput({
threadId: session.threadId,
requestId: asRequestId("req-user-input-1"),
answers: {
sandbox_mode: "workspace-write",
},
});
assert.deepEqual(routing.codex.respondToUserInput.mock.calls, [
[
session.threadId,
asRequestId("req-user-input-1"),
{
sandbox_mode: "workspace-write",
},
],
]);
yield* provider.rollbackConversation({
threadId: session.threadId,
numTurns: 0,
@@ -519,12 +546,12 @@ routing.layer("ProviderServiceLive routing", (it) => {
provider?: string;
cwd?: string;
resumeCursor?: unknown;
resumeThreadId?: string;
threadId?: string;
};
assert.equal(startPayload.provider, "codex");
assert.equal(startPayload.cwd, "/tmp/project");
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.resumeThreadId, "thread-2");
assert.equal(startPayload.threadId, initial.threadId);
}
assert.equal(routing.codex.rollbackThread.mock.calls.length, 1);
const rollbackCall = routing.codex.rollbackThread.mock.calls[0];
@@ -561,12 +588,12 @@ routing.layer("ProviderServiceLive routing", (it) => {
provider?: string;
cwd?: string;
resumeCursor?: unknown;
resumeThreadId?: string;
threadId?: string;
};
assert.equal(startPayload.provider, "codex");
assert.equal(startPayload.cwd, "/tmp/project-send-turn");
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.resumeThreadId, "thread-4");
assert.equal(startPayload.threadId, initial.threadId);
}
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
}),
@@ -629,7 +656,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
};
assert.equal(runtimePayload.cwd, process.cwd());
assert.equal(runtimePayload.model, null);
assert.equal(runtimePayload.activeTurnId, "turn-1");
assert.equal(runtimePayload.activeTurnId, `turn-${String(session.threadId)}`);
assert.equal(runtimePayload.lastError, null);
assert.equal(runtimePayload.lastRuntimeEvent, "provider.sendTurn");
}
@@ -822,7 +849,9 @@ validation.layer("ProviderServiceLive validation", (it) => {
const failure = yield* Effect.result(
provider.startSession(asThreadId("thread-validation"), {
threadId: asThreadId("thread-validation"),
provider: "invalid-provider",
runtimeMode: "full-access",
} as never),
);
@@ -14,6 +14,7 @@ import {
ThreadId,
ProviderInterruptTurnInput,
ProviderRespondToRequestInput,
ProviderRespondToUserInputInput,
ProviderSendTurnInput,
ProviderSessionStartInput,
ProviderStopSessionInput,
@@ -333,6 +334,21 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
});
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
operation: "ProviderService.respondToUserInput",
schema: ProviderRespondToUserInputInput,
payload: rawInput,
});
const routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.respondToUserInput",
allowRecovery: true,
});
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
});
const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
Effect.gen(function* () {
const input = yield* decodeInputOrValidationError({
@@ -442,6 +458,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
getCapabilities,
@@ -11,6 +11,7 @@ import type {
ApprovalRequestId,
ProviderApprovalDecision,
ProviderKind,
ProviderUserInputAnswers,
ProviderRuntimeEvent,
ProviderSendTurnInput,
ProviderSession,
@@ -79,6 +80,15 @@ export interface ProviderAdapterShape<TError> {
decision: ProviderApprovalDecision,
) => Effect.Effect<void, TError>;
/**
* Respond to a structured user-input request.
*/
readonly respondToUserInput: (
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
) => Effect.Effect<void, TError>;
/**
* Stop one provider session.
*/
@@ -15,6 +15,7 @@ import type {
ProviderInterruptTurnInput,
ProviderKind,
ProviderRespondToRequestInput,
ProviderRespondToUserInputInput,
ProviderRuntimeEvent,
ProviderSendTurnInput,
ProviderSession,
@@ -62,6 +63,13 @@ export interface ProviderServiceShape {
input: ProviderRespondToRequestInput,
) => Effect.Effect<void, ProviderServiceError>;
/**
* Respond to a provider structured user-input request.
*/
readonly respondToUserInput: (
input: ProviderRespondToUserInputInput,
) => Effect.Effect<void, ProviderServiceError>;
/**
* Stop a provider session.
*/
+54
View File
@@ -1126,6 +1126,8 @@ describe("WebSocket Server", () => {
projectId: "project-diff",
title: "Diff Thread",
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt,
@@ -1164,6 +1166,7 @@ describe("WebSocket Server", () => {
}),
interruptTurn: () => unsupported(),
respondToRequest: () => unsupported(),
respondToUserInput: () => unsupported(),
stopSession: () => unsupported(),
listSessions: () => Effect.succeed([]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
@@ -1202,6 +1205,8 @@ describe("WebSocket Server", () => {
projectId: "project-1",
title: "Thread 1",
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt,
@@ -1220,6 +1225,7 @@ describe("WebSocket Server", () => {
},
assistantDeliveryMode: "streaming",
runtimeMode: "approval-required",
interactionMode: "default",
createdAt,
});
expect(startTurnResponse.error).toBeUndefined();
@@ -1519,6 +1525,54 @@ describe("WebSocket Server", () => {
});
});
it("supports projects.writeFile within the workspace root", async () => {
const workspace = makeTempDir("t3code-ws-write-file-");
server = await createTestServer({ cwd: "/test" });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
cwd: workspace,
relativePath: "plans/effect-rpc.md",
contents: "# Plan\n\n- step 1\n",
});
expect(response.error).toBeUndefined();
expect(response.result).toEqual({
relativePath: "plans/effect-rpc.md",
});
expect(fs.readFileSync(path.join(workspace, "plans", "effect-rpc.md"), "utf8")).toBe(
"# Plan\n\n- step 1\n",
);
});
it("rejects projects.writeFile paths outside the workspace root", async () => {
const workspace = makeTempDir("t3code-ws-write-file-reject-");
server = await createTestServer({ cwd: "/test" });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const ws = await connectWs(port);
connections.push(ws);
await waitForMessage(ws);
const response = await sendRequest(ws, WS_METHODS.projectsWriteFile, {
cwd: workspace,
relativePath: "../escape.md",
contents: "# no\n",
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("Workspace file path must stay within the project root.");
expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false);
});
it("routes git core methods over websocket", async () => {
const listBranches = vi.fn(() =>
Effect.succeed({
+70
View File
@@ -12,6 +12,7 @@ import type { Duplex } from "node:stream";
import Mime from "@effect/platform-node/Mime";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
type ClientOrchestrationCommand,
type OrchestrationCommand,
ORCHESTRATION_WS_CHANNELS,
@@ -146,6 +147,48 @@ function websocketRawToString(raw: unknown): string | null {
return null;
}
function toPosixRelativePath(input: string): string {
return input.replaceAll("\\", "/");
}
function resolveWorkspaceWritePath(params: {
workspaceRoot: string;
relativePath: string;
path: Path.Path;
}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> {
const normalizedInputPath = params.relativePath.trim();
if (params.path.isAbsolute(normalizedInputPath)) {
return Effect.fail(
new RouteRequestError({
message: "Workspace file path must be relative to the project root.",
}),
);
}
const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath);
const relativeToRoot = toPosixRelativePath(
params.path.relative(params.workspaceRoot, absolutePath),
);
if (
relativeToRoot.length === 0 ||
relativeToRoot === "." ||
relativeToRoot.startsWith("../") ||
relativeToRoot === ".." ||
params.path.isAbsolute(relativeToRoot)
) {
return Effect.fail(
new RouteRequestError({
message: "Workspace file path must stay within the project root.",
}),
);
}
return Effect.succeed({
absolutePath,
relativePath: relativeToRoot,
});
}
function stripRequestTag<T extends { _tag: string }>(body: T) {
return Struct.omit(body, ["_tag"]);
}
@@ -595,6 +638,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
projectId: bootstrapProjectId,
title: "New thread",
model: bootstrapProjectDefaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -684,6 +728,32 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
}
case WS_METHODS.projectsWriteFile: {
const body = stripRequestTag(request.body);
const target = yield* resolveWorkspaceWritePath({
workspaceRoot: body.cwd,
relativePath: body.relativePath,
path,
});
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new RouteRequestError({
message: `Failed to prepare workspace path: ${String(cause)}`,
}),
),
);
yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(
Effect.mapError(
(cause) =>
new RouteRequestError({
message: `Failed to write workspace file: ${String(cause)}`,
}),
),
);
return { relativePath: target.relativePath };
}
case WS_METHODS.shellOpenInEditor: {
const body = stripRequestTag(request.body);
return yield* openInEditor(body);
File diff suppressed because it is too large. Load diff
+27
View File
@@ -4,6 +4,7 @@ import {
detectComposerTrigger,
expandCollapsedComposerCursor,
isCollapsedCursorAdjacentToMention,
parseStandaloneComposerSlashCommand,
replaceTextRange,
} from "./composer-logic";
@@ -43,6 +44,18 @@ describe("detectComposerTrigger", () => {
rangeEnd: text.length,
});
});
it("detects non-model slash commands while typing", () => {
const text = "/pl";
const trigger = detectComposerTrigger(text, text.length);
expect(trigger).toEqual({
kind: "slash-command",
query: "pl",
rangeStart: 0,
rangeEnd: text.length,
});
});
});
describe("replaceTextRange", () => {
@@ -111,3 +124,17 @@ describe("isCollapsedCursorAdjacentToMention", () => {
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
});
});
describe("parseStandaloneComposerSlashCommand", () => {
it("parses standalone /plan command", () => {
expect(parseStandaloneComposerSlashCommand(" /plan ")).toBe("plan");
});
it("parses standalone /default command", () => {
expect(parseStandaloneComposerSlashCommand("/default")).toBe("default");
});
it("ignores slash commands with extra message text", () => {
expect(parseStandaloneComposerSlashCommand("/plan explain this")).toBeNull();
});
});
+15 -1
View File
@@ -1,6 +1,7 @@
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
export type ComposerTriggerKind = "path" | "slash-command" | "slash-model";
export type ComposerSlashCommand = "model" | "plan" | "default";
export interface ComposerTrigger {
kind: ComposerTriggerKind;
@@ -9,6 +10,8 @@ export interface ComposerTrigger {
rangeEnd: number;
}
const SLASH_COMMANDS: readonly ComposerSlashCommand[] = ["model", "plan", "default"];
function clampCursor(text: string, cursor: number): number {
if (!Number.isFinite(cursor)) return text.length;
return Math.max(0, Math.min(text.length, Math.floor(cursor)));
@@ -121,7 +124,7 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos
rangeEnd: cursor,
};
}
if ("model".startsWith(commandQuery.toLowerCase())) {
if (SLASH_COMMANDS.some((command) => command.startsWith(commandQuery.toLowerCase()))) {
return {
kind: "slash-command",
query: commandQuery,
@@ -157,6 +160,17 @@ export function detectComposerTrigger(text: string, cursorInput: number): Compos
};
}
export function parseStandaloneComposerSlashCommand(text: string): Exclude<
ComposerSlashCommand,
"model"
> | null {
const match = /^\/(plan|default)\s*$/i.exec(text.trim());
if (!match) {
return null;
}
return match[1]?.toLowerCase() === "plan" ? "plan" : "default";
}
export function replaceTextRange(
text: string,
rangeStart: number,
+23 -1
View File
@@ -6,9 +6,14 @@ import {
normalizeModelSlug,
type CodexReasoningEffort,
type ProviderKind,
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
type ChatImageAttachment,
} from "./types";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
@@ -40,6 +45,7 @@ interface PersistedDraftThreadState {
projectId: ProjectId;
createdAt: string;
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
branch: string | null;
worktreePath: string | null;
envMode: DraftThreadEnvMode;
@@ -65,6 +71,7 @@ export interface DraftThreadState {
projectId: ProjectId;
createdAt: string;
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
branch: string | null;
worktreePath: string | null;
envMode: DraftThreadEnvMode;
@@ -89,6 +96,7 @@ interface ComposerDraftStoreState {
createdAt?: string;
envMode?: DraftThreadEnvMode;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
},
) => void;
setDraftThreadContext: (
@@ -100,6 +108,7 @@ interface ComposerDraftStoreState {
createdAt?: string;
envMode?: DraftThreadEnvMode;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
},
) => void;
clearProjectDraftThreadId: (projectId: ProjectId) => void;
@@ -270,6 +279,11 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
candidateDraftThread.runtimeMode === "full-access"
? candidateDraftThread.runtimeMode
: DEFAULT_RUNTIME_MODE,
interactionMode:
candidateDraftThread.interactionMode === "plan" ||
candidateDraftThread.interactionMode === "default"
? candidateDraftThread.interactionMode
: DEFAULT_INTERACTION_MODE,
branch: typeof branch === "string" ? branch : null,
worktreePath: normalizedWorktreePath,
envMode: normalizeDraftThreadEnvMode(candidateDraftThread.envMode, normalizedWorktreePath),
@@ -297,6 +311,7 @@ function normalizePersistedComposerDraftState(value: unknown): PersistedComposer
projectId: projectId as ProjectId,
createdAt: new Date().toISOString(),
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
branch: null,
worktreePath: null,
envMode: "local",
@@ -500,6 +515,10 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
projectId,
createdAt: options?.createdAt ?? existingThread?.createdAt ?? new Date().toISOString(),
runtimeMode: options?.runtimeMode ?? existingThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
interactionMode:
options?.interactionMode ??
existingThread?.interactionMode ??
DEFAULT_INTERACTION_MODE,
branch:
options?.branch === undefined
? (existingThread?.branch ?? null)
@@ -515,6 +534,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
existingThread.projectId === nextDraftThread.projectId &&
existingThread.createdAt === nextDraftThread.createdAt &&
existingThread.runtimeMode === nextDraftThread.runtimeMode &&
existingThread.interactionMode === nextDraftThread.interactionMode &&
existingThread.branch === nextDraftThread.branch &&
existingThread.worktreePath === nextDraftThread.worktreePath &&
existingThread.envMode === nextDraftThread.envMode;
@@ -570,6 +590,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
? existing.createdAt
: options.createdAt || existing.createdAt,
runtimeMode: options.runtimeMode ?? existing.runtimeMode,
interactionMode: options.interactionMode ?? existing.interactionMode,
branch: options.branch === undefined ? existing.branch : (options.branch ?? null),
worktreePath: nextWorktreePath,
envMode:
@@ -580,6 +601,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
nextDraftThread.projectId === existing.projectId &&
nextDraftThread.createdAt === existing.createdAt &&
nextDraftThread.runtimeMode === existing.runtimeMode &&
nextDraftThread.interactionMode === existing.interactionMode &&
nextDraftThread.branch === existing.branch &&
nextDraftThread.worktreePath === existing.worktreePath &&
nextDraftThread.envMode === existing.envMode;
+192
View File
@@ -0,0 +1,192 @@
import { describe, expect, it } from "vitest";
import {
buildPendingUserInputAnswers,
countAnsweredPendingUserInputQuestions,
derivePendingUserInputProgress,
findFirstUnansweredPendingUserInputQuestionIndex,
resolvePendingUserInputAnswer,
setPendingUserInputCustomAnswer,
} from "./pendingUserInput";
describe("resolvePendingUserInputAnswer", () => {
it("prefers a custom answer over a selected option", () => {
expect(
resolvePendingUserInputAnswer({
selectedOptionLabel: "Keep current envelope",
customAnswer: "Keep the existing envelope for one release",
}),
).toBe("Keep the existing envelope for one release");
});
it("falls back to the selected option", () => {
expect(
resolvePendingUserInputAnswer({
selectedOptionLabel: "Scaffold only",
}),
).toBe("Scaffold only");
});
it("clears the preset selection when a custom answer is entered", () => {
expect(
setPendingUserInputCustomAnswer(
{
selectedOptionLabel: "Preserve existing tags",
},
"doesn't matter",
),
).toEqual({
selectedOptionLabel: undefined,
customAnswer: "doesn't matter",
});
});
});
describe("buildPendingUserInputAnswers", () => {
it("returns a canonical answer map for complete prompts", () => {
expect(
buildPendingUserInputAnswers(
[
{
id: "scope",
header: "Scope",
question: "What should the plan target first?",
options: [
{
label: "Orchestration-first",
description: "Focus on orchestration first",
},
],
},
{
id: "compat",
header: "Compat",
question: "How strict should compatibility be?",
options: [
{
label: "Keep current envelope",
description: "Preserve current wire format",
},
],
},
],
{
scope: {
selectedOptionLabel: "Orchestration-first",
},
compat: {
customAnswer: "Keep the current envelope for one release window",
},
},
),
).toEqual({
scope: "Orchestration-first",
compat: "Keep the current envelope for one release window",
});
});
it("returns null when any question is unanswered", () => {
expect(
buildPendingUserInputAnswers(
[
{
id: "scope",
header: "Scope",
question: "What should the plan target first?",
options: [
{
label: "Orchestration-first",
description: "Focus on orchestration first",
},
],
},
],
{},
),
).toBeNull();
});
});
describe("pending user input question progress", () => {
const questions = [
{
id: "scope",
header: "Scope",
question: "What should the plan target first?",
options: [
{
label: "Orchestration-first",
description: "Focus on orchestration first",
},
],
},
{
id: "compat",
header: "Compat",
question: "How strict should compatibility be?",
options: [
{
label: "Keep current envelope",
description: "Preserve current wire format",
},
],
},
] as const;
it("counts only answered questions", () => {
expect(
countAnsweredPendingUserInputQuestions(questions, {
scope: {
selectedOptionLabel: "Orchestration-first",
},
}),
).toBe(1);
});
it("finds the first unanswered question", () => {
expect(
findFirstUnansweredPendingUserInputQuestionIndex(questions, {
scope: {
selectedOptionLabel: "Orchestration-first",
},
}),
).toBe(1);
});
it("returns the last question index when all answers are complete", () => {
expect(
findFirstUnansweredPendingUserInputQuestionIndex(questions, {
scope: {
selectedOptionLabel: "Orchestration-first",
},
compat: {
customAnswer: "Keep it for one release window",
},
}),
).toBe(1);
});
it("derives the active question and advancement state", () => {
expect(
derivePendingUserInputProgress(
questions,
{
scope: {
selectedOptionLabel: "Orchestration-first",
},
},
0,
),
).toMatchObject({
questionIndex: 0,
activeQuestion: questions[0],
selectedOptionLabel: "Orchestration-first",
customAnswer: "",
resolvedAnswer: "Orchestration-first",
answeredQuestionCount: 1,
isLastQuestion: false,
isComplete: false,
canAdvance: true,
});
});
});
+122
View File
@@ -0,0 +1,122 @@
import type { UserInputQuestion } from "@t3tools/contracts";
export interface PendingUserInputDraftAnswer {
selectedOptionLabel?: string;
customAnswer?: string;
}
export interface PendingUserInputProgress {
questionIndex: number;
activeQuestion: UserInputQuestion | null;
activeDraft: PendingUserInputDraftAnswer | undefined;
selectedOptionLabel: string | undefined;
customAnswer: string;
resolvedAnswer: string | null;
usingCustomAnswer: boolean;
answeredQuestionCount: number;
isLastQuestion: boolean;
isComplete: boolean;
canAdvance: boolean;
}
function normalizeDraftAnswer(value: string | undefined): string | null {
if (typeof value !== "string") {
return null;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
export function resolvePendingUserInputAnswer(
draft: PendingUserInputDraftAnswer | undefined,
): string | null {
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
if (customAnswer) {
return customAnswer;
}
return normalizeDraftAnswer(draft?.selectedOptionLabel);
}
export function setPendingUserInputCustomAnswer(
draft: PendingUserInputDraftAnswer | undefined,
customAnswer: string,
): PendingUserInputDraftAnswer {
const selectedOptionLabel =
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
return {
customAnswer,
...(selectedOptionLabel ? { selectedOptionLabel } : {}),
};
}
export function buildPendingUserInputAnswers(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): Record<string, string> | null {
const answers: Record<string, string> = {};
for (const question of questions) {
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
if (!answer) {
return null;
}
answers[question.id] = answer;
}
return answers;
}
export function countAnsweredPendingUserInputQuestions(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): number {
return questions.reduce((count, question) => {
return resolvePendingUserInputAnswer(draftAnswers[question.id]) ? count + 1 : count;
}, 0);
}
export function findFirstUnansweredPendingUserInputQuestionIndex(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): number {
const unansweredIndex = questions.findIndex(
(question) => !resolvePendingUserInputAnswer(draftAnswers[question.id]),
);
return unansweredIndex === -1 ? Math.max(questions.length - 1, 0) : unansweredIndex;
}
export function derivePendingUserInputProgress(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
questionIndex: number,
): PendingUserInputProgress {
const normalizedQuestionIndex =
questions.length === 0
? 0
: Math.max(0, Math.min(questionIndex, questions.length - 1));
const activeQuestion = questions[normalizedQuestionIndex] ?? null;
const activeDraft = activeQuestion ? draftAnswers[activeQuestion.id] : undefined;
const resolvedAnswer = resolvePendingUserInputAnswer(activeDraft);
const customAnswer = activeDraft?.customAnswer ?? "";
const answeredQuestionCount = countAnsweredPendingUserInputQuestions(questions, draftAnswers);
const isLastQuestion =
questions.length === 0 ? true : normalizedQuestionIndex >= questions.length - 1;
return {
questionIndex: normalizedQuestionIndex,
activeQuestion,
activeDraft,
selectedOptionLabel: activeDraft?.selectedOptionLabel,
customAnswer,
resolvedAnswer,
usingCustomAnswer: customAnswer.trim().length > 0,
answeredQuestionCount,
isLastQuestion,
isComplete: buildPendingUserInputAnswers(questions, draftAnswers) !== null,
canAdvance: Boolean(resolvedAnswer),
};
}
+123
View File
@@ -0,0 +1,123 @@
import { MessageId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
buildProposedPlanMarkdownFilename,
findLatestProposedPlanMessage,
parseProposedPlanMessage,
proposedPlanTitle,
} from "./proposedPlan";
describe("parseProposedPlanMessage", () => {
it("extracts the proposed plan block and surrounding assistant text", () => {
expect(
parseProposedPlanMessage(
"First I checked the repo.\n\n<proposed_plan>\n# Ship plan\n\n- step 1\n</proposed_plan>\n\nImplement this plan?",
),
).toEqual({
beforeText: "First I checked the repo.",
planMarkdown: "# Ship plan\n\n- step 1",
afterText: "Implement this plan?",
});
});
it("returns null when the assistant message has no plan block", () => {
expect(parseProposedPlanMessage("Plain assistant text")).toBeNull();
});
});
describe("findLatestProposedPlanMessage", () => {
it("prefers the latest turn assistant message id when it contains a proposed plan", () => {
const match = findLatestProposedPlanMessage(
[
{
id: MessageId.makeUnsafe("assistant:older-plan"),
role: "assistant",
text: "<proposed_plan>\n# Older plan\n</proposed_plan>",
createdAt: "2026-03-05T00:00:00.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant:latest-plan"),
role: "assistant",
text: "<proposed_plan>\n# Latest plan\n</proposed_plan>",
createdAt: "2026-03-05T00:01:00.000Z",
streaming: false,
},
],
"assistant:latest-plan",
);
expect(match?.message.id).toBe("assistant:latest-plan");
expect(match?.plan.planMarkdown).toBe("# Latest plan");
});
it("falls back to the latest assistant proposed plan when no latest-turn message id is available", () => {
const match = findLatestProposedPlanMessage(
[
{
id: MessageId.makeUnsafe("assistant:plain"),
role: "assistant",
text: "No plan here",
createdAt: "2026-03-05T00:00:00.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant:plan"),
role: "assistant",
text: "<proposed_plan>\n# Fallback plan\n</proposed_plan>",
createdAt: "2026-03-05T00:01:00.000Z",
streaming: false,
},
],
null,
);
expect(match?.message.id).toBe("assistant:plan");
expect(match?.plan.planMarkdown).toBe("# Fallback plan");
});
});
describe("proposedPlanTitle", () => {
it("reads the first markdown heading as the plan title", () => {
expect(proposedPlanTitle("# Integrate RPC\n\nBody")).toBe("Integrate RPC");
});
it("returns null when the plan has no heading", () => {
expect(proposedPlanTitle("- step 1")).toBeNull();
});
});
describe("buildPlanImplementationPrompt", () => {
it("formats the plan exactly like the Codex follow-up handoff prompt", () => {
expect(buildPlanImplementationPrompt("## Ship it\n\n- step 1\n")).toBe(
"PLEASE IMPLEMENT THIS PLAN:\n## Ship it\n\n- step 1",
);
});
});
describe("buildPlanImplementationThreadTitle", () => {
it("uses the plan heading when building the implementation thread title", () => {
expect(buildPlanImplementationThreadTitle("# Integrate RPC\n\nBody")).toBe(
"Implement Integrate RPC",
);
});
it("falls back when the plan has no markdown heading", () => {
expect(buildPlanImplementationThreadTitle("- step 1")).toBe("Implement plan");
});
});
describe("buildProposedPlanMarkdownFilename", () => {
it("derives a stable markdown filename from the plan heading", () => {
expect(buildProposedPlanMarkdownFilename("# Integrate Effect RPC Into Server App")).toBe(
"integrate-effect-rpc-into-server-app.md",
);
});
it("falls back to a generic filename when the plan has no heading", () => {
expect(buildProposedPlanMarkdownFilename("- step 1")).toBe("plan.md");
});
});
+106
View File
@@ -0,0 +1,106 @@
import type { MessageId } from "@t3tools/contracts";
import type { ChatMessage } from "./types";
export interface ProposedPlanBlock {
beforeText: string;
planMarkdown: string;
afterText: string;
}
export interface ProposedPlanMessageMatch {
message: ChatMessage;
plan: ProposedPlanBlock;
}
const PROPOSED_PLAN_REGEX = /<proposed_plan>\s*([\s\S]*?)\s*<\/proposed_plan>/;
export function parseProposedPlanMessage(text: string): ProposedPlanBlock | null {
const match = PROPOSED_PLAN_REGEX.exec(text);
if (!match) {
return null;
}
const fullMatch = match[0];
const content = match[1];
const start = match.index;
const end = start + fullMatch.length;
const planMarkdown = content?.trim();
if (!planMarkdown) {
return null;
}
return {
beforeText: text.slice(0, start).trim(),
planMarkdown,
afterText: text.slice(end).trim(),
};
}
export function proposedPlanTitle(planMarkdown: string): string | null {
const heading = planMarkdown.match(/^\s{0,3}#{1,6}\s+(.+)$/m)?.[1]?.trim();
return heading && heading.length > 0 ? heading : null;
}
function sanitizePlanFileSegment(input: string): string {
const sanitized = input
.toLowerCase()
.replace(/[`'".,!?()[\]{}]+/g, "")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
return sanitized.length > 0 ? sanitized : "plan";
}
export function findLatestProposedPlanMessage(
messages: readonly ChatMessage[],
assistantMessageId: MessageId | string | null | undefined,
): ProposedPlanMessageMatch | null {
if (assistantMessageId) {
const matchingMessage = messages.find(
(message) => message.id === assistantMessageId && message.role === "assistant",
);
if (matchingMessage) {
const parsedPlan = parseProposedPlanMessage(matchingMessage.text);
if (parsedPlan) {
return {
message: matchingMessage,
plan: parsedPlan,
};
}
}
}
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (!message || message.role !== "assistant") {
continue;
}
const parsedPlan = parseProposedPlanMessage(message.text);
if (!parsedPlan) {
continue;
}
return {
message,
plan: parsedPlan,
};
}
return null;
}
export function buildPlanImplementationPrompt(planMarkdown: string): string {
return `PLEASE IMPLEMENT THIS PLAN:\n${planMarkdown.trim()}`;
}
export function buildPlanImplementationThreadTitle(planMarkdown: string): string {
const title = proposedPlanTitle(planMarkdown);
if (!title) {
return "Implement plan";
}
return `Implement ${title}`;
}
export function buildProposedPlanMarkdownFilename(planMarkdown: string): string {
const title = proposedPlanTitle(planMarkdown);
return `${sanitizePlanFileSegment(title ?? "plan")}.md`;
}
+126
View File
@@ -2,8 +2,10 @@ import { EventId, TurnId, type OrchestrationThreadActivity } from "@t3tools/cont
import { describe, expect, it } from "vitest";
import {
deriveActivePlanState,
PROVIDER_OPTIONS,
derivePendingApprovals,
derivePendingUserInputs,
deriveWorkLogEntries,
hasToolActivityForTurn,
isLatestTurnSettled,
@@ -131,6 +133,130 @@ describe("derivePendingApprovals", () => {
});
});
describe("derivePendingUserInputs", () => {
it("tracks open structured prompts and removes resolved ones", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "user-input-open",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "user-input.requested",
summary: "User input requested",
tone: "info",
payload: {
requestId: "req-user-input-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
}),
makeActivity({
id: "user-input-resolved",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "user-input.resolved",
summary: "User input submitted",
tone: "info",
payload: {
requestId: "req-user-input-2",
answers: {
sandbox_mode: "workspace-write",
},
},
}),
makeActivity({
id: "user-input-open-2",
createdAt: "2026-02-23T00:00:01.500Z",
kind: "user-input.requested",
summary: "User input requested",
tone: "info",
payload: {
requestId: "req-user-input-2",
questions: [
{
id: "approval",
header: "Approval",
question: "Continue?",
options: [
{
label: "yes",
description: "Continue execution",
},
],
},
],
},
}),
];
expect(derivePendingUserInputs(activities)).toEqual([
{
requestId: "req-user-input-1",
createdAt: "2026-02-23T00:00:01.000Z",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
]);
});
});
describe("deriveActivePlanState", () => {
it("returns the latest plan update for the active turn", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "plan-old",
createdAt: "2026-02-23T00:00:01.000Z",
kind: "turn.plan.updated",
summary: "Plan updated",
tone: "info",
turnId: "turn-1",
payload: {
explanation: "Initial plan",
plan: [{ step: "Inspect code", status: "pending" }],
},
}),
makeActivity({
id: "plan-latest",
createdAt: "2026-02-23T00:00:02.000Z",
kind: "turn.plan.updated",
summary: "Plan updated",
tone: "info",
turnId: "turn-1",
payload: {
explanation: "Refined plan",
plan: [{ step: "Implement Codex user input", status: "inProgress" }],
},
}),
];
expect(deriveActivePlanState(activities, TurnId.makeUnsafe("turn-1"))).toEqual({
createdAt: "2026-02-23T00:00:02.000Z",
turnId: "turn-1",
explanation: "Refined plan",
steps: [{ step: "Implement Codex user input", status: "inProgress" }],
});
});
});
describe("deriveWorkLogEntries", () => {
it("omits tool started entries and keeps completed entries", () => {
const activities: OrchestrationThreadActivity[] = [
+166
View File
@@ -3,6 +3,7 @@ import {
type OrchestrationLatestTurn,
type OrchestrationThreadActivity,
type ProviderKind,
type UserInputQuestion,
type TurnId,
} from "@t3tools/contracts";
@@ -33,6 +34,22 @@ export interface PendingApproval {
detail?: string;
}
export interface PendingUserInput {
requestId: ApprovalRequestId;
createdAt: string;
questions: ReadonlyArray<UserInputQuestion>;
}
export interface ActivePlanState {
createdAt: string;
turnId: TurnId | null;
explanation?: string | null;
steps: Array<{
step: string;
status: "pending" | "inProgress" | "completed";
}>;
}
export type TimelineEntry =
| {
id: string;
@@ -161,6 +178,155 @@ export function derivePendingApprovals(
);
}
function parseUserInputQuestions(
payload: Record<string, unknown> | null,
): ReadonlyArray<UserInputQuestion> | null {
const questions = payload?.questions;
if (!Array.isArray(questions)) {
return null;
}
const parsed = questions
.map<UserInputQuestion | null>((entry) => {
if (!entry || typeof entry !== "object") return null;
const question = entry as Record<string, unknown>;
if (
typeof question.id !== "string" ||
typeof question.header !== "string" ||
typeof question.question !== "string" ||
!Array.isArray(question.options)
) {
return null;
}
const options = question.options
.map<UserInputQuestion["options"][number] | null>((option) => {
if (!option || typeof option !== "object") return null;
const optionRecord = option as Record<string, unknown>;
if (
typeof optionRecord.label !== "string" ||
typeof optionRecord.description !== "string"
) {
return null;
}
return {
label: optionRecord.label,
description: optionRecord.description,
};
})
.filter((option): option is UserInputQuestion["options"][number] => option !== null);
if (options.length === 0) {
return null;
}
return {
id: question.id,
header: question.header,
question: question.question,
options,
};
})
.filter((question): question is UserInputQuestion => question !== null);
return parsed.length > 0 ? parsed : null;
}
export function derivePendingUserInputs(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): PendingUserInput[] {
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
const ordered = [...activities].toSorted(compareActivitiesByOrder);
for (const activity of ordered) {
const payload =
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
const requestId =
payload && typeof payload.requestId === "string"
? ApprovalRequestId.makeUnsafe(payload.requestId)
: null;
if (activity.kind === "user-input.requested" && requestId) {
const questions = parseUserInputQuestions(payload);
if (!questions) {
continue;
}
openByRequestId.set(requestId, {
requestId,
createdAt: activity.createdAt,
questions,
});
continue;
}
if (activity.kind === "user-input.resolved" && requestId) {
openByRequestId.delete(requestId);
}
}
return [...openByRequestId.values()].toSorted((left, right) =>
left.createdAt.localeCompare(right.createdAt),
);
}
export function deriveActivePlanState(
activities: ReadonlyArray<OrchestrationThreadActivity>,
latestTurnId: TurnId | undefined,
): ActivePlanState | null {
const ordered = [...activities].toSorted(compareActivitiesByOrder);
const candidates = ordered.filter((activity) => {
if (activity.kind !== "turn.plan.updated") {
return false;
}
if (!latestTurnId) {
return true;
}
return activity.turnId === latestTurnId;
});
const latest = candidates.at(-1);
if (!latest) {
return null;
}
const payload =
latest.payload && typeof latest.payload === "object"
? (latest.payload as Record<string, unknown>)
: null;
const rawPlan = payload?.plan;
if (!Array.isArray(rawPlan)) {
return null;
}
const steps = rawPlan
.map((entry) => {
if (!entry || typeof entry !== "object") return null;
const record = entry as Record<string, unknown>;
if (typeof record.step !== "string") {
return null;
}
const status =
record.status === "completed" || record.status === "inProgress"
? record.status
: "pending";
return {
step: record.step,
status,
};
})
.filter(
(
step,
): step is {
step: string;
status: "pending" | "inProgress" | "completed";
} => step !== null,
);
if (steps.length === 0) {
return null;
}
return {
createdAt: latest.createdAt,
turnId: latest.turnId,
...(payload && "explanation" in payload ? { explanation: payload.explanation as string | null } : {}),
steps,
};
}
export function deriveWorkLogEntries(
activities: ReadonlyArray<OrchestrationThreadActivity>,
latestTurnId: TurnId | undefined,
+3 -1
View File
@@ -2,7 +2,7 @@ import { ProjectId, ThreadId, TurnId, type OrchestrationReadModel } from "@t3too
import { describe, expect, it } from "vitest";
import { markThreadUnread, syncServerReadModel, type AppState } from "./store";
import { DEFAULT_RUNTIME_MODE, type Thread } from "./types";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
return {
@@ -12,6 +12,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
title: "Thread",
model: "gpt-5-codex",
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
session: null,
messages: [],
turnDiffSummaries: [],
@@ -49,6 +50,7 @@ function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"
title: "Thread",
model: "gpt-5.3-codex",
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
branch: null,
worktreePath: null,
latestTurn: null,
+1
View File
@@ -257,6 +257,7 @@ export function syncServerReadModel(
thread.model,
),
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
session: thread.session
? {
provider: toLegacyProvider(thread.session.providerName),
+4
View File
@@ -9,11 +9,14 @@ import type {
MessageId,
CheckpointRef,
ProviderKind,
ProviderInteractionMode,
} from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type RuntimeMode = "approval-required" | "full-access";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export type InteractionMode = ProviderInteractionMode;
export const DEFAULT_INTERACTION_MODE: InteractionMode = "default";
export const DEFAULT_THREAD_TERMINAL_HEIGHT = 280;
export const DEFAULT_THREAD_TERMINAL_ID = "default";
export const MAX_THREAD_TERMINAL_COUNT = 4;
@@ -78,6 +81,7 @@ export interface Thread {
title: string;
model: string;
runtimeMode: RuntimeMode;
interactionMode: InteractionMode;
session: ThreadSession | null;
messages: ChatMessage[];
error: string | null;
+2 -1
View File
@@ -1,7 +1,7 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { DEFAULT_RUNTIME_MODE, type Thread } from "./types";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -12,6 +12,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
title: "Thread",
model: "gpt-5.3-codex",
runtimeMode: DEFAULT_RUNTIME_MODE,
interactionMode: DEFAULT_INTERACTION_MODE,
session: null,
messages: [],
turnDiffSummaries: [],
+19
View File
@@ -6,6 +6,7 @@ import {
ProjectId,
ThreadId,
WS_CHANNELS,
WS_METHODS,
type ServerProviderStatus,
} from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -330,6 +331,24 @@ describe("wsNativeApi", () => {
});
});
it("forwards workspace file writes to the websocket project method", async () => {
requestMock.mockResolvedValue({ relativePath: "plan.md" });
const { createWsNativeApi } = await import("./wsNativeApi");
const api = createWsNativeApi();
await api.projects.writeFile({
cwd: "/tmp/project",
relativePath: "plan.md",
contents: "# Plan\n",
});
expect(requestMock).toHaveBeenCalledWith(WS_METHODS.projectsWriteFile, {
cwd: "/tmp/project",
relativePath: "plan.md",
contents: "# Plan\n",
});
});
it("forwards full-thread diff requests to the orchestration websocket method", async () => {
requestMock.mockResolvedValue({ diff: "patch" });
const { createWsNativeApi } = await import("./wsNativeApi");
+1
View File
@@ -141,6 +141,7 @@ export function createWsNativeApi(): NativeApi {
},
projects: {
searchEntries: (input) => transport.request(WS_METHODS.projectsSearchEntries, input),
writeFile: (input) => transport.request(WS_METHODS.projectsWriteFile, input),
},
shell: {
openInEditor: (cwd, editor) =>
File diff suppressed because it is too large. Load diff
+7 -1
View File
@@ -14,7 +14,12 @@ import type {
GitStatusInput,
GitStatusResult,
} from "./git";
import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "./project";
import type {
ProjectSearchEntriesInput,
ProjectSearchEntriesResult,
ProjectWriteFileInput,
ProjectWriteFileResult,
} from "./project";
import type { ServerConfig } from "./server";
import type {
TerminalClearInput,
@@ -104,6 +109,7 @@ export interface NativeApi {
};
projects: {
searchEntries: (input: ProjectSearchEntriesInput) => Promise<ProjectSearchEntriesResult>;
writeFile: (input: ProjectWriteFileInput) => Promise<ProjectWriteFileResult>;
};
shell: {
openInEditor: (cwd: string, editor: EditorId) => Promise<void>;
+6 -1
View File
@@ -2,6 +2,7 @@ import { assert, it } from "@effect/vitest";
import { Effect, Schema } from "effect";
import {
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
OrchestrationGetTurnDiffInput,
OrchestrationSession,
@@ -110,6 +111,7 @@ it.effect("decodes thread.turn.start defaults for provider and runtime mode", ()
});
assert.strictEqual(parsed.provider, undefined);
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
}),
);
@@ -131,6 +133,7 @@ it.effect("preserves explicit provider and runtime mode in thread.turn.start", (
});
assert.strictEqual(parsed.provider, "claudeCode");
assert.strictEqual(parsed.runtimeMode, "full-access");
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
}),
);
@@ -150,10 +153,11 @@ it.effect("accepts cursor provider in thread.turn.start", () =>
createdAt: "2026-01-01T00:00:00.000Z",
});
assert.strictEqual(parsed.provider, "cursor");
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
}),
);
it.effect("decodes thread.turn-start-requested defaults for provider and runtime mode", () =>
it.effect("decodes thread.turn-start-requested defaults for provider, runtime mode, and interaction mode", () =>
Effect.gen(function* () {
const parsed = yield* decodeThreadTurnStartRequestedPayload({
threadId: "thread-1",
@@ -162,6 +166,7 @@ it.effect("decodes thread.turn-start-requested defaults for provider and runtime
});
assert.strictEqual(parsed.provider, undefined);
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
}),
);
+79
View File
@@ -32,6 +32,9 @@ export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
export type RuntimeMode = typeof RuntimeMode.Type;
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const ProviderInteractionMode = Schema.Literals(["default", "plan"]);
export type ProviderInteractionMode = typeof ProviderInteractionMode.Type;
export const DEFAULT_PROVIDER_INTERACTION_MODE: ProviderInteractionMode = "default";
export const ProviderRequestKind = Schema.Literals(["command", "file-read", "file-change"]);
export type ProviderRequestKind = typeof ProviderRequestKind.Type;
export const AssistantDeliveryMode = Schema.Literals(["buffered", "streaming"]);
@@ -43,6 +46,8 @@ export const ProviderApprovalDecision = Schema.Literals([
"cancel",
]);
export type ProviderApprovalDecision = typeof ProviderApprovalDecision.Type;
export const ProviderUserInputAnswers = Schema.Record(Schema.String, Schema.Unknown);
export type ProviderUserInputAnswers = typeof ProviderUserInputAnswers.Type;
export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000;
export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8;
@@ -219,6 +224,9 @@ export const OrchestrationThread = Schema.Struct({
title: TrimmedNonEmptyString,
model: TrimmedNonEmptyString,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode.pipe(
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
),
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
latestTurn: Schema.NullOr(OrchestrationLatestTurn),
@@ -274,6 +282,9 @@ export const ThreadCreateCommand = Schema.Struct({
title: TrimmedNonEmptyString,
model: TrimmedNonEmptyString,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode.pipe(
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
),
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
createdAt: IsoDateTime,
@@ -303,6 +314,14 @@ export const ThreadRuntimeModeSetCommand = Schema.Struct({
createdAt: IsoDateTime,
});
export const ThreadInteractionModeSetCommand = Schema.Struct({
type: Schema.Literal("thread.interaction-mode.set"),
commandId: CommandId,
threadId: ThreadId,
interactionMode: ProviderInteractionMode,
createdAt: IsoDateTime,
});
export const ThreadTurnStartCommand = Schema.Struct({
type: Schema.Literal("thread.turn.start"),
commandId: CommandId,
@@ -318,6 +337,9 @@ export const ThreadTurnStartCommand = Schema.Struct({
effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
),
createdAt: IsoDateTime,
});
@@ -336,6 +358,7 @@ export const ClientThreadTurnStartCommand = Schema.Struct({
effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
createdAt: IsoDateTime,
});
@@ -356,6 +379,15 @@ export const ThreadApprovalRespondCommand = Schema.Struct({
createdAt: IsoDateTime,
});
export const ThreadUserInputRespondCommand = Schema.Struct({
type: Schema.Literal("thread.user-input.respond"),
commandId: CommandId,
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
createdAt: IsoDateTime,
});
export const ThreadCheckpointRevertCommand = Schema.Struct({
type: Schema.Literal("thread.checkpoint.revert"),
commandId: CommandId,
@@ -379,9 +411,11 @@ export const DispatchableClientOrchestrationCommand = Schema.Union([
ThreadDeleteCommand,
ThreadMetaUpdateCommand,
ThreadRuntimeModeSetCommand,
ThreadInteractionModeSetCommand,
ThreadTurnStartCommand,
ThreadTurnInterruptCommand,
ThreadApprovalRespondCommand,
ThreadUserInputRespondCommand,
ThreadCheckpointRevertCommand,
ThreadSessionStopCommand,
]);
@@ -396,9 +430,11 @@ export const ClientOrchestrationCommand = Schema.Union([
ThreadDeleteCommand,
ThreadMetaUpdateCommand,
ThreadRuntimeModeSetCommand,
ThreadInteractionModeSetCommand,
ClientThreadTurnStartCommand,
ThreadTurnInterruptCommand,
ThreadApprovalRespondCommand,
ThreadUserInputRespondCommand,
ThreadCheckpointRevertCommand,
ThreadSessionStopCommand,
]);
@@ -485,10 +521,12 @@ export const OrchestrationEventType = Schema.Literals([
"thread.deleted",
"thread.meta-updated",
"thread.runtime-mode-set",
"thread.interaction-mode-set",
"thread.message-sent",
"thread.turn-start-requested",
"thread.turn-interrupt-requested",
"thread.approval-response-requested",
"thread.user-input-response-requested",
"thread.checkpoint-revert-requested",
"thread.reverted",
"thread.session-stop-requested",
@@ -532,6 +570,9 @@ export const ThreadCreatedPayload = Schema.Struct({
title: TrimmedNonEmptyString,
model: TrimmedNonEmptyString,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode.pipe(
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
),
branch: Schema.NullOr(TrimmedNonEmptyString),
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
createdAt: IsoDateTime,
@@ -558,6 +599,14 @@ export const ThreadRuntimeModeSetPayload = Schema.Struct({
updatedAt: IsoDateTime,
});
export const ThreadInteractionModeSetPayload = Schema.Struct({
threadId: ThreadId,
interactionMode: ProviderInteractionMode.pipe(
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
),
updatedAt: IsoDateTime,
});
export const ThreadMessageSentPayload = Schema.Struct({
threadId: ThreadId,
messageId: MessageId,
@@ -578,6 +627,9 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
effort: Schema.optional(TrimmedNonEmptyString),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
),
createdAt: IsoDateTime,
});
@@ -594,6 +646,13 @@ export const ThreadApprovalResponseRequestedPayload = Schema.Struct({
createdAt: IsoDateTime,
});
export const ThreadUserInputResponseRequestedPayload = Schema.Struct({
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
createdAt: IsoDateTime,
});
export const ThreadCheckpointRevertRequestedPayload = Schema.Struct({
threadId: ThreadId,
turnCount: NonNegativeInt,
@@ -702,6 +761,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.runtime-mode-set"),
payload: ThreadRuntimeModeSetPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.interaction-mode-set"),
payload: ThreadInteractionModeSetPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.message-sent"),
@@ -722,6 +786,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.approval-response-requested"),
payload: ThreadApprovalResponseRequestedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.user-input-response-requested"),
payload: ThreadUserInputResponseRequestedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.checkpoint-revert-requested"),
@@ -791,6 +860,11 @@ export const OrchestrationPersistedEvent = Schema.Union([
eventType: Schema.Literal("thread.runtime-mode-set"),
payload: ThreadRuntimeModeSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.interaction-mode-set"),
payload: ThreadInteractionModeSetPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.message-sent"),
@@ -811,6 +885,11 @@ export const OrchestrationPersistedEvent = Schema.Union([
eventType: Schema.Literal("thread.approval-response-requested"),
payload: ThreadApprovalResponseRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.user-input-response-requested"),
payload: ThreadUserInputResponseRequestedPayload,
}),
Schema.Struct({
...PersistedEventBaseFields,
eventType: Schema.Literal("thread.checkpoint-revert-requested"),
+15
View File
@@ -2,6 +2,7 @@ import { Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
export const PROJECT_SEARCH_ENTRIES_MAX_LIMIT = 200;
export const PROJECT_WRITE_FILE_PATH_MAX_LENGTH = 512;
export const ProjectSearchEntriesInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
@@ -24,3 +25,17 @@ export const ProjectSearchEntriesResult = Schema.Struct({
truncated: Schema.Boolean,
});
export type ProjectSearchEntriesResult = typeof ProjectSearchEntriesResult.Type;
export const ProjectWriteFileInput = Schema.Struct({
cwd: TrimmedNonEmptyString,
relativePath: TrimmedNonEmptyString.check(
Schema.isMaxLength(PROJECT_WRITE_FILE_PATH_MAX_LENGTH),
),
contents: Schema.String,
});
export type ProjectWriteFileInput = typeof ProjectWriteFileInput.Type;
export const ProjectWriteFileResult = Schema.Struct({
relativePath: TrimmedNonEmptyString,
});
export type ProjectWriteFileResult = typeof ProjectWriteFileResult.Type;
+10
View File
@@ -14,8 +14,10 @@ import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
ProviderApprovalDecision,
ProviderInteractionMode,
ProviderKind,
ProviderRequestKind,
ProviderUserInputAnswers,
RuntimeMode,
TurnCountRange,
} from "./orchestration";
@@ -92,6 +94,7 @@ export const ProviderSendTurnInput = Schema.Struct({
),
model: Schema.optional(TrimmedNonEmptyStringSchema),
effort: Schema.optional(TrimmedNonEmptyStringSchema),
interactionMode: Schema.optional(ProviderInteractionMode),
});
export type ProviderSendTurnInput = typeof ProviderSendTurnInput.Type;
@@ -169,6 +172,13 @@ export const ProviderRespondToRequestInput = Schema.Struct({
});
export type ProviderRespondToRequestInput = typeof ProviderRespondToRequestInput.Type;
export const ProviderRespondToUserInputInput = Schema.Struct({
threadId: ThreadId,
requestId: ApprovalRequestId,
answers: ProviderUserInputAnswers,
});
export type ProviderRespondToUserInputInput = typeof ProviderRespondToUserInputInput.Type;
export const ProviderEventKind = Schema.Literals(["session", "notification", "request", "error"]);
export type ProviderEventKind = typeof ProviderEventKind.Type;
+3 -1
View File
@@ -29,7 +29,7 @@ import {
TerminalWriteInput,
} from "./terminal";
import { KeybindingRule } from "./keybindings";
import { ProjectSearchEntriesInput } from "./project";
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
import { OpenInEditorInput } from "./editor";
// ── WebSocket RPC Method Names ───────────────────────────────────────
@@ -40,6 +40,7 @@ export const WS_METHODS = {
projectsAdd: "projects.add",
projectsRemove: "projects.remove",
projectsSearchEntries: "projects.searchEntries",
projectsWriteFile: "projects.writeFile",
// Shell methods
shellOpenInEditor: "shell.openInEditor",
@@ -101,6 +102,7 @@ export const WebSocketRequestBody = Schema.Union([
// Project Search
tagRequestBody(WS_METHODS.projectsSearchEntries, ProjectSearchEntriesInput),
tagRequestBody(WS_METHODS.projectsWriteFile, ProjectWriteFileInput),
// Shell methods
tagRequestBody(WS_METHODS.shellOpenInEditor, OpenInEditorInput),