@copilotkit/angular 0.5.3 → 0.6.0

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,6 +1,6 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, DestroyRef, Injectable, effect, untracked, input, signal, computed, ChangeDetectionStrategy, Component, PLATFORM_ID, NgZone, reflectComponentType, inputBinding, outputBinding, TemplateRef, viewChild, ViewContainerRef, output, ElementRef, afterRenderEffect, isDevMode, Injector, afterNextRender, runInInjectionContext, Input, Inject, Directive, HostListener, ViewChild, ViewEncapsulation, ContentChild, Optional, linkedSignal, ChangeDetectorRef, contentChild, forwardRef, Renderer2, EventEmitter, Output, CUSTOM_ELEMENTS_SCHEMA, model } from '@angular/core';
3
- import { CopilotKitCoreRuntimeConnectionStatus, CopilotKitCore, ɵInterruptState as _InterruptState, ProxiedCopilotRuntimeAgent, ɵcreateThreadStore as _createThreadStore, ɵselectThreads as _selectThreads, ɵselectThreadsIsLoading as _selectThreadsIsLoading, ɵselectThreadsError as _selectThreadsError, ɵselectFetchMoreError as _selectFetchMoreError, ɵselectHasNextPage as _selectHasNextPage, ɵselectIsFetchingNextPage as _selectIsFetchingNextPage, ɵselectIsMutating as _selectIsMutating, ɵselectMemories as _selectMemories, ɵselectMemoriesIsLoading as _selectMemoriesIsLoading, ɵselectMemoriesError as _selectMemoriesError, ɵselectMemoriesAvailable as _selectMemoriesAvailable, ɵselectMemoriesRealtimeStatus as _selectMemoriesRealtimeStatus, completePartialMarkdown, ɵisHttpAgent as _isHttpAgent, isRunCompletionAware } from '@copilotkit/core';
2
+ import { InjectionToken, inject, DestroyRef, Injectable, effect, untracked, input, signal, computed, ChangeDetectionStrategy, Component, PLATFORM_ID, NgZone, reflectComponentType, inputBinding, outputBinding, TemplateRef, viewChild, ViewContainerRef, output, ElementRef, afterRenderEffect, isDevMode, Injector, afterNextRender, runInInjectionContext, Input, Inject, Directive, HostListener, ApplicationRef, EnvironmentInjector, createComponent, ViewEncapsulation, ContentChild, Optional, linkedSignal, ChangeDetectorRef, ViewChild, contentChild, forwardRef, Renderer2, EventEmitter, Output, CUSTOM_ELEMENTS_SCHEMA, model } from '@angular/core';
3
+ import { CopilotKitCoreRuntimeConnectionStatus, ɵwithHeaderDefaults as _withHeaderDefaults, CopilotKitCore, ɵInterruptState as _InterruptState, ProxiedCopilotRuntimeAgent, ɵcreateThreadStore as _createThreadStore, ɵselectThreads as _selectThreads, ɵselectThreadsIsLoading as _selectThreadsIsLoading, ɵselectThreadsError as _selectThreadsError, ɵselectFetchMoreError as _selectFetchMoreError, ɵselectHasNextPage as _selectHasNextPage, ɵselectIsFetchingNextPage as _selectIsFetchingNextPage, ɵselectIsMutating as _selectIsMutating, ɵselectMemories as _selectMemories, ɵselectMemoriesIsLoading as _selectMemoriesIsLoading, ɵselectMemoriesError as _selectMemoriesError, ɵselectMemoriesAvailable as _selectMemoriesAvailable, ɵselectMemoriesRealtimeStatus as _selectMemoriesRealtimeStatus, completePartialMarkdown, ɵisHttpAgent as _isHttpAgent, isRunCompletionAware } from '@copilotkit/core';
4
4
  import { shouldEnableInspector, A2UI_DEFAULT_GENERATION_GUIDELINES, A2UI_DEFAULT_DESIGN_GUIDELINES, GENERATE_SANDBOXED_UI_DESCRIPTION, schemaToJsonSchema, partialJSONParse, DEFAULT_AGENT_ID, randomUUID as randomUUID$1, TranscriptionErrorCode, copyToClipboard, getSourceUrl, getDocumentIcon, createRowKeyStore, resolveRowRenderKeys, commitRowKeyStore, formatFileSize, matchesAcceptFilter, createAttachmentContent, exceedsMaxSize, getModalityFromMimeType, readFileAsBase64, generateVideoThumbnail, createLicenseContextValue } from '@copilotkit/shared';
5
5
  export { GENERATE_SANDBOXED_UI_DESCRIPTION, TranscriptionErrorCode } from '@copilotkit/shared';
6
6
  import { Subject, filter, take, map, lastValueFrom, Observable, takeUntil, BehaviorSubject, merge, fromEvent, animationFrameScheduler, EMPTY } from 'rxjs';
@@ -19,9 +19,9 @@ import { toSignal, toObservable } from '@angular/core/rxjs-interop';
19
19
  import { Overlay, OverlayPositionBuilder, OverlayModule } from '@angular/cdk/overlay';
20
20
  import { ComponentPortal } from '@angular/cdk/portal';
21
21
  import { Marked } from 'marked';
22
- import DOMPurify from 'dompurify';
23
22
  import hljs from 'highlight.js';
24
- import * as katex from 'katex';
23
+ import DOMPurify from 'dompurify';
24
+ import { renderToString } from 'katex';
25
25
  import * as i1$2 from '@angular/cdk/menu';
26
26
  import { CdkMenuModule } from '@angular/cdk/menu';
27
27
  import { defineCopilotKitThreadsDrawer } from '@copilotkit/web-components/threads-drawer';
@@ -91,7 +91,11 @@ function logLicenseWatermarkWarning(message) {
91
91
  ].join("\n"));
92
92
  }
93
93
  function resolveLicense(config) {
94
- const headerKey = config.headers?.[COPILOT_CLOUD_PUBLIC_API_KEY_HEADER];
94
+ // A builder is only evaluated at send time, so it can't be read here. Rely
95
+ // on `licenseKey` in that case (same fallback the record branch already has).
96
+ const headerKey = typeof config.headers === "function"
97
+ ? undefined
98
+ : config.headers?.[COPILOT_CLOUD_PUBLIC_API_KEY_HEADER];
95
99
  const key = config.licenseKey ?? headerKey;
96
100
  if (!key) {
97
101
  return {
@@ -112,28 +116,33 @@ const COPILOT_KIT_CONFIG = new InjectionToken("COPILOT_KIT_CONFIG");
112
116
  function injectCopilotKitConfig() {
113
117
  return inject(COPILOT_KIT_CONFIG);
114
118
  }
119
+ /**
120
+ * The public-key header default `provideCopilotKit` used to merge directly
121
+ * into `config.headers` (main's behavior, record-only). Now that `headers`
122
+ * can be a builder (#1937), the merge can't happen here — a builder is only
123
+ * evaluated at send time — so `copilotkit.ts` applies these defaults itself,
124
+ * via `ɵwithHeaderDefaults`, where `CopilotKitCore` is constructed and
125
+ * wherever `setHeaders` is called. Kept in this file (rather than
126
+ * `copilotkit.ts`) so the license-key condition has one definition, shared
127
+ * with `resolveLicense`'s watermark check below; this function itself stays
128
+ * a plain computation with no `@copilotkit/core` value import.
129
+ */
130
+ function ɵresolvePublicKeyHeaderDefaults(config) {
131
+ const resolvedLicense = resolveLicense(config);
132
+ return !resolvedLicense.valid || !resolvedLicense.key
133
+ ? {}
134
+ : { [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: resolvedLicense.key };
135
+ }
115
136
  function provideCopilotKit(config = {}) {
116
137
  const resolvedLicense = resolveLicense(config);
117
- const headers = config.headers ?? {};
118
138
  if (LICENSE_WATERMARK_ENABLED &&
119
139
  !resolvedLicense.valid &&
120
140
  resolvedLicense.warning) {
121
141
  logLicenseWatermarkWarning(resolvedLicense.warning);
122
142
  }
123
- const mergedHeaders = headers[COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]
124
- ? headers
125
- : !resolvedLicense.valid || !resolvedLicense.key
126
- ? headers
127
- : {
128
- ...headers,
129
- [COPILOT_CLOUD_PUBLIC_API_KEY_HEADER]: resolvedLicense.key,
130
- };
131
143
  return {
132
144
  provide: COPILOT_KIT_CONFIG,
133
- useValue: {
134
- ...config,
135
- headers: mergedHeaders,
136
- },
145
+ useValue: config,
137
146
  };
138
147
  }
139
148
 
@@ -2271,7 +2280,7 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImpor
2271
2280
  const standardSchemaZodToJsonSchema = (schema, options) => zodToJsonSchema(schema, options);
2272
2281
 
2273
2282
  // Generated from package.json. Do not edit.
2274
- const ANGULAR_SDK_VERSION = "0.5.3";
2283
+ const ANGULAR_SDK_VERSION = "0.6.0";
2275
2284
 
2276
2285
  /**
2277
2286
  * Injection token that reports whether the Inspector treats the app as
@@ -2378,7 +2387,28 @@ class CopilotKit {
2378
2387
  runtimeTransport = this.#runtimeTransport.asReadonly();
2379
2388
  #headers = signal({}, /* @ts-ignore */
2380
2389
  ...(ngDevMode ? [{ debugName: "#headers" }] : /* istanbul ignore next */ []));
2390
+ /**
2391
+ * Snapshot as of the last header SOURCE change (a `setHeaders()`/
2392
+ * `updateRuntime({ headers })` call) — not necessarily current for a
2393
+ * builder. It updates from `onHeadersChanged`, which fires only on a real
2394
+ * source change, never on a builder merely resolving a fresh token during a
2395
+ * run. With a builder this can read `{}` (or a stale record) between
2396
+ * source changes even though requests are already carrying the current
2397
+ * token (#1937). For the value a builder would resolve right now, call
2398
+ * `copilotkit.core.resolveHeaders()` instead.
2399
+ */
2381
2400
  headers = this.#headers.asReadonly();
2401
+ #headersGeneration = signal(0, /* @ts-ignore */
2402
+ ...(ngDevMode ? [{ debugName: "#headersGeneration" }] : /* istanbul ignore next */ []));
2403
+ /**
2404
+ * Bumped only when `setHeaders` accepts a real source change (a new
2405
+ * builder identity, or a record whose normalized values actually differ) —
2406
+ * never when a builder merely resolves a new token. Set from
2407
+ * `onHeadersChanged`, which fires only from a real `setHeaders()` call, so
2408
+ * subscribers can key thread-context dispatch and agent header refresh on
2409
+ * this signal instead of on header VALUES (see #1937).
2410
+ */
2411
+ ɵheadersGeneration = this.#headersGeneration.asReadonly();
2382
2412
  #credentials = signal(undefined, /* @ts-ignore */
2383
2413
  ...(ngDevMode ? [{ debugName: "#credentials" }] : /* istanbul ignore next */ []));
2384
2414
  credentials = this.#credentials.asReadonly();
@@ -2435,9 +2465,27 @@ class CopilotKit {
2435
2465
  #suggestionsByAgent = signal({}, /* @ts-ignore */
2436
2466
  ...(ngDevMode ? [{ debugName: "#suggestionsByAgent" }] : /* istanbul ignore next */ []));
2437
2467
  suggestionsByAgent = this.#suggestionsByAgent.asReadonly();
2468
+ /**
2469
+ * The public-key header default, computed once from this instance's config
2470
+ * (license key / already-present header, see `resolveLicense` in
2471
+ * `config.ts`).
2472
+ */
2473
+ #publicKeyDefaults = ɵresolvePublicKeyHeaderDefaults(this.#config);
2474
+ // `ɵwithHeaderDefaults` returns a new function for a function source on
2475
+ // every call. Remember the last source and its wrapper, so passing the same
2476
+ // builder again hands core the same function and stays a no-op (#1937).
2477
+ #lastHeadersSource;
2478
+ #lastWrappedHeaders;
2479
+ #withPublicKeyDefaults(source) {
2480
+ if (source !== this.#lastHeadersSource) {
2481
+ this.#lastHeadersSource = source;
2482
+ this.#lastWrappedHeaders = _withHeaderDefaults(source, this.#publicKeyDefaults);
2483
+ }
2484
+ return this.#lastWrappedHeaders;
2485
+ }
2438
2486
  core = new CopilotKitCore({
2439
2487
  runtimeUrl: this.#config.runtimeUrl,
2440
- headers: this.#config.headers,
2488
+ headers: this.#withPublicKeyDefaults(this.#config.headers ?? {}),
2441
2489
  credentials: this.#config.credentials,
2442
2490
  messageFilter: this.#config.messageFilter,
2443
2491
  agents__unsafe_dev_only: {
@@ -2485,11 +2533,16 @@ class CopilotKit {
2485
2533
  #a2UIContextIds = [];
2486
2534
  constructor() {
2487
2535
  void this.#inspector.isInspectorEnabled;
2488
- ensureLicenseWatermark(this.#config.headers);
2536
+ // A builder is only evaluated at send time, so it can't be read here.
2537
+ // The record branch below already has its own key-header fallback.
2538
+ ensureLicenseWatermark(typeof this.#config.headers === "function"
2539
+ ? undefined
2540
+ : this.#config.headers);
2489
2541
  this.#runtimeConnectionStatus.set(this.core.runtimeConnectionStatus);
2490
2542
  this.#runtimeUrl.set(this.core.runtimeUrl);
2491
2543
  this.#runtimeTransport.set(this.core.runtimeTransport);
2492
2544
  this.#headers.set(this.core.headers);
2545
+ this.#headersGeneration.set(this.core.ɵheadersGeneration);
2493
2546
  this.#credentials.set(this.core.credentials);
2494
2547
  this.#threadEndpoints.set(this.core.threadEndpoints);
2495
2548
  this.#audioFileTranscriptionEnabled.set(this.core.audioFileTranscriptionEnabled);
@@ -2551,6 +2604,13 @@ class CopilotKit {
2551
2604
  },
2552
2605
  onHeadersChanged: ({ headers }) => {
2553
2606
  this.#headers.set(headers);
2607
+ // Fires only from a real `setHeaders()` call (a new source), never
2608
+ // from a builder resolving a new token — same generation core bumps.
2609
+ // Without this, nothing pokes Angular's reactivity when a source
2610
+ // change lands: `ɵheadersGeneration` (core's) is a plain property
2611
+ // read, not a signal, so `ɵheadersGeneration`-keyed dependents
2612
+ // (threads.ts, agent.ts) only re-read it when this handler sets ours.
2613
+ this.#headersGeneration.set(this.core.ɵheadersGeneration);
2554
2614
  },
2555
2615
  onSuggestionsChanged: ({ agentId, suggestions }) => {
2556
2616
  this.#setSuggestions(agentId, {
@@ -2825,8 +2885,8 @@ class CopilotKit {
2825
2885
  this.#runtimeTransport.set(options.runtimeTransport);
2826
2886
  }
2827
2887
  if (options.headers !== undefined) {
2828
- this.core.setHeaders(options.headers);
2829
- this.#headers.set(options.headers);
2888
+ this.core.setHeaders(this.#withPublicKeyDefaults(options.headers));
2889
+ this.#headers.set(this.core.headers);
2830
2890
  }
2831
2891
  if ("credentials" in options) {
2832
2892
  this.core.setCredentials(options.credentials);
@@ -3540,9 +3600,6 @@ class InterruptController {
3540
3600
  const missingInterruptRunner = async () => {
3541
3601
  throw new Error("AgentStore.interruptController requires a store created by injectAgentStore().");
3542
3602
  };
3543
- function hasAgentHeaders(agent) {
3544
- return "headers" in agent;
3545
- }
3546
3603
  function hasAgentCredentials(agent) {
3547
3604
  return "credentials" in agent;
3548
3605
  }
@@ -3661,13 +3718,13 @@ class CopilotkitAgentFactory {
3661
3718
  CopilotKitCoreRuntimeConnectionStatus.Connecting ||
3662
3719
  runtimeConnectionStatus ===
3663
3720
  CopilotKitCoreRuntimeConnectionStatus.Error)) {
3664
- const headers = this.#copilotkit.headers();
3665
3721
  const credentials = this.#copilotkit.credentials();
3666
3722
  const cached = this.#provisionalCache.get(resolvedAgentId);
3667
3723
  if (cached) {
3668
- if (hasAgentHeaders(cached.provisional)) {
3669
- cached.provisional.headers = { ...headers };
3670
- }
3724
+ // Void, never invokes the builder: installs `ɵruntimeFetch` on a
3725
+ // `ProxiedCopilotRuntimeAgent`, which resolves headers fresh at
3726
+ // send time (#1937) rather than baking in a snapshot here.
3727
+ this.#copilotkit.core.applyHeadersToAgent(cached.provisional);
3671
3728
  if (hasAgentCredentials(cached.provisional)) {
3672
3729
  cached.provisional.credentials = credentials;
3673
3730
  }
@@ -3679,9 +3736,7 @@ class CopilotkitAgentFactory {
3679
3736
  transport: this.#copilotkit.runtimeTransport(),
3680
3737
  credentials,
3681
3738
  });
3682
- if (hasAgentHeaders(provisional)) {
3683
- provisional.headers = { ...headers };
3684
- }
3739
+ this.#copilotkit.core.applyHeadersToAgent(provisional);
3685
3740
  const handoff = new AgentHandoffBridge(provisional);
3686
3741
  this.#provisionalCache.set(resolvedAgentId, handoff);
3687
3742
  return provisional;
@@ -3701,7 +3756,10 @@ class CopilotkitAgentFactory {
3701
3756
  this.#copilotkit.runtimeConnectionStatus();
3702
3757
  this.#copilotkit.runtimeUrl();
3703
3758
  this.#copilotkit.runtimeTransport();
3704
- this.#copilotkit.headers();
3759
+ // Keyed on the generation, not header VALUES: a builder's returned
3760
+ // token can change on every resolution without a new source ever being
3761
+ // set, and this must not re-run `resolveAgent` on that (#1937).
3762
+ this.#copilotkit.ɵheadersGeneration();
3705
3763
  this.#copilotkit.credentials();
3706
3764
  const agent = resolveAgent();
3707
3765
  if (lastAgentStore && lastAgent === agent) {
@@ -4278,7 +4336,13 @@ class ThreadsStore {
4278
4336
  const active = isEnabled();
4279
4337
  const url = runtimeUrl();
4280
4338
  const status = runtimeStatus();
4281
- const headers = this.#copilotkit.headers();
4339
+ // Keyed on the generation, not header VALUES: a builder's returned
4340
+ // token can change on every resolution without a new source ever being
4341
+ // set (e.g. a run refreshing the snapshot), and this must not
4342
+ // re-dispatch the thread context on that (#1937). A real
4343
+ // `setHeaders()` call still re-runs this effect: `ɵheadersGeneration`
4344
+ // is set from `onHeadersChanged`, which fires only then.
4345
+ const headersGeneration = this.#copilotkit.ɵheadersGeneration();
4282
4346
  const id = agentId();
4283
4347
  const archived = includeArchived();
4284
4348
  const pageLimit = limit();
@@ -4309,23 +4373,23 @@ class ThreadsStore {
4309
4373
  clearContext();
4310
4374
  return;
4311
4375
  }
4376
+ // Headers are deliberately NOT part of this context: the store's
4377
+ // `fetch` is `ɵruntimeFetch`, which already resolves and overlays the
4378
+ // current core headers at send time (#1937) — a header snapshot
4379
+ // spread here would go stale the moment a builder's token rotates.
4312
4380
  const context = {
4313
4381
  runtimeUrl: url,
4314
- headers: { ...headers },
4315
4382
  wsUrl,
4316
4383
  agentId: id,
4317
4384
  includeArchived: archived,
4318
4385
  limit: pageLimit,
4319
4386
  };
4320
- // Build the dedup signature with header entries sorted, so a
4321
- // same-content header map with a different key order does not trigger
4322
- // a redundant setContext (and the refetch + resubscribe it causes).
4323
- // Mirrors react-core's `headersKey`. The dispatched context keeps its
4324
- // original header order; only the signature is normalized.
4325
- const signature = JSON.stringify({
4326
- ...context,
4327
- headers: Object.entries(headers).sort(([left], [right]) => left.localeCompare(right)),
4328
- });
4387
+ // The dedup signature adds `headersGeneration` explicitly, even
4388
+ // though it's absent from `context` itself: a real header source
4389
+ // change must still force exactly one re-dispatch (a fresh
4390
+ // subscribe/refetch), even when nothing else about the context
4391
+ // changed. Mirrors react-core's `headersKey` dependency.
4392
+ const signature = JSON.stringify({ ...context, headersGeneration });
4329
4393
  if (signature === lastDispatchedContext) {
4330
4394
  return;
4331
4395
  }
@@ -4559,13 +4623,19 @@ async function transcribeAudio(core, audioBlob, filename = "recording.webm") {
4559
4623
  retryable: false,
4560
4624
  });
4561
4625
  }
4626
+ // Resolve once, up front, OUTSIDE the try below — never through
4627
+ // `ɵruntimeFetch` (this request is built by hand, not sent via an agent),
4628
+ // and never a stale snapshot: a key that no longer resolves must not ride
4629
+ // along (#1937). A builder failure here must surface as itself, not get
4630
+ // caught and re-wrapped as a NETWORK_ERROR `TranscriptionError`.
4631
+ const resolvedHeaders = { ...(await core.resolveHeaders()) };
4562
4632
  let response;
4563
4633
  try {
4564
4634
  response =
4565
4635
  core.runtimeTransport === "single"
4566
4636
  ? await fetch(runtimeUrl, {
4567
4637
  method: "POST",
4568
- headers: { ...core.headers, "Content-Type": "application/json" },
4638
+ headers: { ...resolvedHeaders, "Content-Type": "application/json" },
4569
4639
  body: JSON.stringify({
4570
4640
  method: "transcribe",
4571
4641
  body: {
@@ -4578,7 +4648,7 @@ async function transcribeAudio(core, audioBlob, filename = "recording.webm") {
4578
4648
  : await fetch(`${runtimeUrl}/transcribe`, {
4579
4649
  method: "POST",
4580
4650
  // No Content-Type: the browser sets it (with boundary) for FormData.
4581
- headers: omitContentType(core.headers),
4651
+ headers: omitContentType(resolvedHeaders),
4582
4652
  body: toFormData(audioBlob, filename),
4583
4653
  });
4584
4654
  }
@@ -5575,283 +5645,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImpor
5575
5645
  }]
5576
5646
  }], propDecorators: { message: [{ type: i0.Input, args: [{ isSignal: true, alias: "message", required: true }] }], messages: [{ type: i0.Input, args: [{ isSignal: true, alias: "messages", required: true }] }], agentId: [{ type: i0.Input, args: [{ isSignal: true, alias: "agentId", required: false }] }], isLoading: [{ type: i0.Input, args: [{ isSignal: true, alias: "isLoading", required: false }] }] } });
5577
5647
 
5578
- const HTML_ESCAPES = {
5579
- "&": "&",
5580
- "<": "&lt;",
5581
- ">": "&gt;",
5582
- '"': "&quot;",
5583
- "'": "&#39;",
5584
- };
5585
- function escapeHtmlText(text) {
5586
- return text.replace(/[&<>"']/g, (char) => HTML_ESCAPES[char] ?? char);
5587
- }
5588
- let privatePurifier = null;
5589
- /**
5590
- * Returns a DOMPurify instance owned by this module, or null when there is no
5591
- * DOM or the instance reports it cannot sanitize. An unsupported instance
5592
- * returns its input unchanged from sanitize(), so callers must treat null as
5593
- * "cannot sanitize" and fail closed. The default export is a global instance
5594
- * shared with the host app, whose setConfig() overrides our per-call config
5595
- * and whose hooks would run inside our sanitization, so it is not used here.
5596
- */
5597
- function getPrivatePurifier() {
5598
- if (typeof window === "undefined") {
5599
- return null;
5600
- }
5601
- if (privatePurifier?.window !== window) {
5602
- privatePurifier = { window, purifier: DOMPurify(window) };
5603
- }
5604
- const { purifier } = privatePurifier;
5605
- return purifier.isSupported ? purifier : null;
5606
- }
5607
- /**
5608
- * Sanitizes rendered markdown before it is written to the DOM with innerHTML.
5609
- * KaTeX wraps its MathML in <semantics> and puts the TeX source in an
5610
- * <annotation>. DOMPurify unwraps both by default but keeps their content, so
5611
- * the TeX source leaks as visible text and the MathML structure breaks. They
5612
- * are allowed explicitly; DOMPurify still sanitizes their children and
5613
- * attributes.
5614
- * DOMPurify keeps <style> elements by default. This component uses
5615
- * ViewEncapsulation.None, so a <style> in model output would restyle the whole
5616
- * host page; it is forbidden. The inline style attribute stays allowed because
5617
- * KaTeX layout depends on it.
5618
- */
5619
- function sanitizeRenderedHtml(purifier, html) {
5620
- return purifier.sanitize(html, {
5621
- ADD_TAGS: ["semantics", "annotation"],
5622
- FORBID_TAGS: ["style"],
5623
- });
5624
- }
5625
- function processMathEquationsInHtml(html) {
5626
- // First, temporarily replace code blocks with placeholders to protect them from math processing
5627
- const codeBlocks = [];
5628
- const placeholder = "___CODE_BLOCK_PLACEHOLDER_";
5629
- // Store code blocks and replace with placeholders
5630
- html = html.replace(/<pre><code[\s\S]*?<\/code><\/pre>/g, (match) => {
5631
- const index = codeBlocks.length;
5632
- codeBlocks.push(match);
5633
- return `${placeholder}${index}___`;
5634
- });
5635
- // Also protect inline code
5636
- const inlineCode = [];
5637
- const inlinePlaceholder = "___INLINE_CODE_PLACEHOLDER_";
5638
- html = html.replace(/<code>[\s\S]*?<\/code>/g, (match) => {
5639
- const index = inlineCode.length;
5640
- inlineCode.push(match);
5641
- return `${inlinePlaceholder}${index}___`;
5642
- });
5643
- // Process display math $$ ... $$
5644
- html = html.replace(/\$\$([\s\S]*?)\$\$/g, (match, equation) => {
5645
- try {
5646
- return katex.renderToString(equation, {
5647
- displayMode: true,
5648
- throwOnError: false,
5649
- });
5650
- }
5651
- catch {
5652
- return match;
5653
- }
5654
- });
5655
- // A closing inline-math delimiter cannot be preceded by whitespace or
5656
- // followed by a digit. Those delimiter rules keep ordinary currency ranges
5657
- // such as "$349 ... $289" from becoming one large KaTeX expression.
5658
- html = html.replace(/(?<!\\)\$(?!\s)([^$\n]*?\S)\$(?!\d)/g, (match, equation) => {
5659
- try {
5660
- return katex.renderToString(equation, {
5661
- displayMode: false,
5662
- throwOnError: false,
5663
- });
5664
- }
5665
- catch {
5666
- return match;
5667
- }
5668
- });
5669
- // Restore code blocks
5670
- codeBlocks.forEach((block, index) => {
5671
- html = html.replace(`${placeholder}${index}___`, block);
5672
- });
5673
- // Restore inline code
5674
- inlineCode.forEach((code, index) => {
5675
- html = html.replace(`${inlinePlaceholder}${index}___`, code);
5676
- });
5677
- return html;
5678
- }
5679
- class CopilotChatAssistantMessageRenderer {
5680
- content = input("", /* @ts-ignore */
5681
- ...(ngDevMode ? [{ debugName: "content" }] : /* istanbul ignore next */ []));
5682
- inputClass = input(/* @ts-ignore */
5683
- ...(ngDevMode ? [undefined, { debugName: "inputClass" }] : /* istanbul ignore next */ []));
5684
- labels = injectChatLabels();
5685
- markdownContainer;
5686
- elementRef = inject(ElementRef);
5687
- // Track copy states for code blocks (DOM-updated; no signal needed)
5688
- copyStates = new Map();
5689
- renderedHtml = computed(() => {
5690
- const currentContent = this.content();
5691
- const completedMarkdown = completePartialMarkdown(currentContent);
5692
- return this.renderMarkdown(completedMarkdown);
5693
- }, /* @ts-ignore */
5694
- ...(ngDevMode ? [{ debugName: "renderedHtml" }] : /* istanbul ignore next */ []));
5695
- constructor() {
5696
- explicitEffect(this.content, () => {
5697
- // Reset copy states when content changes
5698
- this.copyStates.clear();
5699
- // If view is ready, update DOM
5700
- if (this.markdownContainer) {
5701
- this.updateContent();
5702
- }
5703
- });
5704
- }
5705
- ngAfterViewInit() {
5706
- this.updateContent();
5707
- }
5708
- updateContent() {
5709
- if (!this.markdownContainer)
5710
- return;
5711
- const container = this.markdownContainer.nativeElement;
5712
- const html = this.renderedHtml();
5713
- container.innerHTML = html;
5714
- }
5715
- codeBlocksMap = new Map();
5716
- markedInstance = null;
5717
- initializeMarked() {
5718
- if (this.markedInstance)
5719
- return;
5720
- // Create a new Marked instance
5721
- this.markedInstance = new Marked();
5722
- // Configure marked options
5723
- this.markedInstance.setOptions({
5724
- gfm: true,
5725
- breaks: true,
5726
- });
5727
- // Add a walkTokens function to process code tokens before rendering
5728
- this.markedInstance.use({
5729
- walkTokens: (token) => {
5730
- if (token.type === "code") {
5731
- const rawCode = token.text;
5732
- const lang = token.lang || "";
5733
- const blockId = this.generateBlockId(rawCode);
5734
- // Store the raw code in our map for copying
5735
- this.codeBlocksMap.set(blockId, rawCode);
5736
- const copyLabel = this.labels.assistantMessageToolbarCopyCodeLabel;
5737
- // Manually highlight the code
5738
- const language = hljs.getLanguage(lang) ? lang : "plaintext";
5739
- const highlighted = hljs.highlight(rawCode, { language }).value;
5740
- const safeLang = escapeHtmlText(lang);
5741
- const codeClass = lang ? `hljs language-${safeLang}` : "hljs";
5742
- // Create the full HTML with header and highlighted code
5743
- const fullHtml = `
5744
- <div class="code-block-container">
5745
- <div class="code-block-header">
5746
- ${lang ? `<span class="code-block-language">${safeLang}</span>` : "<span></span>"}
5747
- <button
5748
- class="code-block-copy-button"
5749
- data-code-block-id="${blockId}"
5750
- aria-label="${copyLabel} code">
5751
- <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.11 0-2-.9-2-2V4c0-1.11.89-2 2-2h10c1.11 0 2 .89 2 2"/></svg>
5752
- <span>${copyLabel}</span>
5753
- </button>
5754
- </div>
5755
- <pre><code class="${codeClass}">${highlighted}</code></pre>
5756
- </div>
5757
- `;
5758
- // Change the token to an html token to bypass marked's escaping
5759
- token.type = "html";
5760
- token.text = fullHtml;
5761
- }
5762
- },
5763
- });
5764
- }
5765
- renderMarkdown(content) {
5766
- // The support check runs on the same instance that sanitizes. When it
5767
- // cannot run (for example during server rendering, without a DOM), its
5768
- // sanitize() would return the HTML unchanged, so rendered HTML cannot be
5769
- // trusted. Emit the escaped markdown source as plain text instead; the
5770
- // browser replaces it with sanitized markdown when it renders there.
5771
- const purifier = getPrivatePurifier();
5772
- if (!purifier) {
5773
- return escapeHtmlText(content);
5774
- }
5775
- // Initialize marked if not already done
5776
- this.initializeMarked();
5777
- // Clear the code blocks map for new render
5778
- this.codeBlocksMap.clear();
5779
- // Parse markdown
5780
- let html = this.markedInstance.parse(content);
5781
- // Process math equations
5782
- html = processMathEquationsInHtml(html);
5783
- return sanitizeRenderedHtml(purifier, html);
5784
- }
5785
- handleClick(event) {
5786
- const target = event.target;
5787
- // Check if clicked on copy button or its children
5788
- const copyButton = target.closest(".code-block-copy-button");
5789
- if (copyButton) {
5790
- event.preventDefault();
5791
- const blockId = copyButton.getAttribute("data-code-block-id");
5792
- if (blockId) {
5793
- // Get the raw code from our map instead of from DOM
5794
- const code = this.codeBlocksMap.get(blockId);
5795
- if (code) {
5796
- this.copyCodeBlock(blockId, code);
5797
- }
5798
- }
5799
- }
5800
- }
5801
- copyCodeBlock(blockId, code) {
5802
- copyToClipboard(code).then((success) => {
5803
- if (!success)
5804
- return;
5805
- // Update the button in the DOM
5806
- const button = this.elementRef.nativeElement.querySelector(`[data-code-block-id="${blockId}"]`);
5807
- if (button) {
5808
- const originalHTML = button.innerHTML;
5809
- button.innerHTML = `
5810
- <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
5811
- <span>${this.labels.assistantMessageToolbarCopyCodeCopiedLabel}</span>
5812
- `;
5813
- button.setAttribute("aria-label", `${this.labels.assistantMessageToolbarCopyCodeCopiedLabel} code`);
5814
- // Reset after 2 seconds
5815
- setTimeout(() => {
5816
- button.innerHTML = originalHTML;
5817
- button.setAttribute("aria-label", `${this.labels.assistantMessageToolbarCopyCodeLabel} code`);
5818
- }, 2000);
5819
- }
5820
- });
5821
- }
5822
- generateBlockId(code) {
5823
- // Simple hash function for generating unique IDs
5824
- let hash = 0;
5825
- for (let i = 0; i < code.length; i++) {
5826
- const char = code.charCodeAt(i);
5827
- hash = (hash << 5) - hash + char;
5828
- hash = hash & hash; // Convert to 32-bit integer
5829
- }
5830
- return `code-block-${hash}`;
5831
- }
5832
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotChatAssistantMessageRenderer, deps: [], target: i0.ɵɵFactoryTarget.Component });
5833
- static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "22.0.0", type: CopilotChatAssistantMessageRenderer, isStandalone: true, selector: "copilot-chat-assistant-message-renderer", inputs: { content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, inputClass: { classPropertyName: "inputClass", publicName: "inputClass", isSignal: true, isRequired: false, transformFunction: null } }, viewQueries: [{ propertyName: "markdownContainer", first: true, predicate: ["markdownContainer"], descendants: true }], ngImport: i0, template: `
5834
- <div
5835
- #markdownContainer
5836
- [class]="inputClass()"
5837
- (click)="handleClick($event)"
5838
- ></div>
5839
- `, isInline: true, styles: ["copilot-chat-assistant-message-renderer{display:block;width:100%}copilot-chat-assistant-message-renderer code:not(pre code){padding:2.5px 4.8px;background-color:#ececec;border-radius:.25rem;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace;font-weight:500;color:#000}.dark copilot-chat-assistant-message-renderer code:not(pre code){background-color:#171717;color:#f8fafc}copilot-chat-assistant-message-renderer .code-block-container{position:relative;margin:.25rem 0;background-color:#f9f9f9;border-radius:1rem}.dark copilot-chat-assistant-message-renderer .code-block-container{background-color:#171717}copilot-chat-assistant-message-renderer .code-block-header{display:flex;align-items:center;justify-content:space-between;padding:.75rem 1rem;font-size:.75rem;background-color:transparent}copilot-chat-assistant-message-renderer .code-block-language{font-weight:400;color:#737373}.dark copilot-chat-assistant-message-renderer .code-block-language{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button{display:flex;align-items:center;gap:.125rem;padding:0 .5rem;font-size:.75rem;color:#737373;cursor:pointer;background:none;border:none;transition:opacity .2s}.dark copilot-chat-assistant-message-renderer .code-block-copy-button{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button:hover{opacity:.8}copilot-chat-assistant-message-renderer .code-block-copy-button svg{width:10px;height:10px}copilot-chat-assistant-message-renderer .code-block-copy-button span{font-size:11px}copilot-chat-assistant-message-renderer pre{margin:0;padding:0 1rem 1rem;overflow-x:auto;background-color:transparent;border-radius:1rem}.dark copilot-chat-assistant-message-renderer pre{background-color:transparent}copilot-chat-assistant-message-renderer pre code{background-color:transparent;padding:0;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace}copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#383a42}.dark copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#abb2bf}copilot-chat-assistant-message-renderer .katex-display{overflow-x:auto;overflow-y:hidden;padding:1rem 0}\n"], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
5840
- }
5841
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotChatAssistantMessageRenderer, decorators: [{
5842
- type: Component,
5843
- args: [{ standalone: true, selector: "copilot-chat-assistant-message-renderer", changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, template: `
5844
- <div
5845
- #markdownContainer
5846
- [class]="inputClass()"
5847
- (click)="handleClick($event)"
5848
- ></div>
5849
- `, styles: ["copilot-chat-assistant-message-renderer{display:block;width:100%}copilot-chat-assistant-message-renderer code:not(pre code){padding:2.5px 4.8px;background-color:#ececec;border-radius:.25rem;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace;font-weight:500;color:#000}.dark copilot-chat-assistant-message-renderer code:not(pre code){background-color:#171717;color:#f8fafc}copilot-chat-assistant-message-renderer .code-block-container{position:relative;margin:.25rem 0;background-color:#f9f9f9;border-radius:1rem}.dark copilot-chat-assistant-message-renderer .code-block-container{background-color:#171717}copilot-chat-assistant-message-renderer .code-block-header{display:flex;align-items:center;justify-content:space-between;padding:.75rem 1rem;font-size:.75rem;background-color:transparent}copilot-chat-assistant-message-renderer .code-block-language{font-weight:400;color:#737373}.dark copilot-chat-assistant-message-renderer .code-block-language{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button{display:flex;align-items:center;gap:.125rem;padding:0 .5rem;font-size:.75rem;color:#737373;cursor:pointer;background:none;border:none;transition:opacity .2s}.dark copilot-chat-assistant-message-renderer .code-block-copy-button{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button:hover{opacity:.8}copilot-chat-assistant-message-renderer .code-block-copy-button svg{width:10px;height:10px}copilot-chat-assistant-message-renderer .code-block-copy-button span{font-size:11px}copilot-chat-assistant-message-renderer pre{margin:0;padding:0 1rem 1rem;overflow-x:auto;background-color:transparent;border-radius:1rem}.dark copilot-chat-assistant-message-renderer pre{background-color:transparent}copilot-chat-assistant-message-renderer pre code{background-color:transparent;padding:0;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace}copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#383a42}.dark copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#abb2bf}copilot-chat-assistant-message-renderer .katex-display{overflow-x:auto;overflow-y:hidden;padding:1rem 0}\n"] }]
5850
- }], ctorParameters: () => [], propDecorators: { content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: false }] }], inputClass: [{ type: i0.Input, args: [{ isSignal: true, alias: "inputClass", required: false }] }], markdownContainer: [{
5851
- type: ViewChild,
5852
- args: ["markdownContainer", { static: false }]
5853
- }] } });
5854
-
5855
5648
  /** Framework-independent renderer for the small Lucide subset used by chat. */
5856
5649
  class CopilotIcon {
5857
5650
  img = input.required(/* @ts-ignore */
@@ -5984,6 +5777,243 @@ const Volume2 = [
5984
5777
  ];
5985
5778
  const X = [path("M18 6 6 18"), path("m6 6 12 12")];
5986
5779
 
5780
+ /**
5781
+ * Language label and copy button above a rendered markdown code block.
5782
+ * Mounted by CopilotChatAssistantMessageRenderer into the sanitized markdown
5783
+ * DOM; styled by that component.
5784
+ */
5785
+ class CopilotChatCodeBlockHeader {
5786
+ language = input("", /* @ts-ignore */
5787
+ ...(ngDevMode ? [{ debugName: "language" }] : /* istanbul ignore next */ []));
5788
+ code = input.required(/* @ts-ignore */
5789
+ ...(ngDevMode ? [{ debugName: "code" }] : /* istanbul ignore next */ []));
5790
+ CopyIcon = Copy;
5791
+ CheckIcon = Check;
5792
+ copied = signal(false, /* @ts-ignore */
5793
+ ...(ngDevMode ? [{ debugName: "copied" }] : /* istanbul ignore next */ []));
5794
+ labels = injectChatLabels();
5795
+ label = computed(() => this.copied()
5796
+ ? this.labels.assistantMessageToolbarCopyCodeCopiedLabel
5797
+ : this.labels.assistantMessageToolbarCopyCodeLabel, /* @ts-ignore */
5798
+ ...(ngDevMode ? [{ debugName: "label" }] : /* istanbul ignore next */ []));
5799
+ resetTimer;
5800
+ constructor() {
5801
+ inject(DestroyRef).onDestroy(() => clearTimeout(this.resetTimer));
5802
+ }
5803
+ copy() {
5804
+ copyToClipboard(this.code()).then((success) => {
5805
+ if (!success)
5806
+ return;
5807
+ this.copied.set(true);
5808
+ clearTimeout(this.resetTimer);
5809
+ this.resetTimer = setTimeout(() => this.copied.set(false), 2000);
5810
+ });
5811
+ }
5812
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotChatCodeBlockHeader, deps: [], target: i0.ɵɵFactoryTarget.Component });
5813
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.1.0", version: "22.0.0", type: CopilotChatCodeBlockHeader, isStandalone: true, selector: "copilot-chat-code-block-header", inputs: { language: { classPropertyName: "language", publicName: "language", isSignal: true, isRequired: false, transformFunction: null }, code: { classPropertyName: "code", publicName: "code", isSignal: true, isRequired: true, transformFunction: null } }, host: { classAttribute: "code-block-header" }, ngImport: i0, template: `
5814
+ <span [class.code-block-language]="language()">{{ language() }}</span>
5815
+ <button
5816
+ type="button"
5817
+ class="code-block-copy-button"
5818
+ [attr.aria-label]="label() + ' code'"
5819
+ (click)="copy()"
5820
+ >
5821
+ <copilot-icon [img]="copied() ? CheckIcon : CopyIcon" [size]="10" />
5822
+ <span>{{ label() }}</span>
5823
+ </button>
5824
+ `, isInline: true, dependencies: [{ kind: "component", type: CopilotIcon, selector: "copilot-icon", inputs: ["img", "size"] }] });
5825
+ }
5826
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotChatCodeBlockHeader, decorators: [{
5827
+ type: Component,
5828
+ args: [{
5829
+ selector: "copilot-chat-code-block-header",
5830
+ imports: [CopilotIcon],
5831
+ host: { class: "code-block-header" },
5832
+ template: `
5833
+ <span [class.code-block-language]="language()">{{ language() }}</span>
5834
+ <button
5835
+ type="button"
5836
+ class="code-block-copy-button"
5837
+ [attr.aria-label]="label() + ' code'"
5838
+ (click)="copy()"
5839
+ >
5840
+ <copilot-icon [img]="copied() ? CheckIcon : CopyIcon" [size]="10" />
5841
+ <span>{{ label() }}</span>
5842
+ </button>
5843
+ `,
5844
+ }]
5845
+ }], ctorParameters: () => [], propDecorators: { language: [{ type: i0.Input, args: [{ isSignal: true, alias: "language", required: false }] }], code: [{ type: i0.Input, args: [{ isSignal: true, alias: "code", required: true }] }] } });
5846
+
5847
+ /**
5848
+ * DOMPurify instance owned by this module, or undefined without a DOM. The
5849
+ * default export is a global instance shared with the host app, whose
5850
+ * setConfig() overrides our per-call config and whose hooks would run inside
5851
+ * our sanitization, so it is not used here.
5852
+ */
5853
+ const purifier = typeof window === "undefined" ? undefined : DOMPurify(window);
5854
+ purifier?.addHook("afterSanitizeAttributes", (node) => {
5855
+ if (node.tagName === "A" && node.hasAttribute("href")) {
5856
+ node.setAttribute("rel", "noopener noreferrer");
5857
+ }
5858
+ });
5859
+ /**
5860
+ * Sanitizes rendered markdown into a DOM fragment with DOMPurify's default
5861
+ * allowlist. Returning nodes instead of a string means the sanitized tree is
5862
+ * never serialized and parsed again, which is where mutation XSS happens.
5863
+ *
5864
+ * Returns null when sanitization cannot run (no DOM, for example during server
5865
+ * rendering, or an unsupported environment, where sanitize() would return its
5866
+ * input unchanged). Callers must fail closed and render text instead.
5867
+ *
5868
+ * KaTeX wraps its MathML in <semantics> and puts the TeX source in an
5869
+ * <annotation>. DOMPurify unwraps both by default but keeps their content, so
5870
+ * the TeX source leaks as visible text and the MathML structure breaks. They
5871
+ * are allowed explicitly; DOMPurify still sanitizes their children and
5872
+ * attributes.
5873
+ * The renderer uses ViewEncapsulation.None, so a <style> in model output would
5874
+ * restyle the whole host page; it is forbidden.
5875
+ */
5876
+ function sanitizeHtml(html) {
5877
+ if (!purifier?.isSupported) {
5878
+ return null;
5879
+ }
5880
+ return purifier.sanitize(html, {
5881
+ ADD_TAGS: ["semantics", "annotation"],
5882
+ FORBID_TAGS: ["style"],
5883
+ RETURN_DOM_FRAGMENT: true,
5884
+ });
5885
+ }
5886
+ /**
5887
+ * Tokenizes `$$...$$` display math and `$...$` inline math as markdown, so
5888
+ * math is never matched inside code spans, link targets, or other attributes.
5889
+ * A closing inline delimiter cannot be preceded by whitespace or followed by a
5890
+ * digit. Those delimiter rules keep ordinary currency ranges such as
5891
+ * "$349 ... $289" from becoming one large KaTeX expression.
5892
+ */
5893
+ const mathExtension = {
5894
+ name: "math",
5895
+ level: "inline",
5896
+ start: (src) => src.indexOf("$"),
5897
+ tokenizer(src) {
5898
+ const display = /^\$\$([\s\S]+?)\$\$/.exec(src);
5899
+ if (display) {
5900
+ return { type: "math", raw: display[0], text: display[1], display: true };
5901
+ }
5902
+ const inline = /^\$(?!\s)([^$\n]*?\S)\$(?!\d)/.exec(src);
5903
+ if (inline) {
5904
+ return { type: "math", raw: inline[0], text: inline[1], display: false };
5905
+ }
5906
+ return undefined;
5907
+ },
5908
+ renderer: (token) => renderToString(token["text"], {
5909
+ displayMode: token["display"],
5910
+ throwOnError: false,
5911
+ }),
5912
+ };
5913
+ const marked = new Marked({ gfm: true, breaks: true }, { extensions: [mathExtension] });
5914
+ /**
5915
+ * Highlights a code block in place. marked has already escaped the code and
5916
+ * its language class; the highlighted markup is sanitized before insertion.
5917
+ * Returns the fence language.
5918
+ */
5919
+ function highlightCode(code) {
5920
+ const lang = /\blanguage-(\S+)/.exec(code.className)?.[1] ?? "";
5921
+ const language = hljs.getLanguage(lang) ? lang : "plaintext";
5922
+ const source = (code.textContent ?? "").replace(/\n$/, "");
5923
+ const highlighted = sanitizeHtml(hljs.highlight(source, { language }).value);
5924
+ if (highlighted) {
5925
+ code.replaceChildren(highlighted);
5926
+ }
5927
+ code.classList.add("hljs");
5928
+ return lang;
5929
+ }
5930
+ /**
5931
+ * Renders possibly incomplete (streaming) markdown into sanitized DOM nodes,
5932
+ * with math and highlighted code. `decorateCodeBlock` is called for each code
5933
+ * block so the caller can add its own UI around it.
5934
+ * Without a working sanitizer (for example during server rendering), returns
5935
+ * the markdown source as a string to show as text; the browser renders it
5936
+ * when it hydrates.
5937
+ */
5938
+ function renderMarkdown(content, decorateCodeBlock) {
5939
+ const source = completePartialMarkdown(content);
5940
+ const fragment = sanitizeHtml(marked.parse(source));
5941
+ if (!fragment) {
5942
+ return source;
5943
+ }
5944
+ for (const code of Array.from(fragment.querySelectorAll("pre > code"))) {
5945
+ decorateCodeBlock(code, highlightCode(code));
5946
+ }
5947
+ return fragment;
5948
+ }
5949
+
5950
+ class CopilotChatAssistantMessageRenderer {
5951
+ content = input("", /* @ts-ignore */
5952
+ ...(ngDevMode ? [{ debugName: "content" }] : /* istanbul ignore next */ []));
5953
+ inputClass = input(/* @ts-ignore */
5954
+ ...(ngDevMode ? [undefined, { debugName: "inputClass" }] : /* istanbul ignore next */ []));
5955
+ labels = injectChatLabels();
5956
+ markdownContainer = viewChild("markdownContainer", /* @ts-ignore */
5957
+ ...(ngDevMode ? [{ debugName: "markdownContainer" }] : /* istanbul ignore next */ []));
5958
+ appRef = inject(ApplicationRef);
5959
+ environmentInjector = inject(EnvironmentInjector);
5960
+ injector = inject(Injector);
5961
+ codeBlockHeaders = [];
5962
+ constructor() {
5963
+ explicitEffect(() => ({
5964
+ container: this.markdownContainer()?.nativeElement,
5965
+ content: this.content(),
5966
+ }), ({ container, content }) => {
5967
+ if (!container)
5968
+ return;
5969
+ this.destroyCodeBlockHeaders();
5970
+ const rendered = renderMarkdown(content, (code, language) => this.addCodeBlockHeader(code, language));
5971
+ // The server DOM has no replaceChildren(); it only gets the text.
5972
+ if (typeof rendered === "string") {
5973
+ container.textContent = rendered;
5974
+ }
5975
+ else {
5976
+ container.replaceChildren(rendered);
5977
+ }
5978
+ });
5979
+ inject(DestroyRef).onDestroy(() => this.destroyCodeBlockHeaders());
5980
+ }
5981
+ /** Wraps a rendered code block and mounts its header component above it. */
5982
+ addCodeBlockHeader(code, language) {
5983
+ const pre = code.parentElement;
5984
+ const container = pre.ownerDocument.createElement("div");
5985
+ container.className = "code-block-container";
5986
+ pre.replaceWith(container);
5987
+ const source = code.textContent ?? "";
5988
+ const header = createComponent(CopilotChatCodeBlockHeader, {
5989
+ environmentInjector: this.environmentInjector,
5990
+ elementInjector: this.injector,
5991
+ bindings: [
5992
+ inputBinding("language", () => language),
5993
+ inputBinding("code", () => source),
5994
+ ],
5995
+ });
5996
+ this.appRef.attachView(header.hostView);
5997
+ header.changeDetectorRef.detectChanges();
5998
+ this.codeBlockHeaders.push(header);
5999
+ container.append(header.location.nativeElement, pre);
6000
+ }
6001
+ destroyCodeBlockHeaders() {
6002
+ this.codeBlockHeaders.forEach((header) => header.destroy());
6003
+ this.codeBlockHeaders = [];
6004
+ }
6005
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotChatAssistantMessageRenderer, deps: [], target: i0.ɵɵFactoryTarget.Component });
6006
+ static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.2.0", version: "22.0.0", type: CopilotChatAssistantMessageRenderer, isStandalone: true, selector: "copilot-chat-assistant-message-renderer", inputs: { content: { classPropertyName: "content", publicName: "content", isSignal: true, isRequired: false, transformFunction: null }, inputClass: { classPropertyName: "inputClass", publicName: "inputClass", isSignal: true, isRequired: false, transformFunction: null } }, viewQueries: [{ propertyName: "markdownContainer", first: true, predicate: ["markdownContainer"], descendants: true, isSignal: true }], ngImport: i0, template: `
6007
+ <div #markdownContainer [class]="inputClass()"></div>
6008
+ `, isInline: true, styles: ["copilot-chat-assistant-message-renderer{display:block;width:100%}copilot-chat-assistant-message-renderer code:not(pre code){padding:2.5px 4.8px;background-color:#ececec;border-radius:.25rem;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace;font-weight:500;color:#000}.dark copilot-chat-assistant-message-renderer code:not(pre code){background-color:#171717;color:#f8fafc}copilot-chat-assistant-message-renderer .code-block-container{position:relative;margin:.25rem 0;background-color:#f9f9f9;border-radius:1rem}.dark copilot-chat-assistant-message-renderer .code-block-container{background-color:#171717}copilot-chat-assistant-message-renderer .code-block-header{display:flex;align-items:center;justify-content:space-between;padding:.75rem 1rem;font-size:.75rem;background-color:transparent}copilot-chat-assistant-message-renderer .code-block-language{font-weight:400;color:#737373}.dark copilot-chat-assistant-message-renderer .code-block-language{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button{display:flex;align-items:center;gap:.125rem;padding:0 .5rem;font-size:.75rem;color:#737373;cursor:pointer;background:none;border:none;transition:opacity .2s}.dark copilot-chat-assistant-message-renderer .code-block-copy-button{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button:hover{opacity:.8}copilot-chat-assistant-message-renderer .code-block-copy-button svg{width:10px;height:10px}copilot-chat-assistant-message-renderer .code-block-copy-button span{font-size:11px}copilot-chat-assistant-message-renderer pre{margin:0;padding:0 1rem 1rem;overflow-x:auto;background-color:transparent;border-radius:1rem}.dark copilot-chat-assistant-message-renderer pre{background-color:transparent}copilot-chat-assistant-message-renderer pre code{background-color:transparent;padding:0;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace}copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#383a42}.dark copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#abb2bf}copilot-chat-assistant-message-renderer .katex-display{overflow-x:auto;overflow-y:hidden;padding:1rem 0}\n"], encapsulation: i0.ViewEncapsulation.None });
6009
+ }
6010
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImport: i0, type: CopilotChatAssistantMessageRenderer, decorators: [{
6011
+ type: Component,
6012
+ args: [{ selector: "copilot-chat-assistant-message-renderer", encapsulation: ViewEncapsulation.None, template: `
6013
+ <div #markdownContainer [class]="inputClass()"></div>
6014
+ `, styles: ["copilot-chat-assistant-message-renderer{display:block;width:100%}copilot-chat-assistant-message-renderer code:not(pre code){padding:2.5px 4.8px;background-color:#ececec;border-radius:.25rem;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace;font-weight:500;color:#000}.dark copilot-chat-assistant-message-renderer code:not(pre code){background-color:#171717;color:#f8fafc}copilot-chat-assistant-message-renderer .code-block-container{position:relative;margin:.25rem 0;background-color:#f9f9f9;border-radius:1rem}.dark copilot-chat-assistant-message-renderer .code-block-container{background-color:#171717}copilot-chat-assistant-message-renderer .code-block-header{display:flex;align-items:center;justify-content:space-between;padding:.75rem 1rem;font-size:.75rem;background-color:transparent}copilot-chat-assistant-message-renderer .code-block-language{font-weight:400;color:#737373}.dark copilot-chat-assistant-message-renderer .code-block-language{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button{display:flex;align-items:center;gap:.125rem;padding:0 .5rem;font-size:.75rem;color:#737373;cursor:pointer;background:none;border:none;transition:opacity .2s}.dark copilot-chat-assistant-message-renderer .code-block-copy-button{color:#fff}copilot-chat-assistant-message-renderer .code-block-copy-button:hover{opacity:.8}copilot-chat-assistant-message-renderer .code-block-copy-button svg{width:10px;height:10px}copilot-chat-assistant-message-renderer .code-block-copy-button span{font-size:11px}copilot-chat-assistant-message-renderer pre{margin:0;padding:0 1rem 1rem;overflow-x:auto;background-color:transparent;border-radius:1rem}.dark copilot-chat-assistant-message-renderer pre{background-color:transparent}copilot-chat-assistant-message-renderer pre code{background-color:transparent;padding:0;font-size:.875rem;font-family:ui-monospace,SFMono-Regular,SF Mono,Consolas,Liberation Mono,Menlo,monospace}copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#383a42}.dark copilot-chat-assistant-message-renderer .hljs{background:transparent;color:#abb2bf}copilot-chat-assistant-message-renderer .katex-display{overflow-x:auto;overflow-y:hidden;padding:1rem 0}\n"] }]
6015
+ }], ctorParameters: () => [], propDecorators: { content: [{ type: i0.Input, args: [{ isSignal: true, alias: "content", required: false }] }], inputClass: [{ type: i0.Input, args: [{ isSignal: true, alias: "inputClass", required: false }] }], markdownContainer: [{ type: i0.ViewChild, args: ["markdownContainer", { isSignal: true }] }] } });
6016
+
5987
6017
  // Base toolbar button component
5988
6018
  class CopilotChatAssistantMessageToolbarButton {
5989
6019
  title = input("", /* @ts-ignore */
@@ -12591,11 +12621,14 @@ class CopilotThreadsDrawer {
12591
12621
  const runtimeEntitlementRetryInProgress = retryableRuntimeEntitlementFailure &&
12592
12622
  (this.copilotkit.runtimeEntitlementRetryPending?.() ?? false) &&
12593
12623
  !hasLegacyRuntimeEntitlementFallback;
12594
- const runtimeEntitlementFailureSettled = hasNonReadyRuntimeEntitlement &&
12595
- !runtimeEntitlementRetryInProgress &&
12624
+ // Only a terminal failure denies features. A retryable failure (a
12625
+ // timeout, a network error, a 5xx) says nothing about what the project
12626
+ // may use.
12627
+ const terminalRuntimeEntitlementFailure = hasNonReadyRuntimeEntitlement &&
12628
+ !retryableRuntimeEntitlementFailure &&
12596
12629
  !hasLegacyRuntimeEntitlementFallback;
12597
12630
  const runtimeLicenseContext = createLicenseContextValue(runtimeEntitlementRetryInProgress ? undefined : runtimeLicenseStatus, runtimeEntitlements);
12598
- if (!runtimeEntitlementFailureSettled) {
12631
+ if (!terminalRuntimeEntitlementFailure) {
12599
12632
  return runtimeLicenseContext;
12600
12633
  }
12601
12634
  return {
@@ -13471,5 +13504,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.0.0", ngImpor
13471
13504
  * Generated bundle index. Do not edit.
13472
13505
  */
13473
13506
 
13474
- export { AGUI_SEND_STATE_SNAPSHOT_TOOL_NAME, AgentStore, AudioRecorderError, COPILOT_CHAT_CONFIGURATION, COPILOT_CHAT_CONFIGURATION_OPTIONS, COPILOT_CHAT_DEFAULT_LABELS, COPILOT_CHAT_LABELS, COPILOT_KIT_CONFIG, ChatState, CopilotA2UIActivityRenderer, CopilotA2UIProgress, CopilotA2UIRecovery, CopilotA2UIToolRenderer, CopilotActivity, CopilotChat, CopilotChatAddFileButton, CopilotChatAssistantMessage, CopilotChatAssistantMessageCopyButton, CopilotChatAssistantMessageReadAloudButton, CopilotChatAssistantMessageRegenerateButton, CopilotChatAssistantMessageRenderer, CopilotChatAssistantMessageThumbsDownButton, CopilotChatAssistantMessageThumbsUpButton, CopilotChatAssistantMessageToolbar, CopilotChatAssistantMessageToolbarButton, CopilotChatAttachmentQueue, CopilotChatAttachmentRenderer, CopilotChatAttachmentsDirective, CopilotChatAudioRecorder, CopilotChatCancelTranscribeButton, CopilotChatConfiguration, CopilotChatFinishTranscribeButton, CopilotChatInput, CopilotChatInputDefaults, CopilotChatMessageView, CopilotChatMessageViewCursor, CopilotChatReasoningMessage, CopilotChatSendButton, CopilotChatStartTranscribeButton, CopilotChatSuggestionPill, CopilotChatSuggestionView, CopilotChatTextarea, CopilotChatToolCallsView, CopilotChatToolbar, CopilotChatToolbarButton, CopilotChatToolsMenu, CopilotChatUserMessage, CopilotChatUserMessageBranchNavigation, CopilotChatUserMessageCopyButton, CopilotChatUserMessageEditButton, CopilotChatUserMessageRenderer, CopilotChatUserMessageToolbar, CopilotChatUserMessageToolbarButton, CopilotChatView, CopilotChatViewDisclaimer, CopilotChatViewFeather, CopilotChatViewHandlers, CopilotChatViewInputContainer, CopilotChatViewInputMeasure, CopilotChatViewScrollToBottomButton, CopilotChatViewScrollView, CopilotDefaultToolRenderer, CopilotKit, CopilotKitAgentContext, CopilotOpenGenerativeUIActivityRenderer, CopilotOpenGenerativeUIRenderer, CopilotOpenGenerativeUIToolRenderer, CopilotPopup, CopilotSidebar, CopilotSlot, CopilotThreadsDrawer, CopilotThreadsDrawerRow, CopilotTooltip, CopilotkitAgentFactory, CopilotkitThreadsFactory, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, GENERATE_SANDBOXED_UI_TOOL_NAME, GenerateSandboxedUiArgsSchema, InterruptController, InterruptExpiredError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, OPEN_GENERATIVE_UI_WEBSANDBOX_LOADER, OpenGenerativeUIContentSchema, RENDER_A2UI_TOOL_NAME, RenderA2UIArgsSchema, RenderToolCalls, ResizeObserverService, SLOT_CONFIG, ScrollPosition, StickToBottom, ThreadsStore, TooltipContent, TranscriptionError, anyActivityContentSchema, cn, connectAgentContext, createSlotConfig, createSlotRenderer, getSlotConfig, injectAgentStore, injectCapabilities, injectChatConfiguration, injectChatLabels, injectChatState, injectCopilotKitConfig, injectInterrupt, injectMemories, injectThreads, isComponentType, isSlotValue, normalizeSlotValue, parseToolCallArguments, pickToolCallHandler, provideCopilotChatConfiguration, provideCopilotChatLabels, provideCopilotKit, provideSlots, readA2UILifecycleContent, registerComponent, registerFrontendTool, registerHumanInTheLoop, registerRenderActivityMessage, registerRenderToolCall, renderSlot, safeToolValue, transcribeAudio, ɵCOPILOTKIT_BUILT_IN_ACTIVITY_RENDERERS, ɵCOPILOTKIT_INSPECTOR_DEVELOPMENT_MODE };
13507
+ export { AGUI_SEND_STATE_SNAPSHOT_TOOL_NAME, AgentStore, AudioRecorderError, COPILOT_CHAT_CONFIGURATION, COPILOT_CHAT_CONFIGURATION_OPTIONS, COPILOT_CHAT_DEFAULT_LABELS, COPILOT_CHAT_LABELS, COPILOT_KIT_CONFIG, ChatState, CopilotA2UIActivityRenderer, CopilotA2UIProgress, CopilotA2UIRecovery, CopilotA2UIToolRenderer, CopilotActivity, CopilotChat, CopilotChatAddFileButton, CopilotChatAssistantMessage, CopilotChatAssistantMessageCopyButton, CopilotChatAssistantMessageReadAloudButton, CopilotChatAssistantMessageRegenerateButton, CopilotChatAssistantMessageRenderer, CopilotChatAssistantMessageThumbsDownButton, CopilotChatAssistantMessageThumbsUpButton, CopilotChatAssistantMessageToolbar, CopilotChatAssistantMessageToolbarButton, CopilotChatAttachmentQueue, CopilotChatAttachmentRenderer, CopilotChatAttachmentsDirective, CopilotChatAudioRecorder, CopilotChatCancelTranscribeButton, CopilotChatConfiguration, CopilotChatFinishTranscribeButton, CopilotChatInput, CopilotChatInputDefaults, CopilotChatMessageView, CopilotChatMessageViewCursor, CopilotChatReasoningMessage, CopilotChatSendButton, CopilotChatStartTranscribeButton, CopilotChatSuggestionPill, CopilotChatSuggestionView, CopilotChatTextarea, CopilotChatToolCallsView, CopilotChatToolbar, CopilotChatToolbarButton, CopilotChatToolsMenu, CopilotChatUserMessage, CopilotChatUserMessageBranchNavigation, CopilotChatUserMessageCopyButton, CopilotChatUserMessageEditButton, CopilotChatUserMessageRenderer, CopilotChatUserMessageToolbar, CopilotChatUserMessageToolbarButton, CopilotChatView, CopilotChatViewDisclaimer, CopilotChatViewFeather, CopilotChatViewHandlers, CopilotChatViewInputContainer, CopilotChatViewInputMeasure, CopilotChatViewScrollToBottomButton, CopilotChatViewScrollView, CopilotDefaultToolRenderer, CopilotKit, CopilotKitAgentContext, CopilotOpenGenerativeUIActivityRenderer, CopilotOpenGenerativeUIRenderer, CopilotOpenGenerativeUIToolRenderer, CopilotPopup, CopilotSidebar, CopilotSlot, CopilotThreadsDrawer, CopilotThreadsDrawerRow, CopilotTooltip, CopilotkitAgentFactory, CopilotkitThreadsFactory, DEFAULT_OPEN_GENERATIVE_UI_DESIGN_SKILL, GENERATE_SANDBOXED_UI_TOOL_NAME, GenerateSandboxedUiArgsSchema, InterruptController, InterruptExpiredError, OPEN_GENERATIVE_UI_ACTIVITY_TYPE, OPEN_GENERATIVE_UI_WEBSANDBOX_LOADER, OpenGenerativeUIContentSchema, RENDER_A2UI_TOOL_NAME, RenderA2UIArgsSchema, RenderToolCalls, ResizeObserverService, SLOT_CONFIG, ScrollPosition, StickToBottom, ThreadsStore, TooltipContent, TranscriptionError, anyActivityContentSchema, cn, connectAgentContext, createSlotConfig, createSlotRenderer, getSlotConfig, injectAgentStore, injectCapabilities, injectChatConfiguration, injectChatLabels, injectChatState, injectCopilotKitConfig, injectInterrupt, injectMemories, injectThreads, isComponentType, isSlotValue, normalizeSlotValue, parseToolCallArguments, pickToolCallHandler, provideCopilotChatConfiguration, provideCopilotChatLabels, provideCopilotKit, provideSlots, readA2UILifecycleContent, registerComponent, registerFrontendTool, registerHumanInTheLoop, registerRenderActivityMessage, registerRenderToolCall, renderSlot, safeToolValue, transcribeAudio, ɵCOPILOTKIT_BUILT_IN_ACTIVITY_RENDERERS, ɵCOPILOTKIT_INSPECTOR_DEVELOPMENT_MODE, ɵresolvePublicKeyHeaderDefaults };
13475
13508
  //# sourceMappingURL=copilotkit-angular.mjs.map