@tangle-network/harness-sessions 1.0.17 → 1.0.19

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/README.md CHANGED
@@ -80,6 +80,8 @@ const { sessions, missing } = await listCapture(captureDir)
80
80
 
81
81
  The SDK and `harness-sessions read <file>` select OpenCode, Hermes and OpenClaw by database schema. NanoClaw uses the inbound and outbound databases in its session directory. A session reference lists its database files and any existing SQLite sidecars. A foreign schema or an absent session ID returns an empty list. Pass `harness` to resolve a database with more than one native schema.
82
82
 
83
+ For a bounded JSON payload from `opencode export`, use `readOpenCodeSessionExport(text, { nativeSessionId, label })`. It verifies session, message and part ownership and records the exported bytes' digest. Its model authority is OpenCode's turn context. The capture owner enumerates and supplies each session in the native family.
84
+
83
85
  Projections trim; the reader never does:
84
86
 
85
87
  - `toChatMessages(session)`: agent-eval's chat-with-tools messages.
@@ -1,3 +1,9 @@
1
- import type { HarnessSessionReader, LocateOptions, SessionRef } from '../schema.js';
1
+ import type { HarnessSession, HarnessSessionReader, LocateOptions, SessionRef } from '../schema.js';
2
+ /** Read one bounded JSON session produced by `opencode export`. The capture
3
+ * owner supplies its expected native identity and enumerates the whole family. */
4
+ export declare function readOpenCodeSessionExport(text: string, options: {
5
+ nativeSessionId: string;
6
+ label?: string;
7
+ }): HarnessSession;
2
8
  export declare function opencodeSessionsInStore(path: string, home: string | null, opts?: LocateOptions): Promise<SessionRef[]>;
3
9
  export declare const opencodeReader: HarnessSessionReader;
@@ -8,14 +8,17 @@ import { EVIDENCE, STORES, mtimeMs, withinPath } from '../stores.js';
8
8
  const FORMAT = 'opencode.sqlite';
9
9
  const STORE = STORES[FORMAT];
10
10
  const HARNESS = 'opencode';
11
+ // OpenCode records reasoning beside its output (its own `total` adds the two), so `output` here is their sum:
12
+ // every completion token, as TokenUsage counts it.
11
13
  function usageOf(tokens) {
12
14
  if (!isRecord(tokens))
13
15
  return null;
14
16
  const cache = isRecord(tokens.cache) ? tokens.cache : {};
17
+ const output = count(tokens.output), reasoning = count(tokens.reasoning);
15
18
  return usageOrNull({
16
19
  input: count(tokens.input),
17
- output: count(tokens.output),
18
- reasoning: count(tokens.reasoning),
20
+ output: output === null && reasoning === null ? null : (output ?? 0) + (reasoning ?? 0),
21
+ reasoning,
19
22
  cacheRead: count(cache.read),
20
23
  cacheWrite: count(cache.write),
21
24
  });
@@ -28,6 +31,8 @@ function errorOf(value, at) {
28
31
  return sessionError(name, str(data.message) ?? str(value.message) ?? name, at, count(data.statusCode));
29
32
  }
30
33
  function parse(json) {
34
+ if (isRecord(json))
35
+ return json;
31
36
  if (typeof json !== 'string')
32
37
  return null;
33
38
  try {
@@ -38,24 +43,19 @@ function parse(json) {
38
43
  return null;
39
44
  }
40
45
  }
41
- function foldSession(db, ref, mode, builder) {
42
- const session = db.prepare('SELECT id, parent_id, directory, time_created, time_updated FROM session WHERE id = ?').get(ref.nativeSessionId);
43
- if (!session) {
44
- builder.gap(`session ${ref.nativeSessionId} is not in the store`);
45
- return;
46
- }
46
+ function foldRows(label, session, messages, partsOf, childIds, builder, source) {
47
47
  builder.cwd = session.directory;
48
48
  builder.parentNativeSessionId = session.parent_id ?? null;
49
49
  builder.seen(session.time_created);
50
50
  const digest = createHash('sha256').update(JSON.stringify(session));
51
51
  let bytes = 0;
52
52
  const note = (row) => {
53
+ if (source)
54
+ return;
53
55
  const data = String(row.data);
54
56
  digest.update(`\n${row.id}\t${row.time_created}\t`).update(data);
55
57
  bytes += Buffer.byteLength(data);
56
58
  };
57
- const messages = db.prepare('SELECT id, time_created, data FROM message WHERE session_id = ? ORDER BY time_created, id').all(ref.nativeSessionId);
58
- const partsOf = db.prepare('SELECT id, time_created, data FROM part WHERE message_id = ? ORDER BY id');
59
59
  let unparsed = 0;
60
60
  let aborted = null;
61
61
  for (const row of messages) {
@@ -69,7 +69,7 @@ function foldSession(db, ref, mode, builder) {
69
69
  const at = builder.seen(time.created ?? row.time_created);
70
70
  builder.seen(time.completed);
71
71
  const parts = [];
72
- for (const partRow of partsOf.iterate(row.id)) {
72
+ for (const partRow of partsOf(row.id)) {
73
73
  note(partRow);
74
74
  const part = parse(partRow.data);
75
75
  if (part === null)
@@ -177,21 +177,70 @@ function foldSession(db, ref, mode, builder) {
177
177
  builder.modelCalls[builder.modelCalls.length - 1].error = messageError;
178
178
  aborted = messageError?.kind === 'MessageAbortedError' ? { at: messageError.at, error: messageError } : null;
179
179
  }
180
- const children = db.prepare('SELECT id FROM session WHERE parent_id = ? ORDER BY time_created, id').all(ref.nativeSessionId);
181
- for (const child of children) {
182
- digest.update(`\n${child.id}`);
183
- builder.child(child.id, null);
180
+ for (const id of childIds) {
181
+ if (!source)
182
+ digest.update(`\n${id}`);
183
+ builder.child(id, null);
184
184
  }
185
- builder.source({ path: `${ref.path}#session=${ref.nativeSessionId}`, sha256: `sha256:${digest.digest('hex')}`, bytes, unparsed });
185
+ builder.source({ path: label, ...(source ?? { sha256: `sha256:${digest.digest('hex')}`, bytes }), unparsed });
186
186
  const last = builder.modelCalls[builder.modelCalls.length - 1];
187
187
  if (aborted && last?.error?.kind === 'MessageAbortedError')
188
188
  last.error = null;
189
189
  builder.inferEnding(aborted ?? undefined);
190
190
  }
191
+ function foldSession(db, ref, builder) {
192
+ const session = db.prepare('SELECT id, parent_id, directory, time_created, time_updated FROM session WHERE id = ?').get(ref.nativeSessionId);
193
+ if (!session) {
194
+ builder.gap(`session ${ref.nativeSessionId} is not in the store`);
195
+ return;
196
+ }
197
+ const messages = db.prepare('SELECT id, time_created, data FROM message WHERE session_id = ? ORDER BY time_created, id').all(ref.nativeSessionId);
198
+ const parts = db.prepare('SELECT id, time_created, data FROM part WHERE message_id = ? ORDER BY id');
199
+ const children = db.prepare('SELECT id FROM session WHERE parent_id = ? ORDER BY time_created, id').all(ref.nativeSessionId);
200
+ foldRows(`${ref.path}#session=${ref.nativeSessionId}`, session, messages, (id) => parts.iterate(id), children.map(({ id }) => id), builder);
201
+ }
202
+ /** Read one bounded JSON session produced by `opencode export`. The capture
203
+ * owner supplies its expected native identity and enumerates the whole family. */
204
+ export function readOpenCodeSessionExport(text, options) {
205
+ const value = parse(text);
206
+ const info = value?.info;
207
+ if (!isRecord(info) || !Array.isArray(value?.messages) || !isRecord(info.time))
208
+ throw new Error('Invalid OpenCode session export');
209
+ const { nativeSessionId, label = `opencode:export:${nativeSessionId}` } = options;
210
+ const { id, directory, parentID, time } = info;
211
+ const created = count(time.created), updated = count(time.updated);
212
+ if (!nativeSessionId || id !== nativeSessionId || typeof directory !== 'string' || created === null || updated === null ||
213
+ (parentID !== undefined && parentID !== null && typeof parentID !== 'string'))
214
+ throw new Error('OpenCode export does not match the declared native session');
215
+ const messages = [];
216
+ const parts = new Map();
217
+ const partIds = new Set();
218
+ for (const message of value.messages) {
219
+ if (!isRecord(message) || !isRecord(message.info) || !Array.isArray(message.parts))
220
+ throw new Error('Invalid OpenCode exported message');
221
+ const data = message.info;
222
+ const messageId = str(data.id);
223
+ const at = isRecord(data.time) ? count(data.time.created) : null;
224
+ if (!messageId || parts.has(messageId) || data.sessionID !== id || at === null || (data.role !== 'assistant' && data.role !== 'user'))
225
+ throw new Error('OpenCode export has an unbound or duplicate message');
226
+ messages.push({ id: messageId, time_created: at, data });
227
+ parts.set(messageId, message.parts.map((part) => {
228
+ if (!isRecord(part) || typeof part.id !== 'string' || !part.id || partIds.has(part.id) ||
229
+ part.sessionID !== id || part.messageID !== messageId || typeof part.type !== 'string')
230
+ throw new Error('OpenCode export has an unbound or duplicate message part');
231
+ partIds.add(part.id);
232
+ return { id: part.id, time_created: null, data: part };
233
+ }));
234
+ }
235
+ const parent = parentID ?? null;
236
+ const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, 'full', id, parent);
237
+ foldRows(label, { id, parent_id: parent, directory, time_created: created, time_updated: updated }, messages, (message) => parts.get(message), [], builder, { sha256: `sha256:${createHash('sha256').update(text).digest('hex')}`, bytes: Buffer.byteLength(text) });
238
+ return builder.build();
239
+ }
191
240
  async function fold(ref, mode, options) {
192
241
  options.signal?.throwIfAborted();
193
242
  const builder = new SessionBuilder(HARNESS, FORMAT, EVIDENCE[FORMAT].servedModel, mode, ref.nativeSessionId, ref.parentNativeSessionId);
194
- await withSqlite(ref.path, (db) => foldSession(db, ref, mode, builder));
243
+ await withSqlite(ref.path, (db) => foldSession(db, ref, builder));
195
244
  if (ref.truncated)
196
245
  builder.markTruncated(`${ref.path}: the store copy was cut short`);
197
246
  return builder;
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export { isNativeStoreDatabase, nativeStoreSessions } from './native-store.js';
7
7
  export { claudeCodeReader, claudeCodeRefForFile } from './formats/claude-code.js';
8
8
  export { claudeRecordIsMachine, claudeTypedPromptText, type ClaudeRecordFacts } from './formats/claude-records.js';
9
9
  export { codexReader, codexRefForFile } from './formats/codex.js';
10
- export { opencodeReader, opencodeSessionsInStore } from './formats/opencode.js';
10
+ export { opencodeReader, opencodeSessionsInStore, readOpenCodeSessionExport } from './formats/opencode.js';
11
11
  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';
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ export { isNativeStoreDatabase, nativeStoreSessions } from './native-store.js';
6
6
  export { claudeCodeReader, claudeCodeRefForFile } from './formats/claude-code.js';
7
7
  export { claudeRecordIsMachine, claudeTypedPromptText } from './formats/claude-records.js';
8
8
  export { codexReader, codexRefForFile } from './formats/codex.js';
9
- export { opencodeReader, opencodeSessionsInStore } from './formats/opencode.js';
9
+ export { opencodeReader, opencodeSessionsInStore, readOpenCodeSessionExport } from './formats/opencode.js';
10
10
  export { piReader, piRefForFile } from './formats/pi.js';
11
11
  export { kimiReader, kimiRefForFile } from './formats/kimi.js';
12
12
  export { factoryReader, factoryRefForFile } from './formats/factory.js';
package/dist/schema.d.ts CHANGED
@@ -15,6 +15,10 @@ export interface SessionEvidenceSources {
15
15
  usage: 'per-response' | 'cumulative' | 'session-total';
16
16
  endingError: 'session-record' | 'none';
17
17
  }
18
+ /**
19
+ * One response's tokens, or a sum of them. `output` is every completion token, reasoning included; `reasoning` is the
20
+ * part of `output` spent reasoning and is never added to it. A reader whose harness records the two apart adds them.
21
+ */
18
22
  export interface TokenUsage {
19
23
  input: number | null;
20
24
  output: number | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/harness-sessions",
3
- "version": "1.0.17",
3
+ "version": "1.0.19",
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,