@bli-cockpit/telemetry-core 0.1.96 → 0.1.97
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/codex-record-copies.d.ts +7 -0
- package/dist/codex-record-copies.js +53 -0
- package/dist/evidence-upload.d.ts +22 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -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-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 +16 -1
- package/dist/session-facts.js +19 -30
- package/package.json +1 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SessionFactsAccumulator } from "./session-facts.js";
|
|
2
|
+
export declare function codexRevisionRecordSelector(): (record: Record<string, unknown>) => boolean;
|
|
3
|
+
/** Shared by metadata counting and the Codex metrics reader; returns whether this record contributes. */
|
|
4
|
+
export declare function includeCodexRevisionRecord(acc: SessionFactsAccumulator, record: Record<string, unknown>): boolean;
|
|
5
|
+
/** Latest cumulative event in a composite, ordinary native last-event semantics otherwise. */
|
|
6
|
+
export declare function observeCodexCumulativeUsage(acc: SessionFactsAccumulator, record: Record<string, unknown>, total: Record<string, unknown>): void;
|
|
7
|
+
export declare function codexRevisionUsageModel(acc: SessionFactsAccumulator): string | null;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Raw revisions retain every segment and duplicate. Readers count only exact
|
|
3
|
+
* cross-segment record copies. Repeated occurrences WITHIN a segment remain
|
|
4
|
+
* distinct, as do divergent payloads with the same provider/turn id. Ordinary
|
|
5
|
+
* native transcripts (without Tower boundaries) are unchanged.
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
export function codexRevisionRecordSelector() {
|
|
9
|
+
let active = false;
|
|
10
|
+
const prior = new Map();
|
|
11
|
+
let current = new Map();
|
|
12
|
+
return (record) => {
|
|
13
|
+
const payload = record["payload"];
|
|
14
|
+
if (record["type"] === "tower_codex_segment" && payload?.["schema_version"] === "codex-segments.v1") {
|
|
15
|
+
for (const [hash, count] of current)
|
|
16
|
+
prior.set(hash, Math.max(prior.get(hash) ?? 0, count));
|
|
17
|
+
current = new Map();
|
|
18
|
+
active = true;
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
21
|
+
if (!active)
|
|
22
|
+
return true;
|
|
23
|
+
// Context is stateful, not a charged request/turn: replay it even in copied history.
|
|
24
|
+
if (record["type"] === "session_meta" || record["type"] === "turn_context")
|
|
25
|
+
return true;
|
|
26
|
+
const hash = createHash("sha256").update(JSON.stringify(record)).digest("hex");
|
|
27
|
+
const occurrence = (current.get(hash) ?? 0) + 1;
|
|
28
|
+
current.set(hash, occurrence);
|
|
29
|
+
return occurrence > (prior.get(hash) ?? 0);
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
const selectors = new WeakMap();
|
|
33
|
+
const usage = new WeakMap();
|
|
34
|
+
/** Shared by metadata counting and the Codex metrics reader; returns whether this record contributes. */
|
|
35
|
+
export function includeCodexRevisionRecord(acc, record) {
|
|
36
|
+
if (record["type"] === "tower_codex_segment" && !selectors.has(acc))
|
|
37
|
+
selectors.set(acc, codexRevisionRecordSelector());
|
|
38
|
+
return selectors.get(acc)?.(record) ?? true;
|
|
39
|
+
}
|
|
40
|
+
/** Latest cumulative event in a composite, ordinary native last-event semantics otherwise. */
|
|
41
|
+
export function observeCodexCumulativeUsage(acc, record, total) {
|
|
42
|
+
const timestamp = typeof record["timestamp"] === "string" ? Date.parse(record["timestamp"]) : NaN;
|
|
43
|
+
const at = Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY;
|
|
44
|
+
const prior = usage.get(acc);
|
|
45
|
+
if (!selectors.has(acc) || !prior || at >= prior.at) {
|
|
46
|
+
acc.codex_total_usage = total;
|
|
47
|
+
if (selectors.has(acc))
|
|
48
|
+
usage.set(acc, { at, model: acc.codex_model_hint });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
export function codexRevisionUsageModel(acc) {
|
|
52
|
+
return usage.get(acc)?.model ?? acc.codex_model_hint;
|
|
53
|
+
}
|
|
@@ -628,9 +628,20 @@ export declare const CodexSessionAttributionSchema: z.ZodObject<{
|
|
|
628
628
|
codex_desktop: "codex_desktop";
|
|
629
629
|
codex_ide: "codex_ide";
|
|
630
630
|
codex_exec: "codex_exec";
|
|
631
|
+
t3_code: "t3_code";
|
|
631
632
|
}>>;
|
|
632
633
|
parent_session_id: z.ZodOptional<z.ZodString>;
|
|
633
634
|
}, z.core.$strict>>;
|
|
635
|
+
hands_on: z.ZodOptional<z.ZodObject<{
|
|
636
|
+
rule_id: z.ZodLiteral<"hands_on.v1">;
|
|
637
|
+
seconds: z.ZodNumber;
|
|
638
|
+
events: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNumber], null>>;
|
|
639
|
+
intervals: z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
|
|
640
|
+
human_count: z.ZodNumber;
|
|
641
|
+
not_human_count: z.ZodNumber;
|
|
642
|
+
unknown_count: z.ZodNumber;
|
|
643
|
+
events_truncated: z.ZodNumber;
|
|
644
|
+
}, z.core.$strict>>;
|
|
634
645
|
}, z.core.$strict>>;
|
|
635
646
|
session_file_mtime: z.ZodOptional<z.ZodString>;
|
|
636
647
|
repo_fingerprint: z.ZodOptional<z.ZodString>;
|
|
@@ -763,9 +774,20 @@ export declare const CodexSessionAttributionReportRequestSchema: z.ZodObject<{
|
|
|
763
774
|
codex_desktop: "codex_desktop";
|
|
764
775
|
codex_ide: "codex_ide";
|
|
765
776
|
codex_exec: "codex_exec";
|
|
777
|
+
t3_code: "t3_code";
|
|
766
778
|
}>>;
|
|
767
779
|
parent_session_id: z.ZodOptional<z.ZodString>;
|
|
768
780
|
}, z.core.$strict>>;
|
|
781
|
+
hands_on: z.ZodOptional<z.ZodObject<{
|
|
782
|
+
rule_id: z.ZodLiteral<"hands_on.v1">;
|
|
783
|
+
seconds: z.ZodNumber;
|
|
784
|
+
events: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNumber], null>>;
|
|
785
|
+
intervals: z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
|
|
786
|
+
human_count: z.ZodNumber;
|
|
787
|
+
not_human_count: z.ZodNumber;
|
|
788
|
+
unknown_count: z.ZodNumber;
|
|
789
|
+
events_truncated: z.ZodNumber;
|
|
790
|
+
}, z.core.$strict>>;
|
|
769
791
|
}, z.core.$strict>>;
|
|
770
792
|
session_file_mtime: z.ZodOptional<z.ZodString>;
|
|
771
793
|
repo_fingerprint: z.ZodOptional<z.ZodString>;
|
package/dist/index.d.ts
CHANGED
|
@@ -39,12 +39,14 @@ export * from "./risk-flags.js";
|
|
|
39
39
|
export * from "./run-verdict.js";
|
|
40
40
|
export * from "./secret-guards.js";
|
|
41
41
|
export * from "./session-facts.js";
|
|
42
|
+
export { codexRevisionRecordSelector } from "./codex-record-copies.js";
|
|
42
43
|
export * from "./session-facts-delta.js";
|
|
43
44
|
export * from "./shelf.js";
|
|
44
45
|
export * from "./safe-log.js";
|
|
45
46
|
export * from "./session-facts-skills.js";
|
|
46
47
|
export * from "./session-facts-spawn.js";
|
|
47
48
|
export * from "./session-facts-active.js";
|
|
49
|
+
export * from "./session-facts-hands-on.js";
|
|
48
50
|
export * from "./session-client-app.js";
|
|
49
51
|
export * from "./source-adapter.js";
|
|
50
52
|
export * from "./ticket-id.js";
|
package/dist/index.js
CHANGED
|
@@ -39,12 +39,14 @@ export * from "./risk-flags.js";
|
|
|
39
39
|
export * from "./run-verdict.js";
|
|
40
40
|
export * from "./secret-guards.js";
|
|
41
41
|
export * from "./session-facts.js";
|
|
42
|
+
export { codexRevisionRecordSelector } from "./codex-record-copies.js";
|
|
42
43
|
export * from "./session-facts-delta.js";
|
|
43
44
|
export * from "./shelf.js";
|
|
44
45
|
export * from "./safe-log.js";
|
|
45
46
|
export * from "./session-facts-skills.js";
|
|
46
47
|
export * from "./session-facts-spawn.js";
|
|
47
48
|
export * from "./session-facts-active.js";
|
|
49
|
+
export * from "./session-facts-hands-on.js";
|
|
48
50
|
export * from "./session-client-app.js";
|
|
49
51
|
export * from "./source-adapter.js";
|
|
50
52
|
export * from "./ticket-id.js";
|
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,208 @@
|
|
|
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 const HANDS_ON_RULE_ID = "hands_on.v1";
|
|
28
|
+
export const HANDS_ON_BEFORE_MS = 3 * 60 * 1000;
|
|
29
|
+
export const HANDS_ON_AFTER_MS = 5 * 60 * 1000;
|
|
30
|
+
/** One session reports at most this many human events; `events_truncated` says how many were dropped. */
|
|
31
|
+
export const HANDS_ON_MAX_EVENTS = 10_000;
|
|
32
|
+
const MAX_EVENT_ID_CHARS = 80;
|
|
33
|
+
const HUMAN_PROMPT_SOURCES = new Set(["typed", "queued", "suggestion_accepted"]);
|
|
34
|
+
const NOT_HUMAN_TURN_ORIGINS = new Set(["task_notification", "peer", "scheduled", "system"]);
|
|
35
|
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
36
|
+
const str = (v) => (typeof v === "string" && v ? v : null);
|
|
37
|
+
/** Is this user record's content only tool results (the agent's tool output echoed back)? */
|
|
38
|
+
function toolResultOnly(record) {
|
|
39
|
+
if (record["toolUseResult"] !== undefined)
|
|
40
|
+
return true;
|
|
41
|
+
const message = record["message"];
|
|
42
|
+
const content = isObj(message) ? message["content"] : undefined;
|
|
43
|
+
return Array.isArray(content) && content.length > 0 && content.every((b) => isObj(b) && b["type"] === "tool_result");
|
|
44
|
+
}
|
|
45
|
+
/** Decide whether one Claude `type:"user"` record is a message the person sent. */
|
|
46
|
+
export function classifyClaudeUserRecord(record) {
|
|
47
|
+
if (record["isCompactSummary"] === true)
|
|
48
|
+
return { label: "not_human", reason: "compact_summary" };
|
|
49
|
+
const origin = isObj(record["origin"]) ? str(record["origin"]["kind"]) : null;
|
|
50
|
+
const turnOrigin = str(record["turnOrigin"]);
|
|
51
|
+
if (origin === "human")
|
|
52
|
+
return { label: "human", reason: "origin_human" };
|
|
53
|
+
if (turnOrigin === "human")
|
|
54
|
+
return { label: "human", reason: "turn_origin_human" };
|
|
55
|
+
const promptSource = str(record["promptSource"]);
|
|
56
|
+
if (promptSource && HUMAN_PROMPT_SOURCES.has(promptSource))
|
|
57
|
+
return { label: "human", reason: "prompt_source_human" };
|
|
58
|
+
if (origin)
|
|
59
|
+
return { label: "not_human", reason: "origin_" + origin.slice(0, 30) };
|
|
60
|
+
if (turnOrigin && NOT_HUMAN_TURN_ORIGINS.has(turnOrigin))
|
|
61
|
+
return { label: "not_human", reason: "turn_origin_" + turnOrigin };
|
|
62
|
+
if (promptSource === "system")
|
|
63
|
+
return { label: "not_human", reason: "prompt_source_system" };
|
|
64
|
+
if (record["isMeta"] === true)
|
|
65
|
+
return { label: "not_human", reason: "meta" };
|
|
66
|
+
if (record["isSidechain"] === true)
|
|
67
|
+
return { label: "not_human", reason: "sidechain" };
|
|
68
|
+
if (toolResultOnly(record))
|
|
69
|
+
return { label: "not_human", reason: "tool_result_only" };
|
|
70
|
+
return { label: "unknown", reason: "untagged" };
|
|
71
|
+
}
|
|
72
|
+
const HUMAN_CODEX_TRIGGERS = new Set(["user", "composer", "queue"]);
|
|
73
|
+
const MACHINE_CODEX_TRIGGERS = new Set(["exec", "guardian_review"]);
|
|
74
|
+
/** Decide whether one Codex `task_started` payload opened a turn the person started. */
|
|
75
|
+
export function classifyCodexTaskStarted(payload) {
|
|
76
|
+
const attribution = payload["turn_attribution"];
|
|
77
|
+
if (!isObj(attribution))
|
|
78
|
+
return { label: "unknown", reason: "no_attribution" };
|
|
79
|
+
const trigger = str(attribution["turn_trigger"]);
|
|
80
|
+
if (!trigger)
|
|
81
|
+
return { label: "unknown", reason: "no_trigger" };
|
|
82
|
+
if (MACHINE_CODEX_TRIGGERS.has(trigger))
|
|
83
|
+
return { label: "not_human", reason: "trigger_" + trigger };
|
|
84
|
+
if (HUMAN_CODEX_TRIGGERS.has(trigger)) {
|
|
85
|
+
const nested = str(attribution["parent_turn_id"]) !== null || str(attribution["initiating_agent_path"]) !== null;
|
|
86
|
+
return nested ? { label: "not_human", reason: "nested_turn" } : { label: "human", reason: "trigger_" + trigger };
|
|
87
|
+
}
|
|
88
|
+
return { label: "unknown", reason: "trigger_other" };
|
|
89
|
+
}
|
|
90
|
+
/** Codex's identity for a human event: the root turn id. */
|
|
91
|
+
export function codexTurnId(payload) {
|
|
92
|
+
const attribution = isObj(payload["turn_attribution"]) ? payload["turn_attribution"] : {};
|
|
93
|
+
return str(attribution["turn_id"]) ?? str(payload["turn_id"]);
|
|
94
|
+
}
|
|
95
|
+
/** Merge `[start, end]` ms intervals (sorted by start, touching intervals join). */
|
|
96
|
+
export function mergeIntervals(intervals) {
|
|
97
|
+
const sorted = [...intervals].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const [start, end] of sorted) {
|
|
100
|
+
const last = out[out.length - 1];
|
|
101
|
+
if (last && start <= last[1])
|
|
102
|
+
last[1] = Math.max(last[1], end);
|
|
103
|
+
else
|
|
104
|
+
out.push([start, end]);
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
export function handsOnWindow(tsMs) {
|
|
109
|
+
return [tsMs - HANDS_ON_BEFORE_MS, tsMs + HANDS_ON_AFTER_MS];
|
|
110
|
+
}
|
|
111
|
+
export function intervalsMs(intervals) {
|
|
112
|
+
return intervals.reduce((sum, [start, end]) => sum + Math.max(0, end - start), 0);
|
|
113
|
+
}
|
|
114
|
+
export function emptyHandsOnDelta() {
|
|
115
|
+
return { events: [], human_count: 0, not_human_count: 0, unknown_count: 0, turn_starts: 0 };
|
|
116
|
+
}
|
|
117
|
+
/** Collects a session's classified events record by record. */
|
|
118
|
+
export class HandsOnTally {
|
|
119
|
+
byId = new Map();
|
|
120
|
+
human = 0;
|
|
121
|
+
notHuman = 0;
|
|
122
|
+
unknown = 0;
|
|
123
|
+
turnStarts = 0;
|
|
124
|
+
/** Count one classified record. A human record with no usable timestamp cannot credit a window, so it counts as unknown. */
|
|
125
|
+
observe(classification, id, tsMs) {
|
|
126
|
+
if (classification.label === "not_human")
|
|
127
|
+
return void (this.notHuman += 1);
|
|
128
|
+
if (classification.label === "unknown")
|
|
129
|
+
return void (this.unknown += 1);
|
|
130
|
+
if (tsMs == null)
|
|
131
|
+
return void (this.unknown += 1);
|
|
132
|
+
this.human += 1;
|
|
133
|
+
// A record with no identity gets one from its timestamp: replays of it dedupe, two distinct ones in a ms collapse.
|
|
134
|
+
const key = (id ?? "ts-" + tsMs).slice(0, MAX_EVENT_ID_CHARS);
|
|
135
|
+
const seen = this.byId.get(key);
|
|
136
|
+
if (seen === undefined || tsMs < seen)
|
|
137
|
+
this.byId.set(key, tsMs);
|
|
138
|
+
}
|
|
139
|
+
mergeDelta(delta) {
|
|
140
|
+
this.human += delta.human_count;
|
|
141
|
+
this.notHuman += delta.not_human_count;
|
|
142
|
+
this.unknown += delta.unknown_count;
|
|
143
|
+
this.turnStarts += delta.turn_starts;
|
|
144
|
+
for (const [id, ts] of delta.events) {
|
|
145
|
+
const seen = this.byId.get(id);
|
|
146
|
+
if (seen === undefined || ts < seen)
|
|
147
|
+
this.byId.set(id, ts);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
toDelta() {
|
|
151
|
+
return {
|
|
152
|
+
events: [...this.byId.entries()].sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0])),
|
|
153
|
+
human_count: this.human,
|
|
154
|
+
not_human_count: this.notHuman,
|
|
155
|
+
unknown_count: this.unknown,
|
|
156
|
+
turn_starts: this.turnStarts,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
export const HandsOnFactsSchema = z
|
|
161
|
+
.object({
|
|
162
|
+
rule_id: z.literal(HANDS_ON_RULE_ID),
|
|
163
|
+
seconds: z.number().int().nonnegative(),
|
|
164
|
+
events: z.array(z.tuple([z.string().min(1).max(MAX_EVENT_ID_CHARS), z.number().int()])).max(HANDS_ON_MAX_EVENTS),
|
|
165
|
+
intervals: z.array(z.tuple([z.number().int(), z.number().int()])).max(HANDS_ON_MAX_EVENTS),
|
|
166
|
+
human_count: z.number().int().nonnegative(),
|
|
167
|
+
not_human_count: z.number().int().nonnegative(),
|
|
168
|
+
unknown_count: z.number().int().nonnegative(),
|
|
169
|
+
events_truncated: z.number().int().nonnegative(),
|
|
170
|
+
})
|
|
171
|
+
.strict();
|
|
172
|
+
/**
|
|
173
|
+
* The finished answer. `codexUserPrompts` lets a Codex file with no `task_started` records at all (an older
|
|
174
|
+
* client) report its prompts as unknown instead of reporting nothing.
|
|
175
|
+
*/
|
|
176
|
+
export function finalizeHandsOn(tally, codexUserPrompts) {
|
|
177
|
+
const delta = tally.toDelta();
|
|
178
|
+
const unknown = delta.unknown_count + (delta.turn_starts === 0 && codexUserPrompts > 0 && delta.human_count === 0 ? codexUserPrompts : 0);
|
|
179
|
+
const intervals = mergeIntervals(delta.events.map(([, ts]) => handsOnWindow(ts)));
|
|
180
|
+
const kept = delta.events.slice(0, HANDS_ON_MAX_EVENTS);
|
|
181
|
+
return {
|
|
182
|
+
rule_id: HANDS_ON_RULE_ID,
|
|
183
|
+
seconds: Math.round(intervalsMs(intervals) / 1000),
|
|
184
|
+
events: kept,
|
|
185
|
+
intervals: intervals.slice(0, HANDS_ON_MAX_EVENTS),
|
|
186
|
+
human_count: delta.human_count,
|
|
187
|
+
not_human_count: delta.not_human_count,
|
|
188
|
+
unknown_count: unknown,
|
|
189
|
+
events_truncated: delta.events.length - kept.length,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
/** Counts only, for one scan's log line: how many sessions carried the estimate and how the records classified. */
|
|
193
|
+
export function summarizeHandsOn(facts) {
|
|
194
|
+
const out = { rule_id: HANDS_ON_RULE_ID, sessions: 0, sessions_with_events: 0, human: 0, not_human: 0, unknown: 0, seconds: 0 };
|
|
195
|
+
for (const f of facts) {
|
|
196
|
+
const h = f?.hands_on;
|
|
197
|
+
if (!h)
|
|
198
|
+
continue;
|
|
199
|
+
out.sessions += 1;
|
|
200
|
+
if (h.events.length > 0)
|
|
201
|
+
out.sessions_with_events += 1;
|
|
202
|
+
out.human += h.human_count;
|
|
203
|
+
out.not_human += h.not_human_count;
|
|
204
|
+
out.unknown += h.unknown_count;
|
|
205
|
+
out.seconds += h.seconds;
|
|
206
|
+
}
|
|
207
|
+
return out;
|
|
208
|
+
}
|
|
@@ -17,7 +17,7 @@ export type SessionSpawnKind = "interactive" | "worker" | "subagent";
|
|
|
17
17
|
* `Claude Code`) and `source` (`exec`, `cli`, `vscode`, or `{subagent: ...}`); Claude Code `entrypoint` (`cli`,
|
|
18
18
|
* `sdk-cli`, `sdk-ts`, `claude-desktop`). A value nobody has observed is `unknown`, never a guess.
|
|
19
19
|
*/
|
|
20
|
-
export declare const CLIENT_APPS: readonly ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "unknown"];
|
|
20
|
+
export declare const CLIENT_APPS: readonly ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "t3_code", "unknown"];
|
|
21
21
|
export type ClientApp = (typeof CLIENT_APPS)[number];
|
|
22
22
|
export interface SessionSpawn {
|
|
23
23
|
kind: SessionSpawnKind;
|
|
@@ -41,6 +41,7 @@ export declare const SessionSpawnSchema: z.ZodObject<{
|
|
|
41
41
|
codex_desktop: "codex_desktop";
|
|
42
42
|
codex_ide: "codex_ide";
|
|
43
43
|
codex_exec: "codex_exec";
|
|
44
|
+
t3_code: "t3_code";
|
|
44
45
|
}>>;
|
|
45
46
|
parent_session_id: z.ZodOptional<z.ZodString>;
|
|
46
47
|
}, z.core.$strict>;
|
|
@@ -15,7 +15,7 @@ import { z } from "zod";
|
|
|
15
15
|
* `Claude Code`) and `source` (`exec`, `cli`, `vscode`, or `{subagent: ...}`); Claude Code `entrypoint` (`cli`,
|
|
16
16
|
* `sdk-cli`, `sdk-ts`, `claude-desktop`). A value nobody has observed is `unknown`, never a guess.
|
|
17
17
|
*/
|
|
18
|
-
export const CLIENT_APPS = ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "unknown"];
|
|
18
|
+
export const CLIENT_APPS = ["claude_cli", "claude_desktop", "claude_ide", "codex_cli", "codex_desktop", "codex_ide", "codex_exec", "t3_code", "unknown"];
|
|
19
19
|
const SPAWN_ID = /^[A-Za-z0-9._-]{1,80}$/u;
|
|
20
20
|
const spawnId = (value) => typeof value === "string" && SPAWN_ID.test(value) ? value : undefined;
|
|
21
21
|
export const SessionSpawnSchema = z
|
|
@@ -88,6 +88,8 @@ export function codexSpawn(current, meta) {
|
|
|
88
88
|
* run, not a Codex client a person used, so it is `unknown`.
|
|
89
89
|
*/
|
|
90
90
|
export function codexClientApp(originator, source) {
|
|
91
|
+
if (originator === "T3 Code")
|
|
92
|
+
return "t3_code";
|
|
91
93
|
if (originator === "codex_exec")
|
|
92
94
|
return "codex_exec";
|
|
93
95
|
if (originator === "Codex Desktop" || originator === "codex_work_desktop")
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Small pure helpers of `session-facts.ts` (moved out so that file stays under the readability band, BLI-23623). */
|
|
2
|
+
import type { SessionFactsUsage } from "./session-facts.js";
|
|
3
|
+
export declare function usageTotal(usage: SessionFactsUsage): number;
|
|
4
|
+
export declare function emptyUsage(): SessionFactsUsage;
|
|
5
|
+
export declare function sumUsage(usages: readonly SessionFactsUsage[]): SessionFactsUsage;
|
|
6
|
+
export declare function byteLength(value: string): number;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export function usageTotal(usage) {
|
|
2
|
+
return (usage.input_tokens +
|
|
3
|
+
usage.output_tokens +
|
|
4
|
+
usage.cache_read_input_tokens +
|
|
5
|
+
usage.cache_creation_input_tokens);
|
|
6
|
+
}
|
|
7
|
+
export function emptyUsage() {
|
|
8
|
+
return {
|
|
9
|
+
input_tokens: 0,
|
|
10
|
+
output_tokens: 0,
|
|
11
|
+
cache_read_input_tokens: 0,
|
|
12
|
+
cache_creation_input_tokens: 0,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export function sumUsage(usages) {
|
|
16
|
+
return usages.reduce((sum, usage) => ({
|
|
17
|
+
input_tokens: sum.input_tokens + usage.input_tokens,
|
|
18
|
+
output_tokens: sum.output_tokens + usage.output_tokens,
|
|
19
|
+
cache_read_input_tokens: sum.cache_read_input_tokens + usage.cache_read_input_tokens,
|
|
20
|
+
cache_creation_input_tokens: sum.cache_creation_input_tokens + usage.cache_creation_input_tokens,
|
|
21
|
+
}), emptyUsage());
|
|
22
|
+
}
|
|
23
|
+
export function byteLength(value) {
|
|
24
|
+
return typeof Buffer === "undefined"
|
|
25
|
+
? new TextEncoder().encode(value).length
|
|
26
|
+
: Buffer.byteLength(value, "utf8");
|
|
27
|
+
}
|
package/dist/session-facts.d.ts
CHANGED
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
* Anthropic-shaped usage the price table expects.
|
|
33
33
|
*/
|
|
34
34
|
import { z } from "zod";
|
|
35
|
+
import { HandsOnTally, type HandsOnFacts } from "./session-facts-hands-on.js";
|
|
35
36
|
import { type SessionSpawn } from "./session-facts-spawn.js";
|
|
36
37
|
import { SkillUseTally } from "./session-facts-skills.js";
|
|
37
38
|
import type { SkillUseCount } from "./session-facts-skills.js";
|
|
@@ -83,6 +84,8 @@ export interface SessionFacts {
|
|
|
83
84
|
skill_use?: SkillUseCount[];
|
|
84
85
|
/** BLI-13066: who started the session (`session-facts-spawn.ts`). Absent from a block a CLI published before this field. */
|
|
85
86
|
spawn?: SessionSpawn;
|
|
87
|
+
/** BLI-23623: hands-on estimate from the person's own message timestamps (`session-facts-hands-on.ts`). Absent from a block a CLI published before this field. */
|
|
88
|
+
hands_on?: HandsOnFacts;
|
|
86
89
|
}
|
|
87
90
|
export interface SessionFactsAccumulator {
|
|
88
91
|
source: SessionFactsSource;
|
|
@@ -103,6 +106,7 @@ export interface SessionFactsAccumulator {
|
|
|
103
106
|
codex_model_hint: string | null;
|
|
104
107
|
skill_tally: SkillUseTally;
|
|
105
108
|
spawn: SessionSpawn | null;
|
|
109
|
+
hands_on: HandsOnTally;
|
|
106
110
|
/** Set only by `session-facts-delta.ts` while it captures one file's contribution (BLI-22797). */
|
|
107
111
|
usage_log?: Array<{
|
|
108
112
|
id: string;
|
|
@@ -117,7 +121,7 @@ export declare function observeSessionFactsFile(acc: SessionFactsAccumulator, fi
|
|
|
117
121
|
lines: number;
|
|
118
122
|
}): void;
|
|
119
123
|
/** One parsed JSONL record. The caller owns parsing; this owns the rules. */
|
|
120
|
-
export declare function observeSessionFactsRecord(acc: SessionFactsAccumulator, record: Record<string, unknown>):
|
|
124
|
+
export declare function observeSessionFactsRecord(acc: SessionFactsAccumulator, record: Record<string, unknown>): boolean;
|
|
121
125
|
export declare function addClaudeUsage(acc: SessionFactsAccumulator, model: string, usage: Record<string, unknown>): void;
|
|
122
126
|
/**
|
|
123
127
|
* OpenAI semantics differ from the Anthropic-shaped usage the price table
|
|
@@ -210,9 +214,20 @@ export declare const SessionFactsSchema: z.ZodObject<{
|
|
|
210
214
|
codex_desktop: "codex_desktop";
|
|
211
215
|
codex_ide: "codex_ide";
|
|
212
216
|
codex_exec: "codex_exec";
|
|
217
|
+
t3_code: "t3_code";
|
|
213
218
|
}>>;
|
|
214
219
|
parent_session_id: z.ZodOptional<z.ZodString>;
|
|
215
220
|
}, z.core.$strict>>;
|
|
221
|
+
hands_on: z.ZodOptional<z.ZodObject<{
|
|
222
|
+
rule_id: z.ZodLiteral<"hands_on.v1">;
|
|
223
|
+
seconds: z.ZodNumber;
|
|
224
|
+
events: z.ZodArray<z.ZodTuple<[z.ZodString, z.ZodNumber], null>>;
|
|
225
|
+
intervals: z.ZodArray<z.ZodTuple<[z.ZodNumber, z.ZodNumber], null>>;
|
|
226
|
+
human_count: z.ZodNumber;
|
|
227
|
+
not_human_count: z.ZodNumber;
|
|
228
|
+
unknown_count: z.ZodNumber;
|
|
229
|
+
events_truncated: z.ZodNumber;
|
|
230
|
+
}, z.core.$strict>>;
|
|
216
231
|
}, z.core.$strict>;
|
|
217
232
|
export type SessionFactsWire = z.infer<typeof SessionFactsSchema>;
|
|
218
233
|
export { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText, normalizeTurnText, textFromPlainTextBlocks, } from "./session-facts-text.js";
|
package/dist/session-facts.js
CHANGED
|
@@ -32,8 +32,11 @@
|
|
|
32
32
|
* Anthropic-shaped usage the price table expects.
|
|
33
33
|
*/
|
|
34
34
|
import { z } from "zod";
|
|
35
|
+
import { includeCodexRevisionRecord, observeCodexCumulativeUsage, codexRevisionUsageModel } from "./codex-record-copies.js";
|
|
35
36
|
import { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText } from "./session-facts-text.js";
|
|
36
37
|
import { activeSeconds } from "./session-facts-active.js";
|
|
38
|
+
import { byteLength, emptyUsage, sumUsage, usageTotal } from "./session-facts-usage-math.js";
|
|
39
|
+
import { classifyClaudeUserRecord, classifyCodexTaskStarted, codexTurnId, finalizeHandsOn, HandsOnFactsSchema, HandsOnTally, } from "./session-facts-hands-on.js";
|
|
37
40
|
import { claudeSpawn, codexSpawn, SessionSpawnSchema } from "./session-facts-spawn.js";
|
|
38
41
|
import { observeClaudeSkillUse, observeCodexSkillUse, SKILL_USE_MAX_SKILLS, SkillUseCountSchema, SkillUseTally } from "./session-facts-skills.js";
|
|
39
42
|
/** Bump when a counting rule changes, never when a field is added. */
|
|
@@ -62,6 +65,7 @@ export function newSessionFactsAccumulator(source) {
|
|
|
62
65
|
codex_model_hint: null,
|
|
63
66
|
skill_tally: new SkillUseTally(),
|
|
64
67
|
spawn: null,
|
|
68
|
+
hands_on: new HandsOnTally(),
|
|
65
69
|
};
|
|
66
70
|
}
|
|
67
71
|
/** One transcript file's size, for callers that never hold its whole text. */
|
|
@@ -72,6 +76,8 @@ export function observeSessionFactsFile(acc, file) {
|
|
|
72
76
|
}
|
|
73
77
|
/** One parsed JSONL record. The caller owns parsing; this owns the rules. */
|
|
74
78
|
export function observeSessionFactsRecord(acc, record) {
|
|
79
|
+
if (acc.source === "codex" && !includeCodexRevisionRecord(acc, record))
|
|
80
|
+
return false;
|
|
75
81
|
acc.record_count += 1;
|
|
76
82
|
const ms = parseTimestampMs(record["timestamp"]);
|
|
77
83
|
if (ms != null) {
|
|
@@ -85,11 +91,13 @@ export function observeSessionFactsRecord(acc, record) {
|
|
|
85
91
|
observeClaudeRecord(acc, record);
|
|
86
92
|
else
|
|
87
93
|
observeCodexRecord(acc, record);
|
|
94
|
+
return true;
|
|
88
95
|
}
|
|
89
96
|
function observeClaudeRecord(acc, record) {
|
|
90
97
|
const type = typeof record["type"] === "string" ? record["type"] : "";
|
|
91
98
|
acc.spawn = claudeSpawn(acc.spawn, record);
|
|
92
99
|
if (type === "user") {
|
|
100
|
+
acc.hands_on.observe(classifyClaudeUserRecord(record), typeof record["uuid"] === "string" ? record["uuid"] : null, parseTimestampMs(record["timestamp"]));
|
|
93
101
|
if (record["isMeta"] === true)
|
|
94
102
|
return;
|
|
95
103
|
const text = claudeUserTurnText(record);
|
|
@@ -162,6 +170,11 @@ function observeCodexRecord(acc, record) {
|
|
|
162
170
|
}
|
|
163
171
|
if (type !== "event_msg")
|
|
164
172
|
return;
|
|
173
|
+
if (String(p["type"] ?? "") === "task_started") {
|
|
174
|
+
acc.hands_on.turnStarts += 1;
|
|
175
|
+
acc.hands_on.observe(classifyCodexTaskStarted(p), codexTurnId(p), parseTimestampMs(record["timestamp"]));
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
165
178
|
if (String(p["type"] ?? "") !== "token_count")
|
|
166
179
|
return;
|
|
167
180
|
const info = p["info"];
|
|
@@ -170,7 +183,7 @@ function observeCodexRecord(acc, record) {
|
|
|
170
183
|
const total = info["total_token_usage"];
|
|
171
184
|
// Cumulative: the last event of the session is the session total.
|
|
172
185
|
if (total && typeof total === "object") {
|
|
173
|
-
acc
|
|
186
|
+
observeCodexCumulativeUsage(acc, record, total);
|
|
174
187
|
}
|
|
175
188
|
}
|
|
176
189
|
function countTool(acc, name) {
|
|
@@ -204,8 +217,9 @@ export function codexUsageFromCumulativeTotal(total) {
|
|
|
204
217
|
}
|
|
205
218
|
export function finalizeSessionFacts(acc) {
|
|
206
219
|
// A Codex session whose usage never named a model is left uncounted, not filed under a guess (as det.v5).
|
|
207
|
-
|
|
208
|
-
|
|
220
|
+
const usageModel = codexRevisionUsageModel(acc);
|
|
221
|
+
if (acc.codex_total_usage && usageModel) {
|
|
222
|
+
acc.usage_by_model[usageModel.slice(0, MAX_MODEL_NAME_CHARS)] =
|
|
209
223
|
codexUsageFromCumulativeTotal(acc.codex_total_usage);
|
|
210
224
|
}
|
|
211
225
|
const usageEntries = Object.entries(acc.usage_by_model).sort((a, b) => usageTotal(b[1]) - usageTotal(a[1]) || a[0].localeCompare(b[0]));
|
|
@@ -244,6 +258,7 @@ export function finalizeSessionFacts(acc) {
|
|
|
244
258
|
skill_use: acc.skill_tally.toList().slice(0, SKILL_USE_MAX_SKILLS),
|
|
245
259
|
...(acc.spawn ? { spawn: acc.spawn } : {}),
|
|
246
260
|
active_seconds: activeSeconds(acc.timestamps_ms),
|
|
261
|
+
hands_on: finalizeHandsOn(acc.hands_on, acc.source === "codex" ? acc.user_prompt_count : 0),
|
|
247
262
|
};
|
|
248
263
|
}
|
|
249
264
|
/**
|
|
@@ -285,33 +300,6 @@ export function computeSessionFacts(options) {
|
|
|
285
300
|
}
|
|
286
301
|
return finalizeSessionFacts(acc);
|
|
287
302
|
}
|
|
288
|
-
function usageTotal(usage) {
|
|
289
|
-
return (usage.input_tokens +
|
|
290
|
-
usage.output_tokens +
|
|
291
|
-
usage.cache_read_input_tokens +
|
|
292
|
-
usage.cache_creation_input_tokens);
|
|
293
|
-
}
|
|
294
|
-
function sumUsage(usages) {
|
|
295
|
-
return usages.reduce((sum, usage) => ({
|
|
296
|
-
input_tokens: sum.input_tokens + usage.input_tokens,
|
|
297
|
-
output_tokens: sum.output_tokens + usage.output_tokens,
|
|
298
|
-
cache_read_input_tokens: sum.cache_read_input_tokens + usage.cache_read_input_tokens,
|
|
299
|
-
cache_creation_input_tokens: sum.cache_creation_input_tokens + usage.cache_creation_input_tokens,
|
|
300
|
-
}), emptyUsage());
|
|
301
|
-
}
|
|
302
|
-
function emptyUsage() {
|
|
303
|
-
return {
|
|
304
|
-
input_tokens: 0,
|
|
305
|
-
output_tokens: 0,
|
|
306
|
-
cache_read_input_tokens: 0,
|
|
307
|
-
cache_creation_input_tokens: 0,
|
|
308
|
-
};
|
|
309
|
-
}
|
|
310
|
-
function byteLength(value) {
|
|
311
|
-
return typeof Buffer === "undefined"
|
|
312
|
-
? new TextEncoder().encode(value).length
|
|
313
|
-
: Buffer.byteLength(value, "utf8");
|
|
314
|
-
}
|
|
315
303
|
function parseTimestampMs(value) {
|
|
316
304
|
if (typeof value !== "string")
|
|
317
305
|
return null;
|
|
@@ -367,6 +355,7 @@ export const SessionFactsSchema = z
|
|
|
367
355
|
truncated_tool_names: z.number().int().nonnegative(),
|
|
368
356
|
skill_use: z.array(SkillUseCountSchema).max(SKILL_USE_MAX_SKILLS).optional(),
|
|
369
357
|
spawn: SessionSpawnSchema.optional(),
|
|
358
|
+
hands_on: HandsOnFactsSchema.optional(),
|
|
370
359
|
})
|
|
371
360
|
.strict();
|
|
372
361
|
export { claudeAssistantText, claudeUserTurnText, codexAssistantText, codexUserTurnText, normalizeTurnText, textFromPlainTextBlocks, } from "./session-facts-text.js";
|