Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e05cc8885c | ||
|
|
f62310b669 | ||
|
|
6538084cde | ||
|
|
383caeaaa9 | ||
|
|
421667c5ad | ||
|
|
938634ca4a | ||
|
|
4f8ed7206f | ||
|
|
12d7a5c411 | ||
|
|
daf4b31fbf | ||
|
|
7d5b896962 |
No files matched your search
@@ -1,327 +0,0 @@
|
||||
# Plan: Cursor ACP (`agent acp`) Provider Integration
|
||||
|
||||
## Goal
|
||||
|
||||
Add Cursor as a first-class provider in T3 Code using ACP (`agent acp`) over JSON-RPC 2.0 stdio, with robust session lifecycle handling and canonical `ProviderRuntimeEvent` projection.
|
||||
|
||||
---
|
||||
|
||||
## 1) Exploration Findings (from live ACP probes)
|
||||
|
||||
### 1.1 Core invocation and transport
|
||||
|
||||
1. Binary is `agent` on PATH (`2026.02.27-e7d2ef6` observed).
|
||||
2. ACP server command is `agent acp`.
|
||||
3. Transport is newline-delimited JSON-RPC 2.0 over stdio.
|
||||
4. Messages:
|
||||
- client -> server: requests and responses to server-initiated requests
|
||||
- server -> client: responses, notifications (`session/update`), and server requests (`session/request_permission`)
|
||||
|
||||
### 1.2 Handshake and session calls observed
|
||||
|
||||
1. `initialize` returns:
|
||||
- `protocolVersion`
|
||||
- `agentCapabilities` (`loadSession`, `mcpCapabilities`, `promptCapabilities`)
|
||||
- `authMethods` (includes `cursor_login`)
|
||||
2. `authenticate { methodId: "cursor_login" }` returns `{}` when logged in.
|
||||
3. `session/new` returns:
|
||||
- `sessionId`
|
||||
- `modes` (`agent`, `plan`, `ask`)
|
||||
4. `session/load` works and requires `sessionId`, `cwd`, `mcpServers`.
|
||||
5. `session/prompt` returns terminal response `{ stopReason: "end_turn" | "cancelled" }`.
|
||||
|
||||
Important sequence note:
|
||||
1. ACP currently allows `session/new` even without explicit `initialize`/`authenticate` when local auth already exists.
|
||||
2. For adapter consistency and forward compatibility, we should still send `initialize` and `authenticate` during startup.
|
||||
|
||||
### 1.3 `session/update` event families observed
|
||||
|
||||
Observed `params.update.sessionUpdate` values:
|
||||
|
||||
1. `available_commands_update`
|
||||
2. `agent_thought_chunk`
|
||||
3. `agent_message_chunk`
|
||||
4. `tool_call`
|
||||
5. `tool_call_update`
|
||||
|
||||
Observed payload behavior:
|
||||
|
||||
1. `agent_*_chunk` provides `content: { type: "text", text: string }`.
|
||||
2. `tool_call` may be emitted multiple times for same `toolCallId`:
|
||||
- initial generic form (`title: "Terminal"`, `rawInput: {}`)
|
||||
- enriched form (`title: "\`pwd\`"`, `rawInput: { command: "pwd" }`)
|
||||
3. `tool_call_update` statuses observed:
|
||||
- `in_progress`
|
||||
- `completed`
|
||||
4. `tool_call_update` on completion may include `rawOutput`:
|
||||
- terminal: `{ exitCode, stdout, stderr }`
|
||||
- search/find: `{ totalFiles, truncated }`
|
||||
|
||||
### 1.4 Permission flow observed
|
||||
|
||||
1. ACP server sends `session/request_permission` (JSON-RPC request with `id`).
|
||||
2. Request shape includes:
|
||||
- `params.sessionId`
|
||||
- `params.toolCall`
|
||||
- `params.options` (`allow-once`, `allow-always`, `reject-once`)
|
||||
3. Client must respond on same `id` with:
|
||||
- `{ outcome: { outcome: "selected", optionId: "<one-option-id>" } }`
|
||||
4. Reject path still results in tool lifecycle completion events (`tool_call_update status: completed`), typically without `rawOutput`.
|
||||
|
||||
### 1.5 Error and capability quirks
|
||||
|
||||
1. `session/cancel` currently returns:
|
||||
- JSON-RPC error `-32601` Method not found
|
||||
2. Error shape examples:
|
||||
- unknown auth method: `-32602`
|
||||
- `session/load` missing/invalid params: `-32602`
|
||||
- `session/prompt` unknown session: `-32603` with details
|
||||
3. Parallel prompts on same session are effectively single-flight:
|
||||
- second prompt can cause first to complete with `stopReason: "cancelled"`.
|
||||
4. `session/new` accepts a `model` field (no explicit echo in response).
|
||||
|
||||
Probe artifacts:
|
||||
1. `.tmp/acp-probe/*/transcript.ndjson`
|
||||
2. `.tmp/acp-probe/*/summary.json`
|
||||
3. `scripts/cursor-acp-probe.mjs`
|
||||
|
||||
---
|
||||
|
||||
## 2) Integration Constraints for T3
|
||||
|
||||
1. T3 adapter contract still requires:
|
||||
- `startSession`, `sendTurn`, `interruptTurn`, `respondToRequest`, `readThread`, `rollbackThread`, `stopSession`, `listSessions`, `hasSession`, `stopAll`, `streamEvents`.
|
||||
2. Orchestration consumes canonical `ProviderRuntimeEvent` only.
|
||||
3. `ProviderCommandReactor` provider precedence fix remains required (respect explicit provider on turn start).
|
||||
4. ACP now supports external permission decisions, so Cursor can participate in T3 approval UX via adapter-managed request/response plumbing.
|
||||
|
||||
---
|
||||
|
||||
## 3) Proposed Architecture
|
||||
|
||||
### 3.1 New server components
|
||||
|
||||
1. `apps/server/src/provider/Services/CursorAdapter.ts` (service contract/tag + ACP event schemas).
|
||||
2. `apps/server/src/provider/Layers/CursorAdapter.ts` (single implementation unit; owns ACP process lifecycle, JSON-RPC routing, runtime projection).
|
||||
3. No manager indirection; keep logic in layer implementation.
|
||||
|
||||
### 3.2 Session model
|
||||
|
||||
1. One long-lived ACP child process per T3 Cursor provider session.
|
||||
2. Track:
|
||||
- `providerSessionId` (T3 synthetic ID)
|
||||
- `acpSessionId` (from `session/new` or restored via `session/load`)
|
||||
- `cwd`, `model`, in-flight turn state
|
||||
- pending permission requests by JSON-RPC request id
|
||||
3. Resume support:
|
||||
- persist `acpSessionId` in provider resume metadata and call `session/load` on reattach.
|
||||
|
||||
### 3.3 Command strategy
|
||||
|
||||
1. `startSession`:
|
||||
- spawn `agent acp`
|
||||
- `initialize`
|
||||
- `authenticate(cursor_login)` (best-effort, typed failure handling)
|
||||
- `session/new` or `session/load`
|
||||
2. `sendTurn`:
|
||||
- send `session/prompt { sessionId, prompt: [...] }`
|
||||
- consume streaming `session/update` notifications until terminal prompt response
|
||||
3. `interruptTurn`:
|
||||
- no native `session/cancel` today; implement fallback:
|
||||
- terminate ACP process + restart + `session/load` for subsequent turns
|
||||
- mark in-flight turn as interrupted/failed in canonical events
|
||||
4. `respondToRequest`:
|
||||
- map T3 approval decision -> ACP `optionId`
|
||||
- reply to exact JSON-RPC request id from `session/request_permission`
|
||||
|
||||
### 3.4 Effect-first implementation style (required)
|
||||
|
||||
1. Keep logic inside `CursorAdapterLive`.
|
||||
2. Use Effect primitives:
|
||||
- `Queue` + `Stream.fromQueue` for event fan-out
|
||||
- `Ref` / `Ref.Synchronized` for session/process/request state
|
||||
- scoped fibers for stdout/stderr read loops
|
||||
3. Typed JSON decode at boundary:
|
||||
- request/response envelopes
|
||||
- `session/update` union schema
|
||||
- permission-request schema
|
||||
4. Keep adapter errors in typed error algebra with explicit mapping at process/protocol boundaries.
|
||||
|
||||
---
|
||||
|
||||
## 4) Canonical Event Mapping Plan (ACP -> ProviderRuntimeEvent)
|
||||
|
||||
1. `session/update: agent_message_chunk`
|
||||
- emit `message.delta` for assistant stream
|
||||
2. prompt terminal response (`session/prompt` result `stopReason: end_turn`)
|
||||
- emit `message.completed` + `turn.completed`
|
||||
3. `session/update: agent_thought_chunk`
|
||||
- initial mapping: emit thinking activity (or ignore if we keep current canonical surface minimal)
|
||||
4. `session/update: tool_call`
|
||||
- first-seen `toolCallId` emits `tool.started`
|
||||
- subsequent `tool_call` for same ID treated as metadata update (no duplicate started event)
|
||||
5. `session/update: tool_call_update`
|
||||
- `in_progress`: optional progress activity
|
||||
- `completed`: emit `tool.completed` with summarized `rawOutput` when present
|
||||
6. `session/request_permission`
|
||||
- emit `approval.requested` with mapped options
|
||||
- when client decision sent, emit `approval.resolved`
|
||||
7. protocol/process error
|
||||
- emit `runtime.error`
|
||||
- fail active turn/session as appropriate
|
||||
|
||||
Synthetic IDs:
|
||||
1. `turnId`: T3-generated UUID per `sendTurn`.
|
||||
2. `itemId`:
|
||||
- assistant stream: `${turnId}:assistant`
|
||||
- tools: `${turnId}:${toolCallId}`
|
||||
|
||||
---
|
||||
|
||||
## 5) Approval, Resume, and Rollback Behavior
|
||||
|
||||
### 5.1 Approvals
|
||||
|
||||
1. Cursor ACP permission requests are externally controllable; implement full `respondToRequest` path in v1.
|
||||
2. Decision mapping:
|
||||
- allow once -> `allow-once`
|
||||
- allow always -> `allow-always`
|
||||
- reject -> `reject-once`
|
||||
|
||||
### 5.2 Resume
|
||||
|
||||
1. `session/load` is available and should be first-class for adapter restart/reconnect.
|
||||
2. Must send required params: `sessionId`, `cwd`, `mcpServers`.
|
||||
|
||||
### 5.3 Rollback / thread read
|
||||
|
||||
1. ACP currently has no observed rollback API.
|
||||
2. Plan for v1:
|
||||
- `readThread`: adapter-maintained snapshot projection
|
||||
- `rollbackThread`: explicit unsupported error
|
||||
3. Product guard:
|
||||
- disable checkpoint revert for Cursor threads in UI until rollback exists.
|
||||
|
||||
---
|
||||
|
||||
## 6) Required Contract and Runtime Changes
|
||||
|
||||
### 6.1 Contracts
|
||||
|
||||
1. Add `cursor` to `ProviderKind`.
|
||||
2. Add Cursor provider start options (`providerOptions.cursor`), ACP-oriented:
|
||||
- optional `binaryPath`
|
||||
- optional auth/mode knobs if needed later
|
||||
3. Extend model options for Cursor list and traits mapping.
|
||||
4. Add schemas for ACP-native event union in Cursor adapter service file.
|
||||
|
||||
### 6.2 Server orchestration and registry
|
||||
|
||||
1. Register `CursorAdapter` in provider registry and server layer wiring.
|
||||
2. Update provider-kind persistence decoding for `cursor`.
|
||||
3. Fix `ProviderCommandReactor` precedence to honor explicit provider in turn-start command.
|
||||
|
||||
### 6.3 Web
|
||||
|
||||
1. Cursor in provider picker and model picker (already partially done).
|
||||
2. Trait controls map to concrete Cursor model identifiers.
|
||||
3. Surface unsupported rollback behavior in UX.
|
||||
|
||||
---
|
||||
|
||||
## 7) Implementation Phases
|
||||
|
||||
### Phase A: ACP process and protocol skeleton
|
||||
|
||||
1. Implement ACP process lifecycle in `CursorAdapterLive`.
|
||||
2. Implement JSON-RPC request/response multiplexer.
|
||||
3. Implement `initialize`/`authenticate`/`session/new|load` flow.
|
||||
4. Wire `streamEvents` from ACP notifications.
|
||||
|
||||
### Phase B: Runtime projection and approvals
|
||||
|
||||
1. Map `session/update` variants to canonical runtime events.
|
||||
2. Implement permission-request bridging to `respondToRequest`.
|
||||
3. Implement dedupe for repeated `tool_call` on same `toolCallId`.
|
||||
|
||||
### Phase C: Turn control and interruption
|
||||
|
||||
1. Implement single in-flight prompt protection per session.
|
||||
2. Implement interruption fallback (process restart + reload) because `session/cancel` unavailable.
|
||||
3. Ensure clean state recovery on ACP process crash.
|
||||
|
||||
### Phase D: Orchestration + UX polish
|
||||
|
||||
1. Provider routing precedence fix.
|
||||
2. Cursor-specific UX notes for unsupported rollback.
|
||||
3. End-to-end smoke and event log validation.
|
||||
|
||||
---
|
||||
|
||||
## 8) Test Plan
|
||||
|
||||
Follow project rule: backend external-service integrations tested via layered fakes, not by mocking core business logic.
|
||||
|
||||
### 8.1 Unit tests (`CursorAdapter`)
|
||||
|
||||
1. JSON-RPC envelope parsing:
|
||||
- response matching by id
|
||||
- server request handling (`session/request_permission`)
|
||||
- notification decode (`session/update`)
|
||||
2. Event projection:
|
||||
- `agent_message_chunk` / `agent_thought_chunk`
|
||||
- `tool_call` + `tool_call_update` dedupe/lifecycle
|
||||
- permission request -> approval events
|
||||
3. Error mapping:
|
||||
- unknown session
|
||||
- method-not-found (`session/cancel`)
|
||||
- invalid params
|
||||
|
||||
### 8.2 Provider service/routing tests
|
||||
|
||||
1. Registry resolves `cursor`.
|
||||
2. Session directory persistence reads/writes `cursor`.
|
||||
3. ProviderService fan-out ordering with Cursor ACP events.
|
||||
|
||||
### 8.3 Orchestration tests
|
||||
|
||||
1. `thread.turn.start` with `provider: cursor` routes to Cursor adapter.
|
||||
2. approval response command maps to ACP permission response.
|
||||
3. checkpoint revert on Cursor thread returns controlled unsupported failure.
|
||||
|
||||
### 8.4 Optional live smoke
|
||||
|
||||
1. Env-gated ACP smoke:
|
||||
- start session
|
||||
- run prompt
|
||||
- observe deltas + completion
|
||||
- exercise permission request path with one tool call
|
||||
|
||||
---
|
||||
|
||||
## 9) Operational Notes
|
||||
|
||||
1. Keep one in-flight turn per ACP session.
|
||||
2. Keep per-session ACP process logs/NDJSON artifacts for debugging.
|
||||
3. Treat `session/cancel` as unsupported until Cursor ships it; avoid relying on it.
|
||||
4. Preserve resume metadata (`acpSessionId`) for crash recovery.
|
||||
|
||||
---
|
||||
|
||||
## 10) Open Questions
|
||||
|
||||
1. Should we call `authenticate` always, or only after auth-required errors?
|
||||
2. Should model selection be passed at `session/new` only, or can/should we support model switching mid-session if ACP adds API?
|
||||
3. For interruption UX, do we expose “hard interrupt” semantics (process restart) explicitly?
|
||||
|
||||
---
|
||||
|
||||
## 11) Delivery Checklist
|
||||
|
||||
1. Plan/documentation switched from headless `agent -p` to ACP `agent acp`.
|
||||
2. Contracts updated (`ProviderKind`, Cursor options, model/trait mapping).
|
||||
3. Cursor ACP adapter layer implemented and registered.
|
||||
4. Provider precedence fixed in orchestration router.
|
||||
5. Approval response path wired through ACP permission requests.
|
||||
6. Tests added for protocol decode, projection, approval flow, and routing.
|
||||
7. Lint + tests green.
|
||||
@@ -152,7 +152,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly rootDir: string;
|
||||
readonly workspaceDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly adapterHarness: TestProviderAdapterHarness;
|
||||
readonly adapterHarness: TestProviderAdapterHarness | null;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
@@ -188,7 +188,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex" | "cursor";
|
||||
readonly provider?: "codex";
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
@@ -435,7 +435,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness: adapterHarness as TestProviderAdapterHarness,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
|
||||
@@ -35,7 +35,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex" | "cursor";
|
||||
readonly provider?: "codex";
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -206,7 +206,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: "codex" | "cursor",
|
||||
provider: "codex",
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -216,7 +216,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: "codex" | "cursor",
|
||||
provider: "codex",
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
|
||||
@@ -32,7 +32,7 @@ const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = "codex" | "cursor";
|
||||
type IntegrationProvider = "codex";
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -180,7 +180,7 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
],
|
||||
};
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession(turnResponse);
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession(turnResponse);
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-single",
|
||||
@@ -314,7 +314,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
@@ -373,7 +373,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
(entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
|
||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
@@ -473,7 +473,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
@@ -538,7 +538,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
assert.equal(resolvedRow.decision, "accept");
|
||||
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness.getApprovalResponses(THREAD_ID),
|
||||
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
|
||||
(responses) => responses.length === 1,
|
||||
"provider approval response",
|
||||
);
|
||||
@@ -554,7 +554,7 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
@@ -633,7 +633,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
@@ -691,7 +691,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(THREAD_ID, {
|
||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
@@ -796,7 +796,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness.getRollbackCalls(THREAD_ID), [1]);
|
||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||
|
||||
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
|
||||
threadId: THREAD_ID,
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import path from "node:path";
|
||||
|
||||
import { Effect, FileSystem, Layer, Logger, ServiceMap } from "effect";
|
||||
|
||||
import { makeEventNdjsonLogger } from "../src/provider/Layers/EventNdjsonLogger.ts";
|
||||
|
||||
class LogDir extends ServiceMap.Service<LogDir, string>()("t3/scripts/logger-scope-repro/LogDir") {}
|
||||
|
||||
const main = Effect.gen(function* () {
|
||||
const logdir = yield* LogDir;
|
||||
const providerLogPath = path.join(logdir, "provider");
|
||||
|
||||
yield* Effect.logInfo(`providerLogPath=${providerLogPath}`);
|
||||
|
||||
const providerLogger = yield* makeEventNdjsonLogger(providerLogPath, {
|
||||
stream: "native",
|
||||
batchWindowMs: 10,
|
||||
});
|
||||
|
||||
yield* Effect.logInfo("before provider write");
|
||||
|
||||
if (providerLogger) {
|
||||
yield* providerLogger.write(
|
||||
{
|
||||
kind: "probe",
|
||||
message: "provider-only event",
|
||||
},
|
||||
"thread-123" as never,
|
||||
);
|
||||
}
|
||||
|
||||
yield* Effect.logInfo("after provider write");
|
||||
yield* Effect.sleep("50 millis");
|
||||
|
||||
if (providerLogger) {
|
||||
yield* providerLogger.close();
|
||||
}
|
||||
yield* Effect.logInfo("after provider close");
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const logContents = yield* fs
|
||||
.readDirectory(logdir, { recursive: true })
|
||||
.pipe(
|
||||
Effect.flatMap((entries) =>
|
||||
Effect.all(entries.map((entry) => fs.readFileString(path.join(logdir, entry)))),
|
||||
),
|
||||
);
|
||||
yield* Effect.logInfo(`logContents=${logContents}`);
|
||||
});
|
||||
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const logdir = path.join(process.cwd(), "logtest");
|
||||
yield* fs.makeDirectory(logdir);
|
||||
|
||||
const fileLogger = yield* Logger.formatSimple.pipe(
|
||||
Logger.toFile(path.join(logdir, "global.log")),
|
||||
);
|
||||
const dualLogger = Logger.layer([fileLogger, Logger.consolePretty()]);
|
||||
|
||||
const mainLayer = Layer.mergeAll(dualLogger, Layer.succeed(LogDir, logdir));
|
||||
|
||||
yield* main.pipe(Effect.provide(mainLayer));
|
||||
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);
|
||||
@@ -7,6 +7,7 @@ import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildCodexInitializeParams,
|
||||
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CodexAppServerManager,
|
||||
classifyCodexStderrLine,
|
||||
@@ -346,6 +347,36 @@ describe("sendTurn", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("passes Codex default mode as a collaboration preset on turn/start", async () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
|
||||
interactionMode: "default",
|
||||
});
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
collaborationMode: {
|
||||
mode: "default",
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects empty turn input", async () => {
|
||||
const { manager } = createSendTurnHarness();
|
||||
|
||||
@@ -454,8 +485,8 @@ describe("respondToUserInput", () => {
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
},
|
||||
);
|
||||
|
||||
@@ -482,6 +513,80 @@ describe("respondToUserInput", () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves explicit empty multi-select answers", async () => {
|
||||
const { manager, context, requireSession, writeMessage, emitEvent } =
|
||||
createPendingUserInputHarness();
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: [],
|
||||
},
|
||||
);
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(writeMessage).toHaveBeenCalledWith(context, {
|
||||
id: 42,
|
||||
result: {
|
||||
answers: {
|
||||
scope: { answers: [] },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "item/tool/requestUserInput/answered",
|
||||
payload: {
|
||||
requestId: "req-user-input-1",
|
||||
answers: {
|
||||
scope: { answers: [] },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("tracks file-read approval requests with the correct method", () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: asThreadId("thread_1"),
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
};
|
||||
type ApprovalRequestContext = {
|
||||
session: typeof context.session;
|
||||
pendingApprovals: typeof context.pendingApprovals;
|
||||
pendingUserInputs: typeof context.pendingUserInputs;
|
||||
};
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerRequest: (
|
||||
context: ApprovalRequestContext,
|
||||
request: Record<string, unknown>,
|
||||
) => void;
|
||||
}
|
||||
).handleServerRequest(context, {
|
||||
jsonrpc: "2.0",
|
||||
id: 42,
|
||||
method: "item/fileRead/requestApproval",
|
||||
params: {},
|
||||
});
|
||||
|
||||
const request = Array.from(context.pendingApprovals.values())[0];
|
||||
expect(request?.requestKind).toBe("file-read");
|
||||
expect(request?.method).toBe("item/fileRead/requestApproval");
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
||||
|
||||
@@ -34,7 +34,10 @@ interface PendingRequest {
|
||||
interface PendingApprovalRequest {
|
||||
requestId: ApprovalRequestId;
|
||||
jsonRpcId: string | number;
|
||||
method: "item/commandExecution/requestApproval" | "item/fileChange/requestApproval";
|
||||
method:
|
||||
| "item/commandExecution/requestApproval"
|
||||
| "item/fileChange/requestApproval"
|
||||
| "item/fileRead/requestApproval";
|
||||
requestKind: ProviderRequestKind;
|
||||
threadId: ThreadId;
|
||||
turnId?: TurnId;
|
||||
@@ -254,6 +257,19 @@ Do not ask "should I proceed?" in the final output. The user can easily switch o
|
||||
Only produce at most one \`<proposed_plan>\` block per turn, and only when you are presenting a complete spec.
|
||||
</collaboration_mode>`;
|
||||
|
||||
export const CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Collaboration Mode: Default
|
||||
|
||||
You are now in Default mode. Any previous instructions for other modes (e.g. Plan mode) are no longer active.
|
||||
|
||||
Your active mode changes only when new developer instructions with a different \`<collaboration_mode>...</collaboration_mode>\` change it; user requests or tool descriptions do not change mode by themselves. Known mode names are Default and Plan.
|
||||
|
||||
## request_user_input availability
|
||||
|
||||
The \`request_user_input\` tool is unavailable in Default mode. If you call it while in Default mode, it will return an error.
|
||||
|
||||
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
|
||||
</collaboration_mode>`;
|
||||
|
||||
function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||
readonly approvalPolicy: "on-request" | "never";
|
||||
readonly sandbox: "workspace-write" | "danger-full-access";
|
||||
@@ -323,7 +339,7 @@ function buildCodexCollaborationMode(input: {
|
||||
readonly effort?: string;
|
||||
}):
|
||||
| {
|
||||
mode: "plan";
|
||||
mode: "default" | "plan";
|
||||
settings: {
|
||||
model: string;
|
||||
reasoning_effort: string;
|
||||
@@ -331,16 +347,19 @@ function buildCodexCollaborationMode(input: {
|
||||
};
|
||||
}
|
||||
| undefined {
|
||||
if (input.interactionMode !== "plan") {
|
||||
if (input.interactionMode === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const model = normalizeCodexModelSlug(input.model) ?? "gpt-5.3-codex";
|
||||
return {
|
||||
mode: "plan",
|
||||
mode: input.interactionMode,
|
||||
settings: {
|
||||
model,
|
||||
reasoning_effort: input.effort ?? "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
developer_instructions:
|
||||
input.interactionMode === "plan"
|
||||
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
|
||||
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -352,18 +371,14 @@ function toCodexUserInputAnswer(value: unknown): CodexUserInputAnswer {
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const answers = value.filter((entry): entry is string => typeof entry === "string");
|
||||
if (answers.length > 0) {
|
||||
return { answers };
|
||||
}
|
||||
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 };
|
||||
}
|
||||
return { answers };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,7 +660,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
effort?: string;
|
||||
serviceTier?: string;
|
||||
collaborationMode?: {
|
||||
mode: "plan";
|
||||
mode: "default" | "plan";
|
||||
settings: {
|
||||
model: string;
|
||||
reasoning_effort: string;
|
||||
@@ -1064,7 +1079,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
method:
|
||||
requestKind === "command"
|
||||
? "item/commandExecution/requestApproval"
|
||||
: "item/fileChange/requestApproval",
|
||||
: requestKind === "file-read"
|
||||
? "item/fileRead/requestApproval"
|
||||
: "item/fileChange/requestApproval",
|
||||
requestKind,
|
||||
threadId: context.session.threadId,
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
|
||||
@@ -9,8 +9,6 @@
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
// Dummy comment.
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
resolveStaticDir,
|
||||
@@ -122,7 +120,7 @@ const CliEnvConfig = Config.all({
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
Option.getOrElse(flag, () => envValue);
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
|
||||
@@ -43,7 +43,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
|
||||
@@ -93,8 +93,7 @@ describe("ProviderCommandReactor", () => {
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
(input.provider === "codex" ||
|
||||
input.provider === "cursor")
|
||||
input.provider === "codex"
|
||||
? input.provider
|
||||
: "codex";
|
||||
const resumeCursor =
|
||||
@@ -186,7 +185,7 @@ describe("ProviderCommandReactor", () => {
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (provider) =>
|
||||
Effect.succeed({
|
||||
sessionModelSwitch: provider === "cursor" ? "unsupported" : "in-session",
|
||||
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
stopAll: () => Effect.void,
|
||||
@@ -384,43 +383,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("starts first turn with cursor provider when provider is specified", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-cursor"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-cursor"),
|
||||
role: "user",
|
||||
text: "hello cursor",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "cursor",
|
||||
cwd: "/tmp/provider-project",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerName).toBe("cursor");
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -467,111 +429,6 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("reuses the same cursor session when requested model is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-same-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-cursor-model-same-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
model: "composer-1.5",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-same-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-cursor-model-same-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
model: "composer-1.5",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("keeps cursor session/model when model change is unsupported", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-change-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-cursor-model-change-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
model: "gpt-5.3-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-cursor-model-change-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-cursor-model-change-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
model: "composer-1.5",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
});
|
||||
});
|
||||
|
||||
it("restarts the provider session when runtime mode is updated on the thread", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -852,7 +709,7 @@ describe("ProviderCommandReactor", () => {
|
||||
harness.respondToRequest.mockImplementation(() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "cursor",
|
||||
provider: "codex",
|
||||
method: "session/request_permission",
|
||||
detail: "Unknown pending permission request: approval-request-1",
|
||||
}),
|
||||
@@ -867,7 +724,7 @@ describe("ProviderCommandReactor", () => {
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "cursor",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
|
||||
@@ -211,10 +211,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const desiredRuntimeMode = thread.runtimeMode;
|
||||
const currentProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" ||
|
||||
thread.session?.providerName === "cursor"
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
|
||||
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
|
||||
@@ -41,7 +41,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
|
||||
@@ -157,30 +157,6 @@ const validationLayer = it.layer(
|
||||
);
|
||||
|
||||
validationLayer("CodexAdapterLive validation", (it) => {
|
||||
it.effect("returns validation error for non-codex provider on startSession", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const result = yield* adapter
|
||||
.startSession({
|
||||
provider: "cursor",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
assert.equal(result._tag, "Failure");
|
||||
assert.deepStrictEqual(
|
||||
result.failure,
|
||||
new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "startSession",
|
||||
issue: "Expected provider 'codex' but received 'cursor'.",
|
||||
}),
|
||||
);
|
||||
assert.equal(validationManager.startSessionImpl.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps codex model options before starting a session", () =>
|
||||
Effect.gen(function* () {
|
||||
validationManager.startSessionImpl.mockClear();
|
||||
@@ -468,6 +444,78 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves file-read request type when mapping serverRequest/resolved", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
const event: ProviderEvent = {
|
||||
id: asEventId("evt-file-read-request-resolved"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "serverRequest/resolved",
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-file-read-1"),
|
||||
payload: {
|
||||
request: {
|
||||
method: "item/fileRead/requestApproval",
|
||||
},
|
||||
decision: "accept",
|
||||
},
|
||||
};
|
||||
|
||||
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, "request.resolved");
|
||||
if (firstEvent.value.type !== "request.resolved") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.payload.requestType, "file_read_approval");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves explicit empty multi-select user-input answers", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
const event: ProviderEvent = {
|
||||
id: asEventId("evt-user-input-empty"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "item/tool/requestUserInput/answered",
|
||||
payload: {
|
||||
answers: {
|
||||
scope: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
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, "user-input.resolved");
|
||||
if (firstEvent.value.type !== "user-input.resolved") {
|
||||
return;
|
||||
}
|
||||
assert.deepEqual(firstEvent.value.payload.answers, {
|
||||
scope: [],
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("maps windowsSandbox/setupCompleted to session state and warning on failure", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
|
||||
@@ -274,9 +274,6 @@ function toCanonicalUserInputAnswers(
|
||||
|
||||
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];
|
||||
}
|
||||
|
||||
@@ -284,7 +281,7 @@ function toCanonicalUserInputAnswers(
|
||||
const answerList = asArray(answerObject?.answers)?.filter(
|
||||
(entry): entry is string => typeof entry === "string",
|
||||
);
|
||||
if (!answerList || answerList.length === 0) {
|
||||
if (!answerList) {
|
||||
return [];
|
||||
}
|
||||
return [[questionId, answerList.length === 1 ? answerList[0] : answerList] as const];
|
||||
|
||||
@@ -51,7 +51,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex" | "cursor";
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
|
||||
@@ -133,6 +133,36 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
}
|
||||
}));
|
||||
|
||||
it("resets adapterKey to the new provider when provider changes without an explicit adapter key", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-provider-change");
|
||||
|
||||
yield* runtimeRepository.upsert({
|
||||
threadId,
|
||||
providerName: "cursor",
|
||||
adapterKey: "cursor",
|
||||
runtimeMode: "full-access",
|
||||
status: "running",
|
||||
lastSeenAt: new Date().toISOString(),
|
||||
resumeCursor: null,
|
||||
runtimePayload: null,
|
||||
});
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: "codex",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const runtime = yield* runtimeRepository.getByThreadId({ threadId });
|
||||
assert.equal(Option.isSome(runtime), true);
|
||||
if (Option.isSome(runtime)) {
|
||||
assert.equal(runtime.value.providerName, "codex");
|
||||
assert.equal(runtime.value.adapterKey, "codex");
|
||||
}
|
||||
}));
|
||||
|
||||
it("rehydrates persisted mappings across layer restart", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-directory-"));
|
||||
@@ -174,26 +204,4 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
}));
|
||||
|
||||
it("accepts cursor provider bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const threadId = ThreadId.makeUnsafe("thread-cursor");
|
||||
|
||||
yield* directory.upsert({
|
||||
provider: "cursor",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const provider = yield* directory.getProvider(threadId);
|
||||
assert.equal(provider, "cursor");
|
||||
const resolvedBinding = yield* directory.getBinding(threadId);
|
||||
assertSome(resolvedBinding, {
|
||||
threadId,
|
||||
provider: "cursor",
|
||||
});
|
||||
if (Option.isSome(resolvedBinding)) {
|
||||
assert.equal(resolvedBinding.value.threadId, threadId);
|
||||
}
|
||||
}));
|
||||
});
|
||||
@@ -25,7 +25,7 @@ function decodeProviderKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
|
||||
if (providerName === "codex" || providerName === "cursor") {
|
||||
if (providerName === "codex") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.fail(
|
||||
@@ -95,11 +95,15 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const providerChanged =
|
||||
existingRuntime !== undefined && existingRuntime.providerName !== binding.provider;
|
||||
yield* repository
|
||||
.upsert({
|
||||
threadId: resolvedThreadId,
|
||||
providerName: binding.provider,
|
||||
adapterKey: binding.adapterKey ?? existingRuntime?.adapterKey ?? binding.provider,
|
||||
adapterKey:
|
||||
binding.adapterKey ??
|
||||
(providerChanged ? binding.provider : (existingRuntime?.adapterKey ?? binding.provider)),
|
||||
runtimeMode: binding.runtimeMode ?? existingRuntime?.runtimeMode ?? "full-access",
|
||||
status: binding.status ?? existingRuntime?.status ?? "running",
|
||||
lastSeenAt: now,
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getAppModelOptions, getSlashModelOptions, normalizeCustomModelSlugs } from "./appSettings";
|
||||
import {
|
||||
getAppModelOptions,
|
||||
getSlashModelOptions,
|
||||
normalizeCustomModelSlugs,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
@@ -15,13 +20,6 @@ describe("normalizeCustomModelSlugs", () => {
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
|
||||
it("normalizes provider-specific aliases for cursor", () => {
|
||||
expect(normalizeCustomModelSlugs(["composer"], "cursor")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["cursor/custom-model"], "cursor")).toEqual([
|
||||
"cursor/custom-model",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
@@ -47,14 +45,18 @@ describe("getAppModelOptions", () => {
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a saved custom provider model available as an exact slug option", () => {
|
||||
const options = getAppModelOptions("cursor", ["cursor/custom-model"], "cursor/custom-model");
|
||||
|
||||
expect(options.some((option) => option.slug === "cursor/custom-model" && option.isCustom)).toBe(
|
||||
true,
|
||||
describe("resolveAppModelSelection", () => {
|
||||
it("preserves saved custom model slugs instead of falling back to the default", () => {
|
||||
expect(resolveAppModelSelection("codex", ["galapagos-alpha"], "galapagos-alpha")).toBe(
|
||||
"galapagos-alpha",
|
||||
);
|
||||
});
|
||||
|
||||
it("falls back to the provider default when no model is selected", () => {
|
||||
expect(resolveAppModelSelection("codex", [], "")).toBe("gpt-5.4");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSlashModelOptions", () => {
|
||||
@@ -79,10 +81,4 @@ describe("getSlashModelOptions", () => {
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
|
||||
});
|
||||
|
||||
it("includes provider-specific custom slugs in non-codex model lists", () => {
|
||||
const cursorOptions = getAppModelOptions("cursor", ["cursor/custom-model"]);
|
||||
|
||||
expect(cursorOptions.some((option) => option.slug === "cursor/custom-model")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,14 +1,13 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
cursor: new Set(getModelOptions("cursor").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
@@ -25,9 +24,6 @@ const AppSettingsSchema = Schema.Struct({
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customCursorModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
@@ -75,7 +71,6 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
||||
customCursorModels: normalizeCustomModelSlugs(settings.customCursorModels, "cursor"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -116,6 +111,38 @@ export function getAppModelOptions(
|
||||
return options;
|
||||
}
|
||||
|
||||
export function resolveAppModelSelection(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
selectedModel: string | null | undefined,
|
||||
): string {
|
||||
const options = getAppModelOptions(provider, customModels, selectedModel);
|
||||
const trimmedSelectedModel = selectedModel?.trim();
|
||||
if (trimmedSelectedModel) {
|
||||
const direct = options.find((option) => option.slug === trimmedSelectedModel);
|
||||
if (direct) {
|
||||
return direct.slug;
|
||||
}
|
||||
|
||||
const byName = options.find(
|
||||
(option) => option.name.toLowerCase() === trimmedSelectedModel.toLowerCase(),
|
||||
);
|
||||
if (byName) {
|
||||
return byName.slug;
|
||||
}
|
||||
}
|
||||
|
||||
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
|
||||
if (!normalizedSelectedModel) {
|
||||
return getDefaultModel(provider);
|
||||
}
|
||||
|
||||
return (
|
||||
options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
|
||||
getDefaultModel(provider)
|
||||
);
|
||||
}
|
||||
|
||||
export function getSlashModelOptions(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import {
|
||||
type ApprovalRequestId,
|
||||
CURSOR_REASONING_OPTIONS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
EDITORS,
|
||||
type EditorId,
|
||||
type KeybindingCommand,
|
||||
type CodexReasoningEffort,
|
||||
type CursorReasoningOption,
|
||||
type MessageId,
|
||||
type ProjectId,
|
||||
type ProjectEntry,
|
||||
@@ -27,12 +25,8 @@ import {
|
||||
import {
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getCursorModelCapabilities,
|
||||
getCursorModelFamilyOptions,
|
||||
getReasoningEffortOptions,
|
||||
normalizeModelSlug,
|
||||
parseCursorModelSelection,
|
||||
resolveCursorModelFromSelection,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
@@ -202,7 +196,7 @@ import { Toggle } from "./ui/toggle";
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { getAppModelOptions, useAppSettings } from "../appSettings";
|
||||
import { getAppModelOptions, resolveAppModelSelection, useAppSettings } from "../appSettings";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
@@ -581,7 +575,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
|
||||
const setComposerDraftModel = useComposerDraftStore((store) => store.setModel);
|
||||
const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);
|
||||
const setComposerDraftInteractionMode = useComposerDraftStore((store) => store.setInteractionMode);
|
||||
const setComposerDraftInteractionMode = useComposerDraftStore(
|
||||
(store) => store.setInteractionMode,
|
||||
);
|
||||
const setComposerDraftEffort = useComposerDraftStore((store) => store.setEffort);
|
||||
const setComposerDraftCodexFastMode = useComposerDraftStore((store) => store.setCodexFastMode);
|
||||
const addComposerDraftImage = useComposerDraftStore((store) => store.addImage);
|
||||
@@ -709,14 +705,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
? buildLocalDraftThread(
|
||||
threadId,
|
||||
draftThread,
|
||||
fallbackDraftProject?.model ?? DEFAULT_MODEL,
|
||||
fallbackDraftProject?.model ?? DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
localDraftError,
|
||||
)
|
||||
: undefined,
|
||||
[draftThread, fallbackDraftProject?.model, localDraftError, threadId],
|
||||
);
|
||||
const activeThread = serverThread ?? localDraftThread;
|
||||
const runtimeMode = composerDraft.runtimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const runtimeMode =
|
||||
composerDraft.runtimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode =
|
||||
composerDraft.interactionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE;
|
||||
const isServerThread = serverThread !== undefined;
|
||||
@@ -761,41 +758,22 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
? (sessionProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
const selectedProvider: ProviderKind = lockedProvider ?? selectedProviderByThreadId ?? "codex";
|
||||
const cursorModelSelectionLockedReason =
|
||||
hasThreadStarted && selectedProvider === "cursor"
|
||||
? "Cursor currently does not support changing models after the first message in a thread."
|
||||
: null;
|
||||
const baseThreadModel = resolveModelSlugForProvider(
|
||||
selectedProvider,
|
||||
activeThread?.model ??
|
||||
activeProject?.model ??
|
||||
getDefaultModel(selectedProvider) ??
|
||||
DEFAULT_MODEL,
|
||||
activeThread?.model ?? activeProject?.model ?? getDefaultModel(selectedProvider),
|
||||
);
|
||||
const customModelsForSelectedProvider = settings.customCodexModels;
|
||||
const selectedModel = useMemo(() => {
|
||||
const draftModel = composerDraft.model;
|
||||
if (!draftModel) {
|
||||
return baseThreadModel;
|
||||
}
|
||||
|
||||
const providerOptions = getCustomModelOptionsByProvider(settings)[selectedProvider];
|
||||
const directMatch = providerOptions.find((option) => option.slug === draftModel);
|
||||
if (directMatch) {
|
||||
return directMatch.slug as ModelSlug;
|
||||
}
|
||||
|
||||
const normalizedDraftModel = normalizeModelSlug(draftModel, selectedProvider);
|
||||
if (normalizedDraftModel) {
|
||||
const normalizedMatch = providerOptions.find(
|
||||
(option) => option.slug === normalizedDraftModel,
|
||||
);
|
||||
if (normalizedMatch) {
|
||||
return normalizedMatch.slug as ModelSlug;
|
||||
}
|
||||
}
|
||||
|
||||
return resolveModelSlugForProvider(selectedProvider, draftModel);
|
||||
}, [baseThreadModel, composerDraft.model, selectedProvider, settings]);
|
||||
return resolveAppModelSelection(
|
||||
selectedProvider,
|
||||
customModelsForSelectedProvider,
|
||||
draftModel,
|
||||
) as ModelSlug;
|
||||
}, [baseThreadModel, composerDraft.model, customModelsForSelectedProvider, selectedProvider]);
|
||||
const reasoningOptions = getReasoningEffortOptions(selectedProvider);
|
||||
const supportsReasoningEffort = reasoningOptions.length > 0;
|
||||
const selectedEffort = composerDraft.effort ?? getDefaultReasoningEffort(selectedProvider);
|
||||
@@ -811,40 +789,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
};
|
||||
return Object.keys(codexOptions).length > 0 ? { codex: codexOptions } : undefined;
|
||||
}, [selectedCodexFastModeEnabled, selectedEffort, selectedProvider, supportsReasoningEffort]);
|
||||
const selectedCursorModel = useMemo(
|
||||
() => (selectedProvider === "cursor" ? parseCursorModelSelection(selectedModel) : null),
|
||||
[selectedModel, selectedProvider],
|
||||
);
|
||||
const selectedCursorModelCapabilities = useMemo(
|
||||
() => (selectedCursorModel ? getCursorModelCapabilities(selectedCursorModel.family) : null),
|
||||
[selectedCursorModel],
|
||||
);
|
||||
const hasSelectedCursorTraits = Boolean(
|
||||
selectedCursorModelCapabilities &&
|
||||
(selectedCursorModelCapabilities.supportsReasoning ||
|
||||
selectedCursorModelCapabilities.supportsFast ||
|
||||
selectedCursorModelCapabilities.supportsThinking),
|
||||
);
|
||||
const selectedModelForPicker =
|
||||
selectedProvider === "cursor" && selectedCursorModel
|
||||
? selectedCursorModel.family
|
||||
: selectedModel;
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => getCustomModelOptionsByProvider(settings),
|
||||
[settings],
|
||||
);
|
||||
const selectedModelForPickerWithCustomFallback = useMemo(() => {
|
||||
if (selectedProvider !== "cursor") {
|
||||
const currentOptions = modelOptionsByProvider[selectedProvider];
|
||||
return currentOptions.some((option) => option.slug === selectedModelForPicker)
|
||||
? selectedModelForPicker
|
||||
: (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);
|
||||
}
|
||||
|
||||
const currentOptions = modelOptionsByProvider.cursor;
|
||||
const currentOptions = modelOptionsByProvider[selectedProvider];
|
||||
return currentOptions.some((option) => option.slug === selectedModelForPicker)
|
||||
? selectedModelForPicker
|
||||
: selectedModelForPicker;
|
||||
: (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);
|
||||
}, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]);
|
||||
const searchableModelOptions = useMemo(
|
||||
() =>
|
||||
@@ -2504,7 +2458,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
const title = truncateTitle(titleSeed);
|
||||
let threadCreateModel: ModelSlug =
|
||||
selectedModel || (activeProject.model as ModelSlug) || DEFAULT_MODEL;
|
||||
selectedModel || (activeProject.model as ModelSlug) || DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
|
||||
if (isLocalDraftThread) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
@@ -2915,7 +2869,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
selectedModel ||
|
||||
(activeThread.model as ModelSlug) ||
|
||||
(activeProject.model as ModelSlug) ||
|
||||
DEFAULT_MODEL;
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
setSendPhase("sending-turn");
|
||||
@@ -3009,73 +2963,26 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const onProviderModelSelect = useCallback(
|
||||
(provider: ProviderKind, model: ModelSlug) => {
|
||||
if (!activeThread) return;
|
||||
if (cursorModelSelectionLockedReason !== null && provider === "cursor") {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
if (lockedProvider !== null && provider !== lockedProvider) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
const resolvedModel =
|
||||
provider === "cursor"
|
||||
? resolveCursorModelFromSelection(parseCursorModelSelection(model))
|
||||
: resolveModelSlugForProvider(provider, model);
|
||||
setComposerDraftProvider(activeThread.id, provider);
|
||||
setComposerDraftModel(activeThread.id, resolvedModel);
|
||||
setComposerDraftModel(
|
||||
activeThread.id,
|
||||
resolveAppModelSelection(provider, settings.customCodexModels, model),
|
||||
);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
cursorModelSelectionLockedReason,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModel,
|
||||
setComposerDraftProvider,
|
||||
settings.customCodexModels,
|
||||
],
|
||||
);
|
||||
const onCursorReasoningSelect = useCallback(
|
||||
(reasoning: CursorReasoningOption) => {
|
||||
if (selectedProvider !== "cursor") return;
|
||||
const cursorSelection = parseCursorModelSelection(selectedModel);
|
||||
const nextModel = resolveCursorModelFromSelection({
|
||||
family: cursorSelection.family,
|
||||
reasoning,
|
||||
fast: cursorSelection.fast,
|
||||
thinking: cursorSelection.thinking,
|
||||
});
|
||||
onProviderModelSelect("cursor", nextModel);
|
||||
},
|
||||
[onProviderModelSelect, selectedModel, selectedProvider],
|
||||
);
|
||||
const onCursorFastModeChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (selectedProvider !== "cursor") return;
|
||||
const cursorSelection = parseCursorModelSelection(selectedModel);
|
||||
const nextModel = resolveCursorModelFromSelection({
|
||||
family: cursorSelection.family,
|
||||
reasoning: cursorSelection.reasoning,
|
||||
fast: enabled,
|
||||
thinking: cursorSelection.thinking,
|
||||
});
|
||||
onProviderModelSelect("cursor", nextModel);
|
||||
},
|
||||
[onProviderModelSelect, selectedModel, selectedProvider],
|
||||
);
|
||||
const onCursorThinkingModeChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (selectedProvider !== "cursor") return;
|
||||
const cursorSelection = parseCursorModelSelection(selectedModel);
|
||||
const nextModel = resolveCursorModelFromSelection({
|
||||
family: cursorSelection.family,
|
||||
reasoning: cursorSelection.reasoning,
|
||||
fast: cursorSelection.fast,
|
||||
thinking: enabled,
|
||||
});
|
||||
onProviderModelSelect("cursor", nextModel);
|
||||
},
|
||||
[onProviderModelSelect, selectedModel, selectedProvider],
|
||||
);
|
||||
const onEffortSelect = useCallback(
|
||||
(effort: CodexReasoningEffort) => {
|
||||
setComposerDraftEffort(threadId, effort);
|
||||
@@ -3594,82 +3501,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 px-2.5 pb-2.5 sm:flex-nowrap sm:gap-0 sm:px-3 sm:pb-3">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:min-w-max sm:overflow-visible">
|
||||
{/* Provider/model picker */}
|
||||
{cursorModelSelectionLockedReason ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span className="inline-flex">
|
||||
<ProviderModelPicker
|
||||
provider={selectedProvider}
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
disabled
|
||||
onProviderModelChange={onProviderModelSelect}
|
||||
/>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top" className="max-w-72 whitespace-normal leading-tight">
|
||||
{cursorModelSelectionLockedReason}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<ProviderModelPicker
|
||||
provider={selectedProvider}
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
onProviderModelChange={onProviderModelSelect}
|
||||
/>
|
||||
)}
|
||||
<ProviderModelPicker
|
||||
provider={selectedProvider}
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
onProviderModelChange={onProviderModelSelect}
|
||||
/>
|
||||
|
||||
{selectedProvider === "cursor" ? (
|
||||
<>
|
||||
{hasSelectedCursorTraits && (
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
)}
|
||||
|
||||
{selectedCursorModel &&
|
||||
selectedCursorModelCapabilities &&
|
||||
hasSelectedCursorTraits && (
|
||||
<>
|
||||
{cursorModelSelectionLockedReason ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<span className="inline-flex">
|
||||
<CursorTraitsPicker
|
||||
selection={selectedCursorModel}
|
||||
capabilities={selectedCursorModelCapabilities}
|
||||
disabled
|
||||
onReasoningChange={onCursorReasoningSelect}
|
||||
onFastModeChange={onCursorFastModeChange}
|
||||
onThinkingModeChange={onCursorThinkingModeChange}
|
||||
/>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup
|
||||
side="top"
|
||||
className="max-w-72 whitespace-normal leading-tight"
|
||||
>
|
||||
{cursorModelSelectionLockedReason}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<CursorTraitsPicker
|
||||
selection={selectedCursorModel}
|
||||
capabilities={selectedCursorModelCapabilities}
|
||||
onReasoningChange={onCursorReasoningSelect}
|
||||
onFastModeChange={onCursorFastModeChange}
|
||||
onThinkingModeChange={onCursorThinkingModeChange}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
) : selectedProvider === "codex" && selectedEffort != null ? (
|
||||
{selectedProvider === "codex" && selectedEffort != null ? (
|
||||
<>
|
||||
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
|
||||
<CodexTraitsPicker
|
||||
@@ -5278,9 +5118,7 @@ const MessagesTimeline = memo(function MessagesTimeline({
|
||||
);
|
||||
});
|
||||
|
||||
function isAvailableProviderOption(
|
||||
option: (typeof PROVIDER_OPTIONS)[number],
|
||||
): option is {
|
||||
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
|
||||
value: ProviderKind;
|
||||
label: string;
|
||||
available: true;
|
||||
@@ -5297,18 +5135,9 @@ const COMING_SOON_PROVIDER_OPTIONS = [
|
||||
|
||||
function getCustomModelOptionsByProvider(settings: {
|
||||
customCodexModels: readonly string[];
|
||||
customCursorModels: readonly string[];
|
||||
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
const cursorFamilyOptions = getCursorModelFamilyOptions();
|
||||
return {
|
||||
codex: getAppModelOptions("codex", settings.customCodexModels),
|
||||
cursor: [
|
||||
...cursorFamilyOptions,
|
||||
...getAppModelOptions("cursor", settings.customCursorModels).filter(
|
||||
(option) =>
|
||||
option.isCustom && !cursorFamilyOptions.some((family) => family.slug === option.slug),
|
||||
),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5348,10 +5177,6 @@ function resolveModelForProviderPicker(
|
||||
return resolved.slug;
|
||||
}
|
||||
|
||||
if (provider === "cursor") {
|
||||
return parseCursorModelSelection(normalized).family;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -5391,10 +5216,7 @@ const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
}
|
||||
>
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<ProviderIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/70"
|
||||
/>
|
||||
<ProviderIcon aria-hidden="true" className="size-4 shrink-0 text-muted-foreground/70" />
|
||||
<span className="truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</span>
|
||||
@@ -5562,117 +5384,6 @@ const CodexTraitsPicker = memo(function CodexTraitsPicker(props: {
|
||||
);
|
||||
});
|
||||
|
||||
const CursorTraitsPicker = memo(function CursorTraitsPicker(props: {
|
||||
selection: ReturnType<typeof parseCursorModelSelection>;
|
||||
capabilities: ReturnType<typeof getCursorModelCapabilities>;
|
||||
disabled?: boolean;
|
||||
onReasoningChange: (reasoning: CursorReasoningOption) => void;
|
||||
onFastModeChange: (enabled: boolean) => void;
|
||||
onThinkingModeChange: (enabled: boolean) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const reasoningLabelByOption: Record<CursorReasoningOption, string> = {
|
||||
low: "Low",
|
||||
normal: "Normal",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
const traitSummary = [
|
||||
...(props.capabilities.supportsReasoning
|
||||
? [reasoningLabelByOption[props.selection.reasoning]]
|
||||
: []),
|
||||
...(props.capabilities.supportsFast && props.selection.fast ? ["Fast"] : []),
|
||||
...(props.capabilities.supportsThinking && props.selection.thinking ? ["Thinking"] : []),
|
||||
];
|
||||
const triggerLabel = traitSummary.length > 0 ? traitSummary.join(" · ") : "Traits";
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (props.disabled) {
|
||||
setIsMenuOpen(false);
|
||||
return;
|
||||
}
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{props.capabilities.supportsReasoning && (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Reasoning</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selection.reasoning}
|
||||
onValueChange={(value) => {
|
||||
if (props.disabled) return;
|
||||
if (!value) return;
|
||||
const nextReasoning = CURSOR_REASONING_OPTIONS.find((option) => option === value);
|
||||
if (!nextReasoning) return;
|
||||
props.onReasoningChange(nextReasoning);
|
||||
}}
|
||||
>
|
||||
{CURSOR_REASONING_OPTIONS.map((reasoning) => (
|
||||
<MenuRadioItem key={reasoning} value={reasoning}>
|
||||
{reasoning}
|
||||
{reasoning === "normal" ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
)}
|
||||
{props.capabilities.supportsReasoning &&
|
||||
(props.capabilities.supportsFast || props.capabilities.supportsThinking) && (
|
||||
<MenuDivider />
|
||||
)}
|
||||
{props.capabilities.supportsFast && (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selection.fast ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
if (props.disabled) return;
|
||||
props.onFastModeChange(value === "on");
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
)}
|
||||
{props.capabilities.supportsFast && props.capabilities.supportsThinking && <MenuDivider />}
|
||||
{props.capabilities.supportsThinking && (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selection.thinking ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
if (props.disabled) return;
|
||||
props.onThinkingModeChange(value === "on");
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
)}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
|
||||
const OpenInPicker = memo(function OpenInPicker({
|
||||
keybindings,
|
||||
availableEditors,
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type DesktopUpdateState,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -506,7 +506,7 @@ export default function Sidebar() {
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: DEFAULT_MODEL,
|
||||
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
createdAt,
|
||||
})
|
||||
.then(() => true)
|
||||
@@ -885,7 +885,7 @@ export default function Sidebar() {
|
||||
? "text-sky-400"
|
||||
: shouldHighlightDesktopUpdateError(desktopUpdateState)
|
||||
? "text-rose-500 animate-pulse"
|
||||
: "text-amber-500 animate-pulse";
|
||||
: "text-amber-500 animate-pulse";
|
||||
const newThreadShortcutLabel = useMemo(
|
||||
() =>
|
||||
shortcutLabelForCommand(keybindings, "chat.newLocal") ??
|
||||
|
||||
@@ -394,15 +394,15 @@ describe("composerDraftStore setProvider", () => {
|
||||
it("persists provider-only selection even when prompt/model are empty", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "cursor");
|
||||
store.setProvider(threadId, "codex");
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("cursor");
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("codex");
|
||||
});
|
||||
|
||||
it("removes empty provider-only draft when provider is reset", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "cursor");
|
||||
store.setProvider(threadId, "codex");
|
||||
store.setProvider(threadId, null);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
|
||||
@@ -208,7 +208,7 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
}
|
||||
|
||||
function normalizeProviderKind(value: unknown): ProviderKind | null {
|
||||
return value === "codex" || value === "cursor" ? value : null;
|
||||
return value === "codex" ? value : null;
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
|
||||
@@ -54,8 +54,6 @@ function getCustomModelsForProvider(
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "cursor":
|
||||
return settings.customCursorModels;
|
||||
case "codex":
|
||||
default:
|
||||
return settings.customCodexModels;
|
||||
@@ -67,8 +65,6 @@ function getDefaultCustomModelsForProvider(
|
||||
provider: ProviderKind,
|
||||
) {
|
||||
switch (provider) {
|
||||
case "cursor":
|
||||
return defaults.customCursorModels;
|
||||
case "codex":
|
||||
default:
|
||||
return defaults.customCodexModels;
|
||||
@@ -77,8 +73,6 @@ function getDefaultCustomModelsForProvider(
|
||||
|
||||
function patchCustomModels(provider: ProviderKind, models: string[]) {
|
||||
switch (provider) {
|
||||
case "cursor":
|
||||
return { customCursorModels: models };
|
||||
case "codex":
|
||||
default:
|
||||
return { customCodexModels: models };
|
||||
@@ -95,7 +89,6 @@ function SettingsRouteView() {
|
||||
Record<ProviderKind, string>
|
||||
>({
|
||||
codex: "",
|
||||
cursor: "",
|
||||
});
|
||||
const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState<
|
||||
Partial<Record<ProviderKind, string | null>>
|
||||
|
||||
@@ -343,6 +343,35 @@ describe("deriveWorkLogEntries", () => {
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
||||
});
|
||||
|
||||
it("omits task start and completion lifecycle entries", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "task-start",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
kind: "task.started",
|
||||
summary: "default task started",
|
||||
tone: "info",
|
||||
}),
|
||||
makeActivity({
|
||||
id: "task-progress",
|
||||
createdAt: "2026-02-23T00:00:02.000Z",
|
||||
kind: "task.progress",
|
||||
summary: "Updating files",
|
||||
tone: "info",
|
||||
}),
|
||||
makeActivity({
|
||||
id: "task-complete",
|
||||
createdAt: "2026-02-23T00:00:03.000Z",
|
||||
kind: "task.completed",
|
||||
summary: "Task completed",
|
||||
tone: "info",
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["task-progress"]);
|
||||
});
|
||||
|
||||
it("filters by turn id when provided", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "turn-1", turnId: "turn-1", summary: "Tool call", kind: "tool.started" }),
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
|
||||
import type { ChatMessage, ProposedPlan, SessionPhase, ThreadSession, TurnDiffSummary } from "./types";
|
||||
|
||||
export type ProviderPickerKind = ProviderKind | "claudeCode";
|
||||
export type ProviderPickerKind = ProviderKind | "claudeCode" | "cursor";
|
||||
|
||||
export const PROVIDER_OPTIONS: Array<{
|
||||
value: ProviderPickerKind;
|
||||
@@ -394,6 +394,7 @@ export function deriveWorkLogEntries(
|
||||
return ordered
|
||||
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
|
||||
.filter((activity) => activity.kind !== "tool.started")
|
||||
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
|
||||
.filter((activity) => activity.summary !== "Checkpoint captured")
|
||||
.map((activity) => {
|
||||
const payload =
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { ProjectId, ThreadId, TurnId, type OrchestrationReadModel } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markThreadUnread, syncServerReadModel, type AppState } from "./store";
|
||||
@@ -139,29 +145,6 @@ describe("store read model sync", () => {
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("gpt-5.3-codex");
|
||||
});
|
||||
|
||||
it("resolves cursor aliases when session provider is cursor", () => {
|
||||
const initialState = makeState(makeThread());
|
||||
const readModel = makeReadModel(
|
||||
makeReadModelThread({
|
||||
model: "composer",
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "cursor",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.threads[0]?.model).toBe("composer-1.5");
|
||||
expect(next.threads[0]?.session?.provider).toBe("cursor");
|
||||
expect(next.threads[0]?.model).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
});
|
||||
});
|
||||
+16
-55
@@ -1,6 +1,6 @@
|
||||
import { Fragment, type ReactNode, createElement, useEffect } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ProviderKind,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
@@ -13,11 +13,7 @@ import {
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import {
|
||||
type ChatMessage,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "./types";
|
||||
import { type ChatMessage, type Project, type Thread } from "./types";
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -114,7 +110,9 @@ function mapProjectsFromReadModel(
|
||||
id: project.id,
|
||||
name: project.title,
|
||||
cwd: project.workspaceRoot,
|
||||
model: existing?.model ?? resolveModelSlug(project.defaultModel ?? DEFAULT_MODEL),
|
||||
model:
|
||||
existing?.model ??
|
||||
resolveModelSlug(project.defaultModel ?? DEFAULT_MODEL_BY_PROVIDER.codex),
|
||||
expanded:
|
||||
existing?.expanded ??
|
||||
(persistedExpandedProjectCwds.size > 0
|
||||
@@ -145,43 +143,25 @@ function toLegacySessionStatus(
|
||||
}
|
||||
|
||||
function toLegacyProvider(providerName: string | null): ProviderKind {
|
||||
if (providerName === "codex" || providerName === "cursor") {
|
||||
if (providerName === "codex") {
|
||||
return providerName;
|
||||
}
|
||||
return "codex";
|
||||
}
|
||||
|
||||
const CODEX_MODEL_SLUGS = new Set<string>(getModelOptions("codex").map((option) => option.slug));
|
||||
const CURSOR_MODEL_SLUGS = new Set<string>(getModelOptions("cursor").map((option) => option.slug));
|
||||
const CURSOR_DISTINCT_MODEL_SLUGS = new Set(
|
||||
[...CURSOR_MODEL_SLUGS].filter((slug) => !CODEX_MODEL_SLUGS.has(slug)),
|
||||
);
|
||||
|
||||
function inferProviderForThreadModel(input: {
|
||||
readonly model: string;
|
||||
readonly sessionProviderName: string | null;
|
||||
}): ProviderKind {
|
||||
if (
|
||||
input.sessionProviderName === "codex" ||
|
||||
input.sessionProviderName === "cursor"
|
||||
) {
|
||||
if (input.sessionProviderName === "codex") {
|
||||
return input.sessionProviderName;
|
||||
}
|
||||
const normalizedCursor = normalizeModelSlug(input.model, "cursor");
|
||||
if (normalizedCursor && CURSOR_DISTINCT_MODEL_SLUGS.has(normalizedCursor)) {
|
||||
return "cursor";
|
||||
}
|
||||
const normalizedCodex = normalizeModelSlug(input.model, "codex");
|
||||
if (normalizedCodex && CODEX_MODEL_SLUGS.has(normalizedCodex)) {
|
||||
return "codex";
|
||||
}
|
||||
if (
|
||||
input.model.trim().startsWith("composer-") ||
|
||||
input.model.trim().startsWith("gemini-") ||
|
||||
input.model.trim().endsWith("-thinking")
|
||||
) {
|
||||
return "cursor";
|
||||
}
|
||||
return "codex";
|
||||
}
|
||||
|
||||
@@ -199,11 +179,7 @@ function resolveWsHttpOrigin(): string {
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:"
|
||||
? "https:"
|
||||
: wsUrl.protocol === "ws:"
|
||||
? "http:"
|
||||
: wsUrl.protocol;
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
@@ -223,17 +199,12 @@ function attachmentPreviewRoutePath(attachmentId: string): string {
|
||||
|
||||
// ── Pure state transition functions ────────────────────────────────────
|
||||
|
||||
export function syncServerReadModel(
|
||||
state: AppState,
|
||||
readModel: OrchestrationReadModel,
|
||||
): AppState {
|
||||
export function syncServerReadModel(state: AppState, readModel: OrchestrationReadModel): AppState {
|
||||
const projects = mapProjectsFromReadModel(
|
||||
readModel.projects.filter((project) => project.deletedAt === null),
|
||||
state.projects,
|
||||
);
|
||||
const existingThreadById = new Map(
|
||||
state.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const));
|
||||
const threads = readModel.threads
|
||||
.filter((thread) => thread.deletedAt === null)
|
||||
.map((thread) => {
|
||||
@@ -352,9 +323,7 @@ export function markThreadUnread(state: AppState, threadId: ThreadId): AppState
|
||||
export function toggleProject(state: AppState, projectId: Project["id"]): AppState {
|
||||
return {
|
||||
...state,
|
||||
projects: state.projects.map((p) =>
|
||||
p.id === projectId ? { ...p, expanded: !p.expanded } : p,
|
||||
),
|
||||
projects: state.projects.map((p) => (p.id === projectId ? { ...p, expanded: !p.expanded } : p)),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -408,27 +377,19 @@ interface AppStore extends AppState {
|
||||
toggleProject: (projectId: Project["id"]) => void;
|
||||
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
|
||||
setError: (threadId: ThreadId, error: string | null) => void;
|
||||
setThreadBranch: (
|
||||
threadId: ThreadId,
|
||||
branch: string | null,
|
||||
worktreePath: string | null,
|
||||
) => void;
|
||||
setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
|
||||
}
|
||||
|
||||
export const useStore = create<AppStore>((set) => ({
|
||||
...readPersistedState(),
|
||||
syncServerReadModel: (readModel) =>
|
||||
set((state) => syncServerReadModel(state, readModel)),
|
||||
syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)),
|
||||
markThreadVisited: (threadId, visitedAt) =>
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
markThreadUnread: (threadId) =>
|
||||
set((state) => markThreadUnread(state, threadId)),
|
||||
toggleProject: (projectId) =>
|
||||
set((state) => toggleProject(state, projectId)),
|
||||
markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)),
|
||||
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
|
||||
setProjectExpanded: (projectId, expanded) =>
|
||||
set((state) => setProjectExpanded(state, projectId, expanded)),
|
||||
setError: (threadId, error) =>
|
||||
set((state) => setError(state, threadId, error)),
|
||||
setError: (threadId, error) => set((state) => setError(state, threadId, error)),
|
||||
setThreadBranch: (threadId, branch, worktreePath) =>
|
||||
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
|
||||
}));
|
||||
|
||||
@@ -302,38 +302,6 @@
|
||||
|
||||
"@hapi/topo": ["@hapi/[email protected]", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-KR3rD5inZbGMrHmgPxsJ9dbi6zEK+C3ZwUwTa+eMwWLz7oijWUTWD2pMSNNYJAU6Qq+65NkxXjqHr/7LM2Xkqg=="],
|
||||
|
||||
"@img/sharp-darwin-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="],
|
||||
|
||||
"@img/sharp-darwin-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="],
|
||||
|
||||
"@img/sharp-libvips-darwin-arm64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g=="],
|
||||
|
||||
"@img/sharp-libvips-darwin-x64": ["@img/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg=="],
|
||||
|
||||
"@img/sharp-libvips-linux-arm": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A=="],
|
||||
|
||||
"@img/sharp-libvips-linux-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw=="],
|
||||
|
||||
"@img/sharp-libvips-linux-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw=="],
|
||||
|
||||
"@img/sharp-libvips-linuxmusl-arm64": ["@img/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw=="],
|
||||
|
||||
"@img/sharp-libvips-linuxmusl-x64": ["@img/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg=="],
|
||||
|
||||
"@img/sharp-linux-arm": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.2.4" }, "os": "linux", "cpu": "arm" }, "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw=="],
|
||||
|
||||
"@img/sharp-linux-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg=="],
|
||||
|
||||
"@img/sharp-linux-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ=="],
|
||||
|
||||
"@img/sharp-linuxmusl-arm64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg=="],
|
||||
|
||||
"@img/sharp-linuxmusl-x64": ["@img/[email protected]", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q=="],
|
||||
|
||||
"@img/sharp-win32-arm64": ["@img/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g=="],
|
||||
|
||||
"@img/sharp-win32-x64": ["@img/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
|
||||
|
||||
"@inquirer/ansi": ["@inquirer/[email protected]", "", {}, "sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ=="],
|
||||
|
||||
"@inquirer/confirm": ["@inquirer/[email protected]", "", { "dependencies": { "@inquirer/core": "^10.3.2", "@inquirer/type": "^3.0.10" }, "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ=="],
|
||||
|
||||
+1
-2
@@ -35,7 +35,6 @@
|
||||
"test": "turbo run test",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"probe:cursor-acp": "node scripts/cursor-acp-probe.mjs",
|
||||
"build:contracts": "turbo run build --filter=@t3tools/contracts",
|
||||
"dist:desktop:artifact": "node scripts/build-desktop-artifact.ts",
|
||||
"dist:desktop:dmg": "node scripts/build-desktop-artifact.ts --platform mac --target dmg",
|
||||
@@ -63,4 +62,4 @@
|
||||
"apps/web/public"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
export const CURSOR_REASONING_OPTIONS = ["low", "normal", "high", "xhigh"] as const;
|
||||
export type CursorReasoningOption = (typeof CURSOR_REASONING_OPTIONS)[number];
|
||||
import { ProviderKind } from "./orchestration";
|
||||
|
||||
export const CODEX_REASONING_EFFORT_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
|
||||
export type CodexReasoningEffort = (typeof CODEX_REASONING_EFFORT_OPTIONS)[number];
|
||||
@@ -12,16 +10,8 @@ export const CodexModelOptions = Schema.Struct({
|
||||
});
|
||||
export type CodexModelOptions = typeof CodexModelOptions.Type;
|
||||
|
||||
export const CursorModelOptions = Schema.Struct({
|
||||
reasoning: Schema.optional(Schema.Literals(CURSOR_REASONING_OPTIONS)),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type CursorModelOptions = typeof CursorModelOptions.Type;
|
||||
|
||||
export const ProviderModelOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexModelOptions),
|
||||
cursor: Schema.optional(CursorModelOptions),
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
|
||||
@@ -30,25 +20,6 @@ type ModelOption = {
|
||||
readonly name: string;
|
||||
};
|
||||
|
||||
type CursorModelFamilyOption = {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
};
|
||||
|
||||
export const CURSOR_MODEL_FAMILY_OPTIONS = [
|
||||
{ slug: "auto", name: "Auto" },
|
||||
{ slug: "composer-1.5", name: "Composer 1.5" },
|
||||
{ slug: "composer-1", name: "Composer 1" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
{ slug: "gpt-5.3-codex-spark-preview", name: "GPT-5.3 Codex Spark" },
|
||||
{ slug: "opus-4.6", name: "Claude 4.6 Opus" },
|
||||
{ slug: "opus-4.5", name: "Claude 4.5 Opus" },
|
||||
{ slug: "sonnet-4.6", name: "Claude 4.6 Sonnet" },
|
||||
{ slug: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },
|
||||
] as const satisfies readonly CursorModelFamilyOption[];
|
||||
|
||||
export type CursorModelFamily = (typeof CURSOR_MODEL_FAMILY_OPTIONS)[number]["slug"];
|
||||
|
||||
export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
codex: [
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
@@ -57,42 +28,15 @@ export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
{ slug: "gpt-5.2-codex", name: "GPT-5.2 Codex" },
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
],
|
||||
cursor: [
|
||||
{ slug: "auto", name: "Auto" },
|
||||
{ slug: "composer-1.5", name: "Composer 1.5" },
|
||||
{ slug: "composer-1", name: "Composer 1" },
|
||||
{ slug: "gpt-5.3-codex-low", name: "GPT-5.3 Codex Low" },
|
||||
{ slug: "gpt-5.3-codex-low-fast", name: "GPT-5.3 Codex Low Fast" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
{ slug: "gpt-5.3-codex-fast", name: "GPT-5.3 Codex Fast" },
|
||||
{ slug: "gpt-5.3-codex-high", name: "GPT-5.3 Codex High" },
|
||||
{ slug: "gpt-5.3-codex-high-fast", name: "GPT-5.3 Codex High Fast" },
|
||||
{ slug: "gpt-5.3-codex-xhigh", name: "GPT-5.3 Codex Extra High" },
|
||||
{ slug: "gpt-5.3-codex-xhigh-fast", name: "GPT-5.3 Codex Extra High Fast" },
|
||||
{ slug: "gpt-5.3-codex-spark-preview", name: "GPT-5.3 Codex Spark" },
|
||||
{ slug: "opus-4.6", name: "Claude 4.6 Opus" },
|
||||
{ slug: "opus-4.6-thinking", name: "Claude 4.6 Opus (Thinking)" },
|
||||
{ slug: "opus-4.5", name: "Claude 4.5 Opus" },
|
||||
{ slug: "opus-4.5-thinking", name: "Claude 4.5 Opus (Thinking)" },
|
||||
{ slug: "sonnet-4.6", name: "Claude 4.6 Sonnet" },
|
||||
{ slug: "sonnet-4.6-thinking", name: "Claude 4.6 Sonnet (Thinking)" },
|
||||
{ slug: "gemini-3.1-pro", name: "Gemini 3.1 Pro" },
|
||||
],
|
||||
} as const satisfies Record<"codex" | "cursor", readonly ModelOption[]>;
|
||||
} as const satisfies Record<ProviderKind, readonly ModelOption[]>;
|
||||
export type ModelOptionsByProvider = typeof MODEL_OPTIONS_BY_PROVIDER;
|
||||
|
||||
type BuiltInModelSlug =
|
||||
(typeof MODEL_OPTIONS_BY_PROVIDER)[keyof typeof MODEL_OPTIONS_BY_PROVIDER][number]["slug"];
|
||||
type BuiltInModelSlug = ModelOptionsByProvider[ProviderKind][number]["slug"];
|
||||
export type ModelSlug = BuiltInModelSlug | (string & {});
|
||||
export type CursorModelSlug = (typeof MODEL_OPTIONS_BY_PROVIDER)["cursor"][number]["slug"];
|
||||
|
||||
export const DEFAULT_MODEL_BY_PROVIDER = {
|
||||
codex: "gpt-5.3-codex",
|
||||
cursor: "opus-4.6-thinking",
|
||||
} as const satisfies Record<keyof typeof MODEL_OPTIONS_BY_PROVIDER, ModelSlug>;
|
||||
|
||||
// Backward compatibility for existing Codex-only call sites.
|
||||
export const MODEL_OPTIONS = MODEL_OPTIONS_BY_PROVIDER.codex;
|
||||
export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
codex: "gpt-5.4",
|
||||
} as const satisfies Record<ProviderKind, ModelSlug>;
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER = {
|
||||
codex: {
|
||||
@@ -102,31 +46,12 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER = {
|
||||
"5.3-spark": "gpt-5.3-codex-spark",
|
||||
"gpt-5.3-spark": "gpt-5.3-codex-spark",
|
||||
},
|
||||
cursor: {
|
||||
composer: "composer-1.5",
|
||||
"composer-1.5": "composer-1.5",
|
||||
"composer-1": "composer-1",
|
||||
"gpt-5.3-codex": "gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark": "gpt-5.3-codex-spark-preview",
|
||||
"gemini-3.1-pro": "gemini-3.1-pro",
|
||||
"claude-4.6-sonnet-thinking": "sonnet-4.6-thinking",
|
||||
"claude-4.6-opus-thinking": "opus-4.6-thinking",
|
||||
"claude-4.5-opus-thinking": "opus-4.5-thinking",
|
||||
"sonnet-4.6-thinking": "sonnet-4.6-thinking",
|
||||
"opus-4.6-thinking": "opus-4.6-thinking",
|
||||
"opus-4.5-thinking": "opus-4.5-thinking",
|
||||
},
|
||||
} as const satisfies Record<keyof typeof MODEL_OPTIONS_BY_PROVIDER, Record<string, ModelSlug>>;
|
||||
} as const satisfies Record<ProviderKind, Record<string, ModelSlug>>;
|
||||
|
||||
export const REASONING_EFFORT_OPTIONS_BY_PROVIDER = {
|
||||
codex: CODEX_REASONING_EFFORT_OPTIONS,
|
||||
cursor: [],
|
||||
} as const satisfies Record<
|
||||
keyof typeof MODEL_OPTIONS_BY_PROVIDER,
|
||||
readonly CodexReasoningEffort[]
|
||||
>;
|
||||
} as const satisfies Record<ProviderKind, readonly CodexReasoningEffort[]>;
|
||||
|
||||
export const DEFAULT_REASONING_EFFORT_BY_PROVIDER = {
|
||||
codex: "high",
|
||||
cursor: null,
|
||||
} as const satisfies Record<keyof typeof MODEL_OPTIONS_BY_PROVIDER, CodexReasoningEffort | null>;
|
||||
} as const satisfies Record<ProviderKind, CodexReasoningEffort | null>;
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
OrchestrationSession,
|
||||
ProjectCreateCommand,
|
||||
ThreadTurnStartCommand,
|
||||
ThreadCreatedPayload,
|
||||
ThreadTurnDiff,
|
||||
ThreadTurnStartRequestedPayload,
|
||||
} from "./orchestration";
|
||||
@@ -21,6 +22,7 @@ const decodeThreadTurnStartRequestedPayload = Schema.decodeUnknownEffect(
|
||||
ThreadTurnStartRequestedPayload,
|
||||
);
|
||||
const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession);
|
||||
const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload);
|
||||
|
||||
it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -128,16 +130,34 @@ it.effect("preserves explicit provider and runtime mode in thread.turn.start", (
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.provider, "cursor");
|
||||
assert.strictEqual(parsed.provider, "codex");
|
||||
assert.strictEqual(parsed.runtimeMode, "full-access");
|
||||
assert.strictEqual(parsed.interactionMode, DEFAULT_PROVIDER_INTERACTION_MODE);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread.created runtime mode for historical events", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadCreatedPayload({
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread title",
|
||||
model: "gpt-5.4",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts provider-scoped model options in thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartCommand({
|
||||
@@ -166,26 +186,6 @@ it.effect("accepts provider-scoped model options in thread.turn.start", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts cursor provider in thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartCommand({
|
||||
type: "thread.turn.start",
|
||||
commandId: "cmd-turn-cursor",
|
||||
threadId: "thread-1",
|
||||
message: {
|
||||
messageId: "msg-3",
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "cursor",
|
||||
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, runtime mode, and interaction mode",
|
||||
() =>
|
||||
|
||||
@@ -27,7 +27,7 @@ export const ORCHESTRATION_WS_CHANNELS = {
|
||||
domainEvent: "orchestration.domainEvent",
|
||||
} as const;
|
||||
|
||||
export const ProviderKind = Schema.Literals(["codex", "cursor"]);
|
||||
export const ProviderKind = Schema.Literal("codex");
|
||||
export type ProviderKind = typeof ProviderKind.Type;
|
||||
export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex";
|
||||
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
|
||||
@@ -594,7 +594,7 @@ export const ThreadCreatedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
model: TrimmedNonEmptyString,
|
||||
runtimeMode: RuntimeMode,
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
|
||||
@@ -42,31 +42,6 @@ describe("ProviderSessionStartInput", () => {
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("accepts cursor provider payloads", () => {
|
||||
const parsed = decodeProviderSessionStartInput({
|
||||
threadId: "thread-1",
|
||||
provider: "cursor",
|
||||
cwd: "/tmp/workspace",
|
||||
model: "composer-1.5",
|
||||
modelOptions: {
|
||||
cursor: {
|
||||
thinking: true,
|
||||
},
|
||||
},
|
||||
providerOptions: {
|
||||
cursor: {
|
||||
binaryPath: "/usr/local/bin/agent",
|
||||
},
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(parsed.provider).toBe("cursor");
|
||||
expect(parsed.model).toBe("composer-1.5");
|
||||
expect(parsed.modelOptions?.cursor?.thinking).toBe(true);
|
||||
expect(parsed.providerOptions?.cursor?.binaryPath).toBe("/usr/local/bin/agent");
|
||||
expect(parsed.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ProviderSendTurnInput", () => {
|
||||
|
||||
@@ -50,13 +50,8 @@ const CodexProviderStartOptions = Schema.Struct({
|
||||
homePath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
|
||||
const CursorProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
|
||||
const ProviderStartOptions = Schema.Struct({
|
||||
codex: Schema.optional(CodexProviderStartOptions),
|
||||
cursor: Schema.optional(CursorProviderStartOptions),
|
||||
});
|
||||
|
||||
export const ProviderSessionStartInput = Schema.Struct({
|
||||
|
||||
@@ -20,9 +20,6 @@ const RuntimeEventRawSource = Schema.Literals([
|
||||
"codex.app-server.request",
|
||||
"codex.eventmsg",
|
||||
"codex.sdk.thread-event",
|
||||
"cursor.acp.notification",
|
||||
"cursor.acp.request",
|
||||
"cursor.acp.response",
|
||||
]);
|
||||
export type RuntimeEventRawSource = typeof RuntimeEventRawSource.Type;
|
||||
|
||||
|
||||
@@ -1,24 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CURSOR_MODEL_FAMILY_OPTIONS,
|
||||
CURSOR_REASONING_OPTIONS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
MODEL_OPTIONS,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
} from "../../contracts/src";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, MODEL_OPTIONS_BY_PROVIDER } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getCursorModelFamilyOptions,
|
||||
getModelOptions,
|
||||
getReasoningEffortOptions,
|
||||
normalizeModelSlug,
|
||||
parseCursorModelSelection,
|
||||
resolveCursorModelFromSelection,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "./model";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
@@ -39,98 +28,31 @@ describe("normalizeModelSlug", () => {
|
||||
expect(normalizeModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
|
||||
});
|
||||
|
||||
it("uses provider-specific aliases", () => {
|
||||
expect(normalizeModelSlug("composer", "cursor")).toBe("composer-1.5");
|
||||
expect(normalizeModelSlug("gpt-5.3-codex-spark", "cursor")).toBe(
|
||||
"gpt-5.3-codex-spark-preview",
|
||||
);
|
||||
expect(normalizeModelSlug("gemini-3.1", "cursor")).toBe("gemini-3.1");
|
||||
expect(normalizeModelSlug("claude-4.6-sonnet-thinking", "cursor")).toBe(
|
||||
"sonnet-4.6-thinking",
|
||||
);
|
||||
it("does not leak prototype properties as aliases", () => {
|
||||
expect(normalizeModelSlug("toString")).toBe("toString");
|
||||
expect(normalizeModelSlug("constructor")).toBe("constructor");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveModelSlug", () => {
|
||||
it("returns default only when the model is missing", () => {
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("preserves unknown custom models", () => {
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe(DEFAULT_MODEL);
|
||||
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
expect(resolveModelSlug("custom/internal-model")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("resolves only supported model options", () => {
|
||||
for (const model of MODEL_OPTIONS) {
|
||||
for (const model of MODEL_OPTIONS_BY_PROVIDER.codex) {
|
||||
expect(resolveModelSlug(model.slug)).toBe(model.slug);
|
||||
}
|
||||
});
|
||||
|
||||
it("supports provider-aware resolution", () => {
|
||||
expect(resolveModelSlugForProvider("cursor", undefined)).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.cursor,
|
||||
);
|
||||
expect(resolveModelSlugForProvider("cursor", "composer")).toBe("composer-1.5");
|
||||
expect(resolveModelSlugForProvider("cursor", "gpt-5.3-codex-high-fast")).toBe(
|
||||
"gpt-5.3-codex-high-fast",
|
||||
);
|
||||
expect(resolveModelSlugForProvider("cursor", "claude-sonnet-4-6")).toBe(
|
||||
DEFAULT_MODEL_BY_PROVIDER.cursor,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps codex defaults for backward compatibility", () => {
|
||||
expect(getDefaultModel()).toBe(DEFAULT_MODEL);
|
||||
expect(getModelOptions()).toEqual(MODEL_OPTIONS);
|
||||
expect(getModelOptions("cursor")).toEqual(MODEL_OPTIONS_BY_PROVIDER.cursor);
|
||||
expect(getCursorModelFamilyOptions()).toEqual(CURSOR_MODEL_FAMILY_OPTIONS);
|
||||
});
|
||||
});
|
||||
|
||||
describe("cursor model selection", () => {
|
||||
it("includes the expected cursor reasoning levels and families", () => {
|
||||
expect(CURSOR_REASONING_OPTIONS).toEqual(["low", "normal", "high", "xhigh"]);
|
||||
expect(getCursorModelFamilyOptions().map((option) => option.slug)).toContain("gpt-5.3-codex");
|
||||
expect(getCursorModelFamilyOptions().map((option) => option.slug)).toContain("opus-4.6");
|
||||
});
|
||||
|
||||
it("parses codex reasoning and fast mode variants", () => {
|
||||
expect(parseCursorModelSelection("gpt-5.3-codex-high-fast")).toEqual({
|
||||
family: "gpt-5.3-codex",
|
||||
reasoning: "high",
|
||||
fast: true,
|
||||
thinking: false,
|
||||
});
|
||||
expect(parseCursorModelSelection("gpt-5.2-codex")).toEqual(
|
||||
parseCursorModelSelection(DEFAULT_MODEL_BY_PROVIDER.cursor),
|
||||
);
|
||||
});
|
||||
|
||||
it("parses and resolves thinking variants", () => {
|
||||
expect(parseCursorModelSelection("sonnet-4.6-thinking")).toEqual({
|
||||
family: "sonnet-4.6",
|
||||
reasoning: "normal",
|
||||
fast: false,
|
||||
thinking: true,
|
||||
});
|
||||
expect(
|
||||
resolveCursorModelFromSelection({
|
||||
family: "sonnet-4.6",
|
||||
thinking: true,
|
||||
}),
|
||||
).toBe("sonnet-4.6-thinking");
|
||||
});
|
||||
|
||||
it("resolves codex family selections into concrete model ids", () => {
|
||||
expect(
|
||||
resolveCursorModelFromSelection({
|
||||
family: "gpt-5.3-codex",
|
||||
reasoning: "xhigh",
|
||||
fast: true,
|
||||
}),
|
||||
).toBe("gpt-5.3-codex-xhigh-fast");
|
||||
expect(getDefaultModel()).toBe(DEFAULT_MODEL_BY_PROVIDER.codex);
|
||||
expect(getModelOptions()).toEqual(MODEL_OPTIONS_BY_PROVIDER.codex);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -138,15 +60,10 @@ describe("getReasoningEffortOptions", () => {
|
||||
it("returns codex reasoning options for codex", () => {
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(["xhigh", "high", "medium", "low"]);
|
||||
});
|
||||
|
||||
it("returns no reasoning options for cursor", () => {
|
||||
expect(getReasoningEffortOptions("cursor")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDefaultReasoningEffort", () => {
|
||||
it("returns provider-scoped defaults", () => {
|
||||
expect(getDefaultReasoningEffort("codex")).toBe("high");
|
||||
expect(getDefaultReasoningEffort("cursor")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,233 +1,25 @@
|
||||
import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
CURSOR_MODEL_FAMILY_OPTIONS,
|
||||
CURSOR_REASONING_OPTIONS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
type CodexReasoningEffort,
|
||||
type CursorModelFamily,
|
||||
type CursorModelSlug,
|
||||
type CursorReasoningOption,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
} from "../../contracts/src";
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
type CatalogProvider = keyof typeof MODEL_OPTIONS_BY_PROVIDER;
|
||||
|
||||
type CursorModelCapability = {
|
||||
readonly supportsReasoning: boolean;
|
||||
readonly supportsFast: boolean;
|
||||
readonly supportsThinking: boolean;
|
||||
readonly defaultReasoning: CursorReasoningOption;
|
||||
readonly defaultThinking: boolean;
|
||||
};
|
||||
|
||||
const CURSOR_MODEL_CAPABILITY_BY_FAMILY: Record<CursorModelFamily, CursorModelCapability> = {
|
||||
auto: {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: false,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: false,
|
||||
},
|
||||
"composer-1.5": {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: false,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: false,
|
||||
},
|
||||
"composer-1": {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: false,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: false,
|
||||
},
|
||||
"gpt-5.3-codex": {
|
||||
supportsReasoning: true,
|
||||
supportsFast: true,
|
||||
supportsThinking: false,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: false,
|
||||
},
|
||||
"gpt-5.3-codex-spark-preview": {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: false,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: false,
|
||||
},
|
||||
"opus-4.6": {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: true,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: true,
|
||||
},
|
||||
"opus-4.5": {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: true,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: true,
|
||||
},
|
||||
"sonnet-4.6": {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: true,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: true,
|
||||
},
|
||||
"gemini-3.1-pro": {
|
||||
supportsReasoning: false,
|
||||
supportsFast: false,
|
||||
supportsThinking: false,
|
||||
defaultReasoning: "normal",
|
||||
defaultThinking: false,
|
||||
},
|
||||
};
|
||||
|
||||
function hasModelCatalog(provider: ProviderKind): provider is CatalogProvider {
|
||||
return Object.hasOwn(MODEL_OPTIONS_BY_PROVIDER, provider);
|
||||
}
|
||||
|
||||
const MODEL_SLUG_SET_BY_PROVIDER: Record<CatalogProvider, ReadonlySet<ModelSlug>> = {
|
||||
codex: new Set(MODEL_OPTIONS_BY_PROVIDER.codex.map((option) => option.slug)),
|
||||
cursor: new Set(MODEL_OPTIONS_BY_PROVIDER.cursor.map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const CURSOR_MODEL_FAMILY_SET = new Set<CursorModelFamily>(
|
||||
CURSOR_MODEL_FAMILY_OPTIONS.map((option) => option.slug),
|
||||
);
|
||||
|
||||
export interface CursorModelSelection {
|
||||
readonly family: CursorModelFamily;
|
||||
readonly reasoning: CursorReasoningOption;
|
||||
readonly fast: boolean;
|
||||
readonly thinking: boolean;
|
||||
}
|
||||
|
||||
export function getModelOptions(provider: ProviderKind = "codex") {
|
||||
return hasModelCatalog(provider) ? MODEL_OPTIONS_BY_PROVIDER[provider] : [];
|
||||
}
|
||||
|
||||
export function getCursorModelFamilyOptions() {
|
||||
return CURSOR_MODEL_FAMILY_OPTIONS;
|
||||
}
|
||||
|
||||
export function getCursorModelCapabilities(family: CursorModelFamily) {
|
||||
return CURSOR_MODEL_CAPABILITY_BY_FAMILY[family];
|
||||
}
|
||||
|
||||
function fallbackCursorModelFamily(): CursorModelFamily {
|
||||
const fallback = parseCursorModelSelection(DEFAULT_MODEL_BY_PROVIDER.cursor);
|
||||
return fallback.family;
|
||||
}
|
||||
|
||||
function resolveCursorModelFamily(model: string | null | undefined): CursorModelFamily {
|
||||
const normalized = normalizeModelSlug(model, "cursor");
|
||||
if (!normalized) {
|
||||
return fallbackCursorModelFamily();
|
||||
}
|
||||
|
||||
if (
|
||||
normalized === "gpt-5.3-codex" ||
|
||||
normalized === "gpt-5.3-codex-fast" ||
|
||||
normalized === "gpt-5.3-codex-low" ||
|
||||
normalized === "gpt-5.3-codex-low-fast" ||
|
||||
normalized === "gpt-5.3-codex-high" ||
|
||||
normalized === "gpt-5.3-codex-high-fast" ||
|
||||
normalized === "gpt-5.3-codex-xhigh" ||
|
||||
normalized === "gpt-5.3-codex-xhigh-fast"
|
||||
) {
|
||||
return "gpt-5.3-codex";
|
||||
}
|
||||
|
||||
if (normalized === "sonnet-4.6-thinking") {
|
||||
return "sonnet-4.6";
|
||||
}
|
||||
if (normalized === "opus-4.6-thinking") {
|
||||
return "opus-4.6";
|
||||
}
|
||||
if (normalized === "opus-4.5-thinking") {
|
||||
return "opus-4.5";
|
||||
}
|
||||
|
||||
return CURSOR_MODEL_FAMILY_SET.has(normalized as CursorModelFamily)
|
||||
? (normalized as CursorModelFamily)
|
||||
: fallbackCursorModelFamily();
|
||||
}
|
||||
|
||||
function resolveCursorReasoning(model: CursorModelSlug): CursorReasoningOption {
|
||||
if (model.includes("-xhigh")) return "xhigh";
|
||||
if (model.includes("-high")) return "high";
|
||||
if (model.includes("-low")) return "low";
|
||||
return "normal";
|
||||
}
|
||||
|
||||
export function parseCursorModelSelection(model: string | null | undefined): CursorModelSelection {
|
||||
const family = resolveCursorModelFamily(model);
|
||||
const capability = CURSOR_MODEL_CAPABILITY_BY_FAMILY[family];
|
||||
const normalized = resolveModelSlugForProvider("cursor", model) as CursorModelSlug;
|
||||
|
||||
if (capability.supportsReasoning) {
|
||||
return {
|
||||
family,
|
||||
reasoning: resolveCursorReasoning(normalized),
|
||||
fast: normalized.endsWith("-fast"),
|
||||
thinking: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (capability.supportsThinking) {
|
||||
return {
|
||||
family,
|
||||
reasoning: capability.defaultReasoning,
|
||||
fast: false,
|
||||
thinking: normalized.endsWith("-thinking"),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
family,
|
||||
reasoning: capability.defaultReasoning,
|
||||
fast: false,
|
||||
thinking: capability.defaultThinking,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveCursorModelFromSelection(input: {
|
||||
readonly family: CursorModelFamily;
|
||||
readonly reasoning?: CursorReasoningOption | null;
|
||||
readonly fast?: boolean;
|
||||
readonly thinking?: boolean;
|
||||
}): CursorModelSlug {
|
||||
const family = resolveCursorModelFamily(input.family);
|
||||
const capability = CURSOR_MODEL_CAPABILITY_BY_FAMILY[family];
|
||||
|
||||
if (capability.supportsReasoning) {
|
||||
const reasoning = CURSOR_REASONING_OPTIONS.includes(input.reasoning ?? "normal")
|
||||
? (input.reasoning ?? "normal")
|
||||
: capability.defaultReasoning;
|
||||
const reasoningSuffix = reasoning === "normal" ? "" : `-${reasoning}`;
|
||||
const fastSuffix = input.fast ? "-fast" : "";
|
||||
const candidate = `${family}${reasoningSuffix}${fastSuffix}`;
|
||||
return resolveModelSlugForProvider("cursor", candidate) as CursorModelSlug;
|
||||
}
|
||||
|
||||
if (capability.supportsThinking) {
|
||||
const candidate = input.thinking ? `${family}-thinking` : family;
|
||||
return resolveModelSlugForProvider("cursor", candidate) as CursorModelSlug;
|
||||
}
|
||||
|
||||
return resolveModelSlugForProvider("cursor", family) as CursorModelSlug;
|
||||
return MODEL_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug {
|
||||
return hasModelCatalog(provider) ? DEFAULT_MODEL_BY_PROVIDER[provider] : DEFAULT_MODEL;
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function normalizeModelSlug(
|
||||
@@ -243,12 +35,9 @@ export function normalizeModelSlug(
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!hasModelCatalog(provider)) {
|
||||
return trimmed as ModelSlug;
|
||||
}
|
||||
|
||||
const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record<string, ModelSlug>;
|
||||
return aliases[trimmed] ?? (trimmed as ModelSlug);
|
||||
const aliased = aliases[trimmed];
|
||||
return typeof aliased === "string" ? aliased : (trimmed as ModelSlug);
|
||||
}
|
||||
|
||||
export function resolveModelSlug(
|
||||
@@ -260,11 +49,9 @@ export function resolveModelSlug(
|
||||
return getDefaultModel(provider);
|
||||
}
|
||||
|
||||
if (!hasModelCatalog(provider)) {
|
||||
return getDefaultModel(provider);
|
||||
}
|
||||
|
||||
return MODEL_SLUG_SET_BY_PROVIDER[provider].has(normalized) ? normalized : getDefaultModel(provider);
|
||||
return MODEL_SLUG_SET_BY_PROVIDER[provider].has(normalized)
|
||||
? normalized
|
||||
: getDefaultModel(provider);
|
||||
}
|
||||
|
||||
export function resolveModelSlugForProvider(
|
||||
|
||||
@@ -1,511 +0,0 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import readline from "node:readline";
|
||||
|
||||
const DEFAULT_PROMPT_TIMEOUT_MS = 120_000;
|
||||
const CANCEL_AFTER_MS = 1_500;
|
||||
|
||||
function parseArgv(argv) {
|
||||
const parsed = {
|
||||
outputDir: "",
|
||||
workspace: process.cwd(),
|
||||
model: "",
|
||||
permissionOption: "allow-once",
|
||||
};
|
||||
|
||||
for (let i = 0; i < argv.length; i += 1) {
|
||||
const token = argv[i];
|
||||
const next = argv[i + 1];
|
||||
if ((token === "--output-dir" || token === "-o") && next) {
|
||||
parsed.outputDir = next;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if ((token === "--workspace" || token === "-w") && next) {
|
||||
parsed.workspace = path.resolve(next);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if ((token === "--model" || token === "-m") && next) {
|
||||
parsed.model = next;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (token === "--permission-option" && next) {
|
||||
parsed.permissionOption = next;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function safeJsonParse(line) {
|
||||
try {
|
||||
return { ok: true, value: JSON.parse(line) };
|
||||
} catch (error) {
|
||||
return { ok: false, error };
|
||||
}
|
||||
}
|
||||
|
||||
class AcpProbeClient {
|
||||
#child;
|
||||
#stdoutRl;
|
||||
#stderrRl;
|
||||
#nextId = 1;
|
||||
#closed = false;
|
||||
#pending = new Map();
|
||||
#onMessage;
|
||||
#onServerRequest;
|
||||
|
||||
constructor({ onMessage, onServerRequest }) {
|
||||
this.#onMessage = onMessage;
|
||||
this.#onServerRequest = onServerRequest;
|
||||
|
||||
this.#child = spawn("agent", ["acp"], {
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
NO_COLOR: "1",
|
||||
},
|
||||
});
|
||||
|
||||
this.#stdoutRl = readline.createInterface({ input: this.#child.stdout });
|
||||
this.#stderrRl = readline.createInterface({ input: this.#child.stderr });
|
||||
|
||||
this.#stdoutRl.on("line", (line) => this.#handleStdoutLine(line));
|
||||
this.#stderrRl.on("line", (line) => {
|
||||
this.#onMessage({
|
||||
ts: nowIso(),
|
||||
channel: "stderr",
|
||||
line,
|
||||
});
|
||||
});
|
||||
|
||||
this.#child.once("exit", (code, signal) => {
|
||||
this.#closed = true;
|
||||
const reason = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
|
||||
for (const [id, pending] of this.#pending.entries()) {
|
||||
this.#pending.delete(id);
|
||||
pending.reject(new Error(reason));
|
||||
}
|
||||
this.#onMessage({
|
||||
ts: nowIso(),
|
||||
channel: "lifecycle",
|
||||
event: "exit",
|
||||
code,
|
||||
signal,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.#closed) return;
|
||||
try {
|
||||
this.#child.stdin.end();
|
||||
} catch {
|
||||
// ignored
|
||||
}
|
||||
this.#child.kill("SIGTERM");
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
if (!this.#closed) {
|
||||
this.#child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
|
||||
async send(method, params, { timeoutMs = DEFAULT_PROMPT_TIMEOUT_MS } = {}) {
|
||||
if (this.#closed) {
|
||||
throw new Error("Cannot send: ACP process is already closed.");
|
||||
}
|
||||
const id = this.#nextId;
|
||||
this.#nextId += 1;
|
||||
|
||||
const message = {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
};
|
||||
|
||||
this.#onMessage({
|
||||
ts: nowIso(),
|
||||
channel: "client->server",
|
||||
message,
|
||||
});
|
||||
this.#child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.#pending.delete(id);
|
||||
reject(new Error(`Timed out waiting for response to '${method}' (id=${id}).`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.#pending.set(id, {
|
||||
resolve: (value) => {
|
||||
clearTimeout(timeout);
|
||||
resolve(value);
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
#respond(id, result) {
|
||||
if (this.#closed) return;
|
||||
const message = {
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
result,
|
||||
};
|
||||
this.#onMessage({
|
||||
ts: nowIso(),
|
||||
channel: "client->server",
|
||||
message,
|
||||
});
|
||||
this.#child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
#handleStdoutLine(line) {
|
||||
const parsed = safeJsonParse(line);
|
||||
if (!parsed.ok) {
|
||||
this.#onMessage({
|
||||
ts: nowIso(),
|
||||
channel: "stdout-non-json",
|
||||
line,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const message = parsed.value;
|
||||
this.#onMessage({
|
||||
ts: nowIso(),
|
||||
channel: "server->client",
|
||||
message,
|
||||
});
|
||||
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(message, "id") &&
|
||||
(Object.prototype.hasOwnProperty.call(message, "result") ||
|
||||
Object.prototype.hasOwnProperty.call(message, "error")) &&
|
||||
!Object.prototype.hasOwnProperty.call(message, "method")
|
||||
) {
|
||||
const pending = this.#pending.get(message.id);
|
||||
if (!pending) return;
|
||||
this.#pending.delete(message.id);
|
||||
if (Object.prototype.hasOwnProperty.call(message, "error")) {
|
||||
pending.reject(message.error);
|
||||
return;
|
||||
}
|
||||
pending.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(message, "id") &&
|
||||
Object.prototype.hasOwnProperty.call(message, "method")
|
||||
) {
|
||||
this.#onServerRequest?.(message, (result) => this.#respond(message.id, result));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeTranscript(entries) {
|
||||
const summary = {
|
||||
counts: {
|
||||
notificationsByMethod: {},
|
||||
sessionUpdateByType: {},
|
||||
serverRequestsByMethod: {},
|
||||
permissionDecisions: {},
|
||||
},
|
||||
samples: {
|
||||
initializeResult: null,
|
||||
authenticateResult: null,
|
||||
sessionNewResult: null,
|
||||
sessionPromptResultByScenario: {},
|
||||
sessionUpdateByType: {},
|
||||
serverRequestByMethod: {},
|
||||
},
|
||||
stderr: [],
|
||||
};
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.channel === "stderr") {
|
||||
summary.stderr.push(entry.line);
|
||||
continue;
|
||||
}
|
||||
if (entry.channel !== "server->client") continue;
|
||||
|
||||
const message = entry.message;
|
||||
if (!message || typeof message !== "object") continue;
|
||||
|
||||
if (typeof message.method === "string" && !Object.prototype.hasOwnProperty.call(message, "id")) {
|
||||
summary.counts.notificationsByMethod[message.method] =
|
||||
(summary.counts.notificationsByMethod[message.method] ?? 0) + 1;
|
||||
if (message.method === "session/update") {
|
||||
const updateType = message.params?.update?.sessionUpdate;
|
||||
if (typeof updateType === "string") {
|
||||
summary.counts.sessionUpdateByType[updateType] =
|
||||
(summary.counts.sessionUpdateByType[updateType] ?? 0) + 1;
|
||||
if (!summary.samples.sessionUpdateByType[updateType]) {
|
||||
summary.samples.sessionUpdateByType[updateType] = message;
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (typeof message.method === "string" && Object.prototype.hasOwnProperty.call(message, "id")) {
|
||||
summary.counts.serverRequestsByMethod[message.method] =
|
||||
(summary.counts.serverRequestsByMethod[message.method] ?? 0) + 1;
|
||||
if (!summary.samples.serverRequestByMethod[message.method]) {
|
||||
summary.samples.serverRequestByMethod[message.method] = message;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.channel !== "scenario-result") continue;
|
||||
if (entry.scenario === "initialize" && !summary.samples.initializeResult) {
|
||||
summary.samples.initializeResult = entry.result;
|
||||
continue;
|
||||
}
|
||||
if (entry.scenario === "authenticate" && !summary.samples.authenticateResult) {
|
||||
summary.samples.authenticateResult = entry.result;
|
||||
continue;
|
||||
}
|
||||
if (entry.scenario === "session/new" && !summary.samples.sessionNewResult) {
|
||||
summary.samples.sessionNewResult = entry.result;
|
||||
continue;
|
||||
}
|
||||
if (entry.scenarioName) {
|
||||
summary.samples.sessionPromptResultByScenario[entry.scenarioName] = entry.result;
|
||||
}
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.channel !== "permission-decision") continue;
|
||||
const optionId = entry.optionId;
|
||||
summary.counts.permissionDecisions[optionId] =
|
||||
(summary.counts.permissionDecisions[optionId] ?? 0) + 1;
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
async function run() {
|
||||
const args = parseArgv(process.argv.slice(2));
|
||||
const allowedPermissionOptions = new Set(["allow-once", "allow-always", "reject-once"]);
|
||||
if (!allowedPermissionOptions.has(args.permissionOption)) {
|
||||
throw new Error(
|
||||
`Invalid --permission-option '${args.permissionOption}'. Expected one of: ${Array.from(allowedPermissionOptions).join(", ")}`,
|
||||
);
|
||||
}
|
||||
const stamp = nowIso().replaceAll(":", "-");
|
||||
const outputDir = args.outputDir
|
||||
? path.resolve(args.outputDir)
|
||||
: path.join(process.cwd(), ".tmp", "acp-probe", stamp);
|
||||
await fs.mkdir(outputDir, { recursive: true });
|
||||
|
||||
const transcript = [];
|
||||
const pushEntry = (entry) => transcript.push(entry);
|
||||
|
||||
let activeScenarioName = null;
|
||||
|
||||
const client = new AcpProbeClient({
|
||||
onMessage: (entry) => {
|
||||
if (
|
||||
activeScenarioName &&
|
||||
entry.channel === "server->client" &&
|
||||
entry.message?.method === "session/update"
|
||||
) {
|
||||
transcript.push({ ...entry, scenarioName: activeScenarioName });
|
||||
return;
|
||||
}
|
||||
transcript.push(entry);
|
||||
},
|
||||
onServerRequest: (message, respond) => {
|
||||
if (message.method === "session/request_permission") {
|
||||
const defaultChoice = args.permissionOption;
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "permission-decision",
|
||||
requestId: message.id,
|
||||
optionId: defaultChoice,
|
||||
params: message.params,
|
||||
});
|
||||
respond({
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: defaultChoice,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
respond({
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "deny",
|
||||
},
|
||||
});
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "server-request-unhandled",
|
||||
method: message.method,
|
||||
requestId: message.id,
|
||||
params: message.params,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const initializeResult = await client.send("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
},
|
||||
clientInfo: {
|
||||
name: "t3-cursor-acp-probe",
|
||||
version: "0.1.0",
|
||||
},
|
||||
});
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "scenario-result",
|
||||
scenario: "initialize",
|
||||
result: initializeResult,
|
||||
});
|
||||
|
||||
const authenticateResult = await client.send("authenticate", {
|
||||
methodId: "cursor_login",
|
||||
});
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "scenario-result",
|
||||
scenario: "authenticate",
|
||||
result: authenticateResult,
|
||||
});
|
||||
|
||||
const sessionParams = {
|
||||
cwd: args.workspace,
|
||||
mcpServers: [],
|
||||
...(args.model ? { model: args.model } : {}),
|
||||
};
|
||||
const sessionResult = await client.send("session/new", sessionParams);
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "scenario-result",
|
||||
scenario: "session/new",
|
||||
result: sessionResult,
|
||||
});
|
||||
|
||||
const sessionId = sessionResult?.sessionId;
|
||||
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
||||
throw new Error(`Missing sessionId from session/new response: ${JSON.stringify(sessionResult)}`);
|
||||
}
|
||||
|
||||
const scenarios = [
|
||||
{
|
||||
name: "hello",
|
||||
prompt: "Say hello in one sentence.",
|
||||
},
|
||||
{
|
||||
name: "tooling",
|
||||
prompt:
|
||||
"Use tools to run `pwd` and then `ls -1 | head -n 8`, and summarize what you found in one paragraph.",
|
||||
},
|
||||
{
|
||||
name: "cancel",
|
||||
prompt:
|
||||
"Think for a while and draft a long detailed migration plan with at least 20 bullet points before answering.",
|
||||
cancelAfterMs: CANCEL_AFTER_MS,
|
||||
},
|
||||
];
|
||||
|
||||
for (const scenario of scenarios) {
|
||||
activeScenarioName = scenario.name;
|
||||
const promptParams = {
|
||||
sessionId,
|
||||
prompt: [{ type: "text", text: scenario.prompt }],
|
||||
};
|
||||
|
||||
const promptPromise = client.send("session/prompt", promptParams, {
|
||||
timeoutMs: DEFAULT_PROMPT_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
if (scenario.cancelAfterMs) {
|
||||
setTimeout(() => {
|
||||
client
|
||||
.send("session/cancel", { sessionId }, { timeoutMs: 15_000 })
|
||||
.then((cancelResult) => {
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "scenario-result",
|
||||
scenario: "session/cancel",
|
||||
scenarioName: scenario.name,
|
||||
result: cancelResult,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "scenario-error",
|
||||
scenario: "session/cancel",
|
||||
scenarioName: scenario.name,
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: typeof error === "string"
|
||||
? error
|
||||
: JSON.stringify(error),
|
||||
});
|
||||
});
|
||||
}, scenario.cancelAfterMs);
|
||||
}
|
||||
|
||||
const promptResult = await promptPromise;
|
||||
pushEntry({
|
||||
ts: nowIso(),
|
||||
channel: "scenario-result",
|
||||
scenario: "session/prompt",
|
||||
scenarioName: scenario.name,
|
||||
result: promptResult,
|
||||
});
|
||||
activeScenarioName = null;
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
|
||||
const summary = summarizeTranscript(transcript);
|
||||
const transcriptPath = path.join(outputDir, "transcript.ndjson");
|
||||
const summaryPath = path.join(outputDir, "summary.json");
|
||||
|
||||
await fs.writeFile(
|
||||
transcriptPath,
|
||||
`${transcript.map((entry) => JSON.stringify(entry)).join("\n")}\n`,
|
||||
"utf8",
|
||||
);
|
||||
await fs.writeFile(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");
|
||||
|
||||
process.stdout.write(`ACP probe complete.\n`);
|
||||
process.stdout.write(` outputDir: ${outputDir}\n`);
|
||||
process.stdout.write(` transcript: ${transcriptPath}\n`);
|
||||
process.stdout.write(` summary: ${summaryPath}\n`);
|
||||
}
|
||||
|
||||
run().catch((error) => {
|
||||
process.stderr.write(`ACP probe failed: ${String(error)}\n`);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
Reference in new issue
Block a user