A desktop coding agent with free access to frontier models.
TypeScript
import { eq } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
import { existsSync } from "node:fs";
import { isSqliteReadonlyError, openRuntimeSqliteDatabase, runtimeDbPath, type RuntimeSqliteDatabase } from "./runtime-db.js";
import type { ServerConfig } from "./types.js";
type WorkspaceKvSchemaVersionColumn = {
name: string;
definition: string;
value: number;
};
type WorkspaceKvExtraColumns = {
schemaVersion?: WorkspaceKvSchemaVersionColumn;
};
type WorkspaceKvStoreOptions<T> = {
tableName: string;
valueColumn: string;
extraColumns?: WorkspaceKvExtraColumns;
parse: (json: string) => T;
serialize: (value: T) => string;
};
type WorkspaceKvTableConfig = {
tableName: string;
valueColumn: string;
createTableSql: string;
selectSql: string;
upsertSql: string;
schemaVersion?: WorkspaceKvSchemaVersionColumn;
};
type WorkspaceKvStoredRow = {
valueJson: string;
updatedAt: number | null;
};
type WorkspaceKvRow<T> = WorkspaceKvStoredRow & {
value: T;
};
type WorkspaceKvDb = {
get: (workspaceId: string) => WorkspaceKvStoredRow | undefined;
upsert: (value: { workspaceId: string; valueJson: string; updatedAt: number }) => void;
};
const IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
const dbByPath = new Map<string, Promise<RuntimeSqliteDatabase>>();
const tableDbByPath = new Map<string, Map<string, Promise<WorkspaceKvDb>>>();
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function validIdentifier(value: string, label: string): string {
if (!IDENTIFIER_RE.test(value)) throw new Error(`Invalid ${label}: ${value}`);
return value;
}
function validSchemaVersion(column: WorkspaceKvSchemaVersionColumn | undefined): WorkspaceKvSchemaVersionColumn | undefined {
if (!column) return undefined;
validIdentifier(column.name, "extra column");
return column;
}
function createTableSql(config: {
tableName: string;
valueColumn: string;
schemaVersion?: WorkspaceKvSchemaVersionColumn;
}): string {
const columns = [
"workspace_id TEXT PRIMARY KEY NOT NULL",
`${config.valueColumn} TEXT NOT NULL`,
...(config.schemaVersion ? [`${config.schemaVersion.name} ${config.schemaVersion.definition}`] : []),
"updated_at INTEGER NOT NULL",
];
return `CREATE TABLE IF NOT EXISTS ${config.tableName} (${columns.join(", ")})`;
}
function upsertSql(config: {
tableName: string;
valueColumn: string;
schemaVersion?: WorkspaceKvSchemaVersionColumn;
}): string {
const insertColumns = ["workspace_id", config.valueColumn, ...(config.schemaVersion ? [config.schemaVersion.name] : []), "updated_at"];
const insertValues = ["?", "?", ...(config.schemaVersion ? [String(config.schemaVersion.value)] : []), "?"];
const updateColumns = [config.valueColumn, ...(config.schemaVersion ? [config.schemaVersion.name] : []), "updated_at"];
const updates = updateColumns.map((column) => `${column} = excluded.${column}`);
return `INSERT INTO ${config.tableName} (${insertColumns.join(", ")}) VALUES (${insertValues.join(", ")}) ON CONFLICT(workspace_id) DO UPDATE SET ${updates.join(", ")}`;
}
function tableConfig<T>(options: WorkspaceKvStoreOptions<T>): WorkspaceKvTableConfig {
const tableName = validIdentifier(options.tableName, "table name");
const valueColumn = validIdentifier(options.valueColumn, "value column");
const schemaVersion = validSchemaVersion(options.extraColumns?.schemaVersion);
return {
tableName,
valueColumn,
createTableSql: createTableSql({ tableName, valueColumn, schemaVersion }),
selectSql: `SELECT ${valueColumn} AS valueJson, updated_at AS updatedAt FROM ${tableName} WHERE workspace_id = ?`,
upsertSql: upsertSql({ tableName, valueColumn, schemaVersion }),
...(schemaVersion ? { schemaVersion } : {}),
};
}
function rowFromUnknown(row: unknown): WorkspaceKvStoredRow | undefined {
if (!isRecord(row) || typeof row.valueJson !== "string") return undefined;
return {
valueJson: row.valueJson,
updatedAt: typeof row.updatedAt === "number" ? row.updatedAt : null,
};
}
async function forgetRuntimeDb(path: string): Promise<void> {
const opened = dbByPath.get(path);
dbByPath.delete(path);
tableDbByPath.delete(path);
const runtime = await opened?.catch(() => null);
try {
runtime?.close();
} catch {
// Already closed.
}
}
async function runtimeDb(path: string): Promise<RuntimeSqliteDatabase> {
const existing = dbByPath.get(path);
if (existing) return existing;
const db = openRuntimeSqliteDatabase(path);
dbByPath.set(path, db);
// A failed open is not kept: the next start (Try again) opens again.
db.catch(() => {
if (dbByPath.get(path) === db) dbByPath.delete(path);
});
return db;
}
async function openTableDb(path: string, config: WorkspaceKvTableConfig): Promise<WorkspaceKvDb> {
const runtime = await runtimeDb(path);
if (runtime.kind === "bun") {
runtime.sqlite.run(config.createTableSql);
const db = runtime.db;
const schemaVersion = config.schemaVersion;
if (schemaVersion) {
const table = sqliteTable(config.tableName, {
workspaceId: text("workspace_id").primaryKey(),
valueJson: text(config.valueColumn).notNull(),
schemaVersion: integer(schemaVersion.name).notNull().default(schemaVersion.value),
updatedAt: integer("updated_at").notNull(),
});
return {
get: (workspaceId) => db
.select({ valueJson: table.valueJson, updatedAt: table.updatedAt })
.from(table)
.where(eq(table.workspaceId, workspaceId))
.get(),
upsert: ({ workspaceId, valueJson, updatedAt }) => {
db
.insert(table)
.values({ workspaceId, valueJson, schemaVersion: schemaVersion.value, updatedAt })
.onConflictDoUpdate({
target: table.workspaceId,
set: { valueJson, schemaVersion: schemaVersion.value, updatedAt },
})
.run();
},
};
}
const table = sqliteTable(config.tableName, {
workspaceId: text("workspace_id").primaryKey(),
valueJson: text(config.valueColumn).notNull(),
updatedAt: integer("updated_at").notNull(),
});
return {
get: (workspaceId) => db
.select({ valueJson: table.valueJson, updatedAt: table.updatedAt })
.from(table)
.where(eq(table.workspaceId, workspaceId))
.get(),
upsert: ({ workspaceId, valueJson, updatedAt }) => {
db
.insert(table)
.values({ workspaceId, valueJson, updatedAt })
.onConflictDoUpdate({
target: table.workspaceId,
set: { valueJson, updatedAt },
})
.run();
},
};
}
const sqlite = runtime.sqlite;
sqlite.exec(config.createTableSql);
const get = sqlite.prepare(config.selectSql);
const upsert = sqlite.prepare(config.upsertSql);
return {
get: (workspaceId) => rowFromUnknown(get.get(workspaceId)),
upsert: ({ workspaceId, valueJson, updatedAt }) => {
upsert.run(workspaceId, valueJson, updatedAt);
},
};
}
async function workspaceKvDb(path: string, config: WorkspaceKvTableConfig): Promise<WorkspaceKvDb> {
let tableDbs = tableDbByPath.get(path);
if (!tableDbs) {
tableDbs = new Map<string, Promise<WorkspaceKvDb>>();
tableDbByPath.set(path, tableDbs);
}
const existing = tableDbs.get(config.tableName);
if (existing) return existing;
const db = openTableDb(path, config);
tableDbs.set(config.tableName, db);
const tables = tableDbs;
db.catch(() => {
if (tables.get(config.tableName) === db) tables.delete(config.tableName);
});
return db;
}
/**
* Reads must never materialize the runtime DB. A fresh install reads stores
* before anything is written (startup provider-auth sync is one), and opening
* with create:true would grow the state directory and an empty SQLite file
* just to learn there is nothing stored. A missing file reads like an empty
* one. An already-open connection still wins: a write in flight has the file
* on the way even when it is not on disk yet.
*/
async function readableWorkspaceKvDb(
path: string,
config: WorkspaceKvTableConfig,
): Promise<WorkspaceKvDb | undefined> {
const opened = tableDbByPath.get(path)?.get(config.tableName);
if (opened) return opened;
if (!dbByPath.has(path) && !existsSync(path)) return undefined;
return workspaceKvDb(path, config);
}
export function createWorkspaceKvStore<T>(options: WorkspaceKvStoreOptions<T>) {
const config = tableConfig(options);
async function getRow(serverConfig: ServerConfig, workspaceId: string): Promise<WorkspaceKvRow<T> | undefined> {
const db = await readableWorkspaceKvDb(runtimeDbPath(serverConfig), config);
const row = db?.get(workspaceId);
return row ? { ...row, value: options.parse(row.valueJson) } : undefined;
}
async function setSerialized(
serverConfig: ServerConfig,
workspaceId: string,
valueJson: string,
updatedAt: number,
): Promise<void> {
const path = runtimeDbPath(serverConfig);
const db = await workspaceKvDb(path, config);
try {
db.upsert({ workspaceId, valueJson, updatedAt });
} catch (error) {
// A connection opened while the file was read-only stays read-only:
// drop it so a write after the file is fixed opens it again.
if (isSqliteReadonlyError(error)) await forgetRuntimeDb(path);
throw error;
}
}
return {
serialize: options.serialize,
getRow,
get: async (serverConfig: ServerConfig, workspaceId: string): Promise<T | undefined> => {
return (await getRow(serverConfig, workspaceId))?.value;
},
has: async (serverConfig: ServerConfig, workspaceId: string): Promise<boolean> => {
const db = await readableWorkspaceKvDb(runtimeDbPath(serverConfig), config);
return Boolean(db?.get(workspaceId));
},
set: async (serverConfig: ServerConfig, workspaceId: string, value: T, updatedAt = Date.now()): Promise<void> => {
await setSerialized(serverConfig, workspaceId, options.serialize(value), updatedAt);
},
setSerialized,
};
}
export function workspaceKvStoreCacheStatsForTests(path: string): { connectionEntries: number; tableEntries: number } {
return {
connectionEntries: dbByPath.has(path) ? 1 : 0,
tableEntries: tableDbByPath.get(path)?.size ?? 0,
};
}