@yishiguji/tokenarena 0.25.0 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +351 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -10947,6 +10947,341 @@ async function runHome(program) {
|
|
|
10947
10947
|
}
|
|
10948
10948
|
}
|
|
10949
10949
|
|
|
10950
|
+
// src/commands/muse.ts
|
|
10951
|
+
import { execFile } from "child_process";
|
|
10952
|
+
import { readFileSync as readFileSync16 } from "fs";
|
|
10953
|
+
import { promisify } from "util";
|
|
10954
|
+
|
|
10955
|
+
// src/services/muse-export.ts
|
|
10956
|
+
import { createHash as createHash8 } from "crypto";
|
|
10957
|
+
import { mkdirSync as mkdirSync4 } from "fs";
|
|
10958
|
+
import { dirname as dirname13 } from "path";
|
|
10959
|
+
var MUSE_USAGE_ROWS_QUERY = `SELECT json_build_object(
|
|
10960
|
+
'ts', u.created_at,
|
|
10961
|
+
'messageId', u.message_id,
|
|
10962
|
+
'sessionId', coalesce(nullif(a.root_session_id, ''), nullif(a.session_id, ''), u.agent_id),
|
|
10963
|
+
'agentId', u.agent_id,
|
|
10964
|
+
'model', a.model,
|
|
10965
|
+
'inputTokens', u.input_tokens,
|
|
10966
|
+
'outputTokens', u.output_tokens
|
|
10967
|
+
)::text AS line
|
|
10968
|
+
FROM agent.agent_message_token_usage u
|
|
10969
|
+
LEFT JOIN agent.agents a ON a.agent_id = u.agent_id
|
|
10970
|
+
ORDER BY u.created_at, u.agent_id, u.message_id`;
|
|
10971
|
+
var MUSE_USAGE_TOTALS_QUERY = `SELECT count(*) AS records,
|
|
10972
|
+
coalesce(sum(input_tokens), 0) AS input_tokens,
|
|
10973
|
+
coalesce(sum(output_tokens), 0) AS output_tokens,
|
|
10974
|
+
max(created_at) AS max_ts
|
|
10975
|
+
FROM agent.agent_message_token_usage`;
|
|
10976
|
+
function sha256Hex(value) {
|
|
10977
|
+
return createHash8("sha256").update(value, "utf8").digest("hex");
|
|
10978
|
+
}
|
|
10979
|
+
function tokenCount6(value) {
|
|
10980
|
+
if (typeof value !== "number") return null;
|
|
10981
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
10982
|
+
}
|
|
10983
|
+
function invalidRow(index, reason) {
|
|
10984
|
+
return new Error(`muse export: row ${index + 1} is invalid: ${reason}`);
|
|
10985
|
+
}
|
|
10986
|
+
function parseMuseRawRow(value, index) {
|
|
10987
|
+
if (typeof value !== "object" || value === null) {
|
|
10988
|
+
throw invalidRow(index, "not an object");
|
|
10989
|
+
}
|
|
10990
|
+
const raw = value;
|
|
10991
|
+
const ts = raw.ts;
|
|
10992
|
+
if (typeof ts !== "number" || !Number.isFinite(ts) || ts < MIN_TS_SECONDS || ts >= MAX_TS_SECONDS) {
|
|
10993
|
+
throw invalidRow(index, "ts is missing or outside the accepted range");
|
|
10994
|
+
}
|
|
10995
|
+
const messageId = raw.messageId;
|
|
10996
|
+
const sessionId = raw.sessionId;
|
|
10997
|
+
const agentId = raw.agentId;
|
|
10998
|
+
if (typeof messageId !== "string" || !messageId || typeof sessionId !== "string" || !sessionId || typeof agentId !== "string" || !agentId) {
|
|
10999
|
+
throw invalidRow(
|
|
11000
|
+
index,
|
|
11001
|
+
"messageId, sessionId and agentId must be non-empty strings"
|
|
11002
|
+
);
|
|
11003
|
+
}
|
|
11004
|
+
const inputTokens = tokenCount6(raw.inputTokens);
|
|
11005
|
+
const outputTokens = tokenCount6(raw.outputTokens);
|
|
11006
|
+
if (inputTokens === null || outputTokens === null) {
|
|
11007
|
+
throw invalidRow(
|
|
11008
|
+
index,
|
|
11009
|
+
"inputTokens and outputTokens must be non-negative integers"
|
|
11010
|
+
);
|
|
11011
|
+
}
|
|
11012
|
+
const model = typeof raw.model === "string" && raw.model.trim() ? raw.model.trim() : void 0;
|
|
11013
|
+
return {
|
|
11014
|
+
ts,
|
|
11015
|
+
messageId,
|
|
11016
|
+
sessionId,
|
|
11017
|
+
agentId,
|
|
11018
|
+
model,
|
|
11019
|
+
inputTokens,
|
|
11020
|
+
outputTokens
|
|
11021
|
+
};
|
|
11022
|
+
}
|
|
11023
|
+
function unwrapRowValue(value, index) {
|
|
11024
|
+
let current = value;
|
|
11025
|
+
if (typeof current === "string") {
|
|
11026
|
+
try {
|
|
11027
|
+
current = JSON.parse(current);
|
|
11028
|
+
} catch {
|
|
11029
|
+
throw invalidRow(index, "line is not valid JSON");
|
|
11030
|
+
}
|
|
11031
|
+
}
|
|
11032
|
+
if (typeof current === "object" && current !== null) {
|
|
11033
|
+
const record = current;
|
|
11034
|
+
if (typeof record.line === "string" && !("messageId" in record)) {
|
|
11035
|
+
try {
|
|
11036
|
+
return JSON.parse(record.line);
|
|
11037
|
+
} catch {
|
|
11038
|
+
throw invalidRow(index, "line is not valid JSON");
|
|
11039
|
+
}
|
|
11040
|
+
}
|
|
11041
|
+
}
|
|
11042
|
+
return current;
|
|
11043
|
+
}
|
|
11044
|
+
function envelopeError(record) {
|
|
11045
|
+
if (record.ok !== false) return null;
|
|
11046
|
+
const error = record.error;
|
|
11047
|
+
if (typeof error === "string" && error) return error;
|
|
11048
|
+
if (typeof error === "object" && error !== null) {
|
|
11049
|
+
const message = error.message;
|
|
11050
|
+
if (typeof message === "string" && message) return message;
|
|
11051
|
+
}
|
|
11052
|
+
return "the database tool reported a failed query (ok: false)";
|
|
11053
|
+
}
|
|
11054
|
+
function envelopeRows(record) {
|
|
11055
|
+
const result = record.result;
|
|
11056
|
+
if (typeof result === "object" && result !== null) {
|
|
11057
|
+
const rows = result.rows;
|
|
11058
|
+
if (Array.isArray(rows)) return rows;
|
|
11059
|
+
}
|
|
11060
|
+
if (Array.isArray(record.rows)) return record.rows;
|
|
11061
|
+
return null;
|
|
11062
|
+
}
|
|
11063
|
+
function expandInputValue(value, into) {
|
|
11064
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
11065
|
+
const record = value;
|
|
11066
|
+
const failure = envelopeError(record);
|
|
11067
|
+
if (failure) throw new Error(`muse export: ${failure}`);
|
|
11068
|
+
const rows = envelopeRows(record);
|
|
11069
|
+
if (rows) {
|
|
11070
|
+
for (const row of rows) into.push(row);
|
|
11071
|
+
return;
|
|
11072
|
+
}
|
|
11073
|
+
}
|
|
11074
|
+
into.push(value);
|
|
11075
|
+
}
|
|
11076
|
+
function documentRowValues(parsed) {
|
|
11077
|
+
if (Array.isArray(parsed)) {
|
|
11078
|
+
const values = [];
|
|
11079
|
+
for (const element of parsed) expandInputValue(element, values);
|
|
11080
|
+
return values;
|
|
11081
|
+
}
|
|
11082
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
11083
|
+
const values = [];
|
|
11084
|
+
expandInputValue(parsed, values);
|
|
11085
|
+
return values;
|
|
11086
|
+
}
|
|
11087
|
+
return null;
|
|
11088
|
+
}
|
|
11089
|
+
function parseMuseRawRows(input2) {
|
|
11090
|
+
const trimmed = input2.trim();
|
|
11091
|
+
if (!trimmed) {
|
|
11092
|
+
throw new Error("muse export: no input \u2014 expected the rows-query result");
|
|
11093
|
+
}
|
|
11094
|
+
let values = null;
|
|
11095
|
+
let document;
|
|
11096
|
+
let isDocument = true;
|
|
11097
|
+
try {
|
|
11098
|
+
document = JSON.parse(trimmed);
|
|
11099
|
+
} catch {
|
|
11100
|
+
isDocument = false;
|
|
11101
|
+
}
|
|
11102
|
+
if (isDocument) {
|
|
11103
|
+
values = documentRowValues(document);
|
|
11104
|
+
}
|
|
11105
|
+
if (values === null) {
|
|
11106
|
+
values = [];
|
|
11107
|
+
let lineNumber = 0;
|
|
11108
|
+
for (const line of trimmed.split("\n")) {
|
|
11109
|
+
lineNumber += 1;
|
|
11110
|
+
const text2 = line.trim();
|
|
11111
|
+
if (!text2) continue;
|
|
11112
|
+
let parsedLine;
|
|
11113
|
+
try {
|
|
11114
|
+
parsedLine = JSON.parse(text2);
|
|
11115
|
+
} catch {
|
|
11116
|
+
throw new Error(
|
|
11117
|
+
`muse export: input line ${lineNumber} is not valid JSON`
|
|
11118
|
+
);
|
|
11119
|
+
}
|
|
11120
|
+
expandInputValue(parsedLine, values);
|
|
11121
|
+
}
|
|
11122
|
+
}
|
|
11123
|
+
if (values.length === 0) {
|
|
11124
|
+
throw new Error("muse export: input contains no rows");
|
|
11125
|
+
}
|
|
11126
|
+
return values.map(
|
|
11127
|
+
(value, index) => parseMuseRawRow(unwrapRowValue(value, index), index)
|
|
11128
|
+
);
|
|
11129
|
+
}
|
|
11130
|
+
function transformMuseRows(rows) {
|
|
11131
|
+
const seen = /* @__PURE__ */ new Set();
|
|
11132
|
+
const records = [];
|
|
11133
|
+
for (const row of rows) {
|
|
11134
|
+
const key = JSON.stringify([row.sessionId, row.messageId]);
|
|
11135
|
+
if (seen.has(key)) continue;
|
|
11136
|
+
seen.add(key);
|
|
11137
|
+
records.push({
|
|
11138
|
+
v: 1,
|
|
11139
|
+
ts: row.ts,
|
|
11140
|
+
messageId: sha256Hex(row.messageId),
|
|
11141
|
+
sessionId: sha256Hex(row.sessionId),
|
|
11142
|
+
agentId: sha256Hex(row.agentId),
|
|
11143
|
+
model: normalizeModel(row.model),
|
|
11144
|
+
inputTokens: row.inputTokens,
|
|
11145
|
+
outputTokens: row.outputTokens
|
|
11146
|
+
});
|
|
11147
|
+
}
|
|
11148
|
+
records.sort((a, b) => a.ts - b.ts);
|
|
11149
|
+
return records;
|
|
11150
|
+
}
|
|
11151
|
+
function serializeMuseExport(records) {
|
|
11152
|
+
if (records.length === 0) return "";
|
|
11153
|
+
return `${records.map((record) => JSON.stringify(record)).join("\n")}
|
|
11154
|
+
`;
|
|
11155
|
+
}
|
|
11156
|
+
function summarizeMuseExport(records) {
|
|
11157
|
+
let inputTokens = 0;
|
|
11158
|
+
let outputTokens = 0;
|
|
11159
|
+
for (const record of records) {
|
|
11160
|
+
inputTokens += record.inputTokens;
|
|
11161
|
+
outputTokens += record.outputTokens;
|
|
11162
|
+
}
|
|
11163
|
+
return { records: records.length, inputTokens, outputTokens };
|
|
11164
|
+
}
|
|
11165
|
+
function writeMuseExportFile(records, targetPath) {
|
|
11166
|
+
mkdirSync4(dirname13(targetPath), { recursive: true, mode: 448 });
|
|
11167
|
+
writePrivateFile(targetPath, serializeMuseExport(records));
|
|
11168
|
+
}
|
|
11169
|
+
|
|
11170
|
+
// src/commands/muse.ts
|
|
11171
|
+
var execFileAsync = promisify(execFile);
|
|
11172
|
+
var PSQL_TIMEOUT_MS = 12e4;
|
|
11173
|
+
var PSQL_MAX_BUFFER = 64 * 1024 * 1024;
|
|
11174
|
+
var PSQL_NOT_FOUND_MESSAGE = "muse export: psql not found \u2014 run `tokenarena muse query` through the Muse host's database tool and pipe the result to `tokenarena muse export` instead";
|
|
11175
|
+
async function readStdinText() {
|
|
11176
|
+
const chunks = [];
|
|
11177
|
+
for await (const chunk of process.stdin) {
|
|
11178
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
11179
|
+
}
|
|
11180
|
+
return Buffer.concat(chunks).toString("utf-8");
|
|
11181
|
+
}
|
|
11182
|
+
var defaultExecFileAsync = async (file, args, options) => {
|
|
11183
|
+
const { stdout, stderr } = await execFileAsync(file, [...args], options);
|
|
11184
|
+
return { stdout: String(stdout), stderr: String(stderr) };
|
|
11185
|
+
};
|
|
11186
|
+
function createPsqlRunner(deps) {
|
|
11187
|
+
return async (query) => {
|
|
11188
|
+
let file = null;
|
|
11189
|
+
for (const candidate of ["psql", "psql.exe"]) {
|
|
11190
|
+
file = deps.resolvePath(candidate);
|
|
11191
|
+
if (file) break;
|
|
11192
|
+
}
|
|
11193
|
+
if (!file) throw new Error(PSQL_NOT_FOUND_MESSAGE);
|
|
11194
|
+
try {
|
|
11195
|
+
const { stdout } = await deps.execFile(
|
|
11196
|
+
file,
|
|
11197
|
+
["-X", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-c", query],
|
|
11198
|
+
{
|
|
11199
|
+
env: process.env,
|
|
11200
|
+
maxBuffer: PSQL_MAX_BUFFER,
|
|
11201
|
+
timeout: PSQL_TIMEOUT_MS,
|
|
11202
|
+
windowsHide: true
|
|
11203
|
+
}
|
|
11204
|
+
);
|
|
11205
|
+
return stdout;
|
|
11206
|
+
} catch (error) {
|
|
11207
|
+
const code = error.code;
|
|
11208
|
+
if (code === "ENOENT") throw new Error(PSQL_NOT_FOUND_MESSAGE);
|
|
11209
|
+
const stderr = error.stderr;
|
|
11210
|
+
const detail = typeof stderr === "string" && stderr.trim() ? stderr.trim() : error instanceof Error ? error.message : String(error);
|
|
11211
|
+
throw new Error(`muse export: psql failed: ${detail}`);
|
|
11212
|
+
}
|
|
11213
|
+
};
|
|
11214
|
+
}
|
|
11215
|
+
var defaultMuseCommandDeps = {
|
|
11216
|
+
readStdin: readStdinText,
|
|
11217
|
+
readFile: (path) => readFileSync16(path, "utf-8"),
|
|
11218
|
+
runPsql: createPsqlRunner({
|
|
11219
|
+
execFile: defaultExecFileAsync,
|
|
11220
|
+
resolvePath: resolveCommandPath
|
|
11221
|
+
}),
|
|
11222
|
+
writeExport: writeMuseExportFile,
|
|
11223
|
+
stdinIsTTY: () => Boolean(process.stdin.isTTY),
|
|
11224
|
+
print: (text2) => process.stdout.write(text2),
|
|
11225
|
+
log: (message) => logger.info(message)
|
|
11226
|
+
};
|
|
11227
|
+
async function runMuseQueryCommand(opts = {}, deps = defaultMuseCommandDeps) {
|
|
11228
|
+
if (opts.totals) {
|
|
11229
|
+
deps.print(
|
|
11230
|
+
[
|
|
11231
|
+
"-- Muse usage totals: the export's record count and token sums must match.",
|
|
11232
|
+
`${MUSE_USAGE_TOTALS_QUERY};`,
|
|
11233
|
+
""
|
|
11234
|
+
].join("\n")
|
|
11235
|
+
);
|
|
11236
|
+
return;
|
|
11237
|
+
}
|
|
11238
|
+
deps.print(
|
|
11239
|
+
[
|
|
11240
|
+
"-- Muse usage rows: one JSON object per message, in export order.",
|
|
11241
|
+
`${MUSE_USAGE_ROWS_QUERY};`,
|
|
11242
|
+
""
|
|
11243
|
+
].join("\n")
|
|
11244
|
+
);
|
|
11245
|
+
}
|
|
11246
|
+
async function runMuseExportCommand(opts = {}, deps = defaultMuseCommandDeps) {
|
|
11247
|
+
if (opts.db && opts.input) {
|
|
11248
|
+
throw new Error("muse export: --db and --input cannot be used together");
|
|
11249
|
+
}
|
|
11250
|
+
let input2;
|
|
11251
|
+
if (opts.db) {
|
|
11252
|
+
input2 = await deps.runPsql(MUSE_USAGE_ROWS_QUERY);
|
|
11253
|
+
if (!input2.trim()) {
|
|
11254
|
+
throw new Error(
|
|
11255
|
+
"muse export: the database query returned no rows \u2014 check the libpq environment (PGHOST, PGPORT, PGUSER, PGDATABASE) and that the Muse database is reachable"
|
|
11256
|
+
);
|
|
11257
|
+
}
|
|
11258
|
+
} else if (opts.input) {
|
|
11259
|
+
try {
|
|
11260
|
+
input2 = deps.readFile(opts.input);
|
|
11261
|
+
} catch (error) {
|
|
11262
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
11263
|
+
throw new Error(
|
|
11264
|
+
`muse export: cannot read input file ${opts.input}: ${detail}`
|
|
11265
|
+
);
|
|
11266
|
+
}
|
|
11267
|
+
} else {
|
|
11268
|
+
if (deps.stdinIsTTY()) {
|
|
11269
|
+
throw new Error(
|
|
11270
|
+
"muse export: no input \u2014 pipe the `tokenarena muse query` result on stdin, pass --input <file>, or use --db"
|
|
11271
|
+
);
|
|
11272
|
+
}
|
|
11273
|
+
input2 = await deps.readStdin();
|
|
11274
|
+
}
|
|
11275
|
+
const records = transformMuseRows(parseMuseRawRows(input2));
|
|
11276
|
+
const targetPath = opts.output ?? getMuseExportPath();
|
|
11277
|
+
deps.writeExport(records, targetPath);
|
|
11278
|
+
const summary = { ...summarizeMuseExport(records), targetPath };
|
|
11279
|
+
deps.log(
|
|
11280
|
+
`Muse usage export written: ${summary.records} records, ${summary.inputTokens} input / ${summary.outputTokens} output tokens \u2192 ${targetPath}`
|
|
11281
|
+
);
|
|
11282
|
+
return summary;
|
|
11283
|
+
}
|
|
11284
|
+
|
|
10950
11285
|
// src/commands/service.ts
|
|
10951
11286
|
function printUsage(backendName) {
|
|
10952
11287
|
logger.info(formatHeader("TokenArena \u540E\u53F0\u670D\u52A1\u7BA1\u7406"));
|
|
@@ -11051,6 +11386,22 @@ function createCli() {
|
|
|
11051
11386
|
)
|
|
11052
11387
|
);
|
|
11053
11388
|
});
|
|
11389
|
+
const muse = program.command("muse").description("Build the Muse usage export from the runtime database");
|
|
11390
|
+
muse.command("query").description("Print the canonical SQL that reads Muse usage").option("--totals", "Print the totals cross-check query instead").action(async (opts) => {
|
|
11391
|
+
await runMuseQueryCommand(opts);
|
|
11392
|
+
});
|
|
11393
|
+
muse.command("export").description("Transform runtime database rows into the usage export file").option(
|
|
11394
|
+
"--input <file>",
|
|
11395
|
+
"Read database rows (JSON or JSONL) from a file instead of stdin"
|
|
11396
|
+
).option(
|
|
11397
|
+
"--output <file>",
|
|
11398
|
+
"Write the export to this file instead of the default export path"
|
|
11399
|
+
).option(
|
|
11400
|
+
"--db",
|
|
11401
|
+
"Run the query directly with psql (libpq environment variables)"
|
|
11402
|
+
).action(async (opts) => {
|
|
11403
|
+
await runMuseExportCommand(opts);
|
|
11404
|
+
});
|
|
11054
11405
|
program.command("uninstall").description("Remove all local configuration and data").action(async () => {
|
|
11055
11406
|
await runUninstall();
|
|
11056
11407
|
});
|