@tangle-network/harness-sessions 1.0.12 → 1.0.13
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 +19 -0
- package/dist/bounded-family.d.ts +48 -0
- package/dist/bounded-family.js +89 -0
- package/dist/builder.d.ts +3 -1
- package/dist/builder.js +6 -0
- package/dist/declared-files.d.ts +33 -0
- package/dist/declared-files.js +177 -0
- package/dist/formats/claude-code.js +30 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -0
- package/dist/schema.d.ts +18 -0
- package/package.json +1 -1
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(),
|
|
@@ -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 = () => {
|
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.
|
|
3
|
+
"version": "1.0.13",
|
|
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,
|