kestrel.markets
Version:
A typed, token-efficient language + runtime for agentic trading: agents author bounded plans, the runtime fires them at the tick. CLI + typed library + MCP server.
108 lines (106 loc) • 4.36 kB
JavaScript
// src/ledger/hosted.ts
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
var HOSTED_STORE_BASENAME = "hosted-runs.jsonl";
var LEGACY_CWD_HOSTED_STORE = `data/${HOSTED_STORE_BASENAME}`;
function defaultHostedStorePath(env = process.env) {
const home = env.KESTREL_HOME ?? homedir();
return join(home, ".kestrel", HOSTED_STORE_BASENAME);
}
function appendHostedRun(storePath, row) {
const dir = dirname(storePath);
if (dir.length > 0 && !existsSync(dir))
mkdirSync(dir, { recursive: true });
appendFileSync(storePath, JSON.stringify(row) + `
`);
}
function readHostedRuns(storePath) {
return collapseHostedRuns(readRawHostedRows(storePath));
}
function readHostedRunsMerged(opts) {
const seen = new Set;
const rows = [];
for (const path of [...opts.fallbacks ?? [], opts.home]) {
if (seen.has(path))
continue;
seen.add(path);
rows.push(...readRawHostedRows(path));
}
return collapseHostedRuns(rows);
}
function readRawHostedRows(storePath) {
if (!existsSync(storePath))
return [];
const text = readFileSync(storePath, "utf8");
const out = [];
const lines = text.split(`
`);
for (let i = 0;i < lines.length; i += 1) {
const line = lines[i].trim();
if (line.length === 0)
continue;
let parsed;
try {
parsed = JSON.parse(line);
} catch (e) {
throw new Error(`ledger/hosted: ${JSON.stringify(storePath)} line ${i + 1} is not valid JSON — refusing to read a corrupt hosted store (fail-closed): ${e instanceof Error ? e.message : String(e)}`);
}
const row = asHostedRunRow(parsed);
if (row === null)
throw new Error(`ledger/hosted: ${JSON.stringify(storePath)} line ${i + 1} is not a hosted-run row — refusing to read a corrupt hosted store (fail-closed)`);
out.push(row);
}
return out;
}
function collapseHostedRuns(rows) {
const byOp = new Map;
for (const row of rows)
byOp.set(row.operation_id, row);
return [...byOp.values()].sort((a, b) => a.issued_at < b.issued_at ? 1 : a.issued_at > b.issued_at ? -1 : a.operation_id < b.operation_id ? -1 : 1);
}
function isPlanDigest(v) {
return typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
}
function asHostedRunRow(v) {
if (typeof v !== "object" || v === null || Array.isArray(v))
return null;
const r = v;
if (r["source"] !== "hosted")
return null;
const str = (k) => typeof r[k] === "string";
const num = (k) => typeof r[k] === "number" && Number.isFinite(r[k]);
if (!(str("slug") && str("requested_slug") && str("operation_id") && str("grade_artifact_id")))
return null;
if (!(str("bus_artifact_id") && str("manifest_artifact_id") && str("proof_url") && str("issued_at")))
return null;
if (!(num("order_count") && num("fill_count") && num("realized_pnl")))
return null;
const strategyRaw = r["strategy"];
const strategy = typeof strategyRaw === "string" && strategyRaw !== "" ? strategyRaw : undefined;
const strategyDigest = isPlanDigest(r["strategy_digest"]) ? r["strategy_digest"] : undefined;
const rawCopyToken = r["copy_token"];
if (rawCopyToken !== undefined && typeof rawCopyToken !== "string")
return null;
const rawNeverFired = r["never_fired_reason"];
const neverFiredReason = typeof rawNeverFired === "string" && rawNeverFired.trim().length > 0 ? rawNeverFired : undefined;
return {
source: "hosted",
slug: r["slug"],
requested_slug: r["requested_slug"],
operation_id: r["operation_id"],
grade_artifact_id: r["grade_artifact_id"],
bus_artifact_id: r["bus_artifact_id"],
manifest_artifact_id: r["manifest_artifact_id"],
order_count: r["order_count"],
fill_count: r["fill_count"],
realized_pnl: r["realized_pnl"],
proof_url: r["proof_url"],
issued_at: r["issued_at"],
...strategy !== undefined ? { strategy } : {},
...strategyDigest !== undefined ? { strategy_digest: strategyDigest } : {},
...typeof rawCopyToken === "string" && rawCopyToken.length > 0 ? { copy_token: rawCopyToken } : {},
...neverFiredReason !== undefined ? { never_fired_reason: neverFiredReason } : {}
};
}
export { HOSTED_STORE_BASENAME, LEGACY_CWD_HOSTED_STORE, defaultHostedStorePath, appendHostedRun, readHostedRuns, readHostedRunsMerged, isPlanDigest };