@vpxa/aikit 0.1.359 → 0.1.361
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/analyzers/dist/index.d.ts +1 -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-d2UQHjpi.js → templates-CNDa9H4e.js} +25 -25
- package/packages/core/dist/index.d.ts +46 -3
- 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 +10 -10
- 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/observations-CfglxBMB.js +6 -0
- package/packages/server/dist/observations-CrQU_HVm.js +5 -0
- package/packages/server/dist/prelude-BIJWSWyX.js +2 -0
- package/packages/server/dist/prelude-Dxc3G0Q2.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-BX1qQuXx.js +2 -0
- package/packages/server/dist/sampling-QHtj6UuO.js +1 -0
- package/packages/server/dist/{server-CICqmfQ_.js → server-CiPwrtSl.js} +171 -171
- package/packages/server/dist/{server-BZVPmRGV.js → server-e0mFUKvp.js} +172 -170
- package/packages/server/dist/{server-http-CPU9_eVT.js → server-http-B3dZd6bx.js} +1 -1
- package/packages/server/dist/{server-http-D3DK1H19.js → server-http-CzScS-EZ.js} +1 -1
- package/packages/server/dist/{server-stdio-BRKxFWyO.js → server-stdio-COkJ2pX9.js} +1 -1
- package/packages/server/dist/{server-stdio-l8I0RW4l.js → server-stdio-DmsOjBSR.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/_shared.mjs +7 -6
- package/scaffold/dist/adapters/claude-code.mjs +7 -7
- package/scaffold/dist/adapters/claude-desktop.mjs +7 -0
- package/scaffold/dist/adapters/copilot.mjs +1 -1
- package/scaffold/dist/adapters/gemini.mjs +6 -6
- package/scaffold/dist/adapters/hermes-agent.mjs +1 -1
- package/scaffold/dist/adapters/hermes.mjs +5 -5
- package/scaffold/dist/adapters/hooks.mjs +1 -1
- package/scaffold/dist/adapters/opencode.mjs +7 -7
- package/scaffold/dist/adapters/zed.mjs +1 -1
- package/scaffold/dist/definitions/exec-hooks.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 -0
- 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-Cvys5TD4.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-CfXBHLpw.js +0 -1
- package/packages/server/dist/prelude-D33q42vQ.js +0 -2
- package/packages/server/dist/routes-9KnBpwfe.js +0 -6
- package/packages/server/dist/routes-B8hTXXR8.js +0 -5
- package/packages/server/dist/sampling-Cs9MoNYX.js +0 -2
- package/packages/server/dist/sampling-DFogBKrL.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var AnnotationInit=(()=>{var N=Object.defineProperty;var O=(
|
|
1
|
+
"use strict";var AnnotationInit=(()=>{var N=Object.defineProperty;var O=(d,t,e)=>t in d?N(d,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):d[t]=e;var s=(d,t,e)=>O(d,typeof t!="symbol"?t+"":t,e);var C=`
|
|
2
2
|
.action-bar {
|
|
3
3
|
flex-shrink: 0;
|
|
4
4
|
position: sticky;
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
.action-bar .bk-multi-select {
|
|
33
33
|
max-width: 10rem;
|
|
34
34
|
}
|
|
35
|
-
`;function b(
|
|
35
|
+
`;function b(d,t){if(document.getElementById(d))return;let e=document.createElement("style");e.id=d,e.textContent=t,document.head.appendChild(e)}var M=document.createElement("div");function g(d){return M.textContent=d,M.innerHTML}var H="aikit-annotation-popover",B=`
|
|
36
36
|
.cp-backdrop {
|
|
37
37
|
position: fixed;
|
|
38
38
|
top: 0;
|
|
@@ -130,7 +130,7 @@
|
|
|
130
130
|
.cp-btn--remove:hover {
|
|
131
131
|
background: var(--dt-annotation-deletion-bg);
|
|
132
132
|
}
|
|
133
|
-
`,v=class{constructor(t,e){
|
|
133
|
+
`,v=class{constructor(t,e){s(this,"el");s(this,"textarea");s(this,"result");s(this,"backdrop");s(this,"options");this.result=t,this.options=e,b(H,B),this.backdrop=document.createElement("div"),this.backdrop.className="cp-backdrop",this.el=document.createElement("div"),this.el.className="cp-popover",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Feedback on selection"),this.el.innerHTML=`
|
|
134
134
|
<div class="cp-header">Feedback</div>
|
|
135
135
|
<div class="cp-excerpt">${this.escapeText(t.text)}</div>
|
|
136
136
|
<textarea class="cp-textarea" placeholder="Add a comment (optional)..." aria-label="Comment text"></textarea>
|
|
@@ -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"),a=this.el.querySelector(".cp-btn--remove"),r=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),a.addEventListener("click",()=>this.handleRemove()),r.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",o=>this.handleKeyDown(o)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",o=>{if(o.key!=="Tab")return;let i=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let
|
|
142
|
+
`,this.textarea=this.el.querySelector(".cp-textarea");let n=this.el.querySelector(".cp-btn--comment"),a=this.el.querySelector(".cp-btn--remove"),r=this.el.querySelector(".cp-btn--cancel");this.backdrop.addEventListener("click",()=>this.handleCancel()),n.addEventListener("click",()=>this.handleComment()),a.addEventListener("click",()=>this.handleRemove()),r.addEventListener("click",()=>this.handleCancel()),this.textarea.addEventListener("keydown",o=>this.handleKeyDown(o)),document.body.appendChild(this.backdrop),document.body.appendChild(this.el),this.positionNearSelection(),this.textarea.focus(),this.el.addEventListener("keydown",o=>{if(o.key!=="Tab")return;let i=this.el.querySelectorAll('button, textarea, [tabindex]:not([tabindex="-1"])');if(i.length===0)return;let l=i[0],c=i[i.length-1];o.shiftKey&&document.activeElement===l?(o.preventDefault(),c.focus()):!o.shiftKey&&document.activeElement===c&&(o.preventDefault(),l.focus())})}destroy(){this.backdrop.remove(),this.el.remove()}escapeText(t){let e=document.createElement("div");return e.textContent=t,e.innerHTML}positionNearSelection(){let t=this.result.range.getBoundingClientRect(),e=window.scrollX,n=window.scrollY,a=this.el.offsetWidth||320,r=this.el.offsetHeight||260,o=8,i=t.left+e+t.width/2-a/2;i=Math.max(o,i),i=Math.min(i,window.innerWidth+e-a-o);let l=window.innerHeight+n,c=t.bottom+n+o,p;c+r<=l?p=c:(p=t.top+n-r-o,p=Math.max(o,p)),this.el.style.left=`${i}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}exportMarkdown(){let e=[...this.store.getState().annotations].sort((o,i)=>o.createdAt-i.createdAt);if(e.length===0)return"No feedback provided.";let n=e.filter(o=>o.type==="COMMENT"),a=e.filter(o=>o.type==="DELETION"),r=["## Reviewer Feedback",""];if(n.length>0){r.push("### Comments","");for(let o of n){let i=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;r.push(`- **${o.comment}**`),r.push(` > "${i}"`),r.push("")}}if(a.length>0){r.push("### Deletions","");for(let o of a){let i=o.originalText.length>80?`${o.originalText.slice(0,80)}\u2026`:o.originalText;r.push("- Remove this"),r.push(` > "${i}"`),r.push("")}}return r.join(`
|
|
143
143
|
`).trimEnd()}exportJSON(){let e=[...this.store.getState().annotations].sort((n,a)=>n.createdAt-a.createdAt);return JSON.stringify(e,null,2)}submitFeedback(t){let e=this.exportMarkdown(),n=this.exportJSON(),a=e==="No feedback provided."?e:`${e}
|
|
144
144
|
|
|
145
145
|
\`\`\`json
|
|
146
146
|
${n}
|
|
147
|
-
\`\`\``;t("annotations",a)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(a=>a.type==="COMMENT").length,n=t.annotations.filter(a=>a.type==="DELETION").length;return{comments:e,deletions:n,total:t.annotations.length}}};var w="aikit-annotation-highlight";function I(){if(document.getElementById(w))return;let
|
|
147
|
+
\`\`\``;t("annotations",a)}getTotalCount(){let t=this.store.getState(),e=t.annotations.filter(a=>a.type==="COMMENT").length,n=t.annotations.filter(a=>a.type==="DELETION").length;return{comments:e,deletions:n,total:t.annotations.length}}};var w="aikit-annotation-highlight";function I(){if(document.getElementById(w))return;let d=document.createElement("style");d.id=w,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(
|
|
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 a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,null),r=0,o=null,i=0,l=null,c=0,p=a.nextNode();for(;p;){let f=(p.textContent||"").length,m=r+f;if(o===null&&m>e&&(o=p,i=e-r),m>=n){l=p,c=n-r;break}r=m,p=a.nextNode()}if(!o||!l)return null;let u=document.createRange();return u.setStart(o,Math.min(i,(o.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 a=document.createElement("mark");a.className=`hl-${t.type}`,a.dataset.annotationId=t.id,a.addEventListener("click",()=>{this.store.select(t.id)});try{n.surroundContents(a)}catch{try{if(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.splitText(n.endOffset),n.startContainer.nodeType===Node.TEXT_NODE){let r=n.startContainer;n.startOffset>0&&r.splitText(n.startOffset);let o=document.createRange();o.setStart(r.nextSibling||r,0),o.setEnd(n.endContainer.nodeType===Node.TEXT_NODE&&n.endContainer.previousSibling||n.endContainer,n.endOffset),o.surroundContents(a)}else throw new Error("Non-text range")}catch{let r=n.extractContents();a.append(r),n.insertNode(a)}}}removeHighlight(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);if(!e)return;let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}updateSelection(t){let e=this.container.querySelectorAll("mark[data-annotation-id]");for(let n of e)n.classList.toggle("hl-selected",n.dataset.annotationId===t)}scrollToAnnotation(t){let e=this.container.querySelector(`mark[data-annotation-id="${t}"]`);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.classList.add("annotation-pulse"),setTimeout(()=>{e.classList.remove("annotation-pulse")},600))}clearAll(){let t=this.container.querySelectorAll("mark[data-annotation-id]");for(let e of t){let n=e.parentNode;if(n){for(;e.firstChild;)n.insertBefore(e.firstChild,e);n.removeChild(e),n.nodeType===Node.ELEMENT_NODE&&n.normalize()}}}};var D=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 a=this.findBlockId(n.startContainer);if(!a)return;let r=this.findBlockContainer(n.startContainer),o=this.findBlockContainer(n.endContainer);if(r!==o)return;let i=this.computeBlockOffset(n.startContainer,n.startOffset),l=this.computeBlockOffset(n.endContainer,n.endOffset);if(i===null||l===null)return;let c={blockId:a,startOffset:i,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 a=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),r=0,o=a.nextNode();for(;o;){if(o===t)return r+e;r+=(o.textContent||"").length,o=a.nextNode()}return null}findBlockContainer(t){let e=t;for(;e;){if(e instanceof HTMLElement&&e.hasAttribute("data-block-id"))return e;e=e.parentNode}return null}clearSelection(){let t=window.getSelection();t&&t.removeAllRanges()}isExcludedElement(t){let e=t;for(;e&&!(e instanceof HTMLElement);)e=e.parentNode;return e?D.has(e.tagName.toLowerCase()):!1}};var R="aikit-annotation-sidebar",z=`
|
|
189
189
|
.as-sidebar {
|
|
190
190
|
width: var(--dt-annotation-sidebar-width, 300px);
|
|
191
191
|
background: var(--dt-bg-secondary);
|
|
@@ -367,7 +367,7 @@ ${n}
|
|
|
367
367
|
font-size: var(--dt-font-size-sm);
|
|
368
368
|
padding: var(--dt-space-6) var(--dt-space-2);
|
|
369
369
|
}
|
|
370
|
-
`,$='<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){
|
|
370
|
+
`,$='<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");this.store=t.store,this.exporter=t.exporter,this.el=this.render(),this.listEl=this.el.querySelector(".as-list"),this.modeToggleBtn=this.el.querySelector(".as-mode-toggle"),this.unsubscribe=this.store.subscribe(n=>{switch(n.type){case"annotation-added":case"annotation-removed":case"annotation-updated":this.renderList(),this.updateHeader();break;case"selection-changed":this.updateCardSelection(n.id);break;case"sidebar-toggled":this.updateVisibility();break;case"mode-changed":this.updateModeToggle();break}}),(t.mountTarget??document.body).appendChild(this.el),this.updateVisibility(),this.updateModeToggle()}destroy(){this.unsubscribe?.(),this.el.remove()}render(){b(R,z);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
371
|
<div class="as-header">
|
|
372
372
|
<span class="as-header-title">Annotations</span>
|
|
373
373
|
<span class="as-count-badge" aria-live="polite">${e.total}</span>
|
|
@@ -381,7 +381,7 @@ ${n}
|
|
|
381
381
|
${t.comment?`<div class="as-card-comment">${g(t.comment)}</div>`:""}
|
|
382
382
|
<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>
|
|
383
383
|
<button class="as-delete-btn" aria-label="Delete annotation">×</button>
|
|
384
|
-
`,e.addEventListener("click",()=>{this.store.select(t.id);let o=e.querySelector(".as-card-comment-detail");if(o){o.classList.toggle("as-card-comment-detail--open");let i=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let
|
|
384
|
+
`,e.addEventListener("click",()=>{this.store.select(t.id);let o=e.querySelector(".as-card-comment-detail");if(o){o.classList.toggle("as-card-comment-detail--open");let i=this.listEl.querySelectorAll(".as-card-comment-detail--open");for(let l of i)l!==o&&l.classList.remove("as-card-comment-detail--open")}}),e.querySelector(".as-delete-btn").addEventListener("click",o=>{o.stopPropagation(),this.handleDelete(t.id)}),e}handleDelete(t){this.store.remove(t)}updateVisibility(){let t=this.store.getState();this.el.style.display=t.isSidebarOpen?"flex":"none"}updateHeader(){let t=this.el.querySelector(".as-count-badge");if(t){let e=this.exporter.getTotalCount();t.textContent=String(e.total)}}updateModeToggle(){let t=this.store.getState().mode==="feedback";this.modeToggleBtn.classList.toggle("as-mode-toggle--active",t),this.modeToggleBtn.setAttribute("aria-pressed",String(t)),this.modeToggleBtn.setAttribute("aria-label",t?"Disable annotation mode":"Enable annotation mode")}updateCardSelection(t){let e=this.el.querySelectorAll(".as-card");for(let n of e){let a=n.dataset.annotationId;n.classList.toggle("as-card--selected",a!==void 0&&a===t)}}};var S=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,a,r,o,i,l,c){let p={id:this.generateId(),type:t,blockId:e,startOffset:n,endOffset:a,originalText:r,comment:o,section:i,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}update(t,e){let n=this.annotations.find(a=>a.id===t);n&&(Object.assign(n,e),this.notify({type:"annotation-updated",id:t,changes:e}))}remove(t){let e=this.annotations.findIndex(n=>n.id===t);e!==-1&&(this.annotations.splice(e,1),this.notify({type:"annotation-removed",id:t}))}select(t){this.selectedId=t,this.notify({type:"selection-changed",id:t})}setMode(t){t!==this.mode&&(this.mode=t,this.notify({type:"mode-changed",mode:t}))}toggleSidebar(t){this.isSidebarOpen=t!==void 0?t:!this.isSidebarOpen,this.notify({type:"sidebar-toggled",open:this.isSidebarOpen})}getState(){return{annotations:[...this.annotations],selectedId:this.selectedId,mode:this.mode,isSidebarOpen:this.isSidebarOpen}}destroy(){this.subscribers.clear(),this.annotations=[],this.selectedId=null,this.mode="selection",this.isSidebarOpen=!1,this.idCounter=0}};var L=25,_="aikit-annotation-guide",q=`
|
|
385
385
|
.as-guide {
|
|
386
386
|
margin: 0 0 var(--dt-space-3) 0;
|
|
387
387
|
padding: var(--dt-space-2) var(--dt-space-3);
|
|
@@ -398,7 +398,7 @@ ${n}
|
|
|
398
398
|
.as-guide--visible {
|
|
399
399
|
display: block;
|
|
400
400
|
}
|
|
401
|
-
`;function j(
|
|
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 a,r;try{if(t.startContainer.nodeType===Node.TEXT_NODE&&t.startOffset>0){let o=t.startContainer.textContent||"",i=Math.max(0,t.startOffset-L);a=o.slice(i,t.startOffset)}if(t.endContainer.nodeType===Node.TEXT_NODE&&t.endOffset<(t.endContainer.textContent?.length||0)){let o=t.endContainer.textContent||"",i=Math.min(o.length,t.endOffset+L);r=o.slice(t.endOffset,i)}}catch{}return{section:e,contextBefore:a,contextAfter:r}}function A(d){let{container:t,mountTarget:e}=d,n=null,a=new S;a.setMode("feedback");let r=new x(a);b(_,q);let o=document.createElement("div");o.className="as-guide",o.textContent="\u27B3 Ready. Select text to annotate or disable Feedback in the sidebar.",t.prepend(o);let i=()=>{let u=a.getState();o.classList.toggle("as-guide--visible",u.mode==="feedback"&&u.annotations.length===0)};i(),a.subscribe(()=>i());let l=new y(t,a);l.start();let c=new E({container:t,mode:()=>a.getState().mode,onSelection:u=>{let f=j(u);n?.destroy();let m=new v(u,{onSubmit:(h,T)=>{a.add("COMMENT",h.blockId,h.startOffset,h.endOffset,h.text,T||void 0,f.section,f.contextBefore,f.contextAfter),m.destroy(),n===m&&(n=null)},onRemove:(h,T)=>{a.add("DELETION",h.blockId,h.startOffset,h.endOffset,h.text,T||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:a,exporter:r,mountTarget:e});return a.openSidebar(),{destroy(){n?.destroy(),n=null,o.remove(),c.destroy(),l.stop(),p.destroy(),a.destroy()},getStore(){return a},getExporter(){return r}}}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 a="aikit-shell-layout";if(!document.getElementById(a)){let i=document.createElement("style");i.id=a,i.textContent=`
|
|
402
402
|
.shell-layout {
|
|
403
403
|
flex: 1;
|
|
404
404
|
display: flex;
|
|
@@ -425,4 +425,4 @@ ${C}
|
|
|
425
425
|
.action-bar {
|
|
426
426
|
margin-top: auto;
|
|
427
427
|
}
|
|
428
|
-
`,document.head.appendChild(
|
|
428
|
+
`,document.head.appendChild(i)}let r=A({container:t,mountTarget:n});r.getStore().subscribe(i=>{i.type==="sidebar-toggled"&&document.documentElement.setAttribute("data-annotation-sidebar",i.open?"open":"")}),r.getStore().getState().isSidebarOpen&&document.documentElement.setAttribute("data-annotation-sidebar","open"),window.__annotationLayer=r;let o=document.querySelectorAll(".bk-actions");if(o.length>0){let i=document.createElement("div");i.className="action-bar";let l=!1;for(let c of o)if(!c.querySelector('[data-action-row="multi"]')){for(;c.firstChild;)i.appendChild(c.firstChild);c.remove(),l=!0}if(l){let c=document.querySelector("main")||document.querySelector(".content");c&&(c.appendChild(i),c.style.paddingBottom="0")}}});})();
|
|
@@ -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-CzScS-EZ.js`);await e(t,n.port)}else{let{startStdioMode:e}=await import(`./server-stdio-DmsOjBSR.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-B3dZd6bx.js`);await e(n,r.port)}else{let{startStdioMode:e}=await import(`./server-stdio-COkJ2pX9.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,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createLogger as e}from"../../core/dist/index.js";import{randomUUID as t}from"node:crypto";const n=e(`observation-capture`),r=[`check`,`test_run`,`search`,`trace`],i=[/\bAuthorization\s*:\s*Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/g,/\b(?:sk|ghp|gho|glpat|xoxb|xoxp)-[A-Za-z0-9\-._]{20,}\b/g,/\b(?:token|key|secret|password|auth(?:orization)?)\s*[=:]\s*['"]?[^\s'"&]{8,}/gi,/\b(?:token|key|secret|password|auth(?:orization)?)=[^\s&]+/gi,/\b[A-Z][A-Z0-9_]*(?:PASSWORD|SECRET|TOKEN|AUTH)[A-Z0-9_]*\b\s*[=:]\s*['"]?[^\s'"]+/g,/\b[A-Z][A-Z0-9_]*KEY[A-Z0-9_]*\b\s*[=:]\s*['"]?[^\s'"]{8,}/g,/-----BEGIN [\w\s]+-----[\s\S]*?-----END [\w\s]+-----/g],a=new Set([`env`,`auth`,`config`]),o=2e3,s={enabled:!0,rateLimit:10,captureFrom:[...r],minContentLength:50};var c=class{maxPerMinute;timestamps=[];constructor(e){this.maxPerMinute=e}canCapture(e=Date.now()){return this.prune(e),this.timestamps.length<this.maxPerMinute}record(e=Date.now()){this.prune(e),this.timestamps.push(e)}setLimit(e){this.maxPerMinute=e,this.prune(Date.now())}prune(e){let t=e-6e4;this.timestamps=this.timestamps.filter(e=>e>t)}};function l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function u(e){return typeof e==`string`?e:l(e)?[Array.isArray(e.content)?e.content.filter(e=>l(e)).map(e=>typeof e.text==`string`?e.text:``).filter(e=>e.length>0).join(`
|
|
3
|
+
`):``,e.structuredContent==null?``:JSON.stringify(e.structuredContent,null,2)].filter(e=>e.length>0).join(`
|
|
4
|
+
|
|
5
|
+
`):JSON.stringify(e)}function d(e,t=500){return e.length<=t?e:e.slice(0,t)}function f(e){let t=e.toLowerCase();return[...a].some(e=>t===e||t.includes(e))}function p(e){let t=e;for(let e of i)t=t.replace(e,`[REDACTED]`);return t.length>o&&(t=`${t.slice(0,o)}\n...[truncated]`),t}function m(e,t){let n=t?.args??{},r=[];switch(t?.workspace&&r.push(`workspace=${t.workspace}`),e){case`check`:typeof n.cwd==`string`&&r.push(`cwd=${n.cwd}`),Array.isArray(n.files)&&n.files.length>0&&r.push(`files=${n.files.join(`, `)}`);break;case`test_run`:typeof n.cwd==`string`&&r.push(`cwd=${n.cwd}`),typeof n.grep==`string`&&r.push(`grep=${n.grep}`),Array.isArray(n.files)&&n.files.length>0&&r.push(`files=${n.files.join(`, `)}`);break;case`search`:typeof n.query==`string`&&r.push(`query=${n.query}`);break;case`trace`:typeof n.start==`string`&&r.push(`start=${n.start}`),typeof n.direction==`string`&&r.push(`direction=${n.direction}`);break;default:break}return r.length>0?r.join(` | `):void 0}var h=class{stateStore;curatedStore;rateLimiter;config;constructor(e,t,n){this.stateStore=e,this.curatedStore=t,this.config={...s,...n,captureFrom:n?.captureFrom?[...n.captureFrom]:[...r]},this.rateLimiter=new c(this.config.rateLimit)}getConfig(){return{...this.config,captureFrom:[...this.config.captureFrom]}}updateConfig(e){this.config={...this.config,...e,captureFrom:e.captureFrom?[...e.captureFrom]:[...this.config.captureFrom]},e.rateLimit!==void 0&&this.rateLimiter.setLimit(e.rateLimit)}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}registerTool(e){this.config.captureFrom.includes(e)||this.config.captureFrom.push(e)}unregisterTool(e){this.config.captureFrom=this.config.captureFrom.filter(t=>t!==e)}async processToolResult(e,t,r){if(!this.config.enabled||f(e)||!this.config.captureFrom.includes(e)||!this.rateLimiter.canCapture())return null;let i=this.extractObservation(e,t,r);if(!i)return null;let a=p(i.content).trim();if(a.length<this.config.minContentLength)return null;let o={...i,content:d(a).trim()},s={...o,content:a};this.rateLimiter.record();try{await this.storeObservation(s)}catch(t){n.warn(`Failed to store observation`,{toolName:e,error:t instanceof Error?t.message:String(t)})}return o}extractObservation(e,t,n){let r=u(t);if(r.trim().length===0)return null;switch(e){case`check`:return this.extractFromCheck(t,r,n);case`test_run`:return this.extractFromTestRun(t,r,n);case`search`:return this.extractFromSearch(r,n);case`trace`:return this.extractFromTrace(r,n);default:return null}}extractFromCheck(e,t,n){return l(e)&&e.isError===!0||/\berror\b/i.test(t)||/failed/i.test(t)?this.buildObservation(`check`,`error`,t,n):null}extractFromTestRun(e,t,n){let r=l(e)&&l(e.structuredContent)?e.structuredContent:void 0,i=typeof r?.failedTests==`number`?r.failedTests:void 0;return l(e)&&e.isError===!0||typeof i==`number`&&i>0||/\bFAIL\b/.test(t)||/failed/i.test(t)?this.buildObservation(`test_run`,`test_failure`,t,n):null}extractFromSearch(e,t){if(!/\b(convention|pattern)\b/i.test(e))return null;let n=/\bconvention\b/i.test(e)?`convention`:`pattern`;return this.buildObservation(`search`,n,e,t)}extractFromTrace(e,t){return this.buildObservation(`trace`,`insight`,e,t)}buildObservation(e,n,r,i){return{id:t(),source:e,type:n,content:r,context:m(e,i),timestamp:new Date().toISOString()}}async storeObservation(e){let t=`Observation ${e.source} ${e.type} ${e.timestamp}`,n=[`Source: ${e.source}`,`Type: ${e.type}`,`Captured: ${e.timestamp}`,e.context?`Context: ${e.context}`:null,``,e.content].filter(e=>e!==null).join(`
|
|
6
|
+
`),r=await this.curatedStore.remember(t,n,`context`,[`observation`,`source-${e.source}`,`type-${e.type}`]);this.stateStore.memoryMetaCreate(r.path,`working`)}};export{s as DEFAULT_OBSERVATION_CONFIG,h as ObservationEngine};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{createLogger as e}from"../../core/dist/index.js";import{randomUUID as t}from"node:crypto";const n=e(`observation-capture`),r=[`check`,`test_run`,`search`,`trace`],i=[/\bAuthorization\s*:\s*Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,/\bBearer\s+[A-Za-z0-9\-._~+/]+=*/g,/\b(?:sk|ghp|gho|glpat|xoxb|xoxp)-[A-Za-z0-9\-._]{20,}\b/g,/\b(?:token|key|secret|password|auth(?:orization)?)\s*[=:]\s*['"]?[^\s'"&]{8,}/gi,/\b(?:token|key|secret|password|auth(?:orization)?)=[^\s&]+/gi,/\b[A-Z][A-Z0-9_]*(?:PASSWORD|SECRET|TOKEN|AUTH)[A-Z0-9_]*\b\s*[=:]\s*['"]?[^\s'"]+/g,/\b[A-Z][A-Z0-9_]*KEY[A-Z0-9_]*\b\s*[=:]\s*['"]?[^\s'"]{8,}/g,/-----BEGIN [\w\s]+-----[\s\S]*?-----END [\w\s]+-----/g],a=new Set([`env`,`auth`,`config`]),o=2e3,s={enabled:!0,rateLimit:10,captureFrom:[...r],minContentLength:50};var c=class{maxPerMinute;timestamps=[];constructor(e){this.maxPerMinute=e}canCapture(e=Date.now()){return this.prune(e),this.timestamps.length<this.maxPerMinute}record(e=Date.now()){this.prune(e),this.timestamps.push(e)}setLimit(e){this.maxPerMinute=e,this.prune(Date.now())}prune(e){let t=e-6e4;this.timestamps=this.timestamps.filter(e=>e>t)}};function l(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function u(e){return typeof e==`string`?e:l(e)?[Array.isArray(e.content)?e.content.filter(e=>l(e)).map(e=>typeof e.text==`string`?e.text:``).filter(e=>e.length>0).join(`
|
|
2
|
+
`):``,e.structuredContent==null?``:JSON.stringify(e.structuredContent,null,2)].filter(e=>e.length>0).join(`
|
|
3
|
+
|
|
4
|
+
`):JSON.stringify(e)}function d(e,t=500){return e.length<=t?e:e.slice(0,t)}function f(e){let t=e.toLowerCase();return[...a].some(e=>t===e||t.includes(e))}function p(e){let t=e;for(let e of i)t=t.replace(e,`[REDACTED]`);return t.length>o&&(t=`${t.slice(0,o)}\n...[truncated]`),t}function m(e,t){let n=t?.args??{},r=[];switch(t?.workspace&&r.push(`workspace=${t.workspace}`),e){case`check`:typeof n.cwd==`string`&&r.push(`cwd=${n.cwd}`),Array.isArray(n.files)&&n.files.length>0&&r.push(`files=${n.files.join(`, `)}`);break;case`test_run`:typeof n.cwd==`string`&&r.push(`cwd=${n.cwd}`),typeof n.grep==`string`&&r.push(`grep=${n.grep}`),Array.isArray(n.files)&&n.files.length>0&&r.push(`files=${n.files.join(`, `)}`);break;case`search`:typeof n.query==`string`&&r.push(`query=${n.query}`);break;case`trace`:typeof n.start==`string`&&r.push(`start=${n.start}`),typeof n.direction==`string`&&r.push(`direction=${n.direction}`);break;default:break}return r.length>0?r.join(` | `):void 0}var h=class{stateStore;curatedStore;rateLimiter;config;constructor(e,t,n){this.stateStore=e,this.curatedStore=t,this.config={...s,...n,captureFrom:n?.captureFrom?[...n.captureFrom]:[...r]},this.rateLimiter=new c(this.config.rateLimit)}getConfig(){return{...this.config,captureFrom:[...this.config.captureFrom]}}updateConfig(e){this.config={...this.config,...e,captureFrom:e.captureFrom?[...e.captureFrom]:[...this.config.captureFrom]},e.rateLimit!==void 0&&this.rateLimiter.setLimit(e.rateLimit)}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1}registerTool(e){this.config.captureFrom.includes(e)||this.config.captureFrom.push(e)}unregisterTool(e){this.config.captureFrom=this.config.captureFrom.filter(t=>t!==e)}async processToolResult(e,t,r){if(!this.config.enabled||f(e)||!this.config.captureFrom.includes(e)||!this.rateLimiter.canCapture())return null;let i=this.extractObservation(e,t,r);if(!i)return null;let a=p(i.content).trim();if(a.length<this.config.minContentLength)return null;let o={...i,content:d(a).trim()},s={...o,content:a};this.rateLimiter.record();try{await this.storeObservation(s)}catch(t){n.warn(`Failed to store observation`,{toolName:e,error:t instanceof Error?t.message:String(t)})}return o}extractObservation(e,t,n){let r=u(t);if(r.trim().length===0)return null;switch(e){case`check`:return this.extractFromCheck(t,r,n);case`test_run`:return this.extractFromTestRun(t,r,n);case`search`:return this.extractFromSearch(r,n);case`trace`:return this.extractFromTrace(r,n);default:return null}}extractFromCheck(e,t,n){return l(e)&&e.isError===!0||/\berror\b/i.test(t)||/failed/i.test(t)?this.buildObservation(`check`,`error`,t,n):null}extractFromTestRun(e,t,n){let r=l(e)&&l(e.structuredContent)?e.structuredContent:void 0,i=typeof r?.failedTests==`number`?r.failedTests:void 0;return l(e)&&e.isError===!0||typeof i==`number`&&i>0||/\bFAIL\b/.test(t)||/failed/i.test(t)?this.buildObservation(`test_run`,`test_failure`,t,n):null}extractFromSearch(e,t){if(!/\b(convention|pattern)\b/i.test(e))return null;let n=/\bconvention\b/i.test(e)?`convention`:`pattern`;return this.buildObservation(`search`,n,e,t)}extractFromTrace(e,t){return this.buildObservation(`trace`,`insight`,e,t)}buildObservation(e,n,r,i){return{id:t(),source:e,type:n,content:r,context:m(e,i),timestamp:new Date().toISOString()}}async storeObservation(e){let t=`Observation ${e.source} ${e.type} ${e.timestamp}`,n=[`Source: ${e.source}`,`Type: ${e.type}`,`Captured: ${e.timestamp}`,e.context?`Context: ${e.context}`:null,``,e.content].filter(e=>e!==null).join(`
|
|
5
|
+
`),r=await this.curatedStore.remember(t,n,`context`,[`observation`,`source-${e.source}`,`type-${e.type}`]);this.stateStore.memoryMetaCreate(r.path,`working`)}};export{s as DEFAULT_OBSERVATION_CONFIG,h as ObservationEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e,t}from"./server-CiPwrtSl.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./server-CiPwrtSl.js";export{e as createSamplingClient};
|