Skip to content

Commit 01d13e8

Browse files
authored
Merge branch 'main' into up/eval-proxy-cost-label
2 parents b85b074 + 3fd2b85 commit 01d13e8

22 files changed

Lines changed: 566 additions & 119 deletions

‎apps/server/src/persistence/DatabaseMaintenance.test.ts‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as NodeServices from "@effect/platform-node/NodeServices";
22
import { assert, it } from "@effect/vitest";
3+
import * as HostProcess from "@t3tools/shared/HostProcess";
34
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
45
import * as Clock from "effect/Clock";
56
import * as Duration from "effect/Duration";
@@ -44,6 +45,7 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
4445
yield* Effect.gen(function* () {
4546
const sql = yield* SqlClient.SqlClient;
4647
yield* sql`CREATE TABLE retained_data (value TEXT)`;
48+
yield* sql`INSERT INTO retained_data VALUES ('keep')`;
4749
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath })));
4850
assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
4951

@@ -52,21 +54,52 @@ it.layer(DatabaseMaintenance.layer.pipe(Layer.provideMerge(NodeServices.layer)))
5254
const sql = yield* SqlClient.SqlClient;
5355
yield* sql`PRAGMA journal_mode = WAL`;
5456
yield* sql`CREATE TABLE v1_data (value TEXT)`;
57+
yield* sql`INSERT INTO v1_data VALUES ('rollback')`;
5558
}).pipe(Effect.provide(openLegacy));
5659
assert.isAbove((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes ?? 0, 0);
5760

5861
const refused = yield* Effect.gen(function* () {
5962
const sql = yield* SqlClient.SqlClient;
6063
yield* sql`SELECT value FROM v1_data`;
61-
return yield* Effect.flip(maintenance.removeLegacyDatabase(dbPath));
64+
const failure = yield* Effect.flip(maintenance.removeLegacyDatabase(dbPath));
65+
assert.deepEqual(yield* sql`SELECT value FROM v1_data`, [{ value: "rollback" }]);
66+
return failure;
6267
}).pipe(Effect.provide(openLegacy));
6368
assert.equal(refused._tag, "DatabaseInUseError");
6469
assert.isTrue(yield* fs.exists(legacy));
6570

66-
yield* maintenance.removeLegacyDatabase(dbPath);
71+
yield* Effect.flatMap(DatabaseMaintenance.DatabaseMaintenance, (service) =>
72+
service.removeLegacyDatabase(dbPath),
73+
).pipe(
74+
Effect.provide(Layer.fresh(DatabaseMaintenance.layer)),
75+
Effect.provideService(HostProcess.Platform, "win32"),
76+
Effect.provideService(FileSystem.FileSystem, {
77+
...fs,
78+
remove: (target, options) =>
79+
Effect.gen(function* () {
80+
if (target === legacy) {
81+
yield* Effect.gen(function* () {
82+
const sql = yield* SqlClient.SqlClient;
83+
yield* sql`PRAGMA busy_timeout = 0`;
84+
yield* sql`BEGIN EXCLUSIVE`;
85+
yield* sql`COMMIT`;
86+
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
87+
// Create sidecars after the probe closes so only Doctor can remove them.
88+
yield* fs.writeFileString(`${legacy}-wal`, "leftover WAL");
89+
yield* fs.writeFileString(`${legacy}-shm`, "leftover SHM");
90+
}
91+
yield* fs.remove(target, options);
92+
}),
93+
}),
94+
);
6795
assert.isFalse(yield* fs.exists(legacy));
6896
assert.isFalse(yield* fs.exists(`${legacy}-wal`));
97+
assert.isFalse(yield* fs.exists(`${legacy}-shm`));
6998
assert.isTrue(yield* fs.exists(dbPath));
99+
yield* Effect.gen(function* () {
100+
const sql = yield* SqlClient.SqlClient;
101+
assert.deepEqual(yield* sql`SELECT value FROM retained_data`, [{ value: "keep" }]);
102+
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: dbPath, readonly: true })));
70103
assert.isNull((yield* maintenance.inspect(dbPath)).legacyDatabaseBytes);
71104
}).pipe(Effect.scoped),
72105
);

‎apps/server/src/persistence/DatabaseMaintenance.ts‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as HostProcess from "@t3tools/shared/HostProcess";
12
import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
23
import * as Context from "effect/Context";
34
import * as Effect from "effect/Effect";
@@ -220,13 +221,23 @@ const make = Effect.gen(function* () {
220221
function* (databasePath: string) {
221222
const legacy = legacyPath(databasePath);
222223
if (!(yield* fs.exists(legacy))) return;
223-
// Older servers may use this file; hold its lock and delete the database before WAL to preserve commits on failure.
224-
yield* Effect.gen(function* () {
225-
yield* lockExclusively(legacy);
226-
for (const suffix of ["", "-wal", "-shm"]) {
227-
yield* fs.remove(legacy + suffix, { force: true });
228-
}
229-
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: legacy })));
224+
// Delete the database before WAL to preserve commits if unlink fails.
225+
const removeFiles = Effect.forEach(
226+
["", "-wal", "-shm"],
227+
(suffix) => fs.remove(legacy + suffix, { force: true }),
228+
{ discard: true },
229+
);
230+
const connection = NodeSqliteClient.layer({ filename: legacy });
231+
if ((yield* HostProcess.Platform) === "win32") {
232+
// Windows blocks unlink while any SQLite handle is open, including our own.
233+
yield* lockExclusively(legacy).pipe(Effect.provide(connection));
234+
yield* removeFiles;
235+
} else {
236+
yield* lockExclusively(legacy).pipe(
237+
Effect.andThen(removeFiles),
238+
Effect.provide(connection),
239+
);
240+
}
230241
},
231242
(effect, databasePath) =>
232243
effect.pipe(

‎docs/operations/development.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -263,18 +263,19 @@ options.
263263

264264
### Prepared server bytecode
265265

266-
Native desktop artifact builds generate server bytecode with the packaged Electron executable,
267-
after ASAR creation and before signing. Cross-platform and cross-architecture builds skip this
268-
step explicitly. CLI, SEA and WSL runtimes keep their existing behavior; only desktop backend
269-
imports covered by generation receive prepared bytecode. Worker-only modules compile normally.
266+
Native macOS and Windows desktop artifact builds generate server bytecode with the packaged
267+
Electron executable, after ASAR creation and before signing. Linux builds skip generation until
268+
native packaging and relocated AppImage reuse have been validated. Cross-platform and
269+
cross-architecture builds also skip generation explicitly. CLI, SEA and WSL runtimes keep their
270+
existing behavior; only desktop backend imports covered by generation receive prepared bytecode.
271+
Worker-only modules compile normally.
270272

271273
Electron's Node 24 cache has no read-only option and includes the producer UID in its directory
272274
name. The backend links individual prepared files into its writable cache with keys for the
273275
installed module paths. Node replaces files atomically, so regeneration cannot write through those
274276
links into signed resources. Windows uses hard links and falls back to normal caching when volumes
275277
differ or resource permissions prevent linking. Protected installations therefore may not reuse
276-
prepared bytecode. No cache bytes are copied during startup. AppImage backends discard their links
277-
on normal exit because each mount changes module paths.
278+
prepared bytecode. No cache bytes are copied during startup.
278279

279280
The key calculation follows Node's internal portable ESM format. Generation checks that the
280281
packaged engine produced the expected CLI entry and fails the build if that format changes.

‎packages/provider-cursor/src/server/CursorAgentSdk.test.ts‎

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { assert, describe, it } from "@effect/vitest";
33
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
44
import * as Effect from "effect/Effect";
55
import * as Layer from "effect/Layer";
6+
import * as Exit from "effect/Exit";
7+
import * as Cause from "effect/Cause";
68
import { vi } from "vite-plus/test";
79

810
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
@@ -94,17 +96,19 @@ const cursorSdkMock = vi.hoisted(() => {
9496
});
9597

9698
vi.mock("./sdk.ts", () => ({
97-
Agent: {
98-
create: cursorSdkMock.create,
99-
resume: cursorSdkMock.resume,
100-
listRuns: cursorSdkMock.listRuns,
101-
cancelRun: cursorSdkMock.cancelRun,
102-
messages: {
103-
list: vi.fn(async () => []),
99+
loadCursorSdk: () => ({
100+
Agent: {
101+
create: cursorSdkMock.create,
102+
resume: cursorSdkMock.resume,
103+
listRuns: cursorSdkMock.listRuns,
104+
cancelRun: cursorSdkMock.cancelRun,
105+
messages: {
106+
list: vi.fn(async () => []),
107+
},
104108
},
105-
},
106-
createAgentPlatform: vi.fn(),
107-
SqliteLocalAgentStore: { open: vi.fn() },
109+
createAgentPlatform: vi.fn(),
110+
}),
111+
loadCursorSqlite: () => ({ SqliteLocalAgentStore: { open: vi.fn() } }),
108112
}));
109113

110114
const layerTest = CursorAgentSdk.layer.pipe(
@@ -132,6 +136,41 @@ const layerTest = CursorAgentSdk.layer.pipe(
132136
);
133137

134138
describe("CursorAgentSdkRunner", () => {
139+
it.effect("constructs without loading and reports first-use load failures as runner errors", () =>
140+
Effect.gen(function* () {
141+
const failure = new Error("missing SDK chunk");
142+
const load = vi.fn(() => {
143+
throw failure;
144+
});
145+
const runner = yield* CursorAgentSdk.makeCursorAgentSdkRunner(() => undefined).pipe(
146+
Effect.provideService(CursorSdk.CursorSdk, {
147+
load,
148+
loadSqlite: () => {
149+
throw new Error("unused SQLite");
150+
},
151+
}),
152+
);
153+
assert.strictEqual(load.mock.calls.length, 0);
154+
const result = yield* runner
155+
.open({
156+
operation: "create",
157+
options: {},
158+
threadId: ThreadId.make("lazy-load"),
159+
providerSessionId: ProviderSessionId.make("lazy-load"),
160+
})
161+
.pipe(Effect.exit);
162+
assert(Exit.isFailure(result));
163+
assert.deepStrictEqual(
164+
Cause.squash(result.cause),
165+
new CursorAgentSdk.CursorAgentSdkRunnerError({
166+
method: "agent.create",
167+
cause: failure,
168+
}),
169+
);
170+
assert.strictEqual(load.mock.calls.length, 1);
171+
}),
172+
);
173+
135174
it.effect("retries a resumed send after cancelling its abandoned local run", () =>
136175
Effect.gen(function* () {
137176
cursorSdkMock.runOperations.length = 0;

‎packages/provider-cursor/src/server/CursorAgentSdk.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ function makeCursorAgentSdkProtocolLogger(input: {
340340
export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(function* (
341341
protocolLoggerFor: (input: CursorAgentSdkOpenInput) => CursorAgentSdkProtocolLogger | undefined,
342342
) {
343-
const { Agent, createAgentPlatform } = yield* CursorSdk.CursorSdk;
343+
const sdk = yield* CursorSdk.CursorSdk;
344344

345345
// Prime with cursorsandbox before any Full access run; the SDK caches sandbox support per process.
346346
const sandboxSupportPrimeStarted = yield* Ref.make(false);
@@ -352,7 +352,9 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
352352
}
353353
yield* Effect.tryPromise(async () => {
354354
const cwd = typeof options.local?.cwd === "string" ? options.local.cwd : undefined;
355-
const platform = await createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
355+
const platform = await sdk
356+
.load()
357+
.createAgentPlatform(cwd === undefined ? {} : { workspaceRef: cwd });
356358
const release = await platform.prewarmLocalWorkspace({
357359
...(options.apiKey === undefined ? {} : { apiKey: options.apiKey }),
358360
local: {
@@ -368,6 +370,10 @@ export const makeCursorAgentSdkRunner = Effect.fn("makeCursorAgentSdkRunner")(fu
368370

369371
return CursorAgentSdkRunner.of({
370372
open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
373+
const { Agent } = yield* Effect.try({
374+
try: sdk.load,
375+
catch: (cause) => runnerError(cause, `agent.${input.operation}`),
376+
});
371377
if (input.options.local?.sandboxOptions?.enabled === false) {
372378
yield* primeCursorSandboxSupport(input.options);
373379
}

‎packages/provider-cursor/src/server/CursorSdk.test.ts‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import { vi } from "vite-plus/test";
55

66
import * as CursorSdk from "./CursorSdk.ts";
77

8-
vi.mock("./sdk.ts", () => ({ Agent: {}, createAgentPlatform: {}, SqliteLocalAgentStore: {} }));
9-
108
// Shaped like the SDK's minified class: the constructor is not named after the error.
119
class o extends Error {
1210
override name = "WriteIterableClosedError";

‎packages/provider-cursor/src/server/CursorSdk.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import * as Context from "effect/Context";
33
import * as Effect from "effect/Effect";
44
import * as Layer from "effect/Layer";
55

6-
import { Agent, createAgentPlatform, SqliteLocalAgentStore } from "./sdk.ts";
6+
import { loadCursorSdk, loadCursorSqlite } from "./sdk.ts";
77

88
// The SDK leaves a shell-error promise unhandled, which would exit the server.
99
const CURSOR_SHELL_SPAWN_MARKERS = [
@@ -60,9 +60,8 @@ function onUnhandledRejection(reason: unknown): void {
6060
export class CursorSdk extends Context.Service<
6161
CursorSdk,
6262
{
63-
readonly Agent: typeof Agent;
64-
readonly createAgentPlatform: typeof createAgentPlatform;
65-
readonly SqliteLocalAgentStore: typeof SqliteLocalAgentStore;
63+
readonly load: typeof loadCursorSdk;
64+
readonly loadSqlite: typeof loadCursorSqlite;
6665
}
6766
>()("@t3tools/provider-cursor/server/CursorSdk") {}
6867

@@ -77,5 +76,5 @@ export const layer = Layer.effect(
7776
Effect.sync(() => {
7877
process.off("unhandledRejection", onUnhandledRejection);
7978
}),
80-
).pipe(Effect.as(CursorSdk.of({ Agent, createAgentPlatform, SqliteLocalAgentStore }))),
79+
).pipe(Effect.as(CursorSdk.of({ load: loadCursorSdk, loadSqlite: loadCursorSqlite }))),
8180
);

0 commit comments

Comments
 (0)