@leitwerk-dev/protocol 0.4.0 → 0.4.2
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/{chunk-JHJ6ACSD.js → chunk-6VYYJ4GN.js} +1 -1
- package/dist/chunk-6VYYJ4GN.js.map +1 -0
- package/dist/dashboard-contracts.d.ts +111 -0
- package/dist/dashboard-contracts.d.ts.map +1 -0
- package/dist/{http-contracts-public-BDrsnENx.d.ts → http-contracts-DrTIVrNI.d.ts} +31 -14
- package/dist/http-contracts-public.d.ts +1 -0
- package/dist/http-contracts-public.d.ts.map +1 -1
- package/dist/http-contracts-public.js +1 -1
- package/dist/http-contracts.d.ts +3 -1
- package/dist/http-contracts.d.ts.map +1 -1
- package/dist/http-contracts.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/dist/skill-pack.d.ts +28 -11
- package/dist/skill-pack.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/dashboard-contracts.ts +111 -0
- package/src/http-contracts-public.ts +1 -0
- package/src/http-contracts.ts +3 -0
- package/src/index.ts +1 -0
- package/src/skill-pack.ts +14 -28
- package/dist/chunk-JHJ6ACSD.js.map +0 -1
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\turl: nonEmpty,\n\tcommit: v.pipe(v.string(), v.regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/)),\n});\n\nconst entrySchema = v.object({\n\tid: skillId,\n\tdirectory: relativePath,\n\tlabel: nonEmpty,\n\tdescription: nonEmpty,\n\tsourcePath: relativePath,\n\tdependencies: v.array(skillId),\n});\n\nconst manifestSchema = v.object({\n\tformatVersion: v.literal(1),\n\tupstream: upstreamSchema,\n\tpatchDigest: v.pipe(v.string(), v.regex(/^[a-f0-9]{64}$/)),\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 interface SkillPackManifest {\n\t/** @public */\n\tformatVersion: 1;\n\t/** @public */\n\tupstream: {\n\t\t/** @public */\n\t\turl: string;\n\t\t/** @public */\n\t\tcommit: string;\n\t};\n\t/** @public */\n\tpatchDigest: string;\n\t/** @public */\n\tskills: {\n\t\t/** @public */\n\t\tid: string;\n\t\t/** @public */\n\t\tdirectory: string;\n\t\t/** @public */\n\t\tlabel: string;\n\t\t/** @public */\n\t\tdescription: string;\n\t\t/** @public */\n\t\tsourcePath: string;\n\t\t/** @public */\n\t\tdependencies: string[];\n\t}[];\n}\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,KA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AC,GACnB;AAChB,QAAM,qBAAqB,mCAAmC,SAAS,YAAY,MAAM;AACzF,MAAI,CAAC,oBAAoB;AACxB,WAAO;AAAA,EACR;AACA,QAAM,mBAAmB,IAAI,IAAI,QAAQ,IAAI,CAAC,UAAU,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,EAAE;AAAA,IAC3E;AAAA,EACD;AACA,MACC,CAAC,kCAAkC,gBAAgB,KACnD,iBAAiB,QAAQ,SAAS,QACjC;AACD,WAAO;AAAA,EACR;AACA,QAAM,aAAa,4BAA4B,iBAAiB,QAAQ,OAAO,EAAE,KAAK;AACtF,SAAO,eAAe,KAAK,aAAa;AACzC;AAGO,SAAS,4BACf,SACA,YACA,SAAkC,CAAC,GACzB;AACV,SAAO,mCAAmC,SAAS,YAAY,MAAM,MAAM;AAC5E;;;ACjSO,SAAS,kCACf,QAC8B;AAC9B,QAAM,YAAyC,CAAC;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"]}
|
|
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"],"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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,MAAM,MAAM,WAAW,KAAK;AACtC;AAGO,SAAS,kCACf,SACA,YACA,SAAkC,CAAC,GACnB;AAChB,QAAM,qBAAqB,mCAAmC,SAAS,YAAY,MAAM;AACzF,MAAI,CAAC,oBAAoB;AACxB,WAAO;AAAA,EACR;AACA,QAAM,mBAAmB,IAAI,IAAI,QAAQ,IAAI,CAAC,UAAU,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,EAAE;AAAA,IAC3E;AAAA,EACD;AACA,MACC,CAAC,kCAAkC,gBAAgB,KACnD,iBAAiB,QAAQ,SAAS,QACjC;AACD,WAAO;AAAA,EACR;AACA,QAAM,aAAa,4BAA4B,iBAAiB,QAAQ,OAAO,EAAE,KAAK;AACtF,SAAO,eAAe,KAAK,aAAa;AACzC;AAGO,SAAS,4BACf,SACA,YACA,SAAkC,CAAC,GACzB;AACV,SAAO,mCAAmC,SAAS,YAAY,MAAM,MAAM;AAC5E;;;ACjSO,SAAS,kCACf,QAC8B;AAC9B,QAAM,YAAyC,CAAC;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"]}
|
package/dist/skill-pack.d.ts
CHANGED
|
@@ -1,18 +1,32 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import * as v from "valibot";
|
|
2
|
+
/** Supports the public inferred manifest declaration. @public */
|
|
3
|
+
declare const manifestSchema: v.ObjectSchema<{
|
|
3
4
|
/** @public */
|
|
4
|
-
formatVersion: 1
|
|
5
|
+
readonly formatVersion: v.LiteralSchema<1, undefined>;
|
|
5
6
|
/** @public */
|
|
6
|
-
upstream: {
|
|
7
|
+
readonly upstream: v.ObjectSchema<{
|
|
7
8
|
/** @public */
|
|
8
|
-
url: string
|
|
9
|
+
readonly url: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
|
|
9
10
|
/** @public */
|
|
10
|
-
commit: string
|
|
11
|
-
}
|
|
11
|
+
readonly commit: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
|
|
12
|
+
}, undefined>;
|
|
12
13
|
/** @public */
|
|
13
|
-
patchDigest: string
|
|
14
|
+
readonly patchDigest: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
|
|
14
15
|
/** @public */
|
|
15
|
-
skills: {
|
|
16
|
+
readonly skills: v.SchemaWithPipe<readonly [v.ArraySchema<v.ObjectSchema<{
|
|
17
|
+
/** @public */
|
|
18
|
+
readonly id: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>;
|
|
19
|
+
/** @public */
|
|
20
|
+
readonly directory: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, undefined>]>;
|
|
21
|
+
/** @public */
|
|
22
|
+
readonly label: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
|
|
23
|
+
/** @public */
|
|
24
|
+
readonly description: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.MinLengthAction<string, 1, undefined>]>;
|
|
25
|
+
/** @public */
|
|
26
|
+
readonly sourcePath: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, undefined>]>;
|
|
27
|
+
/** @public */
|
|
28
|
+
readonly dependencies: v.ArraySchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, undefined>]>, undefined>;
|
|
29
|
+
}, undefined>, undefined>, v.MinLengthAction<{
|
|
16
30
|
/** @public */
|
|
17
31
|
id: string;
|
|
18
32
|
/** @public */
|
|
@@ -25,8 +39,10 @@ export interface SkillPackManifest {
|
|
|
25
39
|
sourcePath: string;
|
|
26
40
|
/** @public */
|
|
27
41
|
dependencies: string[];
|
|
28
|
-
}[]
|
|
29
|
-
}
|
|
42
|
+
}[], 1, undefined>]>;
|
|
43
|
+
}, undefined>;
|
|
44
|
+
/** On-disk contract for an extension's generated skill pack. @public */
|
|
45
|
+
export type SkillPackManifest = v.InferOutput<typeof manifestSchema>;
|
|
30
46
|
/** Provenance retained with an immutable installed skill revision. @internal */
|
|
31
47
|
export interface SkillRevisionProvenance {
|
|
32
48
|
/** @internal */
|
|
@@ -46,4 +62,5 @@ export interface SkillRevisionProvenance {
|
|
|
46
62
|
}
|
|
47
63
|
/** Validates pack-local dependencies as well as the manifest shape. @internal */
|
|
48
64
|
export declare function parseSkillPackManifest(input: unknown): SkillPackManifest;
|
|
65
|
+
export {};
|
|
49
66
|
//# sourceMappingURL=skill-pack.d.ts.map
|
package/dist/skill-pack.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"skill-pack.d.ts","sourceRoot":"","sources":["../src/skill-pack.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"skill-pack.d.ts","sourceRoot":"","sources":["../src/skill-pack.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAuC7B,iEAAiE;AACjE,QAAA,MAAM,cAAc;IACnB,cAAc;;IAEd,cAAc;;QAzBd,cAAc;;QAEd,cAAc;;;IAyBd,cAAc;;IAEd,cAAc;;QAtBd,cAAc;;QAEd,cAAc;;QAEd,cAAc;;QAEd,cAAc;;QAEd,cAAc;;QAEd,cAAc;;;;;;;;;;;;;;;;aAcb,CAAC;AAEH,wEAAwE;AACxE,MAAM,MAAM,iBAAiB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,cAAc,CAAC,CAAC;AAErE,gFAAgF;AAChF,MAAM,WAAW,uBAAuB;IACvC,gBAAgB;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB;IAChB,QAAQ,EAAE,iBAAiB,CAAC,UAAU,CAAC,CAAC;IACxC,gBAAgB;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB;IAChB,YAAY,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,iFAAiF;AACjF,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB,CAkBxE"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leitwerk-dev/protocol",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.2",
|
|
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.4.
|
|
46
|
+
"@leitwerk-dev/domain": "0.4.2",
|
|
47
47
|
"valibot": "^1.3.1"
|
|
48
48
|
},
|
|
49
49
|
"devDependencies": {
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/** A safe, actionable model-readiness finding. @internal */
|
|
2
|
+
export interface DashboardConfigurationIssue {
|
|
3
|
+
/** @internal */
|
|
4
|
+
id: string;
|
|
5
|
+
/** @internal */
|
|
6
|
+
code: string;
|
|
7
|
+
/** @internal */
|
|
8
|
+
severity: "error" | "warning";
|
|
9
|
+
/** @internal */
|
|
10
|
+
message: string;
|
|
11
|
+
/** @internal */
|
|
12
|
+
sources: Array<{
|
|
13
|
+
/** @internal */
|
|
14
|
+
label: string;
|
|
15
|
+
/** Local correction destination, when one exists. @internal */
|
|
16
|
+
href: string | null;
|
|
17
|
+
}>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Server-owned overview of the retained installation. @internal */
|
|
21
|
+
export interface DashboardResponseBody {
|
|
22
|
+
/** @internal */
|
|
23
|
+
generatedAt: string;
|
|
24
|
+
/** @internal */
|
|
25
|
+
definitions: {
|
|
26
|
+
/** @internal */
|
|
27
|
+
total: number;
|
|
28
|
+
/** @internal */
|
|
29
|
+
items: Array<{
|
|
30
|
+
/** @internal */
|
|
31
|
+
id: string;
|
|
32
|
+
/** @internal */
|
|
33
|
+
name: string;
|
|
34
|
+
}>;
|
|
35
|
+
};
|
|
36
|
+
/** @internal */
|
|
37
|
+
watchers: {
|
|
38
|
+
/** @internal */
|
|
39
|
+
total: number;
|
|
40
|
+
/** @internal */
|
|
41
|
+
enabled: number;
|
|
42
|
+
/** @internal */
|
|
43
|
+
items: Array<{
|
|
44
|
+
/** @internal */
|
|
45
|
+
id: string;
|
|
46
|
+
/** @internal */
|
|
47
|
+
name: string;
|
|
48
|
+
/** @internal */
|
|
49
|
+
enabled: boolean;
|
|
50
|
+
}>;
|
|
51
|
+
};
|
|
52
|
+
/** @internal */
|
|
53
|
+
skills: {
|
|
54
|
+
/** @internal */
|
|
55
|
+
total: number;
|
|
56
|
+
/** Operator-managed and extension-installed skills. @internal */
|
|
57
|
+
installed: number;
|
|
58
|
+
/** Automatically available bundled skills. @internal */
|
|
59
|
+
bundled: number;
|
|
60
|
+
};
|
|
61
|
+
/** @internal */
|
|
62
|
+
processes: {
|
|
63
|
+
/** @internal */
|
|
64
|
+
total: number;
|
|
65
|
+
/** @internal */
|
|
66
|
+
byStatus: Array<{
|
|
67
|
+
/** @internal */
|
|
68
|
+
status: "running" | "waiting" | "error" | "completed" | "aborted";
|
|
69
|
+
/** @internal */
|
|
70
|
+
count: number;
|
|
71
|
+
}>;
|
|
72
|
+
/** @internal */
|
|
73
|
+
byDefinition: Array<{
|
|
74
|
+
/** @internal */
|
|
75
|
+
processId: string;
|
|
76
|
+
/** @internal */
|
|
77
|
+
name: string;
|
|
78
|
+
/** @internal */
|
|
79
|
+
count: number;
|
|
80
|
+
}>;
|
|
81
|
+
};
|
|
82
|
+
/** @internal */
|
|
83
|
+
costs: {
|
|
84
|
+
/** Null when turns exist but no cost has been recorded. @internal */
|
|
85
|
+
totalUsd: number | null;
|
|
86
|
+
/** @internal */
|
|
87
|
+
totalLlmTurnCount: number;
|
|
88
|
+
/** @internal */
|
|
89
|
+
pricedTurnCount: number;
|
|
90
|
+
/** @internal */
|
|
91
|
+
missingCostTurnCount: number;
|
|
92
|
+
/** @internal */
|
|
93
|
+
isPartial: boolean;
|
|
94
|
+
/** Descending by recorded cost. @internal */
|
|
95
|
+
byModel: Array<{
|
|
96
|
+
/** Null when historical model identity is unavailable. @internal */
|
|
97
|
+
providerId: string | null;
|
|
98
|
+
/** @internal */
|
|
99
|
+
modelId: string | null;
|
|
100
|
+
/** @internal */
|
|
101
|
+
costUsd: number;
|
|
102
|
+
/** @internal */
|
|
103
|
+
turnCount: number;
|
|
104
|
+
}>;
|
|
105
|
+
};
|
|
106
|
+
/** @internal */
|
|
107
|
+
configuration: {
|
|
108
|
+
/** @internal */
|
|
109
|
+
issues: DashboardConfigurationIssue[];
|
|
110
|
+
};
|
|
111
|
+
}
|
|
@@ -4,6 +4,7 @@ export type {
|
|
|
4
4
|
ApiTokensResponseBody,
|
|
5
5
|
CreateApiTokenResponseBody,
|
|
6
6
|
} from "./api-token-contracts.js";
|
|
7
|
+
export type { DashboardConfigurationIssue, DashboardResponseBody } from "./dashboard-contracts.js";
|
|
7
8
|
export type {
|
|
8
9
|
AuthMeResponseBody,
|
|
9
10
|
CronPreviewResponseBody,
|