@bli-cockpit/telemetry-core 0.1.96 → 0.1.98
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/agent-artifacts.d.ts +3 -0
- package/dist/agent-artifacts.js +1 -1
- package/dist/codex-record-copies.d.ts +7 -0
- package/dist/codex-record-copies.js +58 -0
- package/dist/evidence-completeness.d.ts +2 -2
- package/dist/evidence-rules-fingerprint.js +2 -1
- package/dist/evidence-stubs.d.ts +1 -1
- package/dist/evidence-stubs.js +2 -2
- package/dist/evidence-transcripts.d.ts +1 -1
- package/dist/evidence-transcripts.js +2 -2
- package/dist/evidence-upload.d.ts +72 -0
- package/dist/evidence-upload.js +1 -1
- package/dist/image-byte-scan.js +5 -5
- package/dist/image-descriptions.d.ts +4 -1
- package/dist/image-descriptions.js +3 -1
- package/dist/image-store.d.ts +1 -0
- package/dist/image-store.js +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/ingest-dto.d.ts +2 -2
- package/dist/local-config.d.ts +1 -1
- package/dist/opencode-transcript.d.ts +9 -0
- package/dist/opencode-transcript.js +97 -0
- package/dist/pi-transcript-extract.d.ts +58 -0
- package/dist/pi-transcript-extract.js +56 -0
- package/dist/pi-transcript-lineage.d.ts +14 -0
- package/dist/pi-transcript-lineage.js +20 -0
- package/dist/pi-transcript-usage.d.ts +27 -0
- package/dist/pi-transcript-usage.js +31 -0
- package/dist/pi-transcript.d.ts +38 -0
- package/dist/pi-transcript.js +105 -0
- package/dist/session-facts-delta.d.ts +3 -0
- package/dist/session-facts-delta.js +11 -0
- package/dist/session-facts-hands-on.d.ts +98 -0
- package/dist/session-facts-hands-on.js +208 -0
- package/dist/session-facts-schema.d.ts +109 -0
- package/dist/session-facts-schema.js +63 -0
- package/dist/session-facts-spawn.d.ts +2 -1
- package/dist/session-facts-spawn.js +3 -1
- package/dist/session-facts-usage-math.d.ts +6 -0
- package/dist/session-facts-usage-math.js +27 -0
- package/dist/session-facts.d.ts +24 -108
- package/dist/session-facts.js +38 -88
- package/dist/shelf.d.ts +28 -16
- package/dist/shelf.js +18 -8
- package/dist/t3-projection-message.d.ts +39 -0
- package/dist/t3-projection-message.js +125 -0
- package/dist/transcript-images.js +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/** Stream Pi normalization alongside complete evidence; parse failures do not withhold native bytes. */
|
|
2
|
+
import { type PiTranscriptFacts } from './pi-transcript.js';
|
|
3
|
+
import { type PiUsageDecision, type PiUsageLedger } from './pi-transcript-usage.js';
|
|
4
|
+
export type PiTranscriptEvent = {
|
|
5
|
+
kind: 'record';
|
|
6
|
+
offset: number;
|
|
7
|
+
raw: Uint8Array;
|
|
8
|
+
value: unknown;
|
|
9
|
+
valid: boolean;
|
|
10
|
+
} | {
|
|
11
|
+
kind: 'partial';
|
|
12
|
+
offset: number;
|
|
13
|
+
raw: Uint8Array;
|
|
14
|
+
} | {
|
|
15
|
+
kind: 'revision';
|
|
16
|
+
revision: string;
|
|
17
|
+
bytes: number;
|
|
18
|
+
records: number;
|
|
19
|
+
invalidRecords: number;
|
|
20
|
+
partialBytes: number;
|
|
21
|
+
stable: boolean;
|
|
22
|
+
changed: boolean | null;
|
|
23
|
+
};
|
|
24
|
+
export interface PiExtractedTranscript {
|
|
25
|
+
facts: PiTranscriptFacts;
|
|
26
|
+
revision: Extract<PiTranscriptEvent, {
|
|
27
|
+
kind: 'revision';
|
|
28
|
+
}> | null;
|
|
29
|
+
evidence_bytes: number;
|
|
30
|
+
/** Tentative derived ownership; caller must reconcile/promote only after durable evidence ack. */
|
|
31
|
+
usage_owner_candidates: PiUsageLedger;
|
|
32
|
+
evidence_observation_complete: boolean;
|
|
33
|
+
normalization_complete: boolean;
|
|
34
|
+
reasons: string[];
|
|
35
|
+
}
|
|
36
|
+
export interface PiEntryIdentity {
|
|
37
|
+
type: string | null;
|
|
38
|
+
id: string | null;
|
|
39
|
+
parentId: string | null;
|
|
40
|
+
toolCallIds: string[];
|
|
41
|
+
toolResultId: string | null;
|
|
42
|
+
}
|
|
43
|
+
/** No durable cursor is advanced here; acknowledgment belongs to the existing shared transport. */
|
|
44
|
+
export declare function extractPiTranscript(events: AsyncIterable<PiTranscriptEvent>, options: {
|
|
45
|
+
/** Every raw record/tail must go through the shared redactor, even if normalization fails. */
|
|
46
|
+
onEvidence: (event: Exclude<PiTranscriptEvent, {
|
|
47
|
+
kind: 'revision';
|
|
48
|
+
}>) => void | Promise<void>;
|
|
49
|
+
onEntry?: (entry: PiEntryIdentity) => void | Promise<void>;
|
|
50
|
+
/** Only use this callback on redacted input when persisting text for analysis. */
|
|
51
|
+
onTurn?: (turn: {
|
|
52
|
+
role: 'user' | 'assistant';
|
|
53
|
+
text: string;
|
|
54
|
+
entryId: string | null;
|
|
55
|
+
}) => void | Promise<void>;
|
|
56
|
+
onUsage?: (decision: PiUsageDecision) => void | Promise<void>;
|
|
57
|
+
ledger?: PiUsageLedger;
|
|
58
|
+
}): Promise<PiExtractedTranscript>;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Stream Pi normalization alongside complete evidence; parse failures do not withhold native bytes. */
|
|
2
|
+
import { newPiTranscriptAccumulator, observePiTranscriptRecord, piTurnText } from './pi-transcript.js';
|
|
3
|
+
import { piObject, piString } from './pi-transcript-usage.js';
|
|
4
|
+
/** No durable cursor is advanced here; acknowledgment belongs to the existing shared transport. */
|
|
5
|
+
export async function extractPiTranscript(events, options) {
|
|
6
|
+
const acc = newPiTranscriptAccumulator(options.ledger);
|
|
7
|
+
const reasons = new Set();
|
|
8
|
+
let revision = null, bytes = 0, records = 0, invalidRecords = 0, partialBytes = 0;
|
|
9
|
+
for await (const event of events) {
|
|
10
|
+
if (event.kind === 'revision') {
|
|
11
|
+
revision = event;
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
await options.onEvidence(event);
|
|
15
|
+
if (event.offset !== bytes)
|
|
16
|
+
reasons.add('pi_evidence_offset_mismatch');
|
|
17
|
+
bytes += event.raw.byteLength;
|
|
18
|
+
if (event.kind === 'partial') {
|
|
19
|
+
partialBytes += event.raw.byteLength;
|
|
20
|
+
reasons.add('pi_partial_native_record');
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
records++;
|
|
24
|
+
if (!event.valid) {
|
|
25
|
+
invalidRecords++;
|
|
26
|
+
reasons.add('pi_malformed_native_record');
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
const record = piObject(event.value), message = piObject(record.message);
|
|
30
|
+
const decision = observePiTranscriptRecord(acc, record);
|
|
31
|
+
const content = Array.isArray(message.content) ? message.content.map(piObject) : [];
|
|
32
|
+
await options.onEntry?.({ type: piString(record.type), id: piString(record.id), parentId: piString(record.parentId),
|
|
33
|
+
toolCallIds: content.filter(block => block.type === 'toolCall').flatMap(block => piString(block.id) ? [String(block.id)] : []), toolResultId: piString(message.toolCallId) });
|
|
34
|
+
if (decision)
|
|
35
|
+
await options.onUsage?.(decision);
|
|
36
|
+
for (const role of ['user', 'assistant']) {
|
|
37
|
+
const text = piTurnText(record, role);
|
|
38
|
+
if (text !== null)
|
|
39
|
+
await options.onTurn?.({ role, text, entryId: piString(record.id) });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (!revision)
|
|
43
|
+
reasons.add('pi_revision_receipt_missing');
|
|
44
|
+
if (revision && !revision.stable)
|
|
45
|
+
reasons.add('pi_source_changed_during_read');
|
|
46
|
+
if (revision && (revision.bytes !== bytes || revision.records !== records || revision.invalidRecords !== invalidRecords || revision.partialBytes !== partialBytes))
|
|
47
|
+
reasons.add('pi_evidence_receipt_mismatch');
|
|
48
|
+
if (!acc.facts.session_id)
|
|
49
|
+
reasons.add('pi_session_header_missing');
|
|
50
|
+
if (acc.facts.version !== 3)
|
|
51
|
+
reasons.add('pi_format_version_unverified');
|
|
52
|
+
if (acc.facts.unknown_record_count)
|
|
53
|
+
reasons.add('pi_unknown_native_record');
|
|
54
|
+
const evidenceComplete = Boolean(revision?.stable && revision.bytes === bytes && revision.records === records && !reasons.has('pi_evidence_offset_mismatch') && !reasons.has('pi_evidence_receipt_mismatch'));
|
|
55
|
+
return { facts: acc.facts, revision, usage_owner_candidates: acc.ledger, evidence_bytes: bytes, evidence_observation_complete: evidenceComplete, normalization_complete: evidenceComplete && reasons.size === 0, reasons: [...reasons] };
|
|
56
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Pi forks preserve entry IDs; only an explicitly resolved ancestor can establish copied entries. */
|
|
2
|
+
export interface PiSessionLineage {
|
|
3
|
+
sessionId: string;
|
|
4
|
+
parentSessionId: string | null;
|
|
5
|
+
/** Hash the complete native entry payload, excluding parentId which Pi can rechain when removing labels. */
|
|
6
|
+
entryPayloadHashes: ReadonlyMap<string, string>;
|
|
7
|
+
}
|
|
8
|
+
export type PiEntryOrigin = {
|
|
9
|
+
status: 'new' | 'copied' | 'divergent' | 'unknown';
|
|
10
|
+
ancestorSessionId: string | null;
|
|
11
|
+
reason: string;
|
|
12
|
+
};
|
|
13
|
+
/** Parent paths must resolve to observed native headers before calling this; text/title matching is forbidden. */
|
|
14
|
+
export declare function resolvePiEntryOrigin(session: PiSessionLineage, entryId: string, payloadHash: string, sessions: ReadonlyMap<string, PiSessionLineage>): PiEntryOrigin;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Parent paths must resolve to observed native headers before calling this; text/title matching is forbidden. */
|
|
2
|
+
export function resolvePiEntryOrigin(session, entryId, payloadHash, sessions) {
|
|
3
|
+
const visited = new Set([session.sessionId]);
|
|
4
|
+
let parentId = session.parentSessionId;
|
|
5
|
+
while (parentId !== null) {
|
|
6
|
+
if (visited.has(parentId))
|
|
7
|
+
return { status: 'unknown', ancestorSessionId: null, reason: 'pi_lineage_cycle' };
|
|
8
|
+
visited.add(parentId);
|
|
9
|
+
const parent = sessions.get(parentId);
|
|
10
|
+
if (!parent)
|
|
11
|
+
return { status: 'unknown', ancestorSessionId: null, reason: 'pi_parent_session_unavailable' };
|
|
12
|
+
const inherited = parent.entryPayloadHashes.get(entryId);
|
|
13
|
+
if (inherited !== undefined)
|
|
14
|
+
return inherited === payloadHash
|
|
15
|
+
? { status: 'copied', ancestorSessionId: parent.sessionId, reason: 'pi_exact_ancestor_entry' }
|
|
16
|
+
: { status: 'divergent', ancestorSessionId: parent.sessionId, reason: 'pi_ancestor_entry_payload_differs' };
|
|
17
|
+
parentId = parent.parentSessionId;
|
|
18
|
+
}
|
|
19
|
+
return { status: 'new', ancestorSessionId: null, reason: 'pi_no_matching_ancestor_entry' };
|
|
20
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/** Pi usage is per persisted response; native output already includes reasoning tokens. */
|
|
2
|
+
export interface PiUsage {
|
|
3
|
+
input_tokens: number;
|
|
4
|
+
output_tokens: number;
|
|
5
|
+
cache_read_input_tokens: number;
|
|
6
|
+
cache_creation_input_tokens: number;
|
|
7
|
+
}
|
|
8
|
+
export interface PiUsageOwner {
|
|
9
|
+
sessionId: string;
|
|
10
|
+
entryId: string;
|
|
11
|
+
signature: string;
|
|
12
|
+
}
|
|
13
|
+
export type PiUsageLedger = Map<string, PiUsageOwner>;
|
|
14
|
+
export interface PiUsageDecision {
|
|
15
|
+
status: 'known' | 'copied' | 'repeated' | 'unknown' | 'conflict';
|
|
16
|
+
identity: string | null;
|
|
17
|
+
ownerSessionId: string | null;
|
|
18
|
+
model: string | null;
|
|
19
|
+
provider: string | null;
|
|
20
|
+
usage: PiUsage | null;
|
|
21
|
+
reason: string;
|
|
22
|
+
}
|
|
23
|
+
/** An inventory shares this in-memory ledger; persistence and durable acknowledgment belong to transport. */
|
|
24
|
+
export declare function accountPiUsage(sessionId: string, entry: Record<string, unknown>, ledger: PiUsageLedger): PiUsageDecision;
|
|
25
|
+
/** Native objects stay intact elsewhere; absent typed fields do not become invented values. */
|
|
26
|
+
export declare function piObject(value: unknown): Record<string, unknown>;
|
|
27
|
+
export declare function piString(value: unknown): string | null;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** An inventory shares this in-memory ledger; persistence and durable acknowledgment belong to transport. */
|
|
2
|
+
export function accountPiUsage(sessionId, entry, ledger) {
|
|
3
|
+
const message = piObject(entry.message);
|
|
4
|
+
const provider = piString(message.provider), model = piString(message.model);
|
|
5
|
+
const api = piString(message.api), responseId = piString(message.responseId), entryId = piString(entry.id);
|
|
6
|
+
const identity = provider && api && responseId ? JSON.stringify([provider, api, responseId]) : null;
|
|
7
|
+
const result = { status: 'unknown', identity, ownerSessionId: null, model, provider, usage: null, reason: 'pi_usage_identity_or_fields_missing' };
|
|
8
|
+
const native = piObject(message.usage);
|
|
9
|
+
const fields = ['input', 'output', 'cacheRead', 'cacheWrite', 'totalTokens'];
|
|
10
|
+
if (!identity || !model || !entryId || !fields.every(key => nonnegativeNumber(native[key])))
|
|
11
|
+
return result;
|
|
12
|
+
if (native.totalTokens !== Number(native.input) + Number(native.output) + Number(native.cacheRead) + Number(native.cacheWrite)) {
|
|
13
|
+
return { ...result, reason: 'pi_usage_total_semantics_unknown' };
|
|
14
|
+
}
|
|
15
|
+
const usage = { input_tokens: Number(native.input), output_tokens: Number(native.output), cache_read_input_tokens: Number(native.cacheRead), cache_creation_input_tokens: Number(native.cacheWrite) };
|
|
16
|
+
// Compare accounting fields under the exact provider response identity, never conversation text.
|
|
17
|
+
const signature = JSON.stringify([provider, api, model, ...fields.map(key => native[key])]);
|
|
18
|
+
const owner = ledger.get(identity);
|
|
19
|
+
if (owner && owner.signature !== signature)
|
|
20
|
+
return { ...result, status: 'conflict', ownerSessionId: owner.sessionId, reason: 'pi_response_usage_conflict' };
|
|
21
|
+
if (owner)
|
|
22
|
+
return { ...result, status: owner.sessionId === sessionId ? 'known' : 'copied', ownerSessionId: owner.sessionId, usage: owner.sessionId === sessionId ? usage : null, reason: 'pi_native_response_already_accounted' };
|
|
23
|
+
ledger.set(identity, { sessionId, entryId, signature });
|
|
24
|
+
return { ...result, status: 'known', ownerSessionId: sessionId, usage, reason: 'pi_native_response_first_observation' };
|
|
25
|
+
}
|
|
26
|
+
/** Native objects stay intact elsewhere; absent typed fields do not become invented values. */
|
|
27
|
+
export function piObject(value) {
|
|
28
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
|
|
29
|
+
}
|
|
30
|
+
export function piString(value) { return typeof value === 'string' && value.length > 0 ? value : null; }
|
|
31
|
+
function nonnegativeNumber(value) { return typeof value === 'number' && Number.isFinite(value) && value >= 0; }
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Native Pi semantics; no branch/context renderer replaces physical evidence order. */
|
|
2
|
+
import { type PiUsage, type PiUsageDecision, type PiUsageLedger } from './pi-transcript-usage.js';
|
|
3
|
+
export interface PiTranscriptFacts {
|
|
4
|
+
session_id: string | null;
|
|
5
|
+
version: number | null;
|
|
6
|
+
parent_session: string | null;
|
|
7
|
+
record_count: number;
|
|
8
|
+
user_prompt_count: number;
|
|
9
|
+
assistant_response_count: number;
|
|
10
|
+
tool_call_count: number;
|
|
11
|
+
tool_result_count: number;
|
|
12
|
+
tool_calls_by_name: Record<string, number>;
|
|
13
|
+
compaction_count: number;
|
|
14
|
+
interruption_count: number;
|
|
15
|
+
api_error_count: number;
|
|
16
|
+
unknown_record_count: number;
|
|
17
|
+
types: Record<string, number>;
|
|
18
|
+
first_timestamp_ms: number | null;
|
|
19
|
+
last_timestamp_ms: number | null;
|
|
20
|
+
usage_by_model: Record<string, PiUsage>;
|
|
21
|
+
known_usage_records: number;
|
|
22
|
+
copied_usage_records: number;
|
|
23
|
+
repeated_usage_records: number;
|
|
24
|
+
unknown_usage_records: number;
|
|
25
|
+
conflicting_usage_records: number;
|
|
26
|
+
usage_accounting: 'complete' | 'partial' | 'unavailable';
|
|
27
|
+
}
|
|
28
|
+
export interface PiTranscriptAccumulator {
|
|
29
|
+
facts: PiTranscriptFacts;
|
|
30
|
+
ledger: PiUsageLedger;
|
|
31
|
+
countedIdentities: Set<string>;
|
|
32
|
+
}
|
|
33
|
+
/** Collection and extraction can share these facts before Pi joins the shared source enum. */
|
|
34
|
+
export declare function newPiTranscriptAccumulator(ledger?: PiUsageLedger): PiTranscriptAccumulator;
|
|
35
|
+
/** Text callbacks receive only native user/assistant text, never thinking or tool results. */
|
|
36
|
+
export declare function piTurnText(record: Record<string, unknown>, role: 'user' | 'assistant'): string | null;
|
|
37
|
+
/** Every physical entry contributes facts, including off-branch and pre-compaction records. */
|
|
38
|
+
export declare function observePiTranscriptRecord(acc: PiTranscriptAccumulator, value: unknown): PiUsageDecision | null;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** Native Pi semantics; no branch/context renderer replaces physical evidence order. */
|
|
2
|
+
import { accountPiUsage, piObject, piString } from './pi-transcript-usage.js';
|
|
3
|
+
const knownTypes = new Set(['session', 'message', 'model_change', 'thinking_level_change', 'compaction', 'branch_summary', 'custom', 'custom_message', 'label', 'session_info']);
|
|
4
|
+
/** Collection and extraction can share these facts before Pi joins the shared source enum. */
|
|
5
|
+
export function newPiTranscriptAccumulator(ledger = new Map()) {
|
|
6
|
+
return { ledger: new Map(ledger), countedIdentities: new Set(), facts: { session_id: null, version: null, parent_session: null, record_count: 0, user_prompt_count: 0, assistant_response_count: 0,
|
|
7
|
+
tool_call_count: 0, tool_result_count: 0, tool_calls_by_name: {}, compaction_count: 0, interruption_count: 0, api_error_count: 0, unknown_record_count: 0, types: {},
|
|
8
|
+
first_timestamp_ms: null, last_timestamp_ms: null, usage_by_model: {}, known_usage_records: 0, copied_usage_records: 0, repeated_usage_records: 0, unknown_usage_records: 0, conflicting_usage_records: 0, usage_accounting: 'unavailable' } };
|
|
9
|
+
}
|
|
10
|
+
/** Text callbacks receive only native user/assistant text, never thinking or tool results. */
|
|
11
|
+
export function piTurnText(record, role) {
|
|
12
|
+
const message = piObject(record.message);
|
|
13
|
+
if (record.type !== 'message' || message.role !== role)
|
|
14
|
+
return null;
|
|
15
|
+
if (typeof message.content === 'string')
|
|
16
|
+
return message.content || null;
|
|
17
|
+
if (!Array.isArray(message.content))
|
|
18
|
+
return null;
|
|
19
|
+
return message.content.map(piObject).filter(block => block.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n') || null;
|
|
20
|
+
}
|
|
21
|
+
/** Every physical entry contributes facts, including off-branch and pre-compaction records. */
|
|
22
|
+
export function observePiTranscriptRecord(acc, value) {
|
|
23
|
+
const record = piObject(value), facts = acc.facts, type = piString(record.type) ?? 'unknown';
|
|
24
|
+
facts.record_count++;
|
|
25
|
+
facts.types[type] = (facts.types[type] ?? 0) + 1;
|
|
26
|
+
if (!knownTypes.has(type))
|
|
27
|
+
facts.unknown_record_count++;
|
|
28
|
+
if (type === 'session') {
|
|
29
|
+
facts.session_id = piString(record.id);
|
|
30
|
+
facts.version = typeof record.version === 'number' ? record.version : null;
|
|
31
|
+
facts.parent_session = piString(record.parentSession);
|
|
32
|
+
}
|
|
33
|
+
const message = piObject(record.message);
|
|
34
|
+
observeTimestamp(facts, record.timestamp);
|
|
35
|
+
observeTimestamp(facts, message.timestamp);
|
|
36
|
+
if (type === 'compaction')
|
|
37
|
+
facts.compaction_count++;
|
|
38
|
+
let auxiliaryUsage = null;
|
|
39
|
+
if (type !== 'message' || message.role === 'toolResult') {
|
|
40
|
+
if (type === 'compaction' || type === 'branch_summary' || record.usage != null || message.usage != null) {
|
|
41
|
+
const unknown = { status: 'unknown', identity: null, ownerSessionId: null, model: null, provider: null, usage: null, reason: 'pi_auxiliary_usage_identity_unverified' };
|
|
42
|
+
auxiliaryUsage = unknown;
|
|
43
|
+
observeUsageDecision(facts, unknown);
|
|
44
|
+
if (type !== 'message')
|
|
45
|
+
return unknown;
|
|
46
|
+
}
|
|
47
|
+
if (type !== 'message')
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
if (message.role === 'user')
|
|
51
|
+
facts.user_prompt_count++;
|
|
52
|
+
if (message.role === 'assistant')
|
|
53
|
+
facts.assistant_response_count++;
|
|
54
|
+
if (message.role === 'toolResult')
|
|
55
|
+
facts.tool_result_count++;
|
|
56
|
+
if (message.role === 'assistant' && message.stopReason === 'aborted')
|
|
57
|
+
facts.interruption_count++;
|
|
58
|
+
if (message.role === 'assistant' && message.stopReason === 'error')
|
|
59
|
+
facts.api_error_count++;
|
|
60
|
+
if (message.role !== 'assistant')
|
|
61
|
+
return auxiliaryUsage;
|
|
62
|
+
for (const block of Array.isArray(message.content) ? message.content.map(piObject) : []) {
|
|
63
|
+
if (block.type !== 'toolCall')
|
|
64
|
+
continue;
|
|
65
|
+
facts.tool_call_count++;
|
|
66
|
+
const name = piString(block.name) ?? 'unknown';
|
|
67
|
+
facts.tool_calls_by_name[name] = (facts.tool_calls_by_name[name] ?? 0) + 1;
|
|
68
|
+
}
|
|
69
|
+
let usage = facts.session_id ? accountPiUsage(facts.session_id, record, acc.ledger) : { status: 'unknown', identity: null, ownerSessionId: null, model: null, provider: null, usage: null, reason: 'pi_session_header_missing' };
|
|
70
|
+
if (usage.identity && usage.status === 'known') {
|
|
71
|
+
if (acc.countedIdentities.has(usage.identity))
|
|
72
|
+
usage = { ...usage, status: 'repeated', usage: null };
|
|
73
|
+
else
|
|
74
|
+
acc.countedIdentities.add(usage.identity);
|
|
75
|
+
}
|
|
76
|
+
observeUsageDecision(facts, usage);
|
|
77
|
+
return usage;
|
|
78
|
+
}
|
|
79
|
+
function observeUsageDecision(facts, decision) {
|
|
80
|
+
if (decision.status === 'known' && decision.model && decision.usage) {
|
|
81
|
+
facts.known_usage_records++;
|
|
82
|
+
const totals = facts.usage_by_model[decision.model] ?? { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: 0 };
|
|
83
|
+
for (const key of Object.keys(totals))
|
|
84
|
+
totals[key] += decision.usage[key];
|
|
85
|
+
facts.usage_by_model[decision.model] = totals;
|
|
86
|
+
}
|
|
87
|
+
else if (decision.status === 'copied')
|
|
88
|
+
facts.copied_usage_records++;
|
|
89
|
+
else if (decision.status === 'repeated')
|
|
90
|
+
facts.repeated_usage_records++;
|
|
91
|
+
else {
|
|
92
|
+
facts.unknown_usage_records++;
|
|
93
|
+
if (decision.status === 'conflict')
|
|
94
|
+
facts.conflicting_usage_records++;
|
|
95
|
+
}
|
|
96
|
+
const accounted = facts.known_usage_records + facts.copied_usage_records + facts.repeated_usage_records;
|
|
97
|
+
facts.usage_accounting = facts.unknown_usage_records ? (accounted ? 'partial' : 'unavailable') : 'complete';
|
|
98
|
+
}
|
|
99
|
+
function observeTimestamp(facts, value) {
|
|
100
|
+
const milliseconds = typeof value === 'number' ? value : typeof value === 'string' ? Date.parse(value) : NaN;
|
|
101
|
+
if (!Number.isFinite(milliseconds))
|
|
102
|
+
return;
|
|
103
|
+
facts.first_timestamp_ms = facts.first_timestamp_ms === null ? milliseconds : Math.min(milliseconds, facts.first_timestamp_ms);
|
|
104
|
+
facts.last_timestamp_ms = facts.last_timestamp_ms === null ? milliseconds : Math.max(milliseconds, facts.last_timestamp_ms);
|
|
105
|
+
}
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
* Metadata only: request ids, model and tool NAMES, counts, timestamps. No text.
|
|
17
17
|
*/
|
|
18
18
|
import { type SessionFactsAccumulator, type SessionFactsSource } from "./session-facts.js";
|
|
19
|
+
import type { HandsOnDelta } from "./session-facts-hands-on.js";
|
|
19
20
|
import type { SessionSpawn } from "./session-facts-spawn.js";
|
|
20
21
|
import type { SkillUseCount } from "./session-facts-skills.js";
|
|
21
22
|
/** `[request id, model, input, output, cache read, cache creation]`. */
|
|
@@ -36,6 +37,8 @@ export interface SessionFactsDelta {
|
|
|
36
37
|
codex_model_hint: string | null;
|
|
37
38
|
skills: SkillUseCount[];
|
|
38
39
|
spawn: SessionSpawn | null;
|
|
40
|
+
/** BLI-23623: this file's human events and classification counts. */
|
|
41
|
+
hands_on: HandsOnDelta;
|
|
39
42
|
}
|
|
40
43
|
/** Run `feed` against a fresh accumulator and keep what it did. `feed` does exactly what the caller would do to the live one. */
|
|
41
44
|
export declare function captureSessionFactsDelta(source: SessionFactsSource, feed: (acc: SessionFactsAccumulator) => void): SessionFactsDelta;
|
|
@@ -45,6 +45,7 @@ export function captureSessionFactsDelta(source, feed) {
|
|
|
45
45
|
codex_model_hint: acc.codex_model_hint,
|
|
46
46
|
skills: acc.skill_tally.entries(),
|
|
47
47
|
spawn: acc.spawn ? { ...acc.spawn } : null,
|
|
48
|
+
hands_on: acc.hands_on.toDelta(),
|
|
48
49
|
};
|
|
49
50
|
}
|
|
50
51
|
/** Leave `acc` as a fresh read of the same file would have left it. */
|
|
@@ -83,6 +84,7 @@ export function mergeSessionFactsDelta(acc, delta) {
|
|
|
83
84
|
acc.skill_tally.mergeEntries(delta.skills);
|
|
84
85
|
if (!acc.spawn && delta.spawn)
|
|
85
86
|
acc.spawn = { ...delta.spawn };
|
|
87
|
+
acc.hands_on.mergeDelta(delta.hands_on);
|
|
86
88
|
}
|
|
87
89
|
const isNum = (v) => typeof v === "number" && Number.isFinite(v);
|
|
88
90
|
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
@@ -118,5 +120,14 @@ export function parseSessionFactsDelta(value) {
|
|
|
118
120
|
const spawn = v["spawn"];
|
|
119
121
|
if (spawn !== null && !(isObj(spawn) && typeof spawn["kind"] === "string"))
|
|
120
122
|
return null;
|
|
123
|
+
const handsOn = v["hands_on"];
|
|
124
|
+
if (!isObj(handsOn) || !Array.isArray(handsOn["events"]))
|
|
125
|
+
return null;
|
|
126
|
+
if (!handsOn["events"].every((e) => Array.isArray(e) && e.length === 2 && typeof e[0] === "string" && isNum(e[1])))
|
|
127
|
+
return null;
|
|
128
|
+
for (const key of ["human_count", "not_human_count", "unknown_count", "turn_starts"]) {
|
|
129
|
+
if (!isNum(handsOn[key]))
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
121
132
|
return value;
|
|
122
133
|
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hands-on time estimate (BLI-23623, rule `hands_on.v1`): an ESTIMATE of how long a person was engaged with a
|
|
3
|
+
* session, computed only from the timestamps of the messages THEY sent. It does not measure attention and makes
|
|
4
|
+
* no accuracy claim until it is compared with independently timed real activity.
|
|
5
|
+
*
|
|
6
|
+
* The rule, immutable per rule id:
|
|
7
|
+
* - Every confirmed human event (a Claude prompt `uuid`, a Codex human root `turn_id`) credits the fixed window
|
|
8
|
+
* [t - 3 min, t + 5 min]. Windows do not depend on what the agent did in between.
|
|
9
|
+
* - Windows are unioned inside a session; the server unions again across a person's sessions after deduping
|
|
10
|
+
* replayed events by identity (forks and resumes copy history).
|
|
11
|
+
*
|
|
12
|
+
* Classification is provisional ("v1") until validated on captured real records of known actions. Precedence:
|
|
13
|
+
* Claude: (0) compaction summary: not human, whatever tags it carries (machine-written);
|
|
14
|
+
* (1) `origin.kind` or `turnOrigin` == human: human;
|
|
15
|
+
* (2) `promptSource` typed | queued | suggestion_accepted: human;
|
|
16
|
+
* (3) task-notification / peer / scheduled / system / coordinator origin, isMeta, isSidechain,
|
|
17
|
+
* tool_result-only: not human;
|
|
18
|
+
* (4) anything else (untagged records of an older client, `sdk`): UNKNOWN. Counted in coverage, never
|
|
19
|
+
* silently treated as "no human".
|
|
20
|
+
* Codex: `task_started.turn_attribution.turn_trigger` user | composer | queue with a null `parent_turn_id` and
|
|
21
|
+
* a null `initiating_agent_path`: human; exec | guardian_review (or a nested turn): not human; missing
|
|
22
|
+
* attribution or any other trigger: unknown.
|
|
23
|
+
*
|
|
24
|
+
* Pure. Metadata out: event ids, timestamps, counts. No text is returned.
|
|
25
|
+
*/
|
|
26
|
+
import { z } from "zod";
|
|
27
|
+
export declare const HANDS_ON_RULE_ID = "hands_on.v1";
|
|
28
|
+
export declare const HANDS_ON_BEFORE_MS: number;
|
|
29
|
+
export declare const HANDS_ON_AFTER_MS: number;
|
|
30
|
+
/** One session reports at most this many human events; `events_truncated` says how many were dropped. */
|
|
31
|
+
export declare const HANDS_ON_MAX_EVENTS = 10000;
|
|
32
|
+
export type HandsOnLabel = "human" | "not_human" | "unknown";
|
|
33
|
+
export interface HandsOnClassification {
|
|
34
|
+
label: HandsOnLabel;
|
|
35
|
+
/** A short constant naming the rule that decided (for tests and logs, never content). */
|
|
36
|
+
reason: string;
|
|
37
|
+
}
|
|
38
|
+
/** Decide whether one Claude `type:"user"` record is a message the person sent. */
|
|
39
|
+
export declare function classifyClaudeUserRecord(record: Record<string, unknown>): HandsOnClassification;
|
|
40
|
+
/** Decide whether one Codex `task_started` payload opened a turn the person started. */
|
|
41
|
+
export declare function classifyCodexTaskStarted(payload: Record<string, unknown>): HandsOnClassification;
|
|
42
|
+
/** Codex's identity for a human event: the root turn id. */
|
|
43
|
+
export declare function codexTurnId(payload: Record<string, unknown>): string | null;
|
|
44
|
+
/** Merge `[start, end]` ms intervals (sorted by start, touching intervals join). */
|
|
45
|
+
export declare function mergeIntervals(intervals: ReadonlyArray<readonly [number, number]>): Array<[number, number]>;
|
|
46
|
+
export declare function handsOnWindow(tsMs: number): [number, number];
|
|
47
|
+
export declare function intervalsMs(intervals: ReadonlyArray<readonly [number, number]>): number;
|
|
48
|
+
/** One file's contribution, in the form `session-facts-delta.ts` remembers and replays. */
|
|
49
|
+
export interface HandsOnDelta {
|
|
50
|
+
/** `[event id, ts ms]` per human event, first seen of an id wins, sorted by ts. */
|
|
51
|
+
events: Array<[string, number]>;
|
|
52
|
+
human_count: number;
|
|
53
|
+
not_human_count: number;
|
|
54
|
+
unknown_count: number;
|
|
55
|
+
/** Codex `task_started` records seen, so a Codex file with none can report its prompts as unknown. */
|
|
56
|
+
turn_starts: number;
|
|
57
|
+
}
|
|
58
|
+
export declare function emptyHandsOnDelta(): HandsOnDelta;
|
|
59
|
+
/** Collects a session's classified events record by record. */
|
|
60
|
+
export declare class HandsOnTally {
|
|
61
|
+
private readonly byId;
|
|
62
|
+
human: number;
|
|
63
|
+
notHuman: number;
|
|
64
|
+
unknown: number;
|
|
65
|
+
turnStarts: number;
|
|
66
|
+
/** Count one classified record. A human record with no usable timestamp cannot credit a window, so it counts as unknown. */
|
|
67
|
+
observe(classification: HandsOnClassification, id: string | null, tsMs: number | null): void;
|
|
68
|
+
mergeDelta(delta: HandsOnDelta): void;
|
|
69
|
+
toDelta(): HandsOnDelta;
|
|
70
|
+
}
|
|
71
|
+
export declare const HandsOnFactsSchema: z.ZodObject<{
|
|
72
|
+
rule_id: z.ZodLiteral<"hands_on.v1">;
|
|
73
|
+
seconds: z.ZodNumber;
|
|
74
|
+
events: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNumber], null>>;
|
|
75
|
+
intervals: z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
|
|
76
|
+
human_count: z.ZodNumber;
|
|
77
|
+
not_human_count: z.ZodNumber;
|
|
78
|
+
unknown_count: z.ZodNumber;
|
|
79
|
+
events_truncated: z.ZodNumber;
|
|
80
|
+
}, z.core.$strict>;
|
|
81
|
+
export type HandsOnFacts = z.infer<typeof HandsOnFactsSchema>;
|
|
82
|
+
/**
|
|
83
|
+
* The finished answer. `codexUserPrompts` lets a Codex file with no `task_started` records at all (an older
|
|
84
|
+
* client) report its prompts as unknown instead of reporting nothing.
|
|
85
|
+
*/
|
|
86
|
+
export declare function finalizeHandsOn(tally: HandsOnTally, codexUserPrompts: number): HandsOnFacts;
|
|
87
|
+
/** Counts only, for one scan's log line: how many sessions carried the estimate and how the records classified. */
|
|
88
|
+
export declare function summarizeHandsOn(facts: ReadonlyArray<{
|
|
89
|
+
hands_on?: HandsOnFacts;
|
|
90
|
+
} | null | undefined>): {
|
|
91
|
+
rule_id: string;
|
|
92
|
+
sessions: number;
|
|
93
|
+
sessions_with_events: number;
|
|
94
|
+
human: number;
|
|
95
|
+
not_human: number;
|
|
96
|
+
unknown: number;
|
|
97
|
+
seconds: number;
|
|
98
|
+
};
|