qlogicagent 2.18.3 → 2.18.5
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/dist/agent.js +3 -3
- package/dist/cli.js +1 -1
- package/dist/index.js +559 -519
- package/dist/orchestration.js +1 -1
- package/dist/protocol.js +1 -1
- package/dist/skills/mcp/astraclaw-native-mcp-server.js +6 -6
- package/dist/types/cli/handlers/agents-handler.d.ts +33 -0
- package/dist/types/cli/handlers/community-handler.d.ts +1 -2
- package/dist/types/cli/handlers/memory-handler.d.ts +7 -1
- package/dist/types/cli/handlers/turn-handler.d.ts +10 -0
- package/dist/types/cli/orchestration-memory-context.d.ts +22 -0
- package/dist/types/orchestration/agent-instance.d.ts +5 -0
- package/dist/types/orchestration/goal-mode-adapters.d.ts +4 -0
- package/dist/types/orchestration/planner-memory-brief.d.ts +39 -0
- package/dist/types/orchestration/solo-spec-builder.d.ts +3 -0
- package/dist/types/protocol/methods.d.ts +0 -26
- package/dist/types/protocol/wire/agent-methods.d.ts +0 -12
- package/dist/types/protocol/wire/gateway-rpc.d.ts +11 -14
- package/dist/types/protocol/wire/index.d.ts +1 -1
- package/dist/types/protocol/wire/memory-provider-lifecycle.d.ts +0 -16
- package/dist/types/runtime/community/community-consent-client.d.ts +0 -21
- package/dist/types/runtime/execution/memory-decay.d.ts +1 -1
- package/dist/types/runtime/hooks/memory-hooks.d.ts +6 -0
- package/dist/types/runtime/infra/agent-paths.d.ts +9 -7
- package/dist/types/runtime/infra/astraclaw-capabilities.d.ts +0 -6
- package/dist/types/runtime/infra/checkpoint-backend.d.ts +1 -1
- package/dist/types/runtime/infra/migrate-device-scope.d.ts +49 -0
- package/dist/types/runtime/infra/project-data-paths.d.ts +4 -3
- package/dist/types/runtime/infra/project-skill-manifest.d.ts +3 -2
- package/dist/types/runtime/ports/index.d.ts +1 -1
- package/dist/types/runtime/ports/memory-provider.d.ts +22 -7
- package/dist/types/skills/memory/fts-segment.d.ts +20 -0
- package/dist/types/skills/memory/local-memory-provider.d.ts +55 -10
- package/dist/types/skills/memory/local-store-records.d.ts +6 -1
- package/dist/types/skills/memory/local-store.d.ts +96 -17
- package/dist/types/skills/memory/memdir.d.ts +16 -6
- package/dist/types/skills/memory/memory-consolidation.d.ts +7 -0
- package/dist/types/skills/memory/proposal-consumer.d.ts +51 -0
- package/dist/types/skills/memory/sqlite-memory-mappers.d.ts +2 -1
- package/dist/types/skills/memory/sqlite-memory-schema.d.ts +9 -1
- package/dist/types/skills/tools/image-generate-tool.d.ts +1 -1
- package/package.json +3 -2
- package/dist/types/cli/tool-bootstrap-community-registration.d.ts +0 -9
- package/dist/types/runtime/community/community-discovery-cache.d.ts +0 -24
- package/dist/types/runtime/community/community-discovery-coordinator.d.ts +0 -33
- package/dist/types/runtime/hooks/community-discovery-hook.d.ts +0 -18
- package/dist/types/skills/tools/community-seek-tool.d.ts +0 -49
package/dist/orchestration.js
CHANGED
|
@@ -16,7 +16,7 @@ New messages to integrate:`:void 0,C=U(p,{taskContext:m}),k=await this.config.su
|
|
|
16
16
|
${k}`},_=[...l,A,...d],E=Date.now()-o,b=_.reduce((f,g)=>f+this.config.estimateTokens(g),0);return{messages:_,droppedCount:p.length,strategy:"incremental-compact",metrics:{tokensBefore:u,tokensAfter:b,compressionRatio:u>0?b/u:1,latencyMs:E,usedLlm:!0,cacheInvalidated:!0}}}},P=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}async compressAsync(t,n){let o=R(t),r=B(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),s=R(r.messages),i=o!==s&&r.droppedCount>0;return i&&this.config.onCacheInvalidated?.({droppedCount:r.droppedCount,strategy:r.strategy}),{...r,metrics:{...r.metrics??{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1},cacheInvalidated:i}}}},ne={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function st(e={}){let t={...ne,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function it(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var N=class{events=[];maxEvents;constructor(t=100){this.maxEvents=t}record(t){this.events.push(t),this.events.length>this.maxEvents&&this.events.shift()}snapshot(){let t=this.events.length;if(t===0)return{totalCompressions:0,totalLlmCalls:0,totalCacheInvalidations:0,averageCompressionRatio:1,averageLatencyMs:0,totalTokensSaved:0,recentEvents:[]};let n=0,o=0,r=0,s=0,i=0;for(let a of this.events)n+=a.tokensBefore>0?a.tokensAfter/a.tokensBefore:1,o+=a.latencyMs,r+=Math.max(0,a.tokensBefore-a.tokensAfter),a.usedLlm&&s++,a.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:s,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},D=class{engines=new Map;activeId;register(t){this.engines.set(t.id,t)}activate(t){return this.engines.has(t)?(this.activeId=t,!0):!1}getActive(){return this.activeId?this.engines.get(this.activeId):void 0}listEngines(){return Array.from(this.engines.values()).map(t=>({id:t.id,label:t.label,active:t.id===this.activeId}))}};function oe(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function S(e){let t=typeof e.content=="string"?e.content:e.content!=null?JSON.stringify(e.content):"";return Math.ceil(t.length/4)}function R(e){let t=Math.min(e.length,5),n=[];for(let o=0;o<t;o++){let r=e[o],s=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${s}`)}return n.join("|")}var at=new Set(["file_read","read","Read","bash","shell","Bash","grep","search","Grep","grep_search","glob","Glob","file_search","web_search","WebSearch","web_fetch","WebFetch","file_edit","edit","Edit","file_write","write","Write"]),F=class{constructor(t=20,n=S){this.preserveRecentCount=t;this.estimateTokens=n}preserveRecentCount;estimateTokens;compress(t,n){if(t.length<=this.preserveRecentCount)return{messages:t,droppedCount:0,strategy:"micro-compact"};let o=new Map;for(let l of t){let c=l.tool_calls;if(Array.isArray(c))for(let u of c)u?.id&&u.function?.name&&o.set(u.id,u.function.name)}let r=t.length-this.preserveRecentCount,s=0,i=0;return{messages:t.map((l,c)=>{if(c>=r||l.role!=="tool"||typeof l.content!="string")return l;let u=l.name??o.get(l.tool_call_id??"");if(!u||!at.has(u)||l.content.length<=200)return l;let p=this.estimateTokens(l);return i+=p,s++,{...l,content:`[result cleared \u2014 ${l.content.length} chars]`}}),droppedCount:s,strategy:"micro-compact",metrics:s>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function lt(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];if(o.tool_calls&&Array.isArray(o.tool_calls))for(let r of o.tool_calls){let s=r.function?.name??"";if(/read|edit|write|file/i.test(s)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),a=i.path??i.filePath??i.file_path??i.file;a&&typeof a=="string"&&t.set(a,n)}catch{}}o.role==="tool"&&o.name&&/read|edit|write|file/i.test(o.name)}return[...t.entries()].sort((n,o)=>o[1]-n[1]).map(([n])=>n)}async function ct(e,t,n){let o=n.estimateTokens??(d=>Math.ceil(d.length/4)),r=lt(t);if(r.length===0)return e;let s=e.map(d=>typeof d.content=="string"?d.content:"").join(`
|
|
17
17
|
`),i=r.filter(d=>!s.includes(d));if(i.length===0)return e;let a=n.maxTokenBudget,l=[],c=0;for(let d of i){if(c>=n.maxFiles||a<=0)break;let m=await n.readFile(d);if(!m)continue;let C=o(m);C>a||(a-=C,c++,l.push({role:"system",content:`[Post-compact file recovery: ${d}]
|
|
18
18
|
|
|
19
|
-
${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function ut(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function pt(){return{stages:[]}}function dt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=re(e,t),i=ft(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=re(e,t),{messages:s,stagedCount:i.length}}function mt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:se(e,t),committed:n}}function re(e,t){return t.stages.filter(o=>o.committed).length===0?e:se(e,t)}function se(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function ft(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let p=`${i}-${i+a}`;s.has(p)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as gt,writeFileSync as yt,mkdirSync as Tt}from"node:fs";import{join as ht,dirname as Ct}from"node:path";var Ln=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Pn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var ie=3,ae=2,le=300*1e3,ce=3,ue=720*60*60*1e3,G=4;var Nn=3600*1e3;var Dn=50*1024,Fn=500*1024,Bn=500*1024*1024,Un=50*1024*1024;var Gn=60*1024;var de=0;var _t="skill-patterns.json";function me(e){return ht(e,".qlogicagent",_t)}function fe(e){let t=me(e);try{return JSON.parse(gt(t,"utf8"))}catch{return{version:1,patterns:{}}}}function pe(e,t){let n=me(e);Tt(Ct(n),{recursive:!0}),yt(n,JSON.stringify(t,null,2),"utf8")}function bt(e){let t=Date.now()-ue;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function ge(e,t){if(t.length===0)return!1;let n=ye(t),o=fe(e);bt(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return pe(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=ce;return i&&(s.promoted=!0),pe(e,o),i}function Rt(e){let t=fe(e);return Object.values(t.patterns)}function ye(e){return[...e].sort().join("+")}function St(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ie||e.distinctToolCount<ae||Date.now()-de<le||t?.projectRoot&&t.tools.length>0&&!ge(t.projectRoot,t.tools))}function xt(e){return e.existingSkillName?e.feedback==="negative":!1}function kt(e,t){return xt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:St(e,t)?(de=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function At(e){return[...new Set(e.map(x).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Te(e){let t=At(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, use community_seek (when listed) to find an installable capability, and otherwise state plainly which capability is missing.`}function Et(e){let t=[...new Set(e.map(x).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Te(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function x(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Mt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function It(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=x(n);if(!o)return!1;let r=t.get(o);return!r||Mt(r.status)})}function wt(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ot(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=It({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Te(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Et(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>x(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Lt=["stop","aborted","timeout","cancelled","interrupted","error"],Pt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function he(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Nt(e,t){return{...e,content:[...he(e.content),...he(t.content)]}}function Dt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Ft(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=Dt(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Bt(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Ut(e){return new Set((e??Lt).map(t=>t.trim().toLowerCase()))}function Ce(e,t){return e?Ut(t).has(e.trim().toLowerCase()):!1}function Gt(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function j(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>Bt(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let s=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&s.push(p);continue}if(c.length<l.tool_calls.length){s.push({...l,tool_calls:c});continue}}s.push(l)}let i=Ft(s),a=[];for(let l of i){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Nt(c,l);continue}a.push(l)}return a}function $(e,t){return Ce(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Pt)delete o[r];return o}):[...e]}function H(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function jt(e,t){let n=j(e),o=$(n,t);return H(o,t)}function _e(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Ce(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Gt(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let s=new Set,i=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(s.add(u),i.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!s.has(u))continue;a.add(u)}l.push(c)}for(let[c]of i)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function $t(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function Ht(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function zt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function qt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function be(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Yt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Xt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Kt(e){let t=[],n=j(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=H(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:be({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$t(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Wt(e){let t=_e(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:be({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:zt(t),completedToolCallIds:qt(t)}),recoveryActions:n}}var Vt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Jt(e){return e?Vt.has(e):!0}function Zt(e){return e===429||e===529}function Qt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Zn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function en(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var z=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var q="<fork-child-context>",Re="Fork started \u2014 processing in background";function tn(e){return JSON.stringify(e).includes(q)}function nn(e){return e<G}function on(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
19
|
+
${m}`}))}if(l.length===0)return e;let u=[...e],p=-1;for(let d=0;d<u.length;d++)u[d].role==="system"&&(p=d);return u.splice(p+1,0,...l),u}function ut(e,t,n=S){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,s=[];for(let a of e){let l=a.tool_call_id??"";if(l&&t.has(l)){o+=n(a),r++,t.delete(l);continue}s.push(a)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:s,tokensFreed:o,removedCount:r,boundaryMessage:i}}function pt(){return{stages:[]}}function dt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(a=>a.role!=="system").length<=o)return{messages:e,stagedCount:0};let s=re(e,t),i=ft(s,t,o);if(i.length===0)return{messages:s,stagedCount:0};for(let a of i)t.stages.push(a);return s=re(e,t),{messages:s,stagedCount:i.length}}function mt(e,t){let n=0;for(let o of t.stages)o.committed||(o.committed=!0,n++);return n===0?{messages:e,committed:0}:{messages:se(e,t),committed:n}}function re(e,t){return t.stages.filter(o=>o.committed).length===0?e:se(e,t)}function se(e,t){let n=t.stages.filter(r=>r.committed).sort((r,s)=>s.range[0]-r.range[0]),o=[...e];for(let r of n){let[s,i]=r.range;if(s>=o.length)continue;let a=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(s,a-s,l)}return o}function ft(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],s=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,a=0;for(let l=0;l<o;l++){let c=e[l];if(c.role==="tool"||c.role==="assistant"&&typeof c.content=="string"&&c.content==="")i<0&&(i=l),a++;else{if(a>=3){let p=`${i}-${i+a}`;s.has(p)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}i=-1,a=0}}if(a>=3){let l=`${i}-${i+a}`;s.has(l)||r.push({id:`collapse_${i}_${i+a}`,range:[i,i+a],summary:`[${a} tool results collapsed]`,committed:!1})}return r}import{readFileSync as gt,writeFileSync as yt,mkdirSync as Tt}from"node:fs";import{join as ht,dirname as Ct}from"node:path";var Ln=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100),Pn=Math.max(1e3,Number(process.env.TOOL_LOOP_TOOL_TIMEOUT_MS)||24e4);var ie=3,ae=2,le=300*1e3,ce=3,ue=720*60*60*1e3,G=4;var Nn=3600*1e3;var Dn=50*1024,Fn=500*1024,Bn=500*1024*1024,Un=50*1024*1024;var Gn=60*1024;var de=0;var _t="skill-patterns.json";function me(e){return ht(e,".qlogicagent",_t)}function fe(e){let t=me(e);try{return JSON.parse(gt(t,"utf8"))}catch{return{version:1,patterns:{}}}}function pe(e,t){let n=me(e);Tt(Ct(n),{recursive:!0}),yt(n,JSON.stringify(t,null,2),"utf8")}function bt(e){let t=Date.now()-ue;for(let[n,o]of Object.entries(e.patterns))new Date(o.lastSeen).getTime()<t&&delete e.patterns[n]}function ge(e,t){if(t.length===0)return!1;let n=ye(t),o=fe(e);bt(o);let r=new Date().toISOString(),s=o.patterns[n];if(s||(s={signature:n,count:0,firstSeen:r,lastSeen:r,promoted:!1},o.patterns[n]=s),s.promoted)return pe(e,o),!1;s.count++,s.lastSeen=r;let i=s.count>=ce;return i&&(s.promoted=!0),pe(e,o),i}function Rt(e){let t=fe(e);return Object.values(t.patterns)}function ye(e){return[...e].sort().join("+")}function St(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ie||e.distinctToolCount<ae||Date.now()-de<le||t?.projectRoot&&t.tools.length>0&&!ge(t.projectRoot,t.tools))}function xt(e){return e.existingSkillName?e.feedback==="negative":!1}function kt(e,t){return xt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:St(e,t)?(de=Date.now(),{type:"skill.create",suggestedName:t.suggestedName??`auto-skill-${t.tools.slice(0,3).join("-")}`,description:`Multi-step orchestration using ${t.tools.join(", ")}`,tools:t.tools,stepCount:e.toolCallCount}):null}function At(e){return[...new Set(e.map(x).filter(Boolean))].sort((t,n)=>t.localeCompare(n))}function Te(e){let t=At(e);return t.length===0?"":`Available tools for this round: ${t.join(", ")}. Do not invent or attempt any tool outside this list. If the request needs a capability none of these tools cover, do not silently refuse: consider exec-based scripts/OS commands, and otherwise state plainly which capability is missing.`}function Et(e){let t=[...new Set(e.map(x).filter(Boolean))].sort((i,a)=>i.localeCompare(a)),n=new Set(t),o=Te(e),r=n.has("exec"),s=["read","search","write","edit","patch"].some(i=>n.has(i));return!r||!s?"You must call one of the available tools before responding. "+o:"You must call one of the available tools before responding. "+o+' Tool selection is part of correctness. Use read/search/write/edit/patch for file paths and file maintenance. For search, always include `mode` and `pattern`; examples: {"mode":"filename","pattern":"**/*.md"} or {"mode":"content","pattern":"TODO","fileGlob":"*.ts"}. Use exec only for shell commands with the required `command` field; never pass `path`, `filePath`, or file content to exec.'}function x(e){return e.function&&typeof e.function=="object"&&typeof e.function.name=="string"?e.function.name.trim():typeof e.name=="string"?e.name.trim():""}function Mt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function vt(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function It(e){if(!e.eligibility?.length)return[...e.tools];let t=vt(e.eligibility);return e.tools.filter(n=>{let o=x(n);if(!o)return!1;let r=t.get(o);return!r||Mt(r.status)})}function wt(e){let t=[],n=e.compatibility??{},o=e.toolChoice;if(e.thinkingEnabled&&n.requireAutoWhenThinking){let r=typeof o=="object"&&o&&!Array.isArray(o)?String(o.type??""):o;r&&r!=="auto"&&r!=="none"&&(t.push("tool_choice downgraded to auto because thinking mode requires auto/none compatibility."),o="auto")}if(o==="required"&&n.allowRequiredToolChoice===!1){let r=n.requiredFallback??"auto";t.push(`tool_choice=required is not supported by this provider; downgraded to ${r}.`),o=r}if(o&&typeof o=="object"&&!Array.isArray(o)&&o.type==="function"&&n.allowNamedToolChoice===!1){let r=n.namedFallback??"required";t.push(`named tool_choice is not supported by this provider; downgraded to ${r}.`),o=r}return{normalizedToolChoice:o,warnings:t}}function Ot(e){let t=wt({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=It({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,...r.length>0?{extraSystemPrompt:Te(r)}:{},warnings:o};if(n==="none")return{tools:[],normalizedToolChoice:"none",warnings:o};if(n==="required"){if(r.length===0)throw new Error("tool_choice=required but no tools were provided");return{tools:r,normalizedToolChoice:"required",extraSystemPrompt:Et(r),warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let s=n.function??void 0,i=typeof s?.name=="string"?s.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let a=r.filter(l=>x(l)===i);if(a.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:a,normalizedToolChoice:{type:"function",function:{name:i}},extraSystemPrompt:`You must call the ${i} tool before responding.`,warnings:o}}return{tools:r,normalizedToolChoice:n,warnings:o}}var Lt=["stop","aborted","timeout","cancelled","interrupted","error"],Pt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function he(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function Nt(e,t){return{...e,content:[...he(e.content),...he(t.content)]}}function Dt(e){let t=new Set;if(e.role!=="assistant"||!Array.isArray(e.tool_calls))return t;for(let n of e.tool_calls)typeof n.id=="string"&&n.id&&t.add(n.id);return t}function Ft(e){let t=new Set,n=[];for(let o=0;o<e.length;o+=1){if(t.has(o))continue;let r=e[o];if(!r)continue;n.push(r);let s=Dt(r);if(s.size!==0)for(let i=o+1;i<e.length;i+=1){if(t.has(i))continue;let a=e[i];a?.role==="tool"&&typeof a.tool_call_id=="string"&&s.has(a.tool_call_id)&&(n.push(a),t.add(i))}}return n}function Bt(e){if(!e||typeof e!="object")return!1;if(e.function&&typeof e.function=="object"){let t=e.function.name;if(typeof t=="string"&&t.length>0)return!0}return typeof e.name=="string"&&e.name.length>0}function Ut(e){return new Set((e??Lt).map(t=>t.trim().toLowerCase()))}function Ce(e,t){return e?Ut(t).has(e.trim().toLowerCase()):!1}function Gt(e){let t=e.indexOf("|");return t<=0||t>=e.length-1?{callId:e}:{callId:e.slice(0,t),itemId:e.slice(t+1)}}function j(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(l=>{if(l.role==="assistant"&&Array.isArray(l.tool_calls)){let c=l.tool_calls.filter(u=>Bt(u));return{...l,...c.length>0?{tool_calls:c}:{tool_calls:void 0}}}return{...l}}),n=new Set;for(let l of t)if(!(l.role!=="assistant"||!Array.isArray(l.tool_calls)))for(let c of l.tool_calls)typeof c.id=="string"&&c.id&&n.add(c.id);let o=t.filter(l=>l.role!=="tool"?!0:!!(l.tool_call_id&&n.has(l.tool_call_id))),r=new Set;for(let l of o)l.role==="tool"&&typeof l.tool_call_id=="string"&&l.tool_call_id&&r.add(l.tool_call_id);let s=[];for(let l of o){if(l.role==="assistant"&&Array.isArray(l.tool_calls)&&l.tool_calls.length>0){let c=l.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(c.length===0){let{tool_calls:u,...p}=l;p.content!=null&&p.content!==""&&s.push(p);continue}if(c.length<l.tool_calls.length){s.push({...l,tool_calls:c});continue}}s.push(l)}let i=Ft(s),a=[];for(let l of i){let c=a.length>0?a[a.length-1]:void 0;if(l.role==="user"&&c?.role==="user"){a[a.length-1]=Nt(c,l);continue}a.push(l)}return a}function $(e,t){return Ce(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of Pt)delete o[r];return o}):[...e]}function H(e,t){let n=t?.placeholderToolResult??"Error: Tool loop interrupted before the tool result was replayed.",o=new Set;for(let s of e)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&o.add(s.tool_call_id);let r=[];for(let s of e)if(r.push({...s}),!(s.role!=="assistant"||!Array.isArray(s.tool_calls)||s.tool_calls.length===0))for(let i of s.tool_calls)typeof i.id!="string"||!i.id||o.has(i.id)||(o.add(i.id),r.push({role:"tool",tool_call_id:i.id,content:n}));return r}function jt(e,t){let n=j(e),o=$(n,t);return H(o,t)}function _e(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=Ce(t?.stopReason,t?.forcedStopReasons),r=[];for(let c=0;c<e.length;c+=1){let u=e[c];if(!u||typeof u!="object"){r.push(u);continue}if(u.type==="reasoning"&&typeof u.id=="string"&&u.id.startsWith("rs_")&&!e.slice(c+1).some(m=>m&&typeof m=="object"&&m.type!=="reasoning"))continue;if(u.type!=="function_call"){r.push({...u});continue}let p={...u};if(typeof p.id=="string"){let d=Gt(p.id);d.itemId?.startsWith("fc_")&&(p.id=d.callId)}r.push(p)}let s=new Set,i=new Map;for(let c of r){if(c.type!=="function_call")continue;let u=typeof c.call_id=="string"&&c.call_id?c.call_id:typeof c.id=="string"?c.id:void 0;u&&(s.add(u),i.set(u,c))}let a=new Set,l=[];for(let c of r)if(!(o&&c.type==="function_call")){if(c.type==="function_call_output"){let u=typeof c.call_id=="string"?c.call_id:"";if(!u||!s.has(u))continue;a.add(u)}l.push(c)}for(let[c]of i)a.has(c)||o||l.push({type:"function_call_output",call_id:c,output:n});return l}function $t(e){let t=new Set,n=new Set;for(let o of e){if(o.role==="assistant"&&Array.isArray(o.tool_calls))for(let r of o.tool_calls)typeof r.id=="string"&&r.id&&t.add(r.id);o.role==="tool"&&typeof o.tool_call_id=="string"&&o.tool_call_id&&n.add(o.tool_call_id)}return[...t].filter(o=>!n.has(o))}function Ht(e){let t=new Set;for(let n of e)n.role==="tool"&&typeof n.tool_call_id=="string"&&n.tool_call_id&&t.add(n.tool_call_id);return[...t]}function zt(e){let t=new Set,n=new Set;for(let o of e){if(o.type==="function_call"){let r=typeof o.call_id=="string"&&o.call_id?o.call_id:typeof o.id=="string"?o.id:"";r&&t.add(r)}o.type==="function_call_output"&&typeof o.call_id=="string"&&o.call_id&&n.add(o.call_id)}return[...t].filter(o=>!n.has(o))}function qt(e){let t=new Set;for(let n of e)n.type==="function_call_output"&&typeof n.call_id=="string"&&n.call_id&&t.add(n.call_id);return[...t]}function be(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Yt(e,t){return{round:e.round+1,maxRounds:e.maxRounds,pendingToolCallIds:[...t.pendingToolCallIds??e.pendingToolCallIds],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Xt(e,t){return{round:e.round,maxRounds:e.maxRounds,pendingToolCallIds:[],completedToolCallIds:[...t.completedToolCallIds??e.completedToolCallIds],lastStopReason:t.lastStopReason??e.lastStopReason,replayMessages:[...t.replayMessages??e.replayMessages]}}function Kt(e){let t=[],n=j(e.replayMessages);n.length!==e.replayMessages.length&&t.push({kind:"drop-orphan-tool-result",detail:"Removed orphan tool results or invalid assistant tool calls."});let o=$(n,e.options);o.some((s,i)=>s!==n[i])&&t.push({kind:"strip-forced-stop-tool-metadata",detail:"Removed assistant tool-call metadata after forced stop."});let r=H(o,e.options);return r.length>o.length&&t.push({kind:"inject-placeholder-tool-result",detail:"Injected placeholder tool result for pending tool calls."}),{state:be({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:$t(r),completedToolCallIds:Ht(r)}),recoveryActions:t}}function Wt(e){let t=_e(e.replayItems,e.options),n=[];return t.length!==e.replayItems.length&&n.push({kind:"drop-trailing-reasoning",detail:"Dropped dangling reasoning blocks or injected missing function_call_output items."}),t.some((o,r)=>o!==e.replayItems[r]&&o.type==="function_call")&&n.push({kind:"rewrite-openai-function-call-pair",detail:"Rewrote OpenAI function_call pairing ids for replay compatibility."}),{state:be({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:zt(t),completedToolCallIds:qt(t)}),recoveryActions:n}}var Vt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Jt(e){return e?Vt.has(e):!0}function Zt(e){return e===429||e===529}function Qt(e,t=500,n=32e3){let o=Math.min(t*Math.pow(2,e-1),n);return o+Math.floor(Math.random()*o*.25)}var Zn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function en(){let e=process.env.QLOGICAGENT_PERSISTENT_RETRY;return e==="1"||e==="true"}var z=class extends Error{constructor(n,o){super(`Model fallback triggered: ${n} -> ${o}`);this.originalModel=n;this.fallbackModel=o;this.name="FallbackTriggeredError"}originalModel;fallbackModel};var q="<fork-child-context>",Re="Fork started \u2014 processing in background";function tn(e){return JSON.stringify(e).includes(q)}function nn(e){return e<G}function on(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
|
|
20
20
|
|
|
21
21
|
Your working directory is: ${e.worktreePath}
|
|
22
22
|
All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${q}
|
package/dist/protocol.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var q=["idle","running-right","running-left","waving","jumping","failed","waiting","running","review"];var Y="1.0.0",d={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043},H={REQUEST:"tool.approval.request"};function P(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0}function C(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&(typeof t.id=="string"||typeof t.id=="number")&&!("method"in t)}function I(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function G(e){let t;try{t=JSON.parse(e)}catch{return null}return C(t)||P(t)||I(t)?t:null}import{randomUUID as z}from"node:crypto";var X=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],J=new Set(["memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","pet.asset.import","solo.start","solo.evaluate","product.plan","product.create","product.message"]),Q=["memory.","pet.","usage."],$=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function f(e){return J.has(e)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:X.some(t=>e===t||e.startsWith(`${t}.`)||e.startsWith(t))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function h(e){return $.has(e)||f(e).mutability==="read"?!1:Q.some(t=>e.startsWith(t))}function Z(e,t={}){let r=t.now??Date.now(),n=f(e),i=t.timeoutMs??n.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+i,channel:t.channel??n.channel,idempotencyKey:t.idempotencyKey,traceId:t.traceId}}function v(e,t=Date.now()){let r=e.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=t)return{ok:!1,error:{code:d.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let n=f(e.method).channel;return r.channel!==n?{ok:!1,error:{code:d.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:h(e.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:d.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${e.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var R=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(t={}){this.now=t.now??(()=>Date.now())}begin(t,r){let n=v({method:t,meta:r},this.now());if(!n.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:n.error};if(r.idempotencyKey){let i=this.idempotency.get(r.idempotencyKey);if(i)return this.counters.dedupedRequests+=1,i.error?{status:"deduped",error:i.error}:{status:"deduped",result:i.result}}return this.active.set(r.requestId,{method:t,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(t,r="cancelled"){let n=this.active.get(t);return!n||n.cancelled?!1:(n.cancelled=!0,n.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(t){return this.active.get(t)?(this.active.delete(t),this.counters.deadlineExceededRequests+=1,!0):!1}settle(t,r,n){let i=this.active.get(t);return i?(this.active.delete(t),i.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):i.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,i.meta.idempotencyKey&&this.idempotency.set(i.meta.idempotencyKey,{result:r,error:n,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var ee=["agent.health","agent.metrics","agent.cancel","session.list","session.get","session.create","session.update","session.delete","session.deleteAll","session.archive","session.moveToProject","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.update","project.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.move","files.copy","files.delete","files.search","files.undoOperation","files.gitStatus","turnBaseline.getSummary","turnBaseline.getFileDiff","turnBaseline.listRecent","turnBaseline.getFileBaseline","workingMaterials.get","workingMaterials.replace","workingMaterials.upsert","workingMaterials.remove","workingMaterials.reorder","skills.list","memory.list-files","memory.atlas","memory.activity","memory.observe","memory.propose","memory.consolidate","memory.update","memory.attachment.adopt","memory.attachment.locate"];var M=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.file_changes","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.media_capability_check","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.progress","turn.tool_use_summary","turn.tool_selection_policy","turn.lifecycle","turn.document_maintenance","turn.artifact_contract","turn.usage_update","team.member.notification","session.info","session.recovery_pending","memory.updated","skills.updated","turn.memory_recall","turn.memory_written","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus","workflow.triggerDropped","workflow.alert","workflow.approvalRequested","workflow.approvalTimedOut"],k=["solo.progress","solo.specProgress","solo.agentDelta","solo.agentActivity","solo.agentUsage","solo.evaluation","product.taskStarted","product.taskOutput","product.members","product.agentActivity","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.budgetWarning","product.checkpointed","product.completed","product.dagTopology","plan.interrupted","goal.run_state_changed","goal.phase_boundary","goal.goal_edited","goal.message_queued","goal.acceptance_updated"],te=[...M,...k];var re=1,ne={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},oe={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_REPLAY:"x/product.replay",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",SOLO_SPEC_CHAT:"x/solo.specChat",SOLO_SPEC_JUDGE:"x/solo.specJudge",WORKFLOW_CHAT:"x/workflow.chat",WORKFLOW_MATCH_INTENT:"x/workflow.matchIntent",PRODUCT_SUBSCRIBE:"x/product.subscribe",GOAL_START:"x/goal.start",GOAL_STATUS:"x/goal.status",GOAL_PAUSE:"x/goal.pause",GOAL_RESUME:"x/goal.resume",GOAL_UPDATE_GOAL:"x/goal.updateGoal",GOAL_STOP:"x/goal.stop",GOAL_MESSAGE:"x/goal.message",GOAL_SUBSCRIBE:"x/goal.subscribe",GOAL_EVENTS:"x/goal.events",MENTION_DELEGATE:"x/mention.delegate",MENTION_CANCEL:"x/mention.cancel",MENTION_LIST:"x/mention.list"},x={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update"},ie={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function O(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function N(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function w(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function se(e){let t;try{t=JSON.parse(e)}catch{return null}return w(t)||O(t)||N(t)?t:null}function ae(e){return Object.values(x).includes(e)}function pe(e){return e.startsWith("x_")}var E=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function g(e){return e?e.map(t=>({...t})):void 0}function _(e){return e?e.map(t=>({...t})):void 0}function ce(e){return e?[...e]:void 0}function D(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function m(e){return{...e,toolNamespaces:[...e.toolNamespaces],workspaceIds:[...e.workspaceIds],...e.changedSections?{changedSections:[...e.changedSections]}:{},...e.installedCapabilities?{installedCapabilities:[...e.installedCapabilities]}:{},...e.enabledCapabilities?{enabledCapabilities:[...e.enabledCapabilities]}:{},...e.features?{features:[...e.features]}:{},...e.toolManifests?{toolManifests:g(e.toolManifests)}:{},...e.skillManifests?{skillManifests:g(e.skillManifests)}:{},...e.pluginManifests?{pluginManifests:g(e.pluginManifests)}:{},...e.mcpManifests?{mcpManifests:g(e.mcpManifests)}:{},...e.approvalPolicy?{approvalPolicy:{...e.approvalPolicy}}:{},...e.workspaceSummaries?{workspaceSummaries:_(e.workspaceSummaries)}:{}}}function le(e){let{previous:t,update:r}=e;return!(r.syncMode==="diff"&&t&&(!r.baseSnapshotVersion||t.snapshotVersion===r.baseSnapshotVersion))||!t?m(r):{...m(t),snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,...r.gatewayVersion!==void 0?{gatewayVersion:r.gatewayVersion}:{},...r.syncMode?{syncMode:r.syncMode}:{},...r.baseSnapshotVersion?{baseSnapshotVersion:r.baseSnapshotVersion}:{},...r.changedSections?{changedSections:[...r.changedSections]}:{},...r.toolNamespaces?{toolNamespaces:[...r.toolNamespaces]}:{},...r.workspaceIds?{workspaceIds:[...r.workspaceIds]}:{},...r.installedCapabilities?{installedCapabilities:[...r.installedCapabilities]}:{},...r.enabledCapabilities?{enabledCapabilities:[...r.enabledCapabilities]}:{},...r.features?{features:[...r.features]}:{},...r.approvalMode?{approvalMode:r.approvalMode}:{},...r.toolManifests?{toolManifests:g(r.toolManifests)}:{},...r.skillManifests?{skillManifests:g(r.skillManifests)}:{},...r.pluginManifests?{pluginManifests:g(r.pluginManifests)}:{},...r.mcpManifests?{mcpManifests:g(r.mcpManifests)}:{},...r.approvalPolicy?{approvalPolicy:{...r.approvalPolicy}}:{},...r.workspaceSummaries?{workspaceSummaries:_(r.workspaceSummaries)}:{}}}function de(e){return D(e.map(t=>t.name.split(".")[0]??"").filter(Boolean))}function ue(e){return D(e.map(t=>t.id))}function ge(e){let{previous:t,current:r}=e;if(!t)return{...m(r),syncMode:"full"};if(t.snapshotVersion===r.snapshotVersion)return null;let n=E.filter(s=>JSON.stringify(t[s])!==JSON.stringify(r[s]));if(n.length===E.length)return{...m(r),syncMode:"full"};let i={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:n,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=i;for(let s of n){let o=r[s];if(o!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(o);break;case"approvalPolicy":c[s]={...o};break;case"workspaceSummaries":c[s]=_(o);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(o);break;default:c[s]=o;break}}return i}var me=["web_search","web_fetch","deep_research","browser_execution"],ye=["web-intelligence","browser-execution"],fe=["discovery","read-url","multi-source-research","interactive-browser"],Ae=["stateless","render-backend","interactive-session"],Re=["stateless","stateless-single-step","stateful-session-required"],Ee=["required","conditional","none"],_e=["browser-read","browser-authenticated-read","browser-state-changing"];var Se=["read-page","read-authenticated-page","fill-form","submit-form","download-file","reuse-session"],be=["web_search","web_fetch","deep_research","blocked"],Te=["requires-interaction","requires-login-state","requires-rendered-dom","requires-persistent-session","requires-state-changing-action"],Pe=["none","same-capability-once","degrade-only"];var Ce=["prefetch","sync_turn","on_pre_compress","on_session_end","on_delegation","on_memory_write"],Ie=["turn","sidechain","compress","session-end","agent-remember","auto-extract","implicit-extract","profile-extraction","dream"],he=["observe-only","parent-write","deny"];var ve=2,a={gatewayImage:"gateway.image.desktop-slim",whisperModelTiny:"speech.whisper.model.tiny",ffmpegWin32X64:"runtime.ffmpeg.win32-x64",nodeWin32X64:"runtime.node.win32-x64",dockerDesktopWin32X64:"runtime.docker-desktop.win32-x64",dockerDesktopDarwinX64:"runtime.docker-desktop.darwin-x64",dockerDesktopDarwinArm64:"runtime.docker-desktop.darwin-arm64"},y={desktopDockerBridge:"desktop.docker-bridge",desktopEmbeddedWin32X64:"desktop.embedded.win32-x64"};function U(e){return{...e,artifacts:e.artifacts.map(t=>({...t}))}}function Me(e){return{...e,assetIds:[...e.assetIds]}}function K(){return{[y.desktopDockerBridge]:{id:y.desktopDockerBridge,title:"Desktop Docker Bridge",platform:"any",assetIds:[a.gatewayImage,a.dockerDesktopWin32X64,a.dockerDesktopDarwinX64,a.dockerDesktopDarwinArm64],description:"Docker bridge mode downloads the desktop slim gateway image on demand."},[y.desktopEmbeddedWin32X64]:{id:y.desktopEmbeddedWin32X64,title:"Desktop Embedded Win32 x64",platform:"win32-x64",assetIds:[a.nodeWin32X64,a.ffmpegWin32X64,a.whisperModelTiny],description:"Embedded desktop mode requires the bundled Node/FFmpeg runtimes and the whisper model asset."}}}function W(e,t){return e.assets[t]}function V(e,t){return e.profiles[t]}function ke(e,t){let r=V(e,t);return r?r.assetIds.map(n=>W(e,n)).filter(n=>!!n):[]}function xe(e,t){return e.assets[t.id]=U(t),F(e)}function S(e){if(!e)return;let t=e.artifacts[0];if(!(!t?.url||!t.sha256||typeof t.size!="number"))return{version:e.version,sha256:t.sha256,size:t.size,url:t.url}}function F(e){let t=S(e.assets[a.gatewayImage]),r=S(e.assets[a.whisperModelTiny]);return{...e,gateway:t,whisperModel:r}}function L(e,t){if(!(typeof e.version!="string"||typeof e.url!="string"))return{...t,version:e.version,artifacts:[{fileName:e.url.split("/").pop()||`${t.id}.bin`,url:e.url,sha256:typeof e.sha256=="string"?e.sha256:void 0,size:typeof e.size=="number"?e.size:void 0}]}}function Oe(e){let t=e&&typeof e=="object"?e:{},r={},n=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[o,p]of Object.entries(n)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[o]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let o=L(t.gateway,{id:a.gatewayImage,title:"XiaoZhiClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});o&&(r[o.id]=o)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let o=L(t.whisperModel,{id:a.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});o&&(r[o.id]=o)}let c={...K()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[o,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[o]=Me(u))}return F({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:r,profiles:c})}var Ne=["pending","captured","failed","restored"],we=["file","directory","missing"],De=["metadata-only","workspace-copy","shadow-git"];var Le=["api-key","oauth","token","aws-sdk"],Ue=["rate_limit","auth","server_error","timeout","network","unknown"],Ke=["requiresOpenAiAnthropicToolPayload"];function We(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var j="openai-codex";function A(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function B(e){let t=A(e);return t==="volcengine-plan"?"volcengine":t==="qwen-coding"?"qwen":t==="byteplus-plan"?"byteplus":t}var Ve=B,Fe={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},je={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[j]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function b(e,t){let r=(e??"").toLowerCase();return!!r&&t.some(n=>r.includes(n))}function l(e){let t=A(e??"");return{...Fe,...je[t]}}function Be(e){return l(e).preserveAnthropicThinkingSignatures}function qe(e){let t=l(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function Ye(e){return l(e).anthropicToolSchemaMode==="openai-functions"}function He(e){return l(e).anthropicToolChoiceMode==="openai-string-modes"}function Ge(e){return l(e).openAiCompatTurnValidation}function ze(e){return l(e).providerFamily==="openai"}function Xe(e){return l(e).providerFamily==="anthropic"}function Je(e){return b(e.modelId,l(e.provider).dropThinkingBlockModelHints)}function Qe(e){let t=l(e.provider);return t.providerThoughtSignatureSanitization&&b(e.modelId,t.providerThoughtSignatureModelHints)}function $e(e,t){let r=l(e),n=r.transcriptToolCallIdMode;if(n==="strict9")return n;if(b(t,r.transcriptToolCallIdModelHints))return"strict9"}var T={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],qwen:["DASHSCOPE_API_KEY","QWEN_API_KEY"],"qwen-coding":["DASHSCOPE_API_KEY","QWEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Ze(){return[...new Set(Object.values(T).flat())]}function et(e){let t=A(e.provider),r=e.env??process.env,n=new Set(e.appliedEnvKeys??[]),i=o=>{let p=r[o]?.trim();if(!p)return null;let u=n.has(o)?`shell env: ${o}`:`env: ${o}`;return{apiKey:p,source:u}},c=e.resolveSpecialApiKey?.(t,r,n);if(c)return c;let s=T[t];if(!s||s.length===0)return null;for(let o of s){let p=i(o);if(p)return p}return null}export{oe as ACP_EXTENDED_METHODS,ie as ACP_EXTENDED_SESSION_UPDATE_TYPES,ne as ACP_METHODS,re as ACP_PROTOCOL_VERSION,x as ACP_SESSION_UPDATE_TYPES,H as AGENT_RPC_APPROVAL_METHODS,d as AGENT_RPC_ERROR_CODES,Y as AGENT_RPC_PROTOCOL_VERSION,k as AGENT_TEAM_WS_EVENT_NAMES,M as AGENT_WS_EVENT_NAMES,te as ALL_AGENT_WS_EVENT_NAMES,E as CAPABILITY_MANIFEST_DIFF_SECTIONS,ee as GATEWAY_RPC_METHODS,R as GatewayRpcContract,Ce as MEMORY_OBSERVATION_HOOK_VALUES,Ie as MEMORY_OBSERVATION_SOURCE_VALUES,he as MEMORY_WRITE_ACCESS_VALUES,De as MUTATION_CHECKPOINT_BACKEND_VALUES,we as MUTATION_CHECKPOINT_ENTRY_KIND_VALUES,Ne as MUTATION_CHECKPOINT_PHASE_VALUES,q as PETDEX_ANIMATION_IDS,Le as PROVIDER_RUNTIME_AUTH_MODE_VALUES,Ke as PROVIDER_RUNTIME_COMPAT_FLAG_VALUES,T as PROVIDER_RUNTIME_ENV_API_KEY_CANDIDATES,j as PROVIDER_RUNTIME_OPENAI_CODEX_PROVIDER_ID,Ue as PROVIDER_RUNTIME_VAULT_ERROR_TYPE_VALUES,ve as RESOURCE_MANIFEST_SCHEMA_VERSION,a as RUNTIME_ASSET_IDS,y as RUNTIME_PROFILE_IDS,Se as WEB_ACTION_SCOPE_VALUES,Ee as WEB_APPROVAL_DEFAULT_VALUES,ye as WEB_CAPABILITY_FAMILY_VALUES,me as WEB_CAPABILITY_ID_VALUES,be as WEB_DEGRADATION_TARGET_VALUES,Te as WEB_ESCALATION_REASON_VALUES,Ae as WEB_EXECUTION_MODE_VALUES,_e as WEB_POLICY_RISK_CLASS_VALUES,Pe as WEB_RETRY_POLICY_VALUES,Re as WEB_STATEFULNESS_VALUES,fe as WEB_TASK_MODE_VALUES,Z as buildAgentRpcMeta,f as classifyGatewayRpcMethod,m as cloneCapabilityManifestSnapshot,ge as createCapabilityManifestDiffPayload,K as createDefaultRuntimeResourceProfiles,de as deriveCapabilityToolNamespaces,ue as deriveCapabilityWorkspaceIds,S as getManifestShortcutEntry,W as getRuntimeResourceAsset,V as getRuntimeResourceProfile,ke as getRuntimeResourceProfileAssets,N as isAcpJsonRpcNotification,O as isAcpJsonRpcRequest,w as isAcpJsonRpcResponse,I as isAgentRpcNotification,P as isAgentRpcRequest,C as isAgentRpcResponse,Xe as isAnthropicProviderRuntimeFamily,pe as isExtendedSessionUpdateType,ze as isOpenAiProviderRuntimeFamily,ae as isStandardSessionUpdateType,Ze as listProviderRuntimeEnvApiKeyNames,le as mergeCapabilityManifestSnapshot,A as normalizeProviderRuntimeId,B as normalizeProviderRuntimeIdForAuth,Oe as normalizeRuntimeResourceManifest,se as parseAcpMessage,G as parseAgentRpcMessage,Be as preservesProviderRuntimeAnthropicThinkingSignatures,We as readProviderRuntimeCompatFlag,v as requireGatewayRpcMeta,h as requiresIdempotencyKey,qe as requiresOpenAiCompatibleAnthropicToolPayloadForProviderRuntime,l as resolveProviderRuntimeCapabilities,et as resolveProviderRuntimeEnvApiKey,Ve as resolveProviderRuntimeKeyFamily,$e as resolveProviderRuntimeTranscriptToolCallIdMode,Je as shouldDropThinkingBlocksForProviderRuntimeModel,Qe as shouldSanitizeProviderRuntimeThoughtSignaturesForModel,Ge as supportsOpenAiCompatTurnValidationForProviderRuntime,xe as upsertRuntimeResourceAsset,Ye as usesOpenAiFunctionAnthropicToolSchemaForProviderRuntime,He as usesOpenAiStringModeAnthropicToolChoiceForProviderRuntime};
|
|
1
|
+
var q=["idle","running-right","running-left","waving","jumping","failed","waiting","running","review"];var Y="1.0.0",d={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,TURN_ABORTED:-32e3,TURN_TIMEOUT:-32001,LLM_ERROR:-32010,LLM_AUTH_ERROR:-32011,LLM_RATE_LIMIT:-32012,LLM_QUOTA_EXHAUSTED:-32013,LLM_MODEL_NOT_FOUND:-32014,TOOL_INVOKE_FAILED:-32020,TOOL_TIMEOUT:-32021,PROTOCOL_MISMATCH:-32030,REQUEST_DEADLINE_EXCEEDED:-32040,REQUEST_CANCELLED:-32041,REQUEST_DEDUPED:-32042,REQUEST_IDEMPOTENCY_REQUIRED:-32043},H={REQUEST:"tool.approval.request"};function P(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&t.method.length>0}function C(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&(typeof t.id=="string"||typeof t.id=="number")&&!("method"in t)}function I(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function G(e){let t;try{t=JSON.parse(e)}catch{return null}return C(t)||P(t)||I(t)?t:null}import{randomUUID as z}from"node:crypto";var X=["settings.list","settings.get","settings.validate","provider.list","config.get","config.tunables","tools.list","todos.list","tasks.list","agents.list","agents.get","agents.processes","agents.scan","session.list","session.get","session.resolve","thread.list","project.list","files.list","files.gitStatus","instructions.list","instructions.read","skills.list","skills.stats","memory.atlas","memory.activity","memory.list","memory.read","memory.search","media.listModels","media.status","pet.status","agent.health","agent.metrics"],J=new Set(["memory.dream","memory.propose","memory.consolidate","media.stt","pet.forge","pet.asset.import","solo.start","solo.evaluate","product.plan","product.create","product.message"]),Q=["memory.","pet.","usage."],$=new Set(["memory.atlas","memory.activity","memory.list","memory.read","memory.search","memory.attachment.locate","memory.attachment.adopt","pet.status"]);function f(e){return J.has(e)?{channel:"task",mutability:"write",defaultTimeoutMs:12e4}:X.some(t=>e===t||e.startsWith(`${t}.`)||e.startsWith(t))?{channel:"query",mutability:"read",defaultTimeoutMs:1e4}:{channel:"task",mutability:"write",defaultTimeoutMs:3e4}}function h(e){return $.has(e)||f(e).mutability==="read"?!1:Q.some(t=>e.startsWith(t))}function Z(e,t={}){let r=t.now??Date.now(),n=f(e),i=t.timeoutMs??n.defaultTimeoutMs;return{requestId:t.requestId??z(),createdAt:r,deadlineAt:r+i,channel:t.channel??n.channel,idempotencyKey:t.idempotencyKey,traceId:t.traceId}}function v(e,t=Date.now()){let r=e.meta;if(!r||typeof r!="object")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta is required."}};if(typeof r.requestId!="string"||r.requestId.length===0)return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.requestId is required."}};if(r.channel!=="query"&&r.channel!=="task")return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.channel must be query or task."}};if(typeof r.createdAt!="number"||!Number.isFinite(r.createdAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.createdAt is required."}};if(typeof r.deadlineAt!="number"||!Number.isFinite(r.deadlineAt))return{ok:!1,error:{code:d.INVALID_REQUEST,message:"RPC request meta.deadlineAt is required."}};if(r.deadlineAt<=t)return{ok:!1,error:{code:d.REQUEST_DEADLINE_EXCEEDED,message:"RPC request deadline has already expired."}};let n=f(e.method).channel;return r.channel!==n?{ok:!1,error:{code:d.INVALID_REQUEST,message:`RPC request channel mismatch: expected ${n}, got ${r.channel}.`}}:h(e.method)&&(typeof r.idempotencyKey!="string"||r.idempotencyKey.length===0)?{ok:!1,error:{code:d.REQUEST_IDEMPOTENCY_REQUIRED,message:`RPC method ${e.method} requires meta.idempotencyKey.`}}:{ok:!0,meta:r}}var R=class{now;active=new Map;idempotency=new Map;counters={completedRequests:0,cancelledRequests:0,deadlineExceededRequests:0,dedupedRequests:0,lateResponsesDropped:0,invalidRequests:0};constructor(t={}){this.now=t.now??(()=>Date.now())}begin(t,r){let n=v({method:t,meta:r},this.now());if(!n.ok)return this.counters.invalidRequests+=1,{status:"rejected",error:n.error};if(r.idempotencyKey){let i=this.idempotency.get(r.idempotencyKey);if(i)return this.counters.dedupedRequests+=1,i.error?{status:"deduped",error:i.error}:{status:"deduped",result:i.result}}return this.active.set(r.requestId,{method:t,meta:r,cancelled:!1,startedAt:this.now()}),{status:"started"}}cancel(t,r="cancelled"){let n=this.active.get(t);return!n||n.cancelled?!1:(n.cancelled=!0,n.cancelReason=r,this.counters.cancelledRequests+=1,!0)}expire(t){return this.active.get(t)?(this.active.delete(t),this.counters.deadlineExceededRequests+=1,!0):!1}settle(t,r,n){let i=this.active.get(t);return i?(this.active.delete(t),i.cancelled?(this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"cancelled"}):i.meta.deadlineAt<=this.now()?(this.counters.deadlineExceededRequests+=1,this.counters.lateResponsesDropped+=1,{accepted:!1,reason:"deadline_exceeded"}):(this.counters.completedRequests+=1,i.meta.idempotencyKey&&this.idempotency.set(i.meta.idempotencyKey,{result:r,error:n,settledAt:this.now()}),{accepted:!0})):{accepted:!1,reason:"unknown"}}metrics(){return{activeRequests:this.active.size,...this.counters}}};var ee=["agent.health","agent.metrics","agent.cancel","session.list","session.get","session.create","session.update","session.delete","session.deleteAll","session.archive","session.moveToProject","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.update","project.purgeAll","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.move","files.copy","files.delete","files.search","files.undoOperation","files.gitStatus","turnBaseline.getSummary","turnBaseline.getFileDiff","turnBaseline.listRecent","turnBaseline.getFileBaseline","workingMaterials.get","workingMaterials.replace","workingMaterials.upsert","workingMaterials.remove","workingMaterials.reorder","skills.list","memory.list-files","memory.atlas","memory.activity","memory.propose","memory.consolidate","memory.update","memory.attachment.adopt","memory.attachment.locate"];var M=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","turn.file_changes","turn.tool_call","turn.tool_result","turn.tool_blocked","turn.reasoning_delta","turn.approval_request","turn.skill_instruction","turn.ask_user","turn.media_result","turn.media_progress","turn.media_usage","turn.media_capability_check","turn.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_started","turn.subagent_delta","turn.subagent_ended","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.progress","turn.tool_use_summary","turn.tool_selection_policy","turn.lifecycle","turn.document_maintenance","turn.artifact_contract","turn.usage_update","team.member.notification","session.info","session.recovery_pending","memory.updated","skills.updated","turn.memory_recall","turn.memory_written","pet.soul_ready","pet.reaction","pet.growth","pet.state","pet.confirm","pet.asset.updated","system.activity","workflow.created","workflow.updated","workflow.deleted","workflow.runStarted","workflow.runCompleted","workflow.runFailed","workflow.nodeStatus","workflow.triggerDropped","workflow.alert","workflow.approvalRequested","workflow.approvalTimedOut"],k=["solo.progress","solo.specProgress","solo.agentDelta","solo.agentActivity","solo.agentUsage","solo.evaluation","product.taskStarted","product.taskOutput","product.members","product.agentActivity","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.budgetWarning","product.checkpointed","product.completed","product.dagTopology","plan.interrupted","goal.run_state_changed","goal.phase_boundary","goal.goal_edited","goal.message_queued","goal.acceptance_updated"],te=[...M,...k];var re=1,ne={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_CLOSE:"session/close",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",SESSION_LOAD:"session/load",SESSION_CANCEL:"session/cancel",SESSION_UPDATE:"session/update",SESSION_REQUEST_PERMISSION:"session/request_permission",FS_READ_TEXT_FILE:"fs/read_text_file",FS_WRITE_TEXT_FILE:"fs/write_text_file"},oe={ABORT:"x/abort",DREAM:"x/dream",AGENTS_LIST:"x/agents.list",SOLO_START:"x/solo.start",SOLO_STATUS:"x/solo.status",SOLO_SELECT:"x/solo.select",SOLO_CANCEL:"x/solo.cancel",PRODUCT_CREATE:"x/product.create",PRODUCT_PLAN:"x/product.plan",PRODUCT_CONFIRM:"x/product.confirm",PRODUCT_MESSAGE:"x/product.message",PRODUCT_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_REPLAY:"x/product.replay",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",SOLO_MESSAGE:"x/solo.message",SOLO_EVALUATE:"x/solo.evaluate",SOLO_SPEC_CHAT:"x/solo.specChat",SOLO_SPEC_JUDGE:"x/solo.specJudge",WORKFLOW_CHAT:"x/workflow.chat",WORKFLOW_MATCH_INTENT:"x/workflow.matchIntent",PRODUCT_SUBSCRIBE:"x/product.subscribe",GOAL_START:"x/goal.start",GOAL_STATUS:"x/goal.status",GOAL_PAUSE:"x/goal.pause",GOAL_RESUME:"x/goal.resume",GOAL_UPDATE_GOAL:"x/goal.updateGoal",GOAL_STOP:"x/goal.stop",GOAL_MESSAGE:"x/goal.message",GOAL_SUBSCRIBE:"x/goal.subscribe",GOAL_EVENTS:"x/goal.events",MENTION_DELEGATE:"x/mention.delegate",MENTION_CANCEL:"x/mention.cancel",MENTION_LIST:"x/mention.list"},x={USER_MESSAGE_CHUNK:"user_message_chunk",AGENT_MESSAGE_CHUNK:"agent_message_chunk",AGENT_THOUGHT_CHUNK:"agent_thought_chunk",TOOL_CALL:"tool_call",TOOL_CALL_UPDATE:"tool_call_update",PLAN:"plan",USAGE_UPDATE:"usage_update",CONFIG_OPTION_UPDATE:"config_option_update",SESSION_INFO_UPDATE:"session_info_update",AVAILABLE_COMMANDS_UPDATE:"available_commands_update",CURRENT_MODE_UPDATE:"current_mode_update"},ie={X_SKILL_INSTRUCTION:"x_skill_instruction",X_SESSION_INFO:"x_session_info",X_RELAY:"x_relay"};function O(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function N(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function w(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function se(e){let t;try{t=JSON.parse(e)}catch{return null}return w(t)||O(t)||N(t)?t:null}function ae(e){return Object.values(x).includes(e)}function pe(e){return e.startsWith("x_")}var E=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function g(e){return e?e.map(t=>({...t})):void 0}function _(e){return e?e.map(t=>({...t})):void 0}function ce(e){return e?[...e]:void 0}function D(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,r)=>t.localeCompare(r))}function m(e){return{...e,toolNamespaces:[...e.toolNamespaces],workspaceIds:[...e.workspaceIds],...e.changedSections?{changedSections:[...e.changedSections]}:{},...e.installedCapabilities?{installedCapabilities:[...e.installedCapabilities]}:{},...e.enabledCapabilities?{enabledCapabilities:[...e.enabledCapabilities]}:{},...e.features?{features:[...e.features]}:{},...e.toolManifests?{toolManifests:g(e.toolManifests)}:{},...e.skillManifests?{skillManifests:g(e.skillManifests)}:{},...e.pluginManifests?{pluginManifests:g(e.pluginManifests)}:{},...e.mcpManifests?{mcpManifests:g(e.mcpManifests)}:{},...e.approvalPolicy?{approvalPolicy:{...e.approvalPolicy}}:{},...e.workspaceSummaries?{workspaceSummaries:_(e.workspaceSummaries)}:{}}}function le(e){let{previous:t,update:r}=e;return!(r.syncMode==="diff"&&t&&(!r.baseSnapshotVersion||t.snapshotVersion===r.baseSnapshotVersion))||!t?m(r):{...m(t),snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,...r.gatewayVersion!==void 0?{gatewayVersion:r.gatewayVersion}:{},...r.syncMode?{syncMode:r.syncMode}:{},...r.baseSnapshotVersion?{baseSnapshotVersion:r.baseSnapshotVersion}:{},...r.changedSections?{changedSections:[...r.changedSections]}:{},...r.toolNamespaces?{toolNamespaces:[...r.toolNamespaces]}:{},...r.workspaceIds?{workspaceIds:[...r.workspaceIds]}:{},...r.installedCapabilities?{installedCapabilities:[...r.installedCapabilities]}:{},...r.enabledCapabilities?{enabledCapabilities:[...r.enabledCapabilities]}:{},...r.features?{features:[...r.features]}:{},...r.approvalMode?{approvalMode:r.approvalMode}:{},...r.toolManifests?{toolManifests:g(r.toolManifests)}:{},...r.skillManifests?{skillManifests:g(r.skillManifests)}:{},...r.pluginManifests?{pluginManifests:g(r.pluginManifests)}:{},...r.mcpManifests?{mcpManifests:g(r.mcpManifests)}:{},...r.approvalPolicy?{approvalPolicy:{...r.approvalPolicy}}:{},...r.workspaceSummaries?{workspaceSummaries:_(r.workspaceSummaries)}:{}}}function de(e){return D(e.map(t=>t.name.split(".")[0]??"").filter(Boolean))}function ue(e){return D(e.map(t=>t.id))}function ge(e){let{previous:t,current:r}=e;if(!t)return{...m(r),syncMode:"full"};if(t.snapshotVersion===r.snapshotVersion)return null;let n=E.filter(s=>JSON.stringify(t[s])!==JSON.stringify(r[s]));if(n.length===E.length)return{...m(r),syncMode:"full"};let i={snapshotVersion:r.snapshotVersion,updatedAt:r.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:n,toolNamespaces:[...r.toolNamespaces],workspaceIds:[...r.workspaceIds]},c=i;for(let s of n){let o=r[s];if(o!==void 0)switch(s){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":c[s]=ce(o);break;case"approvalPolicy":c[s]={...o};break;case"workspaceSummaries":c[s]=_(o);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":c[s]=g(o);break;default:c[s]=o;break}}return i}var me=["web_search","web_fetch","deep_research","browser_execution"],ye=["web-intelligence","browser-execution"],fe=["discovery","read-url","multi-source-research","interactive-browser"],Ae=["stateless","render-backend","interactive-session"],Re=["stateless","stateless-single-step","stateful-session-required"],Ee=["required","conditional","none"],_e=["browser-read","browser-authenticated-read","browser-state-changing"];var Se=["read-page","read-authenticated-page","fill-form","submit-form","download-file","reuse-session"],Te=["web_search","web_fetch","deep_research","blocked"],be=["requires-interaction","requires-login-state","requires-rendered-dom","requires-persistent-session","requires-state-changing-action"],Pe=["none","same-capability-once","degrade-only"];var Ce=["prefetch","sync_turn","on_pre_compress","on_session_end","on_delegation","on_memory_write"],Ie=["turn","sidechain","compress","session-end","agent-remember","auto-extract","implicit-extract","profile-extraction","dream"],he=["observe-only","parent-write","deny"];var ve=2,a={gatewayImage:"gateway.image.desktop-slim",whisperModelTiny:"speech.whisper.model.tiny",ffmpegWin32X64:"runtime.ffmpeg.win32-x64",nodeWin32X64:"runtime.node.win32-x64",dockerDesktopWin32X64:"runtime.docker-desktop.win32-x64",dockerDesktopDarwinX64:"runtime.docker-desktop.darwin-x64",dockerDesktopDarwinArm64:"runtime.docker-desktop.darwin-arm64"},y={desktopDockerBridge:"desktop.docker-bridge",desktopEmbeddedWin32X64:"desktop.embedded.win32-x64"};function U(e){return{...e,artifacts:e.artifacts.map(t=>({...t}))}}function Me(e){return{...e,assetIds:[...e.assetIds]}}function K(){return{[y.desktopDockerBridge]:{id:y.desktopDockerBridge,title:"Desktop Docker Bridge",platform:"any",assetIds:[a.gatewayImage,a.dockerDesktopWin32X64,a.dockerDesktopDarwinX64,a.dockerDesktopDarwinArm64],description:"Docker bridge mode downloads the desktop slim gateway image on demand."},[y.desktopEmbeddedWin32X64]:{id:y.desktopEmbeddedWin32X64,title:"Desktop Embedded Win32 x64",platform:"win32-x64",assetIds:[a.nodeWin32X64,a.ffmpegWin32X64,a.whisperModelTiny],description:"Embedded desktop mode requires the bundled Node/FFmpeg runtimes and the whisper model asset."}}}function W(e,t){return e.assets[t]}function V(e,t){return e.profiles[t]}function ke(e,t){let r=V(e,t);return r?r.assetIds.map(n=>W(e,n)).filter(n=>!!n):[]}function xe(e,t){return e.assets[t.id]=U(t),F(e)}function S(e){if(!e)return;let t=e.artifacts[0];if(!(!t?.url||!t.sha256||typeof t.size!="number"))return{version:e.version,sha256:t.sha256,size:t.size,url:t.url}}function F(e){let t=S(e.assets[a.gatewayImage]),r=S(e.assets[a.whisperModelTiny]);return{...e,gateway:t,whisperModel:r}}function L(e,t){if(!(typeof e.version!="string"||typeof e.url!="string"))return{...t,version:e.version,artifacts:[{fileName:e.url.split("/").pop()||`${t.id}.bin`,url:e.url,sha256:typeof e.sha256=="string"?e.sha256:void 0,size:typeof e.size=="number"?e.size:void 0}]}}function Oe(e){let t=e&&typeof e=="object"?e:{},r={},n=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[o,p]of Object.entries(n)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.artifacts)||(r[o]=U(u))}if(!r[a.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let o=L(t.gateway,{id:a.gatewayImage,title:"XiaoZhiClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});o&&(r[o.id]=o)}if(!r[a.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let o=L(t.whisperModel,{id:a.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});o&&(r[o.id]=o)}let c={...K()},s=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[o,p]of Object.entries(s)){if(!p||typeof p!="object")continue;let u=p;!u.id||!Array.isArray(u.assetIds)||(c[o]=Me(u))}return F({schemaVersion:typeof t.schemaVersion=="number"?t.schemaVersion:2,channel:typeof t.channel=="string"?t.channel:void 0,publishedAt:typeof t.publishedAt=="string"?t.publishedAt:void 0,minElectronVersion:typeof t.minElectronVersion=="string"?t.minElectronVersion:void 0,releaseNotes:typeof t.releaseNotes=="string"?t.releaseNotes:void 0,assets:r,profiles:c})}var Ne=["pending","captured","failed","restored"],we=["file","directory","missing"],De=["metadata-only","workspace-copy","shadow-git"];var Le=["api-key","oauth","token","aws-sdk"],Ue=["rate_limit","auth","server_error","timeout","network","unknown"],Ke=["requiresOpenAiAnthropicToolPayload"];function We(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var j="openai-codex";function A(e){let t=e.trim().toLowerCase();return t==="z.ai"||t==="z-ai"?"zai":t==="opencode-zen"?"opencode":t==="kimi-code"?"kimi-coding":t==="bedrock"||t==="aws-bedrock"?"amazon-bedrock":t==="bytedance"||t==="doubao"?"volcengine":t}function B(e){let t=A(e);return t==="volcengine-plan"?"volcengine":t==="qwen-coding"?"qwen":t==="byteplus-plan"?"byteplus":t}var Ve=B,Fe={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},je={anthropic:{providerFamily:"anthropic"},"amazon-bedrock":{providerFamily:"anthropic"},"kimi-coding":{anthropicToolSchemaMode:"openai-functions",anthropicToolChoiceMode:"openai-string-modes",preserveAnthropicThinkingSignatures:!1},mistral:{transcriptToolCallIdMode:"strict9",transcriptToolCallIdModelHints:["mistral","mixtral","codestral","pixtral","devstral","ministral","mistralai"]},openai:{providerFamily:"openai"},[j]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function T(e,t){let r=(e??"").toLowerCase();return!!r&&t.some(n=>r.includes(n))}function l(e){let t=A(e??"");return{...Fe,...je[t]}}function Be(e){return l(e).preserveAnthropicThinkingSignatures}function qe(e){let t=l(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function Ye(e){return l(e).anthropicToolSchemaMode==="openai-functions"}function He(e){return l(e).anthropicToolChoiceMode==="openai-string-modes"}function Ge(e){return l(e).openAiCompatTurnValidation}function ze(e){return l(e).providerFamily==="openai"}function Xe(e){return l(e).providerFamily==="anthropic"}function Je(e){return T(e.modelId,l(e.provider).dropThinkingBlockModelHints)}function Qe(e){let t=l(e.provider);return t.providerThoughtSignatureSanitization&&T(e.modelId,t.providerThoughtSignatureModelHints)}function $e(e,t){let r=l(e),n=r.transcriptToolCallIdMode;if(n==="strict9")return n;if(T(t,r.transcriptToolCallIdModelHints))return"strict9"}var b={anthropic:["ANTHROPIC_OAUTH_TOKEN","ANTHROPIC_API_KEY"],chutes:["CHUTES_OAUTH_TOKEN","CHUTES_API_KEY"],zai:["ZAI_API_KEY","Z_AI_API_KEY"],opencode:["OPENCODE_API_KEY","OPENCODE_ZEN_API_KEY"],qwen:["DASHSCOPE_API_KEY","QWEN_API_KEY"],"qwen-coding":["DASHSCOPE_API_KEY","QWEN_API_KEY"],volcengine:["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_API_KEY","ARK_API_KEY","DOUBAO_API_KEY"],byteplus:["BYTEPLUS_API_KEY"],"byteplus-plan":["BYTEPLUS_API_KEY"],"kimi-coding":["KIMI_API_KEY","KIMICODE_API_KEY"],huggingface:["HUGGINGFACE_HUB_TOKEN","HF_TOKEN"],openai:["OPENAI_API_KEY"],voyage:["VOYAGE_API_KEY"],groq:["GROQ_API_KEY"],deepgram:["DEEPGRAM_API_KEY"],cerebras:["CEREBRAS_API_KEY"],xai:["XAI_API_KEY"],openrouter:["OPENROUTER_API_KEY"],litellm:["LITELLM_API_KEY"],"vercel-ai-gateway":["AI_GATEWAY_API_KEY"],"cloudflare-ai-gateway":["CLOUDFLARE_AI_GATEWAY_API_KEY"],moonshot:["MOONSHOT_API_KEY"],minimax:["MINIMAX_API_KEY"],"minimax-cn":["MINIMAX_CN_API_KEY","MINIMAX_API_KEY"],nvidia:["NVIDIA_API_KEY"],xiaomi:["XIAOMI_API_KEY"],synthetic:["SYNTHETIC_API_KEY"],venice:["VENICE_API_KEY"],mistral:["MISTRAL_API_KEY"],together:["TOGETHER_API_KEY"],qianfan:["QIANFAN_API_KEY"],ollama:["OLLAMA_API_KEY"],vllm:["VLLM_API_KEY"],kilocode:["KILOCODE_API_KEY"]};function Ze(){return[...new Set(Object.values(b).flat())]}function et(e){let t=A(e.provider),r=e.env??process.env,n=new Set(e.appliedEnvKeys??[]),i=o=>{let p=r[o]?.trim();if(!p)return null;let u=n.has(o)?`shell env: ${o}`:`env: ${o}`;return{apiKey:p,source:u}},c=e.resolveSpecialApiKey?.(t,r,n);if(c)return c;let s=b[t];if(!s||s.length===0)return null;for(let o of s){let p=i(o);if(p)return p}return null}export{oe as ACP_EXTENDED_METHODS,ie as ACP_EXTENDED_SESSION_UPDATE_TYPES,ne as ACP_METHODS,re as ACP_PROTOCOL_VERSION,x as ACP_SESSION_UPDATE_TYPES,H as AGENT_RPC_APPROVAL_METHODS,d as AGENT_RPC_ERROR_CODES,Y as AGENT_RPC_PROTOCOL_VERSION,k as AGENT_TEAM_WS_EVENT_NAMES,M as AGENT_WS_EVENT_NAMES,te as ALL_AGENT_WS_EVENT_NAMES,E as CAPABILITY_MANIFEST_DIFF_SECTIONS,ee as GATEWAY_RPC_METHODS,R as GatewayRpcContract,Ce as MEMORY_OBSERVATION_HOOK_VALUES,Ie as MEMORY_OBSERVATION_SOURCE_VALUES,he as MEMORY_WRITE_ACCESS_VALUES,De as MUTATION_CHECKPOINT_BACKEND_VALUES,we as MUTATION_CHECKPOINT_ENTRY_KIND_VALUES,Ne as MUTATION_CHECKPOINT_PHASE_VALUES,q as PETDEX_ANIMATION_IDS,Le as PROVIDER_RUNTIME_AUTH_MODE_VALUES,Ke as PROVIDER_RUNTIME_COMPAT_FLAG_VALUES,b as PROVIDER_RUNTIME_ENV_API_KEY_CANDIDATES,j as PROVIDER_RUNTIME_OPENAI_CODEX_PROVIDER_ID,Ue as PROVIDER_RUNTIME_VAULT_ERROR_TYPE_VALUES,ve as RESOURCE_MANIFEST_SCHEMA_VERSION,a as RUNTIME_ASSET_IDS,y as RUNTIME_PROFILE_IDS,Se as WEB_ACTION_SCOPE_VALUES,Ee as WEB_APPROVAL_DEFAULT_VALUES,ye as WEB_CAPABILITY_FAMILY_VALUES,me as WEB_CAPABILITY_ID_VALUES,Te as WEB_DEGRADATION_TARGET_VALUES,be as WEB_ESCALATION_REASON_VALUES,Ae as WEB_EXECUTION_MODE_VALUES,_e as WEB_POLICY_RISK_CLASS_VALUES,Pe as WEB_RETRY_POLICY_VALUES,Re as WEB_STATEFULNESS_VALUES,fe as WEB_TASK_MODE_VALUES,Z as buildAgentRpcMeta,f as classifyGatewayRpcMethod,m as cloneCapabilityManifestSnapshot,ge as createCapabilityManifestDiffPayload,K as createDefaultRuntimeResourceProfiles,de as deriveCapabilityToolNamespaces,ue as deriveCapabilityWorkspaceIds,S as getManifestShortcutEntry,W as getRuntimeResourceAsset,V as getRuntimeResourceProfile,ke as getRuntimeResourceProfileAssets,N as isAcpJsonRpcNotification,O as isAcpJsonRpcRequest,w as isAcpJsonRpcResponse,I as isAgentRpcNotification,P as isAgentRpcRequest,C as isAgentRpcResponse,Xe as isAnthropicProviderRuntimeFamily,pe as isExtendedSessionUpdateType,ze as isOpenAiProviderRuntimeFamily,ae as isStandardSessionUpdateType,Ze as listProviderRuntimeEnvApiKeyNames,le as mergeCapabilityManifestSnapshot,A as normalizeProviderRuntimeId,B as normalizeProviderRuntimeIdForAuth,Oe as normalizeRuntimeResourceManifest,se as parseAcpMessage,G as parseAgentRpcMessage,Be as preservesProviderRuntimeAnthropicThinkingSignatures,We as readProviderRuntimeCompatFlag,v as requireGatewayRpcMeta,h as requiresIdempotencyKey,qe as requiresOpenAiCompatibleAnthropicToolPayloadForProviderRuntime,l as resolveProviderRuntimeCapabilities,et as resolveProviderRuntimeEnvApiKey,Ve as resolveProviderRuntimeKeyFamily,$e as resolveProviderRuntimeTranscriptToolCallIdMode,Je as shouldDropThinkingBlocksForProviderRuntimeModel,Qe as shouldSanitizeProviderRuntimeThoughtSignaturesForModel,Ge as supportsOpenAiCompatTurnValidationForProviderRuntime,xe as upsertRuntimeResourceAsset,Ye as usesOpenAiFunctionAnthropicToolSchemaForProviderRuntime,He as usesOpenAiStringModeAnthropicToolChoiceForProviderRuntime};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createInterface as
|
|
3
|
-
`),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),o=e.match(/^---\n[\s\S]*?^category:\s*(.+)/m),n=e.match(/^---\n[\s\S]*?^author:\s*(.+)/m),i=e.match(/^---\n[\s\S]*?^requires:\s*(.+)/m),s=e.match(/^---\n[\s\S]*?^environments:\s*(.+)/m),a=e.match(/^---\n([\s\S]*?)\n---/)?.[1]??"";return{version:r?.[1],description:
|
|
4
|
-
`),r=e.findIndex(s=>/^description:/.test(s));if(r===-1)return;let o=e[r].replace(/^description:[ \t]*/,"").trim(),n=/^[>|][+-]?$/.test(o),i=[];!n&&o&&i.push(o);for(let s=r+1;s<e.length;s++){let a=e[s];if(!/^[ \t]/.test(a))break;let l=a.trim();l&&i.push(l)}if(i.length!==0)return i.join(" ").replace(/^["']|["']$/g,"").trim()||void 0}var E=new Map,b=new Map;function ge(t,e,r,o){let n=e.has(t.name),i=r.has(t.name),s=!ve(t.meta,o);return{name:t.name,filePath:t.filePath,baseDir:t.baseDir,globallyDisabled:n,projectDisabled:i,active:!n&&!i&&!s,systemGenerated:t.systemGenerated,description:t.meta.description,version:t.meta.version,category:t.meta.category,author:t.meta.author,requiredTools:t.meta.requiredTools,environments:t.meta.environments}}async function he(t){let e;try{e=await ie(t,{withFileTypes:!0})}catch{e=[]}let r=[];for(let s of e){if(!s.isDirectory()||s.name.startsWith("."))continue;let a=d(t,s.name),l=d(a,"SKILL.md");try{let y=await le(l);if(!y.isFile())continue;r.push({name:s.name,filePath:l,baseDir:a,mtimeMs:y.mtimeMs,size:y.size})}catch{continue}}r.sort((s,a)=>s.name.localeCompare(a.name));let o=r.map(s=>`${s.name}:${s.mtimeMs}:${s.size}`).join("|"),n=E.get(t);if(n&&n.fingerprint===o)return n.raw;let i=[];for(let s of r){let a;try{a=await ae(s.filePath,"utf8")}catch{continue}i.push({name:s.name,filePath:s.filePath,baseDir:s.baseDir,systemGenerated:pe(s.name),mtimeMs:s.mtimeMs,size:s.size,meta:me(a)})}return E.set(t,{fingerprint:o,raw:i}),be(t,i),i}async function ye(t,e){let r=v(),o=A(),n=t?R(t):new Set,i=b.get(r);return i||(i=he(r).finally(()=>b.delete(r)),b.set(r,i)),(await i).map(a=>ge(a,o,n,e))}async function D(t,e){return(await ye(t,e)).filter(r=>r.active)}function j(t){let e=v(),r=d(e,t),o=d(r,"SKILL.md");try{if(se(o).isFile())return{baseDir:r,filePath:o}}catch{}return null}function M(t){if(!t)return;let e=t.replace(/^\[|\]$/g,"").split(/[,\s]+/).map(r=>r.replace(/^["']|["']$/g,"").trim()).filter(Boolean);return e.length>0?e:void 0}function ve(t,e){if(t.environments&&e?.currentEnvironment&&!t.environments.includes(e.currentEnvironment))return!1;if(t.requiredTools){if(!e?.availableToolNames)return!1;let r=new Set(e.availableToolNames);return t.requiredTools.every(o=>r.has(o))}return!0}async function be(t,e){try{let o={version:1,entries:e.map(n=>({name:n.name,size:n.size,mtimeMs:n.mtimeMs,description:n.meta.description,version:n.meta.version,requiredTools:n.meta.requiredTools,environments:n.meta.environments}))};await ce(d(t,de),JSON.stringify(o,null,2),"utf8")}catch{}}var I="astraclaw_capabilities";async function L(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:(await D(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform})).map(Te)}};if(t.tool==="skill_view"){let e=typeof t.args.name=="string"?t.args.name.trim():"";if(!e)throw new Error("skill_view requires a skill name");let r=j(e);if(!r)throw new Error(`Skill not found: ${e}`);return{handled:!0,result:{name:e,content:Se(r.filePath,"utf8")}}}if(t.tool==="mcp_connectors_list"){let e=t.mcpServerFailures??[],r=e.length>0?{failedServers:e,note:`${e.length} configured MCP server(s) are unavailable this session; their tools are missing from this list.`}:{};if(!t.toolCatalog)return{handled:!0,result:{tools:[],note:"AstraClaw MCP connector catalog is not attached to this capability server instance.",...e.length>0?{failedServers:e}:{}}};let o=t.toolCatalog.getToolManifest().filter(n=>n.function.name.startsWith("mcp__")).map(n=>({toolName:n.function.name,server:Pe(n.function.name),name:_e(n.function.name),description:n.function.description,inputSchema:n.function.parameters}));return{handled:!0,result:{tools:o,count:o.length,...r}}}if(t.tool==="mcp_tool_call"){if(!t.toolCatalog)throw new Error("AstraClaw MCP connector catalog is not attached");let e=typeof t.args.toolName=="string"?t.args.toolName.trim():"";if(!e.startsWith("mcp__"))throw new Error("mcp_tool_call requires a connector toolName returned by mcp_connectors_list");let r=t.toolCatalog.findTool(e);if(!r?.execute)throw new Error(`MCP connector tool not found or not executable: ${e}`);let o=ke(t.args.args),n=`astraclaw_mcp_${we().slice(0,8)}`,i=await r.execute(n,o);return{handled:!0,result:{toolName:e,content:i.content,details:i.details,imageUrls:i.imageUrls}}}return{handled:!1}}function Te(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function ke(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function Pe(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function _e(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import p from"node:path";import{fileURLToPath as Ee}from"node:url";import{createRuntime as Me}from"mcporter";var O=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),Ce=new Set([...O,"agent"]);function $(t){return t?.riskLevel?t.riskLevel:t?.isDangerous?"system":t?.isReadOnly?"read":t?.isEgress?"external_egress":"write"}var S=class{toolPool=new Map;setTools(e){this.toolPool.clear();for(let r of e)this.toolPool.set(r.name,r)}addTool(e){this.toolPool.set(e.name,e)}addTools(e){for(let r of e)this.addTool(r)}removeTool(e){return this.toolPool.delete(e)}findTool(e){return this.toolPool.get(e)}hasTool(e){return this.toolPool.has(e)}getToolNames(){return Array.from(this.toolPool.keys())}getToolCount(){return this.toolPool.size}async executeTool(e,r,o,n){let i=this.toolPool.get(e);if(!i)throw new Error(`Tool not found: ${e}`);return i.execute(r,o,n)}getTools(){return Array.from(this.toolPool.values()).filter(e=>e.isEnabled?.()!==!1)}getToolManifest(){let e=[];for(let r of this.toolPool.values()){if(r.isEnabled?.()===!1)continue;let o=$(r);e.push({type:"function",function:{name:r.name,description:r.description,parameters:r.parameters},meta:{category:r.category??"other",displayName:r.displayName??{key:`capability.tool.${r.name}.name`,fallback:r.label},displayDescription:r.displayDescription??{key:`capability.tool.${r.name}.description`,fallback:""},parallelSafe:r.isConcurrencySafe??!1,riskLevel:o,isReadOnly:o==="read",isDangerous:o==="system",isDelete:r.isDelete??!1,isEgress:r.isEgress??o==="external_egress",egressCarriesData:r.egressCarriesData??!1}})}return e}},N=new S;function F(t){N.addTools(t)}function q(t){return N.removeTool(t)}var xe=new Set(["describe","fetch","find","get","inspect","list","query","read","search","stat"]),Ae=new Set(["append","copy","create","delete","edit","move","patch","remove","rename","set","update","upload","write"]);function U(t){let e=t.annotations,r=Re(t.name),o=r.some(l=>Ae.has(l)),n=r.some(l=>xe.has(l)),i=e?.destructiveHint===!0||o,s=e?.readOnlyHint===!0||!i&&n,a=s||e?.idempotentHint===!0&&!i;return{isReadOnly:s,isConcurrencySafe:a,isDestructive:i}}function Re(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var De=12e4,g=3,je=1e3;async function Ie(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),o=Math.max(1,e.attempts),n;for(let i=1;i<=o;i++)try{return await t()}catch(s){n=s,i<o&&(e.onRetry?.(i,s),await r(e.baseDelayMs*i))}throw n}var h=class{runtime=null;definitions=[];toolsByServer=new Map;injectedNames=new Set;log;workspaceRoot;toolCatalog;serverToolFilters=new Map;serverOAuth=new Map;failedServers=new Map;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}},this.workspaceRoot=e.workspaceRoot?p.resolve(e.workspaceRoot):void 0,this.toolCatalog=e.toolCatalog,this.definitions=e.servers.filter(r=>!r.disabled).filter(r=>{let o=Ve(r);for(let n of o)this.log.warn(`[mcp] rejected server "${r.name}": ${n.message}`);return r.tools&&this.serverToolFilters.set(r.name,r.tools),r.oauth===!0&&this.serverOAuth.set(r.name,!0),o.length===0}).map(r=>this.toServerDefinition(r)).filter(r=>r!==null)}markServerFailed(e,r,o){this.failedServers.set(e,{name:e,phase:r,error:o}),console.error(`[mcp] server "${e}" unavailable this session (${r}): ${o}`)}toServerDefinition(e){if((e.type??(e.url?"http":"stdio"))==="http"){if(!e.url)return this.log.warn(`[mcp] server "${e.name}" is type "http" but has no url, skipping`),this.markServerFailed(e.name,"config",'type "http" but no url'),null;let o;try{o=new URL(e.url)}catch{return this.log.warn(`[mcp] server "${e.name}" has an invalid url "${e.url}", skipping`),this.markServerFailed(e.name,"config",`invalid url "${e.url}"`),null}return{name:e.name,command:{kind:"http",url:o,headers:e.headers}}}return e.command?{name:e.name,command:{kind:"stdio",command:e.command,args:e.args??[],cwd:e.cwd??this.workspaceRoot??process.cwd()},env:e.env}:(this.log.warn(`[mcp] server "${e.name}" is type "stdio" but has no command, skipping`),this.markServerFailed(e.name,"config",'type "stdio" but no command'),null)}async connectAll(){this.definitions.length!==0&&(this.runtime=await Me({servers:this.definitions,clientInfo:{name:"qlogicagent",version:"1.0.0"},logger:{info:e=>this.log.info(`[mcp] ${e}`),warn:e=>this.log.warn(`[mcp] ${e}`),error:(e,r)=>this.log.warn(`[mcp] ${e}${r?` (${r instanceof Error?r.message:String(r)})`:""}`),debug:()=>{}}}),await Promise.allSettled(this.definitions.map(async e=>{try{let r=await Ie(()=>this.runtime.listTools(e.name,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e.name)!==!0}),{attempts:g,baseDelayMs:je,onRetry:(n,i)=>this.log.warn(`[mcp] connect attempt ${n}/${g} for ${e.name} failed, retrying: ${i instanceof Error?i.message:i}`)}),o=z(r,this.serverToolFilters.get(e.name));this.toolsByServer.set(e.name,o),this.failedServers.delete(e.name),this.log.info(`[mcp] connected to ${e.name} (${o.length}/${r.length} tools)`)}catch(r){this.log.warn(`[mcp] failed to connect to ${e.name} after ${g} attempts: ${r instanceof Error?r.message:r}`),this.markServerFailed(e.name,"connect",`${r instanceof Error?r.message:String(r)} (after ${g} attempts)`)}})))}injectTools(){for(let[e,r]of this.toolsByServer){let o=this.injectPortableTools(e,r);this.log.info(`[mcp] injected ${o.length} tools from ${e}`)}}async refreshServerTools(e){if(!this.runtime)throw new Error("MCP runtime is not connected");let r=await this.runtime.listTools(e,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e)!==!0}),o=z(r,this.serverToolFilters.get(e));return this.toolsByServer.set(e,o),this.failedServers.delete(e),this.retractServerTools(e),this.injectPortableTools(e,o),o.length}getConnectedServers(){return Array.from(this.toolsByServer.keys())}getFailedServers(){return Array.from(this.failedServers.values())}getToolCount(){let e=0;for(let r of this.toolsByServer.values())e+=r.length;return e}async disconnectAll(){for(let r of this.injectedNames)this.removeRegisteredTool(r);this.injectedNames.clear(),this.toolsByServer.clear(),this.failedServers.clear();let e=this.runtime;if(this.runtime=null,e)try{await e.close()}catch{}}toPortableTool(e,r){let o=U({name:r.name,description:r.description});return{name:`mcp__${G(e)}__${r.name}`,label:`[${e}] ${r.name}`,category:"mcp",description:r.description??`MCP tool from ${e}`,parameters:r.inputSchema??{type:"object",properties:{}},isConcurrencySafe:o.isConcurrencySafe,isReadOnly:o.isReadOnly,isDestructive:o.isDestructive,searchHint:`mcp ${e} ${r.name.replace(/[_-]+/g," ")}`,execute:async(n,i)=>{let s=this.runtime;if(!s)return{content:[{type:"text",text:`MCP server "${e}" is not connected.`}],details:{error:"mcp_not_connected"}};try{let a=await s.callTool(e,r.name,{args:i,timeoutMs:De});return Le(a)}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{error:l}}}}}}wrapToolsForWorkspaceBoundary(e){return this.workspaceRoot?e.map(r=>{if(!r.execute)return r;let o=r.execute;return{...r,execute:async(n,i,s)=>{let a=$e(r.name,i,this.workspaceRoot);return a?{content:[{type:"text",text:a}],details:{type:"mcp",error:"workspace_boundary"}}:o(n,i,s)}}}):e}injectPortableTools(e,r){let o=this.wrapToolsForWorkspaceBoundary(r.map(n=>this.toPortableTool(e,n)));this.registerTools(o);for(let n of o)this.injectedNames.add(n.name);return o}retractServerTools(e){let r=`mcp__${G(e)}__`;for(let o of[...this.injectedNames])o.startsWith(r)&&(this.removeRegisteredTool(o),this.injectedNames.delete(o))}registerTools(e){this.toolCatalog?this.toolCatalog.addTools(e):F(e)}removeRegisteredTool(e){return this.toolCatalog?.removeTool(e)??q(e)}};function Le(t){let e=t&&typeof t=="object"?t:{},o=(Array.isArray(e.content)?e.content:[]).filter(a=>!!a&&typeof a=="object"),n=o.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text),i=o.filter(a=>!(a.type==="text"&&typeof a.text=="string")).map(a=>typeof a.type=="string"&&a.type?a.type:"unknown"),s=n.join(`
|
|
2
|
+
import{createInterface as Ke}from"node:readline";import{existsSync as Qe,readFileSync as Ye}from"node:fs";import{readFileSync as ye}from"node:fs";import{randomUUID as ve}from"node:crypto";import{readdirSync as Tt,readFileSync as kt,statSync as re,writeFileSync as Pt}from"node:fs";import{readdir as oe,readFile as ne,stat as se,writeFile as ie}from"node:fs/promises";import{join as d}from"node:path";import{homedir as Q}from"node:os";import{join as u,resolve as at}from"node:path";import{existsSync as ct}from"node:fs";import{createHash as dt}from"node:crypto";var P=".qlogicagent";function p(){return process.env.QLOGICAGENT_HOME||u(Q(),P)}function v(){return u(p(),"skills")}function _(){return u(p(),"mcp.json")}function Y(t){if(!t)throw new Error("getProjectAgentDir: cwd is required (must not fall back to process.cwd())");return u(t,P)}function C(t){return u(Y(t),"skills-disabled.json")}import{readFileSync as Z,writeFileSync as ft,mkdirSync as gt,renameSync as ht}from"node:fs";import{dirname as vt,join as X}from"node:path";function f(){return{version:1,disabled:[]}}function ee(t){let e;try{e=Z(t,"utf8")}catch(n){return n.code==="ENOENT"?{list:f(),corrupt:!1}:(console.error(`[project-skill-manifest] Cannot read skill mute list at ${t} (${n instanceof Error?n.message:String(n)}); treating it as empty for reads \u2014 muted skills may reactivate.`),{list:f(),corrupt:!0})}let r;try{r=JSON.parse(e)}catch(n){return console.error(`[project-skill-manifest] Skill mute list at ${t} is corrupted (${n instanceof Error?n.message:String(n)}); treating it as empty for reads \u2014 muted skills may reactivate.`),{list:f(),corrupt:!0}}return!r||typeof r!="object"||!Array.isArray(r.disabled)?(console.error(`[project-skill-manifest] Skill mute list at ${t} has an unexpected shape; treating it as empty for reads \u2014 muted skills may reactivate.`),{list:f(),corrupt:!0}):{list:{version:1,disabled:[...new Set(r.disabled.filter(n=>typeof n=="string"&&n.trim().length>0))]},corrupt:!1}}function x(t){return ee(t).list}function te(){return X(p(),"skills-disabled.json")}function A(){return new Set(x(te()).disabled)}function R(t){return new Set(x(C(t)).disabled)}var ae=["auto-skill-","test-skill-"],le=".skills_prompt_snapshot.json";function ce(t){return ae.some(e=>t.startsWith(e))}function ue(t){let e=t.replace(/\r\n/g,`
|
|
3
|
+
`),r=e.match(/^---\n[\s\S]*?^version:\s*(\S+)/m),o=e.match(/^---\n[\s\S]*?^category:\s*(.+)/m),n=e.match(/^---\n[\s\S]*?^author:\s*(.+)/m),i=e.match(/^---\n[\s\S]*?^requires:\s*(.+)/m),s=e.match(/^---\n[\s\S]*?^environments:\s*(.+)/m),a=e.match(/^---\n([\s\S]*?)\n---/)?.[1]??"";return{version:r?.[1],description:de(a),category:o?.[1]?.trim()||void 0,author:n?.[1]?.trim()||void 0,requiredTools:M(i?.[1]),environments:M(s?.[1])}}function de(t){let e=t.split(`
|
|
4
|
+
`),r=e.findIndex(s=>/^description:/.test(s));if(r===-1)return;let o=e[r].replace(/^description:[ \t]*/,"").trim(),n=/^[>|][+-]?$/.test(o),i=[];!n&&o&&i.push(o);for(let s=r+1;s<e.length;s++){let a=e[s];if(!/^[ \t]/.test(a))break;let l=a.trim();l&&i.push(l)}if(i.length!==0)return i.join(" ").replace(/^["']|["']$/g,"").trim()||void 0}var E=new Map,S=new Map;function me(t,e,r,o){let n=e.has(t.name),i=r.has(t.name),s=!ge(t.meta,o);return{name:t.name,filePath:t.filePath,baseDir:t.baseDir,globallyDisabled:n,projectDisabled:i,active:!n&&!i&&!s,systemGenerated:t.systemGenerated,description:t.meta.description,version:t.meta.version,category:t.meta.category,author:t.meta.author,requiredTools:t.meta.requiredTools,environments:t.meta.environments}}async function pe(t){let e;try{e=await oe(t,{withFileTypes:!0})}catch{e=[]}let r=[];for(let s of e){if(!s.isDirectory()||s.name.startsWith("."))continue;let a=d(t,s.name),l=d(a,"SKILL.md");try{let y=await se(l);if(!y.isFile())continue;r.push({name:s.name,filePath:l,baseDir:a,mtimeMs:y.mtimeMs,size:y.size})}catch{continue}}r.sort((s,a)=>s.name.localeCompare(a.name));let o=r.map(s=>`${s.name}:${s.mtimeMs}:${s.size}`).join("|"),n=E.get(t);if(n&&n.fingerprint===o)return n.raw;let i=[];for(let s of r){let a;try{a=await ne(s.filePath,"utf8")}catch{continue}i.push({name:s.name,filePath:s.filePath,baseDir:s.baseDir,systemGenerated:ce(s.name),mtimeMs:s.mtimeMs,size:s.size,meta:ue(a)})}return E.set(t,{fingerprint:o,raw:i}),he(t,i),i}async function fe(t,e){let r=v(),o=A(),n=t?R(t):new Set,i=S.get(r);return i||(i=pe(r).finally(()=>S.delete(r)),S.set(r,i)),(await i).map(a=>me(a,o,n,e))}async function D(t,e){return(await fe(t,e)).filter(r=>r.active)}function j(t){let e=v(),r=d(e,t),o=d(r,"SKILL.md");try{if(re(o).isFile())return{baseDir:r,filePath:o}}catch{}return null}function M(t){if(!t)return;let e=t.replace(/^\[|\]$/g,"").split(/[,\s]+/).map(r=>r.replace(/^["']|["']$/g,"").trim()).filter(Boolean);return e.length>0?e:void 0}function ge(t,e){if(t.environments&&e?.currentEnvironment&&!t.environments.includes(e.currentEnvironment))return!1;if(t.requiredTools){if(!e?.availableToolNames)return!1;let r=new Set(e.availableToolNames);return t.requiredTools.every(o=>r.has(o))}return!0}async function he(t,e){try{let o={version:1,entries:e.map(n=>({name:n.name,size:n.size,mtimeMs:n.mtimeMs,description:n.meta.description,version:n.meta.version,requiredTools:n.meta.requiredTools,environments:n.meta.environments}))};await ie(d(t,le),JSON.stringify(o,null,2),"utf8")}catch{}}var I="astraclaw_capabilities";async function L(t){if(t.tool==="skills_list")return{handled:!0,result:{skills:(await D(t.projectRoot,{availableToolNames:t.availableToolNames,currentEnvironment:t.currentEnvironment??process.platform})).map(Se)}};if(t.tool==="skill_view"){let e=typeof t.args.name=="string"?t.args.name.trim():"";if(!e)throw new Error("skill_view requires a skill name");let r=j(e);if(!r)throw new Error(`Skill not found: ${e}`);return{handled:!0,result:{name:e,content:ye(r.filePath,"utf8")}}}if(t.tool==="mcp_connectors_list"){let e=t.mcpServerFailures??[],r=e.length>0?{failedServers:e,note:`${e.length} configured MCP server(s) are unavailable this session; their tools are missing from this list.`}:{};if(!t.toolCatalog)return{handled:!0,result:{tools:[],note:"AstraClaw MCP connector catalog is not attached to this capability server instance.",...e.length>0?{failedServers:e}:{}}};let o=t.toolCatalog.getToolManifest().filter(n=>n.function.name.startsWith("mcp__")).map(n=>({toolName:n.function.name,server:we(n.function.name),name:Te(n.function.name),description:n.function.description,inputSchema:n.function.parameters}));return{handled:!0,result:{tools:o,count:o.length,...r}}}if(t.tool==="mcp_tool_call"){if(!t.toolCatalog)throw new Error("AstraClaw MCP connector catalog is not attached");let e=typeof t.args.toolName=="string"?t.args.toolName.trim():"";if(!e.startsWith("mcp__"))throw new Error("mcp_tool_call requires a connector toolName returned by mcp_connectors_list");let r=t.toolCatalog.findTool(e);if(!r?.execute)throw new Error(`MCP connector tool not found or not executable: ${e}`);let o=be(t.args.args),n=`astraclaw_mcp_${ve().slice(0,8)}`,i=await r.execute(n,o);return{handled:!0,result:{toolName:e,content:i.content,details:i.details,imageUrls:i.imageUrls}}}return{handled:!1}}function Se(t){return{name:t.name,description:t.description,version:t.version,category:t.category,requiredTools:t.requiredTools,environments:t.environments}}function be(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function we(t){let e=t.split("__");return e.length>=3?e[1]??"":""}function Te(t){let e=t.split("__");return e.length>=3?e.slice(2).join("__"):t}import m from"node:path";import{fileURLToPath as xe}from"node:url";import{createRuntime as Ae}from"mcporter";var O=new Set(["gateway","agents_list","session_status","sessions_send","sessions_list","sessions_history","sessions_spawn","cron","config","workflow"]),ke=new Set([...O,"agent"]);function $(t){return t?.riskLevel?t.riskLevel:t?.isDangerous?"system":t?.isReadOnly?"read":t?.isEgress?"external_egress":"write"}var b=class{toolPool=new Map;setTools(e){this.toolPool.clear();for(let r of e)this.toolPool.set(r.name,r)}addTool(e){this.toolPool.set(e.name,e)}addTools(e){for(let r of e)this.addTool(r)}removeTool(e){return this.toolPool.delete(e)}findTool(e){return this.toolPool.get(e)}hasTool(e){return this.toolPool.has(e)}getToolNames(){return Array.from(this.toolPool.keys())}getToolCount(){return this.toolPool.size}async executeTool(e,r,o,n){let i=this.toolPool.get(e);if(!i)throw new Error(`Tool not found: ${e}`);return i.execute(r,o,n)}getTools(){return Array.from(this.toolPool.values()).filter(e=>e.isEnabled?.()!==!1)}getToolManifest(){let e=[];for(let r of this.toolPool.values()){if(r.isEnabled?.()===!1)continue;let o=$(r);e.push({type:"function",function:{name:r.name,description:r.description,parameters:r.parameters},meta:{category:r.category??"other",displayName:r.displayName??{key:`capability.tool.${r.name}.name`,fallback:r.label},displayDescription:r.displayDescription??{key:`capability.tool.${r.name}.description`,fallback:""},parallelSafe:r.isConcurrencySafe??!1,riskLevel:o,isReadOnly:o==="read",isDangerous:o==="system",isDelete:r.isDelete??!1,isEgress:r.isEgress??o==="external_egress",egressCarriesData:r.egressCarriesData??!1}})}return e}},N=new b;function F(t){N.addTools(t)}function U(t){return N.removeTool(t)}var Pe=new Set(["describe","fetch","find","get","inspect","list","query","read","search","stat"]),_e=new Set(["append","copy","create","delete","edit","move","patch","remove","rename","set","update","upload","write"]);function q(t){let e=t.annotations,r=Ce(t.name),o=r.some(l=>_e.has(l)),n=r.some(l=>Pe.has(l)),i=e?.destructiveHint===!0||o,s=e?.readOnlyHint===!0||!i&&n,a=s||e?.idempotentHint===!0&&!i;return{isReadOnly:s,isConcurrencySafe:a,isDestructive:i}}function Ce(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean)}var Re=12e4,g=3,Ee=1e3;async function Me(t,e){let r=e.sleep??(i=>new Promise(s=>setTimeout(s,i))),o=Math.max(1,e.attempts),n;for(let i=1;i<=o;i++)try{return await t()}catch(s){n=s,i<o&&(e.onRetry?.(i,s),await r(e.baseDelayMs*i))}throw n}var h=class{runtime=null;definitions=[];toolsByServer=new Map;injectedNames=new Set;log;workspaceRoot;toolCatalog;serverToolFilters=new Map;serverOAuth=new Map;failedServers=new Map;constructor(e){this.log=e.log??{info:()=>{},warn:()=>{}},this.workspaceRoot=e.workspaceRoot?m.resolve(e.workspaceRoot):void 0,this.toolCatalog=e.toolCatalog,this.definitions=e.servers.filter(r=>!r.disabled).filter(r=>{let o=Be(r);for(let n of o)this.log.warn(`[mcp] rejected server "${r.name}": ${n.message}`);return r.tools&&this.serverToolFilters.set(r.name,r.tools),r.oauth===!0&&this.serverOAuth.set(r.name,!0),o.length===0}).map(r=>this.toServerDefinition(r)).filter(r=>r!==null)}markServerFailed(e,r,o){this.failedServers.set(e,{name:e,phase:r,error:o}),console.error(`[mcp] server "${e}" unavailable this session (${r}): ${o}`)}toServerDefinition(e){if((e.type??(e.url?"http":"stdio"))==="http"){if(!e.url)return this.log.warn(`[mcp] server "${e.name}" is type "http" but has no url, skipping`),this.markServerFailed(e.name,"config",'type "http" but no url'),null;let o;try{o=new URL(e.url)}catch{return this.log.warn(`[mcp] server "${e.name}" has an invalid url "${e.url}", skipping`),this.markServerFailed(e.name,"config",`invalid url "${e.url}"`),null}return{name:e.name,command:{kind:"http",url:o,headers:e.headers}}}return e.command?{name:e.name,command:{kind:"stdio",command:e.command,args:e.args??[],cwd:e.cwd??this.workspaceRoot??process.cwd()},env:e.env}:(this.log.warn(`[mcp] server "${e.name}" is type "stdio" but has no command, skipping`),this.markServerFailed(e.name,"config",'type "stdio" but no command'),null)}async connectAll(){this.definitions.length!==0&&(this.runtime=await Ae({servers:this.definitions,clientInfo:{name:"qlogicagent",version:"1.0.0"},logger:{info:e=>this.log.info(`[mcp] ${e}`),warn:e=>this.log.warn(`[mcp] ${e}`),error:(e,r)=>this.log.warn(`[mcp] ${e}${r?` (${r instanceof Error?r.message:String(r)})`:""}`),debug:()=>{}}}),await Promise.allSettled(this.definitions.map(async e=>{try{let r=await Me(()=>this.runtime.listTools(e.name,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e.name)!==!0}),{attempts:g,baseDelayMs:Ee,onRetry:(n,i)=>this.log.warn(`[mcp] connect attempt ${n}/${g} for ${e.name} failed, retrying: ${i instanceof Error?i.message:i}`)}),o=z(r,this.serverToolFilters.get(e.name));this.toolsByServer.set(e.name,o),this.failedServers.delete(e.name),this.log.info(`[mcp] connected to ${e.name} (${o.length}/${r.length} tools)`)}catch(r){this.log.warn(`[mcp] failed to connect to ${e.name} after ${g} attempts: ${r instanceof Error?r.message:r}`),this.markServerFailed(e.name,"connect",`${r instanceof Error?r.message:String(r)} (after ${g} attempts)`)}})))}injectTools(){for(let[e,r]of this.toolsByServer){let o=this.injectPortableTools(e,r);this.log.info(`[mcp] injected ${o.length} tools from ${e}`)}}async refreshServerTools(e){if(!this.runtime)throw new Error("MCP runtime is not connected");let r=await this.runtime.listTools(e,{includeSchema:!0,disableOAuth:this.serverOAuth.get(e)!==!0}),o=z(r,this.serverToolFilters.get(e));return this.toolsByServer.set(e,o),this.failedServers.delete(e),this.retractServerTools(e),this.injectPortableTools(e,o),o.length}getConnectedServers(){return Array.from(this.toolsByServer.keys())}getFailedServers(){return Array.from(this.failedServers.values())}getToolCount(){let e=0;for(let r of this.toolsByServer.values())e+=r.length;return e}async disconnectAll(){for(let r of this.injectedNames)this.removeRegisteredTool(r);this.injectedNames.clear(),this.toolsByServer.clear(),this.failedServers.clear();let e=this.runtime;if(this.runtime=null,e)try{await e.close()}catch{}}toPortableTool(e,r){let o=q({name:r.name,description:r.description});return{name:`mcp__${G(e)}__${r.name}`,label:`[${e}] ${r.name}`,category:"mcp",description:r.description??`MCP tool from ${e}`,parameters:r.inputSchema??{type:"object",properties:{}},isConcurrencySafe:o.isConcurrencySafe,isReadOnly:o.isReadOnly,isDestructive:o.isDestructive,searchHint:`mcp ${e} ${r.name.replace(/[_-]+/g," ")}`,execute:async(n,i)=>{let s=this.runtime;if(!s)return{content:[{type:"text",text:`MCP server "${e}" is not connected.`}],details:{error:"mcp_not_connected"}};try{let a=await s.callTool(e,r.name,{args:i,timeoutMs:Re});return De(a)}catch(a){let l=a instanceof Error?a.message:String(a);return{content:[{type:"text",text:`MCP tool error: ${l}`}],details:{error:l}}}}}}wrapToolsForWorkspaceBoundary(e){return this.workspaceRoot?e.map(r=>{if(!r.execute)return r;let o=r.execute;return{...r,execute:async(n,i,s)=>{let a=Ie(r.name,i,this.workspaceRoot);return a?{content:[{type:"text",text:a}],details:{type:"mcp",error:"workspace_boundary"}}:o(n,i,s)}}}):e}injectPortableTools(e,r){let o=this.wrapToolsForWorkspaceBoundary(r.map(n=>this.toPortableTool(e,n)));this.registerTools(o);for(let n of o)this.injectedNames.add(n.name);return o}retractServerTools(e){let r=`mcp__${G(e)}__`;for(let o of[...this.injectedNames])o.startsWith(r)&&(this.removeRegisteredTool(o),this.injectedNames.delete(o))}registerTools(e){this.toolCatalog?this.toolCatalog.addTools(e):F(e)}removeRegisteredTool(e){return this.toolCatalog?.removeTool(e)??U(e)}};function De(t){let e=t&&typeof t=="object"?t:{},o=(Array.isArray(e.content)?e.content:[]).filter(a=>!!a&&typeof a=="object"),n=o.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text),i=o.filter(a=>!(a.type==="text"&&typeof a.text=="string")).map(a=>typeof a.type=="string"&&a.type?a.type:"unknown"),s=n.join(`
|
|
5
5
|
`);if(i.length>0){let a=[...new Set(i)].join(", ");s=s?`${s}
|
|
6
6
|
|
|
7
|
-
[${i.length} non-text blocks omitted: ${a}]`:`[output contains only non-text blocks: ${a}]`}return{content:[{type:"text",text:s||"(no text output)"}],...e.isError?{details:{error:"mcp_tool_error"}}:{}}}function G(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var
|
|
8
|
-
`);if(
|
|
7
|
+
[${i.length} non-text blocks omitted: ${a}]`:`[output contains only non-text blocks: ${a}]`}return{content:[{type:"text",text:s||"(no text output)"}],...e.isError?{details:{error:"mcp_tool_error"}}:{}}}function G(t){return t.replace(/[^a-zA-Z0-9_]/g,"_").toLowerCase()}var je=/(?:^|_)(path|paths|file|files|filename|filenames|dir|dirs|directory|directories|folder|folders|cwd|root|uri)(?:$|_)/i;function Ie(t,e,r){if(!r)return null;for(let o of T(e)){let n=$e(o.value,r);if(n&&!Ne(n.candidate,n.root,n.pathApi))return`Blocked: MCP tool "${t}" path "${o.value}" is outside the workspace boundary "${n.root}"`}return null}function T(t,e="",r=0){if(r>8)return[];if(typeof t=="string")return Le(e,t)?[{key:e,value:t}]:[];if(Array.isArray(t))return t.flatMap(n=>T(n,e,r+1));if(!t||typeof t!="object")return[];let o=[];for(let[n,i]of Object.entries(t))o.push(...T(i,n,r+1));return o}function Le(t,e){if(!je.test(t))return!1;let r=e.trim();return!r||/^https?:\/\//i.test(r)?!1:Oe(r)}function Oe(t){return m.isAbsolute(t)||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)||/^file:\/\//i.test(t)||t.includes("../")||t.includes("..\\")||t.startsWith(".\\")||t.startsWith("./")||t.includes("/")||t.includes("\\")}function $e(t,e){let r=t.trim();if(/^file:\/\//i.test(r))try{r=xe(r)}catch{return null}let o=W(r)||W(e)?m.win32:m,n=o.resolve(e);return{candidate:o.isAbsolute(r)?o.resolve(r):o.resolve(n,r),root:n,pathApi:o}}function Ne(t,e,r){let o=r.relative(e,t);return o===""||!o.startsWith("..")&&!r.isAbsolute(o)}function W(t){return/^[A-Za-z]:[\\/]/.test(t)||/^\\\\/.test(t)}function J(t){if(!t||typeof t!="object")return[];let e=t,r=[],o=e.mcpServers??e.servers??e;for(let[n,i]of Object.entries(o)){if(!i||typeof i!="object")continue;let s=i;if(typeof s.url=="string"){r.push({name:n,type:"http",url:s.url,headers:s.headers&&typeof s.headers=="object"?s.headers:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:B(s.tools)});continue}typeof s.command=="string"&&r.push({name:n,type:"stdio",command:s.command,args:Array.isArray(s.args)?s.args:void 0,env:s.env&&typeof s.env=="object"?s.env:void 0,cwd:typeof s.cwd=="string"?s.cwd:void 0,disabled:s.disabled===!0,oauth:s.oauth===!0,tools:B(s.tools)})}return r}function z(t,e){let r=new Set(e?.include??[]),o=new Set(e?.exclude??[]);return t.filter(n=>r.size>0&&!r.has(n.name)?!1:!o.has(n.name))}function B(t){if(!t||typeof t!="object")return;let e=t,r=H(e.include),o=H(e.exclude);if(!(!r&&!o))return{...r?{include:r}:{},...o?{exclude:o}:{}}}function H(t){if(!Array.isArray(t))return;let e=t.filter(r=>typeof r=="string"&&r.trim().length>0);return e.length>0?e:void 0}var Fe=new Set(["bash","sh","zsh","fish","cmd","cmd.exe","powershell","powershell.exe","pwsh","pwsh.exe"]),Ue=new Set(["-c","/c","-command","-encodedcommand","-e"]),qe=["curl","wget","invokewebrequest","invoke-restmethod","iwr","irm","nc","netcat"],Ge=["env","processenv","apikey","api_key","token","secret","credential","credentials","awsaccesskey","awssecret"],We=["authorizedkeys","sshknownhosts","crontab","launchctl","schtasks","startup","runkey","runonce","bashrc","profile"],ze=/\bssh-(?:rsa|ed25519|ecdsa-[^\s]+)\s+[A-Za-z0-9+/=]{40,}/i;function Be(t){let e=[],r=[t.command??"",...t.args??[],...Object.keys(t.env??{}),...Object.values(t.env??{})].join(`
|
|
8
|
+
`);if(ze.test(r)&&e.push({code:"ioc_public_key",message:"configuration contains an inline SSH public key IOC"}),(t.type??(t.url?"http":"stdio"))!=="stdio"||!He(t.command))return e;let o=Je(t.args??[]);if(!o)return e;let n=Ve(o);return w(n,We)&&e.push({code:"persistence",message:"stdio shell command attempts a persistence write"}),w(n,qe)&&w(n,Ge)&&e.push({code:"dangerous_egress",message:"stdio shell command combines network egress with likely secret access"}),e}function He(t){if(!t)return!1;let e=m.basename(t).toLowerCase();return Fe.has(e)}function Je(t){for(let e=0;e<t.length;e++){let r=t[e]?.toLowerCase();if(r&&Ue.has(r))return t.slice(e+1).join(" ")}return""}function Ve(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"")}function w(t,e){return e.some(r=>t.includes(r))}var Ze=[{name:"skills_list",description:"List AstraClaw skills active for the current workspace.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{name:"skill_view",description:"Read the full SKILL.md instructions for one AstraClaw skill.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Skill name from skills_list."}},required:["name"],additionalProperties:!1}},{name:"mcp_connectors_list",description:"List MCP connector tools installed in AstraClaw's Plugins page and shared with this external agent.",inputSchema:{type:"object",properties:{},additionalProperties:!1}},{name:"mcp_tool_call",description:"Call one AstraClaw shared MCP connector tool by toolName from mcp_connectors_list.",inputSchema:{type:"object",properties:{toolName:{type:"string",description:"Connector tool name, for example mcp__filesystem__read_text_file."},args:{type:"object",description:"Arguments for the connector tool."}},required:["toolName"],additionalProperties:!1}}],k=class{tools=new Map;findTool(e){return this.tools.get(e)}getToolManifest(){return Array.from(this.tools.values()).map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))}getToolNames(){return Array.from(this.tools.keys())}setTools(e){this.tools.clear(),this.addTools(e)}addTool(e){this.tools.set(e.name,e)}addTools(e){for(let r of e)this.addTool(r)}removeTool(e){return this.tools.delete(e)}},c=null,Xe=Ke({input:process.stdin,crlfDelay:Number.POSITIVE_INFINITY});Xe.on("line",t=>{et(t)});async function et(t){let e=t.trim();if(!e)return;let r;try{r=JSON.parse(e)}catch{return}if(r.id===void 0||r.id===null)return r.method==="notifications/initialized",void 0;try{let o=await tt(r);K({jsonrpc:"2.0",id:r.id,result:o})}catch(o){K({jsonrpc:"2.0",id:r.id,error:{code:-32603,message:o instanceof Error?o.message:String(o)}})}}async function tt(t){switch(t.method){case"initialize":return{protocolVersion:"2024-11-05",capabilities:{tools:{}},serverInfo:{name:I,version:"1.0.0"}};case"tools/list":return{tools:Ze};case"tools/call":{let e=V(t.params),r=typeof e.name=="string"?e.name:"",o=V(e.arguments),n=rt(),i=r==="mcp_connectors_list"||r==="mcp_tool_call"?await ot(n):void 0,s=await L({tool:r,args:o,projectRoot:n,toolCatalog:i,mcpServerFailures:i?c?.manager?.getFailedServers():void 0});if(!s.handled)throw new Error(`Unknown tool: ${r}`);return{content:[{type:"text",text:JSON.stringify(s.result)}]}}default:throw new Error(`Unknown method: ${t.method}`)}}function rt(){return process.env.ASTRACLAW_PROJECT_ROOT||process.env.QLOGICAGENT_PROJECT_ROOT||process.cwd()}async function ot(t){if(c?.projectRoot===t)return await c.ready,c.catalog;c?.manager?.disconnectAll().catch(()=>{});let e=new k,r=new h({servers:nt(),workspaceRoot:t,toolCatalog:e,log:{info:n=>process.stderr.write(`${n}
|
|
9
9
|
`),warn:n=>process.stderr.write(`${n}
|
|
10
|
-
`)}}),o=r.connectAll().then(()=>r.injectTools());return
|
|
10
|
+
`)}}),o=r.connectAll().then(()=>r.injectTools());return c={projectRoot:t,catalog:e,manager:r,ready:o},await o,e}function nt(){let t=process.env.ASTRACLAW_MCP_CONFIG_PATH||_();if(!Qe(t))return[];try{let e=Ye(t,"utf8").replace(/^\uFEFF/,"");return J(JSON.parse(e))}catch(e){return process.stderr.write(`[astraclaw-native-mcp] failed to read MCP config: ${e instanceof Error?e.message:String(e)}
|
|
11
11
|
`),[]}}function V(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{}}function K(t){process.stdout.write(`${JSON.stringify(t)}
|
|
12
12
|
`)}
|
|
@@ -78,6 +78,39 @@ export declare function buildExternalHistoryPreamble(messages: Array<{
|
|
|
78
78
|
role: string;
|
|
79
79
|
content: unknown;
|
|
80
80
|
}>): string;
|
|
81
|
+
/** Wraps the owner-level global memory cheat sheet (preferences/boundaries) for an external
|
|
82
|
+
* agent's cold open. Third-party agents (codex/claude/...) run their own brains and never see
|
|
83
|
+
* our per-turn memory channel — without this, a user's standing preferences vanish the moment
|
|
84
|
+
* they switch agents. Injection frequency is ONCE PER PROCESS CONTEXT: it rides the same
|
|
85
|
+
* cold-spawn moment that (re)builds the agent's context (first turn of a session, or a respawn
|
|
86
|
+
* after restart/eviction — where the full history is re-sent anyway), and never on warm turns.
|
|
87
|
+
* That is the floor for a stateless external process, not a per-message tax. Size is capped by
|
|
88
|
+
* readUserIndexForPrompt itself (2048 chars / 40 lines, visible truncation marker). */
|
|
89
|
+
export declare function buildExternalMemoryPreamble(globalIndex: string | null): string;
|
|
90
|
+
/**
|
|
91
|
+
* Decide how a native-cwd session resumes on a COLD spawn, and whether that resume already carries
|
|
92
|
+
* our injected global memory sheet (so the caller can skip re-injecting it). Pure given its inputs.
|
|
93
|
+
*
|
|
94
|
+
* - BINDING resume (a `nativeBinding.nativeSessionId` persisted by a prior app turn): that prior
|
|
95
|
+
* turn injected the sheet into the prompt codex/claude recorded in its OWN rollout, so the
|
|
96
|
+
* restored context carries it → resumedFromBinding=true (skip re-inject).
|
|
97
|
+
* - LAZY-MIGRATION resume (no binding yet, but the canonical id exists in the native store — a
|
|
98
|
+
* session the user may have started in codex/claude directly): its rollout has NEVER seen our
|
|
99
|
+
* sheet → resumedFromBinding=false (inject once; after this turn the binding persists and
|
|
100
|
+
* subsequent resumes take the binding branch, injecting exactly once total).
|
|
101
|
+
* - Neither (brand-new session): no resume → inject as a normal cold open.
|
|
102
|
+
*
|
|
103
|
+
* Conflating binding with lazy-migration (resume===bound) silently starves migrated sessions of the
|
|
104
|
+
* user's preferences — the whole point of the injection is that they follow the user across agents.
|
|
105
|
+
*/
|
|
106
|
+
export declare function resolveNativeColdResume(input: {
|
|
107
|
+
sessionId: string;
|
|
108
|
+
boundNativeSessionId: string | undefined;
|
|
109
|
+
nativeSessionExists: () => Promise<boolean>;
|
|
110
|
+
}): Promise<{
|
|
111
|
+
effectiveResume: string | undefined;
|
|
112
|
+
resumedFromBinding: boolean;
|
|
113
|
+
}>;
|
|
81
114
|
/** Pre-warm an external agent's process (on agent-select) so the first message skips the cold start. */
|
|
82
115
|
export declare function handleAgentsWarm(this: AgentsHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
83
116
|
export declare function handleAgentsPrompt(this: AgentsHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type CommunityConsentClient } from "../../runtime/community/community-consent-client.js";
|
|
2
2
|
import { type AgentRpcError, type AgentRpcRequest } from "../../protocol/wire/index.js";
|
|
3
|
-
export type { CommunityConsentClient, CommunityInstallRiskTier, CommunityInstallResolution,
|
|
3
|
+
export type { CommunityConsentClient, CommunityInstallRiskTier, CommunityInstallResolution, } from "../../runtime/community/community-consent-client.js";
|
|
4
4
|
export interface CommunityHandlerHost {
|
|
5
5
|
resolveCommunityConsentClient?: () => CommunityConsentClient | null;
|
|
6
6
|
sendResponse(id: string | number, result?: unknown, error?: AgentRpcError): void;
|
|
@@ -9,7 +9,6 @@ export interface CommunityHandlerHost {
|
|
|
9
9
|
/** Active owner id, so community pet install/publish land in the same profile pet.status reads. */
|
|
10
10
|
memoryUserId?: string;
|
|
11
11
|
}
|
|
12
|
-
export declare function handleCommunityMatchRegistry(this: CommunityHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
13
12
|
export declare function handleCommunityResolveInstall(this: CommunityHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
14
13
|
export declare function handleCommunityListResourceVersions(this: CommunityHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
15
14
|
export declare function handleCommunityInstallResource(this: CommunityHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
@@ -32,6 +32,13 @@ export interface MemoryHandlerHost {
|
|
|
32
32
|
export declare function handleMemoryList(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
33
33
|
/** memory.list-files: returns actual topic files from memdir. */
|
|
34
34
|
export declare function handleMemoryListFiles(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* memory.proposals: pending factual proposals (implicit-extract / feedback /
|
|
37
|
+
* dream) awaiting corroboration — the candidate surface of the proposal
|
|
38
|
+
* consumer. action=list (default) returns them; action=confirm/dismiss
|
|
39
|
+
* resolves one (confirm commits with manual authority; dismiss rejects).
|
|
40
|
+
*/
|
|
41
|
+
export declare function handleMemoryProposals(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
35
42
|
/**
|
|
36
43
|
* memory.atlas: returns full L2 vector-memory records (wire-safe, no embedding
|
|
37
44
|
* blob) plus category roll-ups, for the 3D memory atlas visualization.
|
|
@@ -42,7 +49,6 @@ export declare function handleMemoryAtlas(this: MemoryHandlerHost, msg: AgentRpc
|
|
|
42
49
|
* powering the atlas timeline ticks and the "memory digest" panel.
|
|
43
50
|
*/
|
|
44
51
|
export declare function handleMemoryActivity(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
45
|
-
export declare function handleMemoryObserve(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
46
52
|
export declare function handleMemoryPropose(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
47
53
|
export declare function handleMemoryConsolidate(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
48
54
|
export declare function handleMemoryRead(this: MemoryHandlerHost, msg: AgentRpcRequest): Promise<void>;
|
|
@@ -134,6 +134,16 @@ export declare function injectSkillContextBeforeLastUser(messages: ChatMessage[]
|
|
|
134
134
|
* switch never re-encodes the byte-stable prefix or the conversation history. The original
|
|
135
135
|
* array/objects are never mutated.
|
|
136
136
|
*/
|
|
137
|
+
/**
|
|
138
|
+
* Two-layer memory INDEX block for the per-turn conversation channel (global
|
|
139
|
+
* owner cheat-sheet first, then project notes; injected before the last user
|
|
140
|
+
* message next to the domain block). Living here instead of the system prompt
|
|
141
|
+
* is deliberate: INDEX content changes whenever the agent takes a note, and as
|
|
142
|
+
* a volatile system-prompt section every memory(add) re-encoded the byte-stable
|
|
143
|
+
* prefix plus the whole conversation history on the next turn. In the per-turn
|
|
144
|
+
* channel only the tail changes — the cached prefix survives.
|
|
145
|
+
*/
|
|
146
|
+
export declare function buildMemoryIndexBlock(globalBlock: string | null, projectBlock: string | null): string | null;
|
|
137
147
|
export declare function injectDomainGuidanceBeforeLastUser(messages: ChatMessage[], domainGuidance: string): ChatMessage[];
|
|
138
148
|
export declare function getFocusedAttachmentModelPurposeForTurn(messages: ChatMessage[]): FocusedAttachmentModelPurpose | null;
|
|
139
149
|
export declare function refreshPermissionCheckerToolMeta(permissionChecker: PermissionMetadataResolver | null | undefined, tools: ToolDefinition[]): void;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cli-side wiring of PlannerMemoryContext (orchestration must not import
|
|
3
|
+
* skills/memory directly — same boundary as memory-hooks' procedureTag).
|
|
4
|
+
*
|
|
5
|
+
* globalIndex reads the owner cheat-sheet fresh每次 (reflects mid-run edits);
|
|
6
|
+
* search resolves the provider lazily and returns [] when long-term memory is
|
|
7
|
+
* unavailable — "no provider" is an empty brief, not an error (the brief
|
|
8
|
+
* builder traces real search failures separately).
|
|
9
|
+
*/
|
|
10
|
+
import type { PlannerMemoryContext } from "../orchestration/planner-memory-brief.js";
|
|
11
|
+
export interface OrchestrationMemoryHost {
|
|
12
|
+
memoryProvider?: {
|
|
13
|
+
search(query: string, userId: string, options?: {
|
|
14
|
+
limit?: number;
|
|
15
|
+
}): Promise<Array<{
|
|
16
|
+
text: string;
|
|
17
|
+
}>>;
|
|
18
|
+
} | null;
|
|
19
|
+
memoryUserId?: string;
|
|
20
|
+
ensureMemoryProvider?(): void;
|
|
21
|
+
}
|
|
22
|
+
export declare function buildOrchestrationMemoryContext(host: OrchestrationMemoryHost): PlannerMemoryContext;
|
|
@@ -15,6 +15,7 @@ import type { AgentProcessManager } from "../runtime/infra/agent-process.js";
|
|
|
15
15
|
import type { AcpDetector } from "../runtime/infra/acp-detector.js";
|
|
16
16
|
import type { AgentConfigStore } from "../runtime/infra/agent-config-store.js";
|
|
17
17
|
import type { ProductPhase, ProductCreateParams, ProductStatus, ProductSummary } from "../protocol/wire/acp-agent-management.js";
|
|
18
|
+
import { type PlannerMemoryContext } from "./planner-memory-brief.js";
|
|
18
19
|
import type { DagMutation } from "./product-planner.js";
|
|
19
20
|
import type { ProductLeaderCoordinator } from "./product-run-coordinator.js";
|
|
20
21
|
export type { ProductLeaderCoordinator } from "./product-run-coordinator.js";
|
|
@@ -83,6 +84,10 @@ export declare class ProductOrchestrator {
|
|
|
83
84
|
private sessions;
|
|
84
85
|
constructor(processManager: AgentProcessManager, acpDetector: AcpDetector, configStore: AgentConfigStore | null, callbacks?: ProductCallbacks, leaderCoordinator?: ProductLeaderCoordinator | undefined);
|
|
85
86
|
setLeaderCoordinator(leaderCoordinator: ProductLeaderCoordinator): void;
|
|
87
|
+
/** (a) Owner global cheat-sheet source for member dispatches (cli-injected;
|
|
88
|
+
* orchestration never imports skills directly). */
|
|
89
|
+
private memoryContext?;
|
|
90
|
+
setMemoryContext(memoryContext: PlannerMemoryContext): void;
|
|
86
91
|
/**
|
|
87
92
|
* Create a new Product Mode session.
|
|
88
93
|
*/
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { AgentProcessManager } from "../runtime/infra/agent-process.js";
|
|
2
2
|
import type { AcpDetector } from "../runtime/infra/acp-detector.js";
|
|
3
|
+
import { type PlannerMemoryContext } from "./planner-memory-brief.js";
|
|
3
4
|
import type { ProductOrchestrator } from "./agent-instance.js";
|
|
4
5
|
import type { LeaderPort, PhaseRunnerPort } from "./goal-loop-coordinator.js";
|
|
5
6
|
import { type AcceptanceCriterion, type AcceptanceDelta, type PhaseSpec } from "./goal-run-types.js";
|
|
@@ -59,6 +60,9 @@ export interface LeaderAdapterDeps {
|
|
|
59
60
|
orchestrator: ProductOrchestrator;
|
|
60
61
|
/** Stable id used as the leader process memberId (one persistent leader per goal-run). */
|
|
61
62
|
goalRunId: string;
|
|
63
|
+
/** (c) Planning-time memory: ONE search per run + global cheat-sheet into the
|
|
64
|
+
* checklist/plan prompts. Optional — planning runs without it. */
|
|
65
|
+
memoryContext?: PlannerMemoryContext;
|
|
62
66
|
log?: {
|
|
63
67
|
info(msg: string): void;
|
|
64
68
|
warn(msg: string): void;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Memory context for long-run orchestration (Product / goal-mode / Solo).
|
|
3
|
+
*
|
|
4
|
+
* Two deliberately different depths — the design decision is graduated, not
|
|
5
|
+
* uniform (worker 每轮召回被否决:杂讯+成本×成员×轮数+破坏验收可复现):
|
|
6
|
+
* (a) EVERY member dispatch carries the owner's global cheat-sheet — the
|
|
7
|
+
* 2KB baseline (language, boundaries, style) any executor must honor.
|
|
8
|
+
* Self-hosted qlogicagent workers already inject it per-turn; this
|
|
9
|
+
* covers third-party workers and is harmlessly redundant otherwise.
|
|
10
|
+
* (c) The LEADER does ONE memory search at planning time (run-scoped) and
|
|
11
|
+
* carries the hits into checklist derivation + phase planning — long
|
|
12
|
+
* tasks plan once and execute many turns, so retrieval belongs to the
|
|
13
|
+
* planning step, not the execution loop.
|
|
14
|
+
*
|
|
15
|
+
* Everything here is injected (no direct skills import from orchestration);
|
|
16
|
+
* the cli wiring supplies readUserIndexForPrompt + provider.search.
|
|
17
|
+
*/
|
|
18
|
+
export interface PlannerMemoryContext {
|
|
19
|
+
/** Owner-level global INDEX (cheat-sheet). Null when absent. */
|
|
20
|
+
globalIndex(): string | null;
|
|
21
|
+
/** One-shot L2 search (goal text as query). Optional — planning must run without it. */
|
|
22
|
+
search?(query: string): Promise<Array<{
|
|
23
|
+
text: string;
|
|
24
|
+
}>>;
|
|
25
|
+
}
|
|
26
|
+
export interface PlannerMemoryLog {
|
|
27
|
+
warn(msg: string): void;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* (c) Planning-time brief: global cheat-sheet + goal-relevant L2 hits.
|
|
31
|
+
* Returns "" when there is nothing — callers splice it in only when non-empty.
|
|
32
|
+
* A failed search degrades to cheat-sheet-only WITH a trace (never silently).
|
|
33
|
+
*/
|
|
34
|
+
export declare function buildPlannerMemoryBrief(ctx: PlannerMemoryContext | undefined, goal: string, log?: PlannerMemoryLog): Promise<string>;
|
|
35
|
+
/**
|
|
36
|
+
* (a) Worker dispatch preamble: cheat-sheet only, no retrieval.
|
|
37
|
+
* Returns "" when the owner has no global layer yet.
|
|
38
|
+
*/
|
|
39
|
+
export declare function buildWorkerMemoryPreamble(ctx: PlannerMemoryContext | undefined, log?: PlannerMemoryLog): string;
|