@bli-cockpit/telemetry-core 0.1.95 → 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.
@@ -8,5 +8,18 @@
8
8
  * Its own file, and its own `./codex-hooks-trust-guide` export, so a browser
9
9
  * component can import one string without pulling in the whole package.
10
10
  * Repo copy of the guide: `docs/runbooks/codex-hooks-trust.md` (BLI-23315).
11
+ * Since BLI-24349 the guide leads with doctor's one question; `/hooks` is the fallback.
11
12
  */
12
13
  export declare const CODEX_HOOKS_TRUST_GUIDE_URL = "https://tower.buildlaunchiterate.ca/docs/trust-the-bli-memory-hooks-in-codex";
14
+ /** The doctor question, word for word (BLI-24349). Surfaces that tell a person to answer it quote this. */
15
+ export declare const CODEX_HOOKS_TRUST_QUESTION_WORDS = "Auto-trust the BLI Memory hooks in Codex?";
16
+ /** The command that trusts them without the question, for a person who said no earlier. */
17
+ export declare const CODEX_HOOKS_TRUST_COMMAND = "cockpit doctor --trust-codex-hooks";
18
+ /**
19
+ * The one sentence every surface prints for `codex.hooks needs_trust`
20
+ * (BLI-24349): lead with doctor's question, keep `/hooks` as the fallback.
21
+ * `reason` is the receipt's reason label for the piece; `trust_declined` and
22
+ * `managed_hooks_stale` get their own words. Every variant names `/hooks`, so
23
+ * the device doctor's `hook_trust` action keeps matching it.
24
+ */
25
+ export declare function codexHooksTrustAction(reason?: string | null): string;
@@ -8,5 +8,26 @@
8
8
  * Its own file, and its own `./codex-hooks-trust-guide` export, so a browser
9
9
  * component can import one string without pulling in the whole package.
10
10
  * Repo copy of the guide: `docs/runbooks/codex-hooks-trust.md` (BLI-23315).
11
+ * Since BLI-24349 the guide leads with doctor's one question; `/hooks` is the fallback.
11
12
  */
12
13
  export const CODEX_HOOKS_TRUST_GUIDE_URL = "https://tower.buildlaunchiterate.ca/docs/trust-the-bli-memory-hooks-in-codex";
14
+ /** The doctor question, word for word (BLI-24349). Surfaces that tell a person to answer it quote this. */
15
+ export const CODEX_HOOKS_TRUST_QUESTION_WORDS = "Auto-trust the BLI Memory hooks in Codex?";
16
+ /** The command that trusts them without the question, for a person who said no earlier. */
17
+ export const CODEX_HOOKS_TRUST_COMMAND = "cockpit doctor --trust-codex-hooks";
18
+ /**
19
+ * The one sentence every surface prints for `codex.hooks needs_trust`
20
+ * (BLI-24349): lead with doctor's question, keep `/hooks` as the fallback.
21
+ * `reason` is the receipt's reason label for the piece; `trust_declined` and
22
+ * `managed_hooks_stale` get their own words. Every variant names `/hooks`, so
23
+ * the device doctor's `hook_trust` action keeps matching it.
24
+ */
25
+ export function codexHooksTrustAction(reason) {
26
+ if (reason === "trust_declined") {
27
+ return `The person answered no to "${CODEX_HOOKS_TRUST_QUESTION_WORDS}". To trust them, run \`${CODEX_HOOKS_TRUST_COMMAND}\` in a terminal on the machine (or open Codex and run /hooks). Guide: ${CODEX_HOOKS_TRUST_GUIDE_URL}`;
28
+ }
29
+ if (reason === "managed_hooks_stale") {
30
+ return `BLI Memory's Codex hooks changed since they were trusted: run \`cockpit doctor\` in a terminal on the machine and answer Y to "${CODEX_HOOKS_TRUST_QUESTION_WORDS}" (fallback: open Codex and run /hooks). Guide: ${CODEX_HOOKS_TRUST_GUIDE_URL}`;
31
+ }
32
+ return `Run \`cockpit doctor\` in a terminal on the machine and answer Y to "${CODEX_HOOKS_TRUST_QUESTION_WORDS}" (one password or administrator prompt). Fallback: open Codex and run /hooks. Guide: ${CODEX_HOOKS_TRUST_GUIDE_URL}`;
33
+ }
@@ -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";
@@ -1,8 +1,17 @@
1
- export type ExperienceStore = "bli" | "supermemory" | "both";
1
+ /**
2
+ * BLI-24380: BLI Memory is the only memory store. `supermemory` and `both` are
3
+ * retired: a new entry naming them is accepted (never an error) and logged as
4
+ * retired, and receipts queued before the retirement still ship unchanged.
5
+ */
6
+ export type ExperienceStore = "bli";
7
+ export type RetiredExperienceStore = "supermemory" | "both";
8
+ /** What a stored or queued receipt may carry: today's store or a retired one. */
9
+ export type RecordedExperienceStore = ExperienceStore | RetiredExperienceStore;
10
+ export declare const RETIRED_EXPERIENCE_STORES: readonly RetiredExperienceStore[];
2
11
  export type ExperienceVerdict = "win" | "loss" | "noise";
3
12
  export interface MemoryExperience {
4
13
  id: string;
5
- store: ExperienceStore;
14
+ store: RecordedExperienceStore;
6
15
  verdict: ExperienceVerdict;
7
16
  reason: string;
8
17
  created_at: string;
@@ -14,6 +23,24 @@ export type ExperienceSender = (entry: MemoryExperience) => Promise<{
14
23
  ok: boolean;
15
24
  reason?: string;
16
25
  }>;
26
+ export type NormalisedExperienceStore = {
27
+ store: ExperienceStore;
28
+ given: string;
29
+ retired: boolean;
30
+ } | {
31
+ store: null;
32
+ given: "supermemory";
33
+ retired: true;
34
+ reason: "store_retired";
35
+ };
36
+ /**
37
+ * The one rule every new-entry door shares (CLI, MCP). Omitted means `bli`.
38
+ * `both` records as `bli`: BLI Memory was one of the stores that answered.
39
+ * `supermemory` records nothing: that store is gone, so a verdict about it is
40
+ * not a fact about anything Tower runs. Anything else is a caller error.
41
+ */
42
+ export declare function normaliseExperienceStore(given: string | undefined): NormalisedExperienceStore;
43
+ /** Validates a receipt. Retired stores stay valid so an old queued receipt still ships. */
17
44
  export declare function validateExperience(store: string, verdict: string, reason: string): void;
18
45
  export declare function experienceLine(entry: MemoryExperience, agent: string, project: string): string;
19
46
  export declare function appendExperience(input: {
@@ -4,20 +4,42 @@ import { randomUUID } from "node:crypto";
4
4
  import { homedir } from "node:os";
5
5
  import path from "node:path";
6
6
  import { redactSecretLikeContent } from "./secret-guards-masking.js";
7
+ export const RETIRED_EXPERIENCE_STORES = ["supermemory", "both"];
8
+ /**
9
+ * The one rule every new-entry door shares (CLI, MCP). Omitted means `bli`.
10
+ * `both` records as `bli`: BLI Memory was one of the stores that answered.
11
+ * `supermemory` records nothing: that store is gone, so a verdict about it is
12
+ * not a fact about anything Tower runs. Anything else is a caller error.
13
+ */
14
+ export function normaliseExperienceStore(given) {
15
+ const value = given ?? "bli";
16
+ if (value === "bli") {
17
+ return { store: "bli", given: value, retired: false };
18
+ }
19
+ if (value === "both") {
20
+ console.error("[memory experience] store retired", JSON.stringify({ given: value, recorded: "bli" }));
21
+ return { store: "bli", given: value, retired: true };
22
+ }
23
+ if (value === "supermemory") {
24
+ console.error("[memory experience] store retired", JSON.stringify({ given: value, recorded: null, reason: "store_retired" }));
25
+ return { store: null, given: value, retired: true, reason: "store_retired" };
26
+ }
27
+ throw new Error("store must be bli (supermemory and both are retired)");
28
+ }
29
+ /** Validates a receipt. Retired stores stay valid so an old queued receipt still ships. */
7
30
  export function validateExperience(store, verdict, reason) {
8
- if (!["bli", "supermemory", "both"].includes(store))
9
- throw new Error("store must be bli, supermemory or both");
31
+ if (store !== "bli" && !RETIRED_EXPERIENCE_STORES.includes(store))
32
+ throw new Error("store must be bli (supermemory and both are retired)");
10
33
  if (!["win", "loss", "noise"].includes(verdict))
11
34
  throw new Error("verdict must be win, loss or noise");
12
35
  if (!reason.trim() || [...reason].length > 500 || /[\r\n\x00-\x1f\x7f]/u.test(reason)) {
13
36
  throw new Error("reason must be one nonempty line of at most 500 characters; opinions only, no prompts, memory bodies or secrets");
14
37
  }
15
38
  }
16
- const markers = { bli: "[bli]", supermemory: "◪", both: "[bli]+◪" };
17
39
  export function experienceLine(entry, agent, project) {
18
40
  const stamp = new Date(Date.parse(entry.created_at) + 7 * 3600000).toISOString().slice(0, 16).replace("T", " ");
19
41
  const label = (value) => value.replace(/[\r\n·]/gu, " ");
20
- return `- ${stamp} ICT · ${label(agent)} · ${label(project)} · ${entry.store} ${markers[entry.store]} · ${entry.verdict}: ${entry.reason}`;
42
+ return `- ${stamp} ICT · ${label(agent)} · ${label(project)} · ${entry.store} [bli] · ${entry.verdict}: ${entry.reason}`;
21
43
  }
22
44
  function paths(home) {
23
45
  return { log: path.join(home, ".codex", "AGENT-EXPERIENCE.md"), queue: path.join(home, ".codex", "agent-experience-outbox") };
@@ -29,6 +51,9 @@ async function saveReceipt(home, entry) {
29
51
  await rename(temp, target);
30
52
  }
31
53
  export async function appendExperience(input, options) {
54
+ // BLI-24380: a new entry records BLI Memory only; callers normalise first.
55
+ if (input.store !== "bli")
56
+ throw new Error("appendExperience records bli only; run normaliseExperienceStore first");
32
57
  validateExperience(input.store, input.verdict, input.reason);
33
58
  // BLI-12187: the reason is free text an agent wrote and it is uploaded, so the
34
59
  // value is masked before the receipt, the local log or the outbox sees it.
@@ -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
+ }