@vpxa/aikit 0.1.249 → 0.1.251

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vpxa/aikit",
3
- "version": "0.1.249",
3
+ "version": "0.1.251",
4
4
  "type": "module",
5
5
  "description": "Local-first AI developer toolkit — knowledge base, code analysis, context management, and developer tools for LLM agents",
6
6
  "license": "MIT",
@@ -14,6 +14,7 @@
14
14
  "scripts": {
15
15
  "build": "tsdown src/index.ts --format esm",
16
16
  "dev": "tsdown src/index.ts --format esm --dts --watch",
17
+ "test": "vitest run",
17
18
  "tokens:check": "node scripts/generate-tokens.ts --check"
18
19
  },
19
20
  "devDependencies": {
@@ -1,4 +1,4 @@
1
- import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";var i=Object.defineProperty,a=(e,t)=>{let n={};for(var r in e)i(n,r,{get:e[r],enumerable:!0});return t||i(n,Symbol.toStringTag,{value:`Module`}),n};const o=[{selector:`.bk-table`,matches:e=>!r(e.ownerDocument),load:()=>Promise.resolve().then(()=>p).then(e=>({hydrate:t=>e.hydrateTable(t)}))},{selector:`.bk-table`,matches:(t,n)=>r(t.ownerDocument)&&e(t,`.bk-table`,n),load:()=>import(`./form-SyIoFeT1.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateForm(t,n)}))},{selector:`.bk-tree`,matches:e=>!n(e.ownerDocument),load:()=>Promise.resolve().then(()=>x).then(e=>({hydrate:t=>e.hydrateTree(t)}))},{selector:`.bk-tree`,matches:e=>n(e.ownerDocument),load:()=>import(`./flame-graph-CV8KCLKu.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateFlameGraph(t,n)}))},{selector:`.bk-actions`,load:()=>Promise.resolve().then(()=>s).then(e=>({hydrate:(t,n)=>n?.onAction?e.hydrateActions(t,n.onAction):()=>{}}))},{selector:`.bk-checklist`,load:()=>Promise.resolve().then(()=>l).then(e=>({hydrate:(t,n)=>e.hydrateChecklist(t,n)}))},{selector:`.bk-cards`,matches:(n,r)=>t(n.ownerDocument)&&e(n,`.bk-cards`,r),load:()=>import(`./picker-CZJricO9.mjs`).then(e=>({hydrate:(t,n)=>e.hydratePicker(t,n)}))}];var s=a({hydrateActions:()=>c});function c(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var l=a({hydrateChecklist:()=>f});function u(e){let t=e.createElement(`style`);return t.textContent=`
1
+ import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";function i(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}function a(e){let t=e.createElement(`style`);return t.textContent=`
2
2
  .bk-checklist-progress {
3
3
  margin-bottom: var(--dt-space-3);
4
4
  color: var(--dt-text-secondary);
@@ -12,4 +12,4 @@ import{a as e,i as t,n,r}from"./payload-DyKkZIOX.mjs";var i=Object.definePropert
12
12
  margin: 0;
13
13
  accent-color: var(--dt-accent-fg);
14
14
  }
15
- `,t}function d(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function f(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=u(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=d(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return d(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var p=a({hydrateTable:()=>b});const m=`data-sort-label`,h=`data-sort-dir`,g=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function _(e){let t=e.getAttribute(m);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(m,n),n}function v(e,t,n){for(let[r,i]of e.entries())i.textContent=_(i),r===t?(i.setAttribute(h,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(h)}function y(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function b(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=g.compare(y(e,t),y(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}v(t,a,o)};for(let[e,n]of t.entries()){_(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=_(e),e.removeAttribute(h),e.removeAttribute(m),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}var x=a({hydrateTree:()=>O});function S(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function C(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return S(n);n=n.parentElement}return null}function w(e){return Array.from(e.querySelectorAll(`summary`))}function T(e){return e.open||e.hasAttribute(`open`)}function E(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function D(e,t){e.textContent=t.every(e=>T(e))?`Collapse all`:`Expand all`}function O(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!T(e));for(let n of t)E(n,e);D(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{D(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=w(e).map(t=>{t.tabIndex=0;let n=n=>{let r=w(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!T(a))E(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&T(a)?E(a,!1):C(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return D(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}const k=`data-hydrated`;function A(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function j(e,t,n){e.push(()=>{n(),t.removeAttribute(k)})}function M(e={}){let t=e.container??document.body,n=[];for(let e of A(t,`.bk-table`))e.hasAttribute(k)||(e.setAttribute(k,``),j(n,e,b(e)));for(let e of A(t,`.bk-tree`))e.hasAttribute(k)||(e.setAttribute(k,``),j(n,e,O(e)));for(let r of A(t,`.bk-checklist`))r.hasAttribute(k)||(r.setAttribute(k,``),j(n,r,f(r,e)));for(let r of A(t,`.bk-actions`))if(!r.hasAttribute(k)){if(r.setAttribute(k,``),e.onAction){j(n,r,c(r,e.onAction));continue}n.push(()=>{r.removeAttribute(k)})}return()=>{for(let e of n)e();n.length=0}}async function N(e={}){let t=e.container??document.body,n={...e,container:t},r=[],i=o.map(e=>({definition:e,elements:A(t,e.selector).filter(t=>!t.hasAttribute(k)&&(e.matches?.(t,n)??!0))})).filter(({elements:e})=>e.length>0);if(i.length===0)return()=>{};let a=await Promise.all(i.map(async({definition:e,elements:t})=>({island:await e.load(),elements:t})));for(let{island:e,elements:t}of a)for(let i of t)i.hasAttribute(k)||(i.setAttribute(k,``),j(r,i,e.hydrate(i,n)));return()=>{for(let e of r)e();r.length=0}}export{o as ISLAND_REGISTRY,M as hydrate,c as hydrateActions,N as hydrateAsync,b as hydrateTable,O as hydrateTree};
15
+ `,t}function o(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function s(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=a(r),s=r.createElement(`div`);s.className=`bk-checklist-progress`,e.parentElement?.insertBefore(s,e),r.head?.appendChild(i);let c=[];for(let[e,i]of n.entries()){let a=i.querySelector(`.bk-checklist-icon`),l=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,u=r.createElement(`input`);u.type=`checkbox`,u.className=`bk-checklist-box`,u.checked=i.getAttribute(`data-checked`)===`true`;let d=()=>{i.setAttribute(`data-checked`,String(u.checked));let r=o(s,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:l,checked:u.checked,complete:r.complete,total:r.total}))};u.addEventListener(`change`,d),c.push(()=>{u.removeEventListener(`change`,d)}),a?a.replaceWith(u):i.insertBefore(u,i.firstChild)}return o(s,n),()=>{for(let e of c)e();s.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}const c=`data-sort-label`,l=`data-sort-dir`,u=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function d(e){let t=e.getAttribute(c);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(c,n),n}function f(e,t,n){for(let[r,i]of e.entries())i.textContent=d(i),r===t?(i.setAttribute(l,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(l)}function p(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function m(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,m=null,h=[],g=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=u.compare(p(e,t),p(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}f(t,a,o)};for(let[e,n]of t.entries()){d(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),g()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),h.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){m=i.ownerDocument.createElement(`input`),m.className=`bk-table-filter`,m.placeholder=`Filter...`;let t=()=>{s=m?.value.toLowerCase().trim()??``,g()};i.insertBefore(m,e),m.addEventListener(`input`,t),h.push(()=>{m?.removeEventListener(`input`,t),m?.remove(),m=null})}return g(),()=>{for(let e of h)e();for(let e of t)e.textContent=d(e),e.removeAttribute(l),e.removeAttribute(c),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}function h(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function g(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return h(n);n=n.parentElement}return null}function _(e){return Array.from(e.querySelectorAll(`summary`))}function v(e){return e.open||e.hasAttribute(`open`)}function y(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function b(e,t){e.textContent=t.every(e=>v(e))?`Collapse all`:`Expand all`}function x(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!v(e));for(let n of t)y(n,e);b(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{b(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=_(e).map(t=>{t.tabIndex=0;let n=n=>{let r=_(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!v(a))y(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&v(a)?y(a,!1):g(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return b(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}const S=[{selector:`.bk-table`,matches:e=>!r(e.ownerDocument),load:async()=>({hydrate:e=>m(e)})},{selector:`.bk-table`,matches:(t,n)=>r(t.ownerDocument)&&e(t,`.bk-table`,n),load:()=>import(`./form-SyIoFeT1.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateForm(t,n)}))},{selector:`.bk-tree`,matches:e=>!n(e.ownerDocument),load:async()=>({hydrate:e=>x(e)})},{selector:`.bk-tree`,matches:e=>n(e.ownerDocument),load:()=>import(`./flame-graph-CV8KCLKu.mjs`).then(e=>({hydrate:(t,n)=>e.hydrateFlameGraph(t,n)}))},{selector:`.bk-actions`,load:async()=>({hydrate:(e,t)=>t?.onAction?i(e,t.onAction):()=>{}})},{selector:`.bk-checklist`,load:async()=>({hydrate:(e,t)=>s(e,t)})},{selector:`.bk-cards`,matches:(n,r)=>t(n.ownerDocument)&&e(n,`.bk-cards`,r),load:()=>import(`./picker-CZJricO9.mjs`).then(e=>({hydrate:(t,n)=>e.hydratePicker(t,n)}))}],C=`data-hydrated`;function w(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function T(e,t,n){e.push(()=>{n(),t.removeAttribute(C)})}function E(e={}){let t=e.container??document.body,n=[];for(let e of w(t,`.bk-table`))e.hasAttribute(C)||(e.setAttribute(C,``),T(n,e,m(e)));for(let e of w(t,`.bk-tree`))e.hasAttribute(C)||(e.setAttribute(C,``),T(n,e,x(e)));for(let r of w(t,`.bk-checklist`))r.hasAttribute(C)||(r.setAttribute(C,``),T(n,r,s(r,e)));for(let r of w(t,`.bk-actions`))if(!r.hasAttribute(C)){if(r.setAttribute(C,``),e.onAction){T(n,r,i(r,e.onAction));continue}n.push(()=>{r.removeAttribute(C)})}return()=>{for(let e of n)e();n.length=0}}async function D(e={}){let t=e.container??document.body,n={...e,container:t},r=[],i=S.map(e=>({definition:e,elements:w(t,e.selector).filter(t=>!t.hasAttribute(C)&&(e.matches?.(t,n)??!0))})).filter(({elements:e})=>e.length>0);if(i.length===0)return()=>{};let a=await Promise.all(i.map(async({definition:e,elements:t})=>({island:await e.load(),elements:t})));for(let{island:e,elements:t}of a)for(let i of t)i.hasAttribute(C)||(i.setAttribute(C,``),T(r,i,e.hydrate(i,n)));return()=>{for(let e of r)e();r.length=0}}export{S as ISLAND_REGISTRY,E as hydrate,i as hydrateActions,D as hydrateAsync,m as hydrateTable,x as hydrateTree};
@@ -20,10 +20,16 @@ interface CrawlResult {
20
20
  relativePath: string;
21
21
  /** Absolute file path */
22
22
  absolutePath: string;
23
- /** File content */
24
- content: string;
25
23
  /** File extension (lowercase, with dot) */
26
24
  extension: string;
25
+ /** File size in bytes */
26
+ size: number;
27
+ /** Last modified time in milliseconds since epoch */
28
+ mtimeMs: number;
29
+ /** Lazily read file content when downstream processing actually needs it. */
30
+ readContent: () => Promise<string>;
31
+ /** Cached file content after the first read. */
32
+ content?: string;
27
33
  }
28
34
  interface CrawlOptions {
29
35
  /** Glob patterns to exclude */
@@ -38,11 +44,13 @@ declare class FilesystemCrawler {
38
44
  /** Binary file extensions that should always be skipped */
39
45
  private static readonly BINARY_EXTENSIONS;
40
46
  private static readonly GENERATED_PATH_PATTERN;
41
- private currentFileSizeBytes;
47
+ private static readonly GENERATED_SAMPLE_LIMIT;
42
48
  crawl(options: CrawlOptions): Promise<CrawlResult[]>;
43
49
  private walkDir;
44
50
  private isExcluded;
45
- private isLikelyGenerated;
51
+ static isLikelyGeneratedPath(relativePath: string): boolean;
52
+ static isLikelyGeneratedContent(content: string, relativePath: string, _size: number): boolean;
53
+ private static readTextPreview;
46
54
  }
47
55
  //#endregion
48
56
  //#region packages/indexer/src/graph-extractor.d.ts
@@ -67,9 +75,14 @@ declare function extractGraph(content: string, sourcePath: string, options?: Ext
67
75
  //#region packages/indexer/src/hash-cache.d.ts
68
76
  /**
69
77
  * Persistent file hash cache.
70
- * Stores path->hash mappings in a JSON file to avoid LanceDB round-trips
71
- * when checking which files have changed during incremental indexing.
78
+ * Stores path->hash + metadata mappings in a JSON file to avoid repeated
79
+ * content reads and LanceDB round-trips when checking which files changed.
72
80
  */
81
+ interface FileHashCacheEntry {
82
+ hash: string;
83
+ size?: number;
84
+ mtimeMs?: number;
85
+ }
73
86
  declare class FileHashCache {
74
87
  private cache;
75
88
  private readonly filePath;
@@ -78,7 +91,11 @@ declare class FileHashCache {
78
91
  /** Load cache from disk. Non-fatal if missing or corrupt. */
79
92
  load(): void;
80
93
  get(path: string): string | undefined;
81
- set(path: string, hash: string): void;
94
+ getEntry(path: string): FileHashCacheEntry | undefined;
95
+ set(path: string, hash: string, metadata?: {
96
+ size: number;
97
+ mtimeMs: number;
98
+ }): void;
82
99
  delete(path: string): void;
83
100
  /** Persist cache to disk if changed. */
84
101
  flush(): void;
@@ -122,6 +139,8 @@ declare class IncrementalIndexer {
122
139
  * Modular — swap this to change dedup normalization strategy.
123
140
  */
124
141
  private normalizeChunkText;
142
+ private loadFileContent;
143
+ private isMetadataUnchanged;
125
144
  /** Set the graph store for auto-population during indexing and cleanup on re-index. */
126
145
  setGraphStore(graphStore: IGraphStore): void;
127
146
  /** Set the hash cache for faster incremental checks. */
@@ -1,3 +1,3 @@
1
- import{createHash as e}from"node:crypto";import{existsSync as t,readFileSync as n,realpathSync as r,statSync as i,writeFileSync as a}from"node:fs";import{lstat as o,readFile as s,readdir as c,stat as l}from"node:fs/promises";import{dirname as u,extname as d,join as f,relative as p,resolve as m}from"node:path";import{AIKIT_PATHS as h,FILE_LIMITS as g,createLogger as _,detectContentType as v,serializeError as y}from"../../core/dist/index.js";import{minimatch as b}from"minimatch";import{availableParallelism as x,loadavg as S}from"node:os";import{createChunkerSync as C}from"../../chunker/dist/index.js";function w(t){return e(`sha256`).update(t).digest(`hex`).slice(0,16)}function T(t,n){let r=`${t}:${n}`;return e(`sha256`).update(r).digest(`hex`).slice(0,16)}const E=_(`indexer`);var D=class e{static BINARY_EXTENSIONS=new Set(`.node,.so,.dylib,.dll,.wasm,.bin,.exe,.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.svg,.mp3,.mp4,.wav,.avi,.mov,.flac,.zip,.gz,.tar,.bz2,.7z,.rar,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.ttf,.otf,.woff,.woff2,.eot,.pyc,.class,.o,.obj,.a,.lib`.split(`,`));static GENERATED_PATH_PATTERN=/(?:lcov\.info|\.min\.(?:js|css)|\.css\.map|\.js\.map|\.map)$/i;currentFileSizeBytes=0;async crawl(e){let t=[],n=new Set;return await this.walkDir(e.rootDir,e.rootDir,e.excludePatterns,t,n),t}async walkDir(t,n,i,a,u){let m;try{m=await c(t,{withFileTypes:!0})}catch(e){let n=e.code;(n===`EACCES`||n===`EPERM`)&&E.warn(`Permission denied, skipping directory`,{dir:t});return}for(let c of m){let m=f(t,c.name),_=p(n,m).replace(/\\/g,`/`);if(!this.isExcluded(_,i)){if(c.isDirectory()){if(c.name.startsWith(`.`)&&!(c.name===h.ai.slice(1)&&_.startsWith(h.ai)))continue;try{if((await o(m)).isSymbolicLink())continue}catch{continue}let e;try{e=r(m)}catch{continue}if(u.has(e))continue;u.add(e),await this.walkDir(m,n,i,a,u)}else if(c.isFile()){let t=d(c.name).toLowerCase();if(e.BINARY_EXTENSIONS.has(t))continue;try{let e=await l(m);if(this.currentFileSizeBytes=e.size,e.size>g.maxFileSizeBytes)continue;let n=await s(m,`utf-8`);if(n.includes(`\0`))continue;if(this.isLikelyGenerated(n,_)){E.debug(`Skipping likely generated file`,{path:_});continue}a.push({relativePath:_,absolutePath:m,content:n,extension:t})}catch{}}}}}isExcluded(e,t){return t.some(t=>b(e,t,{dot:!0}))}isLikelyGenerated(t,n){let r=d(n).toLowerCase();if(e.GENERATED_PATH_PATTERN.test(n)||r===`.snap`&&this.currentFileSizeBytes>5e4||n.split(`/`).includes(`coverage`)&&r===``)return!0;let i=t.slice(0,5e4).split(`
2
- `),a=i.slice(0,100);if(a.length>0&&a.reduce((e,t)=>e+t.length,0)/a.length>500)return!0;let o=i.slice(1,201);if(o.length>=20){let e=new Map,t=0;for(let n of o){let r=n.replace(/\d/g,`#`).slice(0,40),i=(e.get(r)??0)+1;e.set(r,i),i>t&&(t=i)}if(t/o.length>.8)return!0}if(t.length>1e5){let e=0;for(let n of t)if(n===`
3
- `&&(e+=1,e>=10))break;if(e<10)return!0}return!1}};const O=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`]),k=[{pattern:/^export\s+(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!0},{pattern:/^export\s+(?:default\s+)?class\s+(\w+)/gm,kind:`class`,exported:!0},{pattern:/^export\s+interface\s+(\w+)/gm,kind:`interface`,exported:!0},{pattern:/^export\s+type\s+(\w+)/gm,kind:`type`,exported:!0},{pattern:/^export\s+(?:const|let)\s+(\w+)/gm,kind:`const`,exported:!0},{pattern:/^export\s+enum\s+(\w+)/gm,kind:`enum`,exported:!0},{pattern:/^(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!1},{pattern:/^class\s+(\w+)/gm,kind:`class`,exported:!1},{pattern:/^interface\s+(\w+)/gm,kind:`interface`,exported:!1},{pattern:/^type\s+(\w+)/gm,kind:`type`,exported:!1},{pattern:/^enum\s+(\w+)/gm,kind:`enum`,exported:!1}],A=[/import\s+(?:(?:type\s+)?(?:(?:\{[^}]*\}|[\w*]+)\s+from\s+)?)['"]([^'"]+)['"]/g,/import\(\s*['"]([^'"]+)['"]\s*\)/g,/require\(\s*['"]([^'"]+)['"]\s*\)/g];function j(t,n,r){return e(`sha256`).update(`${t}:${n}:${r}`).digest(`hex`).slice(0,16)}function M(t,n,r){return e(`sha256`).update(`${t}-${r}-${n}`).digest(`hex`).slice(0,16)}function N(e,t){return f(u(t),e).replace(/\\/g,`/`).replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function P(e){return e.replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function F(e,t,n){let r=d(t).toLowerCase();if(!O.has(r))return{nodes:[],edges:[]};let i=[],a=[],o=new Date().toISOString(),s=new Set,c=P(t),l=j(`module`,c,c);i.push({id:l,type:`module`,name:t,properties:{ext:r},sourcePath:t,createdAt:o});for(let{pattern:n,kind:r,exported:c}of k){let u=new RegExp(n.source,n.flags),d;for(;(d=u.exec(e))!==null;){let e=d[1],n=`${r}:${e}`;if(s.has(n))continue;s.add(n);let u=j(r,e,t);i.push({id:u,type:r,name:e,properties:{exported:c},sourcePath:t,createdAt:o}),a.push({id:M(l,u,`defines`),fromId:l,toId:u,type:`defines`,weight:c?1:.5})}}let u=n?.workspacePackages,f=new Set;for(let n of A){let r=new RegExp(n.source,n.flags),i;for(;(i=r.exec(e))!==null;){let e=i[1];if(f.has(e))continue;let n;if(e.startsWith(`.`))n=N(e,t);else if(u){let t=e.startsWith(`@`)?e.split(`/`).slice(0,2).join(`/`):e.split(`/`)[0],r=u.get(t);if(!r)continue;n=r}else continue;f.add(e);let r=P(n),o=j(`module`,r,r);a.push({id:M(l,o,`imports`),fromId:l,toId:o,type:`imports`,properties:{source:e}})}}return{nodes:i,edges:a}}const I=_(`hash-cache`);var L=class{cache;filePath;dirty=!1;constructor(e){this.filePath=m(e,`file-hashes.json`),this.cache=new Map}load(){if(t(this.filePath))try{let e=n(this.filePath,`utf-8`),t=JSON.parse(e);this.cache=new Map(Object.entries(t)),I.debug(`Hash cache loaded`,{entries:this.cache.size})}catch(e){I.warn(`Hash cache load failed, starting fresh`,{err:e}),this.cache=new Map}}get(e){return this.cache.get(e)}set(e,t){this.cache.set(e,t),this.dirty=!0}delete(e){this.cache.delete(e)&&(this.dirty=!0)}flush(){if(this.dirty)try{let e={};for(let[t,n]of this.cache)e[t]=n;a(this.filePath,JSON.stringify(e),`utf-8`),this.dirty=!1}catch(e){I.warn(`Hash cache flush failed`,{err:e})}}clear(){this.cache.clear(),this.dirty=!0,this.flush()}get size(){return this.cache.size}};const R=_(`indexer`),z=()=>new Promise(e=>setImmediate(e));async function B(e,t,n,r){let i=0;async function a(){for(;i<e.length;){let n=i++;try{await t(e[n])}catch(t){r?.(e[n],t)}n%10==0&&await z()}}await Promise.all(Array.from({length:Math.min(n,e.length)},()=>a()))}function V(e){let t=x(),n=S()[0]/t;return n>1.5?2:n>1?Math.max(2,Math.floor(e/2)):e}const H=Math.max(2,Math.min(4,Math.floor(x()*.5)));var U=class{embedder;store;crawler;indexing=!1;graphStore;hashCache;get isIndexing(){return this.indexing}constructor(e,t){this.embedder=e,this.store=t,this.crawler=new D}normalizeChunkText(e){return e.replace(/^\/\/ File: [^\n]*\n?/,``).toLowerCase().replace(/\s+/g,` `).trim()}setGraphStore(e){this.graphStore=e}setHashCache(e){this.hashCache=e}async index(e,t){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{return await this.doIndex(e,t,{})}finally{this.indexing=!1}}async getChangedFiles(e){let t=e.indexing.concurrency??H,n=await this.crawlSources(e),{filesToProcess:r}=await this.planIndexWork(n,t,{});return r.map(e=>e.relativePath)}async indexFiles(e,t,n){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{return await this.doIndexFiles(e,t,n)}finally{this.indexing=!1}}async doIndex(e,t,n={}){let r=Date.now(),i=e.indexing.concurrency??H;t?.({phase:`crawling`,filesTotal:0,filesProcessed:0,chunksTotal:0,chunksProcessed:0});let a=await this.crawlSources(e),{filesToProcess:o,filesSkipped:s,pathsToRemove:c}=await this.planIndexWork(a,i,{skipHashCheck:n.skipHashCheck}),{filesProcessed:l,chunksCreated:u,chunksDeduped:d}=await this.processFiles(a,o,i,t,{graphCleared:n.graphCleared}),f=await this.cleanupRemovedFiles(c,i,o.length,l,u,t);return this.hashCache?.flush(),t?.({phase:`done`,filesTotal:o.length,filesProcessed:l,chunksTotal:u,chunksProcessed:u}),{filesProcessed:l,filesSkipped:s,chunksCreated:u,chunksDeduped:d,filesRemoved:f,durationMs:Date.now()-r}}async doIndexFiles(e,t,n){let r=Date.now(),i=e.indexing.concurrency??H,a=new Set(t);if(a.size===0)return{filesProcessed:0,filesSkipped:0,chunksCreated:0,chunksDeduped:0,filesRemoved:0,durationMs:Date.now()-r};n?.({phase:`crawling`,filesTotal:0,filesProcessed:0,chunksTotal:0,chunksProcessed:0});let o=await this.crawlSources(e),{filesToProcess:s,filesSkipped:c}=await this.planIndexWork(o,i,{requestedPaths:a}),{filesProcessed:l,chunksCreated:u,chunksDeduped:d}=await this.processFiles(o,s,i,n,{});return this.hashCache?.flush(),n?.({phase:`done`,filesTotal:s.length,filesProcessed:l,chunksTotal:u,chunksProcessed:u}),{filesProcessed:l,filesSkipped:c,chunksCreated:u,chunksDeduped:d,filesRemoved:0,durationMs:Date.now()-r}}async crawlSources(e){return(await Promise.all(e.sources.map(e=>this.crawler.crawl({rootDir:e.path,excludePatterns:e.excludePatterns})))).flat()}async planIndexWork(e,t,n){let r=n.requestedPaths,i;if(r){let t=e=>e.replace(/\\/g,`/`).toLowerCase(),n=new Set([...r].map(t));i=e.filter(e=>n.has(t(e.relativePath))||n.has(t(e.absolutePath)))}else i=e;if(n.skipHashCheck)return{filesToProcess:i,filesSkipped:0,pathsToRemove:[]};let a=r?[]:await this.getPathsToRemove(e),o=0,s=[];return await B(i,async e=>{let t=w(e.content);if(this.hashCache){if(this.hashCache.get(e.relativePath)===t){o++;return}}else{let n=await this.store.getBySourcePath(e.relativePath);if(n.length>0&&n[0].fileHash===t){o++;return}}s.push(e)},V(t),(e,t)=>R.error(`Hash check failed`,{sourcePath:e.relativePath,...y(t)})),{filesToProcess:s,filesSkipped:o,pathsToRemove:a}}async getPathsToRemove(e){let t=await this.store.listSourcePaths(),n=new Set(e.map(e=>e.relativePath));return t.filter(e=>!n.has(e)&&!e.startsWith(`${h.aiCurated}/`))}async buildWorkspacePackageMap(e){let t=new Map;for(let n of e)if(n.relativePath.endsWith(`package.json`))try{let e=JSON.parse(n.content);if(typeof e.name!=`string`||e.name.length===0)continue;let r=n.relativePath===`package.json`?``:n.relativePath.replace(/\/package\.json$/,``),i=``;if(typeof e.exports==`string`)i=e.exports;else if(e.exports&&typeof e.exports==`object`){let t=e.exports,n=t[`.`]??t;if(typeof n==`string`)i=n;else if(n&&typeof n==`object`){let e=n,t=e.import??e.module??e.default??e.require;typeof t==`string`&&(i=t)}}!i&&typeof e.module==`string`&&(i=e.module),!i&&typeof e.main==`string`&&(i=e.main);let a=i.replace(/^\.\//,``).replace(/^dist\//,`src/`).replace(/\.(ts|js|mjs|cjs|tsx|jsx)$/,``),o=a?r?`${r}/${a}`:a:r?`${r}/src/index`:`src/index`;t.set(e.name,o)}catch{}return t}async processFiles(t,n,r,i,a={}){let o=0,s=0,c=0,l=n.length,u=this.graphStore?await this.buildWorkspacePackageMap(t):void 0,d=new Map,f=[],p=[],m=0,h=[],g=[],_=new Map,b=0,x=async()=>{if(h.length===0)return;let e=h,t=g,n=_;h=[],g=[],_=new Map,b=0;try{await this.store.upsert(e,t);for(let[e,t]of n)this.hashCache?.set(e,t)}catch(r){h.push(...e),g.push(...t);for(let[e,t]of n)_.set(e,t);throw r}},S=async()=>{if(this.graphStore){try{f.length>0&&await this.graphStore.upsertNodes(f),p.length>0&&await this.graphStore.upsertEdges(p)}catch(e){R.warn(`Graph batch flush failed`,y(e))}f=[],p=[],m=0}};return await B(n,async t=>{i?.({phase:`chunking`,filesTotal:l,filesProcessed:o,chunksTotal:s,chunksProcessed:s,currentFile:t.relativePath});let n=v(t.relativePath),r=C(t.extension).chunk(t.content,{sourcePath:t.relativePath,contentType:n});if(r.length===0)return;let E=w(t.content),D=new Date().toISOString(),O=(e,n,r)=>({id:T(t.relativePath,n),content:e.text,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:E,contentHash:r,indexedAt:D,origin:`indexed`,tags:[],version:1}),k=[],A=[];for(let t=0;t<r.length;t++){let n=r[t],i=e(`sha256`).update(this.normalizeChunkText(n.text)).digest(`hex`),a=O(n,t,i),o=d.get(i);if(o&&this.store.upsertWithoutVector){A.push({record:a,sourceRecordId:o}),c++;continue}d.set(i,a.id),k.push({chunk:n,record:a})}i?.({phase:`embedding`,filesTotal:l,filesProcessed:o,chunksTotal:s+r.length,chunksProcessed:s,currentFile:t.relativePath});let j=k.length>0?await this.embedder.embedBatch(k.map(({chunk:e})=>e.text)):[],M=k.map(({record:e})=>e);if(i?.({phase:`storing`,filesTotal:l,filesProcessed:o,chunksTotal:s+r.length,chunksProcessed:s,currentFile:t.relativePath}),M.length>0&&(h.push(...M),g.push(...j),_.set(t.relativePath,E),b++,b>=20&&await x()),A.length>0&&h.length>0&&await x(),this.store.upsertWithoutVector)for(let{record:e,sourceRecordId:t}of A)await this.store.upsertWithoutVector(e,t);if(M.length===0&&A.length>0&&this.hashCache?.set(t.relativePath,E),this.graphStore)try{a.graphCleared||await this.graphStore.deleteBySourcePath(t.relativePath);let e=F(t.content,t.relativePath,{workspacePackages:u});e.nodes.length>0&&f.push(...e.nodes),e.edges.length>0&&p.push(...e.edges),m++,m>=50&&await S()}catch(e){R.warn(`Graph extraction failed`,{sourcePath:t.relativePath,...y(e)})}o++,s+=r.length},V(r),(e,t)=>R.error(`Processing failed`,{sourcePath:e.relativePath,...y(t)})),await x(),await S(),{filesProcessed:o,chunksCreated:s,chunksDeduped:c}}async cleanupRemovedFiles(e,t,n,r,i,a){if(e.length===0)return 0;let o=0;return a?.({phase:`cleanup`,filesTotal:n,filesProcessed:r,chunksTotal:i,chunksProcessed:i}),await B(e,async e=>{await this.store.deleteBySourcePath(e),this.hashCache?.delete(e),this.graphStore&&await this.graphStore.deleteBySourcePath(e).catch(t=>R.warn(`Graph cleanup failed`,{sourcePath:e,...y(t)})),o++},V(t),(e,t)=>R.error(`Cleanup failed`,{sourcePath:e,...y(t)})),o}async reindexAll(e,t){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{if(await this.store.dropTable(),this.graphStore)try{let e=await this.graphStore.getStats();e.nodeCount>0&&(await this.graphStore.clear(),R.info(`Graph store cleared`,{nodeCount:e.nodeCount,edgeCount:e.edgeCount}))}catch(e){R.warn(`Graph store clear failed`,y(e))}return await this.doReindex(e,t)}catch(e){throw this.indexing=!1,e}}async doReindex(e,t){try{return await this.doIndex(e,t,{skipHashCheck:!0,graphCleared:!0})}finally{this.indexing=!1}}async getStats(){return this.store.getStats()}};const W=_(`smart-index`),G=1.5;var K=class{indexer;config;store;trickleTimer=null;stopped=!1;trickleIntervalMs;batchSize;priorityQueue=[];changedFiles=[];lastRefreshTime=0;refreshing=!1;constructor(e,t,n){this.indexer=e,this.config=t,this.store=n,this.trickleIntervalMs=t.indexing.trickleIntervalMs??this.readPositiveIntEnv(`AIKIT_SMART_TRICKLE_MS`,3e4),this.batchSize=t.indexing.trickleBatchSize??this.readPositiveIntEnv(`AIKIT_SMART_BATCH_SIZE`,1)}start(){this.trickleTimer&&=(clearTimeout(this.trickleTimer),null),this.stopped=!1,W.debug(`Smart index scheduler started (trickle mode)`,{intervalMs:this.trickleIntervalMs,batchSize:this.batchSize}),this.scheduleTick()}stop(){this.stopped=!0,this.trickleTimer&&=(clearTimeout(this.trickleTimer),null)}prioritize(...e){let t=[...new Set(e.filter(Boolean))].filter(e=>{try{return!i(e).isDirectory()}catch{return W.debug(`Skipping non-existent path`,{path:e}),!1}});for(let e of t){let t=this.priorityQueue.indexOf(e);t>=0&&this.priorityQueue.splice(t,1)}for(let e of t.reverse())this.priorityQueue.unshift(e);this.priorityQueue.length>500&&(this.priorityQueue.length=500),t.length>0&&W.debug(`Files prioritized for trickle indexing`,{added:t.length,queued:this.priorityQueue.length})}getState(){return{mode:`smart`,queueSize:this.priorityQueue.length,changedFilesSize:this.changedFiles.length,intervalMs:this.trickleIntervalMs,batchSize:this.batchSize,running:this.trickleTimer!==null}}readPositiveIntEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?n:t}scheduleTick(){this.trickleTimer=setTimeout(()=>void this.tick(),this.trickleIntervalMs),this.trickleTimer.unref&&this.trickleTimer.unref()}async tick(){if(!this.stopped)try{if(this.indexer.isIndexing){W.info(`Skipping trickle tick — indexing already in progress`);return}let e=this.getCpuCount(),t=S()[0];if(e>0&&t/e>G){W.info(`Skipping trickle tick — system load too high`,{load:t.toFixed(2),cpuCount:e,threshold:G});return}let n=await this.pickFiles();if(n.length===0){await this.maybeRefreshChangedFiles();return}W.debug(`Trickle indexing tick started`,{count:n.length,files:n});let r=await this.indexer.indexFiles(this.config,n);if(this.store)try{await this.store.createFtsIndex()}catch(e){W.warn(`FTS index rebuild failed after trickle tick`,{error:String(e)})}this.changedFiles=this.changedFiles.filter(e=>!n.includes(e)),W.debug(`Trickle indexing tick complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated})}catch(e){let t=String(e);if(t.includes(`not initialized`)||t.includes(`has been closed`)){W.warn(`Store closed — stopping smart index scheduler`,{error:t}),this.stop();return}W.error(`Trickle indexing tick failed`,{error:t})}finally{this.stopped||this.scheduleTick()}}getCpuCount(){try{return typeof x==`function`?x():4}catch{return 4}}async pickFiles(){let e=[];for(;e.length<this.batchSize&&this.priorityQueue.length>0;){let t=this.priorityQueue.shift();t&&!e.includes(t)&&e.push(t)}if(e.length<this.batchSize)for(await this.maybeRefreshChangedFiles();e.length<this.batchSize&&this.changedFiles.length>0;){let t=this.changedFiles.shift();t&&!e.includes(t)&&e.push(t)}return e}async maybeRefreshChangedFiles(){let e=Date.now();if(!(this.refreshing||this.changedFiles.length>0&&e-this.lastRefreshTime<6e5)){this.refreshing=!0;try{this.changedFiles=await this.indexer.getChangedFiles(this.config),this.lastRefreshTime=e,this.changedFiles.length>0&&W.debug(`Refreshed changed files for trickle indexing`,{count:this.changedFiles.length})}catch(e){let t=String(e);if(t.includes(`not initialized`)||t.includes(`has been closed`)){W.warn(`Store closed — stopping smart index scheduler`,{error:t}),this.stop();return}W.error(`Failed to refresh changed files for trickle indexing`,{error:t})}finally{this.refreshing=!1}}}};export{L as FileHashCache,D as FilesystemCrawler,U as IncrementalIndexer,K as SmartIndexScheduler,F as extractGraph,T as generateRecordId,w as hashContent};
1
+ import{createHash as e}from"node:crypto";import{existsSync as t,readFileSync as n,realpathSync as r,statSync as i,writeFileSync as a}from"node:fs";import{lstat as o,open as s,readFile as c,readdir as l,stat as u}from"node:fs/promises";import{dirname as d,extname as f,join as p,relative as m,resolve as h}from"node:path";import{AIKIT_PATHS as g,FILE_LIMITS as _,createLogger as v,detectContentType as y,serializeError as b}from"../../core/dist/index.js";import{minimatch as x}from"minimatch";import{availableParallelism as S,loadavg as C}from"node:os";import{createChunkerSync as w}from"../../chunker/dist/index.js";function T(t){return e(`sha256`).update(t).digest(`hex`).slice(0,16)}function E(t,n){let r=`${t}:${n}`;return e(`sha256`).update(r).digest(`hex`).slice(0,16)}const D=v(`indexer`);var O=class e{static BINARY_EXTENSIONS=new Set(`.node,.so,.dylib,.dll,.wasm,.bin,.exe,.png,.jpg,.jpeg,.gif,.bmp,.ico,.webp,.svg,.mp3,.mp4,.wav,.avi,.mov,.flac,.zip,.gz,.tar,.bz2,.7z,.rar,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.ttf,.otf,.woff,.woff2,.eot,.pyc,.class,.o,.obj,.a,.lib`.split(`,`));static GENERATED_PATH_PATTERN=/(?:lcov\.info|\.min\.(?:js|css)|\.css\.map|\.js\.map|\.map)$/i;static GENERATED_SAMPLE_LIMIT=5e4;async crawl(e){let t=[],n=new Set;return await this.walkDir(e.rootDir,e.rootDir,e.excludePatterns,t,n),t}async walkDir(t,n,i,a,s){let d;try{d=await l(t,{withFileTypes:!0})}catch(e){let n=e.code;(n===`EACCES`||n===`EPERM`)&&D.warn(`Permission denied, skipping directory`,{dir:t});return}for(let l of d){let d=p(t,l.name),h=m(n,d).replace(/\\/g,`/`);if(!this.isExcluded(h,i)){if(l.isDirectory()){if(l.name.startsWith(`.`)&&!(l.name===g.ai.slice(1)&&h.startsWith(g.ai)))continue;try{if((await o(d)).isSymbolicLink())continue}catch{continue}let e;try{e=r(d)}catch{continue}if(s.has(e))continue;s.add(e),await this.walkDir(d,n,i,a,s)}else if(l.isFile()){let t=f(l.name).toLowerCase();if(e.BINARY_EXTENSIONS.has(t))continue;try{let n=await u(d);if(n.size>_.maxFileSizeBytes)continue;if(e.isLikelyGeneratedPath(h)){D.debug(`Skipping likely generated file`,{path:h});continue}if(t===`.snap`&&n.size>e.GENERATED_SAMPLE_LIMIT){D.debug(`Skipping likely generated snapshot`,{path:h});continue}let r;try{r=await e.readTextPreview(d)}catch{continue}if(r.includes(`\0`))continue;if(e.isLikelyGeneratedContent(r,h,n.size)){D.debug(`Skipping likely generated file`,{path:h});continue}let i,o,s={relativePath:h,absolutePath:d,extension:t,size:n.size,mtimeMs:n.mtimeMs,content:i,readContent:async()=>i===void 0?(o??=c(d,`utf-8`).then(e=>(i=e,s.content=e,e)),o):i};a.push(s)}catch{}}}}}isExcluded(e,t){return t.some(t=>x(e,t,{dot:!0}))}static isLikelyGeneratedPath(t){return e.GENERATED_PATH_PATTERN.test(t)}static isLikelyGeneratedContent(e,t,n){let r=f(t).toLowerCase();if(t.split(`/`).includes(`coverage`)&&r===``)return!0;let i=e.slice(0,5e4).split(`
2
+ `),a=i.slice(0,100);if(a.length>0&&a.reduce((e,t)=>e+t.length,0)/a.length>500)return!0;let o=i.slice(1,201);if(o.length>=20){let e=new Map,t=0;for(let n of o){let r=n.replace(/\d/g,`#`).slice(0,40),i=(e.get(r)??0)+1;e.set(r,i),i>t&&(t=i)}if(t/o.length>.8)return!0}if(e.length>1e5){let t=0;for(let n of e)if(n===`
3
+ `&&(t+=1,t>=10))break;if(t<10)return!0}return!1}static async readTextPreview(t){let n=await s(t,`r`);try{let t=Buffer.alloc(e.GENERATED_SAMPLE_LIMIT),{bytesRead:r}=await n.read(t,0,t.length,0);return t.toString(`utf8`,0,r)}finally{await n.close()}}};const k=new Set([`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`,`.cjs`]),A=[{pattern:/^export\s+(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!0},{pattern:/^export\s+(?:default\s+)?class\s+(\w+)/gm,kind:`class`,exported:!0},{pattern:/^export\s+interface\s+(\w+)/gm,kind:`interface`,exported:!0},{pattern:/^export\s+type\s+(\w+)/gm,kind:`type`,exported:!0},{pattern:/^export\s+(?:const|let)\s+(\w+)/gm,kind:`const`,exported:!0},{pattern:/^export\s+enum\s+(\w+)/gm,kind:`enum`,exported:!0},{pattern:/^(?:async\s+)?function\s+(\w+)/gm,kind:`function`,exported:!1},{pattern:/^class\s+(\w+)/gm,kind:`class`,exported:!1},{pattern:/^interface\s+(\w+)/gm,kind:`interface`,exported:!1},{pattern:/^type\s+(\w+)/gm,kind:`type`,exported:!1},{pattern:/^enum\s+(\w+)/gm,kind:`enum`,exported:!1}],j=[/import\s+(?:(?:type\s+)?(?:(?:\{[^}]*\}|[\w*]+)\s+from\s+)?)['"]([^'"]+)['"]/g,/import\(\s*['"]([^'"]+)['"]\s*\)/g,/require\(\s*['"]([^'"]+)['"]\s*\)/g];function M(t,n,r){return e(`sha256`).update(`${t}:${n}:${r}`).digest(`hex`).slice(0,16)}function N(t,n,r){return e(`sha256`).update(`${t}-${r}-${n}`).digest(`hex`).slice(0,16)}function P(e,t){return p(d(t),e).replace(/\\/g,`/`).replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function F(e){return e.replace(/\.(js|jsx|ts|tsx|mjs|cjs)$/,``)}function I(e,t,n){let r=f(t).toLowerCase();if(!k.has(r))return{nodes:[],edges:[]};let i=[],a=[],o=new Date().toISOString(),s=new Set,c=F(t),l=M(`module`,c,c);i.push({id:l,type:`module`,name:t,properties:{ext:r},sourcePath:t,createdAt:o});for(let{pattern:n,kind:r,exported:c}of A){let u=new RegExp(n.source,n.flags),d;for(;(d=u.exec(e))!==null;){let e=d[1],n=`${r}:${e}`;if(s.has(n))continue;s.add(n);let u=M(r,e,t);i.push({id:u,type:r,name:e,properties:{exported:c},sourcePath:t,createdAt:o}),a.push({id:N(l,u,`defines`),fromId:l,toId:u,type:`defines`,weight:c?1:.5})}}let u=n?.workspacePackages,d=new Set;for(let n of j){let r=new RegExp(n.source,n.flags),i;for(;(i=r.exec(e))!==null;){let e=i[1];if(d.has(e))continue;let n;if(e.startsWith(`.`))n=P(e,t);else if(u){let t=e.startsWith(`@`)?e.split(`/`).slice(0,2).join(`/`):e.split(`/`)[0],r=u.get(t);if(!r)continue;n=r}else continue;d.add(e);let r=F(n),o=M(`module`,r,r);a.push({id:N(l,o,`imports`),fromId:l,toId:o,type:`imports`,properties:{source:e}})}}return{nodes:i,edges:a}}const L=v(`hash-cache`);var R=class{cache;filePath;dirty=!1;constructor(e){this.filePath=h(e,`file-hashes.json`),this.cache=new Map}load(){if(t(this.filePath))try{let e=n(this.filePath,`utf-8`),t=JSON.parse(e);this.cache=new Map(Object.entries(t).map(([e,t])=>[e,typeof t==`string`?{hash:t}:t])),L.debug(`Hash cache loaded`,{entries:this.cache.size})}catch(e){L.warn(`Hash cache load failed, starting fresh`,{err:e}),this.cache=new Map}}get(e){return this.cache.get(e)?.hash}getEntry(e){return this.cache.get(e)}set(e,t,n){this.cache.set(e,{hash:t,...n?{size:n.size,mtimeMs:n.mtimeMs}:{}}),this.dirty=!0}delete(e){this.cache.delete(e)&&(this.dirty=!0)}flush(){if(this.dirty)try{let e={};for(let[t,n]of this.cache)e[t]=n;a(this.filePath,JSON.stringify(e),`utf-8`),this.dirty=!1}catch(e){L.warn(`Hash cache flush failed`,{err:e})}}clear(){this.cache.clear(),this.dirty=!0,this.flush()}get size(){return this.cache.size}};const z=v(`indexer`),B=()=>new Promise(e=>setImmediate(e));async function V(e,t,n,r){let i=0;async function a(){for(;i<e.length;){let n=i++;try{await t(e[n])}catch(t){r?.(e[n],t)}n%10==0&&await B()}}await Promise.all(Array.from({length:Math.min(n,e.length)},()=>a()))}function H(e){let t=S(),n=C()[0]/t;return n>1.5?2:n>1?Math.max(2,Math.floor(e/2)):e}const U=Math.max(2,Math.min(4,Math.floor(S()*.5)));var W=class{embedder;store;crawler;indexing=!1;graphStore;hashCache;get isIndexing(){return this.indexing}constructor(e,t){this.embedder=e,this.store=t,this.crawler=new O}normalizeChunkText(e){return e.replace(/^\/\/ File: [^\n]*\n?/,``).toLowerCase().replace(/\s+/g,` `).trim()}async loadFileContent(e){if(e.content!==void 0)return e.content;let t=await e.readContent();return e.content=t,t}isMetadataUnchanged(e,t){return t?.size!==void 0&&t?.mtimeMs!==void 0&&t.size===e.size&&t.mtimeMs===e.mtimeMs}setGraphStore(e){this.graphStore=e}setHashCache(e){this.hashCache=e}async index(e,t){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{return await this.doIndex(e,t,{})}finally{this.indexing=!1}}async getChangedFiles(e){let t=e.indexing.concurrency??U,n=await this.crawlSources(e),{filesToProcess:r}=await this.planIndexWork(n,t,{});return r.map(e=>e.relativePath)}async indexFiles(e,t,n){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{return await this.doIndexFiles(e,t,n)}finally{this.indexing=!1}}async doIndex(e,t,n={}){let r=Date.now(),i=e.indexing.concurrency??U;t?.({phase:`crawling`,filesTotal:0,filesProcessed:0,chunksTotal:0,chunksProcessed:0});let a=await this.crawlSources(e),{filesToProcess:o,filesSkipped:s,pathsToRemove:c}=await this.planIndexWork(a,i,{skipHashCheck:n.skipHashCheck}),{filesProcessed:l,chunksCreated:u,chunksDeduped:d}=await this.processFiles(a,o,i,t,{graphCleared:n.graphCleared}),f=await this.cleanupRemovedFiles(c,i,o.length,l,u,t);return this.hashCache?.flush(),t?.({phase:`done`,filesTotal:o.length,filesProcessed:l,chunksTotal:u,chunksProcessed:u}),{filesProcessed:l,filesSkipped:s,chunksCreated:u,chunksDeduped:d,filesRemoved:f,durationMs:Date.now()-r}}async doIndexFiles(e,t,n){let r=Date.now(),i=e.indexing.concurrency??U,a=new Set(t);if(a.size===0)return{filesProcessed:0,filesSkipped:0,chunksCreated:0,chunksDeduped:0,filesRemoved:0,durationMs:Date.now()-r};n?.({phase:`crawling`,filesTotal:0,filesProcessed:0,chunksTotal:0,chunksProcessed:0});let o=await this.crawlSources(e),{filesToProcess:s,filesSkipped:c}=await this.planIndexWork(o,i,{requestedPaths:a}),{filesProcessed:l,chunksCreated:u,chunksDeduped:d}=await this.processFiles(o,s,i,n,{});return this.hashCache?.flush(),n?.({phase:`done`,filesTotal:s.length,filesProcessed:l,chunksTotal:u,chunksProcessed:u}),{filesProcessed:l,filesSkipped:c,chunksCreated:u,chunksDeduped:d,filesRemoved:0,durationMs:Date.now()-r}}async crawlSources(e){return(await Promise.all(e.sources.map(e=>this.crawler.crawl({rootDir:e.path,excludePatterns:e.excludePatterns})))).flat()}async planIndexWork(e,t,n){let r=n.requestedPaths,i;if(r){let t=e=>e.replace(/\\/g,`/`).toLowerCase(),n=new Set([...r].map(t));i=e.filter(e=>n.has(t(e.relativePath))||n.has(t(e.absolutePath)))}else i=e;if(n.skipHashCheck)return{filesToProcess:i,filesSkipped:0,pathsToRemove:[]};let a=r?[]:await this.getPathsToRemove(e),o=0,s=[];return await V(i,async e=>{let t=this.hashCache?.getEntry(e.relativePath);if(this.isMetadataUnchanged(e,t)){o++;return}let n=await this.loadFileContent(e);if(n.includes(`\0`)){o++;return}if(O.isLikelyGeneratedContent(n,e.relativePath,e.size)){o++;return}let r=T(n);if(this.hashCache){if((t?.hash??this.hashCache.get(e.relativePath))===r){o++;return}}else{let t=await this.store.getBySourcePath(e.relativePath);if(t.length>0&&t[0].fileHash===r){o++;return}}s.push(e)},H(t),(e,t)=>z.error(`Hash check failed`,{sourcePath:e.relativePath,...b(t)})),{filesToProcess:s,filesSkipped:o,pathsToRemove:a}}async getPathsToRemove(e){let t=await this.store.listSourcePaths(),n=new Set(e.map(e=>e.relativePath));return t.filter(e=>!n.has(e)&&!e.startsWith(`${g.aiCurated}/`))}async buildWorkspacePackageMap(e){let t=new Map;for(let n of e)if(n.relativePath.endsWith(`package.json`))try{let e=JSON.parse(await this.loadFileContent(n));if(typeof e.name!=`string`||e.name.length===0)continue;let r=n.relativePath===`package.json`?``:n.relativePath.replace(/\/package\.json$/,``),i=``;if(typeof e.exports==`string`)i=e.exports;else if(e.exports&&typeof e.exports==`object`){let t=e.exports,n=t[`.`]??t;if(typeof n==`string`)i=n;else if(n&&typeof n==`object`){let e=n,t=e.import??e.module??e.default??e.require;typeof t==`string`&&(i=t)}}!i&&typeof e.module==`string`&&(i=e.module),!i&&typeof e.main==`string`&&(i=e.main);let a=i.replace(/^\.\//,``).replace(/^dist\//,`src/`).replace(/\.(ts|js|mjs|cjs|tsx|jsx)$/,``),o=a?r?`${r}/${a}`:a:r?`${r}/src/index`:`src/index`;t.set(e.name,o)}catch{}return t}async processFiles(t,n,r,i,a={}){let o=0,s=0,c=0,l=n.length,u=this.graphStore?await this.buildWorkspacePackageMap(t):void 0,d=new Map,f=[],p=[],m=0,h=[],g=[],_=new Map,v=0,x=async()=>{if(h.length===0)return;let e=h,t=g,n=_;h=[],g=[],_=new Map,v=0;try{await this.store.upsert(e,t);for(let[e,t]of n)this.hashCache?.set(e,t.hash,{size:t.size,mtimeMs:t.mtimeMs})}catch(r){h.push(...e),g.push(...t);for(let[e,t]of n)_.set(e,t);throw r}},S=async()=>{if(this.graphStore){try{f.length>0&&await this.graphStore.upsertNodes(f),p.length>0&&await this.graphStore.upsertEdges(p)}catch(e){z.warn(`Graph batch flush failed`,b(e))}f=[],p=[],m=0}};return await V(n,async t=>{i?.({phase:`chunking`,filesTotal:l,filesProcessed:o,chunksTotal:s,chunksProcessed:s,currentFile:t.relativePath});let n=await this.loadFileContent(t),r=y(t.relativePath),C=w(t.extension).chunk(n,{sourcePath:t.relativePath,contentType:r});if(C.length===0)return;let D=T(n),O=new Date().toISOString(),k=(e,n,r)=>({id:E(t.relativePath,n),content:e.text,sourcePath:e.sourcePath,contentType:e.contentType,headingPath:e.headingPath,chunkIndex:e.chunkIndex,totalChunks:e.totalChunks,startLine:e.startLine,endLine:e.endLine,fileHash:D,contentHash:r,indexedAt:O,origin:`indexed`,tags:[],version:1}),A=[],j=[];for(let t=0;t<C.length;t++){let n=C[t],r=e(`sha256`).update(this.normalizeChunkText(n.text)).digest(`hex`),i=k(n,t,r),a=d.get(r);if(a&&this.store.upsertWithoutVector){j.push({record:i,sourceRecordId:a}),c++;continue}d.set(r,i.id),A.push({chunk:n,record:i})}i?.({phase:`embedding`,filesTotal:l,filesProcessed:o,chunksTotal:s+C.length,chunksProcessed:s,currentFile:t.relativePath});let M=A.length>0?await this.embedder.embedBatch(A.map(({chunk:e})=>e.text)):[],N=A.map(({record:e})=>e);if(i?.({phase:`storing`,filesTotal:l,filesProcessed:o,chunksTotal:s+C.length,chunksProcessed:s,currentFile:t.relativePath}),N.length>0&&(h.push(...N),g.push(...M),_.set(t.relativePath,{hash:D,size:t.size,mtimeMs:t.mtimeMs}),v++,v>=20&&await x()),j.length>0&&h.length>0&&await x(),this.store.upsertWithoutVector)for(let{record:e,sourceRecordId:t}of j)await this.store.upsertWithoutVector(e,t);if(N.length===0&&j.length>0&&this.hashCache?.set(t.relativePath,D,{size:t.size,mtimeMs:t.mtimeMs}),this.graphStore)try{a.graphCleared||await this.graphStore.deleteBySourcePath(t.relativePath);let e=I(n,t.relativePath,{workspacePackages:u});e.nodes.length>0&&f.push(...e.nodes),e.edges.length>0&&p.push(...e.edges),m++,m>=50&&await S()}catch(e){z.warn(`Graph extraction failed`,{sourcePath:t.relativePath,...b(e)})}o++,s+=C.length},H(r),(e,t)=>z.error(`Processing failed`,{sourcePath:e.relativePath,...b(t)})),await x(),await S(),{filesProcessed:o,chunksCreated:s,chunksDeduped:c}}async cleanupRemovedFiles(e,t,n,r,i,a){if(e.length===0)return 0;let o=0;return a?.({phase:`cleanup`,filesTotal:n,filesProcessed:r,chunksTotal:i,chunksProcessed:i}),await V(e,async e=>{await this.store.deleteBySourcePath(e),this.hashCache?.delete(e),this.graphStore&&await this.graphStore.deleteBySourcePath(e).catch(t=>z.warn(`Graph cleanup failed`,{sourcePath:e,...b(t)})),o++},H(t),(e,t)=>z.error(`Cleanup failed`,{sourcePath:e,...b(t)})),o}async reindexAll(e,t){if(this.indexing)throw Error(`Indexing is already in progress`);this.indexing=!0;try{if(await this.store.dropTable(),this.graphStore)try{let e=await this.graphStore.getStats();e.nodeCount>0&&(await this.graphStore.clear(),z.info(`Graph store cleared`,{nodeCount:e.nodeCount,edgeCount:e.edgeCount}))}catch(e){z.warn(`Graph store clear failed`,b(e))}return await this.doReindex(e,t)}catch(e){throw this.indexing=!1,e}}async doReindex(e,t){try{return await this.doIndex(e,t,{skipHashCheck:!0,graphCleared:!0})}finally{this.indexing=!1}}async getStats(){return this.store.getStats()}};const G=v(`smart-index`),K=1.5;var q=class{indexer;config;store;trickleTimer=null;stopped=!1;trickleIntervalMs;batchSize;priorityQueue=[];changedFiles=[];lastRefreshTime=0;refreshing=!1;constructor(e,t,n){this.indexer=e,this.config=t,this.store=n,this.trickleIntervalMs=t.indexing.trickleIntervalMs??this.readPositiveIntEnv(`AIKIT_SMART_TRICKLE_MS`,3e4),this.batchSize=t.indexing.trickleBatchSize??this.readPositiveIntEnv(`AIKIT_SMART_BATCH_SIZE`,1)}start(){this.trickleTimer&&=(clearTimeout(this.trickleTimer),null),this.stopped=!1,G.debug(`Smart index scheduler started (trickle mode)`,{intervalMs:this.trickleIntervalMs,batchSize:this.batchSize}),this.scheduleTick()}stop(){this.stopped=!0,this.trickleTimer&&=(clearTimeout(this.trickleTimer),null)}prioritize(...e){let t=[...new Set(e.filter(Boolean))].filter(e=>{try{return!i(e).isDirectory()}catch{return G.debug(`Skipping non-existent path`,{path:e}),!1}});for(let e of t){let t=this.priorityQueue.indexOf(e);t>=0&&this.priorityQueue.splice(t,1)}for(let e of t.reverse())this.priorityQueue.unshift(e);this.priorityQueue.length>500&&(this.priorityQueue.length=500),t.length>0&&G.debug(`Files prioritized for trickle indexing`,{added:t.length,queued:this.priorityQueue.length})}getState(){return{mode:`smart`,queueSize:this.priorityQueue.length,changedFilesSize:this.changedFiles.length,intervalMs:this.trickleIntervalMs,batchSize:this.batchSize,running:this.trickleTimer!==null}}readPositiveIntEnv(e,t){let n=Number(process.env[e]);return Number.isFinite(n)&&n>0?n:t}scheduleTick(){this.trickleTimer=setTimeout(()=>void this.tick(),this.trickleIntervalMs),this.trickleTimer.unref&&this.trickleTimer.unref()}async tick(){if(!this.stopped)try{if(this.indexer.isIndexing){G.info(`Skipping trickle tick — indexing already in progress`);return}let e=this.getCpuCount(),t=C()[0];if(e>0&&t/e>K){G.info(`Skipping trickle tick — system load too high`,{load:t.toFixed(2),cpuCount:e,threshold:K});return}let n=await this.pickFiles();if(n.length===0){await this.maybeRefreshChangedFiles();return}G.debug(`Trickle indexing tick started`,{count:n.length,files:n});let r=await this.indexer.indexFiles(this.config,n);if(this.store)try{await this.store.createFtsIndex()}catch(e){G.warn(`FTS index rebuild failed after trickle tick`,{error:String(e)})}this.changedFiles=this.changedFiles.filter(e=>!n.includes(e)),G.debug(`Trickle indexing tick complete`,{filesProcessed:r.filesProcessed,filesSkipped:r.filesSkipped,chunksCreated:r.chunksCreated})}catch(e){let t=String(e);if(t.includes(`not initialized`)||t.includes(`has been closed`)){G.warn(`Store closed — stopping smart index scheduler`,{error:t}),this.stop();return}G.error(`Trickle indexing tick failed`,{error:t})}finally{this.stopped||this.scheduleTick()}}getCpuCount(){try{return typeof S==`function`?S():4}catch{return 4}}async pickFiles(){let e=[];for(;e.length<this.batchSize&&this.priorityQueue.length>0;){let t=this.priorityQueue.shift();t&&!e.includes(t)&&e.push(t)}if(e.length<this.batchSize)for(await this.maybeRefreshChangedFiles();e.length<this.batchSize&&this.changedFiles.length>0;){let t=this.changedFiles.shift();t&&!e.includes(t)&&e.push(t)}return e}async maybeRefreshChangedFiles(){let e=Date.now();if(!(this.refreshing||this.changedFiles.length>0&&e-this.lastRefreshTime<6e5)){this.refreshing=!0;try{this.changedFiles=await this.indexer.getChangedFiles(this.config),this.lastRefreshTime=e,this.changedFiles.length>0&&G.debug(`Refreshed changed files for trickle indexing`,{count:this.changedFiles.length})}catch(e){let t=String(e);if(t.includes(`not initialized`)||t.includes(`has been closed`)){G.warn(`Store closed — stopping smart index scheduler`,{error:t}),this.stop();return}G.error(`Failed to refresh changed files for trickle indexing`,{error:t})}finally{this.refreshing=!1}}}};export{R as FileHashCache,O as FilesystemCrawler,W as IncrementalIndexer,q as SmartIndexScheduler,I as extractGraph,E as generateRecordId,T as hashContent};
@@ -1954,7 +1954,7 @@ Boolean requesting whether a visible border and background is provided by the ho
1954
1954
  - omitted: host decides border`)}),I({method:V(`ui/request-display-mode`),params:I({mode:IS.describe(`The display mode being requested.`)})});var QS=I({mode:IS.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),$S=R([V(`model`),V(`app`)]).describe(`Tool visibility scope - who can access the tool.`);I({resourceUri:j().optional(),visibility:F($S).optional().describe(`Who can access this tool. Default: ["model", "app"]
1955
1955
  - "model": Tool visible to and callable by the agent
1956
1956
  - "app": Tool callable by the app from this server only`),csp:h_().optional(),permissions:h_().optional()}),I({mimeTypes:F(j()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),I({method:V(`ui/download-file`),params:I({contents:F(R([Tx,Ex])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),I({method:V(`ui/message`),params:I({role:V(`user`).describe(`Message role, currently only "user" is supported.`),content:F(Dx).describe(`Message content blocks (text, image, etc.).`)})}),I({method:V(`ui/notifications/sandbox-resource-ready`),params:I({html:j().describe(`HTML content to load into the inner iframe.`),sandbox:j().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:VS.optional().describe(`CSP configuration from resource metadata.`),permissions:HS.optional().describe(`Sandbox permissions from resource metadata.`)})});var eC=I({method:V(`ui/notifications/tool-result`),params:Ix.describe(`Standard MCP tool execution result.`)}),tC=I({toolInfo:I({id:nb.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Nx.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:FS.optional().describe(`Current color theme preference.`),styles:qS.optional().describe(`Style configuration for theming the app.`),displayMode:IS.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:F(IS).optional().describe(`Display modes the host supports.`),containerDimensions:R([I({height:M().describe(`Fixed container height in pixels.`)}),I({maxHeight:R([M(),f_()]).optional().describe(`Maximum container height in pixels.`)})]).and(R([I({width:M().describe(`Fixed container width in pixels.`)}),I({maxWidth:R([M(),f_()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
1957
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),nC=I({method:V(`ui/notifications/host-context-changed`),params:tC.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(Dx).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:_b.describe(`App identification (name and version).`),appCapabilities:ZS.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var rC=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:_b.describe(`Host application identification and version.`),hostCapabilities:XS.describe(`Features and capabilities provided by the host.`),hostContext:tC.describe(`Rich context about the host environment.`)}).passthrough(),iC={target:`draft-2020-12`};async function aC(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](iC);if(n.vendor===`zod`){let{z:n}=await jS(async()=>{let{z:e}=await Promise.resolve().then(()=>(Wy(),Hy));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function oC(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function sC(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function cC(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function lC(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}var uC=class e extends MS{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:WS,toolresult:eC,toolcancelled:GS,hostcontextchanged:nC};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||h({jitless:!0}),this.setRequestHandler(Db,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=DS(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await oC(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await oC(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await aC(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await aC(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(JS,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rx,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Px,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Ix,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},sx,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},tx,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?eS:$x;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},BS,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},fb,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},RS,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},zS,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},QS,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new PS(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:NS}},rC,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function dC(e){let t=e.getAttribute(hC);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(hC,n),n}function fC(e,t,n){for(let[r,i]of e.entries())i.textContent=dC(i),r===t?(i.setAttribute(gC,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(gC)}function pC(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function mC(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=_C.compare(pC(e,t),pC(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}fC(t,a,o)};for(let[e,n]of t.entries()){dC(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=dC(e),e.removeAttribute(gC),e.removeAttribute(hC),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}var hC,gC,_C,vC=t((()=>{hC=`data-sort-label`,gC=`data-sort-dir`,_C=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`})}));function yC(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function bC(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return yC(n);n=n.parentElement}return null}function xC(e){return Array.from(e.querySelectorAll(`summary`))}function SC(e){return e.open||e.hasAttribute(`open`)}function CC(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function wC(e,t){e.textContent=t.every(e=>SC(e))?`Collapse all`:`Expand all`}function TC(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!SC(e));for(let n of t)CC(n,e);wC(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{wC(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=xC(e).map(t=>{t.tabIndex=0;let n=n=>{let r=xC(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!SC(a))CC(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&SC(a)?CC(a,!1):bC(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return wC(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}var EC=t((()=>{}));function DC(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var OC=t((()=>{}));function kC(e){let t=e.createElement(`style`);return t.textContent=MC,t}function AC(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function jC(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=kC(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=AC(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return AC(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var MC,NC=t((()=>{MC=`
1957
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:j().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:j().optional().describe(`User's timezone in IANA format.`),userAgent:j().optional().describe(`Host application identifier.`),platform:R([V(`web`),V(`desktop`),V(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:I({touch:N().optional().describe(`Whether the device supports touch input.`),hover:N().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:I({top:M().describe(`Top safe area inset in pixels.`),right:M().describe(`Right safe area inset in pixels.`),bottom:M().describe(`Bottom safe area inset in pixels.`),left:M().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),nC=I({method:V(`ui/notifications/host-context-changed`),params:tC.describe(`Partial context update containing only changed fields.`)});I({method:V(`ui/update-model-context`),params:I({content:F(Dx).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:z(j(),P().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),I({method:V(`ui/initialize`),params:I({appInfo:_b.describe(`App identification (name and version).`),appCapabilities:ZS.describe(`Features and capabilities this app provides.`),protocolVersion:j().describe(`Protocol version this app supports.`)})});var rC=I({protocolVersion:j().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:_b.describe(`Host application identification and version.`),hostCapabilities:XS.describe(`Features and capabilities provided by the host.`),hostContext:tC.describe(`Rich context about the host environment.`)}).passthrough(),iC={target:`draft-2020-12`};async function aC(e,t){let n=e[`~standard`];if(n.jsonSchema)return n.jsonSchema[t](iC);if(n.vendor===`zod`){let{z:n}=await jS(async()=>{let{z:e}=await Promise.resolve().then(()=>(Wy(),Hy));return{z:e}},void 0,import.meta.url);return n.toJSONSchema(e,{io:t})}throw Error(`Schema (vendor: ${n.vendor}) does not implement Standard JSON Schema (~standard.jsonSchema). Use a library that does (zod v4, ArkType, Valibot) or wrap your schema accordingly.`)}async function oC(e,t,n=``){let r=await e[`~standard`].validate(t);if(r.issues){let e=r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`?e.key:e).join(`.`);return t?`${t}: ${e.message}`:e.message}).join(`; `);throw Error(n+e)}return r.value}function sC(){let e=document.documentElement.getAttribute(`data-theme`);return e===`dark`||e===`light`?e:document.documentElement.classList.contains(`dark`)?`dark`:`light`}function cC(e){let t=document.documentElement;t.setAttribute(`data-theme`,e),t.style.colorScheme=e}function lC(e,t=document.documentElement){for(let[n,r]of Object.entries(e))r!==void 0&&t.style.setProperty(n,r)}var uC=class e extends MS{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:US,toolinputpartial:WS,toolresult:eC,toolcancelled:GS,hostcontextchanged:nC};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||h({jitless:!0}),this.setRequestHandler(Db,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=DS(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await oC(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await oC(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await aC(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await aC(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(JS,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Rx,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Px,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`);break}}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Ix,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},sx,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},tx,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?eS:$x;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},BS,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},fb,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},RS,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},zS,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},QS,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new PS(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:NS}},rC,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}};function dC(e,t){let n=[];for(let r of Array.from(e.querySelectorAll(`[data-action-id]`))){let e=r.getAttribute(`data-action-id`);if(!e)continue;if(r.tagName===`SELECT`){let i=r,a=()=>{t(e,i.value)};i.addEventListener(`change`,a),n.push(()=>{i.removeEventListener(`change`,a)});continue}let i=()=>{t(e)};r.addEventListener(`click`,i),n.push(()=>{r.removeEventListener(`click`,i)})}return()=>{for(let e of n)e()}}var fC=`
1958
1958
  .bk-checklist-progress {
1959
1959
  margin-bottom: var(--dt-space-3);
1960
1960
  color: var(--dt-text-secondary);
@@ -1968,9 +1968,9 @@ container holding the app. Specify either width or maxWidth, and either height o
1968
1968
  margin: 0;
1969
1969
  accent-color: var(--dt-accent-fg);
1970
1970
  }
1971
- `}));OC(),NC(),vC(),EC();var PC=`data-hydrated`;function FC(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function IC(e,t,n){e.push(()=>{n(),t.removeAttribute(PC)})}function LC(e={}){let t=e.container??document.body,n=[];for(let e of FC(t,`.bk-table`))e.hasAttribute(PC)||(e.setAttribute(PC,``),IC(n,e,mC(e)));for(let e of FC(t,`.bk-tree`))e.hasAttribute(PC)||(e.setAttribute(PC,``),IC(n,e,TC(e)));for(let r of FC(t,`.bk-checklist`))r.hasAttribute(PC)||(r.setAttribute(PC,``),IC(n,r,jC(r,e)));for(let r of FC(t,`.bk-actions`))if(!r.hasAttribute(PC)){if(r.setAttribute(PC,``),e.onAction){IC(n,r,DC(r,e.onAction));continue}n.push(()=>{r.removeAttribute(PC)})}return()=>{for(let e of n)e();n.length=0}}vC();var RC=`bk-styles`,zC=new Set;function BC(e){for(let t of e.css)t.trim().length>0&&zC.add(t);return[...zC].join(`
1972
- `)}function VC(e){return di(e,{transport:`browser`})}function HC(e,t=document){let n=BC(e),r=t.getElementById(RC);r||(r=t.createElement(`style`),r.id=RC,t.head.appendChild(r)),r.textContent=n}function UC(e,t){let n=VC(t);return HC(n,e.ownerDocument),e.innerHTML=n.html,n}function WC(e,t,n){return UC(e,{schemaVersion:1,title:`AI Kit Present`,blocks:t}),LC({container:e,onAction:n})}function GC(e){return function(t,n){let r=n??t.label;if(!e){fetch(`/callback`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actionId:t.id,value:r})});return}e.updateModelContext({content:[{type:`text`,text:`Latest UI action: ${t.label}${n?` → ${n}`:``}`}],structuredContent:{actionId:t.id,actionType:t.type,label:t.label,value:r,timestamp:new Date().toISOString()}}),e.sendMessage({role:`user`,content:[{type:`text`,text:`User selected: ${t.label}${n?` → ${n}`:``}`}]})}}function KC(e){return typeof e==`object`&&!!e}function qC(e,t){let n=e.id.split(`@`)[0];return n===`timeline`&&KC(t)&&Array.isArray(t.events)?t.events:n===`tree`&&Array.isArray(t)?{root:{label:`Root`,children:t}}:t}function JC(e,t,n){let r=oi.get(e);if(!r?.supportedTransports.includes(`browser`))return null;let i=qC(r,t);return{blocks:r.blocksFromData(i,{colorScheme:n.colorScheme,transport:`browser`,lang:n.lang,dir:n.dir}),actions:r.actionsFromData?.(i)??[]}}var YC=`present-data`;function XC(e=document,t=YC){let n=e.getElementById(t);return n?.textContent?JSON.parse(n.textContent):null}function ZC(e){return e?{callTool:(t,n)=>e.callServerTool({name:t,arguments:n}),sendMessage:async t=>{await e.sendMessage({role:`user`,content:[{type:`text`,text:t}]})},updateContext:async t=>{await e.updateModelContext({content:[{type:`text`,text:t}]})}}:{callTool:async()=>{throw Error(`callTool is not available in browser mode`)},sendMessage:async()=>{},updateContext:async()=>{}}}var QC=class{app;currentMode=`inline`;availableModes=[];toolbar=null;constructor(e){this.app=e}apply(e){e.displayMode&&(this.currentMode=e.displayMode),e.availableDisplayModes&&(this.availableModes=e.availableDisplayModes),this.updateToolbar()}async requestMode(e){try{let t=await this.app.requestDisplayMode({mode:e});return this.currentMode=t.mode,document.documentElement.dataset.display=t.mode,this.updateToolbar(),t.mode}catch{return this.currentMode}}updateToolbar(){if(this.availableModes.length<=1){this.toolbar?.remove(),this.toolbar=null;return}this.toolbar||=this.createToolbar(),this.renderButtons()}createToolbar(){let e=document.createElement(`div`);return e.className=`display-mode-toolbar`,document.body.appendChild(e),e}renderButtons(){if(!this.toolbar)return;this.toolbar.innerHTML=``;let e={inline:`▣`,fullscreen:`⛶`,pip:`◱`};for(let t of this.availableModes){let n=document.createElement(`button`);n.className=`dm-btn${t===this.currentMode?` dm-active`:``}`,n.textContent=e[t]??t,n.title=t,n.addEventListener(`click`,()=>this.requestMode(t)),this.toolbar.appendChild(n)}}},$C=new Set;function ew(e,t){if($C.has(e))return;$C.add(e);let n=document.createElement(`style`);n.textContent=t,document.head.appendChild(n)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n&&(r.textContent=n),r}function tw(e){return e==null?`null`:Array.isArray(e)?`[${e.map(tw).join(`, `)}]`:String(e)}function nw(e){return typeof e==`object`&&!!e&&`type`in e}var rw=[[400,`compact`],[800,`comfortable`]],iw=class{root;displayMode=`inline`;sizeClass=`comfortable`;constructor(e){this.root=e??document.documentElement}apply(e){this.applyDisplayMode(e),this.applyContainerDimensions(e),this.applySafeArea(e),this.applyPlatform(e),this.applyDeviceCapabilities(e)}getDisplayMode(){return this.displayMode}getSize(){return this.sizeClass}applyDisplayMode(e){e.displayMode&&(this.displayMode=e.displayMode,this.root.dataset.display=e.displayMode)}applyContainerDimensions(e){let t=e.containerDimensions;if(!t)return;let n=this.root.style,r=`width`in t?t.width:`maxWidth`in t?t.maxWidth:void 0,i=`height`in t?t.height:`maxHeight`in t?t.maxHeight:void 0;r!==void 0&&(n.setProperty(`--aikit-container-w`,`${r}px`),this.sizeClass=this.deriveSizeClass(r),this.root.dataset.size=this.sizeClass,n.setProperty(`--aikit-content-max-width`,this.deriveMaxWidth(r)),n.setProperty(`--aikit-body-pad-x`,this.derivePadX()),n.setProperty(`--aikit-grid-cols`,this.deriveGridCols()),n.setProperty(`--aikit-card-min`,this.deriveCardMin()),n.setProperty(`--aikit-metric-min`,this.deriveMetricMin())),i!==void 0&&(n.setProperty(`--aikit-container-h`,`${i}px`),n.setProperty(`--aikit-body-pad-y`,this.derivePadY()))}applySafeArea(e){let t=e.safeAreaInsets;if(!t)return;let n=this.root.style;n.setProperty(`--aikit-safe-top`,`${t.top}px`),n.setProperty(`--aikit-safe-right`,`${t.right}px`),n.setProperty(`--aikit-safe-bottom`,`${t.bottom}px`),n.setProperty(`--aikit-safe-left`,`${t.left}px`)}applyPlatform(e){e.platform&&(this.root.dataset.platform=e.platform)}applyDeviceCapabilities(e){let t=e.deviceCapabilities;t&&(t.touch!==void 0&&(this.root.dataset.touch=String(t.touch)),t.hover!==void 0&&(this.root.dataset.hover=String(t.hover)))}deriveSizeClass(e){for(let[t,n]of rw)if(e<t)return n;return`full`}deriveMaxWidth(e){return this.displayMode===`pip`?`100%`:this.displayMode===`fullscreen`?`none`:e<960?`100%`:`900px`}derivePadX(){return this.sizeClass===`compact`?`8px`:`16px`}derivePadY(){return this.sizeClass===`compact`?`8px`:`16px`}deriveGridCols(){switch(this.sizeClass){case`compact`:return`1`;case`comfortable`:return`2`;case`full`:return`3`}}deriveCardMin(){return this.sizeClass===`compact`?`100%`:`250px`}deriveMetricMin(){return this.sizeClass===`compact`?`100px`:`150px`}},aw=`AI Kit Present`;function ow(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;if(Array.isArray(t.blocks)&&t.blocks.length>0)return t.blocks}return e}function sw(e){if(Array.isArray(e))return e.length===0?[{type:`markdown`,value:`*Empty array*`}]:nw(e[0])?e.filter(nw):typeof e[0]==`object`&&e[0]!==null?[{type:`table`,value:e}]:[{type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1973
- `)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function cw(e){return{...e,options:e.options?.map(e=>typeof e==`string`?{label:e,value:e}:e)}}function lw(e){let t=ow(e.content);return{schemaVersion:1,title:e.title??aw,template:e.template,data:t,blocks:sw(t),actions:e.actions?.map(cw)}}var uw=class{templates=new Map;register(e){this.templates.set(e.name,e)}get(e){return this.templates.get(e)}detect(e){let t,n=0;for(let r of this.templates.values()){let i=r.detect(e);i>n&&(n=i,t=r)}return n>0?t:void 0}getAll(){return[...this.templates.values()]}},dw={"--color-background-primary":`--aikit-bg`,"--color-background-secondary":`--aikit-surface`,"--color-background-tertiary":`--aikit-surface2`,"--color-text-primary":`--aikit-text`,"--color-text-secondary":`--aikit-muted`,"--color-border-primary":`--aikit-border`,"--color-ring-primary":`--aikit-accent`,"--color-text-success":`--aikit-success`,"--color-text-danger":`--aikit-error`,"--color-text-warning":`--aikit-warning`,"--color-text-info":`--aikit-info`,"--font-sans":`--aikit-font-sans`,"--font-mono":`--aikit-font-mono`,"--border-radius-md":`--aikit-radius`,"--shadow-sm":`--aikit-shadow`},fw={"--aikit-bg":`--bg`,"--aikit-text":`--fg`,"--aikit-surface":`--surface`,"--aikit-border":`--border`,"--aikit-accent":`--accent`,"--aikit-success":`--success`,"--aikit-warning":`--warning`,"--aikit-error":`--error`,"--aikit-font-sans":`--font-sans`,"--aikit-font-mono":`--font-mono`,"--aikit-radius":`--radius`,"--aikit-shadow":`--shadow`},pw=`aikit-design-token-bridge`,mw={light:{"--bg":`#ffffff`,"--fg":`rgb(26 26 46)`,"--surface":`#f8f9fa`,"--border":`#e2e8f0`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#1e1e2e`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#ffffff`,"--aikit-surface":`#f8f9fa`,"--aikit-surface2":`#f8f9fa`,"--aikit-text":`rgb(26 26 46)`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#e2e8f0`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#1e1e2e`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`},dark:{"--bg":`#0d1117`,"--fg":`#e6edf3`,"--surface":`#161b22`,"--border":`#30363d`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#161b22`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#0d1117`,"--aikit-surface":`#161b22`,"--aikit-surface2":`#161b22`,"--aikit-text":`#e6edf3`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#30363d`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#161b22`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`}},hw={"--chart-1":`#79c0ff`,"--chart-2":`#38bdf8`,"--chart-3":`#34d399`,"--chart-4":`#fbbf24`,"--chart-5":`#f87171`,"--chart-6":`#a78bfa`,"--chart-7":`#f472b6`,"--chart-8":`#2dd4bf`,"--chart-9":`#fb923c`,"--chart-10":`#22d3ee`,"--chart-11":`#c084fc`,"--chart-12":`#a3e635`,"--chart-others":`#a8a29e`},gw=`
1971
+ `;function pC(e){let t=e.createElement(`style`);return t.textContent=fC,t}function mC(e,t){let n=t.filter(e=>e.getAttribute(`data-checked`)===`true`).length,r=t.length;return e.textContent=`${n}/${r} complete`,{complete:n,total:r}}function hC(e,t={}){let n=Array.from(e.querySelectorAll(`.bk-checklist-item`));if(n.length===0)return()=>{};let r=e.ownerDocument,i=pC(r),a=r.createElement(`div`);a.className=`bk-checklist-progress`,e.parentElement?.insertBefore(a,e),r.head?.appendChild(i);let o=[];for(let[e,i]of n.entries()){let s=i.querySelector(`.bk-checklist-icon`),c=i.querySelector(`.bk-checklist-label`)?.textContent?.trim()??``,l=r.createElement(`input`);l.type=`checkbox`,l.className=`bk-checklist-box`,l.checked=i.getAttribute(`data-checked`)===`true`;let u=()=>{i.setAttribute(`data-checked`,String(l.checked));let r=mC(a,n);t.onAction?.(`checklist`,JSON.stringify({index:e,label:c,checked:l.checked,complete:r.complete,total:r.total}))};l.addEventListener(`change`,u),o.push(()=>{l.removeEventListener(`change`,u)}),s?s.replaceWith(l):i.insertBefore(l,i.firstChild)}return mC(a,n),()=>{for(let e of o)e();a.remove(),i.remove();for(let e of n){let t=e.querySelector(`.bk-checklist-box`);if(!t)continue;let n=r.createElement(`span`);n.className=`bk-checklist-icon`,n.textContent=e.getAttribute(`data-checked`)===`true`?`✓`:`×`,t.replaceWith(n)}}}var gC=`data-sort-label`,_C=`data-sort-dir`,vC=new Intl.Collator(void 0,{numeric:!0,sensitivity:`base`});function yC(e){let t=e.getAttribute(gC);if(t!==null)return t;let n=e.textContent?.trim()??``;return e.setAttribute(gC,n),n}function bC(e,t,n){for(let[r,i]of e.entries())i.textContent=yC(i),r===t?(i.setAttribute(_C,n),i.append(` ${n===`asc`?`▲`:`▼`}`)):i.removeAttribute(_C)}function xC(e,t){return e.querySelectorAll(`td`)[t]?.textContent?.trim()??``}function SC(e){let t=Array.from(e.querySelectorAll(`thead th`)),n=e.querySelector(`tbody`);if(!n||t.length===0)return()=>{};let r=Array.from(n.querySelectorAll(`tr`)),i=e.parentElement,a=null,o=`asc`,s=``,c=null,l=[],u=()=>{let e=[...r];if(a!==null){let t=a;e.sort((e,n)=>{let r=vC.compare(xC(e,t),xC(n,t));return o===`asc`?r:-r})}for(let t of e){n.appendChild(t);let e=t.textContent?.toLowerCase()??``;t.hidden=s.length>0&&!e.includes(s)}bC(t,a,o)};for(let[e,n]of t.entries()){yC(n);let t=()=>{a===e?o=o===`asc`?`desc`:`asc`:(a=e,o=`asc`),u()};n.style.cursor=`pointer`,n.addEventListener(`click`,t),l.push(()=>{n.removeEventListener(`click`,t)})}if(r.length>5&&i){c=i.ownerDocument.createElement(`input`),c.className=`bk-table-filter`,c.placeholder=`Filter...`;let t=()=>{s=c?.value.toLowerCase().trim()??``,u()};i.insertBefore(c,e),c.addEventListener(`input`,t),l.push(()=>{c?.removeEventListener(`input`,t),c?.remove(),c=null})}return u(),()=>{for(let e of l)e();for(let e of t)e.textContent=yC(e),e.removeAttribute(_C),e.removeAttribute(gC),e.style.removeProperty(`cursor`);for(let e of r)e.hidden=!1}}function CC(e){for(let t of Array.from(e.children))if(t.tagName===`SUMMARY`)return t;return null}function wC(e){let t=e.closest(`details`);if(!t)return null;let n=t.parentElement;for(;n;){if(n.tagName===`DETAILS`)return CC(n);n=n.parentElement}return null}function TC(e){return Array.from(e.querySelectorAll(`summary`))}function EC(e){return e.open||e.hasAttribute(`open`)}function DC(e,t){e.open=t,t?e.setAttribute(`open`,``):e.removeAttribute(`open`)}function OC(e,t){e.textContent=t.every(e=>EC(e))?`Collapse all`:`Expand all`}function kC(e){let t=Array.from(e.querySelectorAll(`details`));if(t.length===0)return()=>{};let n=e.ownerDocument.createElement(`button`);n.type=`button`,n.className=`bk-tree-toggle-all`,e.insertBefore(n,e.firstChild);let r=()=>{let e=t.some(e=>!EC(e));for(let n of t)DC(n,e);OC(n,t)},i=()=>{r()};n.addEventListener(`click`,i);let a=t.map(e=>{let r=()=>{OC(n,t)};return e.addEventListener(`toggle`,r),()=>{e.removeEventListener(`toggle`,r)}}),o=TC(e).map(t=>{t.tabIndex=0;let n=n=>{let r=TC(e),i=r.indexOf(t);if(i===-1)return;let a=t.closest(`details`);if(n.key===`ArrowDown`){r[i+1]?.focus(),n.preventDefault();return}if(n.key===`ArrowUp`){r[i-1]?.focus(),n.preventDefault();return}if(n.key===`ArrowRight`){if(a&&!EC(a))DC(a,!0);else{let e=r[i+1];e&&a?.contains(e)&&e.focus()}n.preventDefault();return}n.key===`ArrowLeft`&&(a&&EC(a)?DC(a,!1):wC(t)?.focus(),n.preventDefault())};return t.addEventListener(`keydown`,n),()=>{t.removeEventListener(`keydown`,n)}});return OC(n,t),()=>{n.removeEventListener(`click`,i);for(let e of a)e();for(let e of o)e();n.remove()}}var AC=`data-hydrated`;function jC(e,t){let n=[];return e.matches(t)&&n.push(e),n.push(...Array.from(e.querySelectorAll(t))),n}function MC(e,t,n){e.push(()=>{n(),t.removeAttribute(AC)})}function NC(e={}){let t=e.container??document.body,n=[];for(let e of jC(t,`.bk-table`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,SC(e)));for(let e of jC(t,`.bk-tree`))e.hasAttribute(AC)||(e.setAttribute(AC,``),MC(n,e,kC(e)));for(let r of jC(t,`.bk-checklist`))r.hasAttribute(AC)||(r.setAttribute(AC,``),MC(n,r,hC(r,e)));for(let r of jC(t,`.bk-actions`))if(!r.hasAttribute(AC)){if(r.setAttribute(AC,``),e.onAction){MC(n,r,dC(r,e.onAction));continue}n.push(()=>{r.removeAttribute(AC)})}return()=>{for(let e of n)e();n.length=0}}var PC=`bk-styles`,FC=new Set;function IC(e){for(let t of e.css)t.trim().length>0&&FC.add(t);return[...FC].join(`
1972
+ `)}function LC(e){return di(e,{transport:`browser`})}function RC(e,t=document){let n=IC(e),r=t.getElementById(PC);r||(r=t.createElement(`style`),r.id=PC,t.head.appendChild(r)),r.textContent=n}function zC(e,t){let n=LC(t);return RC(n,e.ownerDocument),e.innerHTML=n.html,n}function BC(e,t,n){return zC(e,{schemaVersion:1,title:`AI Kit Present`,blocks:t}),NC({container:e,onAction:n})}function VC(e){return function(t,n){let r=n??t.label;if(!e){fetch(`/callback`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({actionId:t.id,value:r})});return}e.updateModelContext({content:[{type:`text`,text:`Latest UI action: ${t.label}${n?` → ${n}`:``}`}],structuredContent:{actionId:t.id,actionType:t.type,label:t.label,value:r,timestamp:new Date().toISOString()}}),e.sendMessage({role:`user`,content:[{type:`text`,text:`User selected: ${t.label}${n?` → ${n}`:``}`}]})}}function HC(e){return typeof e==`object`&&!!e}function UC(e,t){let n=e.id.split(`@`)[0];return n===`timeline`&&HC(t)&&Array.isArray(t.events)?t.events:n===`tree`&&Array.isArray(t)?{root:{label:`Root`,children:t}}:t}function WC(e,t,n){let r=oi.get(e);if(!r?.supportedTransports.includes(`browser`))return null;let i=UC(r,t);return{blocks:r.blocksFromData(i,{colorScheme:n.colorScheme,transport:`browser`,lang:n.lang,dir:n.dir}),actions:r.actionsFromData?.(i)??[]}}var GC=`present-data`;function KC(e=document,t=GC){let n=e.getElementById(t);return n?.textContent?JSON.parse(n.textContent):null}function qC(e){return e?{callTool:(t,n)=>e.callServerTool({name:t,arguments:n}),sendMessage:async t=>{await e.sendMessage({role:`user`,content:[{type:`text`,text:t}]})},updateContext:async t=>{await e.updateModelContext({content:[{type:`text`,text:t}]})}}:{callTool:async()=>{throw Error(`callTool is not available in browser mode`)},sendMessage:async()=>{},updateContext:async()=>{}}}var JC=class{app;currentMode=`inline`;availableModes=[];toolbar=null;constructor(e){this.app=e}apply(e){e.displayMode&&(this.currentMode=e.displayMode),e.availableDisplayModes&&(this.availableModes=e.availableDisplayModes),this.updateToolbar()}async requestMode(e){try{let t=await this.app.requestDisplayMode({mode:e});return this.currentMode=t.mode,document.documentElement.dataset.display=t.mode,this.updateToolbar(),t.mode}catch{return this.currentMode}}updateToolbar(){if(this.availableModes.length<=1){this.toolbar?.remove(),this.toolbar=null;return}this.toolbar||=this.createToolbar(),this.renderButtons()}createToolbar(){let e=document.createElement(`div`);return e.className=`display-mode-toolbar`,document.body.appendChild(e),e}renderButtons(){if(!this.toolbar)return;this.toolbar.innerHTML=``;let e={inline:`▣`,fullscreen:`⛶`,pip:`◱`};for(let t of this.availableModes){let n=document.createElement(`button`);n.className=`dm-btn${t===this.currentMode?` dm-active`:``}`,n.textContent=e[t]??t,n.title=t,n.addEventListener(`click`,()=>this.requestMode(t)),this.toolbar.appendChild(n)}}},YC=new Set;function XC(e,t){if(YC.has(e))return;YC.add(e);let n=document.createElement(`style`);n.textContent=t,document.head.appendChild(n)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n&&(r.textContent=n),r}function ZC(e){return e==null?`null`:Array.isArray(e)?`[${e.map(ZC).join(`, `)}]`:String(e)}function QC(e){return typeof e==`object`&&!!e&&`type`in e}var $C=[[400,`compact`],[800,`comfortable`]],ew=class{root;displayMode=`inline`;sizeClass=`comfortable`;constructor(e){this.root=e??document.documentElement}apply(e){this.applyDisplayMode(e),this.applyContainerDimensions(e),this.applySafeArea(e),this.applyPlatform(e),this.applyDeviceCapabilities(e)}getDisplayMode(){return this.displayMode}getSize(){return this.sizeClass}applyDisplayMode(e){e.displayMode&&(this.displayMode=e.displayMode,this.root.dataset.display=e.displayMode)}applyContainerDimensions(e){let t=e.containerDimensions;if(!t)return;let n=this.root.style,r=`width`in t?t.width:`maxWidth`in t?t.maxWidth:void 0,i=`height`in t?t.height:`maxHeight`in t?t.maxHeight:void 0;r!==void 0&&(n.setProperty(`--aikit-container-w`,`${r}px`),this.sizeClass=this.deriveSizeClass(r),this.root.dataset.size=this.sizeClass,n.setProperty(`--aikit-content-max-width`,this.deriveMaxWidth(r)),n.setProperty(`--aikit-body-pad-x`,this.derivePadX()),n.setProperty(`--aikit-grid-cols`,this.deriveGridCols()),n.setProperty(`--aikit-card-min`,this.deriveCardMin()),n.setProperty(`--aikit-metric-min`,this.deriveMetricMin())),i!==void 0&&(n.setProperty(`--aikit-container-h`,`${i}px`),n.setProperty(`--aikit-body-pad-y`,this.derivePadY()))}applySafeArea(e){let t=e.safeAreaInsets;if(!t)return;let n=this.root.style;n.setProperty(`--aikit-safe-top`,`${t.top}px`),n.setProperty(`--aikit-safe-right`,`${t.right}px`),n.setProperty(`--aikit-safe-bottom`,`${t.bottom}px`),n.setProperty(`--aikit-safe-left`,`${t.left}px`)}applyPlatform(e){e.platform&&(this.root.dataset.platform=e.platform)}applyDeviceCapabilities(e){let t=e.deviceCapabilities;t&&(t.touch!==void 0&&(this.root.dataset.touch=String(t.touch)),t.hover!==void 0&&(this.root.dataset.hover=String(t.hover)))}deriveSizeClass(e){for(let[t,n]of $C)if(e<t)return n;return`full`}deriveMaxWidth(e){return this.displayMode===`pip`?`100%`:this.displayMode===`fullscreen`?`none`:e<960?`100%`:`900px`}derivePadX(){return this.sizeClass===`compact`?`8px`:`16px`}derivePadY(){return this.sizeClass===`compact`?`8px`:`16px`}deriveGridCols(){switch(this.sizeClass){case`compact`:return`1`;case`comfortable`:return`2`;case`full`:return`3`}}deriveCardMin(){return this.sizeClass===`compact`?`100%`:`250px`}deriveMetricMin(){return this.sizeClass===`compact`?`100px`:`150px`}},tw=`AI Kit Present`;function nw(e){if(!Array.isArray(e)&&typeof e==`object`&&e){let t=e;if(Array.isArray(t.blocks)&&t.blocks.length>0)return t.blocks}return e}function rw(e){if(Array.isArray(e))return e.length===0?[{type:`markdown`,value:`*Empty array*`}]:QC(e[0])?e.filter(QC):typeof e[0]==`object`&&e[0]!==null?[{type:`table`,value:e}]:[{type:`markdown`,value:e.map(e=>`- ${String(e)}`).join(`
1973
+ `)}];if(typeof e==`string`)return[{type:`markdown`,value:e}];if(typeof e==`object`&&e){let t=e;return Array.isArray(t.nodes)&&Array.isArray(t.edges)?[{type:`graph`,value:t}]:Array.isArray(t.metrics)?[{type:`metrics`,value:t.metrics}]:[{type:`json`,value:t}]}return[{type:`text`,value:String(e??``)}]}function iw(e){return{...e,options:e.options?.map(e=>typeof e==`string`?{label:e,value:e}:e)}}function aw(e){let t=nw(e.content);return{schemaVersion:1,title:e.title??tw,template:e.template,data:t,blocks:rw(t),actions:e.actions?.map(iw)}}var ow=class{templates=new Map;register(e){this.templates.set(e.name,e)}get(e){return this.templates.get(e)}detect(e){let t,n=0;for(let r of this.templates.values()){let i=r.detect(e);i>n&&(n=i,t=r)}return n>0?t:void 0}getAll(){return[...this.templates.values()]}},sw={"--color-background-primary":`--aikit-bg`,"--color-background-secondary":`--aikit-surface`,"--color-background-tertiary":`--aikit-surface2`,"--color-text-primary":`--aikit-text`,"--color-text-secondary":`--aikit-muted`,"--color-border-primary":`--aikit-border`,"--color-ring-primary":`--aikit-accent`,"--color-text-success":`--aikit-success`,"--color-text-danger":`--aikit-error`,"--color-text-warning":`--aikit-warning`,"--color-text-info":`--aikit-info`,"--font-sans":`--aikit-font-sans`,"--font-mono":`--aikit-font-mono`,"--border-radius-md":`--aikit-radius`,"--shadow-sm":`--aikit-shadow`},cw={"--aikit-bg":`--bg`,"--aikit-text":`--fg`,"--aikit-surface":`--surface`,"--aikit-border":`--border`,"--aikit-accent":`--accent`,"--aikit-success":`--success`,"--aikit-warning":`--warning`,"--aikit-error":`--error`,"--aikit-font-sans":`--font-sans`,"--aikit-font-mono":`--font-mono`,"--aikit-radius":`--radius`,"--aikit-shadow":`--shadow`},lw=`aikit-design-token-bridge`,uw={light:{"--bg":`#ffffff`,"--fg":`rgb(26 26 46)`,"--surface":`#f8f9fa`,"--border":`#e2e8f0`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#1e1e2e`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#ffffff`,"--aikit-surface":`#f8f9fa`,"--aikit-surface2":`#f8f9fa`,"--aikit-text":`rgb(26 26 46)`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#e2e8f0`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#1e1e2e`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.08), 0 1px 2px rgba(0,0,0,0.06)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`},dark:{"--bg":`#0d1117`,"--fg":`#e6edf3`,"--surface":`#161b22`,"--border":`#30363d`,"--accent":`#58a6ff`,"--accent-light":`#79c0ff`,"--success":`#22c55e`,"--warning":`#f59e0b`,"--error":`#ef4444`,"--code-bg":`#161b22`,"--code-fg":`#cdd6f4`,"--radius":`8px`,"--shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-bg":`#0d1117`,"--aikit-surface":`#161b22`,"--aikit-surface2":`#161b22`,"--aikit-text":`#e6edf3`,"--aikit-muted":`#94a3b8`,"--aikit-border":`#30363d`,"--aikit-accent":`#58a6ff`,"--aikit-accent-light":`#79c0ff`,"--aikit-success":`#22c55e`,"--aikit-warning":`#f59e0b`,"--aikit-error":`#ef4444`,"--aikit-info":`#58a6ff`,"--aikit-code-bg":`#161b22`,"--aikit-code-fg":`#cdd6f4`,"--aikit-font-sans":`-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif`,"--aikit-font-mono":`'Cascadia Code', 'Fira Code', 'JetBrains Mono', Consolas, monospace`,"--aikit-radius":`8px`,"--aikit-shadow":`0 1px 3px rgba(0,0,0,0.3)`,"--aikit-hover-bg":`color-mix(in srgb, #58a6ff 10%, transparent)`}},dw={"--chart-1":`#79c0ff`,"--chart-2":`#38bdf8`,"--chart-3":`#34d399`,"--chart-4":`#fbbf24`,"--chart-5":`#f87171`,"--chart-6":`#a78bfa`,"--chart-7":`#f472b6`,"--chart-8":`#2dd4bf`,"--chart-9":`#fb923c`,"--chart-10":`#22d3ee`,"--chart-11":`#c084fc`,"--chart-12":`#a3e635`,"--chart-others":`#a8a29e`},fw=`
1974
1974
  :root {
1975
1975
  --dt-bg-primary: var(--aikit-bg, #0d1117);
1976
1976
  --dt-bg-secondary: var(--aikit-surface, #161b22);
@@ -2039,7 +2039,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2039
2039
  [data-theme='light'] {
2040
2040
  color-scheme: light;
2041
2041
  }
2042
- `,_w=class{root;constructor(e){this.root=e??document.documentElement,this.applyFallbackVariables(),this.ensureDesignTokenBridge()}apply(e){e.theme&&cC(e.theme),this.applyFallbackVariables(e.theme),e.styles?.variables&&(lC(e.styles.variables),this.mapTokens(e.styles.variables)),e.styles?.css?.fonts&&this.injectFonts(e.styles.css.fonts)}getTheme(){return sC()}resolveFallbackTheme(e){if(e)return e;let t=this.root.dataset.theme;return t===`light`||t===`dark`?t:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}applyFallbackVariables(e){let t=this.resolveFallbackTheme(e),n=this.root.style;for(let[e,r]of Object.entries(mw[t]))n.setProperty(e,r);for(let[e,t]of Object.entries(hw))n.setProperty(e,t);n.colorScheme=t}mapTokens(e){let t=this.root.style;for(let[n,r]of Object.entries(dw)){let i=e[n];if(i){t.setProperty(r,i);let e=fw[r];e&&t.setProperty(e,i)}}this.getTheme()===`dark`?(t.setProperty(`--code-bg`,e[`--color-background-tertiary`]??`#0f0f1a`),t.setProperty(`--code-fg`,`#cdd6f4`)):(t.setProperty(`--code-bg`,`#f0f0f5`),t.setProperty(`--code-fg`,`#1a1a2e`)),t.setProperty(`--aikit-code-bg`,t.getPropertyValue(`--code-bg`)),t.setProperty(`--aikit-code-fg`,t.getPropertyValue(`--code-fg`));let n=e[`--color-ring-primary`];n&&(t.setProperty(`--aikit-accent-light`,n),t.setProperty(`--accent-light`,n),t.setProperty(`--aikit-hover-bg`,`color-mix(in srgb, ${n} 10%, transparent)`))}injectFonts(e){let t=`aikit-host-fonts`;if(document.getElementById(t))return;let n=document.createElement(`style`);n.id=t,n.textContent=e,document.head.appendChild(n)}ensureDesignTokenBridge(){if(document.getElementById(pw))return;let e=document.createElement(`style`);e.id=pw,e.textContent=gw,document.head.appendChild(e)}},vw=`
2042
+ `,pw=class{root;constructor(e){this.root=e??document.documentElement,this.applyFallbackVariables(),this.ensureDesignTokenBridge()}apply(e){e.theme&&cC(e.theme),this.applyFallbackVariables(e.theme),e.styles?.variables&&(lC(e.styles.variables),this.mapTokens(e.styles.variables)),e.styles?.css?.fonts&&this.injectFonts(e.styles.css.fonts)}getTheme(){return sC()}resolveFallbackTheme(e){if(e)return e;let t=this.root.dataset.theme;return t===`light`||t===`dark`?t:window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}applyFallbackVariables(e){let t=this.resolveFallbackTheme(e),n=this.root.style;for(let[e,r]of Object.entries(uw[t]))n.setProperty(e,r);for(let[e,t]of Object.entries(dw))n.setProperty(e,t);n.colorScheme=t}mapTokens(e){let t=this.root.style;for(let[n,r]of Object.entries(sw)){let i=e[n];if(i){t.setProperty(r,i);let e=cw[r];e&&t.setProperty(e,i)}}this.getTheme()===`dark`?(t.setProperty(`--code-bg`,e[`--color-background-tertiary`]??`#0f0f1a`),t.setProperty(`--code-fg`,`#cdd6f4`)):(t.setProperty(`--code-bg`,`#f0f0f5`),t.setProperty(`--code-fg`,`#1a1a2e`)),t.setProperty(`--aikit-code-bg`,t.getPropertyValue(`--code-bg`)),t.setProperty(`--aikit-code-fg`,t.getPropertyValue(`--code-fg`));let n=e[`--color-ring-primary`];n&&(t.setProperty(`--aikit-accent-light`,n),t.setProperty(`--accent-light`,n),t.setProperty(`--aikit-hover-bg`,`color-mix(in srgb, ${n} 10%, transparent)`))}injectFonts(e){let t=`aikit-host-fonts`;if(document.getElementById(t))return;let n=document.createElement(`style`);n.id=t,n.textContent=e,document.head.appendChild(n)}ensureDesignTokenBridge(){if(document.getElementById(lw))return;let e=document.createElement(`style`);e.id=lw,e.textContent=fw,document.head.appendChild(e)}},mw=`
2043
2043
  .tpl-dashboard { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 14px; }
2044
2044
  .db-card { min-height: 136px; padding: 14px; border: 1px solid var(--aikit-border, #3c3c3c);
2045
2045
  border-left-width: 4px; border-radius: var(--aikit-radius, 10px); background: var(--aikit-surface, #252526);
@@ -2065,7 +2065,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2065
2065
  .db-list-item { display: flex; align-items: center; justify-content: space-between; gap: 12px; color: var(--aikit-text, #e5e7eb);
2066
2066
  font: 500 13px var(--aikit-font-sans, Inter, sans-serif); }
2067
2067
  .db-list-item span:last-child { color: var(--aikit-muted, #9ca3af); font-family: var(--aikit-font-mono, Consolas, monospace); }
2068
- `,yw={name:`dashboard`,label:`Dashboard`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.metrics)?t.metrics[0]:void 0;return n&&typeof n.label==`string`&&`value`in n?.85:0},render(e,t,n){ew(`tpl-dashboard`,vw);let r=t,i=Q(`div`,`block tpl-dashboard`);for(let e of r.metrics){let t=Q(`article`,`db-card status-${e.status??`info`}`),n=Q(`div`,`db-header`);if(n.appendChild(Q(`div`,`db-label`,e.label)),e.trend){let t=e.trend.direction===`up`?`▲`:e.trend.direction===`down`?`▼`:`—`;n.appendChild(Q(`div`,`db-trend ${e.trend.direction}`,`${t} ${e.trend.value}`))}if(t.appendChild(n),t.appendChild(Q(`div`,`db-value`,tw(e.value))),e.type===`progress`){let n=Q(`div`,`db-progress-track`),r=Q(`div`,`db-progress-fill`);r.style.width=`${Math.max(0,Math.min(100,e.progress??0))}%`,n.appendChild(r),t.appendChild(n),t.appendChild(Q(`div`,`db-progress-meta`,`${Math.max(0,Math.min(100,e.progress??0))}% complete`))}if(e.type===`list`&&e.items?.length){let n=Q(`ul`,`db-list`);for(let t of e.items){let e=Q(`li`,`db-list-item`);e.appendChild(Q(`span`,``,t.label)),e.appendChild(Q(`span`,``,t.value)),n.appendChild(e)}t.appendChild(n)}i.appendChild(t)}e.appendChild(i)},styles(){return vw}},bw=`
2068
+ `,hw={name:`dashboard`,label:`Dashboard`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.metrics)?t.metrics[0]:void 0;return n&&typeof n.label==`string`&&`value`in n?.85:0},render(e,t,n){XC(`tpl-dashboard`,mw);let r=t,i=Q(`div`,`block tpl-dashboard`);for(let e of r.metrics){let t=Q(`article`,`db-card status-${e.status??`info`}`),n=Q(`div`,`db-header`);if(n.appendChild(Q(`div`,`db-label`,e.label)),e.trend){let t=e.trend.direction===`up`?`▲`:e.trend.direction===`down`?`▼`:`—`;n.appendChild(Q(`div`,`db-trend ${e.trend.direction}`,`${t} ${e.trend.value}`))}if(t.appendChild(n),t.appendChild(Q(`div`,`db-value`,ZC(e.value))),e.type===`progress`){let n=Q(`div`,`db-progress-track`),r=Q(`div`,`db-progress-fill`);r.style.width=`${Math.max(0,Math.min(100,e.progress??0))}%`,n.appendChild(r),t.appendChild(n),t.appendChild(Q(`div`,`db-progress-meta`,`${Math.max(0,Math.min(100,e.progress??0))}% complete`))}if(e.type===`list`&&e.items?.length){let n=Q(`ul`,`db-list`);for(let t of e.items){let e=Q(`li`,`db-list-item`);e.appendChild(Q(`span`,``,t.label)),e.appendChild(Q(`span`,``,t.value)),n.appendChild(e)}t.appendChild(n)}i.appendChild(t)}e.appendChild(i)},styles(){return mw}},gw=`
2069
2069
  .fg-breadcrumb { display: flex; align-items: center; gap: 4px; padding: 8px 0; flex-wrap: wrap; }
2070
2070
  .fg-crumb { background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
2071
2071
  color: var(--aikit-text, #ccc); padding: 3px 10px; border-radius: 4px; cursor: pointer; font-size: 12px; }
@@ -2080,7 +2080,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2080
2080
  text-overflow: ellipsis; font-weight: 500; }
2081
2081
  .fg-info { font-size: 12px; color: var(--aikit-muted, #858585); padding: 8px 0;
2082
2082
  border-top: 1px solid var(--aikit-border, #3c3c3c); margin-top: 8px; }
2083
- `;function xw(e){return{name:String(e.name??``),total:typeof e.total==`number`?e.total:typeof e.value==`number`?e.value:0,self:typeof e.self==`number`?e.self:void 0,children:Array.isArray(e.children)?e.children.map(e=>xw(e)):void 0}}var Sw={name:`flame-graph`,label:`Flame Graph`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e.profile;return t&&typeof t==`object`&&t.children?.9:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-flame-graph`),a=xw(r.profile),o=a,s=[a],c=Q(`div`,`fg-breadcrumb`);i.appendChild(c);let l=Q(`div`,`fg-canvas`);i.appendChild(l);let u=Q(`div`,`fg-info`);i.appendChild(u);function d(){c.innerHTML=``;for(let e=0;e<s.length;e++){let t=s[e],n=document.createElement(`button`);n.className=`fg-crumb`,n.textContent=t.name,n.addEventListener(`click`,()=>{s.splice(e+1),o=t,d()}),c.appendChild(n),e<s.length-1&&c.appendChild(Q(`span`,`fg-sep`,`›`))}l.innerHTML=``,f(l,o,0,o.total),u.textContent=`${o.name} — total: ${o.total}${o.self==null?``:`, self: ${o.self}`}`}function f(e,t,r,i){let a=Q(`div`,`fg-row`);a.style.paddingLeft=`${r*2}px`;let c=Q(`div`,`fg-bar`),l=Math.max(2,t.total/i*100);c.style.width=`${l}%`,c.style.background=ee(r),c.title=`${t.name}: ${t.total}${t.self==null?``:` (self: ${t.self})`}`;let te=Q(`span`,`fg-bar-label`,`${t.name} (${t.total})`);if(c.appendChild(te),t.children?.length&&(c.style.cursor=`pointer`,c.addEventListener(`click`,()=>{o=t,s.push(t),d(),n.emitAction({type:`button`,id:`zoom`,label:`Zoom`},JSON.stringify({name:t.name,total:t.total}))})),c.addEventListener(`mouseenter`,()=>{u.textContent=`${t.name} — total: ${t.total}${t.self==null?``:`, self: ${t.self}`}`}),a.appendChild(c),e.appendChild(a),t.children)for(let n of t.children)f(e,n,r+1,i)}function ee(e){let t=getComputedStyle(document.documentElement),n=[t.getPropertyValue(`--chart-5`).trim()||`#e24d28`,t.getPropertyValue(`--chart-9`).trim()||`#e8602a`,t.getPropertyValue(`--chart-4`).trim()||`#edad2a`,t.getPropertyValue(`--chart-1`).trim()||`#f5c842`,t.getPropertyValue(`--chart-3`).trim()||`#fce94f`,t.getPropertyValue(`--chart-6`).trim()||`#c4a000`,t.getPropertyValue(`--chart-7`).trim()||`#e07028`,t.getPropertyValue(`--chart-8`).trim()||`#d45500`];return n[e%n.length]}d(),ew(`tpl-flame-graph`,bw),e.appendChild(i)},styles(){return bw}},Cw=`
2083
+ `;function _w(e){return{name:String(e.name??``),total:typeof e.total==`number`?e.total:typeof e.value==`number`?e.value:0,self:typeof e.self==`number`?e.self:void 0,children:Array.isArray(e.children)?e.children.map(e=>_w(e)):void 0}}var vw={name:`flame-graph`,label:`Flame Graph`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e.profile;return t&&typeof t==`object`&&t.children?.9:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-flame-graph`),a=_w(r.profile),o=a,s=[a],c=Q(`div`,`fg-breadcrumb`);i.appendChild(c);let l=Q(`div`,`fg-canvas`);i.appendChild(l);let u=Q(`div`,`fg-info`);i.appendChild(u);function d(){c.innerHTML=``;for(let e=0;e<s.length;e++){let t=s[e],n=document.createElement(`button`);n.className=`fg-crumb`,n.textContent=t.name,n.addEventListener(`click`,()=>{s.splice(e+1),o=t,d()}),c.appendChild(n),e<s.length-1&&c.appendChild(Q(`span`,`fg-sep`,`›`))}l.innerHTML=``,f(l,o,0,o.total),u.textContent=`${o.name} — total: ${o.total}${o.self==null?``:`, self: ${o.self}`}`}function f(e,t,r,i){let a=Q(`div`,`fg-row`);a.style.paddingLeft=`${r*2}px`;let c=Q(`div`,`fg-bar`),l=Math.max(2,t.total/i*100);c.style.width=`${l}%`,c.style.background=ee(r),c.title=`${t.name}: ${t.total}${t.self==null?``:` (self: ${t.self})`}`;let te=Q(`span`,`fg-bar-label`,`${t.name} (${t.total})`);if(c.appendChild(te),t.children?.length&&(c.style.cursor=`pointer`,c.addEventListener(`click`,()=>{o=t,s.push(t),d(),n.emitAction({type:`button`,id:`zoom`,label:`Zoom`},JSON.stringify({name:t.name,total:t.total}))})),c.addEventListener(`mouseenter`,()=>{u.textContent=`${t.name} — total: ${t.total}${t.self==null?``:`, self: ${t.self}`}`}),a.appendChild(c),e.appendChild(a),t.children)for(let n of t.children)f(e,n,r+1,i)}function ee(e){let t=getComputedStyle(document.documentElement),n=[t.getPropertyValue(`--chart-5`).trim()||`#e24d28`,t.getPropertyValue(`--chart-9`).trim()||`#e8602a`,t.getPropertyValue(`--chart-4`).trim()||`#edad2a`,t.getPropertyValue(`--chart-1`).trim()||`#f5c842`,t.getPropertyValue(`--chart-3`).trim()||`#fce94f`,t.getPropertyValue(`--chart-6`).trim()||`#c4a000`,t.getPropertyValue(`--chart-7`).trim()||`#e07028`,t.getPropertyValue(`--chart-8`).trim()||`#d45500`];return n[e%n.length]}d(),XC(`tpl-flame-graph`,gw),e.appendChild(i)},styles(){return gw}},yw=`
2084
2084
  .tpl-kanban { overflow-x: auto; }
2085
2085
  .kbn-board { display: flex; gap: 14px; align-items: flex-start; min-width: min-content; padding-bottom: 4px; }
2086
2086
  .kbn-column { width: 280px; flex: 0 0 280px; border: 1px solid var(--aikit-border, #3c3c3c); border-radius: var(--aikit-radius, 10px);
@@ -2106,7 +2106,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2106
2106
  .kbn-tags { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
2107
2107
  .kbn-tag { padding: 2px 8px; border-radius: 999px; background: var(--aikit-surface, #252526); color: var(--aikit-muted, #9ca3af);
2108
2108
  font: 500 11px var(--aikit-font-sans, Inter, sans-serif); }
2109
- `,ww={name:`kanban`,label:`Kanban`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.cards)?t.cards[0]:void 0;return Array.isArray(t.columns)&&Array.isArray(t.cards)&&typeof n?.column==`string`?.85:0},render(e,t,n){ew(`tpl-kanban`,Cw);let r=t,i=r.cards.map(e=>({...e,tags:e.tags?[...e.tags]:void 0})),a=new Set,o=``,s=Q(`div`,`block tpl-kanban`),c=Q(`div`,`kbn-board`);s.appendChild(c);let l=()=>{c.innerHTML=``;for(let e of r.columns){let t=Q(`section`,`kbn-column`),r=Q(`div`,`kbn-column-header`),s=Q(`div`,`kbn-column-title`),u=Q(`span`,`kbn-column-swatch`);e.color&&(u.style.background=e.color),s.appendChild(u),s.appendChild(Q(`span`,``,e.label)),r.appendChild(s);let d=i.filter(t=>t.column===e.id);r.appendChild(Q(`span`,`kbn-column-count`,String(d.length))),t.appendChild(r);let f=Q(`div`,`kbn-cards`);t.addEventListener(`dragover`,e=>{e.preventDefault(),t.classList.add(`drop-target`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drop-target`)}),t.addEventListener(`drop`,r=>{if(r.preventDefault(),t.classList.remove(`drop-target`),!o)return;let a=i.find(e=>e.id===o);!a||a.column===e.id||(a.column=e.id,l(),n.emitAction({type:`button`,id:`move-card`,label:`Move Card`},JSON.stringify({id:a.id,column:e.id})))});for(let e of d){let t=Q(`article`,`kbn-card priority-${e.priority??`low`}`);if(t.draggable=!0,t.appendChild(Q(`div`,`kbn-card-title`,e.title)),e.description){let n=Q(`div`,`kbn-card-description`,e.description);n.hidden=!a.has(e.id),t.appendChild(n),t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id),n.hidden=!a.has(e.id)})}else t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id)});if(e.tags?.length){let n=Q(`div`,`kbn-tags`);for(let t of e.tags)n.appendChild(Q(`span`,`kbn-tag`,t));t.appendChild(n)}t.addEventListener(`dragstart`,()=>{o=e.id,t.classList.add(`dragging`)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),o=``}),f.appendChild(t)}t.appendChild(f),c.appendChild(t)}};l(),e.appendChild(s)},styles(){return Cw}},Tw=`
2109
+ `,bw={name:`kanban`,label:`Kanban`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e,n=Array.isArray(t.cards)?t.cards[0]:void 0;return Array.isArray(t.columns)&&Array.isArray(t.cards)&&typeof n?.column==`string`?.85:0},render(e,t,n){XC(`tpl-kanban`,yw);let r=t,i=r.cards.map(e=>({...e,tags:e.tags?[...e.tags]:void 0})),a=new Set,o=``,s=Q(`div`,`block tpl-kanban`),c=Q(`div`,`kbn-board`);s.appendChild(c);let l=()=>{c.innerHTML=``;for(let e of r.columns){let t=Q(`section`,`kbn-column`),r=Q(`div`,`kbn-column-header`),s=Q(`div`,`kbn-column-title`),u=Q(`span`,`kbn-column-swatch`);e.color&&(u.style.background=e.color),s.appendChild(u),s.appendChild(Q(`span`,``,e.label)),r.appendChild(s);let d=i.filter(t=>t.column===e.id);r.appendChild(Q(`span`,`kbn-column-count`,String(d.length))),t.appendChild(r);let f=Q(`div`,`kbn-cards`);t.addEventListener(`dragover`,e=>{e.preventDefault(),t.classList.add(`drop-target`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drop-target`)}),t.addEventListener(`drop`,r=>{if(r.preventDefault(),t.classList.remove(`drop-target`),!o)return;let a=i.find(e=>e.id===o);!a||a.column===e.id||(a.column=e.id,l(),n.emitAction({type:`button`,id:`move-card`,label:`Move Card`},JSON.stringify({id:a.id,column:e.id})))});for(let e of d){let t=Q(`article`,`kbn-card priority-${e.priority??`low`}`);if(t.draggable=!0,t.appendChild(Q(`div`,`kbn-card-title`,e.title)),e.description){let n=Q(`div`,`kbn-card-description`,e.description);n.hidden=!a.has(e.id),t.appendChild(n),t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id),n.hidden=!a.has(e.id)})}else t.addEventListener(`click`,()=>{a.has(e.id)?a.delete(e.id):a.add(e.id)});if(e.tags?.length){let n=Q(`div`,`kbn-tags`);for(let t of e.tags)n.appendChild(Q(`span`,`kbn-tag`,t));t.appendChild(n)}t.addEventListener(`dragstart`,()=>{o=e.id,t.classList.add(`dragging`)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),o=``}),f.appendChild(t)}t.appendChild(f),c.appendChild(t)}};l(),e.appendChild(s)},styles(){return yw}},xw=`
2110
2110
  .sort-list { list-style: none; padding: 0; margin: 0; }
2111
2111
  .sort-item { display: flex; align-items: center; gap: 10px; padding: 10px 14px; margin: 4px 0;
2112
2112
  background: var(--aikit-surface, #252526); border: 1px solid var(--aikit-border, #3c3c3c);
@@ -2117,7 +2117,7 @@ container holding the app. Specify either width or maxWidth, and either height o
2117
2117
  .drag-handle { font-size: 18px; color: var(--aikit-muted, #858585); cursor: grab; user-select: none; }
2118
2118
  .sort-label { flex: 1; color: var(--aikit-text, #ccc); }
2119
2119
  .sort-pos { font-size: 12px; color: var(--aikit-muted, #858585); font-variant-numeric: tabular-nums; }
2120
- `,Ew={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);ew(`tpl-list-sort`,Tw);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return Tw}},Dw=document.getElementById(`app`);if(!Dw)throw Error(`Missing #app element`);var $=Dw,Ow=XC(),kw=Ow?void 0:new uC({name:`AI Kit Present`,version:`1.0.0`}),Aw=new uw;Aw.register(Ew),Aw.register(Sw),Aw.register(yw),Aw.register(ww);var jw=GC(kw),Mw={app:kw,data:ZC(kw),emitAction:jw},Nw=new _w,Pw=new iw,Fw=kw?new QC(kw):void 0,Iw=null;function Lw(){Iw?.(),Iw=null,Uw?.destroy&&Uw.destroy(),Uw=null}function Rw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function zw(e,t,n){let r=Rw(t,n);Iw=WC(e,t,(e,t)=>{jw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Bw(e,t,n){let r=document.documentElement.dir,i=JC(e,t,{colorScheme:Nw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var Vw;function Hw(e){Lw(),$.innerHTML=``;let t=lw(e);if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge streaming`,`⟳`)),$.appendChild(t)}let n=Q(`div`,`content`);zw(n,t.blocks??[]),$.appendChild(n)}var Uw=null;function Ww(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function Gw(e){Lw(),$.innerHTML=``;let t=lw(e),n=t.data;if(!n){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge`,`AI KIT`)),$.appendChild(t)}let r=t.template?Aw.get(t.template):Aw.detect(n),i=Q(`div`,`content`);if(r)Uw=r,r.render(i,n,Mw);else if(t.template){let r=Bw(t.template,n,e);r?zw(i,r.blocks,r.actions):zw(i,t.blocks??[],e.actions)}else zw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=WC(t,[{type:`actions`,value:e.actions}],(t,n)=>{jw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Iw;Iw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}kw?(kw.connect().then(()=>{let e=kw.getHostContext();e&&(Nw.apply(e),Pw.apply(e),Fw?.apply(e))}),kw.onhostcontextchanged=e=>{Nw.apply(e),Pw.apply(e),Fw?.apply(e),Uw?.onThemeChange&&Uw.onThemeChange(Nw.getTheme())},kw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(Vw),Vw=setTimeout(()=>{try{let e=t.content;if(!e)return;Hw({title:t.title,template:t.template,content:e})}catch{}},80))},kw.ontoolinput=()=>{clearTimeout(Vw),delete $.dataset.streaming},kw.ontoolresult=e=>{if(clearTimeout(Vw),delete $.dataset.streaming,e.structuredContent)try{Gw(e.structuredContent);return}catch(e){Ww(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{Gw(JSON.parse(t))}catch{Gw({content:t})}}):Ow&&(document.documentElement.dataset.theme=`dark`,Gw(Ow));</script>
2120
+ `,Sw={name:`list-sort`,label:`Sortable List`,detect(e){if(typeof e!=`object`||!e||Array.isArray(e))return 0;let t=e;return t.items&&Array.isArray(t.items)&&!t.categories?.8:0},render(e,t,n){let r=t,i=Q(`div`,`block tpl-list-sort`);XC(`tpl-list-sort`,xw);function a(e){i.innerHTML=``;let t=Q(`ul`,`sort-list`),r=-1;for(let i=0;i<e.length;i++){let o=e[i],s=document.createElement(`li`);s.className=`sort-item`,s.draggable=!0,s.dataset.idx=String(i);let c=Q(`span`,`drag-handle`,`⠿`),l=Q(`span`,`sort-label`,o.label),u=Q(`span`,`sort-pos`,`#${i+1}`);s.appendChild(c),s.appendChild(l),s.appendChild(u),s.addEventListener(`dragstart`,()=>{r=Number(s.dataset.idx),s.classList.add(`dragging`)}),s.addEventListener(`dragend`,()=>{s.classList.remove(`dragging`)}),s.addEventListener(`dragenter`,e=>{e.preventDefault()}),s.addEventListener(`dragover`,e=>{e.preventDefault(),s.classList.add(`drag-over`)}),s.addEventListener(`dragleave`,()=>{s.classList.remove(`drag-over`)}),s.addEventListener(`drop`,t=>{t.preventDefault(),s.classList.remove(`drag-over`);let i=Number(s.dataset.idx);if(r>=0&&r!==i){let t=[...e],[o]=t.splice(r,1);t.splice(i,0,o),a(t),n.emitAction({type:`button`,id:`reorder`,label:`Reorder`},JSON.stringify(t.map(e=>e.id)))}}),t.appendChild(s)}i.appendChild(t)}a([...r.items??[]]),e.appendChild(i)},styles(){return xw}},Cw=document.getElementById(`app`);if(!Cw)throw Error(`Missing #app element`);var $=Cw,ww=KC(),Tw=ww?void 0:new uC({name:`AI Kit Present`,version:`1.0.0`}),Ew=new ow;Ew.register(Sw),Ew.register(vw),Ew.register(hw),Ew.register(bw);var Dw=VC(Tw),Ow={app:Tw,data:qC(Tw),emitAction:Dw},kw=new pw,Aw=new ew,jw=Tw?new JC(Tw):void 0,Mw=null;function Nw(){Mw?.(),Mw=null,zw?.destroy&&zw.destroy(),zw=null}function Pw(e,t){let n=new Map,r=e=>{n.set(o(e.id),e)};for(let e of t??[])r(e);for(let t of e)if(!(t.type!==`actions`||!Array.isArray(t.value)))for(let e of t.value)e&&typeof e==`object`&&`id`in e&&r(e);return n}function Fw(e,t,n){let r=Pw(t,n);Mw=BC(e,t,(e,t)=>{Dw(r.get(e)??{type:t===void 0?`button`:`select`,id:e,label:e},t)})}function Iw(e,t,n){let r=document.documentElement.dir,i=WC(e,t,{colorScheme:kw.getTheme(),lang:document.documentElement.lang||void 0,dir:r===`ltr`||r===`rtl`||r===`auto`?r:void 0});return i?{blocks:i.blocks,actions:n.actions}:null}var Lw;function Rw(e){Nw(),$.innerHTML=``;let t=aw(e);if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge streaming`,`⟳`)),$.appendChild(t)}let n=Q(`div`,`content`);Fw(n,t.blocks??[]),$.appendChild(n)}var zw=null;function Bw(e,t){$.innerHTML=``;let n=Q(`div`,`error-panel`);n.appendChild(Q(`h3`,``,`⚠ ${e}`)),n.appendChild(Q(`pre`,``,t instanceof Error?t.message:String(t))),$.appendChild(n)}function Vw(e){Nw(),$.innerHTML=``;let t=aw(e),n=t.data;if(!n){$.innerHTML=`<p class="no-data">No content data received.</p>`;return}if(e.title){let t=Q(`div`,`header`);t.appendChild(Q(`h1`,``,e.title)),t.appendChild(Q(`span`,`badge`,`AI KIT`)),$.appendChild(t)}let r=t.template?Ew.get(t.template):Ew.detect(n),i=Q(`div`,`content`);if(r)zw=r,r.render(i,n,Ow);else if(t.template){let r=Iw(t.template,n,e);r?Fw(i,r.blocks,r.actions):Fw(i,t.blocks??[],e.actions)}else Fw(i,t.blocks??[],e.actions);if($.appendChild(i),e.actions?.length){let t=Q(`div`,`actions-shell`),n=BC(t,[{type:`actions`,value:e.actions}],(t,n)=>{Dw(e.actions?.find(e=>o(e.id)===t)??{type:n===void 0?`button`:`select`,id:t,label:t},n)}),r=Mw;Mw=()=>{r?.(),n()},$.appendChild(t)}let a=Q(`div`,`footer`);a.innerHTML=`<span class="footer-brand">Powered by <strong>AI Kit</strong></span>`,$.appendChild(a)}Tw?(Tw.connect().then(()=>{let e=Tw.getHostContext();e&&(kw.apply(e),Aw.apply(e),jw?.apply(e))}),Tw.onhostcontextchanged=e=>{kw.apply(e),Aw.apply(e),jw?.apply(e),zw?.onThemeChange&&zw.onThemeChange(kw.getTheme())},Tw.ontoolinputpartial=e=>{let t=e.arguments;t&&($.dataset.streaming=`true`,clearTimeout(Lw),Lw=setTimeout(()=>{try{let e=t.content;if(!e)return;Rw({title:t.title,template:t.template,content:e})}catch{}},80))},Tw.ontoolinput=()=>{clearTimeout(Lw),delete $.dataset.streaming},Tw.ontoolresult=e=>{if(clearTimeout(Lw),delete $.dataset.streaming,e.structuredContent)try{Vw(e.structuredContent);return}catch(e){Bw(`Render error`,e);return}let t=e.content?.find(e=>e.type===`text`)?.text;if(!t){$.innerHTML=`<p>No data received.</p>`;return}try{Vw(JSON.parse(t))}catch{Vw({content:t})}}):ww&&(document.documentElement.dataset.theme=`dark`,Vw(ww));</script>
2121
2121
  </head>
2122
2122
  <body>
2123
2123
  <div id="app">
@@ -5,4 +5,4 @@ import{t as e}from"./rolldown-runtime-yuFVEuWy.js";import{createHash as t,random
5
5
  `).length,fileHash:this.hash(e.content),indexedAt:t,origin:`curated`,tags:e.frontmatter.tags,category:e.frontmatter.category,version:e.frontmatter.version}});try{return await this.store.upsert(i,r),e.length}catch(t){I.error(`Failed to upsert curated batch`,{batchSize:e.length,...p(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return I.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...p(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;I.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...p(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),o=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(o,t,n)}}gitCommitKnowledge(e,t,n){try{if(!h(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;g(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!h(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;_([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>v(e)).join(`/`);return t.split(`/`).every(e=>m.test(e))?`${F}/${t}`:null}async indexCuratedFile(e,t,n){let r=await this.embedder.embed(t),i=`.ai/curated/${e}`,a=new Date().toISOString(),o={id:this.hashId(i,0),content:t,sourcePath:i,contentType:`curated-knowledge`,headingPath:n.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:t.split(`
6
6
  `).length,fileHash:this.hash(t),indexedAt:a,origin:`curated`,tags:n.tags,category:n.category,version:n.version};await this.store.upsert([o],[r])}async indexCuratedFileBestEffort(e,t,n,r){if(d.instance().isDegraded(`embedder`)){I.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:r,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){I.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:r,...p(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||a(t))throw Error(`Invalid path: ${t}. Must be relative within .ai/curated/ directory.`);let n=t.split(`/`)[0];return this.validateCategoryName(n),t}validateCategoryName(e){if(!/^[a-z][a-z0-9-]*$/.test(e))throw Error(`Invalid category name: "${e}". Must be lowercase kebab-case (e.g., "decisions", "api-contracts").`)}validateContentSize(e){if(Buffer.byteLength(e,`utf-8`)>P)throw Error(`Content exceeds maximum size of ${P/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}async uniqueRelativePath(e,t){let n=`${e}/${t}.md`;if(!await this.adapter.exists(n))return n;for(let n=2;n<=100;n++){let r=`${e}/${t}-${n}.md`;if(!await this.adapter.exists(r))return r}throw Error(`Too many entries with slug "${t}" in category "${e}"`)}hash(e){return t(`sha256`).update(e).digest(`hex`).slice(0,16)}hashId(e,t){return this.hash(`${e}::${t}`)}serializeFile(e,t){return`${[`---`,`title: "${t.title.replace(/"/g,`\\"`)}"`,`category: ${t.category}`,`tags: [${t.tags.map(e=>`"${e}"`).join(`, `)}]`,`created: ${t.created}`,`updated: ${t.updated}`,`version: ${t.version}`,`origin: ${t.origin}`,`changelog:`,...t.changelog.map(e=>` - version: ${e.version}\n date: ${e.date}\n reason: "${e.reason.replace(/"/g,`\\"`)}"`),`---`].join(`
7
7
  `)}\n\n${e}\n`}parseFile(e){let t=e.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);if(!t)return{frontmatter:{title:`Untitled`,category:`notes`,tags:[],created:``,updated:``,version:1,origin:`curated`,changelog:[]},content:e};let n=t[1],r=t[2].trim(),i={},a=[],o=n.split(`
8
- `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function R(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const z=f(`server`),B=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function V({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?B.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function H({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function U(e){return e.startsWith(`file://`)?c(e):e}function W(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function G(e){let t=new Map;for(let n of e){let e=U(n.uri);t.set(W(e),e)}return[...t.values()].sort((e,t)=>W(e).localeCompare(W(t)))}function K({config:e,roots:t}){let n=G(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=W(r),t=n.find(t=>W(t)===e);if(t)return t}return n[0]}function q({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=G(r);if(i.length===0)return!1;let a=K({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&W(o)===W(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function J({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=!1,d=!1,f,m=o.server,h=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{u||(u=!0,s())},_=()=>{d||t!==`auto`||(d=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,p(e))}})())},v=t=>t.length===0||(f&&=(clearTimeout(f),void 0),!q({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:l(),...p(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:l(),...p(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,p(e))}}),f=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),q({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function Y(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function X(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Z(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function Q(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function $(){return X()?u({allowPositionals:!0,options:{transport:{type:`string`,default:Y()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:Y(),port:process.env.AIKIT_PORT??`3210`}}async function ee(){let e=R(),t=$();process.on(`unhandledRejection`,e=>{z.error(`Unhandled rejection`,p(e))}),process.on(`uncaughtException`,e=>{z.error(`Uncaught exception — exiting`,p(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&z.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&z.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&z.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>N),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){z.warn(`Startup maintenance failed (non-critical)`,p(e))}}).catch(()=>{})};if(z.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:u},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-CCrLxwqC.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),m=i();z.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json({limit:`1mb`}));let g=Number(t.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=Q(`AIKIT_HTTP_MAX_SESSIONS`,8),x=Q(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=Q(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=H({limit:100,windowMs:6e4}),w=!1;h.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=V({requestOrigin:r,configuredOrigin:v,allowAnyOrigin:y,fallbackOrigin:_});if(i.warn&&!w&&(w=!0,z.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let T=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(T)),h.use(`/mcp`,(e,t,n)=>{let r=Z(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(C.allow(r)){n();return}let i=Math.max(1,Math.ceil(C.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(h,s(),z);let E=new Date().toISOString();h.use(`/settings/api`,u({log:z,mcpInfo:()=>({transport:`http`,port:g,pid:process.pid,startedAt:E})})),c(h,l(),z),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let D=!1,O=null,A=null,M=null,N=null,P=null,F=null,I=null,L=Promise.resolve(),R=async(e,t)=>{if(!D||!M||!N){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=L,i;L=new Promise(e=>{i=e}),await r;try{let r=Z(e);if(!F){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new N({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{I=e,A?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&A?.onSessionEnd(e),I=null}});e.onclose=()=>{F===e&&(F=null),I===e.sessionId&&(I=null)},F=e,await M.connect(e)}let i=F;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(I=i.sessionId,A?.onSessionStart(i.sessionId,{transport:`http`}),A?.onSessionActivity(i.sessionId)):r&&A?.onSessionActivity(r))}catch(e){if(z.error(`MCP handler error`,p(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},B=async(e,t)=>{let n=Z(e);if(P&&(!F||n!==I)){await P.handleRequest(e,t,e.body);return}await R(e,t)};h.post(`/mcp`,B),h.get(`/mcp`,B),h.delete(`/mcp`,B);let U=h.listen(g,`127.0.0.1`,()=>{z.info(`MCP server listening`,{url:`http://127.0.0.1:${g}/mcp`,port:g}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-CWkmhYOe.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);M=l.server,N=i,D=!0,z.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);A=new j(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(I===e&&F){let e=F;F=null,I=null,e.close().catch(()=>void 0)}P?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&z.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),P=new k({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:b,sessionTimeoutMinutes:x,onSessionStart:e=>A?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>A?.onSessionActivity(e),onSessionEnd:e=>A?.onSessionEnd(e)}),A.startGC(),I&&(A.onSessionStart(I,{transport:`http`}),A.onSessionActivity(I)),z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>z.error(`Failed to start session manager`,p(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);z.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),z.info(`Initial index complete`)}catch(e){z.error(`Initial index failed; will retry on aikit_reindex`,p(e))}}).catch(e=>z.error(`AI Kit init or indexing failed`,p(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;O=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),z.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit initialization failed`,p(e))):(l.ready.catch(e=>z.error(`AI Kit initialization failed`,p(e))),z.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){z.error(`Failed to load server modules`,p(e))}},100)}),W=async e=>{z.info(`Shutdown signal received`,{signal:e}),O?.stop(),A?.stop(),await P?.closeAll().catch(()=>void 0),I&&A?.onSessionEnd(I),F&&(await F.close().catch(()=>void 0),F=null,I=null),U.close(),M&&await M.close(),process.exit(0)};process.on(`SIGINT`,()=>W(`SIGINT`)),process.on(`SIGTERM`,()=>W(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-CCrLxwqC.js`),import(`./server-CWkmhYOe.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();z.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let l=n(c),u=i(c,l),{server:d,startInit:f,ready:m,runInitialIndex:h}=u,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await d.connect(_),z.debug(`MCP server started`,{transport:`stdio`}),await J({config:c,indexMode:l,log:z,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:d,startInit:f});let v=null,y=()=>{v&&clearTimeout(v),v=setTimeout(async()=>{z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=u.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),v.unref&&v.unref()};y(),process.stdin.on(`data`,()=>y()),m.catch(e=>{z.error(`Initialization failed — server will continue with limited tools`,p(e))}),l===`smart`?m.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,c,u.aikit.store),n=u.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),z.debug(`Smart index scheduler started (stdio mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit init failed for smart scheduler`,p(e))):z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:l}),r(m,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}}ee();export{M as n,L as t};
8
+ `),s=!1,c={};for(let e of o){if(/^changelog:\s*$/.test(e)){s=!0;continue}if(s){let t=e.match(/^\s+-\s+version:\s*(\d+)$/);if(t){c.version!=null&&a.push(c),c={version:parseInt(t[1],10)};continue}let n=e.match(/^\s+date:\s*(.+)$/);if(n){c.date=n[1].trim();continue}let r=e.match(/^\s+reason:\s*"?(.*?)"?\s*$/);if(r){c.reason=r[1];continue}/^\w/.test(e)&&(s=!1,c.version!=null&&a.push(c),c={});continue}let t=e.match(/^(\w+):\s*(.*)$/);if(t){let e=t[1],n=t[2];typeof n==`string`&&n.startsWith(`[`)&&n.endsWith(`]`)?n=n.slice(1,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``)).filter(e=>e.length>0):typeof n==`string`&&/^\d+$/.test(n)?n=parseInt(n,10):typeof n==`string`&&n.startsWith(`"`)&&n.endsWith(`"`)&&(n=n.slice(1,-1)),i[e]=n}}return c.version!=null&&a.push(c),{frontmatter:{title:i.title??`Untitled`,category:i.category??`notes`,tags:i.tags??[],created:i.created??``,updated:i.updated??``,version:i.version??1,origin:`curated`,changelog:a},content:r}}};function R(){try{let e=s(i(c(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(r(e,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}const z=f(`server`),B=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function V({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?B.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function H({limit:e,windowMs:t}){let n=new Map,r=(e,r)=>{let i=r-t,a=n.get(e)?.filter(e=>e>i)??[];return a.length===0?(n.delete(e),[]):(n.set(e,a),a)};return{allow(t,i=Date.now()){let a=r(t,i);return a.length>=e?!1:(a.push(i),n.set(t,a),!0)},getRetryAfterMs(n,i=Date.now()){let a=r(n,i);return a.length<e?0:Math.max(0,a[0]+t-i)}}}function U(e){return e.startsWith(`file://`)?c(e):e}function W(e){let t=s(e);return process.platform===`win32`?t.toLowerCase():t}function G(e){let t=new Map;for(let n of e){let e=U(n.uri);t.set(W(e),e)}return[...t.values()].sort((e,t)=>W(e).localeCompare(W(t)))}function K({config:e,roots:t}){let n=G(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=W(r),t=n.find(t=>W(t)===e);if(t)return t}return n[0]}function q({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=G(r);if(i.length===0)return!1;let a=K({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path,s=o&&W(o)===W(a)?`configured-source`:`stable-sorted-root`;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:s}),n(e,a),e.allRoots=i,!0}async function J({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:a,server:o,startInit:s,timeoutMs:c=5e3,getCwd:l=()=>process.cwd()}){let u=!1,d=!1,f,m=o.server,h=e=>{let t=p(e),n=`${String(e)} ${String(t.message??``)}`.toLowerCase();return n.includes(`method not found`)||n.includes(`not supported`)||n.includes(`unsupported`)||n.includes(`unknown method`)||n.includes(`roots/list`)},g=()=>{u||(u=!0,s())},_=()=>{d||t!==`auto`||(d=!0,(async()=>{try{await a()}catch(e){n.error(`Initial index failed`,p(e))}})())},v=t=>t.length===0||(f&&=(clearTimeout(f),void 0),!q({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(g(),_(),!0);try{if(v((await m.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(e){if(h(e)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{cwd:l(),...p(e)}),g(),_();return}n.warn(`MCP roots/list failed during bootstrap; waiting for roots/list_changed notification`,{cwd:l(),...p(e)})}m.setNotificationHandler(r,async()=>{try{v((await m.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,p(e))}}),f=setTimeout(()=>{let t=l();n.debug(`Timed out waiting for MCP roots/list_changed; falling back to cwd workspace`,{cwd:t}),q({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(g(),_())},c)}function Y(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function X(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function Z(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function Q(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}function $(){return X()?u({allowPositionals:!0,options:{transport:{type:`string`,default:Y()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:Y(),port:process.env.AIKIT_PORT??`3210`}}async function ee(){let e=R(),t=$();process.on(`unhandledRejection`,e=>{z.error(`Unhandled rejection`,p(e))}),process.on(`uncaughtException`,e=>{z.error(`Uncaught exception — exiting`,p(e)),process.exit(1)});let r=(e,t)=>{e.then(async()=>{try{let{markPromoteRun:e,markPruneRun:n,prune:r,shouldRunStartupPrune:i,shouldRunWeeklyPromote:a}=await import(`../../tools/dist/index.js`),o=t();if(!o)return;if(i()){let e=await r({});n(),e.totalBytesFreed>0&&z.info(`Storage maintenance complete`,{forgeOrphans:e.forgeGroundOrphans.count,legacyLance:e.legacyLance.count,bytesFreed:e.totalBytesFreed});let{groupLessons:t,pruneLessons:i}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),a=await i(o.curated,o.stateStore,{dryRun:!1});a.pruned.length>0&&z.info(`Startup lesson prune complete`,{pruned:a.pruned.length});let s=await t(o.curated,o.stateStore,{dryRun:!1});(s.groupsCreated>0||s.lessonsGrouped>0)&&z.info(`Startup lesson grouping complete`,{groupsCreated:s.groupsCreated,lessonsGrouped:s.lessonsGrouped})}if(a()){let{DEFAULT_PROMOTE_CONFIG:t,collectWorkspaceLessons:n,getGlobalCuratedDir:r,promoteLessons:i,scanForDuplicates:a}=await import(`./promotion-CJFYv4Ye.js`).then(e=>e.o),{CuratedKnowledgeManager:s}=await Promise.resolve().then(()=>N),c=o.curated,l=new s(r(),c.store,c.embedder),u=await n(),d={...t,dryRun:!1},f=await i(a(u,d),l,d);e(),f.promoted.length>0&&z.info(`Weekly lesson promotion complete`,{promoted:f.promoted.length,candidates:f.candidates.length})}}catch(e){z.warn(`Startup maintenance failed (non-critical)`,p(e))}}).catch(()=>{})};if(z.info(`Starting MCP AI Kit server`,{version:e}),t.transport===`http`){let[{default:e},{loadConfig:i,resolveIndexMode:a},{registerDashboardRoutes:o,resolveDashboardDir:s},{registerSettingsRoutes:c,resolveSettingsDir:l},{createSettingsRouter:u},{authMiddleware:d,getOrCreateToken:f}]=await Promise.all([import(`express`),import(`./config-CCrLxwqC.js`),import(`./dashboard-static-CRfR1yKU.js`),import(`./settings-static-B3lnYvcb.js`),import(`./routes-Afg7J7xK.js`),import(`./auth-lzZKfxlV.js`)]),m=i();z.info(`Config loaded`,{sourceCount:m.sources.length,storePath:m.store.path});let h=e();h.use(e.json({limit:`1mb`}));let g=Number(t.port),_=`http://localhost:${g}`,v=process.env.AIKIT_CORS_ORIGIN??_,y=process.env.AIKIT_ALLOW_ANY_ORIGIN===`true`,b=Q(`AIKIT_HTTP_MAX_SESSIONS`,8),x=Q(`AIKIT_HTTP_SESSION_TIMEOUT_MINUTES`,30),S=Q(`AIKIT_HTTP_SESSION_GC_INTERVAL_MINUTES`,5),C=H({limit:100,windowMs:6e4}),w=!1;h.use((e,t,n)=>{let r=Array.isArray(e.headers.origin)?e.headers.origin[0]:e.headers.origin,i=V({requestOrigin:r,configuredOrigin:v,allowAnyOrigin:y,fallbackOrigin:_});if(i.warn&&!w&&(w=!0,z.warn(`Rejected non-local CORS origin while AIKIT_CORS_ORIGIN=*`,{origin:r,allowAnyOriginEnv:`AIKIT_ALLOW_ANY_ORIGIN=true`})),r&&!i.allowOrigin){t.status(403).json({error:`Origin not allowed`});return}if(i.allowOrigin&&t.setHeader(`Access-Control-Allow-Origin`,i.allowOrigin),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, PATCH, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID`),t.setHeader(`Access-Control-Expose-Headers`,`Mcp-Session-Id`),e.method===`OPTIONS`){t.status(204).end();return}n()});let T=f();console.error(`[aikit] Auth token: ~/.aikit/token`),h.use(d(T)),h.use(`/mcp`,(e,t,n)=>{let r=Z(e)??e.ip??e.socket.remoteAddress??`anonymous`;if(C.allow(r)){n();return}let i=Math.max(1,Math.ceil(C.getRetryAfterMs(r)/1e3));t.setHeader(`Retry-After`,String(i)),t.status(429).json({jsonrpc:`2.0`,error:{code:-32003,message:`Rate limit exceeded`},id:null})}),o(h,s(),z);let E=new Date().toISOString();h.use(`/settings/api`,u({log:z,mcpInfo:()=>({transport:`http`,port:g,pid:process.pid,startedAt:E})})),c(h,l(),z),h.get(`/health`,(e,t)=>{t.json({status:`ok`})});let D=!1,O=null,A=null,M=null,N=null,P=null,F=null,I=null,L=Promise.resolve(),R=async(e,t)=>{if(!D||!M||!N){t.status(503).json({jsonrpc:`2.0`,error:{code:-32603,message:`Server initializing — please retry in a few seconds`},id:null});return}let r=L,i;L=new Promise(e=>{i=e}),await r;try{let r=Z(e);if(!F){if(r){t.status(404).json({jsonrpc:`2.0`,error:{code:-32001,message:`Session not found`},id:null});return}let e=new N({sessionIdGenerator:()=>n(),onsessioninitialized:async e=>{I=e,A?.onSessionStart(e,{transport:`http`})},onsessionclosed:async e=>{e&&A?.onSessionEnd(e),I=null}});e.onclose=()=>{F===e&&(F=null),I===e.sessionId&&(I=null)},F=e,await M.connect(e)}let i=F;await i.handleRequest(e,t,e.body),e.method!==`DELETE`&&(!r&&i.sessionId?(I=i.sessionId,A?.onSessionStart(i.sessionId,{transport:`http`}),A?.onSessionActivity(i.sessionId)):r&&A?.onSessionActivity(r))}catch(e){if(z.error(`MCP handler error`,p(e)),!t.headersSent){let n=e instanceof Error?e.message:String(e),r=n.includes(`Not Acceptable`);t.status(r?406:500).json({jsonrpc:`2.0`,error:{code:r?-32e3:-32603,message:r?n:`Internal server error`},id:null})}}finally{i()}},B=async(e,t)=>{let n=Z(e);if(P&&(!F||n!==I)){await P.handleRequest(e,t,e.body);return}await R(e,t)};h.post(`/mcp`,B),h.get(`/mcp`,B),h.delete(`/mcp`,B);let U=h.listen(g,`127.0.0.1`,()=>{z.info(`MCP server listening`,{url:`http://127.0.0.1:${g}/mcp`,port:g}),setTimeout(async()=>{try{let[{createLazyServer:e,createMcpServer:t,ALL_TOOL_NAMES:n},{StreamableHTTPServerTransport:i},{checkForUpdates:o,autoUpgradeScaffold:s}]=await Promise.all([import(`./server-CzPRmJtW.js`),import(`@modelcontextprotocol/sdk/server/streamableHttp.js`),import(`./version-check-gazMo-D4.js`)]);o(),s();let c=a(m),l=e(m,c);M=l.server,N=i,D=!0,z.debug(`MCP server configured (lazy — AI Kit initializing in background)`,{toolCount:n.length,resourceCount:2}),l.startInit(),l.ready.then(()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);A=new j(l.aikit.stateStore,{staleTimeoutMinutes:x,gcIntervalMinutes:S,onBeforeSessionDelete:e=>{if(I===e&&F){let e=F;F=null,I=null,e.close().catch(()=>void 0)}P?.closeSession(e,{notifySessionEnd:!1})},onSessionEndMaintenance:async()=>{if(!l.aikit?.curated||!l.aikit?.stateStore)return;let{pruneLessons:e}=await import(`./evolution-DWaEE6XW.js`).then(e=>e.t),t=await e(l.aikit.curated,l.aikit.stateStore,{dryRun:!1});t.pruned.length>0&&z.info(`Session-end lesson prune`,{pruned:t.pruned.length})}}),P=new k({createServer:()=>{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);return t(l.aikit,m)},createTransport:e=>new i(e),maxSessions:b,sessionTimeoutMinutes:x,onSessionStart:e=>A?.onSessionStart(e,{transport:`http`}),onSessionActivity:e=>A?.onSessionActivity(e),onSessionEnd:e=>A?.onSessionEnd(e)}),A.startGC(),I&&(A.onSessionStart(I,{transport:`http`}),A.onSessionActivity(I)),z.info(`HTTP session runtime ready`,{maxSessions:b,sessionTimeoutMinutes:x,gcIntervalMinutes:S})}).catch(e=>z.error(`Failed to start session manager`,p(e))),c===`auto`?l.ready.then(async()=>{try{let e=m.sources.map(e=>e.path).join(`, `);z.info(`Running initial index`,{sourcePaths:e}),await l.runInitialIndex(),z.info(`Initial index complete`)}catch(e){z.error(`Initial index failed; will retry on aikit_reindex`,p(e))}}).catch(e=>z.error(`AI Kit init or indexing failed`,p(e))):c===`smart`?l.ready.then(async()=>{try{if(!l.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(l.aikit.indexer,m,l.aikit.store),n=l.aikit.store;O=t,t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),l.setSmartScheduler(t),z.debug(`Smart index scheduler started (HTTP mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit initialization failed`,p(e))):(l.ready.catch(e=>z.error(`AI Kit initialization failed`,p(e))),z.info(`Initial full indexing skipped in HTTP mode`,{indexMode:c})),r(l.ready,()=>l.aikit?{curated:l.aikit.curated,stateStore:l.aikit.stateStore}:null)}catch(e){z.error(`Failed to load server modules`,p(e))}},100)}),W=async e=>{z.info(`Shutdown signal received`,{signal:e}),O?.stop(),A?.stop(),await P?.closeAll().catch(()=>void 0),I&&A?.onSessionEnd(I),F&&(await F.close().catch(()=>void 0),F=null,I=null),U.close(),M&&await M.close(),process.exit(0)};process.on(`SIGINT`,()=>W(`SIGINT`)),process.on(`SIGTERM`,()=>W(`SIGTERM`))}else{let[{loadConfig:e,reconfigureForWorkspace:t,resolveIndexMode:n},{createLazyServer:i},{checkForUpdates:a,autoUpgradeScaffold:o},{RootsListChangedNotificationSchema:s}]=await Promise.all([import(`./config-CCrLxwqC.js`),import(`./server-CzPRmJtW.js`),import(`./version-check-gazMo-D4.js`),import(`@modelcontextprotocol/sdk/types.js`)]),c=e();z.info(`Config loaded`,{sourceCount:c.sources.length,storePath:c.store.path}),a(),o();let l=n(c),u=i(c,l),{server:d,startInit:f,ready:m,runInitialIndex:h}=u,{StdioServerTransport:g}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),_=new g;await d.connect(_),z.debug(`MCP server started`,{transport:`stdio`}),await J({config:c,indexMode:l,log:z,rootsChangedNotificationSchema:s,reconfigureForWorkspace:t,runInitialIndex:h,server:d,startInit:f});let v=null,y=()=>{v&&clearTimeout(v),v=setTimeout(async()=>{z.info(`Auto-shutdown: no activity for 30 minutes — shutting down gracefully`);try{let e=u.aikit;e&&await Promise.all([e.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),e.graphStore.close().catch(()=>{}),e.store.close().catch(()=>{})])}catch{}process.exit(0)},18e5),v.unref&&v.unref()};y(),process.stdin.on(`data`,()=>y()),m.catch(e=>{z.error(`Initialization failed — server will continue with limited tools`,p(e))}),l===`smart`?m.then(async()=>{try{if(!u.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(u.aikit.indexer,c,u.aikit.store),n=u.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),u.setSmartScheduler(t),z.debug(`Smart index scheduler started (stdio mode)`)}catch(e){z.error(`Failed to start smart index scheduler`,p(e))}}).catch(e=>z.error(`AI Kit init failed for smart scheduler`,p(e))):z.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:l}),r(m,()=>u.aikit?{curated:u.aikit.curated,stateStore:u.aikit.stateStore}:null)}}ee();export{M as n,L as t};