162 lines
5.2 KiB
TypeScript
162 lines
5.2 KiB
TypeScript
import { spawn } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
|
|
export interface ThtConfig {
|
|
thtBin: string;
|
|
harnessDir: string;
|
|
configPath: string;
|
|
dataRoot?: string;
|
|
}
|
|
|
|
export interface SessionRow {
|
|
id: string;
|
|
status: string;
|
|
question: string;
|
|
summary: string | null;
|
|
created_at: string;
|
|
updated_at: string | null;
|
|
author: string | null;
|
|
}
|
|
|
|
export interface SessionDocument {
|
|
phase: string;
|
|
key: string;
|
|
title: string;
|
|
format: string;
|
|
content: string;
|
|
}
|
|
|
|
export interface OllamaEnsureResult {
|
|
ok: boolean;
|
|
stage?: string;
|
|
error?: string;
|
|
server?: string;
|
|
model?: string;
|
|
model_name?: string;
|
|
}
|
|
|
|
export class ThtRunner {
|
|
constructor(private cfg: ThtConfig) {}
|
|
|
|
/**
|
|
* Resolve the `-c <config>` args. If `workspace` is given AND a matching
|
|
* `workspaces/<workspace>.yaml` exists under harnessDir, select it; otherwise
|
|
* fall back to the default configPath.
|
|
*/
|
|
private configArg(workspace?: string): string[] {
|
|
if (workspace && existsSync(join(this.cfg.harnessDir, "workspaces", `${workspace}.yaml`))) {
|
|
return ["-c", `workspaces/${workspace}.yaml`];
|
|
}
|
|
return ["-c", this.cfg.configPath];
|
|
}
|
|
|
|
/**
|
|
* Build the full argv for a `tht` invocation. `--config`/`-c` is a PER-COMMAND
|
|
* option in the `tht` CLI (there is NO global `-c`), so it MUST be appended
|
|
* AFTER the subcommand + its flags, never prepended.
|
|
*/
|
|
buildArgv(args: string[], workspace?: string): string[] {
|
|
return [...args, ...this.configArg(workspace)];
|
|
}
|
|
|
|
run(args: string[], workspace?: string): Promise<{ code: number; stdout: string; stderr: string }> {
|
|
return new Promise((resolve) => {
|
|
const env: NodeJS.ProcessEnv = { ...process.env };
|
|
delete env.THT_DATA_ROOT;
|
|
if (this.cfg.dataRoot !== undefined) env.THT_DATA_ROOT = this.cfg.dataRoot;
|
|
const ch = spawn(this.cfg.thtBin, this.buildArgv(args, workspace), {
|
|
cwd: this.cfg.harnessDir,
|
|
env,
|
|
});
|
|
let stdout = "";
|
|
let stderr = "";
|
|
ch.stdout.on("data", (d: Buffer) => (stdout += d));
|
|
ch.stderr.on("data", (d: Buffer) => (stderr += d));
|
|
ch.on("close", (code) => resolve({ code: code ?? 0, stdout, stderr }));
|
|
});
|
|
}
|
|
|
|
private async json<T>(args: string[], workspace?: string): Promise<T> {
|
|
const { code, stdout, stderr } = await this.run(args, workspace);
|
|
if (code !== 0) throw new Error(`tht ${args.join(" ")} exit ${code}: ${stderr.trim()}`);
|
|
return JSON.parse(stdout) as T;
|
|
}
|
|
|
|
private async ok(args: string[]): Promise<void> {
|
|
const { code, stderr } = await this.run(args);
|
|
if (code !== 0) throw new Error(`tht ${args.join(" ")} exit ${code}: ${stderr.trim()}`);
|
|
}
|
|
|
|
async sessionNew(o: {
|
|
question: string;
|
|
provider?: string;
|
|
model?: string;
|
|
thinking?: string;
|
|
name?: string;
|
|
workspace?: string;
|
|
}) {
|
|
const a = ["session", "new", o.question];
|
|
for (const [f, v] of [
|
|
["--provider", o.provider],
|
|
["--model", o.model],
|
|
["--thinking", o.thinking],
|
|
["--name", o.name],
|
|
] as const) {
|
|
if (v) a.push(f, v);
|
|
}
|
|
a.push("--json");
|
|
return this.json<{ id: string }>(a, o.workspace);
|
|
}
|
|
|
|
sessionList() {
|
|
return this.json<SessionRow[]>(["session", "list", "--json"]);
|
|
}
|
|
|
|
sessionShow(id: string) {
|
|
return this.json<unknown>(["session", "show", id, "--json"]);
|
|
}
|
|
|
|
sqlPreview(id: string, p: { limit?: number; offset?: number }) {
|
|
// No positional FILE: the harness resolves sql_final.sql from the session
|
|
// via _session_sql_file(cfg, session_id), which respects the workspace path.
|
|
const a = ["sql", "preview", "--session", id, "--json"];
|
|
if (p.limit != null) a.push("--limit", String(p.limit));
|
|
if (p.offset != null) a.push("--offset", String(p.offset));
|
|
return this.json<{
|
|
columns: string[];
|
|
rows: unknown[][];
|
|
execution_ms: number;
|
|
truncated: boolean;
|
|
}>(a);
|
|
}
|
|
|
|
async sqlExport(id: string) {
|
|
const { code, stdout, stderr } = await this.run(["sql", "export", "--session", id]);
|
|
if (code !== 0) throw new Error(`tht sql export exit ${code}: ${stderr.trim()}`);
|
|
return { path: stdout.trim() };
|
|
}
|
|
|
|
setName(id: string, name: string) { return this.ok(["session", "set-name", id, "--name", name]); }
|
|
setGroup(id: string, group: string) { return this.ok(["session", "set-group", id, "--group", group]); }
|
|
archive(id: string) { return this.ok(["session", "archive", id]); }
|
|
unarchive(id: string) { return this.ok(["session", "unarchive", id]); }
|
|
deleteSession(id: string) { return this.ok(["session", "delete", id]); }
|
|
documents(id: string) { return this.json<SessionDocument[]>(["session", "documents", id, "--json"]); }
|
|
|
|
async ollamaEnsure(workspace: string, timeoutSec: number): Promise<OllamaEnsureResult> {
|
|
const { code, stdout, stderr } = await this.run(
|
|
["ollama", "ensure", "--json", "--timeout", String(timeoutSec)],
|
|
workspace,
|
|
);
|
|
let parsed: Partial<OllamaEnsureResult> = {};
|
|
try { parsed = JSON.parse(stdout.trim() || "{}"); } catch { /* leave {} */ }
|
|
if (code === 0) return { ok: true, ...parsed };
|
|
return {
|
|
ok: false,
|
|
stage: parsed.stage,
|
|
error: parsed.error ?? (stderr.trim() || `tht ollama ensure exit ${code}`),
|
|
};
|
|
}
|
|
}
|