@vpxa/aikit 0.1.315 → 0.1.316

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.315",
3
+ "version": "0.1.316",
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",
@@ -1,4 +1,4 @@
1
- "use strict";var AnnotationInit=(()=>{var N=Object.defineProperty;var A=(i,t,e)=>t in i?N(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var d=(i,t,e)=>A(i,typeof t!="symbol"?t+"":t,e);function v(i,t){if(document.getElementById(i))return;let e=document.createElement("style");e.id=i,e.textContent=t,document.head.appendChild(e)}var C=document.createElement("div");function g(i){return C.textContent=i,C.innerHTML}var H="aikit-annotation-popover",O=`
1
+ "use strict";var AnnotationInit=(()=>{var A=Object.defineProperty;var N=(l,t,e)=>t in l?A(l,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[t]=e;var d=(l,t,e)=>N(l,typeof t!="symbol"?t+"":t,e);function b(l,t){if(document.getElementById(l))return;let e=document.createElement("style");e.id=l,e.textContent=t,document.head.appendChild(e)}var C=document.createElement("div");function g(l){return C.textContent=l,C.innerHTML}var H="aikit-annotation-popover",O=`
2
2
  .cp-backdrop {
3
3
  position: fixed;
4
4
  top: 0;
@@ -96,7 +96,7 @@
96
96
  .cp-btn--remove:hover {
97
97
  background: var(--dt-annotation-deletion-bg);
98
98
  }
99
- `,b=class{constructor(t,e){d(this,"el");d(this,"textarea");d(this,"result");d(this,"backdrop");d(this,"options");this.result=t,this.options=e,v(H,O),this.backdrop=document.createElement("div"),this.backdrop.className="cp-backdrop",this.el=document.createElement("div"),this.el.className="cp-popover",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Feedback on selection"),this.el.innerHTML=`
99
+ `,v=class{constructor(t,e){d(this,"el");d(this,"textarea");d(this,"result");d(this,"backdrop");d(this,"options");this.result=t,this.options=e,b(H,O),this.backdrop=document.createElement("div"),this.backdrop.className="cp-backdrop",this.el=document.createElement("div"),this.el.className="cp-popover",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Feedback on selection"),this.el.innerHTML=`
100
100
  <div class="cp-header">Feedback</div>
101
101
  <div class="cp-excerpt">${this.escapeText(t.text)}</div>
102
102
  <textarea class="cp-textarea" placeholder="Add a comment (optional)..." aria-label="Comment text"></textarea>
@@ -105,12 +105,12 @@
105
105
  <button class="cp-btn cp-btn--remove" aria-label="Remove selection without comment">Remove</button>
106
106
  <button class="cp-btn cp-btn--comment" aria-label="Submit comment">Comment</button>
107
107
  </div>
108
- `,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),r=this.el.querySelector(".cp-btn--remove"),a=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),r.addEventListener("click",()=>this.handleRemove()),a.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",o=>this.handleKeyDown(o)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",o=>{if(o.key!=="Tab")return;let s=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(s.length===0)return;let l=s[0],p=s[s.length-1];o.shiftKey&&document.activeElement===l?(o.preventDefault(),p.focus()):!o.shiftKey&&document.activeElement===p&&(o.preventDefault(),l.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}positionNearSelection(){let t=this.result.range.getBoundingClientRect(),e=window.scrollX,n=window.scrollY,r=this.el.offsetWidth||320,a=this.el.offsetHeight||260,o=8,s=t.left+e+t.width/2-r/2;s=Math.max(o,s),s=Math.min(s,window.innerWidth+e-r-o);let l=window.innerHeight+n,p=t.bottom+n+o,c;p+a<=l?c=p:(c=t.top+n-a-o,c=Math.max(o,c)),this.el.style.left=`${s}px`,this.el.style.top=`${c}px`}handleComment(){let t=this.textarea.value.trim();this.options.onSubmit(this.result,t)}handleRemove(){let t=this.textarea.value.trim();this.options.onRemove(this.result,t)}handleCancel(){this.options.onDismiss()}handleKeyDown(t){t.key==="Escape"?(t.preventDefault(),this.handleCancel()):(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.handleComment())}};var x=class{constructor(t){d(this,"store");this.store=t}exportMarkdown(){let e=[...this.store.getState().annotations].sort((o,s)=>o.createdAt-s.createdAt);if(e.length===0)return"No feedback provided.";let n=e.filter(o=>o.type==="COMMENT"),r=e.filter(o=>o.type==="DELETION"),a=["## Reviewer Feedback",""];if(n.length>0){a.push("### Comments","");for(let o of n){let s=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;a.push(`- **${o.comment}**`),a.push(` > "${s}"`),a.push("")}}if(r.length>0){a.push("### Deletions","");for(let o of r){let s=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;a.push("- Remove this"),a.push(` > "${s}"`),a.push("")}}return a.join(`
109
- `).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((n,r)=>n.createdAt-r.createdAt);return JSON.stringify(e,null,2)}submitFeedback(t){let e=this.exportMarkdown(),n=this.exportJSON(),r=e==="No feedback provided."?e:`${e}
108
+ `,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),a=this.el.querySelector(".cp-btn--remove"),r=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),a.addEventListener("click",()=>this.handleRemove()),r.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",o=>this.handleKeyDown(o)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",o=>{if(o.key!=="Tab")return;let i=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let s=i[0],p=i[i.length-1];o.shiftKey&&document.activeElement===s?(o.preventDefault(),p.focus()):!o.shiftKey&&document.activeElement===p&&(o.preventDefault(),s.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}positionNearSelection(){let t=this.result.range.getBoundingClientRect(),e=window.scrollX,n=window.scrollY,a=this.el.offsetWidth||320,r=this.el.offsetHeight||260,o=8,i=t.left+e+t.width/2-a/2;i=Math.max(o,i),i=Math.min(i,window.innerWidth+e-a-o);let s=window.innerHeight+n,p=t.bottom+n+o,c;p+r<=s?c=p:(c=t.top+n-r-o,c=Math.max(o,c)),this.el.style.left=`${i}px`,this.el.style.top=`${c}px`}handleComment(){let t=this.textarea.value.trim();this.options.onSubmit(this.result,t)}handleRemove(){let t=this.textarea.value.trim();this.options.onRemove(this.result,t)}handleCancel(){this.options.onDismiss()}handleKeyDown(t){t.key==="Escape"?(t.preventDefault(),this.handleCancel()):(t.ctrlKey||t.metaKey)&&t.key==="Enter"&&(t.preventDefault(),this.handleComment())}};var x=class{constructor(t){d(this,"store");this.store=t}exportMarkdown(){let e=[...this.store.getState().annotations].sort((o,i)=>o.createdAt-i.createdAt);if(e.length===0)return"No feedback provided.";let n=e.filter(o=>o.type==="COMMENT"),a=e.filter(o=>o.type==="DELETION"),r=["## Reviewer Feedback",""];if(n.length>0){r.push("### Comments","");for(let o of n){let i=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;r.push(`- **${o.comment}**`),r.push(` > "${i}"`),r.push("")}}if(a.length>0){r.push("### Deletions","");for(let o of a){let i=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;r.push("- Remove this"),r.push(` > "${i}"`),r.push("")}}return r.join(`
109
+ `).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((n,a)=>n.createdAt-a.createdAt);return JSON.stringify(e,null,2)}submitFeedback(t){let e=this.exportMarkdown(),n=this.exportJSON(),a=e==="No feedback provided."?e:`${e}
110
110
 
111
111
  \`\`\`json
112
112
  ${n}
113
- \`\`\``;t("annotations",r)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(r=>r.type==="COMMENT").length,n=t.annotations.filter(r=>r.type==="DELETION").length;return{comments:e,deletions:n,total:t.annotations.length}}};var M="aikit-annotation-highlight";function B(){if(document.getElementById(M))return;let i=document.createElement("style");i.id=M,i.textContent=`
113
+ \`\`\``;t("annotations",a)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(a=>a.type==="COMMENT").length,n=t.annotations.filter(a=>a.type==="DELETION").length;return{comments:e,deletions:n,total:t.annotations.length}}};var M="aikit-annotation-highlight";function B(){if(document.getElementById(M))return;let l=document.createElement("style");l.id=M,l.textContent=`
114
114
  mark.hl-COMMENT {
115
115
  background: var(--dt-annotation-comment-bg, rgba(88, 166, 255, 0.15));
116
116
  border-bottom: 2px solid var(--dt-annotation-comment, #58a6ff);
@@ -151,7 +151,7 @@ ${n}
151
151
  50% { transform: scale(1.05); }
152
152
  100% { transform: scale(1); }
153
153
  }
154
- `,document.head.appendChild(i)}var y=class{constructor(t,e){d(this,"container");d(this,"store");d(this,"unsubscribe",null);this.container=t,this.store=e}start(){B(),this.unsubscribe=this.store.subscribe(t=>{switch(t.type){case"annotation-added":this.createHighlight(t.annotation);break;case"annotation-removed":this.removeHighlight(t.id);break;case"selection-changed":this.updateSelection(t.id),t.id!==null&&this.scrollToAnnotation(t.id);break}})}stop(){this.unsubscribe?.(),this.unsubscribe=null,this.clearAll()}findTextNodeRange(t,e,n){let r=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null),a=0,o=null,s=0,l=null,p=0,c=r.nextNode();for(;c;){let f=(c.textContent||"").length,u=a+f;if(o===null&&u>e&&(o=c,s=e-a),u>=n){l=c,p=n-a;break}a=u,c=r.nextNode()}if(!o||!l)return null;let m=document.createRange();return m.setStart(o,Math.min(s,(o.textContent||"").length)),m.setEnd(l,Math.min(p,(l.textContent||"").length)),m}createHighlight(t){let e=this.container.querySelector(`[data-block-id="${t.blockId}"]`);if(!e){console.warn(`[HighlightManager] Block not found for annotation ${t.id}: ${t.blockId}`);return}let n=this.findTextNodeRange(e,t.startOffset,t.endOffset);if(!n){console.warn(`[HighlightManager] Could not resolve text range for annotation ${t.id}`);return}let r=document.createElement("mark");r.className=`hl-${t.type}`,r.dataset.annotationId=t.id,r.addEventListener("click",()=>{this.store.select(t.id)});try{n.surroundContents(r)}catch{try{if(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.splitText(n.endOffset),n.startContainer.nodeType===Node.TEXT_NODE){let a=n.startContainer;n.startOffset>0&&a.splitText(n.startOffset);let o=document.createRange();o.setStart(a.nextSibling||a,0),o.setEnd(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.previousSibling||n.endContainer,n.endOffset),o.surroundContents(r)}else throw new Error("Non-text range")}catch{let a=n.extractContents();r.append(a),n.insertNode(r)}}}removeHighlight(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);if(!e)return;let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}updateSelection(t){let e=this.container.querySelectorAll("mark[data-annotation-id]");for(let n of e)n.classList.toggle("hl-selected",n.dataset.annotationId===t)}scrollToAnnotation(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.classList.add("annotation-pulse"),setTimeout(()=>{e.classList.remove("annotation-pulse")},600))}clearAll(){let t=this.container.querySelectorAll("mark[data-annotation-id]");for(let e of t){let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}}};var I=new Set(["button","input","textarea","select"]),E=class{constructor(t){d(this,"options");d(this,"boundHandleMouseUp");this.options=t,this.boundHandleMouseUp=this.handleMouseUp.bind(this),this.options.container.addEventListener("mouseup",this.boundHandleMouseUp,{passive:!0})}destroy(){this.options.container.removeEventListener("mouseup",this.boundHandleMouseUp)}handleMouseUp(t){if(this.options.mode()==="selection")return;let e=t.target;if(!e||this.isExcludedElement(e))return;let n=this.getSelectionRange();if(!n)return;let r=this.findBlockId(n.startContainer);if(!r)return;let a=this.findBlockContainer(n.startContainer),o=this.findBlockContainer(n.endContainer);if(a!==o)return;let s=this.computeBlockOffset(n.startContainer,n.startOffset),l=this.computeBlockOffset(n.endContainer,n.endOffset);if(s===null||l===null)return;let p={blockId:r,startOffset:s,endOffset:l,text:n.toString(),range:n};this.options.onSelection(p),this.clearSelection()}getSelectionRange(){let t=window.getSelection();return!t||t.isCollapsed||t.rangeCount===0?null:t.getRangeAt(0)}findBlockId(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e.getAttribute("data-block-id");e=e.parentNode}return null}computeBlockOffset(t,e){let n=this.findBlockContainer(t);if(!n)return null;let r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),a=0,o=r.nextNode();for(;o;){if(o===t)return a+e;a+=(o.textContent||"").length,o=r.nextNode()}return null}findBlockContainer(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e;e=e.parentNode}return null}clearSelection(){let t=window.getSelection();t&&t.removeAllRanges()}isExcludedElement(t){let e=t;for(;e&&!(e instanceof HTMLElement);)e=e.parentNode;return e?I.has(e.tagName.toLowerCase()):!1}};var D="aikit-annotation-sidebar",R=`
154
+ `,document.head.appendChild(l)}var y=class{constructor(t,e){d(this,"container");d(this,"store");d(this,"unsubscribe",null);this.container=t,this.store=e}start(){B(),this.unsubscribe=this.store.subscribe(t=>{switch(t.type){case"annotation-added":this.createHighlight(t.annotation);break;case"annotation-removed":this.removeHighlight(t.id);break;case"selection-changed":this.updateSelection(t.id),t.id!==null&&this.scrollToAnnotation(t.id);break}})}stop(){this.unsubscribe?.(),this.unsubscribe=null,this.clearAll()}findTextNodeRange(t,e,n){let a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null),r=0,o=null,i=0,s=null,p=0,c=a.nextNode();for(;c;){let f=(c.textContent||"").length,u=r+f;if(o===null&&u>e&&(o=c,i=e-r),u>=n){s=c,p=n-r;break}r=u,c=a.nextNode()}if(!o||!s)return null;let m=document.createRange();return m.setStart(o,Math.min(i,(o.textContent||"").length)),m.setEnd(s,Math.min(p,(s.textContent||"").length)),m}createHighlight(t){let e=this.container.querySelector(`[data-block-id="${t.blockId}"]`);if(!e){console.warn(`[HighlightManager] Block not found for annotation ${t.id}: ${t.blockId}`);return}let n=this.findTextNodeRange(e,t.startOffset,t.endOffset);if(!n){console.warn(`[HighlightManager] Could not resolve text range for annotation ${t.id}`);return}let a=document.createElement("mark");a.className=`hl-${t.type}`,a.dataset.annotationId=t.id,a.addEventListener("click",()=>{this.store.select(t.id)});try{n.surroundContents(a)}catch{try{if(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.splitText(n.endOffset),n.startContainer.nodeType===Node.TEXT_NODE){let r=n.startContainer;n.startOffset>0&&r.splitText(n.startOffset);let o=document.createRange();o.setStart(r.nextSibling||r,0),o.setEnd(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.previousSibling||n.endContainer,n.endOffset),o.surroundContents(a)}else throw new Error("Non-text range")}catch{let r=n.extractContents();a.append(r),n.insertNode(a)}}}removeHighlight(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);if(!e)return;let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}updateSelection(t){let e=this.container.querySelectorAll("mark[data-annotation-id]");for(let n of e)n.classList.toggle("hl-selected",n.dataset.annotationId===t)}scrollToAnnotation(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.classList.add("annotation-pulse"),setTimeout(()=>{e.classList.remove("annotation-pulse")},600))}clearAll(){let t=this.container.querySelectorAll("mark[data-annotation-id]");for(let e of t){let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}}};var I=new Set(["button","input","textarea","select"]),E=class{constructor(t){d(this,"options");d(this,"boundHandleMouseUp");this.options=t,this.boundHandleMouseUp=this.handleMouseUp.bind(this),this.options.container.addEventListener("mouseup",this.boundHandleMouseUp,{passive:!0})}destroy(){this.options.container.removeEventListener("mouseup",this.boundHandleMouseUp)}handleMouseUp(t){if(this.options.mode()==="selection")return;let e=t.target;if(!e||this.isExcludedElement(e))return;let n=this.getSelectionRange();if(!n)return;let a=this.findBlockId(n.startContainer);if(!a)return;let r=this.findBlockContainer(n.startContainer),o=this.findBlockContainer(n.endContainer);if(r!==o)return;let i=this.computeBlockOffset(n.startContainer,n.startOffset),s=this.computeBlockOffset(n.endContainer,n.endOffset);if(i===null||s===null)return;let p={blockId:a,startOffset:i,endOffset:s,text:n.toString(),range:n};this.options.onSelection(p),this.clearSelection()}getSelectionRange(){let t=window.getSelection();return!t||t.isCollapsed||t.rangeCount===0?null:t.getRangeAt(0)}findBlockId(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e.getAttribute("data-block-id");e=e.parentNode}return null}computeBlockOffset(t,e){let n=this.findBlockContainer(t);if(!n)return null;let a=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),r=0,o=a.nextNode();for(;o;){if(o===t)return r+e;r+=(o.textContent||"").length,o=a.nextNode()}return null}findBlockContainer(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e;e=e.parentNode}return null}clearSelection(){let t=window.getSelection();t&&t.removeAllRanges()}isExcludedElement(t){let e=t;for(;e&&!(e instanceof HTMLElement);)e=e.parentNode;return e?I.has(e.tagName.toLowerCase()):!1}};var D="aikit-annotation-sidebar",R=`
155
155
  .as-sidebar {
156
156
  width: var(--dt-annotation-sidebar-width, 300px);
157
157
  background: var(--dt-bg-secondary);
@@ -333,7 +333,7 @@ ${n}
333
333
  font-size: var(--dt-font-size-sm);
334
334
  padding: var(--dt-space-6) var(--dt-space-2);
335
335
  }
336
- `,z='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"/></svg>',k=class{constructor(t){d(this,"el");d(this,"store");d(this,"exporter");d(this,"unsubscribe",null);d(this,"listEl");d(this,"modeToggleBtn");this.store=t.store,this.exporter=t.exporter,this.el=this.render(),this.listEl=this.el.querySelector(".as-list"),this.modeToggleBtn=this.el.querySelector(".as-mode-toggle"),this.unsubscribe=this.store.subscribe(n=>{switch(n.type){case"annotation-added":case"annotation-removed":case"annotation-updated":this.renderList(),this.updateHeader();break;case"selection-changed":this.updateCardSelection(n.id);break;case"sidebar-toggled":this.updateVisibility();break;case"mode-changed":this.updateModeToggle();break}}),(t.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle()}destroy(){this.unsubscribe?.(),this.el.remove()}render(){v(D,R);let t=document.createElement("div");t.className="as-sidebar",t.setAttribute("role","complementary"),t.setAttribute("aria-label","Annotations");let e=this.exporter.getTotalCount();return t.innerHTML=`
336
+ `,z='<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z"/></svg>',k=class{constructor(t){d(this,"el");d(this,"store");d(this,"exporter");d(this,"unsubscribe",null);d(this,"listEl");d(this,"modeToggleBtn");this.store=t.store,this.exporter=t.exporter,this.el=this.render(),this.listEl=this.el.querySelector(".as-list"),this.modeToggleBtn=this.el.querySelector(".as-mode-toggle"),this.unsubscribe=this.store.subscribe(n=>{switch(n.type){case"annotation-added":case"annotation-removed":case"annotation-updated":this.renderList(),this.updateHeader();break;case"selection-changed":this.updateCardSelection(n.id);break;case"sidebar-toggled":this.updateVisibility();break;case"mode-changed":this.updateModeToggle();break}}),(t.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle()}destroy(){this.unsubscribe?.(),this.el.remove()}render(){b(D,R);let t=document.createElement("div");t.className="as-sidebar",t.setAttribute("role","complementary"),t.setAttribute("aria-label","Annotations");let e=this.exporter.getTotalCount();return t.innerHTML=`
337
337
  <div class="as-header">
338
338
  <span class="as-header-title">Annotations</span>
339
339
  <span class="as-count-badge" aria-live="polite">${e.total}</span>
@@ -342,12 +342,12 @@ ${n}
342
342
  <button class="as-close-btn" aria-label="Close sidebar">&times;</button>
343
343
  </div>
344
344
  <div class="as-list" role="list" aria-label="Annotation list"></div>
345
- `,t.querySelector(".as-close-btn").addEventListener("click",a=>{a.stopPropagation(),this.store.toggleSidebar(!1)}),t.querySelector(".as-mode-toggle").addEventListener("click",a=>{a.stopPropagation();let o=this.store.getState().mode==="feedback"?"selection":"feedback";this.store.setMode(o)}),t}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML="",e.length===0){let r=document.createElement("div");r.className="as-empty",r.textContent="No annotations yet. Select text in Feedback mode.",this.listEl.appendChild(r);return}let n=[...e].sort((r,a)=>a.createdAt-r.createdAt);for(let r of n)this.listEl.appendChild(this.renderAnnotationItem(r))}renderAnnotationItem(t){let e=document.createElement("div");e.className=`as-card as-card--${t.type}`,e.dataset.annotationId=t.id,this.store.getState().selectedId===t.id&&e.classList.add("as-card--selected");let r=t.originalText.length>60?`${t.originalText.slice(0,60)}\u2026`:t.originalText;return e.innerHTML=`
346
- <div class="as-card-excerpt">${g(r)}</div>
345
+ `,t.querySelector(".as-close-btn").addEventListener("click",r=>{r.stopPropagation(),this.store.toggleSidebar(!1)}),t.querySelector(".as-mode-toggle").addEventListener("click",r=>{r.stopPropagation();let o=this.store.getState().mode==="feedback"?"selection":"feedback";this.store.setMode(o)}),t}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML="",e.length===0){let a=document.createElement("div");a.className="as-empty",a.textContent="No annotations yet. Select text in Feedback mode.",this.listEl.appendChild(a);return}let n=[...e].sort((a,r)=>r.createdAt-a.createdAt);for(let a of n)this.listEl.appendChild(this.renderAnnotationItem(a))}renderAnnotationItem(t){let e=document.createElement("div");e.className=`as-card as-card--${t.type}`,e.dataset.annotationId=t.id,this.store.getState().selectedId===t.id&&e.classList.add("as-card--selected");let a=t.originalText.length>60?`${t.originalText.slice(0,60)}\u2026`:t.originalText;return e.innerHTML=`
346
+ <div class="as-card-excerpt">${g(a)}</div>
347
347
  ${t.comment?`<div class="as-card-comment">${g(t.comment)}</div>`:""}
348
348
  <div class="as-card-comment-detail">${t.comment?g(t.comment):'<em style="color:var(--dt-text-tertiary)">No comment \u2014 marked text only</em>'}</div>
349
349
  <button class="as-delete-btn" aria-label="Delete annotation">&times;</button>
350
- `,e.addEventListener("click",()=>{this.store.select(t.id);let o=e.querySelector(".as-card-comment-detail");if(o){o.classList.toggle("as-card-comment-detail--open");let s=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let l of s)l!==o&&l.classList.remove("as-card-comment-detail--open")}}),e.querySelector(".as-delete-btn").addEventListener("click",o=>{o.stopPropagation(),this.handleDelete(t.id)}),e}handleDelete(t){this.store.remove(t)}updateVisibility(){let t=this.store.getState();this.el.style.display=t.isSidebarOpen?"flex":"none"}updateHeader(){let t=this.el.querySelector(".as-count-badge");if(t){let e=this.exporter.getTotalCount();t.textContent=String(e.total)}}updateModeToggle(){let t=this.store.getState().mode==="feedback";this.modeToggleBtn.classList.toggle("as-mode-toggle--active",t),this.modeToggleBtn.setAttribute("aria-pressed",String(t)),this.modeToggleBtn.setAttribute("aria-label",t?"Disable annotation mode":"Enable annotation mode")}updateCardSelection(t){let e=this.el.querySelectorAll(".as-card");for(let n of e){let r=n.dataset.annotationId;n.classList.toggle("as-card--selected",r!==void 0&&r===t)}}};var T=class{constructor(){d(this,"annotations",[]);d(this,"selectedId",null);d(this,"mode","selection");d(this,"isSidebarOpen",!1);d(this,"subscribers",new Set);d(this,"idCounter",0)}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}notify(t){for(let e of this.subscribers)e(t)}generateId(){return this.idCounter+=1,`ann-${this.idCounter}`}openSidebar(){this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})}add(t,e,n,r,a,o,s,l,p){let c={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:r,originalText:a,comment:o,section:s,contextBefore:l,contextAfter:p,createdAt:Date.now()};return this.annotations.push(c),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:c}),c}update(t,e){let n=this.annotations.find(r=>r.id===t);n&&(Object.assign(n,e),this.notify({type:"annotation-updated",id:t,changes:e}))}remove(t){let e=this.annotations.findIndex(n=>n.id===t);e!==-1&&(this.annotations.splice(e,1),this.notify({type:"annotation-removed",id:t}))}select(t){this.selectedId=t,this.notify({type:"selection-changed",id:t})}setMode(t){t!==this.mode&&(this.mode=t,this.notify({type:"mode-changed",mode:t}))}toggleSidebar(t){this.isSidebarOpen=t!==void 0?t:!this.isSidebarOpen,this.notify({type:"sidebar-toggled",open:this.isSidebarOpen})}getState(){return{annotations:[...this.annotations],selectedId:this.selectedId,mode:this.mode,isSidebarOpen:this.isSidebarOpen}}destroy(){this.subscribers.clear(),this.annotations=[],this.selectedId=null,this.mode="selection",this.isSidebarOpen=!1,this.idCounter=0}};var L=25,$="aikit-annotation-guide",j=`
350
+ `,e.addEventListener("click",()=>{this.store.select(t.id);let o=e.querySelector(".as-card-comment-detail");if(o){o.classList.toggle("as-card-comment-detail--open");let i=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let s of i)s!==o&&s.classList.remove("as-card-comment-detail--open")}}),e.querySelector(".as-delete-btn").addEventListener("click",o=>{o.stopPropagation(),this.handleDelete(t.id)}),e}handleDelete(t){this.store.remove(t)}updateVisibility(){let t=this.store.getState();this.el.style.display=t.isSidebarOpen?"flex":"none"}updateHeader(){let t=this.el.querySelector(".as-count-badge");if(t){let e=this.exporter.getTotalCount();t.textContent=String(e.total)}}updateModeToggle(){let t=this.store.getState().mode==="feedback";this.modeToggleBtn.classList.toggle("as-mode-toggle--active",t),this.modeToggleBtn.setAttribute("aria-pressed",String(t)),this.modeToggleBtn.setAttribute("aria-label",t?"Disable annotation mode":"Enable annotation mode")}updateCardSelection(t){let e=this.el.querySelectorAll(".as-card");for(let n of e){let a=n.dataset.annotationId;n.classList.toggle("as-card--selected",a!==void 0&&a===t)}}};var T=class{constructor(){d(this,"annotations",[]);d(this,"selectedId",null);d(this,"mode","selection");d(this,"isSidebarOpen",!1);d(this,"subscribers",new Set);d(this,"idCounter",0)}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}notify(t){for(let e of this.subscribers)e(t)}generateId(){return this.idCounter+=1,`ann-${this.idCounter}`}openSidebar(){this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})}add(t,e,n,a,r,o,i,s,p){let c={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:a,originalText:r,comment:o,section:i,contextBefore:s,contextAfter:p,createdAt:Date.now()};return this.annotations.push(c),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:c}),c}update(t,e){let n=this.annotations.find(a=>a.id===t);n&&(Object.assign(n,e),this.notify({type:"annotation-updated",id:t,changes:e}))}remove(t){let e=this.annotations.findIndex(n=>n.id===t);e!==-1&&(this.annotations.splice(e,1),this.notify({type:"annotation-removed",id:t}))}select(t){this.selectedId=t,this.notify({type:"selection-changed",id:t})}setMode(t){t!==this.mode&&(this.mode=t,this.notify({type:"mode-changed",mode:t}))}toggleSidebar(t){this.isSidebarOpen=t!==void 0?t:!this.isSidebarOpen,this.notify({type:"sidebar-toggled",open:this.isSidebarOpen})}getState(){return{annotations:[...this.annotations],selectedId:this.selectedId,mode:this.mode,isSidebarOpen:this.isSidebarOpen}}destroy(){this.subscribers.clear(),this.annotations=[],this.selectedId=null,this.mode="selection",this.isSidebarOpen=!1,this.idCounter=0}};var L=25,$="aikit-annotation-guide",q=`
351
351
  .as-guide {
352
352
  margin: 0 0 var(--dt-space-3) 0;
353
353
  padding: var(--dt-space-2) var(--dt-space-3);
@@ -364,4 +364,53 @@ ${n}
364
364
  .as-guide--visible {
365
365
  display: block;
366
366
  }
367
- `;function q(i){let{range:t}=i,e,n=t.startContainer;for(;n;){if(n instanceof HTMLElement&&n.tagName.toLowerCase().match(/^h[1-6]$/)){e=n.textContent?.trim()||void 0;break}n=n.parentNode}let r,a;try{if(t.startContainer.nodeType===Node.TEXT_NODE&&t.startOffset>0){let o=t.startContainer.textContent||"",s=Math.max(0,t.startOffset-L);r=o.slice(s,t.startOffset)}if(t.endContainer.nodeType===Node.TEXT_NODE&&t.endOffset<(t.endContainer.textContent?.length||0)){let o=t.endContainer.textContent||"",s=Math.min(o.length,t.endOffset+L);a=o.slice(t.endOffset,s)}}catch{}return{section:e,contextBefore:r,contextAfter:a}}function w(i){let{container:t,mountTarget:e}=i,n=null,r=new T;r.setMode("feedback");let a=new x(r);v($,j);let o=document.createElement("div");o.className="as-guide",o.textContent="\u27B3 Ready. Select text to annotate or disable Feedback in the sidebar.",t.prepend(o);let s=()=>{let m=r.getState();o.classList.toggle("as-guide--visible",m.mode==="feedback"&&m.annotations.length===0)};s(),r.subscribe(()=>s());let l=new y(t,r);l.start();let p=new E({container:t,mode:()=>r.getState().mode,onSelection:m=>{let f=q(m);n?.destroy();let u=new b(m,{onSubmit:(h,S)=>{r.add("COMMENT",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),u.destroy(),n===u&&(n=null)},onRemove:(h,S)=>{r.add("DELETION",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),u.destroy(),n===u&&(n=null)},onDismiss:()=>{u.destroy(),n===u&&(n=null)}});n=u}}),c=new k({store:r,exporter:a,mountTarget:e});return r.openSidebar(),{destroy(){n?.destroy(),n=null,o.remove(),p.destroy(),l.stop(),c.destroy(),r.destroy()},getStore(){return r},getExporter(){return a}}}document.addEventListener("DOMContentLoaded",()=>{let i=document.querySelector(".main-content")||document.querySelector("main")||document.querySelector(".content");if(!i)return;let t=i.parentElement;t?.classList.contains("main-layout")||(t=document.createElement("div"),t.className="main-layout",i.parentNode?.insertBefore(t,i),t.appendChild(i));let e=i.parentElement;e&&!e.classList.contains("content-column")&&(e=document.createElement("div"),e.className="content-column",i.parentNode?.insertBefore(e,i),e.appendChild(i),t.appendChild(e));let n=w({container:i,mountTarget:t});window.__annotationLayer=n});})();
367
+ `;function _(l){let{range:t}=l,e,n=t.startContainer;for(;n;){if(n instanceof HTMLElement&&n.tagName.toLowerCase().match(/^h[1-6]$/)){e=n.textContent?.trim()||void 0;break}n=n.parentNode}let a,r;try{if(t.startContainer.nodeType===Node.TEXT_NODE&&t.startOffset>0){let o=t.startContainer.textContent||"",i=Math.max(0,t.startOffset-L);a=o.slice(i,t.startOffset)}if(t.endContainer.nodeType===Node.TEXT_NODE&&t.endOffset<(t.endContainer.textContent?.length||0)){let o=t.endContainer.textContent||"",i=Math.min(o.length,t.endOffset+L);r=o.slice(t.endOffset,i)}}catch{}return{section:e,contextBefore:a,contextAfter:r}}function w(l){let{container:t,mountTarget:e}=l,n=null,a=new T;a.setMode("feedback");let r=new x(a);b($,q);let o=document.createElement("div");o.className="as-guide",o.textContent="\u27B3 Ready. Select text to annotate or disable Feedback in the sidebar.",t.prepend(o);let i=()=>{let m=a.getState();o.classList.toggle("as-guide--visible",m.mode==="feedback"&&m.annotations.length===0)};i(),a.subscribe(()=>i());let s=new y(t,a);s.start();let p=new E({container:t,mode:()=>a.getState().mode,onSelection:m=>{let f=_(m);n?.destroy();let u=new v(m,{onSubmit:(h,S)=>{a.add("COMMENT",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),u.destroy(),n===u&&(n=null)},onRemove:(h,S)=>{a.add("DELETION",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),u.destroy(),n===u&&(n=null)},onDismiss:()=>{u.destroy(),n===u&&(n=null)}});n=u}}),c=new k({store:a,exporter:r,mountTarget:e});return a.openSidebar(),{destroy(){n?.destroy(),n=null,o.remove(),p.destroy(),s.stop(),c.destroy(),a.destroy()},getStore(){return a},getExporter(){return r}}}document.addEventListener("DOMContentLoaded",()=>{let l=document.querySelector(".content")||document.querySelector("main"),t=l||document.body;if(!l)return;let e=t.parentElement;e?.classList.contains("shell-layout")||(e=document.createElement("div"),e.className="shell-layout",t.parentNode?.insertBefore(e,t),e.appendChild(t));let n="aikit-shell-layout";if(!document.getElementById(n)){let o=document.createElement("style");o.id=n,o.textContent=`
368
+ .shell-layout {
369
+ flex: 1;
370
+ display: flex;
371
+ flex-direction: row;
372
+ width: 100%;
373
+ min-height: 0;
374
+ }
375
+ .shell-layout > main,
376
+ .shell-layout > .content {
377
+ flex: 1;
378
+ min-width: 0;
379
+ min-height: 0;
380
+ overflow-y: auto;
381
+ margin: 0;
382
+ }
383
+ /* When sidebar is docked, unconstrain main width so sidebar sits outside */
384
+ [data-annotation-sidebar="open"] .shell-layout > main,
385
+ [data-annotation-sidebar="open"] .shell-layout > .content {
386
+ max-width: none;
387
+ }
388
+ /* Sticky bottom action bar */
389
+ .action-bar {
390
+ position: sticky;
391
+ bottom: 0;
392
+ display: flex;
393
+ flex-wrap: wrap;
394
+ align-items: center;
395
+ gap: var(--dt-space-2);
396
+ padding: var(--dt-space-3) var(--dt-space-4);
397
+ border-top: 1px solid var(--dt-border-default);
398
+ background: color-mix(in srgb, var(--dt-bg-primary, #0c0c0c) 92%, transparent);
399
+ backdrop-filter: blur(12px);
400
+ -webkit-backdrop-filter: blur(12px);
401
+ flex-shrink: 0;
402
+ }
403
+ .action-bar:empty {
404
+ display: none;
405
+ }
406
+ .action-bar .bk-actions {
407
+ display: flex;
408
+ flex-wrap: wrap;
409
+ align-items: center;
410
+ gap: var(--dt-space-2);
411
+ margin: 0;
412
+ padding: 0;
413
+ border: none;
414
+ background: none;
415
+ }
416
+ `,document.head.appendChild(o)}let a=w({container:t,mountTarget:e});a.getStore().subscribe(o=>{o.type==="sidebar-toggled"&&document.documentElement.setAttribute("data-annotation-sidebar",o.open?"open":"")}),a.getStore().getState().isSidebarOpen&&document.documentElement.setAttribute("data-annotation-sidebar","open"),window.__annotationLayer=a;let r=document.querySelectorAll(".bk-actions");if(r.length>0){let o=document.createElement("div");o.className="action-bar";let i=!1;for(let s of r)if(!s.querySelector('input[type="text"], input:not([type]), textarea')){for(;s.firstChild;)o.appendChild(s.firstChild);s.remove(),i=!0}if(i){let s=document.querySelector("main")||document.querySelector(".content");s&&(s.appendChild(o),s.style.paddingBottom="0")}}});})();
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,serializeError as a}from"../../core/dist/index.js";import{readFileSync as o}from"node:fs";import{dirname as s,isAbsolute as c,join as l,resolve as u}from"node:path";import{createHash as d}from"node:crypto";import{GIT_REF_SLUG_PATTERN as f,gitAvailable as p,gitCommitToRef as m,gitExec as h,slugForRef as g}from"../../tools/dist/index.js";import{mkdir as _,readFile as v,readdir as y,stat as b,unlink as x,writeFile as S}from"node:fs/promises";function C(){try{let t=u(s(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(o(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function w(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function T(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}const E=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function D({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?E.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function O({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 k(t){return t.startsWith(`file://`)?e(t):t}function A(e){let t=u(e);return process.platform===`win32`?t.toLowerCase():t}function j(e){let t=new Map;for(let n of e){let e=k(n.uri);t.set(A(e),e)}return[...t.values()].sort((e,t)=>A(e).localeCompare(A(t)))}function M({config:e,roots:t}){let n=j(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=A(r),t=n.find(t=>A(t)===e);if(t)return t}return n[0]}function N({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=j(r);if(i.length===0)return!1;let a=M({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&A(o)===A(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function P({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:o,server:s,startInit:c,timeoutMs:l=5e3,getCwd:u=()=>process.cwd(),version:d=`0.0.0`}){let f=!1,p=!1,m,h=s.server,g=e=>{let t=a(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`)||n.includes(`timed out`)},_=()=>{f||(f=!0,c())},v=()=>{p||t!==`auto`||(p=!0,(async()=>{try{await o()}catch(e){n.error(`Initial index failed`,{version:d,...a(e)})}})())},y=t=>t.length===0||(m&&=(clearTimeout(m),void 0),!N({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(_(),v(),!0);try{if(y((await h.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(g(t)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:d,cwd:u(),...a(t)}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:u()}]})&&(_(),v());return}n.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:d,cwd:u(),...a(t)})}h.setNotificationHandler(r,async()=>{try{y((await h.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,{version:d,...a(e)})}}),m=setTimeout(()=>{let t=u();n.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(_(),v())},l)}var F=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await _(this.baseDir,{recursive:!0})}async read(e){let t=l(this.baseDir,e);try{return await v(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=l(this.baseDir,e);await _(s(r),{recursive:!0}),await S(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=l(this.baseDir,e);try{return await x(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=l(this.baseDir,e),r;try{r=await y(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=l(this.baseDir,r);try{let e=await b(i);t.push({path:r,size:e.size,mtimeMs:e.mtimeMs})}catch{}}}return t}async exists(e){let t=l(this.baseDir,e);try{return await b(t),!0}catch{return!1}}async listDirectories(){try{return(await y(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const I=50*1024,L=`refs/aikit/knowledge`,R=i(`server`);var z=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new F(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{R.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...a(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!p(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=h([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
2
+ import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as n}from"node:util";import{HealthBus as r,createLogger as i,serializeError as a}from"../../core/dist/index.js";import{readFileSync as o}from"node:fs";import{dirname as s,isAbsolute as c,join as l,resolve as u}from"node:path";import{createHash as d}from"node:crypto";import{GIT_REF_SLUG_PATTERN as f,gitAvailable as p,gitCommitToRef as m,gitExec as h,slugForRef as g}from"../../tools/dist/index.js";import{mkdir as _,readFile as v,readdir as y,stat as b,unlink as x,writeFile as S}from"node:fs/promises";function C(){try{let t=u(s(e(import.meta.url)),`..`,`..`,`..`,`package.json`);return JSON.parse(o(t,`utf-8`)).version??`0.0.0`}catch{return`0.0.0`}}function w(e){let t=e.headers[`mcp-session-id`];return Array.isArray(t)?t[0]:t}function T(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}const E=/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i;function D({requestOrigin:e,configuredOrigin:t,allowAnyOrigin:n,fallbackOrigin:r}){let i=t??r;return i===`*`?n?{allowOrigin:`*`,warn:!1}:e?E.test(e)?{allowOrigin:e,warn:!1}:{allowOrigin:null,warn:!0}:{allowOrigin:r,warn:!1}:{allowOrigin:i,warn:!1}}function O({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 k(t){return t.startsWith(`file://`)?e(t):t}function A(e){let t=u(e);return process.platform===`win32`?t.toLowerCase():t}function j(e){let t=new Map;for(let n of e){let e=k(n.uri);t.set(A(e),e)}return[...t.values()].sort((e,t)=>A(e).localeCompare(A(t)))}function M({config:e,roots:t}){let n=j(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=A(r),t=n.find(t=>A(t)===e);if(t)return t}return n[0]}function N({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let i=j(r);if(i.length===0)return!1;let a=M({config:e,roots:i.map(e=>({uri:e}))});if(!a)return!1;let o=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:a,rootCount:i.length,selectedBy:o&&A(o)===A(a)?`configured-source`:`stable-sorted-root`}),n(e,a),e.allRoots=i,!0}async function P({config:e,indexMode:t,log:n,rootsChangedNotificationSchema:r,reconfigureForWorkspace:i,runInitialIndex:o,server:s,startInit:c,timeoutMs:l=5e3,getCwd:u=()=>process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),version:d=`0.0.0`}){let f=!1,p=!1,m,h=s.server,g=e=>{let t=a(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`)||n.includes(`timed out`)},_=()=>{f||(f=!0,c())},v=()=>{p||t!==`auto`||(p=!0,(async()=>{try{await o()}catch(e){n.error(`Initial index failed`,{version:d,...a(e)})}})())},y=t=>t.length===0||(m&&=(clearTimeout(m),void 0),!N({config:e,log:n,reconfigureForWorkspace:i,roots:t}))?!1:(_(),v(),!0);try{if(y((await h.listRoots()).roots))return;n.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(t){if(g(t)){n.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:d,cwd:u(),...a(t)}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:u()}]})&&(_(),v());return}n.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:d,cwd:u(),...a(t)})}h.setNotificationHandler(r,async()=>{try{y((await h.listRoots()).roots)}catch(e){n.warn(`roots/list retry failed after notification`,{version:d,...a(e)})}}),m=setTimeout(()=>{let t=u();n.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),N({config:e,log:n,reconfigureForWorkspace:i,roots:[{uri:t}]})&&(_(),v())},l)}var F=class{baseDir;constructor(e){this.baseDir=e}async initialize(){await _(this.baseDir,{recursive:!0})}async read(e){let t=l(this.baseDir,e);try{return await v(t,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async write(e,t,n){let r=l(this.baseDir,e);await _(s(r),{recursive:!0}),await S(r,t,{encoding:`utf-8`,flag:n?.exclusive?`wx`:`w`})}async delete(e){let t=l(this.baseDir,e);try{return await x(t),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}}async list(e){let t=[],n=e?[e]:await this.listDirectories();for(let e of n){let n=l(this.baseDir,e),r;try{r=await y(n)}catch{continue}for(let n of r){if(!n.endsWith(`.md`))continue;let r=`${e}/${n}`,i=l(this.baseDir,r);try{let e=await b(i);t.push({path:r,size:e.size,mtimeMs:e.mtimeMs})}catch{}}}return t}async exists(e){let t=l(this.baseDir,e);try{return await b(t),!0}catch{return!1}}async listDirectories(){try{return(await y(this.baseDir,{withFileTypes:!0})).filter(e=>e.isDirectory()&&/^[a-z][a-z0-9-]*$/.test(e.name)).map(e=>e.name)}catch{return[]}}async close(){}};const I=50*1024,L=`refs/aikit/knowledge`,R=i(`server`);var z=class{curatedDir;store;embedder;adapter;constructor(e,t,n,r=new F(e)){this.curatedDir=e,this.store=t,this.embedder=n,this.adapter=r}async remember(e,t,n,r=[]){this.validateCategoryName(n),this.validateContentSize(t);let i=this.normalizeTags(r),a=this.slugify(e),o=await this.uniqueRelativePath(n,a),s=new Date().toISOString(),c={title:e,category:n,tags:i,created:s,updated:s,version:1,origin:`curated`,changelog:[{version:1,date:s,reason:`Initial creation`}]},l=this.serializeFile(t,c);try{await this.adapter.write(o,l,{exclusive:!0})}catch(e){throw e.code===`EEXIST`?Error(`Concurrent write collision for "${o}" — retry the operation`):e}return this.gitCommitKnowledge(o,l,`remember: ${e}\n\nCategory: ${n}\nTags: ${i.join(`, `)}`),await this.indexCuratedFileBestEffort(o,t,c,`remember`),{path:o}}async upsertAutoKnowledge(e,t,n,r,i=[],a=`Auto-knowledge refresh`){e=this.guardPath(e),this.validateCategoryName(r),this.validateContentSize(n),this.ensureCategoryPath(e,r);let o=this.normalizeTags(i),s=await this.adapter.read(e);if(s==null){let i=new Date().toISOString(),a={title:t,category:r,tags:o,created:i,updated:i,version:1,origin:`curated`,changelog:[{version:1,date:i,reason:`Initial creation`}]},s=this.serializeFile(n,a);try{await this.adapter.write(e,s,{exclusive:!0})}catch(t){throw t.code===`EEXIST`?Error(`Concurrent write collision for "${e}" — retry the operation`):t}return this.gitCommitKnowledge(e,s,`remember: ${t}\n\nCategory: ${r}\nTags: ${o.join(`, `)}`),await this.indexCuratedFileBestEffort(e,n,a,`remember`),{path:e,status:`created`,version:1}}let{frontmatter:c,content:l}=this.parseFile(s),u=this.normalizeTags(c.tags??[]),d=t.trim()||c.title;if(l===n&&c.category===r&&c.title===d&&this.sameTags(u,o))return{path:e,status:`unchanged`,version:c.version??1};let f=(c.version??1)+1,p=new Date().toISOString();c.title=d,c.category=r,c.tags=o,c.version=f,c.updated=p,c.changelog=[...c.changelog??[],{version:f,date:p,reason:a}];let m=this.serializeFile(n,c);return await this.adapter.write(e,m),this.gitCommitKnowledge(e,m,`update(v${f}): ${c.title}\n\nReason: ${a}\nVersion: ${f}`),await this.indexCuratedFileBestEffort(e,n,c,`update`),{path:e,status:`updated`,version:f}}async update(e,t,n){e=this.guardPath(e),this.validateContentSize(t);let r=await this.adapter.read(e);if(r==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:i}=this.parseFile(r),a=(i.version??1)+1,o=new Date().toISOString();i.version=a,i.updated=o,i.changelog=[...i.changelog??[],{version:a,date:o,reason:n}];let s=this.serializeFile(t,i);return await this.adapter.write(e,s),this.gitCommitKnowledge(e,s,`update(v${a}): ${i.title}\n\nReason: ${n}\nVersion: ${a}`),await this.indexCuratedFileBestEffort(e,t,i,`update`),{path:e,version:a}}async forget(e,t){if(e=this.guardPath(e),!await this.adapter.delete(e))throw Error(`Curated entry not found: ${e}`);let n=`.ai/curated/${e}`;return await this.store.deleteBySourcePath(n).catch(e=>{R.warn(`File deleted but vector cleanup failed`,{sourcePath:n,...a(e)})}),this.gitDeleteKnowledgeRef(e),{path:e}}async history(e,t=20){if(e=this.guardPath(e),!p(this.curatedDir))return[];let n=this.knowledgeRefForPath(e);if(!n)return[];let r=h([`log`,`--format=%H|%aI|%s`,n,`-n`,String(t)],this.curatedDir);return r?r.split(`
3
3
  `).filter(Boolean).map(e=>{let[t,n,...r]=e.split(`|`);return{sha:t,date:n,message:r.join(`|`)}}):[]}async diff(e,t,n){if(e=this.guardPath(e),!p(this.curatedDir))return``;if(!n){let r=await this.history(e,2);if(r.length===0)return``;n=r[0].sha,r.length>1&&!t&&(t=r[1].sha)}return t&&n?h([`diff`,`${t}:entry.md`,`${n}:entry.md`],this.curatedDir)??``:n?h([`show`,`${n}:entry.md`],this.curatedDir)??``:``}async recover(e){if(e=this.guardPath(e),await this.adapter.exists(e))throw Error(`Entry already exists on filesystem: ${e}. Use update() instead.`);if(!p(this.curatedDir))return null;let t=this.knowledgeRefForPath(e);if(!t)return null;let n=h([`show`,`${t}:entry.md`],this.curatedDir);if(!n)return null;await this.adapter.write(e,n);let{frontmatter:r,content:i}=this.parseFile(n);return await this.indexCuratedFile(e,i,r),{path:e,version:r.version??1}}async listOrphaned(){if(!p(this.curatedDir))return[];let e=h([`for-each-ref`,`--format=%(refname)|%(subject)`,`${L}/`],this.curatedDir);if(!e)return[];let t=[];for(let n of e.split(`
4
4
  `).filter(Boolean)){let[e,...r]=n.split(`|`),i=r.join(`|`),a=`${e.replace(`${L}/`,``)}.md`;await this.adapter.exists(a)||t.push({ref:e,path:a,lastMessage:i})}return t}async read(e){e=this.guardPath(e);let t=await this.adapter.read(e);if(t==null)throw Error(`Curated entry not found: ${e}`);let{frontmatter:n,content:r}=this.parseFile(t),i=e.split(`/`)[0];return{path:e,title:n.title??e,category:i,tags:n.tags??[],version:n.version??1,created:n.created??``,updated:n.updated??``,contentPreview:r.slice(0,200),content:r}}async list(e){return(await this.listPage(e)).entries}async listPage(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);for(let r of t)n.push({path:r.path,category:e,mtimeMs:r.mtimeMs??0})}let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit),a=(e?.order??`asc`)===`desc`?-1:1,o=e?.orderBy??`path`;if(o===`path`||o===`updated`){let t=this.sortCandidateMetadata(n,o,a);if(e?.tag){let n=i==null?void 0:r+i+1,{entries:a,scannedAll:o}=await this.readCandidateEntries(t,{tag:e.tag,maxMatches:n}),s=i==null?a.slice(r):a.slice(r,r+i),c=i!=null&&(a.length>r+s.length||!o);return{entries:s,totalCount:o?a.length:r+s.length+ +!!c,totalCountIsExact:o,limit:i,offset:r,hasMore:c}}let s=i==null?t.slice(r):t.slice(r,r+i),{entries:c}=await this.readCandidateEntries(s);return{entries:c,totalCount:t.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+c.length<t.length}}let{entries:s}=await this.readCandidateEntries(n,{tag:e?.tag}),c=s.sort((e,t)=>{switch(o){case`created`:return(Date.parse(e.created)-Date.parse(t.created))*a;case`updated`:return(Date.parse(e.updated)-Date.parse(t.updated))*a;case`path`:return e.path.localeCompare(t.path)*a;default:return 0}}),l=i==null?c.slice(r):c.slice(r,r+i);return{entries:l,totalCount:c.length,totalCountIsExact:!0,limit:i,offset:r,hasMore:i!=null&&r+l.length<c.length}}async count(e){if(e?.tag)return(await this.listPage({...e,limit:void 0})).totalCount;let t=e?.category?[e.category]:await this.discoverCategories(),n=0;for(let e of t)n+=(await this.adapter.list(e)).length;return n}async listPaths(e){let t=e?.category?[e.category]:await this.discoverCategories(),n=[];for(let e of t){let t=await this.adapter.list(e);n.push(...t.map(e=>e.path))}n.sort((e,t)=>e.localeCompare(t));let r=Math.max(0,e?.offset??0),i=e?.limit==null?null:Math.max(1,e.limit);return i==null?n.slice(r):n.slice(r,r+i)}sortCandidateMetadata(e,t,n){return[...e].sort((e,r)=>t===`updated`?(e.mtimeMs-r.mtimeMs)*n:e.path.localeCompare(r.path)*n)}async readCandidateEntries(e,t){let n=[];for(let r of e){let e=await this.adapter.read(r.path);if(e==null)continue;let{frontmatter:i,content:a}=this.parseFile(e),o=i.tags??[];if(!(t?.tag&&!o.includes(t.tag))&&(n.push({path:r.path,title:i.title??r.path,category:r.category,tags:o,version:i.version??1,created:i.created??``,updated:i.updated??``,contentPreview:a.slice(0,200)}),t?.maxMatches!=null&&n.length>=t.maxMatches))return{entries:n,scannedAll:!1}}return{entries:n,scannedAll:!0}}async reindexAll(){let e=await this.discoverCategories(),t=[],n=[];for(let r of e){let e=await this.adapter.list(r);for(let r of e){let e=r.path;try{let r=await this.adapter.read(e);if(r==null){t.push(`${e}: read failed`);continue}let{frontmatter:i,content:a}=this.parseFile(r);n.push({relativePath:e,content:a,frontmatter:i})}catch(n){R.error(`Failed to read curated file`,{relativePath:e,...a(n)}),t.push(`${e}: read failed`)}}}if(n.length===0)return{indexed:0,errors:t};let r=new Date().toISOString(),i=0;for(let e=0;e<n.length;e+=16){let a=n.slice(e,e+16);i+=await this.embedAndUpsertBatch(a,r,t)}return{indexed:i,errors:t}}async embedAndUpsertBatch(e,t,n){try{let r=await this.embedder.embedBatch(e.map(e=>e.content)),i=e.map(e=>{let n=`.ai/curated/${e.relativePath}`;return{id:this.hashId(n,0),content:e.content,sourcePath:n,contentType:`curated-knowledge`,headingPath:e.frontmatter.title,chunkIndex:0,totalChunks:1,startLine:1,endLine:e.content.split(`
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){R.error(`Failed to upsert curated batch`,{batchSize:e.length,...a(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return R.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...a(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;R.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...a(r)});let i=Math.ceil(e.length/2),o=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(o,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!p(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;m(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!p(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;h([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>g(e)).join(`/`);return t.split(`/`).every(e=>f.test(e))?`${L}/${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(`
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,t as i}from"./server-utils-De-aZNQa.js";import{n as a,r as o,t as s}from"./workspace-bootstrap-BPWA6BVf.js";import{t as c}from"./curated-manager-BrgM_znO.js";import{pathToFileURL as l}from"node:url";import{parseArgs as u}from"node:util";import{createLogger as d,serializeError as f}from"../../core/dist/index.js";const p=d(`server`);function m(e,t){return t?{version:e,...f(t)}:{version:e}}function h(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function g(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function _(){return g()?u({allowPositionals:!0,options:{transport:{type:`string`,default:h()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:h(),port:process.env.AIKIT_PORT??`3210`}}async function v(){let e=t(),n=_();if(process.on(`unhandledRejection`,t=>{p.error(`Unhandled rejection`,m(e,t))}),process.on(`uncaughtException`,t=>{p.error(`Uncaught exception — exiting`,m(e,t)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let{startHttpMode:t}=await import(`./server-http-DVx48qhg.js`);await t(e,n.port)}else{let{startStdioMode:t}=await import(`./server-stdio-D_r13voI.js`);await t(e)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,n as getSessionIdHeader,v as main,r as readPositiveIntEnv,t as readVersion,e as resolveCorsOrigin,o as selectWorkspaceRoot};
1
+ import{a as e,i as t,n,r,t as i}from"./server-utils-De-aZNQa.js";import{n as a,r as o,t as s}from"./workspace-bootstrap-DupGrGox.js";import{t as c}from"./curated-manager-BrgM_znO.js";import{pathToFileURL as l}from"node:url";import{parseArgs as u}from"node:util";import{createLogger as d,serializeError as f}from"../../core/dist/index.js";const p=d(`server`);function m(e,t){return t?{version:e,...f(t)}:{version:e}}function h(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function g(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function _(){return g()?u({allowPositionals:!0,options:{transport:{type:`string`,default:h()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:h(),port:process.env.AIKIT_PORT??`3210`}}async function v(){let e=t(),n=_();if(process.on(`unhandledRejection`,t=>{p.error(`Unhandled rejection`,m(e,t))}),process.on(`uncaughtException`,t=>{p.error(`Uncaught exception — exiting`,m(e,t)),process.exit(1)}),p.info(`Starting MCP AI Kit server`,{version:e}),n.transport===`http`){let{startHttpMode:t}=await import(`./server-http-DVx48qhg.js`);await t(e,n.port)}else{let{startStdioMode:t}=await import(`./server-stdio-C9ybt-xS.js`);await t(e)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,n as getSessionIdHeader,v as main,r as readPositiveIntEnv,t as readVersion,e as resolveCorsOrigin,o as selectWorkspaceRoot};
@@ -1 +1 @@
1
- import{n as e}from"./workspace-bootstrap-BPWA6BVf.js";import{n as t,t as n}from"./startup-maintenance-D0Uhpi3k.js";import{t as r}from"./repair-json-B6Q_HRoP.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return s.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-B-wvmMyo.js`),import(`./server-PfiU5e1x.js`),import(`./version-check-CggUKvv8.js`),import(`@modelcontextprotocol/sdk/types.js`)]),h=i();o(h.logging?.errorDetails===!0),h.configError&&s.warn(`Config load failure`,{error:h.configError}),s.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path}),p(),setInterval(f,1440*60*1e3).unref();let g=u(h),_=d(h,g),{server:v,startInit:y,ready:b,runInitialIndex:x}=_,{StdioServerTransport:S}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),C=new S;if(typeof C._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);C._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await v.connect(C),s.debug(`MCP server started`,{transport:`stdio`}),await e({config:h,indexMode:g,log:s,rootsChangedNotificationSchema:m,reconfigureForWorkspace:l,runInitialIndex:x,server:v,startInit:y,version:r});let w=null,T=null,E=!1,D=async e=>{E||(E=!0,s.info(`Shutdown signal received`,{signal:e}),w&&=(clearTimeout(w),null),T?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await C.close().catch(()=>void 0),await v.close().catch(()=>void 0),_.aikit&&await Promise.all([_.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),_.aikit.graphStore.close().catch(()=>{}),_.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),_.aikit.store.close().catch(()=>{})]),process.exit(0))},O=()=>{w&&clearTimeout(w),w=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=_.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),w.unref&&w.unref()};O(),process.stdin.on(`data`,()=>O()),process.stdin.on(`end`,()=>void D(`stdin-end`)),process.stdin.on(`close`,()=>void D(`stdin-close`)),process.stdin.on(`error`,()=>void D(`stdin-error`)),process.on(`SIGINT`,()=>void D(`SIGINT`)),process.on(`SIGTERM`,()=>void D(`SIGTERM`)),b.catch(e=>{s.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),g===`smart`?b.then(async()=>{try{if(!_.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(_.aikit.indexer,h,_.aikit.store);T=t;let n=_.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),_.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:g}),n(b,()=>_.aikit?{curated:_.aikit.curated,stateStore:_.aikit.stateStore}:null,r)}export{l as startStdioMode};
1
+ import{n as e}from"./workspace-bootstrap-DupGrGox.js";import{n as t,t as n}from"./startup-maintenance-D0Uhpi3k.js";import{t as r}from"./repair-json-B6Q_HRoP.js";import{createLogger as i,serializeError as a,setDetailedErrorLoggingEnabled as o}from"../../core/dist/index.js";const s=i(`server`);var c=class{buffer;append(e){this.buffer=this.buffer?Buffer.concat([this.buffer,e]):e}readMessage(){if(!this.buffer)return null;for(let e=0;e<this.buffer.length;e++){if(this.buffer[e]!==10)continue;let t=this.buffer.toString(`utf8`,0,e).replace(/\r$/,``),n=e+1;try{let e=JSON.parse(t);return this.buffer=this.buffer.subarray(n),e}catch{try{let e=r(t);return s.warn(`JSON parse failed on MCP message — repair succeeded`,{preview:t.slice(0,80)}),this.buffer=this.buffer.subarray(n),e}catch{}}}return null}clear(){this.buffer=void 0}};async function l(r){let[{loadConfig:i,reconfigureForWorkspace:l,resolveIndexMode:u},{createLazyServer:d},{checkForUpdates:f,autoUpgradeScaffold:p},{RootsListChangedNotificationSchema:m}]=await Promise.all([import(`./config-B-wvmMyo.js`),import(`./server-PfiU5e1x.js`),import(`./version-check-CggUKvv8.js`),import(`@modelcontextprotocol/sdk/types.js`)]),h=i();o(h.logging?.errorDetails===!0),h.configError&&s.warn(`Config load failure`,{error:h.configError}),s.info(`Config loaded`,{sourceCount:h.sources.length,storePath:h.store.path}),p(),setInterval(f,1440*60*1e3).unref();let g=u(h),_=d(h,g),{server:v,startInit:y,ready:b,runInitialIndex:x}=_,{StdioServerTransport:S}=await import(`@modelcontextprotocol/sdk/server/stdio.js`),C=new S;if(typeof C._readBuffer?.readMessage!=`function`)throw Error(`Cannot install JSON repair: StdioServerTransport._readBuffer has unexpected shape`);C._readBuffer=new c,s.debug(`JSON repair installed on stdio transport`),await v.connect(C),s.debug(`MCP server started`,{transport:`stdio`}),await e({config:h,indexMode:g,log:s,rootsChangedNotificationSchema:m,reconfigureForWorkspace:l,runInitialIndex:x,server:v,startInit:y,version:r});let w=null,T=null,E=!1,D=async e=>{E||(E=!0,s.info(`Shutdown signal received`,{signal:e}),w&&=(clearTimeout(w),null),T?.stop(),await import(`../../tools/dist/index.js`).then(({processStopAll:e})=>e()).catch(()=>{}),await C.close().catch(()=>void 0),await v.close().catch(()=>void 0),_.aikit&&await Promise.all([_.aikit.embedder.shutdown?.().catch(()=>{})??Promise.resolve(),_.aikit.graphStore.close().catch(()=>{}),_.aikit.closeStateStore?.().catch(()=>{})??Promise.resolve(),_.aikit.store.close().catch(()=>{})]),process.exit(0))},O=()=>{w&&clearTimeout(w),w=setTimeout(async()=>{s.info(`Auto-shutdown: no activity for 30 minutes — releasing resources`);try{let e=_.aikit;e&&(e.embedder.shutdown?.().catch(()=>{}),e.store.releaseMemory?.(),e.graphStore.releaseMemory?.())}catch(e){s.warn(`Resource release failed during shutdown`,a(e))}},18e5),w.unref&&w.unref()};O(),process.stdin.on(`data`,()=>O()),process.stdin.on(`end`,()=>void D(`stdin-end`)),process.stdin.on(`close`,()=>void D(`stdin-close`)),process.stdin.on(`error`,()=>void D(`stdin-error`)),process.on(`SIGINT`,()=>void D(`SIGINT`)),process.on(`SIGTERM`,()=>void D(`SIGTERM`)),b.catch(e=>{s.error(`Initialization failed — server will continue with limited tools`,t(r,e))}),g===`smart`?b.then(async()=>{try{if(!_.aikit)throw Error(`AI Kit components are not available after initialization`);let{SmartIndexScheduler:e}=await import(`../../indexer/dist/index.js`),t=new e(_.aikit.indexer,h,_.aikit.store);T=t;let n=_.aikit.store;t.start(),n.onBeforeClose&&n.onBeforeClose(()=>t.stop()),_.setSmartScheduler(t),s.debug(`Smart index scheduler started (stdio mode)`)}catch(e){s.error(`Failed to start smart index scheduler`,t(r,e))}}).catch(e=>s.error(`AI Kit init failed for smart scheduler`,t(r,e))):s.warn(`Initial full indexing skipped; use aikit_reindex to index manually`,{indexMode:g}),n(b,()=>_.aikit?{curated:_.aikit.curated,stateStore:_.aikit.stateStore}:null,r)}export{l as startStdioMode};
@@ -0,0 +1 @@
1
+ import{fileURLToPath as e}from"node:url";import{serializeError as t}from"../../core/dist/index.js";import{resolve as n}from"node:path";function r(t){return t.startsWith(`file://`)?e(t):t}function i(e){let t=n(e);return process.platform===`win32`?t.toLowerCase():t}function a(e){let t=new Map;for(let n of e){let e=r(n.uri);t.set(i(e),e)}return[...t.values()].sort((e,t)=>i(e).localeCompare(i(t)))}function o({config:e,roots:t}){let n=a(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=i(r),t=n.find(t=>i(t)===e);if(t)return t}return n[0]}function s({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let s=a(r);if(s.length===0)return!1;let c=o({config:e,roots:s.map(e=>({uri:e}))});if(!c)return!1;let l=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:c,rootCount:s.length,selectedBy:l&&i(l)===i(c)?`configured-source`:`stable-sorted-root`}),n(e,c),e.allRoots=s,!0}async function c({config:e,indexMode:n,log:r,rootsChangedNotificationSchema:i,reconfigureForWorkspace:a,runInitialIndex:o,server:c,startInit:l,timeoutMs:u=5e3,getCwd:d=()=>process.env.AIKIT_WORKSPACE_ROOT??process.cwd(),version:f=`0.0.0`}){let p=!1,m=!1,h,g=c.server,_=e=>{let n=t(e),r=`${String(e)} ${String(n.message??``)}`.toLowerCase();return r.includes(`method not found`)||r.includes(`not supported`)||r.includes(`unsupported`)||r.includes(`unknown method`)||r.includes(`roots/list`)||r.includes(`timed out`)},v=()=>{p||(p=!0,l())},y=()=>{m||n!==`auto`||(m=!0,(async()=>{try{await o()}catch(e){r.error(`Initial index failed`,{version:f,...t(e)})}})())},b=t=>t.length===0||(h&&=(clearTimeout(h),void 0),!s({config:e,log:r,reconfigureForWorkspace:a,roots:t}))?!1:(v(),y(),!0);try{if(b((await g.listRoots()).roots))return;r.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(n){if(_(n)){r.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:f,cwd:d(),...t(n)}),s({config:e,log:r,reconfigureForWorkspace:a,roots:[{uri:d()}]})&&(v(),y());return}r.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:f,cwd:d(),...t(n)})}g.setNotificationHandler(i,async()=>{try{b((await g.listRoots()).roots)}catch(e){r.warn(`roots/list retry failed after notification`,{version:f,...t(e)})}}),h=setTimeout(()=>{let t=d();r.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),s({config:e,log:r,reconfigureForWorkspace:a,roots:[{uri:t}]})&&(v(),y())},u)}export{c as n,o as r,s as t};
@@ -1 +0,0 @@
1
- import{fileURLToPath as e}from"node:url";import{serializeError as t}from"../../core/dist/index.js";import{resolve as n}from"node:path";function r(t){return t.startsWith(`file://`)?e(t):t}function i(e){let t=n(e);return process.platform===`win32`?t.toLowerCase():t}function a(e){let t=new Map;for(let n of e){let e=r(n.uri);t.set(i(e),e)}return[...t.values()].sort((e,t)=>i(e).localeCompare(i(t)))}function o({config:e,roots:t}){let n=a(t);if(n.length===0)return null;let r=e.sources?.[0]?.path;if(r){let e=i(r),t=n.find(t=>i(t)===e);if(t)return t}return n[0]}function s({config:e,log:t,reconfigureForWorkspace:n,roots:r}){let s=a(r);if(s.length===0)return!1;let c=o({config:e,roots:s.map(e=>({uri:e}))});if(!c)return!1;let l=e.sources?.[0]?.path;return t.debug(`MCP roots resolved`,{rootPath:c,rootCount:s.length,selectedBy:l&&i(l)===i(c)?`configured-source`:`stable-sorted-root`}),n(e,c),e.allRoots=s,!0}async function c({config:e,indexMode:n,log:r,rootsChangedNotificationSchema:i,reconfigureForWorkspace:a,runInitialIndex:o,server:c,startInit:l,timeoutMs:u=5e3,getCwd:d=()=>process.cwd(),version:f=`0.0.0`}){let p=!1,m=!1,h,g=c.server,_=e=>{let n=t(e),r=`${String(e)} ${String(n.message??``)}`.toLowerCase();return r.includes(`method not found`)||r.includes(`not supported`)||r.includes(`unsupported`)||r.includes(`unknown method`)||r.includes(`roots/list`)||r.includes(`timed out`)},v=()=>{p||(p=!0,l())},y=()=>{m||n!==`auto`||(m=!0,(async()=>{try{await o()}catch(e){r.error(`Initial index failed`,{version:f,...t(e)})}})())},b=t=>t.length===0||(h&&=(clearTimeout(h),void 0),!s({config:e,log:r,reconfigureForWorkspace:a,roots:t}))?!1:(v(),y(),!0);try{if(b((await g.listRoots()).roots))return;r.debug(`No MCP roots yet; waiting for roots/list_changed notification`)}catch(n){if(_(n)){r.warn(`MCP roots/list not supported by client; using cwd fallback`,{version:f,cwd:d(),...t(n)}),s({config:e,log:r,reconfigureForWorkspace:a,roots:[{uri:d()}]})&&(v(),y());return}r.warn(`MCP roots/list failed; waiting for roots/list_changed notification`,{version:f,cwd:d(),...t(n)})}g.setNotificationHandler(i,async()=>{try{b((await g.listRoots()).roots)}catch(e){r.warn(`roots/list retry failed after notification`,{version:f,...t(e)})}}),h=setTimeout(()=>{let t=d();r.debug(`Timed out waiting for roots/list_changed; falling back to cwd workspace`,{cwd:t}),s({config:e,log:r,reconfigureForWorkspace:a,roots:[{uri:t}]})&&(v(),y())},u)}export{c as n,o as r,s as t};