@aintela/chat 0.2.30 → 0.2.31

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.
@@ -1 +1 @@
1
- {"version":3,"file":"httpSessionService-B_G3Ej2C.js","sources":["../src/services/sessionEventDecoder.ts","../src/services/httpSessionService.ts"],"sourcesContent":["import { ServerEvent } from '../models/ServerEvent';\nimport { LlmEvent } from '../models/semanticKernelModel/models';\nimport { createEventSerializer } from '../models/semanticKernelModel/serializer';\nimport { EventType } from '../models/enums';\nimport type { Interaction } from '../models/Interaction';\nimport type { InteractionPart } from '../models/InteractionPart';\nimport type { Artifact } from '../models/Artifact';\n\n/**\n * Strip the persistence-only `$type: \"MongoDbEvent\"` marker from the wire\n * object before handing it to typedjson. The server's session-detail endpoint\n * returns base-class `Event` instances (not `MongoDbEvent`), but downstream\n * resources that come through other code paths sometimes carry that marker;\n * leaving it in confuses typedjson because it isn't registered in\n * `KNOWN_CONTENT_TYPES`.\n */\nfunction stripMongoDbDiscriminator(raw: unknown): unknown {\n if (raw === null || typeof raw !== 'object') return raw;\n const obj = raw as Record<string, unknown>;\n if (obj['$type'] === 'MongoDbEvent') {\n const { ['$type']: _drop, ...rest } = obj;\n return rest;\n }\n return obj;\n}\n\nfunction firstUserText(events: LlmEvent[]): string | undefined {\n for (const e of events) {\n if (e.role?.label?.toLowerCase() !== 'user') continue;\n const item = e.content?.items?.find(p => 'text' in p && typeof (p as Record<string, unknown>).text === 'string');\n if (item) return (item as { text?: string }).text;\n }\n return undefined;\n}\n\n// The .NET semantic-kernel metadata key that carries the model's reasoning\n// trace on persisted (consolidated) events. typedjson drops `metadata` on\n// KernelContent-derived items (it's undecorated), so the reasoning only\n// survives on the RAW wire object — we read it from there.\nconst REASONING_METADATA_KEY = 'ChatResponseMessage.ReasoningContent';\n\n/**\n * Pull the reasoning trace out of a raw wire event. The server duplicates it\n * onto the message `content.metadata` and onto each text item's `metadata`;\n * prefer the event-level copy, fall back to the first item that carries one.\n */\nfunction extractReasoning(rawEvent: unknown): string | undefined {\n const content = (rawEvent as { content?: Record<string, any> })?.content;\n if (!content) return undefined;\n const fromContent = content.metadata?.[REASONING_METADATA_KEY];\n if (typeof fromContent === 'string' && fromContent.trim()) return fromContent.trim();\n for (const item of content.items ?? []) {\n const r = item?.metadata?.[REASONING_METADATA_KEY];\n if (typeof r === 'string' && r.trim()) return r.trim();\n }\n return undefined;\n}\n\nfunction isFunctionCallType(t: EventType): boolean {\n return t === EventType.FunctionCall || t === EventType.PartialFunctionCall;\n}\n\n/**\n * Fold a FunctionResponse part onto the call part it answers, mirroring the\n * final state a live `merge` would have reached for that call: the call's\n * parsed `args`/`name`/`start` are preserved and the response's\n * `response`/`status`/`end` are layered on. eventType flips to\n * FunctionResponse, which is the completed-call shape the UI renders.\n */\nfunction foldResponseIntoCall(call: InteractionPart, response: InteractionPart): InteractionPart {\n return {\n ...call,\n eventType: EventType.FunctionResponse,\n functionDetails: {\n id: call.functionDetails!.id,\n name: response.functionDetails?.name ?? call.functionDetails!.name,\n args: call.functionDetails!.args ?? response.functionDetails?.args,\n text: call.functionDetails!.text,\n response: response.functionDetails?.response,\n status: response.functionDetails?.status ?? 'Done',\n start: call.functionDetails!.start,\n end: response.functionDetails?.end ?? call.functionDetails!.end,\n silent: call.functionDetails!.silent,\n },\n };\n}\n\n/**\n * Rebuilds the `Interaction[]` the chat UI renders from the historical event\n * log returned by <c>GET /sessions/{id}</c>.\n *\n * Unlike the live turn loop, this does NOT route events through\n * `InteractionService.merge`. The merge pipeline (and its `FlatParts` step) is\n * built for the *live* stream, where each event carries a single content item\n * arriving incrementally; it flattens every event down to one part. The\n * *persisted* log is different: the server stores consolidated blocks where a\n * single event's `content.items` holds many parts at once — e.g. a text\n * preamble plus several FunctionCalls. Running those through `merge` collapsed\n * each event to one part and silently dropped the rest (every function call in\n * a multi-item event disappeared on replay).\n *\n * This restore path instead reads *every* item as its own `InteractionPart`\n * (via `ServerEvent.parseFromTypedEvent`, which already maps one part per\n * item) and only applies the one piece of merge logic replay genuinely needs:\n * folding each FunctionResponse onto the call it answers, keyed by `callId`.\n * No copy-on-write cloning, no event-bus side effects, no streaming-append.\n */\nexport function decodeSessionEvents(rawEvents: unknown[]): Interaction[] {\n const serializer = createEventSerializer();\n\n // Parse + group by interactionId, preserving first-seen order so the\n // rendered timeline mirrors the wire-log order. Keep the typed LlmEvent\n // alongside the mapped ServerEvent — the former carries the role label\n // used to derive the interaction's question.\n const order: string[] = [];\n const grouped = new Map<string, { llm: LlmEvent[]; server: ServerEvent[]; raw: unknown[] }>();\n for (const raw of rawEvents) {\n const stripped = stripMongoDbDiscriminator(raw);\n const llmEvent = serializer.parse(stripped as Record<string, unknown>);\n if (!llmEvent) continue;\n const serverEvent = ServerEvent.parseFromTypedEvent(llmEvent);\n if (!serverEvent) continue;\n\n const key = serverEvent.interactionId ?? '__root__';\n let bucket = grouped.get(key);\n if (!bucket) {\n bucket = { llm: [], server: [], raw: [] };\n grouped.set(key, bucket);\n order.push(key);\n }\n bucket.llm.push(llmEvent);\n bucket.server.push(serverEvent);\n // Keep the stripped raw object — typedjson drops the item `metadata`\n // that holds the reasoning trace, so we recover it from here.\n bucket.raw.push(stripped);\n }\n\n const interactions: Interaction[] = [];\n for (const interactionId of order) {\n const { llm, server, raw } = grouped.get(interactionId)!;\n\n const parts: InteractionPart[] = [];\n const artifactData: Artifact[] = [];\n // callId → index in `parts` of the (possibly already folded) call part.\n const callIndex = new Map<string, number>();\n\n const pushPart = (part: InteractionPart) => {\n const stamped: InteractionPart = {\n ...part,\n id: `${parts.length + 1}-${interactionId}`,\n partial: false,\n isStillWriting: false,\n };\n parts.push(stamped);\n return parts.length - 1;\n };\n\n for (let i = 0; i < server.length; i++) {\n const event = server[i];\n\n // `user` events are the question (captured below as\n // interactionQuestion), and `system` events are injected context\n // (schema, instructions) — neither renders as a chat part. The\n // live turn loop never feeds these through merge either; only the\n // persisted log co-locates them under the turn's interactionId.\n const role = llm[i].role?.label?.toLowerCase();\n if (role === 'user' || role === 'system') {\n // The user/system text isn't a chat part (the question is captured as\n // interactionQuestion via firstUserText). But a user turn may carry a client-only\n // UI representation — a UserUiContent that ServerEvent mapped to a UserAnswer part —\n // which must re-hydrate on reload. Push those; drop everything else on this event.\n if (role === 'user') {\n for (const part of event.parts) {\n if (part.eventType === EventType.UserAnswer) pushPart(part);\n }\n }\n continue;\n }\n\n // Artifacts: dedupe by id, last write wins (same as the live merge).\n if (event.llmArtifacts && event.llmArtifacts.length > 0) {\n for (const llmArtifact of event.llmArtifacts) {\n const artifact = llmArtifact.toArtifact();\n const i = artifactData.findIndex(a => a.id === artifact.id);\n if (i === -1) artifactData.push(artifact);\n else artifactData[i] = artifact;\n }\n }\n\n // The model's reasoning trace for this step lives in the event's\n // metadata (dropped by typedjson — read from raw). It rides the\n // event's text item, so attach it to the first text part: a\n // non-empty answer keeps its body and carries the trace in the\n // thinking strip; an empty \"thinking-only\" step becomes a Thought.\n const reasoning = extractReasoning(raw[i]);\n let reasoningUsed = false;\n\n for (const part of event.parts) {\n const callId = part.functionDetails?.id;\n\n // A response folds onto its matching call rather than becoming\n // a separate part.\n if (part.eventType === EventType.FunctionResponse && callId && callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n parts[idx] = foldResponseIntoCall(parts[idx], part);\n continue;\n }\n\n // A client-only output sibling folds its payload onto the call it belongs to\n // (never a separate part). This is the persisted/replay counterpart of the live\n // StreamingFinalFunctionResultContent.clientOutput; a uiTool renderer reads it.\n if (part.eventType === EventType.FunctionClientOutput && callId) {\n if (callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n const prev = parts[idx];\n parts[idx] = {\n ...prev,\n functionDetails: {\n ...prev.functionDetails!,\n clientOutput: part.functionDetails?.clientOutput,\n },\n };\n }\n // No matching call (shouldn't happen — the call precedes its Tool message):\n // drop it rather than render a standalone part.\n continue;\n }\n\n // A repeated full call for an id we've already seen (e.g. a\n // full FunctionCall following a PartialFunctionCall) updates the\n // existing part in place instead of duplicating it.\n if (isFunctionCallType(part.eventType) && callId && callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n const prev = parts[idx];\n parts[idx] = {\n ...prev,\n eventType: part.eventType,\n functionDetails: { ...prev.functionDetails!, ...part.functionDetails! },\n };\n continue;\n }\n\n if (part.eventType === EventType.Text) {\n const hasText = !!part.text && part.text.length > 0;\n const attachReasoning = !!reasoning && !reasoningUsed;\n\n // Empty text with no reasoning to carry is a bare\n // placeholder — the consolidated log emits these alongside\n // function calls; dropping them keeps the timeline clean.\n if (!hasText && !attachReasoning && !part.thoughtDetails) {\n continue;\n }\n\n if (attachReasoning) {\n pushPart({\n ...part,\n eventType: hasText ? EventType.Text : EventType.Thought,\n thoughtDetails: { text: reasoning! },\n });\n reasoningUsed = true;\n continue;\n }\n\n pushPart(part);\n continue;\n }\n\n const idx = pushPart(part);\n if (isFunctionCallType(part.eventType) && callId) {\n callIndex.set(callId, idx);\n }\n }\n\n // Reasoning with no text item to ride on (rare) — surface it so\n // the trace isn't silently lost.\n if (reasoning && !reasoningUsed) {\n pushPart({\n id: '', author: event.author, eventType: EventType.Thought,\n created: event.created, partial: false, isStillWriting: false,\n mustPush: false, textAppendable: false,\n thoughtDetails: { text: reasoning },\n });\n }\n }\n\n const functionMap = new Map<string, InteractionPart>();\n for (const [callId, idx] of callIndex) functionMap.set(callId, parts[idx]);\n\n interactions.push({\n created: server[0]?.created ?? new Date(),\n interactionId,\n artifactData,\n partial: false,\n turn_complete: true,\n parts,\n version: server.length,\n functionMap,\n interactionQuestion: firstUserText(llm) ?? '',\n });\n }\n\n return interactions;\n}\n","import { ChatSession, Customer, decodeSessionEvents, Interaction, ISessionService } from \"..\";\n\n/**\n * Wire shape returned by `GET /sessions` and the `.header` of `GET /sessions/{id}`.\n * Mirrors `Envision.SemanticKernel.Models.Session.SessionHeader` on the C#\n * side after the default camelCase rename ASP.NET Core applies on serialize.\n */\ninterface SessionHeaderWire {\n id: string;\n created?: string | null;\n updatedAt?: string | null;\n user?: ChatSession['user'];\n customer?: ChatSession['customer'];\n overview?: string | null;\n agentType?: ChatSession['agentType'];\n userDescription?: string | null;\n lastQuestion?: string | null;\n activityCount?: number;\n lastGeneratedOverview?: string | null;\n artifacts?: string[];\n}\n\ninterface SessionDetailWire {\n header: SessionHeaderWire;\n events: unknown[];\n}\n\nfunction headerToChatSession(h: SessionHeaderWire, interactions: Interaction[] = []): ChatSession {\n return {\n id: h.id,\n browserScopeId: h.id,\n fullyLoaded: interactions.length > 0,\n interactions,\n artifacts: h.artifacts ?? [],\n overview: h.overview ?? '',\n agentType: h.agentType as ChatSession['agentType'],\n userDescription: h.userDescription ?? undefined,\n lastQuestion: h.lastQuestion ?? undefined,\n customer: h.customer ?? null,\n activityCount: h.activityCount ?? 0,\n user: h.user as ChatSession['user'],\n lastGeneratedOverview: h.lastGeneratedOverview ? new Date(h.lastGeneratedOverview) : null,\n sessionRunMode: 'normal' as ChatSession['sessionRunMode'],\n created: h.created ? new Date(h.created) : undefined,\n updatedAt: h.updatedAt ? new Date(h.updatedAt) : undefined,\n } as ChatSession;\n}\n\n/**\n * Minimal ISessionService over the WSServer's REST `/sessions` endpoints.\n *\n * Reads from the unified `Sessions` collection. The list endpoint returns\n * header projections; the detail endpoint returns header + the raw\n * `LlmEvent[]` log which we replay through `decodeSessionEvents` to rebuild\n * the chat UI's `Interaction[]`. Mutation methods are no-ops — write paths\n * are exercised by the live agent turn loop and the WS connection, not by\n * REST calls from the picker.\n */\nexport class HttpSessionService implements ISessionService {\n private serverBaseUrl: string;\n private accessToken: string;\n\n constructor(serverBaseUrl: string, accessToken: string) {\n this.serverBaseUrl = serverBaseUrl.replace(/\\/$/, '');\n this.accessToken = accessToken;\n }\n\n private get headers(): HeadersInit {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.accessToken}`,\n };\n }\n\n async getAllSessions(): Promise<ChatSession[]> {\n const r = await fetch(`${this.serverBaseUrl}/sessions?top=50`, {\n headers: this.headers,\n });\n if (!r.ok) throw new Error(`getAllSessions HTTP ${r.status}`);\n const headers = (await r.json()) as SessionHeaderWire[];\n return headers.map(h => headerToChatSession(h));\n }\n\n async retrieveSession(sessionId: string): Promise<ChatSession | null> {\n const r = await fetch(`${this.serverBaseUrl}/sessions/${sessionId}`, {\n headers: this.headers,\n });\n if (r.status === 404) return null;\n if (!r.ok) throw new Error(`retrieveSession HTTP ${r.status}`);\n const detail = (await r.json()) as SessionDetailWire;\n const interactions = decodeSessionEvents(detail.events ?? []);\n // The decoder doesn't know the sessionId — stamp it now so downstream\n // consumers (artifact loaders, debugging surfaces) can correlate back.\n for (const it of interactions) it.sessionId = detail.header.id;\n return headerToChatSession(detail.header, interactions);\n }\n\n async getLastUsedSession(): Promise<ChatSession | null> {\n const all = await this.getAllSessions();\n return all[0] ?? null;\n }\n\n // — Most write paths are inert: after the dual-collection collapse the\n // server populates Session UI-header fields automatically during the turn.\n // The two exceptions are rename (`patchSession` → PATCH /Session/Overview)\n // and delete (`removeSession` → DELETE /Session/{id}), which are driven by\n // the picker UI and have no WS-side equivalent. —\n\n async removeSession(sessionId: string): Promise<void> {\n const r = await fetch(`${this.serverBaseUrl}/Session/${encodeURIComponent(sessionId)}`, {\n method: 'DELETE',\n headers: this.headers,\n });\n if (!r.ok) throw new Error(`removeSession HTTP ${r.status}`);\n }\n async createSession(_sessionId: string, _agentName: string, _customer?: Customer): Promise<ChatSession | null> { return null; }\n async createAgentSession(): Promise<any> { return { sessionId: null }; }\n async closeSession(_sessionId: string): Promise<void> { /* no-op */ }\n async generateOverviewForCurrentSession(_sys: string, _model: string): Promise<string | null> { return null; }\n async storeSession(session: ChatSession): Promise<any> { return { data: session }; }\n async patchSession(sessionId: string, partial: Partial<ChatSession>): Promise<void> {\n // SessionController.PatchOverview binds sessionId/overview from the\n // query string (no body, no route params). Anything else on `partial`\n // has no server-side endpoint yet — ignore it instead of guessing.\n if (partial.overview == null) return;\n const url =\n `${this.serverBaseUrl}/Session/Overview` +\n `?sessionId=${encodeURIComponent(sessionId)}` +\n `&overview=${encodeURIComponent(partial.overview)}`;\n const r = await fetch(url, { method: 'PATCH', headers: this.headers });\n if (!r.ok) throw new Error(`patchSession HTTP ${r.status}`);\n }\n delayedPatchActiveSession(_partial: Partial<ChatSession>): void { /* no-op */ }\n\n async patchActiveSession(_partial: Partial<ChatSession>): Promise<ChatSession | null> {\n return Promise.resolve(null);\n }\n async getLlmSessionInformation(): Promise<any> { return { id: null, instructionSummaries: [] }; }\n transformIntoInstances(session: ChatSession): ChatSession { return session; }\n}\n"],"names":["stripMongoDbDiscriminator","raw","obj","_drop","rest","__name","firstUserText","events","e","_b","_a","item","_d","_c","p","REASONING_METADATA_KEY","extractReasoning","rawEvent","content","fromContent","r","isFunctionCallType","EventType","foldResponseIntoCall","call","response","_e","decodeSessionEvents","rawEvents","serializer","createEventSerializer","order","grouped","stripped","llmEvent","serverEvent","ServerEvent","key","bucket","interactions","interactionId","llm","server","parts","artifactData","callIndex","pushPart","part","stamped","i","event","role","llmArtifact","artifact","a","reasoning","reasoningUsed","callId","idx","prev","hasText","attachReasoning","functionMap","headerToChatSession","h","_HttpSessionService","serverBaseUrl","accessToken","__publicField","sessionId","detail","it","_sessionId","_agentName","_customer","_sys","_model","session","partial","url","_partial","HttpSessionService"],"mappings":";;;;;;;AAgBA,SAASA,EAA0BC,GAAuB;AACtD,MAAIA,MAAQ,QAAQ,OAAOA,KAAQ,SAAU,QAAOA;AACpD,QAAMC,IAAMD;AACZ,MAAIC,EAAI,UAAa,gBAAgB;AACjC,UAAM,EAAE,CAAC,OAAO,GAAGC,GAAO,GAAGC,MAASF;AACtC,WAAOE;AAAA,EACX;AACA,SAAOF;AACX;AARSG,EAAAL,GAAA;AAUT,SAASM,EAAcC,GAAwC;;AAC3D,aAAWC,KAAKD,GAAQ;AACpB,UAAIE,KAAAC,IAAAF,EAAE,SAAF,gBAAAE,EAAQ,UAAR,gBAAAD,EAAe,mBAAkB,OAAQ;AAC7C,UAAME,KAAOC,K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ionService-BO81zAcx.js","sources":["../src/services/sessionEventDecoder.ts","../src/services/httpSessionService.ts"],"sourcesContent":["import { ServerEvent } from '../models/ServerEvent';\nimport { LlmEvent } from '../models/semanticKernelModel/models';\nimport { createEventSerializer } from '../models/semanticKernelModel/serializer';\nimport { EventType } from '../models/enums';\nimport type { Interaction } from '../models/Interaction';\nimport type { InteractionPart } from '../models/InteractionPart';\nimport type { Artifact } from '../models/Artifact';\n\n/**\n * Strip the persistence-only `$type: \"MongoDbEvent\"` marker from the wire\n * object before handing it to typedjson. The server's session-detail endpoint\n * returns base-class `Event` instances (not `MongoDbEvent`), but downstream\n * resources that come through other code paths sometimes carry that marker;\n * leaving it in confuses typedjson because it isn't registered in\n * `KNOWN_CONTENT_TYPES`.\n */\nfunction stripMongoDbDiscriminator(raw: unknown): unknown {\n if (raw === null || typeof raw !== 'object') return raw;\n const obj = raw as Record<string, unknown>;\n if (obj['$type'] === 'MongoDbEvent') {\n const { ['$type']: _drop, ...rest } = obj;\n return rest;\n }\n return obj;\n}\n\nfunction firstUserText(events: LlmEvent[]): string | undefined {\n for (const e of events) {\n if (e.role?.label?.toLowerCase() !== 'user') continue;\n const item = e.content?.items?.find(p => 'text' in p && typeof (p as Record<string, unknown>).text === 'string');\n if (item) return (item as { text?: string }).text;\n }\n return undefined;\n}\n\n// The .NET semantic-kernel metadata key that carries the model's reasoning\n// trace on persisted (consolidated) events. typedjson drops `metadata` on\n// KernelContent-derived items (it's undecorated), so the reasoning only\n// survives on the RAW wire object — we read it from there.\nconst REASONING_METADATA_KEY = 'ChatResponseMessage.ReasoningContent';\n\n/**\n * Pull the reasoning trace out of a raw wire event. The server duplicates it\n * onto the message `content.metadata` and onto each text item's `metadata`;\n * prefer the event-level copy, fall back to the first item that carries one.\n */\nfunction extractReasoning(rawEvent: unknown): string | undefined {\n const content = (rawEvent as { content?: Record<string, any> })?.content;\n if (!content) return undefined;\n const fromContent = content.metadata?.[REASONING_METADATA_KEY];\n if (typeof fromContent === 'string' && fromContent.trim()) return fromContent.trim();\n for (const item of content.items ?? []) {\n const r = item?.metadata?.[REASONING_METADATA_KEY];\n if (typeof r === 'string' && r.trim()) return r.trim();\n }\n return undefined;\n}\n\nfunction isFunctionCallType(t: EventType): boolean {\n return t === EventType.FunctionCall || t === EventType.PartialFunctionCall;\n}\n\n/**\n * Fold a FunctionResponse part onto the call part it answers, mirroring the\n * final state a live `merge` would have reached for that call: the call's\n * parsed `args`/`name`/`start` are preserved and the response's\n * `response`/`status`/`end` are layered on. eventType flips to\n * FunctionResponse, which is the completed-call shape the UI renders.\n */\nfunction foldResponseIntoCall(call: InteractionPart, response: InteractionPart): InteractionPart {\n return {\n ...call,\n eventType: EventType.FunctionResponse,\n functionDetails: {\n id: call.functionDetails!.id,\n name: response.functionDetails?.name ?? call.functionDetails!.name,\n args: call.functionDetails!.args ?? response.functionDetails?.args,\n text: call.functionDetails!.text,\n response: response.functionDetails?.response,\n status: response.functionDetails?.status ?? 'Done',\n start: call.functionDetails!.start,\n end: response.functionDetails?.end ?? call.functionDetails!.end,\n silent: call.functionDetails!.silent,\n },\n };\n}\n\n/**\n * Rebuilds the `Interaction[]` the chat UI renders from the historical event\n * log returned by <c>GET /sessions/{id}</c>.\n *\n * Unlike the live turn loop, this does NOT route events through\n * `InteractionService.merge`. The merge pipeline (and its `FlatParts` step) is\n * built for the *live* stream, where each event carries a single content item\n * arriving incrementally; it flattens every event down to one part. The\n * *persisted* log is different: the server stores consolidated blocks where a\n * single event's `content.items` holds many parts at once — e.g. a text\n * preamble plus several FunctionCalls. Running those through `merge` collapsed\n * each event to one part and silently dropped the rest (every function call in\n * a multi-item event disappeared on replay).\n *\n * This restore path instead reads *every* item as its own `InteractionPart`\n * (via `ServerEvent.parseFromTypedEvent`, which already maps one part per\n * item) and only applies the one piece of merge logic replay genuinely needs:\n * folding each FunctionResponse onto the call it answers, keyed by `callId`.\n * No copy-on-write cloning, no event-bus side effects, no streaming-append.\n */\nexport function decodeSessionEvents(rawEvents: unknown[]): Interaction[] {\n const serializer = createEventSerializer();\n\n // Parse + group by interactionId, preserving first-seen order so the\n // rendered timeline mirrors the wire-log order. Keep the typed LlmEvent\n // alongside the mapped ServerEvent — the former carries the role label\n // used to derive the interaction's question.\n const order: string[] = [];\n const grouped = new Map<string, { llm: LlmEvent[]; server: ServerEvent[]; raw: unknown[] }>();\n for (const raw of rawEvents) {\n const stripped = stripMongoDbDiscriminator(raw);\n const llmEvent = serializer.parse(stripped as Record<string, unknown>);\n if (!llmEvent) continue;\n const serverEvent = ServerEvent.parseFromTypedEvent(llmEvent);\n if (!serverEvent) continue;\n\n const key = serverEvent.interactionId ?? '__root__';\n let bucket = grouped.get(key);\n if (!bucket) {\n bucket = { llm: [], server: [], raw: [] };\n grouped.set(key, bucket);\n order.push(key);\n }\n bucket.llm.push(llmEvent);\n bucket.server.push(serverEvent);\n // Keep the stripped raw object — typedjson drops the item `metadata`\n // that holds the reasoning trace, so we recover it from here.\n bucket.raw.push(stripped);\n }\n\n const interactions: Interaction[] = [];\n for (const interactionId of order) {\n const { llm, server, raw } = grouped.get(interactionId)!;\n\n const parts: InteractionPart[] = [];\n const artifactData: Artifact[] = [];\n // callId → index in `parts` of the (possibly already folded) call part.\n const callIndex = new Map<string, number>();\n\n const pushPart = (part: InteractionPart) => {\n const stamped: InteractionPart = {\n ...part,\n id: `${parts.length + 1}-${interactionId}`,\n partial: false,\n isStillWriting: false,\n };\n parts.push(stamped);\n return parts.length - 1;\n };\n\n for (let i = 0; i < server.length; i++) {\n const event = server[i];\n\n // `user` events are the question (captured below as\n // interactionQuestion), and `system` events are injected context\n // (schema, instructions) — neither renders as a chat part. The\n // live turn loop never feeds these through merge either; only the\n // persisted log co-locates them under the turn's interactionId.\n const role = llm[i].role?.label?.toLowerCase();\n if (role === 'user' || role === 'system') {\n // The user/system text isn't a chat part (the question is captured as\n // interactionQuestion via firstUserText). But a user turn may carry a client-only\n // UI representation — a UserUiContent that ServerEvent mapped to a UserAnswer part —\n // which must re-hydrate on reload. Push those; drop everything else on this event.\n if (role === 'user') {\n for (const part of event.parts) {\n if (part.eventType === EventType.UserAnswer) pushPart(part);\n }\n }\n continue;\n }\n\n // Artifacts: dedupe by id, last write wins (same as the live merge).\n if (event.llmArtifacts && event.llmArtifacts.length > 0) {\n for (const llmArtifact of event.llmArtifacts) {\n const artifact = llmArtifact.toArtifact();\n const i = artifactData.findIndex(a => a.id === artifact.id);\n if (i === -1) artifactData.push(artifact);\n else artifactData[i] = artifact;\n }\n }\n\n // The model's reasoning trace for this step lives in the event's\n // metadata (dropped by typedjson — read from raw). It rides the\n // event's text item, so attach it to the first text part: a\n // non-empty answer keeps its body and carries the trace in the\n // thinking strip; an empty \"thinking-only\" step becomes a Thought.\n const reasoning = extractReasoning(raw[i]);\n let reasoningUsed = false;\n\n for (const part of event.parts) {\n const callId = part.functionDetails?.id;\n\n // A response folds onto its matching call rather than becoming\n // a separate part.\n if (part.eventType === EventType.FunctionResponse && callId && callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n parts[idx] = foldResponseIntoCall(parts[idx], part);\n continue;\n }\n\n // A client-only output sibling folds its payload onto the call it belongs to\n // (never a separate part). This is the persisted/replay counterpart of the live\n // StreamingFinalFunctionResultContent.clientOutput; a uiTool renderer reads it.\n if (part.eventType === EventType.FunctionClientOutput && callId) {\n if (callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n const prev = parts[idx];\n parts[idx] = {\n ...prev,\n functionDetails: {\n ...prev.functionDetails!,\n clientOutput: part.functionDetails?.clientOutput,\n },\n };\n }\n // No matching call (shouldn't happen — the call precedes its Tool message):\n // drop it rather than render a standalone part.\n continue;\n }\n\n // A repeated full call for an id we've already seen (e.g. a\n // full FunctionCall following a PartialFunctionCall) updates the\n // existing part in place instead of duplicating it.\n if (isFunctionCallType(part.eventType) && callId && callIndex.has(callId)) {\n const idx = callIndex.get(callId)!;\n const prev = parts[idx];\n parts[idx] = {\n ...prev,\n eventType: part.eventType,\n functionDetails: { ...prev.functionDetails!, ...part.functionDetails! },\n };\n continue;\n }\n\n if (part.eventType === EventType.Text) {\n const hasText = !!part.text && part.text.length > 0;\n const attachReasoning = !!reasoning && !reasoningUsed;\n\n // Empty text with no reasoning to carry is a bare\n // placeholder — the consolidated log emits these alongside\n // function calls; dropping them keeps the timeline clean.\n if (!hasText && !attachReasoning && !part.thoughtDetails) {\n continue;\n }\n\n if (attachReasoning) {\n pushPart({\n ...part,\n eventType: hasText ? EventType.Text : EventType.Thought,\n thoughtDetails: { text: reasoning! },\n });\n reasoningUsed = true;\n continue;\n }\n\n pushPart(part);\n continue;\n }\n\n const idx = pushPart(part);\n if (isFunctionCallType(part.eventType) && callId) {\n callIndex.set(callId, idx);\n }\n }\n\n // Reasoning with no text item to ride on (rare) — surface it so\n // the trace isn't silently lost.\n if (reasoning && !reasoningUsed) {\n pushPart({\n id: '', author: event.author, eventType: EventType.Thought,\n created: event.created, partial: false, isStillWriting: false,\n mustPush: false, textAppendable: false,\n thoughtDetails: { text: reasoning },\n });\n }\n }\n\n const functionMap = new Map<string, InteractionPart>();\n for (const [callId, idx] of callIndex) functionMap.set(callId, parts[idx]);\n\n interactions.push({\n created: server[0]?.created ?? new Date(),\n interactionId,\n artifactData,\n partial: false,\n turn_complete: true,\n parts,\n version: server.length,\n functionMap,\n interactionQuestion: firstUserText(llm) ?? '',\n });\n }\n\n return interactions;\n}\n","import { ChatSession, Customer, decodeSessionEvents, Interaction, ISessionService } from \"..\";\n\n/**\n * Wire shape returned by `GET /sessions` and the `.header` of `GET /sessions/{id}`.\n * Mirrors `Envision.SemanticKernel.Models.Session.SessionHeader` on the C#\n * side after the default camelCase rename ASP.NET Core applies on serialize.\n */\ninterface SessionHeaderWire {\n id: string;\n created?: string | null;\n updatedAt?: string | null;\n user?: ChatSession['user'];\n customer?: ChatSession['customer'];\n overview?: string | null;\n agentType?: ChatSession['agentType'];\n userDescription?: string | null;\n lastQuestion?: string | null;\n activityCount?: number;\n lastGeneratedOverview?: string | null;\n artifacts?: string[];\n}\n\ninterface SessionDetailWire {\n header: SessionHeaderWire;\n events: unknown[];\n}\n\nfunction headerToChatSession(h: SessionHeaderWire, interactions: Interaction[] = []): ChatSession {\n return {\n id: h.id,\n browserScopeId: h.id,\n fullyLoaded: interactions.length > 0,\n interactions,\n artifacts: h.artifacts ?? [],\n overview: h.overview ?? '',\n agentType: h.agentType as ChatSession['agentType'],\n userDescription: h.userDescription ?? undefined,\n lastQuestion: h.lastQuestion ?? undefined,\n customer: h.customer ?? null,\n activityCount: h.activityCount ?? 0,\n user: h.user as ChatSession['user'],\n lastGeneratedOverview: h.lastGeneratedOverview ? new Date(h.lastGeneratedOverview) : null,\n sessionRunMode: 'normal' as ChatSession['sessionRunMode'],\n created: h.created ? new Date(h.created) : undefined,\n updatedAt: h.updatedAt ? new Date(h.updatedAt) : undefined,\n } as ChatSession;\n}\n\n/**\n * Minimal ISessionService over the WSServer's REST `/sessions` endpoints.\n *\n * Reads from the unified `Sessions` collection. The list endpoint returns\n * header projections; the detail endpoint returns header + the raw\n * `LlmEvent[]` log which we replay through `decodeSessionEvents` to rebuild\n * the chat UI's `Interaction[]`. Mutation methods are no-ops — write paths\n * are exercised by the live agent turn loop and the WS connection, not by\n * REST calls from the picker.\n */\nexport class HttpSessionService implements ISessionService {\n private serverBaseUrl: string;\n private accessToken: string;\n\n constructor(serverBaseUrl: string, accessToken: string) {\n this.serverBaseUrl = serverBaseUrl.replace(/\\/$/, '');\n this.accessToken = accessToken;\n }\n\n private get headers(): HeadersInit {\n return {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.accessToken}`,\n };\n }\n\n async getAllSessions(): Promise<ChatSession[]> {\n const r = await fetch(`${this.serverBaseUrl}/sessions?top=50`, {\n headers: this.headers,\n });\n if (!r.ok) throw new Error(`getAllSessions HTTP ${r.status}`);\n const headers = (await r.json()) as SessionHeaderWire[];\n return headers.map(h => headerToChatSession(h));\n }\n\n async retrieveSession(sessionId: string): Promise<ChatSession | null> {\n const r = await fetch(`${this.serverBaseUrl}/sessions/${sessionId}`, {\n headers: this.headers,\n });\n if (r.status === 404) return null;\n if (!r.ok) throw new Error(`retrieveSession HTTP ${r.status}`);\n const detail = (await r.json()) as SessionDetailWire;\n const interactions = decodeSessionEvents(detail.events ?? []);\n // The decoder doesn't know the sessionId — stamp it now so downstream\n // consumers (artifact loaders, debugging surfaces) can correlate back.\n for (const it of interactions) it.sessionId = detail.header.id;\n return headerToChatSession(detail.header, interactions);\n }\n\n async getLastUsedSession(): Promise<ChatSession | null> {\n const all = await this.getAllSessions();\n return all[0] ?? null;\n }\n\n // — Most write paths are inert: after the dual-collection collapse the\n // server populates Session UI-header fields automatically during the turn.\n // The two exceptions are rename (`patchSession` → PATCH /Session/Overview)\n // and delete (`removeSession` → DELETE /Session/{id}), which are driven by\n // the picker UI and have no WS-side equivalent. —\n\n async removeSession(sessionId: string): Promise<void> {\n const r = await fetch(`${this.serverBaseUrl}/Session/${encodeURIComponent(sessionId)}`, {\n method: 'DELETE',\n headers: this.headers,\n });\n if (!r.ok) throw new Error(`removeSession HTTP ${r.status}`);\n }\n async createSession(_sessionId: string, _agentName: string, _customer?: Customer): Promise<ChatSession | null> { return null; }\n async createAgentSession(): Promise<any> { return { sessionId: null }; }\n async closeSession(_sessionId: string): Promise<void> { /* no-op */ }\n async generateOverviewForCurrentSession(_sys: string, _model: string): Promise<string | null> { return null; }\n async storeSession(session: ChatSession): Promise<any> { return { data: session }; }\n async patchSession(sessionId: string, partial: Partial<ChatSession>): Promise<void> {\n // SessionController.PatchOverview binds sessionId/overview from the\n // query string (no body, no route params). Anything else on `partial`\n // has no server-side endpoint yet — ignore it instead of guessing.\n if (partial.overview == null) return;\n const url =\n `${this.serverBaseUrl}/Session/Overview` +\n `?sessionId=${encodeURIComponent(sessionId)}` +\n `&overview=${encodeURIComponent(partial.overview)}`;\n const r = await fetch(url, { method: 'PATCH', headers: this.headers });\n if (!r.ok) throw new Error(`patchSession HTTP ${r.status}`);\n }\n delayedPatchActiveSession(_partial: Partial<ChatSession>): void { /* no-op */ }\n\n async patchActiveSession(_partial: Partial<ChatSession>): Promise<ChatSession | null> {\n return Promise.resolve(null);\n }\n async getLlmSessionInformation(): Promise<any> { return { id: null, instructionSummaries: [] }; }\n transformIntoInstances(session: ChatSession): ChatSession { return session; }\n}\n"],"names":["stripMongoDbDiscriminator","raw","obj","_drop","rest","__name","firstUserText","events","e","_b","_a","item","_d","_c","p","REASONING_METADATA_KEY","extractReasoning","rawEvent","content","fromContent","r","isFunctionCallType","EventType","foldResponseIntoCall","call","response","_e","decodeSessionEvents","rawEvents","serializer","createEventSerializer","order","grouped","stripped","llmEvent","serverEvent","ServerEvent","key","bucket","interactions","interactionId","llm","server","parts","artifactData","callIndex","pushPart","part","stamped","i","event","role","llmArtifact","artifact","a","reasoning","reasoningUsed","callId","idx","prev","hasText","attachReasoning","functionMap","headerToChatSession","h","_HttpSessionService","serverBaseUrl","accessToken","__publicField","sessionId","detail","it","_sessionId","_agentName","_customer","_sys","_model","session","partial","url","_partial","HttpSessionService"],"mappings":";;;;;;;AAgBA,SAASA,EAA0BC,GAAuB;AACtD,MAAIA,MAAQ,QAAQ,OAAOA,KAAQ,SAAU,QAAOA;AACpD,QAAMC,IAAMD;AACZ,MAAIC,EAAI,UAAa,gBAAgB;AACjC,UAAM,EAAE,CAAC,OAAO,GAAGC,GAAO,GAAGC,MAASF;AACtC,WAAOE;AAAA,EACX;AACA,SAAOF;AACX;AARSG,EAAAL,GAAA;AAUT,SAASM,EAAcC,GAAwC;;AAC3D,aAAWC,KAAKD,GAAQ;AACpB,UAAIE,KAAAC,IAAAF,EAAE,SAAF,gBAAAE,EAAQ,UAAR,gBAAAD,EAAe,mBAAkB,OAAQ;AAC7C,UAAME,KAAOC,KAAAC,IAAAL,EAAE,YAAF,gBAAAK,EAAW,UAAX,gBAAAD,EAAkB,KAAK,CAAAE,MAAK,UAAUA,KAAK,OAAQA,EAA8B,QAAS;AACvG,QAAIH,UAAcA,EAA2B;AAAA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AE,GAAI,OAAM,IAAI,MAAM,sBAAsBA,EAAE,MAAM,EAAE;AAAA,EAC/D;AAAA,EACA,MAAM,cAAcoD,GAAoBC,GAAoBC,GAAmD;AAAE,WAAO;AAAA,EAAM;AAAA,EAC9H,MAAM,qBAAmC;AAAE,WAAO,EAAE,WAAW,KAAA;AAAA,EAAQ;AAAA,EACvE,MAAM,aAAaF,GAAmC;AAAA,EAAc;AAAA,EACpE,MAAM,kCAAkCG,GAAcC,GAAwC;AAAE,WAAO;AAAA,EAAM;AAAA,EAC7G,MAAM,aAAaC,GAAoC;AAAE,WAAO,EAAE,MAAMA,EAAA;AAAA,EAAW;AAAA,EACnF,MAAM,aAAaR,GAAmBS,GAA8C;AAIhF,QAAIA,EAAQ,YAAY,KAAM;AAC9B,UAAMC,IACF,GAAG,KAAK,aAAa,+BACP,mBAAmBV,CAAS,CAAC,aAC9B,mBAAmBS,EAAQ,QAAQ,CAAC,IAC/C1D,IAAI,MAAM,MAAM2D,GAAK,EAAE,QAAQ,SAAS,SAAS,KAAK,SAAS;AACrE,QAAI,CAAC3D,EAAE,GAAI,OAAM,IAAI,MAAM,qBAAqBA,EAAE,MAAM,EAAE;AAAA,EAC9D;AAAA,EACA,0BAA0B4D,GAAsC;AAAA,EAAc;AAAA,EAE9E,MAAM,mBAAmBA,GAA6D;AAClF,WAAO,QAAQ,QAAQ,IAAI;AAAA,EAC/B;AAAA,EACA,MAAM,2BAAyC;AAAE,WAAO,EAAE,IAAI,MAAM,sBAAsB,CAAA,EAAC;AAAA,EAAK;AAAA,EAChG,uBAAuBH,GAAmC;AAAE,WAAOA;AAAA,EAAS;AAChF;AAjF2DxE,EAAA4D,GAAA;AAApD,IAAMgB,IAANhB;"}
package/dist/index.js CHANGED
@@ -1,17 +1,17 @@
1
1
  import "reflect-metadata";
2
- import { C as s, F as o, a as n, I as r, L as i, S as c, b as l, c as S, d as p, e as A, T as C, f as d, g, h as I, i as v, s as E, j as h } from "./serializer-BZjKrhXT.js";
2
+ import { C as s, F as o, a as n, I as r, L as i, S as c, b as l, c as S, d as p, e as A, T as C, f as d, g, h as I, i as v, s as E, j as h } from "./serializer-DTyYgExG.js";
3
3
  import { A as T, a as u, C as L, M as x, b as P, S as f, i as R } from "./Memory-DjLZqgbF.js";
4
4
  import { C as U, C as y } from "./ClientMessage-EKgfuTp8.js";
5
5
  import { C as D, P as B } from "./Prompt-DZb7OaPp.js";
6
6
  import { A as F, a as b, b as k, c as N, d as H, e as G, C as O, f as W, D as w, E as z, g as J, G as j, h as q, M as K, i as X, R as Y, j as Q, S as Z, l as $, m as ee, n as ae, o as te, p as se, q as oe, r as ne, s as re, t as ie, u as ce } from "./environmentUtils-CUVZ6Dq1.js";
7
- import { A as Se, a as pe, E as Ae, H as Ce, I as de, L as ge, W as Ie } from "./httpArtifactService-COu1QCBJ.js";
7
+ import { A as Se, a as pe, E as Ae, H as Ce, I as de, L as ge, W as Ie } from "./httpArtifactService-RtW5tek8.js";
8
8
  import { A as Ee } from "./artifactHtmlHandler-CMQJf1cX.js";
9
- import { H as me, d as Te } from "./httpSessionService-B_G3Ej2C.js";
9
+ import { H as me, d as Te } from "./httpSessionService-BO81zAcx.js";
10
10
  import { APPBAR_V2_HEIGHT as Le, AgentActivityV2 as xe, AiChat as Pe, AiChatDrawer as fe, AiChatFloating as Re, AiChatFloatingV2 as Me, AiChatProvider as Ue, AiChatServiceContext as ye, AiChatV2Pane as _e, AppBarV2 as De, AppRailV2 as Be, AppShellV2 as Ve, ArtifactRender as Fe, BoxedPart as be, BrainIcon as ke, ChartIcon as Ne, ChatIcon as He, ChatPane as Ge, ChatsHistoryV2 as Oe, CheckIcon as We, ChevronIcon as we, ChevronRightIcon as ze, CloseIcon as Je, CodeIcon as je, ComposerIcon as qe, DEFAULT_PART_RENDERERS as Ke, DashboardIcon as Xe, DataExplorerIcon as Ye, DelayTextComponent as Qe, EnvironmentProvider as Ze, FileIcon as $e, FunctionPart as ea, GlobeIcon as aa, HistoryIcon as ta, IDLE_TIMEOUT as sa, InertEnvironmentProvider as oa, JsxErrorBoundary as na, LIVE_TSX_DEFAULT_MAX_CHARS_FOR_FULL as ra, LastPromptsV2 as ia, LinearBackgroundProgress as ca, LinearProgressBarWithMarkers as la, ListCheckIcon as Sa, LiveJsxBlock as pa, LiveTsxConfigProvider as Aa, LlmResponseRender as Ca, LoadingDots as da, LockClosedIcon as ga, LockOpenIcon as Ia, MOBILE_NAV_DEFAULT as va, MarkdownExtended as Ea, MenuIcon as ha, Message as ma, MobileDrawerV2 as Ta, PanelIcon as ua, PauseIcon as La, PinIcon as xa, PlusIcon as Pa, PromptDateMarkers as fa, PromptV2 as Ra, RunProgressPanelV2 as Ma, RunProgressStripV2 as Ua, SearchIcon as ya, SendIcon as _a, SessionStateManagerService as Da, SparkleIcon as Ba, Sparkline as Va, StopIcon as Fa, Stopwatch as ba, SubAgentBox as ka, SubAgentBoxV2 as Na, SuspendedPart as Ha, TableIcon as Ga, TaskListV2 as Oa, TerminalIcon as Wa, TextPart as wa, ThoughtPart as za, ToolIcon as Ja, TrashIcon as ja, UiToolDispatcher as qa, UsersIcon as Ka, V2_CHART_PALETTE as Xa, WARNING_THRESHOLD as Ya, WaitingPart as Qa, classifyPart as Za, configureFriendlyMapping as $a, createAiChatSessionStore as et, createAiChatSessionStore as at, createUiToolRegistry as tt, extendDefaultScope as st, extendModuleRegistry as ot, getDefaultJsxScope as nt, getFriendlyLabel as rt, parseClientOutput as it, parseContentBlocks as ct, parseUiArgs as lt, useAiChatServices as St, useAiChatSessionStore as pt, useEnvironment as At, useEnvironmentOptional as Ct, useLiveTsxMaxCharsForFull as dt, useResponsiveLayout as gt, v2Card as It, v2Chip as vt, v2IconBtn as Et, v2MonoMeta as ht, v2SectionLabel as mt, v2Theme as Tt } from "./components.js";
11
11
  import { u as Lt, a as xt, b as Pt, c as ft } from "./useContainerWidth-D0CQQqZ2.js";
12
12
  import { A as Mt, a as Ut, b as yt, G as _t, d as Dt, c as Bt, e as Vt, f as Ft, g as bt, h as kt, i as Nt, j as Ht, k as Gt, l as Ot, m as Wt, n as wt, o as zt, p as Jt, q as jt, r as qt, s as Kt, t as Xt, u as Yt, v as Qt } from "./auth-BN22f1HF.js";
13
13
  import { S as $t, c as es, a as as, e as ts, b as ss, f as os, i as ns, d as rs, p as is, g as cs, s as ls, k as Ss, t as ps } from "./atMentions-DqhG_vde.js";
14
- import { u as Cs } from "./useChatSessions-D5y5kCID.js";
14
+ import { u as Cs } from "./useChatSessions-C9IQGLh_.js";
15
15
  import { Score as gs } from "./interfaces.js";
16
16
  export {
17
17
  Mt as ALLOWED_DOMAINS,
package/dist/models.js CHANGED
@@ -1,4 +1,4 @@
1
- import { C as a, F as s, a as n, I as o, L as i, S as r, b as C, c as l, d as p, e as S, T as g, f as m, g as T, h as c, i as y, s as E, j as d } from "./serializer-BZjKrhXT.js";
1
+ import { C as a, F as s, a as n, I as o, L as i, S as r, b as C, c as l, d as p, e as S, T as g, f as m, g as T, h as c, i as y, s as E, j as d } from "./serializer-DTyYgExG.js";
2
2
  import { A as M, a as v, C as f, M as u, b as x, S as h, i as R } from "./Memory-DjLZqgbF.js";
3
3
  import { C as F, C as U } from "./ClientMessage-EKgfuTp8.js";
4
4
  import { C as L, P as N } from "./Prompt-DZb7OaPp.js";
@@ -2,8 +2,8 @@ var wt = Object.defineProperty;
2
2
  var Jt = (s, t, i) => t in s ? wt(s, t, { enumerable: !0, configurable: !0, writable: !0, value: i }) : s[t] = i;
3
3
  var l = (s, t) => wt(s, "name", { value: t, configurable: !0 });
4
4
  var e = (s, t, i) => Jt(s, typeof t != "symbol" ? t + "" : t, i);
5
- import { E as m, q as Et, A as Wt, G as $t } from "./environmentUtils-CUVZ6Dq1.js";
6
- import { jsonMember as o, jsonObject as d, AnyT as Ft, jsonArrayMember as ft, TypedJSON as Pt } from "typedjson";
5
+ import { E as m, q as Ft, A as Wt, G as $t } from "./environmentUtils-CUVZ6Dq1.js";
6
+ import { jsonMember as o, jsonObject as d, AnyT as It, jsonArrayMember as ft, TypedJSON as vt } from "typedjson";
7
7
  const w = class w {
8
8
  static replaceFirstTwoTabsPerLine(t) {
9
9
  const i = /^\s{15}/gm;
@@ -96,7 +96,7 @@ const w = class w {
96
96
  return {
97
97
  text: t,
98
98
  eventType: m.Text,
99
- id: r ?? Et(),
99
+ id: r ?? Ft(),
100
100
  created: /* @__PURE__ */ new Date(),
101
101
  author: i ?? "main",
102
102
  partial: !1,
@@ -113,7 +113,7 @@ const w = class w {
113
113
  */
114
114
  static fromUserUi(t, i, r) {
115
115
  return {
116
- id: r ?? Et(),
116
+ id: r ?? Ft(),
117
117
  eventType: m.UserAnswer,
118
118
  author: "user",
119
119
  created: /* @__PURE__ */ new Date(),
@@ -290,7 +290,7 @@ n([
290
290
  o(String)
291
291
  ], h.prototype, "modelId", 2);
292
292
  n([
293
- o(Ft)
293
+ o(It)
294
294
  ], h.prototype, "metadata", 2);
295
295
  h = n([
296
296
  d({ name: "KernelContent" })
@@ -339,7 +339,7 @@ xt = n([
339
339
  d({ name: "TextContent" })
340
340
  ], xt);
341
341
  var M;
342
- let P = (M = class extends C {
342
+ let v = (M = class extends C {
343
343
  constructor() {
344
344
  super();
345
345
  e(this, "eventName");
@@ -349,18 +349,18 @@ let P = (M = class extends C {
349
349
  }, l(M, "StreamingToolEventContent"), M);
350
350
  n([
351
351
  o(String)
352
- ], P.prototype, "eventName", 2);
352
+ ], v.prototype, "eventName", 2);
353
353
  n([
354
354
  o(String)
355
- ], P.prototype, "eventData", 2);
355
+ ], v.prototype, "eventData", 2);
356
356
  n([
357
357
  o(String)
358
- ], P.prototype, "sessionId", 2);
359
- P = n([
358
+ ], v.prototype, "sessionId", 2);
359
+ v = n([
360
360
  d({ name: "StreamingToolEventContent" })
361
- ], P);
361
+ ], v);
362
362
  var B;
363
- let v = (B = class extends h {
363
+ let P = (B = class extends h {
364
364
  constructor() {
365
365
  super();
366
366
  e(this, "eventName");
@@ -370,16 +370,16 @@ let v = (B = class extends h {
370
370
  }, l(B, "ToolEventContent"), B);
371
371
  n([
372
372
  o(String)
373
- ], v.prototype, "eventName", 2);
373
+ ], P.prototype, "eventName", 2);
374
374
  n([
375
375
  o(String)
376
- ], v.prototype, "eventData", 2);
376
+ ], P.prototype, "eventData", 2);
377
377
  n([
378
378
  o(String)
379
- ], v.prototype, "sessionId", 2);
380
- v = n([
379
+ ], P.prototype, "sessionId", 2);
380
+ P = n([
381
381
  d({ name: "ToolEventContent" })
382
- ], v);
382
+ ], P);
383
383
  var K;
384
384
  let ht = (K = class extends h {
385
385
  constructor() {
@@ -419,7 +419,7 @@ n([
419
419
  o(String)
420
420
  ], A.prototype, "functionName", 2);
421
421
  n([
422
- o(Ft)
422
+ o(It)
423
423
  ], A.prototype, "arguments", 2);
424
424
  A = n([
425
425
  d({ name: "FunctionCallContent" })
@@ -490,7 +490,7 @@ n([
490
490
  o(String)
491
491
  ], U.prototype, "functionName", 2);
492
492
  n([
493
- o(Ft)
493
+ o(It)
494
494
  ], U.prototype, "result", 2);
495
495
  U = n([
496
496
  d({ name: "FunctionResultContent" })
@@ -517,7 +517,7 @@ n([
517
517
  o(String)
518
518
  ], I.prototype, "functionName", 2);
519
519
  n([
520
- o(Ft)
520
+ o(It)
521
521
  ], I.prototype, "result", 2);
522
522
  n([
523
523
  o(k)
@@ -892,7 +892,9 @@ function Bt(s) {
892
892
  return {
893
893
  isUi: r("isUi", "IsUi") === !0,
894
894
  askUserComponent: r("askUserComponent", "AskUserComponent") || void 0,
895
- argsDescription: r("argsDescription", "ArgsDescription") || void 0
895
+ argsDescription: r("argsDescription", "ArgsDescription") || void 0,
896
+ // Runtime override on a RESULT: the UI tool chose not to render (CallContext.CancelUiRender).
897
+ cancelUi: r("cancelUi", "CancelUi") === !0 || void 0
896
898
  };
897
899
  }
898
900
  l(Bt, "readPresentation");
@@ -970,7 +972,7 @@ const N = class N {
970
972
  return i.mimeType = t.mimeType, i.created = new Date(t.timestamp), i.eventType = m.NotDefined, i.partial = ((p = (a = t.partial) == null ? void 0 : a.toString()) == null ? void 0 : p.toLowerCase()) === "true", i.turn_complete = t.turnComplete, i.visible = t.visible, i.isFinalResponse = t.turnComplete ?? !1, i.artifactsDelta = [], t.artifactsGenerated && t.artifactsGenerated.length > 0 && (i.created = new Date(t.timestamp), i.llmArtifacts = t.artifactsGenerated), i.subAgentId = t.subAgentId, i.subAgentName = t.subAgentName, i;
971
973
  }
972
974
  static getPartType(t) {
973
- return t instanceof xt ? "TextContent" : t instanceof A ? "FunctionCallContent" : t instanceof U ? "FunctionResultContent" : t instanceof O ? "StreamingFunctionCallUpdateContent" : t instanceof b ? "StreamingFinalFunctionCallContent" : t instanceof I ? "StreamingFinalFunctionResultContent" : t instanceof mt ? "FunctionClientOutputContent" : t instanceof gt ? "StreamingClientOutputContent" : t instanceof dt ? "UserUiContent" : t instanceof Ct ? "StreamingTextContent" : t instanceof Dt ? "StreamingReasoningContent" : t instanceof v ? "ToolEventContent" : t instanceof P ? "StreamingToolEventContent" : "Unknown";
975
+ return t instanceof xt ? "TextContent" : t instanceof A ? "FunctionCallContent" : t instanceof U ? "FunctionResultContent" : t instanceof O ? "StreamingFunctionCallUpdateContent" : t instanceof b ? "StreamingFinalFunctionCallContent" : t instanceof I ? "StreamingFinalFunctionResultContent" : t instanceof mt ? "FunctionClientOutputContent" : t instanceof gt ? "StreamingClientOutputContent" : t instanceof dt ? "UserUiContent" : t instanceof Ct ? "StreamingTextContent" : t instanceof Dt ? "StreamingReasoningContent" : t instanceof P ? "ToolEventContent" : t instanceof v ? "StreamingToolEventContent" : "Unknown";
974
976
  }
975
977
  static parseFromTypedEvent(t) {
976
978
  var p, c, g, _, bt, Ut, Ot;
@@ -1019,7 +1021,7 @@ const N = class N {
1019
1021
  u.thoughtDetails = {
1020
1022
  text: ""
1021
1023
  };
1022
- const It = Bt(a);
1024
+ const Et = Bt(a);
1023
1025
  u.functionDetails = {
1024
1026
  id: (a == null ? void 0 : a.id) ?? "",
1025
1027
  args: a == null ? void 0 : a.arguments,
@@ -1029,13 +1031,15 @@ const N = class N {
1029
1031
  name: (a == null ? void 0 : a.functionName) ?? "",
1030
1032
  status: u.eventType == m.FunctionCall ? "Executing" : "Done",
1031
1033
  response: y,
1032
- isUi: It.isUi,
1033
- argsDescription: It.argsDescription,
1034
+ isUi: Et.isUi,
1035
+ argsDescription: Et.argsDescription,
1034
1036
  // Client-only payload riding the RESULT event: live top-level `clientOutput`, or
1035
1037
  // metadata.clientOutput on the collapsed/persisted result. Calls leave it undefined.
1036
1038
  // The persisted-replay form also folds in via FunctionClientOutputContent.
1037
1039
  clientOutput: (a == null ? void 0 : a.clientOutput) ?? ((g = a == null ? void 0 : a.metadata) == null ? void 0 : g.clientOutput),
1038
- askUserComponent: It.askUserComponent
1040
+ askUserComponent: Et.askUserComponent,
1041
+ // Runtime "don't render" override on a RESULT (CallContext.CancelUiRender).
1042
+ cancelUi: Et.cancelUi
1039
1043
  }, u.functionDetails.isAskUser = !!u.functionDetails.askUserComponent, t.text = a == null ? void 0 : a.arguments;
1040
1044
  }
1041
1045
  } else if (T == x.StreamingTextContent)
@@ -1123,7 +1127,7 @@ const N = class N {
1123
1127
  thoughtDetails: {
1124
1128
  text: i
1125
1129
  },
1126
- id: Et(),
1130
+ id: Ft(),
1127
1131
  created: /* @__PURE__ */ new Date(),
1128
1132
  eventType: m.Thought,
1129
1133
  author: "main",
@@ -1171,7 +1175,7 @@ const N = class N {
1171
1175
  thoughtDetails: r ? {
1172
1176
  text: r
1173
1177
  } : void 0,
1174
- id: Et(),
1178
+ id: Ft(),
1175
1179
  created: /* @__PURE__ */ new Date(),
1176
1180
  // Part eventType MUST match the outer event's eventType.
1177
1181
  // Was previously `Thought` here, which made the merger
@@ -1193,12 +1197,12 @@ const N = class N {
1193
1197
  };
1194
1198
  l(N, "ServerEvent");
1195
1199
  let Rt = N;
1196
- const vt = [
1200
+ const Pt = [
1197
1201
  // KernelContent derived types
1198
1202
  xt,
1199
1203
  ht,
1200
1204
  A,
1201
- v,
1205
+ P,
1202
1206
  U,
1203
1207
  mt,
1204
1208
  dt,
@@ -1207,7 +1211,7 @@ const vt = [
1207
1211
  Ct,
1208
1212
  O,
1209
1213
  Dt,
1210
- P,
1214
+ v,
1211
1215
  b,
1212
1216
  I,
1213
1217
  gt,
@@ -1227,18 +1231,18 @@ function zt(s, t) {
1227
1231
  }
1228
1232
  l(zt, "dotnetTypeResolver");
1229
1233
  function _t() {
1230
- const s = new Pt(S);
1234
+ const s = new vt(S);
1231
1235
  return s.config({
1232
- knownTypes: vt,
1236
+ knownTypes: Pt,
1233
1237
  typeHintEmitter: kt,
1234
1238
  typeResolver: zt
1235
1239
  }), s;
1236
1240
  }
1237
1241
  l(_t, "createEventSerializer");
1238
1242
  function Ht() {
1239
- const s = new Pt(F);
1243
+ const s = new vt(F);
1240
1244
  return s.config({
1241
- knownTypes: vt,
1245
+ knownTypes: Pt,
1242
1246
  typeHintEmitter: kt,
1243
1247
  typeResolver: zt
1244
1248
  }), s;
@@ -1335,4 +1339,4 @@ export {
1335
1339
  jt as j,
1336
1340
  Lt as s
1337
1341
  };
1338
- //# sourceMappingURL=serializer-BZjKrhXT.js.map
1342
+ //# sourceMappingURL=serializer-DTyYgExG.js.map