@tangle-network/harness-sessions 1.0.5 → 1.0.7
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/builder.d.ts +0 -24
- package/dist/builder.js +0 -28
- package/dist/capture.d.ts +0 -11
- package/dist/capture.js +3 -21
- package/dist/catalog.d.ts +16 -22
- package/dist/catalog.js +8 -26
- package/dist/cli.js +0 -8
- package/dist/formats/claude-code.d.ts +0 -1
- package/dist/formats/claude-code.js +0 -9
- package/dist/formats/claude-records.d.ts +0 -12
- package/dist/formats/claude-records.js +0 -10
- package/dist/formats/codex.js +0 -34
- package/dist/formats/factory.js +0 -3
- package/dist/formats/fold.d.ts +0 -5
- package/dist/formats/grok.js +12 -3
- package/dist/formats/head.d.ts +0 -7
- package/dist/formats/head.js +0 -10
- package/dist/formats/hermes.d.ts +3 -0
- package/dist/formats/hermes.js +93 -0
- package/dist/formats/kimi.d.ts +0 -1
- package/dist/formats/kimi.js +0 -6
- package/dist/formats/nanoclaw.d.ts +3 -0
- package/dist/formats/nanoclaw.js +65 -0
- package/dist/formats/openclaw.d.ts +3 -0
- package/dist/formats/openclaw.js +102 -0
- package/dist/formats/opencode.d.ts +0 -1
- package/dist/formats/opencode.js +0 -6
- package/dist/formats/pi.d.ts +1 -1
- package/dist/formats/pi.js +3 -9
- package/dist/formats/prime.d.ts +2 -0
- package/dist/formats/prime.js +35 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +4 -0
- package/dist/input.d.ts +0 -10
- package/dist/input.js +0 -2
- package/dist/projections/chat.d.ts +0 -8
- package/dist/projections/chat.js +0 -5
- package/dist/projections/otlp.d.ts +0 -6
- package/dist/projections/otlp.js +0 -5
- package/dist/projections/turns.d.ts +0 -18
- package/dist/projections/turns.js +0 -7
- package/dist/registry.d.ts +0 -5
- package/dist/registry.js +5 -6
- package/dist/schema.d.ts +0 -39
- package/dist/source.d.ts +0 -11
- package/dist/source.js +0 -19
- package/dist/stores.d.ts +0 -10
- package/dist/stores.js +0 -11
- package/package.json +1 -1
package/dist/formats/codex.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { isRecord } from '@tangle-network/agent-core';
|
|
2
|
-
/** Codex rollout jsonl. turn_context is the configured model. total_token_usage is the session total. */
|
|
3
2
|
import { basename } from 'node:path';
|
|
4
3
|
import { SessionBuilder, argumentsOf, count, sessionError, str, textOf, usageOrNull, } from '../builder.js';
|
|
5
4
|
import { fileRecords, isMissing } from '../source.js';
|
|
@@ -12,7 +11,6 @@ const FORMAT = 'codex.rollout-jsonl';
|
|
|
12
11
|
const STORE = STORES[FORMAT];
|
|
13
12
|
const HARNESS = 'codex';
|
|
14
13
|
const ID_IN_NAME = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/u;
|
|
15
|
-
/** Codex counts cached tokens inside `input_tokens`; the normalized input excludes them. */
|
|
16
14
|
function usageOf(value) {
|
|
17
15
|
if (!isRecord(value))
|
|
18
16
|
return null;
|
|
@@ -39,7 +37,6 @@ function addTotals(a, b) {
|
|
|
39
37
|
const sum = (x, y) => (x === null && y === null ? null : (x ?? 0) + (y ?? 0));
|
|
40
38
|
return { input: sum(a.input, b.input), output: sum(a.output, b.output), reasoning: sum(a.reasoning, b.reasoning), cacheRead: sum(a.cacheRead, b.cacheRead), cacheWrite: sum(a.cacheWrite, b.cacheWrite) };
|
|
41
39
|
}
|
|
42
|
-
// Text the harness puts in a user-role message: environment context, instructions, shell output.
|
|
43
40
|
const INJECTED_USER_TEXT = /^\s*(?:<[a-z_]+(?:\s[^>]*)?>|# AGENTS\.md instructions)/u;
|
|
44
41
|
function contentParts(content) {
|
|
45
42
|
const parts = [];
|
|
@@ -57,16 +54,12 @@ function contentParts(content) {
|
|
|
57
54
|
}
|
|
58
55
|
return parts;
|
|
59
56
|
}
|
|
60
|
-
// `exec_command` and `write_stdin` answer with a text header (`Chunk ID`, `Wall time`, then
|
|
61
|
-
// `Process exited with code N` once the process is done) before `Output:`; a still-running process
|
|
62
|
-
// says `Process running with session ID` instead and has no status yet.
|
|
63
57
|
const PROCESS_EXIT = /^Process exited with code (-?\d+)\s*$/mu;
|
|
64
58
|
function processFailed(text) {
|
|
65
59
|
const header = text.split(/^Output:/mu, 1)[0] ?? '';
|
|
66
60
|
const match = PROCESS_EXIT.exec(header);
|
|
67
61
|
return match !== null && Number(match[1]) !== 0;
|
|
68
62
|
}
|
|
69
|
-
/** A nonzero numeric `exit_code` anywhere in a parsed JSON value (code-mode tool results nest it). */
|
|
70
63
|
function jsonExitFailed(value, depth = 0) {
|
|
71
64
|
if (depth > 4)
|
|
72
65
|
return false;
|
|
@@ -78,10 +71,6 @@ function jsonExitFailed(value, depth = 0) {
|
|
|
78
71
|
return true;
|
|
79
72
|
return Object.values(value).some((v) => jsonExitFailed(v, depth + 1));
|
|
80
73
|
}
|
|
81
|
-
/**
|
|
82
|
-
* Code mode runs JavaScript in an `exec` call; its `tools.exec_command(...)` results are printed
|
|
83
|
-
* as JSON items carrying `exit_code`. The first item is `Script failed` when the script threw.
|
|
84
|
-
*/
|
|
85
74
|
function codeModeFailed(output) {
|
|
86
75
|
if (!Array.isArray(output))
|
|
87
76
|
return false;
|
|
@@ -126,9 +115,6 @@ export function createFold(ref, mode, stats) {
|
|
|
126
115
|
let aborted = null;
|
|
127
116
|
let sawMeta = false;
|
|
128
117
|
let compacted = 0;
|
|
129
|
-
// A forked rollout replays the parent's history after the parent's own session_meta; that
|
|
130
|
-
// history is copied context, not this session's turns. It ends at this session's first turn,
|
|
131
|
-
// whose (time-ordered, UUIDv7) turn id sorts at or after the session id.
|
|
132
118
|
let forked = false;
|
|
133
119
|
let inherited = false;
|
|
134
120
|
let inheritedRecords = 0;
|
|
@@ -200,7 +186,6 @@ export function createFold(ref, mode, stats) {
|
|
|
200
186
|
case 'response_item': {
|
|
201
187
|
const kind = str(payload.type) ?? '';
|
|
202
188
|
if (kind === 'agent_message') {
|
|
203
|
-
// A message from another agent of the same run (a task or a reply); input to this thread.
|
|
204
189
|
open = null;
|
|
205
190
|
builder.message({ id: str(payload.id) ?? `${builder.nativeSessionId}:${stats.line}`, role: 'user', actor: 'subagent-spawn', at, modelCallId: null, parts: contentParts(payload.content) });
|
|
206
191
|
}
|
|
@@ -235,7 +220,6 @@ export function createFold(ref, mode, stats) {
|
|
|
235
220
|
assistantMessage(at, call, [{ type: 'tool-call', toolCallId: callId }]);
|
|
236
221
|
tools.set(callId, { name, input: typeof raw === 'string' ? raw : '' });
|
|
237
222
|
builder.toolCall({ id: callId, name, ...argumentsOf(raw), at, messageId: openMessage });
|
|
238
|
-
// A web search is answered inside the response; there is no output item.
|
|
239
223
|
if (kind === 'web_search_call')
|
|
240
224
|
builder.toolResult(callId, { output: payload.action ?? null, text: null, isError: payload.status === 'failed', at, messageId: openMessage });
|
|
241
225
|
}
|
|
@@ -251,9 +235,6 @@ export function createFold(ref, mode, stats) {
|
|
|
251
235
|
case 'event_msg': {
|
|
252
236
|
const kind = str(payload.type);
|
|
253
237
|
if (kind === 'item_completed') {
|
|
254
|
-
// Items of this thread repeat its response items. Items of another thread are a child
|
|
255
|
-
// thread's activity (a review or a sub-agent) logged in this rollout; that thread is its
|
|
256
|
-
// own session.
|
|
257
238
|
const thread = str(payload.thread_id);
|
|
258
239
|
if (thread && thread !== builder.nativeSessionId && !foreignThreads.has(thread)) {
|
|
259
240
|
foreignThreads.add(thread);
|
|
@@ -265,13 +246,10 @@ export function createFold(ref, mode, stats) {
|
|
|
265
246
|
if (info === null)
|
|
266
247
|
break;
|
|
267
248
|
const totalSignature = signature(info.total_token_usage);
|
|
268
|
-
// Codex repeats a token_count without a new response (rate-limit refreshes); a
|
|
269
|
-
// response is counted once, when the cumulative counter moves.
|
|
270
249
|
if (totalSignature !== '' && totalSignature === lastTotalSignature)
|
|
271
250
|
break;
|
|
272
251
|
if (isRecord(info.total_token_usage)) {
|
|
273
252
|
const raw = info.total_token_usage;
|
|
274
|
-
// A resumed process restarts the counter; bank what the previous process reported.
|
|
275
253
|
if (lastTotalRaw && count(raw.total_tokens) !== null && count(lastTotalRaw.total_tokens) !== null && raw.total_tokens < lastTotalRaw.total_tokens) {
|
|
276
254
|
committedTotal = addTotals(committedTotal, lastTotal);
|
|
277
255
|
}
|
|
@@ -293,7 +271,6 @@ export function createFold(ref, mode, stats) {
|
|
|
293
271
|
open = null;
|
|
294
272
|
}
|
|
295
273
|
else if (kind === 'stream_error') {
|
|
296
|
-
// A dropped stream that Codex retries. It is a model request that returned no answer.
|
|
297
274
|
calls += 1;
|
|
298
275
|
builder.modelCall({ id: `${builder.nativeSessionId}:response:${calls}`, at, provider, servedModel: model, requestedModel: model, usage: null, costUsd: null, stopReason: null, error: sessionError('stream_error', str(payload.message) ?? 'stream error', at, httpStatusOf(payload)) });
|
|
299
276
|
}
|
|
@@ -308,8 +285,6 @@ export function createFold(ref, mode, stats) {
|
|
|
308
285
|
else if (kind === 'task_complete') {
|
|
309
286
|
aborted = null;
|
|
310
287
|
open = null;
|
|
311
|
-
// Codex 0.145 records a turn that ended on a failed request only here: the request that
|
|
312
|
-
// failed returned no answer, so it is a model call with that error and no served model.
|
|
313
288
|
if (isRecord(payload.error)) {
|
|
314
289
|
const failure = payload.error;
|
|
315
290
|
calls += 1;
|
|
@@ -357,7 +332,6 @@ function httpStatusOf(payload) {
|
|
|
357
332
|
}
|
|
358
333
|
const ROLLOUT = storeGlob(CODEX_HOME_RULE.rollout);
|
|
359
334
|
const UUID_V7 = /^([0-9a-f]{8})-([0-9a-f]{4})-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu;
|
|
360
|
-
/** Every rollout file, live and archived, in every Codex home under `home`. */
|
|
361
335
|
async function rollouts(home) {
|
|
362
336
|
const files = [];
|
|
363
337
|
for (const codexHome of await codexHomes(home)) {
|
|
@@ -370,12 +344,10 @@ async function rollouts(home) {
|
|
|
370
344
|
}
|
|
371
345
|
return files;
|
|
372
346
|
}
|
|
373
|
-
/** A UUIDv7's creation time: a session's rollout is written at or after its thread id is made. */
|
|
374
347
|
function uuidV7Ms(id) {
|
|
375
348
|
const match = UUID_V7.exec(id);
|
|
376
349
|
return match ? Number.parseInt(`${match[1]}${match[2]}`, 16) : 0;
|
|
377
350
|
}
|
|
378
|
-
/** A ref for each of `files` that passes the filters, from its `session_meta`, with the file's bytes. */
|
|
379
351
|
async function refsOf(files, home, opts) {
|
|
380
352
|
const found = await mapLimit(files, LOCATE_READS, async (path) => {
|
|
381
353
|
let info;
|
|
@@ -413,12 +385,6 @@ async function refsOf(files, home, opts) {
|
|
|
413
385
|
});
|
|
414
386
|
return found.filter((entry) => entry !== null);
|
|
415
387
|
}
|
|
416
|
-
/**
|
|
417
|
-
* Sessions in every Codex home under `home`. A lookup by id takes the rollout named for it; when no
|
|
418
|
-
* name carries the id, it reads the `session_meta` of each rollout written since the id was made.
|
|
419
|
-
* A session copied into several homes (`acct move`) is one ref, its largest copy, which holds
|
|
420
|
-
* every record.
|
|
421
|
-
*/
|
|
422
388
|
async function locate(home, opts) {
|
|
423
389
|
const files = await rollouts(home);
|
|
424
390
|
const id = opts.nativeSessionId;
|
package/dist/formats/factory.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { isRecord } from '@tangle-network/agent-core';
|
|
2
|
-
/** Factory Droid sessions: jsonl transcript plus a sibling settings file (model and token totals). */
|
|
3
2
|
import { readFile } from 'node:fs/promises';
|
|
4
3
|
import { basename, join } from 'node:path';
|
|
5
4
|
import { SessionBuilder, count, str, textOf, usageOrNull } from '../builder.js';
|
|
@@ -78,7 +77,6 @@ export function createFold(ref, mode, stats, settings = { model: null, usage: nu
|
|
|
78
77
|
};
|
|
79
78
|
const finish = () => {
|
|
80
79
|
builder.source(stats);
|
|
81
|
-
// Factory records only the session's token totals, in its settings file.
|
|
82
80
|
if (settings.usage !== null)
|
|
83
81
|
builder.setSessionUsage(settings.usage);
|
|
84
82
|
builder.inferEnding();
|
|
@@ -125,7 +123,6 @@ async function locate(home, opts) {
|
|
|
125
123
|
const filtered = [];
|
|
126
124
|
for (const ref of refs) {
|
|
127
125
|
if (opts.cwd) {
|
|
128
|
-
// The directory name encodes the cwd with `/` as `-`; the session_start line holds it exactly.
|
|
129
126
|
const head = await headRecord(ref.path, (r) => r.type === 'session_start', 1);
|
|
130
127
|
const cwd = head ? str(head.cwd) : null;
|
|
131
128
|
ref.cwd = cwd;
|
package/dist/formats/fold.d.ts
CHANGED
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
import type { SessionBuilder } from '../builder.js';
|
|
2
2
|
import type { RecordSource } from '../source.js';
|
|
3
|
-
/**
|
|
4
|
-
* One format's fold, driven by whoever has the records: `observe` takes each record in order and
|
|
5
|
-
* `finish` closes the session. Reading a file drives it asynchronously; text or parsed records in
|
|
6
|
-
* memory drive it synchronously. Either way it is the same fold.
|
|
7
|
-
*/
|
|
8
3
|
export interface SessionFold {
|
|
9
4
|
builder: SessionBuilder;
|
|
10
5
|
observe(record: Record<string, unknown>): void;
|
package/dist/formats/grok.js
CHANGED
|
@@ -93,12 +93,21 @@ function createFold(ref, mode, stats, model, usage) {
|
|
|
93
93
|
};
|
|
94
94
|
return { builder, observe, finish: () => { builder.source(stats); builder.inferEnding(); return builder; } };
|
|
95
95
|
}
|
|
96
|
+
async function markedJson(ref, name, mark) {
|
|
97
|
+
for (const file of [join(dirname(ref.path), name), ...ref.files]) {
|
|
98
|
+
if (file === ref.path)
|
|
99
|
+
continue;
|
|
100
|
+
const parsed = await readJson(file);
|
|
101
|
+
if (isRecord(parsed) && mark in parsed)
|
|
102
|
+
return parsed;
|
|
103
|
+
}
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
96
106
|
async function fold(ref, mode, options) {
|
|
97
107
|
const records = fileRecords(ref.path, { strict: options.corruption === 'strict', signal: options.signal });
|
|
98
|
-
const
|
|
99
|
-
const summary = await readJson(join(dir, 'summary.json'));
|
|
108
|
+
const summary = await markedJson(ref, 'summary.json', 'current_model_id');
|
|
100
109
|
const model = isRecord(summary) ? str(summary.current_model_id) : null;
|
|
101
|
-
return runFold(createFold(ref, mode, records.stats, model, usageOf(await
|
|
110
|
+
return runFold(createFold(ref, mode, records.stats, model, usageOf(await markedJson(ref, 'signals.json', 'primaryModelId'))), records);
|
|
102
111
|
}
|
|
103
112
|
export const grokReader = {
|
|
104
113
|
harness: HARNESS,
|
package/dist/formats/head.d.ts
CHANGED
|
@@ -1,8 +1 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The first record among a session file's first `limit` records that satisfies `match`. Locate
|
|
3
|
-
* reads one for every session in a store, so it reads the file a small step at a time and stops
|
|
4
|
-
* at the answer: never the rest of the file, and no digest of it. Lines parse as the session
|
|
5
|
-
* reader parses them: a blank, malformed or non-object line is skipped, and a last line with no
|
|
6
|
-
* newline counts when it is a whole record.
|
|
7
|
-
*/
|
|
8
1
|
export declare function headRecord(path: string, match: (record: Record<string, unknown>) => boolean, limit?: number): Promise<Record<string, unknown> | null>;
|
package/dist/formats/head.js
CHANGED
|
@@ -1,15 +1,7 @@
|
|
|
1
1
|
import { open } from 'node:fs/promises';
|
|
2
2
|
import { StringDecoder } from 'node:string_decoder';
|
|
3
3
|
import { isMissing } from '../source.js';
|
|
4
|
-
/** Bytes a head read takes at a time. A session's identifying record is almost always in the first. */
|
|
5
4
|
const HEAD_CHUNK = 64 * 1024;
|
|
6
|
-
/**
|
|
7
|
-
* The first record among a session file's first `limit` records that satisfies `match`. Locate
|
|
8
|
-
* reads one for every session in a store, so it reads the file a small step at a time and stops
|
|
9
|
-
* at the answer: never the rest of the file, and no digest of it. Lines parse as the session
|
|
10
|
-
* reader parses them: a blank, malformed or non-object line is skipped, and a last line with no
|
|
11
|
-
* newline counts when it is a whole record.
|
|
12
|
-
*/
|
|
13
5
|
export async function headRecord(path, match, limit = 64) {
|
|
14
6
|
let handle;
|
|
15
7
|
try {
|
|
@@ -21,7 +13,6 @@ export async function headRecord(path, match, limit = 64) {
|
|
|
21
13
|
throw error;
|
|
22
14
|
}
|
|
23
15
|
let seen = 0;
|
|
24
|
-
// undefined: read on; null: `limit` records without a match; a record: the match.
|
|
25
16
|
const take = (line) => {
|
|
26
17
|
const text = line.replace(/\r$/u, '');
|
|
27
18
|
if (text.trim().length === 0)
|
|
@@ -43,7 +34,6 @@ export async function headRecord(path, match, limit = 64) {
|
|
|
43
34
|
try {
|
|
44
35
|
const decoder = new StringDecoder('utf8');
|
|
45
36
|
const buffer = Buffer.allocUnsafe(HEAD_CHUNK);
|
|
46
|
-
// The line being read, in pieces, so a record longer than a step is joined once.
|
|
47
37
|
let pending = [];
|
|
48
38
|
let position = 0;
|
|
49
39
|
for (;;) {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { basename, join } from 'node:path';
|
|
2
|
+
import { SessionBuilder, count, str, usageOrNull } from '../builder.js';
|
|
3
|
+
import { withSqlite } from '../source.js';
|
|
4
|
+
import { EVIDENCE, STORES, mtimeMs, walkFiles } from '../stores.js';
|
|
5
|
+
const FORMAT = 'hermes.state-sqlite';
|
|
6
|
+
const STORE = STORES[FORMAT];
|
|
7
|
+
const HARNESS = 'hermes';
|
|
8
|
+
function callsOf(raw) {
|
|
9
|
+
let value = raw;
|
|
10
|
+
if (typeof raw === 'string') {
|
|
11
|
+
try {
|
|
12
|
+
value = JSON.parse(raw);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return [];
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
if (!Array.isArray(value))
|
|
19
|
+
return [];
|
|
20
|
+
return value.flatMap((call) => {
|
|
21
|
+
if (!call || typeof call !== 'object')
|
|
22
|
+
return [];
|
|
23
|
+
const row = call;
|
|
24
|
+
const fn = row.function;
|
|
25
|
+
const id = str(row.id);
|
|
26
|
+
const name = str(row.name) ?? str(fn?.name);
|
|
27
|
+
if (!id || !name)
|
|
28
|
+
return [];
|
|
29
|
+
return [{ id, name, input: row.arguments ?? fn?.arguments ?? null }];
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
function readDb(db, sessionId, builder) {
|
|
33
|
+
const session = db.prepare('SELECT model, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, started_at FROM sessions WHERE id = ?').get(sessionId);
|
|
34
|
+
const at = session ? builder.seen(session.started_at ? session.started_at * 1000 : null) : null;
|
|
35
|
+
const usage = session ? usageOrNull({ input: count(session.input_tokens), output: count(session.output_tokens), reasoning: null, cacheRead: count(session.cache_read_tokens), cacheWrite: count(session.cache_write_tokens) }) : null;
|
|
36
|
+
const model = session ? str(session.model) : null;
|
|
37
|
+
const rows = db.prepare('SELECT id, role, content, tool_call_id, tool_calls, tool_name, timestamp FROM messages WHERE session_id = ? ORDER BY id').all(sessionId);
|
|
38
|
+
let calls = 0;
|
|
39
|
+
for (const row of rows) {
|
|
40
|
+
const when = builder.seen(row.timestamp ? row.timestamp * 1000 : null);
|
|
41
|
+
const id = String(row.id);
|
|
42
|
+
if (row.role === 'user' && row.content)
|
|
43
|
+
builder.message({ id, role: 'user', actor: 'human', at: when, modelCallId: null, parts: [{ type: 'text', text: row.content }] });
|
|
44
|
+
if (row.role === 'assistant') {
|
|
45
|
+
const modelCallId = `${sessionId}:${calls}`;
|
|
46
|
+
builder.modelCall({ id: modelCallId, at: when ?? at, provider: null, servedModel: model, requestedModel: model, usage: calls === 0 ? usage : null, costUsd: null, stopReason: null, error: null });
|
|
47
|
+
calls += 1;
|
|
48
|
+
for (const call of callsOf(row.tool_calls))
|
|
49
|
+
builder.toolCall({ id: call.id, name: call.name, input: call.input, inputText: null, at: when, messageId: id });
|
|
50
|
+
if (row.content)
|
|
51
|
+
builder.message({ id, role: 'assistant', actor: 'agent', at: when, modelCallId, parts: [{ type: 'text', text: row.content }] });
|
|
52
|
+
}
|
|
53
|
+
if (row.role === 'tool' && row.tool_call_id)
|
|
54
|
+
builder.toolResult(row.tool_call_id, { output: row.content, text: row.content, isError: false, at: when, messageId: id });
|
|
55
|
+
}
|
|
56
|
+
return usage;
|
|
57
|
+
}
|
|
58
|
+
async function fold(ref, mode) {
|
|
59
|
+
const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
|
|
60
|
+
await withSqlite(ref.path, (db) => readDb(db, ref.nativeSessionId, builder));
|
|
61
|
+
builder.inferEnding();
|
|
62
|
+
return builder;
|
|
63
|
+
}
|
|
64
|
+
export async function hermesSessionsInStore(path) {
|
|
65
|
+
const refs = [];
|
|
66
|
+
await withSqlite(path, (db) => {
|
|
67
|
+
for (const row of db.prepare('SELECT id FROM sessions').all()) {
|
|
68
|
+
refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: row.id, path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null });
|
|
69
|
+
}
|
|
70
|
+
}).catch(() => undefined);
|
|
71
|
+
return refs;
|
|
72
|
+
}
|
|
73
|
+
export const hermesReader = {
|
|
74
|
+
harness: HARNESS, aliases: [], formats: [FORMAT], stores: [STORE], globs: { session: STORE.files[0] }, evidence: EVIDENCE[FORMAT],
|
|
75
|
+
async locate(home, opts = {}) {
|
|
76
|
+
const root = join(home, STORE.root);
|
|
77
|
+
const refs = [];
|
|
78
|
+
for (const rel of await walkFiles(root)) {
|
|
79
|
+
if (basename(rel) !== 'state.db')
|
|
80
|
+
continue;
|
|
81
|
+
const path = join(root, rel);
|
|
82
|
+
const mtime = await mtimeMs(path);
|
|
83
|
+
for (const ref of await hermesSessionsInStore(path)) {
|
|
84
|
+
if (opts.nativeSessionId && ref.nativeSessionId !== opts.nativeSessionId)
|
|
85
|
+
continue;
|
|
86
|
+
refs.push({ ...ref, home, mtimeMs: mtime });
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
return refs;
|
|
90
|
+
},
|
|
91
|
+
async read(ref, _opts = {}) { return (await fold(ref, 'full')).build(); },
|
|
92
|
+
async summarize(ref, _opts = {}) { return (await fold(ref, 'summary')).summary(); },
|
|
93
|
+
};
|
package/dist/formats/kimi.d.ts
CHANGED
|
@@ -5,5 +5,4 @@ import { type SessionFold } from './fold.js';
|
|
|
5
5
|
export declare function createFold(ref: SessionRef, mode: BuildMode, stats: SourceStats): SessionFold;
|
|
6
6
|
export declare function fold(ref: SessionRef, mode: BuildMode, options: ReadOptions, source?: RecordSource): Promise<SessionBuilder>;
|
|
7
7
|
export declare const kimiReader: HarnessSessionReader;
|
|
8
|
-
/** A session read from its `wire.jsonl` outside a HOME layout. */
|
|
9
8
|
export declare function kimiRefForFile(path: string): SessionRef;
|
package/dist/formats/kimi.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { isRecord } from '@tangle-network/agent-core';
|
|
2
|
-
/** Kimi wire.jsonl: TurnBegin, StepBegin, ToolCall, StatusUpdate, ToolResult, StepRetry. Legacy wire has no model. */
|
|
3
2
|
import { basename, dirname, join } from 'node:path';
|
|
4
3
|
import { SessionBuilder, count, sessionError, str, textOf, usageOrNull } from '../builder.js';
|
|
5
4
|
import { fileRecords } from '../source.js';
|
|
@@ -8,10 +7,8 @@ import { EVIDENCE, mtimeMs, storeGlob, walkFiles, withinPath } from '../stores.j
|
|
|
8
7
|
import { runFold } from './fold.js';
|
|
9
8
|
const FORMAT = 'kimi.session-dir';
|
|
10
9
|
const HARNESS = 'kimi-code';
|
|
11
|
-
/** The event stream this reader folds; the store also holds context.jsonl and state.json. */
|
|
12
10
|
const WIRE = '*/{id}/wire.jsonl';
|
|
13
11
|
const CHILD_WIRE = '*/*/subagents/{id}/wire.jsonl';
|
|
14
|
-
/** Current main agents belong to session_<uuid>; legacy child wires retain their own agent IDs. */
|
|
15
12
|
function sessionIdentity(path) {
|
|
16
13
|
const directory = dirname(path);
|
|
17
14
|
const container = dirname(directory);
|
|
@@ -59,7 +56,6 @@ export function createFold(ref, mode, stats) {
|
|
|
59
56
|
const observe = (record) => {
|
|
60
57
|
const message = isRecord(record.message) ? record.message : {};
|
|
61
58
|
const outer = str(record.type);
|
|
62
|
-
// Both protocols have metadata; only flat payload events use namespaced discriminators.
|
|
63
59
|
flat ||= outer?.includes('.') === true;
|
|
64
60
|
const payload = outer === 'context.append_loop_event' && isRecord(record.event) ? record.event : outer ? record : isRecord(message.payload) ? message.payload : {};
|
|
65
61
|
const type = outer === 'context.append_loop_event' ? str(payload.type) : outer ?? str(message.type);
|
|
@@ -150,7 +146,6 @@ export function createFold(ref, mode, stats) {
|
|
|
150
146
|
break;
|
|
151
147
|
}
|
|
152
148
|
case 'StepRetry': {
|
|
153
|
-
// A failed attempt Kimi retried: a model call that returned no answer.
|
|
154
149
|
builder.modelCall({
|
|
155
150
|
id: `${builder.nativeSessionId}:turn:${turn}:retry:${builder.modelCalls.length + 1}`, at, provider: null, servedModel: null, requestedModel: null, usage: null, costUsd: null, stopReason: null,
|
|
156
151
|
error: sessionError(str(payload.error_type) ?? 'retry', `${str(payload.error_type) ?? 'error'}${payload.status_code ? ` (status ${String(payload.status_code)})` : ''}`, at, count(payload.status_code)),
|
|
@@ -254,7 +249,6 @@ export const kimiReader = {
|
|
|
254
249
|
return (await fold(ref, 'summary', opts)).summary();
|
|
255
250
|
},
|
|
256
251
|
};
|
|
257
|
-
/** A session read from its `wire.jsonl` outside a HOME layout. */
|
|
258
252
|
export function kimiRefForFile(path) {
|
|
259
253
|
const { id, parent } = sessionIdentity(path);
|
|
260
254
|
return { harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: parent };
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { basename, dirname, join } from 'node:path';
|
|
2
|
+
import { SessionBuilder } from '../builder.js';
|
|
3
|
+
import { withSqlite } from '../source.js';
|
|
4
|
+
import { EVIDENCE, STORES, mtimeMs, storeGlob, walkFiles } from '../stores.js';
|
|
5
|
+
const FORMAT = 'nanoclaw.session-sqlite';
|
|
6
|
+
const STORE = STORES[FORMAT];
|
|
7
|
+
const HARNESS = 'nanoclaw';
|
|
8
|
+
function textOf(content) {
|
|
9
|
+
try {
|
|
10
|
+
const value = JSON.parse(content);
|
|
11
|
+
if (typeof value.text === 'string')
|
|
12
|
+
return value.text;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
}
|
|
16
|
+
return content;
|
|
17
|
+
}
|
|
18
|
+
function readTable(db, table, role, builder) {
|
|
19
|
+
const rows = db.prepare(`SELECT id, timestamp, content, kind FROM ${table} ORDER BY seq`).all();
|
|
20
|
+
for (const row of rows) {
|
|
21
|
+
if (row.kind === 'system')
|
|
22
|
+
continue;
|
|
23
|
+
const text = textOf(row.content);
|
|
24
|
+
if (!text)
|
|
25
|
+
continue;
|
|
26
|
+
builder.message({ id: row.id, role, actor: role === 'user' ? 'human' : 'agent', at: builder.seen(row.timestamp), modelCallId: null, parts: [{ type: 'text', text }] });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function fold(ref, mode) {
|
|
30
|
+
const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
|
|
31
|
+
const dir = dirname(ref.path);
|
|
32
|
+
await withSqlite(join(dir, 'inbound.db'), (db) => readTable(db, 'messages_in', 'user', builder)).catch(() => undefined);
|
|
33
|
+
await withSqlite(join(dir, 'outbound.db'), (db) => readTable(db, 'messages_out', 'assistant', builder));
|
|
34
|
+
builder.inferEnding();
|
|
35
|
+
return builder;
|
|
36
|
+
}
|
|
37
|
+
export const nanoclawReader = {
|
|
38
|
+
harness: HARNESS,
|
|
39
|
+
aliases: [],
|
|
40
|
+
formats: [FORMAT],
|
|
41
|
+
stores: [STORE],
|
|
42
|
+
globs: { session: STORE.files[0] },
|
|
43
|
+
evidence: EVIDENCE[FORMAT],
|
|
44
|
+
async locate(home, opts = {}) {
|
|
45
|
+
const root = join(home, STORE.root);
|
|
46
|
+
const pattern = storeGlob(STORE.files[0], opts.nativeSessionId);
|
|
47
|
+
const refs = [];
|
|
48
|
+
for (const rel of await walkFiles(root)) {
|
|
49
|
+
if (!pattern.test(rel))
|
|
50
|
+
continue;
|
|
51
|
+
const path = join(root, rel);
|
|
52
|
+
const id = basename(dirname(rel));
|
|
53
|
+
const mtime = await mtimeMs(path);
|
|
54
|
+
if ((opts.sinceMs && mtime < opts.sinceMs) || (opts.nativeSessionId && id !== opts.nativeSessionId))
|
|
55
|
+
continue;
|
|
56
|
+
refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path, join(dirname(path), 'inbound.db')], home, cwd: null, mtimeMs: mtime, parentNativeSessionId: null });
|
|
57
|
+
}
|
|
58
|
+
return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
59
|
+
},
|
|
60
|
+
async read(ref, _opts = {}) { return (await fold(ref, 'full')).build(); },
|
|
61
|
+
async summarize(ref, _opts = {}) { return (await fold(ref, 'summary')).summary(); },
|
|
62
|
+
};
|
|
63
|
+
export function nanoclawRefForFile(path) {
|
|
64
|
+
return { harness: HARNESS, format: FORMAT, nativeSessionId: basename(dirname(path)), path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null };
|
|
65
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { zstdDecompressSync } from 'node:zlib';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { isRecord } from '@tangle-network/agent-core';
|
|
4
|
+
import { SessionBuilder, count, str, textOf, usageOrNull } from '../builder.js';
|
|
5
|
+
import { withSqlite } from '../source.js';
|
|
6
|
+
import { EVIDENCE, STORES, mtimeMs, walkFiles } from '../stores.js';
|
|
7
|
+
const FORMAT = 'openclaw.session-jsonl';
|
|
8
|
+
const STORE = STORES[FORMAT];
|
|
9
|
+
const HARNESS = 'openclaw';
|
|
10
|
+
const TOOL_CALL = new Set(['toolCall', 'toolUse', 'functionCall']);
|
|
11
|
+
function usageOf(value) {
|
|
12
|
+
if (!isRecord(value))
|
|
13
|
+
return null;
|
|
14
|
+
return usageOrNull({ input: count(value.input), output: count(value.output), reasoning: count(value.reasoning), cacheRead: count(value.cacheRead), cacheWrite: count(value.cacheWrite) });
|
|
15
|
+
}
|
|
16
|
+
function decode(json, zstd) {
|
|
17
|
+
const text = typeof json === 'string' && json ? json : zstd instanceof Uint8Array ? zstdDecompressSync(zstd).toString('utf8') : null;
|
|
18
|
+
if (!text)
|
|
19
|
+
return null;
|
|
20
|
+
try {
|
|
21
|
+
const value = JSON.parse(text);
|
|
22
|
+
return isRecord(value) ? value : null;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function readDb(db, sessionId, builder) {
|
|
29
|
+
const rows = db.prepare('SELECT event_json, event_zstd FROM transcript_events WHERE session_id = ? ORDER BY seq').all(sessionId);
|
|
30
|
+
let calls = 0;
|
|
31
|
+
for (const row of rows) {
|
|
32
|
+
const event = decode(row.event_json, row.event_zstd);
|
|
33
|
+
if (!event || event.type !== 'message' || !isRecord(event.message))
|
|
34
|
+
continue;
|
|
35
|
+
const message = event.message;
|
|
36
|
+
const role = str(message.role);
|
|
37
|
+
const at = builder.seen(event.timestamp);
|
|
38
|
+
const id = str(event.id) ?? `${sessionId}:${calls}`;
|
|
39
|
+
const text = textOf(message.content) ?? str(message.content);
|
|
40
|
+
if (role === 'user' && text) {
|
|
41
|
+
builder.message({ id, role: 'user', actor: 'human', at, modelCallId: null, parts: [{ type: 'text', text }] });
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (role === 'toolResult') {
|
|
45
|
+
const callId = str(message.toolCallId) ?? str(message.toolUseId) ?? id;
|
|
46
|
+
builder.toolResult(callId, { output: message.content ?? null, text, isError: message.isError === true, at, messageId: id });
|
|
47
|
+
builder.message({ id, role: 'tool', actor: 'tool-result', at, modelCallId: null, parts: [{ type: 'tool-result', toolCallId: callId }] });
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (role !== 'assistant')
|
|
51
|
+
continue;
|
|
52
|
+
const model = str(message.responseModel) ?? str(message.model);
|
|
53
|
+
const modelCallId = `${sessionId}:${calls}`;
|
|
54
|
+
builder.modelCall({ id: modelCallId, at, provider: str(message.provider), servedModel: model, requestedModel: str(message.model), usage: usageOf(message.usage), costUsd: null, stopReason: str(message.stopReason), error: null });
|
|
55
|
+
calls += 1;
|
|
56
|
+
const parts = text ? [{ type: 'text', text }] : [];
|
|
57
|
+
if (Array.isArray(message.content))
|
|
58
|
+
for (const block of message.content) {
|
|
59
|
+
if (!isRecord(block) || typeof block.type !== 'string' || !TOOL_CALL.has(block.type))
|
|
60
|
+
continue;
|
|
61
|
+
const callId = str(block.id) ?? `${modelCallId}:call`;
|
|
62
|
+
const input = block.arguments ?? block.input ?? null;
|
|
63
|
+
parts.push({ type: 'tool-call', toolCallId: callId });
|
|
64
|
+
builder.toolCall({ id: callId, name: str(block.name) ?? 'tool', input, inputText: typeof input === 'string' ? input : null, at, messageId: id });
|
|
65
|
+
}
|
|
66
|
+
builder.message({ id, role: 'assistant', actor: 'agent', at, modelCallId, parts });
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
export async function openclawSessionsInStore(path) {
|
|
70
|
+
const refs = [];
|
|
71
|
+
await withSqlite(path, (db) => {
|
|
72
|
+
for (const row of db.prepare('SELECT session_id FROM session_windows').all())
|
|
73
|
+
refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: row.session_id, path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null });
|
|
74
|
+
}).catch(() => undefined);
|
|
75
|
+
return refs;
|
|
76
|
+
}
|
|
77
|
+
async function fold(ref, mode) {
|
|
78
|
+
const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
|
|
79
|
+
await withSqlite(ref.path, (db) => readDb(db, ref.nativeSessionId, builder));
|
|
80
|
+
builder.inferEnding();
|
|
81
|
+
return builder;
|
|
82
|
+
}
|
|
83
|
+
export const openclawReader = {
|
|
84
|
+
harness: HARNESS, aliases: [], formats: [FORMAT], stores: [STORE], globs: { session: STORE.files[0] }, evidence: EVIDENCE[FORMAT],
|
|
85
|
+
async locate(home, opts = {}) {
|
|
86
|
+
const refs = [];
|
|
87
|
+
for (const rel of await walkFiles(join(home, STORE.root))) {
|
|
88
|
+
if (!rel.endsWith('openclaw-agent.sqlite'))
|
|
89
|
+
continue;
|
|
90
|
+
const path = join(home, STORE.root, rel);
|
|
91
|
+
const mtime = await mtimeMs(path);
|
|
92
|
+
for (const ref of await openclawSessionsInStore(path)) {
|
|
93
|
+
if (opts.nativeSessionId && ref.nativeSessionId !== opts.nativeSessionId)
|
|
94
|
+
continue;
|
|
95
|
+
refs.push({ ...ref, home, mtimeMs: mtime });
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
99
|
+
},
|
|
100
|
+
async read(ref, _opts = {}) { return (await fold(ref, 'full')).build(); },
|
|
101
|
+
async summarize(ref, _opts = {}) { return (await fold(ref, 'summary')).summary(); },
|
|
102
|
+
};
|
|
@@ -1,4 +1,3 @@
|
|
|
1
1
|
import type { HarnessSessionReader, LocateOptions, SessionRef } from '../schema.js';
|
|
2
|
-
/** Every session in one store file, read in place without writing it. */
|
|
3
2
|
export declare function opencodeSessionsInStore(path: string, home: string | null, opts?: LocateOptions): Promise<SessionRef[]>;
|
|
4
3
|
export declare const opencodeReader: HarnessSessionReader;
|
package/dist/formats/opencode.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { isRecord } from '@tangle-network/agent-core';
|
|
2
|
-
/** OpenCode sqlite at ~/.local/share/opencode/opencode.db. Opened read-only, including the wal. */
|
|
3
2
|
import { createHash } from 'node:crypto';
|
|
4
3
|
import { join } from 'node:path';
|
|
5
4
|
import { SessionBuilder, count, isoTime, sessionError, str, usageOrNull } from '../builder.js';
|
|
@@ -47,8 +46,6 @@ function foldSession(db, ref, mode, builder) {
|
|
|
47
46
|
builder.cwd = session.directory;
|
|
48
47
|
builder.parentNativeSessionId = session.parent_id ?? null;
|
|
49
48
|
builder.seen(session.time_created);
|
|
50
|
-
// The session's source is the rows this fold reads, not the whole store: a digest of the store
|
|
51
|
-
// file would read every other session in it and change whenever any of them did.
|
|
52
49
|
const digest = createHash('sha256').update(JSON.stringify(session));
|
|
53
50
|
let bytes = 0;
|
|
54
51
|
const note = (row) => {
|
|
@@ -159,7 +156,6 @@ function foldSession(db, ref, mode, builder) {
|
|
|
159
156
|
break;
|
|
160
157
|
}
|
|
161
158
|
case 'retry': {
|
|
162
|
-
// A failed request OpenCode retried: a model call that returned no answer.
|
|
163
159
|
builder.modelCall({ id: `${row.id}:retry:${partId}`, at: isoTime(partTime.created) ?? partAt, provider, servedModel: null, requestedModel: model, usage: null, costUsd: null, stopReason: null, error: errorOf(part.error, partAt) ?? sessionError('retry', 'retried request', partAt) });
|
|
164
160
|
break;
|
|
165
161
|
}
|
|
@@ -168,7 +164,6 @@ function foldSession(db, ref, mode, builder) {
|
|
|
168
164
|
}
|
|
169
165
|
}
|
|
170
166
|
if (steps === 0) {
|
|
171
|
-
// No response step was recorded: the request failed or the process stopped first.
|
|
172
167
|
builder.modelCall({ id: `${row.id}:request`, at, provider: messageError ? null : provider, servedModel: messageError ? null : model, requestedModel: model, usage: usageOf(data.tokens), costUsd: count(data.cost), stopReason: str(data.finish), error: messageError });
|
|
173
168
|
if (messageError)
|
|
174
169
|
builder.message({ id: row.id, role: 'assistant', actor: 'injected', at, modelCallId: `${row.id}:request`, parts: [{ type: 'text', text: messageError.message }] });
|
|
@@ -198,7 +193,6 @@ async function fold(ref, mode, options) {
|
|
|
198
193
|
builder.markTruncated(`${ref.path}: the store copy was cut short`);
|
|
199
194
|
return builder;
|
|
200
195
|
}
|
|
201
|
-
/** Every session in one store file, read in place without writing it. */
|
|
202
196
|
export async function opencodeSessionsInStore(path, home, opts = {}) {
|
|
203
197
|
const mtime = await mtimeMs(path);
|
|
204
198
|
const files = [path];
|
package/dist/formats/pi.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { SessionBuilder, type BuildMode } from '../builder.js';
|
|
|
2
2
|
import type { HarnessSessionReader, ReadOptions, SessionRef } from '../schema.js';
|
|
3
3
|
import { type RecordSource, type SourceStats } from '../source.js';
|
|
4
4
|
import { type SessionFold } from './fold.js';
|
|
5
|
-
export declare function createFold(ref: SessionRef, mode: BuildMode, stats: SourceStats): SessionFold;
|
|
5
|
+
export declare function createFold(ref: SessionRef, mode: BuildMode, stats: SourceStats, harness?: string, format?: 'pi.session-jsonl' | 'prime.session-jsonl'): SessionFold;
|
|
6
6
|
export declare function fold(ref: SessionRef, mode: BuildMode, options: ReadOptions, source?: RecordSource): Promise<SessionBuilder>;
|
|
7
7
|
export declare const piReader: HarnessSessionReader;
|
|
8
8
|
export declare function piRefForFile(path: string): SessionRef;
|