@vpxa/aikit 0.1.360 → 0.1.362
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/README.md +442 -442
- package/package.json +3 -1
- package/packages/claude-desktop/dist/manifest.json +31 -0
- package/packages/claude-desktop/dist/mcp-source.json +16 -0
- package/packages/cli/dist/index.js +14 -14
- package/packages/cli/dist/init-JfM6gnAO.js +7 -0
- package/packages/cli/dist/mcp-entry.json +8 -0
- package/packages/cli/dist/{templates-DUUaYk_d.js → templates-CNDa9H4e.js} +25 -25
- package/packages/core/dist/index.d.ts +4 -2
- package/packages/core/dist/index.js +1 -1
- package/packages/flows/dist/index.d.ts +1 -1
- package/packages/flows/dist/index.js +1 -1
- package/packages/present/dist/annotation-layer.js +97 -14
- package/packages/present/dist/index.html +92 -9
- package/packages/server/dist/bin.js +1 -1
- package/packages/server/dist/config-B4klhHVp.js +2 -0
- package/packages/server/dist/config-D3rRPB9X.js +1 -0
- package/packages/server/dist/index.js +1 -1
- package/packages/server/dist/prelude-BgvW6Hp5.js +2 -0
- package/packages/server/dist/prelude-Di-ZDdDk.js +1 -0
- package/packages/server/dist/routes-Ct7q5jrL.js +6 -0
- package/packages/server/dist/routes-DsSm9ea0.js +5 -0
- package/packages/server/dist/sampling-CFWUnzbA.js +1 -0
- package/packages/server/dist/sampling-lcC_v6KY.js +2 -0
- package/packages/server/dist/server-Bsceh-AT.js +3070 -0
- package/packages/server/dist/server-DUWF6mtP.js +3071 -0
- package/packages/server/dist/{server-http-Dd2uCMBi.js → server-http-BGcKUn5y.js} +1 -1
- package/packages/server/dist/{server-http-BaMUtb5Y.js → server-http-Cx4tvbmK.js} +1 -1
- package/packages/server/dist/{server-stdio-B5rk-PAI.js → server-stdio-BmGuXkkF.js} +1 -1
- package/packages/server/dist/{server-stdio-CtR4QNT3.js → server-stdio-C66e05P_.js} +1 -1
- package/packages/server/viewers/architecture-static.html +794 -794
- package/packages/server/viewers/report-template.html +11 -11
- package/packages/server/viewers/tour-viewer.html +26 -26
- package/packages/settings-ui/dist/index.html +12 -12
- package/packages/tools/dist/index.d.ts +109 -14
- package/packages/tools/dist/index.js +118 -98
- package/scaffold/definitions/mcp-entry.json +1 -1
- package/scaffold/dist/adapters/claude-code.mjs +5 -5
- package/scaffold/dist/adapters/claude-desktop.mjs +6 -6
- package/scaffold/dist/adapters/copilot.mjs +1 -1
- package/scaffold/dist/adapters/gemini.mjs +2 -2
- package/scaffold/dist/adapters/hermes-agent.mjs +1 -1
- package/scaffold/dist/adapters/hermes.mjs +1 -1
- package/scaffold/dist/adapters/opencode.mjs +2 -2
- package/scaffold/dist/adapters/zed.mjs +1 -1
- package/scaffold/dist/definitions/flows.mjs +40 -162
- package/scaffold/dist/definitions/mcp-entry.json +1 -1
- package/scaffold/dist/definitions/platform-capabilities.mjs +1 -1
- package/scaffold/dist/definitions/protocols.mjs +22 -19
- package/scaffold/dist/definitions/skills/adr-skill.mjs +1 -1
- package/scaffold/dist/definitions/skills/docs.mjs +51 -1
- package/scaffold/dist/definitions/skills/lesson-learned.mjs +21 -0
- package/scaffold/vitest.config.mjs +1 -0
- package/packages/cli/dist/init-C_WzeMTD.js +0 -7
- package/packages/server/dist/config-4M54ZAT8.js +0 -2
- package/packages/server/dist/config-BXd38nVn.js +0 -1
- package/packages/server/dist/prelude-CNOjd5qt.js +0 -2
- package/packages/server/dist/prelude-Dki25eYn.js +0 -1
- package/packages/server/dist/routes-9KnBpwfe.js +0 -6
- package/packages/server/dist/routes-B8hTXXR8.js +0 -5
- package/packages/server/dist/sampling-B8NwOv_z.js +0 -1
- package/packages/server/dist/sampling-DOOgTH1B.js +0 -2
- package/packages/server/dist/server-C2n9kQMF.js +0 -3069
- package/packages/server/dist/server-CizTllz1.js +0 -3070
- package/scaffold/AUTOMATION-BOUNDARY-ANALYSIS.md +0 -78
|
@@ -139,12 +139,12 @@
|
|
|
139
139
|
<button class="cp-btn cp-btn--remove" aria-label="Remove selection without comment">Remove</button>
|
|
140
140
|
<button class="cp-btn cp-btn--comment" aria-label="Submit comment">Comment</button>
|
|
141
141
|
</div>
|
|
142
|
-
`,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),
|
|
143
|
-
`).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((n,
|
|
142
|
+
`,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),o=this.el.querySelector(".cp-btn--remove"),i=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),o.addEventListener("click",()=>this.handleRemove()),i.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",a=>this.handleKeyDown(a)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",a=>{if(a.key!=="Tab")return;let r=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(r.length===0)return;let l=r[0],c=r[r.length-1];a.shiftKey&&document.activeElement===l?(a.preventDefault(),c.focus()):!a.shiftKey&&document.activeElement===c&&(a.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,o=this.el.offsetWidth||320,i=this.el.offsetHeight||260,a=8,r=t.left+e+t.width/2-o/2;r=Math.max(a,r),r=Math.min(r,window.innerWidth+e-o-a);let l=window.innerHeight+n,c=t.bottom+n+a,p;c+i<=l?p=c:(p=t.top+n-i-a,p=Math.max(a,p)),this.el.style.left=`${r}px`,this.el.style.top=`${p}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){s(this,"store");this.store=t}escapeMd(t){return t.replace(/[`*_{}[\]()#+\-.!|~]/g,"\\$&")}exportMarkdown(){let e=[...this.store.getState().annotations].sort((r,l)=>r.createdAt-l.createdAt);if(e.length===0)return"No feedback provided.";let n=e.filter(r=>r.type==="COMMENT"),o=e.filter(r=>r.type==="DELETION"),i=e.filter(r=>r.type==="GLOBAL_COMMENT"),a=["## Reviewer Feedback",""];if(i.length>0){a.push("### General Notes","");for(let r of i)a.push(`- ${this.escapeMd(r.comment||"")}`),a.push("")}if(n.length>0){a.push("### Comments","");for(let r of n){let l=r.originalText.length>80?`${r.originalText.slice(0,80)}\u2026`:r.originalText;a.push(`- **${this.escapeMd(r.comment||"")}**`),a.push(` > "${this.escapeMd(l)}"`),a.push("")}}if(o.length>0){a.push("### Deletions","");for(let r of o){let l=r.originalText.length>80?`${r.originalText.slice(0,80)}\u2026`:r.originalText;a.push("- Remove this"),a.push(` > "${this.escapeMd(l)}"`),a.push("")}}return a.join(`
|
|
143
|
+
`).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((n,o)=>n.createdAt-o.createdAt);return JSON.stringify(e,null,2)}submitFeedback(t){let e=this.exportMarkdown(),n=this.exportJSON(),o=e==="No feedback provided."?e:`${e}
|
|
144
144
|
|
|
145
145
|
\`\`\`json
|
|
146
146
|
${n}
|
|
147
|
-
\`\`\``;t("annotations",
|
|
147
|
+
\`\`\``;t("annotations",o)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(i=>i.type==="COMMENT").length,n=t.annotations.filter(i=>i.type==="DELETION").length,o=t.annotations.filter(i=>i.type==="GLOBAL_COMMENT").length;return{comments:e,deletions:n,global:o,total:t.annotations.length}}};var L="aikit-annotation-highlight";function I(){if(document.getElementById(L))return;let d=document.createElement("style");d.id=L,d.textContent=`
|
|
148
148
|
mark.hl-COMMENT {
|
|
149
149
|
background: var(--dt-annotation-comment-bg, rgba(88, 166, 255, 0.15));
|
|
150
150
|
border-bottom: 2px solid var(--dt-annotation-comment, #58a6ff);
|
|
@@ -185,7 +185,7 @@ ${n}
|
|
|
185
185
|
50% { transform: scale(1.05); }
|
|
186
186
|
100% { transform: scale(1); }
|
|
187
187
|
}
|
|
188
|
-
`,document.head.appendChild(d)}var y=class{constructor(t,e){s(this,"container");s(this,"store");s(this,"unsubscribe",null);this.container=t,this.store=e}start(){I(),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
|
|
188
|
+
`,document.head.appendChild(d)}var y=class{constructor(t,e){s(this,"container");s(this,"store");s(this,"unsubscribe",null);this.container=t,this.store=e}start(){I(),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 o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null),i=0,a=null,r=0,l=null,c=0,p=o.nextNode();for(;p;){let f=(p.textContent||"").length,m=i+f;if(a===null&&m>e&&(a=p,r=e-i),m>=n){l=p,c=n-i;break}i=m,p=o.nextNode()}if(!a||!l)return null;let u=document.createRange();return u.setStart(a,Math.min(r,(a.textContent||"").length)),u.setEnd(l,Math.min(c,(l.textContent||"").length)),u}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 o=document.createElement("mark");o.className=`hl-${t.type}`,o.dataset.annotationId=t.id,o.addEventListener("click",()=>{this.store.select(t.id)});try{n.surroundContents(o)}catch{try{if(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.splitText(n.endOffset),n.startContainer.nodeType===Node.TEXT_NODE){let i=n.startContainer;n.startOffset>0&&i.splitText(n.startOffset);let a=document.createRange();a.setStart(i.nextSibling||i,0),a.setEnd(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.previousSibling||n.endContainer,n.endOffset),a.surroundContents(o)}else throw new Error("Non-text range")}catch{let i=n.extractContents();o.append(i),n.insertNode(o)}}}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 z=new Set(["button","input","textarea","select"]),E=class{constructor(t){s(this,"options");s(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 o=this.findBlockId(n.startContainer);if(!o)return;let i=this.findBlockContainer(n.startContainer),a=this.findBlockContainer(n.endContainer);if(i!==a)return;let r=this.computeBlockOffset(n.startContainer,n.startOffset),l=this.computeBlockOffset(n.endContainer,n.endOffset);if(r===null||l===null)return;let c={blockId:o,startOffset:r,endOffset:l,text:n.toString(),range:n};this.options.onSelection(c),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 o=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=0,a=o.nextNode();for(;a;){if(a===t)return i+e;i+=(a.textContent||"").length,a=o.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?z.has(e.tagName.toLowerCase()):!1}};var D="aikit-annotation-sidebar",R=`
|
|
189
189
|
.as-sidebar {
|
|
190
190
|
width: var(--dt-annotation-sidebar-width, 300px);
|
|
191
191
|
background: var(--dt-bg-secondary);
|
|
@@ -289,6 +289,9 @@ ${n}
|
|
|
289
289
|
.as-card--DELETION {
|
|
290
290
|
border-left: 2px solid var(--dt-annotation-deletion, #f85149);
|
|
291
291
|
}
|
|
292
|
+
.as-card--GLOBAL_COMMENT {
|
|
293
|
+
border-left: 2px solid var(--dt-accent-fg, #6366f1);
|
|
294
|
+
}
|
|
292
295
|
|
|
293
296
|
.as-card:hover {
|
|
294
297
|
background: var(--dt-annotation-hover);
|
|
@@ -302,6 +305,18 @@ ${n}
|
|
|
302
305
|
outline: 2px solid var(--dt-annotation-deletion, #f85149);
|
|
303
306
|
outline-offset: -2px;
|
|
304
307
|
}
|
|
308
|
+
.as-card--GLOBAL_COMMENT.as-card--selected {
|
|
309
|
+
outline: 2px solid var(--dt-accent-fg, #6366f1);
|
|
310
|
+
outline-offset: -2px;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
.as-card-type-badge {
|
|
314
|
+
display: inline-block;
|
|
315
|
+
font-size: var(--dt-font-size-xs);
|
|
316
|
+
font-weight: 600;
|
|
317
|
+
color: var(--dt-text-tertiary);
|
|
318
|
+
margin-bottom: 2px;
|
|
319
|
+
}
|
|
305
320
|
|
|
306
321
|
.as-card-excerpt {
|
|
307
322
|
font-size: var(--dt-font-size-sm);
|
|
@@ -367,21 +382,89 @@ ${n}
|
|
|
367
382
|
font-size: var(--dt-font-size-sm);
|
|
368
383
|
padding: var(--dt-space-6) var(--dt-space-2);
|
|
369
384
|
}
|
|
370
|
-
|
|
385
|
+
|
|
386
|
+
/* \u2500\u2500 Global comment footer \u2500\u2500 */
|
|
387
|
+
.as-footer {
|
|
388
|
+
border-top: 1px solid var(--dt-border-default);
|
|
389
|
+
padding: var(--dt-space-3);
|
|
390
|
+
flex-shrink: 0;
|
|
391
|
+
display: flex;
|
|
392
|
+
flex-direction: column;
|
|
393
|
+
gap: var(--dt-space-2);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
.as-global-input {
|
|
397
|
+
font: inherit;
|
|
398
|
+
font-size: var(--dt-font-size-sm);
|
|
399
|
+
line-height: 1.4;
|
|
400
|
+
padding: var(--dt-space-2);
|
|
401
|
+
border: 1px solid var(--dt-border-default);
|
|
402
|
+
border-radius: var(--dt-radius-md);
|
|
403
|
+
background: var(--dt-bg-primary);
|
|
404
|
+
color: var(--dt-text-primary);
|
|
405
|
+
resize: vertical;
|
|
406
|
+
min-height: 2.5rem;
|
|
407
|
+
max-height: 6rem;
|
|
408
|
+
width: 100%;
|
|
409
|
+
box-sizing: border-box;
|
|
410
|
+
outline: none;
|
|
411
|
+
transition: border-color var(--dt-transition-fast);
|
|
412
|
+
}
|
|
413
|
+
.as-global-input:focus {
|
|
414
|
+
border-color: var(--dt-accent-fg);
|
|
415
|
+
}
|
|
416
|
+
.as-global-input::placeholder {
|
|
417
|
+
color: var(--dt-text-tertiary);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
.as-global-btn {
|
|
421
|
+
display: inline-flex;
|
|
422
|
+
align-items: center;
|
|
423
|
+
justify-content: center;
|
|
424
|
+
gap: 4px;
|
|
425
|
+
padding: var(--dt-space-1) var(--dt-space-3);
|
|
426
|
+
border: 1px solid var(--dt-accent-fg);
|
|
427
|
+
border-radius: var(--dt-radius-md);
|
|
428
|
+
background: var(--dt-accent-emphasis);
|
|
429
|
+
color: #ffffff;
|
|
430
|
+
font-size: var(--dt-font-size-sm);
|
|
431
|
+
font-weight: 600;
|
|
432
|
+
cursor: pointer;
|
|
433
|
+
transition: opacity var(--dt-transition-fast);
|
|
434
|
+
font-family: inherit;
|
|
435
|
+
align-self: flex-end;
|
|
436
|
+
}
|
|
437
|
+
.as-global-btn:hover {
|
|
438
|
+
opacity: 0.9;
|
|
439
|
+
}
|
|
440
|
+
.as-global-btn:disabled {
|
|
441
|
+
opacity: 0.5;
|
|
442
|
+
cursor: default;
|
|
443
|
+
}
|
|
444
|
+
`,_='<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){s(this,"el");s(this,"store");s(this,"exporter");s(this,"unsubscribe",null);s(this,"listEl");s(this,"modeToggleBtn");s(this,"globalInput");s(this,"globalBtn");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.globalInput=this.el.querySelector(".as-global-input"),this.globalBtn=this.el.querySelector(".as-global-btn"),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}}),this.globalBtn.addEventListener("click",n=>{n.stopPropagation(),this.submitGlobalComment()}),this.globalInput.addEventListener("keydown",n=>{n.key==="Enter"&&!n.shiftKey&&(n.preventDefault(),this.submitGlobalComment())}),this.globalInput.addEventListener("input",()=>{this.updateGlobalBtnState()}),(t.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle(),this.updateGlobalBtnState()}destroy(){this.unsubscribe?.(),this.el.remove()}submitGlobalComment(){let t=this.globalInput.value.trim();t&&(this.store.addGeneralComment(t),this.globalInput.value="",this.updateGlobalBtnState())}updateGlobalBtnState(){this.globalBtn.disabled=this.globalInput.value.trim().length===0}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=`
|
|
371
445
|
<div class="as-header">
|
|
372
446
|
<span class="as-header-title">Annotations</span>
|
|
373
447
|
<span class="as-count-badge" aria-live="polite">${e.total}</span>
|
|
374
448
|
<span class="as-header-spacer"></span>
|
|
375
|
-
<button class="as-mode-toggle" aria-label="Toggle annotation mode">${
|
|
449
|
+
<button class="as-mode-toggle" aria-label="Toggle annotation mode">${_} Feedback</button>
|
|
376
450
|
<button class="as-close-btn" aria-label="Close sidebar">×</button>
|
|
377
451
|
</div>
|
|
378
452
|
<div class="as-list" role="list" aria-label="Annotation list"></div>
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
453
|
+
<div class="as-footer">
|
|
454
|
+
<textarea class="as-global-input" placeholder="Add general feedback comment..." rows="2" maxlength="5000" aria-label="Add general comment"></textarea>
|
|
455
|
+
<button class="as-global-btn" disabled>Add Comment</button>
|
|
456
|
+
</div>
|
|
457
|
+
`,t.querySelector(".as-close-btn").addEventListener("click",i=>{i.stopPropagation(),this.store.toggleSidebar(!1)}),t.querySelector(".as-mode-toggle").addEventListener("click",i=>{i.stopPropagation();let a=this.store.getState().mode==="feedback"?"selection":"feedback";this.store.setMode(a)}),t}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML="",e.length===0){let o=document.createElement("div");o.className="as-empty",o.textContent="No annotations yet. Select text in Feedback mode or add a general comment below.",this.listEl.appendChild(o);return}let n=[...e].sort((o,i)=>i.createdAt-o.createdAt);for(let o of n)this.listEl.appendChild(this.renderAnnotationItem(o))}renderAnnotationItem(t){let e=document.createElement("div");if(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"),t.type==="GLOBAL_COMMENT")e.innerHTML=`
|
|
458
|
+
<div class="as-card-type-badge">General Comment</div>
|
|
459
|
+
<div class="as-card-comment">${g(t.comment||"")}</div>
|
|
460
|
+
<div class="as-card-comment-detail">${g(t.comment||"")}</div>
|
|
461
|
+
<button class="as-delete-btn" aria-label="Delete annotation">×</button>
|
|
462
|
+
`;else{let i=t.originalText.length>60?`${t.originalText.slice(0,60)}\u2026`:t.originalText;e.innerHTML=`
|
|
463
|
+
<div class="as-card-excerpt">${g(i)}</div>
|
|
464
|
+
${t.comment?`<div class="as-card-comment">${g(t.comment)}</div>`:""}
|
|
465
|
+
<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>
|
|
466
|
+
<button class="as-delete-btn" aria-label="Delete annotation">×</button>
|
|
467
|
+
`}return e.addEventListener("click",()=>{this.store.select(t.id);let i=e.querySelector(".as-card-comment-detail");if(i){i.classList.toggle("as-card-comment-detail--open");let a=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let r of a)r!==i&&r.classList.remove("as-card-comment-detail--open")}}),e.querySelector(".as-delete-btn").addEventListener("click",i=>{i.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 o=n.dataset.annotationId;n.classList.toggle("as-card--selected",o!==void 0&&o===t)}}};var T=class{constructor(){s(this,"annotations",[]);s(this,"selectedId",null);s(this,"mode","selection");s(this,"isSidebarOpen",!1);s(this,"subscribers",new Set);s(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,o,i,a,r,l,c){let p={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:o,originalText:i,comment:a,section:r,contextBefore:l,contextAfter:c,createdAt:Date.now()};return this.annotations.push(p),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:p}),p}addGeneralComment(t){let e={id:this.generateId(),type:"GLOBAL_COMMENT",blockId:"",startOffset:0,endOffset:0,originalText:"",comment:t,createdAt:Date.now()};return this.annotations.push(e),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:"sidebar-toggled",open:!0})),this.notify({type:"annotation-added",annotation:e}),e}update(t,e){let n=this.annotations.find(o=>o.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 w=25,$="aikit-annotation-guide",q=`
|
|
385
468
|
.as-guide {
|
|
386
469
|
margin: 0 0 var(--dt-space-3) 0;
|
|
387
470
|
padding: var(--dt-space-2) var(--dt-space-3);
|
|
@@ -398,7 +481,7 @@ ${n}
|
|
|
398
481
|
.as-guide--visible {
|
|
399
482
|
display: block;
|
|
400
483
|
}
|
|
401
|
-
`;function j(d){let{range:t}=d,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
|
|
484
|
+
`;function j(d){let{range:t}=d,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 o,i;try{if(t.startContainer.nodeType===Node.TEXT_NODE&&t.startOffset>0){let a=t.startContainer.textContent||"",r=Math.max(0,t.startOffset-w);o=a.slice(r,t.startOffset)}if(t.endContainer.nodeType===Node.TEXT_NODE&&t.endOffset<(t.endContainer.textContent?.length||0)){let a=t.endContainer.textContent||"",r=Math.min(a.length,t.endOffset+w);i=a.slice(t.endOffset,r)}}catch{}return{section:e,contextBefore:o,contextAfter:i}}function A(d){let{container:t,mountTarget:e}=d,n=null,o=new T;o.setMode("feedback");let i=new x(o);b($,q);let a=document.createElement("div");a.className="as-guide",a.textContent="\u27B3 Ready. Select text to annotate or disable Feedback in the sidebar.",t.prepend(a);let r=()=>{let u=o.getState();a.classList.toggle("as-guide--visible",u.mode==="feedback"&&u.annotations.length===0)};r(),o.subscribe(()=>r());let l=new y(t,o);l.start();let c=new E({container:t,mode:()=>o.getState().mode,onSelection:u=>{let f=j(u);n?.destroy();let m=new v(u,{onSubmit:(h,S)=>{o.add("COMMENT",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),m.destroy(),n===m&&(n=null)},onRemove:(h,S)=>{o.add("DELETION",h.blockId,h.startOffset,h.endOffset,h.text,S||void 0,f.section,f.contextBefore,f.contextAfter),m.destroy(),n===m&&(n=null)},onDismiss:()=>{m.destroy(),n===m&&(n=null)}});n=m}}),p=new k({store:o,exporter:i,mountTarget:e});return o.openSidebar(),{destroy(){n?.destroy(),n=null,a.remove(),c.destroy(),l.stop(),p.destroy(),o.destroy()},getStore(){return o},getExporter(){return i}}}document.addEventListener("DOMContentLoaded",()=>{let d=document.querySelector(".content")||document.querySelector("main"),t=d||document.body;if(!d||!(document.querySelector(".bk-actions")!==null))return;let n=t.parentElement;n?.classList.contains("shell-layout")||(n=document.createElement("div"),n.className="shell-layout",t.parentNode?.insertBefore(n,t),n.appendChild(t));let o="aikit-shell-layout";if(!document.getElementById(o)){let r=document.createElement("style");r.id=o,r.textContent=`
|
|
402
485
|
.shell-layout {
|
|
403
486
|
flex: 1;
|
|
404
487
|
display: flex;
|
|
@@ -425,4 +508,4 @@ ${C}
|
|
|
425
508
|
.action-bar {
|
|
426
509
|
margin-top: auto;
|
|
427
510
|
}
|
|
428
|
-
`,document.head.appendChild(
|
|
511
|
+
`,document.head.appendChild(r)}let i=A({container:t,mountTarget:n});i.getStore().subscribe(r=>{r.type==="sidebar-toggled"&&document.documentElement.setAttribute("data-annotation-sidebar",r.open?"open":"")}),i.getStore().getState().isSidebarOpen&&document.documentElement.setAttribute("data-annotation-sidebar","open"),window.__annotationLayer=i;let a=document.querySelectorAll(".bk-actions");if(a.length>0){let r=document.createElement("div");r.className="action-bar";let l=!1;for(let c of a)if(!c.querySelector('[data-action-row="multi"]')){for(;c.firstChild;)r.appendChild(c.firstChild);c.remove(),l=!0}if(l){let c=document.querySelector("main")||document.querySelector(".content");c&&(c.appendChild(r),c.style.paddingBottom="0")}}});})();
|
|
@@ -3540,8 +3540,8 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
3540
3540
|
<button class="cp-btn cp-btn--remove" aria-label="Remove selection without comment">Remove</button>
|
|
3541
3541
|
<button class="cp-btn cp-btn--comment" aria-label="Submit comment">Comment</button>
|
|
3542
3542
|
</div>
|
|
3543
|
-
`,this.textarea=this.el.querySelector(`.cp-textarea`);let n=this.el.querySelector(`.cp-btn--comment`),r=this.el.querySelector(`.cp-btn--remove`),i=this.el.querySelector(`.cp-btn--cancel`);this.backdrop.addEventListener(`click`,()=>this.handleCancel()),n.addEventListener(`click`,()=>this.handleComment()),r.addEventListener(`click`,()=>this.handleRemove()),i.addEventListener(`click`,()=>this.handleCancel()),this.textarea.addEventListener(`keydown`,e=>this.handleKeyDown(e)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener(`keydown`,e=>{if(e.key!==`Tab`)return;let t=this.el.querySelectorAll(`button, textarea, [tabindex]:not([tabindex="-1"])`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}positionNearSelection(){let e=this.result.range.getBoundingClientRect(),t=window.scrollX,n=window.scrollY,r=this.el.offsetWidth||320,i=this.el.offsetHeight||260,a=e.left+t+e.width/2-r/2;a=Math.max(8,a),a=Math.min(a,window.innerWidth+t-r-8);let o=window.innerHeight+n,s=e.bottom+n+8,c;s+i<=o?c=s:(c=e.top+n-i-8,c=Math.max(8,c)),this.el.style.left=`${a}px`,this.el.style.top=`${c}px`}handleComment(){let e=this.textarea.value.trim();this.options.onSubmit(this.result,e)}handleRemove(){let e=this.textarea.value.trim();this.options.onRemove(this.result,e)}handleCancel(){this.options.onDismiss()}handleKeyDown(e){e.key===`Escape`?(e.preventDefault(),this.handleCancel()):(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),this.handleComment())}},dw=class{store;constructor(e){this.store=e}exportMarkdown(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);if(e.length===0)return`No feedback provided.`;let t=e.filter(e=>e.type===`COMMENT`),n=e.filter(e=>e.type===`DELETION`),r=[`## Reviewer Feedback`,``];if(
|
|
3544
|
-
`).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);return JSON.stringify(e,null,2)}submitFeedback(e){let t=this.exportMarkdown(),n=this.exportJSON();e(`annotations`,t===`No feedback provided.`?t:`${t}\n\n\`\`\`json\n${n}\n\`\`\``)}getTotalCount(){let e=this.store.getState();return{comments:e.annotations.filter(e=>e.type===`COMMENT`).length,deletions:e.annotations.filter(e=>e.type===`DELETION`).length,total:e.annotations.length}}},fw=`aikit-annotation-highlight`;function pw(){if(document.getElementById(fw))return;let e=document.createElement(`style`);e.id=fw,e.textContent=`
|
|
3543
|
+
`,this.textarea=this.el.querySelector(`.cp-textarea`);let n=this.el.querySelector(`.cp-btn--comment`),r=this.el.querySelector(`.cp-btn--remove`),i=this.el.querySelector(`.cp-btn--cancel`);this.backdrop.addEventListener(`click`,()=>this.handleCancel()),n.addEventListener(`click`,()=>this.handleComment()),r.addEventListener(`click`,()=>this.handleRemove()),i.addEventListener(`click`,()=>this.handleCancel()),this.textarea.addEventListener(`keydown`,e=>this.handleKeyDown(e)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener(`keydown`,e=>{if(e.key!==`Tab`)return;let t=this.el.querySelectorAll(`button, textarea, [tabindex]:not([tabindex="-1"])`);if(t.length===0)return;let n=t[0],r=t[t.length-1];e.shiftKey&&document.activeElement===n?(e.preventDefault(),r.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}positionNearSelection(){let e=this.result.range.getBoundingClientRect(),t=window.scrollX,n=window.scrollY,r=this.el.offsetWidth||320,i=this.el.offsetHeight||260,a=e.left+t+e.width/2-r/2;a=Math.max(8,a),a=Math.min(a,window.innerWidth+t-r-8);let o=window.innerHeight+n,s=e.bottom+n+8,c;s+i<=o?c=s:(c=e.top+n-i-8,c=Math.max(8,c)),this.el.style.left=`${a}px`,this.el.style.top=`${c}px`}handleComment(){let e=this.textarea.value.trim();this.options.onSubmit(this.result,e)}handleRemove(){let e=this.textarea.value.trim();this.options.onRemove(this.result,e)}handleCancel(){this.options.onDismiss()}handleKeyDown(e){e.key===`Escape`?(e.preventDefault(),this.handleCancel()):(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),this.handleComment())}},dw=class{store;constructor(e){this.store=e}escapeMd(e){return e.replace(/[`*_{}[\]()#+\-.!|~]/g,`\\$&`)}exportMarkdown(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);if(e.length===0)return`No feedback provided.`;let t=e.filter(e=>e.type===`COMMENT`),n=e.filter(e=>e.type===`DELETION`),r=e.filter(e=>e.type===`GLOBAL_COMMENT`),i=[`## Reviewer Feedback`,``];if(r.length>0){i.push(`### General Notes`,``);for(let e of r)i.push(`- ${this.escapeMd(e.comment||``)}`),i.push(``)}if(t.length>0){i.push(`### Comments`,``);for(let e of t){let t=e.originalText.length>80?`${e.originalText.slice(0,80)}\u2026`:e.originalText;i.push(`- **${this.escapeMd(e.comment||``)}**`),i.push(` > "${this.escapeMd(t)}"`),i.push(``)}}if(n.length>0){i.push(`### Deletions`,``);for(let e of n){let t=e.originalText.length>80?`${e.originalText.slice(0,80)}\u2026`:e.originalText;i.push(`- Remove this`),i.push(` > "${this.escapeMd(t)}"`),i.push(``)}}return i.join(`
|
|
3544
|
+
`).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((e,t)=>e.createdAt-t.createdAt);return JSON.stringify(e,null,2)}submitFeedback(e){let t=this.exportMarkdown(),n=this.exportJSON();e(`annotations`,t===`No feedback provided.`?t:`${t}\n\n\`\`\`json\n${n}\n\`\`\``)}getTotalCount(){let e=this.store.getState();return{comments:e.annotations.filter(e=>e.type===`COMMENT`).length,deletions:e.annotations.filter(e=>e.type===`DELETION`).length,global:e.annotations.filter(e=>e.type===`GLOBAL_COMMENT`).length,total:e.annotations.length}}},fw=`aikit-annotation-highlight`;function pw(){if(document.getElementById(fw))return;let e=document.createElement(`style`);e.id=fw,e.textContent=`
|
|
3545
3545
|
mark.hl-COMMENT {
|
|
3546
3546
|
background: var(--dt-annotation-comment-bg, rgba(88, 166, 255, 0.15));
|
|
3547
3547
|
border-bottom: 2px solid var(--dt-annotation-comment, #58a6ff);
|
|
@@ -3686,6 +3686,9 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
3686
3686
|
.as-card--DELETION {
|
|
3687
3687
|
border-left: 2px solid var(--dt-annotation-deletion, #f85149);
|
|
3688
3688
|
}
|
|
3689
|
+
.as-card--GLOBAL_COMMENT {
|
|
3690
|
+
border-left: 2px solid var(--dt-accent-fg, #6366f1);
|
|
3691
|
+
}
|
|
3689
3692
|
|
|
3690
3693
|
.as-card:hover {
|
|
3691
3694
|
background: var(--dt-annotation-hover);
|
|
@@ -3699,6 +3702,18 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
3699
3702
|
outline: 2px solid var(--dt-annotation-deletion, #f85149);
|
|
3700
3703
|
outline-offset: -2px;
|
|
3701
3704
|
}
|
|
3705
|
+
.as-card--GLOBAL_COMMENT.as-card--selected {
|
|
3706
|
+
outline: 2px solid var(--dt-accent-fg, #6366f1);
|
|
3707
|
+
outline-offset: -2px;
|
|
3708
|
+
}
|
|
3709
|
+
|
|
3710
|
+
.as-card-type-badge {
|
|
3711
|
+
display: inline-block;
|
|
3712
|
+
font-size: var(--dt-font-size-xs);
|
|
3713
|
+
font-weight: 600;
|
|
3714
|
+
color: var(--dt-text-tertiary);
|
|
3715
|
+
margin-bottom: 2px;
|
|
3716
|
+
}
|
|
3702
3717
|
|
|
3703
3718
|
.as-card-excerpt {
|
|
3704
3719
|
font-size: var(--dt-font-size-sm);
|
|
@@ -3764,7 +3779,66 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
3764
3779
|
font-size: var(--dt-font-size-sm);
|
|
3765
3780
|
padding: var(--dt-space-6) var(--dt-space-2);
|
|
3766
3781
|
}
|
|
3767
|
-
|
|
3782
|
+
|
|
3783
|
+
/* ── Global comment footer ── */
|
|
3784
|
+
.as-footer {
|
|
3785
|
+
border-top: 1px solid var(--dt-border-default);
|
|
3786
|
+
padding: var(--dt-space-3);
|
|
3787
|
+
flex-shrink: 0;
|
|
3788
|
+
display: flex;
|
|
3789
|
+
flex-direction: column;
|
|
3790
|
+
gap: var(--dt-space-2);
|
|
3791
|
+
}
|
|
3792
|
+
|
|
3793
|
+
.as-global-input {
|
|
3794
|
+
font: inherit;
|
|
3795
|
+
font-size: var(--dt-font-size-sm);
|
|
3796
|
+
line-height: 1.4;
|
|
3797
|
+
padding: var(--dt-space-2);
|
|
3798
|
+
border: 1px solid var(--dt-border-default);
|
|
3799
|
+
border-radius: var(--dt-radius-md);
|
|
3800
|
+
background: var(--dt-bg-primary);
|
|
3801
|
+
color: var(--dt-text-primary);
|
|
3802
|
+
resize: vertical;
|
|
3803
|
+
min-height: 2.5rem;
|
|
3804
|
+
max-height: 6rem;
|
|
3805
|
+
width: 100%;
|
|
3806
|
+
box-sizing: border-box;
|
|
3807
|
+
outline: none;
|
|
3808
|
+
transition: border-color var(--dt-transition-fast);
|
|
3809
|
+
}
|
|
3810
|
+
.as-global-input:focus {
|
|
3811
|
+
border-color: var(--dt-accent-fg);
|
|
3812
|
+
}
|
|
3813
|
+
.as-global-input::placeholder {
|
|
3814
|
+
color: var(--dt-text-tertiary);
|
|
3815
|
+
}
|
|
3816
|
+
|
|
3817
|
+
.as-global-btn {
|
|
3818
|
+
display: inline-flex;
|
|
3819
|
+
align-items: center;
|
|
3820
|
+
justify-content: center;
|
|
3821
|
+
gap: 4px;
|
|
3822
|
+
padding: var(--dt-space-1) var(--dt-space-3);
|
|
3823
|
+
border: 1px solid var(--dt-accent-fg);
|
|
3824
|
+
border-radius: var(--dt-radius-md);
|
|
3825
|
+
background: var(--dt-accent-emphasis);
|
|
3826
|
+
color: #ffffff;
|
|
3827
|
+
font-size: var(--dt-font-size-sm);
|
|
3828
|
+
font-weight: 600;
|
|
3829
|
+
cursor: pointer;
|
|
3830
|
+
transition: opacity var(--dt-transition-fast);
|
|
3831
|
+
font-family: inherit;
|
|
3832
|
+
align-self: flex-end;
|
|
3833
|
+
}
|
|
3834
|
+
.as-global-btn:hover {
|
|
3835
|
+
opacity: 0.9;
|
|
3836
|
+
}
|
|
3837
|
+
.as-global-btn:disabled {
|
|
3838
|
+
opacity: 0.5;
|
|
3839
|
+
cursor: default;
|
|
3840
|
+
}
|
|
3841
|
+
`,yw=`<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>`,bw=class{el;store;exporter;unsubscribe=null;listEl;modeToggleBtn;globalInput;globalBtn;constructor(e){this.store=e.store,this.exporter=e.exporter,this.el=this.render(),this.listEl=this.el.querySelector(`.as-list`),this.modeToggleBtn=this.el.querySelector(`.as-mode-toggle`),this.globalInput=this.el.querySelector(`.as-global-input`),this.globalBtn=this.el.querySelector(`.as-global-btn`),this.unsubscribe=this.store.subscribe(e=>{switch(e.type){case`annotation-added`:case`annotation-removed`:case`annotation-updated`:this.renderList(),this.updateHeader();break;case`selection-changed`:this.updateCardSelection(e.id);break;case`sidebar-toggled`:this.updateVisibility();break;case`mode-changed`:this.updateModeToggle();break}}),this.globalBtn.addEventListener(`click`,e=>{e.stopPropagation(),this.submitGlobalComment()}),this.globalInput.addEventListener(`keydown`,e=>{e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),this.submitGlobalComment())}),this.globalInput.addEventListener(`input`,()=>{this.updateGlobalBtnState()}),(e.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle(),this.updateGlobalBtnState()}destroy(){this.unsubscribe?.(),this.el.remove()}submitGlobalComment(){let e=this.globalInput.value.trim();e&&(this.store.addGeneralComment(e),this.globalInput.value=``,this.updateGlobalBtnState())}updateGlobalBtnState(){this.globalBtn.disabled=this.globalInput.value.trim().length===0}render(){aw(_w,vw);let e=document.createElement(`div`);return e.className=`as-sidebar`,e.setAttribute(`role`,`complementary`),e.setAttribute(`aria-label`,`Annotations`),e.innerHTML=`
|
|
3768
3842
|
<div class="as-header">
|
|
3769
3843
|
<span class="as-header-title">Annotations</span>
|
|
3770
3844
|
<span class="as-count-badge" aria-live="polite">${this.exporter.getTotalCount().total}</span>
|
|
@@ -3773,12 +3847,21 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
3773
3847
|
<button class="as-close-btn" aria-label="Close sidebar">×</button>
|
|
3774
3848
|
</div>
|
|
3775
3849
|
<div class="as-list" role="list" aria-label="Annotation list"></div>
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
|
|
3780
|
-
|
|
3781
|
-
|
|
3850
|
+
<div class="as-footer">
|
|
3851
|
+
<textarea class="as-global-input" placeholder="Add general feedback comment..." rows="2" maxlength="5000" aria-label="Add general comment"></textarea>
|
|
3852
|
+
<button class="as-global-btn" disabled>Add Comment</button>
|
|
3853
|
+
</div>
|
|
3854
|
+
`,e.querySelector(`.as-close-btn`).addEventListener(`click`,e=>{e.stopPropagation(),this.store.toggleSidebar(!1)}),e.querySelector(`.as-mode-toggle`).addEventListener(`click`,e=>{e.stopPropagation();let t=this.store.getState().mode===`feedback`?`selection`:`feedback`;this.store.setMode(t)}),e}renderList(){let e=this.store.getState().annotations;if(this.listEl.innerHTML=``,e.length===0){let e=document.createElement(`div`);e.className=`as-empty`,e.textContent=`No annotations yet. Select text in Feedback mode or add a general comment below.`,this.listEl.appendChild(e);return}let t=[...e].sort((e,t)=>t.createdAt-e.createdAt);for(let e of t)this.listEl.appendChild(this.renderAnnotationItem(e))}renderAnnotationItem(e){let t=document.createElement(`div`);return t.className=`as-card as-card--${e.type}`,t.dataset.annotationId=e.id,this.store.getState().selectedId===e.id&&t.classList.add(`as-card--selected`),e.type===`GLOBAL_COMMENT`?t.innerHTML=`
|
|
3855
|
+
<div class="as-card-type-badge">General Comment</div>
|
|
3856
|
+
<div class="as-card-comment">${sw(e.comment||``)}</div>
|
|
3857
|
+
<div class="as-card-comment-detail">${sw(e.comment||``)}</div>
|
|
3858
|
+
<button class="as-delete-btn" aria-label="Delete annotation">×</button>
|
|
3859
|
+
`:t.innerHTML=`
|
|
3860
|
+
<div class="as-card-excerpt">${sw(e.originalText.length>60?`${e.originalText.slice(0,60)}\u2026`:e.originalText)}</div>
|
|
3861
|
+
${e.comment?`<div class="as-card-comment">${sw(e.comment)}</div>`:``}
|
|
3862
|
+
<div class="as-card-comment-detail">${e.comment?sw(e.comment):`<em style="color:var(--dt-text-tertiary)">No comment — marked text only</em>`}</div>
|
|
3863
|
+
<button class="as-delete-btn" aria-label="Delete annotation">×</button>
|
|
3864
|
+
`,t.addEventListener(`click`,()=>{this.store.select(e.id);let n=t.querySelector(`.as-card-comment-detail`);if(n){n.classList.toggle(`as-card-comment-detail--open`);let e=this.listEl.querySelectorAll(`.as-card-comment-detail--open`);for(let t of e)t!==n&&t.classList.remove(`as-card-comment-detail--open`)}}),t.querySelector(`.as-delete-btn`).addEventListener(`click`,t=>{t.stopPropagation(),this.handleDelete(e.id)}),t}handleDelete(e){this.store.remove(e)}updateVisibility(){let e=this.store.getState();this.el.style.display=e.isSidebarOpen?`flex`:`none`}updateHeader(){let e=this.el.querySelector(`.as-count-badge`);if(e){let t=this.exporter.getTotalCount();e.textContent=String(t.total)}}updateModeToggle(){let e=this.store.getState().mode===`feedback`;this.modeToggleBtn.classList.toggle(`as-mode-toggle--active`,e),this.modeToggleBtn.setAttribute(`aria-pressed`,String(e)),this.modeToggleBtn.setAttribute(`aria-label`,e?`Disable annotation mode`:`Enable annotation mode`)}updateCardSelection(e){let t=this.el.querySelectorAll(`.as-card`);for(let n of t){let t=n.dataset.annotationId;n.classList.toggle(`as-card--selected`,t!==void 0&&t===e)}}},xw=class{annotations=[];selectedId=null;mode=`selection`;isSidebarOpen=!1;subscribers=new Set;idCounter=0;subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}notify(e){for(let t of this.subscribers)t(e)}generateId(){return this.idCounter+=1,`ann-${this.idCounter}`}openSidebar(){this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})}add(e,t,n,r,i,a,o,s,c){let l={id:this.generateId(),type:e,blockId:t,startOffset:n,endOffset:r,originalText:i,comment:a,section:o,contextBefore:s,contextAfter:c,createdAt:Date.now()};return this.annotations.push(l),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})),this.notify({type:`annotation-added`,annotation:l}),l}addGeneralComment(e){let t={id:this.generateId(),type:`GLOBAL_COMMENT`,blockId:``,startOffset:0,endOffset:0,originalText:``,comment:e,createdAt:Date.now()};return this.annotations.push(t),this.annotations.length===1&&(this.isSidebarOpen=!0,this.notify({type:`sidebar-toggled`,open:!0})),this.notify({type:`annotation-added`,annotation:t}),t}update(e,t){let n=this.annotations.find(t=>t.id===e);n&&(Object.assign(n,t),this.notify({type:`annotation-updated`,id:e,changes:t}))}remove(e){let t=this.annotations.findIndex(t=>t.id===e);t!==-1&&(this.annotations.splice(t,1),this.notify({type:`annotation-removed`,id:e}))}select(e){this.selectedId=e,this.notify({type:`selection-changed`,id:e})}setMode(e){e!==this.mode&&(this.mode=e,this.notify({type:`mode-changed`,mode:e}))}toggleSidebar(e){this.isSidebarOpen=e===void 0?!this.isSidebarOpen:e,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}},Sw=25,Cw=`aikit-annotation-guide`,ww=`
|
|
3782
3865
|
.as-guide {
|
|
3783
3866
|
margin: 0 0 var(--dt-space-3) 0;
|
|
3784
3867
|
padding: var(--dt-space-2) var(--dt-space-3);
|
|
@@ -5,4 +5,4 @@ import{fileURLToPath as e,pathToFileURL as t}from"node:url";import{parseArgs as
|
|
|
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){z.error(`Failed to upsert curated batch`,{batchSize:e.length,...o(t)});for(let t of e)n.push(`${t.relativePath}: upsert failed`);return 0}}catch(r){if(e.length===1)return z.error(`Failed to embed curated item`,{relativePath:e[0].relativePath,...o(r)}),n.push(`${e[0].relativePath}: reindex failed`),0;z.warn(`Curated embed batch failed, retrying with smaller chunks`,{batchSize:e.length,...o(r)});let i=Math.ceil(e.length/2),a=e.slice(0,i),s=e.slice(i);return await this.embedAndUpsertBatch(a,t,n)+await this.embedAndUpsertBatch(s,t,n)}}gitCommitKnowledge(e,t,n){try{if(!b(this.curatedDir))return;let r=this.knowledgeRefForPath(e);if(!r)return;x(r,`entry.md`,t,n,this.curatedDir)}catch{}}gitDeleteKnowledgeRef(e){try{if(!b(this.curatedDir))return;let t=this.knowledgeRefForPath(e);if(!t)return;S([`update-ref`,`-d`,t],this.curatedDir)}catch{}}knowledgeRefForPath(e){let t=e.replace(/\.md$/,``).split(`/`).map(e=>C(e)).join(`/`);return t.split(`/`).every(e=>y.test(e))?`${R}/${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,i){if(r.instance().isDegraded(`embedder`)){z.debug(`Skipping vector indexing — embedder degraded`,{relativePath:e,operation:i,subsystem:`embedder`});return}try{await this.indexCuratedFile(e,t,n)}catch(t){z.warn(`Curated file persisted but vector indexing deferred`,{relativePath:e,operation:i,...o(t)})}}async discoverCategories(){return this.adapter.listDirectories()}guardPath(e){let t=e.replace(/^\.ai\/curated\//,``);if(t.endsWith(`.md`)||(t+=`.md`),t.includes(`..`)||l(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`)>L)throw Error(`Content exceeds maximum size of ${L/1024}KB`)}slugify(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``).slice(0,80)}normalizeTags(e){return[...new Set(e.map(e=>e.trim()).filter(Boolean))]}sameTags(e,t){if(e.length!==t.length)return!1;let n=new Set(e);return t.every(e=>n.has(e))}ensureCategoryPath(e,t){if(!e.startsWith(`${t}/`))throw Error(`Curated path "${e}" must stay within category "${t}"`)}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 v(`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}}};const V=i(`server`);function H(e,t){return t?{version:e,...o(t)}:{version:e}}function U(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function W(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function G(){return W()?n({allowPositionals:!0,options:{transport:{type:`string`,default:U()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:U(),port:process.env.AIKIT_PORT??`3210`}}async function K(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=w(),n=G();if(process.on(`unhandledRejection`,e=>{V.error(`Unhandled rejection`,H(t,e))}),process.on(`uncaughtException`,e=>{V.error(`Uncaught exception — exiting`,H(t,e)),process.exit(1)}),V.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-
|
|
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}}};const V=i(`server`);function H(e,t){return t?{version:e,...o(t)}:{version:e}}function U(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function W(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===t(e).href}catch{return!1}}function G(){return W()?n({allowPositionals:!0,options:{transport:{type:`string`,default:U()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:U(),port:process.env.AIKIT_PORT??`3210`}}async function K(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let t=w(),n=G();if(process.on(`unhandledRejection`,e=>{V.error(`Unhandled rejection`,H(t,e))}),process.on(`uncaughtException`,e=>{V.error(`Uncaught exception — exiting`,H(t,e)),process.exit(1)}),V.info(`Starting MCP AI Kit server`,{version:t}),n.transport===`http`){let{startHttpMode:e}=await import(`./server-http-BGcKUn5y.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-C66e05P_.js`);await e(t)}}K();export{T as a,k as i,I as n,E as o,F as r,O as s,B as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{o as e,t}from"./supersession-DO_ZROFl.js";import{fileURLToPath as n}from"node:url";import{AIKIT_RUNTIME_PATHS as r,DEFAULT_SERVER_NAME as i,EMBEDDING_DEFAULTS as a,computePartitionKey as o,createLogger as s,getPartitionDir as c,migrateLegacyWorkspaceLayout as l,safeCwd as u,serializeError as d}from"../../core/dist/index.js";import{existsSync as f,mkdirSync as p,readFileSync as m,writeFileSync as h}from"node:fs";import{dirname as g,isAbsolute as _,relative as v,resolve as y}from"node:path";import{homedir as b}from"node:os";const x={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},S={working:1,episodic:2,semantic:4,procedural:12};function C(e,t=x){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function w(e,t,n){e.memoryMetaUpdateTier(t,n)}const T={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function E(e){return{...T,...e}}function D(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function O(e){return e&&e in S?e:`working`}function k(e,t,n,r=T,i){let a=typeof r==`string`?O(r):`working`,o=E(typeof r==`string`?i:r),s=D(e,D(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*S[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function A(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=k(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function j(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=k(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function M(e,t){let n=E(t);return e.memoryMetaList().map(t=>A(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const N=g(n(import.meta.url)),P=s(`server`),F=[`auto`,`manual`,`smart`],I={model:a.model,dimensions:a.dimensions,childProcess:!0,idleTimeoutMs:3e5};function L(e){return typeof e==`string`&&F.includes(e)}function R(e,t,n){let r=y(e),i=v(y(t),r);if(i.startsWith(`..`)||_(i))throw Error(`Config ${n} path escapes allowed root: ${e} is not under ${t}`);return r}function z(e,t){let n=y(e),r=v(y(t),n);return!(r.startsWith(`..`)||_(r))}function B(e){return c(o(e))}function V(e,t,n,r,i){let a=r?y(t,r):t;if(!n)return R(a,t,i);let o=y(e,n);return z(o,t)?r&&y(o)===y(t)?R(a,t,i):R(o,t,i):R(a,t,i)}function H(e){let t=[e.store?.path,e.curated?.path,e.onboardDir,e.stateDir,e.l0CardDir];for(let e of t)e&&p(e,{recursive:!0})}function U(e,t){l(t);let n=B(t);e.store={...e.store,path:V(t,n,e.store?.path,r.data,`store`)},e.curated={...e.curated,path:V(t,n,e.curated?.path,r.curated,`curated`)},e.onboardDir=V(t,n,e.onboardDir,r.onboard,`onboard`),e.stateDir=V(t,n,e.stateDir,r.state,`state`),e.l0CardDir=V(t,n,e.l0CardDir,r.l0Cards,`l0CardDir`)}function W(e){let t=process.env.AIKIT_INDEX_MODE;if(L(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function G(){let n=u(),r=process.env.AIKIT_CONFIG_PATH??(n&&f(y(n,`aikit.config.json`))?y(n,`aikit.config.json`):y(N,`..`,`..`,`..`,`aikit.config.json`));try{if(!f(r))return P.info(`No config file found, using defaults`,{configPath:r}),q();let n=m(r,`utf-8`),i=JSON.parse(n),a={...I,...i.embedding};if(i.embedding=a,i.memory={retention:{...T,...i.memory?.retention},lessons:{...e,...i.memory?.lessons},consolidation:{...x,...i.memory?.consolidation},supersession:{...t,...i.memory?.supersession}},i.logging?.errorDetails!==void 0&&typeof i.logging.errorDetails!=`boolean`)throw Error(`Config logging.errorDetails must be a boolean`);if(i.logging={errorDetails:i.logging?.errorDetails===!0},!i.sources||!Array.isArray(i.sources)||i.sources.length===0)throw Error(`Config must have at least one source`);if(!i.store?.path)throw Error(`Config must specify store.path`);if(i.autoIndex!==void 0&&typeof i.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(i.indexMode!==void 0&&!L(i.indexMode))throw Error(`Config indexMode must be one of: ${F.join(`, `)}`);if(typeof a.model!=`string`||a.model.trim()===``)throw Error(`Config embedding.model must be a non-empty string`);if(a.nativeDim!==void 0&&(!Number.isInteger(a.nativeDim)||a.nativeDim<=0))throw Error(`Config embedding.nativeDim must be a positive integer`);if(a.dimensions!==void 0&&(!Number.isInteger(a.dimensions)||a.dimensions<=0))throw Error(`Config embedding.dimensions must be a positive integer`);if(a.dimensions!==void 0&&a.nativeDim!==void 0&&a.dimensions>a.nativeDim)throw Error(`Config embedding.dimensions must not exceed embedding.nativeDim`);if(a.queryPrefix!==void 0&&typeof a.queryPrefix!=`string`)throw Error(`Config embedding.queryPrefix must be a string`);let o=g(r);return i.sources=i.sources.map(e=>({...e,path:R(y(o,e.path),o,`source`)})),J(i,r),U(i,o),i.layeredKnowledge===void 0&&(i.layeredKnowledge=process.env.AIKIT_LAYERED_KNOWLEDGE===`true`),i.indexMode=W(i),i}catch(e){let t=`Failed to load config from ${r}. ${e instanceof Error?e.message:String(e)}`;console.error(`\n ⚠ CONFIG ERROR — ${t}\n Check that the file exists, is valid JSON, and all required fields are present.\n`),P.error(`Failed to load config`,{configPath:r,...d(e)}),P.warn(`Falling back to default configuration`,{configPath:r});let n=q();return n.configError=t,n}}const K=[`.git/**`,`**/node_modules/**`,`*.lock`,`pnpm-lock.yaml`,`package-lock.json`,`**/dist/**`,`**/build/**`,`**/out/**`,`**/.output/**`,`**/cdk.out/**`,`**/.next/**`,`**/.nuxt/**`,`**/.vercel/**`,`**/.serverless/**`,`**/.turbo/**`,`**/.cache/**`,`**/.parcel-cache/**`,`**/coverage/**`,`**/.terraform/**`,`**/__pycache__/**`,`**/.venv/**`,`**/.docusaurus/**`,`**/.temp/**`,`**/tmp/**`];function q(){let n=process.env.AIKIT_WORKSPACE_ROOT??u()??b(),a=B(n),o={sources:[{path:n,excludePatterns:[...K]}],serverName:i,indexing:{chunkSize:800,chunkOverlap:150,minChunkSize:100},embedding:{...I},store:{backend:`sqlite-vec`,path:y(a,r.data)},curated:{path:y(a,r.curated)},memory:{retention:{...T},lessons:{...e},consolidation:{...x},supersession:{...t}},logging:{errorDetails:!1},onboardDir:y(a,r.onboard),stateDir:y(a,r.state)};return o.indexMode=W(o),o}function J(e,t){let n=e.configVersion??0;if(n>=1)return e;if(n<1)for(let t of e.sources){t.excludePatterns=t.excludePatterns??[];let e=new Set(t.excludePatterns);for(let n of K)e.has(n)||t.excludePatterns.push(n)}e.configVersion=1;try{h(t,`${JSON.stringify(e,null,2)}\n`,`utf-8`),P.info(`Config auto-upgraded`,{from:n,to:1,configPath:t})}catch(e){P.warn(`Failed to write upgraded config`,{configPath:t,...d(e)})}return e}function Y(e,t){if(!f(t))throw Error(`Workspace root does not exist: ${t}`);l(t),P.debug(`Reconfiguring for workspace root`,{workspaceRoot:t});try{process.chdir(t),P.debug(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){P.warn(`Failed to chdir to workspace root`,{workspaceRoot:t,...d(e)})}e.sources=[{path:t,excludePatterns:e.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],U(e,t),H(e)}export{K as DEFAULT_EXCLUDE_PATTERNS,C as a,x as i,G as loadConfig,A as n,w as o,j as r,Y as reconfigureForWorkspace,W as resolveIndexMode,M as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e,t}from"./supersession-CWEne3av.js";import{fileURLToPath as n}from"node:url";import{AIKIT_RUNTIME_PATHS as r,DEFAULT_SERVER_NAME as i,EMBEDDING_DEFAULTS as a,computePartitionKey as o,createLogger as s,getPartitionDir as c,migrateLegacyWorkspaceLayout as l,safeCwd as u,serializeError as d}from"../../core/dist/index.js";import{existsSync as f,mkdirSync as p,readFileSync as m,writeFileSync as h}from"node:fs";import{dirname as g,isAbsolute as _,relative as v,resolve as y}from"node:path";import{homedir as b}from"node:os";const x={workingToEpisodicAccesses:2,episodicToSemanticReferences:3,semanticToProceduralVerifications:5},S={working:1,episodic:2,semantic:4,procedural:12};function C(e,t=x){switch(e.tier){case`working`:if(e.accessCount>=t.workingToEpisodicAccesses)return`episodic`;break;case`episodic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences)return`semantic`;break;case`semantic`:if(e.accessCount>=t.workingToEpisodicAccesses+t.episodicToSemanticReferences+t.semanticToProceduralVerifications)return`procedural`;break;case`procedural`:break;default:break}}function w(e,t,n){e.memoryMetaUpdateTier(t,n)}const T={stabilityHours:168,accessMultiplier:1.5,flagThreshold:.1,maxStabilityHours:8760};function E(e){return{...T,...e}}function D(e,t){if(!e)return t;let n=Date.parse(e);return Number.isNaN(n)?t:n}function O(e){return e&&e in S?e:`working`}function k(e,t,n,r=T,i){let a=typeof r==`string`?O(r):`working`,o=E(typeof r==`string`?i:r),s=D(e,D(n,Date.now())),c=Math.max(0,Date.now()-s)/(1e3*60*60),l=Math.min(o.stabilityHours*S[a]*o.accessMultiplier**Math.max(0,t),o.maxStabilityHours);return Math.exp(-c/l)}function A(e,t,n){let r=e.memoryMetaGet(t);if(!r)return;let i=k(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return r.retentionScore!==i&&e.memoryMetaUpdateScore(t,i),e.memoryMetaGet(t)??{...r,retentionScore:i}}function j(e,t,n){e.memoryMetaGet(t)||e.memoryMetaCreate(t),e.memoryMetaTouch(t);let r=e.memoryMetaGet(t);if(!r)return 1;let i=k(r.lastAccessedAt,r.accessCount,r.createdAt,r.tier,n);return e.memoryMetaUpdateScore(t,i),i}function M(e,t){let n=E(t);return e.memoryMetaList().map(t=>A(e,t.entryId,n)??t).filter(e=>e.retentionScore<n.flagThreshold).sort((e,t)=>e.retentionScore-t.retentionScore)}const N=g(n(import.meta.url)),P=s(`server`),F=[`auto`,`manual`,`smart`],I={model:a.model,dimensions:a.dimensions,childProcess:!0,idleTimeoutMs:3e5};function L(e){return typeof e==`string`&&F.includes(e)}function R(e,t,n){let r=y(e),i=v(y(t),r);if(i.startsWith(`..`)||_(i))throw Error(`Config ${n} path escapes allowed root: ${e} is not under ${t}`);return r}function z(e,t){let n=y(e),r=v(y(t),n);return!(r.startsWith(`..`)||_(r))}function B(e){return c(o(e))}function V(e,t,n,r,i){let a=r?y(t,r):t;if(!n)return R(a,t,i);let o=y(e,n);return z(o,t)?r&&y(o)===y(t)?R(a,t,i):R(o,t,i):R(a,t,i)}function H(e){let t=[e.store?.path,e.curated?.path,e.onboardDir,e.stateDir,e.l0CardDir];for(let e of t)e&&p(e,{recursive:!0})}function U(e,t){l(t);let n=B(t);e.store={...e.store,path:V(t,n,e.store?.path,r.data,`store`)},e.curated={...e.curated,path:V(t,n,e.curated?.path,r.curated,`curated`)},e.onboardDir=V(t,n,e.onboardDir,r.onboard,`onboard`),e.stateDir=V(t,n,e.stateDir,r.state,`state`),e.l0CardDir=V(t,n,e.l0CardDir,r.l0Cards,`l0CardDir`)}function W(e){let t=process.env.AIKIT_INDEX_MODE;if(L(t))return t;if(e.indexMode)return e.indexMode;let n=process.env.AIKIT_AUTO_INDEX;return n===void 0?e.autoIndex===void 0?`smart`:e.autoIndex?`auto`:`manual`:n===`true`?`auto`:`manual`}function G(){let n=u(),r=process.env.AIKIT_CONFIG_PATH??(n&&f(y(n,`aikit.config.json`))?y(n,`aikit.config.json`):y(N,`..`,`..`,`..`,`aikit.config.json`));try{if(!f(r))return P.info(`No config file found, using defaults`,{configPath:r}),q();let n=m(r,`utf-8`),i=JSON.parse(n),a={...I,...i.embedding};if(i.embedding=a,i.memory={retention:{...T,...i.memory?.retention},lessons:{...e,...i.memory?.lessons},consolidation:{...x,...i.memory?.consolidation},supersession:{...t,...i.memory?.supersession}},i.logging?.errorDetails!==void 0&&typeof i.logging.errorDetails!=`boolean`)throw Error(`Config logging.errorDetails must be a boolean`);if(i.logging={errorDetails:i.logging?.errorDetails===!0},!i.sources||!Array.isArray(i.sources)||i.sources.length===0)throw Error(`Config must have at least one source`);if(!i.store?.path)throw Error(`Config must specify store.path`);if(i.autoIndex!==void 0&&typeof i.autoIndex!=`boolean`)throw Error(`Config autoIndex must be a boolean`);if(i.indexMode!==void 0&&!L(i.indexMode))throw Error(`Config indexMode must be one of: ${F.join(`, `)}`);if(typeof a.model!=`string`||a.model.trim()===``)throw Error(`Config embedding.model must be a non-empty string`);if(a.nativeDim!==void 0&&(!Number.isInteger(a.nativeDim)||a.nativeDim<=0))throw Error(`Config embedding.nativeDim must be a positive integer`);if(a.dimensions!==void 0&&(!Number.isInteger(a.dimensions)||a.dimensions<=0))throw Error(`Config embedding.dimensions must be a positive integer`);if(a.dimensions!==void 0&&a.nativeDim!==void 0&&a.dimensions>a.nativeDim)throw Error(`Config embedding.dimensions must not exceed embedding.nativeDim`);if(a.queryPrefix!==void 0&&typeof a.queryPrefix!=`string`)throw Error(`Config embedding.queryPrefix must be a string`);let o=g(r);return i.sources=i.sources.map(e=>({...e,path:R(y(o,e.path),o,`source`)})),J(i,r),U(i,o),i.layeredKnowledge===void 0&&(i.layeredKnowledge=process.env.AIKIT_LAYERED_KNOWLEDGE===`true`),i.indexMode=W(i),i}catch(e){let t=`Failed to load config from ${r}. ${e instanceof Error?e.message:String(e)}`;console.error(`\n ⚠ CONFIG ERROR — ${t}\n Check that the file exists, is valid JSON, and all required fields are present.\n`),P.error(`Failed to load config`,{configPath:r,...d(e)}),P.warn(`Falling back to default configuration`,{configPath:r});let n=q();return n.configError=t,n}}const K=[`.git/**`,`**/node_modules/**`,`*.lock`,`pnpm-lock.yaml`,`package-lock.json`,`**/dist/**`,`**/build/**`,`**/out/**`,`**/.output/**`,`**/cdk.out/**`,`**/.next/**`,`**/.nuxt/**`,`**/.vercel/**`,`**/.serverless/**`,`**/.turbo/**`,`**/.cache/**`,`**/.parcel-cache/**`,`**/coverage/**`,`**/.terraform/**`,`**/__pycache__/**`,`**/.venv/**`,`**/.docusaurus/**`,`**/.temp/**`,`**/tmp/**`];function q(){let n=process.env.AIKIT_WORKSPACE_ROOT??u()??b(),a=B(n),o={sources:[{path:n,excludePatterns:[...K]}],serverName:i,indexing:{chunkSize:800,chunkOverlap:150,minChunkSize:100},embedding:{...I},store:{backend:`sqlite-vec`,path:y(a,r.data)},curated:{path:y(a,r.curated)},memory:{retention:{...T},lessons:{...e},consolidation:{...x},supersession:{...t}},logging:{errorDetails:!1},onboardDir:y(a,r.onboard),stateDir:y(a,r.state)};return o.indexMode=W(o),o}function J(e,t){let n=e.configVersion??0;if(n>=1)return e;if(n<1)for(let t of e.sources){t.excludePatterns=t.excludePatterns??[];let e=new Set(t.excludePatterns);for(let n of K)e.has(n)||t.excludePatterns.push(n)}e.configVersion=1;try{h(t,`${JSON.stringify(e,null,2)}\n`,`utf-8`),P.info(`Config auto-upgraded`,{from:n,to:1,configPath:t})}catch(e){P.warn(`Failed to write upgraded config`,{configPath:t,...d(e)})}return e}function Y(e,t){if(!f(t))throw Error(`Workspace root does not exist: ${t}`);l(t),P.debug(`Reconfiguring for workspace root`,{workspaceRoot:t});try{process.chdir(t),P.debug(`Changed process cwd to workspace root`,{cwd:process.cwd()})}catch(e){P.warn(`Failed to chdir to workspace root`,{workspaceRoot:t,...d(e)})}e.sources=[{path:t,excludePatterns:e.sources[0]?.excludePatterns??[`node_modules/**`,`dist/**`,`.git/**`,`coverage/**`,`*.lock`,`pnpm-lock.yaml`]}],U(e,t),H(e)}export{K as DEFAULT_EXCLUDE_PATTERNS,C as a,x as i,G as loadConfig,A as n,w as o,j as r,Y as reconfigureForWorkspace,W as resolveIndexMode,M as t};
|
|
@@ -351,4 +351,4 @@ svg text{fill:var(--body);font-family:var(--sans);font-size:12px}
|
|
|
351
351
|
<\/script>
|
|
352
352
|
</body>
|
|
353
353
|
</html>`}const U=`<!-- DIAGRAM:SVG -->`;function W(e){let t=e.indexOf(U);if(t===-1)return null;let n=t+20,r=e.indexOf(U,n);if(r===-1)return null;let i=e.slice(n,r).trim();if(i.startsWith(`<svg`))return i;let a=e.slice(Math.max(0,t),r+20),o=a.match(/viewBox="([^"]+)"/),s=o?o[1]:`0 0 1200 800`,c=a.match(/width="(\d+)"/),l=c?c[1]:`1200`,u=a.match(/height="(\d+)"/);return[`<svg xmlns="http://www.w3.org/2000/svg" viewBox="${s}" width="${l}" height="${u?u[1]:`800`}">`,` <defs>`,` <style>`,` text { font-family: system-ui, -apple-system, sans-serif; }`,` .title { font-size: 20px; font-weight: 600; fill: #fff; }`,` .subtitle { font-size: 14px; fill: #94a3b8; }`,` </style>`,` </defs>`,i,`</svg>`].join(`
|
|
354
|
-
`)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-
|
|
354
|
+
`)}function he(e){let t=e.match(/<title>([^<]+)<\/title>/);return t?t[1]:`diagram`}async function ge(e,t,n){let r=m(n);await h(r,{recursive:!0});let i=he(e).replace(/[^a-zA-Z0-9\s-]/g,``).replace(/\s+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).toLowerCase().slice(0,80)||`diagram`,a=p(r,`${i}.html`);await g(a,e,`utf-8`);let o=null,s=W(e);s&&(o=p(r,`${i}.svg`),await g(o,s,`utf-8`));let c=null;return t&&(c=p(r,`${i}.md`),await g(c,t,`utf-8`)),{htmlPath:a,svgPath:o,mdPath:c}}const G=10*1024*1024,K=2e3;function _e(e){try{return JSON.stringify(e)}catch{return``}}function ve(e){switch(e.diagram_type){case`architecture`:return ae(e);case`workflow`:return H(e);case`sequence`:return R(e);case`dataflow`:return ce(e);case`lifecycle`:return P(e)}}function q(e,t={}){Y(e);let n=J(e);if(n.length>0)throw Error(`Diagram validation failed: ${n.join(`; `)}`);let r=t.title??e.meta.title,i=t.subtitle??e.meta.subtitle,a=t.dualOutput??!0,{svg:o,cardsHtml:s,detailData:c}=ve(e),l=c&&Object.keys(c).length>0?`\n<script id="diagram-node-data" type="application/json">${_e(c)}<\/script>`:``,u=e.meta?.palette===`warm`?`warm`:`technical`;return{html:me().replaceAll(`[TITLE]`,X(r)).replaceAll(`[SUBTITLE]`,X(i??``)).replaceAll(`[PALETTE]`,u===`warm`?` data-palette="warm"`:``).replaceAll(`<!-- DIAGRAM:SVG -->`,o).replaceAll(`<!-- DIAGRAM:CARDS -->`,s).replace(`</body>`,`${l}\n</body>`),markdown:a?_(e):void 0}}function ye(e,t={}){return q(e,{...t,dualOutput:!1}).html}function be(e){return _(e)}function xe(e){try{return Y(e),J(e)}catch(e){return[e.message]}}function J(e){if(!e||typeof e!=`object`)return[`Input must be an object`];if(!e.diagram_type)return[`Missing diagram_type`];if(!e.meta?.title)return[`meta.title is required`];if(e.schema_version!==1)return[`schema_version must be 1`];let t=e.diagram_type,n=e,r=n.components??n.nodes??n.participants??n.states??[],i=n.connections??n.edges??n.messages??n.flows??n.transitions??[],a=new Set(r.map(e=>e.id));if(a.size!==r.length)return[`${t}: Node/component IDs must be unique`];for(let e of i){if(e.from&&!a.has(e.from))return[`${t}: Edge references unknown source "${e.from}"`];if(e.to&&!a.has(e.to))return[`${t}: Edge references unknown target "${e.to}"`]}return[]}function Y(e){let t=JSON.stringify(e),n=Buffer.byteLength(t,`utf-8`);if(n>G)throw Error(`Input too large: ${(n/1024/1024).toFixed(1)}MB (max ${G/1024/1024}MB)`);let r=e,i=r.components??r.nodes??r.participants??[];if(i.length>500)throw Error(`Too many components/nodes: ${i.length} (max 500)`);let a=r.connections??r.edges??r.messages??r.flows??r.transitions??[];if(a.length>K)throw Error(`Too many edges/connections: ${a.length} (max ${K})`)}function Se(e){return e.replace(/[^a-zA-Z0-9-_]/g,`_`).toLowerCase().slice(0,120)}function X(e){let t={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};return String(e??``).replace(/[&<>"']/g,e=>t[e]??e)}const Z=d(`server`);function Q(e,t){return t?{version:e,...f(t)}:{version:e}}function $(){return process.env.AIKIT_TRANSPORT?process.env.AIKIT_TRANSPORT:process.stdin.isTTY?`http`:`stdio`}function Ce(){let e=process.argv[1];if(!e)return!1;try{return import.meta.url===l(e).href}catch{return!1}}function we(){return Ce()?u({allowPositionals:!0,options:{transport:{type:`string`,default:$()},port:{type:`string`,default:process.env.AIKIT_PORT??`3210`}}}).values:{transport:$(),port:process.env.AIKIT_PORT??`3210`}}async function Te(){let e=t=>{t.name===`ExperimentalWarning`&&t.message.includes(`SQLite`)||(process.off(`warning`,e),process.emitWarning(t),process.on(`warning`,e))};process.on(`warning`,e);let n=t(),r=we();if(process.on(`unhandledRejection`,e=>{Z.error(`Unhandled rejection`,Q(n,e))}),process.on(`uncaughtException`,e=>{Z.error(`Uncaught exception — exiting`,Q(n,e)),process.exit(1)}),Z.info(`Starting MCP AI Kit server`,{version:n}),r.transport===`http`){let{startHttpMode:e}=await import(`./server-http-Cx4tvbmK.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-BmGuXkkF.js`);await e(n)}}export{c as CuratedKnowledgeManager,s as applyWorkspaceRoots,a as bootstrapWorkspaceRoots,i as createSlidingWindowRateLimiter,ge as exportDiagram,W as extractSvg,n as getSessionIdHeader,Te as main,r as readPositiveIntEnv,t as readVersion,ye as renderHtml,be as renderMd,q as renderToResult,e as resolveCorsOrigin,Se as sanitizeTitle,o as selectWorkspaceRoot,xe as validate};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./server-Bsceh-AT.js";export{t as buildPreludeInjection,e as generatePrelude};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{DEFAULT_SERVER_NAME as e,getGlobalDataDir as t,isUserInstalled as n,safeCwdOrHome as r}from"../../core/dist/index.js";import{existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,writeFileSync as c}from"node:fs";import{dirname as l,resolve as u}from"node:path";import{z as d}from"zod";import{Router as f}from"express";const p=[{key:`serverName`,type:`string`,default:e,description:`MCP server name advertised to clients.`,group:`general`,requiresRestart:!0},{key:`toolPrefix`,type:`string`,default:``,description:`Prefix prepended to every MCP tool name (e.g. "aikit_").`,group:`general`,requiresRestart:!0},{key:`toolProfile`,type:`string`,default:`full`,description:`Active tool profile.`,group:`general`,enum:[`full`,`safe`,`research`,`minimal`,`discovery`],requiresRestart:!0},{key:`autoIndex`,type:`boolean`,default:!1,description:`Deprecated. Prefer indexMode. true → auto, false → manual.`,group:`indexing`},{key:`indexMode`,type:`string`,default:`smart`,description:`Indexing strategy. auto = full on startup, manual = on demand, smart = on-demand + idle.`,group:`indexing`,enum:[`auto`,`manual`,`smart`]},{key:`sources`,type:`array`,description:`Source roots to index. Each entry has { path, excludePatterns }.`,group:`indexing`,requiresRestart:!0},{key:`indexing.chunkSize`,type:`number`,default:1500,description:`Maximum chunk size in characters.`,group:`indexing`},{key:`indexing.chunkOverlap`,type:`number`,default:200,description:`Overlap between adjacent chunks.`,group:`indexing`},{key:`indexing.minChunkSize`,type:`number`,default:100,description:`Minimum chunk size before merging into the next chunk.`,group:`indexing`},{key:`indexing.concurrency`,type:`number`,description:`Max files processed concurrently. Defaults to half of CPU cores.`,group:`indexing`},{key:`embedding.model`,type:`string`,default:`mixedbread-ai/mxbai-embed-large-v1`,description:`Embedding model identifier.`,group:`embedding`,requiresRestart:!0},{key:`embedding.dimensions`,type:`number`,default:1024,description:`Embedding vector dimensions. Must match the model.`,group:`embedding`,requiresRestart:!0},{key:`store.backend`,type:`string`,default:`sqlite-vec`,description:`Vector store backend (sqlite-vec | lancedb).`,group:`store`,requiresRestart:!0},{key:`store.path`,type:`string`,description:`Filesystem path for the vector store.`,group:`store`,requiresRestart:!0},{key:`curated.path`,type:`string`,description:`Path to curated knowledge directory.`,group:`store`,requiresRestart:!0},{key:`onboardDir`,type:`string`,description:`Directory for onboard / produce_knowledge output.`,group:`store`,requiresRestart:!0},{key:`stateDir`,type:`string`,description:`Directory for session state (stash, checkpoints, etc.).`,group:`store`,requiresRestart:!0},{key:`er.enabled`,type:`boolean`,default:!1,description:`Enable enterprise RAG bridge integration.`,group:`enterprise-bridge`,requiresRestart:!0},{key:`er.baseUrl`,type:`string`,description:`Base URL of the ER API.`,group:`enterprise-bridge`,requiresRestart:!0},{key:`er.timeoutMs`,type:`number`,default:5e3,description:`ER request timeout in milliseconds.`,group:`enterprise-bridge`},{key:`er.fallbackThreshold`,type:`number`,default:.45,description:`Vector similarity threshold below which ER fallback triggers.`,group:`enterprise-bridge`}],m=[{key:`AIKIT_TRANSPORT`,type:`string`,default:`stdio`,description:`MCP transport mode.`,group:`transport`,enum:[`stdio`,`http`],defaultScope:`workspace`},{key:`AIKIT_PORT`,type:`string`,default:`3210`,description:`HTTP port when transport = http.`,group:`transport`,defaultScope:`workspace`},{key:`AIKIT_CORS_ORIGIN`,type:`string`,description:`CORS Access-Control-Allow-Origin header for HTTP mode.`,group:`transport`,defaultScope:`workspace`},{key:`AIKIT_CONFIG_PATH`,type:`string`,description:`Override path to aikit.config.json.`,group:`paths`,defaultScope:`workspace`},{key:`AIKIT_WORKSPACE_ROOT`,type:`string`,description:`Override workspace root used when no config file is present.`,group:`paths`,defaultScope:`workspace`},{key:`AIKIT_GLOBAL_DATA_DIR`,type:`string`,description:`Override global data directory (default: ~/.aikit).`,group:`paths`,defaultScope:`global`},{key:`AIKIT_INDEX_MODE`,type:`string`,description:`Override config indexMode.`,group:`indexing`,enum:[`auto`,`manual`,`smart`],defaultScope:`workspace`},{key:`AIKIT_AUTO_INDEX`,type:`string`,description:`Legacy boolean override. Prefer AIKIT_INDEX_MODE.`,group:`indexing`,enum:[`true`,`false`],defaultScope:`workspace`},{key:`AIKIT_TOOLSET`,type:`string`,description:`Override active tool profile.`,group:`general`,defaultScope:`workspace`},{key:`AIKIT_BROWSER_DEFAULT_MODE`,type:`string`,default:`ui`,description:`Default browser launch mode for browser_* tools.`,group:`browser`,enum:[`ui`,`headless`,`panel`],defaultScope:`workspace`},{key:`AIKIT_BROWSER_PATH`,type:`string`,description:`Optional Playwright browser download path override.`,group:`browser`,defaultScope:`workspace`},{key:`AIKIT_BROWSER_IDLE_MINUTES`,type:`string`,default:`10`,description:`Idle shutdown timeout in minutes for the shared browser runtime.`,group:`browser`,defaultScope:`workspace`},{key:`AIKIT_BROWSER_EVAL_TIMEOUT_MS`,type:`string`,default:`5000`,description:`Default browser_eval timeout in milliseconds.`,group:`browser`,defaultScope:`workspace`},{key:`AIKIT_SEARCH_DEADLINE_MS`,type:`string`,default:`10000`,description:`Multi-provider web search deadline (milliseconds).`,group:`search-providers`,defaultScope:`global`},{key:`SEARXNG_URL`,type:`string`,description:`Optional SearXNG instance URL for the web_search tool.`,group:`search-providers`,defaultScope:`global`},{key:`GOOGLE_API_KEY`,type:`secret`,description:`Google Custom Search API key.`,group:`search-providers`,defaultScope:`global`},{key:`GOOGLE_CSE_ID`,type:`string`,description:`Google Custom Search Engine ID.`,group:`search-providers`,defaultScope:`global`},{key:`BRAVE_API_KEY`,type:`secret`,description:`Brave Search API key.`,group:`search-providers`,defaultScope:`global`},{key:`BING_API_KEY`,type:`secret`,description:`Bing Web Search API key.`,group:`search-providers`,defaultScope:`global`}];function h(e){return m.find(t=>t.key===e)}function g(e){let t=h(e);return t?t.type===`secret`:/(_KEY|_TOKEN|_SECRET|_PASSWORD|_PASS|_PWD)$/i.test(e)}const _=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function v(e){let t=e.replace(/^\s+/,``);if(t.startsWith(`"`)){let e=1,n=``;for(;e<t.length;){let r=t[e];if(r===`\\`&&e+1<t.length){let r=t[e+1];r===`n`?n+=`
|
|
3
|
+
`:r===`r`?n+=`\r`:r===`t`?n+=` `:n+=r,e+=2;continue}if(r===`"`){let r=t.slice(e+1),i=r.indexOf(`#`),a=i===-1?``:r.slice(i);return{value:n,quoted:!0,inlineComment:a}}n+=r,e+=1}return{value:t.slice(1),quoted:!0,inlineComment:``}}let n=t.match(/(\s+#.*)$/);return n&&n.index!==void 0?{value:t.slice(0,n.index).trimEnd(),quoted:!1,inlineComment:n[1].trimStart()}:{value:t.trimEnd(),quoted:!1,inlineComment:``}}function y(e){let t;t=e.quoted||/[\s#"']/.test(e.value)||e.value.includes(`
|
|
4
|
+
`)||e.value.length===0?`"${e.value.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}"`:e.value;let n=e.inlineComment?` ${e.inlineComment}`:``;return`${e.key}=${t}${n}`}function b(e){let t=[],n=e.split(/\r?\n/),r=e.endsWith(`
|
|
5
|
+
`)?n.slice(0,-1):n;for(let e of r){let n=e.match(_);if(!n){t.push({kind:`raw`,text:e});continue}let r=n[1],{value:i,quoted:a,inlineComment:o}=v(n[2]);t.push({kind:`assign`,key:r,value:i,quoted:a,inlineComment:o})}return{lines:t}}function x(e){return`${e.lines.map(e=>e.kind===`assign`?y(e):e.text).join(`
|
|
6
|
+
`)}\n`}function S(e){let t={};for(let n of e.lines)n.kind===`assign`&&(t[n.key]=n.value);return t}function C(e,t,n){let r=e.lines.map(e=>e.kind===`assign`&&e.key===t?{...e,value:n}:e);return e.lines.some(e=>e.kind===`assign`&&e.key===t)||r.push({kind:`assign`,key:t,value:n,quoted:!1,inlineComment:``}),{lines:r}}function w(e,t){return{lines:e.lines.filter(e=>!(e.kind===`assign`&&e.key===t))}}function T(e){return u(e,`.env`)}function E(){return u(t(),`global.env`)}function D(e,t){return e===`workspace`?T(t):E()}function O(e){return i(e)?b(o(e,`utf-8`)):{lines:[]}}function k(e,t){let n=l(e);i(n)||a(n,{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;c(r,x(t),{encoding:`utf-8`,mode:384}),s(r,e)}function A(e,t,n={}){let r=D(e,t),a=i(r),o=S(O(r)),s={};for(let[e,t]of Object.entries(o))s[e]=n.reveal||!g(e)?t:j(t);return{scope:e,path:r,exists:a,vars:s}}function j(e){return e.length===0?``:e.length<=4?`•`.repeat(e.length):`${e.slice(0,2)}${`•`.repeat(Math.min(e.length-4,12))}${e.slice(-2)}`}function M(){return process.env.AIKIT_WORKSPACE_ROOT??r()}function N(){return n()?`user`:`workspace`}function P(){let e=t();return i(e)||a(e,{recursive:!0}),e}var F=class extends Error{details;constructor(e,t){super(e),this.name=`ConfigValidationError`,this.details=t}};function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function L(e=M()){let t=process.env.AIKIT_CONFIG_PATH;return t?u(t):u(e,`aikit.config.json`)}function R(e){if(!i(e))return null;let t=o(e,`utf-8`),n=JSON.parse(t);if(!I(n))throw new F(`config-not-object`,[`Config file must contain a JSON object at the root.`]);return n}function z(e,t){let n=l(e);i(n)||a(n,{recursive:!0});let r=`${JSON.stringify(t,null,2)}\n`,o=`${e}.${process.pid}.${Date.now()}.tmp`;c(o,r,{encoding:`utf-8`}),s(o,e)}function B(e){return e.length===0?[]:e.split(`.`)}function V(e,t,n){let r=B(t);if(r.length===0)throw new F(`invalid-path`,[`Patch path must not be empty.`]);let i={...e},a=i;for(let e=0;e<r.length-1;e+=1){let t=r[e],n=r[e+1],i=/^\d+$/.test(n);if(Array.isArray(a)){let n=Number(t);if(!Number.isInteger(n))throw new F(`invalid-path`,[`Path segment "${t}" must be an integer index for array at depth ${e}.`]);let r=a[n];if(i){let e=Array.isArray(r)?[...r]:[];a[n]=e,a=e}else{let e=I(r)?{...r}:{};a[n]=e,a=e}continue}let o=a[t];if(i){let e=Array.isArray(o)?[...o]:[];a[t]=e,a=e}else{let e=I(o)?{...o}:{};a[t]=e,a=e}}let o=r[r.length-1];if(Array.isArray(a)){let e=Number(o);if(!Number.isInteger(e))throw new F(`invalid-path`,[`Path segment "${o}" must be an integer index for array.`]);a[e]=n}else a[o]=n;return i}function H(e,t){let n=B(t);if(n.length===0)throw new F(`invalid-path`,[`Patch path must not be empty.`]);let r={...e},i=r;for(let e=0;e<n.length-1;e+=1){let t=n[e];if(Array.isArray(i)){let e=Number(t);if(!Number.isInteger(e))return r;let n=i[e];if(!I(n)&&!Array.isArray(n))return r;let a=Array.isArray(n)?[...n]:{...n};i[e]=a,i=a;continue}let a=i[t];if(!I(a)&&!Array.isArray(a))return r;let o=Array.isArray(a)?[...a]:{...a};i[t]=o,i=o}let a=n[n.length-1];if(Array.isArray(i)){let e=Number(a);Number.isInteger(e)&&i.splice(e,1)}else delete i[a];return r}function U(e,t){let n=e;for(let e of t)n=e.op===`set`?V(n,e.path,e.value):H(n,e.path);return n}function W(e){let t=[];if(`autoIndex`in e&&e.autoIndex!==void 0&&typeof e.autoIndex!=`boolean`&&t.push(`autoIndex must be a boolean.`),`serverName`in e&&e.serverName!==void 0&&typeof e.serverName!=`string`&&t.push(`serverName must be a string.`),`toolPrefix`in e&&e.toolPrefix!==void 0&&typeof e.toolPrefix!=`string`&&t.push(`toolPrefix must be a string.`),`indexMode`in e&&e.indexMode!==void 0&&![`auto`,`manual`,`smart`].includes(e.indexMode)&&t.push(`indexMode must be one of: auto, manual, smart.`),(!Array.isArray(e.sources)||e.sources.length===0)&&t.push(`sources must be a non-empty array.`),`indexing`in e&&e.indexing!==void 0)if(!I(e.indexing))t.push(`indexing must be an object.`);else for(let n of[`chunkSize`,`chunkOverlap`,`minChunkSize`,`concurrency`]){let r=e.indexing[n];r!==void 0&&(typeof r!=`number`||!Number.isFinite(r)||r<=0)&&t.push(`indexing.${n} must be a positive number.`)}return`store`in e&&e.store!==void 0&&(I(e.store)?(typeof e.store.backend!=`string`&&t.push(`store.backend must be a string.`),typeof e.store.path!=`string`&&t.push(`store.path must be a string.`)):t.push(`store must be an object.`)),t}const G=d.object({ops:d.array(d.object({op:d.enum([`set`,`unset`]),path:d.string().min(1),value:d.unknown().optional()})).min(1)}),K=d.string().min(1).regex(/^[A-Za-z_][A-Za-z0-9_]*$/,`Invalid env key`),q=d.object({value:d.string(),scope:d.enum([`workspace`,`global`])}),J=d.enum([`workspace`,`global`]);function Y(e,t,n,r){e.status(t).json({error:n,details:r})}function X(e){let t=f(),n=e.workspaceRoot??M;return t.get(`/status`,(t,r)=>{let a=n(),o=L(a);r.json({mode:N(),cwd:(()=>{try{return process.cwd()}catch{return`<unavailable>`}})(),workspaceRoot:a,configPath:o,configExists:i(o),globalDataDir:P(),envPaths:{workspace:T(a),global:E()},mcp:e.mcpInfo?.()??{transport:`http`,pid:process.pid,startedAt:new Date(0).toISOString()}})}),t.get(`/schema`,(e,t)=>{t.json({config:p,env:m})}),t.get(`/config`,(e,t)=>{let r=L(n());try{let e=R(r);t.json({path:r,exists:e!==null,content:e??{}})}catch(e){if(e instanceof F){Y(t,400,e.message,e.details);return}Y(t,500,`config-read-failed`,e instanceof Error?e.message:String(e))}}),t.patch(`/config`,(t,r)=>{let i=G.safeParse(t.body);if(!i.success){Y(r,400,`invalid-body`,i.error.issues);return}let a=L(n()),o;try{o=R(a)??{}}catch(e){if(e instanceof F){Y(r,400,e.message,e.details);return}Y(r,500,`config-read-failed`,e instanceof Error?e.message:String(e));return}let s;try{s=U(o,i.data.ops)}catch(e){if(e instanceof F){Y(r,400,e.message,e.details);return}Y(r,400,`patch-failed`,e instanceof Error?e.message:String(e));return}let c=W(s);if(c.length>0){Y(r,400,`invalid-config`,c);return}try{z(a,s)}catch(e){Y(r,500,`config-write-failed`,e instanceof Error?e.message:String(e));return}e.log.info(`Settings: config updated`,{path:a,ops:i.data.ops.length}),r.json({path:a,content:s,restartRecommended:!0})}),t.get(`/env`,(t,r)=>{let i=t.query.reveal===`true`||t.query.reveal===`1`;i&&e.log.warn(`Settings: env values revealed`,{ip:t.ip??`unknown`});let a=n();r.json({workspace:A(`workspace`,a,{reveal:i}),global:A(`global`,a,{reveal:i}),processOverrides:Object.keys(process.env).filter(e=>e.startsWith(`AIKIT_`)||/^(SEARXNG_URL|GOOGLE_|BRAVE_|BING_)/.test(e)).sort()})}),t.put(`/env/:key`,(t,r)=>{let i=K.safeParse(t.params.key);if(!i.success){Y(r,400,`invalid-key`,i.error.issues);return}let a=q.safeParse(t.body);if(!a.success){Y(r,400,`invalid-body`,a.error.issues);return}let o=a.data.scope,s=D(o,n());try{k(s,C(O(s),i.data,a.data.value)),e.log.info(`Settings: env set`,{key:i.data,scope:o,path:s}),r.json({ok:!0,scope:o,path:s,restartRecommended:!0})}catch(e){Y(r,500,`env-write-failed`,e instanceof Error?e.message:String(e))}}),t.delete(`/env/:key`,(t,r)=>{let i=K.safeParse(t.params.key);if(!i.success){Y(r,400,`invalid-key`,i.error.issues);return}let a=J.safeParse(t.query.scope);if(!a.success){Y(r,400,`invalid-scope`,a.error.issues);return}let o=a.data,s=D(o,n());try{k(s,w(O(s),i.data)),e.log.info(`Settings: env unset`,{key:i.data,scope:o,path:s}),r.json({ok:!0,scope:o,path:s,restartRecommended:!0})}catch(e){Y(r,500,`env-write-failed`,e instanceof Error?e.message:String(e))}}),t}export{X as createSettingsRouter};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{DEFAULT_SERVER_NAME as e,getGlobalDataDir as t,isUserInstalled as n,safeCwdOrHome as r}from"../../core/dist/index.js";import{existsSync as i,mkdirSync as a,readFileSync as o,renameSync as s,writeFileSync as c}from"node:fs";import{dirname as l,resolve as u}from"node:path";import{z as d}from"zod";import{Router as f}from"express";const p=[{key:`serverName`,type:`string`,default:e,description:`MCP server name advertised to clients.`,group:`general`,requiresRestart:!0},{key:`toolPrefix`,type:`string`,default:``,description:`Prefix prepended to every MCP tool name (e.g. "aikit_").`,group:`general`,requiresRestart:!0},{key:`toolProfile`,type:`string`,default:`full`,description:`Active tool profile.`,group:`general`,enum:[`full`,`safe`,`research`,`minimal`,`discovery`],requiresRestart:!0},{key:`autoIndex`,type:`boolean`,default:!1,description:`Deprecated. Prefer indexMode. true → auto, false → manual.`,group:`indexing`},{key:`indexMode`,type:`string`,default:`smart`,description:`Indexing strategy. auto = full on startup, manual = on demand, smart = on-demand + idle.`,group:`indexing`,enum:[`auto`,`manual`,`smart`]},{key:`sources`,type:`array`,description:`Source roots to index. Each entry has { path, excludePatterns }.`,group:`indexing`,requiresRestart:!0},{key:`indexing.chunkSize`,type:`number`,default:1500,description:`Maximum chunk size in characters.`,group:`indexing`},{key:`indexing.chunkOverlap`,type:`number`,default:200,description:`Overlap between adjacent chunks.`,group:`indexing`},{key:`indexing.minChunkSize`,type:`number`,default:100,description:`Minimum chunk size before merging into the next chunk.`,group:`indexing`},{key:`indexing.concurrency`,type:`number`,description:`Max files processed concurrently. Defaults to half of CPU cores.`,group:`indexing`},{key:`embedding.model`,type:`string`,default:`mixedbread-ai/mxbai-embed-large-v1`,description:`Embedding model identifier.`,group:`embedding`,requiresRestart:!0},{key:`embedding.dimensions`,type:`number`,default:1024,description:`Embedding vector dimensions. Must match the model.`,group:`embedding`,requiresRestart:!0},{key:`store.backend`,type:`string`,default:`sqlite-vec`,description:`Vector store backend (sqlite-vec | lancedb).`,group:`store`,requiresRestart:!0},{key:`store.path`,type:`string`,description:`Filesystem path for the vector store.`,group:`store`,requiresRestart:!0},{key:`curated.path`,type:`string`,description:`Path to curated knowledge directory.`,group:`store`,requiresRestart:!0},{key:`onboardDir`,type:`string`,description:`Directory for onboard / produce_knowledge output.`,group:`store`,requiresRestart:!0},{key:`stateDir`,type:`string`,description:`Directory for session state (stash, checkpoints, etc.).`,group:`store`,requiresRestart:!0},{key:`er.enabled`,type:`boolean`,default:!1,description:`Enable enterprise RAG bridge integration.`,group:`enterprise-bridge`,requiresRestart:!0},{key:`er.baseUrl`,type:`string`,description:`Base URL of the ER API.`,group:`enterprise-bridge`,requiresRestart:!0},{key:`er.timeoutMs`,type:`number`,default:5e3,description:`ER request timeout in milliseconds.`,group:`enterprise-bridge`},{key:`er.fallbackThreshold`,type:`number`,default:.45,description:`Vector similarity threshold below which ER fallback triggers.`,group:`enterprise-bridge`}],m=[{key:`AIKIT_TRANSPORT`,type:`string`,default:`stdio`,description:`MCP transport mode.`,group:`transport`,enum:[`stdio`,`http`],defaultScope:`workspace`},{key:`AIKIT_PORT`,type:`string`,default:`3210`,description:`HTTP port when transport = http.`,group:`transport`,defaultScope:`workspace`},{key:`AIKIT_CORS_ORIGIN`,type:`string`,description:`CORS Access-Control-Allow-Origin header for HTTP mode.`,group:`transport`,defaultScope:`workspace`},{key:`AIKIT_CONFIG_PATH`,type:`string`,description:`Override path to aikit.config.json.`,group:`paths`,defaultScope:`workspace`},{key:`AIKIT_WORKSPACE_ROOT`,type:`string`,description:`Override workspace root used when no config file is present.`,group:`paths`,defaultScope:`workspace`},{key:`AIKIT_GLOBAL_DATA_DIR`,type:`string`,description:`Override global data directory (default: ~/.aikit).`,group:`paths`,defaultScope:`global`},{key:`AIKIT_INDEX_MODE`,type:`string`,description:`Override config indexMode.`,group:`indexing`,enum:[`auto`,`manual`,`smart`],defaultScope:`workspace`},{key:`AIKIT_AUTO_INDEX`,type:`string`,description:`Legacy boolean override. Prefer AIKIT_INDEX_MODE.`,group:`indexing`,enum:[`true`,`false`],defaultScope:`workspace`},{key:`AIKIT_TOOLSET`,type:`string`,description:`Override active tool profile.`,group:`general`,defaultScope:`workspace`},{key:`AIKIT_BROWSER_DEFAULT_MODE`,type:`string`,default:`ui`,description:`Default browser launch mode for browser_* tools.`,group:`browser`,enum:[`ui`,`headless`,`panel`],defaultScope:`workspace`},{key:`AIKIT_BROWSER_PATH`,type:`string`,description:`Optional Playwright browser download path override.`,group:`browser`,defaultScope:`workspace`},{key:`AIKIT_BROWSER_IDLE_MINUTES`,type:`string`,default:`10`,description:`Idle shutdown timeout in minutes for the shared browser runtime.`,group:`browser`,defaultScope:`workspace`},{key:`AIKIT_BROWSER_EVAL_TIMEOUT_MS`,type:`string`,default:`5000`,description:`Default browser_eval timeout in milliseconds.`,group:`browser`,defaultScope:`workspace`},{key:`AIKIT_SEARCH_DEADLINE_MS`,type:`string`,default:`10000`,description:`Multi-provider web search deadline (milliseconds).`,group:`search-providers`,defaultScope:`global`},{key:`SEARXNG_URL`,type:`string`,description:`Optional SearXNG instance URL for the web_search tool.`,group:`search-providers`,defaultScope:`global`},{key:`GOOGLE_API_KEY`,type:`secret`,description:`Google Custom Search API key.`,group:`search-providers`,defaultScope:`global`},{key:`GOOGLE_CSE_ID`,type:`string`,description:`Google Custom Search Engine ID.`,group:`search-providers`,defaultScope:`global`},{key:`BRAVE_API_KEY`,type:`secret`,description:`Brave Search API key.`,group:`search-providers`,defaultScope:`global`},{key:`BING_API_KEY`,type:`secret`,description:`Bing Web Search API key.`,group:`search-providers`,defaultScope:`global`}];function h(e){return m.find(t=>t.key===e)}function g(e){let t=h(e);return t?t.type===`secret`:/(_KEY|_TOKEN|_SECRET|_PASSWORD|_PASS|_PWD)$/i.test(e)}const _=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=(.*)$/;function v(e){let t=e.replace(/^\s+/,``);if(t.startsWith(`"`)){let e=1,n=``;for(;e<t.length;){let r=t[e];if(r===`\\`&&e+1<t.length){let r=t[e+1];r===`n`?n+=`
|
|
2
|
+
`:r===`r`?n+=`\r`:r===`t`?n+=` `:n+=r,e+=2;continue}if(r===`"`){let r=t.slice(e+1),i=r.indexOf(`#`),a=i===-1?``:r.slice(i);return{value:n,quoted:!0,inlineComment:a}}n+=r,e+=1}return{value:t.slice(1),quoted:!0,inlineComment:``}}let n=t.match(/(\s+#.*)$/);return n&&n.index!==void 0?{value:t.slice(0,n.index).trimEnd(),quoted:!1,inlineComment:n[1].trimStart()}:{value:t.trimEnd(),quoted:!1,inlineComment:``}}function y(e){let t;t=e.quoted||/[\s#"']/.test(e.value)||e.value.includes(`
|
|
3
|
+
`)||e.value.length===0?`"${e.value.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`)}"`:e.value;let n=e.inlineComment?` ${e.inlineComment}`:``;return`${e.key}=${t}${n}`}function b(e){let t=[],n=e.split(/\r?\n/),r=e.endsWith(`
|
|
4
|
+
`)?n.slice(0,-1):n;for(let e of r){let n=e.match(_);if(!n){t.push({kind:`raw`,text:e});continue}let r=n[1],{value:i,quoted:a,inlineComment:o}=v(n[2]);t.push({kind:`assign`,key:r,value:i,quoted:a,inlineComment:o})}return{lines:t}}function x(e){return`${e.lines.map(e=>e.kind===`assign`?y(e):e.text).join(`
|
|
5
|
+
`)}\n`}function S(e){let t={};for(let n of e.lines)n.kind===`assign`&&(t[n.key]=n.value);return t}function C(e,t,n){let r=e.lines.map(e=>e.kind===`assign`&&e.key===t?{...e,value:n}:e);return e.lines.some(e=>e.kind===`assign`&&e.key===t)||r.push({kind:`assign`,key:t,value:n,quoted:!1,inlineComment:``}),{lines:r}}function w(e,t){return{lines:e.lines.filter(e=>!(e.kind===`assign`&&e.key===t))}}function T(e){return u(e,`.env`)}function E(){return u(t(),`global.env`)}function D(e,t){return e===`workspace`?T(t):E()}function O(e){return i(e)?b(o(e,`utf-8`)):{lines:[]}}function k(e,t){let n=l(e);i(n)||a(n,{recursive:!0});let r=`${e}.${process.pid}.${Date.now()}.tmp`;c(r,x(t),{encoding:`utf-8`,mode:384}),s(r,e)}function A(e,t,n={}){let r=D(e,t),a=i(r),o=S(O(r)),s={};for(let[e,t]of Object.entries(o))s[e]=n.reveal||!g(e)?t:j(t);return{scope:e,path:r,exists:a,vars:s}}function j(e){return e.length===0?``:e.length<=4?`•`.repeat(e.length):`${e.slice(0,2)}${`•`.repeat(Math.min(e.length-4,12))}${e.slice(-2)}`}function M(){return process.env.AIKIT_WORKSPACE_ROOT??r()}function N(){return n()?`user`:`workspace`}function P(){let e=t();return i(e)||a(e,{recursive:!0}),e}var F=class extends Error{details;constructor(e,t){super(e),this.name=`ConfigValidationError`,this.details=t}};function I(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function L(e=M()){let t=process.env.AIKIT_CONFIG_PATH;return t?u(t):u(e,`aikit.config.json`)}function R(e){if(!i(e))return null;let t=o(e,`utf-8`),n=JSON.parse(t);if(!I(n))throw new F(`config-not-object`,[`Config file must contain a JSON object at the root.`]);return n}function z(e,t){let n=l(e);i(n)||a(n,{recursive:!0});let r=`${JSON.stringify(t,null,2)}\n`,o=`${e}.${process.pid}.${Date.now()}.tmp`;c(o,r,{encoding:`utf-8`}),s(o,e)}function B(e){return e.length===0?[]:e.split(`.`)}function V(e,t,n){let r=B(t);if(r.length===0)throw new F(`invalid-path`,[`Patch path must not be empty.`]);let i={...e},a=i;for(let e=0;e<r.length-1;e+=1){let t=r[e],n=r[e+1],i=/^\d+$/.test(n);if(Array.isArray(a)){let n=Number(t);if(!Number.isInteger(n))throw new F(`invalid-path`,[`Path segment "${t}" must be an integer index for array at depth ${e}.`]);let r=a[n];if(i){let e=Array.isArray(r)?[...r]:[];a[n]=e,a=e}else{let e=I(r)?{...r}:{};a[n]=e,a=e}continue}let o=a[t];if(i){let e=Array.isArray(o)?[...o]:[];a[t]=e,a=e}else{let e=I(o)?{...o}:{};a[t]=e,a=e}}let o=r[r.length-1];if(Array.isArray(a)){let e=Number(o);if(!Number.isInteger(e))throw new F(`invalid-path`,[`Path segment "${o}" must be an integer index for array.`]);a[e]=n}else a[o]=n;return i}function H(e,t){let n=B(t);if(n.length===0)throw new F(`invalid-path`,[`Patch path must not be empty.`]);let r={...e},i=r;for(let e=0;e<n.length-1;e+=1){let t=n[e];if(Array.isArray(i)){let e=Number(t);if(!Number.isInteger(e))return r;let n=i[e];if(!I(n)&&!Array.isArray(n))return r;let a=Array.isArray(n)?[...n]:{...n};i[e]=a,i=a;continue}let a=i[t];if(!I(a)&&!Array.isArray(a))return r;let o=Array.isArray(a)?[...a]:{...a};i[t]=o,i=o}let a=n[n.length-1];if(Array.isArray(i)){let e=Number(a);Number.isInteger(e)&&i.splice(e,1)}else delete i[a];return r}function U(e,t){let n=e;for(let e of t)n=e.op===`set`?V(n,e.path,e.value):H(n,e.path);return n}function W(e){let t=[];if(`autoIndex`in e&&e.autoIndex!==void 0&&typeof e.autoIndex!=`boolean`&&t.push(`autoIndex must be a boolean.`),`serverName`in e&&e.serverName!==void 0&&typeof e.serverName!=`string`&&t.push(`serverName must be a string.`),`toolPrefix`in e&&e.toolPrefix!==void 0&&typeof e.toolPrefix!=`string`&&t.push(`toolPrefix must be a string.`),`indexMode`in e&&e.indexMode!==void 0&&![`auto`,`manual`,`smart`].includes(e.indexMode)&&t.push(`indexMode must be one of: auto, manual, smart.`),(!Array.isArray(e.sources)||e.sources.length===0)&&t.push(`sources must be a non-empty array.`),`indexing`in e&&e.indexing!==void 0)if(!I(e.indexing))t.push(`indexing must be an object.`);else for(let n of[`chunkSize`,`chunkOverlap`,`minChunkSize`,`concurrency`]){let r=e.indexing[n];r!==void 0&&(typeof r!=`number`||!Number.isFinite(r)||r<=0)&&t.push(`indexing.${n} must be a positive number.`)}return`store`in e&&e.store!==void 0&&(I(e.store)?(typeof e.store.backend!=`string`&&t.push(`store.backend must be a string.`),typeof e.store.path!=`string`&&t.push(`store.path must be a string.`)):t.push(`store must be an object.`)),t}const G=d.object({ops:d.array(d.object({op:d.enum([`set`,`unset`]),path:d.string().min(1),value:d.unknown().optional()})).min(1)}),K=d.string().min(1).regex(/^[A-Za-z_][A-Za-z0-9_]*$/,`Invalid env key`),q=d.object({value:d.string(),scope:d.enum([`workspace`,`global`])}),J=d.enum([`workspace`,`global`]);function Y(e,t,n,r){e.status(t).json({error:n,details:r})}function X(e){let t=f(),n=e.workspaceRoot??M;return t.get(`/status`,(t,r)=>{let a=n(),o=L(a);r.json({mode:N(),cwd:(()=>{try{return process.cwd()}catch{return`<unavailable>`}})(),workspaceRoot:a,configPath:o,configExists:i(o),globalDataDir:P(),envPaths:{workspace:T(a),global:E()},mcp:e.mcpInfo?.()??{transport:`http`,pid:process.pid,startedAt:new Date(0).toISOString()}})}),t.get(`/schema`,(e,t)=>{t.json({config:p,env:m})}),t.get(`/config`,(e,t)=>{let r=L(n());try{let e=R(r);t.json({path:r,exists:e!==null,content:e??{}})}catch(e){if(e instanceof F){Y(t,400,e.message,e.details);return}Y(t,500,`config-read-failed`,e instanceof Error?e.message:String(e))}}),t.patch(`/config`,(t,r)=>{let i=G.safeParse(t.body);if(!i.success){Y(r,400,`invalid-body`,i.error.issues);return}let a=L(n()),o;try{o=R(a)??{}}catch(e){if(e instanceof F){Y(r,400,e.message,e.details);return}Y(r,500,`config-read-failed`,e instanceof Error?e.message:String(e));return}let s;try{s=U(o,i.data.ops)}catch(e){if(e instanceof F){Y(r,400,e.message,e.details);return}Y(r,400,`patch-failed`,e instanceof Error?e.message:String(e));return}let c=W(s);if(c.length>0){Y(r,400,`invalid-config`,c);return}try{z(a,s)}catch(e){Y(r,500,`config-write-failed`,e instanceof Error?e.message:String(e));return}e.log.info(`Settings: config updated`,{path:a,ops:i.data.ops.length}),r.json({path:a,content:s,restartRecommended:!0})}),t.get(`/env`,(t,r)=>{let i=t.query.reveal===`true`||t.query.reveal===`1`;i&&e.log.warn(`Settings: env values revealed`,{ip:t.ip??`unknown`});let a=n();r.json({workspace:A(`workspace`,a,{reveal:i}),global:A(`global`,a,{reveal:i}),processOverrides:Object.keys(process.env).filter(e=>e.startsWith(`AIKIT_`)||/^(SEARXNG_URL|GOOGLE_|BRAVE_|BING_)/.test(e)).sort()})}),t.put(`/env/:key`,(t,r)=>{let i=K.safeParse(t.params.key);if(!i.success){Y(r,400,`invalid-key`,i.error.issues);return}let a=q.safeParse(t.body);if(!a.success){Y(r,400,`invalid-body`,a.error.issues);return}let o=a.data.scope,s=D(o,n());try{k(s,C(O(s),i.data,a.data.value)),e.log.info(`Settings: env set`,{key:i.data,scope:o,path:s}),r.json({ok:!0,scope:o,path:s,restartRecommended:!0})}catch(e){Y(r,500,`env-write-failed`,e instanceof Error?e.message:String(e))}}),t.delete(`/env/:key`,(t,r)=>{let i=K.safeParse(t.params.key);if(!i.success){Y(r,400,`invalid-key`,i.error.issues);return}let a=J.safeParse(t.query.scope);if(!a.success){Y(r,400,`invalid-scope`,a.error.issues);return}let o=a.data,s=D(o,n());try{k(s,w(O(s),i.data)),e.log.info(`Settings: env unset`,{key:i.data,scope:o,path:s}),r.json({ok:!0,scope:o,path:s,restartRecommended:!0})}catch(e){Y(r,500,`env-write-failed`,e instanceof Error?e.message:String(e))}}),t}export{X as createSettingsRouter};
|