@tangle-network/harness-sessions 1.0.4 → 1.0.6

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 CHANGED
@@ -17,12 +17,7 @@ export declare function httpStatusIn(text: string | null | undefined): number |
17
17
  export declare function usageOrNull(usage: TokenUsage): TokenUsage | null;
18
18
  /** The key a served model is counted under: `provider/model`, or the bare model with no provider. */
19
19
  export declare function servedModelKey(call: Pick<ModelCall, 'provider' | 'servedModel'>): string | null;
20
- /**
21
- * Folds one session's records into a {@link HarnessSession}. Every format reader drives this
22
- * builder, and `read` and `summarize` share the same fold: in summary mode the builder keeps the
23
- * counts, the model calls and the ending, and drops message and tool-call content, so a 700 MB
24
- * rollout is summarized without holding its outputs.
25
- */
20
+ /** Folds one session's records into a {@link HarnessSession}. Every format reader drives this builder, and `read` and `summarize` share the same fold: in summary mode the builder keeps the counts, the model calls and the ending, and drops message and tool-call content, so a 700 MB rollout is summarized without holding its outputs. */
26
21
  export declare class SessionBuilder {
27
22
  readonly harness: string;
28
23
  readonly format: SessionFormatId;
@@ -95,13 +90,7 @@ export declare class SessionBuilder {
95
90
  /** The harness's own session total, when it records one; it wins over the per-call sum. */
96
91
  setSessionUsage(usage: TokenUsage | null): void;
97
92
  end(ending: SessionEnding): void;
98
- /**
99
- * The ending every format shares, from what the session holds when the records run out:
100
- * `aborted` when the harness recorded an abort last; `error` when the last model call failed
101
- * and no new input followed it; `completed` when the last model call succeeded, every tool call
102
- * has its result and the agent spoke last; `open` otherwise (the turn was still running, or the
103
- * process died mid-turn).
104
- */
93
+ /** The ending every format shares, from what the session holds when the records run out: `aborted` when the harness recorded an abort last; `error` when the last model call failed and no new input followed it; `completed` when the last model call succeeded, every tool call has its result and the agent spoke last; `open` otherwise (the turn was still running, or the process died mid-turn). */
105
94
  inferEnding(aborted?: {
106
95
  at: string | null;
107
96
  error: SessionError | null;
package/dist/builder.js CHANGED
@@ -66,12 +66,7 @@ export function servedModelKey(call) {
66
66
  return null;
67
67
  return call.provider === null ? call.servedModel : `${call.provider}/${call.servedModel}`;
68
68
  }
69
- /**
70
- * Folds one session's records into a {@link HarnessSession}. Every format reader drives this
71
- * builder, and `read` and `summarize` share the same fold: in summary mode the builder keeps the
72
- * counts, the model calls and the ending, and drops message and tool-call content, so a 700 MB
73
- * rollout is summarized without holding its outputs.
74
- */
69
+ /** Folds one session's records into a {@link HarnessSession}. Every format reader drives this builder, and `read` and `summarize` share the same fold: in summary mode the builder keeps the counts, the model calls and the ending, and drops message and tool-call content, so a 700 MB rollout is summarized without holding its outputs. */
75
70
  export class SessionBuilder {
76
71
  harness;
77
72
  format;
@@ -229,13 +224,7 @@ export class SessionBuilder {
229
224
  end(ending) {
230
225
  this.ending = ending;
231
226
  }
232
- /**
233
- * The ending every format shares, from what the session holds when the records run out:
234
- * `aborted` when the harness recorded an abort last; `error` when the last model call failed
235
- * and no new input followed it; `completed` when the last model call succeeded, every tool call
236
- * has its result and the agent spoke last; `open` otherwise (the turn was still running, or the
237
- * process died mid-turn).
238
- */
227
+ /** The ending every format shares, from what the session holds when the records run out: `aborted` when the harness recorded an abort last; `error` when the last model call failed and no new input followed it; `completed` when the last model call succeeded, every tool call has its result and the agent spoke last; `open` otherwise (the turn was still running, or the process died mid-turn). */
239
228
  inferEnding(aborted) {
240
229
  if (aborted) {
241
230
  const error = aborted.error ?? this.modelCalls.at(-1)?.error ?? null;
package/dist/capture.d.ts CHANGED
@@ -31,10 +31,7 @@ export interface CaptureListing {
31
31
  detail?: string;
32
32
  }>;
33
33
  }
34
- /**
35
- * Every native session in a capture: from `manifest.nativeSessions` when a v2 manifest is given
36
- * (files relative to `dir`), otherwise from the retention layout under `dir`.
37
- */
34
+ /** Every native session in a capture: from `manifest.nativeSessions` when a v2 manifest is given (files relative to `dir`), otherwise from the retention layout under `dir`. */
38
35
  export declare function listCapture(dir: string, manifest?: RawEvidenceArchiveManifestV2 | null, options?: {
39
36
  harness?: string;
40
37
  }): Promise<CaptureListing>;
package/dist/capture.js CHANGED
@@ -94,11 +94,7 @@ async function fromV2(archiveDir, manifest, listing) {
94
94
  }
95
95
  }
96
96
  }
97
- /**
98
- * The file's path relative to the runtime HOME, which the store globs match. The sidecar's archive
99
- * stores payloads under flat member names (`path`) and names the HOME path in `storePath`; a
100
- * capture laid out like the HOME carries it in `path` itself.
101
- */
97
+ /** The file's path relative to the runtime HOME, which the store globs match. The sidecar's archive stores payloads under flat member names (`path`) and names the HOME path in `storePath`; a capture laid out like the HOME carries it in `path` itself. */
102
98
  function storePathOf(file) {
103
99
  return file.storePath ?? file.path;
104
100
  }
@@ -194,10 +190,7 @@ async function fromRetention(captureDir, listing, fallbackHarness) {
194
190
  }
195
191
  }
196
192
  }
197
- /**
198
- * Every native session in a capture: from `manifest.nativeSessions` when a v2 manifest is given
199
- * (files relative to `dir`), otherwise from the retention layout under `dir`.
200
- */
193
+ /** Every native session in a capture: from `manifest.nativeSessions` when a v2 manifest is given (files relative to `dir`), otherwise from the retention layout under `dir`. */
201
194
  export async function listCapture(dir, manifest, options = {}) {
202
195
  const listing = { sessions: [], missing: [] };
203
196
  if (manifest && Array.isArray(manifest.nativeSessions))
package/dist/catalog.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export declare const SESSION_FORMAT_IDS: readonly ["claude-code.projects-jsonl", "codex.rollout-jsonl", "opencode.sqlite", "pi.session-jsonl", "kimi.session-dir", "factory.session-jsonl", "gemini.chat-json", "amp.thread-json", "forge.sqlite", "hermes.state-sqlite", "prime.session-jsonl", "openclaw.session-jsonl", "grok.acp-session-dir"];
1
+ export declare const SESSION_FORMAT_IDS: readonly ["claude-code.projects-jsonl", "codex.rollout-jsonl", "opencode.sqlite", "pi.session-jsonl", "kimi.session-dir", "factory.session-jsonl", "gemini.chat-json", "amp.thread-json", "forge.sqlite", "hermes.state-sqlite", "prime.session-jsonl", "openclaw.session-jsonl", "grok.acp-session-dir", "nanoclaw.session-sqlite"];
2
2
  /** Store layouts, relative to the HOME a harness ran with. */
3
3
  export declare const STORES: {
4
4
  readonly 'claude-code.projects-jsonl': {
@@ -92,6 +92,13 @@ export declare const STORES: {
92
92
  write: "jsonl-append" | "json-rewrite" | "sqlite-wal";
93
93
  shared: boolean;
94
94
  };
95
+ readonly 'nanoclaw.session-sqlite': {
96
+ format: "nanoclaw.session-sqlite";
97
+ root: string;
98
+ files: readonly ["*/{id}/outbound.db", "*/{id}/inbound.db"];
99
+ write: "jsonl-append" | "json-rewrite" | "sqlite-wal";
100
+ shared: boolean;
101
+ };
95
102
  };
96
103
  /** Kimi Code's current and retained legacy layouts; the legacy catalog entry stays stable. */
97
104
  export declare const KIMI_STORES: readonly [{
@@ -176,6 +183,11 @@ export declare const EVIDENCE: {
176
183
  readonly usage: "session-total";
177
184
  readonly endingError: "none";
178
185
  };
186
+ readonly 'nanoclaw.session-sqlite': {
187
+ readonly servedModel: "none";
188
+ readonly usage: "per-response";
189
+ readonly endingError: "none";
190
+ };
179
191
  };
180
192
  /** Codex homes: `.codex`, `.codex-*`, acct homes, and a fleet seat's `codex` directory. */
181
193
  export declare const CODEX_HOME_RULE: {
@@ -196,11 +208,7 @@ export declare const CODEX_HOME_RULE: {
196
208
  export declare function isCodexHome(dir: string): boolean;
197
209
  /** True when `path` is `root` or lies under it on a path boundary: `/x/agent` is not under `/x/age`. */
198
210
  export declare function withinPath(path: string, root: string): boolean;
199
- /**
200
- * Compile one store glob. `*` matches within a path segment, `**` matches any number of
201
- * segments, and `{id}` matches the native session id: the literal id when one is given, any
202
- * segment text otherwise (the reader then takes the id from the session's own header).
203
- */
211
+ /** Compile one store glob. `*` matches within a path segment, `**` matches any number of segments, and `{id}` matches the native session id: the literal id when one is given, any segment text otherwise (the reader then takes the id from the session's own header). */
204
212
  export declare function storeGlob(glob: string, nativeSessionId?: string): RegExp;
205
213
  /** A store root must be a normalized path relative to HOME: not absolute, no `.`/`..` segments. */
206
214
  export declare function assertStoreRoot(root: string): void;
package/dist/catalog.js CHANGED
@@ -12,10 +12,11 @@ export const SESSION_FORMAT_IDS = [
12
12
  'prime.session-jsonl',
13
13
  'openclaw.session-jsonl',
14
14
  'grok.acp-session-dir',
15
+ 'nanoclaw.session-sqlite',
15
16
  ];
16
17
  /** One catalog declaration owns append-only defaults and shared SQLite copy semantics. */
17
- function store(format, root, files, write = 'jsonl-append') {
18
- return { format, root, files, write, shared: write === 'sqlite-wal' };
18
+ function store(format, root, files, write = 'jsonl-append', shared = write === 'sqlite-wal') {
19
+ return { format, root, files, write, shared };
19
20
  }
20
21
  /** Store layouts, relative to the HOME a harness ran with. */
21
22
  export const STORES = {
@@ -40,6 +41,7 @@ export const STORES = {
40
41
  'prime.session-jsonl': store('prime.session-jsonl', '.prime-provider/prime-agent-dirs', ['**/*_{id}.jsonl']),
41
42
  'openclaw.session-jsonl': store('openclaw.session-jsonl', '.openclaw/agents', ['**/{id}.jsonl']),
42
43
  'grok.acp-session-dir': store('grok.acp-session-dir', '.grok/sessions', ['*/{id}/updates.jsonl']),
44
+ 'nanoclaw.session-sqlite': store('nanoclaw.session-sqlite', '.nanoclaw/data/v2-sessions', ['*/{id}/outbound.db', '*/{id}/inbound.db'], 'sqlite-wal', false),
43
45
  };
44
46
  /** Kimi Code's current and retained legacy layouts; the legacy catalog entry stays stable. */
45
47
  export const KIMI_STORES = [
@@ -60,6 +62,7 @@ export const EVIDENCE = {
60
62
  'prime.session-jsonl': { servedModel: 'session-record', usage: 'per-response', endingError: 'session-record' },
61
63
  'openclaw.session-jsonl': { servedModel: 'session-record', usage: 'per-response', endingError: 'none' },
62
64
  'grok.acp-session-dir': { servedModel: 'session-record', usage: 'session-total', endingError: 'none' },
65
+ 'nanoclaw.session-sqlite': { servedModel: 'none', usage: 'per-response', endingError: 'none' },
63
66
  };
64
67
  /** Codex homes: `.codex`, `.codex-*`, acct homes, and a fleet seat's `codex` directory. */
65
68
  export const CODEX_HOME_RULE = {
@@ -93,11 +96,7 @@ export function withinPath(path, root) {
93
96
  return p === r || p.startsWith(`${r}/`);
94
97
  }
95
98
  const REGEX_SPECIALS = /[.+^$()|[\]\\]/gu;
96
- /**
97
- * Compile one store glob. `*` matches within a path segment, `**` matches any number of
98
- * segments, and `{id}` matches the native session id: the literal id when one is given, any
99
- * segment text otherwise (the reader then takes the id from the session's own header).
100
- */
99
+ /** Compile one store glob. `*` matches within a path segment, `**` matches any number of segments, and `{id}` matches the native session id: the literal id when one is given, any segment text otherwise (the reader then takes the id from the session's own header). */
101
100
  export function storeGlob(glob, nativeSessionId) {
102
101
  let pattern = '';
103
102
  for (let i = 0; i < glob.length; i += 1) {
package/dist/cli.js CHANGED
@@ -1,12 +1,5 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * harness-sessions read <file|home|capture> [--harness h] [--session id] [--cwd dir] [--summary] [--json]
4
- *
5
- * Reads native harness sessions into the normalized form, for callers that are not JavaScript.
6
- * A file is one session file (or an OpenCode store); a directory is a capture when it holds
7
- * `__retention__/sessions`, otherwise a HOME searched through every reader's store layout.
8
- * `--json` prints one JSON document per session, one per line.
9
- */
2
+ /** harness-sessions read <file|home|capture> [--harness h] [--session id] [--cwd dir] [--summary] [--json] Reads native harness sessions into the normalized form, for callers that are not JavaScript. A file is one session file (or an OpenCode store); a directory is a capture when it holds `__retention__/sessions`, otherwise a HOME searched through every reader's store layout. `--json` prints one JSON document per session, one per line. */
10
3
  import { stat } from 'node:fs/promises';
11
4
  import { join } from 'node:path';
12
5
  import { listCapture, RETENTION_SESSIONS } from './capture.js';
@@ -1,8 +1,4 @@
1
- /**
2
- * Which Claude Code `user` records a person typed and which the harness wrote. Claude Code stores
3
- * both as `type: "user"`; the markers below are the only difference. This is the one owner of the
4
- * rule, so every reader of a Claude Code transcript (traces, agent-eval) classifies turns alike.
5
- */
1
+ /** Which Claude Code `user` records a person typed and which the harness wrote. Claude Code stores both as `type: "user"`; the markers below are the only difference. This is the one owner of the rule, so every reader of a Claude Code transcript (traces, agent-eval) classifies turns alike. */
6
2
  export interface ClaudeRecordFacts {
7
3
  /** The record's text (the first text part for block content). */
8
4
  text: string;
@@ -1,8 +1,4 @@
1
- /**
2
- * Which Claude Code `user` records a person typed and which the harness wrote. Claude Code stores
3
- * both as `type: "user"`; the markers below are the only difference. This is the one owner of the
4
- * rule, so every reader of a Claude Code transcript (traces, agent-eval) classifies turns alike.
5
- */
1
+ /** Which Claude Code `user` records a person typed and which the harness wrote. Claude Code stores both as `type: "user"`; the markers below are the only difference. This is the one owner of the rule, so every reader of a Claude Code transcript (traces, agent-eval) classifies turns alike. */
6
2
  const MACHINE_TEXT_PREFIXES = [
7
3
  '<local-command-caveat>',
8
4
  '<local-command-stdout>',
@@ -413,12 +413,7 @@ async function refsOf(files, home, opts) {
413
413
  });
414
414
  return found.filter((entry) => entry !== null);
415
415
  }
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
- */
416
+ /** Sessions in every Codex home under `home`. A lookup by id takes the rollout named for it; when no name carries the id, it reads the `session_meta` of each rollout written since the id was made. A session copied into several homes (`acct move`) is one ref, its largest copy, which holds every record. */
422
417
  async function locate(home, opts) {
423
418
  const files = await rollouts(home);
424
419
  const id = opts.nativeSessionId;
@@ -1,10 +1,6 @@
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
- */
3
+ /** One format's fold, driven by whoever has the records: `observe` takes each record in order and `finish` closes the session. Reading a file drives it asynchronously; text or parsed records in memory drive it synchronously. Either way it is the same fold. */
8
4
  export interface SessionFold {
9
5
  builder: SessionBuilder;
10
6
  observe(record: Record<string, unknown>): void;
@@ -16,6 +16,19 @@ function textBlocks(value) {
16
16
  return value.map(textBlocks).filter(Boolean).join('');
17
17
  return isRecord(value) ? str(value.text) ?? textBlocks(value.content) : '';
18
18
  }
19
+ function toolText(update) {
20
+ const fromContent = textBlocks(update.content);
21
+ if (fromContent)
22
+ return fromContent;
23
+ const raw = update.rawOutput;
24
+ if (typeof raw === 'string')
25
+ return raw;
26
+ if (isRecord(raw) && typeof raw.output_for_prompt === 'string' && raw.output_for_prompt)
27
+ return raw.output_for_prompt;
28
+ if (isRecord(raw) && Array.isArray(raw.output) && raw.output.every((byte) => typeof byte === 'number' && byte >= 0 && byte <= 255))
29
+ return Buffer.from(raw.output).toString('utf8');
30
+ return textOf(raw);
31
+ }
19
32
  function usageOf(value) {
20
33
  if (!isRecord(value))
21
34
  return null;
@@ -40,7 +53,8 @@ async function readJson(path) {
40
53
  }
41
54
  function createFold(ref, mode, stats, model, usage) {
42
55
  const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
43
- let opened = false;
56
+ let modelCalls = 0;
57
+ let modelCallId = callId(ref.nativeSessionId);
44
58
  const observe = (record) => {
45
59
  const update = isRecord(record.params) && isRecord(record.params.update) ? record.params.update : isRecord(record.update) ? record.update : record;
46
60
  const kind = str(update.sessionUpdate);
@@ -55,22 +69,25 @@ function createFold(ref, mode, stats, model, usage) {
55
69
  return;
56
70
  }
57
71
  if (kind === 'agent_message_chunk' || kind === 'agent_thought_chunk') {
58
- if (!opened)
59
- builder.modelCall({ id: callId(builder.nativeSessionId), at, provider: null, servedModel: model, requestedModel: model, usage, costUsd: null, stopReason: null, error: null });
60
- opened = true;
72
+ if (kind === 'agent_message_chunk' || modelCalls === 0) {
73
+ modelCallId = `${callId(ref.nativeSessionId)}:${modelCalls}`;
74
+ builder.modelCall({ id: modelCallId, at, provider: null, servedModel: model, requestedModel: model, usage: modelCalls === 0 ? usage : null, costUsd: null, stopReason: null, error: null });
75
+ modelCalls += 1;
76
+ }
61
77
  const text = textBlocks(update.content);
62
78
  const parts = kind === 'agent_thought_chunk' ? [{ type: 'reasoning', text, redacted: text.length === 0 }] : [{ type: 'text', text }];
63
79
  if (text || kind === 'agent_thought_chunk')
64
- builder.message({ id, role: 'assistant', actor: 'agent', at, modelCallId: callId(builder.nativeSessionId), parts });
80
+ builder.message({ id, role: 'assistant', actor: 'agent', at, modelCallId, parts });
65
81
  return;
66
82
  }
67
83
  if (kind === 'tool_call' && typeof update.toolCallId === 'string') {
68
84
  builder.toolCall({ id: update.toolCallId, name: str(update.title) ?? str(update.kind) ?? 'unknown', input: update.rawInput ?? null, inputText: null, at, messageId: id });
69
- builder.message({ id, role: 'assistant', actor: 'agent', at, modelCallId: callId(builder.nativeSessionId), parts: [{ type: 'tool-call', toolCallId: update.toolCallId }] });
85
+ builder.message({ id, role: 'assistant', actor: 'agent', at, modelCallId, parts: [{ type: 'tool-call', toolCallId: update.toolCallId }] });
70
86
  return;
71
87
  }
72
88
  if (kind === 'tool_call_update' && typeof update.toolCallId === 'string') {
73
- builder.toolResult(update.toolCallId, { output: update.rawOutput ?? update.content ?? null, text: textOf(update.rawOutput ?? update.content), isError: update.status === 'failed', at, messageId: `${id}:tool` });
89
+ const text = toolText(update);
90
+ builder.toolResult(update.toolCallId, { output: update.rawOutput ?? update.content ?? null, text, isError: update.status === 'failed', at, messageId: `${id}:tool` });
74
91
  builder.message({ id: `${id}:tool`, role: 'tool', actor: 'tool-result', at, modelCallId: null, parts: [{ type: 'tool-result', toolCallId: update.toolCallId }] });
75
92
  }
76
93
  };
@@ -1,8 +1,2 @@
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
- */
1
+ /** The first record among a session file's first `limit` records that satisfies `match`. Locate reads one for every session in a store, so it reads the file a small step at a time and stops at the answer: never the rest of the file, and no digest of it. Lines parse as the session reader parses them: a blank, malformed or non-object line is skipped, and a last line with no newline counts when it is a whole record. */
8
2
  export declare function headRecord(path: string, match: (record: Record<string, unknown>) => boolean, limit?: number): Promise<Record<string, unknown> | null>;
@@ -3,13 +3,7 @@ import { StringDecoder } from 'node:string_decoder';
3
3
  import { isMissing } from '../source.js';
4
4
  /** Bytes a head read takes at a time. A session's identifying record is almost always in the first. */
5
5
  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
- */
6
+ /** The first record among a session file's first `limit` records that satisfies `match`. Locate reads one for every session in a store, so it reads the file a small step at a time and stops at the answer: never the rest of the file, and no digest of it. Lines parse as the session reader parses them: a blank, malformed or non-object line is skipped, and a last line with no newline counts when it is a whole record. */
13
7
  export async function headRecord(path, match, limit = 64) {
14
8
  let handle;
15
9
  try {
@@ -0,0 +1,3 @@
1
+ import type { HarnessSessionReader, SessionRef } from '../schema.js';
2
+ export declare const nanoclawReader: HarnessSessionReader;
3
+ export declare function nanoclawRefForFile(path: string): SessionRef;
@@ -0,0 +1,66 @@
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
+ // A non-JSON body is already the message text.
16
+ }
17
+ return content;
18
+ }
19
+ function readTable(db, table, role, builder) {
20
+ const rows = db.prepare(`SELECT id, timestamp, content, kind FROM ${table} ORDER BY seq`).all();
21
+ for (const row of rows) {
22
+ if (row.kind === 'system')
23
+ continue;
24
+ const text = textOf(row.content);
25
+ if (!text)
26
+ continue;
27
+ builder.message({ id: row.id, role, actor: role === 'user' ? 'human' : 'agent', at: builder.seen(row.timestamp), modelCallId: null, parts: [{ type: 'text', text }] });
28
+ }
29
+ }
30
+ async function fold(ref, mode) {
31
+ const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
32
+ const dir = dirname(ref.path);
33
+ await withSqlite(join(dir, 'inbound.db'), (db) => readTable(db, 'messages_in', 'user', builder)).catch(() => undefined);
34
+ await withSqlite(join(dir, 'outbound.db'), (db) => readTable(db, 'messages_out', 'assistant', builder));
35
+ builder.inferEnding();
36
+ return builder;
37
+ }
38
+ export const nanoclawReader = {
39
+ harness: HARNESS,
40
+ aliases: [],
41
+ formats: [FORMAT],
42
+ stores: [STORE],
43
+ globs: { session: STORE.files[0] },
44
+ evidence: EVIDENCE[FORMAT],
45
+ async locate(home, opts = {}) {
46
+ const root = join(home, STORE.root);
47
+ const pattern = storeGlob(STORE.files[0], opts.nativeSessionId);
48
+ const refs = [];
49
+ for (const rel of await walkFiles(root)) {
50
+ if (!pattern.test(rel))
51
+ continue;
52
+ const path = join(root, rel);
53
+ const id = basename(dirname(rel));
54
+ const mtime = await mtimeMs(path);
55
+ if ((opts.sinceMs && mtime < opts.sinceMs) || (opts.nativeSessionId && id !== opts.nativeSessionId))
56
+ continue;
57
+ refs.push({ harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path, join(dirname(path), 'inbound.db')], home, cwd: null, mtimeMs: mtime, parentNativeSessionId: null });
58
+ }
59
+ return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
60
+ },
61
+ async read(ref, _opts = {}) { return (await fold(ref, 'full')).build(); },
62
+ async summarize(ref, _opts = {}) { return (await fold(ref, 'summary')).summary(); },
63
+ };
64
+ export function nanoclawRefForFile(path) {
65
+ return { harness: HARNESS, format: FORMAT, nativeSessionId: basename(dirname(path)), path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: null };
66
+ }
package/dist/index.d.ts CHANGED
@@ -12,6 +12,7 @@ export { piReader, piRefForFile } from './formats/pi.js';
12
12
  export { kimiReader, kimiRefForFile } from './formats/kimi.js';
13
13
  export { factoryReader, factoryRefForFile } from './formats/factory.js';
14
14
  export { grokReader, grokRefForFile } from './formats/grok.js';
15
+ export { nanoclawReader, nanoclawRefForFile } from './formats/nanoclaw.js';
15
16
  export { listCapture, readCapture, RETENTION_MANIFEST_KIND, RETENTION_SESSIONS, type CaptureListing, type CapturedSessionRef, } from './capture.js';
16
17
  export { SessionParseError } from './source.js';
17
18
  export { servedModelKey } from './builder.js';
package/dist/index.js CHANGED
@@ -10,6 +10,7 @@ export { piReader, piRefForFile } from './formats/pi.js';
10
10
  export { kimiReader, kimiRefForFile } from './formats/kimi.js';
11
11
  export { factoryReader, factoryRefForFile } from './formats/factory.js';
12
12
  export { grokReader, grokRefForFile } from './formats/grok.js';
13
+ export { nanoclawReader, nanoclawRefForFile } from './formats/nanoclaw.js';
13
14
  export { listCapture, readCapture, RETENTION_MANIFEST_KIND, RETENTION_SESSIONS, } from './capture.js';
14
15
  export { SessionParseError } from './source.js';
15
16
  export { servedModelKey } from './builder.js';
package/dist/input.d.ts CHANGED
@@ -11,11 +11,7 @@ export interface SessionInputInit {
11
11
  parentNativeSessionId?: string | null;
12
12
  /** Names the source in integrity records (a path, a blob ref). */
13
13
  label?: string;
14
- /**
15
- * The file line `input` starts on, when it continues a longer file (records appended since a
16
- * previous read). A record without an id of its own is named by its line, so the same record
17
- * gets the same id whichever way the file is read. Default 1.
18
- */
14
+ /** The file line `input` starts on, when it continues a longer file (records appended since a previous read). A record without an id of its own is named by its line, so the same record gets the same id whichever way the file is read. Default 1. */
19
15
  firstLine?: number;
20
16
  }
21
17
  /** Read a JSONL-format session (Claude Code, Codex, Pi, Kimi) from text or parsed records, synchronously. */
@@ -23,9 +23,5 @@ export interface ChatProjectionOptions {
23
23
  /** Keep `system` messages. Default true. */
24
24
  system?: boolean;
25
25
  }
26
- /**
27
- * The session as chat-with-tools messages: each assistant message carries its text, reasoning
28
- * and tool calls; each tool result is a `tool` message answering its call. Content is complete;
29
- * a projection that needs less trims it itself.
30
- */
26
+ /** The session as chat-with-tools messages: each assistant message carries its text, reasoning and tool calls; each tool result is a `tool` message answering its call. Content is complete; a projection that needs less trims it itself. */
31
27
  export declare function toChatMessages(session: HarnessSession, options?: ChatProjectionOptions): ChatMessage[];
@@ -14,11 +14,7 @@ function resultContent(output, text) {
14
14
  return '';
15
15
  return JSON.stringify(output);
16
16
  }
17
- /**
18
- * The session as chat-with-tools messages: each assistant message carries its text, reasoning
19
- * and tool calls; each tool result is a `tool` message answering its call. Content is complete;
20
- * a projection that needs less trims it itself.
21
- */
17
+ /** The session as chat-with-tools messages: each assistant message carries its text, reasoning and tool calls; each tool result is a `tool` message answering its call. Content is complete; a projection that needs less trims it itself. */
22
18
  export function toChatMessages(session, options = {}) {
23
19
  const keepInjected = options.injected !== false;
24
20
  const keepSystem = options.system !== false;
@@ -4,9 +4,5 @@ export interface OtlpProjectionOptions {
4
4
  /** Characters of message text kept per span attribute. Default 8000; 0 keeps none. */
5
5
  contentChars?: number;
6
6
  }
7
- /**
8
- * The session as contract spans: one AGENT span for the session, one LLM span per model call
9
- * (served model, tokens, cost, error status) and one TOOL span per tool call under the model call
10
- * that made it. Ids derive from the native session id, so two exports of one session join.
11
- */
7
+ /** The session as contract spans: one AGENT span for the session, one LLM span per model call (served model, tokens, cost, error status) and one TOOL span per tool call under the model call that made it. Ids derive from the native session id, so two exports of one session join. */
12
8
  export declare function toOtlpSpans(session: HarnessSession, options?: OtlpProjectionOptions): ContractSpan[];
@@ -1,10 +1,6 @@
1
1
  import { contractSpan, deriveHexId, llmSpan, toolSpan, } from '@tangle-network/agent-trace-contract';
2
2
  const cap = (text, n) => (text.length <= n ? text : `${text.slice(0, n)}…`);
3
- /**
4
- * The session as contract spans: one AGENT span for the session, one LLM span per model call
5
- * (served model, tokens, cost, error status) and one TOOL span per tool call under the model call
6
- * that made it. Ids derive from the native session id, so two exports of one session join.
7
- */
3
+ /** The session as contract spans: one AGENT span for the session, one LLM span per model call (served model, tokens, cost, error status) and one TOOL span per tool call under the model call that made it. Ids derive from the native session id, so two exports of one session join. */
8
4
  export function toOtlpSpans(session, options = {}) {
9
5
  const chars = options.contentChars ?? 8000;
10
6
  const traceId = deriveHexId(`${session.harness}:${session.nativeSessionId}`, 16);
@@ -41,11 +41,7 @@ export interface TurnOptions {
41
41
  filesOf?: (call: SessionToolCall) => string[];
42
42
  }
43
43
  export declare function summarizeText(text: string, n: number): string;
44
- /**
45
- * The session as the blog's turns: one turn per human message and per assistant message, with
46
- * the tool calls an assistant message made, the files they touched, the model that answered,
47
- * its usage and the error it ended with.
48
- */
44
+ /** The session as the blog's turns: one turn per human message and per assistant message, with the tool calls an assistant message made, the files they touched, the model that answered, its usage and the error it ended with. */
49
45
  export declare function toTurns(session: HarnessSession, options?: TurnOptions): Turn[];
50
46
  /** The model a session was answered by most often, or null when it recorded none. */
51
47
  export declare function primaryModel(session: Pick<HarnessSession, 'modelCalls'>): string | null;
@@ -60,11 +60,7 @@ function inputPreview(call) {
60
60
  function text(message, type) {
61
61
  return message.parts.filter((p) => p.type === type).map((p) => p.text).join('\n');
62
62
  }
63
- /**
64
- * The session as the blog's turns: one turn per human message and per assistant message, with
65
- * the tool calls an assistant message made, the files they touched, the model that answered,
66
- * its usage and the error it ended with.
67
- */
63
+ /** The session as the blog's turns: one turn per human message and per assistant message, with the tool calls an assistant message made, the files they touched, the model that answered, its usage and the error it ended with. */
68
64
  export function toTurns(session, options = {}) {
69
65
  const textChars = options.textChars ?? 8000;
70
66
  const summaryChars = options.summaryChars ?? 280;
package/dist/registry.js CHANGED
@@ -3,9 +3,10 @@ import { codexReader } from './formats/codex.js';
3
3
  import { kimiReader } from './formats/kimi.js';
4
4
  import { factoryReader } from './formats/factory.js';
5
5
  import { grokReader } from './formats/grok.js';
6
+ import { nanoclawReader } from './formats/nanoclaw.js';
6
7
  import { opencodeReader } from './formats/opencode.js';
7
8
  import { piReader } from './formats/pi.js';
8
- const READERS = [claudeCodeReader, codexReader, opencodeReader, piReader, kimiReader, factoryReader, grokReader];
9
+ const READERS = [claudeCodeReader, codexReader, opencodeReader, piReader, kimiReader, factoryReader, grokReader, nanoclawReader];
9
10
  const BY_NAME = new Map();
10
11
  for (const reader of READERS) {
11
12
  BY_NAME.set(reader.harness, reader);
package/dist/source.d.ts CHANGED
@@ -22,12 +22,7 @@ export declare class SessionParseError extends Error {
22
22
  readonly line: number;
23
23
  constructor(path: string, line: number, reason: string);
24
24
  }
25
- /**
26
- * Streams the JSON records of one append-only JSONL file. Each record is parsed and yielded in
27
- * order; the whole file is hashed as it is read. An unparsable line is counted (or thrown in
28
- * strict mode). A final line without a newline that does not parse is a record the harness was
29
- * still writing when the copy was taken, so it is reported as a torn tail rather than corruption.
30
- */
25
+ /** Stream one JSONL file in order and hash it. Unparsable lines count, or throw in strict mode. A torn tail is an unfinished last line, not corruption. */
31
26
  export declare function readJsonlRecords(path: string, stats: SourceStats, options?: {
32
27
  strict?: boolean;
33
28
  signal?: AbortSignal;
@@ -40,21 +35,13 @@ export declare function fileRecords(path: string, options?: {
40
35
  }): RecordSource;
41
36
  /** Stats for bytes already in memory. */
42
37
  export declare function memoryStats(label: string, text?: string): SourceStats;
43
- /**
44
- * The records of JSONL text already in memory (a retained copy, a blob), read synchronously.
45
- * `firstLine` numbers the text's first line, for text that continues a longer file.
46
- */
38
+ /** JSONL text already in memory. `firstLine` numbers its first line when the text continues a longer file. */
47
39
  export declare function textRecordsSync(text: string, stats: SourceStats, options?: {
48
40
  strict?: boolean;
49
41
  firstLine?: number;
50
42
  }): Generator<Record<string, unknown>>;
51
43
  /** Records a caller already parsed (one per line, in order, the first on line `firstLine`). Non-objects count as unparsed. */
52
44
  export declare function arrayRecordsSync(values: readonly unknown[], stats: SourceStats, firstLine?: number): Generator<Record<string, unknown>>;
53
- /**
54
- * Run `use` against a SQLite store opened read-only in place ({@link openSqlite}). A store SQLite
55
- * cannot open in place is read from a private copy instead: a write-ahead log with no `-shm` in a
56
- * directory SQLite cannot write (a capture on read-only storage), or a Node whose `node:sqlite`
57
- * does not accept URI file names (before 22.15).
58
- */
45
+ /** Run `use` on a store opened read-only in place. If SQLite cannot, read a private copy: a WAL with no `-shm` on read-only storage, or Node before 22.15 without URI file names. */
59
46
  export declare function withSqlite<T>(path: string, use: (db: DatabaseSync) => T): Promise<T>;
60
47
  export declare function isMissing(error: unknown): boolean;
package/dist/source.js CHANGED
@@ -23,12 +23,7 @@ export class SessionParseError extends Error {
23
23
  }
24
24
  }
25
25
  const NEWLINE = 0x0a;
26
- /**
27
- * Streams the JSON records of one append-only JSONL file. Each record is parsed and yielded in
28
- * order; the whole file is hashed as it is read. An unparsable line is counted (or thrown in
29
- * strict mode). A final line without a newline that does not parse is a record the harness was
30
- * still writing when the copy was taken, so it is reported as a torn tail rather than corruption.
31
- */
26
+ /** Stream one JSONL file in order and hash it. Unparsable lines count, or throw in strict mode. A torn tail is an unfinished last line, not corruption. */
32
27
  export async function* readJsonlRecords(path, stats, options = {}) {
33
28
  const hash = createHash('sha256');
34
29
  let pending = [];
@@ -126,10 +121,7 @@ export function memoryStats(label, text) {
126
121
  const bytes = Buffer.from(text, 'utf8');
127
122
  return { path: label, sha256: `sha256:${createHash('sha256').update(bytes).digest('hex')}`, bytes: bytes.length, unparsed: 0, tornTail: false, line: 0 };
128
123
  }
129
- /**
130
- * The records of JSONL text already in memory (a retained copy, a blob), read synchronously.
131
- * `firstLine` numbers the text's first line, for text that continues a longer file.
132
- */
124
+ /** JSONL text already in memory. `firstLine` numbers its first line when the text continues a longer file. */
133
125
  export function* textRecordsSync(text, stats, options = {}) {
134
126
  const lines = text.split('\n');
135
127
  const first = options.firstLine ?? 1;
@@ -191,14 +183,7 @@ async function exists(path) {
191
183
  throw error;
192
184
  }
193
185
  }
194
- /**
195
- * Open a SQLite store read-only where it lies. A store with a write-ahead log beside it is opened
196
- * `mode=ro`: SQLite reads the log's committed tail and coordinates with a live writer through the
197
- * store's shared-memory index (`-shm`), and never writes the store or its log or checkpoints it. A
198
- * store without a log is opened `immutable=1`: no connection holds it open, the file holds every
199
- * committed row, and SQLite creates no `-wal` or `-shm` beside it. Throws when SQLite cannot read
200
- * the store in place.
201
- */
186
+ /** Open a SQLite store read-only in place. A WAL uses `mode=ro` (committed tail, coordinates through `-shm`, never writes or checkpoints). No log uses `immutable=1` (no live connection, no new `-wal`/`-shm`). Throws when SQLite cannot read it there. */
202
187
  async function openSqlite(path) {
203
188
  const mode = (await exists(`${path}-wal`)) ? 'mode=ro' : 'immutable=1';
204
189
  const { DatabaseSync } = loadSqlite();
@@ -220,12 +205,7 @@ function cannotOpen(error) {
220
205
  const code = error?.errcode;
221
206
  return typeof code === 'number' && (code & 0xff) === 14;
222
207
  }
223
- /**
224
- * Run `use` against a SQLite store opened read-only in place ({@link openSqlite}). A store SQLite
225
- * cannot open in place is read from a private copy instead: a write-ahead log with no `-shm` in a
226
- * directory SQLite cannot write (a capture on read-only storage), or a Node whose `node:sqlite`
227
- * does not accept URI file names (before 22.15).
228
- */
208
+ /** Run `use` on a store opened read-only in place. If SQLite cannot, read a private copy: a WAL with no `-shm` on read-only storage, or Node before 22.15 without URI file names. */
229
209
  export async function withSqlite(path, use) {
230
210
  // SQLite follows a symlinked store to its target and keeps the log there, so the log is looked
231
211
  // for there too. A missing store throws ENOENT here, which callers read as "no sessions".
@@ -276,11 +256,7 @@ async function storeKey(path) {
276
256
  }
277
257
  return `${path}|${parts.join('|')}`;
278
258
  }
279
- /**
280
- * Run `use` against a private copy of a SQLite store: the store and its `-wal` and `-shm` siblings
281
- * are copied and only the copy is opened, writable, so SQLite replays the copied log into it. `use`
282
- * is synchronous so no other read can replace the copy while it runs.
283
- */
259
+ /** Run `use` on a private copy of the store and its `-wal`/`-shm`, opened writable so SQLite replays the log. `use` is synchronous. */
284
260
  async function withSqliteCopy(path, use) {
285
261
  const key = await storeKey(path);
286
262
  if (current?.key !== key) {
package/dist/stores.d.ts CHANGED
@@ -6,11 +6,5 @@ export declare const LOCATE_READS = 32;
6
6
  /** `fn` over `items`, at most `limit` at a time, with the results in the order of `items`. */
7
7
  export declare function mapLimit<T, R>(items: readonly T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]>;
8
8
  export declare function mtimeMs(path: string): Promise<number>;
9
- /**
10
- * Every Codex home under `home`, by `CODEX_HOME_RULE`: `home` itself when it is one (a fleet seat's
11
- * `codex` passed as a store root), `.codex` and each `.codex-<name>` in it, and each acct account
12
- * home. `$CODEX_HOME` and `$ACCT_CONFIG` describe this process's own HOME, so they apply only when
13
- * `home` is that HOME; another HOME (a store root, a capture) is read by its layout alone. Homes
14
- * that resolve to one directory, such as an account home linked to `~/.codex`, count once.
15
- */
9
+ /** Every Codex home under `home`, by `CODEX_HOME_RULE`: `home` itself when it is one (a fleet seat's `codex` passed as a store root), `.codex` and each `.codex-<name>` in it, and each acct account home. `$CODEX_HOME` and `$ACCT_CONFIG` describe this process's own HOME, so they apply only when `home` is that HOME; another HOME (a store root, a capture) is read by its layout alone. Homes that resolve to one directory, such as an account home linked to `~/.codex`, count once. */
16
10
  export declare function codexHomes(home: string): Promise<string[]>;
package/dist/stores.js CHANGED
@@ -70,13 +70,7 @@ async function childDirs(dir) {
70
70
  throw error;
71
71
  }
72
72
  }
73
- /**
74
- * Every Codex home under `home`, by `CODEX_HOME_RULE`: `home` itself when it is one (a fleet seat's
75
- * `codex` passed as a store root), `.codex` and each `.codex-<name>` in it, and each acct account
76
- * home. `$CODEX_HOME` and `$ACCT_CONFIG` describe this process's own HOME, so they apply only when
77
- * `home` is that HOME; another HOME (a store root, a capture) is read by its layout alone. Homes
78
- * that resolve to one directory, such as an account home linked to `~/.codex`, count once.
79
- */
73
+ /** Every Codex home under `home`, by `CODEX_HOME_RULE`: `home` itself when it is one (a fleet seat's `codex` passed as a store root), `.codex` and each `.codex-<name>` in it, and each acct account home. `$CODEX_HOME` and `$ACCT_CONFIG` describe this process's own HOME, so they apply only when `home` is that HOME; another HOME (a store root, a capture) is read by its layout alone. Homes that resolve to one directory, such as an account home linked to `~/.codex`, count once. */
80
74
  export async function codexHomes(home) {
81
75
  const own = resolve(home) === resolve(process.env.HOME || homedir());
82
76
  const candidates = isCodexHome(home) ? [home] : [];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/harness-sessions",
3
- "version": "1.0.4",
3
+ "version": "1.0.6",
4
4
  "description": "One reader for every coding-agent harness's native session (Claude Code, Codex, OpenCode, Pi): store layouts, a normalized session with messages, tool calls, served models, usage and ending errors, and projections to chat messages, OTLP spans and turns",
5
5
  "type": "module",
6
6
  "sideEffects": false,