@tangle-network/harness-sessions 1.0.12 → 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/README.md CHANGED
@@ -51,6 +51,10 @@ Pi's session-header `parentSession` is fork/clone/handoff lineage; it does not p
51
51
 
52
52
  A bounded local capture inspection on 2026-10-25 found explicit Kimi child events and separate child wires. Its Pi and Factory Droid samples contained no explicit subagent binding: the latest 20 files per harness held 7,724 and 245 records respectively; an additional size-stratified selection read seven Pi files (8,229 records) and 20 Factory files (252 records). These are sample limits, not a claim that every producer version lacks the metadata. The remaining Pi/Factory child coverage is unknown. Closing it requires a retained parent/child capture with an explicit source binding, followed by a reader-to-OTLP integration proof; the graph-corpus integrating owner owns that follow-up.
53
53
 
54
+ For a producer or retained reader with an already attested file inventory, `readBoundHarnessSessions` verifies the exact native root and recorded children through caller-supplied bounded `read`, strict `parse` and `validatePath` callbacks. Optional `nativeSessionIds` binds every observed native conversation across retries; the reader requires all of them and rejects ambiguous roots or cyclic parentage. It checks file digests, byte counts, unique paths, parent attribution, parse integrity and the shared `BOUND_HARNESS_SESSION_READ_LIMITS`. It refuses credential-shaped paths before reading. The path validator is awaited before any read, including asynchronous host confinement checks. The host owns filesystem confinement and must honor the supplied abort signal in its validation and read callbacks; this operation does not discover an ambient HOME, attest an inventory or grant access to files. Runtime's existing entrypoint supplies its archive path policy, abortable read and validation error identity.
55
+
56
+ `locateDeclaredSessionFiles` reuses the sidecar's Linux descriptor-relative inventory for an opened HOME and caller-selected store declarations. It returns held regular-file handles for the declared writer UID; callers close them and own redaction. `readHeldSessionFile` reads bounded bytes from an already-held regular file, checks cancellation and unchanged identity/size/timestamps, and leaves the handle open. `completeLinePrefix` accepts those bytes or a held handle without modifying the source. The entry bound applies per store. Absent optional stores are skipped; unreadable, linked or capped stores remain explicit gaps. Inventory requires Linux `/proc/self/fd`; it does not attest an ambient HOME or secure a path opened by the caller.
57
+
54
58
  ## Use
55
59
 
56
60
  ```ts
@@ -73,6 +77,21 @@ Projections trim; the reader never does:
73
77
  - `toOtlpSpans(session)`: contract spans (`@tangle-network/agent-trace-contract`), one LLM span per model call and one TOOL span per tool call.
74
78
  - `toTurns(session)`: the blog's turns, with the model, usage and error of each assistant turn.
75
79
 
80
+ ### Recorded tool definitions
81
+
82
+ When Claude Code records `prompt_snapshot.tools[*].schema`, the session retains the actual
83
+ names, descriptions and `input_schema` objects in `toolDefinitionSnapshots`. Each model
84
+ response names the inventory already observed when it first appeared through
85
+ `toolDefinitionSnapshotId`. A later snapshot never supplies definitions to an earlier
86
+ response, and a newer snapshot without definitions clears that binding. Malformed or
87
+ duplicate definitions mark their snapshot incomplete without inventing a schema from a call.
88
+ Inventories are stored once; responses reference them, including when many responses share
89
+ the same definitions. Other formats with no recorded definitions leave these optional fields absent.
90
+
91
+ These are chronological observations, not a session-wide union of available tools. A trainer
92
+ format that accepts one static tool inventory for a whole conversation must check that every
93
+ response used that same complete inventory; it cannot apply the latest schema to earlier turns.
94
+
76
95
  For callers that are not JavaScript:
77
96
 
78
97
  ```bash
@@ -0,0 +1,48 @@
1
+ /** One native-family read bound shared by producers and retained readers. */
2
+ export declare const BOUND_HARNESS_SESSION_READ_LIMITS: Readonly<{
3
+ maxFileBytes: number;
4
+ maxTotalBytes: number;
5
+ maxFiles: 1000;
6
+ }>;
7
+ /** Credential-shaped paths are refused even when a producer lists them. */
8
+ export declare const HARNESS_TRANSCRIPT_DENY: RegExp;
9
+ export interface BoundHarnessSession {
10
+ readonly nativeSessionId: string;
11
+ readonly parentNativeSessionId?: string | null;
12
+ readonly children: readonly {
13
+ readonly nativeSessionId: string;
14
+ }[];
15
+ readonly integrity: {
16
+ readonly truncated: boolean;
17
+ readonly unparsedRecords: number;
18
+ readonly gaps: readonly unknown[];
19
+ };
20
+ }
21
+ export interface HarnessFileBinding {
22
+ readonly path: string;
23
+ readonly nativeSessionId: string;
24
+ readonly sha256?: string;
25
+ readonly byteLength?: number;
26
+ }
27
+ /** Verify a bound native family without owning a store, filesystem layout or native parser. */
28
+ export declare function readBoundHarnessSessions<S extends BoundHarnessSession>(input: {
29
+ readonly nativeSessionId: string;
30
+ /** Every native conversation observed for this execution, in execution order. */
31
+ readonly nativeSessionIds?: readonly string[];
32
+ readonly files: readonly HarnessFileBinding[];
33
+ readonly read: (file: HarnessFileBinding, signal?: AbortSignal) => Promise<Uint8Array>;
34
+ readonly parse: (text: string, file: HarnessFileBinding) => S;
35
+ readonly signal?: AbortSignal;
36
+ /** Host-owned relative-path policy, applied before any read. */
37
+ readonly validatePath: (path: string, signal?: AbortSignal) => void | Promise<void>;
38
+ /** Compatibility error identity remains with the execution owner. */
39
+ readonly failure?: (message: string) => Error;
40
+ }): Promise<{
41
+ files: {
42
+ path: string;
43
+ nativeSessionId: string;
44
+ sha256: string;
45
+ byteLength: number;
46
+ }[];
47
+ sessions: S[];
48
+ }>;
@@ -0,0 +1,89 @@
1
+ import { sha256Hex } from '@tangle-network/agent-core/node';
2
+ /** One native-family read bound shared by producers and retained readers. */
3
+ export const BOUND_HARNESS_SESSION_READ_LIMITS = Object.freeze({
4
+ maxFileBytes: 2 * 1024 * 1024,
5
+ maxTotalBytes: 16 * 1024 * 1024,
6
+ maxFiles: 1_000,
7
+ });
8
+ /** Credential-shaped paths are refused even when a producer lists them. */
9
+ export const HARNESS_TRANSCRIPT_DENY = /(^|\/)(auth\.json|\.credentials\.json|credentials|\.netrc|\.env(\..*)?|secrets?(\.|$)|.*\.(pem|key|p12|pfx)|id_[a-z0-9_]+)$/iu;
10
+ /** Verify a bound native family without owning a store, filesystem layout or native parser. */
11
+ export async function readBoundHarnessSessions(input) {
12
+ const files = [];
13
+ const sessions = new Map();
14
+ const parents = new Map();
15
+ const paths = new Set();
16
+ const invalid = input.failure ?? ((message) => new Error(message));
17
+ const roots = input.nativeSessionIds ?? [input.nativeSessionId];
18
+ if (!roots.length || roots.length > BOUND_HARNESS_SESSION_READ_LIMITS.maxFiles ||
19
+ roots.some(id => !id) || new Set(roots).size !== roots.length ||
20
+ !roots.includes(input.nativeSessionId))
21
+ throw invalid('Native capture has ambiguous root session identities');
22
+ const pending = [...roots];
23
+ let total = 0;
24
+ while (pending.length) {
25
+ const id = pending.shift();
26
+ if (sessions.has(id))
27
+ continue;
28
+ const candidates = input.files.filter((file) => file.nativeSessionId === id);
29
+ if (!candidates.length)
30
+ throw invalid('The exact native session or a recorded child was not retained');
31
+ for (const file of candidates) {
32
+ input.signal?.throwIfAborted();
33
+ if (files.length >= BOUND_HARNESS_SESSION_READ_LIMITS.maxFiles)
34
+ throw invalid('Native file count exceeds the capture bound');
35
+ await input.validatePath(file.path, input.signal);
36
+ input.signal?.throwIfAborted();
37
+ if (HARNESS_TRANSCRIPT_DENY.test(file.path) || paths.has(file.path))
38
+ throw invalid('Native file path is denied or repeated');
39
+ paths.add(file.path);
40
+ const bytes = await input.read(file, input.signal);
41
+ total += bytes.byteLength;
42
+ if (bytes.byteLength > BOUND_HARNESS_SESSION_READ_LIMITS.maxFileBytes ||
43
+ total > BOUND_HARNESS_SESSION_READ_LIMITS.maxTotalBytes)
44
+ throw invalid('Native bytes exceed the capture bound');
45
+ const actual = `sha256:${sha256Hex(bytes)}`;
46
+ if ((file.sha256 && file.sha256.replace(/^sha256:/, '') !== actual.slice(7)) ||
47
+ (file.byteLength !== undefined && file.byteLength !== bytes.byteLength))
48
+ throw invalid('Captured native session bytes changed');
49
+ const session = input.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes), file);
50
+ if (session.nativeSessionId !== id ||
51
+ session.integrity.truncated ||
52
+ session.integrity.unparsedRecords ||
53
+ session.integrity.gaps.length)
54
+ throw invalid('Native session identity or integrity did not match its binding');
55
+ if (session.parentNativeSessionId &&
56
+ parents.has(id) &&
57
+ session.parentNativeSessionId !== parents.get(id))
58
+ throw invalid('Native child has a different recorded parent');
59
+ const prior = files.find((value) => value.nativeSessionId === id);
60
+ if (prior && prior.sha256 !== actual)
61
+ throw invalid('Native session copies are ambiguous');
62
+ files.push({
63
+ path: file.path,
64
+ nativeSessionId: id,
65
+ sha256: actual,
66
+ byteLength: bytes.byteLength,
67
+ });
68
+ if (!prior)
69
+ sessions.set(id, session);
70
+ }
71
+ for (const child of sessions.get(id).children) {
72
+ if (parents.has(child.nativeSessionId) && parents.get(child.nativeSessionId) !== id)
73
+ throw invalid('Native child has ambiguous recorded parents');
74
+ const recordedChild = sessions.get(child.nativeSessionId);
75
+ if (recordedChild?.parentNativeSessionId && recordedChild.parentNativeSessionId !== id)
76
+ throw invalid('Native child has a different recorded parent');
77
+ let ancestor = id;
78
+ while (ancestor !== undefined) {
79
+ if (ancestor === child.nativeSessionId)
80
+ throw invalid('Native child has a cyclic recorded parent');
81
+ ancestor = parents.get(ancestor);
82
+ }
83
+ parents.set(child.nativeSessionId, id);
84
+ if (!sessions.has(child.nativeSessionId))
85
+ pending.push(child.nativeSessionId);
86
+ }
87
+ }
88
+ return { files, sessions: [...sessions.values()] };
89
+ }
package/dist/builder.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { HarnessSession, ModelCall, Part, SessionEnding, SessionError, SessionFormatId, SessionMessage, SessionSummary, TokenUsage } from './schema.js';
1
+ import type { HarnessSession, ModelCall, Part, SessionEnding, SessionError, SessionFormatId, SessionMessage, SessionSummary, SessionToolDefinitionSnapshot, TokenUsage } from './schema.js';
2
2
  import type { SourceStats } from './source.js';
3
3
  export type BuildMode = 'full' | 'summary';
4
4
  export declare function isoTime(value: unknown): string | null;
@@ -33,6 +33,7 @@ export declare class SessionBuilder {
33
33
  private replies;
34
34
  readonly modelCalls: ModelCall[];
35
35
  private readonly modelCallById;
36
+ private readonly toolDefinitionSnapshots;
36
37
  private readonly children;
37
38
  private readonly gaps;
38
39
  private readonly sources;
@@ -65,6 +66,7 @@ export declare class SessionBuilder {
65
66
  }): void;
66
67
  modelCall(call: ModelCall): ModelCall;
67
68
  getModelCall(id: string): ModelCall | undefined;
69
+ toolDefinitionSnapshot(snapshot: SessionToolDefinitionSnapshot): void;
68
70
  child(nativeSessionId: string, toolCallId: string | null): void;
69
71
  gap(text: string): void;
70
72
  source(stats: SourceStats | {
package/dist/builder.js CHANGED
@@ -81,6 +81,7 @@ export class SessionBuilder {
81
81
  replies = 0;
82
82
  modelCalls = [];
83
83
  modelCallById = new Map();
84
+ toolDefinitionSnapshots = [];
84
85
  children = [];
85
86
  gaps = [];
86
87
  sources = [];
@@ -179,6 +180,10 @@ export class SessionBuilder {
179
180
  getModelCall(id) {
180
181
  return this.modelCallById.get(id);
181
182
  }
183
+ toolDefinitionSnapshot(snapshot) {
184
+ if (this.full)
185
+ this.toolDefinitionSnapshots.push(snapshot);
186
+ }
182
187
  child(nativeSessionId, toolCallId) {
183
188
  if (this.children.some((c) => c.nativeSessionId === nativeSessionId))
184
189
  return;
@@ -264,6 +269,7 @@ export class SessionBuilder {
264
269
  messages: this.messages,
265
270
  toolCalls,
266
271
  modelCalls: this.modelCalls,
272
+ ...(this.toolDefinitionSnapshots.length ? { toolDefinitionSnapshots: this.toolDefinitionSnapshots } : {}),
267
273
  servedModels: this.servedModels(),
268
274
  modelSource: this.modelSource,
269
275
  usage: this.usage(),
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). */
@@ -0,0 +1,33 @@
1
+ import { type FileHandle } from 'node:fs/promises';
2
+ export interface DeclaredSessionStore<Store> {
3
+ store: Store;
4
+ /** Normalized, nonempty POSIX path relative to the opened HOME. */
5
+ root: string;
6
+ matches(relative: string): boolean;
7
+ }
8
+ export interface DeclaredSessionFile<Store> {
9
+ store: Store;
10
+ /** Relative to the opened HOME. */
11
+ path: string;
12
+ /** Caller closes every returned handle; no link was followed and the writer UID matched. */
13
+ handle: FileHandle;
14
+ }
15
+ /**
16
+ * Linux descriptor-relative traversal extracted from the sidecar settled-copy path.
17
+ * No ambient HOME discovery or path opening authority is inferred. The caller opens
18
+ * and closes `home`, selects declarations and writer UID, and owns the entry ceiling.
19
+ */
20
+ export declare function locateDeclaredSessionFiles<Store>(input: {
21
+ home: FileHandle;
22
+ stores: readonly DeclaredSessionStore<Store>[];
23
+ uid: number;
24
+ maxEntries: number;
25
+ signal?: AbortSignal;
26
+ }): Promise<{
27
+ files: DeclaredSessionFile<Store>[];
28
+ rejected: string[];
29
+ }>;
30
+ /** Bounded stable bytes from an already-held regular file; the caller keeps path/ownership and handle lifetime. */
31
+ export declare function readHeldSessionFile(handle: FileHandle, maxBytes: number, signal?: AbortSignal): Promise<Buffer>;
32
+ /** Length of the prefix of the first `limit` bytes that ends on a newline. Does not modify the source. */
33
+ export declare function completeLinePrefix(source: FileHandle | Uint8Array, limit: number): Promise<number>;
@@ -0,0 +1,177 @@
1
+ /** Descriptor-relative native-store inventory. The host owns the root handle and writer policy. */
2
+ import { constants } from 'node:fs';
3
+ import { open, readdir } from 'node:fs/promises';
4
+ const DIRECTORY_FLAGS = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
5
+ const FILE_FLAGS = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
6
+ const inDirectory = (handle, name) => `/proc/self/fd/${handle.fd}${name === undefined ? '' : `/${name}`}`;
7
+ async function openDirectoryPath(parent, relative) {
8
+ let current = parent;
9
+ for (const name of relative.split('/')) {
10
+ let next;
11
+ try {
12
+ next = await open(inDirectory(current, name), DIRECTORY_FLAGS);
13
+ }
14
+ catch (error) {
15
+ if (current !== parent)
16
+ await current.close();
17
+ if (error.code === 'ENOENT')
18
+ return undefined;
19
+ throw error;
20
+ }
21
+ if (current !== parent)
22
+ await current.close();
23
+ current = next;
24
+ }
25
+ return current;
26
+ }
27
+ /**
28
+ * Linux descriptor-relative traversal extracted from the sidecar settled-copy path.
29
+ * No ambient HOME discovery or path opening authority is inferred. The caller opens
30
+ * and closes `home`, selects declarations and writer UID, and owns the entry ceiling.
31
+ */
32
+ export async function locateDeclaredSessionFiles(input) {
33
+ if (process.platform !== 'linux')
34
+ throw new Error('Descriptor-relative native-store inventory requires Linux /proc/self/fd');
35
+ if (!Number.isSafeInteger(input.maxEntries) || input.maxEntries < 1)
36
+ throw new Error('Native-store entry ceiling must be a positive safe integer');
37
+ if (!Number.isSafeInteger(input.uid) || input.uid < 0)
38
+ throw new Error('Native-store writer UID must be a nonnegative safe integer');
39
+ for (const { root } of input.stores) {
40
+ if (!root || root.includes('\\') || root.includes('\0') || root.split('/').some((part) => !part || part === '.' || part === '..')) {
41
+ throw new Error('Native-store root must be a normalized relative POSIX path');
42
+ }
43
+ }
44
+ const found = [];
45
+ const rejected = [];
46
+ const owner = await input.home.stat();
47
+ if (!owner.isDirectory())
48
+ throw new Error('Native-store HOME handle must name a directory');
49
+ try {
50
+ for (const declaration of input.stores) {
51
+ input.signal?.throwIfAborted();
52
+ const { root, store } = declaration;
53
+ let rootHandle;
54
+ try {
55
+ rootHandle = await openDirectoryPath(input.home, root);
56
+ }
57
+ catch {
58
+ rejected.push(`store_directory_unreadable:${root}`);
59
+ continue;
60
+ }
61
+ // Declared alternative stores need not exist yet; an absent archive is not a missing session.
62
+ if (!rootHandle)
63
+ continue;
64
+ const pending = [{ handle: rootHandle, relative: '' }];
65
+ let visited = 0;
66
+ let capped = false;
67
+ try {
68
+ while (pending.length > 0) {
69
+ const { handle: directory, relative } = pending.pop();
70
+ try {
71
+ input.signal?.throwIfAborted();
72
+ if (visited >= input.maxEntries) {
73
+ capped = true;
74
+ continue;
75
+ }
76
+ let entries;
77
+ try {
78
+ entries = await readdir(inDirectory(directory), { withFileTypes: true });
79
+ }
80
+ catch {
81
+ rejected.push(`store_directory_unreadable:${root}/${relative}`);
82
+ continue;
83
+ }
84
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
85
+ input.signal?.throwIfAborted();
86
+ if (visited >= input.maxEntries) {
87
+ capped = true;
88
+ break;
89
+ }
90
+ visited++;
91
+ const child = relative ? `${relative}/${entry.name}` : entry.name;
92
+ if (entry.isDirectory()) {
93
+ const opened = await open(inDirectory(directory, entry.name), DIRECTORY_FLAGS).catch(() => undefined);
94
+ if (opened)
95
+ pending.push({ handle: opened, relative: child });
96
+ else
97
+ rejected.push(`store_directory_unreadable:${root}/${child}`);
98
+ }
99
+ else if (declaration.matches(child)) {
100
+ const path = `${root}/${child}`;
101
+ if (!entry.isFile()) {
102
+ rejected.push(`store_file_not_regular:${path}`);
103
+ continue;
104
+ }
105
+ const opened = await open(inDirectory(directory, entry.name), FILE_FLAGS).catch(() => undefined);
106
+ if (!opened) {
107
+ rejected.push(`store_file_unreadable:${path}`);
108
+ continue;
109
+ }
110
+ const stats = await opened.stat().catch(() => undefined);
111
+ if (!stats?.isFile() || stats.uid !== input.uid) {
112
+ await opened.close();
113
+ rejected.push(`store_file_not_owned:${path}${stats ? ` file_uid=${stats.uid} file_gid=${stats.gid} expected_uid=${input.uid} home_uid=${owner.uid} nlink=${stats.nlink}` : ''}`);
114
+ continue;
115
+ }
116
+ found.push({ store, path, handle: opened });
117
+ }
118
+ }
119
+ }
120
+ finally {
121
+ await directory.close();
122
+ }
123
+ }
124
+ }
125
+ finally {
126
+ await Promise.all(pending.splice(0).map((item) => item.handle.close()));
127
+ }
128
+ if (capped)
129
+ rejected.push(`store_entries_capped:${root}`);
130
+ }
131
+ return { files: found.sort((a, b) => a.path.localeCompare(b.path)), rejected };
132
+ }
133
+ catch (error) {
134
+ await Promise.all(found.map((file) => file.handle.close()));
135
+ throw error;
136
+ }
137
+ }
138
+ /** Bounded stable bytes from an already-held regular file; the caller keeps path/ownership and handle lifetime. */
139
+ export async function readHeldSessionFile(handle, maxBytes, signal) {
140
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0)
141
+ throw new Error('Native-store byte ceiling must be a nonnegative safe integer');
142
+ signal?.throwIfAborted();
143
+ const before = await handle.stat();
144
+ if (!before.isFile() || !Number.isSafeInteger(before.size) || before.size > maxBytes)
145
+ throw new Error('Native source is not a bounded regular file');
146
+ const bytes = Buffer.alloc(before.size);
147
+ for (let offset = 0; offset < bytes.length;) {
148
+ signal?.throwIfAborted();
149
+ const { bytesRead } = await handle.read(bytes, offset, bytes.length - offset, offset);
150
+ if (!bytesRead)
151
+ throw new Error('Native source ended before its held size');
152
+ offset += bytesRead;
153
+ }
154
+ const after = await handle.stat();
155
+ signal?.throwIfAborted();
156
+ if (!after.isFile() || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size ||
157
+ before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs)
158
+ throw new Error('Native source changed during held read');
159
+ return bytes;
160
+ }
161
+ /** Length of the prefix of the first `limit` bytes that ends on a newline. Does not modify the source. */
162
+ export async function completeLinePrefix(source, limit) {
163
+ if (!Number.isSafeInteger(limit) || limit < 0)
164
+ throw new Error('Native-store byte ceiling must be a nonnegative safe integer');
165
+ if (source instanceof Uint8Array)
166
+ return Buffer.from(source).subarray(0, limit).lastIndexOf(0x0a) + 1;
167
+ const window = Buffer.allocUnsafe(64 * 1024);
168
+ for (let end = limit; end > 0;) {
169
+ const start = Math.max(0, end - window.length);
170
+ const { bytesRead } = await source.read(window, 0, end - start, start);
171
+ const newline = window.subarray(0, bytesRead).lastIndexOf(0x0a);
172
+ if (newline >= 0)
173
+ return start + newline + 1;
174
+ end = start;
175
+ }
176
+ return 0;
177
+ }
@@ -35,6 +35,7 @@ export function createFold(ref, mode, stats) {
35
35
  let aborted = null;
36
36
  let errors = 0;
37
37
  let identified = false;
38
+ let toolDefinitionSnapshotId;
38
39
  const seenUuids = new Set();
39
40
  const observe = (record) => {
40
41
  if (!subagent && record.isSidechain === true) {
@@ -69,6 +70,34 @@ export function createFold(ref, mode, stats) {
69
70
  // A queued command is a message sent while the turn ran, so it is a prompt.
70
71
  const attachment = isRecord(record.attachment) ? record.attachment : {};
71
72
  const kind = str(attachment.type) ?? 'attachment';
73
+ if (kind === 'prompt_snapshot') {
74
+ // Only this producer-recorded inventory establishes exposure. A newer snapshot
75
+ // without definitions clears the prior inventory rather than assuming it survived.
76
+ toolDefinitionSnapshotId = undefined;
77
+ if (Object.hasOwn(attachment, 'tools')) {
78
+ const definitions = [];
79
+ const names = new Set();
80
+ let complete = Array.isArray(attachment.tools);
81
+ for (const tool of Array.isArray(attachment.tools) ? attachment.tools : []) {
82
+ const schema = isRecord(tool) && isRecord(tool.schema) ? tool.schema : null;
83
+ const name = schema === null ? null : str(schema.name);
84
+ if (!name || !schema || !isRecord(schema.input_schema) ||
85
+ (tool.name !== undefined && tool.name !== name) || names.has(name) ||
86
+ (schema.description !== undefined && typeof schema.description !== 'string')) {
87
+ complete = false;
88
+ continue;
89
+ }
90
+ names.add(name);
91
+ definitions.push({
92
+ name,
93
+ ...(typeof schema.description === 'string' ? { description: schema.description } : {}),
94
+ inputSchema: schema.input_schema,
95
+ });
96
+ }
97
+ toolDefinitionSnapshotId = uuid;
98
+ builder.toolDefinitionSnapshot({ id: uuid, at, source: kind, definitions, complete });
99
+ }
100
+ }
72
101
  const queued = kind === 'queued_command' ? textOf(attachment.prompt) : null;
73
102
  if (queued !== null) {
74
103
  const typed = attachment.commandMode === 'prompt' && !machine(queued);
@@ -180,7 +209,7 @@ export function createFold(ref, mode, stats) {
180
209
  builder.appendParts(apiId, parts);
181
210
  return;
182
211
  }
183
- builder.modelCall({ id: apiId, at, provider: null, servedModel: model, requestedModel: null, usage: usageOf(message.usage), costUsd: null, stopReason: str(message.stop_reason), error: null });
212
+ builder.modelCall({ id: apiId, at, provider: null, servedModel: model, requestedModel: null, usage: usageOf(message.usage), costUsd: null, stopReason: str(message.stop_reason), error: null, ...(toolDefinitionSnapshotId === undefined ? {} : { toolDefinitionSnapshotId }) });
184
213
  builder.message({ id: apiId, role: 'assistant', actor: 'agent', at, modelCallId: apiId, parts });
185
214
  };
186
215
  const finish = () => {
@@ -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/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { HarnessSession, HarnessSessionReader, LocateOptions, ModelCall, NativeSessionCopy, NativeSessionStore, Part, RawEvidenceArchiveManifestV2, ReadOptions, SessionEnding, SessionError, SessionEvidenceSources, SessionFormatId, SessionIntegrity, SessionMessage, SessionRef, SessionSummary, SessionToolCall, TokenUsage, } from './schema.js';
1
+ export type { HarnessSession, HarnessSessionReader, LocateOptions, ModelCall, NativeSessionCopy, NativeSessionStore, Part, RawEvidenceArchiveManifestV2, ReadOptions, SessionEnding, SessionError, SessionEvidenceSources, SessionFormatId, SessionIntegrity, SessionMessage, SessionRef, SessionSummary, SessionToolCall, SessionToolDefinition, SessionToolDefinitionSnapshot, TokenUsage, } from './schema.js';
2
2
  export { HARNESS_SESSION_SCHEMA } from './schema.js';
3
3
  export { CLAUDE_CODE_STORES, CODEX_HOME_RULE, CODEX_STORES, EVIDENCE, KIMI_STORES, SESSION_FORMAT_IDS, STORES, assertStoreRoot, isCodexHome, storeGlob, withinPath } from './catalog.js';
4
4
  export { codexHomes } from './stores.js';
@@ -23,3 +23,5 @@ export { toChatMessages, type ChatMessage, type ChatProjectionOptions, type Chat
23
23
  export { primaryModel, summarizeText, toTurns, type Turn, type TurnOptions, type TurnToolCall } from './projections/turns.js';
24
24
  export { toOtlpSpans, type OtlpProjectionOptions } from './projections/otlp.js';
25
25
  export { readSessionInput, summarizeSessionInput, type SessionInput, type SessionInputInit } from './input.js';
26
+ export { readBoundHarnessSessions, BOUND_HARNESS_SESSION_READ_LIMITS, HARNESS_TRANSCRIPT_DENY, type BoundHarnessSession, type HarnessFileBinding, } from './bounded-family.js';
27
+ export { completeLinePrefix, locateDeclaredSessionFiles, readHeldSessionFile, type DeclaredSessionFile, type DeclaredSessionStore } from './declared-files.js';
package/dist/index.js CHANGED
@@ -22,3 +22,5 @@ export { toChatMessages } from './projections/chat.js';
22
22
  export { primaryModel, summarizeText, toTurns } from './projections/turns.js';
23
23
  export { toOtlpSpans } from './projections/otlp.js';
24
24
  export { readSessionInput, summarizeSessionInput } from './input.js';
25
+ export { readBoundHarnessSessions, BOUND_HARNESS_SESSION_READ_LIMITS, HARNESS_TRANSCRIPT_DENY, } from './bounded-family.js';
26
+ export { completeLinePrefix, locateDeclaredSessionFiles, readHeldSessionFile } from './declared-files.js';
package/dist/schema.d.ts CHANGED
@@ -83,6 +83,22 @@ export interface ModelCall {
83
83
  costUsd: number | null;
84
84
  stopReason: string | null;
85
85
  error: SessionError | null;
86
+ /** Source inventory already observed when this response first appeared; never backfilled. */
87
+ toolDefinitionSnapshotId?: string;
88
+ }
89
+ export interface SessionToolDefinition {
90
+ name: string;
91
+ description?: string;
92
+ inputSchema: Record<string, unknown>;
93
+ }
94
+ /** A recorded tool inventory, kept once even when many responses use it. */
95
+ export interface SessionToolDefinitionSnapshot {
96
+ id: string;
97
+ at: string | null;
98
+ source: string;
99
+ definitions: SessionToolDefinition[];
100
+ /** False when the source declares tools but one or more definitions cannot be read. */
101
+ complete: boolean;
86
102
  }
87
103
  export interface SessionEnding {
88
104
  status: 'completed' | 'error' | 'aborted' | 'open';
@@ -111,6 +127,8 @@ export interface HarnessSession {
111
127
  messages: SessionMessage[];
112
128
  toolCalls: SessionToolCall[];
113
129
  modelCalls: ModelCall[];
130
+ /** Absent when this native format/capture did not record actual tool definitions. */
131
+ toolDefinitionSnapshots?: SessionToolDefinitionSnapshot[];
114
132
  servedModels: Record<string, number>;
115
133
  modelSource: SessionEvidenceSources['servedModel'];
116
134
  usage: TokenUsage | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/harness-sessions",
3
- "version": "1.0.12",
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,