Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89c6025328 | ||
|
|
8ac57f7944 | ||
|
|
29cb917ac4 | ||
|
|
9c64f12ea0 | ||
|
|
0f184c28b0 | ||
|
|
a3b1df5224 | ||
|
|
4e0c003e78 | ||
|
|
60387f67e9 | ||
|
|
ce94feeea1 | ||
|
|
39ca3ee858 | ||
|
|
52a6067802 | ||
|
|
721b6b4c6f | ||
|
|
40009735ee | ||
|
|
df9d34004f |
No files matched your search
@@ -5,7 +5,7 @@ on:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
schedule:
|
||||
- cron: "0 9 * * *"
|
||||
- cron: "0 */3 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
@@ -26,8 +26,45 @@ permissions:
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: ubuntu-24.04
|
||||
outputs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
run: |
|
||||
last_nightly_tag=$(git tag --list 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
if [[ -z "$last_nightly_tag" ]]; then
|
||||
echo "No previous nightly tag found. Proceeding with release."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
|
||||
head_sha=$(git rev-parse HEAD)
|
||||
|
||||
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
|
||||
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
|
||||
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
preflight:
|
||||
name: Preflight
|
||||
needs: [check_changes]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
@@ -134,6 +171,7 @@ jobs:
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
@@ -156,7 +194,7 @@ jobs:
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022 # blacksmith-32vcpu-windows-2025
|
||||
runner: blacksmith-32vcpu-windows-2025
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
@@ -188,6 +226,23 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$installPath = & $vswhere -products * -latest -property installationPath
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
Write-Error "Visual Studio Installer failed with exit code $code"
|
||||
exit $code
|
||||
}
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
@@ -299,6 +354,7 @@ jobs:
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
@@ -333,7 +389,8 @@ jobs:
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -341,11 +398,19 @@ jobs:
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -434,7 +499,7 @@ jobs:
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: needs.preflight.outputs.release_channel == 'stable'
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
|
||||
needs: [preflight, release]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
|
||||
describe("waitForBackendStartupReady", () => {
|
||||
it("falls back to the HTTP probe when no listening signal exists", async () => {
|
||||
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
const cancelHttpWait = vi.fn();
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("http");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the listening signal and cancels the HTTP probe", async () => {
|
||||
let rejectHttpWait: ((error: unknown) => void) | null = null;
|
||||
const waitForHttpReady = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((_resolve, reject) => {
|
||||
rejectHttpWait = reject;
|
||||
}),
|
||||
);
|
||||
const cancelHttpWait = vi.fn(() => {
|
||||
rejectHttpWait?.(new BackendReadinessAbortedError());
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.resolve(),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("listening");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects when the listening signal fails before HTTP readiness", async () => {
|
||||
const error = new Error("backend exited");
|
||||
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.reject(error),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait: vi.fn(),
|
||||
}),
|
||||
).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,56 @@
|
||||
import { isBackendReadinessAborted } from "./backendReadiness.ts";
|
||||
|
||||
export interface WaitForBackendStartupReadyOptions {
|
||||
readonly listeningPromise?: Promise<void> | null;
|
||||
readonly waitForHttpReady: () => Promise<void>;
|
||||
readonly cancelHttpWait: () => void;
|
||||
}
|
||||
|
||||
export async function waitForBackendStartupReady(
|
||||
options: WaitForBackendStartupReadyOptions,
|
||||
): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = options.waitForHttpReady();
|
||||
const listeningPromise = options.listeningPromise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
options.cancelHttpWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
+11
-48
@@ -57,6 +57,7 @@ import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure.ts";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
|
||||
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
@@ -459,51 +460,13 @@ function cancelBackendReadinessWait(): void {
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
return await waitForBackendStartupReady({
|
||||
listeningPromise: backendListeningDetector?.promise ?? null,
|
||||
waitForHttpReady: () =>
|
||||
waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
}),
|
||||
cancelHttpWait: cancelBackendReadinessWait,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2119,9 +2082,9 @@ async function bootstrap(): Promise<void> {
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
void waitForBackendHttpReady(backendHttpUrl)
|
||||
.then(() => {
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
void waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -58,6 +58,7 @@ import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -351,6 +352,12 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => Effect.void,
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
@@ -42,6 +43,7 @@
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
#!/usr/bin/env bun
|
||||
import { appendFileSync } from "node:fs";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as EffectAcpAgent from "effect-acp/agent";
|
||||
import * as AcpError from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/schema";
|
||||
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
}
|
||||
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
logExit("SIGINT");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("exit", (code) => {
|
||||
logExit(`exit:${code}`);
|
||||
});
|
||||
|
||||
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
if (parameterizedModelPicker) {
|
||||
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentModeId,
|
||||
options: availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
...(mode.description ? { description: mode.description } : {}),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ value: "claude-opus-4-6", name: "Opus 4.6" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
switch (currentModelId) {
|
||||
case "gpt-5.4":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "none", name: "None" },
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "extra-high", name: "Extra High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "context",
|
||||
name: "Context",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: currentContext,
|
||||
options: [
|
||||
{ value: "272k", name: "272K" },
|
||||
{ value: "1m", name: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "composer-2":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "claude-opus-4-6":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
category: "model_config",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
];
|
||||
default:
|
||||
return baseOptions;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select" as const,
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
|
||||
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
description: "Request permission before making any changes",
|
||||
},
|
||||
{
|
||||
id: "architect",
|
||||
name: "Architect",
|
||||
description: "Design and plan software systems without implementation",
|
||||
},
|
||||
{
|
||||
id: "code",
|
||||
name: "Code",
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
|
||||
function modeState(): AcpSchema.SessionModeState {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
|
||||
yield* agent.handleInitialize((request) =>
|
||||
Effect.sync(() => {
|
||||
parameterizedModelPicker =
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionConfigOption((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (exitOnSetConfigOption) {
|
||||
return yield* Effect.sync(() => {
|
||||
process.exit(7);
|
||||
});
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
"Mock invalid params for session/set_config_option",
|
||||
{
|
||||
method: "session/set_config_option",
|
||||
params: request,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (request.configId === "mode" && typeof request.value === "string") {
|
||||
currentModeId = request.value;
|
||||
}
|
||||
if (request.configId === "model" && typeof request.value === "string") {
|
||||
currentModelId = request.value;
|
||||
}
|
||||
if (request.configId === "reasoning" && typeof request.value === "string") {
|
||||
currentReasoning = request.value;
|
||||
}
|
||||
if (request.configId === "context" && typeof request.value === "string") {
|
||||
currentContext = request.value;
|
||||
}
|
||||
if (request.configId === "fast") {
|
||||
currentFast = request.value === true || request.value === "true";
|
||||
}
|
||||
return {
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "before tool" },
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["echo", "hello"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "hello",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "after tool" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
title: "`cat server/package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist: cat server/package.json",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
|
||||
const cancelled =
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: cancelled ? "cancelled" : "end_turn" };
|
||||
}
|
||||
|
||||
if (emitGenericToolPlaceholders) {
|
||||
const toolCallId = "tool-call-generic-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Read File",
|
||||
kind: "read",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
content: "package.json\n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
title: "Question",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Which scope?",
|
||||
options: [
|
||||
{ id: "workspace", label: "Workspace" },
|
||||
{ id: "session", label: "Session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: promptResponseText ?? "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
|
||||
const nextModeId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"modeId" in params &&
|
||||
typeof params.modeId === "string"
|
||||
? params.modeId
|
||||
: typeof params === "object" &&
|
||||
params !== null &&
|
||||
"mode" in params &&
|
||||
typeof params.mode === "string"
|
||||
? params.mode
|
||||
: undefined;
|
||||
const requestedSessionId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"sessionId" in params &&
|
||||
typeof params.sessionId === "string"
|
||||
? params.sessionId
|
||||
: sessionId;
|
||||
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
return agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.as({}));
|
||||
}
|
||||
|
||||
return Effect.succeed({});
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EffectAcpAgent.layerStdio(
|
||||
requestLogPath
|
||||
? {
|
||||
logIncoming: true,
|
||||
logger: (event) => {
|
||||
if (event.direction !== "incoming" || event.stage !== "raw") {
|
||||
return Effect.void;
|
||||
}
|
||||
if (typeof event.payload !== "string") {
|
||||
return Effect.void;
|
||||
}
|
||||
const payload = event.payload;
|
||||
return Effect.sync(() => {
|
||||
appendFileSync(
|
||||
requestLogPath,
|
||||
payload.endsWith("\n") ? payload : `${payload}\n`,
|
||||
"utf8",
|
||||
);
|
||||
});
|
||||
},
|
||||
}
|
||||
: {},
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
NodeRuntime.runMain(program);
|
||||
@@ -0,0 +1,435 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import process from "node:process";
|
||||
import readline from "node:readline";
|
||||
|
||||
type JsonPrimitive = null | boolean | number | string;
|
||||
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
type JsonRpcId = number | string;
|
||||
|
||||
type JsonRpcMessage = {
|
||||
jsonrpc?: string;
|
||||
id?: JsonRpcId;
|
||||
method?: string;
|
||||
params?: JsonValue;
|
||||
result?: JsonValue;
|
||||
error?: JsonValue;
|
||||
headers?: JsonValue;
|
||||
};
|
||||
|
||||
type SelectLeafOption = {
|
||||
value: string;
|
||||
label?: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
type SelectGroupOption = {
|
||||
label?: string;
|
||||
name?: string;
|
||||
options: SelectLeafOption[];
|
||||
};
|
||||
|
||||
type SessionConfigOption = {
|
||||
id: string;
|
||||
name?: string;
|
||||
category?: string;
|
||||
type?: string;
|
||||
options?: Array<SelectLeafOption | SelectGroupOption>;
|
||||
};
|
||||
|
||||
type SessionNewResult = {
|
||||
sessionId: string;
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type SetConfigResult = {
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type PendingRequest = {
|
||||
method: string;
|
||||
resolve: (value: JsonValue | undefined) => void;
|
||||
reject: (error: Error) => void;
|
||||
};
|
||||
|
||||
const targetCwd = process.argv[2] ?? process.cwd();
|
||||
const targetModel = process.argv[3] ?? "gpt-5.4";
|
||||
const promptText = process.argv[4] ?? "helo";
|
||||
const targetReasoning = process.env.CURSOR_REASONING ?? "";
|
||||
const targetContext = process.env.CURSOR_CONTEXT ?? "";
|
||||
const targetFast = process.env.CURSOR_FAST ?? "";
|
||||
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
|
||||
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
|
||||
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
|
||||
|
||||
function logSection(title: string, value: unknown) {
|
||||
process.stdout.write(`\n=== ${title} ===\n`);
|
||||
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function fail(message: string): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function asString(value: JsonValue | undefined): string | null {
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
|
||||
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
for (const entry of option.options) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
if ("value" in entry && typeof entry.value === "string") {
|
||||
values.push(entry.value);
|
||||
continue;
|
||||
}
|
||||
if ("options" in entry && Array.isArray(entry.options)) {
|
||||
for (const nested of entry.options) {
|
||||
if (nested && typeof nested === "object" && typeof nested.value === "string") {
|
||||
values.push(nested.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function findConfigOption(
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
): SessionConfigOption | undefined {
|
||||
return configOptions.find(predicate);
|
||||
}
|
||||
|
||||
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
|
||||
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
|
||||
return haystack.includes(keyword.toLowerCase());
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
class JsonRpcChild {
|
||||
readonly child: ChildProcessWithoutNullStreams;
|
||||
readonly pending = new Map<JsonRpcId, PendingRequest>();
|
||||
nextId = 1;
|
||||
closed = false;
|
||||
|
||||
constructor(bin: string, args: string[], cwd: string) {
|
||||
this.child = spawn(bin, args, {
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
this.child.on("exit", (code, signal) => {
|
||||
this.closed = true;
|
||||
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
this.child.on("error", (error) => {
|
||||
this.closed = true;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(error);
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
const stdout = readline.createInterface({ input: this.child.stdout });
|
||||
stdout.on("line", (line) => {
|
||||
void this.handleStdoutLine(line);
|
||||
});
|
||||
|
||||
const stderr = readline.createInterface({ input: this.child.stderr });
|
||||
stderr.on("line", (line) => {
|
||||
process.stdout.write(`[stderr] ${line}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
write(message: JsonRpcMessage) {
|
||||
if (this.closed) {
|
||||
fail("ACP process is already closed.");
|
||||
}
|
||||
const payload = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
headers: [],
|
||||
...message,
|
||||
});
|
||||
process.stdout.write(`>>> ${payload}\n`);
|
||||
this.child.stdin.write(`${payload}\n`);
|
||||
}
|
||||
|
||||
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
|
||||
const id = this.nextId++;
|
||||
|
||||
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(id, {
|
||||
method,
|
||||
resolve: (value) => {
|
||||
clearTimeout(timeout);
|
||||
resolve(value);
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
this.write({
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
});
|
||||
|
||||
return responsePromise;
|
||||
}
|
||||
|
||||
notify(method: string, params: JsonValue) {
|
||||
this.write({
|
||||
method,
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
respond(id: JsonRpcId, result: JsonValue) {
|
||||
this.write({
|
||||
id,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
respondError(id: JsonRpcId, code: number, message: string) {
|
||||
this.write({
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async handleStdoutLine(line: string) {
|
||||
if (line.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(`<<< ${line}\n`);
|
||||
|
||||
let message: JsonRpcMessage;
|
||||
try {
|
||||
message = JSON.parse(line) as JsonRpcMessage;
|
||||
} catch (error) {
|
||||
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && !message.method) {
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
if (typeof message.error !== "undefined") {
|
||||
pending.reject(
|
||||
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
|
||||
this.respond(message.id, {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && message.id !== "") {
|
||||
this.respondError(
|
||||
message.id,
|
||||
-32601,
|
||||
`Unhandled server request: ${message.method ?? "unknown"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.child.kill("SIGTERM");
|
||||
await sleep(250);
|
||||
if (!this.closed) {
|
||||
this.child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function setSelectOptionIfAdvertised(
|
||||
rpc: JsonRpcChild,
|
||||
sessionId: string,
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
value: string,
|
||||
label: string,
|
||||
) {
|
||||
if (value.length === 0) {
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const option = findConfigOption(configOptions, predicate);
|
||||
const values = flattenSelectValues(option);
|
||||
if (!option || !values.includes(value)) {
|
||||
logSection(`SKIP_${label}`, {
|
||||
requestedValue: value,
|
||||
availableValues: values,
|
||||
});
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const response = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: option.id,
|
||||
value,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
|
||||
logSection(`SET_${label}_RESPONSE`, response);
|
||||
return response?.configOptions ?? configOptions;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
|
||||
|
||||
try {
|
||||
const initializeResponse = await rpc.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: {
|
||||
name: "cursor-acp-model-mismatch-probe",
|
||||
version: "0.0.0",
|
||||
},
|
||||
});
|
||||
logSection("INITIALIZE_RESPONSE", initializeResponse);
|
||||
|
||||
const authenticateResponse = await rpc.request("authenticate", {
|
||||
methodId: "cursor_login",
|
||||
});
|
||||
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
|
||||
|
||||
const sessionResponse = (await rpc.request("session/new", {
|
||||
cwd: targetCwd,
|
||||
mcpServers: [],
|
||||
})) as SessionNewResult;
|
||||
logSection("SESSION_NEW_RESPONSE", sessionResponse);
|
||||
|
||||
const sessionId = asString(sessionResponse.sessionId);
|
||||
if (!sessionId) {
|
||||
fail("session/new did not return a sessionId.");
|
||||
}
|
||||
|
||||
let configOptions = sessionResponse.configOptions ?? [];
|
||||
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
|
||||
const advertisedModels = flattenSelectValues(modelConfig);
|
||||
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
|
||||
|
||||
if (!modelConfig || modelConfig.type !== "select") {
|
||||
fail("Cursor ACP did not expose a select-type model config option.");
|
||||
}
|
||||
|
||||
if (!advertisedModels.includes(targetModel)) {
|
||||
fail(
|
||||
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const setModelResponse = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: modelConfig.id,
|
||||
value: targetModel,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
logSection("SET_MODEL_RESPONSE", setModelResponse);
|
||||
|
||||
configOptions = setModelResponse?.configOptions ?? configOptions;
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "thought_level",
|
||||
targetReasoning,
|
||||
"REASONING",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
|
||||
targetContext,
|
||||
"CONTEXT",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
|
||||
targetFast,
|
||||
"FAST",
|
||||
);
|
||||
|
||||
const promptResponse = await rpc.request("session/prompt", {
|
||||
sessionId,
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: promptText,
|
||||
},
|
||||
],
|
||||
});
|
||||
logSection("PROMPT_RESPONSE", promptResponse);
|
||||
|
||||
await sleep(promptWaitMs);
|
||||
rpc.notify("session/cancel", { sessionId });
|
||||
} finally {
|
||||
await rpc.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
process.stderr.write(
|
||||
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -19,6 +19,8 @@ import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
|
||||
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -245,6 +247,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
|
||||
@@ -11,7 +11,6 @@ import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
@@ -30,6 +29,7 @@ import {
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { resolveClaudeApiModelId } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
|
||||
@@ -110,7 +110,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveApiModelId(modelSelection),
|
||||
resolveClaudeApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
function shellSingleQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'"'"'`)}'`;
|
||||
}
|
||||
|
||||
const CursorTextGenerationTestLayer = CursorTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-cursor-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeAcpAgentWrapper(dir: string, env: Record<string, string>): string {
|
||||
const binDir = path.join(dir, "bin");
|
||||
const agentPath = path.join(binDir, "agent");
|
||||
mkdirSync(binDir, { recursive: true });
|
||||
writeFileSync(
|
||||
agentPath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
...Object.entries(env).map(([key, value]) => `export ${key}=${shellSingleQuote(value)}`),
|
||||
'if [ "$1" != "acp" ]; then',
|
||||
' printf "%s\\n" "unexpected args: $*" >&2',
|
||||
" exit 11",
|
||||
"fi",
|
||||
`exec bun ${JSON.stringify(mockAgentPath)}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
chmodSync(agentPath, 0o755);
|
||||
return agentPath;
|
||||
}
|
||||
|
||||
function withFakeAcpAgent<A, E, R>(
|
||||
env: Record<string, string>,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
): Effect.Effect<A, E | ServerSettingsError, R | ServerSettingsService> {
|
||||
return Effect.gen(function* () {
|
||||
const tempDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-acp-"));
|
||||
const agentPath = makeAcpAgentWrapper(tempDir, env);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const previousSettings = yield* serverSettings.getSettings;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
cursor: {
|
||||
binaryPath: agentPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return yield* effect.pipe(
|
||||
Effect.ensuring(
|
||||
serverSettings
|
||||
.updateSettings({
|
||||
providers: {
|
||||
cursor: {
|
||||
binaryPath: previousSettings.providers.cursor.binaryPath,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForFileContent(path: string): Effect.Effect<string> {
|
||||
return Effect.promise(async () => {
|
||||
const deadline = Date.now() + 5_000;
|
||||
for (;;) {
|
||||
try {
|
||||
return readFileSync(path, "utf8");
|
||||
} catch (error) {
|
||||
if (Date.now() >= deadline) {
|
||||
throw error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 25));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
it.layer(CursorTextGenerationTestLayer)("CursorTextGenerationLive", (it) => {
|
||||
it.effect("uses ACP model config options instead of raw CLI model ids", () => {
|
||||
const requestLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-log-"));
|
||||
const requestLogPath = path.join(requestLogDir, "requests.ndjson");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Add generated commit message",
|
||||
body: "- verify cursor acp model config path",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-text-generation",
|
||||
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoning: "xhigh",
|
||||
fastMode: true,
|
||||
contextWindow: "1m",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add generated commit message");
|
||||
expect(generated.body).toBe("- verify cursor acp model config path");
|
||||
|
||||
const requests = readFileSync(requestLogPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => JSON.parse(line) as { method?: string; params?: Record<string, unknown> });
|
||||
|
||||
expect(
|
||||
requests.find((request) => request.method === "initialize")?.params?.clientCapabilities,
|
||||
).toMatchObject({
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
});
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "model" &&
|
||||
request.params?.value === "gpt-5.4",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "reasoning" &&
|
||||
request.params?.value === "extra-high",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "context" &&
|
||||
request.params?.value === "1m",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.some(
|
||||
(request) =>
|
||||
request.method === "session/set_config_option" &&
|
||||
request.params?.configId === "fast" &&
|
||||
request.params?.value === "true",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requests.find((request) => request.method === "session/prompt")?.params?.prompt,
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "text",
|
||||
text: expect.stringContaining("Staged patch:"),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
rmSync(requestLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("accepts json objects with extra assistant text around them", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT:
|
||||
'Sure, here is the JSON:\n```json\n{\n "subject": "Update README dummy comment with attribution and date",\n "body": ""\n}\n```\nDone.',
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-noisy-json",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Update README dummy comment with attribution and date");
|
||||
expect(generated.body).toBe("");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles through Cursor ACP text generation", () =>
|
||||
withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
title: '"Trim reconnect spinner status after resume."',
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix the reconnect spinner after a resumed session.",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Trim reconnect spinner status after resume.");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process after text generation completes", () => {
|
||||
const exitLogDir = mkdtempSync(path.join(os.tmpdir(), "t3code-cursor-text-exit-log-"));
|
||||
const exitLogPath = path.join(exitLogDir, "exit.log");
|
||||
|
||||
return withFakeAcpAgent(
|
||||
{
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
T3_ACP_PROMPT_RESPONSE_TEXT: JSON.stringify({
|
||||
subject: "Close runtime after generation",
|
||||
body: "",
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/cursor-runtime-close",
|
||||
stagedSummary: "M apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
stagedPatch:
|
||||
"diff --git a/apps/server/src/git/Layers/CursorTextGeneration.ts b/apps/server/src/git/Layers/CursorTextGeneration.ts",
|
||||
modelSelection: {
|
||||
provider: "cursor",
|
||||
model: "composer-2",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Close runtime after generation");
|
||||
|
||||
const exitLog = yield* waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("exit:0");
|
||||
|
||||
rmSync(exitLogDir, { recursive: true, force: true });
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
import { Effect, Layer, Option, Ref, Schema } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { CursorModelSelection } from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
type ThreadTitleGenerationResult,
|
||||
type TextGenerationShape,
|
||||
TextGeneration,
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import { sanitizeCommitSubject, sanitizePrTitle, sanitizeThreadTitle } from "../Utils.ts";
|
||||
import {
|
||||
applyCursorAcpModelSelection,
|
||||
makeCursorAcpRuntime,
|
||||
} from "../../provider/acp/CursorAcpSupport.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const CURSOR_TIMEOUT_MS = 180_000;
|
||||
|
||||
function extractJsonObject(raw: string): string {
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const start = trimmed.indexOf("{");
|
||||
if (start < 0) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
let depth = 0;
|
||||
let inString = false;
|
||||
let escaping = false;
|
||||
for (let index = start; index < trimmed.length; index += 1) {
|
||||
const char = trimmed[index];
|
||||
if (inString) {
|
||||
if (escaping) {
|
||||
escaping = false;
|
||||
} else if (char === "\\") {
|
||||
escaping = true;
|
||||
} else if (char === '"') {
|
||||
inString = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "{") {
|
||||
depth += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0) {
|
||||
return trimmed.slice(start, index + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return trimmed.slice(start);
|
||||
}
|
||||
|
||||
function mapCursorAcpError(
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
detail: string,
|
||||
cause: unknown,
|
||||
): TextGenerationError {
|
||||
return new TextGenerationError({
|
||||
operation,
|
||||
detail,
|
||||
...(cause !== undefined ? { cause } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function isTextGenerationError(error: unknown): error is TextGenerationError {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"_tag" in error &&
|
||||
error._tag === "TextGenerationError"
|
||||
);
|
||||
}
|
||||
|
||||
const makeCursorTextGeneration = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||
|
||||
const runCursorJson = <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: CursorModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const cursorSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.cursor,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const outputRef = yield* Ref.make("");
|
||||
const runtime = yield* makeCursorAcpRuntime({
|
||||
cursorSettings,
|
||||
childProcessSpawner: commandSpawner,
|
||||
cwd,
|
||||
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
|
||||
});
|
||||
|
||||
yield* runtime.handleSessionUpdate((notification) => {
|
||||
const update = notification.update;
|
||||
if (update.sessionUpdate !== "agent_message_chunk") {
|
||||
return Effect.void;
|
||||
}
|
||||
const content = update.content;
|
||||
if (content.type !== "text") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Ref.update(outputRef, (current) => current + content.text);
|
||||
});
|
||||
|
||||
const promptResult = yield* Effect.gen(function* () {
|
||||
yield* runtime.start();
|
||||
yield* Effect.ignore(runtime.setMode("ask"));
|
||||
yield* applyCursorAcpModelSelection({
|
||||
runtime,
|
||||
model: modelSelection.model,
|
||||
modelOptions: modelSelection.options,
|
||||
mapError: ({ cause, configId, step }) =>
|
||||
mapCursorAcpError(
|
||||
operation,
|
||||
step === "set-config-option"
|
||||
? `Failed to set Cursor ACP config option "${configId}" for text generation.`
|
||||
: "Failed to set Cursor ACP base model for text generation.",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
|
||||
return yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: prompt }],
|
||||
});
|
||||
}).pipe(
|
||||
Effect.timeoutOption(CURSOR_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor Agent request timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapCursorAcpError(operation, "Cursor ACP request failed.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
const rawResult = (yield* Ref.get(outputRef)).trim();
|
||||
if (!rawResult) {
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
promptResult.stopReason === "cancelled"
|
||||
? "Cursor ACP request was cancelled."
|
||||
: "Cursor Agent returned empty output.",
|
||||
});
|
||||
}
|
||||
|
||||
return yield* Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))(
|
||||
extractJsonObject(rawResult),
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Cursor Agent returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
isTextGenerationError(cause)
|
||||
? cause
|
||||
: mapCursorAcpError(operation, "Cursor ACP text generation failed.", cause),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CursorTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||
"CursorTextGeneration.generatePrContent",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||
"CursorTextGeneration.generateBranchName",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"CursorTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "cursor") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
} satisfies ThreadTitleGenerationResult;
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const CursorTextGenerationLive = Layer.effect(TextGeneration, makeCursorTextGeneration);
|
||||
@@ -40,6 +40,15 @@ function writeTextFile(
|
||||
});
|
||||
}
|
||||
|
||||
function readTextFile(
|
||||
filePath: string,
|
||||
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.readFileString(filePath);
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
@@ -659,8 +668,32 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
"feature/demo",
|
||||
"origin/feature/remote-only",
|
||||
]);
|
||||
expect(result.branches.find((branch) => branch.name === "feature/demo")?.originRef).toBe(
|
||||
"origin/feature/demo",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("matches branch queries against tracked origin refs for local branches", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const { initialBranch } = yield* initRepoWithCommit(tmp);
|
||||
yield* git(tmp, ["remote", "add", "origin", remote]);
|
||||
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({
|
||||
cwd: tmp,
|
||||
query: "origin/",
|
||||
limit: 10,
|
||||
});
|
||||
|
||||
expect(result.branches.map((branch) => branch.name)).toEqual([initialBranch]);
|
||||
expect(result.branches[0]?.originRef).toBe(`origin/${initialBranch}`);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── checkoutGitBranch ──
|
||||
@@ -1361,6 +1394,40 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("can base a new worktree on the latest fetched origin branch", () =>
|
||||
Effect.gen(function* () {
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
const updater = yield* makeTmpDir();
|
||||
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
const { initialBranch } = yield* initRepoWithCommit(source);
|
||||
yield* git(source, ["remote", "add", "origin", remote]);
|
||||
yield* git(source, ["push", "-u", "origin", initialBranch]);
|
||||
|
||||
yield* git(updater, ["clone", remote, "."]);
|
||||
yield* git(updater, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(updater, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(path.join(updater, "README.md"), "latest from origin\n");
|
||||
yield* git(updater, ["add", "README.md"]);
|
||||
yield* git(updater, ["commit", "-m", "advance origin"]);
|
||||
yield* git(updater, ["push", "origin", initialBranch]);
|
||||
|
||||
const wtPath = path.join(source, "wt-origin-latest");
|
||||
yield* (yield* GitCore).createWorktree({
|
||||
cwd: source,
|
||||
branch: initialBranch,
|
||||
newBranch: "wt-origin-latest",
|
||||
fetchLatestOrigin: true,
|
||||
path: wtPath,
|
||||
});
|
||||
|
||||
expect(yield* readTextFile(path.join(wtPath, "README.md"))).toBe("latest from origin\n");
|
||||
|
||||
yield* (yield* GitCore).removeWorktree({ cwd: source, path: wtPath });
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when new branch name already exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -213,7 +213,11 @@ function filterBranchesForListQuery(
|
||||
}
|
||||
|
||||
const normalizedQuery = query.toLowerCase();
|
||||
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
|
||||
return branches.filter(
|
||||
(branch) =>
|
||||
branch.name.toLowerCase().includes(normalizedQuery) ||
|
||||
branch.originRef?.toLowerCase().includes(normalizedQuery) === true,
|
||||
);
|
||||
}
|
||||
|
||||
function paginateBranches(input: {
|
||||
@@ -1868,28 +1872,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
}
|
||||
}
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => ({
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.code === 0
|
||||
? remoteBranchResult.stdout
|
||||
@@ -1925,6 +1907,38 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
})
|
||||
: [];
|
||||
|
||||
const originRemoteRefs = new Set(
|
||||
remoteBranches
|
||||
.filter((branch) => branch.remoteName === "origin")
|
||||
.map((branch) => branch.name),
|
||||
);
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((branch): branch is { name: string; current: boolean } => branch !== null)
|
||||
.map((branch) => {
|
||||
const originRef = `origin/${branch.name}`;
|
||||
return {
|
||||
name: branch.name,
|
||||
current: branch.current,
|
||||
isRemote: false,
|
||||
originRef: originRemoteRefs.has(originRef) ? originRef : undefined,
|
||||
isDefault: branch.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(branch.name) ?? null,
|
||||
};
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const branches = paginateBranches({
|
||||
branches: filterBranchesForListQuery(
|
||||
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
|
||||
@@ -1949,9 +1963,29 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const sanitizedBranch = targetBranch.replace(/\//g, "-");
|
||||
const repoName = path.basename(input.cwd);
|
||||
const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch);
|
||||
let baseRef = input.branch;
|
||||
|
||||
if (input.fetchLatestOrigin) {
|
||||
yield* executeGit(
|
||||
"GitCore.createWorktree.fetchLatestOrigin",
|
||||
input.cwd,
|
||||
[
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
`+refs/heads/${input.branch}:refs/remotes/origin/${input.branch}`,
|
||||
],
|
||||
{
|
||||
fallbackErrorMessage: `git fetch origin ${input.branch} failed`,
|
||||
},
|
||||
);
|
||||
baseRef = `origin/${input.branch}`;
|
||||
}
|
||||
|
||||
const args = input.newBranch
|
||||
? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch]
|
||||
: ["worktree", "add", worktreePath, input.branch];
|
||||
? ["worktree", "add", "-b", input.newBranch, worktreePath, baseRef]
|
||||
: ["worktree", "add", worktreePath, baseRef];
|
||||
|
||||
yield* executeGit("GitCore.createWorktree", input.cwd, args, {
|
||||
fallbackErrorMessage: "git worktree add failed",
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Duration, Effect, Layer } from "effect";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { beforeEach, expect, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const state = {
|
||||
startCalls: [] as string[],
|
||||
promptUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
closeCalls: [] as string[],
|
||||
promptResult: undefined as { data?: { info?: { structured?: unknown } } } | undefined,
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.promptUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.promptResult = undefined;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../../provider/opencodeRuntime.ts", async () => {
|
||||
const actual = await vi.importActual<typeof import("../../provider/opencodeRuntime.ts")>(
|
||||
"../../provider/opencodeRuntime.ts",
|
||||
);
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
const index = runtimeMock.state.startCalls.length + 1;
|
||||
const url = `http://127.0.0.1:${4_300 + index}`;
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
return {
|
||||
url,
|
||||
process: {} as ChildProcess,
|
||||
close: () => {
|
||||
runtimeMock.state.closeCalls.push(url);
|
||||
},
|
||||
};
|
||||
}),
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => ({ data: { id: `${baseUrl}/session` } })),
|
||||
prompt: vi.fn(async () => {
|
||||
runtimeMock.state.promptUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return (
|
||||
runtimeMock.state.promptResult ?? {
|
||||
data: {
|
||||
info: {
|
||||
structured: {
|
||||
subject: "Improve OpenCode reuse",
|
||||
body: "Reuse one server for the full action.",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "opencode" as const,
|
||||
model: "openai/gpt-5",
|
||||
};
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
const OpenCodeTextGenerationTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-opencode-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const OpenCodeTextGenerationExistingServerTestLayer = OpenCodeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-opencode-text-generation-existing-server-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const advanceIdleClock = Effect.gen(function* () {
|
||||
yield* Effect.yieldNow;
|
||||
yield* TestClock.adjust(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS + 1));
|
||||
yield* Effect.yieldNow;
|
||||
});
|
||||
|
||||
it.layer(OpenCodeTextGenerationTestLayer)("OpenCodeTextGenerationLive", (it) => {
|
||||
it.effect("reuses a warm server across back-to-back requests and closes it after idling", () =>
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode"]);
|
||||
expect(runtimeMock.state.promptUrls).toEqual([
|
||||
"http://127.0.0.1:4301",
|
||||
"http://127.0.0.1:4301",
|
||||
]);
|
||||
expect(runtimeMock.state.closeCalls).toEqual([]);
|
||||
|
||||
yield* advanceIdleClock;
|
||||
|
||||
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("starts a new server after the warm server idles out", () =>
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
yield* advanceIdleClock;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual(["fake-opencode", "fake-opencode"]);
|
||||
expect(runtimeMock.state.promptUrls).toEqual([
|
||||
"http://127.0.0.1:4301",
|
||||
"http://127.0.0.1:4302",
|
||||
]);
|
||||
expect(runtimeMock.state.closeCalls).toEqual(["http://127.0.0.1:4301"]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
|
||||
it.effect("returns a typed missing-output error when OpenCode omits info.structured", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.promptResult = { data: {} };
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const error = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
expect(error.message).toContain("OpenCode returned no structured output.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(OpenCodeTextGenerationExistingServerTestLayer)(
|
||||
"OpenCodeTextGenerationLive with configured server URL",
|
||||
(it) => {
|
||||
it.effect("reuses a configured OpenCode server URL without spawning or applying idle TTL", () =>
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/opencode-reuse",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(runtimeMock.state.startCalls).toEqual([]);
|
||||
expect(runtimeMock.state.promptUrls).toEqual([
|
||||
"http://127.0.0.1:9999",
|
||||
"http://127.0.0.1:9999",
|
||||
]);
|
||||
expect(runtimeMock.state.authHeaders).toEqual([
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
|
||||
yield* advanceIdleClock;
|
||||
|
||||
expect(runtimeMock.state.closeCalls).toEqual([]);
|
||||
}).pipe(Effect.provide(TestClock.layer())),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,422 @@
|
||||
import { Duration, Effect, Exit, Fiber, Layer, Schema, Scope } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import {
|
||||
TextGenerationError,
|
||||
type ChatAttachment,
|
||||
type OpenCodeModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "../Prompts.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import {
|
||||
createOpenCodeSdkClient,
|
||||
type OpenCodeServerConnection,
|
||||
type OpenCodeServerProcess,
|
||||
parseOpenCodeModelSlug,
|
||||
startOpenCodeServerProcess,
|
||||
toOpenCodeFileParts,
|
||||
} from "../../provider/opencodeRuntime.ts";
|
||||
|
||||
const OPENCODE_TEXT_GENERATION_IDLE_TTL_MS = 30_000;
|
||||
|
||||
interface SharedOpenCodeTextGenerationServerState {
|
||||
server: OpenCodeServerProcess | null;
|
||||
binaryPath: string | null;
|
||||
activeRequests: number;
|
||||
idleCloseFiber: Fiber.Fiber<void, never> | null;
|
||||
}
|
||||
|
||||
const makeOpenCodeTextGeneration = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
const idleFiberScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
|
||||
Scope.close(scope, Exit.void),
|
||||
);
|
||||
const sharedServerMutex = yield* Semaphore.make(1);
|
||||
const sharedServerState: SharedOpenCodeTextGenerationServerState = {
|
||||
server: null,
|
||||
binaryPath: null,
|
||||
activeRequests: 0,
|
||||
idleCloseFiber: null,
|
||||
};
|
||||
|
||||
const closeSharedServer = (server: OpenCodeServerProcess) => {
|
||||
if (sharedServerState.server === server) {
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
}
|
||||
server.close();
|
||||
};
|
||||
|
||||
const cancelIdleCloseFiber = Effect.fn("cancelIdleCloseFiber")(function* () {
|
||||
const idleCloseFiber = sharedServerState.idleCloseFiber;
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
if (idleCloseFiber !== null) {
|
||||
yield* Fiber.interrupt(idleCloseFiber).pipe(Effect.ignore);
|
||||
}
|
||||
});
|
||||
|
||||
const scheduleIdleClose = Effect.fn("scheduleIdleClose")(function* (
|
||||
server: OpenCodeServerProcess,
|
||||
) {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const fiber = yield* Effect.sleep(Duration.millis(OPENCODE_TEXT_GENERATION_IDLE_TTL_MS)).pipe(
|
||||
Effect.andThen(
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.sync(() => {
|
||||
if (sharedServerState.server !== server || sharedServerState.activeRequests > 0) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.idleCloseFiber = null;
|
||||
closeSharedServer(server);
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.forkIn(idleFiberScope),
|
||||
);
|
||||
sharedServerState.idleCloseFiber = fiber;
|
||||
});
|
||||
|
||||
const acquireSharedServer = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
}) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
|
||||
const existingServer = sharedServerState.server;
|
||||
if (existingServer !== null) {
|
||||
if (
|
||||
sharedServerState.binaryPath !== input.binaryPath &&
|
||||
sharedServerState.activeRequests === 0
|
||||
) {
|
||||
closeSharedServer(existingServer);
|
||||
} else {
|
||||
if (sharedServerState.binaryPath !== input.binaryPath) {
|
||||
yield* Effect.logWarning(
|
||||
"OpenCode shared server binary path mismatch: requested " +
|
||||
input.binaryPath +
|
||||
" but active server uses " +
|
||||
sharedServerState.binaryPath +
|
||||
"; reusing existing server because there are active requests",
|
||||
);
|
||||
}
|
||||
sharedServerState.activeRequests += 1;
|
||||
return existingServer;
|
||||
}
|
||||
}
|
||||
|
||||
const server = yield* Effect.tryPromise({
|
||||
try: () => startOpenCodeServerProcess({ binaryPath: input.binaryPath }),
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: cause instanceof Error ? cause.message : "Failed to start OpenCode server.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
sharedServerState.server = server;
|
||||
sharedServerState.binaryPath = input.binaryPath;
|
||||
sharedServerState.activeRequests = 1;
|
||||
return server;
|
||||
}),
|
||||
);
|
||||
|
||||
const releaseSharedServer = (server: OpenCodeServerProcess) =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
if (sharedServerState.server !== server) {
|
||||
return;
|
||||
}
|
||||
sharedServerState.activeRequests = Math.max(0, sharedServerState.activeRequests - 1);
|
||||
if (sharedServerState.activeRequests === 0) {
|
||||
yield* scheduleIdleClose(server);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
sharedServerMutex.withPermit(
|
||||
Effect.gen(function* () {
|
||||
yield* cancelIdleCloseFiber();
|
||||
const server = sharedServerState.server;
|
||||
sharedServerState.server = null;
|
||||
sharedServerState.binaryPath = null;
|
||||
sharedServerState.activeRequests = 0;
|
||||
if (server !== null) {
|
||||
server.close();
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runOpenCodeJson = Effect.fn("runOpenCodeJson")(function* <S extends Schema.Top>(input: {
|
||||
readonly operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle";
|
||||
readonly cwd: string;
|
||||
readonly prompt: string;
|
||||
readonly outputSchemaJson: S;
|
||||
readonly modelSelection: OpenCodeModelSelection;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
}) {
|
||||
const parsedModel = parseOpenCodeModelSlug(input.modelSelection.model);
|
||||
if (!parsedModel) {
|
||||
return yield* new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: "OpenCode model selection must use the 'provider/model' format.",
|
||||
});
|
||||
}
|
||||
|
||||
const settings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map(
|
||||
(value) =>
|
||||
value.providers?.opencode ?? {
|
||||
enabled: true,
|
||||
binaryPath: "opencode",
|
||||
serverUrl: "",
|
||||
serverPassword: "",
|
||||
customModels: [],
|
||||
},
|
||||
),
|
||||
Effect.orElseSucceed(() => ({
|
||||
enabled: true,
|
||||
binaryPath: "opencode",
|
||||
serverUrl: "",
|
||||
serverPassword: "",
|
||||
customModels: [],
|
||||
})),
|
||||
);
|
||||
|
||||
const fileParts = toOpenCodeFileParts({
|
||||
attachments: input.attachments,
|
||||
resolveAttachmentPath: (attachment) =>
|
||||
resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }),
|
||||
});
|
||||
|
||||
const runAgainstServer = (server: Pick<OpenCodeServerConnection, "url">) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(settings.serverUrl.length > 0 && settings.serverPassword
|
||||
? { serverPassword: settings.serverPassword }
|
||||
: {}),
|
||||
});
|
||||
const session = await client.session.create({
|
||||
title: `T3 Code ${input.operation}`,
|
||||
permission: [{ permission: "*", pattern: "*", action: "deny" }],
|
||||
});
|
||||
if (!session.data) {
|
||||
throw new Error("OpenCode session.create returned no session payload.");
|
||||
}
|
||||
|
||||
const result = await client.session.prompt({
|
||||
sessionID: session.data.id,
|
||||
model: parsedModel,
|
||||
...(input.modelSelection.options?.agent
|
||||
? { agent: input.modelSelection.options.agent }
|
||||
: {}),
|
||||
...(input.modelSelection.options?.variant
|
||||
? { variant: input.modelSelection.options.variant }
|
||||
: {}),
|
||||
format: {
|
||||
type: "json_schema",
|
||||
schema: toJsonSchemaObject(input.outputSchemaJson) as Record<string, unknown>,
|
||||
},
|
||||
parts: [{ type: "text", text: input.prompt }, ...fileParts],
|
||||
});
|
||||
const structured = result.data?.info?.structured;
|
||||
if (structured === undefined) {
|
||||
throw new Error("OpenCode returned no structured output.");
|
||||
}
|
||||
return structured;
|
||||
},
|
||||
catch: (cause) =>
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail:
|
||||
cause instanceof Error ? cause.message : "OpenCode text generation request failed.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
|
||||
const structuredOutput =
|
||||
settings.serverUrl.length > 0
|
||||
? yield* runAgainstServer({ url: settings.serverUrl })
|
||||
: yield* Effect.acquireUseRelease(
|
||||
acquireSharedServer({
|
||||
binaryPath: settings.binaryPath,
|
||||
operation: input.operation,
|
||||
}),
|
||||
runAgainstServer,
|
||||
releaseSharedServer,
|
||||
);
|
||||
|
||||
return yield* Schema.decodeUnknownEffect(input.outputSchemaJson)(structuredOutput).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: input.operation,
|
||||
detail: "OpenCode returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generateCommitMessage",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildCommitMessagePrompt({
|
||||
branch: input.branch,
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generatePrContent",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildPrContentPrompt({
|
||||
baseBranch: input.baseBranch,
|
||||
headBranch: input.headBranch,
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizePrTitle(generated.title),
|
||||
body: generated.body.trim(),
|
||||
};
|
||||
});
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generateBranchName",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
|
||||
"OpenCodeTextGeneration.generateThreadTitle",
|
||||
)(function* (input) {
|
||||
if (input.modelSelection.provider !== "opencode") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const { prompt, outputSchema } = buildThreadTitlePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
return {
|
||||
title: sanitizeThreadTitle(generated.title),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
generatePrContent,
|
||||
generateBranchName,
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const OpenCodeTextGenerationLive = Layer.effect(TextGeneration, makeOpenCodeTextGeneration);
|
||||
@@ -18,6 +18,8 @@ import {
|
||||
} from "../Services/TextGeneration.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
import { CursorTextGenerationLive } from "./CursorTextGeneration.ts";
|
||||
import { OpenCodeTextGenerationLive } from "./OpenCodeTextGeneration.ts";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal service tags so both concrete layers can coexist.
|
||||
@@ -31,6 +33,14 @@ class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>(
|
||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
||||
) {}
|
||||
|
||||
class CursorTextGen extends Context.Service<CursorTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/CursorTextGen",
|
||||
) {}
|
||||
|
||||
class OpenCodeTextGen extends Context.Service<OpenCodeTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/OpenCodeTextGen",
|
||||
) {}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Routing implementation
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -38,9 +48,17 @@ class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>(
|
||||
const makeRoutingTextGeneration = Effect.gen(function* () {
|
||||
const codex = yield* CodexTextGen;
|
||||
const claude = yield* ClaudeTextGen;
|
||||
const cursor = yield* CursorTextGen;
|
||||
const openCode = yield* OpenCodeTextGen;
|
||||
|
||||
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
|
||||
provider === "claudeAgent" ? claude : codex;
|
||||
provider === "claudeAgent"
|
||||
? claude
|
||||
: provider === "opencode"
|
||||
? openCode
|
||||
: provider === "cursor"
|
||||
? cursor
|
||||
: codex;
|
||||
|
||||
return {
|
||||
generateCommitMessage: (input) =>
|
||||
@@ -67,7 +85,28 @@ const InternalClaudeLayer = Layer.effect(
|
||||
}),
|
||||
).pipe(Layer.provide(ClaudeTextGenerationLive));
|
||||
|
||||
const InternalCursorLayer = Layer.effect(
|
||||
CursorTextGen,
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* TextGeneration;
|
||||
return svc;
|
||||
}),
|
||||
).pipe(Layer.provide(CursorTextGenerationLive));
|
||||
|
||||
const InternalOpenCodeLayer = Layer.effect(
|
||||
OpenCodeTextGen,
|
||||
Effect.gen(function* () {
|
||||
const svc = yield* TextGeneration;
|
||||
return svc;
|
||||
}),
|
||||
).pipe(Layer.provide(OpenCodeTextGenerationLive));
|
||||
|
||||
export const RoutingTextGenerationLive = Layer.effect(
|
||||
TextGeneration,
|
||||
makeRoutingTextGeneration,
|
||||
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
|
||||
).pipe(
|
||||
Layer.provide(InternalCodexLayer),
|
||||
Layer.provide(InternalClaudeLayer),
|
||||
Layer.provide(InternalCursorLayer),
|
||||
Layer.provide(InternalOpenCodeLayer),
|
||||
);
|
||||
@@ -13,7 +13,7 @@ import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
import type { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
/** Providers that support git text generation (commit messages, PR content, branch names). */
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent";
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "opencode";
|
||||
|
||||
export interface CommitMessageGenerationInput {
|
||||
cwd: string;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../Services/OrchestrationReactor.ts";
|
||||
import { makeOrchestrationReactor } from "./OrchestrationReactor.ts";
|
||||
|
||||
@@ -17,7 +18,7 @@ describe("OrchestrationReactor", () => {
|
||||
runtime = null;
|
||||
});
|
||||
|
||||
it("starts provider ingestion, provider command, and checkpoint reactors", async () => {
|
||||
it("starts provider ingestion, provider command, checkpoint, and thread deletion reactors", async () => {
|
||||
const started: string[] = [];
|
||||
|
||||
runtime = ManagedRuntime.make(
|
||||
@@ -49,10 +50,19 @@ describe("OrchestrationReactor", () => {
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => {
|
||||
started.push("thread-deletion-reactor");
|
||||
return Effect.void;
|
||||
},
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor));
|
||||
const reactor = await runtime!.runPromise(Effect.service(OrchestrationReactor));
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
|
||||
|
||||
@@ -60,6 +70,7 @@ describe("OrchestrationReactor", () => {
|
||||
"provider-runtime-ingestion",
|
||||
"provider-command-reactor",
|
||||
"checkpoint-reactor",
|
||||
"thread-deletion-reactor",
|
||||
]);
|
||||
|
||||
await Effect.runPromise(Scope.close(scope, Exit.void));
|
||||
|
||||
@@ -7,16 +7,19 @@ import {
|
||||
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
|
||||
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ThreadDeletionReactor } from "../Services/ThreadDeletionReactor.ts";
|
||||
|
||||
export const makeOrchestrationReactor = Effect.gen(function* () {
|
||||
const providerRuntimeIngestion = yield* ProviderRuntimeIngestionService;
|
||||
const providerCommandReactor = yield* ProviderCommandReactor;
|
||||
const checkpointReactor = yield* CheckpointReactor;
|
||||
const threadDeletionReactor = yield* ThreadDeletionReactor;
|
||||
|
||||
const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* providerRuntimeIngestion.start();
|
||||
yield* providerCommandReactor.start();
|
||||
yield* checkpointReactor.start();
|
||||
yield* threadDeletionReactor.start();
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -266,7 +266,7 @@ describe("ProviderCommandReactor", () => {
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
runtime = ManagedRuntime.make(layer);
|
||||
|
||||
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
|
||||
const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor));
|
||||
@@ -750,6 +750,57 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
@@ -802,57 +853,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-unsupported-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-unsupported-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1100,6 +1100,71 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
harness.startSession.mockImplementationOnce(
|
||||
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("rejects provider changes after a thread is already bound to a session provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1172,71 +1237,6 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-initial-full-access-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-restart-failure-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
harness.startSession.mockImplementationOnce(
|
||||
(_: unknown, __: unknown) => Effect.fail(new Error("simulated restart failure")) as never,
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.make("cmd-runtime-mode-set-restart-failure"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await harness.drain();
|
||||
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -89,9 +89,16 @@ function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolea
|
||||
: false;
|
||||
}
|
||||
|
||||
function findProviderAdapterRequestError(
|
||||
cause: Cause.Cause<ProviderServiceError>,
|
||||
): ProviderAdapterRequestError | undefined {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
return Schema.is(ProviderAdapterRequestError)(failReason?.error) ? failReason.error : undefined;
|
||||
}
|
||||
|
||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending approval request") ||
|
||||
@@ -106,8 +113,8 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
||||
}
|
||||
|
||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
||||
}
|
||||
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
|
||||
@@ -198,6 +205,17 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
|
||||
const failReason = cause.reasons.find(Cause.isFailReason);
|
||||
const providerError = Schema.is(ProviderAdapterRequestError)(failReason?.error)
|
||||
? failReason.error
|
||||
: undefined;
|
||||
if (providerError) {
|
||||
return providerError.detail;
|
||||
}
|
||||
return Cause.pretty(cause);
|
||||
};
|
||||
|
||||
const setThreadSession = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly session: OrchestrationSession;
|
||||
@@ -211,7 +229,30 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
|
||||
const setThreadSessionErrorOnTurnStartFailure = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
const session = thread?.session;
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
yield* setThreadSession({
|
||||
threadId: input.threadId,
|
||||
session: {
|
||||
...session,
|
||||
status: session.status === "stopped" ? "stopped" : "ready",
|
||||
activeTurnId: null,
|
||||
lastError: input.detail,
|
||||
updatedAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
return readModel.threads.find((entry) => entry.id === threadId);
|
||||
});
|
||||
@@ -247,7 +288,7 @@ const make = Effect.gen(function* () {
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const preferredProvider: ProviderKind = threadProvider;
|
||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
@@ -293,9 +334,6 @@ const make = Effect.gen(function* () {
|
||||
thread.session && thread.session.status !== "stopped" && activeSession ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
@@ -303,7 +341,7 @@ const make = Effect.gen(function* () {
|
||||
const modelChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "unsupported";
|
||||
const previousModelSelection = threadModelSelections.get(threadId);
|
||||
const shouldRestartForModelSelectionChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
@@ -312,17 +350,15 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
!providerChanged &&
|
||||
!shouldRestartForModelChange &&
|
||||
!shouldRestartForModelSelectionChange
|
||||
) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
|
||||
const resumeCursor =
|
||||
providerChanged || shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
const resumeCursor = shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
@@ -331,7 +367,6 @@ const make = Effect.gen(function* () {
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelSelectionChange,
|
||||
@@ -356,7 +391,7 @@ const make = Effect.gen(function* () {
|
||||
return startedSession.threadId;
|
||||
});
|
||||
|
||||
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
|
||||
const buildSendTurnRequestForThread = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
@@ -366,7 +401,9 @@ const make = Effect.gen(function* () {
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
return yield* Effect.die(
|
||||
new Error(`Thread '${input.threadId}' was not found in read model.`),
|
||||
);
|
||||
}
|
||||
yield* ensureSessionForThread(
|
||||
input.threadId,
|
||||
@@ -390,7 +427,7 @@ const make = Effect.gen(function* () {
|
||||
const requestedModelSelection =
|
||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported"
|
||||
sessionModelSwitch === "unsupported" && input.modelSelection === undefined
|
||||
? activeSession?.model !== undefined
|
||||
? {
|
||||
...requestedModelSelection,
|
||||
@@ -399,13 +436,13 @@ const make = Effect.gen(function* () {
|
||||
: requestedModelSelection
|
||||
: input.modelSelection;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
};
|
||||
});
|
||||
|
||||
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
|
||||
@@ -564,7 +601,43 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
yield* sendTurnForThread({
|
||||
const handleTurnStartFailure = (cause: Cause.Cause<unknown>) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.void;
|
||||
}
|
||||
const detail = formatFailureDetail(cause);
|
||||
return setThreadSessionErrorOnTurnStartFailure({
|
||||
threadId: event.payload.threadId,
|
||||
detail,
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
Effect.flatMap(() =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
};
|
||||
|
||||
const recoverTurnStartFailure = (cause: Cause.Cause<unknown>) =>
|
||||
handleTurnStartFailure(cause).pipe(
|
||||
Effect.catchCause((recoveryCause) =>
|
||||
Effect.logWarning("provider command reactor failed to recover turn start failure", {
|
||||
eventType: event.type,
|
||||
threadId: event.payload.threadId,
|
||||
cause: Cause.pretty(recoveryCause),
|
||||
originalCause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const sendTurnRequest = yield* buildSendTurnRequestForThread({
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
@@ -574,17 +647,17 @@ const make = Effect.gen(function* () {
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
}),
|
||||
),
|
||||
Effect.map(Option.some),
|
||||
Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe(Effect.as(Option.none()))),
|
||||
);
|
||||
|
||||
if (Option.isNone(sendTurnRequest)) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* providerService
|
||||
.sendTurn(sendTurnRequest.value)
|
||||
.pipe(Effect.catchCause(recoverTurnStartFailure), Effect.forkScoped);
|
||||
});
|
||||
|
||||
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
|
||||
|
||||
@@ -723,6 +723,146 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves completed tool metadata on projected tool activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-tool-completed-with-data"),
|
||||
provider: "cursor",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-tool-completed"),
|
||||
itemId: asItemId("item-tool-completed"),
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
status: "completed",
|
||||
title: "Read file",
|
||||
data: {
|
||||
toolCallId: "tool-read-1",
|
||||
kind: "read",
|
||||
rawOutput: {
|
||||
content: 'import * as Effect from "effect/Effect"\n',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-tool-completed-with-data",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-tool-completed-with-data",
|
||||
);
|
||||
const payload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
const data =
|
||||
payload?.data && typeof payload.data === "object"
|
||||
? (payload.data as Record<string, unknown>)
|
||||
: undefined;
|
||||
const rawOutput =
|
||||
data?.rawOutput && typeof data.rawOutput === "object"
|
||||
? (data.rawOutput as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.kind).toBe("tool.completed");
|
||||
expect(activity?.summary).toBe("Read file");
|
||||
expect(payload?.itemType).toBe("dynamic_tool_call");
|
||||
expect(payload?.detail).toBeUndefined();
|
||||
expect(data?.toolCallId).toBe("tool-read-1");
|
||||
expect(data?.kind).toBe("read");
|
||||
expect(rawOutput?.content).toBe('import * as Effect from "effect/Effect"\n');
|
||||
});
|
||||
|
||||
it("normalizes command execution activities to ran-command summaries", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-command-completed"),
|
||||
provider: "cursor",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-command-completed"),
|
||||
itemId: asItemId("item-command-completed"),
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "bun run lint",
|
||||
data: {
|
||||
toolCallId: "tool-command-1",
|
||||
kind: "execute",
|
||||
command: "bun run lint",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-command-completed",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-command-completed",
|
||||
);
|
||||
const payload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.summary).toBe("Ran command");
|
||||
expect(payload?.detail).toBe("bun run lint");
|
||||
});
|
||||
|
||||
it("uses structured read-file paths when available", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-read-path-completed"),
|
||||
provider: "cursor",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-read-path"),
|
||||
itemId: asItemId("item-read-path"),
|
||||
payload: {
|
||||
itemType: "dynamic_tool_call",
|
||||
status: "completed",
|
||||
title: "Read file",
|
||||
detail: "/tmp/app.ts",
|
||||
data: {
|
||||
toolCallId: "tool-read-path-1",
|
||||
kind: "read",
|
||||
locations: [{ path: "/tmp/app.ts" }],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-read-path-completed",
|
||||
),
|
||||
);
|
||||
const activity = thread.activities.find(
|
||||
(entry: ProviderRuntimeTestActivity) => entry.id === "evt-read-path-completed",
|
||||
);
|
||||
const payload =
|
||||
activity?.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
expect(activity?.summary).toBe("Read file");
|
||||
expect(payload?.detail).toBe("/tmp/app.ts");
|
||||
});
|
||||
|
||||
it("projects completed plan items into first-class proposed plans", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1392,6 +1532,432 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("flushes and completes buffered assistant text when an approval request opens", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-request-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-flush",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-request-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
itemId: asItemId("item-buffered-request-flush"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "visible before approval",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-buffered-request-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-flush"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-request-flush"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-flush" &&
|
||||
!message.streaming &&
|
||||
message.text === "visible before approval",
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-flush",
|
||||
);
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("flushes and completes buffered assistant text when user input is requested", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-user-input-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-user-input-flush",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-user-input-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
itemId: asItemId("item-buffered-user-input-flush"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "visible before user input",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "user-input.requested",
|
||||
eventId: asEventId("evt-user-input-requested-buffered-user-input-flush"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-user-input-flush"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-user-input-flush"),
|
||||
payload: {
|
||||
questions: [
|
||||
{
|
||||
id: "choice",
|
||||
header: "Choice",
|
||||
question: "Pick one",
|
||||
options: [{ label: "A", description: "Option A" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-user-input-flush" &&
|
||||
!message.streaming &&
|
||||
message.text === "visible before user input",
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) =>
|
||||
entry.id === "assistant:item-buffered-user-input-flush",
|
||||
);
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("does not create assistant segments for whitespace-only buffered text at approval boundaries", async () => {
|
||||
const harness = await createHarness();
|
||||
const startedAt = "2026-03-28T06:28:00.000Z";
|
||||
const pausedAt = "2026-03-28T06:28:01.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-whitespace-request"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-whitespace-request",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-whitespace-request"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
itemId: asItemId("item-buffered-whitespace-request"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "\n\n\n",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-buffered-whitespace-request"),
|
||||
provider: "codex",
|
||||
createdAt: pausedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-whitespace-request"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-whitespace-request"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "approval.requested",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
thread.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-whitespace-request",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("starts a new buffered assistant message segment after approval and completes without duplication", async () => {
|
||||
const harness = await createHarness();
|
||||
const startedAt = "2026-03-28T06:07:00.000Z";
|
||||
const pausedAt = "2026-03-28T06:07:01.000Z";
|
||||
const resumedAt = "2026-03-28T06:07:02.000Z";
|
||||
const completedAt = "2026-03-28T06:07:03.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-buffered-request-append"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-buffered-request-append",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-request-append-initial"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
itemId: asItemId("item-buffered-request-append"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "first half",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-buffered-request-append"),
|
||||
provider: "codex",
|
||||
createdAt: pausedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
requestId: ApprovalRequestId.make("req-buffered-request-append"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append" &&
|
||||
!message.streaming &&
|
||||
message.text === "first half",
|
||||
),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-buffered-request-append-followup"),
|
||||
provider: "codex",
|
||||
createdAt: resumedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
itemId: asItemId("item-buffered-request-append"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: " second half",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-buffered-request-append"),
|
||||
provider: "codex",
|
||||
createdAt: completedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-buffered-request-append"),
|
||||
itemId: asItemId("item-buffered-request-append"),
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-buffered-request-append:segment:1" &&
|
||||
!message.streaming &&
|
||||
message.text === " second half",
|
||||
),
|
||||
);
|
||||
const firstMessage = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.id === "assistant:item-buffered-request-append",
|
||||
);
|
||||
const resumedMessage = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) =>
|
||||
entry.id === "assistant:item-buffered-request-append:segment:1",
|
||||
);
|
||||
expect(firstMessage?.text).toBe("first half");
|
||||
expect(firstMessage?.streaming).toBe(false);
|
||||
expect(resumedMessage?.text).toBe(" second half");
|
||||
expect(resumedMessage?.streaming).toBe(false);
|
||||
|
||||
const events = await Effect.runPromise(
|
||||
Stream.runCollect(harness.engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk) => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
const assistantEvents = events.filter(
|
||||
(event): event is Extract<(typeof events)[number], { type: "thread.message-sent" }> =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.messageId.startsWith("assistant:item-buffered-request-append"),
|
||||
);
|
||||
expect(assistantEvents).toHaveLength(4);
|
||||
expect(assistantEvents[0]?.payload.streaming).toBe(true);
|
||||
expect(assistantEvents[0]?.payload.text).toBe("first half");
|
||||
expect(assistantEvents[1]?.payload.streaming).toBe(false);
|
||||
expect(assistantEvents[1]?.payload.text).toBe("");
|
||||
expect(assistantEvents[2]?.payload.messageId).toBe(
|
||||
"assistant:item-buffered-request-append:segment:1",
|
||||
);
|
||||
expect(assistantEvents[2]?.payload.streaming).toBe(true);
|
||||
expect(assistantEvents[2]?.payload.text).toBe(" second half");
|
||||
expect(assistantEvents[3]?.payload.messageId).toBe(
|
||||
"assistant:item-buffered-request-append:segment:1",
|
||||
);
|
||||
expect(assistantEvents[3]?.payload.streaming).toBe(false);
|
||||
expect(assistantEvents[3]?.payload.text).toBe("");
|
||||
});
|
||||
|
||||
it("starts a new streaming assistant message segment after approval", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const startedAt = "2026-03-28T07:00:00.000Z";
|
||||
const pausedAt = "2026-03-28T07:00:01.000Z";
|
||||
const resumedAt = "2026-03-28T07:00:02.000Z";
|
||||
const completedAt = "2026-03-28T07:00:03.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-streaming-request-segment"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
});
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" &&
|
||||
thread.session?.activeTurnId === "turn-streaming-request-segment",
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-streaming-request-segment-initial"),
|
||||
provider: "codex",
|
||||
createdAt: startedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
itemId: asItemId("item-streaming-request-segment"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "before approval",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "request.opened",
|
||||
eventId: asEventId("evt-request-opened-streaming-request-segment"),
|
||||
provider: "codex",
|
||||
createdAt: pausedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
requestId: ApprovalRequestId.make("req-streaming-request-segment"),
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "pwd",
|
||||
},
|
||||
});
|
||||
|
||||
await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment" &&
|
||||
!message.streaming &&
|
||||
message.text === "before approval",
|
||||
),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-message-delta-streaming-request-segment-followup"),
|
||||
provider: "codex",
|
||||
createdAt: resumedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
itemId: asItemId("item-streaming-request-segment"),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: " after approval",
|
||||
},
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-message-completed-streaming-request-segment"),
|
||||
provider: "codex",
|
||||
createdAt: completedAt,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-streaming-request-segment"),
|
||||
itemId: asItemId("item-streaming-request-segment"),
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment:segment:1" &&
|
||||
!message.streaming &&
|
||||
message.text === " after approval",
|
||||
),
|
||||
);
|
||||
expect(
|
||||
thread.messages.find(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment",
|
||||
)?.text,
|
||||
).toBe("before approval");
|
||||
expect(
|
||||
thread.messages.find(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.id === "assistant:item-streaming-request-segment:segment:1",
|
||||
)?.text,
|
||||
).toBe(" after approval");
|
||||
});
|
||||
|
||||
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,36 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Exit } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
|
||||
|
||||
describe("logCleanupCauseUnlessInterrupted", () => {
|
||||
const threadId = ThreadId.make("thread-deletion-reactor-test");
|
||||
|
||||
it("swallows ordinary cleanup failures", async () => {
|
||||
const exit = await Effect.runPromiseExit(
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: Effect.fail("cleanup failed"),
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isSuccess(exit)).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves interrupt causes", async () => {
|
||||
const exit = await Effect.runPromiseExit(
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: Effect.interrupt,
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(Exit.isFailure(exit)).toBe(true);
|
||||
if (Exit.isFailure(exit)) {
|
||||
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { OrchestrationEvent } from "@t3tools/contracts";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
import { Cause, Effect, Layer, Stream } from "effect";
|
||||
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { TerminalManager } from "../../terminal/Services/Manager.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import {
|
||||
ThreadDeletionReactor,
|
||||
type ThreadDeletionReactorShape,
|
||||
} from "../Services/ThreadDeletionReactor.ts";
|
||||
|
||||
type ThreadDeletedEvent = Extract<OrchestrationEvent, { type: "thread.deleted" }>;
|
||||
|
||||
export const logCleanupCauseUnlessInterrupted = <R, E>({
|
||||
effect,
|
||||
message,
|
||||
threadId,
|
||||
}: {
|
||||
readonly effect: Effect.Effect<void, E, R>;
|
||||
readonly message: string;
|
||||
readonly threadId: ThreadDeletedEvent["payload"]["threadId"];
|
||||
}): Effect.Effect<void, E, R> =>
|
||||
effect.pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logDebug(message, {
|
||||
threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const terminalManager = yield* TerminalManager;
|
||||
|
||||
const stopProviderSession = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: providerService.stopSession({ threadId }),
|
||||
message: "thread deletion cleanup skipped provider session stop",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const closeThreadTerminals = (threadId: ThreadDeletedEvent["payload"]["threadId"]) =>
|
||||
logCleanupCauseUnlessInterrupted({
|
||||
effect: terminalManager.close({ threadId, deleteHistory: true }),
|
||||
message: "thread deletion cleanup skipped terminal close",
|
||||
threadId,
|
||||
});
|
||||
|
||||
const processThreadDeleted = Effect.fn("processThreadDeleted")(function* (
|
||||
event: ThreadDeletedEvent,
|
||||
) {
|
||||
const { threadId } = event.payload;
|
||||
yield* stopProviderSession(threadId);
|
||||
yield* closeThreadTerminals(threadId);
|
||||
});
|
||||
|
||||
const processThreadDeletedSafely = (event: ThreadDeletedEvent) =>
|
||||
processThreadDeleted(event).pipe(
|
||||
Effect.catchCause((cause) => {
|
||||
if (Cause.hasInterruptsOnly(cause)) {
|
||||
return Effect.failCause(cause);
|
||||
}
|
||||
return Effect.logWarning("thread deletion reactor failed to process event", {
|
||||
eventType: event.type,
|
||||
threadId: event.payload.threadId,
|
||||
cause: Cause.pretty(cause),
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
const worker = yield* makeDrainableWorker(processThreadDeletedSafely);
|
||||
|
||||
const start: ThreadDeletionReactorShape["start"] = Effect.fn("start")(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (event.type !== "thread.deleted") {
|
||||
return Effect.void;
|
||||
}
|
||||
return worker.enqueue(event);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
start,
|
||||
drain: worker.drain,
|
||||
} satisfies ThreadDeletionReactorShape;
|
||||
});
|
||||
|
||||
export const ThreadDeletionReactorLive = Layer.effect(ThreadDeletionReactor, make);
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* ThreadDeletionReactor - Thread deletion cleanup reactor service interface.
|
||||
*
|
||||
* Owns background workers that react to thread deletion domain events and
|
||||
* perform best-effort runtime cleanup for provider sessions and terminals.
|
||||
*
|
||||
* @module ThreadDeletionReactor
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import type { Effect, Scope } from "effect";
|
||||
|
||||
/**
|
||||
* ThreadDeletionReactorShape - Service API for thread deletion cleanup.
|
||||
*/
|
||||
export interface ThreadDeletionReactorShape {
|
||||
/**
|
||||
* Start reacting to thread.deleted orchestration domain events.
|
||||
*
|
||||
* The returned effect must be run in a scope so all worker fibers can be
|
||||
* finalized on shutdown.
|
||||
*/
|
||||
readonly start: () => Effect.Effect<void, never, Scope.Scope>;
|
||||
|
||||
/**
|
||||
* Resolves when the internal processing queue is empty and idle.
|
||||
* Intended for test use to replace timing-sensitive sleeps.
|
||||
*/
|
||||
readonly drain: Effect.Effect<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ThreadDeletionReactor - Service tag for thread deletion cleanup workers.
|
||||
*/
|
||||
export class ThreadDeletionReactor extends Context.Service<
|
||||
ThreadDeletionReactor,
|
||||
ThreadDeletionReactorShape
|
||||
>()("t3/orchestration/Services/ThreadDeletionReactor") {}
|
||||
@@ -0,0 +1,226 @@
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { decideOrchestrationCommand } from "./decider.ts";
|
||||
import { createEmptyReadModel, projectEvent } from "./projector.ts";
|
||||
|
||||
const asCommandId = (value: string): CommandId => CommandId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
async function seedReadModel(): Promise<OrchestrationReadModel> {
|
||||
const now = new Date().toISOString();
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = await Effect.runPromise(
|
||||
projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-delete"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Project Delete",
|
||||
workspaceRoot: "/tmp/project-delete",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const withFirstThread = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create-1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-create-1"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Thread Delete 1",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
return Effect.runPromise(
|
||||
projectEvent(withFirstThread, {
|
||||
sequence: 3,
|
||||
eventId: asEventId("evt-thread-create-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: asThreadId("thread-delete-2"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: asCommandId("cmd-thread-create-2"),
|
||||
causationEventId: null,
|
||||
correlationId: asCommandId("cmd-thread-create-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: asThreadId("thread-delete-2"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
title: "Thread Delete 2",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
type PlannedEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
|
||||
function normalizeDeleteEvent(event: PlannedEvent | ReadonlyArray<PlannedEvent>) {
|
||||
const events = Array.isArray(event) ? event : [event];
|
||||
return events.map((entry) => {
|
||||
switch (entry.type) {
|
||||
case "thread.deleted":
|
||||
return {
|
||||
type: entry.type,
|
||||
aggregateKind: entry.aggregateKind,
|
||||
aggregateId: entry.aggregateId,
|
||||
commandId: entry.commandId,
|
||||
correlationId: entry.correlationId,
|
||||
payload: {
|
||||
threadId: entry.payload.threadId,
|
||||
},
|
||||
};
|
||||
case "project.deleted":
|
||||
return {
|
||||
type: entry.type,
|
||||
aggregateKind: entry.aggregateKind,
|
||||
aggregateId: entry.aggregateId,
|
||||
commandId: entry.commandId,
|
||||
correlationId: entry.correlationId,
|
||||
payload: {
|
||||
projectId: entry.payload.projectId,
|
||||
},
|
||||
};
|
||||
default:
|
||||
return entry;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
describe("decider deletion flows", () => {
|
||||
it("rejects deleting a non-empty project without force", async () => {
|
||||
const readModel = await seedReadModel();
|
||||
|
||||
await expect(
|
||||
Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "project.delete",
|
||||
commandId: asCommandId("cmd-project-delete-no-force"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
),
|
||||
).rejects.toThrow("cannot be deleted without force=true");
|
||||
});
|
||||
|
||||
it("reuses thread.delete semantics when force-deleting a non-empty project", async () => {
|
||||
const readModel = await seedReadModel();
|
||||
const projectDeleteCommand: Extract<OrchestrationCommand, { type: "project.delete" }> = {
|
||||
type: "project.delete",
|
||||
commandId: asCommandId("cmd-project-delete-force"),
|
||||
projectId: asProjectId("project-delete"),
|
||||
force: true,
|
||||
};
|
||||
|
||||
const forcedResult = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: projectDeleteCommand,
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
const forcedEvents = Array.isArray(forcedResult) ? forcedResult : [forcedResult];
|
||||
|
||||
expect(forcedEvents.map((event) => event.type)).toEqual([
|
||||
"thread.deleted",
|
||||
"thread.deleted",
|
||||
"project.deleted",
|
||||
]);
|
||||
|
||||
let sequentialReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
const sequentialEvents: PlannedEvent[] = [];
|
||||
for (const nextCommand of [
|
||||
{
|
||||
type: "thread.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
threadId: asThreadId("thread-delete-1"),
|
||||
},
|
||||
{
|
||||
type: "thread.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
threadId: asThreadId("thread-delete-2"),
|
||||
},
|
||||
{
|
||||
type: "project.delete",
|
||||
commandId: projectDeleteCommand.commandId,
|
||||
projectId: asProjectId("project-delete"),
|
||||
},
|
||||
] satisfies ReadonlyArray<OrchestrationCommand>) {
|
||||
const decided = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: nextCommand,
|
||||
readModel: sequentialReadModel,
|
||||
}),
|
||||
);
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
sequentialEvents.push(...nextEvents);
|
||||
for (const nextEvent of nextEvents) {
|
||||
nextSequence += 1;
|
||||
sequentialReadModel = await Effect.runPromise(
|
||||
projectEvent(sequentialReadModel, {
|
||||
...nextEvent,
|
||||
sequence: nextSequence,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
expect(normalizeDeleteEvent(forcedResult)).toEqual(normalizeDeleteEvent(sequentialEvents));
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { Effect } from "effect";
|
||||
|
||||
import { OrchestrationCommandInvariantError } from "./Errors.ts";
|
||||
import {
|
||||
listThreadsByProjectId,
|
||||
requireProject,
|
||||
requireProjectAbsent,
|
||||
requireThread,
|
||||
@@ -14,6 +15,7 @@ import {
|
||||
requireThreadAbsent,
|
||||
requireThreadNotArchived,
|
||||
} from "./commandInvariants.ts";
|
||||
import { projectEvent } from "./projector.ts";
|
||||
|
||||
const nowIso = () => new Date().toISOString();
|
||||
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
|
||||
@@ -47,16 +49,49 @@ function withEventBase(
|
||||
};
|
||||
}
|
||||
|
||||
type PlannedOrchestrationEvent = Omit<OrchestrationEvent, "sequence">;
|
||||
|
||||
type DecideOrchestrationCommandResult =
|
||||
| PlannedOrchestrationEvent
|
||||
| ReadonlyArray<PlannedOrchestrationEvent>;
|
||||
|
||||
const decideCommandSequence = Effect.fn("decideCommandSequence")(function* ({
|
||||
commands,
|
||||
readModel,
|
||||
}: {
|
||||
readonly commands: ReadonlyArray<OrchestrationCommand>;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<ReadonlyArray<PlannedOrchestrationEvent>, OrchestrationCommandInvariantError> {
|
||||
let nextReadModel = readModel;
|
||||
let nextSequence = readModel.snapshotSequence;
|
||||
const plannedEvents: PlannedOrchestrationEvent[] = [];
|
||||
|
||||
for (const nextCommand of commands) {
|
||||
const decided = yield* decideOrchestrationCommand({
|
||||
command: nextCommand,
|
||||
readModel: nextReadModel,
|
||||
});
|
||||
const nextEvents = Array.isArray(decided) ? decided : [decided];
|
||||
for (const nextEvent of nextEvents) {
|
||||
plannedEvents.push(nextEvent);
|
||||
nextSequence += 1;
|
||||
nextReadModel = yield* projectEvent(nextReadModel, {
|
||||
...nextEvent,
|
||||
sequence: nextSequence,
|
||||
}).pipe(Effect.orDie);
|
||||
}
|
||||
}
|
||||
|
||||
return plannedEvents;
|
||||
});
|
||||
|
||||
export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({
|
||||
command,
|
||||
readModel,
|
||||
}: {
|
||||
readonly command: OrchestrationCommand;
|
||||
readonly readModel: OrchestrationReadModel;
|
||||
}): Effect.fn.Return<
|
||||
Omit<OrchestrationEvent, "sequence"> | ReadonlyArray<Omit<OrchestrationEvent, "sequence">>,
|
||||
OrchestrationCommandInvariantError
|
||||
> {
|
||||
}): Effect.fn.Return<DecideOrchestrationCommandResult, OrchestrationCommandInvariantError> {
|
||||
switch (command.type) {
|
||||
case "project.create": {
|
||||
yield* requireProjectAbsent({
|
||||
@@ -119,6 +154,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
projectId: command.projectId,
|
||||
});
|
||||
const activeThreads = listThreadsByProjectId(readModel, command.projectId).filter(
|
||||
(thread) => thread.deletedAt === null,
|
||||
);
|
||||
if (activeThreads.length > 0 && command.force !== true) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
detail: `Project '${command.projectId}' is not empty and cannot be deleted without force=true.`,
|
||||
});
|
||||
}
|
||||
if (activeThreads.length > 0) {
|
||||
return yield* decideCommandSequence({
|
||||
readModel,
|
||||
commands: [
|
||||
...activeThreads.map(
|
||||
(thread): Extract<OrchestrationCommand, { type: "thread.delete" }> => ({
|
||||
type: "thread.delete",
|
||||
commandId: command.commandId,
|
||||
threadId: thread.id,
|
||||
}),
|
||||
),
|
||||
{
|
||||
type: "project.delete",
|
||||
commandId: command.commandId,
|
||||
projectId: command.projectId,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
@@ -127,7 +191,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "project.deleted",
|
||||
type: "project.deleted" as const,
|
||||
payload: {
|
||||
projectId: command.projectId,
|
||||
deletedAt: occurredAt,
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
import { spawn, type ChildProcess, type ChildProcessByStdio } from "node:child_process";
|
||||
import type { Readable } from "node:stream";
|
||||
|
||||
import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { TerminalProcessInspector } from "../Services/TerminalProcessInspector.ts";
|
||||
import { TerminalProcessInspectorLive } from "./TerminalProcessInspector.ts";
|
||||
|
||||
type ListenerProcess = ChildProcessByStdio<null, Readable, Readable>;
|
||||
|
||||
interface StartedProcess {
|
||||
readonly process: ListenerProcess;
|
||||
readonly port: number;
|
||||
}
|
||||
|
||||
const stopProcess = (child: ChildProcess) =>
|
||||
Effect.callback<void>((resume) => {
|
||||
if (child.exitCode !== null || child.signalCode !== null) {
|
||||
resume(Effect.void);
|
||||
return;
|
||||
}
|
||||
|
||||
child.kill("SIGTERM");
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
if (child.exitCode === null && child.signalCode === null) {
|
||||
child.kill("SIGKILL");
|
||||
}
|
||||
}, 1_000);
|
||||
|
||||
child.once("exit", () => {
|
||||
clearTimeout(timeout);
|
||||
resume(Effect.void);
|
||||
});
|
||||
});
|
||||
|
||||
const waitForPort = (child: ListenerProcess) =>
|
||||
Effect.callback<number, Error>((resume) => {
|
||||
const timeout = setTimeout(() => {
|
||||
cleanup();
|
||||
resume(Effect.fail(new Error("Timed out waiting for listener port")));
|
||||
}, 3_000);
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
child.stdout.off("data", onStdout);
|
||||
child.stderr.off("data", onStderr);
|
||||
child.off("exit", onExit);
|
||||
};
|
||||
|
||||
const onStdout = (chunk: Buffer) => {
|
||||
stdout += chunk.toString("utf8");
|
||||
const match = stdout.match(/PORT:(\d+)/);
|
||||
if (!match?.[1]) return;
|
||||
const port = Number(match[1]);
|
||||
if (!Number.isInteger(port) || port <= 0) return;
|
||||
cleanup();
|
||||
resume(Effect.succeed(port));
|
||||
};
|
||||
|
||||
const onStderr = (chunk: Buffer) => {
|
||||
stderr += chunk.toString("utf8");
|
||||
};
|
||||
|
||||
const onExit = (code: number | null) => {
|
||||
cleanup();
|
||||
resume(
|
||||
Effect.fail(
|
||||
new Error(
|
||||
`Listener process exited before reporting port (code=${String(code)}): ${stderr.trim()}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
child.stdout.on("data", onStdout);
|
||||
child.stderr.on("data", onStderr);
|
||||
child.on("exit", onExit);
|
||||
|
||||
return Effect.sync(cleanup);
|
||||
});
|
||||
|
||||
const startListenerProcess = Effect.gen(function* () {
|
||||
const script = [
|
||||
"const { createServer } = require('node:http');",
|
||||
"const server = createServer((_req, res) => {",
|
||||
" res.statusCode = 200;",
|
||||
" res.end('ok');",
|
||||
"});",
|
||||
"server.listen(0, '127.0.0.1', () => {",
|
||||
" const address = server.address();",
|
||||
" if (typeof address !== 'object' || !address) process.exit(1);",
|
||||
" console.log(`PORT:${address.port}`);",
|
||||
"});",
|
||||
"const shutdown = () => server.close(() => process.exit(0));",
|
||||
"process.on('SIGTERM', shutdown);",
|
||||
"process.on('SIGINT', shutdown);",
|
||||
"setInterval(() => {}, 10_000);",
|
||||
].join("");
|
||||
|
||||
const process = spawn("node", ["-e", script], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const port = yield* waitForPort(process);
|
||||
return { process, port } satisfies StartedProcess;
|
||||
});
|
||||
|
||||
const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
const testLayer = TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer));
|
||||
|
||||
it.layer(testLayer)("TerminalProcessInspectorLive", (it) => {
|
||||
it.effect("detects listening ports when the terminal root pid is the listener", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startListenerProcess,
|
||||
({ process, port }) =>
|
||||
Effect.gen(function* () {
|
||||
const listenerPid = process.pid;
|
||||
if (!listenerPid) {
|
||||
return yield* Effect.fail(new Error("Listener process pid missing"));
|
||||
}
|
||||
|
||||
const inspector = yield* TerminalProcessInspector;
|
||||
const activity = yield* inspector.inspect(listenerPid);
|
||||
|
||||
assert.equal(activity.hasRunningSubprocess, true);
|
||||
assert.deepStrictEqual(activity.runningPorts.includes(port), true);
|
||||
}),
|
||||
({ process }) => stopProcess(process),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns idle activity when root process has no children and no listening ports", () =>
|
||||
Effect.acquireUseRelease(
|
||||
Effect.sync(() =>
|
||||
spawn("node", ["-e", "setInterval(() => {}, 10_000)"], {
|
||||
stdio: ["ignore", "ignore", "ignore"],
|
||||
}),
|
||||
),
|
||||
(process) =>
|
||||
Effect.gen(function* () {
|
||||
const idlePid = process.pid;
|
||||
if (!idlePid) {
|
||||
return yield* Effect.fail(new Error("Idle process pid missing"));
|
||||
}
|
||||
|
||||
const inspector = yield* TerminalProcessInspector;
|
||||
const activity = yield* inspector.inspect(idlePid);
|
||||
|
||||
assert.equal(activity.hasRunningSubprocess, false);
|
||||
assert.deepStrictEqual(activity.runningPorts, []);
|
||||
}),
|
||||
stopProcess,
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,232 +0,0 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
import { Effect, Layer, Option, PlatformError, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { collectPosixProcessFamilyPids, checkPosixListeningPorts } from "../posix.ts";
|
||||
import type {
|
||||
TerminalProcessInspectorShape,
|
||||
TerminalSubprocessActivity,
|
||||
} from "../Services/TerminalProcessInspector.ts";
|
||||
import {
|
||||
TerminalProcessInspector,
|
||||
TerminalProcessInspectionError,
|
||||
} from "../Services/TerminalProcessInspector.ts";
|
||||
import { checkWindowsListeningPorts, collectWindowsChildPids } from "../win32.ts";
|
||||
|
||||
const DEFAULT_COMMAND_KILL_GRACE_MS = 1_000;
|
||||
|
||||
interface InspectorCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
interface CollectOutputResult {
|
||||
readonly text: string;
|
||||
readonly truncated: boolean;
|
||||
}
|
||||
|
||||
interface RunInspectorCommandInput {
|
||||
readonly operation: string;
|
||||
readonly terminalPid: number;
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly timeoutMs: number;
|
||||
readonly maxOutputBytes: number;
|
||||
}
|
||||
|
||||
function commandLabel(command: string, args: ReadonlyArray<string>): string {
|
||||
return [command, ...args].join(" ");
|
||||
}
|
||||
|
||||
const collectOutput = Effect.fn("process.collectOutput")(function* (
|
||||
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
|
||||
maxOutputBytes: number,
|
||||
): Effect.fn.Return<CollectOutputResult, PlatformError.PlatformError> {
|
||||
return yield* stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => ({
|
||||
text: "",
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}),
|
||||
(state, chunk) => {
|
||||
if (state.bytes >= maxOutputBytes) {
|
||||
return {
|
||||
...state,
|
||||
truncated: true,
|
||||
};
|
||||
}
|
||||
|
||||
const chunkBytes = Buffer.byteLength(chunk);
|
||||
const remainingBytes = maxOutputBytes - state.bytes;
|
||||
if (chunkBytes <= remainingBytes) {
|
||||
return {
|
||||
text: `${state.text}${chunk}`,
|
||||
bytes: state.bytes + chunkBytes,
|
||||
truncated: state.truncated,
|
||||
};
|
||||
}
|
||||
|
||||
const truncatedChunk = Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8");
|
||||
return {
|
||||
text: `${state.text}${truncatedChunk}`,
|
||||
bytes: state.bytes + remainingBytes,
|
||||
truncated: true,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map(({ text, truncated }) => ({ text, truncated })),
|
||||
);
|
||||
});
|
||||
|
||||
const makeTerminalProcessInspector = Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const runInspectorCommand = Effect.fn("process.runInspectorCommand")(function* (
|
||||
input: RunInspectorCommandInput,
|
||||
) {
|
||||
const command = ChildProcess.make(input.command, [...input.args], {
|
||||
killSignal: "SIGTERM",
|
||||
forceKillAfter: DEFAULT_COMMAND_KILL_GRACE_MS,
|
||||
});
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const child = yield* spawner.spawn(command).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to spawn inspector command.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectOutput(child.stdout, input.maxOutputBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to read stdout from inspector command.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
collectOutput(child.stderr, input.maxOutputBytes).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to read stderr from inspector command.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
child.exitCode.pipe(
|
||||
Effect.map(Number),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Failed to read inspector command exit code.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
exitCode,
|
||||
} satisfies InspectorCommandResult;
|
||||
}).pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(input.timeoutMs),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TerminalProcessInspectionError({
|
||||
operation: input.operation,
|
||||
terminalPid: input.terminalPid,
|
||||
command: commandLabel(input.command, input.args),
|
||||
detail: "Inspector command timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const inspect: TerminalProcessInspectorShape["inspect"] = Effect.fn("process.inspect")(function* (
|
||||
terminalPid: number,
|
||||
) {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [],
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const childPids = yield* collectWindowsChildPids(terminalPid, runInspectorCommand);
|
||||
const processPidsForPortScan = [terminalPid, ...childPids];
|
||||
const runningPorts = yield* checkWindowsListeningPorts(processPidsForPortScan, {
|
||||
terminalPid,
|
||||
runCommand: runInspectorCommand,
|
||||
});
|
||||
return {
|
||||
hasRunningSubprocess: childPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
}
|
||||
|
||||
const processFamilyPids = yield* collectPosixProcessFamilyPids(
|
||||
terminalPid,
|
||||
runInspectorCommand,
|
||||
);
|
||||
if (processFamilyPids.length === 0) {
|
||||
return {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [],
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
}
|
||||
|
||||
const subprocessPids = processFamilyPids.filter((pid: number) => pid !== terminalPid);
|
||||
const runningPorts = yield* checkPosixListeningPorts(processFamilyPids, {
|
||||
terminalPid,
|
||||
runCommand: runInspectorCommand,
|
||||
platform: process.platform,
|
||||
});
|
||||
return {
|
||||
hasRunningSubprocess: subprocessPids.length > 0 || runningPorts.length > 0,
|
||||
runningPorts,
|
||||
} satisfies TerminalSubprocessActivity;
|
||||
});
|
||||
|
||||
return {
|
||||
inspect,
|
||||
} satisfies TerminalProcessInspectorShape;
|
||||
});
|
||||
|
||||
export const TerminalProcessInspectorLive = Layer.effect(
|
||||
TerminalProcessInspector,
|
||||
makeTerminalProcessInspector,
|
||||
);
|
||||
@@ -1,153 +0,0 @@
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
||||
|
||||
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
|
||||
import { WebPortInspectionError, WebPortInspector } from "../Services/WebPortInspector.ts";
|
||||
import { WebPortInspectorLive } from "./WebPortInspector.ts";
|
||||
|
||||
const closeServer = (server: Server) =>
|
||||
Effect.callback<void>((resume) => {
|
||||
server.closeAllConnections?.();
|
||||
server.closeIdleConnections?.();
|
||||
server.close(() => {
|
||||
resume(Effect.void);
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
try {
|
||||
server.closeAllConnections?.();
|
||||
server.closeIdleConnections?.();
|
||||
server.close();
|
||||
} catch {
|
||||
// Ignore cleanup failures in tests.
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const listenServer = (server: Server) =>
|
||||
Effect.callback<number, Error>((resume) => {
|
||||
const onError = (error: Error) => {
|
||||
cleanup();
|
||||
resume(Effect.fail(error));
|
||||
};
|
||||
|
||||
const cleanup = () => {
|
||||
server.off("error", onError);
|
||||
};
|
||||
|
||||
server.once("error", onError);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
cleanup();
|
||||
const address = server.address();
|
||||
if (!address || typeof address !== "object") {
|
||||
resume(Effect.fail(new Error("Server did not provide a valid listening address.")));
|
||||
return;
|
||||
}
|
||||
|
||||
resume(Effect.succeed(address.port));
|
||||
});
|
||||
|
||||
return Effect.gen(function* () {
|
||||
cleanup();
|
||||
yield* closeServer(server);
|
||||
});
|
||||
});
|
||||
|
||||
const startServer = (
|
||||
handler: (request: IncomingMessage, response: ServerResponse) => void,
|
||||
): Effect.Effect<{ server: Server; port: number }, Error> =>
|
||||
Effect.gen(function* () {
|
||||
const server = createServer(handler);
|
||||
const port = yield* listenServer(server);
|
||||
return { server, port };
|
||||
});
|
||||
|
||||
it.layer(WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)))(
|
||||
"WebPortInspectorLive",
|
||||
(it) => {
|
||||
it.effect("treats slow HTML responses as web ports", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startServer((_request, response) => {
|
||||
setTimeout(() => {
|
||||
response.statusCode = 200;
|
||||
response.setHeader("content-type", "text/html; charset=utf-8");
|
||||
response.end(
|
||||
"<!DOCTYPE html><html><head><title>ok</title></head><body>hello</body></html>",
|
||||
);
|
||||
}, 800);
|
||||
}),
|
||||
({ port }) =>
|
||||
Effect.gen(function* () {
|
||||
const inspector = yield* WebPortInspector;
|
||||
const isWeb = yield* inspector.inspect(port);
|
||||
assert.equal(isWeb, true);
|
||||
}),
|
||||
({ server }) => closeServer(server),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("treats HTML responses with large bodies as web ports", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startServer((_request, response) => {
|
||||
response.statusCode = 200;
|
||||
response.setHeader("content-type", "text/html; charset=utf-8");
|
||||
response.end(
|
||||
`<!DOCTYPE html><html><head><title>x</title></head><body>${"x".repeat(20_000)}</body></html>`,
|
||||
);
|
||||
}),
|
||||
({ port }) =>
|
||||
Effect.gen(function* () {
|
||||
const inspector = yield* WebPortInspector;
|
||||
const isWeb = yield* inspector.inspect(port);
|
||||
assert.equal(isWeb, true);
|
||||
}),
|
||||
({ server }) => closeServer(server),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores HTTP 404 responses", () =>
|
||||
Effect.acquireUseRelease(
|
||||
startServer((_request, response) => {
|
||||
response.statusCode = 404;
|
||||
response.end();
|
||||
}),
|
||||
({ port }) =>
|
||||
Effect.gen(function* () {
|
||||
const inspector = yield* WebPortInspector;
|
||||
const isWeb = yield* inspector.inspect(port);
|
||||
assert.equal(isWeb, false);
|
||||
}),
|
||||
({ server }) => closeServer(server),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.effect("WebPortInspectorLive preserves typed timeout errors", () =>
|
||||
Effect.gen(function* () {
|
||||
const inspector = yield* WebPortInspector;
|
||||
const error = yield* inspector.inspect(3000).pipe(Effect.flip);
|
||||
|
||||
assert.equal(Schema.is(WebPortInspectionError)(error), true);
|
||||
assert.equal(error.detail, "HTTP probe timed out.");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
WebPortInspectorLive.pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(HttpClient.HttpClient, {
|
||||
execute: () =>
|
||||
Effect.fail(
|
||||
new WebPortInspectionError({
|
||||
port: 3000,
|
||||
host: "127.0.0.1",
|
||||
detail: "HTTP probe timed out.",
|
||||
}),
|
||||
),
|
||||
} as never),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -1,179 +0,0 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
||||
|
||||
import type { WebPortInspectorShape } from "../Services/WebPortInspector.ts";
|
||||
import { WebPortInspector, WebPortInspectionError } from "../Services/WebPortInspector.ts";
|
||||
|
||||
const DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS = 2_000;
|
||||
const WEB_PORT_PROBE_MAX_BODY_BYTES = 8_192;
|
||||
|
||||
interface WebProbeResult {
|
||||
readonly status: number;
|
||||
readonly contentType: string;
|
||||
readonly body: string;
|
||||
readonly location: string;
|
||||
}
|
||||
|
||||
function normalizeHeaderValue(value: string | string[] | undefined): string {
|
||||
if (typeof value === "string") return value;
|
||||
if (Array.isArray(value)) return value[0] ?? "";
|
||||
return "";
|
||||
}
|
||||
|
||||
function isLikelyWebProbe(result: WebProbeResult | null): boolean {
|
||||
if (!result) return false;
|
||||
if (result.status === 404) return false;
|
||||
if (result.status >= 300 && result.status < 400 && result.location.length > 0) {
|
||||
return true;
|
||||
}
|
||||
const contentType = result.contentType.toLowerCase();
|
||||
if (contentType.includes("text/html") || contentType.includes("application/xhtml+xml")) {
|
||||
return true;
|
||||
}
|
||||
const body = result.body.toLowerCase();
|
||||
return body.includes("<!doctype") || body.includes("<html") || body.includes("<head");
|
||||
}
|
||||
|
||||
const collectBodyPreview = <E>(
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, never> =>
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => ({
|
||||
text: "",
|
||||
bytes: 0,
|
||||
}),
|
||||
(state, chunk) => {
|
||||
if (state.bytes >= WEB_PORT_PROBE_MAX_BODY_BYTES) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const chunkBytes = Buffer.byteLength(chunk);
|
||||
const remainingBytes = WEB_PORT_PROBE_MAX_BODY_BYTES - state.bytes;
|
||||
if (chunkBytes <= remainingBytes) {
|
||||
return {
|
||||
text: `${state.text}${chunk}`,
|
||||
bytes: state.bytes + chunkBytes,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
text: `${state.text}${Buffer.from(chunk).subarray(0, remainingBytes).toString("utf8")}`,
|
||||
bytes: state.bytes + remainingBytes,
|
||||
};
|
||||
},
|
||||
),
|
||||
Effect.map((preview) => preview.text),
|
||||
Effect.orElseSucceed(() => ""),
|
||||
);
|
||||
|
||||
const makeWebPortInspector = Effect.gen(function* () {
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
|
||||
const probeWebPortOnHost = Effect.fn("process.probeWebPortOnHost")(function* (
|
||||
port: number,
|
||||
host: string,
|
||||
): Effect.fn.Return<WebProbeResult | null, WebPortInspectionError> {
|
||||
const request = HttpClientRequest.get(`http://${host}:${port}/`).pipe(
|
||||
HttpClientRequest.setHeaders({
|
||||
accept: "text/html,application/xhtml+xml;q=1,*/*;q=0.1",
|
||||
}),
|
||||
);
|
||||
|
||||
return yield* httpClient.execute(request).pipe(
|
||||
Effect.flatMap((response) =>
|
||||
Effect.gen(function* () {
|
||||
const status = response.status;
|
||||
const contentType = normalizeHeaderValue(response.headers["content-type"]);
|
||||
const location = normalizeHeaderValue(response.headers.location);
|
||||
|
||||
if (
|
||||
(status >= 300 && status < 400 && location.length > 0) ||
|
||||
contentType.toLowerCase().includes("text/html") ||
|
||||
contentType.toLowerCase().includes("application/xhtml+xml")
|
||||
) {
|
||||
return {
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body: "",
|
||||
} satisfies WebProbeResult;
|
||||
}
|
||||
|
||||
const body = yield* collectBodyPreview(response.stream);
|
||||
return {
|
||||
status,
|
||||
contentType,
|
||||
location,
|
||||
body,
|
||||
} satisfies WebProbeResult;
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(DEFAULT_WEB_PORT_PROBE_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new WebPortInspectionError({
|
||||
port,
|
||||
host,
|
||||
detail: "HTTP probe timed out.",
|
||||
}),
|
||||
),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((error) =>
|
||||
Schema.is(WebPortInspectionError)(error)
|
||||
? error
|
||||
: new WebPortInspectionError({
|
||||
port,
|
||||
host,
|
||||
detail: "Failed to execute HTTP probe request.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const inspect: WebPortInspectorShape["inspect"] = Effect.fn("process.inspectWebPort")(function* (
|
||||
port: number,
|
||||
) {
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65_535) {
|
||||
return yield* new WebPortInspectionError({
|
||||
port,
|
||||
host: "127.0.0.1",
|
||||
detail: "Port must be an integer between 1 and 65535.",
|
||||
});
|
||||
}
|
||||
|
||||
const ipv4Result = yield* probeWebPortOnHost(port, "127.0.0.1").pipe(Effect.exit);
|
||||
if (ipv4Result._tag === "Success" && isLikelyWebProbe(ipv4Result.value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const ipv6Result = yield* probeWebPortOnHost(port, "::1").pipe(Effect.exit);
|
||||
if (ipv6Result._tag === "Success" && isLikelyWebProbe(ipv6Result.value)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ipv4Result._tag === "Success" || ipv6Result._tag === "Success") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ipv6Result._tag === "Failure") {
|
||||
return yield* Effect.failCause(ipv6Result.cause);
|
||||
}
|
||||
|
||||
return yield* Effect.failCause(ipv4Result.cause);
|
||||
});
|
||||
|
||||
return {
|
||||
inspect,
|
||||
} satisfies WebPortInspectorShape;
|
||||
});
|
||||
|
||||
export const WebPortInspectorLive = Layer.effect(WebPortInspector, makeWebPortInspector);
|
||||
@@ -1,53 +0,0 @@
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
function describeTerminalInspectorCause(cause: unknown): string | null {
|
||||
if (cause instanceof Error && cause.message.length > 0) {
|
||||
return cause.message;
|
||||
}
|
||||
if (typeof cause === "string" && cause.length > 0) {
|
||||
return cause;
|
||||
}
|
||||
if (cause === undefined || cause === null) {
|
||||
return null;
|
||||
}
|
||||
return String(cause);
|
||||
}
|
||||
|
||||
export class TerminalProcessInspectionError extends Schema.TaggedErrorClass<TerminalProcessInspectionError>()(
|
||||
"TerminalProcessInspectionError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
terminalPid: Schema.Int,
|
||||
command: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const cause = describeTerminalInspectorCause(this.cause);
|
||||
return `${this.operation} failed for terminal pid ${this.terminalPid} (${this.command}): ${this.detail}${
|
||||
cause ? ` Cause: ${cause}` : ""
|
||||
}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TerminalSubprocessActivity {
|
||||
hasRunningSubprocess: boolean;
|
||||
runningPorts: number[];
|
||||
}
|
||||
|
||||
export type TerminalSubprocessInspector = (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
|
||||
|
||||
export interface TerminalProcessInspectorShape {
|
||||
readonly inspect: (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<TerminalSubprocessActivity, TerminalProcessInspectionError>;
|
||||
}
|
||||
|
||||
export class TerminalProcessInspector extends Context.Service<
|
||||
TerminalProcessInspector,
|
||||
TerminalProcessInspectorShape
|
||||
>()("t3/process/Services/TerminalProcessInspector") {}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { Context, Schema } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export const DEFAULT_WEB_PORT_PROBE_TTL_MS = 10_000;
|
||||
|
||||
export type TerminalWebPortInspector = (
|
||||
port: number,
|
||||
) => Effect.Effect<boolean, WebPortInspectionError>;
|
||||
|
||||
export class WebPortInspectionError extends Schema.TaggedErrorClass<WebPortInspectionError>()(
|
||||
"WebPortInspectionError",
|
||||
{
|
||||
port: Schema.Int,
|
||||
host: Schema.String,
|
||||
detail: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Web port probe failed for ${this.host}:${this.port}: ${this.detail}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface WebPortInspectorShape {
|
||||
readonly inspect: (port: number) => Effect.Effect<boolean, WebPortInspectionError>;
|
||||
}
|
||||
|
||||
export class WebPortInspector extends Context.Service<WebPortInspector, WebPortInspectorShape>()(
|
||||
"t3/process/Services/WebPortInspector",
|
||||
) {}
|
||||
@@ -1,60 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { checkPosixListeningPorts } from "./posix.ts";
|
||||
|
||||
describe("process.checkPosixListeningPorts", () => {
|
||||
it.effect("falls back to ss when lsof exits with code 1", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: string[] = [];
|
||||
|
||||
const ports = yield* checkPosixListeningPorts([123], {
|
||||
terminalPid: 123,
|
||||
platform: "linux",
|
||||
runCommand: (input) => {
|
||||
commands.push(input.command);
|
||||
if (input.command === "lsof") {
|
||||
return Effect.succeed({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
});
|
||||
}
|
||||
|
||||
return Effect.succeed({
|
||||
stdout:
|
||||
"State Recv-Q Send-Q Local Address:Port Peer Address:Port Process\n" +
|
||||
'LISTEN 0 511 127.0.0.1:3773 0.0.0.0:* users:(("node",pid=123,fd=18))\n',
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(ports, [3773]);
|
||||
assert.deepStrictEqual(commands, ["lsof", "ss"]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not try ss on darwin when lsof reports no listening ports", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: string[] = [];
|
||||
|
||||
const ports = yield* checkPosixListeningPorts([123], {
|
||||
terminalPid: 123,
|
||||
platform: "darwin",
|
||||
runCommand: (input) => {
|
||||
commands.push(input.command);
|
||||
return Effect.succeed({
|
||||
stdout: "",
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(ports, []);
|
||||
assert.deepStrictEqual(commands, ["lsof"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,147 +0,0 @@
|
||||
import { Effect } from "effect";
|
||||
|
||||
import type { TerminalProcessInspectionError } from "./Services/TerminalProcessInspector.ts";
|
||||
import { MAX_PORT_NUMBER, portFromAddress } from "./utils.ts";
|
||||
|
||||
interface InspectorCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
interface PosixRunCommand {
|
||||
(
|
||||
input: Readonly<{
|
||||
operation: string;
|
||||
terminalPid: number;
|
||||
command: string;
|
||||
args: ReadonlyArray<string>;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes: number;
|
||||
}>,
|
||||
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
|
||||
}
|
||||
|
||||
export const collectPosixProcessFamilyPids = Effect.fn("process.collectPosixProcessFamilyPids")(
|
||||
function* (
|
||||
terminalPid: number,
|
||||
runCommand: PosixRunCommand,
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
const psResult = yield* runCommand({
|
||||
operation: "TerminalProcessInspector.collectPosixProcessFamilyPids",
|
||||
terminalPid,
|
||||
command: "ps",
|
||||
args: ["-eo", "pid=,ppid="],
|
||||
timeoutMs: 1_000,
|
||||
maxOutputBytes: 262_144,
|
||||
});
|
||||
if (psResult.exitCode !== 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const childrenByParentPid = new Map<number, number[]>();
|
||||
for (const line of psResult.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
const children = childrenByParentPid.get(ppid);
|
||||
if (children) {
|
||||
children.push(pid);
|
||||
} else {
|
||||
childrenByParentPid.set(ppid, [pid]);
|
||||
}
|
||||
}
|
||||
|
||||
const processFamily = new Set<number>([terminalPid]);
|
||||
const pendingParents = [terminalPid];
|
||||
while (pendingParents.length > 0) {
|
||||
const parentPid = pendingParents.shift();
|
||||
if (!parentPid) continue;
|
||||
const childPids = childrenByParentPid.get(parentPid);
|
||||
if (!childPids || childPids.length === 0) continue;
|
||||
for (const childPid of childPids) {
|
||||
if (processFamily.has(childPid)) continue;
|
||||
processFamily.add(childPid);
|
||||
pendingParents.push(childPid);
|
||||
}
|
||||
}
|
||||
|
||||
return [...processFamily];
|
||||
},
|
||||
);
|
||||
|
||||
export const checkPosixListeningPorts = Effect.fn("process.checkPosixListeningPorts")(function* (
|
||||
processIds: number[],
|
||||
input: {
|
||||
terminalPid: number;
|
||||
runCommand: PosixRunCommand;
|
||||
platform?: NodeJS.Platform;
|
||||
},
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
if (processIds.length === 0) return [];
|
||||
|
||||
const ports = new Set<number>();
|
||||
const pidFilter = new Set(processIds);
|
||||
const platform = input.platform ?? process.platform;
|
||||
|
||||
const lsofResult = yield* input
|
||||
.runCommand({
|
||||
operation: "TerminalProcessInspector.checkPosixListeningPorts.lsof",
|
||||
terminalPid: input.terminalPid,
|
||||
command: "lsof",
|
||||
args: ["-nP", "-a", "-iTCP", "-sTCP:LISTEN", "-p", processIds.join(",")],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 262_144,
|
||||
})
|
||||
.pipe(Effect.exit);
|
||||
|
||||
if (lsofResult._tag === "Success") {
|
||||
if (lsofResult.value.exitCode === 0) {
|
||||
for (const line of lsofResult.value.stdout.split(/\r?\n/g)) {
|
||||
const match = line.match(/:(\d+)\s+\(LISTEN\)$/);
|
||||
if (!match?.[1]) continue;
|
||||
const port = Number(match[1]);
|
||||
if (Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
return [...ports].toSorted((left, right) => left - right);
|
||||
}
|
||||
if (lsofResult.value.exitCode === 1 && platform === "darwin") {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const ssResult = yield* input.runCommand({
|
||||
operation: "TerminalProcessInspector.checkPosixListeningPorts.ss",
|
||||
terminalPid: input.terminalPid,
|
||||
command: "ss",
|
||||
args: ["-ltnp"],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 524_288,
|
||||
});
|
||||
if (ssResult.exitCode !== 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
for (const line of ssResult.stdout.split(/\r?\n/g)) {
|
||||
if (!line.includes("pid=")) continue;
|
||||
const localAddress = line.trim().split(/\s+/g)[3];
|
||||
if (!localAddress) continue;
|
||||
const port = portFromAddress(localAddress);
|
||||
if (port === null) continue;
|
||||
|
||||
const pidMatches = [...line.matchAll(/pid=(\d+)/g)];
|
||||
if (pidMatches.length === 0) continue;
|
||||
if (
|
||||
pidMatches.some((match) => {
|
||||
const pid = Number(match[1]);
|
||||
return Number.isInteger(pid) && pidFilter.has(pid);
|
||||
})
|
||||
) {
|
||||
ports.add(port);
|
||||
}
|
||||
}
|
||||
return [...ports].toSorted((left, right) => left - right);
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
export const MAX_PORT_NUMBER = 65_535;
|
||||
|
||||
export function normalizeRunningPorts(ports: number[]): number[] {
|
||||
if (ports.length === 0) return [];
|
||||
return [...new Set(ports)]
|
||||
.filter((port) => Number.isInteger(port) && port > 0 && port <= MAX_PORT_NUMBER)
|
||||
.toSorted((left, right) => left - right);
|
||||
}
|
||||
|
||||
export function parsePidList(stdout: string): number[] {
|
||||
const pids: number[] = [];
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
const pid = Number(line.trim());
|
||||
if (!Number.isInteger(pid) || pid <= 0) {
|
||||
continue;
|
||||
}
|
||||
pids.push(pid);
|
||||
}
|
||||
return [...new Set(pids)];
|
||||
}
|
||||
|
||||
export function parsePortList(stdout: string): number[] {
|
||||
const ports: number[] = [];
|
||||
for (const line of stdout.split(/\r?\n/g)) {
|
||||
const port = Number(line.trim());
|
||||
if (!Number.isInteger(port)) {
|
||||
continue;
|
||||
}
|
||||
ports.push(port);
|
||||
}
|
||||
return normalizeRunningPorts(ports);
|
||||
}
|
||||
|
||||
export function portFromAddress(address: string): number | null {
|
||||
const match = address.match(/:(\d+)$/);
|
||||
if (!match?.[1]) return null;
|
||||
const port = Number(match[1]);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > MAX_PORT_NUMBER) {
|
||||
return null;
|
||||
}
|
||||
return port;
|
||||
}
|
||||
|
||||
export function arePortListsEqual(left: number[], right: number[]): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
for (let index = 0; index < left.length; index += 1) {
|
||||
if (left[index] !== right[index]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import { collectWindowsChildPids } from "./win32.ts";
|
||||
|
||||
function parentPidFromCommand(command: string | undefined): number {
|
||||
return Number(/ParentProcessId = (\d+)/.exec(command ?? "")?.[1] ?? "0");
|
||||
}
|
||||
|
||||
describe("process.collectWindowsChildPids", () => {
|
||||
it.effect("walks the full descendant tree breadth-first", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: string[] = [];
|
||||
const childMap = new Map<number, string>([
|
||||
[100, "200\n300\n"],
|
||||
[200, "400\n"],
|
||||
[300, ""],
|
||||
[400, ""],
|
||||
]);
|
||||
|
||||
const childPids = yield* collectWindowsChildPids(100, (input) => {
|
||||
const command = input.args[3] ?? "";
|
||||
commands.push(command);
|
||||
return Effect.succeed({
|
||||
stdout: childMap.get(parentPidFromCommand(command)) ?? "",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(childPids, [200, 300, 400]);
|
||||
assert.equal(commands.length, 4);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates repeated descendants to avoid traversal loops", () =>
|
||||
Effect.gen(function* () {
|
||||
const childMap = new Map<number, string>([
|
||||
[100, "200\n300\n"],
|
||||
[200, "300\n400\n"],
|
||||
[300, "200\n"],
|
||||
[400, ""],
|
||||
]);
|
||||
|
||||
const childPids = yield* collectWindowsChildPids(100, (input) => {
|
||||
const parentPid = parentPidFromCommand(input.args[3]);
|
||||
return Effect.succeed({
|
||||
stdout: childMap.get(parentPid) ?? "",
|
||||
stderr: "",
|
||||
exitCode: 0,
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(childPids, [200, 300, 400]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
import { Effect } from "effect";
|
||||
|
||||
import type { TerminalProcessInspectionError } from "./Services/TerminalProcessInspector.ts";
|
||||
import { parsePidList, parsePortList } from "./utils.ts";
|
||||
|
||||
interface InspectorCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly exitCode: number;
|
||||
}
|
||||
|
||||
interface WindowsRunCommand {
|
||||
(
|
||||
input: Readonly<{
|
||||
operation: string;
|
||||
terminalPid: number;
|
||||
command: string;
|
||||
args: ReadonlyArray<string>;
|
||||
timeoutMs: number;
|
||||
maxOutputBytes: number;
|
||||
}>,
|
||||
): Effect.Effect<InspectorCommandResult, TerminalProcessInspectionError>;
|
||||
}
|
||||
|
||||
export const collectWindowsChildPids = Effect.fn("process.collectWindowsChildPids")(function* (
|
||||
terminalPid: number,
|
||||
runCommand: WindowsRunCommand,
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
const seenPids = new Set<number>([terminalPid]);
|
||||
const childPids: number[] = [];
|
||||
const pendingParentPids = [terminalPid];
|
||||
|
||||
while (pendingParentPids.length > 0) {
|
||||
const parentPid = pendingParentPids.shift();
|
||||
if (parentPid === undefined) {
|
||||
break;
|
||||
}
|
||||
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${parentPid}" -ErrorAction SilentlyContinue`,
|
||||
"if (-not $children) { exit 0 }",
|
||||
"$children | Select-Object -ExpandProperty ProcessId",
|
||||
].join("; ");
|
||||
const result = yield* runCommand({
|
||||
operation: "TerminalProcessInspector.collectWindowsChildPids",
|
||||
terminalPid,
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 32_768,
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const childPid of parsePidList(result.stdout)) {
|
||||
if (seenPids.has(childPid)) {
|
||||
continue;
|
||||
}
|
||||
seenPids.add(childPid);
|
||||
childPids.push(childPid);
|
||||
pendingParentPids.push(childPid);
|
||||
}
|
||||
}
|
||||
return childPids;
|
||||
});
|
||||
|
||||
export const checkWindowsListeningPorts = Effect.fn("process.checkWindowsListeningPorts")(
|
||||
function* (
|
||||
processIds: number[],
|
||||
input: {
|
||||
terminalPid: number;
|
||||
runCommand: WindowsRunCommand;
|
||||
},
|
||||
): Effect.fn.Return<number[], TerminalProcessInspectionError> {
|
||||
if (processIds.length === 0) return [];
|
||||
|
||||
const processFilter = processIds.map((pid) => `$_.OwningProcess -eq ${pid}`).join(" -or ");
|
||||
const command = [
|
||||
"$connections = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue",
|
||||
`$matching = $connections | Where-Object { ${processFilter} }`,
|
||||
"if (-not $matching) { exit 0 }",
|
||||
"$matching | Select-Object -ExpandProperty LocalPort -Unique",
|
||||
].join("; ");
|
||||
const result = yield* input.runCommand({
|
||||
operation: "TerminalProcessInspector.checkWindowsListeningPorts",
|
||||
terminalPid: input.terminalPid,
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
timeoutMs: 1_500,
|
||||
maxOutputBytes: 65_536,
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
return [];
|
||||
}
|
||||
return parsePortList(result.stdout);
|
||||
},
|
||||
);
|
||||
@@ -42,12 +42,7 @@ import {
|
||||
type UserInputQuestion,
|
||||
ClaudeAgentEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
resolveApiModelId,
|
||||
resolveEffort,
|
||||
trimOrNull,
|
||||
} from "@t3tools/shared/model";
|
||||
import { applyClaudePromptEffortPrefix, resolveEffort, trimOrNull } from "@t3tools/shared/model";
|
||||
import {
|
||||
Cause,
|
||||
DateTime,
|
||||
@@ -66,7 +61,7 @@ import {
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "./ClaudeProvider.ts";
|
||||
import { getClaudeModelCapabilities, resolveClaudeApiModelId } from "./ClaudeProvider.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
@@ -2829,7 +2824,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
|
||||
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
|
||||
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
|
||||
null) as ClaudeAgentEffort | null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
@@ -2853,7 +2848,13 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
...(apiModelId ? { model: apiModelId } : {}),
|
||||
pathToClaudeCodeExecutable: claudeBinaryPath,
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
// The SDK type lags the CLI here: Opus 4.7 accepts `xhigh` even though
|
||||
// the published `Options["effort"]` union currently stops at `max`.
|
||||
...(effectiveEffort
|
||||
? {
|
||||
effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions["effort"]>,
|
||||
}
|
||||
: {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(permissionMode === "bypassPermissions"
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
@@ -3006,7 +3007,7 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
}
|
||||
|
||||
if (modelSelection?.model) {
|
||||
const apiModelId = resolveApiModelId(modelSelection);
|
||||
const apiModelId = resolveClaudeApiModelId(modelSelection);
|
||||
if (context.currentApiModelId !== apiModelId) {
|
||||
yield* Effect.tryPromise({
|
||||
try: () => context.query.setModel(apiModelId),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type {
|
||||
ClaudeSettings,
|
||||
ClaudeModelSelection,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
@@ -86,6 +87,23 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-5",
|
||||
name: "Claude Opus 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
@@ -146,6 +164,14 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveClaudeApiModelId(modelSelection: ClaudeModelSelection): string {
|
||||
switch (modelSelection.options?.contextWindow) {
|
||||
case "1m":
|
||||
return `${modelSelection.model}[1m]`;
|
||||
default:
|
||||
return modelSelection.model;
|
||||
}
|
||||
}
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly auth: Pick<ServerProviderAuth, "status">;
|
||||
|
||||
@@ -144,7 +144,6 @@ const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
remove: () => Effect.void,
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,687 @@
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { chmod, mkdtemp, readFile, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildCursorProviderSnapshot,
|
||||
buildCursorCapabilitiesFromConfigOptions,
|
||||
buildCursorDiscoveredModelsFromConfigOptions,
|
||||
discoverCursorModelCapabilitiesViaAcp,
|
||||
discoverCursorModelsViaAcp,
|
||||
getCursorFallbackModels,
|
||||
getCursorParameterizedModelPickerUnsupportedMessage,
|
||||
parseCursorAboutOutput,
|
||||
parseCursorCliConfigChannel,
|
||||
parseCursorVersionDate,
|
||||
resolveCursorAcpBaseModelId,
|
||||
resolveCursorAcpConfigUpdates,
|
||||
} from "./CursorProvider.ts";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
|
||||
async function makeMockAgentWrapper(extraEnv?: Record<string, string>) {
|
||||
const dir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-mock-"));
|
||||
const wrapperPath = path.join(dir, "fake-agent.sh");
|
||||
const envExports = Object.entries(extraEnv ?? {})
|
||||
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
|
||||
.join("\n");
|
||||
const script = `#!/bin/sh
|
||||
${envExports}
|
||||
exec ${JSON.stringify("bun")} ${JSON.stringify(mockAgentPath)} "$@"
|
||||
`;
|
||||
await writeFile(wrapperPath, script, "utf8");
|
||||
await chmod(wrapperPath, 0o755);
|
||||
return wrapperPath;
|
||||
}
|
||||
|
||||
async function waitForFileContent(filePath: string, attempts = 40): Promise<string> {
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
try {
|
||||
const content = await readFile(filePath, "utf8");
|
||||
if (content.trim().length > 0) {
|
||||
return content;
|
||||
}
|
||||
} catch {}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error(`Timed out waiting for file content at ${filePath}`);
|
||||
}
|
||||
|
||||
const parameterizedGpt54ConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "gpt-5.4-medium-fast",
|
||||
options: [{ name: "GPT-5.4", value: "gpt-5.4-medium-fast" }],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "medium",
|
||||
options: [
|
||||
{ name: "None", value: "none" },
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
{ name: "Extra High", value: "extra-high" },
|
||||
],
|
||||
category: "thought_level",
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "272k",
|
||||
options: [
|
||||
{ name: "272K", value: "272k" },
|
||||
{ name: "1M", value: "1m" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "context",
|
||||
name: "Context",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "false",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: "Fast", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const parameterizedClaudeConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "claude-4.6-opus-high-thinking",
|
||||
options: [{ name: "Opus 4.6", value: "claude-4.6-opus-high-thinking" }],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "high",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
],
|
||||
category: "thought_level",
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
},
|
||||
{
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
category: "model_config",
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const parameterizedClaudeModelOptionConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "claude-opus-4-6",
|
||||
options: [{ name: "Opus 4.6", value: "claude-opus-4-6" }],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "high",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
],
|
||||
category: "thought_level",
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "max",
|
||||
options: [
|
||||
{ name: "Low", value: "low" },
|
||||
{ name: "Medium", value: "medium" },
|
||||
{ name: "High", value: "high" },
|
||||
{ name: "Max", value: "max" },
|
||||
],
|
||||
category: "model_option",
|
||||
id: "effort",
|
||||
name: "Effort",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: "Fast", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: ":icon-brain:", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const sessionNewCursorConfigOptions = [
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "agent",
|
||||
options: [
|
||||
{ name: "Agent", value: "agent", description: "Full agent capabilities with tool access" },
|
||||
],
|
||||
category: "mode",
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
description: "Controls how the agent executes tasks",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "composer-2",
|
||||
options: [
|
||||
{ name: "Auto", value: "default" },
|
||||
{ name: "Composer 2", value: "composer-2" },
|
||||
{ name: "GPT-5.4", value: "gpt-5.4" },
|
||||
{ name: "Sonnet 4.6", value: "claude-sonnet-4-6" },
|
||||
{ name: "Opus 4.6", value: "claude-opus-4-6" },
|
||||
{ name: "Codex 5.3 Spark", value: "gpt-5.3-codex-spark" },
|
||||
],
|
||||
category: "model",
|
||||
id: "model",
|
||||
name: "Model",
|
||||
description: "Controls which model is used for responses",
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
currentValue: "true",
|
||||
options: [
|
||||
{ name: "Off", value: "false" },
|
||||
{ name: "Fast", value: "true" },
|
||||
],
|
||||
category: "model_config",
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
description: "Faster speeds.",
|
||||
},
|
||||
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
|
||||
|
||||
const baseCursorSettings: CursorSettings = {
|
||||
enabled: true,
|
||||
binaryPath: "agent",
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
};
|
||||
|
||||
const emptyCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
} as const;
|
||||
|
||||
describe("getCursorFallbackModels", () => {
|
||||
it("does not publish any built-in cursor models before ACP discovery", () => {
|
||||
expect(
|
||||
getCursorFallbackModels({
|
||||
customModels: ["internal/cursor-model"],
|
||||
}).map((model) => model.slug),
|
||||
).toEqual(["internal/cursor-model"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorProviderSnapshot", () => {
|
||||
it("downgrades ready status to warning when ACP model discovery times out", () => {
|
||||
expect(
|
||||
buildCursorProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
cursorSettings: baseCursorSettings,
|
||||
parsed: {
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated", type: "Team", label: "Cursor Team Subscription" },
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery timed out after 15000ms.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "warning",
|
||||
message: "Cursor ACP model discovery timed out after 15000ms.",
|
||||
models: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves provider error state while appending discovery warnings", () => {
|
||||
expect(
|
||||
buildCursorProviderSnapshot({
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
cursorSettings: {
|
||||
...baseCursorSettings,
|
||||
customModels: ["claude-sonnet-4-6"],
|
||||
},
|
||||
parsed: {
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "error",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
},
|
||||
discoveryWarning: "Cursor ACP model discovery failed. Check server logs for details.",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "error",
|
||||
message:
|
||||
"Cursor Agent is not authenticated. Run `agent login` and try again. Cursor ACP model discovery failed. Check server logs for details.",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
isCustom: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorCapabilitiesFromConfigOptions", () => {
|
||||
it("derives model capabilities from parameterized Cursor ACP config options", () => {
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedGpt54ConfigOptions)).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium", isDefault: true },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "272k", label: "272K", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("detects boolean thinking toggles from model_config options", () => {
|
||||
expect(buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeConfigOptions)).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("prefers the newer model_option effort control over legacy thought_level", () => {
|
||||
expect(
|
||||
buildCursorCapabilitiesFromConfigOptions(parameterizedClaudeModelOptionConfigOptions),
|
||||
).toEqual({
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High" },
|
||||
{ value: "max", label: "Max", isDefault: true },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
|
||||
it("publishes ACP model choices immediately from session/new config options", () => {
|
||||
expect(buildCursorDiscoveredModelsFromConfigOptions(sessionNewCursorConfigOptions)).toEqual([
|
||||
{
|
||||
slug: "default",
|
||||
name: "Auto",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "composer-2",
|
||||
name: "Composer 2",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Sonnet 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "Codex 5.3 Spark",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverCursorModelsViaAcp", () => {
|
||||
it("keeps the ACP probe runtime alive long enough to discover models", async () => {
|
||||
const wrapperPath = await makeMockAgentWrapper();
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
"default",
|
||||
"composer-2",
|
||||
"gpt-5.4",
|
||||
"claude-opus-4-6",
|
||||
]);
|
||||
});
|
||||
|
||||
it("closes the ACP probe runtime after discovery completes", async () => {
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-provider-exit-log-"));
|
||||
const exitLogPath = path.join(tempDir, "exit.log");
|
||||
const wrapperPath = await makeMockAgentWrapper({
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
});
|
||||
|
||||
await Effect.runPromise(
|
||||
discoverCursorModelsViaAcp({
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
const exitLog = await waitForFileContent(exitLogPath);
|
||||
expect(exitLog).toContain("SIGTERM");
|
||||
});
|
||||
});
|
||||
|
||||
describe("discoverCursorModelCapabilitiesViaAcp", () => {
|
||||
it("closes all ACP probe runtimes after capability enrichment completes", async () => {
|
||||
const tempDir = await mkdtemp(path.join(os.tmpdir(), "cursor-capabilities-exit-log-"));
|
||||
const exitLogPath = path.join(tempDir, "exit.log");
|
||||
const wrapperPath = await makeMockAgentWrapper({
|
||||
T3_ACP_EXIT_LOG_PATH: exitLogPath,
|
||||
});
|
||||
const existingModels: ReadonlyArray<ServerProviderModel> = [
|
||||
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
|
||||
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: emptyCapabilities,
|
||||
},
|
||||
];
|
||||
|
||||
const models = await Effect.runPromise(
|
||||
discoverCursorModelCapabilitiesViaAcp(
|
||||
{
|
||||
enabled: true,
|
||||
binaryPath: wrapperPath,
|
||||
apiEndpoint: "",
|
||||
customModels: [],
|
||||
},
|
||||
existingModels,
|
||||
).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
expect(models.map((model) => model.slug)).toEqual([
|
||||
"default",
|
||||
"composer-2",
|
||||
"gpt-5.4",
|
||||
"claude-opus-4-6",
|
||||
]);
|
||||
|
||||
const exitLog = await waitForFileContent(exitLogPath);
|
||||
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCursorAboutOutput", () => {
|
||||
it("parses json about output and forwards subscription metadata", () => {
|
||||
expect(
|
||||
parseCursorAboutOutput({
|
||||
code: 0,
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
subscriptionTier: "Team",
|
||||
userEmail: "[email protected]",
|
||||
}),
|
||||
stderr: "",
|
||||
}),
|
||||
).toEqual({
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "ready",
|
||||
auth: {
|
||||
status: "authenticated",
|
||||
type: "Team",
|
||||
label: "Cursor Team Subscription",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("treats json about output with a logged-out email as unauthenticated", () => {
|
||||
expect(
|
||||
parseCursorAboutOutput({
|
||||
code: 0,
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
subscriptionTier: "Team",
|
||||
userEmail: "Not logged in",
|
||||
}),
|
||||
stderr: "",
|
||||
}),
|
||||
).toEqual({
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "error",
|
||||
auth: {
|
||||
status: "unauthenticated",
|
||||
},
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
});
|
||||
});
|
||||
|
||||
it("treats json about output with a null email as unauthenticated", () => {
|
||||
expect(
|
||||
parseCursorAboutOutput({
|
||||
code: 0,
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
subscriptionTier: null,
|
||||
userEmail: null,
|
||||
}),
|
||||
stderr: "",
|
||||
}),
|
||||
).toEqual({
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
status: "error",
|
||||
auth: {
|
||||
status: "unauthenticated",
|
||||
},
|
||||
message: "Cursor Agent is not authenticated. Run `agent login` and try again.",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Cursor parameterized model picker preview gating", () => {
|
||||
it("parses Cursor CLI version dates from build versions", () => {
|
||||
expect(parseCursorVersionDate("2026.04.08-c4e73a3")).toBe(20260408);
|
||||
expect(parseCursorVersionDate("2026.04.09")).toBe(20260409);
|
||||
expect(parseCursorVersionDate("not-a-version")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("parses the Cursor CLI channel from cli-config.json", () => {
|
||||
expect(parseCursorCliConfigChannel('{ "channel": "lab" }')).toBe("lab");
|
||||
expect(parseCursorCliConfigChannel('{ "channel": "stable" }')).toBe("stable");
|
||||
expect(parseCursorCliConfigChannel('{ "version": 1 }')).toBeUndefined();
|
||||
expect(parseCursorCliConfigChannel("not-json")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns no warning when the preview requirements are met", () => {
|
||||
expect(
|
||||
getCursorParameterizedModelPickerUnsupportedMessage({
|
||||
version: "2026.04.08-c4e73a3",
|
||||
channel: "lab",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("explains when the Cursor Agent version is too old", () => {
|
||||
expect(
|
||||
getCursorParameterizedModelPickerUnsupportedMessage({
|
||||
version: "2026.04.07-c4e73a3",
|
||||
channel: "lab",
|
||||
}),
|
||||
).toContain("too old");
|
||||
});
|
||||
|
||||
it("explains when the Cursor Agent channel is not lab", () => {
|
||||
expect(
|
||||
getCursorParameterizedModelPickerUnsupportedMessage({
|
||||
version: "2026.04.08-c4e73a3",
|
||||
channel: "stable",
|
||||
}),
|
||||
).toContain("lab channel");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCursorAcpBaseModelId", () => {
|
||||
it("drops bracket traits without rewriting raw ACP model ids", () => {
|
||||
expect(resolveCursorAcpBaseModelId("gpt-5.4[reasoning=medium,context=272k]")).toBe("gpt-5.4");
|
||||
expect(resolveCursorAcpBaseModelId("gpt-5.4-medium-fast")).toBe("gpt-5.4-medium-fast");
|
||||
expect(resolveCursorAcpBaseModelId("claude-4.6-opus-high-thinking")).toBe(
|
||||
"claude-4.6-opus-high-thinking",
|
||||
);
|
||||
expect(resolveCursorAcpBaseModelId("composer-2")).toBe("composer-2");
|
||||
expect(resolveCursorAcpBaseModelId("auto")).toBe("auto");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCursorAcpConfigUpdates", () => {
|
||||
it("maps Cursor model options onto separate ACP config option updates", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
|
||||
reasoning: "xhigh",
|
||||
fastMode: true,
|
||||
contextWindow: "1m",
|
||||
}),
|
||||
).toEqual([
|
||||
{ configId: "reasoning", value: "extra-high" },
|
||||
{ configId: "context", value: "1m" },
|
||||
{ configId: "fast", value: "true" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps boolean thinking toggles when the model exposes them separately", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeConfigOptions, {
|
||||
thinking: false,
|
||||
}),
|
||||
).toEqual([{ configId: "thinking", value: false }]);
|
||||
});
|
||||
|
||||
it("maps explicit fastMode: false so the adapter can clear a prior fast selection", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedGpt54ConfigOptions, {
|
||||
fastMode: false,
|
||||
}),
|
||||
).toEqual([{ configId: "fast", value: "false" }]);
|
||||
});
|
||||
|
||||
it("writes Cursor effort changes through the newer model_option config when available", () => {
|
||||
expect(
|
||||
resolveCursorAcpConfigUpdates(parameterizedClaudeModelOptionConfigOptions, {
|
||||
reasoning: "max",
|
||||
thinking: false,
|
||||
}),
|
||||
).toEqual([
|
||||
{ configId: "effort", value: "max" },
|
||||
{ configId: "thinking", value: "false" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,486 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import {
|
||||
appendOpenCodeAssistantTextDelta,
|
||||
makeOpenCodeAdapterLive,
|
||||
mergeOpenCodeAssistantText,
|
||||
} from "./OpenCodeAdapter.ts";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
type MessageEntry = {
|
||||
info: {
|
||||
id: string;
|
||||
role: "user" | "assistant";
|
||||
};
|
||||
parts: Array<unknown>;
|
||||
};
|
||||
|
||||
const state = {
|
||||
startCalls: [] as string[],
|
||||
sessionCreateUrls: [] as string[],
|
||||
authHeaders: [] as Array<string | null>,
|
||||
abortCalls: [] as string[],
|
||||
closeCalls: [] as string[],
|
||||
revertCalls: [] as Array<{ sessionID: string; messageID?: string }>,
|
||||
promptAsyncError: null as Error | null,
|
||||
closeError: null as Error | null,
|
||||
messages: [] as MessageEntry[],
|
||||
subscribedEvents: [] as unknown[],
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.startCalls.length = 0;
|
||||
state.sessionCreateUrls.length = 0;
|
||||
state.authHeaders.length = 0;
|
||||
state.abortCalls.length = 0;
|
||||
state.closeCalls.length = 0;
|
||||
state.revertCalls.length = 0;
|
||||
state.promptAsyncError = null;
|
||||
state.closeError = null;
|
||||
state.messages = [];
|
||||
state.subscribedEvents = [];
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
startOpenCodeServerProcess: vi.fn(async ({ binaryPath }: { binaryPath: string }) => {
|
||||
runtimeMock.state.startCalls.push(binaryPath);
|
||||
return {
|
||||
url: "http://127.0.0.1:4301",
|
||||
process: {
|
||||
once() {},
|
||||
},
|
||||
close() {},
|
||||
};
|
||||
}),
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
process: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {
|
||||
runtimeMock.state.closeCalls.push(serverUrl ?? "http://127.0.0.1:4301");
|
||||
if (runtimeMock.state.closeError) {
|
||||
throw runtimeMock.state.closeError;
|
||||
}
|
||||
},
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(
|
||||
({ baseUrl, serverPassword }: { baseUrl: string; serverPassword?: string }) => ({
|
||||
session: {
|
||||
create: vi.fn(async () => {
|
||||
runtimeMock.state.sessionCreateUrls.push(baseUrl);
|
||||
runtimeMock.state.authHeaders.push(
|
||||
serverPassword ? `Basic ${btoa(`opencode:${serverPassword}`)}` : null,
|
||||
);
|
||||
return { data: { id: `${baseUrl}/session` } };
|
||||
}),
|
||||
abort: vi.fn(async ({ sessionID }: { sessionID: string }) => {
|
||||
runtimeMock.state.abortCalls.push(sessionID);
|
||||
}),
|
||||
promptAsync: vi.fn(async () => {
|
||||
if (runtimeMock.state.promptAsyncError) {
|
||||
throw runtimeMock.state.promptAsyncError;
|
||||
}
|
||||
}),
|
||||
messages: vi.fn(async () => ({ data: runtimeMock.state.messages })),
|
||||
revert: vi.fn(
|
||||
async ({ sessionID, messageID }: { sessionID: string; messageID?: string }) => {
|
||||
runtimeMock.state.revertCalls.push({
|
||||
sessionID,
|
||||
...(messageID ? { messageID } : {}),
|
||||
});
|
||||
if (!messageID) {
|
||||
runtimeMock.state.messages = [];
|
||||
return;
|
||||
}
|
||||
|
||||
const targetIndex = runtimeMock.state.messages.findIndex(
|
||||
(entry) => entry.info.id === messageID,
|
||||
);
|
||||
runtimeMock.state.messages =
|
||||
targetIndex >= 0
|
||||
? runtimeMock.state.messages.slice(0, targetIndex + 1)
|
||||
: runtimeMock.state.messages;
|
||||
},
|
||||
),
|
||||
},
|
||||
event: {
|
||||
subscribe: vi.fn(async () => ({
|
||||
stream: (async function* () {
|
||||
for (const event of runtimeMock.state.subscribedEvents) {
|
||||
yield event;
|
||||
}
|
||||
})(),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
const providerSessionDirectoryTestLayer = Layer.succeed(ProviderSessionDirectory, {
|
||||
upsert: () => Effect.void,
|
||||
getProvider: () =>
|
||||
Effect.die(new Error("ProviderSessionDirectory.getProvider is not used in test")),
|
||||
getBinding: () => Effect.succeed(Option.none()),
|
||||
listThreadIds: () => Effect.succeed([]),
|
||||
listBindings: () => Effect.succeed([]),
|
||||
});
|
||||
|
||||
const OpenCodeAdapterTestLayer = makeOpenCodeAdapterLive().pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const sleep = (ms: number) =>
|
||||
Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, ms)));
|
||||
|
||||
it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
it.effect("reuses a configured OpenCode server URL instead of spawning a local server", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-opencode"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
assert.equal(session.provider, "opencode");
|
||||
assert.equal(session.threadId, "thread-opencode");
|
||||
assert.deepEqual(runtimeMock.state.startCalls, []);
|
||||
assert.deepEqual(runtimeMock.state.sessionCreateUrls, ["http://127.0.0.1:9999"]);
|
||||
assert.deepEqual(runtimeMock.state.authHeaders, [
|
||||
`Basic ${btoa("opencode:secret-password")}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops a configured-server session without trying to own server lifecycle", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-opencode"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(asThreadId("thread-opencode"));
|
||||
|
||||
assert.deepEqual(runtimeMock.state.startCalls, []);
|
||||
assert.deepEqual(
|
||||
runtimeMock.state.abortCalls.includes("http://127.0.0.1:9999/session"),
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears session state when stopAll cleanup fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-stop-all-a"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-stop-all-b"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
runtimeMock.state.closeError = new Error("close failed");
|
||||
const error = yield* adapter.stopAll().pipe(Effect.flip);
|
||||
const sessions = yield* adapter.listSessions();
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterProcessError");
|
||||
assert.equal(error.detail, "Failed to stop 2 OpenCode sessions.");
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, [
|
||||
"http://127.0.0.1:9999",
|
||||
"http://127.0.0.1:9999",
|
||||
]);
|
||||
assert.deepEqual(sessions, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rolls back session state when sendTurn fails before OpenCode accepts the prompt", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-send-turn-failure"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
runtimeMock.state.promptAsyncError = new Error("prompt failed");
|
||||
const error = yield* adapter
|
||||
.sendTurn({
|
||||
threadId: asThreadId("thread-send-turn-failure"),
|
||||
input: "Fix it",
|
||||
modelSelection: {
|
||||
provider: "opencode",
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
const sessions = yield* adapter.listSessions();
|
||||
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
if (error._tag !== "ProviderAdapterRequestError") {
|
||||
throw new Error("Unexpected error type");
|
||||
}
|
||||
assert.equal(error.detail, "prompt failed");
|
||||
assert.equal(
|
||||
error.message,
|
||||
"Provider adapter request failed (opencode) for session.promptAsync: prompt failed",
|
||||
);
|
||||
assert.equal(sessions.length, 1);
|
||||
assert.equal(sessions[0]?.status, "ready");
|
||||
assert.equal(sessions[0]?.activeTurnId, undefined);
|
||||
assert.equal(sessions[0]?.lastError, "prompt failed");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reverts the full thread when rollback removes every assistant turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-rollback-all");
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
runtimeMock.state.messages = [
|
||||
{
|
||||
info: { id: "assistant-1", role: "assistant" },
|
||||
parts: [],
|
||||
},
|
||||
{
|
||||
info: { id: "assistant-2", role: "assistant" },
|
||||
parts: [],
|
||||
},
|
||||
];
|
||||
|
||||
const snapshot = yield* adapter.rollbackThread(threadId, 2);
|
||||
|
||||
assert.deepEqual(runtimeMock.state.revertCalls, [
|
||||
{ sessionID: "http://127.0.0.1:9999/session" },
|
||||
]);
|
||||
assert.deepEqual(snapshot.turns, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deduplicates overlapping assistant text deltas after part updates", () =>
|
||||
Effect.sync(() => {
|
||||
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
|
||||
const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world");
|
||||
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hello world!");
|
||||
|
||||
assert.deepEqual(
|
||||
[firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit],
|
||||
["Hello", " world", "!"],
|
||||
);
|
||||
assert.equal(secondUpdate.latestText, "Hello world!");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("writes provider-native observability records using the session thread id", () =>
|
||||
Effect.gen(function* () {
|
||||
const nativeEvents: Array<{
|
||||
readonly event?: {
|
||||
readonly provider?: string;
|
||||
readonly threadId?: string;
|
||||
readonly providerThreadId?: string;
|
||||
readonly type?: string;
|
||||
};
|
||||
}> = [];
|
||||
const nativeThreadIds: Array<string | null> = [];
|
||||
runtimeMock.state.subscribedEvents = [
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
info: {
|
||||
id: "msg-missing-session",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/other-session",
|
||||
info: {
|
||||
id: "msg-other-session",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "msg-native-log",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const nativeEventLogger = {
|
||||
filePath: "memory://opencode-native-events",
|
||||
write: (event: unknown, threadId: ThreadId | null) => {
|
||||
nativeEvents.push(event as (typeof nativeEvents)[number]);
|
||||
nativeThreadIds.push(threadId ?? null);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const session = yield* Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const started = yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-native-log"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* sleep(10);
|
||||
return started;
|
||||
}).pipe(Effect.provide(adapterLayer));
|
||||
|
||||
assert.equal(session.threadId, "thread-native-log");
|
||||
assert.equal(nativeEvents.length, 1);
|
||||
assert.equal(
|
||||
nativeEvents.some((record) => record.event?.provider === "opencode"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some(
|
||||
(record) => record.event?.providerThreadId === "http://127.0.0.1:9999/session",
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some((record) => record.event?.threadId === "thread-native-log"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeEvents.some((record) => record.event?.type === "message.updated"),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
nativeThreadIds.every((threadId) => threadId === "thread-native-log"),
|
||||
true,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the event pump alive when native event logging fails", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.subscribedEvents = [
|
||||
{
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "msg-native-log-failure",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const nativeEventLogger = {
|
||||
filePath: "memory://opencode-native-events",
|
||||
write: () => Effect.die(new Error("native log write failed")),
|
||||
close: () => Effect.void,
|
||||
};
|
||||
|
||||
const adapterLayer = makeOpenCodeAdapterLive({ nativeEventLogger }).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(
|
||||
ServerSettingsService.layerTest({
|
||||
providers: {
|
||||
opencode: {
|
||||
binaryPath: "fake-opencode",
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(providerSessionDirectoryTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const sessions = yield* Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: "opencode",
|
||||
threadId: asThreadId("thread-native-log-failure"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* sleep(10);
|
||||
return yield* adapter.listSessions();
|
||||
}).pipe(Effect.provide(adapterLayer));
|
||||
|
||||
assert.equal(sessions.length, 1);
|
||||
assert.equal(sessions[0]?.threadId, "thread-native-log-failure");
|
||||
assert.deepEqual(runtimeMock.state.closeCalls, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,138 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { beforeEach, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import { makeOpenCodeProviderLive } from "./OpenCodeProvider.ts";
|
||||
|
||||
const runtimeMock = vi.hoisted(() => {
|
||||
const state = {
|
||||
runVersionError: null as Error | null,
|
||||
inventoryError: null as Error | null,
|
||||
};
|
||||
|
||||
return {
|
||||
state,
|
||||
reset() {
|
||||
state.runVersionError = null;
|
||||
state.inventoryError = null;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("../opencodeRuntime.ts", async () => {
|
||||
const actual =
|
||||
await vi.importActual<typeof import("../opencodeRuntime.ts")>("../opencodeRuntime.ts");
|
||||
|
||||
return {
|
||||
...actual,
|
||||
runOpenCodeCommand: vi.fn(async () => {
|
||||
if (runtimeMock.state.runVersionError) {
|
||||
throw runtimeMock.state.runVersionError;
|
||||
}
|
||||
return { stdout: "opencode 1.0.0\n", stderr: "", code: 0 };
|
||||
}),
|
||||
connectToOpenCodeServer: vi.fn(async ({ serverUrl }: { serverUrl?: string }) => ({
|
||||
url: serverUrl ?? "http://127.0.0.1:4301",
|
||||
process: null,
|
||||
external: Boolean(serverUrl),
|
||||
close() {},
|
||||
})),
|
||||
createOpenCodeSdkClient: vi.fn(() => ({})),
|
||||
loadOpenCodeInventory: vi.fn(async () => {
|
||||
if (runtimeMock.state.inventoryError) {
|
||||
throw runtimeMock.state.inventoryError;
|
||||
}
|
||||
return {
|
||||
providerList: { connected: [], all: [] },
|
||||
agents: [],
|
||||
};
|
||||
}),
|
||||
flattenOpenCodeModels: vi.fn(() => []),
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
runtimeMock.reset();
|
||||
});
|
||||
|
||||
const makeTestLayer = (settingsOverrides?: Parameters<typeof ServerSettingsService.layerTest>[0]) =>
|
||||
makeOpenCodeProviderLive().pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(settingsOverrides)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
it.layer(makeTestLayer())("OpenCodeProviderLive", (it) => {
|
||||
it.effect("shows a codex-style missing binary message", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.runVersionError = new Error("spawn opencode ENOENT");
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, false);
|
||||
assert.equal(snapshot.message, "OpenCode CLI (`opencode`) is not installed or not on PATH.");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("hides generic Effect.tryPromise text for local CLI probe failures", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.runVersionError = new Error("An error occurred in Effect.tryPromise");
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(snapshot.message, "Failed to execute OpenCode CLI health check.");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(
|
||||
makeTestLayer({
|
||||
providers: {
|
||||
opencode: {
|
||||
serverUrl: "http://127.0.0.1:9999",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
}),
|
||||
)("OpenCodeProviderLive with configured server URL", (it) => {
|
||||
it.effect("surfaces a friendly auth error for configured servers", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error("401 Unauthorized");
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(
|
||||
snapshot.message,
|
||||
"OpenCode server rejected authentication. Check the server URL and password.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("surfaces a friendly connection error for configured servers", () =>
|
||||
Effect.gen(function* () {
|
||||
runtimeMock.state.inventoryError = new Error(
|
||||
"fetch failed: connect ECONNREFUSED 127.0.0.1:9999",
|
||||
);
|
||||
const provider = yield* OpenCodeProvider;
|
||||
const snapshot = yield* provider.refresh;
|
||||
|
||||
assert.equal(snapshot.status, "error");
|
||||
assert.equal(snapshot.installed, true);
|
||||
assert.equal(
|
||||
snapshot.message,
|
||||
"Couldn't reach the configured OpenCode server at http://127.0.0.1:9999. Check that the server is running and the URL is correct.",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,342 @@
|
||||
import type { OpenCodeSettings, ServerProvider } from "@t3tools/contracts";
|
||||
import { Cause, Effect, Equal, Layer, Stream } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";
|
||||
import {
|
||||
buildServerProvider,
|
||||
isCommandMissingCause,
|
||||
parseGenericCliVersion,
|
||||
providerModelsFromSettings,
|
||||
} from "../providerSnapshot.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import {
|
||||
connectToOpenCodeServer,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
createOpenCodeSdkClient,
|
||||
flattenOpenCodeModels,
|
||||
loadOpenCodeInventory,
|
||||
runOpenCodeCommand,
|
||||
} from "../opencodeRuntime.ts";
|
||||
|
||||
const PROVIDER = "opencode" as const;
|
||||
|
||||
class OpenCodeProbePromiseError extends Error {
|
||||
override readonly cause: unknown;
|
||||
|
||||
constructor(cause: unknown) {
|
||||
super(cause instanceof Error ? cause.message : String(cause));
|
||||
this.cause = cause;
|
||||
this.name = "OpenCodeProbePromiseError";
|
||||
}
|
||||
}
|
||||
|
||||
function toOpenCodeProbeError(cause: unknown): OpenCodeProbePromiseError {
|
||||
return new OpenCodeProbePromiseError(cause);
|
||||
}
|
||||
|
||||
function normalizedErrorMessage(cause: unknown): string | undefined {
|
||||
if (!(cause instanceof Error)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const message = cause.message.trim();
|
||||
if (message.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
message === "An error occurred in Effect.tryPromise" ||
|
||||
message === "An error occurred in Effect.try"
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
function formatOpenCodeProbeError(input: {
|
||||
readonly cause: unknown;
|
||||
readonly isExternalServer: boolean;
|
||||
readonly serverUrl: string;
|
||||
}): { readonly installed: boolean; readonly message: string } {
|
||||
const lower = input.cause instanceof Error ? input.cause.message.toLowerCase() : "";
|
||||
const detail = normalizedErrorMessage(input.cause);
|
||||
|
||||
if (input.isExternalServer) {
|
||||
if (
|
||||
lower.includes("401") ||
|
||||
lower.includes("403") ||
|
||||
lower.includes("unauthorized") ||
|
||||
lower.includes("forbidden")
|
||||
) {
|
||||
return {
|
||||
installed: true,
|
||||
message: "OpenCode server rejected authentication. Check the server URL and password.",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes("econnrefused") ||
|
||||
lower.includes("enotfound") ||
|
||||
lower.includes("fetch failed") ||
|
||||
lower.includes("networkerror") ||
|
||||
lower.includes("timed out") ||
|
||||
lower.includes("timeout") ||
|
||||
lower.includes("socket hang up")
|
||||
) {
|
||||
return {
|
||||
installed: true,
|
||||
message: `Couldn't reach the configured OpenCode server at ${input.serverUrl}. Check that the server is running and the URL is correct.`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
installed: true,
|
||||
message: detail ?? "Failed to connect to the configured OpenCode server.",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.cause instanceof Error && isCommandMissingCause(input.cause)) {
|
||||
return {
|
||||
installed: false,
|
||||
message: "OpenCode CLI (`opencode`) is not installed or not on PATH.",
|
||||
};
|
||||
}
|
||||
|
||||
if (lower.includes("quarantine")) {
|
||||
return {
|
||||
installed: true,
|
||||
message:
|
||||
"macOS is blocking the OpenCode binary (quarantine). Run `xattr -d com.apple.quarantine $(which opencode)` to fix this.",
|
||||
};
|
||||
}
|
||||
|
||||
if (lower.includes("invalid code signature") || lower.includes("corrupted")) {
|
||||
return {
|
||||
installed: true,
|
||||
message:
|
||||
"macOS killed the OpenCode process due to an invalid code signature. The binary may be corrupted — try reinstalling OpenCode.",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
installed: true,
|
||||
message: detail
|
||||
? `Failed to execute OpenCode CLI health check: ${detail}`
|
||||
: "Failed to execute OpenCode CLI health check.",
|
||||
};
|
||||
}
|
||||
|
||||
const makePendingOpenCodeProvider = (openCodeSettings: OpenCodeSettings): ServerProvider => {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const models = providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
openCodeSettings.customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
if (!openCodeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
openCodeSettings.serverUrl.trim().length > 0
|
||||
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
|
||||
: "OpenCode is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "OpenCode provider status has not been checked in this session yet.",
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
export function checkOpenCodeProviderStatus(input: {
|
||||
readonly settings: OpenCodeSettings;
|
||||
readonly cwd: string;
|
||||
}): Effect.Effect<ServerProvider> {
|
||||
const checkedAt = new Date().toISOString();
|
||||
const customModels = input.settings.customModels;
|
||||
const isExternalServer = input.settings.serverUrl.trim().length > 0;
|
||||
|
||||
const fallback = (cause: unknown, version: string | null = null) => {
|
||||
const failure = formatOpenCodeProbeError({
|
||||
cause,
|
||||
isExternalServer,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
});
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: input.settings.enabled,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: failure.installed,
|
||||
version,
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: failure.message,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
if (!input.settings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models: providerModelsFromSettings(
|
||||
[],
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
),
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: isExternalServer
|
||||
? "OpenCode is disabled in T3 Code settings. A server URL is configured."
|
||||
: "OpenCode is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
let version: string | null = null;
|
||||
if (!isExternalServer) {
|
||||
const versionExit = yield* Effect.exit(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
runOpenCodeCommand({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
args: ["--version"],
|
||||
}),
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
);
|
||||
if (versionExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(versionExit.cause));
|
||||
}
|
||||
version = parseGenericCliVersion(versionExit.value.stdout) ?? null;
|
||||
}
|
||||
|
||||
const inventoryExit = yield* Effect.exit(
|
||||
Effect.acquireUseRelease(
|
||||
Effect.tryPromise({
|
||||
try: () =>
|
||||
connectToOpenCodeServer({
|
||||
binaryPath: input.settings.binaryPath,
|
||||
serverUrl: input.settings.serverUrl,
|
||||
}),
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
(server) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
const client = createOpenCodeSdkClient({
|
||||
baseUrl: server.url,
|
||||
directory: input.cwd,
|
||||
...(isExternalServer && input.settings.serverPassword
|
||||
? { serverPassword: input.settings.serverPassword }
|
||||
: {}),
|
||||
});
|
||||
return await loadOpenCodeInventory(client);
|
||||
},
|
||||
catch: toOpenCodeProbeError,
|
||||
}),
|
||||
(server) => Effect.sync(() => server.close()),
|
||||
),
|
||||
);
|
||||
if (inventoryExit._tag === "Failure") {
|
||||
return fallback(Cause.squash(inventoryExit.cause), version);
|
||||
}
|
||||
|
||||
const models = providerModelsFromSettings(
|
||||
flattenOpenCodeModels(inventoryExit.value),
|
||||
PROVIDER,
|
||||
customModels,
|
||||
DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
);
|
||||
const connectedCount = inventoryExit.value.providerList.connected.length;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: true,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version,
|
||||
status: connectedCount > 0 ? "ready" : "warning",
|
||||
auth: {
|
||||
status: connectedCount > 0 ? "authenticated" : "unknown",
|
||||
type: "opencode",
|
||||
},
|
||||
message:
|
||||
connectedCount > 0
|
||||
? `${connectedCount} upstream provider${connectedCount === 1 ? "" : "s"} connected through ${isExternalServer ? "the configured OpenCode server" : "OpenCode"}.`
|
||||
: isExternalServer
|
||||
? "Connected to the configured OpenCode server, but it did not report any connected upstream providers."
|
||||
: "OpenCode is available, but it did not report any connected upstream providers.",
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function makeOpenCodeProviderLive() {
|
||||
return Layer.effect(
|
||||
OpenCodeProvider,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig;
|
||||
|
||||
const getProviderSettings = serverSettings.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.opencode),
|
||||
);
|
||||
|
||||
return yield* makeManagedServerProvider<OpenCodeSettings>({
|
||||
getSettings: getProviderSettings.pipe(Effect.orDie),
|
||||
streamSettings: serverSettings.streamChanges.pipe(
|
||||
Stream.map((settings) => settings.providers.opencode),
|
||||
),
|
||||
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
|
||||
initialSnapshot: makePendingOpenCodeProvider,
|
||||
checkProvider: getProviderSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
checkOpenCodeProviderStatus({
|
||||
settings,
|
||||
cwd: serverConfig.cwd,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const OpenCodeProviderLive = makeOpenCodeProviderLive();
|
||||
@@ -8,6 +8,10 @@ import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import type { ClaudeAdapterShape } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import type { CodexAdapterShape } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import type { CursorAdapterShape } from "../Services/CursorAdapter.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
import type { OpenCodeAdapterShape } from "../Services/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./ProviderAdapterRegistry.ts";
|
||||
import { ProviderUnsupportedError } from "../Errors.ts";
|
||||
@@ -47,6 +51,40 @@ const fakeClaudeAdapter: ClaudeAdapterShape = {
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeOpenCodeAdapter: OpenCodeAdapterShape = {
|
||||
provider: "opencode",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const fakeCursorAdapter: CursorAdapterShape = {
|
||||
provider: "cursor",
|
||||
capabilities: { sessionModelSwitch: "in-session" },
|
||||
startSession: vi.fn(),
|
||||
sendTurn: vi.fn(),
|
||||
interruptTurn: vi.fn(),
|
||||
respondToRequest: vi.fn(),
|
||||
respondToUserInput: vi.fn(),
|
||||
stopSession: vi.fn(),
|
||||
listSessions: vi.fn(),
|
||||
hasSession: vi.fn(),
|
||||
readThread: vi.fn(),
|
||||
rollbackThread: vi.fn(),
|
||||
stopAll: vi.fn(),
|
||||
streamEvents: Stream.empty,
|
||||
};
|
||||
|
||||
const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
Layer.provide(
|
||||
@@ -54,6 +92,8 @@ const layer = it.layer(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(CodexAdapter, fakeCodexAdapter),
|
||||
Layer.succeed(ClaudeAdapter, fakeClaudeAdapter),
|
||||
Layer.succeed(OpenCodeAdapter, fakeOpenCodeAdapter),
|
||||
Layer.succeed(CursorAdapter, fakeCursorAdapter),
|
||||
),
|
||||
),
|
||||
NodeServices.layer,
|
||||
@@ -66,11 +106,15 @@ layer("ProviderAdapterRegistryLive", (it) => {
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const codex = yield* registry.getByProvider("codex");
|
||||
const claude = yield* registry.getByProvider("claudeAgent");
|
||||
const openCode = yield* registry.getByProvider("opencode");
|
||||
const cursor = yield* registry.getByProvider("cursor");
|
||||
assert.equal(codex, fakeCodexAdapter);
|
||||
assert.equal(claude, fakeClaudeAdapter);
|
||||
assert.equal(openCode, fakeOpenCodeAdapter);
|
||||
assert.equal(cursor, fakeCursorAdapter);
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent"]);
|
||||
assert.deepEqual(providers, ["codex", "claudeAgent", "opencode", "cursor"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ import {
|
||||
} from "../Services/ProviderAdapterRegistry.ts";
|
||||
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
|
||||
import { CodexAdapter } from "../Services/CodexAdapter.ts";
|
||||
import { CursorAdapter } from "../Services/CursorAdapter.ts";
|
||||
import { OpenCodeAdapter } from "../Services/OpenCodeAdapter.ts";
|
||||
|
||||
export interface ProviderAdapterRegistryLiveOptions {
|
||||
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
|
||||
@@ -25,10 +27,16 @@ export interface ProviderAdapterRegistryLiveOptions {
|
||||
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
|
||||
options?: ProviderAdapterRegistryLiveOptions,
|
||||
) {
|
||||
const cursorAdapterOption = yield* Effect.serviceOption(CursorAdapter);
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter];
|
||||
: [
|
||||
yield* CodexAdapter,
|
||||
yield* ClaudeAdapter,
|
||||
yield* OpenCodeAdapter,
|
||||
...(cursorAdapterOption._tag === "Some" ? [cursorAdapterOption.value] : []),
|
||||
];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
|
||||
@@ -30,14 +30,34 @@ import {
|
||||
readCodexConfigModelProvider,
|
||||
} from "./CodexProvider.ts";
|
||||
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider.ts";
|
||||
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry.ts";
|
||||
import {
|
||||
haveProvidersChanged,
|
||||
mergeProviderSnapshot,
|
||||
ProviderRegistryLive,
|
||||
} from "./ProviderRegistry.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
|
||||
|
||||
process.env.T3CODE_CURSOR_ENABLED = "1";
|
||||
|
||||
// ── Test helpers ────────────────────────────────────────────────────
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const fakeOpenCodeSnapshot: ServerProvider = {
|
||||
provider: "opencode",
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: false,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: null,
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
message: "OpenCode test stub",
|
||||
};
|
||||
|
||||
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
@@ -563,10 +583,106 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
|
||||
});
|
||||
|
||||
it.effect("does not probe provider health during registry startup", () =>
|
||||
it("preserves previously discovered provider models when a refresh returns none", () => {
|
||||
const previousProvider = {
|
||||
provider: "cursor",
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [{ value: "high", label: "High", isDefault: true }],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...previousProvider,
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it("fills missing capabilities from the previous provider snapshot", () => {
|
||||
const previousProvider = {
|
||||
provider: "cursor",
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-14T00:00:00.000Z",
|
||||
version: "2026.04.09-f2b0fcd",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [{ value: "high", label: "High", isDefault: true }],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshedProvider = {
|
||||
...previousProvider,
|
||||
checkedAt: "2026-04-14T00:01:00.000Z",
|
||||
models: [
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Opus 4.6",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
} satisfies ServerProvider;
|
||||
|
||||
assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [
|
||||
...previousProvider.models,
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("probes enabled providers in the background during registry startup", () =>
|
||||
Effect.gen(function* () {
|
||||
let spawnCount = 0;
|
||||
const serverSettings = yield* makeMutableServerSettingsService();
|
||||
const serverSettings = yield* makeMutableServerSettingsService(
|
||||
Schema.decodeSync(ServerSettings)(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, {
|
||||
providers: {
|
||||
claudeAgent: { enabled: false },
|
||||
cursor: { enabled: false },
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
@@ -596,20 +712,24 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ServerSettingsService, serverSettings),
|
||||
providerRegistryLayer,
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
assert.deepStrictEqual(yield* registry.getProviders, []);
|
||||
assert.strictEqual(spawnCount, 0);
|
||||
|
||||
const refreshed = yield* registry.refresh("codex");
|
||||
assert.strictEqual(spawnCount > 0, true);
|
||||
const refreshed = yield* Effect.gen(function* () {
|
||||
for (let remainingAttempts = 50; remainingAttempts > 0; remainingAttempts -= 1) {
|
||||
const providers = yield* registry.getProviders;
|
||||
const codexProvider = providers.find((provider) => provider.provider === "codex");
|
||||
if (codexProvider?.status === "ready") {
|
||||
return providers;
|
||||
}
|
||||
yield* Effect.sleep("10 millis");
|
||||
}
|
||||
return yield* registry.getProviders;
|
||||
});
|
||||
assert.strictEqual(
|
||||
refreshed.find((provider) => provider.provider === "codex")?.status,
|
||||
"ready",
|
||||
@@ -630,6 +750,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(OpenCodeProvider, {
|
||||
getSnapshot: Effect.succeed(fakeOpenCodeSnapshot),
|
||||
refresh: Effect.succeed(fakeOpenCodeSnapshot),
|
||||
streamChanges: Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
const joined = args.join(" ");
|
||||
@@ -639,6 +766,19 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
}
|
||||
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
|
||||
}
|
||||
if (joined === "about --format json") {
|
||||
return {
|
||||
stdout: JSON.stringify({
|
||||
cliVersion: "2026.04.09-f2b0fcd",
|
||||
userEmail: null,
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
};
|
||||
}
|
||||
if (joined === "about") {
|
||||
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
|
||||
}
|
||||
if (joined === "login status") {
|
||||
return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
}
|
||||
@@ -646,19 +786,13 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ServerSettingsService, serverSettings),
|
||||
providerRegistryLayer,
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
const runtimeServices = yield* Layer.build(providerRegistryLayer).pipe(
|
||||
Scope.provide(scope),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
|
||||
const initial = yield* registry.getProviders;
|
||||
assert.deepStrictEqual(initial, []);
|
||||
|
||||
const refreshed = yield* registry.refresh("codex");
|
||||
assert.strictEqual(
|
||||
refreshed.find((status) => status.provider === "codex")?.status,
|
||||
@@ -690,6 +824,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"keeps cursor disabled and skips probing when the provider setting is disabled",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* makeMutableServerSettingsService(
|
||||
Schema.decodeSync(ServerSettings)(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, {
|
||||
providers: {
|
||||
cursor: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
let cursorSpawned = false;
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const providerRegistryLayer = ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
mockCommandSpawnerLayer((command, args) => {
|
||||
if (command === "agent") {
|
||||
cursorSpawned = true;
|
||||
}
|
||||
const joined = args.join(" ");
|
||||
if (joined === "--version") {
|
||||
return { stdout: `${command} 1.0.0\n`, stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "login status") {
|
||||
return { stdout: "Logged in\n", stderr: "", code: 0 };
|
||||
}
|
||||
if (joined === "auth status") {
|
||||
return { stdout: '{"authenticated":true}\n', stderr: "", code: 0 };
|
||||
}
|
||||
throw new Error(`Unexpected args: ${command} ${joined}`);
|
||||
}),
|
||||
),
|
||||
);
|
||||
const runtimeServices = yield* Layer.build(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(ServerSettingsService, serverSettings),
|
||||
providerRegistryLayer,
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
const providers = yield* registry.getProviders;
|
||||
const cursorProvider = providers.find((provider) => provider.provider === "cursor");
|
||||
|
||||
assert.deepStrictEqual(
|
||||
providers.map((provider) => provider.provider),
|
||||
["codex", "claudeAgent", "opencode", "cursor"],
|
||||
);
|
||||
assert.strictEqual(cursorProvider?.enabled, false);
|
||||
assert.strictEqual(cursorProvider?.status, "disabled");
|
||||
assert.strictEqual(
|
||||
cursorProvider?.message,
|
||||
"Cursor is disabled in T3 Code settings.",
|
||||
);
|
||||
assert.strictEqual(cursorSpawned, false);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips codex probes entirely when the provider is disabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest({
|
||||
|
||||
@@ -9,10 +9,12 @@ import { Effect, Equal, FileSystem, Layer, Path, PubSub, Ref, Stream } from "eff
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ClaudeProviderLive } from "./ClaudeProvider.ts";
|
||||
import { CodexProviderLive } from "./CodexProvider.ts";
|
||||
import type { ClaudeProviderShape } from "../Services/ClaudeProvider.ts";
|
||||
import { CursorProviderLive } from "./CursorProvider.ts";
|
||||
import { OpenCodeProviderLive } from "./OpenCodeProvider.ts";
|
||||
import { ClaudeProvider } from "../Services/ClaudeProvider.ts";
|
||||
import type { CodexProviderShape } from "../Services/CodexProvider.ts";
|
||||
import { CodexProvider } from "../Services/CodexProvider.ts";
|
||||
import { CursorProvider } from "../Services/CursorProvider.ts";
|
||||
import { OpenCodeProvider } from "../Services/OpenCodeProvider.ts";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry.ts";
|
||||
import {
|
||||
hydrateCachedProvider,
|
||||
@@ -23,34 +25,112 @@ import {
|
||||
writeProviderStatusCache,
|
||||
} from "../providerStatusCache.ts";
|
||||
|
||||
type ProviderSnapshotSource = {
|
||||
readonly provider: ProviderKind;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly refresh: Effect.Effect<ServerProvider>;
|
||||
readonly streamChanges: Stream.Stream<ServerProvider>;
|
||||
};
|
||||
|
||||
const loadProviders = (
|
||||
codexProvider: CodexProviderShape,
|
||||
claudeProvider: ClaudeProviderShape,
|
||||
): Effect.Effect<readonly [ServerProvider, ServerProvider]> =>
|
||||
Effect.all([codexProvider.getSnapshot, claudeProvider.getSnapshot], {
|
||||
providerSources: ReadonlyArray<ProviderSnapshotSource>,
|
||||
): Effect.Effect<ReadonlyArray<ServerProvider>> =>
|
||||
Effect.forEach(providerSources, (providerSource) => providerSource.getSnapshot, {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
|
||||
const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean =>
|
||||
(model.capabilities?.reasoningEffortLevels.length ?? 0) > 0 ||
|
||||
model.capabilities?.supportsFastMode === true ||
|
||||
model.capabilities?.supportsThinkingToggle === true ||
|
||||
(model.capabilities?.contextWindowOptions.length ?? 0) > 0 ||
|
||||
(model.capabilities?.promptInjectedEffortLevels.length ?? 0) > 0;
|
||||
|
||||
const mergeProviderModels = (
|
||||
previousModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
if (nextModels.length === 0 && previousModels.length > 0) {
|
||||
return previousModels;
|
||||
}
|
||||
|
||||
const previousBySlug = new Map(previousModels.map((model) => [model.slug, model] as const));
|
||||
const mergedModels = nextModels.map((model) => {
|
||||
const previousModel = previousBySlug.get(model.slug);
|
||||
if (!previousModel || hasModelCapabilities(model) || !hasModelCapabilities(previousModel)) {
|
||||
return model;
|
||||
}
|
||||
return {
|
||||
...model,
|
||||
capabilities: previousModel.capabilities,
|
||||
};
|
||||
});
|
||||
const nextSlugs = new Set(nextModels.map((model) => model.slug));
|
||||
return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))];
|
||||
};
|
||||
|
||||
export const mergeProviderSnapshot = (
|
||||
previousProvider: ServerProvider | undefined,
|
||||
nextProvider: ServerProvider,
|
||||
): ServerProvider =>
|
||||
!previousProvider
|
||||
? nextProvider
|
||||
: {
|
||||
...nextProvider,
|
||||
models: mergeProviderModels(previousProvider.models, nextProvider.models),
|
||||
};
|
||||
|
||||
export const haveProvidersChanged = (
|
||||
previousProviders: ReadonlyArray<ServerProvider>,
|
||||
nextProviders: ReadonlyArray<ServerProvider>,
|
||||
): boolean => !Equal.equals(previousProviders, nextProviders);
|
||||
|
||||
export const ProviderRegistryLive = Layer.effect(
|
||||
const ProviderRegistryLiveBase = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexProvider = yield* CodexProvider;
|
||||
const claudeProvider = yield* ClaudeProvider;
|
||||
const openCodeProvider = yield* OpenCodeProvider;
|
||||
const config = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const cursorProvider = yield* CursorProvider;
|
||||
|
||||
const providerSources = [
|
||||
{
|
||||
provider: "codex",
|
||||
getSnapshot: codexProvider.getSnapshot,
|
||||
refresh: codexProvider.refresh,
|
||||
streamChanges: codexProvider.streamChanges,
|
||||
},
|
||||
{
|
||||
provider: "claudeAgent",
|
||||
getSnapshot: claudeProvider.getSnapshot,
|
||||
refresh: claudeProvider.refresh,
|
||||
streamChanges: claudeProvider.streamChanges,
|
||||
},
|
||||
{
|
||||
provider: "opencode",
|
||||
getSnapshot: openCodeProvider.getSnapshot,
|
||||
refresh: openCodeProvider.refresh,
|
||||
streamChanges: openCodeProvider.streamChanges,
|
||||
},
|
||||
{
|
||||
provider: "cursor",
|
||||
getSnapshot: cursorProvider.getSnapshot,
|
||||
refresh: cursorProvider.refresh,
|
||||
streamChanges: cursorProvider.streamChanges,
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderSnapshotSource>;
|
||||
const activeProviders = PROVIDER_CACHE_IDS;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const fallbackProviders = yield* loadProviders(codexProvider, claudeProvider);
|
||||
const fallbackProviders = yield* loadProviders(providerSources);
|
||||
const cachePathByProvider = new Map(
|
||||
PROVIDER_CACHE_IDS.map(
|
||||
activeProviders.map(
|
||||
(provider) =>
|
||||
[
|
||||
provider,
|
||||
@@ -64,8 +144,9 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
const fallbackByProvider = new Map(
|
||||
fallbackProviders.map((provider) => [provider.provider, provider] as const),
|
||||
);
|
||||
|
||||
const cachedProviders = yield* Effect.forEach(
|
||||
PROVIDER_CACHE_IDS,
|
||||
activeProviders,
|
||||
(provider) => {
|
||||
const filePath = cachePathByProvider.get(provider)!;
|
||||
const fallbackProvider = fallbackByProvider.get(provider)!;
|
||||
@@ -116,7 +197,10 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
);
|
||||
|
||||
for (const provider of nextProviders) {
|
||||
mergedProviders.set(provider.provider, provider);
|
||||
mergedProviders.set(
|
||||
provider.provider,
|
||||
mergeProviderSnapshot(mergedProviders.get(provider.provider), provider),
|
||||
);
|
||||
}
|
||||
|
||||
const providers = orderProviderSnapshots([...mergedProviders.values()]);
|
||||
@@ -147,39 +231,40 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
});
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
return yield* codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
case "claudeAgent":
|
||||
return yield* claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
default:
|
||||
return yield* Effect.all(
|
||||
[
|
||||
codexProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
claudeProvider.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
),
|
||||
],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
if (provider) {
|
||||
const providerSource = providerSources.find((candidate) => candidate.provider === provider);
|
||||
if (!providerSource) {
|
||||
return yield* Ref.get(providersRef);
|
||||
}
|
||||
return yield* providerSource.refresh.pipe(
|
||||
Effect.flatMap((nextProvider) => syncProvider(nextProvider)),
|
||||
);
|
||||
}
|
||||
|
||||
return yield* Effect.forEach(
|
||||
providerSources,
|
||||
(providerSource) => providerSource.refresh.pipe(Effect.flatMap(syncProvider)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
).pipe(Effect.andThen(Ref.get(providersRef)));
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Stream.runForEach(claudeProvider.streamChanges, (provider) =>
|
||||
syncProvider(provider),
|
||||
).pipe(Effect.forkScoped);
|
||||
yield* Effect.forEach(
|
||||
providerSources,
|
||||
(providerSource) =>
|
||||
Stream.runForEach(providerSource.streamChanges, (provider) => syncProvider(provider)).pipe(
|
||||
Effect.forkScoped,
|
||||
),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
discard: true,
|
||||
},
|
||||
);
|
||||
yield* loadProviders(providerSources).pipe(
|
||||
Effect.flatMap((providers) => upsertProviders(providers, { publish: false })),
|
||||
);
|
||||
|
||||
return {
|
||||
getProviders: Ref.get(providersRef),
|
||||
@@ -193,4 +278,15 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
},
|
||||
} satisfies ProviderRegistryShape;
|
||||
}),
|
||||
).pipe(Layer.provideMerge(CodexProviderLive), Layer.provideMerge(ClaudeProviderLive));
|
||||
);
|
||||
|
||||
export const ProviderRegistryLive = Layer.unwrap(
|
||||
Effect.sync(() =>
|
||||
ProviderRegistryLiveBase.pipe(
|
||||
Layer.provideMerge(CursorProviderLive),
|
||||
Layer.provideMerge(CodexProviderLive),
|
||||
Layer.provideMerge(ClaudeProviderLive),
|
||||
Layer.provideMerge(OpenCodeProviderLive),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { it, assert, vi } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
|
||||
import { Effect, Fiber, Layer, Metric, Option, PubSub, Ref, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -246,14 +245,17 @@ const hasMetricSnapshot = (
|
||||
function makeProviderServiceLayer() {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
const claude = makeFakeCodexAdapter("claudeAgent");
|
||||
const cursor = makeFakeCodexAdapter("cursor");
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(codex.adapter)
|
||||
: provider === "claudeAgent"
|
||||
? Effect.succeed(claude.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
|
||||
: provider === "cursor"
|
||||
? Effect.succeed(cursor.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex", "claudeAgent", "cursor"]),
|
||||
};
|
||||
|
||||
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
|
||||
@@ -280,6 +282,7 @@ function makeProviderServiceLayer() {
|
||||
return {
|
||||
codex,
|
||||
claude,
|
||||
cursor,
|
||||
layer,
|
||||
};
|
||||
}
|
||||
@@ -334,6 +337,62 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
|
||||
);
|
||||
|
||||
const routing = makeProviderServiceLayer();
|
||||
|
||||
it.effect("ProviderServiceLive writes canonical events to the emitting thread segment", () =>
|
||||
Effect.gen(function* () {
|
||||
const codex = makeFakeCodexAdapter();
|
||||
const canonicalEvents: ProviderRuntimeEvent[] = [];
|
||||
const canonicalThreadIds: Array<string | null> = [];
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(codex.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
|
||||
Layer.provide(SqlitePersistenceMemory),
|
||||
);
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
|
||||
const providerLayer = makeProviderServiceLive({
|
||||
canonicalEventLogger: {
|
||||
filePath: "memory://provider-canonical-events",
|
||||
write: (event, threadId) => {
|
||||
canonicalEvents.push(event as ProviderRuntimeEvent);
|
||||
canonicalThreadIds.push(threadId ?? null);
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* ProviderService;
|
||||
yield* sleep(10);
|
||||
codex.emit({
|
||||
eventId: asEventId("evt-canonical-thread-segment"),
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-canonical-thread-segment"),
|
||||
createdAt: new Date().toISOString(),
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
yield* sleep(20);
|
||||
}).pipe(Effect.provide(providerLayer));
|
||||
|
||||
assert.equal(canonicalEvents.length, 1);
|
||||
assert.equal(canonicalEvents[0]?.threadId, "thread-canonical-thread-segment");
|
||||
assert.deepEqual(canonicalThreadIds, ["thread-canonical-thread-segment"]);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", () =>
|
||||
Effect.gen(function* () {
|
||||
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-"));
|
||||
@@ -574,20 +633,31 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
});
|
||||
|
||||
yield* provider.stopSession({ threadId: session.threadId });
|
||||
const sendAfterStop = yield* Effect.result(
|
||||
provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "after-stop",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
assertFailure(
|
||||
sendAfterStop,
|
||||
new ProviderValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
issue: `Cannot route thread '${session.threadId}' because no persisted provider binding exists.`,
|
||||
}),
|
||||
);
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.sendTurn.mockClear();
|
||||
|
||||
yield* provider.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "after-stop",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.equal(routing.codex.startSession.mock.calls.length, 1);
|
||||
const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
|
||||
if (resumedStartInput && typeof resumedStartInput === "object") {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "codex");
|
||||
assert.equal(startPayload.cwd, "/tmp/project");
|
||||
assert.deepEqual(startPayload.resumeCursor, session.resumeCursor);
|
||||
assert.equal(startPayload.threadId, session.threadId);
|
||||
}
|
||||
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -631,6 +701,57 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves the persisted binding when stopping a session", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-reap-preserve"), {
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-reap-preserve"),
|
||||
cwd: "/tmp/project-reap-preserve",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* provider.stopSession({ threadId: initial.threadId });
|
||||
|
||||
const persistedAfterStop = yield* runtimeRepository.getByThreadId({
|
||||
threadId: initial.threadId,
|
||||
});
|
||||
assert.equal(Option.isSome(persistedAfterStop), true);
|
||||
if (Option.isSome(persistedAfterStop)) {
|
||||
assert.equal(persistedAfterStop.value.status, "stopped");
|
||||
assert.deepEqual(persistedAfterStop.value.resumeCursor, initial.resumeCursor);
|
||||
}
|
||||
|
||||
routing.codex.startSession.mockClear();
|
||||
routing.codex.sendTurn.mockClear();
|
||||
|
||||
yield* provider.sendTurn({
|
||||
threadId: initial.threadId,
|
||||
input: "resume after reap",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.equal(routing.codex.startSession.mock.calls.length, 1);
|
||||
const resumedStartInput = routing.codex.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
|
||||
if (resumedStartInput && typeof resumedStartInput === "object") {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "codex");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-reap-preserve");
|
||||
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
|
||||
assert.equal(startPayload.threadId, initial.threadId);
|
||||
}
|
||||
assert.equal(routing.codex.sendTurn.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("routes explicit claudeAgent provider session starts to the claude adapter", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
@@ -161,7 +161,9 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Effect.succeed(event).pipe(
|
||||
Effect.tap((canonicalEvent) =>
|
||||
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
|
||||
canonicalEventLogger
|
||||
? canonicalEventLogger.write(canonicalEvent, canonicalEvent.threadId)
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||
Effect.asVoid,
|
||||
@@ -620,7 +622,14 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
if (routed.isActive) {
|
||||
yield* routed.adapter.stopSession(routed.threadId);
|
||||
}
|
||||
yield* directory.remove(input.threadId);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
status: "stopped",
|
||||
runtimePayload: {
|
||||
activeTurnId: null,
|
||||
},
|
||||
});
|
||||
yield* analytics.record("provider.session.stopped", {
|
||||
provider: routed.adapter.provider,
|
||||
});
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { assertFailure, assertSome } from "@effect/vitest/utils";
|
||||
import { assertSome } from "@effect/vitest/utils";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
} from "../../persistence/Layers/Sqlite.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionDirectoryPersistenceError } from "../Errors.ts";
|
||||
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
|
||||
import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts";
|
||||
|
||||
@@ -31,7 +30,7 @@ function makeDirectoryLayer<E, R>(persistenceLayer: Layer.Layer<SqlClient.SqlCli
|
||||
}
|
||||
|
||||
it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryLive", (it) => {
|
||||
it("upserts, reads, and removes thread bindings", () =>
|
||||
it("upserts and reads thread bindings", () =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeRepository = yield* ProviderSessionRuntimeRepository;
|
||||
@@ -76,16 +75,6 @@ it.layer(makeDirectoryLayer(SqlitePersistenceMemory))("ProviderSessionDirectoryL
|
||||
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
assert.deepEqual(threadIds, [nextThreadId]);
|
||||
|
||||
yield* directory.remove(nextThreadId);
|
||||
const missingProvider = yield* directory.getProvider(nextThreadId).pipe(Effect.result);
|
||||
assertFailure(
|
||||
missingProvider,
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation: "ProviderSessionDirectory.getProvider",
|
||||
detail: `No persisted provider binding found for thread '${nextThreadId}'.`,
|
||||
}),
|
||||
);
|
||||
}));
|
||||
|
||||
it("persists runtime fields and merges payload updates", () =>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type ProviderKind, type ThreadId } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
import { ProviderKind, type ThreadId } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
|
||||
import type { ProviderSessionRuntime } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
import { ProviderSessionRuntimeRepository } from "../../persistence/Services/ProviderSessionRuntime.ts";
|
||||
@@ -24,14 +24,15 @@ function decodeProviderKind(
|
||||
providerName: string,
|
||||
operation: string,
|
||||
): Effect.Effect<ProviderKind, ProviderSessionDirectoryPersistenceError> {
|
||||
if (providerName === "codex" || providerName === "claudeAgent") {
|
||||
return Effect.succeed(providerName);
|
||||
}
|
||||
return Effect.fail(
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Unknown persisted provider '${providerName}'.`,
|
||||
}),
|
||||
return Schema.decodeUnknownEffect(ProviderKind)(providerName).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderSessionDirectoryPersistenceError({
|
||||
operation,
|
||||
detail: `Unknown persisted provider '${providerName}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -145,13 +146,6 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const remove: ProviderSessionDirectoryShape["remove"] = (threadId) =>
|
||||
repository
|
||||
.deleteByThreadId({ threadId })
|
||||
.pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.remove:deleteByThreadId")),
|
||||
);
|
||||
|
||||
const listThreadIds: ProviderSessionDirectoryShape["listThreadIds"] = () =>
|
||||
repository.list().pipe(
|
||||
Effect.mapError(toPersistenceError("ProviderSessionDirectory.listThreadIds:list")),
|
||||
@@ -174,7 +168,6 @@ const makeProviderSessionDirectory = Effect.gen(function* () {
|
||||
upsert,
|
||||
getProvider,
|
||||
getBinding,
|
||||
remove,
|
||||
listThreadIds,
|
||||
listBindings,
|
||||
} satisfies ProviderSessionDirectoryShape;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Context } from "effect";
|
||||
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
export interface CursorAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "cursor";
|
||||
}
|
||||
|
||||
export class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()(
|
||||
"t3/provider/Services/CursorAdapter",
|
||||
) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Context } from "effect";
|
||||
|
||||
import type { ServerProviderShape } from "./ServerProvider.ts";
|
||||
|
||||
export interface CursorProviderShape extends ServerProviderShape {}
|
||||
|
||||
export class CursorProvider extends Context.Service<CursorProvider, CursorProviderShape>()(
|
||||
"t3/provider/Services/CursorProvider",
|
||||
) {}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Context } from "effect";
|
||||
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
export interface OpenCodeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "opencode";
|
||||
}
|
||||
|
||||
export class OpenCodeAdapter extends Context.Service<OpenCodeAdapter, OpenCodeAdapterShape>()(
|
||||
"t3/provider/Services/OpenCodeAdapter",
|
||||
) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Context } from "effect";
|
||||
|
||||
import type { ServerProviderShape } from "./ServerProvider.ts";
|
||||
|
||||
export interface OpenCodeProviderShape extends ServerProviderShape {}
|
||||
|
||||
export class OpenCodeProvider extends Context.Service<OpenCodeProvider, OpenCodeProviderShape>()(
|
||||
"t3/provider/Services/OpenCodeProvider",
|
||||
) {}
|
||||
@@ -23,7 +23,7 @@ import type {
|
||||
import type { Effect } from "effect";
|
||||
import type { Stream } from "effect";
|
||||
|
||||
export type ProviderSessionModelSwitchMode = "in-session" | "restart-session" | "unsupported";
|
||||
export type ProviderSessionModelSwitchMode = "in-session" | "unsupported";
|
||||
|
||||
export interface ProviderAdapterCapabilities {
|
||||
/**
|
||||
|
||||
@@ -45,10 +45,6 @@ export interface ProviderSessionDirectoryShape {
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<ProviderRuntimeBinding>, ProviderSessionDirectoryReadError>;
|
||||
|
||||
readonly remove: (
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<void, ProviderSessionDirectoryPersistenceError>;
|
||||
|
||||
readonly listThreadIds: () => Effect.Effect<
|
||||
ReadonlyArray<ThreadId>,
|
||||
ProviderSessionDirectoryPersistenceError
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import { acpPermissionOutcome, mapAcpToAdapterError } from "./AcpAdapterSupport.ts";
|
||||
|
||||
describe("AcpAdapterSupport", () => {
|
||||
it("maps ACP approval decisions to permission outcomes", () => {
|
||||
expect(acpPermissionOutcome("accept")).toBe("allow-once");
|
||||
expect(acpPermissionOutcome("acceptForSession")).toBe("allow-always");
|
||||
expect(acpPermissionOutcome("decline")).toBe("reject-once");
|
||||
});
|
||||
|
||||
it("maps ACP request errors to provider adapter request errors", () => {
|
||||
const error = mapAcpToAdapterError(
|
||||
"cursor",
|
||||
"thread-1" as never,
|
||||
"session/prompt",
|
||||
new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: "Invalid params",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(error._tag).toBe("ProviderAdapterRequestError");
|
||||
expect(error.message).toContain("Invalid params");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import {
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderKind,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import {
|
||||
ProviderAdapterRequestError,
|
||||
ProviderAdapterSessionClosedError,
|
||||
type ProviderAdapterError,
|
||||
} from "../Errors.ts";
|
||||
|
||||
export function mapAcpToAdapterError(
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
method: string,
|
||||
error: EffectAcpErrors.AcpError,
|
||||
): ProviderAdapterError {
|
||||
if (Schema.is(EffectAcpErrors.AcpProcessExitedError)(error)) {
|
||||
return new ProviderAdapterSessionClosedError({
|
||||
provider,
|
||||
threadId,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
if (Schema.is(EffectAcpErrors.AcpRequestError)(error)) {
|
||||
return new ProviderAdapterRequestError({
|
||||
provider,
|
||||
method,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
return new ProviderAdapterRequestError({
|
||||
provider,
|
||||
method,
|
||||
detail: error.message,
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
|
||||
export function acpPermissionOutcome(decision: ProviderApprovalDecision): string {
|
||||
switch (decision) {
|
||||
case "acceptForSession":
|
||||
return "allow-always";
|
||||
case "accept":
|
||||
return "allow-once";
|
||||
case "decline":
|
||||
default:
|
||||
return "reject-once";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { RuntimeRequestId, TurnId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
makeAcpAssistantItemEvent,
|
||||
makeAcpContentDeltaEvent,
|
||||
makeAcpPlanUpdatedEvent,
|
||||
makeAcpRequestOpenedEvent,
|
||||
makeAcpRequestResolvedEvent,
|
||||
makeAcpToolCallEvent,
|
||||
} from "./AcpCoreRuntimeEvents.ts";
|
||||
|
||||
describe("AcpCoreRuntimeEvents", () => {
|
||||
it("maps ACP permission requests to canonical runtime events", () => {
|
||||
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const permissionRequest = {
|
||||
kind: "execute" as const,
|
||||
detail: "cat package.json",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
status: "pending" as const,
|
||||
command: "cat package.json",
|
||||
detail: "cat package.json",
|
||||
data: { toolCallId: "tool-1", kind: "execute" },
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
makeAcpRequestOpenedEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
requestId: RuntimeRequestId.make("request-1"),
|
||||
permissionRequest,
|
||||
detail: "cat package.json",
|
||||
args: { command: ["cat", "package.json"] },
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/request_permission",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: "exec_command_approval",
|
||||
detail: "cat package.json",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpRequestResolvedEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
requestId: RuntimeRequestId.make("request-1"),
|
||||
permissionRequest,
|
||||
decision: "accept",
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: "exec_command_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("maps ACP core plan, tool-call, and content updates", () => {
|
||||
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
|
||||
const turnId = TurnId.make("turn-1");
|
||||
|
||||
expect(
|
||||
makeAcpPlanUpdatedEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
payload: {
|
||||
plan: [{ step: "Inspect state", status: "inProgress" }],
|
||||
},
|
||||
source: "acp.cursor.extension",
|
||||
method: "cursor/update_todos",
|
||||
rawPayload: { todos: [] },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "turn.plan.updated",
|
||||
raw: {
|
||||
method: "cursor/update_todos",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpToolCallEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
title: "Terminal",
|
||||
detail: "bun run test",
|
||||
data: { command: "bun run test" },
|
||||
},
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
text: "hello",
|
||||
rawPayload: { sessionId: "session-1" },
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "content.delta",
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
payload: {
|
||||
delta: "hello",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
makeAcpAssistantItemEvent({
|
||||
stamp,
|
||||
provider: "cursor",
|
||||
threadId: "thread-1" as never,
|
||||
turnId,
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
lifecycle: "item.started",
|
||||
}),
|
||||
).toMatchObject({
|
||||
type: "item.started",
|
||||
itemId: "assistant:session-1:segment:0",
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "inProgress",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
import {
|
||||
type RuntimeEventRawSource,
|
||||
RuntimeItemId,
|
||||
type CanonicalRequestType,
|
||||
type EventId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderKind,
|
||||
type ProviderRuntimeEvent,
|
||||
type RuntimeRequestId,
|
||||
type ThreadId,
|
||||
type ToolLifecycleItemType,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { AcpPermissionRequest, AcpPlanUpdate, AcpToolCallState } from "./AcpRuntimeModel.ts";
|
||||
|
||||
type AcpAdapterRawSource = Extract<
|
||||
RuntimeEventRawSource,
|
||||
"acp.jsonrpc" | `acp.${string}.extension`
|
||||
>;
|
||||
|
||||
interface AcpEventStamp {
|
||||
readonly eventId: EventId;
|
||||
readonly createdAt: string;
|
||||
}
|
||||
|
||||
type AcpCanonicalRequestType = Extract<
|
||||
CanonicalRequestType,
|
||||
"exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown"
|
||||
>;
|
||||
|
||||
function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonicalRequestType {
|
||||
switch (kind) {
|
||||
case "execute":
|
||||
return "exec_command_approval";
|
||||
case "read":
|
||||
return "file_read_approval";
|
||||
case "edit":
|
||||
case "delete":
|
||||
case "move":
|
||||
return "file_change_approval";
|
||||
default:
|
||||
return "unknown";
|
||||
}
|
||||
}
|
||||
|
||||
function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
|
||||
switch (kind) {
|
||||
case "execute":
|
||||
return "command_execution";
|
||||
case "edit":
|
||||
case "delete":
|
||||
case "move":
|
||||
return "file_change";
|
||||
case "search":
|
||||
case "fetch":
|
||||
return "web_search";
|
||||
default:
|
||||
return "dynamic_tool_call";
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeItemStatusFromAcpToolStatus(
|
||||
status: AcpToolCallState["status"],
|
||||
): "inProgress" | "completed" | "failed" | undefined {
|
||||
switch (status) {
|
||||
case "pending":
|
||||
case "inProgress":
|
||||
return "inProgress";
|
||||
case "completed":
|
||||
return "completed";
|
||||
case "failed":
|
||||
return "failed";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function makeAcpRequestOpenedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly permissionRequest: AcpPermissionRequest;
|
||||
readonly detail: string;
|
||||
readonly args: unknown;
|
||||
readonly source: AcpAdapterRawSource;
|
||||
readonly method: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "request.opened",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
requestId: input.requestId,
|
||||
payload: {
|
||||
requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),
|
||||
detail: input.detail,
|
||||
args: input.args,
|
||||
},
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpRequestResolvedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly requestId: RuntimeRequestId;
|
||||
readonly permissionRequest: AcpPermissionRequest;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "request.resolved",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
requestId: input.requestId,
|
||||
payload: {
|
||||
requestType: canonicalRequestTypeFromAcpKind(input.permissionRequest.kind),
|
||||
decision: input.decision,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpPlanUpdatedEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly payload: AcpPlanUpdate;
|
||||
readonly source: AcpAdapterRawSource;
|
||||
readonly method: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "turn.plan.updated",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
payload: input.payload,
|
||||
raw: {
|
||||
source: input.source,
|
||||
method: input.method,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpToolCallEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly toolCall: AcpToolCallState;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
const runtimeStatus = runtimeItemStatusFromAcpToolStatus(input.toolCall.status);
|
||||
return {
|
||||
type:
|
||||
input.toolCall.status === "completed" || input.toolCall.status === "failed"
|
||||
? "item.completed"
|
||||
: "item.updated",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
itemId: RuntimeItemId.make(input.toolCall.toolCallId),
|
||||
payload: {
|
||||
itemType: canonicalItemTypeFromAcpToolKind(input.toolCall.kind),
|
||||
...(runtimeStatus ? { status: runtimeStatus } : {}),
|
||||
...(input.toolCall.title ? { title: input.toolCall.title } : {}),
|
||||
...(input.toolCall.detail ? { detail: input.toolCall.detail } : {}),
|
||||
...(Object.keys(input.toolCall.data).length > 0 ? { data: input.toolCall.data } : {}),
|
||||
},
|
||||
raw: {
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpAssistantItemEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly itemId: string;
|
||||
readonly lifecycle: "item.started" | "item.completed";
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: input.lifecycle,
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
itemId: RuntimeItemId.make(input.itemId),
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: input.lifecycle === "item.completed" ? "completed" : "inProgress",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpContentDeltaEvent(input: {
|
||||
readonly stamp: AcpEventStamp;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | undefined;
|
||||
readonly itemId?: string;
|
||||
readonly text: string;
|
||||
readonly rawPayload: unknown;
|
||||
}): ProviderRuntimeEvent {
|
||||
return {
|
||||
type: "content.delta",
|
||||
...input.stamp,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
...(input.itemId ? { itemId: RuntimeItemId.make(input.itemId) } : {}),
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: input.text,
|
||||
},
|
||||
raw: {
|
||||
source: "acp.jsonrpc",
|
||||
method: "session/update",
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
import * as path from "node:path";
|
||||
import * as os from "node:os";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { AcpSessionRuntime, type AcpSessionRequestLogEvent } from "./AcpSessionRuntime.ts";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
|
||||
const bunExe = "bun";
|
||||
|
||||
describe("AcpSessionRuntime", () => {
|
||||
it.effect("merges custom initialize client capabilities into the ACP handshake", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const initializeStarted = requestEvents.find(
|
||||
(event) => event.method === "initialize" && event.status === "started",
|
||||
);
|
||||
expect(initializeStarted?.payload).toMatchObject({
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
_meta: { parameterizedModelPicker: true },
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientCapabilities: {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
requestLogger: (event) =>
|
||||
Effect.sync(() => {
|
||||
requestEvents.push(event);
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("starts a session, prompts, and emits normalized events against the mock agent", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
|
||||
expect(started.initializeResult).toMatchObject({ protocolVersion: 1 });
|
||||
expect(started.sessionId).toBe("mock-session-1");
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
|
||||
expect(notes).toHaveLength(4);
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"PlanUpdated",
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
]);
|
||||
const planUpdate = notes.find((note) => note._tag === "PlanUpdated");
|
||||
expect(planUpdate?._tag).toBe("PlanUpdated");
|
||||
if (planUpdate?._tag === "PlanUpdated") {
|
||||
expect(planUpdate.payload.plan).toHaveLength(2);
|
||||
}
|
||||
const assistantStart = notes[1];
|
||||
const assistantDelta = notes[2];
|
||||
if (
|
||||
assistantStart?._tag === "AssistantItemStarted" &&
|
||||
assistantDelta?._tag === "ContentDelta"
|
||||
) {
|
||||
expect(assistantDelta.itemId).toBe(assistantStart.itemId);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("segments assistant text around ACP tool calls", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 7)));
|
||||
expect(notes.map((note) => note._tag)).toEqual([
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
"AssistantItemCompleted",
|
||||
"ToolCallUpdated",
|
||||
"ToolCallUpdated",
|
||||
"AssistantItemStarted",
|
||||
"ContentDelta",
|
||||
]);
|
||||
|
||||
const firstStarted = notes[0];
|
||||
const firstDelta = notes[1];
|
||||
const firstCompleted = notes[2];
|
||||
const secondStarted = notes[5];
|
||||
const secondDelta = notes[6];
|
||||
expect(firstStarted?._tag).toBe("AssistantItemStarted");
|
||||
expect(firstCompleted?._tag).toBe("AssistantItemCompleted");
|
||||
expect(secondStarted?._tag).toBe("AssistantItemStarted");
|
||||
if (
|
||||
firstStarted?._tag === "AssistantItemStarted" &&
|
||||
firstDelta?._tag === "ContentDelta" &&
|
||||
firstCompleted?._tag === "AssistantItemCompleted" &&
|
||||
secondStarted?._tag === "AssistantItemStarted" &&
|
||||
secondDelta?._tag === "ContentDelta"
|
||||
) {
|
||||
expect(firstDelta.itemId).toBe(firstStarted.itemId);
|
||||
expect(firstCompleted.itemId).toBe(firstStarted.itemId);
|
||||
expect(secondStarted.itemId).not.toBe(firstStarted.itemId);
|
||||
expect(secondDelta.itemId).toBe(secondStarted.itemId);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
env: {
|
||||
T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("suppresses generic placeholder tool updates until completion", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const promptResult = yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
expect(promptResult).toMatchObject({ stopReason: "end_turn" });
|
||||
|
||||
const notes = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 1)));
|
||||
expect(notes.map((note) => note._tag)).toEqual(["ToolCallUpdated"]);
|
||||
const toolCall = notes[0];
|
||||
expect(toolCall?._tag).toBe("ToolCallUpdated");
|
||||
if (toolCall?._tag === "ToolCallUpdated") {
|
||||
expect(toolCall.toolCall.status).toBe("completed");
|
||||
expect(toolCall.toolCall.title).toBe("Read file");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
env: {
|
||||
T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS: "1",
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
authMethodId: "test",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("logs ACP requests from the shared runtime", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.setModel("composer-2");
|
||||
yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
|
||||
expect(
|
||||
requestEvents.some(
|
||||
(event) => event.method === "session/set_config_option" && event.status === "started",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requestEvents.some(
|
||||
(event) => event.method === "session/set_config_option" && event.status === "succeeded",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requestEvents.some(
|
||||
(event) => event.method === "session/prompt" && event.status === "started",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
requestEvents.some(
|
||||
(event) => event.method === "session/prompt" && event.status === "succeeded",
|
||||
),
|
||||
).toBe(true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
requestLogger: (event) =>
|
||||
Effect.sync(() => {
|
||||
requestEvents.push(event);
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("skips no-op session config writes when the requested value is already active", () => {
|
||||
const requestEvents: Array<AcpSessionRequestLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.setConfigOption("model", "default");
|
||||
yield* runtime.setMode("ask");
|
||||
|
||||
expect(
|
||||
requestEvents.some(
|
||||
(event) => event.method === "session/set_config_option" && event.status === "started",
|
||||
),
|
||||
).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
requestLogger: (event) =>
|
||||
Effect.sync(() => {
|
||||
requestEvents.push(event);
|
||||
}),
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits low-level ACP protocol logs for raw and decoded messages", () => {
|
||||
const protocolEvents: Array<EffectAcpProtocol.AcpProtocolLogEvent> = [];
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
yield* runtime.prompt({
|
||||
prompt: [{ type: "text", text: "hi" }],
|
||||
});
|
||||
|
||||
expect(
|
||||
protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "raw"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
protocolEvents.some((event) => event.direction === "outgoing" && event.stage === "decoded"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
protocolEvents.some((event) => event.direction === "incoming" && event.stage === "raw"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
protocolEvents.some((event) => event.direction === "incoming" && event.stage === "decoded"),
|
||||
).toBe(true);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
protocolLogging: {
|
||||
logIncoming: true,
|
||||
logOutgoing: true,
|
||||
logger: (event) =>
|
||||
Effect.sync(() => {
|
||||
protocolEvents.push(event);
|
||||
}),
|
||||
},
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("rejects invalid config option values before sending session/set_config_option", () => {
|
||||
const tempDir = mkdtempSync(path.join(os.tmpdir(), "acp-runtime-"));
|
||||
const requestLogPath = path.join(tempDir, "requests.ndjson");
|
||||
return Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
yield* runtime.start();
|
||||
|
||||
const error = yield* runtime.setModel("composer-2[fast=false]").pipe(Effect.flip);
|
||||
expect(error._tag).toBe("AcpRequestError");
|
||||
if (error._tag === "AcpRequestError") {
|
||||
expect(error.code).toBe(-32602);
|
||||
expect(error.message).toContain(
|
||||
'Invalid value "composer-2[fast=false]" for session config option "model"',
|
||||
);
|
||||
expect(error.message).toContain("composer-2[fast=true]");
|
||||
}
|
||||
|
||||
const recordedRequests = readFileSync(requestLogPath, "utf8")
|
||||
.trim()
|
||||
.split("\n")
|
||||
.filter((line) => line.length > 0)
|
||||
.map((line) => JSON.parse(line) as { method?: string; params?: { value?: unknown } });
|
||||
expect(
|
||||
recordedRequests.some(
|
||||
(message) =>
|
||||
message.method === "session/set_config_option" &&
|
||||
message.params?.value === "composer-2[fast=false]",
|
||||
),
|
||||
).toBe(false);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "test",
|
||||
spawn: {
|
||||
command: bunExe,
|
||||
args: [mockAgentPath],
|
||||
env: {
|
||||
T3_ACP_REQUEST_LOG_PATH: requestLogPath,
|
||||
},
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientInfo: { name: "t3-test", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
Effect.ensuring(Effect.sync(() => rmSync(tempDir, { recursive: true, force: true }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import type { ProviderKind, ThreadId } from "@t3tools/contracts";
|
||||
import { Cause, Effect } from "effect";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import type { EventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts";
|
||||
import type { AcpSessionRequestLogEvent, AcpSessionRuntimeOptions } from "./AcpSessionRuntime.ts";
|
||||
|
||||
function writeNativeAcpLog(input: {
|
||||
readonly nativeEventLogger: EventNdjsonLogger | undefined;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly kind: "request" | "protocol";
|
||||
readonly payload: unknown;
|
||||
}): Effect.Effect<void, never> {
|
||||
return Effect.gen(function* () {
|
||||
if (!input.nativeEventLogger) return;
|
||||
const observedAt = new Date().toISOString();
|
||||
yield* input.nativeEventLogger.write(
|
||||
{
|
||||
observedAt,
|
||||
event: {
|
||||
id: crypto.randomUUID(),
|
||||
kind: input.kind,
|
||||
provider: input.provider,
|
||||
createdAt: observedAt,
|
||||
threadId: input.threadId,
|
||||
payload: input.payload,
|
||||
},
|
||||
},
|
||||
input.threadId,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function formatRequestLogPayload(event: AcpSessionRequestLogEvent) {
|
||||
return {
|
||||
method: event.method,
|
||||
status: event.status,
|
||||
request: event.payload,
|
||||
...(event.result !== undefined ? { result: event.result } : {}),
|
||||
...(event.cause !== undefined ? { cause: Cause.pretty(event.cause) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function makeAcpNativeLoggers(input: {
|
||||
readonly nativeEventLogger: EventNdjsonLogger | undefined;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId: ThreadId;
|
||||
}): Pick<AcpSessionRuntimeOptions, "requestLogger" | "protocolLogging"> {
|
||||
return {
|
||||
requestLogger: (event) =>
|
||||
writeNativeAcpLog({
|
||||
nativeEventLogger: input.nativeEventLogger,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
kind: "request",
|
||||
payload: formatRequestLogPayload(event),
|
||||
}),
|
||||
...(input.nativeEventLogger
|
||||
? {
|
||||
protocolLogging: {
|
||||
logIncoming: true,
|
||||
logOutgoing: true,
|
||||
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
|
||||
writeNativeAcpLog({
|
||||
nativeEventLogger: input.nativeEventLogger,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId,
|
||||
kind: "protocol",
|
||||
payload: event,
|
||||
}),
|
||||
} satisfies NonNullable<AcpSessionRuntimeOptions["protocolLogging"]>,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import {
|
||||
extractModelConfigId,
|
||||
mergeToolCallState,
|
||||
parsePermissionRequest,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
describe("AcpRuntimeModel", () => {
|
||||
it("parses session mode state from typed ACP session setup responses", () => {
|
||||
const modeState = parseSessionModeState({
|
||||
sessionId: "session-1",
|
||||
modes: {
|
||||
currentModeId: " code ",
|
||||
availableModes: [
|
||||
{ id: " ask ", name: " Ask ", description: " Request approval " },
|
||||
{ id: " code ", name: " Code " },
|
||||
],
|
||||
},
|
||||
configOptions: [],
|
||||
} satisfies EffectAcpSchema.NewSessionResponse);
|
||||
|
||||
expect(modeState).toEqual({
|
||||
currentModeId: "code",
|
||||
availableModes: [
|
||||
{ id: "ask", name: "Ask", description: "Request approval" },
|
||||
{ id: "code", name: "Code" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts the model config id from typed ACP config options", () => {
|
||||
const modelConfigId = extractModelConfigId({
|
||||
sessionId: "session-1",
|
||||
configOptions: [
|
||||
{
|
||||
id: "approval",
|
||||
name: "Approval Mode",
|
||||
category: "permission",
|
||||
type: "select",
|
||||
currentValue: "ask",
|
||||
options: [{ value: "ask", name: "Ask" }],
|
||||
},
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: "default",
|
||||
options: [{ value: "default", name: "Auto" }],
|
||||
},
|
||||
],
|
||||
} satisfies EffectAcpSchema.NewSessionResponse);
|
||||
|
||||
expect(modelConfigId).toBe("model");
|
||||
});
|
||||
|
||||
it("projects typed ACP tool call updates into runtime events", () => {
|
||||
const created = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
executable: "bun",
|
||||
args: ["run", "typecheck"],
|
||||
},
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Running checks",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
expect(created.events).toEqual([
|
||||
{
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
title: "Ran command",
|
||||
status: "pending",
|
||||
command: "bun run typecheck",
|
||||
detail: "bun run typecheck",
|
||||
data: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
command: "bun run typecheck",
|
||||
rawInput: {
|
||||
executable: "bun",
|
||||
args: ["run", "typecheck"],
|
||||
},
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Running checks",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
rawPayload: {
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-1",
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
executable: "bun",
|
||||
args: ["run", "typecheck"],
|
||||
},
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Running checks",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const updated = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
rawOutput: { exitCode: 0 },
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
expect(updated.events).toHaveLength(1);
|
||||
expect(updated.events[0]?._tag).toBe("ToolCallUpdated");
|
||||
const createdEvent = created.events[0];
|
||||
const updatedEvent = updated.events[0];
|
||||
if (createdEvent?._tag === "ToolCallUpdated" && updatedEvent?._tag === "ToolCallUpdated") {
|
||||
expect(mergeToolCallState(createdEvent.toolCall, updatedEvent.toolCall)).toMatchObject({
|
||||
toolCallId: "tool-1",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "bun run typecheck",
|
||||
command: "bun run typecheck",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("trims padded current mode updates before emitting a mode change", () => {
|
||||
const result = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId: " code ",
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
expect(result.modeId).toBe("code");
|
||||
expect(result.events).toEqual([
|
||||
{
|
||||
_tag: "ModeChanged",
|
||||
modeId: "code",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("projects typed ACP plan and content updates", () => {
|
||||
const planResult = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{ content: " Inspect state ", priority: "high", status: "completed" },
|
||||
{ content: "", priority: "medium", status: "in_progress" },
|
||||
],
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
expect(planResult.events).toEqual([
|
||||
{
|
||||
_tag: "PlanUpdated",
|
||||
payload: {
|
||||
plan: [
|
||||
{ step: "Inspect state", status: "completed" },
|
||||
{ step: "Step 2", status: "inProgress" },
|
||||
],
|
||||
},
|
||||
rawPayload: {
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{ content: " Inspect state ", priority: "high", status: "completed" },
|
||||
{ content: "", priority: "medium", status: "in_progress" },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const contentResult = parseSessionUpdateEvent({
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "hello from acp",
|
||||
},
|
||||
},
|
||||
} satisfies EffectAcpSchema.SessionNotification);
|
||||
|
||||
expect(contentResult.events).toEqual([
|
||||
{
|
||||
_tag: "ContentDelta",
|
||||
text: "hello from acp",
|
||||
rawPayload: {
|
||||
sessionId: "session-1",
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "hello from acp",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps permission request parsing compatible with loose extension payloads", () => {
|
||||
const request = parsePermissionRequest({
|
||||
sessionId: "session-1",
|
||||
options: [
|
||||
{
|
||||
optionId: "allow-once",
|
||||
name: "Allow once",
|
||||
kind: "allow_once",
|
||||
},
|
||||
],
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
title: "`cat package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(request).toMatchObject({
|
||||
kind: "execute",
|
||||
detail: "cat package.json",
|
||||
toolCall: {
|
||||
toolCallId: "tool-1",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
command: "cat package.json",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,482 @@
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { deriveToolActivityPresentation } from "@t3tools/shared/toolActivity";
|
||||
import type { ToolLifecycleItemType } from "@t3tools/contracts";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export interface AcpSessionMode {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description?: string;
|
||||
}
|
||||
|
||||
export interface AcpSessionModeState {
|
||||
readonly currentModeId: string;
|
||||
readonly availableModes: ReadonlyArray<AcpSessionMode>;
|
||||
}
|
||||
|
||||
export interface AcpToolCallState {
|
||||
readonly toolCallId: string;
|
||||
readonly kind?: string;
|
||||
readonly title?: string;
|
||||
readonly status?: "pending" | "inProgress" | "completed" | "failed";
|
||||
readonly command?: string;
|
||||
readonly detail?: string;
|
||||
readonly data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface AcpPlanUpdate {
|
||||
readonly explanation?: string | null;
|
||||
readonly plan: ReadonlyArray<{
|
||||
readonly step: string;
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface AcpPermissionRequest {
|
||||
readonly kind: string | "unknown";
|
||||
readonly detail?: string;
|
||||
readonly toolCall?: AcpToolCallState;
|
||||
}
|
||||
|
||||
export type AcpParsedSessionEvent =
|
||||
| {
|
||||
readonly _tag: "ModeChanged";
|
||||
readonly modeId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "AssistantItemStarted";
|
||||
readonly itemId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "AssistantItemCompleted";
|
||||
readonly itemId: string;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "PlanUpdated";
|
||||
readonly payload: AcpPlanUpdate;
|
||||
readonly rawPayload: unknown;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ToolCallUpdated";
|
||||
readonly toolCall: AcpToolCallState;
|
||||
readonly rawPayload: unknown;
|
||||
}
|
||||
| {
|
||||
readonly _tag: "ContentDelta";
|
||||
readonly itemId?: string;
|
||||
readonly text: string;
|
||||
readonly rawPayload: unknown;
|
||||
};
|
||||
|
||||
type AcpSessionSetupResponse =
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
|
||||
type AcpToolCallUpdate = Extract<
|
||||
EffectAcpSchema.SessionNotification["update"],
|
||||
{ readonly sessionUpdate: "tool_call" | "tool_call_update" }
|
||||
>;
|
||||
|
||||
export function extractModelConfigId(sessionResponse: AcpSessionSetupResponse): string | undefined {
|
||||
const configOptions = sessionResponse.configOptions;
|
||||
if (!configOptions) return undefined;
|
||||
for (const opt of configOptions) {
|
||||
if (opt.category === "model" && opt.id.trim().length > 0) {
|
||||
return opt.id.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function findSessionConfigOption(
|
||||
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
|
||||
configId: string,
|
||||
): EffectAcpSchema.SessionConfigOption | undefined {
|
||||
if (!configOptions) {
|
||||
return undefined;
|
||||
}
|
||||
const normalizedConfigId = configId.trim();
|
||||
if (!normalizedConfigId) {
|
||||
return undefined;
|
||||
}
|
||||
return configOptions.find((option) => option.id.trim() === normalizedConfigId);
|
||||
}
|
||||
|
||||
export function collectSessionConfigOptionValues(
|
||||
configOption: EffectAcpSchema.SessionConfigOption,
|
||||
): ReadonlyArray<string> {
|
||||
if (configOption.type !== "select") {
|
||||
return [];
|
||||
}
|
||||
return configOption.options.flatMap((entry) =>
|
||||
"value" in entry ? [entry.value] : entry.options.map((option) => option.value),
|
||||
);
|
||||
}
|
||||
|
||||
export function parseSessionModeState(
|
||||
sessionResponse: AcpSessionSetupResponse,
|
||||
): AcpSessionModeState | undefined {
|
||||
const modes = sessionResponse.modes;
|
||||
if (!modes) return undefined;
|
||||
const currentModeId = modes.currentModeId.trim();
|
||||
if (!currentModeId) {
|
||||
return undefined;
|
||||
}
|
||||
const availableModes = modes.availableModes
|
||||
.map((mode) => {
|
||||
const id = mode.id.trim();
|
||||
const name = mode.name.trim();
|
||||
if (!id || !name) {
|
||||
return undefined;
|
||||
}
|
||||
const description = mode.description?.trim() || undefined;
|
||||
return description !== undefined
|
||||
? ({ id, name, description } satisfies AcpSessionMode)
|
||||
: ({ id, name } satisfies AcpSessionMode);
|
||||
})
|
||||
.filter((mode): mode is AcpSessionMode => mode !== undefined);
|
||||
if (availableModes.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizePlanStepStatus(raw: unknown): "pending" | "inProgress" | "completed" {
|
||||
switch (raw) {
|
||||
case "completed":
|
||||
return "completed";
|
||||
case "in_progress":
|
||||
case "inProgress":
|
||||
return "inProgress";
|
||||
default:
|
||||
return "pending";
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeToolCallStatus(
|
||||
raw: unknown,
|
||||
fallback?: "pending" | "inProgress" | "completed" | "failed",
|
||||
): "pending" | "inProgress" | "completed" | "failed" | undefined {
|
||||
switch (raw) {
|
||||
case "pending":
|
||||
return "pending";
|
||||
case "in_progress":
|
||||
case "inProgress":
|
||||
return "inProgress";
|
||||
case "completed":
|
||||
return "completed";
|
||||
case "failed":
|
||||
return "failed";
|
||||
default:
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCommandValue(value: unknown): string | undefined {
|
||||
if (typeof value === "string" && value.trim().length > 0) {
|
||||
return value.trim();
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => (typeof entry === "string" && entry.trim().length > 0 ? entry.trim() : null))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
function extractCommandFromTitle(title: string | undefined): string | undefined {
|
||||
if (!title) {
|
||||
return undefined;
|
||||
}
|
||||
const match = /`([^`]+)`/.exec(title);
|
||||
return match?.[1]?.trim() || undefined;
|
||||
}
|
||||
|
||||
function extractToolCallCommand(rawInput: unknown, title: string | undefined): string | undefined {
|
||||
if (isRecord(rawInput)) {
|
||||
const directCommand = normalizeCommandValue(rawInput.command);
|
||||
if (directCommand) {
|
||||
return directCommand;
|
||||
}
|
||||
const executable = typeof rawInput.executable === "string" ? rawInput.executable.trim() : "";
|
||||
const args = normalizeCommandValue(rawInput.args);
|
||||
if (executable && args) {
|
||||
return `${executable} ${args}`;
|
||||
}
|
||||
if (executable) {
|
||||
return executable;
|
||||
}
|
||||
}
|
||||
return extractCommandFromTitle(title);
|
||||
}
|
||||
|
||||
function extractTextContentFromToolCallContent(
|
||||
content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
|
||||
): string | undefined {
|
||||
if (!content) return undefined;
|
||||
const chunks = content
|
||||
.map((entry) => {
|
||||
if (entry.type !== "content") {
|
||||
return undefined;
|
||||
}
|
||||
const nestedContent = entry.content;
|
||||
if (nestedContent.type !== "text") {
|
||||
return undefined;
|
||||
}
|
||||
return nestedContent.text.trim().length > 0 ? nestedContent.text.trim() : undefined;
|
||||
})
|
||||
.filter((entry): entry is string => entry !== undefined);
|
||||
return chunks.length > 0 ? chunks.join("\n") : undefined;
|
||||
}
|
||||
|
||||
function normalizeToolKind(kind: unknown): string | undefined {
|
||||
return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;
|
||||
}
|
||||
|
||||
function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {
|
||||
switch (kind) {
|
||||
case "execute":
|
||||
return "command_execution";
|
||||
case "edit":
|
||||
case "delete":
|
||||
case "move":
|
||||
return "file_change";
|
||||
case "search":
|
||||
case "fetch":
|
||||
return "web_search";
|
||||
default:
|
||||
return "dynamic_tool_call";
|
||||
}
|
||||
}
|
||||
|
||||
function makeToolCallState(
|
||||
input: {
|
||||
readonly toolCallId: string;
|
||||
readonly title?: string | null | undefined;
|
||||
readonly kind?: EffectAcpSchema.ToolKind | null | undefined;
|
||||
readonly status?: EffectAcpSchema.ToolCallStatus | null | undefined;
|
||||
readonly rawInput?: unknown;
|
||||
readonly rawOutput?: unknown;
|
||||
readonly content?: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined;
|
||||
readonly locations?: ReadonlyArray<EffectAcpSchema.ToolCallLocation> | null | undefined;
|
||||
},
|
||||
options?: {
|
||||
readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
|
||||
},
|
||||
): AcpToolCallState | undefined {
|
||||
const toolCallId = input.toolCallId.trim();
|
||||
if (!toolCallId) {
|
||||
return undefined;
|
||||
}
|
||||
const title = input.title?.trim() || undefined;
|
||||
const command = extractToolCallCommand(input.rawInput, title);
|
||||
const textContent = extractTextContentFromToolCallContent(input.content);
|
||||
const normalizedTitle =
|
||||
title && title.toLowerCase() !== "terminal" && title.toLowerCase() !== "tool call"
|
||||
? title
|
||||
: undefined;
|
||||
const data: Record<string, unknown> = { toolCallId };
|
||||
const kind = normalizeToolKind(input.kind);
|
||||
if (kind) {
|
||||
data.kind = kind;
|
||||
}
|
||||
if (command) {
|
||||
data.command = command;
|
||||
}
|
||||
if (input.rawInput !== undefined) {
|
||||
data.rawInput = input.rawInput;
|
||||
}
|
||||
if (input.rawOutput !== undefined) {
|
||||
data.rawOutput = input.rawOutput;
|
||||
}
|
||||
if (input.content !== undefined) {
|
||||
data.content = input.content;
|
||||
}
|
||||
if (input.locations !== undefined) {
|
||||
data.locations = input.locations;
|
||||
}
|
||||
const fallbackDetail = command ?? normalizedTitle ?? textContent;
|
||||
const hasPresentationSeed =
|
||||
title !== undefined ||
|
||||
kind !== undefined ||
|
||||
command !== undefined ||
|
||||
normalizedTitle !== undefined ||
|
||||
textContent !== undefined;
|
||||
const presentation = hasPresentationSeed
|
||||
? deriveToolActivityPresentation({
|
||||
itemType: canonicalItemTypeFromAcpToolKind(kind),
|
||||
title,
|
||||
detail: fallbackDetail,
|
||||
data,
|
||||
fallbackSummary: title ?? "Tool",
|
||||
})
|
||||
: undefined;
|
||||
const status = normalizeToolCallStatus(input.status, options?.fallbackStatus);
|
||||
return {
|
||||
toolCallId,
|
||||
...(kind ? { kind } : {}),
|
||||
...(presentation?.summary ? { title: presentation.summary } : {}),
|
||||
...(status ? { status } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(presentation?.detail ? { detail: presentation.detail } : {}),
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
function parseTypedToolCallState(
|
||||
event: AcpToolCallUpdate,
|
||||
options?: {
|
||||
readonly fallbackStatus?: "pending" | "inProgress" | "completed" | "failed";
|
||||
},
|
||||
): AcpToolCallState | undefined {
|
||||
return makeToolCallState(
|
||||
{
|
||||
toolCallId: event.toolCallId,
|
||||
title: event.title,
|
||||
kind: event.kind,
|
||||
status: event.status,
|
||||
rawInput: event.rawInput,
|
||||
rawOutput: event.rawOutput,
|
||||
content: event.content,
|
||||
locations: event.locations,
|
||||
},
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
export function mergeToolCallState(
|
||||
previous: AcpToolCallState | undefined,
|
||||
next: AcpToolCallState,
|
||||
): AcpToolCallState {
|
||||
const nextKind = typeof next.data.kind === "string" ? next.data.kind : undefined;
|
||||
const kind = nextKind ?? previous?.kind;
|
||||
const title = next.title ?? previous?.title;
|
||||
const status = next.status ?? previous?.status;
|
||||
const command = next.command ?? previous?.command;
|
||||
const detail = next.detail ?? previous?.detail;
|
||||
return {
|
||||
toolCallId: next.toolCallId,
|
||||
...(kind ? { kind } : {}),
|
||||
...(title ? { title } : {}),
|
||||
...(status ? { status } : {}),
|
||||
...(command ? { command } : {}),
|
||||
...(detail ? { detail } : {}),
|
||||
data: {
|
||||
...previous?.data,
|
||||
...next.data,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function parsePermissionRequest(
|
||||
params: EffectAcpSchema.RequestPermissionRequest,
|
||||
): AcpPermissionRequest {
|
||||
const toolCall = makeToolCallState(
|
||||
{
|
||||
toolCallId: params.toolCall.toolCallId,
|
||||
title: params.toolCall.title,
|
||||
kind: params.toolCall.kind,
|
||||
status: params.toolCall.status,
|
||||
rawInput: params.toolCall.rawInput,
|
||||
rawOutput: params.toolCall.rawOutput,
|
||||
content: params.toolCall.content,
|
||||
locations: params.toolCall.locations,
|
||||
},
|
||||
{ fallbackStatus: "pending" },
|
||||
);
|
||||
const kind = normalizeToolKind(params.toolCall.kind) ?? "unknown";
|
||||
const detail =
|
||||
toolCall?.command ??
|
||||
toolCall?.title ??
|
||||
toolCall?.detail ??
|
||||
(typeof params.sessionId === "string" ? `Session ${params.sessionId}` : undefined);
|
||||
return {
|
||||
kind,
|
||||
...(detail ? { detail } : {}),
|
||||
...(toolCall ? { toolCall } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseSessionUpdateEvent(params: EffectAcpSchema.SessionNotification): {
|
||||
readonly modeId?: string;
|
||||
readonly events: ReadonlyArray<AcpParsedSessionEvent>;
|
||||
} {
|
||||
const upd = params.update;
|
||||
const events: Array<AcpParsedSessionEvent> = [];
|
||||
let modeId: string | undefined;
|
||||
|
||||
switch (upd.sessionUpdate) {
|
||||
case "current_mode_update": {
|
||||
modeId = upd.currentModeId.trim();
|
||||
if (modeId) {
|
||||
events.push({
|
||||
_tag: "ModeChanged",
|
||||
modeId,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "plan": {
|
||||
const plan = upd.entries.map((entry, index) => ({
|
||||
step: entry.content.trim().length > 0 ? entry.content.trim() : `Step ${index + 1}`,
|
||||
status: normalizePlanStepStatus(entry.status),
|
||||
}));
|
||||
if (plan.length > 0) {
|
||||
events.push({
|
||||
_tag: "PlanUpdated",
|
||||
payload: {
|
||||
plan,
|
||||
},
|
||||
rawPayload: params,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "tool_call": {
|
||||
const toolCall = parseTypedToolCallState(upd, {
|
||||
fallbackStatus: "pending",
|
||||
});
|
||||
if (toolCall) {
|
||||
events.push({
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall,
|
||||
rawPayload: params,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "tool_call_update": {
|
||||
const toolCall = parseTypedToolCallState(upd);
|
||||
if (toolCall) {
|
||||
events.push({
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall,
|
||||
rawPayload: params,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "agent_message_chunk": {
|
||||
if (upd.content.type === "text" && upd.content.text.length > 0) {
|
||||
events.push({
|
||||
_tag: "ContentDelta",
|
||||
text: upd.content.text,
|
||||
rawPayload: params,
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return { ...(modeId !== undefined ? { modeId } : {}), events };
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
import { Cause, Deferred, Effect, Exit, Layer, Queue, Ref, Scope, Context, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as EffectAcpClient from "effect-acp/client";
|
||||
import * as EffectAcpErrors from "effect-acp/errors";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import type * as EffectAcpProtocol from "effect-acp/protocol";
|
||||
|
||||
import {
|
||||
collectSessionConfigOptionValues,
|
||||
extractModelConfigId,
|
||||
findSessionConfigOption,
|
||||
mergeToolCallState,
|
||||
parseSessionModeState,
|
||||
parseSessionUpdateEvent,
|
||||
type AcpParsedSessionEvent,
|
||||
type AcpSessionModeState,
|
||||
type AcpToolCallState,
|
||||
} from "./AcpRuntimeModel.ts";
|
||||
|
||||
export interface AcpSpawnInput {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly cwd?: string;
|
||||
readonly env?: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeOptions {
|
||||
readonly spawn: AcpSpawnInput;
|
||||
readonly cwd: string;
|
||||
readonly resumeSessionId?: string;
|
||||
readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"];
|
||||
readonly clientInfo: {
|
||||
readonly name: string;
|
||||
readonly version: string;
|
||||
};
|
||||
readonly authMethodId: string;
|
||||
readonly requestLogger?: (event: AcpSessionRequestLogEvent) => Effect.Effect<void, never>;
|
||||
readonly protocolLogging?: {
|
||||
readonly logIncoming?: boolean;
|
||||
readonly logOutgoing?: boolean;
|
||||
readonly logger?: (event: EffectAcpProtocol.AcpProtocolLogEvent) => Effect.Effect<void, never>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AcpSessionRequestLogEvent {
|
||||
readonly method: string;
|
||||
readonly payload: unknown;
|
||||
readonly status: "started" | "succeeded" | "failed";
|
||||
readonly result?: unknown;
|
||||
readonly cause?: Cause.Cause<EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeStartResult {
|
||||
readonly sessionId: string;
|
||||
readonly initializeResult: EffectAcpSchema.InitializeResponse;
|
||||
readonly sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
readonly modelConfigId: string | undefined;
|
||||
}
|
||||
|
||||
export interface AcpSessionRuntimeShape {
|
||||
readonly handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"];
|
||||
readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"];
|
||||
readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"];
|
||||
readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"];
|
||||
readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"];
|
||||
readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"];
|
||||
readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"];
|
||||
readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"];
|
||||
readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"];
|
||||
readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"];
|
||||
readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"];
|
||||
readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"];
|
||||
readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"];
|
||||
readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"];
|
||||
readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"];
|
||||
readonly start: () => Effect.Effect<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
readonly getEvents: () => Stream.Stream<AcpParsedSessionEvent, never>;
|
||||
readonly getModeState: Effect.Effect<AcpSessionModeState | undefined>;
|
||||
readonly getConfigOptions: Effect.Effect<ReadonlyArray<EffectAcpSchema.SessionConfigOption>>;
|
||||
readonly prompt: (
|
||||
payload: Omit<EffectAcpSchema.PromptRequest, "sessionId">,
|
||||
) => Effect.Effect<EffectAcpSchema.PromptResponse, EffectAcpErrors.AcpError>;
|
||||
readonly cancel: Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly setMode: (
|
||||
modeId: string,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionModeResponse, EffectAcpErrors.AcpError>;
|
||||
readonly setConfigOption: (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
) => Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError>;
|
||||
readonly setModel: (model: string) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
readonly request: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
|
||||
readonly notify: (
|
||||
method: string,
|
||||
payload: unknown,
|
||||
) => Effect.Effect<void, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
interface AcpStartedState extends AcpSessionRuntimeStartResult {}
|
||||
|
||||
type AcpStartState =
|
||||
| { readonly _tag: "NotStarted" }
|
||||
| {
|
||||
readonly _tag: "Starting";
|
||||
readonly deferred: Deferred.Deferred<AcpSessionRuntimeStartResult, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
| { readonly _tag: "Started"; readonly result: AcpStartedState };
|
||||
|
||||
interface AcpAssistantSegmentState {
|
||||
readonly nextSegmentIndex: number;
|
||||
readonly activeItemId?: string;
|
||||
}
|
||||
|
||||
interface EnsureActiveAssistantSegmentResult {
|
||||
readonly itemId: string;
|
||||
readonly startedEvent?: Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>;
|
||||
}
|
||||
|
||||
export class AcpSessionRuntime extends Context.Service<AcpSessionRuntime, AcpSessionRuntimeShape>()(
|
||||
"t3/provider/acp/AcpSessionRuntime",
|
||||
) {
|
||||
static layer(
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Layer.Layer<
|
||||
AcpSessionRuntime,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return Layer.effect(AcpSessionRuntime, makeAcpSessionRuntime(options));
|
||||
}
|
||||
}
|
||||
|
||||
const makeAcpSessionRuntime = (
|
||||
options: AcpSessionRuntimeOptions,
|
||||
): Effect.Effect<
|
||||
AcpSessionRuntimeShape,
|
||||
EffectAcpErrors.AcpError,
|
||||
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
|
||||
> =>
|
||||
Effect.gen(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const runtimeScope = yield* Scope.Scope;
|
||||
const eventQueue = yield* Queue.unbounded<AcpParsedSessionEvent>();
|
||||
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
|
||||
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
|
||||
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
|
||||
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
|
||||
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
|
||||
|
||||
const logRequest = (event: AcpSessionRequestLogEvent) =>
|
||||
options.requestLogger ? options.requestLogger(event) : Effect.void;
|
||||
|
||||
const runLoggedRequest = <A>(
|
||||
method: string,
|
||||
payload: unknown,
|
||||
effect: Effect.Effect<A, EffectAcpErrors.AcpError>,
|
||||
): Effect.Effect<A, EffectAcpErrors.AcpError> =>
|
||||
logRequest({ method, payload, status: "started" }).pipe(
|
||||
Effect.flatMap(() =>
|
||||
effect.pipe(
|
||||
Effect.tap((result) =>
|
||||
logRequest({
|
||||
method,
|
||||
payload,
|
||||
status: "succeeded",
|
||||
result,
|
||||
}),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
logRequest({
|
||||
method,
|
||||
payload,
|
||||
status: "failed",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const child = yield* spawner
|
||||
.spawn(
|
||||
ChildProcess.make(options.spawn.command, [...options.spawn.args], {
|
||||
...(options.spawn.cwd ? { cwd: options.spawn.cwd } : {}),
|
||||
...(options.spawn.env ? { env: { ...process.env, ...options.spawn.env } } : {}),
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.provideService(Scope.Scope, runtimeScope),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new EffectAcpErrors.AcpSpawnError({
|
||||
command: options.spawn.command,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const acpContext = yield* Layer.build(
|
||||
EffectAcpClient.layerChildProcess(child, {
|
||||
...(options.protocolLogging?.logIncoming !== undefined
|
||||
? { logIncoming: options.protocolLogging.logIncoming }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logOutgoing !== undefined
|
||||
? { logOutgoing: options.protocolLogging.logOutgoing }
|
||||
: {}),
|
||||
...(options.protocolLogging?.logger ? { logger: options.protocolLogging.logger } : {}),
|
||||
}),
|
||||
).pipe(Effect.provideService(Scope.Scope, runtimeScope));
|
||||
|
||||
const acp = yield* Effect.service(EffectAcpClient.AcpClient).pipe(Effect.provide(acpContext));
|
||||
|
||||
yield* acp.handleSessionUpdate((notification) =>
|
||||
handleSessionUpdate({
|
||||
queue: eventQueue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params: notification,
|
||||
}),
|
||||
);
|
||||
|
||||
const initializeClientCapabilities = {
|
||||
fs: {
|
||||
readTextFile: false,
|
||||
writeTextFile: false,
|
||||
...options.clientCapabilities?.fs,
|
||||
},
|
||||
terminal: options.clientCapabilities?.terminal ?? false,
|
||||
...(options.clientCapabilities?.auth ? { auth: options.clientCapabilities.auth } : {}),
|
||||
...(options.clientCapabilities?.elicitation
|
||||
? { elicitation: options.clientCapabilities.elicitation }
|
||||
: {}),
|
||||
...(options.clientCapabilities?._meta ? { _meta: options.clientCapabilities._meta } : {}),
|
||||
} satisfies NonNullable<EffectAcpSchema.InitializeRequest["clientCapabilities"]>;
|
||||
|
||||
const getStartedState = Effect.gen(function* () {
|
||||
const state = yield* Ref.get(startStateRef);
|
||||
if (state._tag === "Started") {
|
||||
return state.result;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpTransportError({
|
||||
detail: "ACP session runtime has not been started",
|
||||
cause: new Error("ACP session runtime has not been started"),
|
||||
});
|
||||
});
|
||||
|
||||
const validateConfigOptionValue = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
): Effect.Effect<void, EffectAcpErrors.AcpError> =>
|
||||
Effect.gen(function* () {
|
||||
const configOption = findSessionConfigOption(yield* Ref.get(configOptionsRef), configId);
|
||||
if (!configOption) {
|
||||
return;
|
||||
}
|
||||
if (configOption.type === "boolean") {
|
||||
if (typeof value === "boolean") {
|
||||
return;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected boolean`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "boolean",
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
}
|
||||
if (typeof value !== "string") {
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected string`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
expectedType: "string",
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
}
|
||||
const allowedValues = collectSessionConfigOptionValues(configOption);
|
||||
if (allowedValues.includes(value)) {
|
||||
return;
|
||||
}
|
||||
return yield* new EffectAcpErrors.AcpRequestError({
|
||||
code: -32602,
|
||||
errorMessage: `Invalid value ${JSON.stringify(value)} for session config option "${configOption.id}": expected one of ${allowedValues.join(", ")}`,
|
||||
data: {
|
||||
configId: configOption.id,
|
||||
allowedValues,
|
||||
receivedValue: value,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const updateConfigOptions = (
|
||||
response:
|
||||
| EffectAcpSchema.SetSessionConfigOptionResponse
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse,
|
||||
): Effect.Effect<void> => Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(response));
|
||||
|
||||
const updateCurrentModeId = (modeId: string): Effect.Effect<void> =>
|
||||
Ref.update(modeStateRef, (current) =>
|
||||
current ? { ...current, currentModeId: modeId } : current,
|
||||
);
|
||||
|
||||
const setConfigOption = (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
): Effect.Effect<EffectAcpSchema.SetSessionConfigOptionResponse, EffectAcpErrors.AcpError> =>
|
||||
validateConfigOptionValue(configId, value).pipe(
|
||||
Effect.flatMap(() => getStartedState),
|
||||
Effect.flatMap((started) =>
|
||||
Ref.get(configOptionsRef).pipe(
|
||||
Effect.flatMap((configOptions) => {
|
||||
const existing = findSessionConfigOption(configOptions, configId);
|
||||
if (existing && configOptionCurrentValueMatches(existing, value)) {
|
||||
return Effect.succeed({
|
||||
configOptions,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionResponse);
|
||||
}
|
||||
const requestPayload =
|
||||
typeof value === "boolean"
|
||||
? ({
|
||||
sessionId: started.sessionId,
|
||||
configId,
|
||||
type: "boolean",
|
||||
value,
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
sessionId: started.sessionId,
|
||||
configId,
|
||||
value: String(value),
|
||||
} satisfies EffectAcpSchema.SetSessionConfigOptionRequest);
|
||||
return runLoggedRequest(
|
||||
"session/set_config_option",
|
||||
requestPayload,
|
||||
acp.agent.setSessionConfigOption(requestPayload),
|
||||
).pipe(Effect.tap((response) => updateConfigOptions(response)));
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const startOnce = Effect.gen(function* () {
|
||||
const initializePayload = {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: initializeClientCapabilities,
|
||||
clientInfo: options.clientInfo,
|
||||
} satisfies EffectAcpSchema.InitializeRequest;
|
||||
|
||||
const initializeResult = yield* runLoggedRequest(
|
||||
"initialize",
|
||||
initializePayload,
|
||||
acp.agent.initialize(initializePayload),
|
||||
);
|
||||
|
||||
const authenticatePayload = {
|
||||
methodId: options.authMethodId,
|
||||
} satisfies EffectAcpSchema.AuthenticateRequest;
|
||||
|
||||
yield* runLoggedRequest(
|
||||
"authenticate",
|
||||
authenticatePayload,
|
||||
acp.agent.authenticate(authenticatePayload),
|
||||
);
|
||||
|
||||
let sessionId: string;
|
||||
let sessionSetupResult:
|
||||
| EffectAcpSchema.LoadSessionResponse
|
||||
| EffectAcpSchema.NewSessionResponse
|
||||
| EffectAcpSchema.ResumeSessionResponse;
|
||||
if (options.resumeSessionId) {
|
||||
const loadPayload = {
|
||||
sessionId: options.resumeSessionId,
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.LoadSessionRequest;
|
||||
const resumed = yield* runLoggedRequest(
|
||||
"session/load",
|
||||
loadPayload,
|
||||
acp.agent.loadSession(loadPayload),
|
||||
).pipe(Effect.exit);
|
||||
if (Exit.isSuccess(resumed)) {
|
||||
sessionId = options.resumeSessionId;
|
||||
sessionSetupResult = resumed.value;
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
} else {
|
||||
const createPayload = {
|
||||
cwd: options.cwd,
|
||||
mcpServers: [],
|
||||
} satisfies EffectAcpSchema.NewSessionRequest;
|
||||
const created = yield* runLoggedRequest(
|
||||
"session/new",
|
||||
createPayload,
|
||||
acp.agent.createSession(createPayload),
|
||||
);
|
||||
sessionId = created.sessionId;
|
||||
sessionSetupResult = created;
|
||||
}
|
||||
|
||||
yield* Ref.set(modeStateRef, parseSessionModeState(sessionSetupResult));
|
||||
yield* Ref.set(configOptionsRef, sessionConfigOptionsFromSetup(sessionSetupResult));
|
||||
|
||||
const nextState = {
|
||||
sessionId,
|
||||
initializeResult,
|
||||
sessionSetupResult,
|
||||
modelConfigId: extractModelConfigId(sessionSetupResult),
|
||||
} satisfies AcpStartedState;
|
||||
return nextState;
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
const deferred = yield* Deferred.make<
|
||||
AcpSessionRuntimeStartResult,
|
||||
EffectAcpErrors.AcpError
|
||||
>();
|
||||
const effect = yield* Ref.modify(startStateRef, (state) => {
|
||||
switch (state._tag) {
|
||||
case "Started":
|
||||
return [Effect.succeed(state.result), state] as const;
|
||||
case "Starting":
|
||||
return [Deferred.await(state.deferred), state] as const;
|
||||
case "NotStarted":
|
||||
return [
|
||||
startOnce.pipe(
|
||||
Effect.tap((result) =>
|
||||
Ref.set(startStateRef, { _tag: "Started", result }).pipe(
|
||||
Effect.andThen(Deferred.succeed(deferred, result)),
|
||||
),
|
||||
),
|
||||
Effect.onError((cause) =>
|
||||
Deferred.failCause(deferred, cause).pipe(
|
||||
Effect.andThen(Ref.set(startStateRef, { _tag: "NotStarted" })),
|
||||
),
|
||||
),
|
||||
),
|
||||
{ _tag: "Starting", deferred } satisfies AcpStartState,
|
||||
] as const;
|
||||
}
|
||||
});
|
||||
return yield* effect;
|
||||
});
|
||||
|
||||
return {
|
||||
handleRequestPermission: acp.handleRequestPermission,
|
||||
handleElicitation: acp.handleElicitation,
|
||||
handleReadTextFile: acp.handleReadTextFile,
|
||||
handleWriteTextFile: acp.handleWriteTextFile,
|
||||
handleCreateTerminal: acp.handleCreateTerminal,
|
||||
handleTerminalOutput: acp.handleTerminalOutput,
|
||||
handleTerminalWaitForExit: acp.handleTerminalWaitForExit,
|
||||
handleTerminalKill: acp.handleTerminalKill,
|
||||
handleTerminalRelease: acp.handleTerminalRelease,
|
||||
handleSessionUpdate: acp.handleSessionUpdate,
|
||||
handleElicitationComplete: acp.handleElicitationComplete,
|
||||
handleUnknownExtRequest: acp.handleUnknownExtRequest,
|
||||
handleUnknownExtNotification: acp.handleUnknownExtNotification,
|
||||
handleExtRequest: acp.handleExtRequest,
|
||||
handleExtNotification: acp.handleExtNotification,
|
||||
start: () => start,
|
||||
getEvents: () => Stream.fromQueue(eventQueue),
|
||||
getModeState: Ref.get(modeStateRef),
|
||||
getConfigOptions: Ref.get(configOptionsRef),
|
||||
prompt: (payload) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => {
|
||||
const requestPayload = {
|
||||
sessionId: started.sessionId,
|
||||
...payload,
|
||||
} satisfies EffectAcpSchema.PromptRequest;
|
||||
return closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}).pipe(
|
||||
Effect.andThen(
|
||||
runLoggedRequest(
|
||||
"session/prompt",
|
||||
requestPayload,
|
||||
acp.agent.prompt(requestPayload),
|
||||
),
|
||||
),
|
||||
Effect.tap(() =>
|
||||
closeActiveAssistantSegment({
|
||||
queue: eventQueue,
|
||||
assistantSegmentRef,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
cancel: getStartedState.pipe(
|
||||
Effect.flatMap((started) => acp.agent.cancel({ sessionId: started.sessionId })),
|
||||
),
|
||||
setMode: (modeId) =>
|
||||
Ref.get(modeStateRef).pipe(
|
||||
Effect.flatMap((modeState) => {
|
||||
if (modeState?.currentModeId === modeId) {
|
||||
return Effect.succeed({} satisfies EffectAcpSchema.SetSessionModeResponse);
|
||||
}
|
||||
return setConfigOption("mode", modeId).pipe(
|
||||
Effect.tap(() => updateCurrentModeId(modeId)),
|
||||
Effect.as({} satisfies EffectAcpSchema.SetSessionModeResponse),
|
||||
);
|
||||
}),
|
||||
),
|
||||
setConfigOption,
|
||||
setModel: (model) =>
|
||||
getStartedState.pipe(
|
||||
Effect.flatMap((started) => setConfigOption(started.modelConfigId ?? "model", model)),
|
||||
Effect.asVoid,
|
||||
),
|
||||
request: (method, payload) =>
|
||||
runLoggedRequest(method, payload, acp.raw.request(method, payload)),
|
||||
notify: acp.raw.notify,
|
||||
} satisfies AcpSessionRuntimeShape;
|
||||
});
|
||||
|
||||
function sessionConfigOptionsFromSetup(
|
||||
response:
|
||||
| {
|
||||
readonly configOptions?: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null;
|
||||
}
|
||||
| undefined,
|
||||
): ReadonlyArray<EffectAcpSchema.SessionConfigOption> {
|
||||
return response?.configOptions ?? [];
|
||||
}
|
||||
|
||||
function configOptionCurrentValueMatches(
|
||||
configOption: EffectAcpSchema.SessionConfigOption,
|
||||
value: string | boolean,
|
||||
): boolean {
|
||||
const currentValue = configOption.currentValue;
|
||||
if (configOption.type === "boolean") {
|
||||
return currentValue === value;
|
||||
}
|
||||
if (typeof currentValue !== "string") {
|
||||
return false;
|
||||
}
|
||||
return currentValue.trim() === String(value).trim();
|
||||
}
|
||||
|
||||
const handleSessionUpdate = ({
|
||||
queue,
|
||||
modeStateRef,
|
||||
toolCallsRef,
|
||||
assistantSegmentRef,
|
||||
params,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
|
||||
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly params: EffectAcpSchema.SessionNotification;
|
||||
}): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = parseSessionUpdateEvent(params);
|
||||
if (parsed.modeId) {
|
||||
yield* Ref.update(modeStateRef, (current) =>
|
||||
current === undefined ? current : updateModeState(current, parsed.modeId!),
|
||||
);
|
||||
}
|
||||
for (const event of parsed.events) {
|
||||
if (event._tag === "ToolCallUpdated") {
|
||||
yield* closeActiveAssistantSegment({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
});
|
||||
const { previous, merged } = yield* Ref.modify(toolCallsRef, (current) => {
|
||||
const previous = current.get(event.toolCall.toolCallId);
|
||||
const nextToolCall = mergeToolCallState(previous, event.toolCall);
|
||||
const next = new Map(current);
|
||||
if (nextToolCall.status === "completed" || nextToolCall.status === "failed") {
|
||||
next.delete(nextToolCall.toolCallId);
|
||||
} else {
|
||||
next.set(nextToolCall.toolCallId, nextToolCall);
|
||||
}
|
||||
return [{ previous, merged: nextToolCall }, next] as const;
|
||||
});
|
||||
if (!shouldEmitToolCallUpdate(previous, merged)) {
|
||||
continue;
|
||||
}
|
||||
yield* Queue.offer(queue, {
|
||||
_tag: "ToolCallUpdated",
|
||||
toolCall: merged,
|
||||
rawPayload: event.rawPayload,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (event._tag === "ContentDelta") {
|
||||
if (event.text.trim().length === 0) {
|
||||
const assistantSegmentState = yield* Ref.get(assistantSegmentRef);
|
||||
if (!assistantSegmentState.activeItemId) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const itemId = yield* ensureActiveAssistantSegment({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId: params.sessionId,
|
||||
});
|
||||
yield* Queue.offer(queue, {
|
||||
...event,
|
||||
itemId,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
yield* Queue.offer(queue, event);
|
||||
}
|
||||
});
|
||||
|
||||
function updateModeState(modeState: AcpSessionModeState, nextModeId: string): AcpSessionModeState {
|
||||
const normalized = nextModeId.trim();
|
||||
if (!normalized) {
|
||||
return modeState;
|
||||
}
|
||||
return modeState.availableModes.some((mode) => mode.id === normalized)
|
||||
? {
|
||||
...modeState,
|
||||
currentModeId: normalized,
|
||||
}
|
||||
: modeState;
|
||||
}
|
||||
|
||||
function shouldEmitToolCallUpdate(
|
||||
previous: AcpToolCallState | undefined,
|
||||
next: AcpToolCallState,
|
||||
): boolean {
|
||||
if (next.status === "completed" || next.status === "failed") {
|
||||
return true;
|
||||
}
|
||||
if (!next.detail) {
|
||||
return false;
|
||||
}
|
||||
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
|
||||
}
|
||||
|
||||
const assistantItemId = (sessionId: string, segmentIndex: number) =>
|
||||
`assistant:${sessionId}:segment:${segmentIndex}`;
|
||||
|
||||
const ensureActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
sessionId,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
readonly sessionId: string;
|
||||
}) =>
|
||||
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
|
||||
assistantSegmentRef,
|
||||
(current) => {
|
||||
if (current.activeItemId) {
|
||||
return [{ itemId: current.activeItemId }, current] as const;
|
||||
}
|
||||
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
|
||||
return [
|
||||
{
|
||||
itemId,
|
||||
startedEvent: {
|
||||
_tag: "AssistantItemStarted",
|
||||
itemId,
|
||||
} satisfies Extract<AcpParsedSessionEvent, { readonly _tag: "AssistantItemStarted" }>,
|
||||
},
|
||||
{
|
||||
nextSegmentIndex: current.nextSegmentIndex + 1,
|
||||
activeItemId: itemId,
|
||||
} satisfies AcpAssistantSegmentState,
|
||||
] as const;
|
||||
},
|
||||
).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.startedEvent
|
||||
? Queue.offer(queue, result.startedEvent).pipe(Effect.as(result.itemId))
|
||||
: Effect.succeed(result.itemId),
|
||||
),
|
||||
);
|
||||
|
||||
const closeActiveAssistantSegment = ({
|
||||
queue,
|
||||
assistantSegmentRef,
|
||||
}: {
|
||||
readonly queue: Queue.Queue<AcpParsedSessionEvent>;
|
||||
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
|
||||
}) =>
|
||||
Ref.modify(assistantSegmentRef, (current) => {
|
||||
if (!current.activeItemId) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
return [
|
||||
{
|
||||
_tag: "AssistantItemCompleted",
|
||||
itemId: current.activeItemId,
|
||||
} satisfies AcpParsedSessionEvent,
|
||||
{
|
||||
nextSegmentIndex: current.nextSegmentIndex,
|
||||
} satisfies AcpAssistantSegmentState,
|
||||
] as const;
|
||||
}).pipe(Effect.flatMap((event) => (event ? Queue.offer(queue, event) : Effect.void)));
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* Optional integration check against a real `agent acp` install.
|
||||
* Enable with: T3_CURSOR_ACP_PROBE=1 bun run test --filter CursorAcpCliProbe
|
||||
*/
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect } from "effect";
|
||||
import { describe, expect } from "vitest";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
|
||||
import { AcpSessionRuntime } from "./AcpSessionRuntime.ts";
|
||||
|
||||
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
|
||||
it.effect("initialize and authenticate against real agent acp", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
expect(started.initializeResult).toBeDefined();
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientCapabilities: {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
authMethodId: "cursor_login",
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("session/new returns configOptions with a model selector", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
const result = started.sessionSetupResult;
|
||||
console.log("session/new result:", JSON.stringify(result, null, 2));
|
||||
|
||||
expect(typeof started.sessionId).toBe("string");
|
||||
|
||||
const configOptions = result.configOptions;
|
||||
console.log("session/new configOptions:", JSON.stringify(configOptions, null, 2));
|
||||
|
||||
if (Array.isArray(configOptions)) {
|
||||
const modelConfig = configOptions.find((opt) => opt.category === "model");
|
||||
const parameterizedOptions = configOptions.filter(
|
||||
(opt) =>
|
||||
opt.category === "thought_level" ||
|
||||
opt.category === "model_option" ||
|
||||
opt.category === "model_config",
|
||||
);
|
||||
console.log("Model config option:", JSON.stringify(modelConfig, null, 2));
|
||||
console.log(
|
||||
"Parameterized model config options:",
|
||||
JSON.stringify(parameterizedOptions, null, 2),
|
||||
);
|
||||
expect(modelConfig).toBeDefined();
|
||||
expect(typeof modelConfig?.id).toBe("string");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "cursor_login",
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientCapabilities: {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("session/set_config_option switches the model in-session", () =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = yield* AcpSessionRuntime;
|
||||
const started = yield* runtime.start();
|
||||
const newResult = started.sessionSetupResult;
|
||||
|
||||
const configOptions = newResult.configOptions;
|
||||
let modelConfigId = "model";
|
||||
if (Array.isArray(configOptions)) {
|
||||
const modelConfig = configOptions.find((opt) => opt.category === "model");
|
||||
if (typeof modelConfig?.id === "string") {
|
||||
modelConfigId = modelConfig.id;
|
||||
}
|
||||
}
|
||||
|
||||
const setResult: EffectAcpSchema.SetSessionConfigOptionResponse =
|
||||
yield* runtime.setConfigOption(modelConfigId, "gpt-5.4");
|
||||
|
||||
console.log("session/set_config_option result:", JSON.stringify(setResult, null, 2));
|
||||
|
||||
if (Array.isArray(setResult.configOptions)) {
|
||||
const modelConfig = setResult.configOptions.find((opt) => opt.category === "model");
|
||||
const parameterizedOptions = setResult.configOptions.filter(
|
||||
(opt) =>
|
||||
opt.category === "thought_level" ||
|
||||
opt.category === "model_option" ||
|
||||
opt.category === "model_config",
|
||||
);
|
||||
if (modelConfig?.type === "select") {
|
||||
expect(modelConfig.currentValue).toBe("gpt-5.4");
|
||||
}
|
||||
expect(parameterizedOptions.length).toBeGreaterThan(0);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
AcpSessionRuntime.layer({
|
||||
authMethodId: "cursor_login",
|
||||
spawn: {
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: process.cwd(),
|
||||
},
|
||||
cwd: process.cwd(),
|
||||
clientCapabilities: {
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: { name: "t3-probe", version: "0.0.0" },
|
||||
}),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
extractAskQuestions,
|
||||
extractPlanMarkdown,
|
||||
extractTodosAsPlan,
|
||||
} from "./CursorAcpExtension.ts";
|
||||
|
||||
describe("CursorAcpExtension", () => {
|
||||
it("extracts ask-question prompts from the real Cursor ACP payload shape", () => {
|
||||
const questions = extractAskQuestions({
|
||||
toolCallId: "ask-1",
|
||||
title: "Need input",
|
||||
questions: [
|
||||
{
|
||||
id: "language",
|
||||
prompt: "Which language should I use?",
|
||||
options: [
|
||||
{ id: "ts", label: "TypeScript" },
|
||||
{ id: "rs", label: "Rust" },
|
||||
],
|
||||
allowMultiple: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "language",
|
||||
header: "Question",
|
||||
question: "Which language should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "TypeScript", description: "TypeScript" },
|
||||
{ label: "Rust", description: "Rust" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("defaults ask-question multi-select to false when Cursor omits allowMultiple", () => {
|
||||
const questions = extractAskQuestions({
|
||||
toolCallId: "ask-2",
|
||||
questions: [
|
||||
{
|
||||
id: "mode",
|
||||
prompt: "Which mode should I use?",
|
||||
options: [
|
||||
{ id: "agent", label: "Agent" },
|
||||
{ id: "plan", label: "Plan" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(questions).toEqual([
|
||||
{
|
||||
id: "mode",
|
||||
header: "Question",
|
||||
question: "Which mode should I use?",
|
||||
multiSelect: false,
|
||||
options: [
|
||||
{ label: "Agent", description: "Agent" },
|
||||
{ label: "Plan", description: "Plan" },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("extracts plan markdown from the real Cursor create-plan payload shape", () => {
|
||||
const planMarkdown = extractPlanMarkdown({
|
||||
toolCallId: "plan-1",
|
||||
name: "Refactor parser",
|
||||
overview: "Tighten ACP parsing",
|
||||
plan: "# Plan\n\n1. Add schemas\n2. Remove casts",
|
||||
todos: [
|
||||
{ id: "t1", content: "Add schemas", status: "in_progress" },
|
||||
{ id: "t2", content: "Remove casts", status: "pending" },
|
||||
],
|
||||
isProject: false,
|
||||
});
|
||||
|
||||
expect(planMarkdown).toBe("# Plan\n\n1. Add schemas\n2. Remove casts");
|
||||
});
|
||||
|
||||
it("projects todo updates into a plan shape and drops invalid entries", () => {
|
||||
expect(
|
||||
extractTodosAsPlan({
|
||||
toolCallId: "todos-1",
|
||||
todos: [
|
||||
{ id: "1", content: "Inspect state", status: "completed" },
|
||||
{ id: "2", content: " Apply fix ", status: "in_progress" },
|
||||
{ id: "3", title: "Fallback title", status: "pending" },
|
||||
{ id: "4", content: "Unknown status", status: "weird_status" },
|
||||
{ id: "5", content: " " },
|
||||
],
|
||||
merge: true,
|
||||
}),
|
||||
).toEqual({
|
||||
plan: [
|
||||
{ step: "Inspect state", status: "completed" },
|
||||
{ step: "Apply fix", status: "inProgress" },
|
||||
{ step: "Fallback title", status: "pending" },
|
||||
{ step: "Unknown status", status: "pending" },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* Public Docs: https://cursor.com/docs/cli/acp#cursor-extension-methods
|
||||
* Additional reference provided by the Cursor team: https://anysphere.enterprise.slack.com/files/U068SSJE141/F0APT1HSZRP/cursor-acp-extension-method-schemas.md
|
||||
*/
|
||||
import type { UserInputQuestion } from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
|
||||
const CursorAskQuestionOption = Schema.Struct({
|
||||
id: Schema.String,
|
||||
label: Schema.String,
|
||||
});
|
||||
|
||||
const CursorAskQuestion = Schema.Struct({
|
||||
id: Schema.String,
|
||||
prompt: Schema.String,
|
||||
options: Schema.Array(CursorAskQuestionOption),
|
||||
allowMultiple: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
|
||||
export const CursorAskQuestionRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
title: Schema.optional(Schema.String),
|
||||
questions: Schema.Array(CursorAskQuestion),
|
||||
});
|
||||
|
||||
const CursorTodoStatus = Schema.String;
|
||||
|
||||
const CursorTodo = Schema.Struct({
|
||||
id: Schema.optional(Schema.String),
|
||||
content: Schema.optional(Schema.String),
|
||||
title: Schema.optional(Schema.String),
|
||||
status: Schema.optional(CursorTodoStatus),
|
||||
});
|
||||
|
||||
const CursorPlanPhase = Schema.Struct({
|
||||
name: Schema.String,
|
||||
todos: Schema.Array(CursorTodo),
|
||||
});
|
||||
|
||||
export const CursorCreatePlanRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
name: Schema.optional(Schema.String),
|
||||
overview: Schema.optional(Schema.String),
|
||||
plan: Schema.String,
|
||||
todos: Schema.Array(CursorTodo),
|
||||
isProject: Schema.optional(Schema.Boolean),
|
||||
phases: Schema.optional(Schema.Array(CursorPlanPhase)),
|
||||
});
|
||||
|
||||
export const CursorUpdateTodosRequest = Schema.Struct({
|
||||
toolCallId: Schema.String,
|
||||
todos: Schema.Array(CursorTodo),
|
||||
merge: Schema.Boolean,
|
||||
});
|
||||
|
||||
export function extractAskQuestions(
|
||||
params: typeof CursorAskQuestionRequest.Type,
|
||||
): ReadonlyArray<UserInputQuestion> {
|
||||
return params.questions.map((question) => ({
|
||||
id: question.id,
|
||||
header: "Question",
|
||||
question: question.prompt,
|
||||
multiSelect: question.allowMultiple === true,
|
||||
options:
|
||||
question.options.length > 0
|
||||
? question.options.map((option) => ({
|
||||
label: option.label,
|
||||
description: option.label,
|
||||
}))
|
||||
: [{ label: "OK", description: "Continue" }],
|
||||
}));
|
||||
}
|
||||
|
||||
export function extractPlanMarkdown(params: typeof CursorCreatePlanRequest.Type): string {
|
||||
return params.plan || "# Plan\n\n(Cursor did not supply plan text.)";
|
||||
}
|
||||
|
||||
export function extractTodosAsPlan(params: typeof CursorUpdateTodosRequest.Type): {
|
||||
readonly explanation?: string;
|
||||
readonly plan: ReadonlyArray<{
|
||||
readonly step: string;
|
||||
readonly status: "pending" | "inProgress" | "completed";
|
||||
}>;
|
||||
} {
|
||||
const plan = params.todos.flatMap((todo) => {
|
||||
const step = todo.content?.trim() ?? todo.title?.trim() ?? "";
|
||||
if (step === "") {
|
||||
return [];
|
||||
}
|
||||
const status: "pending" | "inProgress" | "completed" =
|
||||
todo.status === "completed"
|
||||
? "completed"
|
||||
: todo.status === "in_progress" || todo.status === "inProgress"
|
||||
? "inProgress"
|
||||
: "pending";
|
||||
return [{ step, status }];
|
||||
});
|
||||
return { plan };
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import { Effect } from "effect";
|
||||
import type * as EffectAcpSchema from "effect-acp/schema";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { applyCursorAcpModelSelection, buildCursorAcpSpawnInput } from "./CursorAcpSupport.ts";
|
||||
|
||||
const parameterizedGpt54ConfigOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> = [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: "gpt-5.4-medium-fast",
|
||||
options: [{ value: "gpt-5.4-medium-fast", name: "GPT-5.4" }],
|
||||
},
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: "medium",
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "extra-high", name: "Extra High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "context",
|
||||
name: "Context",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: "272k",
|
||||
options: [
|
||||
{ value: "272k", name: "272K" },
|
||||
{ value: "1m", name: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: "false",
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe("buildCursorAcpSpawnInput", () => {
|
||||
it("builds the default Cursor ACP command", () => {
|
||||
expect(buildCursorAcpSpawnInput(undefined, "/tmp/project")).toEqual({
|
||||
command: "agent",
|
||||
args: ["acp"],
|
||||
cwd: "/tmp/project",
|
||||
});
|
||||
});
|
||||
|
||||
it("includes the configured api endpoint when present", () => {
|
||||
expect(
|
||||
buildCursorAcpSpawnInput(
|
||||
{
|
||||
binaryPath: "/usr/local/bin/agent",
|
||||
apiEndpoint: "http://localhost:3000",
|
||||
},
|
||||
"/tmp/project",
|
||||
),
|
||||
).toEqual({
|
||||
command: "/usr/local/bin/agent",
|
||||
args: ["-e", "http://localhost:3000", "acp"],
|
||||
cwd: "/tmp/project",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("applyCursorAcpModelSelection", () => {
|
||||
it("sets the base model before applying separate config options", async () => {
|
||||
const calls: Array<
|
||||
| { readonly type: "model"; readonly value: string }
|
||||
| { readonly type: "config"; readonly configId: string; readonly value: string | boolean }
|
||||
> = [];
|
||||
|
||||
const runtime = {
|
||||
getConfigOptions: Effect.succeed(parameterizedGpt54ConfigOptions),
|
||||
setModel: (value: string) =>
|
||||
Effect.sync(() => {
|
||||
calls.push({ type: "model", value });
|
||||
}),
|
||||
setConfigOption: (configId: string, value: string | boolean) =>
|
||||
Effect.sync(() => {
|
||||
calls.push({ type: "config", configId, value });
|
||||
}),
|
||||
};
|
||||
|
||||
await Effect.runPromise(
|
||||
applyCursorAcpModelSelection({
|
||||
runtime,
|
||||
model: "gpt-5.4-medium-fast[reasoning=medium,context=272k]",
|
||||
modelOptions: {
|
||||
reasoning: "xhigh",
|
||||
contextWindow: "1m",
|
||||
fastMode: true,
|
||||
},
|
||||
mapError: ({ step, configId, cause }) =>
|
||||
new Error(
|
||||
step === "set-config-option"
|
||||
? `failed to set config option ${configId}: ${cause.message}`
|
||||
: `failed to set model: ${cause.message}`,
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(calls).toEqual([
|
||||
{ type: "model", value: "gpt-5.4-medium-fast" },
|
||||
{ type: "config", configId: "reasoning", value: "extra-high" },
|
||||
{ type: "config", configId: "context", value: "1m" },
|
||||
{ type: "config", configId: "fast", value: "true" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { type CursorModelOptions, type CursorSettings } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Scope } from "effect";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import type * as EffectAcpErrors from "effect-acp/errors";
|
||||
|
||||
import {
|
||||
CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
resolveCursorAcpBaseModelId,
|
||||
resolveCursorAcpConfigUpdates,
|
||||
} from "../Layers/CursorProvider.ts";
|
||||
import {
|
||||
AcpSessionRuntime,
|
||||
type AcpSessionRuntimeOptions,
|
||||
type AcpSessionRuntimeShape,
|
||||
type AcpSpawnInput,
|
||||
} from "./AcpSessionRuntime.ts";
|
||||
|
||||
type CursorAcpRuntimeCursorSettings = Pick<CursorSettings, "apiEndpoint" | "binaryPath">;
|
||||
|
||||
export interface CursorAcpRuntimeInput extends Omit<
|
||||
AcpSessionRuntimeOptions,
|
||||
"authMethodId" | "clientCapabilities" | "spawn"
|
||||
> {
|
||||
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
|
||||
readonly cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined;
|
||||
}
|
||||
|
||||
export interface CursorAcpModelSelectionErrorContext {
|
||||
readonly cause: EffectAcpErrors.AcpError;
|
||||
readonly step: "set-config-option" | "set-model";
|
||||
readonly configId?: string;
|
||||
}
|
||||
|
||||
export function buildCursorAcpSpawnInput(
|
||||
cursorSettings: CursorAcpRuntimeCursorSettings | null | undefined,
|
||||
cwd: string,
|
||||
): AcpSpawnInput {
|
||||
return {
|
||||
command: cursorSettings?.binaryPath || "agent",
|
||||
args: [
|
||||
...(cursorSettings?.apiEndpoint ? (["-e", cursorSettings.apiEndpoint] as const) : []),
|
||||
"acp",
|
||||
],
|
||||
cwd,
|
||||
};
|
||||
}
|
||||
|
||||
export const makeCursorAcpRuntime = (
|
||||
input: CursorAcpRuntimeInput,
|
||||
): Effect.Effect<AcpSessionRuntimeShape, EffectAcpErrors.AcpError, Scope.Scope> =>
|
||||
Effect.gen(function* () {
|
||||
const acpContext = yield* Layer.build(
|
||||
AcpSessionRuntime.layer({
|
||||
...input,
|
||||
spawn: buildCursorAcpSpawnInput(input.cursorSettings, input.cwd),
|
||||
authMethodId: "cursor_login",
|
||||
clientCapabilities: CURSOR_PARAMETERIZED_MODEL_PICKER_CAPABILITIES,
|
||||
}).pipe(
|
||||
Layer.provide(
|
||||
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
|
||||
),
|
||||
),
|
||||
);
|
||||
return yield* Effect.service(AcpSessionRuntime).pipe(Effect.provide(acpContext));
|
||||
});
|
||||
|
||||
interface CursorAcpModelSelectionRuntime {
|
||||
readonly getConfigOptions: AcpSessionRuntimeShape["getConfigOptions"];
|
||||
readonly setConfigOption: (
|
||||
configId: string,
|
||||
value: string | boolean,
|
||||
) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
|
||||
readonly setModel: (model: string) => Effect.Effect<unknown, EffectAcpErrors.AcpError>;
|
||||
}
|
||||
|
||||
export function applyCursorAcpModelSelection<E>(input: {
|
||||
readonly runtime: CursorAcpModelSelectionRuntime;
|
||||
readonly model: string | null | undefined;
|
||||
readonly modelOptions: CursorModelOptions | null | undefined;
|
||||
readonly mapError: (context: CursorAcpModelSelectionErrorContext) => E;
|
||||
}): Effect.Effect<void, E> {
|
||||
return Effect.gen(function* () {
|
||||
yield* input.runtime.setModel(resolveCursorAcpBaseModelId(input.model)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
step: "set-model",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const configUpdates = resolveCursorAcpConfigUpdates(
|
||||
yield* input.runtime.getConfigOptions,
|
||||
input.modelOptions,
|
||||
);
|
||||
for (const update of configUpdates) {
|
||||
yield* input.runtime.setConfigOption(update.configId, update.value).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
input.mapError({
|
||||
cause,
|
||||
step: "set-config-option",
|
||||
configId: update.configId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import { describe, it, assert } from "@effect/vitest";
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { Deferred, Effect, Fiber, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { makeManagedServerProvider } from "./makeManagedServerProvider.ts";
|
||||
|
||||
interface TestSettings {
|
||||
readonly enabled: boolean;
|
||||
}
|
||||
|
||||
const initialSnapshot: ServerProvider = {
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-04-10T00:00:00.000Z",
|
||||
message: "Checking provider availability...",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const refreshedSnapshot: ServerProvider = {
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-04-10T00:00:01.000Z",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
};
|
||||
|
||||
const enrichedSnapshot: ServerProvider = {
|
||||
...refreshedSnapshot,
|
||||
checkedAt: "2026-04-10T00:00:02.000Z",
|
||||
models: [
|
||||
{
|
||||
slug: "composer-2",
|
||||
name: "Composer 2",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const refreshedSnapshotSecond: ServerProvider = {
|
||||
...refreshedSnapshot,
|
||||
checkedAt: "2026-04-10T00:00:03.000Z",
|
||||
message: "Refreshed provider availability again.",
|
||||
};
|
||||
|
||||
const enrichedSnapshotSecond: ServerProvider = {
|
||||
...refreshedSnapshotSecond,
|
||||
checkedAt: "2026-04-10T00:00:04.000Z",
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("makeManagedServerProvider", () => {
|
||||
it.effect(
|
||||
"runs the initial provider check in the background and streams the refreshed snapshot",
|
||||
() =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => initialSnapshot,
|
||||
checkProvider: Ref.update(checkCalls, (count) => count + 1).pipe(
|
||||
Effect.flatMap(() => Deferred.await(releaseCheck)),
|
||||
Effect.as(refreshedSnapshot),
|
||||
),
|
||||
refreshInterval: "1 hour",
|
||||
});
|
||||
|
||||
const initial = yield* provider.getSnapshot;
|
||||
assert.deepStrictEqual(initial, initialSnapshot);
|
||||
|
||||
const updatesFiber = yield* Stream.take(provider.streamChanges, 1).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* Deferred.succeed(releaseCheck, undefined);
|
||||
|
||||
const updates = Array.from(yield* Fiber.join(updatesFiber));
|
||||
const latest = yield* provider.getSnapshot;
|
||||
|
||||
assert.deepStrictEqual(updates, [refreshedSnapshot]);
|
||||
assert.deepStrictEqual(latest, refreshedSnapshot);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reruns the provider check when streamed settings change", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const settingsRef = yield* Ref.make<TestSettings>({ enabled: true });
|
||||
const settingsChanges = yield* PubSub.unbounded<TestSettings>();
|
||||
const checkCalls = yield* Ref.make(0);
|
||||
const releaseInitialCheck = yield* Deferred.make<void>();
|
||||
const releaseSettingsCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
getSettings: Ref.get(settingsRef),
|
||||
streamSettings: Stream.fromPubSub(settingsChanges),
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => initialSnapshot,
|
||||
checkProvider: Ref.updateAndGet(checkCalls, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) =>
|
||||
count === 1
|
||||
? Deferred.await(releaseInitialCheck).pipe(Effect.as(refreshedSnapshot))
|
||||
: Deferred.await(releaseSettingsCheck).pipe(Effect.as(refreshedSnapshotSecond)),
|
||||
),
|
||||
),
|
||||
refreshInterval: "1 hour",
|
||||
});
|
||||
|
||||
const updatesFiber = yield* Stream.take(provider.streamChanges, 2).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* Deferred.succeed(releaseInitialCheck, undefined);
|
||||
yield* Ref.set(settingsRef, { enabled: false });
|
||||
yield* PubSub.publish(settingsChanges, { enabled: false });
|
||||
yield* Deferred.succeed(releaseSettingsCheck, undefined);
|
||||
|
||||
const updates = Array.from(yield* Fiber.join(updatesFiber));
|
||||
const latest = yield* provider.getSnapshot;
|
||||
|
||||
assert.deepStrictEqual(updates, [refreshedSnapshot, refreshedSnapshotSecond]);
|
||||
assert.deepStrictEqual(latest, refreshedSnapshotSecond);
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 2);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("streams supplemental snapshot updates after the base provider check completes", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const releaseEnrichment = yield* Deferred.make<void>();
|
||||
const releaseCheck = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => initialSnapshot,
|
||||
checkProvider: Deferred.await(releaseCheck).pipe(Effect.as(refreshedSnapshot)),
|
||||
enrichSnapshot: ({ publishSnapshot }) =>
|
||||
Deferred.await(releaseEnrichment).pipe(
|
||||
Effect.flatMap(() => publishSnapshot(enrichedSnapshot)),
|
||||
),
|
||||
refreshInterval: "1 hour",
|
||||
});
|
||||
|
||||
const updatesFiber = yield* Stream.take(provider.streamChanges, 2).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* Deferred.succeed(releaseCheck, undefined);
|
||||
|
||||
yield* Deferred.succeed(releaseEnrichment, undefined);
|
||||
|
||||
const updates = Array.from(yield* Fiber.join(updatesFiber));
|
||||
const latest = yield* provider.getSnapshot;
|
||||
|
||||
assert.deepStrictEqual(updates, [refreshedSnapshot, enrichedSnapshot]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshot);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("ignores stale enrichment callbacks after a newer refresh advances generation", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const publishCallbacks: Array<(snapshot: ServerProvider) => Effect.Effect<void>> = [];
|
||||
const refreshCount = yield* Ref.make(0);
|
||||
const firstCallbackReady = yield* Deferred.make<void>();
|
||||
const secondCallbackReady = yield* Deferred.make<void>();
|
||||
const allowFirstRefresh = yield* Deferred.make<void>();
|
||||
const provider = yield* makeManagedServerProvider<TestSettings>({
|
||||
getSettings: Effect.succeed({ enabled: true }),
|
||||
streamSettings: Stream.empty,
|
||||
haveSettingsChanged: (previous, next) => previous.enabled !== next.enabled,
|
||||
initialSnapshot: () => initialSnapshot,
|
||||
checkProvider: Ref.updateAndGet(refreshCount, (count) => count + 1).pipe(
|
||||
Effect.flatMap((count) =>
|
||||
count === 1
|
||||
? Deferred.await(allowFirstRefresh).pipe(Effect.as(refreshedSnapshot))
|
||||
: Effect.succeed(refreshedSnapshotSecond),
|
||||
),
|
||||
),
|
||||
enrichSnapshot: ({ publishSnapshot }) =>
|
||||
Effect.gen(function* () {
|
||||
publishCallbacks.push(publishSnapshot);
|
||||
if (publishCallbacks.length === 1) {
|
||||
yield* Deferred.succeed(firstCallbackReady, undefined).pipe(Effect.ignore);
|
||||
} else if (publishCallbacks.length === 2) {
|
||||
yield* Deferred.succeed(secondCallbackReady, undefined).pipe(Effect.ignore);
|
||||
}
|
||||
}),
|
||||
refreshInterval: "1 hour",
|
||||
});
|
||||
|
||||
const updatesFiber = yield* Stream.take(provider.streamChanges, 3).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
yield* Deferred.succeed(allowFirstRefresh, undefined);
|
||||
yield* Deferred.await(firstCallbackReady);
|
||||
|
||||
yield* provider.refresh;
|
||||
yield* Deferred.await(secondCallbackReady);
|
||||
|
||||
yield* publishCallbacks[0]!(enrichedSnapshot);
|
||||
yield* publishCallbacks[1]!(enrichedSnapshotSecond);
|
||||
|
||||
const updates = Array.from(yield* Fiber.join(updatesFiber));
|
||||
const latest = yield* provider.getSnapshot;
|
||||
|
||||
assert.deepStrictEqual(updates, [
|
||||
refreshedSnapshot,
|
||||
refreshedSnapshotSecond,
|
||||
enrichedSnapshotSecond,
|
||||
]);
|
||||
assert.deepStrictEqual(latest, enrichedSnapshotSecond);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,15 @@
|
||||
import type { ServerProvider } from "@t3tools/contracts";
|
||||
import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";
|
||||
import { Duration, Effect, Equal, Fiber, PubSub, Ref, Scope, Stream } from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider.ts";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
interface ProviderSnapshotState {
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly enrichmentGeneration: number;
|
||||
}
|
||||
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
@@ -13,6 +18,12 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
readonly initialSnapshot: (settings: Settings) => ServerProvider;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
|
||||
readonly enrichSnapshot?: (input: {
|
||||
readonly settings: Settings;
|
||||
readonly snapshot: ServerProvider;
|
||||
readonly getSnapshot: Effect.Effect<ServerProvider>;
|
||||
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
|
||||
}) => Effect.Effect<void>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
@@ -22,8 +33,61 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
);
|
||||
const initialSettings = yield* input.getSettings;
|
||||
const initialSnapshot = input.initialSnapshot(initialSettings);
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const snapshotStateRef = yield* Ref.make<ProviderSnapshotState>({
|
||||
snapshot: initialSnapshot,
|
||||
enrichmentGeneration: 0,
|
||||
});
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
const enrichmentFiberRef = yield* Ref.make<Fiber.Fiber<void, unknown> | null>(null);
|
||||
const scope = yield* Effect.scope;
|
||||
|
||||
const publishEnrichedSnapshot = Effect.fn("publishEnrichedSnapshot")(function* (
|
||||
generation: number,
|
||||
nextSnapshot: ServerProvider,
|
||||
) {
|
||||
const snapshotToPublish = yield* Ref.modify(snapshotStateRef, (state) => {
|
||||
if (state.enrichmentGeneration !== generation || Equal.equals(state.snapshot, nextSnapshot)) {
|
||||
return [null, state] as const;
|
||||
}
|
||||
return [
|
||||
nextSnapshot,
|
||||
{
|
||||
...state,
|
||||
snapshot: nextSnapshot,
|
||||
},
|
||||
] as const;
|
||||
});
|
||||
if (snapshotToPublish === null) {
|
||||
return;
|
||||
}
|
||||
yield* PubSub.publish(changesPubSub, snapshotToPublish);
|
||||
});
|
||||
|
||||
const restartSnapshotEnrichment = Effect.fn("restartSnapshotEnrichment")(function* (
|
||||
settings: Settings,
|
||||
snapshot: ServerProvider,
|
||||
generation: number,
|
||||
) {
|
||||
const previousFiber = yield* Ref.getAndSet(enrichmentFiberRef, null);
|
||||
if (previousFiber) {
|
||||
yield* Fiber.interrupt(previousFiber).pipe(Effect.ignore);
|
||||
}
|
||||
|
||||
if (!input.enrichSnapshot) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fiber = yield* input
|
||||
.enrichSnapshot({
|
||||
settings,
|
||||
snapshot,
|
||||
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
|
||||
publishSnapshot: (nextSnapshot) => publishEnrichedSnapshot(generation, nextSnapshot),
|
||||
})
|
||||
.pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(scope));
|
||||
|
||||
yield* Ref.set(enrichmentFiberRef, fiber);
|
||||
});
|
||||
|
||||
const applySnapshotBase = Effect.fn("applySnapshot")(function* (
|
||||
nextSettings: Settings,
|
||||
@@ -33,13 +97,25 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
const previousSettings = yield* Ref.get(settingsRef);
|
||||
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
return yield* Ref.get(snapshotRef);
|
||||
return yield* Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot));
|
||||
}
|
||||
|
||||
const nextSnapshot = yield* input.checkProvider;
|
||||
const nextGeneration = yield* Ref.modify(snapshotStateRef, (state) => {
|
||||
const generation = input.enrichSnapshot
|
||||
? state.enrichmentGeneration + 1
|
||||
: state.enrichmentGeneration;
|
||||
return [
|
||||
generation,
|
||||
{
|
||||
snapshot: nextSnapshot,
|
||||
enrichmentGeneration: generation,
|
||||
},
|
||||
] as const;
|
||||
});
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
yield* Ref.set(snapshotRef, nextSnapshot);
|
||||
yield* PubSub.publish(changesPubSub, nextSnapshot);
|
||||
yield* restartSnapshotEnrichment(nextSettings, nextSnapshot, nextGeneration);
|
||||
return nextSnapshot;
|
||||
});
|
||||
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
|
||||
@@ -61,6 +137,11 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
yield* applySnapshot(initialSettings, { forceRefresh: true }).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { describe, it, vi } from "vitest";
|
||||
|
||||
const childProcessMock = vi.hoisted(() => ({
|
||||
execFileSync: vi.fn((command: string, args: ReadonlyArray<string>) => {
|
||||
if (command === "which" && args[0] === "opencode") {
|
||||
return "/opt/homebrew/bin/opencode\n";
|
||||
}
|
||||
return "";
|
||||
}),
|
||||
spawn: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:child_process", () => childProcessMock);
|
||||
|
||||
describe("resolveOpenCodeBinaryPath", () => {
|
||||
it("returns absolute binary paths without PATH lookup", async () => {
|
||||
const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts");
|
||||
|
||||
assert.equal(resolveOpenCodeBinaryPath("/usr/local/bin/opencode"), "/usr/local/bin/opencode");
|
||||
assert.equal(childProcessMock.execFileSync.mock.calls.length, 0);
|
||||
});
|
||||
|
||||
it("resolves command names through PATH", async () => {
|
||||
const { resolveOpenCodeBinaryPath } = await import("./opencodeRuntime.ts");
|
||||
|
||||
assert.equal(resolveOpenCodeBinaryPath("opencode"), "/opt/homebrew/bin/opencode");
|
||||
assert.deepEqual(childProcessMock.execFileSync.mock.calls[0], [
|
||||
"which",
|
||||
["opencode"],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,573 @@
|
||||
import { execFileSync, spawn, type ChildProcess } from "node:child_process";
|
||||
import * as FS from "node:fs";
|
||||
import { createServer, type AddressInfo } from "node:net";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import type {
|
||||
ChatAttachment,
|
||||
ModelCapabilities,
|
||||
ProviderApprovalDecision,
|
||||
RuntimeMode,
|
||||
ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
createOpencodeClient,
|
||||
type Agent,
|
||||
type FilePartInput,
|
||||
type OpencodeClient,
|
||||
type PermissionRuleset,
|
||||
type ProviderListResponse,
|
||||
type QuestionAnswer,
|
||||
type QuestionRequest,
|
||||
} from "@opencode-ai/sdk/v2";
|
||||
|
||||
const OPENCODE_SERVER_READY_PREFIX = "opencode server listening";
|
||||
const DEFAULT_OPENCODE_SERVER_TIMEOUT_MS = 5_000;
|
||||
const DEFAULT_HOSTNAME = "127.0.0.1";
|
||||
|
||||
const OPENAI_VARIANTS = ["none", "minimal", "low", "medium", "high", "xhigh"];
|
||||
const ANTHROPIC_VARIANTS = ["high", "max"];
|
||||
const GOOGLE_VARIANTS = ["low", "high"];
|
||||
|
||||
export const DEFAULT_OPENCODE_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
|
||||
export interface OpenCodeServerProcess {
|
||||
readonly url: string;
|
||||
readonly process: ChildProcess;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
export interface OpenCodeServerConnection {
|
||||
readonly url: string;
|
||||
readonly process: ChildProcess | null;
|
||||
readonly external: boolean;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
function buildOpenCodeBasicAuthorizationHeader(password: string): string {
|
||||
return `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`;
|
||||
}
|
||||
|
||||
export interface OpenCodeCommandResult {
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
readonly code: number;
|
||||
}
|
||||
|
||||
export interface OpenCodeInventory {
|
||||
readonly providerList: ProviderListResponse;
|
||||
readonly agents: ReadonlyArray<Agent>;
|
||||
}
|
||||
|
||||
export interface ParsedOpenCodeModelSlug {
|
||||
readonly providerID: string;
|
||||
readonly modelID: string;
|
||||
}
|
||||
|
||||
function titleCaseSlug(value: string): string {
|
||||
return value
|
||||
.split(/[-_/]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function parseServerUrlFromOutput(output: string): string | null {
|
||||
for (const line of output.split("\n")) {
|
||||
if (!line.startsWith(OPENCODE_SERVER_READY_PREFIX)) {
|
||||
continue;
|
||||
}
|
||||
const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
|
||||
return match?.[1] ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isPrimaryAgent(agent: Agent): boolean {
|
||||
return !agent.hidden && (agent.mode === "primary" || agent.mode === "all");
|
||||
}
|
||||
|
||||
function inferVariantValues(providerID: string): ReadonlyArray<string> {
|
||||
if (providerID === "anthropic") {
|
||||
return ANTHROPIC_VARIANTS;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return OPENAI_VARIANTS;
|
||||
}
|
||||
if (providerID.startsWith("google")) {
|
||||
return GOOGLE_VARIANTS;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function inferDefaultVariant(
|
||||
providerID: string,
|
||||
variants: ReadonlyArray<string>,
|
||||
): string | undefined {
|
||||
if (variants.length === 1) {
|
||||
return variants[0];
|
||||
}
|
||||
if (providerID === "anthropic" || providerID.startsWith("google")) {
|
||||
return variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
if (providerID === "openai" || providerID === "opencode") {
|
||||
return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function buildVariantOptions(
|
||||
providerID: string,
|
||||
model: ProviderListResponse["all"][number]["models"][string],
|
||||
) {
|
||||
const variantValues = Object.keys(model.variants ?? {});
|
||||
const resolvedValues =
|
||||
variantValues.length > 0 ? variantValues : [...inferVariantValues(providerID)];
|
||||
const defaultVariant = inferDefaultVariant(providerID, resolvedValues);
|
||||
|
||||
return resolvedValues.map((value) => {
|
||||
const option: { value: string; label: string; isDefault?: boolean } = {
|
||||
value,
|
||||
label: titleCaseSlug(value),
|
||||
};
|
||||
if (defaultVariant === value) {
|
||||
option.isDefault = true;
|
||||
}
|
||||
return option;
|
||||
});
|
||||
}
|
||||
|
||||
function buildAgentOptions(agents: ReadonlyArray<Agent>) {
|
||||
const primaryAgents = agents.filter(isPrimaryAgent);
|
||||
const defaultAgent =
|
||||
primaryAgents.find((agent) => agent.name === "build")?.name ??
|
||||
primaryAgents[0]?.name ??
|
||||
undefined;
|
||||
return primaryAgents.map((agent) => {
|
||||
const option: { value: string; label: string; isDefault?: boolean } = {
|
||||
value: agent.name,
|
||||
label: titleCaseSlug(agent.name),
|
||||
};
|
||||
if (defaultAgent === agent.name) {
|
||||
option.isDefault = true;
|
||||
}
|
||||
return option;
|
||||
});
|
||||
}
|
||||
|
||||
function openCodeCapabilitiesForModel(input: {
|
||||
readonly providerID: string;
|
||||
readonly model: ProviderListResponse["all"][number]["models"][string];
|
||||
readonly agents: ReadonlyArray<Agent>;
|
||||
}): ModelCapabilities {
|
||||
const variantOptions = buildVariantOptions(input.providerID, input.model);
|
||||
const agentOptions = buildAgentOptions(input.agents);
|
||||
return {
|
||||
...DEFAULT_OPENCODE_MODEL_CAPABILITIES,
|
||||
...(variantOptions.length > 0 ? { variantOptions } : {}),
|
||||
...(agentOptions.length > 0 ? { agentOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function parseOpenCodeModelSlug(
|
||||
slug: string | null | undefined,
|
||||
): ParsedOpenCodeModelSlug | null {
|
||||
if (typeof slug !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = slug.trim();
|
||||
const separator = trimmed.indexOf("/");
|
||||
if (separator <= 0 || separator === trimmed.length - 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
providerID: trimmed.slice(0, separator),
|
||||
modelID: trimmed.slice(separator + 1),
|
||||
};
|
||||
}
|
||||
|
||||
export function toOpenCodeModelSlug(providerID: string, modelID: string): string {
|
||||
return `${providerID}/${modelID}`;
|
||||
}
|
||||
|
||||
export function openCodeQuestionId(
|
||||
index: number,
|
||||
question: QuestionRequest["questions"][number],
|
||||
): string {
|
||||
const header = question.header
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9_-]+/g, "-");
|
||||
return header.length > 0 ? `question-${index}-${header}` : `question-${index}`;
|
||||
}
|
||||
|
||||
export function toOpenCodeFileParts(input: {
|
||||
readonly attachments: ReadonlyArray<ChatAttachment> | undefined;
|
||||
readonly resolveAttachmentPath: (attachment: ChatAttachment) => string | null;
|
||||
}): Array<FilePartInput> {
|
||||
const parts: Array<FilePartInput> = [];
|
||||
|
||||
for (const attachment of input.attachments ?? []) {
|
||||
const attachmentPath = input.resolveAttachmentPath(attachment);
|
||||
if (!attachmentPath) {
|
||||
continue;
|
||||
}
|
||||
|
||||
parts.push({
|
||||
type: "file",
|
||||
mime: attachment.mimeType,
|
||||
filename: attachment.name,
|
||||
url: pathToFileURL(attachmentPath).href,
|
||||
});
|
||||
}
|
||||
|
||||
return parts;
|
||||
}
|
||||
|
||||
export function buildOpenCodePermissionRules(runtimeMode: RuntimeMode): PermissionRuleset {
|
||||
if (runtimeMode === "full-access") {
|
||||
return [{ permission: "*", pattern: "*", action: "allow" }];
|
||||
}
|
||||
|
||||
return [
|
||||
{ permission: "*", pattern: "*", action: "ask" },
|
||||
{ permission: "bash", pattern: "*", action: "ask" },
|
||||
{ permission: "edit", pattern: "*", action: "ask" },
|
||||
{ permission: "webfetch", pattern: "*", action: "ask" },
|
||||
{ permission: "websearch", pattern: "*", action: "ask" },
|
||||
{ permission: "codesearch", pattern: "*", action: "ask" },
|
||||
{ permission: "external_directory", pattern: "*", action: "ask" },
|
||||
{ permission: "doom_loop", pattern: "*", action: "ask" },
|
||||
{ permission: "question", pattern: "*", action: "allow" },
|
||||
];
|
||||
}
|
||||
|
||||
export function toOpenCodePermissionReply(
|
||||
decision: ProviderApprovalDecision,
|
||||
): "once" | "always" | "reject" {
|
||||
switch (decision) {
|
||||
case "accept":
|
||||
return "once";
|
||||
case "acceptForSession":
|
||||
return "always";
|
||||
case "decline":
|
||||
case "cancel":
|
||||
default:
|
||||
return "reject";
|
||||
}
|
||||
}
|
||||
|
||||
export function toOpenCodeQuestionAnswers(
|
||||
request: QuestionRequest,
|
||||
answers: Record<string, unknown>,
|
||||
): Array<QuestionAnswer> {
|
||||
return request.questions.map((question, index) => {
|
||||
const raw =
|
||||
answers[openCodeQuestionId(index, question)] ??
|
||||
answers[question.header] ??
|
||||
answers[question.question];
|
||||
if (Array.isArray(raw)) {
|
||||
return raw.filter((value): value is string => typeof value === "string");
|
||||
}
|
||||
if (typeof raw === "string") {
|
||||
return raw.trim().length > 0 ? [raw] : [];
|
||||
}
|
||||
return [];
|
||||
});
|
||||
}
|
||||
|
||||
export async function findAvailablePort(): Promise<number> {
|
||||
const server = createServer();
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(0, DEFAULT_HOSTNAME, () => resolve());
|
||||
});
|
||||
const address = server.address() as AddressInfo;
|
||||
const port = address.port;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
server.close((error) => (error ? reject(error) : resolve()));
|
||||
});
|
||||
return port;
|
||||
}
|
||||
|
||||
export function resolveOpenCodeBinaryPath(binaryPath: string): string {
|
||||
if (Path.isAbsolute(binaryPath)) {
|
||||
return binaryPath;
|
||||
}
|
||||
return execFileSync("which", [binaryPath], {
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
}).trim();
|
||||
}
|
||||
|
||||
export function detectMacosSigkillHint(binaryPath: string): string | null {
|
||||
try {
|
||||
// Check for quarantine xattr first.
|
||||
const resolvedPath = resolveOpenCodeBinaryPath(binaryPath);
|
||||
const xattr = execFileSync("xattr", ["-l", resolvedPath], {
|
||||
encoding: "utf8",
|
||||
timeout: 3_000,
|
||||
});
|
||||
if (xattr.includes("com.apple.quarantine")) {
|
||||
return (
|
||||
`macOS quarantine is blocking the OpenCode binary. ` +
|
||||
`Run: xattr -d com.apple.quarantine ${resolvedPath}`
|
||||
);
|
||||
}
|
||||
|
||||
// Look for a recent crash report with the termination reason.
|
||||
const crashDir = Path.join(OS.homedir(), "Library/Logs/DiagnosticReports");
|
||||
const binaryName = Path.basename(resolvedPath);
|
||||
const recentReports = FS.readdirSync(crashDir)
|
||||
.filter((f) => f.startsWith(binaryName) && f.endsWith(".ips"))
|
||||
.toSorted()
|
||||
.toReversed()
|
||||
.slice(0, 1);
|
||||
|
||||
for (const report of recentReports) {
|
||||
const content = FS.readFileSync(Path.join(crashDir, report), "utf8");
|
||||
if (content.includes('"namespace":"CODESIGNING"')) {
|
||||
return (
|
||||
"macOS killed the process due to an invalid code signature. " +
|
||||
"The binary may be corrupted — try reinstalling OpenCode."
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best-effort detection — don't fail the original error path.
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function startOpenCodeServerProcess(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}): Promise<OpenCodeServerProcess> {
|
||||
const hostname = input.hostname ?? DEFAULT_HOSTNAME;
|
||||
const port = input.port ?? (await findAvailablePort());
|
||||
const timeoutMs = input.timeoutMs ?? DEFAULT_OPENCODE_SERVER_TIMEOUT_MS;
|
||||
const args = ["serve", `--hostname=${hostname}`, `--port=${port}`];
|
||||
const child = spawn(input.binaryPath, args, {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: {
|
||||
...process.env,
|
||||
OPENCODE_CONFIG_CONTENT: JSON.stringify({}),
|
||||
},
|
||||
});
|
||||
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let closed = false;
|
||||
const close = () => {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
child.kill();
|
||||
};
|
||||
|
||||
const url = await new Promise<string>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
close();
|
||||
reject(new Error(`Timed out waiting for OpenCode server start after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timeout);
|
||||
child.stdout.off("data", onStdout);
|
||||
child.stderr.off("data", onStderr);
|
||||
child.off("error", onError);
|
||||
child.off("close", onClose);
|
||||
};
|
||||
|
||||
const onStdout = (chunk: string) => {
|
||||
stdout += chunk;
|
||||
const parsed = parseServerUrlFromOutput(stdout);
|
||||
if (!parsed) {
|
||||
return;
|
||||
}
|
||||
cleanup();
|
||||
resolve(parsed);
|
||||
};
|
||||
|
||||
const onStderr = (chunk: string) => {
|
||||
stderr += chunk;
|
||||
};
|
||||
|
||||
const onError = (error: Error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
};
|
||||
|
||||
const onClose = (code: number | null, signal: NodeJS.Signals | null) => {
|
||||
cleanup();
|
||||
const exitReason = signal ? `signal: ${signal}` : `code: ${code ?? "unknown"}`;
|
||||
const hint =
|
||||
signal === "SIGKILL" && process.platform === "darwin"
|
||||
? detectMacosSigkillHint(input.binaryPath)
|
||||
: null;
|
||||
reject(
|
||||
new Error(
|
||||
[
|
||||
`OpenCode server exited before startup completed (${exitReason}).`,
|
||||
hint,
|
||||
stdout.trim() ? `stdout:\n${stdout.trim()}` : null,
|
||||
stderr.trim() ? `stderr:\n${stderr.trim()}` : null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n"),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
child.stdout.on("data", onStdout);
|
||||
child.stderr.on("data", onStderr);
|
||||
child.once("error", onError);
|
||||
child.once("close", onClose);
|
||||
});
|
||||
|
||||
return {
|
||||
url,
|
||||
process: child,
|
||||
close,
|
||||
};
|
||||
}
|
||||
|
||||
export async function connectToOpenCodeServer(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly serverUrl?: string | null;
|
||||
readonly port?: number;
|
||||
readonly hostname?: string;
|
||||
readonly timeoutMs?: number;
|
||||
}): Promise<OpenCodeServerConnection> {
|
||||
const serverUrl = input.serverUrl?.trim();
|
||||
if (serverUrl) {
|
||||
return {
|
||||
url: serverUrl,
|
||||
process: null,
|
||||
external: true,
|
||||
close() {},
|
||||
};
|
||||
}
|
||||
|
||||
const server = await startOpenCodeServerProcess({
|
||||
binaryPath: input.binaryPath,
|
||||
...(input.port !== undefined ? { port: input.port } : {}),
|
||||
...(input.hostname !== undefined ? { hostname: input.hostname } : {}),
|
||||
...(input.timeoutMs !== undefined ? { timeoutMs: input.timeoutMs } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
url: server.url,
|
||||
process: server.process,
|
||||
external: false,
|
||||
close: () => server.close(),
|
||||
};
|
||||
}
|
||||
|
||||
export async function runOpenCodeCommand(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}): Promise<OpenCodeCommandResult> {
|
||||
const child = spawn(input.binaryPath, [...input.args], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
child.stdout?.setEncoding("utf8");
|
||||
child.stderr?.setEncoding("utf8");
|
||||
|
||||
const stdoutChunks: Array<string> = [];
|
||||
const stderrChunks: Array<string> = [];
|
||||
|
||||
child.stdout?.on("data", (chunk: string) => stdoutChunks.push(chunk));
|
||||
child.stderr?.on("data", (chunk: string) => stderrChunks.push(chunk));
|
||||
|
||||
const code = await new Promise<number>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("exit", (exitCode) => resolve(exitCode ?? 0));
|
||||
});
|
||||
|
||||
return {
|
||||
stdout: stdoutChunks.join(""),
|
||||
stderr: stderrChunks.join(""),
|
||||
code,
|
||||
};
|
||||
}
|
||||
|
||||
export function createOpenCodeSdkClient(input: {
|
||||
readonly baseUrl: string;
|
||||
readonly directory: string;
|
||||
readonly serverPassword?: string;
|
||||
}): OpencodeClient {
|
||||
return createOpencodeClient({
|
||||
baseUrl: input.baseUrl,
|
||||
directory: input.directory,
|
||||
...(input.serverPassword
|
||||
? {
|
||||
headers: {
|
||||
Authorization: buildOpenCodeBasicAuthorizationHeader(input.serverPassword),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
throwOnError: true,
|
||||
});
|
||||
}
|
||||
|
||||
export async function loadOpenCodeInventory(client: OpencodeClient): Promise<OpenCodeInventory> {
|
||||
const [providerListResult, agentsResult] = await Promise.all([
|
||||
client.provider.list(),
|
||||
client.app.agents(),
|
||||
]);
|
||||
if (!providerListResult.data) {
|
||||
throw new Error("OpenCode provider inventory was empty.");
|
||||
}
|
||||
return {
|
||||
providerList: providerListResult.data,
|
||||
agents: agentsResult.data ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
export function flattenOpenCodeModels(
|
||||
input: OpenCodeInventory,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const connected = new Set(input.providerList.connected);
|
||||
const models: Array<ServerProviderModel> = [];
|
||||
|
||||
for (const provider of input.providerList.all) {
|
||||
if (!connected.has(provider.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const model of Object.values(provider.models)) {
|
||||
models.push({
|
||||
slug: toOpenCodeModelSlug(provider.id, model.id),
|
||||
name: `${provider.name} · ${model.name}`,
|
||||
isCustom: false,
|
||||
capabilities: openCodeCapabilitiesForModel({
|
||||
providerID: provider.id,
|
||||
model,
|
||||
agents: input.agents,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return models.toSorted((left, right) => left.name.localeCompare(right.name));
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ModelCapabilities } from "@t3tools/contracts";
|
||||
|
||||
import { providerModelsFromSettings } from "./providerSnapshot.ts";
|
||||
|
||||
const OPENCODE_CUSTOM_MODEL_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
variantOptions: [{ value: "medium", label: "Medium", isDefault: true }],
|
||||
agentOptions: [{ value: "build", label: "Build", isDefault: true }],
|
||||
};
|
||||
|
||||
describe("providerModelsFromSettings", () => {
|
||||
it("applies the provided capabilities to custom models", () => {
|
||||
const models = providerModelsFromSettings(
|
||||
[],
|
||||
"opencode",
|
||||
["openai/gpt-5"],
|
||||
OPENCODE_CUSTOM_MODEL_CAPABILITIES,
|
||||
);
|
||||
|
||||
expect(models).toEqual([
|
||||
{
|
||||
slug: "openai/gpt-5",
|
||||
name: "openai/gpt-5",
|
||||
isCustom: true,
|
||||
capabilities: OPENCODE_CUSTOM_MODEL_CAPABILITIES,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,10 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
});
|
||||
const openCodeProvider = makeProvider("opencode", {
|
||||
status: "warning",
|
||||
auth: { status: "unknown", type: "opencode" },
|
||||
});
|
||||
const codexPath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "codex",
|
||||
@@ -45,6 +49,10 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
cacheDir: tempDir,
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
const openCodePath = resolveProviderStatusCachePath({
|
||||
cacheDir: tempDir,
|
||||
provider: "opencode",
|
||||
});
|
||||
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: codexPath,
|
||||
@@ -54,16 +62,34 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
filePath: claudePath,
|
||||
provider: claudeProvider,
|
||||
});
|
||||
yield* writeProviderStatusCache({
|
||||
filePath: openCodePath,
|
||||
provider: openCodeProvider,
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(codexPath), codexProvider);
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(claudePath), claudeProvider);
|
||||
assert.deepStrictEqual(yield* readProviderStatusCache(openCodePath), openCodeProvider);
|
||||
}),
|
||||
);
|
||||
|
||||
it("hydrates cached provider status onto current settings-derived models", () => {
|
||||
it("hydrates cached provider status while preserving current settings-derived models", () => {
|
||||
const cachedCodex = makeProvider("codex", {
|
||||
checkedAt: "2026-04-10T12:00:00.000Z",
|
||||
models: [],
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-5-mini",
|
||||
name: "GPT-5 Mini",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
message: "Cached message",
|
||||
skills: [
|
||||
{
|
||||
@@ -99,6 +125,21 @@ it.layer(NodeServices.layer)("providerStatusCache", (it) => {
|
||||
}),
|
||||
{
|
||||
...fallbackCodex,
|
||||
models: [
|
||||
...fallbackCodex.models,
|
||||
{
|
||||
slug: "gpt-5-mini",
|
||||
name: "GPT-5 Mini",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
installed: cachedCodex.installed,
|
||||
version: cachedCodex.version,
|
||||
status: cachedCodex.status,
|
||||
|
||||
@@ -2,9 +2,12 @@ import * as nodePath from "node:path";
|
||||
import { type ServerProvider, ServerProvider as ServerProviderSchema } from "@t3tools/contracts";
|
||||
import { Cause, Effect, FileSystem, Path, Schema } from "effect";
|
||||
|
||||
export const PROVIDER_CACHE_IDS = ["codex", "claudeAgent"] as const satisfies ReadonlyArray<
|
||||
ServerProvider["provider"]
|
||||
>;
|
||||
export const PROVIDER_CACHE_IDS = [
|
||||
"codex",
|
||||
"claudeAgent",
|
||||
"opencode",
|
||||
"cursor",
|
||||
] as const satisfies ReadonlyArray<ServerProvider["provider"]>;
|
||||
|
||||
const decodeProviderStatusCache = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(ServerProviderSchema),
|
||||
@@ -15,6 +18,14 @@ const providerOrderRank = (provider: ServerProvider["provider"]): number => {
|
||||
return rank === -1 ? Number.MAX_SAFE_INTEGER : rank;
|
||||
};
|
||||
|
||||
const mergeProviderModels = (
|
||||
fallbackModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
cachedModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
const fallbackSlugs = new Set(fallbackModels.map((model) => model.slug));
|
||||
return [...fallbackModels, ...cachedModels.filter((model) => !fallbackSlugs.has(model.slug))];
|
||||
};
|
||||
|
||||
export const orderProviderSnapshots = (
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ReadonlyArray<ServerProvider> =>
|
||||
@@ -36,6 +47,7 @@ export const hydrateCachedProvider = (input: {
|
||||
const { message: _fallbackMessage, ...fallbackWithoutMessage } = input.fallbackProvider;
|
||||
const hydratedProvider: ServerProvider = {
|
||||
...fallbackWithoutMessage,
|
||||
models: mergeProviderModels(input.fallbackProvider.models, input.cachedProvider.models),
|
||||
installed: input.cachedProvider.installed,
|
||||
version: input.cachedProvider.version,
|
||||
status: input.cachedProvider.status,
|
||||
|
||||
@@ -3605,6 +3605,69 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("passes fetchLatestOrigin through bootstrap worktree creation when requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const createWorktree = vi.fn((_: Parameters<GitCoreShape["createWorktree"]>[0]) =>
|
||||
Effect.succeed({
|
||||
worktree: {
|
||||
branch: "t3code/bootstrap-branch",
|
||||
path: "/tmp/bootstrap-worktree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
gitCore: {
|
||||
createWorktree,
|
||||
},
|
||||
orchestrationEngine: {
|
||||
dispatch: () => Effect.succeed({ sequence: 1 }),
|
||||
readEvents: () => Stream.empty,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createdAt = new Date().toISOString();
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-bootstrap-turn-start-fetch-origin"),
|
||||
threadId: ThreadId.make("thread-bootstrap-fetch-origin"),
|
||||
message: {
|
||||
messageId: MessageId.make("msg-bootstrap-fetch-origin"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/tmp/project",
|
||||
baseBranch: "main",
|
||||
branch: "t3code/bootstrap-branch",
|
||||
fetchLatestOrigin: true,
|
||||
},
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
|
||||
cwd: "/tmp/project",
|
||||
branch: "main",
|
||||
newBranch: "t3code/bootstrap-branch",
|
||||
fetchLatestOrigin: true,
|
||||
path: null,
|
||||
});
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatchedCommands: Array<OrchestrationCommand> = [];
|
||||
|
||||
@@ -21,6 +21,8 @@ import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionD
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter.ts";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter.ts";
|
||||
import { makeCursorAdapterLive } from "./provider/Layers/CursorAdapter.ts";
|
||||
import { makeOpenCodeAdapterLive } from "./provider/Layers/OpenCodeAdapter.ts";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService.ts";
|
||||
import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
|
||||
@@ -39,6 +41,7 @@ import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
|
||||
import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
|
||||
import { ServerSettingsLive } from "./serverSettings.ts";
|
||||
import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
|
||||
@@ -48,8 +51,6 @@ import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
|
||||
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
|
||||
import { TerminalProcessInspectorLive } from "./process/Layers/TerminalProcessInspector.ts";
|
||||
import { WebPortInspectorLive } from "./process/Layers/WebPortInspector.ts";
|
||||
import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
|
||||
import {
|
||||
authBearerBootstrapRouteLayer,
|
||||
@@ -129,6 +130,7 @@ const ReactorLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(ProviderRuntimeIngestionLive),
|
||||
Layer.provideMerge(ProviderCommandReactorLive),
|
||||
Layer.provideMerge(CheckpointReactorLive),
|
||||
Layer.provideMerge(ThreadDeletionReactorLive),
|
||||
Layer.provideMerge(RuntimeReceiptBusLive),
|
||||
);
|
||||
|
||||
@@ -156,9 +158,17 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
const claudeAdapterLayer = makeClaudeAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const openCodeAdapterLayer = makeOpenCodeAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const cursorAdapterLayer = makeCursorAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provide(openCodeAdapterLayer),
|
||||
Layer.provide(cursorAdapterLayer),
|
||||
Layer.provideMerge(ProviderSessionDirectoryLayerLive),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
@@ -185,11 +195,7 @@ const GitLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(GitCoreLive),
|
||||
);
|
||||
|
||||
const TerminalLayerLive = TerminalManagerLive.pipe(
|
||||
Layer.provideMerge(WebPortInspectorLive),
|
||||
Layer.provideMerge(TerminalProcessInspectorLive),
|
||||
Layer.provide(PtyAdapterLive),
|
||||
);
|
||||
const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
|
||||
|
||||
const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
|
||||
@@ -184,6 +184,11 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
claudeAgent: {
|
||||
binaryPath: " /opt/homebrew/bin/claude ",
|
||||
},
|
||||
opencode: {
|
||||
binaryPath: " /opt/homebrew/bin/opencode ",
|
||||
serverUrl: " http://127.0.0.1:4096 ",
|
||||
serverPassword: " secret-password ",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -199,6 +204,13 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
customModels: [],
|
||||
launchArgs: "",
|
||||
});
|
||||
assert.deepEqual(next.providers.opencode, {
|
||||
enabled: true,
|
||||
binaryPath: "/opt/homebrew/bin/opencode",
|
||||
serverUrl: "http://127.0.0.1:4096",
|
||||
serverPassword: "secret-password",
|
||||
customModels: [],
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
@@ -257,6 +269,10 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
codex: {
|
||||
binaryPath: "/opt/homebrew/bin/codex",
|
||||
},
|
||||
opencode: {
|
||||
serverUrl: "http://127.0.0.1:4096",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -273,6 +289,10 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
codex: {
|
||||
binaryPath: "/opt/homebrew/bin/codex",
|
||||
},
|
||||
opencode: {
|
||||
serverUrl: "http://127.0.0.1:4096",
|
||||
serverPassword: "secret-password",
|
||||
},
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
|
||||
@@ -105,7 +105,7 @@ export class ServerSettingsService extends Context.Service<
|
||||
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
|
||||
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
|
||||
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent", "opencode", "cursor"];
|
||||
|
||||
/**
|
||||
* Ensure the `textGenerationModelSelection` points to an enabled provider.
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeChildProcessSpawner from "@effect/platform-node/NodeChildProcessSpawner";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
type TerminalEvent,
|
||||
@@ -17,7 +15,6 @@ import {
|
||||
Exit,
|
||||
Fiber,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
PlatformError,
|
||||
Ref,
|
||||
@@ -27,17 +24,6 @@ import {
|
||||
import { TestClock } from "effect/testing";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { TerminalProcessInspectorLive } from "../../process/Layers/TerminalProcessInspector.ts";
|
||||
import { WebPortInspectorLive } from "../../process/Layers/WebPortInspector.ts";
|
||||
import {
|
||||
TerminalProcessInspectionError,
|
||||
TerminalProcessInspector,
|
||||
} from "../../process/Services/TerminalProcessInspector.ts";
|
||||
import {
|
||||
WebPortInspector,
|
||||
WebPortInspectionError,
|
||||
type TerminalWebPortInspector,
|
||||
} from "../../process/Services/WebPortInspector.ts";
|
||||
import type { TerminalManagerShape } from "../Services/Manager.ts";
|
||||
import {
|
||||
type PtyAdapterShape,
|
||||
@@ -46,11 +32,7 @@ import {
|
||||
type PtySpawnInput,
|
||||
PtySpawnError,
|
||||
} from "../Services/PTY.ts";
|
||||
import {
|
||||
describeSubprocessInspectorError,
|
||||
makeTerminalManagerWithOptions,
|
||||
nextSubprocessActivityErrorLogState,
|
||||
} from "./Manager.ts";
|
||||
import { makeTerminalManagerWithOptions } from "./Manager.ts";
|
||||
|
||||
class FakePtyProcess implements PtyProcess {
|
||||
readonly writes: string[] = [];
|
||||
@@ -212,13 +194,9 @@ function multiTerminalHistoryLogPath(
|
||||
|
||||
interface CreateManagerOptions {
|
||||
shellResolver?: () => string;
|
||||
subprocessInspector?: (
|
||||
terminalPid: number,
|
||||
) => Effect.Effect<{ hasRunningSubprocess: boolean; runningPorts: number[] }>;
|
||||
webPortInspector?: TerminalWebPortInspector;
|
||||
webPortProbeCacheTtlMs?: number;
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
subprocessChecker?: (terminalPid: number) => Effect.Effect<boolean>;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -239,7 +217,7 @@ const createManager = (
|
||||
): Effect.Effect<
|
||||
ManagerFixture,
|
||||
PlatformError.PlatformError,
|
||||
FileSystem.FileSystem | Scope.Scope | TerminalProcessInspector | WebPortInspector
|
||||
FileSystem.FileSystem | Scope.Scope
|
||||
> =>
|
||||
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -252,17 +230,11 @@ const createManager = (
|
||||
historyLineLimit,
|
||||
ptyAdapter,
|
||||
...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}),
|
||||
...(options.subprocessInspector !== undefined
|
||||
? { subprocessInspector: options.subprocessInspector }
|
||||
: {}),
|
||||
...(options.webPortInspector !== undefined
|
||||
? { webPortInspector: options.webPortInspector }
|
||||
: {}),
|
||||
...(options.webPortProbeCacheTtlMs !== undefined
|
||||
? { webPortProbeCacheTtlMs: options.webPortProbeCacheTtlMs }
|
||||
: {}),
|
||||
...(options.platform !== undefined ? { platform: options.platform } : {}),
|
||||
...(options.env !== undefined ? { env: options.env } : {}),
|
||||
...(options.subprocessChecker !== undefined
|
||||
? { subprocessChecker: options.subprocessChecker }
|
||||
: {}),
|
||||
...(options.subprocessPollIntervalMs !== undefined
|
||||
? { subprocessPollIntervalMs: options.subprocessPollIntervalMs }
|
||||
: {}),
|
||||
@@ -290,71 +262,7 @@ const createManager = (
|
||||
}),
|
||||
);
|
||||
|
||||
const nodeChildProcessLayer = NodeChildProcessSpawner.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
|
||||
it.effect("formats subprocess inspector errors with command and underlying cause details", () =>
|
||||
Effect.sync(() => {
|
||||
const error = new TerminalProcessInspectionError({
|
||||
operation: "TerminalProcessInspector.checkPosixListeningPorts.ss",
|
||||
terminalPid: 77_411,
|
||||
command: "ss -ltnp",
|
||||
detail: "Failed to spawn inspector command.",
|
||||
cause: new Error("spawn ss ENOENT"),
|
||||
});
|
||||
|
||||
const description = describeSubprocessInspectorError(error);
|
||||
|
||||
assert.equal(description.operation, "TerminalProcessInspector.checkPosixListeningPorts.ss");
|
||||
assert.equal(description.command, "ss -ltnp");
|
||||
assert.equal(description.detail, "Failed to spawn inspector command.");
|
||||
assert.equal(description.cause, "spawn ss ENOENT");
|
||||
assert.include(description.error, "ss -ltnp");
|
||||
assert.include(description.error, "spawn ss ENOENT");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"suppresses repeated identical subprocess inspector warnings inside the throttle window",
|
||||
() =>
|
||||
Effect.sync(() => {
|
||||
const first = nextSubprocessActivityErrorLogState({
|
||||
previous: undefined,
|
||||
fingerprint: "same-error",
|
||||
now: 1_000,
|
||||
throttleMs: 30_000,
|
||||
});
|
||||
assert.equal(first.shouldLog, true);
|
||||
assert.equal(first.suppressedRepeats, 0);
|
||||
|
||||
const second = nextSubprocessActivityErrorLogState({
|
||||
previous: first.next,
|
||||
fingerprint: "same-error",
|
||||
now: 2_000,
|
||||
throttleMs: 30_000,
|
||||
});
|
||||
assert.equal(second.shouldLog, false);
|
||||
assert.equal(second.next.suppressedRepeats, 1);
|
||||
|
||||
const third = nextSubprocessActivityErrorLogState({
|
||||
previous: second.next,
|
||||
fingerprint: "same-error",
|
||||
now: 32_000,
|
||||
throttleMs: 30_000,
|
||||
});
|
||||
assert.equal(third.shouldLog, true);
|
||||
assert.equal(third.suppressedRepeats, 1);
|
||||
assert.equal(third.next.suppressedRepeats, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.layer(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
WebPortInspectorLive.pipe(Layer.provide(FetchHttpClient.layer)),
|
||||
TerminalProcessInspectorLive.pipe(Layer.provide(nodeChildProcessLayer)),
|
||||
),
|
||||
{ excludeTestServices: true },
|
||||
)("TerminalManager", (it) => {
|
||||
it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => {
|
||||
it.effect("spawns lazily and reuses running terminal per thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const { manager, ptyAdapter } = yield* createManager();
|
||||
@@ -652,114 +560,32 @@ it.layer(
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("emits subprocess activity events when child-process state or web ports change", () =>
|
||||
it.effect("emits subprocess activity events when child-process state changes", () =>
|
||||
Effect.gen(function* () {
|
||||
let activity = {
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [] as number[],
|
||||
};
|
||||
let hasRunningSubprocess = false;
|
||||
const { manager, getEvents } = yield* createManager(5, {
|
||||
subprocessInspector: () => Effect.succeed(activity),
|
||||
webPortInspector: (port) => Effect.succeed(port === 3000),
|
||||
subprocessChecker: () => Effect.succeed(hasRunningSubprocess),
|
||||
subprocessPollIntervalMs: 20,
|
||||
});
|
||||
|
||||
yield* manager.open(openInput());
|
||||
expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false);
|
||||
|
||||
activity = { hasRunningSubprocess: true, runningPorts: [3000] };
|
||||
hasRunningSubprocess = true;
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.join(",") === "3000",
|
||||
),
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
activity = { hasRunningSubprocess: true, runningPorts: [5173] };
|
||||
hasRunningSubprocess = false;
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.length === 0,
|
||||
),
|
||||
events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
activity = { hasRunningSubprocess: false, runningPorts: [5173] };
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === false &&
|
||||
event.runningPorts.length === 0,
|
||||
),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a confirmed web port during transient probe failures after cache expiry", () =>
|
||||
Effect.gen(function* () {
|
||||
let activity = {
|
||||
hasRunningSubprocess: true,
|
||||
runningPorts: [3000],
|
||||
};
|
||||
let probeCalls = 0;
|
||||
const { manager, getEvents } = yield* createManager(5, {
|
||||
subprocessInspector: () => Effect.succeed(activity),
|
||||
webPortInspector: () => {
|
||||
probeCalls += 1;
|
||||
return probeCalls === 1
|
||||
? Effect.succeed(true)
|
||||
: Effect.fail(
|
||||
new WebPortInspectionError({
|
||||
port: 3000,
|
||||
host: "127.0.0.1",
|
||||
detail: "transient web probe failure",
|
||||
}),
|
||||
);
|
||||
},
|
||||
webPortProbeCacheTtlMs: 25,
|
||||
subprocessPollIntervalMs: 20,
|
||||
});
|
||||
|
||||
yield* manager.open(openInput());
|
||||
yield* waitFor(
|
||||
Effect.map(getEvents, (events) =>
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.join(",") === "3000",
|
||||
),
|
||||
),
|
||||
"1200 millis",
|
||||
);
|
||||
|
||||
yield* waitFor(
|
||||
Effect.sync(() => probeCalls >= 2),
|
||||
"1200 millis",
|
||||
);
|
||||
const events = yield* getEvents;
|
||||
expect(
|
||||
events.some(
|
||||
(event) =>
|
||||
event.type === "activity" &&
|
||||
event.hasRunningSubprocess === true &&
|
||||
event.runningPorts.length === 0,
|
||||
),
|
||||
).toBe(false);
|
||||
activity = { hasRunningSubprocess: false, runningPorts: [] };
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -767,12 +593,9 @@ it.layer(
|
||||
Effect.gen(function* () {
|
||||
let checks = 0;
|
||||
const { manager } = yield* createManager(5, {
|
||||
subprocessInspector: () => {
|
||||
subprocessChecker: () => {
|
||||
checks += 1;
|
||||
return Effect.succeed({
|
||||
hasRunningSubprocess: false,
|
||||
runningPorts: [],
|
||||
});
|
||||
return Effect.succeed(false);
|
||||
},
|
||||
subprocessPollIntervalMs: 20,
|
||||
});
|
||||
|
||||
@@ -28,18 +28,7 @@ import {
|
||||
terminalRestartsTotal,
|
||||
terminalSessionsTotal,
|
||||
} from "../../observability/Metrics.ts";
|
||||
import { arePortListsEqual, normalizeRunningPorts } from "../../process/utils.ts";
|
||||
import {
|
||||
TerminalProcessInspector,
|
||||
TerminalProcessInspectionError,
|
||||
type TerminalSubprocessActivity,
|
||||
type TerminalSubprocessInspector,
|
||||
} from "../../process/Services/TerminalProcessInspector.ts";
|
||||
import {
|
||||
DEFAULT_WEB_PORT_PROBE_TTL_MS,
|
||||
WebPortInspector,
|
||||
type TerminalWebPortInspector,
|
||||
} from "../../process/Services/WebPortInspector.ts";
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import {
|
||||
TerminalCwdError,
|
||||
TerminalHistoryError,
|
||||
@@ -59,13 +48,22 @@ import {
|
||||
const DEFAULT_HISTORY_LINE_LIMIT = 5_000;
|
||||
const DEFAULT_PERSIST_DEBOUNCE_MS = 40;
|
||||
const DEFAULT_SUBPROCESS_POLL_INTERVAL_MS = 1_000;
|
||||
const DEFAULT_SUBPROCESS_ACTIVITY_ERROR_LOG_THROTTLE_MS = 30_000;
|
||||
const DEFAULT_PROCESS_KILL_GRACE_MS = 1_000;
|
||||
const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
|
||||
const DEFAULT_OPEN_COLS = 120;
|
||||
const DEFAULT_OPEN_ROWS = 30;
|
||||
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
|
||||
|
||||
class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubprocessCheckError>()(
|
||||
"TerminalSubprocessCheckError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
terminalPid: Schema.Number,
|
||||
command: Schema.Literals(["powershell", "pgrep", "ps"]),
|
||||
},
|
||||
) {}
|
||||
|
||||
class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcessSignalError>()(
|
||||
"TerminalProcessSignalError",
|
||||
{
|
||||
@@ -75,94 +73,8 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcess
|
||||
},
|
||||
) {}
|
||||
|
||||
interface SubprocessActivityErrorLogState {
|
||||
fingerprint: string;
|
||||
lastLoggedAt: number;
|
||||
suppressedRepeats: number;
|
||||
}
|
||||
|
||||
export function describeSubprocessInspectorError(error: unknown): {
|
||||
fingerprint: string;
|
||||
error: string;
|
||||
operation?: string;
|
||||
command?: string;
|
||||
detail?: string;
|
||||
cause?: string;
|
||||
} {
|
||||
if (Schema.is(TerminalProcessInspectionError)(error)) {
|
||||
const cause =
|
||||
error.cause instanceof Error
|
||||
? error.cause.message
|
||||
: typeof error.cause === "string"
|
||||
? error.cause
|
||||
: error.cause === undefined || error.cause === null
|
||||
? undefined
|
||||
: String(error.cause);
|
||||
return {
|
||||
fingerprint: JSON.stringify([
|
||||
error.operation,
|
||||
error.terminalPid,
|
||||
error.command,
|
||||
error.detail,
|
||||
cause ?? "",
|
||||
]),
|
||||
error: error.message,
|
||||
operation: error.operation,
|
||||
command: error.command,
|
||||
detail: error.detail,
|
||||
...(cause ? { cause } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
return {
|
||||
fingerprint: message,
|
||||
error: message,
|
||||
};
|
||||
}
|
||||
|
||||
export function nextSubprocessActivityErrorLogState(input: {
|
||||
previous: SubprocessActivityErrorLogState | undefined;
|
||||
fingerprint: string;
|
||||
now: number;
|
||||
throttleMs: number;
|
||||
}): {
|
||||
shouldLog: boolean;
|
||||
suppressedRepeats: number;
|
||||
next: SubprocessActivityErrorLogState;
|
||||
} {
|
||||
if (!input.previous || input.previous.fingerprint !== input.fingerprint) {
|
||||
return {
|
||||
shouldLog: true,
|
||||
suppressedRepeats: 0,
|
||||
next: {
|
||||
fingerprint: input.fingerprint,
|
||||
lastLoggedAt: input.now,
|
||||
suppressedRepeats: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (input.now - input.previous.lastLoggedAt >= input.throttleMs) {
|
||||
return {
|
||||
shouldLog: true,
|
||||
suppressedRepeats: input.previous.suppressedRepeats,
|
||||
next: {
|
||||
fingerprint: input.fingerprint,
|
||||
lastLoggedAt: input.now,
|
||||
suppressedRepeats: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
shouldLog: false,
|
||||
suppressedRepeats: input.previous.suppressedRepeats + 1,
|
||||
next: {
|
||||
...input.previous,
|
||||
suppressedRepeats: input.previous.suppressedRepeats + 1,
|
||||
},
|
||||
};
|
||||
interface TerminalSubprocessChecker {
|
||||
(terminalPid: number): Effect.Effect<boolean, TerminalSubprocessCheckError>;
|
||||
}
|
||||
|
||||
interface ShellCandidate {
|
||||
@@ -201,7 +113,6 @@ interface TerminalSessionState {
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runningSubprocessPorts: number[];
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
}
|
||||
|
||||
@@ -436,6 +347,108 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function checkWindowsSubprocessActivity(
|
||||
terminalPid: number,
|
||||
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
|
||||
const command = [
|
||||
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
|
||||
"if ($children) { exit 0 }",
|
||||
"exit 1",
|
||||
].join("; ");
|
||||
return Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
|
||||
timeoutMs: 1_500,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to check Windows terminal subprocess activity.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "powershell",
|
||||
}),
|
||||
}).pipe(Effect.map((result) => result.code === 0));
|
||||
}
|
||||
|
||||
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
|
||||
terminalPid: number,
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
|
||||
const runPgrep = Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("pgrep", ["-P", String(terminalPid)], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 32_768,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with pgrep.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "pgrep",
|
||||
}),
|
||||
});
|
||||
|
||||
const runPs = Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess("ps", ["-eo", "pid=,ppid="], {
|
||||
timeoutMs: 1_000,
|
||||
allowNonZeroExit: true,
|
||||
maxBufferBytes: 262_144,
|
||||
outputMode: "truncate",
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new TerminalSubprocessCheckError({
|
||||
message: "Failed to inspect terminal subprocesses with ps.",
|
||||
cause,
|
||||
terminalPid,
|
||||
command: "ps",
|
||||
}),
|
||||
});
|
||||
|
||||
const pgrepResult = yield* Effect.exit(runPgrep);
|
||||
if (pgrepResult._tag === "Success") {
|
||||
if (pgrepResult.value.code === 0) {
|
||||
return pgrepResult.value.stdout.trim().length > 0;
|
||||
}
|
||||
if (pgrepResult.value.code === 1) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const psResult = yield* Effect.exit(runPs);
|
||||
if (psResult._tag === "Failure" || psResult.value.code !== 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const line of psResult.value.stdout.split(/\r?\n/g)) {
|
||||
const [pidRaw, ppidRaw] = line.trim().split(/\s+/g);
|
||||
const pid = Number(pidRaw);
|
||||
const ppid = Number(ppidRaw);
|
||||
if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue;
|
||||
if (ppid === terminalPid) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
|
||||
terminalPid: number,
|
||||
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
|
||||
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
|
||||
return false;
|
||||
}
|
||||
if (process.platform === "win32") {
|
||||
return yield* checkWindowsSubprocessActivity(terminalPid);
|
||||
}
|
||||
return yield* checkPosixSubprocessActivity(terminalPid);
|
||||
});
|
||||
|
||||
function capHistory(history: string, maxLines: number): string {
|
||||
if (history.length === 0) return history;
|
||||
const hasTrailingNewline = history.endsWith("\n");
|
||||
@@ -681,11 +694,9 @@ interface TerminalManagerOptions {
|
||||
historyLineLimit?: number;
|
||||
ptyAdapter: PtyAdapterShape;
|
||||
shellResolver?: () => string;
|
||||
subprocessInspector?: TerminalSubprocessInspector;
|
||||
webPortInspector?: TerminalWebPortInspector;
|
||||
webPortProbeCacheTtlMs?: number;
|
||||
platform?: NodeJS.Platform;
|
||||
env?: NodeJS.ProcessEnv;
|
||||
subprocessChecker?: TerminalSubprocessChecker;
|
||||
subprocessPollIntervalMs?: number;
|
||||
processKillGraceMs?: number;
|
||||
maxRetainedInactiveSessions?: number;
|
||||
@@ -711,17 +722,12 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
const platform = options.platform ?? process.platform;
|
||||
const baseEnv = options.env ?? process.env;
|
||||
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
|
||||
const subprocessInspector =
|
||||
options.subprocessInspector ?? (yield* TerminalProcessInspector).inspect;
|
||||
const webPortInspector = options.webPortInspector ?? (yield* WebPortInspector).inspect;
|
||||
const webPortProbeCacheTtlMs = options.webPortProbeCacheTtlMs ?? DEFAULT_WEB_PORT_PROBE_TTL_MS;
|
||||
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
|
||||
const subprocessPollIntervalMs =
|
||||
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
|
||||
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
|
||||
const maxRetainedInactiveSessions =
|
||||
options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS;
|
||||
const webPortProbeCache = new Map<number, { isWeb: true; checkedAt: number }>();
|
||||
const subprocessActivityErrorLogState = new Map<string, SubprocessActivityErrorLogState>();
|
||||
|
||||
yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie);
|
||||
|
||||
@@ -741,66 +747,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
}
|
||||
});
|
||||
|
||||
const inspectWebPortCached = (port: number) =>
|
||||
Effect.gen(function* () {
|
||||
const now = Date.now();
|
||||
const cached = webPortProbeCache.get(port);
|
||||
for (const [cachedPort, entry] of webPortProbeCache) {
|
||||
if (cachedPort !== port && now - entry.checkedAt > webPortProbeCacheTtlMs) {
|
||||
webPortProbeCache.delete(cachedPort);
|
||||
}
|
||||
}
|
||||
|
||||
if (cached && now - cached.checkedAt <= webPortProbeCacheTtlMs) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const probeResult = yield* webPortInspector(port).pipe(Effect.exit);
|
||||
if (probeResult._tag === "Success") {
|
||||
if (probeResult.value) {
|
||||
webPortProbeCache.set(port, {
|
||||
isWeb: true,
|
||||
checkedAt: Date.now(),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
webPortProbeCache.delete(port);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cached) {
|
||||
webPortProbeCache.set(port, {
|
||||
isWeb: true,
|
||||
checkedAt: Date.now(),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
|
||||
const detectWebPorts = (runningPorts: number[]) =>
|
||||
Effect.gen(function* () {
|
||||
if (runningPorts.length === 0) {
|
||||
return [] as number[];
|
||||
}
|
||||
|
||||
const checks = yield* Effect.forEach(
|
||||
runningPorts,
|
||||
(port) =>
|
||||
Effect.map(inspectWebPortCached(port), (isWeb) => ({
|
||||
port,
|
||||
isWeb,
|
||||
})),
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return checks
|
||||
.filter((entry) => entry.isWeb)
|
||||
.map((entry) => entry.port)
|
||||
.toSorted((left, right) => left - right);
|
||||
});
|
||||
|
||||
const historyPath = (threadId: string, terminalId: string) => {
|
||||
const threadPart = toSafeThreadId(threadId);
|
||||
if (terminalId === DEFAULT_TERMINAL_ID) {
|
||||
@@ -1264,7 +1210,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.status = "exited";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.pendingProcessEvents = [];
|
||||
@@ -1332,7 +1277,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.process = null;
|
||||
session.pid = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.status = "exited";
|
||||
session.pendingHistoryControlSequence = "";
|
||||
session.pendingProcessEvents = [];
|
||||
@@ -1426,7 +1370,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.exitCode = null;
|
||||
session.exitSignal = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
@@ -1500,7 +1443,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session.unsubscribeData = null;
|
||||
session.unsubscribeExit = null;
|
||||
session.hasRunningSubprocess = false;
|
||||
session.runningSubprocessPorts = [];
|
||||
session.pendingProcessEvents = [];
|
||||
session.pendingProcessEventIndex = 0;
|
||||
session.processEventDrainRunning = false;
|
||||
@@ -1562,14 +1504,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
(session): session is TerminalSessionState & { pid: number } =>
|
||||
session.status === "running" && Number.isInteger(session.pid),
|
||||
);
|
||||
const activeRunningSessionKeys = new Set(
|
||||
runningSessions.map((session) => toSessionKey(session.threadId, session.terminalId)),
|
||||
);
|
||||
for (const sessionKey of subprocessActivityErrorLogState.keys()) {
|
||||
if (!activeRunningSessionKeys.has(sessionKey)) {
|
||||
subprocessActivityErrorLogState.delete(sessionKey);
|
||||
}
|
||||
}
|
||||
|
||||
if (runningSessions.length === 0) {
|
||||
return;
|
||||
@@ -1579,49 +1513,22 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
session: TerminalSessionState & { pid: number },
|
||||
) {
|
||||
const terminalPid = session.pid;
|
||||
const sessionKey = toSessionKey(session.threadId, session.terminalId);
|
||||
const activity = yield* subprocessInspector(terminalPid).pipe(
|
||||
Effect.tap(() => Effect.sync(() => subprocessActivityErrorLogState.delete(sessionKey))),
|
||||
const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe(
|
||||
Effect.map(Option.some),
|
||||
Effect.catch((error) => {
|
||||
const description = describeSubprocessInspectorError(error);
|
||||
const logDecision = nextSubprocessActivityErrorLogState({
|
||||
previous: subprocessActivityErrorLogState.get(sessionKey),
|
||||
fingerprint: description.fingerprint,
|
||||
now: Date.now(),
|
||||
throttleMs: DEFAULT_SUBPROCESS_ACTIVITY_ERROR_LOG_THROTTLE_MS,
|
||||
});
|
||||
subprocessActivityErrorLogState.set(sessionKey, logDecision.next);
|
||||
if (!logDecision.shouldLog) {
|
||||
return Effect.succeed(Option.none<TerminalSubprocessActivity>());
|
||||
}
|
||||
return Effect.logWarning("failed to check terminal subprocess activity", {
|
||||
Effect.catch((reason) =>
|
||||
Effect.logWarning("failed to check terminal subprocess activity", {
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
terminalPid,
|
||||
error: description.error,
|
||||
...(description.operation ? { operation: description.operation } : {}),
|
||||
...(description.command ? { command: description.command } : {}),
|
||||
...(description.detail ? { detail: description.detail } : {}),
|
||||
...(description.cause ? { cause: description.cause } : {}),
|
||||
...(logDecision.suppressedRepeats > 0
|
||||
? { suppressedRepeats: logDecision.suppressedRepeats }
|
||||
: {}),
|
||||
}).pipe(Effect.as(Option.none<TerminalSubprocessActivity>()));
|
||||
}),
|
||||
reason,
|
||||
}).pipe(Effect.as(Option.none<boolean>())),
|
||||
),
|
||||
);
|
||||
|
||||
if (Option.isNone(activity)) {
|
||||
if (Option.isNone(hasRunningSubprocess)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hasRunningSubprocess = activity.value.hasRunningSubprocess === true;
|
||||
const runningPorts = hasRunningSubprocess
|
||||
? normalizeRunningPorts(
|
||||
yield* detectWebPorts(normalizeRunningPorts(activity.value.runningPorts)),
|
||||
)
|
||||
: [];
|
||||
|
||||
const event = yield* modifyManagerState((state) => {
|
||||
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
|
||||
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
|
||||
@@ -1630,14 +1537,12 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
Option.isNone(liveSession) ||
|
||||
liveSession.value.status !== "running" ||
|
||||
liveSession.value.pid !== terminalPid ||
|
||||
(liveSession.value.hasRunningSubprocess === hasRunningSubprocess &&
|
||||
arePortListsEqual(liveSession.value.runningSubprocessPorts, runningPorts))
|
||||
liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value
|
||||
) {
|
||||
return [Option.none(), state] as const;
|
||||
}
|
||||
|
||||
liveSession.value.hasRunningSubprocess = hasRunningSubprocess;
|
||||
liveSession.value.runningSubprocessPorts = runningPorts;
|
||||
liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value;
|
||||
liveSession.value.updatedAt = new Date().toISOString();
|
||||
|
||||
return [
|
||||
@@ -1646,8 +1551,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
threadId: liveSession.value.threadId,
|
||||
terminalId: liveSession.value.terminalId,
|
||||
createdAt: new Date().toISOString(),
|
||||
hasRunningSubprocess,
|
||||
runningPorts,
|
||||
hasRunningSubprocess: hasRunningSubprocess.value,
|
||||
}),
|
||||
state,
|
||||
] as const;
|
||||
@@ -1746,7 +1650,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runningSubprocessPorts: [],
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
|
||||
@@ -1926,7 +1829,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
|
||||
unsubscribeData: null,
|
||||
unsubscribeExit: null,
|
||||
hasRunningSubprocess: false,
|
||||
runningSubprocessPorts: [],
|
||||
runtimeEnv: normalizedRuntimeEnv(input.env),
|
||||
};
|
||||
const createdSession = session;
|
||||
|
||||
@@ -51,7 +51,6 @@ export interface TerminalSessionState {
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runningSubprocessPorts: number[];
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -457,6 +457,7 @@ const makeWsRpcLayer = (currentSessionId: AuthSessionId) =>
|
||||
cwd: bootstrap.prepareWorktree.projectCwd,
|
||||
branch: bootstrap.prepareWorktree.baseBranch,
|
||||
newBranch: bootstrap.prepareWorktree.branch,
|
||||
...(bootstrap.prepareWorktree.fetchLatestOrigin ? { fetchLatestOrigin: true } : {}),
|
||||
path: null,
|
||||
});
|
||||
targetWorktreePath = worktree.worktree.path;
|
||||
|
||||
@@ -9,7 +9,7 @@ export default defineConfig({
|
||||
outDir: "dist",
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
inlineOnly: false,
|
||||
banner: {
|
||||
js: "#!/usr/bin/env node\n",
|
||||
|
||||
@@ -23,6 +23,8 @@ interface BranchToolbarProps {
|
||||
effectiveEnvModeOverride?: EnvMode;
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
fetchLatestOriginOverride?: boolean;
|
||||
onFetchLatestOriginOverrideChange?: (fetchLatestOrigin: boolean) => void;
|
||||
envLocked: boolean;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
@@ -38,6 +40,8 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
fetchLatestOriginOverride,
|
||||
onFetchLatestOriginOverrideChange,
|
||||
envLocked,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
@@ -109,6 +113,8 @@ export const BranchToolbar = memo(function BranchToolbar({
|
||||
{...(effectiveEnvModeOverride ? { effectiveEnvModeOverride } : {})}
|
||||
{...(activeThreadBranchOverride !== undefined ? { activeThreadBranchOverride } : {})}
|
||||
{...(onActiveThreadBranchOverrideChange ? { onActiveThreadBranchOverrideChange } : {})}
|
||||
{...(fetchLatestOriginOverride !== undefined ? { fetchLatestOriginOverride } : {})}
|
||||
{...(onFetchLatestOriginOverrideChange ? { onFetchLatestOriginOverrideChange } : {})}
|
||||
{...(onCheckoutPullRequestRequest ? { onCheckoutPullRequestRequest } : {})}
|
||||
{...(onComposerFocusRequest ? { onComposerFocusRequest } : {})}
|
||||
/>
|
||||
|
||||
@@ -42,6 +42,7 @@ import {
|
||||
ComboboxStatus,
|
||||
ComboboxTrigger,
|
||||
} from "./ui/combobox";
|
||||
import { Switch } from "./ui/switch";
|
||||
import { toastManager } from "./ui/toast";
|
||||
|
||||
interface BranchToolbarBranchSelectorProps {
|
||||
@@ -52,6 +53,8 @@ interface BranchToolbarBranchSelectorProps {
|
||||
effectiveEnvModeOverride?: "local" | "worktree";
|
||||
activeThreadBranchOverride?: string | null;
|
||||
onActiveThreadBranchOverrideChange?: (branch: string | null) => void;
|
||||
fetchLatestOriginOverride?: boolean;
|
||||
onFetchLatestOriginOverrideChange?: (fetchLatestOrigin: boolean) => void;
|
||||
onCheckoutPullRequestRequest?: (reference: string) => void;
|
||||
onComposerFocusRequest?: () => void;
|
||||
}
|
||||
@@ -83,6 +86,8 @@ export function BranchToolbarBranchSelector({
|
||||
effectiveEnvModeOverride,
|
||||
activeThreadBranchOverride,
|
||||
onActiveThreadBranchOverrideChange,
|
||||
fetchLatestOriginOverride,
|
||||
onFetchLatestOriginOverrideChange,
|
||||
onCheckoutPullRequestRequest,
|
||||
onComposerFocusRequest,
|
||||
}: BranchToolbarBranchSelectorProps) {
|
||||
@@ -118,6 +123,10 @@ export function BranchToolbarBranchSelector({
|
||||
activeThreadBranchOverride !== undefined
|
||||
? activeThreadBranchOverride
|
||||
: (serverThread?.branch ?? draftThread?.branch ?? null);
|
||||
const fetchLatestOrigin =
|
||||
fetchLatestOriginOverride !== undefined
|
||||
? fetchLatestOriginOverride
|
||||
: (draftThread?.fetchLatestOriginOnWorktreeCreate ?? false);
|
||||
const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
|
||||
const activeProjectCwd = activeProject?.cwd ?? null;
|
||||
const branchCwd = activeWorktreePath ?? activeProjectCwd;
|
||||
@@ -233,7 +242,6 @@ export function BranchToolbarBranchSelector({
|
||||
activeThreadBranch,
|
||||
currentGitBranch,
|
||||
});
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchByName = useMemo(
|
||||
() => new Map(branches.map((branch) => [branch.name, branch] as const)),
|
||||
[branches],
|
||||
@@ -249,6 +257,7 @@ export function BranchToolbarBranchSelector({
|
||||
const createBranchItemValue = canCreateBranch
|
||||
? `__create_new_branch__:${trimmedBranchQuery}`
|
||||
: null;
|
||||
const branchNames = useMemo(() => branches.map((branch) => branch.name), [branches]);
|
||||
const branchPickerItems = useMemo(() => {
|
||||
const items = [...branchNames];
|
||||
if (createBranchItemValue && !hasExactBranchMatch) {
|
||||
@@ -285,6 +294,16 @@ export function BranchToolbarBranchSelector({
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
const shouldVirtualizeBranchList = filteredBranchPickerItems.length > 40;
|
||||
const totalBranchCount = branchesSearchData?.pages[0]?.totalCount ?? 0;
|
||||
const hasOriginRemote =
|
||||
branchesSearchData?.pages[0]?.hasOriginRemote ??
|
||||
branchStatusQuery.data?.hasOriginRemote ??
|
||||
false;
|
||||
const selectedBaseBranch = resolvedActiveBranch ? branchByName.get(resolvedActiveBranch) : null;
|
||||
const shouldShowFetchLatestOriginToggle =
|
||||
isSelectingWorktreeBase &&
|
||||
hasOriginRemote &&
|
||||
resolvedActiveBranch !== null &&
|
||||
!(selectedBaseBranch?.isRemote ?? resolvedActiveBranch.startsWith("origin/"));
|
||||
const branchStatusText = isBranchesSearchPending
|
||||
? "Loading branches..."
|
||||
: isFetchingNextPage
|
||||
@@ -305,14 +324,32 @@ export function BranchToolbarBranchSelector({
|
||||
});
|
||||
};
|
||||
|
||||
const selectWorktreeBaseBranch = (branchName: string) => {
|
||||
if (!isSelectingWorktreeBase || isBranchActionPending) return;
|
||||
setThreadBranch(branchName, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
};
|
||||
|
||||
const setFetchLatestOriginForWorktreeCreate = useCallback(
|
||||
(nextFetchLatestOrigin: boolean) => {
|
||||
if (hasServerThread) {
|
||||
onFetchLatestOriginOverrideChange?.(nextFetchLatestOrigin);
|
||||
return;
|
||||
}
|
||||
setDraftThreadContext(draftId ?? threadRef, {
|
||||
fetchLatestOriginOnWorktreeCreate: nextFetchLatestOrigin,
|
||||
});
|
||||
},
|
||||
[draftId, hasServerThread, onFetchLatestOriginOverrideChange, setDraftThreadContext, threadRef],
|
||||
);
|
||||
|
||||
const selectBranch = (branch: GitBranch) => {
|
||||
const api = readEnvironmentApi(environmentId);
|
||||
if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return;
|
||||
|
||||
if (isSelectingWorktreeBase) {
|
||||
setThreadBranch(branch.name, null);
|
||||
setIsBranchMenuOpen(false);
|
||||
onComposerFocusRequest?.();
|
||||
selectWorktreeBaseBranch(branch.name);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -591,6 +628,17 @@ export function BranchToolbarBranchSelector({
|
||||
onChange={(event) => setBranchQuery(event.target.value)}
|
||||
/>
|
||||
</div>
|
||||
{shouldShowFetchLatestOriginToggle ? (
|
||||
<label className="flex min-w-0 items-center justify-between gap-3 border-b px-3 py-2">
|
||||
<span className="min-w-0 truncate text-sm">Fetch latest origin before creation</span>
|
||||
<Switch
|
||||
className="shrink-0"
|
||||
checked={fetchLatestOrigin}
|
||||
aria-label="Fetch latest origin before creation"
|
||||
onCheckedChange={(checked) => setFetchLatestOriginForWorktreeCreate(Boolean(checked))}
|
||||
/>
|
||||
</label>
|
||||
) : null}
|
||||
<ComboboxEmpty>No branches found.</ComboboxEmpty>
|
||||
|
||||
{shouldVirtualizeBranchList ? (
|
||||
|
||||
@@ -1753,7 +1753,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
terminalHeight: 280,
|
||||
terminalIds: ["default"],
|
||||
runningTerminalIds: [],
|
||||
runningTerminalPorts: {},
|
||||
activeTerminalId: "default",
|
||||
terminalGroups: [{ id: "group-default", terminalIds: ["default"] }],
|
||||
activeTerminalGroupId: "group-default",
|
||||
@@ -2606,6 +2605,110 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("can fetch the latest origin ref before creating a worktree", async () => {
|
||||
const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: {
|
||||
...snapshot,
|
||||
threads: snapshot.threads.map((thread) =>
|
||||
thread.id === THREAD_ID ? Object.assign({}, thread, { session: null }) : thread,
|
||||
),
|
||||
},
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitListBranches) {
|
||||
return {
|
||||
isRepo: true,
|
||||
hasOriginRemote: true,
|
||||
nextCursor: null,
|
||||
totalCount: 1,
|
||||
branches: [
|
||||
{
|
||||
name: "main",
|
||||
originRef: "origin/main",
|
||||
current: true,
|
||||
isDefault: true,
|
||||
worktreePath: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
if (body._tag === ORCHESTRATION_WS_METHODS.dispatchCommand) {
|
||||
return {
|
||||
sequence: fixture.snapshot.snapshotSequence + 1,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
(await waitForButtonByText("Current checkout")).click();
|
||||
await page.getByText("New worktree", { exact: true }).click();
|
||||
await page.getByText("From main", { exact: true }).click();
|
||||
await page.getByRole("switch", { name: "Fetch latest origin before creation" }).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const turnStartRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
|
||||
request.type === "thread.turn.start",
|
||||
) as
|
||||
| {
|
||||
_tag: string;
|
||||
type?: string;
|
||||
bootstrap?: {
|
||||
prepareWorktree?: {
|
||||
baseBranch?: string;
|
||||
fetchLatestOrigin?: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
expect(findButtonByText("From main")).toBeTruthy();
|
||||
expect(turnStartRequest?.bootstrap?.prepareWorktree?.fetchLatestOrigin).not.toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().setPrompt(THREAD_REF, "Ship it");
|
||||
await waitForLayout();
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(false);
|
||||
sendButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const turnStartRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
|
||||
request.type === "thread.turn.start",
|
||||
) as
|
||||
| {
|
||||
_tag: string;
|
||||
type?: string;
|
||||
bootstrap?: {
|
||||
prepareWorktree?: {
|
||||
baseBranch?: string;
|
||||
fetchLatestOrigin?: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
| undefined;
|
||||
|
||||
expect(turnStartRequest?.bootstrap?.prepareWorktree?.baseBranch).toBe("main");
|
||||
expect(turnStartRequest?.bootstrap?.prepareWorktree?.fetchLatestOrigin).toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("clears pending worktree overrides when switching empty server threads", async () => {
|
||||
const secondThreadId = "thread-browser-test-second" as ThreadId;
|
||||
const snapshot = addThreadToSnapshot(createDraftOnlySnapshot(), THREAD_ID);
|
||||
|
||||
Loaded 100 of 171 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user