@leitwerk-dev/protocol 0.5.3 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/usage-snapshot.ts","../src/ws-event-payloads.ts","../src/compact-turn-summary.ts","../src/extension-ui-contracts.ts","../src/initial-prompt.ts","../src/live-turn-projection.ts","../src/pi-session-message.ts","../src/timestamp-ordering.ts","../src/tool-result-truncation.ts","../src/session-entry-tree.ts","../src/skill-pack.ts","../src/streamable-events.ts","../src/text-preview.ts","../src/timeline-projection.ts","../src/turn-continuation.ts","../src/usage-by-turn-record.ts"],"sourcesContent":["import { copiedUnknownRecordSchema as unknownRecordSchema } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\n\n/** @internal */\nexport interface UsageCostSnapshot {\n\t/** @internal */\n\tinput: number;\n\t/** @internal */\n\toutput: number;\n\t/** @internal */\n\tcacheRead: number;\n\t/** @internal */\n\tcacheWrite: number;\n\t/** @internal */\n\ttotal: number;\n}\n\n/** @internal */\nexport interface UsageTokenCounts {\n\t/** @internal */\n\tinput: number;\n\t/** @internal */\n\toutput: number;\n\t/** Provider-reported reasoning/thinking tokens. This is a subset of output tokens. @internal */\n\treasoning?: number;\n\t/** @internal */\n\tcacheRead: number;\n\t/** @internal */\n\tcacheWrite: number;\n\t/** @internal */\n\ttotalTokens: number;\n}\n\n/** @internal */\nexport interface UsageSnapshot extends UsageTokenCounts {\n\t/** @internal */\n\tcost: UsageCostSnapshot | null;\n\t/** Number of model requests represented by this aggregate, when known. @internal */\n\trequestCount?: number;\n\t/** Largest input-token count for a single represented model request, when known. @internal */\n\tmaxInputTokens?: number;\n}\n\nfunction readFiniteNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction normalizeUsageCostSnapshot(value: unknown): UsageCostSnapshot | null {\n\tconst parsedValue = v.safeParse(unknownRecordSchema, value);\n\tif (!parsedValue.success) {\n\t\treturn null;\n\t}\n\tconst record = parsedValue.output;\n\tconst input = readFiniteNumber(record.input) ?? 0;\n\tconst output = readFiniteNumber(record.output) ?? 0;\n\tconst cacheRead = readFiniteNumber(record.cacheRead) ?? 0;\n\tconst cacheWrite = readFiniteNumber(record.cacheWrite) ?? 0;\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\ttotal: readFiniteNumber(record.total) ?? input + output + cacheRead + cacheWrite,\n\t};\n}\n\n/** @internal */\nexport function cloneUsageSnapshot(usage: UsageSnapshot | null | undefined): UsageSnapshot | null {\n\tif (!usage) {\n\t\treturn null;\n\t}\n\treturn {\n\t\t...usage,\n\t\tcost: usage.cost ? { ...usage.cost } : null,\n\t};\n}\n\n/** @internal */\nexport function normalizeUsageSnapshot(value: unknown): UsageSnapshot | null {\n\tconst parsedValue = v.safeParse(unknownRecordSchema, value);\n\tif (!parsedValue.success) {\n\t\treturn null;\n\t}\n\tconst record = parsedValue.output;\n\tconst input = readFiniteNumber(record.input) ?? 0;\n\tconst output = readFiniteNumber(record.output) ?? 0;\n\tconst reasoning = readFiniteNumber(record.reasoning);\n\tconst cacheRead = readFiniteNumber(record.cacheRead) ?? 0;\n\tconst cacheWrite = readFiniteNumber(record.cacheWrite) ?? 0;\n\tconst cost = normalizeUsageCostSnapshot(record.cost);\n\tconst maxInputTokens = readFiniteNumber(record.maxInputTokens);\n\tconst hasExplicitUsageTelemetry =\n\t\t[\"input\", \"output\", \"reasoning\", \"cacheRead\", \"cacheWrite\", \"totalTokens\"].some(\n\t\t\t(key) => readFiniteNumber(record[key]) !== undefined,\n\t\t) || cost !== null;\n\tif (!hasExplicitUsageTelemetry) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\t...(reasoning !== undefined ? { reasoning } : {}),\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\ttotalTokens: readFiniteNumber(record.totalTokens) ?? input + output + cacheRead + cacheWrite,\n\t\tcost,\n\t\trequestCount: Math.max(0, Math.floor(readFiniteNumber(record.requestCount) ?? 1)),\n\t\tmaxInputTokens: maxInputTokens !== undefined ? Math.max(0, maxInputTokens) : input,\n\t};\n}\n\n/** @internal */\nexport function mergeUsageSnapshots(\n\ttotal: UsageSnapshot | null,\n\tusage: UsageSnapshot | null,\n): UsageSnapshot | null {\n\tif (!usage) {\n\t\treturn cloneUsageSnapshot(total);\n\t}\n\tif (!total) {\n\t\treturn cloneUsageSnapshot(usage);\n\t}\n\tconst hasRequestMetrics =\n\t\ttotal.requestCount !== undefined ||\n\t\tusage.requestCount !== undefined ||\n\t\ttotal.maxInputTokens !== undefined ||\n\t\tusage.maxInputTokens !== undefined;\n\treturn {\n\t\tinput: total.input + usage.input,\n\t\toutput: total.output + usage.output,\n\t\t...(total.reasoning !== undefined || usage.reasoning !== undefined\n\t\t\t? { reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0) }\n\t\t\t: {}),\n\t\tcacheRead: total.cacheRead + usage.cacheRead,\n\t\tcacheWrite: total.cacheWrite + usage.cacheWrite,\n\t\ttotalTokens: total.totalTokens + usage.totalTokens,\n\t\tcost:\n\t\t\ttotal.cost && usage.cost\n\t\t\t\t? {\n\t\t\t\t\t\tinput: total.cost.input + usage.cost.input,\n\t\t\t\t\t\toutput: total.cost.output + usage.cost.output,\n\t\t\t\t\t\tcacheRead: total.cost.cacheRead + usage.cost.cacheRead,\n\t\t\t\t\t\tcacheWrite: total.cost.cacheWrite + usage.cost.cacheWrite,\n\t\t\t\t\t\ttotal: total.cost.total + usage.cost.total,\n\t\t\t\t\t}\n\t\t\t\t: null,\n\t\t...(hasRequestMetrics\n\t\t\t? {\n\t\t\t\t\trequestCount: (total.requestCount ?? 1) + (usage.requestCount ?? 1),\n\t\t\t\t\tmaxInputTokens: Math.max(\n\t\t\t\t\t\ttotal.maxInputTokens ?? total.input,\n\t\t\t\t\t\tusage.maxInputTokens ?? usage.input,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n","import { asUnknownRecord, trimToNull as readWsEventNonEmptyString } from \"@leitwerk-dev/domain\";\n\n/** @internal */\nexport interface WsEventPayloadRecord extends Record<string, unknown> {}\n\n/** @internal */\nexport interface ResolveWsEventToolCallIdOptions {\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttoolName?: string;\n\t/** @internal */\n\tordinal?: number;\n}\n\n/** @internal */\nexport function asWsEventPayloadRecord(value: unknown): WsEventPayloadRecord {\n\treturn asUnknownRecord(value) ?? {};\n}\n\nexport { readWsEventNonEmptyString };\n\n/** @internal */\nexport function readWsEventTimestamp(\n\tdata: WsEventPayloadRecord,\n\tfallbackTimestamp: string,\n): string {\n\treturn readWsEventNonEmptyString(data.timestamp) ?? fallbackTimestamp;\n}\n\n/** @internal */\nexport function readWsEventTurnRecordId(data: WsEventPayloadRecord): string | null {\n\treturn readWsEventNonEmptyString(data.turnRecordId);\n}\n\n/** @internal */\nexport function readWsEventPiTurnId(data: WsEventPayloadRecord): string | null {\n\treturn readWsEventNonEmptyString(data.turnId);\n}\n\n/** @internal */\nexport function readWsEventStreamText(data: WsEventPayloadRecord): string | null {\n\treturn typeof data.text === \"string\"\n\t\t? data.text\n\t\t: typeof data.delta === \"string\"\n\t\t\t? data.delta\n\t\t\t: typeof data.chunk === \"string\"\n\t\t\t\t? data.chunk\n\t\t\t\t: null;\n}\n\n/** @internal */\nexport function readWsEventToolName(data: WsEventPayloadRecord): string {\n\treturn readWsEventNonEmptyString(data.name) ?? readWsEventNonEmptyString(data.toolName) ?? \"tool\";\n}\n\n/** @internal */\nexport function readWsEventToolArguments(\n\tdata: WsEventPayloadRecord,\n): Record<string, unknown> | null {\n\treturn asUnknownRecord(data.arguments ?? data.args);\n}\n\n/** @internal */\nexport function readWsEventToolCallId(data: WsEventPayloadRecord): string | null {\n\treturn readWsEventNonEmptyString(data.toolCallId);\n}\n\n/** @internal */\nexport function resolveWsEventToolCallId(\n\tdata: WsEventPayloadRecord,\n\toptions: ResolveWsEventToolCallIdOptions,\n): string {\n\treturn (\n\t\treadWsEventToolCallId(data) ??\n\t\t`${options.toolName ?? readWsEventToolName(data)}:${options.timestamp}${options.ordinal ? `:${options.ordinal}` : \"\"}`\n\t);\n}\n","import type {\n\tPrimaryPathActiveTurnSnapshot,\n\tPrimaryPathToolCallSnapshot,\n} from \"./primary-path-snapshot.js\";\nimport {\n\tmergeUsageSnapshots,\n\tnormalizeUsageSnapshot,\n\ttype UsageSnapshot,\n} from \"./usage-snapshot.js\";\nimport {\n\treadWsEventStreamText,\n\treadWsEventTimestamp,\n\treadWsEventToolCallId,\n\treadWsEventToolName,\n} from \"./ws-event-payloads.js\";\n\n/** @internal */\nexport const REASONING_PREVIEW_MAX_CHARS = 1_024;\n\n/** @internal */\nexport interface CompactTurnSummary {\n\t/** @internal */\n\tassistant: {\n\t\t/** @internal */\n\t\ttext: string;\n\t\t/** @internal */\n\t\tthinking: string;\n\t\t/** @internal */\n\t\tlastUpdatedAt: string | null;\n\t};\n\t/** @internal */\n\tcurrentTool: Pick<\n\t\tPrimaryPathToolCallSnapshot,\n\t\t\"toolCallId\" | \"toolName\" | \"status\" | \"isError\"\n\t> | null;\n\t/** @internal */\n\tusage: UsageSnapshot | null;\n\t/** @internal */\n\ttoolCallCount: number;\n\t/** @internal */\n\ttraceItemCount: number;\n\t/** The last persisted event incorporated into this projection. @internal */\n\tthroughEventSequence: number;\n\t/** @internal */\n\tlastTraceKind: \"thinking\" | \"tool_call\" | \"operational_event\" | null;\n}\n\n/** Initial-page state. It never contains trace items, tool arguments or results. @internal */\nexport interface CompactActiveTurnSnapshot\n\textends CompactTurnSummary,\n\t\tPick<\n\t\t\tPrimaryPathActiveTurnSnapshot,\n\t\t\t\"turnRecordId\" | \"turnId\" | \"turnType\" | \"pathType\" | \"startedAt\"\n\t\t> {\n\t/** @internal */\n\tsummaryPending: boolean;\n}\n\n/** @internal */\nexport function emptyCompactTurnSummary(): CompactTurnSummary {\n\treturn {\n\t\tassistant: { text: \"\", thinking: \"\", lastUpdatedAt: null },\n\t\tcurrentTool: null,\n\t\tusage: null,\n\t\ttoolCallCount: 0,\n\t\ttraceItemCount: 0,\n\t\tthroughEventSequence: 0,\n\t\tlastTraceKind: null,\n\t};\n}\n\n/** Retain paragraph context; wrapping and blank-line removal belong to the preview viewport. @internal */\nexport function reasoningPreviewTail(text: string): string {\n\tconst normalized = text.replace(/\\r\\n?/g, \"\\n\");\n\tconst lines = normalized.split(\"\\n\").filter((line) => line.trim() !== \"\");\n\tconst separator = /\\n[^\\S\\n]*$/.test(normalized) ? \"\\n\" : \"\";\n\treturn (lines.join(\"\\n\") + separator).slice(-REASONING_PREVIEW_MAX_CHARS);\n}\n\n/** @internal */\nexport function applyEventToCompactTurnSummary(\n\tprevious: CompactTurnSummary,\n\tevent: {\n\t\t/** @internal */\n\t\teventType: string;\n\t\t/** @internal */\n\t\tdata: Record<string, unknown>;\n\t\t/** @internal */\n\t\tcreatedAt: string;\n\t\t/** @internal */\n\t\teventSequence: number;\n\t},\n): CompactTurnSummary {\n\tif (event.eventSequence <= previous.throughEventSequence) return previous;\n\tconst next = {\n\t\t...previous,\n\t\tassistant: { ...previous.assistant },\n\t\tthroughEventSequence: event.eventSequence,\n\t};\n\tconst { eventType, data } = event;\n\tif (eventType === \"pi.stream.delta\") {\n\t\tconst text = readWsEventStreamText(data);\n\t\tconst key = data.streamType === \"thinking\" ? \"thinking\" : \"text\";\n\t\tnext.assistant[key] = reasoningPreviewTail(next.assistant[key] + text);\n\t\tif (text) next.assistant.lastUpdatedAt = readWsEventTimestamp(data, event.createdAt);\n\t\tif (key === \"thinking\" && text) {\n\t\t\tif (next.lastTraceKind !== \"thinking\") next.traceItemCount++;\n\t\t\tnext.lastTraceKind = \"thinking\";\n\t\t}\n\t} else if (eventType === \"pi.tool.call\" || eventType === \"pi.tool.result\") {\n\t\tconst isResult = eventType === \"pi.tool.result\";\n\t\tconst toolCallId = (readWsEventToolCallId(data) ?? `tool-${event.eventSequence}`).slice(0, 256);\n\t\tif (!isResult) {\n\t\t\tnext.toolCallCount++;\n\t\t\tnext.traceItemCount++;\n\t\t\tnext.lastTraceKind = \"tool_call\";\n\t\t}\n\t\tif (!isResult || !next.currentTool || next.currentTool.toolCallId === toolCallId) {\n\t\t\tnext.currentTool = {\n\t\t\t\ttoolCallId: toolCallId.slice(0, 256),\n\t\t\t\ttoolName: readWsEventToolName(data).slice(0, 256),\n\t\t\t\tstatus: isResult ? \"completed\" : \"running\",\n\t\t\t\tisError: data.isError === true,\n\t\t\t};\n\t\t}\n\t} else if (eventType === \"pi.usage\") {\n\t\tnext.usage = mergeUsageSnapshots(next.usage, normalizeUsageSnapshot(data));\n\t} else if (\n\t\t[\n\t\t\t\"pi.error\",\n\t\t\t\"pi.retry.start\",\n\t\t\t\"pi.retry.end\",\n\t\t\t\"pi.compaction.start\",\n\t\t\t\"pi.compaction.end\",\n\t\t].includes(eventType)\n\t) {\n\t\tnext.traceItemCount++;\n\t\tnext.lastTraceKind = \"operational_event\";\n\t}\n\treturn next;\n}\n","import { isUnknownRecord } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\n\n// Wire shape only; the catalog validates manifests and hosts check supported versions.\nconst recordSchema = v.custom<Record<string, unknown>>(isUnknownRecord);\nconst versionSchema = v.custom<number>((value) => typeof value === \"number\");\n\n/** @internal */\nexport const leafOutcomeRendererDescriptorSchema = v.pipe(\n\trecordSchema,\n\tv.object({\n\t\t/** @internal */\n\t\tok: v.literal(true),\n\t\t/** @internal */\n\t\trendererId: v.string(),\n\t\t/** @internal */\n\t\tkind: v.literal(\"custom_element\"),\n\t\t/** @internal */\n\t\ttagName: v.string(),\n\t\t/** @internal */\n\t\tmodulePath: v.string(),\n\t\t/** @internal */\n\t\trendererApiVersion: versionSchema,\n\t\t/** @internal */\n\t\textensionManifestId: v.string(),\n\t\t/** @internal */\n\t\tmoduleUrl: v.string(),\n\t}),\n);\n/** @internal */\nexport type LeafOutcomeRendererDescriptor = v.InferOutput<\n\ttypeof leafOutcomeRendererDescriptorSchema\n>;\n\n/** @internal */\nexport const leafOutcomeRendererFailureSchema = v.pipe(\n\trecordSchema,\n\tv.object({\n\t\t/** @internal */\n\t\tok: v.literal(false),\n\t\t/** @internal */\n\t\trendererId: v.string(),\n\t\t/** @internal */\n\t\tcode: v.string(),\n\t\t/** @internal */\n\t\tmessage: v.string(),\n\t}),\n);\n/** @internal */\nexport type LeafOutcomeRendererFailure = v.InferOutput<typeof leafOutcomeRendererFailureSchema>;\n\n/** @internal */\nexport const browserUiExtensionDescriptorSchema = v.pipe(\n\trecordSchema,\n\tv.object({\n\t\t/** @internal */\n\t\textensionManifestId: v.string(),\n\t\t/** @internal */\n\t\tmodulePath: v.string(),\n\t\t/** @internal */\n\t\tmoduleUrl: v.string(),\n\t\t/** @internal */\n\t\tbrowserApiVersion: versionSchema,\n\t}),\n);\n/** @internal */\nexport type BrowserUiExtensionDescriptor = v.InferOutput<typeof browserUiExtensionDescriptorSchema>;\n","import { isUnknownRecord as isRecord } from \"@leitwerk-dev/domain\";\nimport type { FutureExecutionOverviewItem, FutureExecutionSummary } from \"./http-contracts.js\";\n\n// Best-effort extraction of an operator-facing prompt/command from launch params\n// for compact overview and detail read models. Process launchers use several\n// established field names; keep this priority list shared so server and browser\n// projections cannot drift.\n/** @internal */\nexport const INITIAL_PROMPT_FIELD_PRIORITY = [\n\t\"initialPrompt\",\n\t\"prompt\",\n\t\"taskPrompt\",\n\t\"userPrompt\",\n\t\"instructions\",\n\t\"instruction\",\n\t\"initialCommand\",\n\t\"command\",\n\t\"query\",\n\t\"message\",\n\t\"requestedChange\",\n\t\"request\",\n\t\"description\",\n] as const;\n\nfunction normalizePromptValue(value: string): string | null {\n\tconst normalized = value.replace(/\\s+/g, \" \").trim();\n\treturn normalized.length > 0 ? normalized : null;\n}\n\n/** @internal */\nexport function truncatePromptPreview(\n\tvalue: string | null | undefined,\n\tmaxLength = 180,\n): string | null {\n\tconst normalized = typeof value === \"string\" ? normalizePromptValue(value) : null;\n\treturn normalized && normalized.length > maxLength\n\t\t? `${normalized.slice(0, maxLength).trimEnd()}…`\n\t\t: normalized;\n}\n\nfunction readStringField(record: Record<string, unknown>, fieldName: string): string | null {\n\tconst exact = record[fieldName];\n\tif (typeof exact === \"string\") {\n\t\treturn exact.trim() ? exact : null;\n\t}\n\n\tconst normalizedFieldName = fieldName.toLowerCase();\n\tfor (const [key, value] of Object.entries(record)) {\n\t\tif (key.toLowerCase() !== normalizedFieldName || typeof value !== \"string\") {\n\t\t\tcontinue;\n\t\t}\n\t\treturn value.trim() ? value : null;\n\t}\n\n\treturn null;\n}\n\n/** @internal */\nexport function extractInitialPromptFromValue(value: unknown): string | null {\n\tif (!isRecord(value)) {\n\t\treturn null;\n\t}\n\n\tfor (const fieldName of INITIAL_PROMPT_FIELD_PRIORITY) {\n\t\tconst prompt = readStringField(value, fieldName);\n\t\tif (prompt) {\n\t\t\treturn prompt;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/** @internal */\nexport function extractInitialPromptFromParamsJson(\n\tparamsJson: string | null | undefined,\n): string | null {\n\tif (!paramsJson) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\treturn extractInitialPromptFromValue(JSON.parse(paramsJson));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** @internal */\nexport function extractInitialPromptPreviewFromParamsJson(\n\tparamsJson: string | null | undefined,\n\tmaxLength = 180,\n): string | null {\n\treturn truncatePromptPreview(extractInitialPromptFromParamsJson(paramsJson), maxLength);\n}\n\n/** @internal */\nexport function projectFutureExecutionOverview(\n\tsummary: FutureExecutionSummary,\n): FutureExecutionOverviewItem {\n\tconst common = {\n\t\tid: summary.id,\n\t\tscheduleKind: summary.scheduleKind,\n\t\tprocessId: summary.processId,\n\t\tnextRunAt: summary.nextRunAt,\n\t\tcronExpression: summary.cronExpression,\n\t\ttitle: summary.title,\n\t\tstatus: summary.status ?? \"scheduled\",\n\t\tblockedReason: summary.blockedReason ?? null,\n\t\tinitialPromptPreview:\n\t\t\tsummary.kind === \"launch\"\n\t\t\t\t? truncatePromptPreview(extractInitialPromptFromValue(summary.launcherInput))\n\t\t\t\t: null,\n\t};\n\treturn summary.kind === \"action\"\n\t\t? {\n\t\t\t\t...common,\n\t\t\t\tkind: \"action\",\n\t\t\t\tinstanceId: summary.instanceId,\n\t\t\t\tactionId: summary.actionId,\n\t\t\t\tactionLabel: summary.actionLabel,\n\t\t\t}\n\t\t: {\n\t\t\t\t...common,\n\t\t\t\tkind: \"launch\",\n\t\t\t\tinstanceId: null,\n\t\t\t\tlauncherId: summary.launcherId,\n\t\t\t\tlauncherLabel: summary.launcherLabel,\n\t\t\t};\n}\n","import {\n\ttype ProcessEvent,\n\treadFiniteNumber as readNumber,\n\treadNonBlankString as readString,\n} from \"@leitwerk-dev/domain\";\nimport type { TurnTraceSnapshot, TurnTraceToolCallSnapshot } from \"./http-contracts.js\";\nimport { extractPiSessionMessageText } from \"./pi-session-message.js\";\nimport type {\n\tPrimaryPathActiveTurnSnapshot,\n\tPrimaryPathOperationalTraceItemSnapshot,\n\tPrimaryPathStreamingAssistantSnapshot,\n\tPrimaryPathToolCallSnapshot,\n\tPrimaryPathTraceItemSnapshot,\n} from \"./primary-path-snapshot.js\";\nimport { compareTimestampStrings } from \"./timestamp-ordering.js\";\nimport { isToolResultTruncated } from \"./tool-result-truncation.js\";\nimport {\n\tcloneUsageSnapshot,\n\tmergeUsageSnapshots,\n\tnormalizeUsageSnapshot,\n\ttype UsageSnapshot,\n} from \"./usage-snapshot.js\";\nimport {\n\tasWsEventPayloadRecord,\n\treadWsEventNonEmptyString,\n\treadWsEventStreamText,\n\treadWsEventTimestamp,\n\treadWsEventToolArguments,\n\treadWsEventToolCallId,\n\treadWsEventToolName,\n\tresolveWsEventToolCallId,\n\ttype WsEventPayloadRecord,\n} from \"./ws-event-payloads.js\";\n\ninterface ProjectionToolCall extends PrimaryPathToolCallSnapshot {\n\trestoredResult?: Pick<TurnTraceToolCallSnapshot, \"resultText\" | \"truncated\">;\n}\n\ninterface LiveTurnProjectionState {\n\tassistant: PrimaryPathStreamingAssistantSnapshot;\n\ttraceItems: PrimaryPathTraceItemSnapshot[];\n\tusage: UsageSnapshot | null;\n\ttoolCallsById: Map<string, ProjectionToolCall>;\n\tnextFallbackOrdinal: number;\n}\n\n/** @internal */\nexport interface LiveTurnProjectionEvent {\n\t/** @internal */\n\teventType: string;\n\t/** @internal */\n\tdata: WsEventPayloadRecord;\n\t/** @internal */\n\tfallbackTimestamp: string;\n}\n\n/** @internal */\nexport type LiveTurnSnapshot = Pick<\n\tPrimaryPathActiveTurnSnapshot,\n\t\"assistant\" | \"toolCalls\" | \"traceItems\" | \"usage\"\n>;\n\n/** Projection of events already scoped and ordered by the caller. @internal */\nexport interface TurnTraceProjection {\n\t/** Canonicalize and incorporate one event. Transport deduplication belongs to the caller. @internal */\n\tapply(event: LiveTurnProjectionEvent): AppliedLiveTurnProjectionEvent;\n\t/** Present retained content, preserving the restored prompt unless one is supplied. @internal */\n\tsnapshot(piInput?: TurnTraceSnapshot[\"piInput\"]): TurnTraceSnapshot;\n}\n\n/** Event-backed projection retaining original tool results. @internal */\nexport interface LiveTurnProjection extends TurnTraceProjection {\n\t/** Read the recorded result values as well as the projected activity. @internal */\n\trawSnapshot(): LiveTurnSnapshot;\n}\n\n/** @internal */\nexport interface AppliedLiveTurnProjectionEvent {\n\t/** @internal */\n\tcanonicalData: WsEventPayloadRecord;\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttoolCallId: string | null;\n\t/** @internal */\n\ttoolName: string | null;\n\t/** Aggregate usage without copying the full activity history. @internal */\n\tusage: UsageSnapshot | null;\n}\n\n/** @internal */\nexport const PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES = [\n\t\"pi.error\",\n\t\"pi.retry.start\",\n\t\"pi.retry.end\",\n\t\"pi.compaction.start\",\n\t\"pi.compaction.end\",\n] as const;\n\nfunction cloneToolCall(toolCall: ProjectionToolCall): ProjectionToolCall {\n\treturn {\n\t\t...toolCall,\n\t\t...(toolCall.arguments ? { arguments: { ...toolCall.arguments } } : {}),\n\t};\n}\n\nfunction formatReason(value: unknown): string | null {\n\tconst reason = readString(value);\n\treturn reason ? reason.replace(/[_-]+/g, \" \") : null;\n}\n\nfunction firstMessage(data: WsEventPayloadRecord, keys: readonly string[]): string | null {\n\tfor (const key of keys) {\n\t\tconst value = readString(data[key]);\n\t\tif (value) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction retryStartFallbackMessage(data: WsEventPayloadRecord): string {\n\tconst attempt = readNumber(data.attempt);\n\tconst maxAttempts = readNumber(data.maxAttempts);\n\tconst delayMs = readNumber(data.delayMs);\n\tconst attemptLabel = attempt !== null && maxAttempts !== null ? ` ${attempt}/${maxAttempts}` : \"\";\n\tconst delayLabel = delayMs !== null && delayMs > 0 ? ` in ${delayMs}ms` : \"\";\n\treturn `Retry${attemptLabel} scheduled${delayLabel}.`;\n}\n\nfunction retryEndFallbackMessage(data: WsEventPayloadRecord): string {\n\tconst attempt = readNumber(data.attempt);\n\tif (data.success === true) {\n\t\treturn attempt !== null\n\t\t\t? `Retry sequence succeeded after ${attempt} ${attempt === 1 ? \"retry\" : \"retries\"}.`\n\t\t\t: \"Retry sequence succeeded.\";\n\t}\n\treturn attempt !== null\n\t\t? `Retry sequence ended after ${attempt} ${attempt === 1 ? \"retry\" : \"retries\"}.`\n\t\t: \"Retry sequence ended.\";\n}\n\n/** @internal */\nexport function buildPrimaryPathOperationalTraceItem(input: {\n\t/** @internal */\n\teventType: string;\n\t/** @internal */\n\tdata: WsEventPayloadRecord;\n\t/** @internal */\n\tfallbackTimestamp: string;\n}): PrimaryPathOperationalTraceItemSnapshot | null {\n\tlet presentation: Pick<PrimaryPathOperationalTraceItemSnapshot, \"severity\" | \"title\" | \"message\">;\n\tif (input.eventType === \"pi.error\") {\n\t\tpresentation = {\n\t\t\tseverity: \"error\",\n\t\t\ttitle: \"Pi request failed\",\n\t\t\tmessage:\n\t\t\t\tfirstMessage(input.data, [\"message\", \"errorMessage\", \"finalError\"]) ??\n\t\t\t\t\"Pi reported an error.\",\n\t\t};\n\t} else if (input.eventType === \"pi.retry.start\") {\n\t\tpresentation = {\n\t\t\tseverity: \"warning\",\n\t\t\ttitle: \"Retry scheduled\",\n\t\t\tmessage:\n\t\t\t\tfirstMessage(input.data, [\"message\", \"errorMessage\"]) ??\n\t\t\t\tretryStartFallbackMessage(input.data),\n\t\t};\n\t} else if (input.eventType === \"pi.retry.end\") {\n\t\tconst success = input.data.success === true;\n\t\tpresentation = {\n\t\t\tseverity: success ? \"success\" : \"error\",\n\t\t\ttitle: success ? \"Retry succeeded\" : \"Retry exhausted\",\n\t\t\tmessage:\n\t\t\t\tfirstMessage(input.data, [\"message\", \"finalError\", \"errorMessage\"]) ??\n\t\t\t\tretryEndFallbackMessage(input.data),\n\t\t};\n\t} else if (input.eventType === \"pi.compaction.start\") {\n\t\tconst reason = formatReason(input.data.reason);\n\t\tpresentation = {\n\t\t\tseverity: \"info\",\n\t\t\ttitle: \"Context compaction started\",\n\t\t\tmessage: reason\n\t\t\t\t? `Pi started compacting context (${reason}).`\n\t\t\t\t: \"Pi started compacting context.\",\n\t\t};\n\t} else if (input.eventType === \"pi.compaction.end\") {\n\t\tconst reason = formatReason(input.data.reason);\n\t\tconst errorMessage = firstMessage(input.data, [\"errorMessage\", \"message\"]);\n\t\tconst aborted = input.data.aborted === true;\n\t\tpresentation = {\n\t\t\tseverity: errorMessage ? \"error\" : aborted ? \"warning\" : \"success\",\n\t\t\ttitle: errorMessage\n\t\t\t\t? \"Context compaction failed\"\n\t\t\t\t: aborted\n\t\t\t\t\t? \"Context compaction cancelled\"\n\t\t\t\t\t: \"Context compacted\",\n\t\t\tmessage:\n\t\t\t\terrorMessage ??\n\t\t\t\t(aborted\n\t\t\t\t\t? \"Context compaction was cancelled.\"\n\t\t\t\t\t: `Pi compacted context${reason ? ` (${reason})` : \"\"}.${input.data.willRetry === true ? \" Pi will continue automatically.\" : \"\"}`),\n\t\t};\n\t} else {\n\t\treturn null;\n\t}\n\treturn {\n\t\tkind: \"operational_event\",\n\t\teventType: input.eventType,\n\t\ttimestamp: readWsEventTimestamp(input.data, input.fallbackTimestamp),\n\t\t...presentation,\n\t};\n}\n\nfunction canonicalizeToolCallId(input: {\n\tprojection: LiveTurnProjectionState;\n\tdata: WsEventPayloadRecord;\n\ttimestamp: string;\n\ttoolName: string;\n\tpreferOpenCall: boolean;\n}): string {\n\tconst explicitToolCallId = readWsEventToolCallId(input.data);\n\tif (explicitToolCallId) return explicitToolCallId;\n\tif (input.preferOpenCall) {\n\t\tconst openToolCall = [...input.projection.toolCallsById.values()]\n\t\t\t.reverse()\n\t\t\t.find((tool) => tool.status === \"running\" && tool.toolName === input.toolName);\n\t\tif (openToolCall) return openToolCall.toolCallId;\n\t}\n\t// Replayed canonical IDs and restored snapshots do not retain the old ordinal.\n\t// Reserve their identities by checking the index, without interpreting ID strings.\n\tlet toolCallId: string;\n\tdo {\n\t\ttoolCallId = resolveWsEventToolCallId(input.data, {\n\t\t\ttimestamp: input.timestamp,\n\t\t\ttoolName: input.toolName,\n\t\t\tordinal: input.projection.nextFallbackOrdinal++,\n\t\t});\n\t} while (input.projection.toolCallsById.has(toolCallId));\n\treturn toolCallId;\n}\n\nfunction appendThinkingTraceText(projection: LiveTurnProjectionState, text: string): void {\n\tif (text.length === 0) {\n\t\treturn;\n\t}\n\tconst lastTraceItem = projection.traceItems.at(-1);\n\tif (lastTraceItem?.kind === \"thinking\") {\n\t\tlastTraceItem.text += text;\n\t\treturn;\n\t}\n\tprojection.traceItems.push({\n\t\tkind: \"thinking\",\n\t\ttext,\n\t});\n}\n\nfunction ensureToolTraceItem(projection: LiveTurnProjectionState, toolCallId: string): void {\n\tif (\n\t\tprojection.traceItems.some(\n\t\t\t(traceItem) => traceItem.kind === \"tool_call\" && traceItem.toolCallId === toolCallId,\n\t\t)\n\t) {\n\t\treturn;\n\t}\n\tprojection.traceItems.push({\n\t\tkind: \"tool_call\",\n\t\ttoolCallId,\n\t});\n}\n\nfunction createProjectionState(): LiveTurnProjectionState {\n\treturn {\n\t\tassistant: {\n\t\t\ttext: \"\",\n\t\t\tthinking: \"\",\n\t\t\tlastUpdatedAt: null,\n\t\t},\n\t\ttraceItems: [],\n\t\tusage: null,\n\t\ttoolCallsById: new Map<string, ProjectionToolCall>(),\n\t\tnextFallbackOrdinal: 1,\n\t};\n}\n\nfunction snapshotProjection<T>(\n\tprojection: LiveTurnProjectionState,\n\tpresentTool: (tool: ProjectionToolCall) => T,\n) {\n\treturn {\n\t\tassistant: { ...projection.assistant },\n\t\ttraceItems: projection.traceItems.map((item) => ({ ...item })),\n\t\tusage: cloneUsageSnapshot(projection.usage),\n\t\ttoolCalls: Array.from(projection.toolCallsById.values(), (tool) =>\n\t\t\tpresentTool(cloneToolCall(tool)),\n\t\t),\n\t};\n}\n\nfunction applyPiEventToLiveTurnProjection(\n\tprojection: LiveTurnProjectionState,\n\tinput: LiveTurnProjectionEvent,\n): AppliedLiveTurnProjectionEvent {\n\tlet timestamp = readWsEventTimestamp(input.data, input.fallbackTimestamp);\n\tlet canonicalData = input.data;\n\tlet toolCallId: string | null = null;\n\tlet toolName: string | null = null;\n\tif (input.eventType === \"pi.stream.delta\") {\n\t\tconst text = readWsEventStreamText(input.data);\n\t\tif (text) {\n\t\t\tif (readWsEventNonEmptyString(input.data.streamType) === \"thinking\") {\n\t\t\t\tprojection.assistant.thinking += text;\n\t\t\t\tappendThinkingTraceText(projection, text);\n\t\t\t} else {\n\t\t\t\tprojection.assistant.text += text;\n\t\t\t}\n\t\t\tprojection.assistant.lastUpdatedAt = timestamp;\n\t\t}\n\t} else if (input.eventType === \"pi.tool.call\" || input.eventType === \"pi.tool.result\") {\n\t\tconst isResult = input.eventType === \"pi.tool.result\";\n\t\ttoolName = readWsEventToolName(input.data);\n\t\ttoolCallId = canonicalizeToolCallId({\n\t\t\tprojection,\n\t\t\tdata: input.data,\n\t\t\ttimestamp,\n\t\t\ttoolName,\n\t\t\tpreferOpenCall: isResult,\n\t\t});\n\t\tcanonicalData =\n\t\t\treadWsEventToolCallId(input.data) === toolCallId ? input.data : { ...input.data, toolCallId };\n\t\tconst existingToolCall = projection.toolCallsById.get(toolCallId);\n\t\tconst toolCall: ProjectionToolCall = existingToolCall ?? {\n\t\t\ttoolCallId,\n\t\t\ttoolName,\n\t\t\tstatus: \"running\",\n\t\t\tstartedAt: timestamp,\n\t\t\tcompletedAt: null,\n\t\t\targuments: isResult ? null : readWsEventToolArguments(canonicalData),\n\t\t\tresult: null,\n\t\t\tisError: false,\n\t\t};\n\t\tif (!existingToolCall) projection.toolCallsById.set(toolCallId, toolCall);\n\t\tif (isResult) {\n\t\t\ttoolCall.status = \"completed\";\n\t\t\ttoolCall.completedAt = timestamp;\n\t\t\ttoolCall.result = canonicalData.result ?? null;\n\t\t\tdelete toolCall.restoredResult;\n\t\t\ttoolCall.isError = canonicalData.isError === true;\n\t\t}\n\t\tensureToolTraceItem(projection, toolCallId);\n\t} else if (input.eventType === \"pi.usage\") {\n\t\tprojection.usage = mergeUsageSnapshots(projection.usage, normalizeUsageSnapshot(input.data));\n\t} else {\n\t\tconst operationalTraceItem = buildPrimaryPathOperationalTraceItem(input);\n\t\tif (operationalTraceItem) {\n\t\t\tprojection.traceItems.push(operationalTraceItem);\n\t\t\ttimestamp = operationalTraceItem.timestamp;\n\t\t}\n\t}\n\n\treturn {\n\t\tcanonicalData,\n\t\ttimestamp,\n\t\ttoolCallId,\n\t\ttoolName,\n\t\tusage: cloneUsageSnapshot(projection.usage),\n\t};\n}\n\nfunction compareProcessEventsChronologically(left: ProcessEvent, right: ProcessEvent): number {\n\tif (left.eventSequence !== undefined && right.eventSequence !== undefined) {\n\t\treturn left.eventSequence - right.eventSequence;\n\t}\n\tconst leftTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(left.data), left.createdAt);\n\tconst rightTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(right.data), right.createdAt);\n\tconst timestampComparison = compareTimestampStrings(leftTimestamp, rightTimestamp);\n\tif (timestampComparison !== 0) {\n\t\treturn timestampComparison;\n\t}\n\tconst createdAtComparison = compareTimestampStrings(left.createdAt, right.createdAt);\n\tif (createdAtComparison !== 0) {\n\t\treturn createdAtComparison;\n\t}\n\treturn left.id.localeCompare(right.id);\n}\n\nfunction snapshotToolTrace({\n\tresult,\n\trestoredResult,\n\t...tool\n}: ProjectionToolCall): TurnTraceToolCallSnapshot {\n\tif (restoredResult) return { ...tool, ...restoredResult };\n\tconst record = result && typeof result === \"object\" ? (result as Record<string, unknown>) : null;\n\tconst resultText =\n\t\tresult == null\n\t\t\t? null\n\t\t\t: typeof result === \"string\"\n\t\t\t\t? result\n\t\t\t\t: record && \"content\" in record\n\t\t\t\t\t? extractPiSessionMessageText(record.content)\n\t\t\t\t\t: JSON.stringify(result, null, 2);\n\treturn {\n\t\t...tool,\n\t\tresultText,\n\t\ttruncated: isToolResultTruncated({\n\t\t\tresultText,\n\t\t\tresultDetails: record?.details,\n\t\t\tresultValue: result,\n\t\t}),\n\t};\n}\n\nfunction traceProjection(\n\tstate: LiveTurnProjectionState,\n\tretainedPiInput: TurnTraceSnapshot[\"piInput\"] = null,\n): TurnTraceProjection {\n\treturn {\n\t\tapply: (event) => applyPiEventToLiveTurnProjection(state, event),\n\t\tsnapshot: (piInput = retainedPiInput) => ({\n\t\t\t...snapshotProjection(state, snapshotToolTrace),\n\t\t\tpiInput,\n\t\t}),\n\t};\n}\n\n/** Start empty, or replay recorded events in their persisted order. @internal */\nexport function createLiveTurnProjection(events: readonly ProcessEvent[] = []): LiveTurnProjection {\n\tconst state = createProjectionState();\n\tfor (const event of [...events].sort(compareProcessEventsChronologically)) {\n\t\tapplyPiEventToLiveTurnProjection(state, {\n\t\t\teventType: event.eventType,\n\t\t\tdata: asWsEventPayloadRecord(event.data),\n\t\t\tfallbackTimestamp: event.createdAt,\n\t\t});\n\t}\n\treturn {\n\t\t...traceProjection(state),\n\t\trawSnapshot: () =>\n\t\t\tsnapshotProjection(state, ({ restoredResult: _restoredResult, ...tool }) => tool),\n\t};\n}\n\n/**\n * Resume presentation from a Trace, including correlation for its running tools.\n * A Trace retains displayed results, not the original structured tool results.\n * @internal\n */\nexport function restoreTurnTraceProjection(trace: TurnTraceSnapshot): TurnTraceProjection {\n\tconst state = createProjectionState();\n\tstate.assistant = { ...trace.assistant };\n\tstate.traceItems = trace.traceItems.map((item) => ({ ...item }));\n\tstate.usage = cloneUsageSnapshot(trace.usage);\n\tfor (const { resultText, truncated, ...tool } of trace.toolCalls) {\n\t\tconst toolCall = cloneToolCall({\n\t\t\t...tool,\n\t\t\tresult: null,\n\t\t\trestoredResult: { resultText, truncated },\n\t\t});\n\t\tstate.toolCallsById.set(toolCall.toolCallId, toolCall);\n\t}\n\treturn traceProjection(state, trace.piInput);\n}\n","/** @internal */\nexport interface PiSessionMessageLike {\n\t/** @internal */\n\trole?: unknown;\n\t/** @internal */\n\tcontent?: unknown;\n\t/** @internal */\n\tdetails?: unknown;\n\t/** @internal */\n\ttoolCallId?: unknown;\n\t/** @internal */\n\ttoolName?: unknown;\n\t/** @internal */\n\tisError?: unknown;\n\t/** @internal */\n\tusage?: unknown;\n}\n\n/** @internal */\nexport interface PiSessionMessageEntryLike {\n\t/** @internal */\n\ttype?: unknown;\n\t/** @internal */\n\tmessage?: unknown;\n}\n\n/** @internal */\nexport function isPiSessionMessageEntryType<\n\tTEntry extends {\n\t\t/** @internal */\n\t\ttype?: unknown;\n\t},\n>(entry: TEntry | undefined): entry is TEntry & { type: \"message\" } {\n\treturn entry?.type === \"message\";\n}\n\n/** @internal */\nexport function isPiSessionMessageRecord(value: unknown): value is PiSessionMessageLike {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** @internal */\nexport function isPiSessionMessageEntryWithRecord<TEntry extends PiSessionMessageEntryLike>(\n\tentry: TEntry | undefined,\n): entry is TEntry & { type: \"message\"; message: NonNullable<TEntry[\"message\"]> } {\n\treturn isPiSessionMessageEntryType(entry) && isPiSessionMessageRecord(entry.message);\n}\n\n/** @internal */\nexport function extractPiSessionMessageText(content: unknown): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\tif (!Array.isArray(content)) {\n\t\treturn \"\";\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (typeof block !== \"object\" || block === null || Array.isArray(block)) {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\tconst record = block as { type?: unknown; text?: unknown };\n\t\t\treturn record.type === \"text\" && typeof record.text === \"string\" ? record.text : \"\";\n\t\t})\n\t\t.join(\"\");\n}\n","/** @internal */\nexport function compareTimestampStrings(left: string, right: string): number {\n\tconst leftMs = Date.parse(left);\n\tconst rightMs = Date.parse(right);\n\tif (Number.isFinite(leftMs) && Number.isFinite(rightMs)) {\n\t\treturn leftMs - rightMs;\n\t}\n\treturn left.localeCompare(right);\n}\n\n/** @internal */\nexport function happenedOnOrAfterStart(entryTimestamp: string, startedAt: string | null): boolean {\n\tif (!startedAt) {\n\t\treturn true;\n\t}\n\treturn compareTimestampStrings(entryTimestamp, startedAt) >= 0;\n}\n","import { asUnknownRecord } from \"@leitwerk-dev/domain\";\n\nconst TOOL_TRUNCATION_BOOLEAN_KEYS = [\n\t\"truncated\",\n\t\"isTruncated\",\n\t\"wasTruncated\",\n\t\"outputTruncated\",\n\t\"resultTruncated\",\n] as const;\nconst TOOL_TRUNCATION_TEXT_MARKERS = [\n\t\"output truncated\",\n\t\"result truncated\",\n\t\"response was too big\",\n\t\"too large to display\",\n\t\"truncated after\",\n\t\"truncated to last\",\n\t\"truncated since\",\n] as const;\n\nfunction readTruncationPayload(value: unknown): unknown {\n\tconst record = asUnknownRecord(value);\n\tif (!record) {\n\t\treturn null;\n\t}\n\tif (\"truncation\" in record) {\n\t\treturn record.truncation;\n\t}\n\tfor (const key of TOOL_TRUNCATION_BOOLEAN_KEYS) {\n\t\tif (key in record) {\n\t\t\treturn record[key];\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction isExplicitFalseTruncationString(value: string): boolean {\n\tconst normalized = value.trim().toLowerCase();\n\treturn (\n\t\tnormalized === \"\" ||\n\t\tnormalized === \"false\" ||\n\t\tnormalized === \"none\" ||\n\t\tnormalized === \"null\" ||\n\t\tnormalized === \"no\" ||\n\t\tnormalized === \"0\"\n\t);\n}\n\nfunction isTruthyTruncationValue(value: unknown): boolean {\n\tif (value === null || value === undefined) {\n\t\treturn false;\n\t}\n\tif (typeof value === \"boolean\") {\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\treturn Number.isFinite(value) && value > 0;\n\t}\n\tif (typeof value === \"string\") {\n\t\treturn !isExplicitFalseTruncationString(value);\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.length > 0;\n\t}\n\tconst record = asUnknownRecord(value);\n\tif (!record) {\n\t\treturn true;\n\t}\n\tfor (const key of TOOL_TRUNCATION_BOOLEAN_KEYS) {\n\t\tif (record[key] === true) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn Object.keys(record).some((key) => {\n\t\tif (\n\t\t\tTOOL_TRUNCATION_BOOLEAN_KEYS.includes(key as (typeof TOOL_TRUNCATION_BOOLEAN_KEYS)[number])\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn isTruthyTruncationValue(record[key]);\n\t});\n}\n\n/** @internal */\nexport function isToolResultTruncated(input: {\n\t/** @internal */\n\tresultText: string | null;\n\t/** @internal */\n\tresultDetails: unknown;\n\t/** @internal */\n\tresultValue: unknown;\n}): boolean {\n\tconst normalizedText = input.resultText?.toLowerCase() ?? \"\";\n\treturn (\n\t\tTOOL_TRUNCATION_TEXT_MARKERS.some((marker) => normalizedText.includes(marker)) ||\n\t\tisTruthyTruncationValue(readTruncationPayload(input.resultDetails)) ||\n\t\tisTruthyTruncationValue(readTruncationPayload(input.resultValue))\n\t);\n}\n","/** @internal */\nexport interface SessionTreeEntryLike {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tparentId: string | null;\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttype: string;\n}\n\n/** @internal */\nexport interface ReadonlyEntryTree<TEntry extends SessionTreeEntryLike> {\n\t/** @internal */\n\tentries: TEntry[];\n\t/** @internal */\n\tleafId: string | null;\n\t/** @internal */\n\tgetEntry(id: string): TEntry | undefined;\n\t/** @internal */\n\tgetChildren(parentId: string): TEntry[];\n\t/** @internal */\n\tgetBranch(fromId?: string | null): TEntry[];\n}\n\n/** @internal */\nexport function createReadonlyEntryTree<TEntry extends SessionTreeEntryLike>(\n\tentries: readonly TEntry[],\n): ReadonlyEntryTree<TEntry> {\n\tconst orderedEntries = [...entries];\n\tconst entriesById = new Map(orderedEntries.map((entry) => [entry.id, entry]));\n\tconst childrenByParentId = new Map<string, TEntry[]>();\n\n\tfor (const entry of orderedEntries) {\n\t\tif (typeof entry.parentId !== \"string\" || entry.parentId.trim() === \"\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst siblings = childrenByParentId.get(entry.parentId) ?? [];\n\t\tsiblings.push(entry);\n\t\tchildrenByParentId.set(entry.parentId, siblings);\n\t}\n\n\tconst leafId = orderedEntries.at(-1)?.id ?? null;\n\n\tconst getEntry = (id: string): TEntry | undefined => entriesById.get(id);\n\tconst getChildren = (parentId: string): TEntry[] =>\n\t\t(childrenByParentId.get(parentId) ?? []).slice();\n\tconst getBranch = (fromId?: string | null): TEntry[] => {\n\t\tconst resolvedFromId = fromId ?? leafId ?? undefined;\n\t\tif (!resolvedFromId) {\n\t\t\treturn [];\n\t\t}\n\t\tconst branch: TEntry[] = [];\n\t\tconst visited = new Set<string>();\n\t\tlet currentEntry = entriesById.get(resolvedFromId);\n\t\twhile (currentEntry) {\n\t\t\tif (visited.has(currentEntry.id)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvisited.add(currentEntry.id);\n\t\t\tbranch.unshift(currentEntry);\n\t\t\tcurrentEntry = currentEntry.parentId ? entriesById.get(currentEntry.parentId) : undefined;\n\t\t}\n\t\treturn branch;\n\t};\n\n\treturn {\n\t\tentries: orderedEntries,\n\t\tleafId,\n\t\tgetEntry,\n\t\tgetChildren,\n\t\tgetBranch,\n\t};\n}\n","import { orderDependencies } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\n\nconst nonEmpty = v.pipe(v.string(), v.minLength(1));\nconst skillId = v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9-]{0,62}$/));\nconst relativePath = v.pipe(\n\tv.string(),\n\tv.check(\n\t\t(value) =>\n\t\t\tvalue.length > 0 &&\n\t\t\t!value.includes(\"\\\\\") &&\n\t\t\t!value.includes(\"\\0\") &&\n\t\t\tvalue\n\t\t\t\t.split(\"/\")\n\t\t\t\t.every((part) => part !== \"\" && part !== \".\" && part !== \"..\" && part !== \".git\"),\n\t),\n);\n\nconst upstreamSchema = v.object({\n\t/** @public */\n\turl: nonEmpty,\n\t/** @public */\n\tcommit: v.pipe(v.string(), v.regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)),\n});\n\nconst entrySchema = v.object({\n\t/** @public */\n\tid: skillId,\n\t/** @public */\n\tdirectory: relativePath,\n\t/** @public */\n\tlabel: nonEmpty,\n\t/** @public */\n\tdescription: nonEmpty,\n\t/** @public */\n\tsourcePath: relativePath,\n\t/** @public */\n\tdependencies: v.array(skillId),\n});\n\n/** Supports the public inferred manifest declaration. @public */\nconst manifestSchema = v.object({\n\t/** @public */\n\tformatVersion: v.literal(1),\n\t/** @public */\n\tupstream: upstreamSchema,\n\t/** @public */\n\tpatchDigest: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/)),\n\t/** @public */\n\tskills: v.pipe(v.array(entrySchema), v.minLength(1)),\n});\n\n/** On-disk contract for an extension's generated skill pack. @public */\nexport type SkillPackManifest = v.InferOutput<typeof manifestSchema>;\n\n/** Provenance retained with an immutable installed skill revision. @internal */\nexport interface SkillRevisionProvenance {\n\t/** @internal */\n\textensionId: string;\n\t/** @internal */\n\tpackageName: string;\n\t/** @internal */\n\tpackageVersion: string;\n\t/** @internal */\n\tupstream: SkillPackManifest[\"upstream\"];\n\t/** @internal */\n\tsourcePath: string;\n\t/** @internal */\n\tpatchDigest: string;\n\t/** @internal */\n\tdependencies: string[];\n}\n\n/** Validates pack-local dependencies as well as the manifest shape. @internal */\nexport function parseSkillPackManifest(input: unknown): SkillPackManifest {\n\tconst manifest = v.parse(manifestSchema, input);\n\tconst byId = new Map(manifest.skills.map((skill) => [skill.id, skill]));\n\tif (byId.size !== manifest.skills.length) throw new Error(\"Duplicate skill ID in skill pack\");\n\tconst directories = new Set(manifest.skills.map((skill) => skill.directory));\n\tif (directories.size !== manifest.skills.length) throw new Error(\"Duplicate skill directory\");\n\torderDependencies(\n\t\tbyId.keys(),\n\t\t(id) => {\n\t\t\tconst entry = byId.get(id);\n\t\t\tif (!entry) throw new Error(`Missing skill pack dependency '${id}'`);\n\t\t\tif (new Set(entry.dependencies).size !== entry.dependencies.length)\n\t\t\t\tthrow new Error(`Duplicate dependencies for skill '${id}'`);\n\t\t\treturn entry.dependencies;\n\t\t},\n\t\t(id) => `Circular skill dependency at '${id}'`,\n\t);\n\treturn manifest;\n}\n","/** @internal */\nexport const STREAMABLE_WORKER_EVENT_TYPES = [\n\t\"pi.stream.delta\",\n\t\"pi.turn.start\",\n\t\"pi.turn.end\",\n\t\"pi.tool.call\",\n\t\"pi.tool.result\",\n\t\"pi.label.changed\",\n\t\"pi.error\",\n\t\"pi.retry.start\",\n\t\"pi.retry.end\",\n\t\"pi.usage\",\n\t\"pi.compaction.start\",\n\t\"pi.compaction.end\",\n] as const;\n\n/** @internal */\nexport type StreamableWorkerEventType = (typeof STREAMABLE_WORKER_EVENT_TYPES)[number];\n\nconst STREAMABLE_EVENT_TYPES = new Set<string>(STREAMABLE_WORKER_EVENT_TYPES);\n\n/** @internal */\nexport function isStreamableEvent(eventType: string): eventType is StreamableWorkerEventType {\n\treturn STREAMABLE_EVENT_TYPES.has(eventType);\n}\n","/** @internal */\nexport interface TextPreview {\n\t/** @internal */\n\ttext: string;\n\t/** @internal */\n\ttruncated: boolean;\n}\n\n/** @internal */\nexport function truncateTextPreview(value: string, maxLength: number): TextPreview {\n\treturn value.length <= maxLength\n\t\t? { text: value, truncated: false }\n\t\t: { text: value.slice(0, maxLength).trimEnd(), truncated: true };\n}\n\n/** @internal */\nexport function buildTrailingLinePreview(\n\tvalue: string,\n\tlineCount: number,\n\tmaxLength: number,\n): TextPreview {\n\tconst lines = value.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n\tif (lines.length === 1 && lines[0] === \"\") return { text: \"\", truncated: false };\n\n\tlet text = lines.slice(-lineCount).join(\"\\n\");\n\tlet truncated = lines.length > lineCount;\n\tif (text.length > maxLength) {\n\t\ttext = text.slice(-maxLength);\n\t\ttruncated = true;\n\t}\n\tif (truncated) {\n\t\tconst previewLines = text.split(\"\\n\");\n\t\tpreviewLines[0] = previewLines[0] ? `… ${previewLines[0]}` : \"…\";\n\t\ttext = previewLines.join(\"\\n\");\n\t}\n\treturn { text, truncated };\n}\n","import type {\n\tProcessTimelineTurnPresentation,\n\tProcessTimelineTurnSummary,\n} from \"./http-contracts.js\";\nimport type { PrimaryPathActiveTurnSnapshot } from \"./primary-path-snapshot.js\";\n\n/** @internal */\nexport function timelinePresentationForTurnType(\n\tturnType: ProcessTimelineTurnSummary[\"turnType\"],\n): ProcessTimelineTurnPresentation {\n\tif (turnType === \"external\") return \"external_trigger\";\n\tif (turnType === \"human\") return \"operator_decision\";\n\treturn turnType === \"automatic\" ? \"automatic_turn\" : \"llm_turn\";\n}\n\n/** @internal */\nexport function buildActiveTimelineTurnSummary(\n\tactiveTurn: Pick<\n\t\tPrimaryPathActiveTurnSnapshot,\n\t\t\"turnRecordId\" | \"turnId\" | \"turnType\" | \"pathType\" | \"startedAt\" | \"assistant\"\n\t>,\n\tinput: {\n\t\t/** @internal */\n\t\tsummary: string;\n\t\t/** @internal */\n\t\toutput: string;\n\t\t/** @internal */\n\t\tactionSource?: ProcessTimelineTurnSummary[\"actionSource\"];\n\t} = { summary: `Current step: ${activeTurn.turnId}`, output: activeTurn.assistant.text.trim() },\n): ProcessTimelineTurnSummary {\n\treturn {\n\t\tid: activeTurn.turnRecordId,\n\t\tturnId: activeTurn.turnId,\n\t\tturnType: activeTurn.turnType,\n\t\tdisplayTurn: activeTurn.turnId,\n\t\toutcome: \"in_progress\",\n\t\tsummary: input.summary,\n\t\toutput: input.output,\n\t\tturnResultMarkdown: \"\",\n\t\tpathType: activeTurn.pathType,\n\t\tcreatedAt: activeTurn.startedAt,\n\t\tpresentation: timelinePresentationForTurnType(activeTurn.turnType),\n\t\tstatus: \"in_progress\",\n\t\tmodelProfileId: null,\n\t\tattemptNumber: 1,\n\t\tparentTurnRecordId: null,\n\t\tstartedAt: activeTurn.startedAt,\n\t\tendedAt: null,\n\t\tactionSource: input.actionSource ?? null,\n\t\tprogress: null,\n\t};\n}\n","import { trimToNull } from \"@leitwerk-dev/domain\";\nimport {\n\textractPiSessionMessageText,\n\tisPiSessionMessageEntryType,\n\tisPiSessionMessageEntryWithRecord,\n} from \"./pi-session-message.js\";\nimport type { ReadonlyEntryTree } from \"./session-entry-tree.js\";\nimport { compareTimestampStrings, happenedOnOrAfterStart } from \"./timestamp-ordering.js\";\n\n/** @internal */\nexport interface ContinuationTreeEntry {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tparentId: string | null;\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttype: string;\n\t/** @internal */\n\tmessage?: {\n\t\t/** @internal */\n\t\trole?: string;\n\t\t/** @internal */\n\t\tcontent?: unknown;\n\t};\n}\n\n/** @internal */\nexport interface ContinuationTurnRecordLike {\n\t/** @internal */\n\tforkPiEntryId?: string | null;\n\t/** @internal */\n\tresultPiEntryId?: string | null;\n\t/** @internal */\n\tstartedAt?: string | null;\n\t/** @internal */\n\tstatus?: string | null;\n}\n\n/** @internal */\nexport interface ContinuationSliceBounds {\n\t/** @internal */\n\tendedAt?: string | null;\n}\n\n/** @internal */\nexport interface TurnContinuationIndex<TEntry extends ContinuationTreeEntry> {\n\t/** @internal */\n\tresolveLeafEntryId(\n\t\tturnRecord: ContinuationTurnRecordLike,\n\t\tbounds?: ContinuationSliceBounds,\n\t): string | null;\n\t/** @internal */\n\tbuildSlice(turnRecord: ContinuationTurnRecordLike, bounds?: ContinuationSliceBounds): TEntry[];\n}\n\nfunction branchContainsAncestor(\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\tentryId: string,\n\tancestorId: string,\n): boolean {\n\tconst visited = new Set<string>();\n\tlet current = entriesById.get(entryId);\n\twhile (current) {\n\t\tif (visited.has(current.id)) {\n\t\t\treturn false;\n\t\t}\n\t\tvisited.add(current.id);\n\t\tif (current.id === ancestorId) {\n\t\t\treturn true;\n\t\t}\n\t\tcurrent = current.parentId ? entriesById.get(current.parentId) : undefined;\n\t}\n\treturn false;\n}\n\nfunction happenedOnOrBeforeEnd(entryTimestamp: string, endedAt: string | null): boolean {\n\tif (!endedAt) {\n\t\treturn true;\n\t}\n\treturn compareTimestampStrings(entryTimestamp, endedAt) <= 0;\n}\n\nfunction isContinuableEntryWithinBounds(\n\tentry: ContinuationTreeEntry | undefined,\n\tstartedAt: string | null,\n\tendedAt: string | null,\n): entry is ContinuationTreeEntry {\n\treturn (\n\t\t(isPiSessionMessageEntryType(entry) || entry?.type === \"compaction\") &&\n\t\thappenedOnOrAfterStart(entry.timestamp, startedAt) &&\n\t\thappenedOnOrBeforeEnd(entry.timestamp, endedAt)\n\t);\n}\n\nfunction isExplicitLeafUsable(\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\tleafId: string,\n\tforkPiEntryId: string | null,\n\tstartedAt: string | null,\n\tendedAt: string | null,\n): boolean {\n\tconst leafEntry = entriesById.get(leafId);\n\tif (!isContinuableEntryWithinBounds(leafEntry, startedAt, endedAt)) {\n\t\treturn false;\n\t}\n\treturn !forkPiEntryId || branchContainsAncestor(entriesById, leafId, forkPiEntryId);\n}\n\nfunction findLatestContinuableEntryIdOnBranch(\n\tentries: readonly ContinuationTreeEntry[],\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\toptions: { startedAt: string | null; endedAt: string | null; ancestorId: string | null },\n): string | null {\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (!isContinuableEntryWithinBounds(entry, options.startedAt, options.endedAt)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (options.ancestorId && !branchContainsAncestor(entriesById, entry.id, options.ancestorId)) {\n\t\t\tcontinue;\n\t\t}\n\t\treturn entry.id;\n\t}\n\treturn null;\n}\n\nfunction resolveTurnContinuationLeafEntryIdFromIndex(\n\tentries: readonly ContinuationTreeEntry[],\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): string | null {\n\tconst startedAt = trimToNull(turnRecord.startedAt);\n\tconst endedAt = trimToNull(bounds.endedAt);\n\tconst forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);\n\tconst explicitLeafId = trimToNull(turnRecord.resultPiEntryId);\n\tif (\n\t\texplicitLeafId &&\n\t\tisExplicitLeafUsable(entriesById, explicitLeafId, forkPiEntryId, startedAt, endedAt)\n\t) {\n\t\tif (turnRecord.status !== \"failed\") {\n\t\t\treturn explicitLeafId;\n\t\t}\n\t\treturn findLatestContinuableEntryIdOnBranch(entries, entriesById, {\n\t\t\tstartedAt,\n\t\t\tendedAt,\n\t\t\tancestorId: explicitLeafId,\n\t\t});\n\t}\n\n\treturn findLatestContinuableEntryIdOnBranch(entries, entriesById, {\n\t\tstartedAt,\n\t\tendedAt,\n\t\tancestorId: forkPiEntryId,\n\t});\n}\n\n/** @internal */\nexport function createTurnContinuationIndex<TEntry extends ContinuationTreeEntry>(\n\tentries: readonly TEntry[],\n): TurnContinuationIndex<TEntry> {\n\tconst entriesById = new Map(entries.map((entry) => [entry.id, entry]));\n\n\tconst resolveLeafEntryId = (\n\t\tturnRecord: ContinuationTurnRecordLike,\n\t\tbounds: ContinuationSliceBounds = {},\n\t): string | null =>\n\t\tresolveTurnContinuationLeafEntryIdFromIndex(entries, entriesById, turnRecord, bounds);\n\n\tconst buildSlice = (\n\t\tturnRecord: ContinuationTurnRecordLike,\n\t\tbounds: ContinuationSliceBounds = {},\n\t): TEntry[] => {\n\t\tconst continuationLeafId = resolveLeafEntryId(turnRecord, bounds);\n\t\tif (!continuationLeafId) {\n\t\t\treturn [];\n\t\t}\n\t\tconst forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);\n\t\tconst reversedSlice: TEntry[] = [];\n\t\tconst visited = new Set<string>();\n\t\tlet current = entriesById.get(continuationLeafId);\n\t\tlet foundFork = forkPiEntryId === null;\n\t\twhile (current && !visited.has(current.id)) {\n\t\t\tvisited.add(current.id);\n\t\t\tif (current.id === forkPiEntryId) {\n\t\t\t\tfoundFork = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treversedSlice.push(current);\n\t\t\tcurrent = current.parentId ? entriesById.get(current.parentId) : undefined;\n\t\t}\n\t\tif (!foundFork) {\n\t\t\treturn [];\n\t\t}\n\t\tconst startedAt = trimToNull(turnRecord.startedAt);\n\t\tconst endedAt = trimToNull(bounds.endedAt);\n\t\treturn reversedSlice\n\t\t\t.reverse()\n\t\t\t.filter(\n\t\t\t\t(entry) =>\n\t\t\t\t\thappenedOnOrAfterStart(entry.timestamp, startedAt) &&\n\t\t\t\t\thappenedOnOrBeforeEnd(entry.timestamp, endedAt),\n\t\t\t);\n\t};\n\n\treturn { resolveLeafEntryId, buildSlice };\n}\n\n/** @internal */\nexport function resolveTurnContinuationLeafEntryId(\n\tentries: readonly ContinuationTreeEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): string | null {\n\treturn createTurnContinuationIndex(entries).resolveLeafEntryId(turnRecord, bounds);\n}\n\n/** @internal */\nexport function buildTurnContinuationSliceFromTree<TEntry extends ContinuationTreeEntry>(\n\ttree: ReadonlyEntryTree<TEntry>,\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): TEntry[] {\n\treturn createTurnContinuationIndex(tree.entries).buildSlice(turnRecord, bounds);\n}\n\n/** @internal */\nexport function buildTurnContinuationSlice<TEntry extends ContinuationTreeEntry>(\n\tentries: readonly TEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): TEntry[] {\n\treturn createTurnContinuationIndex(entries).buildSlice(turnRecord, bounds);\n}\n\n/** @internal */\nexport interface BranchUserPromptSnapshot {\n\t/** @internal */\n\ttext: string | null;\n\t/** @internal */\n\tcreatedAt: string | null;\n}\n\n/** @internal */\nexport function extractFirstUserPromptOnBranch<TEntry extends ContinuationTreeEntry>(\n\ttree: ReadonlyEntryTree<TEntry>,\n\tleafId: string | null | undefined,\n): BranchUserPromptSnapshot {\n\tconst resolvedLeafId = trimToNull(leafId);\n\tif (!resolvedLeafId) {\n\t\treturn { text: null, createdAt: null };\n\t}\n\tconst branch = tree.getBranch(resolvedLeafId);\n\tfor (const entry of branch) {\n\t\tif (!isPiSessionMessageEntryWithRecord(entry) || entry.message.role !== \"user\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst text = extractPiSessionMessageText(entry.message.content).trim();\n\t\tif (text === \"\") {\n\t\t\tcontinue;\n\t\t}\n\t\treturn {\n\t\t\ttext,\n\t\t\tcreatedAt: entry.timestamp,\n\t\t};\n\t}\n\treturn { text: null, createdAt: null };\n}\n\n/** @internal */\nexport function resolveTurnContinuationUserPrompt(\n\tentries: readonly ContinuationTreeEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): string | null {\n\tconst continuationLeafId = resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds);\n\tif (!continuationLeafId) {\n\t\treturn null;\n\t}\n\tconst continuationLeaf = new Map(entries.map((entry) => [entry.id, entry])).get(\n\t\tcontinuationLeafId,\n\t);\n\tif (\n\t\t!isPiSessionMessageEntryWithRecord(continuationLeaf) ||\n\t\tcontinuationLeaf.message.role !== \"user\"\n\t) {\n\t\treturn null;\n\t}\n\tconst promptText = extractPiSessionMessageText(continuationLeaf.message.content).trim();\n\treturn promptText !== \"\" ? promptText : null;\n}\n\n/** @internal */\nexport function hasTurnContinuationProgress(\n\tentries: readonly ContinuationTreeEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): boolean {\n\treturn resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds) !== null;\n}\n","import type { ProcessEvent } from \"@leitwerk-dev/domain\";\nimport {\n\tmergeUsageSnapshots,\n\tnormalizeUsageSnapshot,\n\ttype UsageSnapshot,\n} from \"./usage-snapshot.js\";\nimport { asWsEventPayloadRecord, readWsEventTurnRecordId } from \"./ws-event-payloads.js\";\n\n/** @internal */\nexport type UsageSnapshotByTurnRecordId = Record<string, UsageSnapshot>;\n\n/** @internal */\nexport function buildUsageSnapshotsByTurnRecordId(\n\tevents: readonly ProcessEvent[],\n): UsageSnapshotByTurnRecordId {\n\tconst snapshots: UsageSnapshotByTurnRecordId = {};\n\tfor (const event of events) {\n\t\tif (event.eventType !== \"pi.usage\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst payload = asWsEventPayloadRecord(event.data);\n\t\tconst turnRecordId = readWsEventTurnRecordId(payload);\n\t\tif (!turnRecordId) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst usage = normalizeUsageSnapshot(payload);\n\t\tif (!usage) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst merged = mergeUsageSnapshots(snapshots[turnRecordId] ?? null, usage);\n\t\tif (merged) {\n\t\t\tsnapshots[turnRecordId] = merged;\n\t\t}\n\t}\n\treturn snapshots;\n}\n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,OAAO;AAC5C,QAAI,CAAC,OAAO;AACX;AAAA,IACD;AACA,UAAM,SAAS,oBAAoB,UAAU,YAAY,KAAK,MAAM,KAAK;AACzE,QAAI,QAAQ;AACX,gBAAU,YAAY,IAAI;AAAA,IAC3B;AAAA,EACD;AACA,SAAO;AACR;","names":["v","asUnknownRecord","v"]}
1
+ {"version":3,"sources":["../src/usage-snapshot.ts","../src/ws-event-payloads.ts","../src/compact-turn-summary.ts","../src/extension-ui-contracts.ts","../src/initial-prompt.ts","../src/live-turn-projection.ts","../src/pi-session-message.ts","../src/timestamp-ordering.ts","../src/tool-result-truncation.ts","../src/model-requirements.ts","../src/session-entry-tree.ts","../src/skill-pack.ts","../src/streamable-events.ts","../src/text-preview.ts","../src/timeline-projection.ts","../src/turn-continuation.ts","../src/usage-by-turn-record.ts"],"sourcesContent":["import { copiedUnknownRecordSchema as unknownRecordSchema } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\n\n/** @internal */\nexport interface UsageCostSnapshot {\n\t/** @internal */\n\tinput: number;\n\t/** @internal */\n\toutput: number;\n\t/** @internal */\n\tcacheRead: number;\n\t/** @internal */\n\tcacheWrite: number;\n\t/** @internal */\n\ttotal: number;\n}\n\n/** @internal */\nexport interface UsageTokenCounts {\n\t/** @internal */\n\tinput: number;\n\t/** @internal */\n\toutput: number;\n\t/** Provider-reported reasoning/thinking tokens. This is a subset of output tokens. @internal */\n\treasoning?: number;\n\t/** @internal */\n\tcacheRead: number;\n\t/** @internal */\n\tcacheWrite: number;\n\t/** @internal */\n\ttotalTokens: number;\n}\n\n/** @internal */\nexport interface UsageSnapshot extends UsageTokenCounts {\n\t/** @internal */\n\tcost: UsageCostSnapshot | null;\n\t/** Number of model requests represented by this aggregate, when known. @internal */\n\trequestCount?: number;\n\t/** Largest input-token count for a single represented model request, when known. @internal */\n\tmaxInputTokens?: number;\n}\n\nfunction readFiniteNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n}\n\nfunction normalizeUsageCostSnapshot(value: unknown): UsageCostSnapshot | null {\n\tconst parsedValue = v.safeParse(unknownRecordSchema, value);\n\tif (!parsedValue.success) {\n\t\treturn null;\n\t}\n\tconst record = parsedValue.output;\n\tconst input = readFiniteNumber(record.input) ?? 0;\n\tconst output = readFiniteNumber(record.output) ?? 0;\n\tconst cacheRead = readFiniteNumber(record.cacheRead) ?? 0;\n\tconst cacheWrite = readFiniteNumber(record.cacheWrite) ?? 0;\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\ttotal: readFiniteNumber(record.total) ?? input + output + cacheRead + cacheWrite,\n\t};\n}\n\n/** @internal */\nexport function cloneUsageSnapshot(usage: UsageSnapshot | null | undefined): UsageSnapshot | null {\n\tif (!usage) {\n\t\treturn null;\n\t}\n\treturn {\n\t\t...usage,\n\t\tcost: usage.cost ? { ...usage.cost } : null,\n\t};\n}\n\n/** @internal */\nexport function normalizeUsageSnapshot(value: unknown): UsageSnapshot | null {\n\tconst parsedValue = v.safeParse(unknownRecordSchema, value);\n\tif (!parsedValue.success) {\n\t\treturn null;\n\t}\n\tconst record = parsedValue.output;\n\tconst input = readFiniteNumber(record.input) ?? 0;\n\tconst output = readFiniteNumber(record.output) ?? 0;\n\tconst reasoning = readFiniteNumber(record.reasoning);\n\tconst cacheRead = readFiniteNumber(record.cacheRead) ?? 0;\n\tconst cacheWrite = readFiniteNumber(record.cacheWrite) ?? 0;\n\tconst cost = normalizeUsageCostSnapshot(record.cost);\n\tconst maxInputTokens = readFiniteNumber(record.maxInputTokens);\n\tconst hasExplicitUsageTelemetry =\n\t\t[\"input\", \"output\", \"reasoning\", \"cacheRead\", \"cacheWrite\", \"totalTokens\"].some(\n\t\t\t(key) => readFiniteNumber(record[key]) !== undefined,\n\t\t) || cost !== null;\n\tif (!hasExplicitUsageTelemetry) {\n\t\treturn null;\n\t}\n\treturn {\n\t\tinput,\n\t\toutput,\n\t\t...(reasoning !== undefined ? { reasoning } : {}),\n\t\tcacheRead,\n\t\tcacheWrite,\n\t\ttotalTokens: readFiniteNumber(record.totalTokens) ?? input + output + cacheRead + cacheWrite,\n\t\tcost,\n\t\trequestCount: Math.max(0, Math.floor(readFiniteNumber(record.requestCount) ?? 1)),\n\t\tmaxInputTokens: maxInputTokens !== undefined ? Math.max(0, maxInputTokens) : input,\n\t};\n}\n\n/** @internal */\nexport function mergeUsageSnapshots(\n\ttotal: UsageSnapshot | null,\n\tusage: UsageSnapshot | null,\n): UsageSnapshot | null {\n\tif (!usage) {\n\t\treturn cloneUsageSnapshot(total);\n\t}\n\tif (!total) {\n\t\treturn cloneUsageSnapshot(usage);\n\t}\n\tconst hasRequestMetrics =\n\t\ttotal.requestCount !== undefined ||\n\t\tusage.requestCount !== undefined ||\n\t\ttotal.maxInputTokens !== undefined ||\n\t\tusage.maxInputTokens !== undefined;\n\treturn {\n\t\tinput: total.input + usage.input,\n\t\toutput: total.output + usage.output,\n\t\t...(total.reasoning !== undefined || usage.reasoning !== undefined\n\t\t\t? { reasoning: (total.reasoning ?? 0) + (usage.reasoning ?? 0) }\n\t\t\t: {}),\n\t\tcacheRead: total.cacheRead + usage.cacheRead,\n\t\tcacheWrite: total.cacheWrite + usage.cacheWrite,\n\t\ttotalTokens: total.totalTokens + usage.totalTokens,\n\t\tcost:\n\t\t\ttotal.cost && usage.cost\n\t\t\t\t? {\n\t\t\t\t\t\tinput: total.cost.input + usage.cost.input,\n\t\t\t\t\t\toutput: total.cost.output + usage.cost.output,\n\t\t\t\t\t\tcacheRead: total.cost.cacheRead + usage.cost.cacheRead,\n\t\t\t\t\t\tcacheWrite: total.cost.cacheWrite + usage.cost.cacheWrite,\n\t\t\t\t\t\ttotal: total.cost.total + usage.cost.total,\n\t\t\t\t\t}\n\t\t\t\t: null,\n\t\t...(hasRequestMetrics\n\t\t\t? {\n\t\t\t\t\trequestCount: (total.requestCount ?? 1) + (usage.requestCount ?? 1),\n\t\t\t\t\tmaxInputTokens: Math.max(\n\t\t\t\t\t\ttotal.maxInputTokens ?? total.input,\n\t\t\t\t\t\tusage.maxInputTokens ?? usage.input,\n\t\t\t\t\t),\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n}\n","import { asUnknownRecord, trimToNull as readWsEventNonEmptyString } from \"@leitwerk-dev/domain\";\n\n/** @internal */\nexport interface WsEventPayloadRecord extends Record<string, unknown> {}\n\n/** @internal */\nexport interface ResolveWsEventToolCallIdOptions {\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttoolName?: string;\n\t/** @internal */\n\tordinal?: number;\n}\n\n/** @internal */\nexport function asWsEventPayloadRecord(value: unknown): WsEventPayloadRecord {\n\treturn asUnknownRecord(value) ?? {};\n}\n\nexport { readWsEventNonEmptyString };\n\n/** @internal */\nexport function readWsEventTimestamp(\n\tdata: WsEventPayloadRecord,\n\tfallbackTimestamp: string,\n): string {\n\treturn readWsEventNonEmptyString(data.timestamp) ?? fallbackTimestamp;\n}\n\n/** @internal */\nexport function readWsEventTurnRecordId(data: WsEventPayloadRecord): string | null {\n\treturn readWsEventNonEmptyString(data.turnRecordId);\n}\n\n/** @internal */\nexport function readWsEventPiTurnId(data: WsEventPayloadRecord): string | null {\n\treturn readWsEventNonEmptyString(data.turnId);\n}\n\n/** @internal */\nexport function readWsEventStreamText(data: WsEventPayloadRecord): string | null {\n\treturn typeof data.text === \"string\"\n\t\t? data.text\n\t\t: typeof data.delta === \"string\"\n\t\t\t? data.delta\n\t\t\t: typeof data.chunk === \"string\"\n\t\t\t\t? data.chunk\n\t\t\t\t: null;\n}\n\n/** @internal */\nexport function readWsEventToolName(data: WsEventPayloadRecord): string {\n\treturn readWsEventNonEmptyString(data.name) ?? readWsEventNonEmptyString(data.toolName) ?? \"tool\";\n}\n\n/** @internal */\nexport function readWsEventToolArguments(\n\tdata: WsEventPayloadRecord,\n): Record<string, unknown> | null {\n\treturn asUnknownRecord(data.arguments ?? data.args);\n}\n\n/** @internal */\nexport function readWsEventToolCallId(data: WsEventPayloadRecord): string | null {\n\treturn readWsEventNonEmptyString(data.toolCallId);\n}\n\n/** @internal */\nexport function resolveWsEventToolCallId(\n\tdata: WsEventPayloadRecord,\n\toptions: ResolveWsEventToolCallIdOptions,\n): string {\n\treturn (\n\t\treadWsEventToolCallId(data) ??\n\t\t`${options.toolName ?? readWsEventToolName(data)}:${options.timestamp}${options.ordinal ? `:${options.ordinal}` : \"\"}`\n\t);\n}\n","import type {\n\tPrimaryPathActiveTurnSnapshot,\n\tPrimaryPathToolCallSnapshot,\n} from \"./primary-path-snapshot.js\";\nimport {\n\tmergeUsageSnapshots,\n\tnormalizeUsageSnapshot,\n\ttype UsageSnapshot,\n} from \"./usage-snapshot.js\";\nimport {\n\treadWsEventStreamText,\n\treadWsEventTimestamp,\n\treadWsEventToolCallId,\n\treadWsEventToolName,\n} from \"./ws-event-payloads.js\";\n\n/** @internal */\nexport const REASONING_PREVIEW_MAX_CHARS = 1_024;\n\n/** @internal */\nexport interface CompactTurnSummary {\n\t/** @internal */\n\tassistant: {\n\t\t/** @internal */\n\t\ttext: string;\n\t\t/** @internal */\n\t\tthinking: string;\n\t\t/** @internal */\n\t\tlastUpdatedAt: string | null;\n\t};\n\t/** @internal */\n\tcurrentTool: Pick<\n\t\tPrimaryPathToolCallSnapshot,\n\t\t\"toolCallId\" | \"toolName\" | \"status\" | \"isError\"\n\t> | null;\n\t/** @internal */\n\tusage: UsageSnapshot | null;\n\t/** @internal */\n\ttoolCallCount: number;\n\t/** @internal */\n\ttraceItemCount: number;\n\t/** The last persisted event incorporated into this projection. @internal */\n\tthroughEventSequence: number;\n\t/** @internal */\n\tlastTraceKind: \"thinking\" | \"tool_call\" | \"operational_event\" | null;\n}\n\n/** Initial-page state. It never contains trace items, tool arguments or results. @internal */\nexport interface CompactActiveTurnSnapshot\n\textends CompactTurnSummary,\n\t\tPick<\n\t\t\tPrimaryPathActiveTurnSnapshot,\n\t\t\t\"turnRecordId\" | \"turnId\" | \"turnType\" | \"pathType\" | \"startedAt\"\n\t\t> {\n\t/** @internal */\n\tsummaryPending: boolean;\n}\n\n/** @internal */\nexport function emptyCompactTurnSummary(): CompactTurnSummary {\n\treturn {\n\t\tassistant: { text: \"\", thinking: \"\", lastUpdatedAt: null },\n\t\tcurrentTool: null,\n\t\tusage: null,\n\t\ttoolCallCount: 0,\n\t\ttraceItemCount: 0,\n\t\tthroughEventSequence: 0,\n\t\tlastTraceKind: null,\n\t};\n}\n\n/** Retain paragraph context; wrapping and blank-line removal belong to the preview viewport. @internal */\nexport function reasoningPreviewTail(text: string): string {\n\tconst normalized = text.replace(/\\r\\n?/g, \"\\n\");\n\tconst lines = normalized.split(\"\\n\").filter((line) => line.trim() !== \"\");\n\tconst separator = /\\n[^\\S\\n]*$/.test(normalized) ? \"\\n\" : \"\";\n\treturn (lines.join(\"\\n\") + separator).slice(-REASONING_PREVIEW_MAX_CHARS);\n}\n\n/** @internal */\nexport function applyEventToCompactTurnSummary(\n\tprevious: CompactTurnSummary,\n\tevent: {\n\t\t/** @internal */\n\t\teventType: string;\n\t\t/** @internal */\n\t\tdata: Record<string, unknown>;\n\t\t/** @internal */\n\t\tcreatedAt: string;\n\t\t/** @internal */\n\t\teventSequence: number;\n\t},\n): CompactTurnSummary {\n\tif (event.eventSequence <= previous.throughEventSequence) return previous;\n\tconst next = {\n\t\t...previous,\n\t\tassistant: { ...previous.assistant },\n\t\tthroughEventSequence: event.eventSequence,\n\t};\n\tconst { eventType, data } = event;\n\tif (eventType === \"pi.stream.delta\") {\n\t\tconst text = readWsEventStreamText(data);\n\t\tconst key = data.streamType === \"thinking\" ? \"thinking\" : \"text\";\n\t\tnext.assistant[key] = reasoningPreviewTail(next.assistant[key] + text);\n\t\tif (text) next.assistant.lastUpdatedAt = readWsEventTimestamp(data, event.createdAt);\n\t\tif (key === \"thinking\" && text) {\n\t\t\tif (next.lastTraceKind !== \"thinking\") next.traceItemCount++;\n\t\t\tnext.lastTraceKind = \"thinking\";\n\t\t}\n\t} else if (eventType === \"pi.tool.call\" || eventType === \"pi.tool.result\") {\n\t\tconst isResult = eventType === \"pi.tool.result\";\n\t\tconst toolCallId = (readWsEventToolCallId(data) ?? `tool-${event.eventSequence}`).slice(0, 256);\n\t\tif (!isResult) {\n\t\t\tnext.toolCallCount++;\n\t\t\tnext.traceItemCount++;\n\t\t\tnext.lastTraceKind = \"tool_call\";\n\t\t}\n\t\tif (!isResult || !next.currentTool || next.currentTool.toolCallId === toolCallId) {\n\t\t\tnext.currentTool = {\n\t\t\t\ttoolCallId: toolCallId.slice(0, 256),\n\t\t\t\ttoolName: readWsEventToolName(data).slice(0, 256),\n\t\t\t\tstatus: isResult ? \"completed\" : \"running\",\n\t\t\t\tisError: data.isError === true,\n\t\t\t};\n\t\t}\n\t} else if (eventType === \"pi.usage\") {\n\t\tnext.usage = mergeUsageSnapshots(next.usage, normalizeUsageSnapshot(data));\n\t} else if (\n\t\t[\n\t\t\t\"pi.error\",\n\t\t\t\"pi.retry.start\",\n\t\t\t\"pi.retry.end\",\n\t\t\t\"pi.compaction.start\",\n\t\t\t\"pi.compaction.end\",\n\t\t].includes(eventType)\n\t) {\n\t\tnext.traceItemCount++;\n\t\tnext.lastTraceKind = \"operational_event\";\n\t}\n\treturn next;\n}\n","import { isUnknownRecord } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\n\n// Wire shape only; the catalog validates manifests and hosts check supported versions.\nconst recordSchema = v.custom<Record<string, unknown>>(isUnknownRecord);\nconst versionSchema = v.custom<number>((value) => typeof value === \"number\");\n\n/** @internal */\nexport const leafOutcomeRendererDescriptorSchema = v.pipe(\n\trecordSchema,\n\tv.object({\n\t\t/** @internal */\n\t\tok: v.literal(true),\n\t\t/** @internal */\n\t\trendererId: v.string(),\n\t\t/** @internal */\n\t\tkind: v.literal(\"custom_element\"),\n\t\t/** @internal */\n\t\ttagName: v.string(),\n\t\t/** @internal */\n\t\tmodulePath: v.string(),\n\t\t/** @internal */\n\t\trendererApiVersion: versionSchema,\n\t\t/** @internal */\n\t\textensionManifestId: v.string(),\n\t\t/** @internal */\n\t\tmoduleUrl: v.string(),\n\t}),\n);\n/** @internal */\nexport type LeafOutcomeRendererDescriptor = v.InferOutput<\n\ttypeof leafOutcomeRendererDescriptorSchema\n>;\n\n/** @internal */\nexport const leafOutcomeRendererFailureSchema = v.pipe(\n\trecordSchema,\n\tv.object({\n\t\t/** @internal */\n\t\tok: v.literal(false),\n\t\t/** @internal */\n\t\trendererId: v.string(),\n\t\t/** @internal */\n\t\tcode: v.string(),\n\t\t/** @internal */\n\t\tmessage: v.string(),\n\t}),\n);\n/** @internal */\nexport type LeafOutcomeRendererFailure = v.InferOutput<typeof leafOutcomeRendererFailureSchema>;\n\n/** @internal */\nexport const browserUiExtensionDescriptorSchema = v.pipe(\n\trecordSchema,\n\tv.object({\n\t\t/** @internal */\n\t\textensionManifestId: v.string(),\n\t\t/** @internal */\n\t\tmodulePath: v.string(),\n\t\t/** @internal */\n\t\tmoduleUrl: v.string(),\n\t\t/** @internal */\n\t\tbrowserApiVersion: versionSchema,\n\t}),\n);\n/** @internal */\nexport type BrowserUiExtensionDescriptor = v.InferOutput<typeof browserUiExtensionDescriptorSchema>;\n","import { isUnknownRecord as isRecord } from \"@leitwerk-dev/domain\";\nimport type { FutureExecutionOverviewItem, FutureExecutionSummary } from \"./http-contracts.js\";\n\n// Best-effort extraction of an operator-facing prompt/command from launch params\n// for compact overview and detail read models. Process launchers use several\n// established field names; keep this priority list shared so server and browser\n// projections cannot drift.\n/** @internal */\nexport const INITIAL_PROMPT_FIELD_PRIORITY = [\n\t\"initialPrompt\",\n\t\"prompt\",\n\t\"taskPrompt\",\n\t\"userPrompt\",\n\t\"instructions\",\n\t\"instruction\",\n\t\"initialCommand\",\n\t\"command\",\n\t\"query\",\n\t\"message\",\n\t\"requestedChange\",\n\t\"request\",\n\t\"description\",\n] as const;\n\nfunction normalizePromptValue(value: string): string | null {\n\tconst normalized = value.replace(/\\s+/g, \" \").trim();\n\treturn normalized.length > 0 ? normalized : null;\n}\n\n/** @internal */\nexport function truncatePromptPreview(\n\tvalue: string | null | undefined,\n\tmaxLength = 180,\n): string | null {\n\tconst normalized = typeof value === \"string\" ? normalizePromptValue(value) : null;\n\treturn normalized && normalized.length > maxLength\n\t\t? `${normalized.slice(0, maxLength).trimEnd()}…`\n\t\t: normalized;\n}\n\nfunction readStringField(record: Record<string, unknown>, fieldName: string): string | null {\n\tconst exact = record[fieldName];\n\tif (typeof exact === \"string\") {\n\t\treturn exact.trim() ? exact : null;\n\t}\n\n\tconst normalizedFieldName = fieldName.toLowerCase();\n\tfor (const [key, value] of Object.entries(record)) {\n\t\tif (key.toLowerCase() !== normalizedFieldName || typeof value !== \"string\") {\n\t\t\tcontinue;\n\t\t}\n\t\treturn value.trim() ? value : null;\n\t}\n\n\treturn null;\n}\n\n/** @internal */\nexport function extractInitialPromptFromValue(value: unknown): string | null {\n\tif (!isRecord(value)) {\n\t\treturn null;\n\t}\n\n\tfor (const fieldName of INITIAL_PROMPT_FIELD_PRIORITY) {\n\t\tconst prompt = readStringField(value, fieldName);\n\t\tif (prompt) {\n\t\t\treturn prompt;\n\t\t}\n\t}\n\n\treturn null;\n}\n\n/** @internal */\nexport function extractInitialPromptFromParamsJson(\n\tparamsJson: string | null | undefined,\n): string | null {\n\tif (!paramsJson) {\n\t\treturn null;\n\t}\n\n\ttry {\n\t\treturn extractInitialPromptFromValue(JSON.parse(paramsJson));\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** @internal */\nexport function extractInitialPromptPreviewFromParamsJson(\n\tparamsJson: string | null | undefined,\n\tmaxLength = 180,\n): string | null {\n\treturn truncatePromptPreview(extractInitialPromptFromParamsJson(paramsJson), maxLength);\n}\n\n/** @internal */\nexport function projectFutureExecutionOverview(\n\tsummary: FutureExecutionSummary,\n): FutureExecutionOverviewItem {\n\tconst common = {\n\t\tid: summary.id,\n\t\tscheduleKind: summary.scheduleKind,\n\t\tprocessId: summary.processId,\n\t\tnextRunAt: summary.nextRunAt,\n\t\tcronExpression: summary.cronExpression,\n\t\ttitle: summary.title,\n\t\tstatus: summary.status ?? \"scheduled\",\n\t\tblockedReason: summary.blockedReason ?? null,\n\t\tinitialPromptPreview:\n\t\t\tsummary.kind === \"launch\"\n\t\t\t\t? truncatePromptPreview(extractInitialPromptFromValue(summary.launcherInput))\n\t\t\t\t: null,\n\t};\n\treturn summary.kind === \"action\"\n\t\t? {\n\t\t\t\t...common,\n\t\t\t\tkind: \"action\",\n\t\t\t\tinstanceId: summary.instanceId,\n\t\t\t\tactionId: summary.actionId,\n\t\t\t\tactionLabel: summary.actionLabel,\n\t\t\t}\n\t\t: {\n\t\t\t\t...common,\n\t\t\t\tkind: \"launch\",\n\t\t\t\tinstanceId: null,\n\t\t\t\tlauncherId: summary.launcherId,\n\t\t\t\tlauncherLabel: summary.launcherLabel,\n\t\t\t};\n}\n","import {\n\ttype ProcessEvent,\n\treadFiniteNumber as readNumber,\n\treadNonBlankString as readString,\n} from \"@leitwerk-dev/domain\";\nimport type { TurnTraceSnapshot, TurnTraceToolCallSnapshot } from \"./http-contracts.js\";\nimport { extractPiSessionMessageText } from \"./pi-session-message.js\";\nimport type {\n\tPrimaryPathActiveTurnSnapshot,\n\tPrimaryPathOperationalTraceItemSnapshot,\n\tPrimaryPathStreamingAssistantSnapshot,\n\tPrimaryPathToolCallSnapshot,\n\tPrimaryPathTraceItemSnapshot,\n} from \"./primary-path-snapshot.js\";\nimport { compareTimestampStrings } from \"./timestamp-ordering.js\";\nimport { isToolResultTruncated } from \"./tool-result-truncation.js\";\nimport {\n\tcloneUsageSnapshot,\n\tmergeUsageSnapshots,\n\tnormalizeUsageSnapshot,\n\ttype UsageSnapshot,\n} from \"./usage-snapshot.js\";\nimport {\n\tasWsEventPayloadRecord,\n\treadWsEventNonEmptyString,\n\treadWsEventStreamText,\n\treadWsEventTimestamp,\n\treadWsEventToolArguments,\n\treadWsEventToolCallId,\n\treadWsEventToolName,\n\tresolveWsEventToolCallId,\n\ttype WsEventPayloadRecord,\n} from \"./ws-event-payloads.js\";\n\ninterface ProjectionToolCall extends PrimaryPathToolCallSnapshot {\n\trestoredResult?: Pick<TurnTraceToolCallSnapshot, \"resultText\" | \"truncated\">;\n}\n\ninterface LiveTurnProjectionState {\n\tassistant: PrimaryPathStreamingAssistantSnapshot;\n\ttraceItems: PrimaryPathTraceItemSnapshot[];\n\tusage: UsageSnapshot | null;\n\ttoolCallsById: Map<string, ProjectionToolCall>;\n\tnextFallbackOrdinal: number;\n}\n\n/** @internal */\nexport interface LiveTurnProjectionEvent {\n\t/** @internal */\n\teventType: string;\n\t/** @internal */\n\tdata: WsEventPayloadRecord;\n\t/** @internal */\n\tfallbackTimestamp: string;\n}\n\n/** @internal */\nexport type LiveTurnSnapshot = Pick<\n\tPrimaryPathActiveTurnSnapshot,\n\t\"assistant\" | \"toolCalls\" | \"traceItems\" | \"usage\"\n>;\n\n/** Projection of events already scoped and ordered by the caller. @internal */\nexport interface TurnTraceProjection {\n\t/** Canonicalize and incorporate one event. Transport deduplication belongs to the caller. @internal */\n\tapply(event: LiveTurnProjectionEvent): AppliedLiveTurnProjectionEvent;\n\t/** Present retained content, preserving the restored prompt unless one is supplied. @internal */\n\tsnapshot(piInput?: TurnTraceSnapshot[\"piInput\"]): TurnTraceSnapshot;\n}\n\n/** Event-backed projection retaining original tool results. @internal */\nexport interface LiveTurnProjection extends TurnTraceProjection {\n\t/** Read the recorded result values as well as the projected activity. @internal */\n\trawSnapshot(): LiveTurnSnapshot;\n}\n\n/** @internal */\nexport interface AppliedLiveTurnProjectionEvent {\n\t/** @internal */\n\tcanonicalData: WsEventPayloadRecord;\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttoolCallId: string | null;\n\t/** @internal */\n\ttoolName: string | null;\n\t/** Aggregate usage without copying the full activity history. @internal */\n\tusage: UsageSnapshot | null;\n}\n\n/** @internal */\nexport const PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES = [\n\t\"pi.error\",\n\t\"pi.retry.start\",\n\t\"pi.retry.end\",\n\t\"pi.compaction.start\",\n\t\"pi.compaction.end\",\n] as const;\n\nfunction cloneToolCall(toolCall: ProjectionToolCall): ProjectionToolCall {\n\treturn {\n\t\t...toolCall,\n\t\t...(toolCall.arguments ? { arguments: { ...toolCall.arguments } } : {}),\n\t};\n}\n\nfunction formatReason(value: unknown): string | null {\n\tconst reason = readString(value);\n\treturn reason ? reason.replace(/[_-]+/g, \" \") : null;\n}\n\nfunction firstMessage(data: WsEventPayloadRecord, keys: readonly string[]): string | null {\n\tfor (const key of keys) {\n\t\tconst value = readString(data[key]);\n\t\tif (value) {\n\t\t\treturn value;\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction retryStartFallbackMessage(data: WsEventPayloadRecord): string {\n\tconst attempt = readNumber(data.attempt);\n\tconst maxAttempts = readNumber(data.maxAttempts);\n\tconst delayMs = readNumber(data.delayMs);\n\tconst attemptLabel = attempt !== null && maxAttempts !== null ? ` ${attempt}/${maxAttempts}` : \"\";\n\tconst delayLabel = delayMs !== null && delayMs > 0 ? ` in ${delayMs}ms` : \"\";\n\treturn `Retry${attemptLabel} scheduled${delayLabel}.`;\n}\n\nfunction retryEndFallbackMessage(data: WsEventPayloadRecord): string {\n\tconst attempt = readNumber(data.attempt);\n\tif (data.success === true) {\n\t\treturn attempt !== null\n\t\t\t? `Retry sequence succeeded after ${attempt} ${attempt === 1 ? \"retry\" : \"retries\"}.`\n\t\t\t: \"Retry sequence succeeded.\";\n\t}\n\treturn attempt !== null\n\t\t? `Retry sequence ended after ${attempt} ${attempt === 1 ? \"retry\" : \"retries\"}.`\n\t\t: \"Retry sequence ended.\";\n}\n\n/** @internal */\nexport function buildPrimaryPathOperationalTraceItem(input: {\n\t/** @internal */\n\teventType: string;\n\t/** @internal */\n\tdata: WsEventPayloadRecord;\n\t/** @internal */\n\tfallbackTimestamp: string;\n}): PrimaryPathOperationalTraceItemSnapshot | null {\n\tlet presentation: Pick<PrimaryPathOperationalTraceItemSnapshot, \"severity\" | \"title\" | \"message\">;\n\tif (input.eventType === \"pi.error\") {\n\t\tpresentation = {\n\t\t\tseverity: \"error\",\n\t\t\ttitle: \"Pi request failed\",\n\t\t\tmessage:\n\t\t\t\tfirstMessage(input.data, [\"message\", \"errorMessage\", \"finalError\"]) ??\n\t\t\t\t\"Pi reported an error.\",\n\t\t};\n\t} else if (input.eventType === \"pi.retry.start\") {\n\t\tpresentation = {\n\t\t\tseverity: \"warning\",\n\t\t\ttitle: \"Retry scheduled\",\n\t\t\tmessage:\n\t\t\t\tfirstMessage(input.data, [\"message\", \"errorMessage\"]) ??\n\t\t\t\tretryStartFallbackMessage(input.data),\n\t\t};\n\t} else if (input.eventType === \"pi.retry.end\") {\n\t\tconst success = input.data.success === true;\n\t\tpresentation = {\n\t\t\tseverity: success ? \"success\" : \"error\",\n\t\t\ttitle: success ? \"Retry succeeded\" : \"Retry exhausted\",\n\t\t\tmessage:\n\t\t\t\tfirstMessage(input.data, [\"message\", \"finalError\", \"errorMessage\"]) ??\n\t\t\t\tretryEndFallbackMessage(input.data),\n\t\t};\n\t} else if (input.eventType === \"pi.compaction.start\") {\n\t\tconst reason = formatReason(input.data.reason);\n\t\tpresentation = {\n\t\t\tseverity: \"info\",\n\t\t\ttitle: \"Context compaction started\",\n\t\t\tmessage: reason\n\t\t\t\t? `Pi started compacting context (${reason}).`\n\t\t\t\t: \"Pi started compacting context.\",\n\t\t};\n\t} else if (input.eventType === \"pi.compaction.end\") {\n\t\tconst reason = formatReason(input.data.reason);\n\t\tconst errorMessage = firstMessage(input.data, [\"errorMessage\", \"message\"]);\n\t\tconst aborted = input.data.aborted === true;\n\t\tpresentation = {\n\t\t\tseverity: errorMessage ? \"error\" : aborted ? \"warning\" : \"success\",\n\t\t\ttitle: errorMessage\n\t\t\t\t? \"Context compaction failed\"\n\t\t\t\t: aborted\n\t\t\t\t\t? \"Context compaction cancelled\"\n\t\t\t\t\t: \"Context compacted\",\n\t\t\tmessage:\n\t\t\t\terrorMessage ??\n\t\t\t\t(aborted\n\t\t\t\t\t? \"Context compaction was cancelled.\"\n\t\t\t\t\t: `Pi compacted context${reason ? ` (${reason})` : \"\"}.${input.data.willRetry === true ? \" Pi will continue automatically.\" : \"\"}`),\n\t\t};\n\t} else {\n\t\treturn null;\n\t}\n\treturn {\n\t\tkind: \"operational_event\",\n\t\teventType: input.eventType,\n\t\ttimestamp: readWsEventTimestamp(input.data, input.fallbackTimestamp),\n\t\t...presentation,\n\t};\n}\n\nfunction canonicalizeToolCallId(input: {\n\tprojection: LiveTurnProjectionState;\n\tdata: WsEventPayloadRecord;\n\ttimestamp: string;\n\ttoolName: string;\n\tpreferOpenCall: boolean;\n}): string {\n\tconst explicitToolCallId = readWsEventToolCallId(input.data);\n\tif (explicitToolCallId) return explicitToolCallId;\n\tif (input.preferOpenCall) {\n\t\tconst openToolCall = [...input.projection.toolCallsById.values()]\n\t\t\t.reverse()\n\t\t\t.find((tool) => tool.status === \"running\" && tool.toolName === input.toolName);\n\t\tif (openToolCall) return openToolCall.toolCallId;\n\t}\n\t// Replayed canonical IDs and restored snapshots do not retain the old ordinal.\n\t// Reserve their identities by checking the index, without interpreting ID strings.\n\tlet toolCallId: string;\n\tdo {\n\t\ttoolCallId = resolveWsEventToolCallId(input.data, {\n\t\t\ttimestamp: input.timestamp,\n\t\t\ttoolName: input.toolName,\n\t\t\tordinal: input.projection.nextFallbackOrdinal++,\n\t\t});\n\t} while (input.projection.toolCallsById.has(toolCallId));\n\treturn toolCallId;\n}\n\nfunction appendThinkingTraceText(projection: LiveTurnProjectionState, text: string): void {\n\tif (text.length === 0) {\n\t\treturn;\n\t}\n\tconst lastTraceItem = projection.traceItems.at(-1);\n\tif (lastTraceItem?.kind === \"thinking\") {\n\t\tlastTraceItem.text += text;\n\t\treturn;\n\t}\n\tprojection.traceItems.push({\n\t\tkind: \"thinking\",\n\t\ttext,\n\t});\n}\n\nfunction ensureToolTraceItem(projection: LiveTurnProjectionState, toolCallId: string): void {\n\tif (\n\t\tprojection.traceItems.some(\n\t\t\t(traceItem) => traceItem.kind === \"tool_call\" && traceItem.toolCallId === toolCallId,\n\t\t)\n\t) {\n\t\treturn;\n\t}\n\tprojection.traceItems.push({\n\t\tkind: \"tool_call\",\n\t\ttoolCallId,\n\t});\n}\n\nfunction createProjectionState(): LiveTurnProjectionState {\n\treturn {\n\t\tassistant: {\n\t\t\ttext: \"\",\n\t\t\tthinking: \"\",\n\t\t\tlastUpdatedAt: null,\n\t\t},\n\t\ttraceItems: [],\n\t\tusage: null,\n\t\ttoolCallsById: new Map<string, ProjectionToolCall>(),\n\t\tnextFallbackOrdinal: 1,\n\t};\n}\n\nfunction snapshotProjection<T>(\n\tprojection: LiveTurnProjectionState,\n\tpresentTool: (tool: ProjectionToolCall) => T,\n) {\n\treturn {\n\t\tassistant: { ...projection.assistant },\n\t\ttraceItems: projection.traceItems.map((item) => ({ ...item })),\n\t\tusage: cloneUsageSnapshot(projection.usage),\n\t\ttoolCalls: Array.from(projection.toolCallsById.values(), (tool) =>\n\t\t\tpresentTool(cloneToolCall(tool)),\n\t\t),\n\t};\n}\n\nfunction applyPiEventToLiveTurnProjection(\n\tprojection: LiveTurnProjectionState,\n\tinput: LiveTurnProjectionEvent,\n): AppliedLiveTurnProjectionEvent {\n\tlet timestamp = readWsEventTimestamp(input.data, input.fallbackTimestamp);\n\tlet canonicalData = input.data;\n\tlet toolCallId: string | null = null;\n\tlet toolName: string | null = null;\n\tif (input.eventType === \"pi.stream.delta\") {\n\t\tconst text = readWsEventStreamText(input.data);\n\t\tif (text) {\n\t\t\tif (readWsEventNonEmptyString(input.data.streamType) === \"thinking\") {\n\t\t\t\tprojection.assistant.thinking += text;\n\t\t\t\tappendThinkingTraceText(projection, text);\n\t\t\t} else {\n\t\t\t\tprojection.assistant.text += text;\n\t\t\t}\n\t\t\tprojection.assistant.lastUpdatedAt = timestamp;\n\t\t}\n\t} else if (input.eventType === \"pi.tool.call\" || input.eventType === \"pi.tool.result\") {\n\t\tconst isResult = input.eventType === \"pi.tool.result\";\n\t\ttoolName = readWsEventToolName(input.data);\n\t\ttoolCallId = canonicalizeToolCallId({\n\t\t\tprojection,\n\t\t\tdata: input.data,\n\t\t\ttimestamp,\n\t\t\ttoolName,\n\t\t\tpreferOpenCall: isResult,\n\t\t});\n\t\tcanonicalData =\n\t\t\treadWsEventToolCallId(input.data) === toolCallId ? input.data : { ...input.data, toolCallId };\n\t\tconst existingToolCall = projection.toolCallsById.get(toolCallId);\n\t\tconst toolCall: ProjectionToolCall = existingToolCall ?? {\n\t\t\ttoolCallId,\n\t\t\ttoolName,\n\t\t\tstatus: \"running\",\n\t\t\tstartedAt: timestamp,\n\t\t\tcompletedAt: null,\n\t\t\targuments: isResult ? null : readWsEventToolArguments(canonicalData),\n\t\t\tresult: null,\n\t\t\tisError: false,\n\t\t};\n\t\tif (!existingToolCall) projection.toolCallsById.set(toolCallId, toolCall);\n\t\tif (isResult) {\n\t\t\ttoolCall.status = \"completed\";\n\t\t\ttoolCall.completedAt = timestamp;\n\t\t\ttoolCall.result = canonicalData.result ?? null;\n\t\t\tdelete toolCall.restoredResult;\n\t\t\ttoolCall.isError = canonicalData.isError === true;\n\t\t}\n\t\tensureToolTraceItem(projection, toolCallId);\n\t} else if (input.eventType === \"pi.usage\") {\n\t\tprojection.usage = mergeUsageSnapshots(projection.usage, normalizeUsageSnapshot(input.data));\n\t} else {\n\t\tconst operationalTraceItem = buildPrimaryPathOperationalTraceItem(input);\n\t\tif (operationalTraceItem) {\n\t\t\tprojection.traceItems.push(operationalTraceItem);\n\t\t\ttimestamp = operationalTraceItem.timestamp;\n\t\t}\n\t}\n\n\treturn {\n\t\tcanonicalData,\n\t\ttimestamp,\n\t\ttoolCallId,\n\t\ttoolName,\n\t\tusage: cloneUsageSnapshot(projection.usage),\n\t};\n}\n\nfunction compareProcessEventsChronologically(left: ProcessEvent, right: ProcessEvent): number {\n\tif (left.eventSequence !== undefined && right.eventSequence !== undefined) {\n\t\treturn left.eventSequence - right.eventSequence;\n\t}\n\tconst leftTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(left.data), left.createdAt);\n\tconst rightTimestamp = readWsEventTimestamp(asWsEventPayloadRecord(right.data), right.createdAt);\n\tconst timestampComparison = compareTimestampStrings(leftTimestamp, rightTimestamp);\n\tif (timestampComparison !== 0) {\n\t\treturn timestampComparison;\n\t}\n\tconst createdAtComparison = compareTimestampStrings(left.createdAt, right.createdAt);\n\tif (createdAtComparison !== 0) {\n\t\treturn createdAtComparison;\n\t}\n\treturn left.id.localeCompare(right.id);\n}\n\nfunction snapshotToolTrace({\n\tresult,\n\trestoredResult,\n\t...tool\n}: ProjectionToolCall): TurnTraceToolCallSnapshot {\n\tif (restoredResult) return { ...tool, ...restoredResult };\n\tconst record = result && typeof result === \"object\" ? (result as Record<string, unknown>) : null;\n\tconst resultText =\n\t\tresult == null\n\t\t\t? null\n\t\t\t: typeof result === \"string\"\n\t\t\t\t? result\n\t\t\t\t: record && \"content\" in record\n\t\t\t\t\t? extractPiSessionMessageText(record.content)\n\t\t\t\t\t: JSON.stringify(result, null, 2);\n\treturn {\n\t\t...tool,\n\t\tresultText,\n\t\ttruncated: isToolResultTruncated({\n\t\t\tresultText,\n\t\t\tresultDetails: record?.details,\n\t\t\tresultValue: result,\n\t\t}),\n\t};\n}\n\nfunction traceProjection(\n\tstate: LiveTurnProjectionState,\n\tretainedPiInput: TurnTraceSnapshot[\"piInput\"] = null,\n): TurnTraceProjection {\n\treturn {\n\t\tapply: (event) => applyPiEventToLiveTurnProjection(state, event),\n\t\tsnapshot: (piInput = retainedPiInput) => ({\n\t\t\t...snapshotProjection(state, snapshotToolTrace),\n\t\t\tpiInput,\n\t\t}),\n\t};\n}\n\n/** Start empty, or replay recorded events in their persisted order. @internal */\nexport function createLiveTurnProjection(events: readonly ProcessEvent[] = []): LiveTurnProjection {\n\tconst state = createProjectionState();\n\tfor (const event of [...events].sort(compareProcessEventsChronologically)) {\n\t\tapplyPiEventToLiveTurnProjection(state, {\n\t\t\teventType: event.eventType,\n\t\t\tdata: asWsEventPayloadRecord(event.data),\n\t\t\tfallbackTimestamp: event.createdAt,\n\t\t});\n\t}\n\treturn {\n\t\t...traceProjection(state),\n\t\trawSnapshot: () =>\n\t\t\tsnapshotProjection(state, ({ restoredResult: _restoredResult, ...tool }) => tool),\n\t};\n}\n\n/**\n * Resume presentation from a Trace, including correlation for its running tools.\n * A Trace retains displayed results, not the original structured tool results.\n * @internal\n */\nexport function restoreTurnTraceProjection(trace: TurnTraceSnapshot): TurnTraceProjection {\n\tconst state = createProjectionState();\n\tstate.assistant = { ...trace.assistant };\n\tstate.traceItems = trace.traceItems.map((item) => ({ ...item }));\n\tstate.usage = cloneUsageSnapshot(trace.usage);\n\tfor (const { resultText, truncated, ...tool } of trace.toolCalls) {\n\t\tconst toolCall = cloneToolCall({\n\t\t\t...tool,\n\t\t\tresult: null,\n\t\t\trestoredResult: { resultText, truncated },\n\t\t});\n\t\tstate.toolCallsById.set(toolCall.toolCallId, toolCall);\n\t}\n\treturn traceProjection(state, trace.piInput);\n}\n","/** @internal */\nexport interface PiSessionMessageLike {\n\t/** @internal */\n\trole?: unknown;\n\t/** @internal */\n\tcontent?: unknown;\n\t/** @internal */\n\tdetails?: unknown;\n\t/** @internal */\n\ttoolCallId?: unknown;\n\t/** @internal */\n\ttoolName?: unknown;\n\t/** @internal */\n\tisError?: unknown;\n\t/** @internal */\n\tusage?: unknown;\n}\n\n/** @internal */\nexport interface PiSessionMessageEntryLike {\n\t/** @internal */\n\ttype?: unknown;\n\t/** @internal */\n\tmessage?: unknown;\n}\n\n/** @internal */\nexport function isPiSessionMessageEntryType<\n\tTEntry extends {\n\t\t/** @internal */\n\t\ttype?: unknown;\n\t},\n>(entry: TEntry | undefined): entry is TEntry & { type: \"message\" } {\n\treturn entry?.type === \"message\";\n}\n\n/** @internal */\nexport function isPiSessionMessageRecord(value: unknown): value is PiSessionMessageLike {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** @internal */\nexport function isPiSessionMessageEntryWithRecord<TEntry extends PiSessionMessageEntryLike>(\n\tentry: TEntry | undefined,\n): entry is TEntry & { type: \"message\"; message: NonNullable<TEntry[\"message\"]> } {\n\treturn isPiSessionMessageEntryType(entry) && isPiSessionMessageRecord(entry.message);\n}\n\n/** @internal */\nexport function extractPiSessionMessageText(content: unknown): string {\n\tif (typeof content === \"string\") {\n\t\treturn content;\n\t}\n\tif (!Array.isArray(content)) {\n\t\treturn \"\";\n\t}\n\treturn content\n\t\t.map((block) => {\n\t\t\tif (typeof block !== \"object\" || block === null || Array.isArray(block)) {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\tconst record = block as { type?: unknown; text?: unknown };\n\t\t\treturn record.type === \"text\" && typeof record.text === \"string\" ? record.text : \"\";\n\t\t})\n\t\t.join(\"\");\n}\n","/** @internal */\nexport function compareTimestampStrings(left: string, right: string): number {\n\tconst leftMs = Date.parse(left);\n\tconst rightMs = Date.parse(right);\n\tif (Number.isFinite(leftMs) && Number.isFinite(rightMs)) {\n\t\treturn leftMs - rightMs;\n\t}\n\treturn left.localeCompare(right);\n}\n\n/** @internal */\nexport function happenedOnOrAfterStart(entryTimestamp: string, startedAt: string | null): boolean {\n\tif (!startedAt) {\n\t\treturn true;\n\t}\n\treturn compareTimestampStrings(entryTimestamp, startedAt) >= 0;\n}\n","import { asUnknownRecord } from \"@leitwerk-dev/domain\";\n\nconst TOOL_TRUNCATION_BOOLEAN_KEYS = [\n\t\"truncated\",\n\t\"isTruncated\",\n\t\"wasTruncated\",\n\t\"outputTruncated\",\n\t\"resultTruncated\",\n] as const;\nconst TOOL_TRUNCATION_TEXT_MARKERS = [\n\t\"output truncated\",\n\t\"result truncated\",\n\t\"response was too big\",\n\t\"too large to display\",\n\t\"truncated after\",\n\t\"truncated to last\",\n\t\"truncated since\",\n] as const;\n\nfunction readTruncationPayload(value: unknown): unknown {\n\tconst record = asUnknownRecord(value);\n\tif (!record) {\n\t\treturn null;\n\t}\n\tif (\"truncation\" in record) {\n\t\treturn record.truncation;\n\t}\n\tfor (const key of TOOL_TRUNCATION_BOOLEAN_KEYS) {\n\t\tif (key in record) {\n\t\t\treturn record[key];\n\t\t}\n\t}\n\treturn null;\n}\n\nfunction isExplicitFalseTruncationString(value: string): boolean {\n\tconst normalized = value.trim().toLowerCase();\n\treturn (\n\t\tnormalized === \"\" ||\n\t\tnormalized === \"false\" ||\n\t\tnormalized === \"none\" ||\n\t\tnormalized === \"null\" ||\n\t\tnormalized === \"no\" ||\n\t\tnormalized === \"0\"\n\t);\n}\n\nfunction isTruthyTruncationValue(value: unknown): boolean {\n\tif (value === null || value === undefined) {\n\t\treturn false;\n\t}\n\tif (typeof value === \"boolean\") {\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\treturn Number.isFinite(value) && value > 0;\n\t}\n\tif (typeof value === \"string\") {\n\t\treturn !isExplicitFalseTruncationString(value);\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.length > 0;\n\t}\n\tconst record = asUnknownRecord(value);\n\tif (!record) {\n\t\treturn true;\n\t}\n\tfor (const key of TOOL_TRUNCATION_BOOLEAN_KEYS) {\n\t\tif (record[key] === true) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn Object.keys(record).some((key) => {\n\t\tif (\n\t\t\tTOOL_TRUNCATION_BOOLEAN_KEYS.includes(key as (typeof TOOL_TRUNCATION_BOOLEAN_KEYS)[number])\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn isTruthyTruncationValue(record[key]);\n\t});\n}\n\n/** @internal */\nexport function isToolResultTruncated(input: {\n\t/** @internal */\n\tresultText: string | null;\n\t/** @internal */\n\tresultDetails: unknown;\n\t/** @internal */\n\tresultValue: unknown;\n}): boolean {\n\tconst normalizedText = input.resultText?.toLowerCase() ?? \"\";\n\treturn (\n\t\tTOOL_TRUNCATION_TEXT_MARKERS.some((marker) => normalizedText.includes(marker)) ||\n\t\tisTruthyTruncationValue(readTruncationPayload(input.resultDetails)) ||\n\t\tisTruthyTruncationValue(readTruncationPayload(input.resultValue))\n\t);\n}\n","import * as v from \"valibot\";\n\n/** Static model restrictions. Every layer is conjunctive; unknown capability support fails closed. @public */\nexport interface ModelRequirements {\n\t/** Installation-specific profile allowlist. Empty lists are invalid. @public */\n\treadonly profiles?: readonly string[];\n\t/** Provider-established capabilities required by the caller. @public */\n\treadonly capabilities?: readonly string[];\n\t/** Operator-owned, case-sensitive labels. @public */\n\treadonly labels?: {\n\t\t/** @public */\n\t\treadonly all_of?: readonly string[];\n\t\t/** At least one label in this clause must match. Empty lists are invalid. @public */\n\t\treadonly any_of?: readonly string[];\n\t\t/** @public */\n\t\treadonly none_of?: readonly string[];\n\t};\n}\n\n/** Policy label and capability identifiers are lowercase ASCII, with optional hyphens, underscores, and dots. @public */\nexport const MODEL_POLICY_IDENTIFIER = /^[a-z][a-z0-9_.-]*$/;\n\n/** @internal */\nexport const modelPolicyIdentifiersSchema = v.array(\n\tv.pipe(v.string(), v.regex(MODEL_POLICY_IDENTIFIER)),\n);\n\n/** @internal */\nexport const modelRequirementsSchema = v.strictObject({\n\t/** @internal */\n\tprofiles: v.optional(\n\t\tv.pipe(\n\t\t\tv.array(\n\t\t\t\tv.pipe(\n\t\t\t\t\tv.string(),\n\t\t\t\t\tv.check((value) => !!value.trim() && value === value.trim()),\n\t\t\t\t),\n\t\t\t),\n\t\t\tv.nonEmpty(),\n\t\t),\n\t),\n\t/** @internal */\n\tcapabilities: v.optional(modelPolicyIdentifiersSchema),\n\t/** @internal */\n\tlabels: v.optional(\n\t\tv.strictObject({\n\t\t\t/** @internal */\n\t\t\tall_of: v.optional(modelPolicyIdentifiersSchema),\n\t\t\t/** @internal */\n\t\t\tany_of: v.optional(v.pipe(modelPolicyIdentifiersSchema, v.nonEmpty())),\n\t\t\t/** @internal */\n\t\t\tnone_of: v.optional(modelPolicyIdentifiersSchema),\n\t\t}),\n\t),\n});\n\n/** Reject invalid declarations at definition/configuration time. @internal */\nexport function assertValidModelRequirements(requirements: ModelRequirements): void {\n\tv.parse(modelRequirementsSchema, requirements, { message: \"Invalid model requirements\" });\n}\n\n/** Fixed presentation and deterministic tie-break order; never inferred from prices. @internal */\nexport const MODEL_COST_LABELS = [\"free\", \"economy\", \"standard\", \"premium\"] as const;\n\n/** @internal */\nexport function modelCostRank(labels: readonly string[] = []): number {\n\tconst rank = MODEL_COST_LABELS.findIndex((label) => labels.includes(label));\n\treturn rank < 0 ? MODEL_COST_LABELS.length : rank;\n}\n\n/** Locale-independent identity ordering. @internal */\nexport function compareModelProfileIds(a: string, b: string): number {\n\treturn a < b ? -1 : a > b ? 1 : 0;\n}\n","/** @internal */\nexport interface SessionTreeEntryLike {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tparentId: string | null;\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttype: string;\n}\n\n/** @internal */\nexport interface ReadonlyEntryTree<TEntry extends SessionTreeEntryLike> {\n\t/** @internal */\n\tentries: TEntry[];\n\t/** @internal */\n\tleafId: string | null;\n\t/** @internal */\n\tgetEntry(id: string): TEntry | undefined;\n\t/** @internal */\n\tgetChildren(parentId: string): TEntry[];\n\t/** @internal */\n\tgetBranch(fromId?: string | null): TEntry[];\n}\n\n/** @internal */\nexport function createReadonlyEntryTree<TEntry extends SessionTreeEntryLike>(\n\tentries: readonly TEntry[],\n): ReadonlyEntryTree<TEntry> {\n\tconst orderedEntries = [...entries];\n\tconst entriesById = new Map(orderedEntries.map((entry) => [entry.id, entry]));\n\tconst childrenByParentId = new Map<string, TEntry[]>();\n\n\tfor (const entry of orderedEntries) {\n\t\tif (typeof entry.parentId !== \"string\" || entry.parentId.trim() === \"\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst siblings = childrenByParentId.get(entry.parentId) ?? [];\n\t\tsiblings.push(entry);\n\t\tchildrenByParentId.set(entry.parentId, siblings);\n\t}\n\n\tconst leafId = orderedEntries.at(-1)?.id ?? null;\n\n\tconst getEntry = (id: string): TEntry | undefined => entriesById.get(id);\n\tconst getChildren = (parentId: string): TEntry[] =>\n\t\t(childrenByParentId.get(parentId) ?? []).slice();\n\tconst getBranch = (fromId?: string | null): TEntry[] => {\n\t\tconst resolvedFromId = fromId ?? leafId ?? undefined;\n\t\tif (!resolvedFromId) {\n\t\t\treturn [];\n\t\t}\n\t\tconst branch: TEntry[] = [];\n\t\tconst visited = new Set<string>();\n\t\tlet currentEntry = entriesById.get(resolvedFromId);\n\t\twhile (currentEntry) {\n\t\t\tif (visited.has(currentEntry.id)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tvisited.add(currentEntry.id);\n\t\t\tbranch.unshift(currentEntry);\n\t\t\tcurrentEntry = currentEntry.parentId ? entriesById.get(currentEntry.parentId) : undefined;\n\t\t}\n\t\treturn branch;\n\t};\n\n\treturn {\n\t\tentries: orderedEntries,\n\t\tleafId,\n\t\tgetEntry,\n\t\tgetChildren,\n\t\tgetBranch,\n\t};\n}\n","import { orderDependencies } from \"@leitwerk-dev/domain\";\nimport * as v from \"valibot\";\n\nconst nonEmpty = v.pipe(v.string(), v.minLength(1));\nconst skillId = v.pipe(v.string(), v.regex(/^[a-z0-9][a-z0-9-]{0,62}$/));\nconst relativePath = v.pipe(\n\tv.string(),\n\tv.check(\n\t\t(value) =>\n\t\t\tvalue.length > 0 &&\n\t\t\t!value.includes(\"\\\\\") &&\n\t\t\t!value.includes(\"\\0\") &&\n\t\t\tvalue\n\t\t\t\t.split(\"/\")\n\t\t\t\t.every((part) => part !== \"\" && part !== \".\" && part !== \"..\" && part !== \".git\"),\n\t),\n);\n\nconst upstreamSchema = v.object({\n\t/** @public */\n\turl: nonEmpty,\n\t/** @public */\n\tcommit: v.pipe(v.string(), v.regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)),\n});\n\nconst entrySchema = v.object({\n\t/** @public */\n\tid: skillId,\n\t/** @public */\n\tdirectory: relativePath,\n\t/** @public */\n\tlabel: nonEmpty,\n\t/** @public */\n\tdescription: nonEmpty,\n\t/** @public */\n\tsourcePath: relativePath,\n\t/** @public */\n\tdependencies: v.array(skillId),\n});\n\n/** Supports the public inferred manifest declaration. @public */\nconst manifestSchema = v.object({\n\t/** @public */\n\tformatVersion: v.literal(1),\n\t/** @public */\n\tupstream: upstreamSchema,\n\t/** @public */\n\tpatchDigest: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/)),\n\t/** @public */\n\tskills: v.pipe(v.array(entrySchema), v.minLength(1)),\n});\n\n/** On-disk contract for an extension's generated skill pack. @public */\nexport type SkillPackManifest = v.InferOutput<typeof manifestSchema>;\n\n/** Provenance retained with an immutable installed skill revision. @internal */\nexport interface SkillRevisionProvenance {\n\t/** @internal */\n\textensionId: string;\n\t/** @internal */\n\tpackageName: string;\n\t/** @internal */\n\tpackageVersion: string;\n\t/** @internal */\n\tupstream: SkillPackManifest[\"upstream\"];\n\t/** @internal */\n\tsourcePath: string;\n\t/** @internal */\n\tpatchDigest: string;\n\t/** @internal */\n\tdependencies: string[];\n}\n\n/** Validates pack-local dependencies as well as the manifest shape. @internal */\nexport function parseSkillPackManifest(input: unknown): SkillPackManifest {\n\tconst manifest = v.parse(manifestSchema, input);\n\tconst byId = new Map(manifest.skills.map((skill) => [skill.id, skill]));\n\tif (byId.size !== manifest.skills.length) throw new Error(\"Duplicate skill ID in skill pack\");\n\tconst directories = new Set(manifest.skills.map((skill) => skill.directory));\n\tif (directories.size !== manifest.skills.length) throw new Error(\"Duplicate skill directory\");\n\torderDependencies(\n\t\tbyId.keys(),\n\t\t(id) => {\n\t\t\tconst entry = byId.get(id);\n\t\t\tif (!entry) throw new Error(`Missing skill pack dependency '${id}'`);\n\t\t\tif (new Set(entry.dependencies).size !== entry.dependencies.length)\n\t\t\t\tthrow new Error(`Duplicate dependencies for skill '${id}'`);\n\t\t\treturn entry.dependencies;\n\t\t},\n\t\t(id) => `Circular skill dependency at '${id}'`,\n\t);\n\treturn manifest;\n}\n","/** @internal */\nexport const STREAMABLE_WORKER_EVENT_TYPES = [\n\t\"pi.stream.delta\",\n\t\"pi.turn.start\",\n\t\"pi.turn.end\",\n\t\"pi.tool.call\",\n\t\"pi.tool.result\",\n\t\"pi.label.changed\",\n\t\"pi.error\",\n\t\"pi.retry.start\",\n\t\"pi.retry.end\",\n\t\"pi.usage\",\n\t\"pi.compaction.start\",\n\t\"pi.compaction.end\",\n] as const;\n\n/** @internal */\nexport type StreamableWorkerEventType = (typeof STREAMABLE_WORKER_EVENT_TYPES)[number];\n\nconst STREAMABLE_EVENT_TYPES = new Set<string>(STREAMABLE_WORKER_EVENT_TYPES);\n\n/** @internal */\nexport function isStreamableEvent(eventType: string): eventType is StreamableWorkerEventType {\n\treturn STREAMABLE_EVENT_TYPES.has(eventType);\n}\n","/** @internal */\nexport interface TextPreview {\n\t/** @internal */\n\ttext: string;\n\t/** @internal */\n\ttruncated: boolean;\n}\n\n/** @internal */\nexport function truncateTextPreview(value: string, maxLength: number): TextPreview {\n\treturn value.length <= maxLength\n\t\t? { text: value, truncated: false }\n\t\t: { text: value.slice(0, maxLength).trimEnd(), truncated: true };\n}\n\n/** @internal */\nexport function buildTrailingLinePreview(\n\tvalue: string,\n\tlineCount: number,\n\tmaxLength: number,\n): TextPreview {\n\tconst lines = value.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n\tif (lines.length === 1 && lines[0] === \"\") return { text: \"\", truncated: false };\n\n\tlet text = lines.slice(-lineCount).join(\"\\n\");\n\tlet truncated = lines.length > lineCount;\n\tif (text.length > maxLength) {\n\t\ttext = text.slice(-maxLength);\n\t\ttruncated = true;\n\t}\n\tif (truncated) {\n\t\tconst previewLines = text.split(\"\\n\");\n\t\tpreviewLines[0] = previewLines[0] ? `… ${previewLines[0]}` : \"…\";\n\t\ttext = previewLines.join(\"\\n\");\n\t}\n\treturn { text, truncated };\n}\n","import type {\n\tProcessTimelineTurnPresentation,\n\tProcessTimelineTurnSummary,\n} from \"./http-contracts.js\";\nimport type { PrimaryPathActiveTurnSnapshot } from \"./primary-path-snapshot.js\";\n\n/** @internal */\nexport function timelinePresentationForTurnType(\n\tturnType: ProcessTimelineTurnSummary[\"turnType\"],\n): ProcessTimelineTurnPresentation {\n\tif (turnType === \"external\") return \"external_trigger\";\n\tif (turnType === \"human\") return \"operator_decision\";\n\treturn turnType === \"automatic\" ? \"automatic_turn\" : \"llm_turn\";\n}\n\n/** @internal */\nexport function buildActiveTimelineTurnSummary(\n\tactiveTurn: Pick<\n\t\tPrimaryPathActiveTurnSnapshot,\n\t\t\"turnRecordId\" | \"turnId\" | \"turnType\" | \"pathType\" | \"startedAt\" | \"assistant\"\n\t>,\n\tinput: {\n\t\t/** @internal */\n\t\tsummary: string;\n\t\t/** @internal */\n\t\toutput: string;\n\t\t/** @internal */\n\t\tactionSource?: ProcessTimelineTurnSummary[\"actionSource\"];\n\t} = { summary: `Current step: ${activeTurn.turnId}`, output: activeTurn.assistant.text.trim() },\n): ProcessTimelineTurnSummary {\n\treturn {\n\t\tid: activeTurn.turnRecordId,\n\t\tturnId: activeTurn.turnId,\n\t\tturnType: activeTurn.turnType,\n\t\tdisplayTurn: activeTurn.turnId,\n\t\toutcome: \"in_progress\",\n\t\tsummary: input.summary,\n\t\toutput: input.output,\n\t\tturnResultMarkdown: \"\",\n\t\tpathType: activeTurn.pathType,\n\t\tcreatedAt: activeTurn.startedAt,\n\t\tpresentation: timelinePresentationForTurnType(activeTurn.turnType),\n\t\tstatus: \"in_progress\",\n\t\tmodelProfileId: null,\n\t\tattemptNumber: 1,\n\t\tparentTurnRecordId: null,\n\t\tstartedAt: activeTurn.startedAt,\n\t\tendedAt: null,\n\t\tactionSource: input.actionSource ?? null,\n\t\tprogress: null,\n\t};\n}\n","import { trimToNull } from \"@leitwerk-dev/domain\";\nimport {\n\textractPiSessionMessageText,\n\tisPiSessionMessageEntryType,\n\tisPiSessionMessageEntryWithRecord,\n} from \"./pi-session-message.js\";\nimport type { ReadonlyEntryTree } from \"./session-entry-tree.js\";\nimport { compareTimestampStrings, happenedOnOrAfterStart } from \"./timestamp-ordering.js\";\n\n/** @internal */\nexport interface ContinuationTreeEntry {\n\t/** @internal */\n\tid: string;\n\t/** @internal */\n\tparentId: string | null;\n\t/** @internal */\n\ttimestamp: string;\n\t/** @internal */\n\ttype: string;\n\t/** @internal */\n\tmessage?: {\n\t\t/** @internal */\n\t\trole?: string;\n\t\t/** @internal */\n\t\tcontent?: unknown;\n\t};\n}\n\n/** @internal */\nexport interface ContinuationTurnRecordLike {\n\t/** @internal */\n\tforkPiEntryId?: string | null;\n\t/** @internal */\n\tresultPiEntryId?: string | null;\n\t/** @internal */\n\tstartedAt?: string | null;\n\t/** @internal */\n\tstatus?: string | null;\n}\n\n/** @internal */\nexport interface ContinuationSliceBounds {\n\t/** @internal */\n\tendedAt?: string | null;\n}\n\n/** @internal */\nexport interface TurnContinuationIndex<TEntry extends ContinuationTreeEntry> {\n\t/** @internal */\n\tresolveLeafEntryId(\n\t\tturnRecord: ContinuationTurnRecordLike,\n\t\tbounds?: ContinuationSliceBounds,\n\t): string | null;\n\t/** @internal */\n\tbuildSlice(turnRecord: ContinuationTurnRecordLike, bounds?: ContinuationSliceBounds): TEntry[];\n}\n\nfunction branchContainsAncestor(\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\tentryId: string,\n\tancestorId: string,\n): boolean {\n\tconst visited = new Set<string>();\n\tlet current = entriesById.get(entryId);\n\twhile (current) {\n\t\tif (visited.has(current.id)) {\n\t\t\treturn false;\n\t\t}\n\t\tvisited.add(current.id);\n\t\tif (current.id === ancestorId) {\n\t\t\treturn true;\n\t\t}\n\t\tcurrent = current.parentId ? entriesById.get(current.parentId) : undefined;\n\t}\n\treturn false;\n}\n\nfunction happenedOnOrBeforeEnd(entryTimestamp: string, endedAt: string | null): boolean {\n\tif (!endedAt) {\n\t\treturn true;\n\t}\n\treturn compareTimestampStrings(entryTimestamp, endedAt) <= 0;\n}\n\nfunction isContinuableEntryWithinBounds(\n\tentry: ContinuationTreeEntry | undefined,\n\tstartedAt: string | null,\n\tendedAt: string | null,\n): entry is ContinuationTreeEntry {\n\treturn (\n\t\t(isPiSessionMessageEntryType(entry) || entry?.type === \"compaction\") &&\n\t\thappenedOnOrAfterStart(entry.timestamp, startedAt) &&\n\t\thappenedOnOrBeforeEnd(entry.timestamp, endedAt)\n\t);\n}\n\nfunction isExplicitLeafUsable(\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\tleafId: string,\n\tforkPiEntryId: string | null,\n\tstartedAt: string | null,\n\tendedAt: string | null,\n): boolean {\n\tconst leafEntry = entriesById.get(leafId);\n\tif (!isContinuableEntryWithinBounds(leafEntry, startedAt, endedAt)) {\n\t\treturn false;\n\t}\n\treturn !forkPiEntryId || branchContainsAncestor(entriesById, leafId, forkPiEntryId);\n}\n\nfunction findLatestContinuableEntryIdOnBranch(\n\tentries: readonly ContinuationTreeEntry[],\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\toptions: { startedAt: string | null; endedAt: string | null; ancestorId: string | null },\n): string | null {\n\tfor (let index = entries.length - 1; index >= 0; index -= 1) {\n\t\tconst entry = entries[index];\n\t\tif (!isContinuableEntryWithinBounds(entry, options.startedAt, options.endedAt)) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (options.ancestorId && !branchContainsAncestor(entriesById, entry.id, options.ancestorId)) {\n\t\t\tcontinue;\n\t\t}\n\t\treturn entry.id;\n\t}\n\treturn null;\n}\n\nfunction resolveTurnContinuationLeafEntryIdFromIndex(\n\tentries: readonly ContinuationTreeEntry[],\n\tentriesById: ReadonlyMap<string, ContinuationTreeEntry>,\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): string | null {\n\tconst startedAt = trimToNull(turnRecord.startedAt);\n\tconst endedAt = trimToNull(bounds.endedAt);\n\tconst forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);\n\tconst explicitLeafId = trimToNull(turnRecord.resultPiEntryId);\n\tif (\n\t\texplicitLeafId &&\n\t\tisExplicitLeafUsable(entriesById, explicitLeafId, forkPiEntryId, startedAt, endedAt)\n\t) {\n\t\tif (turnRecord.status !== \"failed\") {\n\t\t\treturn explicitLeafId;\n\t\t}\n\t\treturn findLatestContinuableEntryIdOnBranch(entries, entriesById, {\n\t\t\tstartedAt,\n\t\t\tendedAt,\n\t\t\tancestorId: explicitLeafId,\n\t\t});\n\t}\n\n\treturn findLatestContinuableEntryIdOnBranch(entries, entriesById, {\n\t\tstartedAt,\n\t\tendedAt,\n\t\tancestorId: forkPiEntryId,\n\t});\n}\n\n/** @internal */\nexport function createTurnContinuationIndex<TEntry extends ContinuationTreeEntry>(\n\tentries: readonly TEntry[],\n): TurnContinuationIndex<TEntry> {\n\tconst entriesById = new Map(entries.map((entry) => [entry.id, entry]));\n\n\tconst resolveLeafEntryId = (\n\t\tturnRecord: ContinuationTurnRecordLike,\n\t\tbounds: ContinuationSliceBounds = {},\n\t): string | null =>\n\t\tresolveTurnContinuationLeafEntryIdFromIndex(entries, entriesById, turnRecord, bounds);\n\n\tconst buildSlice = (\n\t\tturnRecord: ContinuationTurnRecordLike,\n\t\tbounds: ContinuationSliceBounds = {},\n\t): TEntry[] => {\n\t\tconst continuationLeafId = resolveLeafEntryId(turnRecord, bounds);\n\t\tif (!continuationLeafId) {\n\t\t\treturn [];\n\t\t}\n\t\tconst forkPiEntryId = trimToNull(turnRecord.forkPiEntryId);\n\t\tconst reversedSlice: TEntry[] = [];\n\t\tconst visited = new Set<string>();\n\t\tlet current = entriesById.get(continuationLeafId);\n\t\tlet foundFork = forkPiEntryId === null;\n\t\twhile (current && !visited.has(current.id)) {\n\t\t\tvisited.add(current.id);\n\t\t\tif (current.id === forkPiEntryId) {\n\t\t\t\tfoundFork = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\treversedSlice.push(current);\n\t\t\tcurrent = current.parentId ? entriesById.get(current.parentId) : undefined;\n\t\t}\n\t\tif (!foundFork) {\n\t\t\treturn [];\n\t\t}\n\t\tconst startedAt = trimToNull(turnRecord.startedAt);\n\t\tconst endedAt = trimToNull(bounds.endedAt);\n\t\treturn reversedSlice\n\t\t\t.reverse()\n\t\t\t.filter(\n\t\t\t\t(entry) =>\n\t\t\t\t\thappenedOnOrAfterStart(entry.timestamp, startedAt) &&\n\t\t\t\t\thappenedOnOrBeforeEnd(entry.timestamp, endedAt),\n\t\t\t);\n\t};\n\n\treturn { resolveLeafEntryId, buildSlice };\n}\n\n/** @internal */\nexport function resolveTurnContinuationLeafEntryId(\n\tentries: readonly ContinuationTreeEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): string | null {\n\treturn createTurnContinuationIndex(entries).resolveLeafEntryId(turnRecord, bounds);\n}\n\n/** @internal */\nexport function buildTurnContinuationSliceFromTree<TEntry extends ContinuationTreeEntry>(\n\ttree: ReadonlyEntryTree<TEntry>,\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): TEntry[] {\n\treturn createTurnContinuationIndex(tree.entries).buildSlice(turnRecord, bounds);\n}\n\n/** @internal */\nexport function buildTurnContinuationSlice<TEntry extends ContinuationTreeEntry>(\n\tentries: readonly TEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): TEntry[] {\n\treturn createTurnContinuationIndex(entries).buildSlice(turnRecord, bounds);\n}\n\n/** @internal */\nexport interface BranchUserPromptSnapshot {\n\t/** @internal */\n\ttext: string | null;\n\t/** @internal */\n\tcreatedAt: string | null;\n}\n\n/** @internal */\nexport function extractFirstUserPromptOnBranch<TEntry extends ContinuationTreeEntry>(\n\ttree: ReadonlyEntryTree<TEntry>,\n\tleafId: string | null | undefined,\n): BranchUserPromptSnapshot {\n\tconst resolvedLeafId = trimToNull(leafId);\n\tif (!resolvedLeafId) {\n\t\treturn { text: null, createdAt: null };\n\t}\n\tconst branch = tree.getBranch(resolvedLeafId);\n\tfor (const entry of branch) {\n\t\tif (!isPiSessionMessageEntryWithRecord(entry) || entry.message.role !== \"user\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst text = extractPiSessionMessageText(entry.message.content).trim();\n\t\tif (text === \"\") {\n\t\t\tcontinue;\n\t\t}\n\t\treturn {\n\t\t\ttext,\n\t\t\tcreatedAt: entry.timestamp,\n\t\t};\n\t}\n\treturn { text: null, createdAt: null };\n}\n\n/** @internal */\nexport function resolveTurnContinuationUserPrompt(\n\tentries: readonly ContinuationTreeEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): string | null {\n\tconst continuationLeafId = resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds);\n\tif (!continuationLeafId) {\n\t\treturn null;\n\t}\n\tconst continuationLeaf = new Map(entries.map((entry) => [entry.id, entry])).get(\n\t\tcontinuationLeafId,\n\t);\n\tif (\n\t\t!isPiSessionMessageEntryWithRecord(continuationLeaf) ||\n\t\tcontinuationLeaf.message.role !== \"user\"\n\t) {\n\t\treturn null;\n\t}\n\tconst promptText = extractPiSessionMessageText(continuationLeaf.message.content).trim();\n\treturn promptText !== \"\" ? promptText : null;\n}\n\n/** @internal */\nexport function hasTurnContinuationProgress(\n\tentries: readonly ContinuationTreeEntry[],\n\tturnRecord: ContinuationTurnRecordLike,\n\tbounds: ContinuationSliceBounds = {},\n): boolean {\n\treturn resolveTurnContinuationLeafEntryId(entries, turnRecord, bounds) !== null;\n}\n","import type { ProcessEvent } from \"@leitwerk-dev/domain\";\nimport {\n\tmergeUsageSnapshots,\n\tnormalizeUsageSnapshot,\n\ttype UsageSnapshot,\n} from \"./usage-snapshot.js\";\nimport { asWsEventPayloadRecord, readWsEventTurnRecordId } from \"./ws-event-payloads.js\";\n\n/** @internal */\nexport type UsageSnapshotByTurnRecordId = Record<string, UsageSnapshot>;\n\n/** @internal */\nexport function buildUsageSnapshotsByTurnRecordId(\n\tevents: readonly ProcessEvent[],\n): UsageSnapshotByTurnRecordId {\n\tconst snapshots: UsageSnapshotByTurnRecordId = {};\n\tfor (const event of events) {\n\t\tif (event.eventType !== \"pi.usage\") {\n\t\t\tcontinue;\n\t\t}\n\t\tconst payload = asWsEventPayloadRecord(event.data);\n\t\tconst turnRecordId = readWsEventTurnRecordId(payload);\n\t\tif (!turnRecordId) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst usage = normalizeUsageSnapshot(payload);\n\t\tif (!usage) {\n\t\t\tcontinue;\n\t\t}\n\t\tconst merged = mergeUsageSnapshots(snapshots[turnRecordId] ?? null, usage);\n\t\tif (merged) {\n\t\t\tsnapshots[turnRecordId] = merged;\n\t\t}\n\t}\n\treturn snapshots;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,6BAA6B,2BAA2B;AACjE,YAAY,OAAO;AA0CnB,SAAS,iBAAiB,OAAoC;AAC7D,SAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ;AACtE;AAEA,SAAS,2BAA2B,OAA0C;AAC7E,QAAM,cAAgB,YAAU,qBAAqB,KAAK;AAC1D,MAAI,CAAC,YAAY,SAAS;AACzB,WAAO;AAAA,EACR;AACA,QAAM,SAAS,YAAY;AAC3B,QAAM,QAAQ,iBAAiB,OAAO,KAAK,KAAK;AAChD,QAAM,SAAS,iBAAiB,OAAO,MAAM,KAAK;AAClD,QAAM,YAAY,iBAAiB,OAAO,SAAS,KAAK;AACxD,QAAM,aAAa,iBAAiB,OAAO,UAAU,KAAK;AAC1D,SAAO;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO,iBAAiB,OAAO,KAAK,KAAK,QAAQ,SAAS,YAAY;AAAA,EACvE;AACD;AAGO,SAAS,mBAAmB,OAA+D;AACjG,MAAI,CAAC,OAAO;AACX,WAAO;AAAA,EACR;AACA,SAAO;AAAA,IACN,GAAG;AAAA,IACH,MAAM,MAAM,OAAO,EAAE,GAAG,MAAM,KAAK,IAAI;AAAA,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C;AAChD,aAAW,SAAS,QAAQ;AAC3B,QAAI,MAAM,cAAc,YAAY;AACnC;AAAA,IACD;AACA,UAAM,UAAU,uBAAuB,MAAM,IAAI;AACjD,UAAM,eAAe,wBAAwB,OAAO;AACpD,QAAI,CAAC,cAAc;AAClB;AAAA,IACD;AACA,UAAM,QAAQ,uBAAuB,OAAO;AAC5C,QAAI,CAAC,OAAO;AACX;AAAA,IACD;AACA,UAAM,SAAS,oBAAoB,UAAU,YAAY,KAAK,MAAM,KAAK;AACzE,QAAI,QAAQ;AACX,gBAAU,YAAY,IAAI;AAAA,IAC3B;AAAA,EACD;AACA,SAAO;AACR;","names":["v","asUnknownRecord","v","v","nonEmpty"]}
@@ -0,0 +1,46 @@
1
+ import * as v from "valibot";
2
+ /** Static model restrictions. Every layer is conjunctive; unknown capability support fails closed. @public */
3
+ export interface ModelRequirements {
4
+ /** Installation-specific profile allowlist. Empty lists are invalid. @public */
5
+ readonly profiles?: readonly string[];
6
+ /** Provider-established capabilities required by the caller. @public */
7
+ readonly capabilities?: readonly string[];
8
+ /** Operator-owned, case-sensitive labels. @public */
9
+ readonly labels?: {
10
+ /** @public */
11
+ readonly all_of?: readonly string[];
12
+ /** At least one label in this clause must match. Empty lists are invalid. @public */
13
+ readonly any_of?: readonly string[];
14
+ /** @public */
15
+ readonly none_of?: readonly string[];
16
+ };
17
+ }
18
+ /** Policy label and capability identifiers are lowercase ASCII, with optional hyphens, underscores, and dots. @public */
19
+ export declare const MODEL_POLICY_IDENTIFIER: RegExp;
20
+ /** @internal */
21
+ export declare const modelPolicyIdentifiersSchema: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
22
+ /** @internal */
23
+ export declare const modelRequirementsSchema: v.StrictObjectSchema<{
24
+ /** @internal */
25
+ readonly profiles: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, undefined>]>, undefined>, v.NonEmptyAction<string[], undefined>]>, undefined>;
26
+ /** @internal */
27
+ readonly capabilities: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>, undefined>;
28
+ /** @internal */
29
+ readonly labels: v.OptionalSchema<v.StrictObjectSchema<{
30
+ /** @internal */
31
+ readonly all_of: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>, undefined>;
32
+ /** @internal */
33
+ readonly any_of: v.OptionalSchema<v.SchemaWithPipe<readonly [v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>, v.NonEmptyAction<string[], undefined>]>, undefined>;
34
+ /** @internal */
35
+ readonly none_of: v.OptionalSchema<v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>, undefined>;
36
+ }, undefined>, undefined>;
37
+ }, undefined>;
38
+ /** Reject invalid declarations at definition/configuration time. @internal */
39
+ export declare function assertValidModelRequirements(requirements: ModelRequirements): void;
40
+ /** Fixed presentation and deterministic tie-break order; never inferred from prices. @internal */
41
+ export declare const MODEL_COST_LABELS: readonly ["free", "economy", "standard", "premium"];
42
+ /** @internal */
43
+ export declare function modelCostRank(labels?: readonly string[]): number;
44
+ /** Locale-independent identity ordering. @internal */
45
+ export declare function compareModelProfileIds(a: string, b: string): number;
46
+ //# sourceMappingURL=model-requirements.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-requirements.d.ts","sourceRoot":"","sources":["../src/model-requirements.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,8GAA8G;AAC9G,MAAM,WAAW,iBAAiB;IACjC,gFAAgF;IAChF,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,wEAAwE;IACxE,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,qDAAqD;IACrD,QAAQ,CAAC,MAAM,CAAC,EAAE;QACjB,cAAc;QACd,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QACpC,qFAAqF;QACrF,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;QACpC,cAAc;QACd,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;KACrC,CAAC;CACF;AAED,yHAAyH;AACzH,eAAO,MAAM,uBAAuB,QAAwB,CAAC;AAE7D,gBAAgB;AAChB,eAAO,MAAM,4BAA4B,oHAExC,CAAC;AAEF,gBAAgB;AAChB,eAAO,MAAM,uBAAuB;IACnC,gBAAgB;;IAYhB,gBAAgB;;IAEhB,gBAAgB;;QAGd,gBAAgB;;QAEhB,gBAAgB;;QAEhB,gBAAgB;;;aAIjB,CAAC;AAEH,8EAA8E;AAC9E,wBAAgB,4BAA4B,CAAC,YAAY,EAAE,iBAAiB,GAAG,IAAI,CAElF;AAED,kGAAkG;AAClG,eAAO,MAAM,iBAAiB,qDAAsD,CAAC;AAErF,gBAAgB;AAChB,wBAAgB,aAAa,CAAC,MAAM,GAAE,SAAS,MAAM,EAAO,GAAG,MAAM,CAGpE;AAED,sDAAsD;AACtD,wBAAgB,sBAAsB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAEnE"}
@@ -32,6 +32,8 @@ export interface SettingMetadata {
32
32
  }
33
33
  /** @public */
34
34
  export interface SettingChoice {
35
+ /** Server-supplied profile labels for model controls only. @internal */
36
+ labels?: readonly string[];
35
37
  /** @public */
36
38
  value: string;
37
39
  /** @public */
@@ -1 +1 @@
1
- {"version":3,"file":"scoped-settings.d.ts","sourceRoot":"","sources":["../src/scoped-settings.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EA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gB;QAChB,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB;QAChB,QAAQ,CAAC,EAAE,qBAAqB,CAAC;KACjC,CAAC,CAAC;IACH,gBAAgB;IAChB,QAAQ,EAAE,KAAK,CACd,eAAe,GAAG;QACjB,gBAAgB;QAChB,MAAM,EAAE,OAAO,CAAC;QAChB,+EAA+E;QAC/E,WAAW,EAAE,OAAO,CAAC;KACrB,CACD,CAAC;CACF;AAED,8FAA8F;AAC9F,MAAM,WAAW,wBAAwB;IACxC,gBAAgB;IAChB,KAAK,EAAE,KAAK,CAAC;QACZ,gBAAgB,CAAC,SAAS,EAAE,MAAM,CAAC;QACnC,oDAAoD,CAAC,UAAU,EAAE,MAAM,EAAE,CAAC;QAC1E,yEAAyE,CAAC,OAAO,CAAC,EAAE,aAAa,EAAE,CAAC;QACpG,gFAAgF,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;KAClG,CAAC,CAAC;CACH;AAED,+EAA+E;AAC/E,MAAM,WAAW,cAAc;IAC9B,cAAc,CAAC,EAAE,EAAE,MAAM,CAAC;IAC1B,cAAc,CAAC,IAAI,EAAE,MAAM,CAAC;IAC5B,cAAc,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC;CAChC;AAED,gFAAgF;AAChF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,EAAE,CAc/D"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@leitwerk-dev/protocol",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/leitwerk-dev/leitwerk.git",
@@ -43,7 +43,7 @@
43
43
  "build": "tsup --silent"
44
44
  },
45
45
  "dependencies": {
46
- "@leitwerk-dev/domain": "0.5.3",
46
+ "@leitwerk-dev/domain": "0.5.5",
47
47
  "valibot": "^1.3.1"
48
48
  },
49
49
  "devDependencies": {
@@ -114,6 +114,10 @@ export interface WorkerRuntimeConfigSnapshot {
114
114
 
115
115
  /** @public */
116
116
  export interface ModelProfileSnapshot {
117
+ /** Operator-owned policy labels; duplicates have no semantic effect. @public */
118
+ labels?: string[];
119
+ /** Candidate for automatic selection after inherited preferences. @public */
120
+ default?: boolean;
117
121
  /** @public */
118
122
  id: string;
119
123
  /** @public */
@@ -192,12 +196,16 @@ export interface ProcessPiConfigSnapshot {
192
196
 
193
197
  /** @public */
194
198
  export interface ProcessTurnConfigSnapshot {
199
+ /** Additional static restrictions; cannot widen code-defined requirements. @public */
200
+ model_requirements?: import("./model-requirements.js").ModelRequirements;
195
201
  /** @internal */
196
202
  model_profile?: string;
197
203
  }
198
204
 
199
205
  /** @public */
200
206
  export interface ProcessConfigSnapshot {
207
+ /** Additional static restrictions; cannot widen code-defined requirements. @public */
208
+ model_requirements?: import("./model-requirements.js").ModelRequirements;
201
209
  /** Server-only installed skill IDs for new launches. Replaces global defaults; [] opts out. @public */
202
210
  default_skills?: string[];
203
211
  /** @public */
@@ -412,6 +412,12 @@ export type ModelProfileAvailability = "available" | "unavailable" | "stale";
412
412
 
413
413
  /** @internal */
414
414
  export type ModelProfileOptionSummary = {
415
+ /** Independent of cached availability; includes failed requirement origins. @internal */
416
+ policyReason?: string;
417
+ /** @internal */
418
+ labels?: readonly string[];
419
+ /** @internal */
420
+ default?: boolean;
415
421
  /** @internal */
416
422
  id: string;
417
423
  /** @internal */
@@ -524,6 +530,10 @@ export type ProcessModelConfigurationIssueView = {
524
530
 
525
531
  /** @internal */
526
532
  export interface ProcessModelConfigurationView {
533
+ /** @internal */
534
+ excludedProfiles?: Readonly<Record<string, readonly ModelProfileOptionSummary[]>>;
535
+ /** @internal */
536
+ profilesByTurn?: Readonly<Record<string, readonly ModelProfileOptionSummary[]>>;
527
537
  /** @internal */
528
538
  state:
529
539
  | {
@@ -819,6 +829,10 @@ export interface ProcessDetailData extends ProcessDiagnosticsData {
819
829
 
820
830
  /** @internal */
821
831
  export interface LauncherModelConfigSchema {
832
+ /** Empty key denotes process preference; other keys are turn IDs. @internal */
833
+ excludedProfiles?: Readonly<Record<string, readonly ModelProfileOptionSummary[]>>;
834
+ /** @internal */
835
+ profilesByTurn?: Readonly<Record<string, readonly ModelProfileOptionSummary[]>>;
822
836
  /** @internal */
823
837
  availableProfiles: readonly ModelProfileOptionSummary[];
824
838
  /** @internal */
@@ -846,6 +860,8 @@ export interface LauncherTurnModelConfigPreview {
846
860
  description: string;
847
861
  /** @internal */
848
862
  effective: {
863
+ /** @internal */
864
+ explanation?: string;
849
865
  /** @internal */
850
866
  error?: string;
851
867
  /** @internal */
@@ -1985,6 +2001,9 @@ const futureLaunchPayloadInputSchema = v.object({
1985
2001
  "process_config_default",
1986
2002
  "scoped_purpose_default",
1987
2003
  "catalog_default",
2004
+ "marked_default",
2005
+ "automatic",
2006
+ "fixed_purpose",
1988
2007
  "legacy_persisted",
1989
2008
  ]),
1990
2009
  ),
package/src/index.ts CHANGED
@@ -107,6 +107,16 @@ export {
107
107
  PRIMARY_PATH_OPERATIONAL_PI_EVENT_TYPES,
108
108
  restoreTurnTraceProjection,
109
109
  } from "./live-turn-projection.js";
110
+ export {
111
+ assertValidModelRequirements,
112
+ compareModelProfileIds,
113
+ MODEL_COST_LABELS,
114
+ MODEL_POLICY_IDENTIFIER,
115
+ type ModelRequirements,
116
+ modelCostRank,
117
+ modelPolicyIdentifiersSchema,
118
+ modelRequirementsSchema,
119
+ } from "./model-requirements.js";
110
120
  export {
111
121
  extractPiSessionMessageText,
112
122
  isPiSessionMessageEntryWithRecord,