omp-fabric 1.25.19 → 1.25.21

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/chunks/{chunk-QJKOPPW2.js → chunk-5CW2S6EB.js} +2 -2
  3. package/dist/chunks/{chunk-5SSQD7TW.js → chunk-7NWMFYD3.js} +73 -20
  4. package/dist/chunks/chunk-7NWMFYD3.js.map +7 -0
  5. package/dist/chunks/{chunk-WQUMHDOS.js → chunk-ESPCTYVX.js} +39 -1
  6. package/dist/chunks/chunk-ESPCTYVX.js.map +7 -0
  7. package/dist/chunks/{chunk-YNABLCR3.js → chunk-KW6EUFD2.js} +2 -2
  8. package/dist/chunks/{chunk-BD6FHI24.js → chunk-OLFP7R5J.js} +3 -3
  9. package/dist/chunks/{chunk-NPM24GG6.js → chunk-TDO2BRZM.js} +2 -2
  10. package/dist/chunks/{chunk-D55BFSFK.js → chunk-TRM76YFF.js} +6 -84
  11. package/dist/chunks/chunk-TRM76YFF.js.map +7 -0
  12. package/dist/compaction/hook.js +1 -1
  13. package/dist/core/token-math.d.ts +4 -22
  14. package/dist/core/token-math.d.ts.map +1 -1
  15. package/dist/core/truncation-marker.d.ts +8 -0
  16. package/dist/core/truncation-marker.d.ts.map +1 -0
  17. package/dist/fabric-exec-tool.d.ts.map +1 -1
  18. package/dist/fabric-runtime-state.js +7 -7
  19. package/dist/fabric-runtime-state.js.map +3 -3
  20. package/dist/index.js +15 -10
  21. package/dist/index.js.map +2 -2
  22. package/dist/providers/omp-tools-provider.d.ts +2 -1
  23. package/dist/providers/omp-tools-provider.d.ts.map +1 -1
  24. package/dist/residency/host.js +4 -4
  25. package/dist/residency/omp-entry.js +4 -4
  26. package/dist/ui/core-tool-render.d.ts.map +1 -1
  27. package/dist/ui/dashboard.js +2 -2
  28. package/dist/ui/fabric-render.d.ts.map +1 -1
  29. package/docs/architecture.md +6 -0
  30. package/docs/certification.md +1 -1
  31. package/package.json +8 -8
  32. package/dist/chunks/chunk-5SSQD7TW.js.map +0 -7
  33. package/dist/chunks/chunk-D55BFSFK.js.map +0 -7
  34. package/dist/chunks/chunk-WQUMHDOS.js.map +0 -7
  35. /package/dist/chunks/{chunk-QJKOPPW2.js.map → chunk-5CW2S6EB.js.map} +0 -0
  36. /package/dist/chunks/{chunk-YNABLCR3.js.map → chunk-KW6EUFD2.js.map} +0 -0
  37. /package/dist/chunks/{chunk-BD6FHI24.js.map → chunk-OLFP7R5J.js.map} +0 -0
  38. /package/dist/chunks/{chunk-NPM24GG6.js.map → chunk-TDO2BRZM.js.map} +0 -0
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/compaction/hook.ts", "../../src/core/token-math.ts", "../../src/core/session-context.ts", "../../src/compaction/threshold.ts", "../../src/compaction/enrichers.ts", "../../src/run-display.ts", "../../src/ui/fabric-title-hint.ts", "../../src/compaction/normalize.ts", "../../src/compaction/projections.ts", "../../src/compaction/branch-summary.ts"],
4
- "sourcesContent": ["import type { CompactionResult } from \"@oh-my-pi/pi-agent-core/compaction\";\nimport {\n type ExtensionAPI,\n type ExtensionContext,\n type SessionBeforeCompactEvent,\n type SessionBeforeTreeEvent,\n type SessionEntry,\n} from \"@oh-my-pi/pi-coding-agent\";\nimport { calculateContextTokens, DEFAULT_COMPACTION_SETTINGS, estimateTokens } from \"../core/token-math.js\";\nimport { buildSessionContext, sessionEntryToContextMessages } from \"../core/session-context.js\";\nimport { clipUtf8, MAX_SUMMARY_BYTES } from \"./bounds.js\";\nimport { modelCompactionKey } from \"./threshold.js\";\nimport { NO_BUILTIN_ENRICHERS, runEnrichers, type CompactionEnricher } from \"./enrichers.js\";\nimport { compileLcmBranchSummary } from \"./branch-summary.js\";\nimport {\n decodeCompactionInstructions,\n type CompactionInstructionDecodeError,\n type CompactionInstructionPolicy,\n} from \"./instructions.js\";\nimport { countErasedThinkingBlocks, isOmpCustomMessageEntry, normalizeEntries } from \"./normalize.js\";\nimport {\n projectWithMetadata,\n type ProjectionOmittedCounts,\n type Sections,\n} from \"./projections.js\";\nimport { renderSummary } from \"./render.js\";\n\ntype CompactionEngine = \"omp\" | \"lcm\";\n\ninterface LiveEntry {\n entry: SessionEntry;\n branchIndex: number;\n turnBoundary: boolean;\n cutPoint: boolean;\n estimatedTokens: number;\n message?: {\n role?: unknown;\n content?: unknown;\n toolCallId?: unknown;\n };\n}\n\ninterface CallResultSpan {\n first: number;\n last: number;\n hasCall: boolean;\n hasResult: boolean;\n}\n\nexport interface FabricCompactionBudget {\n contextWindow: number;\n targetContextRatio: number;\n reserveTokens: number;\n keepRecentTokens: number;\n}\n\ntype FabricCompactionBindingConstraint =\n | \"continuity\"\n | \"occupancy\"\n | \"reserve\"\n | \"reduction\";\n\nexport interface FabricCompactionBudgetDetails {\n strategy: \"adaptive\" | \"continuity\";\n contextWindow: number;\n targetContextRatio: number;\n targetContextTokens: number;\n reserveTokens: number;\n keepRecentTokens: number;\n rawTokensBefore: number;\n tokenScale: number;\n fixedOverheadTokens: number;\n retainedRawTokens: number;\n projectedTokensAfter: number;\n continuityTargetTokens?: number;\n occupancyCeilingTokens?: number;\n safeCeilingTokens?: number;\n reductionCeilingTokens?: number;\n rawTailTokenBudget?: number;\n bindingConstraint?: FabricCompactionBindingConstraint;\n}\n\ninterface ContinuityCutPlan {\n contextWindow: number;\n targetContextRatio: number;\n targetContextTokens: number;\n reserveTokens: number;\n keepRecentTokens: number;\n rawTokensBefore: number;\n tokenScale: number;\n fixedOverheadTokens: number;\n continuityTargetTokens: number;\n occupancyCeilingTokens: number;\n safeCeilingTokens: number;\n reductionCeilingTokens: number;\n rawTailTokenBudget: number;\n bindingConstraint: FabricCompactionBindingConstraint;\n}\n\nconst SUMMARY_RAW_TOKEN_BUDGET = Math.ceil(MAX_SUMMARY_BYTES / 4);\nconst HARD_CEILING_SAFETY_RATIO = 0.9;\nconst MAX_PRECOMPACTION_RATIO = 0.95;\n// An overflow rejection proves the provider's effective window is below the\n// failed request size, so the observation is stronger evidence than the\n// advertised (possibly proxy-inflated) model window. The haircut absorbs the\n// removed error message and estimator slop.\nconst OVERFLOW_WINDOW_EVIDENCE_RATIO = 0.9;\n\nconst isMessageEntry = (entry: SessionEntry): entry is Extract<SessionEntry, { type: \"message\" }> =>\n entry.type === \"message\";\n\nconst isHiddenEmptyCustom = (message: unknown): boolean => {\n if (!message || typeof message !== \"object\") return false;\n const candidate = message as { role?: unknown; display?: unknown; content?: unknown };\n if (candidate.role !== \"custom\" || candidate.display !== false) return false;\n const content = candidate.content;\n return content === \"\" || (Array.isArray(content) && content.length === 0);\n};\n\nconst toolCallIdsOf = (message: { content?: unknown }): string[] => {\n const content = message.content;\n if (!Array.isArray(content)) return [];\n const ids: string[] = [];\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part) || part.type !== \"toolCall\") continue;\n const id = (part as { id?: unknown }).id;\n if (typeof id === \"string\") ids.push(id);\n }\n return ids;\n};\n\nconst contextMessages = (entry: SessionEntry): ReturnType<typeof sessionEntryToContextMessages> => {\n try {\n return sessionEntryToContextMessages(entry);\n } catch {\n return [];\n }\n};\n\nconst findLastCompaction = (entries: SessionEntry[]): { index: number; firstKeptEntryId: string } | undefined => {\n for (let index = entries.length - 1; index >= 0; index--) {\n const entry = entries[index]!;\n if (entry.type === \"compaction\") {\n return { index, firstKeptEntryId: entry.firstKeptEntryId };\n }\n }\n return undefined;\n};\n\nconst collectContextEntries = (entries: SessionEntry[], startIndex: number): LiveEntry[] => {\n const contextEntries: LiveEntry[] = [];\n for (let index = Math.max(0, startIndex); index < entries.length; index++) {\n const entry = entries[index]!;\n if (entry.type === \"compaction\") continue;\n if (entry.type === \"custom_message\" && !isOmpCustomMessageEntry(entry)) continue;\n if (isMessageEntry(entry) && isHiddenEmptyCustom(entry.message)) continue;\n const messages = contextMessages(entry);\n if (messages.length === 0) continue;\n const roles = messages.map((message) => message.role);\n const rawMessage = isMessageEntry(entry)\n ? entry.message as NonNullable<LiveEntry[\"message\"]>\n : undefined;\n contextEntries.push({\n entry,\n branchIndex: index,\n turnBoundary: roles.some((role) =>\n role === \"user\"\n || role === \"custom\"\n || role === \"bashExecution\"\n || role === \"branchSummary\"\n || role === \"compactionSummary\"),\n cutPoint: roles.some((role) => role !== \"toolResult\"),\n estimatedTokens: messages.reduce((total, message) => total + estimateTokens(message), 0),\n ...(rawMessage ? { message: rawMessage } : {}),\n });\n }\n return contextEntries;\n};\n\nconst collectLive = (entries: SessionEntry[]): LiveEntry[] => {\n const last = findLastCompaction(entries);\n if (!last) return collectContextEntries(entries, 0);\n if (last.firstKeptEntryId) {\n const keptIndex = entries.findIndex((entry) => entry.id === last.firstKeptEntryId);\n if (keptIndex >= 0) return collectContextEntries(entries, keptIndex);\n }\n return collectContextEntries(entries, last.index + 1);\n};\n\nconst previousBoundaryAtOrBefore = (live: LiveEntry[], branchIndex: number): number => {\n for (let index = live.length - 1; index >= 0; index--) {\n const item = live[index]!;\n if (item.branchIndex <= branchIndex && item.turnBoundary) return index;\n }\n return -1;\n};\n\nconst lastBoundaryIndex = (live: LiveEntry[]): number => {\n for (let index = live.length - 1; index >= 0; index--) {\n if (live[index]!.turnBoundary) return index;\n }\n return -1;\n};\n\nconst callResultSpans = (entries: SessionEntry[]): Map<string, CallResultSpan> => {\n const spans = new Map<string, CallResultSpan>();\n const record = (id: string, index: number, kind: \"call\" | \"result\"): void => {\n if (!id) return;\n const span = spans.get(id) ?? {\n first: index,\n last: index,\n hasCall: false,\n hasResult: false,\n };\n span.first = Math.min(span.first, index);\n span.last = Math.max(span.last, index);\n if (kind === \"call\") span.hasCall = true;\n else span.hasResult = true;\n spans.set(id, span);\n };\n for (let index = 0; index < entries.length; index++) {\n const entry = entries[index]!;\n if (!isMessageEntry(entry)) continue;\n const message = entry.message as NonNullable<LiveEntry[\"message\"]>;\n for (const id of toolCallIdsOf(message)) record(id, index, \"call\");\n if (message.role === \"toolResult\" && typeof message.toolCallId === \"string\") {\n record(message.toolCallId, index, \"result\");\n }\n }\n return spans;\n};\n\nconst spanCrosses = (span: CallResultSpan, boundaryIndex: number): boolean =>\n span.hasCall\n && span.hasResult\n && span.first < boundaryIndex\n && span.last >= boundaryIndex;\n\nconst closureSafe = (spans: Map<string, CallResultSpan>, boundaryIndex: number): boolean =>\n [...spans.values()].every((span) => !spanCrosses(span, boundaryIndex));\n\nconst closeCut = (\n branchEntries: SessionEntry[],\n live: LiveEntry[],\n candidateLiveIndex: number,\n): number => {\n const spans = callResultSpans(branchEntries);\n let liveIndex = candidateLiveIndex;\n while (liveIndex > 0) {\n const boundaryIndex = live[liveIndex]!.branchIndex;\n let earliestCrossing = boundaryIndex;\n for (const span of spans.values()) {\n if (spanCrosses(span, boundaryIndex)) {\n earliestCrossing = Math.min(earliestCrossing, span.first);\n }\n }\n if (earliestCrossing === boundaryIndex) return liveIndex;\n const closed = previousBoundaryAtOrBefore(live, earliestCrossing);\n if (closed < 0 || closed >= liveIndex) return 0;\n liveIndex = closed;\n }\n return 0;\n};\n\nexport const rawContextTokens = (branchEntries: SessionEntry[]): number =>\n buildSessionContext(branchEntries).messages.reduce(\n (total, message) => total + estimateTokens(message),\n 0,\n );\n\ninterface UsageCheckpoint {\n rawTokens: number;\n contextTokens: number;\n}\n\nconst usageCheckpoints = (branchEntries: SessionEntry[]): UsageCheckpoint[] => {\n const lastCompaction = findLastCompaction(branchEntries);\n const startIndex = lastCompaction ? lastCompaction.index + 1 : 0;\n let rawTokens = lastCompaction\n ? rawContextTokens(branchEntries.slice(0, lastCompaction.index + 1))\n : 0;\n const checkpoints: UsageCheckpoint[] = [];\n for (let index = startIndex; index < branchEntries.length; index++) {\n for (const message of contextMessages(branchEntries[index]!)) {\n rawTokens += estimateTokens(message);\n if (message.role !== \"assistant\") continue;\n const contextTokens = calculateContextTokens(message.usage);\n if (Number.isFinite(contextTokens) && contextTokens > 0) {\n checkpoints.push({ rawTokens, contextTokens });\n }\n }\n }\n return checkpoints;\n};\n\n// Fit an upper affine envelope: context \u2248 fixed overhead + scale \u00D7 raw messages.\n// Only post-marker usage is comparable; the fallback treats all unexplained tokens as fixed.\nconst tokenCalibration = (\n branchEntries: SessionEntry[],\n tokensBefore: number,\n rawTokensBefore: number,\n): { tokenScale: number; fixedOverheadTokens: number } => {\n const minimumDelta = Math.max(4_096, Math.floor(rawTokensBefore * 0.1));\n const checkpoints = usageCheckpoints(branchEntries).filter(\n (checkpoint) => checkpoint.rawTokens < rawTokensBefore\n && checkpoint.contextTokens <= tokensBefore,\n );\n const slopes = checkpoints.flatMap((checkpoint) => {\n const rawDelta = rawTokensBefore - checkpoint.rawTokens;\n const contextDelta = tokensBefore - checkpoint.contextTokens;\n return rawDelta >= minimumDelta && contextDelta >= 0\n ? [contextDelta / rawDelta]\n : [];\n }).filter((slope) => Number.isFinite(slope) && slope >= 0);\n\n if (slopes.length === 0) {\n return {\n tokenScale: 1,\n fixedOverheadTokens: Math.max(0, tokensBefore - rawTokensBefore),\n };\n }\n\n const tokenScale = Math.max(1, ...slopes);\n const fixedOverheadTokens = Math.max(\n 0,\n tokensBefore - tokenScale * rawTokensBefore,\n ...checkpoints.map(\n (checkpoint) => checkpoint.contextTokens - tokenScale * checkpoint.rawTokens,\n ),\n );\n return { tokenScale, fixedOverheadTokens };\n};\n\nconst continuityCutPlan = (\n branchEntries: SessionEntry[],\n tokensBefore: number,\n budget: FabricCompactionBudget,\n): ContinuityCutPlan | undefined => {\n if (!Number.isFinite(budget.contextWindow) || budget.contextWindow <= 0) return undefined;\n const contextWindow = Math.floor(budget.contextWindow);\n const reserveTokens = Math.max(0, Math.floor(budget.reserveTokens));\n const keepRecentTokens = Math.max(0, Math.floor(budget.keepRecentTokens));\n const targetContextRatio = Math.max(0.25, Math.min(0.85, budget.targetContextRatio));\n const rawTokensBefore = rawContextTokens(branchEntries);\n const { tokenScale, fixedOverheadTokens } = tokenCalibration(\n branchEntries,\n tokensBefore,\n rawTokensBefore,\n );\n const continuityTargetTokens = Math.max(1, Math.ceil(\n fixedOverheadTokens + (keepRecentTokens + SUMMARY_RAW_TOKEN_BUDGET) * tokenScale,\n ));\n const occupancyCeilingTokens = Math.max(1, Math.floor(contextWindow * targetContextRatio));\n const hardCeiling = Math.max(1, contextWindow - reserveTokens);\n const safeCeilingTokens = Math.max(1, Math.floor(hardCeiling * HARD_CEILING_SAFETY_RATIO));\n const reductionCeilingTokens = Math.max(1, Math.floor(tokensBefore * MAX_PRECOMPACTION_RATIO));\n const constraints: Array<{\n binding: FabricCompactionBindingConstraint;\n tokens: number;\n }> = [\n { binding: \"continuity\", tokens: continuityTargetTokens },\n { binding: \"occupancy\", tokens: occupancyCeilingTokens },\n { binding: \"reserve\", tokens: safeCeilingTokens },\n { binding: \"reduction\", tokens: reductionCeilingTokens },\n ];\n const targetContextTokens = Math.min(...constraints.map(({ tokens }) => tokens));\n const bindingConstraint = constraints.find(\n ({ tokens }) => tokens === targetContextTokens,\n )!.binding;\n const rawPostBudget = Math.max(\n 0,\n Math.floor((targetContextTokens - fixedOverheadTokens) / tokenScale),\n );\n return {\n contextWindow,\n targetContextRatio,\n targetContextTokens,\n reserveTokens,\n keepRecentTokens,\n rawTokensBefore,\n tokenScale,\n fixedOverheadTokens,\n continuityTargetTokens,\n occupancyCeilingTokens,\n safeCeilingTokens,\n reductionCeilingTokens,\n rawTailTokenBudget: Math.max(0, rawPostBudget - SUMMARY_RAW_TOKEN_BUDGET),\n bindingConstraint,\n };\n};\n\nexport type CutResult =\n | {\n ok: true;\n summarized: SessionEntry[];\n firstKeptEntryId: string;\n firstSummarizedEntryId: string;\n lastSummarizedEntryId: string;\n lastTimestamp: string;\n budget?: Omit<FabricCompactionBudgetDetails, \"projectedTokensAfter\">;\n }\n | { ok: false; reason: \"empty\" };\n\nconst boundary = (\n summarized: SessionEntry[],\n firstKeptEntryId: string,\n budget?: Omit<FabricCompactionBudgetDetails, \"projectedTokensAfter\">,\n): CutResult => {\n if (summarized.length === 0) return { ok: false, reason: \"empty\" };\n const first = summarized[0]!;\n const last = summarized.at(-1)!;\n return {\n ok: true,\n summarized,\n firstKeptEntryId,\n firstSummarizedEntryId: first.id,\n lastSummarizedEntryId: last.id,\n lastTimestamp: last.timestamp,\n ...(budget ? { budget } : {}),\n };\n};\n\nconst computeContinuityCut = (\n branchEntries: SessionEntry[],\n live: LiveEntry[],\n plan: ContinuityCutPlan,\n): CutResult => {\n const suffixTokens = new Array<number>(live.length + 1).fill(0);\n for (let index = live.length - 1; index >= 0; index--) {\n suffixTokens[index] = suffixTokens[index + 1]! + live[index]!.estimatedTokens;\n }\n const spans = callResultSpans(branchEntries);\n // OMP replays entries contiguously from firstKeptEntryId, including compaction markers.\n const previousCompactionIndex = findLastCompaction(branchEntries)?.index ?? -1;\n let cutIndex = live.length;\n for (let index = 1; index < live.length; index++) {\n const item = live[index]!;\n if (item.branchIndex <= previousCompactionIndex) continue;\n if (!item.cutPoint || suffixTokens[index]! > plan.rawTailTokenBudget) continue;\n if (!closureSafe(spans, item.branchIndex)) continue;\n cutIndex = index;\n break;\n }\n const retainedRawTokens = suffixTokens[cutIndex] ?? 0;\n const details = {\n strategy: \"continuity\" as const,\n contextWindow: plan.contextWindow,\n targetContextRatio: plan.targetContextRatio,\n targetContextTokens: plan.targetContextTokens,\n reserveTokens: plan.reserveTokens,\n keepRecentTokens: plan.keepRecentTokens,\n rawTokensBefore: plan.rawTokensBefore,\n tokenScale: plan.tokenScale,\n fixedOverheadTokens: plan.fixedOverheadTokens,\n retainedRawTokens,\n continuityTargetTokens: plan.continuityTargetTokens,\n occupancyCeilingTokens: plan.occupancyCeilingTokens,\n safeCeilingTokens: plan.safeCeilingTokens,\n reductionCeilingTokens: plan.reductionCeilingTokens,\n rawTailTokenBudget: plan.rawTailTokenBudget,\n bindingConstraint: plan.bindingConstraint,\n };\n if (cutIndex >= live.length) {\n return boundary(live.map((item) => item.entry), \"\", details);\n }\n return boundary(\n live.slice(0, cutIndex).map((item) => item.entry),\n live[cutIndex]!.entry.id,\n details,\n );\n};\n\nexport const computeCut = (\n branchEntries: SessionEntry[],\n options?: { tokensBefore: number; budget: FabricCompactionBudget },\n): CutResult => {\n const live = collectLive(branchEntries);\n if (live.length === 0) return { ok: false, reason: \"empty\" };\n\n if (options) {\n const plan = continuityCutPlan(branchEntries, options.tokensBefore, options.budget);\n if (plan) return computeContinuityCut(branchEntries, live, plan);\n }\n\n const lastBoundary = lastBoundaryIndex(live);\n if (lastBoundary <= 0) return boundary(live.map((item) => item.entry), \"\");\n const closed = closeCut(branchEntries, live, lastBoundary);\n const previousCompactionIndex = findLastCompaction(branchEntries)?.index ?? -1;\n if (closed <= 0 || live[closed]!.branchIndex <= previousCompactionIndex) {\n return boundary(live.map((item) => item.entry), \"\");\n }\n\n return boundary(\n live.slice(0, closed).map((item) => item.entry),\n live[closed]!.entry.id,\n );\n};\n\ninterface FabricCompactionDetailsV1 {\n compactor: \"fabric\";\n version: 1;\n sections: string[];\n summarizedEntryRange: { first: string; last: string };\n sourceEntryCount: number;\n firstKeptEntryId: string;\n timestamp: string;\n}\n\ninterface EntryRange {\n first: string;\n last: string;\n}\n\nexport interface FabricCompactionDetailsV2 {\n compactor: \"fabric\";\n version: 2;\n sections: string[];\n coverage: {\n cumulativeSourceRange: EntryRange;\n liveCutRange: EntryRange;\n };\n counts: {\n branchEntries: number;\n cumulativeSourceEntries: number;\n sourceEvents: number;\n liveCutEntries: number;\n priorFabricV1: number;\n priorFabricV2: number;\n };\n omittedCounts: ProjectionOmittedCounts & { preserve: number; thinking?: number };\n instructionPolicy: CompactionInstructionPolicy;\n stableAddresses: {\n firstKeptEntryId: string;\n cumulativeSourceRange: EntryRange;\n recall: \"session-entry-id-range\";\n };\n budget?: FabricCompactionBudgetDetails;\n timestamp: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst isEntryRange = (value: unknown): boolean =>\n isRecord(value) && typeof value.first === \"string\" && typeof value.last === \"string\";\n\nconst isStringArray = (value: unknown): boolean =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nconst isFabricV1Details = (value: Record<string, unknown>): boolean =>\n isStringArray(value.sections)\n && isEntryRange(value.summarizedEntryRange)\n && typeof value.sourceEntryCount === \"number\"\n && Number.isFinite(value.sourceEntryCount)\n && typeof value.firstKeptEntryId === \"string\"\n && typeof value.timestamp === \"string\";\n\nconst hasFiniteNumbers = (value: Record<string, unknown>, keys: readonly string[]): boolean =>\n keys.every((key) => typeof value[key] === \"number\" && Number.isFinite(value[key]));\n\nconst isCompactionBudgetDetails = (value: unknown): boolean => {\n if (!isRecord(value) || (value.strategy !== \"adaptive\" && value.strategy !== \"continuity\")) {\n return false;\n }\n if (!hasFiniteNumbers(value, [\n \"contextWindow\",\n \"targetContextRatio\",\n \"targetContextTokens\",\n \"reserveTokens\",\n \"keepRecentTokens\",\n \"rawTokensBefore\",\n \"tokenScale\",\n \"fixedOverheadTokens\",\n \"retainedRawTokens\",\n \"projectedTokensAfter\",\n ])) {\n return false;\n }\n if (value.strategy === \"adaptive\") return true;\n return hasFiniteNumbers(value, [\n \"continuityTargetTokens\",\n \"occupancyCeilingTokens\",\n \"safeCeilingTokens\",\n \"reductionCeilingTokens\",\n \"rawTailTokenBudget\",\n ])\n && (\n value.bindingConstraint === \"continuity\"\n || value.bindingConstraint === \"occupancy\"\n || value.bindingConstraint === \"reserve\"\n || value.bindingConstraint === \"reduction\"\n );\n};\n\nconst isFabricV2Details = (value: Record<string, unknown>): boolean => {\n if (!isStringArray(value.sections) || !isRecord(value.coverage) || !isRecord(value.counts)) return false;\n if (!isRecord(value.omittedCounts) || !isRecord(value.instructionPolicy) || !isRecord(value.stableAddresses)) {\n return false;\n }\n const instructionModes = new Set([\"none\", \"plain\", \"typed-v1\", \"malformed-typed-prefix\"]);\n return isEntryRange(value.coverage.cumulativeSourceRange)\n && isEntryRange(value.coverage.liveCutRange)\n && hasFiniteNumbers(value.counts, [\n \"branchEntries\",\n \"cumulativeSourceEntries\",\n \"sourceEvents\",\n \"liveCutEntries\",\n \"priorFabricV1\",\n \"priorFabricV2\",\n ])\n && hasFiniteNumbers(value.omittedCounts, [\n \"goal\",\n \"files\",\n \"outstanding\",\n \"earlierTurns\",\n \"transcript\",\n \"preserve\",\n ])\n && (value.omittedCounts.activity === undefined\n || (typeof value.omittedCounts.activity === \"number\" && Number.isFinite(value.omittedCounts.activity)))\n && (value.omittedCounts.commits === undefined\n || (typeof value.omittedCounts.commits === \"number\" && Number.isFinite(value.omittedCounts.commits)))\n && (value.omittedCounts.thinking === undefined\n || (typeof value.omittedCounts.thinking === \"number\" && Number.isFinite(value.omittedCounts.thinking)))\n && typeof value.instructionPolicy.mode === \"string\"\n && instructionModes.has(value.instructionPolicy.mode)\n && typeof value.instructionPolicy.canonicalized === \"boolean\"\n && typeof value.instructionPolicy.truncated === \"boolean\"\n && hasFiniteNumbers(value.instructionPolicy, [\n \"sourceBytes\",\n \"preserveCount\",\n \"omittedPreserveCount\",\n ])\n && typeof value.stableAddresses.firstKeptEntryId === \"string\"\n && isEntryRange(value.stableAddresses.cumulativeSourceRange)\n && value.stableAddresses.recall === \"session-entry-id-range\"\n && (value.budget === undefined || isCompactionBudgetDetails(value.budget))\n && typeof value.timestamp === \"string\";\n};\n\nexport const fabricCompactionVersion = (details: unknown): 1 | 2 | undefined => {\n if (!isRecord(details) || details.compactor !== \"fabric\") return undefined;\n if (details.version === 1 && isFabricV1Details(details)) return 1;\n if (details.version === 2 && isFabricV2Details(details)) return 2;\n return undefined;\n};\n\nconst cumulativeSource = (\n branchEntries: SessionEntry[],\n firstKeptEntryId: string,\n): { entries: SessionEntry[]; prefixEntries: SessionEntry[]; events: ReturnType<typeof normalizeEntries>; range: EntryRange; timestamp: string } => {\n const boundaryIndex = firstKeptEntryId\n ? branchEntries.findIndex((entry) => entry.id === firstKeptEntryId)\n : branchEntries.length;\n const prefix = branchEntries.slice(0, boundaryIndex >= 0 ? boundaryIndex : branchEntries.length);\n const events = normalizeEntries(prefix);\n const contentEntryIds = new Set(events.map((event) => event.sourceEntryId));\n const entries = prefix.filter((entry) => contentEntryIds.has(entry.id));\n return {\n entries,\n prefixEntries: prefix,\n events,\n range: {\n first: entries[0]?.id ?? \"\",\n last: entries.at(-1)?.id ?? \"\",\n },\n timestamp: entries.at(-1)?.timestamp ?? \"\",\n };\n};\n\nconst priorFabricVersions = (entries: SessionEntry[]): { v1: number; v2: number } => {\n let v1 = 0;\n let v2 = 0;\n for (const entry of entries) {\n if (entry.type !== \"compaction\") continue;\n const version = fabricCompactionVersion((entry as SessionEntry & { details?: unknown }).details);\n if (version === 1) v1 += 1;\n if (version === 2) v2 += 1;\n }\n return { v1, v2 };\n};\n\nexport const compileFabricSummary = (\n branchEntries: SessionEntry[],\n tokensBefore: number,\n enrichers: readonly CompactionEnricher[] = NO_BUILTIN_ENRICHERS,\n customInstructions?: string,\n budget?: FabricCompactionBudget,\n): { compaction: CompactionResult<FabricCompactionDetailsV2> } | {\n cancel: true;\n reason: string;\n instructionError?: CompactionInstructionDecodeError;\n} => {\n const instructions = decodeCompactionInstructions(customInstructions);\n if (!instructions.ok) {\n return {\n cancel: true,\n reason: `fabric: ${instructions.error.code}: ${instructions.error.message}`,\n instructionError: instructions.error,\n };\n }\n const cut = computeCut(\n branchEntries,\n budget ? { tokensBefore, budget } : undefined,\n );\n if (!cut.ok) return { cancel: true, reason: \"fabric: nothing to compact\" };\n\n const source = cumulativeSource(branchEntries, cut.firstKeptEntryId);\n if (source.events.length === 0) return { cancel: true, reason: \"fabric: no raw cumulative source\" };\n const projected = projectWithMetadata(source.events);\n const sections: Sections = projected.sections;\n runEnrichers(enrichers, source.events, sections);\n\n const summary = renderSummary(sections, {\n firstEntryId: source.range.first,\n lastEntryId: source.range.last,\n lastTimestamp: source.timestamp,\n requestLines: instructions.requestLines,\n });\n const projectedTokensAfter = cut.budget\n ? Math.ceil(\n cut.budget.fixedOverheadTokens\n + (cut.budget.retainedRawTokens + Math.ceil(summary.length / 4))\n * cut.budget.tokenScale,\n )\n : undefined;\n const budgetDetails = cut.budget && projectedTokensAfter !== undefined\n ? { ...cut.budget, projectedTokensAfter }\n : undefined;\n // The maximum-summary reservation should make this unreachable unless fixed overhead alone\n // makes the target infeasible. Never persist an expanding or nominally unsafe result.\n if (budgetDetails && budgetDetails.projectedTokensAfter > budgetDetails.targetContextTokens) {\n return {\n cancel: true,\n reason: \"fabric: no deterministic summary fits the continuity context target\",\n };\n }\n const versions = priorFabricVersions(branchEntries);\n const sectionHeaders = SECTION_HEADERS\n .filter(({ key }) => sections[key].length > 0)\n .map(({ header }) => header);\n if (instructions.requestLines.length > 0) sectionHeaders.splice(1, 0, \"[Compaction Request]\");\n\n const details: FabricCompactionDetailsV2 = {\n compactor: \"fabric\",\n version: 2,\n sections: sectionHeaders,\n coverage: {\n cumulativeSourceRange: source.range,\n liveCutRange: {\n first: cut.firstSummarizedEntryId,\n last: cut.lastSummarizedEntryId,\n },\n },\n counts: {\n branchEntries: branchEntries.length,\n cumulativeSourceEntries: source.entries.length,\n sourceEvents: source.events.length,\n liveCutEntries: cut.summarized.length,\n priorFabricV1: versions.v1,\n priorFabricV2: versions.v2,\n },\n omittedCounts: {\n ...projected.omittedCounts,\n preserve: instructions.policy.omittedPreserveCount,\n // Thinking parts never survive normalization into a rendered summary;\n // the structural count keeps that erasure auditable against the raw\n // prefix instead of letting deliberation vanish untracked.\n thinking: countErasedThinkingBlocks(source.prefixEntries),\n },\n instructionPolicy: instructions.policy,\n stableAddresses: {\n firstKeptEntryId: cut.firstKeptEntryId,\n cumulativeSourceRange: source.range,\n recall: \"session-entry-id-range\",\n },\n ...(budgetDetails ? { budget: budgetDetails } : {}),\n timestamp: source.timestamp,\n };\n\n return {\n compaction: {\n summary,\n firstKeptEntryId: cut.firstKeptEntryId,\n tokensBefore,\n details,\n },\n };\n};\n\nconst SECTION_HEADERS: { key: keyof Sections; header: string }[] = [\n { key: \"goal\", header: \"[Session Goal]\" },\n { key: \"files\", header: \"[Files And Changes]\" },\n { key: \"activity\", header: \"[Fabric Activity]\" },\n { key: \"outstanding\", header: \"[Outstanding Context]\" },\n { key: \"earlierTurns\", header: \"[Earlier Turns]\" },\n { key: \"status\", header: \"[Current Status]\" },\n];\n\nexport interface LcmCompactionInput {\n branchEntries: readonly SessionEntry[];\n sessionId: string;\n firstKeptEntryId: string;\n tokensBefore: number;\n isSplitTurn?: boolean;\n customInstructions?: string;\n}\n\nexport interface LcmCompactionOutput {\n summary: string;\n firstKeptEntryId: string;\n tokensBefore: number;\n source: \"ready-frontier\" | \"emergency\";\n details?: unknown;\n}\n\ninterface LcmCompactionOptions {\n compact: (input: LcmCompactionInput) => LcmCompactionOutput | undefined;\n}\n\nexport interface CompactionHookOptions {\n getEngine: () => CompactionEngine;\n getTargetContextRatio?: () => number;\n enrichers?: readonly CompactionEnricher[];\n lcm?: LcmCompactionOptions;\n}\n\nconst notifyInstructionError = (\n context: ExtensionContext | undefined,\n error: CompactionInstructionDecodeError,\n): void => {\n if (!context?.hasUI) return;\n context.ui.notify(clipUtf8(`Fabric compaction rejected: ${error.code}: ${error.message}`, 512), \"error\");\n};\n\nexport const registerCompactionHook = (omp: ExtensionAPI, options: CompactionHookOptions): void => {\n omp.on(\"session_before_compact\", (event: SessionBeforeCompactEvent, context: ExtensionContext) => {\n if (options.getEngine() === \"omp\") return;\n if (!options.lcm) return { cancel: true };\n const instructions = decodeCompactionInstructions(event.customInstructions);\n if (!instructions.ok) {\n notifyInstructionError(context, instructions.error);\n return { cancel: true };\n }\n const branchEntries = event.branchEntries ?? [];\n const sessionManager = context?.sessionManager;\n const sessionId = sessionManager?.getSessionId?.() ?? \"\";\n let output: LcmCompactionOutput | undefined;\n try {\n output = options.lcm.compact({\n branchEntries,\n sessionId,\n firstKeptEntryId: event.preparation.firstKeptEntryId,\n tokensBefore: event.preparation.tokensBefore,\n ...(typeof (event.preparation as { isSplitTurn?: unknown }).isSplitTurn === \"boolean\" ? { isSplitTurn: (event.preparation as { isSplitTurn: boolean }).isSplitTurn } : {}),\n ...(event.customInstructions === undefined ? {} : { customInstructions: event.customInstructions }),\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n console.warn(`[omp-fabric] LCM compaction failed: ${message}`);\n if (context?.hasUI) context.ui.notify(`LCM compaction failed: ${message}`, \"error\");\n return { cancel: true };\n }\n if (!output || typeof output.summary !== \"string\" || output.summary.length === 0\n || (output.source !== \"ready-frontier\" && output.source !== \"emergency\")\n || output.tokensBefore !== event.preparation.tokensBefore\n || typeof output.firstKeptEntryId !== \"string\"\n || branchEntries.length === 0\n || (output.firstKeptEntryId.length > 0 && !branchEntries.some((entry) => entry.id === output.firstKeptEntryId))) {\n return { cancel: true };\n }\n return {\n compaction: {\n summary: output.summary,\n firstKeptEntryId: output.firstKeptEntryId,\n tokensBefore: output.tokensBefore,\n details: {\n compactor: \"lcm\",\n source: output.source,\n ...(output.details && typeof output.details === \"object\" ? output.details : {}),\n },\n },\n };\n });\n\n omp.on(\"session_before_tree\", (event: SessionBeforeTreeEvent) => {\n if (options.getEngine() !== \"lcm\" || !event.preparation.userWantsSummary) return;\n const compiled = compileLcmBranchSummary(\n event.preparation.entriesToSummarize,\n undefined,\n options.enrichers,\n event.preparation.oldLeafId,\n );\n if (!compiled) return;\n return { summary: compiled };\n });\n};\n", "// Mirrors the OMP host tokenizer for the block and role kinds Fabric projects,\n// verified against @oh-my-pi/pi-coding-agent/extensibility/legacy-pi-coding-agent-shim.\n\nconst IMAGE_TOKEN_ESTIMATE = 1200;\nconst FRAME_TOKEN_ESTIMATE = 5024;\n\nexport const DEFAULT_COMPACTION_SETTINGS = {\n enabled: true,\n reserveTokens: 16384,\n keepRecentTokens: 20000,\n} as const;\n\ninterface TokenContentPart {\n type: string;\n text?: string;\n thinking?: string;\n thinkingSignature?: string;\n data?: string;\n block?: unknown;\n name?: string;\n arguments?: unknown;\n}\n\ntype TokenMessage = {\n role: string;\n content?: unknown;\n command?: unknown;\n output?: unknown;\n summary?: unknown;\n blocks?: readonly TokenContentPart[];\n images?: readonly unknown[];\n};\n\nconst contentParts = (content: unknown): readonly TokenContentPart[] =>\n Array.isArray(content) ? (content as readonly TokenContentPart[]) : [];\n\nconst stringifyArguments = (value: unknown): string => {\n try {\n return JSON.stringify(value) ?? \"null\";\n } catch {\n try {\n return JSON.stringify(value, (_key, nested) => (typeof nested === \"bigint\" ? nested.toString() : nested)) ?? \"null\";\n } catch {\n return \"null\";\n }\n }\n};\n\nconst blockTokens = (chars: number): number => (chars > 0 ? Math.ceil(chars / 4) : 0);\n\nconst textLength = (value: unknown): number =>\n typeof value === \"string\" ? Buffer.byteLength(value, \"utf-8\") : 0;\n\nexport const estimateTokens = (message: TokenMessage): number => {\n let tokens = 0;\n switch (message.role) {\n case \"user\":\n case \"developer\": {\n if (typeof message.content === \"string\") return blockTokens(textLength(message.content));\n for (const block of contentParts(message.content)) {\n if (block.type === \"text\") tokens += blockTokens(textLength(block.text));\n else if (block.type === \"image\") tokens += IMAGE_TOKEN_ESTIMATE;\n }\n return tokens;\n }\n case \"assistant\": {\n for (const block of contentParts(message.content)) {\n if (block.type === \"text\") {\n tokens += blockTokens(textLength(block.text));\n } else if (block.type === \"thinking\") {\n tokens += blockTokens(textLength(block.thinking));\n tokens += blockTokens(textLength(block.thinkingSignature));\n } else if (block.type === \"toolCall\") {\n tokens += blockTokens(textLength(block.name));\n tokens += blockTokens(textLength(stringifyArguments(block.arguments)));\n } else if (block.type === \"redactedThinking\") {\n tokens += blockTokens(textLength(block.data));\n } else if (block.type === \"anthropicServerTool\") {\n tokens += blockTokens(textLength(stringifyArguments(block.block)));\n }\n }\n return tokens;\n }\n case \"custom\":\n case \"hookMessage\":\n case \"toolResult\": {\n if (typeof message.content === \"string\") return blockTokens(textLength(message.content));\n for (const block of contentParts(message.content)) {\n if (block.type === \"text\") tokens += blockTokens(textLength(block.text));\n else if (block.type === \"image\") tokens += IMAGE_TOKEN_ESTIMATE;\n }\n return tokens;\n }\n case \"bashExecution\":\n return blockTokens(textLength(message.command)) + blockTokens(textLength(message.output));\n case \"branchSummary\":\n return blockTokens(textLength(message.summary));\n case \"compactionSummary\": {\n tokens = blockTokens(textLength(message.summary));\n if (message.blocks) {\n for (const block of message.blocks) {\n if (block.type === \"text\") tokens += blockTokens(textLength(block.text));\n else tokens += FRAME_TOKEN_ESTIMATE;\n }\n } else if (message.images) {\n tokens += message.images.length * FRAME_TOKEN_ESTIMATE;\n }\n return tokens;\n }\n }\n return 0;\n};\n\nexport const calculateContextTokens = (usage: unknown): number => {\n if (typeof usage !== \"object\" || usage === null) return 0;\n const record = usage as Record<string, unknown>;\n const totalTokens = record.totalTokens;\n // Host evaluates `usage.totalTokens || input + output + ...`; zero and\n // missing totals both fall through to the component sum.\n if (typeof totalTokens === \"number\" && totalTokens > 0) return totalTokens;\n const count = (value: unknown): number => (typeof value === \"number\" ? value : 0);\n return count(record.input) + count(record.output) + count(record.cacheRead) + count(record.cacheWrite);\n};\n", "import { buildSessionContext as buildOmpSessionContext } from \"@oh-my-pi/pi-coding-agent/session/session-context\";\nimport type { SessionContext } from \"@oh-my-pi/pi-coding-agent/session/session-context\";\nimport type { SessionEntry } from \"@oh-my-pi/pi-coding-agent\";\n\nexport type ContextMessage = SessionContext[\"messages\"][number];\n\nexport const sessionEntryToContextMessages = (entry: SessionEntry): ContextMessage[] =>\n buildOmpSessionContext([entry], entry.id, new Map([[entry.id, entry]]), {\n transcript: true,\n keepDanglingToolCalls: true,\n }).messages;\n\nexport const buildSessionContext = (\n entries: readonly SessionEntry[],\n leafId?: string,\n byId?: Map<string, SessionEntry>,\n): SessionContext => buildOmpSessionContext([...entries], leafId, byId);\n", "import type { ExtensionContext } from \"@oh-my-pi/pi-coding-agent\";\nimport type { FabricConfig } from \"../config.js\";\n\nexport const modelCompactionKey = (\n model: Pick<NonNullable<ExtensionContext[\"model\"]>, \"provider\" | \"id\"> | undefined,\n): string | undefined => model ? `${model.provider}/${model.id}` : undefined;\n\n// A configured token threshold takes precedence over a ratio for the same\n// model; the settings UI keeps the maps mutually exclusive, and hand-written\n// configs resolve to the more explicit token value.\nconst configuredCompactionTokenThreshold = (\n config: FabricConfig,\n modelKey: string | undefined,\n): number | undefined =>\n modelKey === undefined ? undefined : config.compaction.tokenThresholds[modelKey];\n\nconst configuredCompactionThreshold = (\n config: FabricConfig,\n modelKey: string | undefined,\n): number | undefined =>\n modelKey === undefined ? undefined : config.compaction.thresholds[modelKey];\n\nconst runThresholdCompact = async (context: ExtensionContext): Promise<boolean> => {\n try {\n await context.compact();\n return true;\n } catch (error) {\n if (context.hasUI) {\n context.ui.notify(`Fabric threshold compaction failed: ${error instanceof Error ? error.message : String(error)}`, \"warning\");\n }\n return false;\n }\n};\n\nexport const compactAtConfiguredThreshold = async (\n context: ExtensionContext,\n config: FabricConfig,\n): Promise<boolean> => {\n const modelKey = modelCompactionKey(context.model);\n const usage = context.getContextUsage();\n if (usage === undefined) return false;\n\n const tokenThreshold = configuredCompactionTokenThreshold(config, modelKey);\n if (tokenThreshold !== undefined) {\n if (usage.tokens === null || usage.tokens < tokenThreshold) return false;\n return runThresholdCompact(context);\n }\n\n const threshold = configuredCompactionThreshold(config, modelKey)\n ?? (config.compaction.hardThresholdRatio > 0 ? config.compaction.hardThresholdRatio : undefined);\n if (threshold === undefined || usage.percent === null) return false;\n if (usage.percent / 100 < threshold) return false;\n\n return runThresholdCompact(context);\n};\n", "import type { CompactionEvent } from \"./normalize.js\";\nimport type { Sections } from \"./projections.js\";\n\n// Optional, isolated, format-specific annotation. The deterministic core\n// never inspects prose (principle 2); anything that needs to \u2014 e.g. pulling a\n// TypeScript compiler line number out of a bash `tsc` result, or annotating a\n// test-failure section \u2014 plugs in here, behind this interface. The core ships\n// ZERO built-in enrichers on purpose: the redistilled core is the minimal clean\n// baseline, and prose understanding is an additive concern an extension can\n// register later without touching the projections.\n//\n// An enricher is called once per compaction, AFTER the structural sections are\n// computed. It may append to (or replace) any section. It must be deterministic:\n// the same event stream must yield the same contribution, so the overall\n// serialization stays byte-identical for a given input (principle 5).\nexport interface CompactionEnricher {\n readonly name: string;\n // Decide whether this enricher has anything to add for the given event\n // stream. Returning false lets the core skip contribute() cheaply.\n applies(events: CompactionEvent[]): boolean;\n // Mutate `sections` in place to add format-specific annotation. The full\n // event stream is available so the enricher can derive its own state without\n // re-walking the raw log differently from the core.\n contribute(events: CompactionEvent[], sections: Sections): void;\n}\n\n// No built-in enrichers. Kept explicit (and exported) so tests and docs can\n// reference the empty set and so the registration path stays exercised.\nexport const NO_BUILTIN_ENRICHERS: readonly CompactionEnricher[] = Object.freeze([]);\n\nexport const runEnrichers = (\n enrichers: readonly CompactionEnricher[],\n events: CompactionEvent[],\n sections: Sections,\n): void => {\n for (const enricher of enrichers) {\n if (!enricher.applies(events)) continue;\n enricher.contribute(events, sections);\n }\n};\n", "import type { FabricRunDisplay } from \"./activity/types.js\";\n\n// Silent repair for fabric_exec `display` near-misses. The declared shape is\n// the object { name?, description? }, but models reliably cold-start with a\n// bare objective string (or a JSON-stringified object) instead, which strict\n// schema validation used to reject at the cost of a zero-work round trip.\n// Both spellings carry identical intent, so coerce them. See the\n// flat-tool-schema note in fabric-exec-tool.ts.\n\nconst recordDisplay = (record: Record<string, unknown>): FabricRunDisplay | undefined => {\n const display: FabricRunDisplay = {};\n if (typeof record.name === \"string\") display.name = record.name;\n if (typeof record.description === \"string\") display.description = record.description;\n return display.name !== undefined || display.description !== undefined ? display : undefined;\n};\n\nconst parseObjectString = (text: string): Record<string, unknown> | undefined => {\n if (!text.startsWith(\"{\") || !text.endsWith(\"}\")) return undefined;\n try {\n const parsed: unknown = JSON.parse(text);\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nexport const normalizeRunDisplay = (input: unknown): FabricRunDisplay | undefined => {\n if (typeof input === \"string\") {\n const text = input.trim();\n if (!text) return undefined;\n const parsed = text.startsWith(\"{\") ? parseObjectString(text) : undefined;\n // Fall back to the raw string as the name: intent preservation beats shape\n // pedantry for a cosmetic label.\n return (parsed && recordDisplay(parsed)) ?? { name: input };\n }\n if (typeof input === \"object\" && input !== null && !Array.isArray(input)) {\n return recordDisplay(input as Record<string, unknown>);\n }\n return undefined;\n};\n", "import { fabricExecTitleHint } from \"./fabric-code-parser.js\";\n\n// Session-wide memo for the lexical fallback title, keyed by the exact program\n// string. The same key recurs in three places \u2014 the compact renderCall card\n// (re-rendered on every streaming tick), the activity store start, and\n// compaction normalization over recorded arguments \u2014 so one tokenize pass per\n// unique program covers all three. Bounded with insertion-order eviction: run\n// names stay cheap for arbitrarily long sessions without retention growth.\nconst TITLE_HINT_CACHE_MAX = 256;\n\nconst titleHintCache = new Map<string, string | undefined>();\n\nexport const fabricExecTitleHintCached = (code: string): string | undefined => {\n const hit = titleHintCache.get(code);\n if (hit !== undefined || titleHintCache.has(code)) return hit;\n const hint = fabricExecTitleHint(code);\n if (titleHintCache.size >= TITLE_HINT_CACHE_MAX) {\n const oldest = titleHintCache.keys().next().value;\n if (oldest !== undefined) titleHintCache.delete(oldest);\n }\n titleHintCache.set(code, hint);\n return hint;\n};", "import type { SessionEntry, SessionMessageEntry } from \"@oh-my-pi/pi-coding-agent\";\nimport type { FabricExecutionOutcomeV1, FabricTraceJsonValue } from \"../audit/trace.js\";\nimport { readFabricProjectionTrace, type FabricProjectionSource } from \"./trace-events.js\";\nimport {\n FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES,\n FABRIC_BRANCH_RUN_NAME_MAX_BYTES,\n readFabricBranchSummaryDetails,\n} from \"./branch-details.js\";\nimport { clipUtf8, utf8Bytes } from \"./bounds.js\";\nimport { normalizeRunDisplay } from \"../run-display.js\";\nimport { fabricExecTitleHintCached } from \"../ui/fabric-title-hint.js\";\n\n// A purely structural, typed view of one session window. Every event carries\n// the 1-based `index` it occupied in the normalized stream (stable, used by the\n// brief-transcript `(#N)` references), a stable fact `entryId`, and the actual\n// `sourceEntryId` that carried it. Normalization extracts ONLY\n// typed structure \u2014 roles, tool names, JSON arguments, isError flags, bash\n// commands and exit codes. It never inspects prose. See docs/compaction.md\n// principle 2.\n//\n// Assistant thinking parts are deliberate scratchpad, not commitments: they are\n// never normalized into events, so no summary section can leak truncated\n// deliberation that reads like fact. `countErasedThinkingBlocks` keeps that\n// erasure auditable in compaction details. See docs/compaction.md (Transcript).\n\ninterface EventBase {\n index: number;\n entryId: string;\n sourceEntryId: string;\n}\n\ninterface UserEvent extends EventBase {\n kind: \"user\";\n text: string;\n}\n\ninterface AssistantTextEvent extends EventBase {\n kind: \"assistantText\";\n text: string;\n}\n\ninterface CustomMessageEvent extends EventBase {\n kind: \"customMessage\";\n customType: string;\n text: string;\n display: boolean;\n details?: FabricTraceJsonValue;\n}\n\nexport interface ToolCallEvent extends EventBase {\n kind: \"toolCall\";\n toolCallId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\ninterface ToolResultEvent extends EventBase {\n kind: \"toolResult\";\n toolCallId: string;\n toolName: string;\n isError: boolean;\n text: string;\n}\n\ninterface BashEvent extends EventBase {\n kind: \"bash\";\n toolCallId: string;\n command: string;\n isError: boolean;\n exitCode: number | null;\n error?: string;\n}\n\ninterface FabricPhaseEvent extends EventBase {\n kind: \"fabricPhase\";\n subordinal: string;\n address: string;\n phase: string;\n}\n\nexport interface FabricRunEvent extends EventBase {\n kind: \"fabricRun\";\n toolCallId: string;\n subordinal: string;\n address: string;\n name: string;\n description?: string;\n outcome: FabricExecutionOutcomeV1;\n source: FabricProjectionSource | \"result\" | \"branch\";\n}\n\ninterface FabricOperationEvent extends EventBase {\n kind: \"fabricOperation\";\n subordinal: string;\n address: string;\n ref: string;\n provider?: string;\n action?: string;\n tool: string;\n args: Record<string, FabricTraceJsonValue>;\n outcome: FabricExecutionOutcomeV1;\n error?: string;\n result?: FabricTraceJsonValue;\n source: FabricProjectionSource | \"branch\";\n}\n\nexport type CompactionEvent =\n | UserEvent\n | AssistantTextEvent\n | CustomMessageEvent\n | ToolCallEvent\n | ToolResultEvent\n | BashEvent\n | FabricPhaseEvent\n | FabricRunEvent\n | FabricOperationEvent;\n\nconst isMessageEntry = (entry: SessionEntry): entry is Extract<SessionEntry, { type: \"message\" }> =>\n entry.type === \"message\";\n\nconst MAX_CUSTOM_DETAILS_DEPTH = 12;\nconst MAX_CUSTOM_DETAILS_NODES = 256;\nconst MAX_CUSTOM_DETAILS_COLLECTION = 64;\nconst MAX_CUSTOM_DETAILS_STRING_BYTES = 1024;\nconst MAX_CUSTOM_DETAILS_BYTES = 8 * 1024;\n\ninterface JsonSanitizerState {\n nodes: number;\n ancestors: Set<object>;\n}\n\nconst boundedJsonValue = (\n value: unknown,\n state: JsonSanitizerState,\n depth = 0,\n): FabricTraceJsonValue | undefined => {\n state.nodes += 1;\n if (state.nodes > MAX_CUSTOM_DETAILS_NODES) return undefined;\n if (value === null || typeof value === \"boolean\") return value;\n if (typeof value === \"string\") return clipUtf8(value, MAX_CUSTOM_DETAILS_STRING_BYTES);\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value !== \"object\" || depth > MAX_CUSTOM_DETAILS_DEPTH || state.ancestors.has(value)) return undefined;\n state.ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n const output: FabricTraceJsonValue[] = [];\n for (const item of value.slice(0, MAX_CUSTOM_DETAILS_COLLECTION)) {\n const sanitized = boundedJsonValue(item, state, depth + 1);\n if (sanitized === undefined) return undefined;\n output.push(sanitized);\n }\n return output;\n }\n const output = Object.create(null) as Record<string, FabricTraceJsonValue>;\n const keys = Object.keys(value).sort().slice(0, MAX_CUSTOM_DETAILS_COLLECTION);\n for (const key of keys) {\n const sanitized = boundedJsonValue((value as Record<string, unknown>)[key], state, depth + 1);\n if (sanitized === undefined) return undefined;\n output[key] = sanitized;\n }\n return output;\n } finally {\n state.ancestors.delete(value);\n }\n};\n\nconst customDetails = (value: unknown): FabricTraceJsonValue | undefined => {\n if (value === undefined) return undefined;\n try {\n const sanitized = boundedJsonValue(value, { nodes: 0, ancestors: new Set<object>() });\n if (sanitized === undefined || utf8Bytes(JSON.stringify(sanitized)) > MAX_CUSTOM_DETAILS_BYTES) return undefined;\n return sanitized;\n } catch {\n return undefined;\n }\n};\n\nconst isTypedCustomContent = (content: unknown): boolean => {\n if (typeof content === \"string\") return true;\n if (!Array.isArray(content)) return false;\n return content.every((part) => {\n if (part === null || typeof part !== \"object\") return false;\n const candidate = part as { type?: unknown; text?: unknown };\n if (candidate.type === \"text\") return typeof candidate.text === \"string\";\n return candidate.type === \"image\";\n });\n};\n\nexport const isOmpCustomMessageEntry = (\n entry: SessionEntry,\n): entry is Extract<SessionEntry, { type: \"custom_message\" }> => {\n try {\n if (entry.type !== \"custom_message\") return false;\n const candidate = entry as SessionEntry & {\n customType?: unknown;\n content?: unknown;\n display?: unknown;\n };\n return typeof candidate.customType === \"string\"\n && typeof candidate.display === \"boolean\"\n && isTypedCustomContent(candidate.content);\n } catch {\n return false;\n }\n};\n\nconst textOfContent = (content: unknown): string => {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content) {\n if (part && typeof part === \"object\" && \"type\" in part) {\n if (part.type === \"text\" && typeof part.text === \"string\") parts.push(part.text);\n }\n }\n return parts.join(\"\\n\");\n};\n\nconst firstLine = (text: string): string => {\n const trimmed = text.trimStart();\n const nl = trimmed.indexOf(\"\\n\");\n return nl < 0 ? trimmed : trimmed.slice(0, nl);\n};\n\ninterface PendingCall {\n entryId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\ninterface FabricRunIntent {\n name: string;\n description?: string;\n}\n\nconst fabricRunIntent = (call: PendingCall | undefined): FabricRunIntent | undefined => {\n if (!call || call.name !== \"fabric_exec\") return undefined;\n const display = normalizeRunDisplay(call.args.display);\n // Fallback parity with the compact card header and the activity feed: when\n // no name is declared, derive one lexically from the recorded program so\n // intent continuity never depends on the live UI. A declared description is\n // preserved even when the name comes from the program.\n const intentName = display?.name?.trim()\n ? display.name\n : typeof call.args.code === \"string\"\n ? fabricExecTitleHintCached(call.args.code)\n : undefined;\n if (intentName === undefined) return undefined;\n const name = clipUtf8(intentName.trim(), FABRIC_BRANCH_RUN_NAME_MAX_BYTES);\n if (!name) return undefined;\n const description = display?.description !== undefined\n ? clipUtf8(display.description.trim(), FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES)\n : \"\";\n return { name, ...(description ? { description } : {}) };\n};\n\ntype DistributiveOmit<T, K extends keyof any> = T extends T ? Omit<T, K> : never;\n\n// Normalize a SessionEntry source prefix into a flat, typed event stream.\n// The caller selects the cumulative raw active-branch prefix before the new\n// kept boundary. Tool results are paired back to their tool calls by\n// id so a bash result can carry the command from the originating call; this\n// pairing is structural (id match), never prose-based.\nexport const normalizeEntries = (entries: SessionEntry[]): CompactionEvent[] => {\n const events: CompactionEvent[] = [];\n const calls = new Map<string, PendingCall>();\n let index = 0;\n\n const push = (event: DistributiveOmit<CompactionEvent, \"index\">): void => {\n index += 1;\n events.push({ ...event, index } as CompactionEvent);\n };\n\n const pushBranchFacts = (entry: SessionEntry & { details?: unknown }): void => {\n const details = readFabricBranchSummaryDetails(entry.details);\n if (!details) return;\n for (const fact of details.facts) {\n if (fact.kind === \"user\") {\n push({ kind: \"user\", entryId: fact.entryId, sourceEntryId: entry.id, text: fact.text });\n } else if (fact.kind === \"customMessage\") {\n push({\n kind: \"customMessage\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n customType: fact.customType,\n text: fact.text,\n display: fact.display,\n ...(fact.details !== undefined ? { details: fact.details } : {}),\n });\n } else if (fact.kind === \"phase\") {\n push({\n kind: \"fabricPhase\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n subordinal: fact.subordinal,\n address: fact.address,\n phase: fact.phase,\n });\n } else if (fact.kind === \"fabricRun\") {\n push({\n kind: \"fabricRun\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n toolCallId: fact.subordinal.startsWith(\"call:\")\n ? fact.subordinal.slice(\"call:\".length)\n : fact.subordinal,\n subordinal: fact.subordinal,\n address: fact.address,\n name: fact.name,\n ...(fact.description !== undefined ? { description: fact.description } : {}),\n outcome: fact.outcome,\n source: \"branch\",\n });\n } else {\n push({\n kind: \"fabricOperation\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n subordinal: fact.subordinal,\n address: fact.address,\n ref: fact.ref,\n ...(fact.provider ? { provider: fact.provider } : {}),\n ...(fact.action ? { action: fact.action } : {}),\n tool: fact.tool,\n args: fact.args,\n outcome: fact.outcome,\n ...(fact.error !== undefined ? { error: fact.error } : {}),\n ...(fact.result !== undefined ? { result: fact.result } : {}),\n source: \"branch\",\n });\n }\n }\n };\n\n for (const entry of entries) {\n if (entry.type === \"branch_summary\") {\n pushBranchFacts(entry as SessionEntry & { details?: unknown });\n continue;\n }\n if (entry.type === \"custom_message\") {\n try {\n if (!isOmpCustomMessageEntry(entry)) continue;\n const details = customDetails(entry.details);\n push({\n kind: \"customMessage\",\n entryId: entry.id,\n sourceEntryId: entry.id,\n customType: entry.customType,\n text: textOfContent(entry.content),\n display: entry.display,\n ...(details !== undefined ? { details } : {}),\n });\n } catch {\n // Malformed extension-owned entries are ignored without affecting later source.\n }\n continue;\n }\n if (!isMessageEntry(entry)) continue;\n const message = entry.message as SessionMessageEntry[\"message\"];\n if (!message || typeof message !== \"object\") continue;\n const role = (message as { role?: unknown }).role;\n const entryId = entry.id;\n\n if (role === \"user\") {\n push({ kind: \"user\", entryId, sourceEntryId: entryId, text: textOfContent((message as { content: unknown }).content) });\n continue;\n }\n\n if (role === \"assistant\") {\n const content = (message as { content: unknown }).content;\n if (!Array.isArray(content)) continue;\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n if (part.type === \"text\" && typeof part.text === \"string\") {\n push({ kind: \"assistantText\", entryId, sourceEntryId: entryId, text: part.text });\n } else if (part.type === \"toolCall\" && typeof part.id === \"string\" && typeof part.name === \"string\") {\n const args = (part.arguments ?? {}) as Record<string, unknown>;\n calls.set(part.id, { entryId, name: part.name, args });\n push({ kind: \"toolCall\", entryId, sourceEntryId: entryId, toolCallId: part.id, name: part.name, args });\n }\n }\n continue;\n }\n\n if (role === \"toolResult\") {\n const toolResult = message as {\n toolCallId?: string;\n toolName?: string;\n isError?: boolean;\n content?: unknown;\n details?: unknown;\n };\n const toolCallId = typeof toolResult.toolCallId === \"string\" ? toolResult.toolCallId : \"\";\n const toolName = typeof toolResult.toolName === \"string\" ? toolResult.toolName : \"\";\n const isError = toolResult.isError === true;\n const text = textOfContent(toolResult.content);\n const pending = toolCallId ? calls.get(toolCallId) : undefined;\n if (toolName === \"bash\") {\n const command =\n pending && typeof pending.args.command === \"string\"\n ? pending.args.command\n : \"\";\n push({\n kind: \"bash\",\n entryId,\n sourceEntryId: entryId,\n toolCallId,\n command,\n isError,\n exitCode: null,\n ...(isError && text ? { error: text } : {}),\n });\n } else {\n push({ kind: \"toolResult\", entryId, sourceEntryId: entryId, toolCallId, toolName, isError, text });\n }\n if (toolName === \"fabric_exec\") {\n const nested = readFabricProjectionTrace(toolResult.details);\n const intent = fabricRunIntent(pending);\n if (intent && pending) {\n const subordinal = `call:${toolCallId}`;\n push({\n kind: \"fabricRun\",\n entryId: pending.entryId,\n sourceEntryId: entryId,\n toolCallId,\n subordinal,\n address: `${pending.entryId}/${subordinal}`,\n name: intent.name,\n ...(intent.description !== undefined ? { description: intent.description } : {}),\n outcome: nested?.outcome ?? (isError ? \"failed\" : \"succeeded\"),\n source: nested?.source ?? \"result\",\n });\n }\n if (nested) {\n for (let phaseIndex = 0; phaseIndex < nested.phases.length; phaseIndex++) {\n const subordinal = `phase:${phaseIndex}`;\n push({\n kind: \"fabricPhase\",\n entryId,\n sourceEntryId: entryId,\n subordinal,\n address: `${entryId}/${subordinal}`,\n phase: nested.phases[phaseIndex]!,\n });\n }\n for (const operation of nested.operations) {\n const subordinal = String(operation.sequence);\n push({\n kind: \"fabricOperation\",\n entryId,\n sourceEntryId: entryId,\n subordinal,\n address: `${entryId}/${subordinal}`,\n ref: operation.ref,\n ...(operation.provider ? { provider: operation.provider } : {}),\n ...(operation.action ? { action: operation.action } : {}),\n tool: operation.tool,\n args: operation.args,\n outcome: operation.outcome,\n ...(operation.error !== undefined ? { error: operation.error } : {}),\n ...(operation.result !== undefined ? { result: operation.result } : {}),\n source: operation.source,\n });\n }\n }\n }\n continue;\n }\n\n if (role === \"bashExecution\") {\n const bash = message as {\n command?: string;\n exitCode?: number | undefined;\n output?: string;\n };\n const exitCode = typeof bash.exitCode === \"number\" ? bash.exitCode : null;\n const isError = exitCode !== null && exitCode !== 0;\n push({\n kind: \"bash\",\n entryId,\n sourceEntryId: entryId,\n toolCallId: \"\",\n command: typeof bash.command === \"string\" ? bash.command : \"\",\n isError,\n exitCode,\n ...(isError && typeof bash.output === \"string\" && bash.output ? { error: bash.output } : {}),\n });\n continue;\n }\n\n // Message-role custom / branchSummary / compactionSummary and any other\n // roles are not top-level OMP custom_message entries and are skipped here.\n }\n\n return events;\n};\n\n// Structural count of assistant thinking parts erased by normalization. The\n// walk mirrors normalizeEntries selection (typed part, string payload) so the\n// details counter cannot disagree with what the summary silently dropped.\n// Entry-level ranges are unnecessary: erased blocks always lie inside the\n// cumulative source range recorded beside the count.\nexport const countErasedThinkingBlocks = (entries: SessionEntry[]): number => {\n let count = 0;\n for (const entry of entries) {\n if (!isMessageEntry(entry)) continue;\n const message = entry.message as { role?: unknown; content?: unknown };\n if (message.role !== \"assistant\" || !Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n if (\n part.type === \"thinking\" &&\n typeof (part as { thinking?: unknown }).thinking === \"string\"\n ) count += 1;\n }\n }\n return count;\n};\n\nexport { firstLine };\n", "import { clipUtf8, omissionLine, sampleAddressed, sampleAddressedFrom } from \"./bounds.js\";\nimport {\n firstLine,\n type CompactionEvent,\n type FabricRunEvent,\n type ToolCallEvent,\n} from \"./normalize.js\";\n\n// Section folds: each projection is a pure function of the typed event stream.\n// Together they implement graded decay (principle 4): the oldest turns\n// collapse to one line, recent events stay as a collapsed transcript with\n// stable `(#N)` references, and the very last action is surfaced in Current\n// Status. Salience (principle 3) is *computed* from the event stream by the\n// outstanding fold's state machine \u2014 nothing is remembered, only re-derived.\n\nexport interface Sections {\n goal: string[];\n files: string[];\n activity: string[];\n outstanding: string[];\n earlierTurns: string[];\n status: string[];\n transcript: string[];\n}\n\nconst MAX_LINE = 140;\nconst FILE_TOOLS = new Set([\"read\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"]);\nconst MODIFYING_TOOLS = new Set([\"edit\", \"write\"]);\nconst MAX_USER_GOAL_LINES = 3;\nconst MAX_USER_GOAL_LINE = 1024;\nconst MAX_USER_ONELINER = 120;\nconst MAX_EARLIER_USER = 80;\nconst MAX_STATUS_LINE = 140;\nconst MAX_TRANSCRIPT_LINE = 100;\nconst MAX_TRANSCRIPT_CMD = 80;\nconst MAX_FABRIC_RUN_NAME = 80;\nconst MAX_FABRIC_RUN_DESCRIPTION = 180;\nconst MAX_FABRIC_RUN_TRANSCRIPT_NAME = 60;\nconst MAX_FABRIC_RUN_EARLIER_NAME = 48;\nconst MAX_FABRIC_RUN_STATUS_NAME = 96;\nconst MAX_LATER_GOALS = 24;\nconst MAX_FILES_PER_KIND = 24;\nconst MAX_OUTSTANDING = 32;\nconst MAX_ACTIVITY = 48;\nconst MAX_UNRESOLVED = 24;\nconst MAX_RESOLVED = MAX_OUTSTANDING - MAX_UNRESOLVED;\nconst MAX_EARLIER_TURNS = 32;\nconst TRANSCRIPT_WINDOW = 40;\n\nexport interface ProjectionOmittedCounts {\n goal: number;\n files: number;\n activity: number;\n outstanding: number;\n earlierTurns: number;\n transcript: number;\n}\n\nexport interface ProjectionResult {\n sections: Sections;\n omittedCounts: ProjectionOmittedCounts;\n}\n\ninterface ProjectedSection {\n lines: string[];\n omitted: number;\n}\n\nconst truncate = (text: string, max: number): string => {\n const flat = text.replace(/\\s+/g, \" \").trim();\n return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;\n};\n\nconst quoted = (text: string, max: number): string => JSON.stringify(truncate(text, max));\n\nconst customDetailsSuffix = (details: unknown, max = 160): string => {\n if (details === undefined) return \"\";\n try {\n return ` details=${truncate(JSON.stringify(details), max)}`;\n } catch {\n return \"\";\n }\n};\n\nconst customMessageLine = (\n event: Extract<CompactionEvent, { kind: \"customMessage\" }>,\n maxText: number,\n): string => {\n const visibility = event.display ? \"visible\" : \"hidden\";\n return `custom ${quoted(event.customType, 80)} (${visibility}): ${quoted(event.text, maxText)}${customDetailsSuffix(event.details)}`;\n};\n\nconst trailingEllipsis = (lines: string[], max: number): string[] => {\n if (lines.length <= max) return lines;\n return [...lines.slice(0, max), \"\u2026\"];\n};\n\nconst pathOf = (args: Record<string, unknown>): string | undefined => {\n const value = args.path ?? args.file ?? args.dir;\n return typeof value === \"string\" && value.trim() ? value : undefined;\n};\n\ninterface StructuralOperation {\n index: number;\n entryId: string;\n address: string;\n tool: string;\n ref: string;\n provider?: string;\n action?: string;\n args: Record<string, unknown>;\n outcome: \"succeeded\" | \"failed\" | \"aborted\" | \"timed_out\";\n error?: string;\n result?: unknown;\n nested: boolean;\n}\n\nconst collectOperations = (events: CompactionEvent[]): StructuralOperation[] => {\n const calls = new Map<string, ToolCallEvent>();\n for (const event of events) {\n if (event.kind === \"toolCall\") calls.set(event.toolCallId, event);\n }\n const operations: StructuralOperation[] = [];\n for (const event of events) {\n if (event.kind === \"fabricOperation\") {\n operations.push({\n index: event.index,\n entryId: event.entryId,\n address: event.address,\n tool: event.tool,\n ref: event.ref,\n ...(event.provider ? { provider: event.provider } : {}),\n ...(event.action ? { action: event.action } : {}),\n args: event.args,\n outcome: event.outcome,\n ...(event.error !== undefined ? { error: event.error } : {}),\n ...(event.result !== undefined ? { result: event.result } : {}),\n nested: true,\n });\n continue;\n }\n if (event.kind === \"toolResult\" && event.toolName !== \"bash\") {\n const call = event.toolCallId ? calls.get(event.toolCallId) : undefined;\n if (!call) continue;\n operations.push({\n index: event.index,\n entryId: call.entryId,\n address: call.entryId,\n tool: call.name,\n ref: call.name,\n args: call.args,\n outcome: event.isError ? \"failed\" : \"succeeded\",\n ...(event.isError && event.text ? { error: event.text } : {}),\n nested: false,\n });\n continue;\n }\n if (event.kind === \"bash\") {\n operations.push({\n index: event.index,\n entryId: event.entryId,\n address: event.entryId,\n tool: \"bash\",\n ref: \"bash\",\n args: { command: event.command },\n outcome: event.isError ? \"failed\" : \"succeeded\",\n ...(event.error ? { error: event.error } : {}),\n nested: false,\n });\n }\n }\n return operations.sort((left, right) => left.index - right.index);\n};\n\nconst isFileOperation = (operation: StructuralOperation): boolean =>\n FILE_TOOLS.has(operation.tool)\n && (operation.ref === operation.tool || operation.ref === `omp.${operation.tool}`);\n\nconst isBashOperation = (operation: StructuralOperation): boolean =>\n operation.tool === \"bash\"\n && (operation.ref === \"bash\" || operation.ref === \"omp.bash\");\n\nconst resultProvesCreation = (result: unknown): boolean => {\n if (!result || typeof result !== \"object\" || Array.isArray(result)) return false;\n const record = result as Record<string, unknown>;\n if (record.created === true) return true;\n const details = record.details;\n return Boolean(details && typeof details === \"object\" && !Array.isArray(details)\n && (details as Record<string, unknown>).created === true);\n};\n\n// Longest common path prefix (by segment) across a set of paths, returned with\n// a trailing separator. Returns \"\" when there is none.\nconst commonRoot = (paths: string[]): string => {\n if (paths.length === 0) return \"\";\n const split = paths.map((p) => p.split(/[\\\\/]/).filter(Boolean));\n let common = 0;\n const first = split[0]!;\n loop: while (common < first.length) {\n const segment = first[common];\n for (let i = 1; i < split.length; i++) {\n if (split[i]!.length <= common || split[i]![common] !== segment) break loop;\n }\n common += 1;\n }\n if (common === 0) return \"\";\n return `${first.slice(0, common).join(\"/\")}/`;\n};\n\nconst stripRoot = (root: string, path: string): string =>\n root ? path.replace(root, \"\") : path;\n\n// [Session Goal] keeps up to three mechanically normalized, bounded lines\n// from the first user message. Later scope changes use bounded one-liners and\n// deterministic earliest/latest sampling with source addresses.\nconst projectGoal = (events: CompactionEvent[]): ProjectedSection => {\n const first = events.find(\n (event): event is Extract<CompactionEvent, { kind: \"user\" }> => event.kind === \"user\",\n );\n if (!first) return { lines: [], omitted: 0 };\n const firstLines = first.text.split(\"\\n\").filter((line, i, arr) =>\n line.trim() !== \"\" || (i === 0 && arr.length === 1),\n ).map((line) => truncate(line, MAX_USER_GOAL_LINE));\n const lines: string[] = [...trailingEllipsis(firstLines, MAX_USER_GOAL_LINES)];\n function* laterUsers(): Generator<Extract<CompactionEvent, { kind: \"user\" }>> {\n let skippedFirst = false;\n for (const event of events) {\n if (event.kind !== \"user\") continue;\n if (!skippedFirst) {\n skippedFirst = true;\n continue;\n }\n yield event;\n }\n }\n const sampled = sampleAddressedFrom(laterUsers(), MAX_LATER_GOALS);\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"user scope changes\",\n ));\n }\n const user = sampled.values[index]!;\n const line = truncate(firstLine(user.text), MAX_USER_ONELINER);\n if (line) lines.push(`- ${line} [entry ${user.entryId}]`);\n }\n return { lines, omitted: sampled.omitted };\n};\n\n// [Files And Changes] uses only successful structural operations. Writes are\n// labelled Written unless a typed result explicitly proves creation.\ninterface FileAddress {\n path: string;\n entryId: string;\n}\n\nconst projectFiles = (events: CompactionEvent[]): ProjectedSection => {\n const read = new Map<string, FileAddress>();\n const modified = new Map<string, FileAddress>();\n const written = new Map<string, FileAddress>();\n const created = new Map<string, FileAddress>();\n\n for (const operation of collectOperations(events)) {\n if (!isFileOperation(operation) || operation.outcome !== \"succeeded\") continue;\n const path = pathOf(operation.args);\n if (!path) continue;\n const address = { path, entryId: operation.address };\n if (operation.tool === \"write\") {\n const target = resultProvesCreation(operation.result) ? created : written;\n if (!target.has(path)) target.set(path, address);\n } else if (operation.tool === \"edit\") {\n if (!modified.has(path)) modified.set(path, address);\n } else if (!read.has(path)) {\n read.set(path, address);\n }\n }\n\n const modifiedSet = new Set<string>();\n for (const path of modified.keys()) modifiedSet.add(path);\n for (const path of written.keys()) modifiedSet.add(path);\n for (const path of created.keys()) modifiedSet.add(path);\n function* filteredRead(): Generator<FileAddress> {\n for (const item of read.values()) {\n if (!modifiedSet.has(item.path)) yield item;\n }\n }\n const sampledCreated = sampleAddressedFrom(created.values(), MAX_FILES_PER_KIND);\n const sampledWritten = sampleAddressedFrom(written.values(), MAX_FILES_PER_KIND);\n const sampledModified = sampleAddressedFrom(modified.values(), MAX_FILES_PER_KIND);\n const sampledRead = sampleAddressedFrom(filteredRead(), MAX_FILES_PER_KIND);\n const allSampled = [\n ...sampledCreated.values,\n ...sampledWritten.values,\n ...sampledModified.values,\n ...sampledRead.values,\n ];\n if (allSampled.length === 0) return { lines: [], omitted: 0 };\n const root = commonRoot(allSampled.map((item) => item.path));\n const lines: string[] = [];\n let omitted = 0;\n if (root) lines.push(`(under ${root})`);\n\n const appendKind = (\n header: string,\n sampled: ReturnType<typeof sampleAddressed<FileAddress>>,\n ): void => {\n if (sampled.values.length === 0 && sampled.omitted === 0) return;\n lines.push(header);\n omitted += sampled.omitted;\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(` ${omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"file addresses\",\n )}`);\n }\n const item = sampled.values[index]!;\n lines.push(` ${stripRoot(root, item.path)} [entry ${item.entryId}]`);\n }\n };\n\n appendKind(\"Created:\", sampledCreated);\n appendKind(\"Written:\", sampledWritten);\n appendKind(\"Modified:\", sampledModified);\n appendKind(\"Read:\", sampledRead);\n return { lines, omitted };\n};\n\ninterface ActivityItem {\n entryId: string;\n line: string;\n}\n\nconst fabricRunPointer = (event: FabricRunEvent): string =>\n event.source === \"branch\" ? event.address : event.entryId;\n\nconst projectActivity = (events: CompactionEvent[]): ProjectedSection => {\n const items: ActivityItem[] = [];\n for (const event of events) {\n if (event.kind === \"fabricRun\") {\n const name = clipUtf8(truncate(event.name, MAX_FABRIC_RUN_NAME), 192);\n const description = event.description\n ? clipUtf8(truncate(event.description, MAX_FABRIC_RUN_DESCRIPTION), 512)\n : \"\";\n items.push({\n entryId: fabricRunPointer(event),\n line: `- ${name}${description ? ` \u2014 ${description}` : \"\"} \u2192 ${event.outcome}`,\n });\n } else if (event.kind === \"fabricPhase\") {\n items.push({ entryId: event.address, line: `- Phase: ${truncate(event.phase, MAX_LINE)}` });\n } else if (event.kind === \"fabricOperation\") {\n if (FILE_TOOLS.has(event.tool)\n && (event.ref === event.tool || event.ref === `omp.${event.tool}`)) continue;\n const bash = event.tool === \"bash\"\n && (event.ref === \"bash\" || event.ref === \"omp.bash\");\n const primary = bash\n ? event.args.command\n : event.args.id ?? event.args.name ?? event.args.query ?? event.args.action;\n const detail = typeof primary === \"string\" && primary.trim()\n ? ` (${truncate(firstLine(primary), 72)})`\n : \"\";\n items.push({\n entryId: event.address,\n line: `- ${event.ref}${detail} \u2192 ${event.outcome}`,\n });\n }\n }\n const sampled = sampleAddressed(items, MAX_ACTIVITY);\n const lines: string[] = [];\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"Fabric activity records\",\n ));\n }\n const item = sampled.values[index]!;\n lines.push(`${item.line} [entry ${item.entryId}]`);\n }\n return { lines, omitted: sampled.omitted };\n};\n\ninterface ErrorItem {\n index: number;\n entryId: string;\n description: string;\n resolved: boolean;\n}\n\n// [Outstanding Context] is keyed only by typed operation identity. A later\n// success resolves a failure only when action+path, action+command, or the\n// generic ref+arguments identity is exactly equal.\nconst projectOutstandingWithMetadata = (events: CompactionEvent[]): ProjectedSection => {\n const operations = collectOperations(events);\n const keyOf = (operation: StructuralOperation): string => {\n const path = isFileOperation(operation) ? pathOf(operation.args) : undefined;\n if (path) return `file\\0${operation.tool}\\0${path}`;\n const command = isBashOperation(operation) && typeof operation.args.command === \"string\"\n ? operation.args.command\n : undefined;\n if (command !== undefined) return `bash\\0${operation.tool}\\0${command}`;\n return `generic\\0${operation.ref}\\0${JSON.stringify(operation.args)}`;\n };\n const successes = operations\n .filter((operation) => operation.outcome === \"succeeded\")\n .map((operation) => ({ index: operation.index, key: keyOf(operation) }));\n const items: ErrorItem[] = [];\n\n for (const operation of operations) {\n if (operation.outcome === \"succeeded\") continue;\n const path = isFileOperation(operation) ? pathOf(operation.args) : undefined;\n const command = isBashOperation(operation) && typeof operation.args.command === \"string\"\n ? operation.args.command\n : undefined;\n const subject = path\n ? `${operation.ref} ${path}`\n : command !== undefined\n ? `${operation.ref}: ${truncate(firstLine(command), MAX_LINE)}`\n : operation.ref;\n const error = operation.error ? `: ${truncate(firstLine(operation.error), MAX_LINE)}` : `: ${operation.outcome}`;\n const key = keyOf(operation);\n const resolved = successes.some((success) => success.index > operation.index && success.key === key);\n items.push({\n index: operation.index,\n entryId: operation.address,\n description: `${subject}${error}`,\n resolved,\n });\n }\n\n if (items.length === 0) return { lines: [], omitted: 0 };\n const unresolved = items.filter((i) => !i.resolved).sort((a, b) => a.index - b.index);\n const resolved = items.filter((i) => i.resolved).sort((a, b) => a.index - b.index);\n const sampledUnresolved = sampleAddressed(unresolved, MAX_UNRESOLVED);\n const sampledResolved = sampleAddressed(resolved, MAX_RESOLVED);\n const lines: string[] = [];\n const append = (sampled: ReturnType<typeof sampleAddressed<ErrorItem>>, noun: string): void => {\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n noun,\n ));\n }\n const item = sampled.values[index]!;\n lines.push(`- ${item.description}${item.resolved ? \" [RESOLVED]\" : \"\"} [entry ${item.entryId}]`);\n }\n };\n append(sampledUnresolved, \"open error records\");\n append(sampledResolved, \"resolved error records\");\n return { lines, omitted: sampledUnresolved.omitted + sampledResolved.omitted };\n};\n\nexport const projectOutstanding = (events: CompactionEvent[]): string[] =>\n projectOutstandingWithMetadata(events).lines;\n\ninterface EarlierTurnAddress {\n entryId: string;\n contextLine: string;\n tools: string;\n run: string;\n}\n\n// [Earlier Turns] \u2014 sampled one-liners for turns before the latest summarized\n// one (which Current Status surfaces), plus tool-name histograms and an\n// entry-range address for any omitted middle turns.\nconst projectEarlierTurns = (events: CompactionEvent[]): ProjectedSection => {\n function* earlierTurns(): Generator<EarlierTurnAddress> {\n let currentContext: Extract<CompactionEvent, { kind: \"user\" | \"customMessage\" }> | undefined;\n let counts = new Map<string, number>();\n let order: string[] = [];\n let lastRun: FabricRunEvent | undefined;\n const completed = (): EarlierTurnAddress | undefined => {\n if (!currentContext) return undefined;\n return {\n entryId: currentContext.entryId,\n contextLine: currentContext.kind === \"user\"\n ? quoted(firstLine(currentContext.text), MAX_EARLIER_USER)\n : customMessageLine(currentContext, MAX_EARLIER_USER),\n tools: order.map((name) => `${name}:${counts.get(name) ?? 0}`).join(\" \"),\n run: lastRun\n ? `fabric:${quoted(clipUtf8(lastRun.name, 128), MAX_FABRIC_RUN_EARLIER_NAME)}\u2192${lastRun.outcome}`\n : \"\",\n };\n };\n for (const event of events) {\n if (event.kind === \"user\" || event.kind === \"customMessage\") {\n const turn = completed();\n if (turn) yield turn;\n currentContext = event;\n counts = new Map<string, number>();\n order = [];\n lastRun = undefined;\n continue;\n }\n if (!currentContext) continue;\n if (event.kind === \"fabricRun\") lastRun = event;\n const name = event.kind === \"toolCall\"\n ? (event.name === \"fabric_exec\" ? undefined : event.name)\n : event.kind === \"bash\"\n ? \"bash\"\n : event.kind === \"fabricOperation\"\n ? event.tool\n : undefined;\n if (!name) continue;\n if (!counts.has(name)) order.push(name);\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n }\n\n const sampled = sampleAddressedFrom(earlierTurns(), MAX_EARLIER_TURNS);\n const lines: string[] = [];\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"earlier turns\",\n ));\n }\n const turn = sampled.values[index]!;\n const metadata = [turn.tools, turn.run].filter(Boolean).join(\" | \");\n lines.push(`${turn.contextLine}${metadata ? ` | ${metadata}` : \"\"} [entry ${turn.entryId}]`);\n }\n return { lines, omitted: sampled.omitted };\n};\n\n// [Current Status] \u2014 a bridge from the summarized window into the kept tail:\n// the last summarized user request, the last file-modifying tool call, and the\n// last assistant line. Only non-empty fields are emitted.\nconst projectStatus = (events: CompactionEvent[]): string[] => {\n const lastContext = [...events].reverse().find(\n (event): event is Extract<CompactionEvent, { kind: \"user\" | \"customMessage\" }> =>\n event.kind === \"user\" || event.kind === \"customMessage\",\n );\n const lines: string[] = [];\n if (lastContext?.kind === \"user\") {\n lines.push(`Last request: ${truncate(firstLine(lastContext.text), MAX_STATUS_LINE)}`);\n } else if (lastContext) {\n lines.push(`Last context: ${customMessageLine(lastContext, MAX_STATUS_LINE)}`);\n }\n let lastModify: { tool: string; args: Record<string, unknown> } | undefined;\n for (const operation of collectOperations(events)) {\n if (isFileOperation(operation) && MODIFYING_TOOLS.has(operation.tool)) lastModify = operation;\n }\n if (lastModify) {\n const path = pathOf(lastModify.args) ?? \"\";\n lines.push(`Last change: ${lastModify.tool}${path ? ` ${path}` : \"\"}`);\n }\n const lastRun = [...events]\n .reverse()\n .find((event): event is FabricRunEvent => event.kind === \"fabricRun\");\n if (lastRun) {\n lines.push(\n `Last execution: ${clipUtf8(truncate(lastRun.name, MAX_FABRIC_RUN_STATUS_NAME), 256)} \u2192 ${lastRun.outcome} [entry ${fabricRunPointer(lastRun)}]`,\n );\n }\n const lastAssistant = [...events]\n .reverse()\n .find((e): e is Extract<CompactionEvent, { kind: \"assistantText\" }> => e.kind === \"assistantText\");\n if (lastAssistant) {\n const text = truncate(firstLine(lastAssistant.text), MAX_STATUS_LINE);\n if (text) lines.push(`Last note: ${text}`);\n }\n return lines;\n};\n\nconst summarizeArgs = (name: string, args: Record<string, unknown>): string => {\n if (name === \"fabric_exec\") return \"structured execution\";\n const primary =\n name === \"bash\" ? args.command ?? args.cmd ?? args.shell\n : name === \"grep\" ? args.pattern ?? args.query ?? args.regex\n : name === \"find\" ? args.pattern\n : pathOf(args);\n if (typeof primary === \"string\" && primary.trim()) {\n return truncate(firstLine(primary), MAX_TRANSCRIPT_CMD);\n }\n const entries = Object.entries(args).slice(0, 2);\n return entries.map(([key, value]) => `${key}=${truncate(String(value), 40)}`).join(\" \");\n};\n\n// Brief transcript \u2014 the \"collapsed transcript\" tier of graded decay. A\n// rolling window of the last 40 events rendered as one-liners, each prefixed\n// with its stable `(#N)` reference so the agent can point back at a specific\n// event without storing its content (principle 0).\nconst projectTranscript = (events: CompactionEvent[]): ProjectedSection => {\n const completedFabricCalls = new Set(\n events\n .filter((event): event is FabricRunEvent => event.kind === \"fabricRun\")\n .map((event) => event.toolCallId),\n );\n const transcriptEvents = events.filter((event) => {\n if (event.kind === \"toolCall\") {\n return event.name !== \"fabric_exec\" || !completedFabricCalls.has(event.toolCallId);\n }\n if (event.kind === \"toolResult\") {\n return event.toolName !== \"fabric_exec\" || !completedFabricCalls.has(event.toolCallId);\n }\n return true;\n });\n const window = transcriptEvents.slice(-TRANSCRIPT_WINDOW);\n const lines: string[] = [];\n const omitted = transcriptEvents.length - window.length;\n if (omitted > 0) {\n lines.push(omissionLine(\n omitted,\n transcriptEvents[0]?.entryId,\n transcriptEvents[omitted - 1]?.entryId,\n \"transcript events\",\n ));\n }\n for (const e of window) {\n const ref = `(#${e.index})`;\n if (e.kind === \"user\") {\n lines.push(`${ref} user: ${truncate(firstLine(e.text), MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"assistantText\") {\n lines.push(`${ref} assistant: ${truncate(firstLine(e.text), MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"customMessage\") {\n lines.push(`${ref} ${customMessageLine(e, MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"toolCall\") {\n lines.push(`${ref} ${e.name}(${summarizeArgs(e.name, e.args)})`);\n } else if (e.kind === \"toolResult\") {\n const status = e.isError ? \"error\" : \"ok\";\n lines.push(`${ref} \u2192 ${status}: ${truncate(firstLine(e.text), MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"bash\") {\n const status = e.isError ? \"error\" : \"ok\";\n lines.push(`${ref} bash(${truncate(firstLine(e.command), MAX_TRANSCRIPT_CMD)}) \u2192 ${status}`);\n } else if (e.kind === \"fabricRun\") {\n lines.push(\n `${ref} fabric_exec ${quoted(clipUtf8(e.name, 160), MAX_FABRIC_RUN_TRANSCRIPT_NAME)} \u2192 ${e.outcome} [entry ${fabricRunPointer(e)}]`,\n );\n } else if (e.kind === \"fabricPhase\") {\n lines.push(`${ref} phase(${truncate(e.phase, MAX_TRANSCRIPT_CMD)}) [${e.address}]`);\n } else if (e.kind === \"fabricOperation\") {\n lines.push(`${ref} ${e.ref}(${summarizeArgs(e.tool, e.args)}) \u2192 ${e.outcome} [${e.address}]`);\n }\n }\n return { lines, omitted };\n};\n\nexport const projectWithMetadata = (events: CompactionEvent[]): ProjectionResult => {\n const goal = projectGoal(events);\n const files = projectFiles(events);\n const activity = projectActivity(events);\n const outstanding = projectOutstandingWithMetadata(events);\n const earlierTurns = projectEarlierTurns(events);\n const transcript = projectTranscript(events);\n return {\n sections: {\n goal: goal.lines,\n files: files.lines,\n activity: activity.lines,\n outstanding: outstanding.lines,\n earlierTurns: earlierTurns.lines,\n status: projectStatus(events),\n transcript: transcript.lines,\n },\n omittedCounts: {\n goal: goal.omitted,\n files: files.omitted,\n activity: activity.omitted,\n outstanding: outstanding.omitted,\n earlierTurns: earlierTurns.omitted,\n transcript: transcript.omitted,\n },\n };\n};\n\nexport const project = (events: CompactionEvent[]): Sections =>\n projectWithMetadata(events).sections;\n", "import type { SessionEntry } from \"@oh-my-pi/pi-coding-agent\";\nimport type { FabricTraceJsonValue } from \"../audit/trace.js\";\nimport { clipUtf8, sampleAddressed } from \"./bounds.js\";\nimport {\n FABRIC_BRANCH_SUMMARY_KIND,\n FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES,\n FABRIC_BRANCH_RUN_NAME_MAX_BYTES,\n FABRIC_BRANCH_SUMMARY_MAX_BYTES,\n FABRIC_BRANCH_SUMMARY_MAX_FACTS,\n FABRIC_BRANCH_SUMMARY_VERSION,\n type FabricBranchFactV2,\n type FabricBranchOperationFactV1,\n type FabricBranchSummaryDetailsV2,\n} from \"./branch-details.js\";\nimport { NO_BUILTIN_ENRICHERS, runEnrichers, type CompactionEnricher } from \"./enrichers.js\";\nimport { decodeCompactionInstructions } from \"./instructions.js\";\nimport { normalizeEntries, type CompactionEvent, type ToolCallEvent } from \"./normalize.js\";\nimport { projectWithMetadata, type Sections } from \"./projections.js\";\nimport { renderSummary } from \"./render.js\";\n\nconst SECTION_HEADERS: { key: keyof Sections; header: string }[] = [\n { key: \"goal\", header: \"[Session Goal]\" },\n { key: \"files\", header: \"[Files And Changes]\" },\n { key: \"activity\", header: \"[Fabric Activity]\" },\n { key: \"outstanding\", header: \"[Outstanding Context]\" },\n { key: \"earlierTurns\", header: \"[Earlier Turns]\" },\n { key: \"status\", header: \"[Current Status]\" },\n];\n\nconst asJsonObject = (value: Record<string, unknown>): Record<string, FabricTraceJsonValue> | undefined => {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n return cloned && typeof cloned === \"object\" && !Array.isArray(cloned)\n ? cloned as Record<string, FabricTraceJsonValue>\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst directOperationFact = (\n call: ToolCallEvent,\n outcome: \"succeeded\" | \"failed\",\n error?: string,\n): FabricBranchOperationFactV1 | undefined => {\n if (call.name === \"fabric_exec\") return undefined;\n const args = asJsonObject(call.args);\n if (!args) return undefined;\n const subordinal = `call:${call.toolCallId}`;\n return {\n kind: \"operation\",\n entryId: call.entryId,\n subordinal,\n address: `${call.entryId}/${subordinal}`,\n ref: call.name,\n action: call.name,\n tool: call.name,\n args,\n outcome,\n ...(error ? { error: clipUtf8(error, 8 * 1024) } : {}),\n };\n};\n\nconst factsFromEvents = (events: CompactionEvent[]): FabricBranchFactV2[] => {\n const facts: FabricBranchFactV2[] = [];\n const calls = new Map<string, ToolCallEvent>();\n for (const event of events) {\n if (event.kind === \"toolCall\") calls.set(event.toolCallId, event);\n }\n for (const event of events) {\n if (event.kind === \"user\") {\n facts.push({\n kind: \"user\",\n entryId: event.entryId,\n subordinal: \"user\",\n address: `${event.entryId}/user`,\n text: clipUtf8(event.text, 2 * 1024),\n });\n } else if (event.kind === \"customMessage\") {\n facts.push({\n kind: \"customMessage\",\n entryId: event.entryId,\n subordinal: \"custom-message\",\n address: `${event.entryId}/custom-message`,\n customType: clipUtf8(event.customType, 256),\n text: clipUtf8(event.text, 4 * 1024),\n display: event.display,\n ...(event.details !== undefined ? { details: event.details } : {}),\n });\n } else if (event.kind === \"fabricPhase\") {\n facts.push({\n kind: \"phase\",\n entryId: event.entryId,\n subordinal: event.subordinal,\n address: event.address,\n phase: event.phase,\n });\n } else if (event.kind === \"fabricRun\") {\n facts.push({\n kind: \"fabricRun\",\n entryId: event.entryId,\n subordinal: event.subordinal,\n address: event.address,\n name: clipUtf8(event.name, FABRIC_BRANCH_RUN_NAME_MAX_BYTES),\n ...(event.description !== undefined\n ? { description: clipUtf8(event.description, FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES) }\n : {}),\n outcome: event.outcome,\n });\n } else if (event.kind === \"fabricOperation\") {\n facts.push({\n kind: \"operation\",\n entryId: event.entryId,\n subordinal: event.subordinal,\n address: event.address,\n ref: event.ref,\n ...(event.provider ? { provider: event.provider } : {}),\n ...(event.action ? { action: event.action } : {}),\n tool: event.tool,\n args: event.args,\n outcome: event.outcome,\n ...(event.error !== undefined ? { error: event.error } : {}),\n ...(event.result !== undefined ? { result: event.result } : {}),\n });\n } else if (event.kind === \"toolResult\" && event.toolName !== \"bash\") {\n const call = event.toolCallId ? calls.get(event.toolCallId) : undefined;\n if (!call) continue;\n const fact = directOperationFact(call, event.isError ? \"failed\" : \"succeeded\", event.isError ? event.text : undefined);\n if (fact) facts.push(fact);\n } else if (event.kind === \"bash\") {\n const call = event.toolCallId ? calls.get(event.toolCallId) : undefined;\n if (call) {\n const fact = directOperationFact(call, event.isError ? \"failed\" : \"succeeded\", event.error);\n if (fact) facts.push(fact);\n } else {\n const subordinal = \"bash\";\n facts.push({\n kind: \"operation\",\n entryId: event.entryId,\n subordinal,\n address: `${event.entryId}/${subordinal}`,\n ref: \"bash\",\n action: \"bash\",\n tool: \"bash\",\n args: { command: event.command },\n outcome: event.isError ? \"failed\" : \"succeeded\",\n ...(event.error ? { error: clipUtf8(event.error, 8 * 1024) } : {}),\n });\n }\n }\n }\n return facts;\n};\n\nconst serializedBytes = (value: unknown): number => Buffer.byteLength(JSON.stringify(value), \"utf8\");\n\nconst boundedDetails = (\n sourceEntries: SessionEntry[],\n facts: FabricBranchFactV2[],\n sections: string[],\n request: { text: string; sourceBytes: number; truncated: boolean },\n oldLeafId: string | null,\n): FabricBranchSummaryDetailsV2 => {\n const sampled = sampleAddressed(facts, FABRIC_BRANCH_SUMMARY_MAX_FACTS);\n const details: FabricBranchSummaryDetailsV2 = {\n kind: FABRIC_BRANCH_SUMMARY_KIND,\n version: FABRIC_BRANCH_SUMMARY_VERSION,\n source: {\n firstEntryId: sourceEntries[0]?.id ?? \"\",\n lastEntryId: sourceEntries.at(-1)?.id ?? \"\",\n entryCount: sourceEntries.length,\n oldLeafId,\n },\n facts: sampled.values,\n omittedFacts: sampled.omitted,\n sections,\n request: {\n text: request.text,\n sourceBytes: request.sourceBytes,\n truncated: request.truncated,\n },\n };\n for (let index = details.facts.length - 1; serializedBytes(details) > FABRIC_BRANCH_SUMMARY_MAX_BYTES && index >= 0; index--) {\n const fact = details.facts[index]!;\n if (fact.kind === \"operation\" && fact.result !== undefined) delete fact.result;\n }\n while (serializedBytes(details) > FABRIC_BRANCH_SUMMARY_MAX_BYTES && details.facts.length > 0) {\n const middle = Math.floor(details.facts.length / 2);\n details.facts.splice(middle, 1);\n details.omittedFacts += 1;\n }\n return details;\n};\n\nexport interface FabricBranchSummaryCompilation {\n summary: string;\n details: FabricBranchSummaryDetailsV2;\n}\n\nexport const compileLcmBranchSummary = (\n entriesToSummarize: SessionEntry[],\n customInstructions?: string,\n enrichers: readonly CompactionEnricher[] = NO_BUILTIN_ENRICHERS,\n oldLeafId: string | null = null,\n): FabricBranchSummaryCompilation | undefined => {\n const instructions = decodeCompactionInstructions(customInstructions);\n if (!instructions.ok) return undefined;\n const events = normalizeEntries(entriesToSummarize);\n if (events.length === 0) return undefined;\n const projected = projectWithMetadata(events);\n runEnrichers(enrichers, events, projected.sections);\n const request = {\n text: instructions.requestLines.join(\"\\n\"),\n sourceBytes: instructions.policy.sourceBytes,\n truncated: instructions.policy.truncated,\n };\n const sections = SECTION_HEADERS\n .filter(({ key }) => projected.sections[key].length > 0)\n .map(({ header }) => header);\n if (request.text) sections.splice(1, 0, \"[Compaction Request]\");\n const summary = renderSummary(projected.sections, {\n firstEntryId: entriesToSummarize[0]?.id ?? \"\",\n lastEntryId: entriesToSummarize.at(-1)?.id ?? \"\",\n lastTimestamp: entriesToSummarize.at(-1)?.timestamp ?? \"\",\n ...(instructions.requestLines.length > 0 ? { requestLines: instructions.requestLines } : {}),\n summaryKind: \"branch\",\n });\n return {\n summary,\n details: boundedDetails(entriesToSummarize, factsFromEvents(events), sections, request, oldLeafId),\n };\n};\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAMO;;;ACJP,IAAM,uBAAuB;AAC7B,IAAM,uBAAuB;AA6B7B,IAAM,eAAe,CAAC,YACpB,MAAM,QAAQ,OAAO,IAAK,UAA0C,CAAC;AAEvE,IAAM,qBAAqB,CAAC,UAA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,OAAO,YAAY,YAAY,OAAO,QAAQ,WAAW,KACzE,OAAO,WAAW,oBAAoB,OAAO,WAAW,eACzD,OAAO,iBAAiB,MAAM,YAAY,gBAC1C,OAAO,OAAO,qBAAqB,YACnC,cAAc,WAAW,KACxB,OAAO,iBAAiB,SAAS,KAAK,CAAC,cAAc,KAAK,CAAC,UAAU,MAAM,OAAO,OAAO,gBAAgB,GAAI;AACjH,aAAO,EAAE,QAAQ,KAAK;AAAA,IACxB;AACA,WAAO;AAAA,MACL,YAAY;AAAA,QACV,SAAS,OAAO;AAAA,QAChB,kBAAkB,OAAO;AAAA,QACzB,cAAc,OAAO;AAAA,QACrB,SAAS;AAAA,UACP,WAAW;AAAA,UACX,QAAQ,OAAO;AAAA,UACf,GAAI,OAAO,WAAW,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU,CAAC;AAAA,QAC/E;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AAED,MAAI,GAAG,uBAAuB,CAAC,UAAkC;AAC/D,QAAI,QAAQ,UAAU,MAAM,SAAS,CAAC,MAAM,YAAY,iBAAkB;AAC1E,UAAM,WAAW;AAAA,MACf,MAAM,YAAY;AAAA,MAClB;AAAA,MACA,QAAQ;AAAA,MACR,MAAM,YAAY;AAAA,IACpB;AACA,QAAI,CAAC,SAAU;AACf,WAAO,EAAE,SAAS,SAAS;AAAA,EAC7B,CAAC;AACH;",
6
- "names": ["output", "resolved", "isMessageEntry", "SECTION_HEADERS"]
7
- }
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/core/call-preview.ts", "../../src/ui/preview-lines.ts", "../../src/providers/write-diff-limits.ts", "../../src/ui/transcript-reader.ts", "../../src/ui/transcript-parser.ts", "../../src/ui/transcript.ts"],
4
- "sourcesContent": ["// A shared, provider-agnostic heuristic for the one-line \"headline\" argument\n// of a nested Fabric call \u2014 the value shown beside a tool's name in the chat\n// preview (e.g. `recall <query>`) and appended to its ref in the dashboard\n// (e.g. `extensions.vcc_recall \u00B7 <query>`). OMP core tools and the first-class\n// Fabric providers (agents/mesh/mcp management) keep their bespoke, tuned\n// previews; this picks up everything else \u2014 captured extension tools and\n// arbitrary MCP tools \u2014 so they no longer render as a bare tool name.\n//\n// The key order preserves the dashboard's prior task -> path -> query ->\n// message preference for the fields it already recognized, then extends to\n// other common payload names. The final first-string fallback covers tools\n// whose argument names are unfamiliar, skipping structural/metadata keys\n// (label/title/mode/limit/...) that describe the call rather than its\n// payload. Control characters are not stripped here: the inline preview\n// already tolerates them (matching the existing task fallback) and the\n// dashboard sanitizes labels via safeText at render time.\nexport const HEADLINE_ARG_KEYS = [\n \"task\", \"path\", \"query\", \"message\", \"search\", \"pattern\", \"command\", \"text\",\n \"prompt\", \"question\", \"input\", \"content\", \"expression\", \"url\", \"topic\",\n \"key\", \"filter\", \"name\", \"q\",\n] as const;\n\nconst HEADLINE_SKIP_KEYS = new Set([\n \"label\", \"title\", \"type\", \"kind\", \"mode\", \"format\", \"resultFormat\",\n \"limit\", \"max\", \"offset\", \"start\", \"concurrency\", \"overwrite\", \"id\",\n \"provider\", \"namespace\", \"server\", \"tool\", \"ref\", \"recursive\", \"synthesize\",\n \"commandDigest\",\n]);\n\nconst cleanOneLine = (value: string, max: number): string => {\n const single = value.replace(/\\s+/g, \" \").trim();\n if (!single) return \"\";\n return single.length <= max ? single : `${single.slice(0, Math.max(1, max - 1))}\u2026`;\n};\n\n/**\n * Pick the best single-line argument value to display beside a nested call's\n * tool name, for tools that have no bespoke preview. Returns `undefined`\n * when no string payload argument is present.\n */\nexport const headlineArg = (\n args: Record<string, unknown> | undefined,\n max = 96,\n): string | undefined => {\n if (!args) return undefined;\n for (const key of HEADLINE_ARG_KEYS) {\n const value = args[key];\n if (typeof value === \"string\") {\n const cleaned = cleanOneLine(value, max);\n if (cleaned) return cleaned;\n }\n }\n for (const [key, value] of Object.entries(args)) {\n if (HEADLINE_SKIP_KEYS.has(key)) continue;\n if (typeof value === \"string\") {\n const cleaned = cleanOneLine(value, max);\n if (cleaned) return cleaned;\n }\n }\n return undefined;\n};\n", "// Adapted from pi-code-previews; see THIRD_PARTY_NOTICES.md.\n\nexport type PreviewLineEntry<T> =\n | { kind: \"line\"; line: T; index: number }\n | { kind: \"hidden\"; hidden: number };\n\nexport function countContentLines(content: string): number {\n if (!content) return 0;\n let terminators = 0;\n for (let index = 0; index < content.length; index++) {\n const code = content.charCodeAt(index);\n if (code === 13) {\n terminators++;\n if (content.charCodeAt(index + 1) === 10) index++;\n } else if (code === 10) {\n terminators++;\n }\n }\n const finalCode = content.charCodeAt(content.length - 1);\n return terminators + (finalCode === 10 || finalCode === 13 ? 0 : 1);\n}\n\nexport function selectPreviewTextLines(\n text: string,\n limit: number,\n): { entries: Array<PreviewLineEntry<string>>; shown: number; hidden: number; total: number } {\n if (!Number.isInteger(limit)) {\n const lines = collectPreviewTextLines(text);\n return { ...selectPreviewLines(lines, limit), total: lines.length };\n }\n\n const entries: Array<PreviewLineEntry<string>> = [];\n const split = limit >= 8;\n const head = split ? Math.ceil(limit * 0.65) : limit;\n const tailLimit = split ? Math.max(1, limit - head - 1) : 0;\n const tail: Array<string | undefined> = [];\n let tailSize = 0;\n let tailCursor = 0;\n let total = 0;\n forEachPreviewTextLine(text, (line, index) => {\n total++;\n if (limit <= 0 || index < limit) entries.push({ kind: \"line\", line, index });\n if (!split || index < head) return;\n tail[tailCursor] = line;\n if (++tailCursor === tailLimit) tailCursor = 0;\n if (tailSize < tailLimit) tailSize++;\n });\n\n if (limit <= 0 || total <= limit) return { entries, shown: total, hidden: 0, total };\n if (!split) return { entries, shown: limit, hidden: total - limit, total };\n const hidden = total - head - tailLimit;\n const selected = entries.slice(0, head);\n selected.push({ kind: \"hidden\", hidden });\n let tailSlot = tailSize === tailLimit ? tailCursor : 0;\n for (let offset = 0; offset < tailSize; offset++) {\n const line = tail[tailSlot];\n if (line === undefined) throw new RangeError(`Missing preview tail line ${offset}`);\n selected.push({ kind: \"line\", line, index: total - tailSize + offset });\n if (++tailSlot === tailLimit) tailSlot = 0;\n }\n return { entries: selected, shown: head + tailLimit, hidden, total };\n}\n\nfunction selectPreviewLines<T>(\n lines: T[],\n limit: number,\n): { entries: Array<PreviewLineEntry<T>>; shown: number; hidden: number } {\n if (lines.length <= limit || limit <= 0) {\n return {\n entries: lines.map((line, index) => ({ kind: \"line\", line, index })),\n shown: lines.length,\n hidden: 0,\n };\n }\n if (limit < 8) {\n return {\n entries: lines.slice(0, limit).map((line, index) => ({ kind: \"line\", line, index })),\n shown: limit,\n hidden: lines.length - limit,\n };\n }\n const head = Math.ceil(limit * 0.65);\n const tail = Math.max(1, limit - head - 1);\n const hidden = lines.length - head - tail;\n return {\n entries: [\n ...lines.slice(0, head).map((line, index) => ({ kind: \"line\" as const, line, index })),\n { kind: \"hidden\", hidden },\n ...lines.slice(-tail).map((line, offset) => ({\n kind: \"line\" as const,\n line,\n index: lines.length - tail + offset,\n })),\n ],\n shown: head + tail,\n hidden,\n };\n}\n\nfunction collectPreviewTextLines(text: string): string[] {\n const lines: string[] = [];\n forEachPreviewTextLine(text, (line) => lines.push(line));\n return lines;\n}\n\nfunction forEachPreviewTextLine(\n text: string,\n callback: (line: string, index: number) => void,\n): void {\n let index = 0;\n let pendingEmpty = 0;\n forEachRawTextLine(text, (line) => {\n if (line === \"\") {\n pendingEmpty++;\n return;\n }\n while (pendingEmpty > 0) {\n callback(\"\", index++);\n pendingEmpty--;\n }\n callback(line, index++);\n });\n if (index === 0 && pendingEmpty > 0 && text.length > 0) callback(\"\", index);\n}\n\nfunction forEachRawTextLine(text: string, callback: (line: string) => void): void {\n let start = 0;\n while (start <= text.length) {\n const newline = text.indexOf(\"\\n\", start);\n if (newline < 0) {\n callback(text.slice(start));\n break;\n }\n callback(text.slice(start, newline));\n start = newline + 1;\n }\n}\n", "// Pure write-diff size guards shared by the write-preview tool wrapper and the\n// dashboard's core-tool-render. Keep this module free of imports from\n// \"@oh-my-pi/pi-coding-agent\": it is part of the lazily imported\n// dashboard graph, which cannot resolve OMP's host package in managed\n// installs (issue #13).\n\nconst configuredMaxBytes = Number.parseInt(\n process.env.CODE_PREVIEW_MAX_WRITE_DIFF_BYTES ?? \"\",\n 10,\n);\nexport const MAX_WRITE_DIFF_BYTES =\n Number.isFinite(configuredMaxBytes) && configuredMaxBytes > 0\n ? configuredMaxBytes\n : 200_000;\n\nconst configuredMaxChangedLineCells = Number.parseInt(\n process.env.CODE_PREVIEW_MAX_WRITE_DIFF_CHANGED_LINE_CELLS ?? \"\",\n 10,\n);\nconst MAX_WRITE_DIFF_CHANGED_LINE_CELLS =\n Number.isFinite(configuredMaxChangedLineCells) && configuredMaxChangedLineCells > 0\n ? configuredMaxChangedLineCells\n : 1_000_000;\n\nexport const writeContentForPreview = (content: string): string | undefined =>\n Buffer.byteLength(content, \"utf8\") <= MAX_WRITE_DIFF_BYTES ? content : undefined;\n\nexport const shouldSkipWriteDiffBytes = (...texts: string[]): boolean => {\n let total = 0;\n for (const text of texts) {\n total += Buffer.byteLength(text, \"utf8\");\n if (total > MAX_WRITE_DIFF_BYTES) return true;\n }\n return false;\n};\n\nexport const shouldSkipWriteDiffComplexity = (before: string, after: string): boolean => {\n const beforeLines = before.split(\"\\n\");\n const afterLines = after.split(\"\\n\");\n const sharedLimit = Math.min(beforeLines.length, afterLines.length);\n let prefix = 0;\n while (prefix < sharedLimit && beforeLines[prefix] === afterLines[prefix]) prefix++;\n\n let suffix = 0;\n const suffixLimit = sharedLimit - prefix;\n while (\n suffix < suffixLimit &&\n beforeLines[beforeLines.length - suffix - 1] ===\n afterLines[afterLines.length - suffix - 1]\n ) {\n suffix++;\n }\n\n const changedBefore = beforeLines.length - prefix - suffix;\n const changedAfter = afterLines.length - prefix - suffix;\n return changedBefore * changedAfter > MAX_WRITE_DIFF_CHANGED_LINE_CELLS;\n};\n", "import fs from \"node:fs\";\nimport { readJsonlPageFromDescriptor } from \"../log-tail.js\";\nimport type { FabricLogLine } from \"../agents/types.js\";\nimport {\n missingToolStartIds,\n normalizedToolStarts,\n parsedEvents,\n parseRaw,\n TranscriptAccumulator,\n} from \"./transcript-parser.js\";\nimport type { FabricAgentTranscript, FabricTranscriptSource } from \"./transcript.js\";\n\nconst PAGE_LINES = 40;\nconst TOOL_LIFECYCLE_CONTEXT_LINES = PAGE_LINES * 4;\nconst MAX_PAGE_BYTES = 512 * 1024;\nconst MAX_CACHE_ENTRIES = 32;\nconst FORWARD_READ_CHUNK_BYTES = 64 * 1024;\n\ninterface CachedTranscript {\n device: number;\n inode: number;\n modifiedAt: number;\n offset: number;\n completeEnd: number;\n pageStart: number;\n pageEnd: number;\n hasMore: boolean;\n transcript: FabricAgentTranscript;\n}\n\ninterface ForwardTranscriptPage {\n lines: FabricLogLine[];\n end: number;\n}\n\nconst completeLogEnd = (descriptor: number, size: number, fallback = 0): number => {\n if (size <= 0) return 0;\n const scanFloor = Math.max(0, size - MAX_PAGE_BYTES);\n let scanEnd = size;\n while (scanEnd > scanFloor) {\n const scanStart = Math.max(scanFloor, scanEnd - FORWARD_READ_CHUNK_BYTES);\n const chunk = Buffer.allocUnsafe(scanEnd - scanStart);\n const bytesRead = fs.readSync(descriptor, chunk, 0, chunk.length, scanStart);\n if (bytesRead <= 0) return 0;\n for (let index = bytesRead - 1; index >= 0; index--) {\n if (chunk[index] === 0x0a) return scanStart + index + 1;\n }\n scanEnd = scanStart;\n }\n return Math.min(fallback, size);\n};\n\nconst readForwardPage = (\n descriptor: number,\n start: number,\n end: number,\n): ForwardTranscriptPage => {\n const lines: FabricLogLine[] = [];\n const readLimit = Math.min(end, Math.max(0, start) + MAX_PAGE_BYTES);\n let readOffset = Math.max(0, start);\n let pending = Buffer.alloc(0);\n let pendingOffset = readOffset;\n let pageEnd = readOffset;\n\n while (readOffset < readLimit && lines.length < PAGE_LINES) {\n const chunkSize = Math.min(FORWARD_READ_CHUNK_BYTES, readLimit - readOffset);\n const chunk = Buffer.allocUnsafe(chunkSize);\n const bytesRead = fs.readSync(descriptor, chunk, 0, chunkSize, readOffset);\n if (bytesRead <= 0) break;\n const data = pending.length > 0\n ? Buffer.concat([pending, chunk.subarray(0, bytesRead)])\n : chunk.subarray(0, bytesRead);\n const dataOffset = pending.length > 0 ? pendingOffset : readOffset;\n let lineStart = 0;\n for (let index = 0; index < data.length; index++) {\n if (data[index] !== 0x0a) continue;\n const raw = data.subarray(lineStart, index).toString(\"utf8\").replace(/\\r$/, \"\");\n pageEnd = dataOffset + index + 1;\n if (raw) {\n const offset = dataOffset + lineStart;\n const parsed = parseRaw(raw);\n lines.push({ offset, raw, ...(parsed ? { parsed } : {}) });\n if (lines.length >= PAGE_LINES) return { lines, end: pageEnd };\n }\n lineStart = index + 1;\n }\n pending = Buffer.from(data.subarray(lineStart));\n pendingOffset = dataOffset + lineStart;\n readOffset += bytesRead;\n }\n\n return { lines, end: readOffset >= end ? end : pageEnd };\n};\n\nexport class AgentTranscriptReader {\n readonly #cache = new Map<string, CachedTranscript>();\n\n read(\n source: FabricTranscriptSource,\n followLatest = true,\n ): FabricAgentTranscript {\n const filePath = source.logFile;\n if (!filePath) {\n return { entries: [], truncated: false, hasMore: false, hasNewer: false };\n }\n const cached = this.#cache.get(filePath);\n let descriptor: number | undefined;\n try {\n const noFollow = typeof fs.constants.O_NOFOLLOW === \"number\" ? fs.constants.O_NOFOLLOW : 0;\n descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);\n const stat = fs.fstatSync(descriptor);\n if (!stat.isFile()) {\n return cached?.transcript ?? {\n entries: [],\n truncated: false,\n hasMore: false,\n hasNewer: false,\n };\n }\n const sameFile = cached?.device === stat.dev && cached.inode === stat.ino;\n const sameSizeRewrite =\n sameFile && cached.offset === stat.size && cached.modifiedAt !== stat.mtimeMs;\n let state: CachedTranscript;\n if (!cached || !sameFile || stat.size < cached.offset || sameSizeRewrite) {\n state = this.#latestState(descriptor, stat);\n } else if (stat.size !== cached.offset || stat.mtimeMs !== cached.modifiedAt) {\n const wasAtTail = cached.pageEnd >= cached.completeEnd;\n const completeEnd = completeLogEnd(descriptor, stat.size, cached.completeEnd);\n if (\n cached.pageEnd > completeEnd ||\n (followLatest && wasAtTail && completeEnd > cached.completeEnd)\n ) {\n state = this.#latestState(descriptor, stat, completeEnd);\n } else {\n state = {\n ...cached,\n modifiedAt: stat.mtimeMs,\n offset: stat.size,\n completeEnd,\n transcript: {\n ...cached.transcript,\n hasNewer: cached.pageEnd < completeEnd,\n updatedAt: stat.mtimeMs,\n },\n };\n }\n } else {\n state = cached;\n }\n this.#remember(filePath, state);\n return state.transcript;\n } catch {\n return cached?.transcript ?? {\n entries: [],\n truncated: false,\n hasMore: false,\n hasNewer: false,\n };\n } finally {\n if (descriptor !== undefined) {\n try { fs.closeSync(descriptor); } catch {}\n }\n }\n }\n\n loadOlder(source: FabricTranscriptSource): boolean {\n const filePath = source.logFile;\n if (!filePath) return false;\n this.read(source, false);\n const cached = this.#cache.get(filePath);\n if (!cached?.hasMore || cached.pageStart <= 0) return false;\n let descriptor: number | undefined;\n try {\n const noFollow = typeof fs.constants.O_NOFOLLOW === \"number\" ? fs.constants.O_NOFOLLOW : 0;\n descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);\n const stat = fs.fstatSync(descriptor);\n if (!stat.isFile() || stat.dev !== cached.device || stat.ino !== cached.inode) return false;\n const completeEnd = completeLogEnd(descriptor, stat.size, cached.completeEnd);\n const pageEnd = Math.min(cached.pageStart, completeEnd);\n const page = readJsonlPageFromDescriptor(\n descriptor,\n PAGE_LINES,\n pageEnd,\n stat.size,\n MAX_PAGE_BYTES,\n );\n const pageStart = page.lines[0]?.offset;\n if (pageStart === undefined) return false;\n const state = this.#stateForPage(\n descriptor,\n stat,\n completeEnd,\n page.lines,\n pageStart,\n pageEnd,\n page.hasMore,\n );\n this.#remember(filePath, state);\n return true;\n } catch {\n return false;\n } finally {\n if (descriptor !== undefined) {\n try { fs.closeSync(descriptor); } catch {}\n }\n }\n }\n\n loadNewer(source: FabricTranscriptSource): boolean {\n const filePath = source.logFile;\n if (!filePath) return false;\n this.read(source, false);\n const cached = this.#cache.get(filePath);\n if (!cached || cached.pageEnd >= cached.completeEnd) return false;\n let descriptor: number | undefined;\n try {\n const noFollow = typeof fs.constants.O_NOFOLLOW === \"number\" ? fs.constants.O_NOFOLLOW : 0;\n descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);\n const stat = fs.fstatSync(descriptor);\n if (!stat.isFile() || stat.dev !== cached.device || stat.ino !== cached.inode) return false;\n const completeEnd = completeLogEnd(descriptor, stat.size, cached.completeEnd);\n const page = readForwardPage(descriptor, cached.pageEnd, completeEnd);\n if (page.lines.length === 0 || page.end <= cached.pageEnd) return false;\n const state = this.#stateForPage(\n descriptor,\n stat,\n completeEnd,\n page.lines,\n cached.pageEnd,\n page.end,\n cached.pageEnd > 0,\n );\n this.#remember(filePath, state);\n return true;\n } catch {\n return false;\n } finally {\n if (descriptor !== undefined) {\n try { fs.closeSync(descriptor); } catch {}\n }\n }\n }\n\n loadLatest(source: FabricTranscriptSource): boolean {\n const filePath = source.logFile;\n if (!filePath) return false;\n this.read(source, false);\n const cached = this.#cache.get(filePath);\n let descriptor: number | undefined;\n try {\n const noFollow = typeof fs.constants.O_NOFOLLOW === \"number\" ? fs.constants.O_NOFOLLOW : 0;\n descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | noFollow);\n const stat = fs.fstatSync(descriptor);\n if (!stat.isFile()) return false;\n if (cached && (stat.dev !== cached.device || stat.ino !== cached.inode)) return false;\n const completeEnd = completeLogEnd(descriptor, stat.size, cached?.completeEnd ?? 0);\n const state = this.#latestState(descriptor, stat, completeEnd);\n this.#remember(filePath, state);\n return true;\n } catch {\n return false;\n } finally {\n if (descriptor !== undefined) {\n try { fs.closeSync(descriptor); } catch {}\n }\n }\n }\n\n clear(): void {\n this.#cache.clear();\n }\n\n #latestState(\n descriptor: number,\n stat: fs.Stats,\n knownCompleteEnd?: number,\n ): CachedTranscript {\n const completeEnd = knownCompleteEnd ?? completeLogEnd(descriptor, stat.size);\n const page = readJsonlPageFromDescriptor(\n descriptor,\n PAGE_LINES,\n completeEnd,\n stat.size,\n MAX_PAGE_BYTES,\n );\n return this.#stateForPage(\n descriptor,\n stat,\n completeEnd,\n page.lines,\n page.lines[0]?.offset ?? completeEnd,\n completeEnd,\n page.hasMore,\n );\n }\n\n #stateForPage(\n descriptor: number,\n stat: fs.Stats,\n completeEnd: number,\n lines: FabricLogLine[],\n pageStart: number,\n pageEnd: number,\n hasMore: boolean,\n ): CachedTranscript {\n const events = parsedEvents(lines);\n const missingStarts = missingToolStartIds(events);\n const lifecycleContext: Array<Record<string, unknown>> = [];\n if (missingStarts.size > 0 && pageStart > 0) {\n const contextPage = readJsonlPageFromDescriptor(\n descriptor,\n TOOL_LIFECYCLE_CONTEXT_LINES,\n pageStart,\n stat.size,\n MAX_PAGE_BYTES,\n );\n const contextEvents = parsedEvents(contextPage.lines);\n for (let index = contextEvents.length - 1; index >= 0 && missingStarts.size > 0; index--) {\n const starts = normalizedToolStarts(contextEvents[index]!);\n for (let startIndex = starts.length - 1; startIndex >= 0; startIndex--) {\n const start = starts[startIndex]!;\n if (!missingStarts.delete(start.id)) continue;\n lifecycleContext.unshift(start.event);\n }\n }\n }\n const accumulator = new TranscriptAccumulator();\n accumulator.append([...lifecycleContext, ...events]);\n const transcript = {\n ...accumulator.snapshot(hasMore, stat.mtimeMs, Number.MAX_SAFE_INTEGER),\n hasNewer: pageEnd < completeEnd,\n };\n return {\n device: stat.dev,\n inode: stat.ino,\n modifiedAt: stat.mtimeMs,\n offset: stat.size,\n completeEnd,\n pageStart,\n pageEnd,\n hasMore: transcript.hasMore ?? false,\n transcript,\n };\n }\n\n #remember(filePath: string, state: CachedTranscript): void {\n this.#cache.delete(filePath);\n this.#cache.set(filePath, state);\n while (this.#cache.size > MAX_CACHE_ENTRIES) {\n const oldest = this.#cache.keys().next().value as string | undefined;\n if (!oldest) break;\n this.#cache.delete(oldest);\n }\n }\n}\n", "import type { FabricLogLine } from \"../agents/types.js\";\nimport type { FabricAgentTranscript, FabricTranscriptEntry } from \"./transcript.js\";\nimport { unwrapActorEnvelopeText } from \"./conversation-transcript.js\";\nimport {\n clip,\n compactRedactedValue,\n contentText,\n messageError,\n recordOf,\n redact,\n redactRecord,\n terminalSafe,\n} from \"./transcript-sanitization.js\";\n\nconst MAX_TOOL_SUMMARY_CHARS = 500;\nconst MAX_TRANSCRIPT_MESSAGE_CHARS = 40_000;\nconst TRANSCRIPT_ENTRY_LIMIT = 80;\n\ntype FabricTranscriptEntryStatus = \"running\" | \"completed\" | \"failed\";\n\nexport class TranscriptAccumulator {\n readonly entries: FabricTranscriptEntry[] = [];\n readonly #tools = new Map<string, FabricTranscriptEntry>();\n readonly #anonymousTools = new Map<string, FabricTranscriptEntry[]>();\n readonly #activeTools: FabricTranscriptEntry[] = [];\n #assistant: FabricTranscriptEntry | undefined;\n #retry: FabricTranscriptEntry | undefined;\n #compaction: FabricTranscriptEntry | undefined;\n readonly #userMessages = new Map<string, FabricTranscriptEntry>();\n readonly #userBoundaries = new Map<string, { serial: number; ended: boolean }>();\n #sequence = 0;\n\n append(events: Array<Record<string, unknown>>): void {\n for (const event of events) this.#append(event);\n }\n\n snapshot(\n olderAvailable = false,\n updatedAt?: number,\n maxEntries = TRANSCRIPT_ENTRY_LIMIT,\n ): FabricAgentTranscript {\n const entries = maxEntries > 0 && this.entries.length > maxEntries\n ? this.entries.slice(-maxEntries)\n : this.entries;\n const omitted = entries.length < this.entries.length;\n return {\n entries: entries.map((entry) => ({ ...entry })),\n truncated: olderAvailable || omitted,\n hasMore: olderAvailable || omitted,\n ...(updatedAt !== undefined ? { updatedAt } : {}),\n };\n }\n\n #nextId(event: Record<string, unknown>, prefix = \"event\"): string {\n if (typeof event.toolCallId === \"string\") return event.toolCallId;\n if (typeof event.uuid === \"string\") return event.uuid;\n if (typeof event.id === \"string\") return event.id;\n return `${prefix}-${this.#sequence++}`;\n }\n\n #finishAssistant(status: \"completed\" | \"failed\"): void {\n if (!this.#assistant) return;\n this.#assistant.status = status;\n this.#assistant = undefined;\n }\n\n #pushMessage(\n kind: \"user\" | \"assistant\",\n id: string,\n text: string,\n status: FabricTranscriptEntryStatus = \"completed\",\n label = kind === \"assistant\" ? \"Agent\" : \"User\",\n identity?: string,\n ): void {\n const display = kind === \"user\" ? (unwrapActorEnvelopeText(text) ?? text) : text;\n const safe = clip(display, MAX_TRANSCRIPT_MESSAGE_CHARS, kind !== \"user\");\n if (!safe) return;\n const entry: FabricTranscriptEntry = { id, kind, label, text: safe, status };\n if (kind === \"user\" && identity) {\n // Identity-aware start/end correlation: message_start and message_end\n // carry the same timestamp/content within one lifecycle. The boundary\n // serial distinguishes repeated turns even if their timestamps collide.\n const existing = this.#userMessages.get(identity);\n if (existing) {\n existing.text = safe;\n return;\n }\n this.#userMessages.set(identity, entry);\n }\n this.entries.push(entry);\n }\n\n #userIdentity(event: Record<string, unknown>, message: Record<string, unknown>): string | undefined {\n if (event.type === \"message_start\" || event.type === \"message_end\" || event.type === \"message\") {\n const timestamp = message.timestamp;\n if (typeof timestamp === \"number\" && Number.isFinite(timestamp)) {\n const base = JSON.stringify([timestamp, contentText(message.content)]);\n let boundary = this.#userBoundaries.get(base);\n if (!boundary || (event.type === \"message_start\" && boundary.ended)) {\n boundary = { serial: (boundary?.serial ?? -1) + 1, ended: false };\n this.#userBoundaries.set(base, boundary);\n }\n if (event.type === \"message_end\") boundary.ended = true;\n return `user:${base}:${boundary.serial}`;\n }\n }\n return undefined;\n }\n\n #toolParent(id: string): FabricTranscriptEntry | undefined {\n if (!id.startsWith(\"fabric_\")) return undefined;\n for (let index = this.#activeTools.length - 1; index >= 0; index--) {\n const candidate = this.#activeTools[index];\n if (candidate?.toolName === \"fabric_exec\" && candidate.status === \"running\") return candidate;\n }\n return undefined;\n }\n\n #startTool(\n id: string,\n label: string,\n args: unknown,\n ): FabricTranscriptEntry {\n const existing = this.#tools.get(id);\n const safeArgs = args === undefined ? undefined : redactRecord(args);\n if (existing) {\n if (safeArgs !== undefined) existing.args = safeArgs;\n if (args !== undefined) existing.text = compactRedactedValue(safeArgs ?? redact(args));\n return existing;\n }\n const parent = this.#toolParent(id);\n const safeLabel = terminalSafe(label) || \"tool\";\n const entry: FabricTranscriptEntry = {\n id,\n kind: \"tool\",\n label: safeLabel,\n toolName: safeLabel,\n status: \"running\",\n ...(safeArgs !== undefined ? { args: safeArgs } : {}),\n ...(args !== undefined\n ? { text: compactRedactedValue(safeArgs ?? redact(args)) }\n : {}),\n ...(parent ? { parentId: parent.id, depth: (parent.depth ?? 0) + 1 } : {}),\n };\n this.entries.push(entry);\n this.#tools.set(id, entry);\n this.#activeTools.push(entry);\n return entry;\n }\n\n #finishTool(id: string | undefined, label: string, result: unknown, failed: boolean): void {\n const safeLabel = terminalSafe(label) || \"tool\";\n const anonymous = this.#anonymousTools.get(safeLabel);\n const entry = id ? this.#tools.get(id) : anonymous?.shift();\n if (anonymous?.length === 0) this.#anonymousTools.delete(safeLabel);\n const safeResult = result === undefined ? undefined : redact(result);\n if (entry) {\n entry.status = failed ? \"failed\" : \"completed\";\n if (safeResult !== undefined) entry.result = safeResult;\n if (failed && result !== undefined) {\n const failure = compactRedactedValue(safeResult);\n entry.text = clip(\n `${entry.text ? `${entry.text} \u00B7 ` : \"\"}error: ${failure}`,\n MAX_TOOL_SUMMARY_CHARS,\n );\n }\n this.#tools.delete(entry.id);\n const activeIndex = this.#activeTools.indexOf(entry);\n if (activeIndex >= 0) this.#activeTools.splice(activeIndex, 1);\n return;\n }\n this.entries.push({\n id: id ?? `tool-${this.#sequence++}`,\n kind: \"tool\",\n label: safeLabel,\n toolName: safeLabel,\n status: failed ? \"failed\" : \"completed\",\n ...(safeResult !== undefined ? { result: safeResult } : {}),\n ...(failed && safeResult !== undefined ? { text: compactRedactedValue(safeResult) } : {}),\n });\n }\n\n #appendSessionMessage(event: Record<string, unknown>, message: Record<string, unknown>): void {\n const id = this.#nextId(event, \"message\");\n if (message.role === \"user\") {\n this.#pushMessage(\"user\", id, contentText(message.content), \"completed\", \"User\", this.#userIdentity(event, message));\n return;\n }\n if (message.role === \"assistant\") {\n const error = messageError(message);\n const text = contentText(message.content);\n if (text) this.#pushMessage(\"assistant\", id, text, error ? \"failed\" : \"completed\");\n if (error) {\n this.entries.push({\n id: `${id}-error`,\n kind: \"error\",\n label: \"Agent error\",\n text: error,\n status: \"failed\",\n });\n }\n if (Array.isArray(message.content)) {\n for (const value of message.content) {\n const part = recordOf(value);\n if (part?.type !== \"toolCall\" || typeof part.name !== \"string\") continue;\n const toolId = typeof part.id === \"string\" ? part.id : `session-tool-${this.#sequence++}`;\n this.#startTool(toolId, part.name, part.arguments);\n }\n }\n return;\n }\n if (message.role === \"toolResult\") {\n const toolId = typeof message.toolCallId === \"string\" ? message.toolCallId : undefined;\n const label = typeof message.toolName === \"string\" ? message.toolName : \"tool\";\n this.#finishTool(\n toolId,\n label,\n { content: message.content, ...(message.details !== undefined ? { details: message.details } : {}) },\n message.isError === true,\n );\n }\n }\n\n #append(event: Record<string, unknown>): void {\n if (typeof event.type !== \"string\") return;\n const id = this.#nextId(event);\n\n if (event.type === \"message\") {\n const message = recordOf(event.message);\n if (message) this.#appendSessionMessage(event, message);\n return;\n }\n\n if (event.type === \"model_changed\") {\n const provider = typeof event.provider === \"string\" ? event.provider : \"\";\n const model = typeof event.modelId === \"string\" ? event.modelId : \"\";\n this.entries.push({\n id,\n kind: \"status\",\n label: \"Model changed\",\n ...(provider || model ? { text: [provider, model].filter(Boolean).join(\"/\") } : {}),\n status: \"completed\",\n });\n return;\n }\n\n if (event.type === \"thinking_level_changed\") {\n this.entries.push({\n id,\n kind: \"status\",\n label: \"Thinking changed\",\n ...(typeof event.thinkingLevel === \"string\" ? { text: event.thinkingLevel } : {}),\n status: \"completed\",\n });\n return;\n }\n\n if (event.type === \"compaction\") {\n this.entries.push({\n id,\n kind: \"status\",\n label: \"Compacted context\",\n ...(typeof event.summary === \"string\" ? { text: terminalSafe(event.summary) } : {}),\n status: \"completed\",\n });\n return;\n }\n\n if (event.type === \"stream_event\") {\n const stream = recordOf(event.event);\n const delta = recordOf(stream?.delta);\n if (stream?.type === \"content_block_delta\" && delta?.type === \"text_delta\") {\n const text = typeof delta.text === \"string\" ? terminalSafe(delta.text, false) : \"\";\n if (!text) return;\n if (!this.#assistant) {\n this.#assistant = {\n id,\n kind: \"assistant\",\n label: \"Claude\",\n text: clip(text, MAX_TRANSCRIPT_MESSAGE_CHARS, false),\n status: \"running\",\n };\n this.entries.push(this.#assistant);\n } else {\n this.#assistant.text = clip(\n `${this.#assistant.text ?? \"\"}${text}`,\n MAX_TRANSCRIPT_MESSAGE_CHARS,\n false,\n );\n }\n }\n return;\n }\n\n if (event.type === \"assistant\") {\n const message = recordOf(event.message);\n if (!message || message.role !== \"assistant\") return;\n if (Array.isArray(message.content)) {\n for (const value of message.content) {\n const part = recordOf(value);\n if (part?.type !== \"tool_use\") continue;\n const toolId = typeof part.id === \"string\" ? part.id : `claude-tool-${this.#sequence++}`;\n const label = typeof part.name === \"string\" ? part.name : \"tool\";\n this.#startTool(toolId, label, part.input);\n }\n }\n const text = terminalSafe(contentText(message.content));\n if (text) {\n if (this.#assistant) {\n this.#assistant.text = clip(text, MAX_TRANSCRIPT_MESSAGE_CHARS);\n this.#finishAssistant(\"completed\");\n } else {\n this.#pushMessage(\"assistant\", id, text, \"completed\", \"Claude\");\n }\n }\n if (typeof event.error === \"string\") {\n this.entries.push({\n id: `${id}-error`,\n kind: \"error\",\n label: \"Claude error\",\n text: clip(event.error, MAX_TOOL_SUMMARY_CHARS),\n status: \"failed\",\n });\n }\n return;\n }\n\n if (event.type === \"user\") {\n const message = recordOf(event.message);\n if (!message || !Array.isArray(message.content)) return;\n let hasToolResult = false;\n for (const value of message.content) {\n const part = recordOf(value);\n if (part?.type !== \"tool_result\" || typeof part.tool_use_id !== \"string\") continue;\n hasToolResult = true;\n this.#finishTool(part.tool_use_id, \"tool\", part.content, part.is_error === true);\n }\n if (!hasToolResult) this.#pushMessage(\"user\", id, contentText(message.content));\n return;\n }\n\n if (event.type === \"result\") {\n this.#finishAssistant(event.is_error === true ? \"failed\" : \"completed\");\n if (event.is_error === true || event.subtype !== \"success\") {\n const errors = Array.isArray(event.errors)\n ? event.errors.filter((value): value is string => typeof value === \"string\").join(\" \u00B7 \")\n : \"\";\n const text = errors || (typeof event.result === \"string\" ? event.result : \"Claude run failed\");\n this.entries.push({\n id,\n kind: \"error\",\n label: \"Claude result\",\n text: clip(text, MAX_TOOL_SUMMARY_CHARS),\n status: \"failed\",\n });\n }\n return;\n }\n\n if (event.type === \"system\" && event.subtype === \"api_retry\") {\n this.entries.push({\n id,\n kind: \"status\",\n label: \"Claude API retry\",\n status: \"running\",\n ...(typeof event.error === \"string\"\n ? { text: clip(event.error, MAX_TOOL_SUMMARY_CHARS) }\n : {}),\n });\n return;\n }\n\n if (event.type === \"message_start\") this.#finishAssistant(\"completed\");\n if (event.type === \"message_start\" || event.type === \"message_update\") {\n const message = recordOf(event.message);\n if (!message) return;\n if (message.role === \"user\") {\n if (event.type === \"message_start\") {\n this.#pushMessage(\"user\", id, contentText(message.content), \"completed\", \"User\", this.#userIdentity(event, message));\n }\n return;\n }\n if (message.role !== \"assistant\") return;\n const text = terminalSafe(contentText(message.content));\n if (!text) return;\n if (!this.#assistant) {\n this.#assistant = {\n id,\n kind: \"assistant\",\n label: \"Agent\",\n text: clip(text, MAX_TRANSCRIPT_MESSAGE_CHARS),\n status: \"running\",\n };\n this.entries.push(this.#assistant);\n } else {\n this.#assistant.text = clip(text, MAX_TRANSCRIPT_MESSAGE_CHARS);\n if (!this.entries.includes(this.#assistant)) this.entries.push(this.#assistant);\n }\n return;\n }\n\n if (event.type === \"message_end\") {\n const message = recordOf(event.message);\n if (!message) return;\n if (message.role === \"user\") {\n this.#pushMessage(\"user\", id, contentText(message.content), \"completed\", \"User\", this.#userIdentity(event, message));\n return;\n }\n if (message.role !== \"assistant\") return;\n const error = messageError(message);\n if (error) {\n this.#finishAssistant(\"failed\");\n this.entries.push({ id, kind: \"error\", label: \"Agent error\", text: error, status: \"failed\" });\n return;\n }\n const text = terminalSafe(contentText(message.content));\n if (!text) {\n this.#finishAssistant(\"completed\");\n return;\n }\n if (!this.#assistant) this.#pushMessage(\"assistant\", id, text);\n else {\n this.#assistant.text = clip(text, MAX_TRANSCRIPT_MESSAGE_CHARS);\n this.#finishAssistant(\"completed\");\n }\n return;\n }\n\n if (event.type === \"response\" && event.command === \"prompt\" && event.success === false) {\n const text = typeof event.error === \"string\" ? event.error : \"OMP rejected the prompt\";\n this.entries.push({\n id,\n kind: \"error\",\n label: \"Prompt rejected\",\n text: clip(text, MAX_TOOL_SUMMARY_CHARS),\n status: \"failed\",\n });\n return;\n }\n\n if (event.type === \"tool_execution_start\") {\n const label = typeof event.toolName === \"string\" ? event.toolName : \"tool\";\n const entry = this.#startTool(id, label, event.args);\n if (typeof event.toolCallId !== \"string\") {\n const key = terminalSafe(label) || \"tool\";\n this.#tools.delete(entry.id);\n this.#anonymousTools.set(key, [...(this.#anonymousTools.get(key) ?? []), entry]);\n }\n return;\n }\n\n if (event.type === \"tool_execution_end\") {\n const label = typeof event.toolName === \"string\" ? event.toolName : \"tool\";\n this.#finishTool(\n typeof event.toolCallId === \"string\" ? event.toolCallId : undefined,\n label,\n event.result,\n event.isError === true,\n );\n return;\n }\n\n if (event.type === \"auto_retry_start\") {\n const attempt = typeof event.attempt === \"number\" ? ` ${event.attempt}` : \"\";\n this.#retry = {\n id,\n kind: \"status\",\n label: `Retry${attempt}`,\n status: \"running\",\n ...(typeof event.errorMessage === \"string\"\n ? { text: clip(event.errorMessage, MAX_TOOL_SUMMARY_CHARS) }\n : {}),\n };\n this.entries.push(this.#retry);\n return;\n }\n if (event.type === \"auto_retry_end\") {\n const failed = event.success === false;\n if (this.#retry) {\n this.#retry.status = failed ? \"failed\" : \"completed\";\n if (failed && typeof event.finalError === \"string\") {\n this.#retry.text = clip(event.finalError, MAX_TOOL_SUMMARY_CHARS);\n }\n this.#retry = undefined;\n }\n return;\n }\n\n if (event.type === \"auto_compaction_start\") {\n this.#compaction = {\n id,\n kind: \"status\",\n label: \"Compacting context\",\n status: \"running\",\n };\n this.entries.push(this.#compaction);\n return;\n }\n if (event.type === \"auto_compaction_end\") {\n if (this.#compaction) {\n const failed = event.aborted === true || typeof event.errorMessage === \"string\";\n this.#compaction.status = failed ? \"failed\" : \"completed\";\n if (typeof event.errorMessage === \"string\") {\n this.#compaction.text = clip(event.errorMessage, MAX_TOOL_SUMMARY_CHARS);\n }\n this.#compaction = undefined;\n }\n return;\n }\n\n if (event.type === \"extension_error\" || event.type === \"worker_stderr\") {\n const text =\n typeof event.error === \"string\"\n ? event.error\n : typeof event.text === \"string\"\n ? event.text\n : \"Extension error\";\n const warningLines = text.split(/\\r?\\n/).filter((line) => line.trim());\n const warningCount = event.type === \"worker_stderr\" && warningLines.length > 0 &&\n warningLines.every((line) => /^\\s*Warning:/.test(line)) ? warningLines.length : 0;\n this.entries.push({\n id,\n kind: \"error\",\n label: event.type === \"worker_stderr\" ? \"Worker stderr\" : \"Error\",\n text: clip(text, warningCount > 0 ? MAX_TRANSCRIPT_MESSAGE_CHARS : MAX_TOOL_SUMMARY_CHARS),\n ...(event.type === \"worker_stderr\" ? { warningCount } : {}),\n status: \"failed\",\n });\n }\n }\n}\n\nexport const parseRaw = (raw: string): Record<string, unknown> | undefined => {\n try {\n return recordOf(JSON.parse(raw));\n } catch {\n return undefined;\n }\n};\n\nexport const parsedEvents = (lines: FabricLogLine[]): Array<Record<string, unknown>> =>\n lines\n .map((line) => recordOf(line.parsed) ?? parseRaw(line.raw))\n .filter((event): event is Record<string, unknown> => event !== undefined);\n\ninterface ToolLifecycleStart {\n id: string;\n event: Record<string, unknown>;\n}\n\nexport const normalizedToolStarts = (event: Record<string, unknown>): ToolLifecycleStart[] => {\n if (\n event.type === \"tool_execution_start\" &&\n typeof event.toolCallId === \"string\"\n ) {\n return [{ id: event.toolCallId, event }];\n }\n\n const starts: ToolLifecycleStart[] = [];\n const appendContentStarts = (\n content: unknown,\n type: \"toolCall\" | \"tool_use\",\n ): void => {\n if (!Array.isArray(content)) return;\n for (const value of content) {\n const part = recordOf(value);\n if (part?.type !== type || typeof part.id !== \"string\") continue;\n const name = typeof part.name === \"string\" ? part.name : \"tool\";\n starts.push({\n id: part.id,\n event: {\n type: \"tool_execution_start\",\n toolCallId: part.id,\n toolName: name,\n args: type === \"toolCall\" ? part.arguments : part.input,\n },\n });\n }\n };\n\n if (event.type === \"message\") {\n const message = recordOf(event.message);\n if (message?.role === \"assistant\") appendContentStarts(message.content, \"toolCall\");\n } else if (event.type === \"assistant\") {\n const message = recordOf(event.message);\n if (message?.role === \"assistant\") appendContentStarts(message.content, \"tool_use\");\n }\n return starts;\n};\n\nconst toolLifecycleEndIds = (event: Record<string, unknown>): string[] => {\n if (event.type === \"tool_execution_end\" && typeof event.toolCallId === \"string\") {\n return [event.toolCallId];\n }\n if (event.type === \"message\") {\n const message = recordOf(event.message);\n return message?.role === \"toolResult\" && typeof message.toolCallId === \"string\"\n ? [message.toolCallId]\n : [];\n }\n if (event.type !== \"user\") return [];\n const message = recordOf(event.message);\n if (!Array.isArray(message?.content)) return [];\n return message.content.flatMap((value) => {\n const part = recordOf(value);\n return part?.type === \"tool_result\" && typeof part.tool_use_id === \"string\"\n ? [part.tool_use_id]\n : [];\n });\n};\n\nexport const missingToolStartIds = (events: Array<Record<string, unknown>>): Set<string> => {\n const active = new Set<string>();\n const missing = new Set<string>();\n for (const event of events) {\n for (const start of normalizedToolStarts(event)) active.add(start.id);\n for (const id of toolLifecycleEndIds(event)) {\n if (active.has(id)) active.delete(id);\n else missing.add(id);\n }\n }\n return missing;\n};\n", "import { TranscriptAccumulator } from \"./transcript-parser.js\";\nimport { AgentTranscriptReader } from \"./transcript-reader.js\";\nimport { recordOf } from \"./transcript-sanitization.js\";\n\ntype FabricTranscriptEntryStatus = \"running\" | \"completed\" | \"failed\";\n\nexport interface FabricTranscriptEntry {\n id: string;\n kind: \"user\" | \"assistant\" | \"tool\" | \"error\" | \"status\";\n label: string;\n text?: string;\n status?: FabricTranscriptEntryStatus;\n toolName?: string;\n args?: Record<string, unknown>;\n result?: unknown;\n parentId?: string;\n depth?: number;\n /** Count only when the original stderr chunk contains warnings exclusively. */\n warningCount?: number;\n}\n\nexport interface FabricAgentTranscript {\n entries: FabricTranscriptEntry[];\n /** Kept for compatibility; true means older pages are available. */\n truncated: boolean;\n hasMore?: boolean;\n hasNewer?: boolean;\n updatedAt?: number;\n}\n\nexport interface FabricTranscriptSource {\n id: string;\n status: string;\n logFile?: string;\n}\n\nexport interface FabricAgentToolPreviewNode {\n id: string;\n name: string;\n status?: string;\n runner?: \"omp\" | \"claude\" | \"veda\";\n owner?: \"agent\" | \"actor\";\n /** Most recent tool the agent was observed running, when known. */\n currentTool?: string;\n text?: string;\n tools: FabricTranscriptEntry[];\n /** Descendant previews, one branch per spawned nested agent run. */\n agents?: FabricAgentToolPreviewNode[];\n /** True when descendant previews were cut by the preview tree budget. */\n agentsTruncated?: boolean;\n}\n\nexport interface FabricAgentToolPreview extends FabricAgentToolPreviewNode {\n kind: \"fabric-agent-tools\";\n}\n\nexport const projectAgentTranscript = (\n events: Array<Record<string, unknown>>,\n olderAvailable = false,\n): FabricAgentTranscript => {\n const accumulator = new TranscriptAccumulator();\n accumulator.append(events);\n return accumulator.snapshot(olderAvailable);\n};\n\nconst PREVIEW_TREE_GUARD_MAX_DEPTH = 8;\n\nconst isFabricAgentToolPreviewNode = (\n value: unknown,\n depth: number,\n): value is FabricAgentToolPreviewNode => {\n const record = recordOf(value);\n if (\n !record ||\n typeof record.id !== \"string\" ||\n typeof record.name !== \"string\" ||\n (record.text !== undefined && typeof record.text !== \"string\") ||\n (record.currentTool !== undefined && typeof record.currentTool !== \"string\") ||\n !Array.isArray(record.tools)\n ) {\n return false;\n }\n if (record.agents === undefined) return true;\n if (depth >= PREVIEW_TREE_GUARD_MAX_DEPTH || !Array.isArray(record.agents)) return false;\n return record.agents.every((child) => isFabricAgentToolPreviewNode(child, depth + 1));\n};\n\nexport const isFabricAgentToolPreview = (value: unknown): value is FabricAgentToolPreview =>\n recordOf(value)?.kind === \"fabric-agent-tools\" && isFabricAgentToolPreviewNode(value, 0);\n\nexport const recentTranscriptTools = (\n transcript: FabricAgentTranscript,\n limit = 2,\n): FabricTranscriptEntry[] => {\n const tools = transcript.entries.filter((entry) => entry.kind === \"tool\");\n const boundedLimit = Math.max(1, limit);\n const running = tools.filter((entry) => entry.status === \"running\");\n const completed = tools.filter((entry) => entry.status !== \"running\");\n const completedSlots = Math.max(0, boundedLimit - Math.min(running.length, boundedLimit));\n const retained = new Set([\n ...running.slice(-boundedLimit),\n ...completed.slice(-completedSlots),\n ]);\n return tools\n .filter((entry) => retained.has(entry))\n .slice(-boundedLimit)\n .map((entry) => ({ ...entry }));\n};\n\nexport { AgentTranscriptReader };\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;AAgBO,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAS;AAAA,EAAW;AAAA,EAAU;AAAA,EAAW;AAAA,EAAW;AAAA,EACpE;AAAA,EAAU;AAAA,EAAY;AAAA,EAAS;AAAA,EAAW;AAAA,EAAc;AAAA,EAAO;AAAA,EAC/D;AAAA,EAAO;AAAA,EAAU;AAAA,EAAQ;AAC3B;AAEA,IAAM,qBAAqB,oBAAI,IAAI;AAAA,EACjC;AAAA,EAAS;AAAA,EAAS;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAQ;AAAA,EAAU;AAAA,EACpD;AAAA,EAAS;AAAA,EAAO;AAAA,EAAU;AAAA,EAAS;AAAA,EAAe;AAAA,EAAa;AAAA,EAC/D;AAAA,EAAY;AAAA,EAAa;AAAA,EAAU;AAAA,EAAQ;AAAA,EAAO;AAAA,EAAa;AAAA,EAC/D;AACF,CAAC;AAED,IAAM,eAAe,CAAC,OAAe,QAAwB;AAC3D,QAAM,SAAS,MAAM,QA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