@tangle-network/harness-sessions 1.0.13 → 1.0.14

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/capture.js CHANGED
@@ -6,6 +6,7 @@ import { str } from './builder.js';
6
6
  import { opencodeSessionsInStore } from './formats/opencode.js';
7
7
  import { hermesSessionsInStore } from './formats/hermes.js';
8
8
  import { openclawSessionsInStore } from './formats/openclaw.js';
9
+ import { kimiRefForFile, linkKimiFamily } from './formats/kimi.js';
9
10
  import { maybeReaderFor, readerFor, readerForFormat } from './registry.js';
10
11
  import { isMissing } from './source.js';
11
12
  import { storeGlob } from './stores.js';
@@ -121,13 +122,29 @@ async function fromV2(archiveDir, manifest, listing) {
121
122
  continue;
122
123
  }
123
124
  const mainPath = join(archiveDir, mainFile.path);
124
- const nestedFiles = copy.files.filter((f) => { const rel = inStore(storePathOf(f)); return rel !== null && nested.some((n) => n.test(rel)); }).map((f) => join(archiveDir, f.path));
125
+ const nestedCopies = [...new Map(copy.files.filter((f) => {
126
+ const rel = inStore(storePathOf(f));
127
+ return rel !== null && !main.test(rel) && nested.some((n) => n.test(rel));
128
+ }).map((f) => [storePathOf(f), f])).values()];
129
+ const nestedFiles = nestedCopies.map((f) => join(archiveDir, f.path));
125
130
  const declared = store.files.map((pattern) => storeGlob(pattern, copy.nativeSessionId));
126
131
  const files = [...new Set([mainPath, ...nestedFiles, ...copy.files.filter((f) => { const rel = inStore(storePathOf(f)); return rel !== null && declared.some((pattern) => pattern.test(rel)); }).map((f) => join(archiveDir, f.path))])];
127
- listing.sessions.push(captured({ harness: reader.harness, format: store.format, nativeSessionId: copy.nativeSessionId, path: mainPath, files, home: null, cwd: null, mtimeMs: Date.parse(copy.capturedAt) || 0, parentNativeSessionId: null, truncated: mainFile.truncated }, copy, true, archiveDir, mainPath));
128
- for (const file of nestedFiles) {
129
- const child = file.split('/').pop().replace(/\.jsonl$/u, '').replace(/^agent-/u, '');
130
- listing.sessions.push(captured({ harness: reader.harness, format: store.format, nativeSessionId: child, path: file, files: [file], home: null, cwd: null, mtimeMs: Date.parse(copy.capturedAt) || 0, parentNativeSessionId: copy.nativeSessionId, truncated }, copy, false, archiveDir, file));
132
+ const family = [{ harness: reader.harness, format: store.format, nativeSessionId: copy.nativeSessionId, path: mainPath, files, home: null, cwd: null, mtimeMs: Date.parse(copy.capturedAt) || 0, parentNativeSessionId: null, truncated: mainFile.truncated }];
133
+ for (const file of nestedCopies) {
134
+ const path = join(archiveDir, file.path);
135
+ const child = path.split('/').pop().replace(/\.jsonl$/u, '').replace(/^agent-/u, '');
136
+ const identity = reader.harness === 'kimi-code'
137
+ ? kimiRefForFile(path, storePathOf(file))
138
+ : { harness: reader.harness, format: store.format, nativeSessionId: child, parentNativeSessionId: copy.nativeSessionId };
139
+ family.push({ ...identity, path, files: [path], home: null, cwd: null, mtimeMs: Date.parse(copy.capturedAt) || 0, truncated: reader.harness === 'kimi-code' ? file.truncated : truncated });
140
+ }
141
+ if (reader.harness === 'kimi-code' && nestedFiles.length) {
142
+ const state = storeGlob('wd_*/{id}/state.json', copy.nativeSessionId);
143
+ const index = copy.files.find(file => state.test(inStore(storePathOf(file)) ?? ''));
144
+ await linkKimiFamily(family, index && !index.truncated ? join(archiveDir, index.path) : undefined);
145
+ }
146
+ for (const ref of family) {
147
+ listing.sessions.push(captured(ref, copy, ref.path === mainPath, archiveDir, ref.path));
131
148
  }
132
149
  }
133
150
  }
package/dist/catalog.d.ts CHANGED
@@ -111,6 +111,7 @@ export declare const KIMI_STORES: readonly [{
111
111
  readonly files: readonly ["wd_*/{id}/**"];
112
112
  readonly globs: {
113
113
  readonly session: "wd_*/{id}/agents/main/wire.jsonl";
114
+ readonly children: "wd_*/{id}/agents/*/wire.jsonl";
114
115
  };
115
116
  readonly format: "kimi.session-dir";
116
117
  readonly write: "jsonl-append" | "json-rewrite" | "sqlite-wal";
package/dist/catalog.js CHANGED
@@ -42,7 +42,7 @@ export const STORES = {
42
42
  'nanoclaw.session-sqlite': store('nanoclaw.session-sqlite', '.nanoclaw/data/v2-sessions', ['*/{id}/outbound.db', '*/{id}/inbound.db'], 'sqlite-wal', false),
43
43
  };
44
44
  export const KIMI_STORES = [
45
- { ...STORES['kimi.session-dir'], root: '.kimi-code/sessions', files: ['wd_*/{id}/**'], globs: { session: 'wd_*/{id}/agents/main/wire.jsonl' } },
45
+ { ...STORES['kimi.session-dir'], root: '.kimi-code/sessions', files: ['wd_*/{id}/**'], globs: { session: 'wd_*/{id}/agents/main/wire.jsonl', children: 'wd_*/{id}/agents/*/wire.jsonl' } },
46
46
  STORES['kimi.session-dir'],
47
47
  ];
48
48
  /** Every root the pinned CLIs write transcripts to: the classic home layout and the XDG config layout (#553). */
@@ -4,5 +4,7 @@ import { type RecordSource, type SourceStats } from '../source.js';
4
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
+ /** Recover the originating call's owner only for a requested family missing its native index. */
8
+ export declare function linkKimiFamily(refs: SessionRef[], statePath?: string, options?: ReadOptions): Promise<void>;
7
9
  export declare const kimiReader: HarnessSessionReader;
8
- export declare function kimiRefForFile(path: string): SessionRef;
10
+ export declare function kimiRefForFile(path: string, storePath?: string): SessionRef;
@@ -1,20 +1,55 @@
1
1
  import { isRecord } from '@tangle-network/agent-core';
2
- import { basename, dirname, join } from 'node:path';
2
+ import { readFileSync } from 'node:fs';
3
+ import { readdir } from 'node:fs/promises';
4
+ import { basename, dirname, isAbsolute, join } from 'node:path';
3
5
  import { SessionBuilder, count, sessionError, str, textOf, usageOrNull } from '../builder.js';
4
- import { fileRecords } from '../source.js';
6
+ import { fileRecords, isMissing } from '../source.js';
5
7
  import { KIMI_STORES } from '../catalog.js';
6
8
  import { EVIDENCE, mtimeMs, storeGlob, walkFiles, withinPath } from '../stores.js';
7
9
  import { foldedReader, runFold } from './fold.js';
8
10
  const FORMAT = 'kimi.session-dir';
9
11
  const HARNESS = 'kimi-code';
10
12
  const WIRE = '*/{id}/wire.jsonl';
11
- const CHILD_WIRE = '*/*/subagents/{id}/wire.jsonl';
13
+ const CHILD_WIRE = '*/{id}/subagents/*/wire.jsonl';
14
+ function scopedAgent(root, agent) {
15
+ return agent === 'main' ? root : `${root}/${agent}`;
16
+ }
12
17
  function sessionIdentity(path) {
13
18
  const directory = dirname(path);
14
19
  const container = dirname(directory);
15
- if (basename(container) === 'agents' && basename(directory) === 'main')
16
- return { id: basename(dirname(container)), parent: null };
17
- return { id: basename(directory), parent: basename(container) === 'subagents' ? basename(dirname(container)) : null };
20
+ const agent = basename(directory);
21
+ if (basename(container) === 'agents') {
22
+ const root = basename(dirname(container));
23
+ return { id: scopedAgent(root, agent), parent: null, root };
24
+ }
25
+ return { id: agent, parent: basename(container) === 'subagents' ? basename(dirname(container)) : null, root: null };
26
+ }
27
+ /** In 2.x every agent has a sibling directory. The small native index names its actual parent. */
28
+ function stateParents(path) {
29
+ let state;
30
+ try {
31
+ state = JSON.parse(readFileSync(path, 'utf8'));
32
+ }
33
+ catch (error) {
34
+ if (isMissing(error) || error instanceof SyntaxError)
35
+ return new Map();
36
+ throw error;
37
+ }
38
+ const parents = new Map();
39
+ if (isRecord(state) && typeof state.id === 'string' && isRecord(state.agents)) {
40
+ for (const [agent, row] of Object.entries(state.agents)) {
41
+ if (isRecord(row) && typeof row.parentAgentId === 'string')
42
+ parents.set(scopedAgent(state.id, agent), scopedAgent(state.id, row.parentAgentId));
43
+ }
44
+ }
45
+ return parents;
46
+ }
47
+ function spawnEdge(ref, payload) {
48
+ const [root, agent = 'main'] = ref.nativeSessionId.split('/');
49
+ const child = str(payload.subagentId);
50
+ if (!root || !child || child === 'main' || payload.parentAgentId !== agent || payload.callerAgentId !== agent)
51
+ return null;
52
+ return { id: scopedAgent(root, child), tool: str(payload.parentToolCallId) };
18
53
  }
19
54
  function usageOf(value) {
20
55
  if (!isRecord(value))
@@ -175,6 +210,12 @@ export function createFold(ref, mode, stats) {
175
210
  case 'CompactionBegin':
176
211
  compactions += 1;
177
212
  break;
213
+ case 'subagent.spawned': {
214
+ const child = spawnEdge(ref, payload);
215
+ if (child)
216
+ builder.child(child.id, child.tool);
217
+ break;
218
+ }
178
219
  case 'SubagentEvent': {
179
220
  subagentEvents += 1;
180
221
  const agent = str(payload.agent_id);
@@ -204,38 +245,118 @@ export function createFold(ref, mode, stats) {
204
245
  return { builder, observe, finish };
205
246
  }
206
247
  export async function fold(ref, mode, options, source = fileRecords(ref.path, { strict: options.corruption === 'strict', signal: options.signal })) {
248
+ const { root } = sessionIdentity(ref.path);
249
+ if (ref.parentNativeSessionId === null && root && ref.nativeSessionId !== root) {
250
+ // A direct file read may have only the retained wires, without the session index.
251
+ const agents = dirname(dirname(ref.path));
252
+ ref = { ...ref };
253
+ const family = [ref];
254
+ for (const entry of await readdir(agents, { withFileTypes: true })) {
255
+ const path = join(agents, entry.name, 'wire.jsonl');
256
+ if (entry.isDirectory() && path !== ref.path && await mtimeMs(path))
257
+ family.push(refForWire(path, path));
258
+ }
259
+ await linkKimiFamily(family, undefined, options);
260
+ }
207
261
  return runFold(createFold(ref, mode, source.stats), source);
208
262
  }
263
+ /** Recover the originating call's owner only for a requested family missing its native index. */
264
+ export async function linkKimiFamily(refs, statePath, options = {}) {
265
+ const indexed = statePath ? stateParents(statePath) : new Map();
266
+ const missing = new Map();
267
+ for (const ref of refs) {
268
+ ref.parentNativeSessionId ??= indexed.get(ref.nativeSessionId) ?? null;
269
+ if (ref.parentNativeSessionId === null && ref.nativeSessionId.includes('/'))
270
+ missing.set(ref.nativeSessionId, ref);
271
+ }
272
+ if (!missing.size)
273
+ return;
274
+ // A root normally records the first spawn long before it finishes. Stop at that record.
275
+ const parents = [...refs].sort((a, b) => Number(a.nativeSessionId.includes('/')) - Number(b.nativeSessionId.includes('/')));
276
+ for (const parent of parents) {
277
+ if (missing.size === 1 && missing.has(parent.nativeSessionId))
278
+ continue;
279
+ for await (const row of fileRecords(parent.path, { signal: options.signal, strict: options.corruption === 'strict' }).records) {
280
+ if (row.type !== 'subagent.spawned')
281
+ continue;
282
+ const edge = spawnEdge(parent, row);
283
+ const child = edge && missing.get(edge.id);
284
+ if (child) {
285
+ child.parentNativeSessionId = parent.nativeSessionId;
286
+ missing.delete(child.nativeSessionId);
287
+ if (!missing.size)
288
+ return;
289
+ }
290
+ }
291
+ }
292
+ }
209
293
  async function locate(home, opts) {
210
- const refs = [];
294
+ const found = [];
295
+ const indices = new Map();
211
296
  for (const store of KIMI_STORES) {
212
297
  const root = join(home, store.root);
213
298
  const pattern = storeGlob('globs' in store ? store.globs.session : WIRE);
214
- const children = storeGlob(CHILD_WIRE);
299
+ const children = storeGlob('globs' in store && store.globs.children ? store.globs.children : CHILD_WIRE);
215
300
  const matches = (rel) => {
216
- const { id, parent } = sessionIdentity(rel);
217
- return (pattern.test(rel) || children.test(rel)) && (!opts.nativeSessionId || id === opts.nativeSessionId || parent === opts.nativeSessionId);
301
+ if (!pattern.test(rel) && !children.test(rel))
302
+ return false;
303
+ if (!opts.nativeSessionId)
304
+ return true;
305
+ const { id, parent, root: sessionRoot } = sessionIdentity(rel);
306
+ return sessionRoot !== null
307
+ ? sessionRoot === opts.nativeSessionId.split('/')[0]
308
+ : id === opts.nativeSessionId || parent === opts.nativeSessionId;
218
309
  };
219
310
  for (const rel of await walkFiles(root, undefined, matches)) {
220
311
  const path = join(root, rel);
221
- const mtime = await mtimeMs(path);
222
- if (opts.sinceMs && mtime < opts.sinceMs)
223
- continue;
224
312
  const context = join(dirname(path), 'context.jsonl');
225
313
  const files = (await mtimeMs(context)) > 0 ? [path, context] : [path];
226
- const ref = { ...kimiRefForFile(path), files, home, mtimeMs: mtime };
227
- if (opts.cwd) {
228
- ref.cwd = (await fold(ref, 'summary', {})).cwd;
229
- if (ref.cwd === null || !withinPath(ref.cwd, opts.cwd))
230
- continue;
231
- }
232
- refs.push(ref);
314
+ found.push({ ...refForWire(path, path, indices), files, home, mtimeMs: await mtimeMs(path) });
233
315
  }
234
316
  }
235
- return refs.sort((a, b) => b.mtimeMs - a.mtimeMs);
317
+ const refs = found.filter(ref => !opts.sinceMs || ref.mtimeMs >= opts.sinceMs);
318
+ // Inventory stays a metadata operation. An explicit family read can recover a missing parent from its own wires.
319
+ if (opts.nativeSessionId && refs.some(ref => ref.nativeSessionId.includes('/') && ref.parentNativeSessionId === null))
320
+ await linkKimiFamily(found);
321
+ const byId = new Map(found.map((ref) => [ref.nativeSessionId, ref]));
322
+ const selected = (ref) => {
323
+ if (!opts.nativeSessionId || ref.nativeSessionId.split('/')[0] === opts.nativeSessionId)
324
+ return true;
325
+ let id = ref.nativeSessionId;
326
+ const seen = new Set();
327
+ while (id !== null && !seen.has(id)) {
328
+ if (id === opts.nativeSessionId)
329
+ return true;
330
+ seen.add(id);
331
+ id = byId.get(id)?.parentNativeSessionId ?? null;
332
+ }
333
+ return false;
334
+ };
335
+ const selectedRefs = [];
336
+ for (const ref of refs) {
337
+ if (!selected(ref))
338
+ continue;
339
+ if (opts.cwd) {
340
+ ref.cwd = (await fold(ref, 'summary', {})).cwd;
341
+ if (ref.cwd === null || !withinPath(ref.cwd, opts.cwd))
342
+ continue;
343
+ }
344
+ selectedRefs.push(ref);
345
+ }
346
+ return selectedRefs.sort((a, b) => b.mtimeMs - a.mtimeMs);
236
347
  }
237
348
  export const kimiReader = foldedReader({ harness: HARNESS, aliases: ['kimi', 'kimi-cli'], format: FORMAT, globs: { session: WIRE, children: CHILD_WIRE }, stores: KIMI_STORES }, locate, fold);
238
- export function kimiRefForFile(path) {
239
- const { id, parent } = sessionIdentity(path);
240
- return { harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: parent };
349
+ function refForWire(path, storePath, indices) {
350
+ const { id, parent, root } = sessionIdentity(storePath);
351
+ let owner = parent;
352
+ if (root && id !== root && path === storePath && isAbsolute(path)) {
353
+ const state = join(dirname(dirname(dirname(path))), 'state.json');
354
+ const parents = indices?.get(state) ?? stateParents(state);
355
+ indices?.set(state, parents);
356
+ owner = parents.get(id) ?? null;
357
+ }
358
+ return { harness: HARNESS, format: FORMAT, nativeSessionId: id, path, files: [path], home: null, cwd: null, mtimeMs: 0, parentNativeSessionId: owner };
359
+ }
360
+ export function kimiRefForFile(path, storePath = path) {
361
+ return refForWire(path, storePath);
241
362
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/harness-sessions",
3
- "version": "1.0.13",
3
+ "version": "1.0.14",
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,