qlogicagent 2.3.0 → 2.4.0

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.
Files changed (65) hide show
  1. package/dist/agent.js +6 -6
  2. package/dist/cli.js +212 -211
  3. package/dist/index.js +211 -210
  4. package/dist/orchestration.js +2 -2
  5. package/dist/protocol.js +1 -0
  6. package/dist/types/agent/tunable-defaults.d.ts +4 -0
  7. package/dist/types/agent/types.d.ts +24 -100
  8. package/dist/types/cli/stdio-server.d.ts +7 -0
  9. package/dist/types/cli/tool-bootstrap.d.ts +6 -0
  10. package/dist/types/contracts/index.d.ts +2 -3
  11. package/dist/types/llm/provider-def.d.ts +3 -0
  12. package/dist/types/llm/transport.d.ts +25 -25
  13. package/dist/types/llm/transports/anthropic-messages.d.ts +2 -2
  14. package/dist/types/llm/transports/gemini-generatecontent.d.ts +2 -2
  15. package/dist/types/llm/transports/openai-chat.d.ts +2 -2
  16. package/dist/types/llm/transports/openai-responses.d.ts +9 -9
  17. package/dist/types/llm/transports/volcengine-responses.d.ts +11 -11
  18. package/dist/types/orchestration/agent-instance.d.ts +15 -0
  19. package/dist/types/orchestration/solo-evaluator.d.ts +7 -0
  20. package/dist/types/orchestration/tool-loop/tool-choice-policy.d.ts +1 -1
  21. package/dist/types/protocol/methods.d.ts +143 -53
  22. package/dist/types/protocol/notifications.d.ts +4 -514
  23. package/dist/types/protocol/wire/acp-protocol.d.ts +411 -0
  24. package/dist/types/protocol/wire/agent-events.d.ts +32 -0
  25. package/dist/types/protocol/wire/agent-methods.d.ts +587 -0
  26. package/dist/types/protocol/wire/agent-rpc.d.ts +97 -0
  27. package/dist/types/protocol/wire/capability-manifest.d.ts +111 -0
  28. package/dist/types/protocol/wire/capability-transport.d.ts +207 -0
  29. package/dist/types/protocol/wire/channel-ingress.d.ts +29 -0
  30. package/dist/types/protocol/wire/channel.d.ts +89 -0
  31. package/dist/types/protocol/wire/chat-types.d.ts +87 -0
  32. package/dist/types/protocol/wire/checkpoint-runtime.d.ts +61 -0
  33. package/dist/types/protocol/wire/checkpoint.d.ts +72 -0
  34. package/dist/types/protocol/wire/execution.d.ts +391 -0
  35. package/dist/types/protocol/wire/gateway-rpc.d.ts +314 -0
  36. package/dist/types/protocol/wire/gateway.d.ts +62 -0
  37. package/dist/types/protocol/wire/hook-protocol.d.ts +37 -0
  38. package/dist/types/protocol/wire/index.d.ts +25 -0
  39. package/dist/types/protocol/wire/memory-provider-lifecycle.d.ts +80 -0
  40. package/dist/types/protocol/wire/notification-payloads.d.ts +581 -0
  41. package/dist/types/protocol/wire/provider-runtime-contract.d.ts +66 -0
  42. package/dist/types/protocol/wire/provider-runtime-core.d.ts +147 -0
  43. package/dist/types/protocol/wire/provider-runtime-io.d.ts +20 -0
  44. package/dist/types/protocol/wire/resource-manifest.d.ts +68 -0
  45. package/dist/types/protocol/wire/session.d.ts +32 -0
  46. package/dist/types/protocol/wire/thread-protocol.d.ts +157 -0
  47. package/dist/types/protocol/wire/transport.d.ts +57 -0
  48. package/dist/types/protocol/wire/turn.d.ts +208 -0
  49. package/dist/types/protocol/wire/web-capability.d.ts +51 -0
  50. package/dist/types/runtime/hooks/memory-hooks.d.ts +2 -2
  51. package/dist/types/runtime/infra/acp-types.d.ts +3 -142
  52. package/dist/types/runtime/infra/token-budget.d.ts +3 -3
  53. package/dist/types/runtime/session/index.d.ts +1 -1
  54. package/dist/types/runtime/session/session-memory.d.ts +46 -0
  55. package/dist/types/runtime/session/session-persistence.d.ts +34 -8
  56. package/dist/types/runtime/session/session-state.d.ts +4 -4
  57. package/dist/types/skills/memory/memory-tool.d.ts +1 -1
  58. package/dist/types/skills/memory/qmemory-adapter.d.ts +1 -1
  59. package/dist/types/skills/permissions/hook-runner.d.ts +4 -4
  60. package/dist/types/skills/permissions/permission-classifier.d.ts +2 -2
  61. package/dist/types/skills/tools/project-switch-tool.d.ts +24 -0
  62. package/dist/types/skills/tools.d.ts +5 -5
  63. package/dist/types/transport/acp-event-emitter.d.ts +1 -1
  64. package/dist/types/transport/acp-server.d.ts +17 -10
  65. package/package.json +14 -3
@@ -16,8 +16,8 @@ New messages to integrate:`:void 0,C=B(d,{taskContext:f}),S=await this.config.su
16
16
  ${S}`},_=[...l,k,...p],A=Date.now()-o,b=_.reduce((m,g)=>m+this.config.estimateTokens(g),0);return{messages:_,droppedCount:d.length,strategy:"incremental-compact",metrics:{tokensBefore:c,tokensAfter:b,compressionRatio:c>0?b/c:1,latencyMs:A,usedLlm:!0,cacheInvalidated:!0}}}},O=class{config;constructor(t){this.config=t}compress(t,n){let o=R(t),r=this.config.inner.compress(t,n),a=R(r.messages),i=o!==a&&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=D(this.config.inner)?await this.config.inner.compressAsync(t,n):this.config.inner.compress(t,n),a=R(r.messages),i=o!==a&&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}}}},te={modelContextWindow:128e3,targetUsageRatio:.75,minBudget:16e3,maxBudget:12e4};function tt(e={}){let t={...te,...e},n=Math.floor(t.modelContextWindow*t.targetUsageRatio);return Math.max(t.minBudget,Math.min(n,t.maxBudget))}function nt(e,t){let n=e/t;return n<=.8?"none":n<=1?"trim-only":n<=1.5?"sliding-window":"llm-summarize"}var P=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,a=0,i=0;for(let s of this.events)n+=s.tokensBefore>0?s.tokensAfter/s.tokensBefore:1,o+=s.latencyMs,r+=Math.max(0,s.tokensBefore-s.tokensAfter),s.usedLlm&&a++,s.cacheInvalidated&&i++;return{totalCompressions:t,totalLlmCalls:a,totalCacheInvalidations:i,averageCompressionRatio:n/t,averageLatencyMs:o/t,totalTokensSaved:r,recentEvents:this.events.slice(-10)}}reset(){this.events.length=0}},N=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 ne(e){let t=[],n=[];for(let o of e)o.role==="system"?t.push(o):n.push(o);return{system:t,nonSystem:n}}function x(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],a=typeof r.content=="string"?r.content.slice(0,200):"";n.push(`${r.role}:${a}`)}return n.join("|")}var ot=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=x){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=t.length-this.preserveRecentCount,r=0,a=0;return{messages:t.map((s,l)=>{if(l>=o||s.role!=="tool"||typeof s.content!="string"||!s.name||!ot.has(s.name)||s.content.length<=200)return s;let u=this.estimateTokens(s);return a+=u,r++,{...s,content:`[result cleared \u2014 ${s.content.length} chars]`}}),droppedCount:r,strategy:"micro-compact",metrics:r>0?{tokensBefore:0,tokensAfter:0,compressionRatio:0,latencyMs:0,usedLlm:!1,cacheInvalidated:!1}:void 0}}};function rt(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 a=r.function?.name??"";if(/read|edit|write|file/i.test(a)&&r.function?.arguments)try{let i=JSON.parse(r.function.arguments),s=i.path??i.filePath??i.file_path??i.file;s&&typeof s=="string"&&t.set(s,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 st(e,t,n){let o=n.estimateTokens??(p=>Math.ceil(p.length/4)),r=rt(t);if(r.length===0)return e;let a=e.map(p=>typeof p.content=="string"?p.content:"").join(`
17
17
  `),i=r.filter(p=>!a.includes(p));if(i.length===0)return e;let s=n.maxTokenBudget,l=[],u=0;for(let p of i){if(u>=n.maxFiles||s<=0)break;let f=await n.readFile(p);if(!f)continue;let C=o(f);C>s||(s-=C,u++,l.push({role:"system",content:`[Post-compact file recovery: ${p}]
18
18
 
19
- ${f}`}))}if(l.length===0)return e;let c=[...e],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function it(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}a.push(s)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:i}}function at(){return{stages:[]}}function lt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=oe(e,t),i=ut(a,t,o);if(i.length===0)return{messages:a,stagedCount:0};for(let s of i)t.stages.push(s);return a=oe(e,t),{messages:a,stagedCount:i.length}}function ct(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:re(e,t),committed:n}}function oe(e,t){return t.stages.filter(o=>o.committed).length===0?e:re(e,t)}function re(e,t){let n=t.stages.filter(r=>r.committed).sort((r,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,i]=r.range;if(a>=o.length)continue;let s=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(a,s-a,l)}return o}function ut(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,s=0;for(let l=0;l<o;l++){let u=e[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=l),s++;else{if(s>=3){let d=`${i}-${i+s}`;a.has(d)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}i=-1,s=0}}if(s>=3){let l=`${i}-${i+s}`;a.has(l)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as j,readdirSync as ue,readFileSync as pt}from"node:fs";import{join as pe}from"node:path";var An=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var se=20;var ie=3,ae=2,le=300*1e3;var Mn=300*1e3,U=4;var En=50*1024,In=500*1024,vn=500*1024*1024;var Ln=60*1024;var de=0;function ce(e){return[...e].sort().join("+")}function dt(e,t){if(!j(t))return null;let n=ce(e);try{let o=ue(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let a=pe(t,r.name,"SKILL.md");try{let s=pt(a,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let l=s[1].split(`
20
- `).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(ce(l)===n)return r.name}}catch{}}}catch{}return null}function mt(e){if(!j(e))return 0;try{return ue(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&j(pe(e,t.name,"SKILL.md"))).length}catch{return 0}}function ft(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ie||e.distinctToolCount<ae||Date.now()-de<le||t?.projectSkillsDir&&(mt(t.projectSkillsDir)>=se||t.tools.length>0&&dt(t.tools,t.projectSkillsDir)))}function gt(e){return e.existingSkillName?e.feedback==="negative":!1}function yt(e,t){return gt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ft(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 me(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 Tt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ht(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ct(e){if(!e.eligibility?.length)return[...e.tools];let t=ht(e.eligibility);return e.tools.filter(n=>{let o=me(n);if(!o)return!1;let r=t.get(o);return!r||Tt(r.status)})}function _t(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 bt(e){let t=_t({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Ct({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,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:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let a=n.function??void 0,i=typeof a?.name=="string"?a.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>me(l)===i);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:s,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 Rt=["stop","aborted","timeout","cancelled","interrupted","error"],xt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function fe(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function St(e,t){return{...e,content:[...fe(e.content),...fe(t.content)]}}function kt(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 At(e){return new Set((e??Rt).map(t=>t.trim().toLowerCase()))}function ge(e,t){return e?At(t).has(e.trim().toLowerCase()):!1}function Mt(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 G(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let l=s.tool_calls.filter(u=>kt(u));return{...s,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let l of s.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let a=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let l=s.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=s;c.content!=null&&c.content!==""&&a.push(c);continue}if(l.length<s.tool_calls.length){a.push({...s,tool_calls:l});continue}}a.push(s)}let i=[];for(let s of a){let l=i.length>0?i[i.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){i[i.length-1]=St(l,s);continue}i.push(s)}return i}function $(e,t){return ge(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of xt)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 a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let i of a.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 Et(e,t){let n=G(e),o=$(n,t);return H(o,t)}function ye(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=ge(t?.stopReason,t?.forcedStopReasons),r=[];for(let u=0;u<e.length;u+=1){let c=e[u];if(!c||typeof c!="object"){r.push(c);continue}if(c.type==="reasoning"&&typeof c.id=="string"&&c.id.startsWith("rs_")&&!e.slice(u+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Mt(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let a=new Set,i=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(a.add(c),i.set(c,u))}let s=new Set,l=[];for(let u of r)if(!(o&&u.type==="function_call")){if(u.type==="function_call_output"){let c=typeof u.call_id=="string"?u.call_id:"";if(!c||!a.has(c))continue;s.add(c)}l.push(u)}for(let[u]of i)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function It(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 vt(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 Lt(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 wt(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 Te(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ot(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 Pt(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 Nt(e){let t=[],n=G(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((a,i)=>a!==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:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:It(r),completedToolCallIds:vt(r)}),recoveryActions:t}}function Ft(e){let t=ye(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:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Lt(t),completedToolCallIds:wt(t)}),recoveryActions:n}}var Dt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Bt(e){return e?Dt.has(e):!0}function Ut(e){return e===429||e===529}function jt(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 $n={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Gt(){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>",he="Fork started \u2014 processing in background";function $t(e){return JSON.stringify(e).includes(q)}function Ht(e){return e<U}function zt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
19
+ ${f}`}))}if(l.length===0)return e;let c=[...e],d=-1;for(let p=0;p<c.length;p++)c[p].role==="system"&&(d=p);return c.splice(d+1,0,...l),c}function it(e,t,n=x){if(t.size===0)return{messages:e,tokensFreed:0,removedCount:0};let o=0,r=0,a=[];for(let s of e){let l=s.tool_call_id??"";if(l&&t.has(l)){o+=n(s),r++,t.delete(l);continue}a.push(s)}let i=r>0?{role:"system",content:`[${r} messages removed by snip]`}:void 0;return{messages:a,tokensFreed:o,removedCount:r,boundaryMessage:i}}function at(){return{stages:[]}}function lt(e,t,n){let o=n?.thresholdMessages??40;if(e.filter(s=>s.role!=="system").length<=o)return{messages:e,stagedCount:0};let a=oe(e,t),i=ut(a,t,o);if(i.length===0)return{messages:a,stagedCount:0};for(let s of i)t.stages.push(s);return a=oe(e,t),{messages:a,stagedCount:i.length}}function ct(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:re(e,t),committed:n}}function oe(e,t){return t.stages.filter(o=>o.committed).length===0?e:re(e,t)}function re(e,t){let n=t.stages.filter(r=>r.committed).sort((r,a)=>a.range[0]-r.range[0]),o=[...e];for(let r of n){let[a,i]=r.range;if(a>=o.length)continue;let s=Math.min(i,o.length),l={role:"system",content:r.summary};o.splice(a,s-a,l)}return o}function ut(e,t,n){let o=Math.max(0,e.length-Math.floor(n/2)),r=[],a=new Set(t.stages.map(l=>`${l.range[0]}-${l.range[1]}`)),i=-1,s=0;for(let l=0;l<o;l++){let u=e[l];if(u.role==="tool"||u.role==="assistant"&&typeof u.content=="string"&&u.content==="")i<0&&(i=l),s++;else{if(s>=3){let d=`${i}-${i+s}`;a.has(d)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}i=-1,s=0}}if(s>=3){let l=`${i}-${i+s}`;a.has(l)||r.push({id:`collapse_${i}_${i+s}`,range:[i,i+s],summary:`[${s} tool results collapsed]`,committed:!1})}return r}import{existsSync as j,readdirSync as ue,readFileSync as pt}from"node:fs";import{join as pe}from"node:path";var An=Math.min(Math.max(1,Number(process.env.TOOL_LOOP_DEFAULT_BUDGET)||25),100);var se=20;var ie=3,ae=2,le=300*1e3;var Mn=300*1e3,U=4;var En=50*1024,In=500*1024,vn=500*1024*1024,Ln=50*1024*1024;var wn=60*1024;var de=0;function ce(e){return[...e].sort().join("+")}function dt(e,t){if(!j(t))return null;let n=ce(e);try{let o=ue(t,{withFileTypes:!0});for(let r of o){if(!r.isDirectory())continue;let a=pe(t,r.name,"SKILL.md");try{let s=pt(a,"utf8").match(/^tools:\s*\n((?:\s+-\s+\S+\n?)+)/m);if(s){let l=s[1].split(`
20
+ `).map(u=>u.replace(/^\s*-\s*/,"").trim()).filter(Boolean);if(ce(l)===n)return r.name}}catch{}}}catch{}return null}function mt(e){if(!j(e))return 0;try{return ue(e,{withFileTypes:!0}).filter(t=>t.isDirectory()&&j(pe(e,t.name,"SKILL.md"))).length}catch{return 0}}function ft(e,t){return!(!e.ok||e.existingSkillName||!e.multiStep||e.toolCallCount<ie||e.distinctToolCount<ae||Date.now()-de<le||t?.projectSkillsDir&&(mt(t.projectSkillsDir)>=se||t.tools.length>0&&dt(t.tools,t.projectSkillsDir)))}function gt(e){return e.existingSkillName?e.feedback==="negative":!1}function yt(e,t){return gt(e)?{type:"skill.improve",skillName:e.existingSkillName,reason:"negative user feedback on existing skill execution"}:ft(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 me(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 Tt(e){return e==="enabled-eligible"||e==="installed-awaiting-approval"}function ht(e){return new Map((e??[]).map(t=>[t.toolName,t]))}function Ct(e){if(!e.eligibility?.length)return[...e.tools];let t=ht(e.eligibility);return e.tools.filter(n=>{let o=me(n);if(!o)return!1;let r=t.get(o);return!r||Tt(r.status)})}function _t(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 bt(e){let t=_t({toolChoice:e.toolChoice,thinkingEnabled:e.thinkingEnabled,compatibility:e.compatibility}),n=t.normalizedToolChoice,o=[...t.warnings],r=Ct({tools:e.tools,eligibility:e.eligibility});if(!n||n==="auto")return{tools:r,normalizedToolChoice:n,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:"You must call one of the available tools before responding.",warnings:o}}if(typeof n=="object"&&!Array.isArray(n)&&n.type==="function"){let a=n.function??void 0,i=typeof a?.name=="string"?a.name.trim():"";if(!i)throw new Error("tool_choice.function.name is required");let s=r.filter(l=>me(l)===i);if(s.length===0)throw new Error(`tool_choice requested unknown tool: ${i}`);return{tools:s,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 Rt=["stop","aborted","timeout","cancelled","interrupted","error"],xt=["tool_calls","toolCalls","function_call","functionCall","raw_tool_calls","rawToolCalls"];function fe(e){return e==null?[]:typeof e=="string"?e.length>0?[{type:"text",text:e}]:[]:Array.isArray(e)?e:[{type:"text",text:String(e)}]}function St(e,t){return{...e,content:[...fe(e.content),...fe(t.content)]}}function kt(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 At(e){return new Set((e??Rt).map(t=>t.trim().toLowerCase()))}function ge(e,t){return e?At(t).has(e.trim().toLowerCase()):!1}function Mt(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 G(e){if(!Array.isArray(e)||e.length===0)return[...e];let t=e.map(s=>{if(s.role==="assistant"&&Array.isArray(s.tool_calls)){let l=s.tool_calls.filter(u=>kt(u));return{...s,...l.length>0?{tool_calls:l}:{tool_calls:void 0}}}return{...s}}),n=new Set;for(let s of t)if(!(s.role!=="assistant"||!Array.isArray(s.tool_calls)))for(let l of s.tool_calls)typeof l.id=="string"&&l.id&&n.add(l.id);let o=t.filter(s=>s.role!=="tool"?!0:!!(s.tool_call_id&&n.has(s.tool_call_id))),r=new Set;for(let s of o)s.role==="tool"&&typeof s.tool_call_id=="string"&&s.tool_call_id&&r.add(s.tool_call_id);let a=[];for(let s of o){if(s.role==="assistant"&&Array.isArray(s.tool_calls)&&s.tool_calls.length>0){let l=s.tool_calls.filter(u=>typeof u.id=="string"&&r.has(u.id));if(l.length===0){let{tool_calls:u,...c}=s;c.content!=null&&c.content!==""&&a.push(c);continue}if(l.length<s.tool_calls.length){a.push({...s,tool_calls:l});continue}}a.push(s)}let i=[];for(let s of a){let l=i.length>0?i[i.length-1]:void 0;if(s.role==="user"&&l?.role==="user"){i[i.length-1]=St(l,s);continue}i.push(s)}return i}function $(e,t){return ge(t?.stopReason,t?.forcedStopReasons)?e.map(n=>{if(n.role!=="assistant")return{...n};let o={...n};for(let r of xt)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 a of e)a.role==="tool"&&typeof a.tool_call_id=="string"&&a.tool_call_id&&o.add(a.tool_call_id);let r=[];for(let a of e)if(r.push({...a}),!(a.role!=="assistant"||!Array.isArray(a.tool_calls)||a.tool_calls.length===0))for(let i of a.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 Et(e,t){let n=G(e),o=$(n,t);return H(o,t)}function ye(e,t){let n=t?.placeholderFunctionCallOutput??"Error: Tool loop interrupted before function_call_output was provided.",o=ge(t?.stopReason,t?.forcedStopReasons),r=[];for(let u=0;u<e.length;u+=1){let c=e[u];if(!c||typeof c!="object"){r.push(c);continue}if(c.type==="reasoning"&&typeof c.id=="string"&&c.id.startsWith("rs_")&&!e.slice(u+1).some(f=>f&&typeof f=="object"&&f.type!=="reasoning"))continue;if(c.type!=="function_call"){r.push({...c});continue}let d={...c};if(typeof d.id=="string"){let p=Mt(d.id);p.itemId?.startsWith("fc_")&&(d.id=p.callId)}r.push(d)}let a=new Set,i=new Map;for(let u of r){if(u.type!=="function_call")continue;let c=typeof u.call_id=="string"&&u.call_id?u.call_id:typeof u.id=="string"?u.id:void 0;c&&(a.add(c),i.set(c,u))}let s=new Set,l=[];for(let u of r)if(!(o&&u.type==="function_call")){if(u.type==="function_call_output"){let c=typeof u.call_id=="string"?u.call_id:"";if(!c||!a.has(c))continue;s.add(c)}l.push(u)}for(let[u]of i)s.has(u)||o||l.push({type:"function_call_output",call_id:u,output:n});return l}function It(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 vt(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 Lt(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 wt(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 Te(e){return{round:e.round??0,maxRounds:e.maxRounds,pendingToolCallIds:[...e.pendingToolCallIds??[]],completedToolCallIds:[...e.completedToolCallIds??[]],lastStopReason:e.lastStopReason,replayMessages:[...e.replayMessages??[]]}}function Ot(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 Pt(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 Nt(e){let t=[],n=G(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((a,i)=>a!==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:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:r,pendingToolCallIds:It(r),completedToolCallIds:vt(r)}),recoveryActions:t}}function Ft(e){let t=ye(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:Te({maxRounds:e.maxRounds,round:e.round,lastStopReason:e.lastStopReason,replayMessages:t,pendingToolCallIds:Lt(t),completedToolCallIds:wt(t)}),recoveryActions:n}}var Dt=new Set(["main","sdk","agent","compact","hook","verification","side_question"]);function Bt(e){return e?Dt.has(e):!0}function Ut(e){return e===429||e===529}function jt(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 Hn={maxBackoffMs:300*1e3,resetCapMs:360*60*1e3,heartbeatIntervalMs:3e4};function Gt(){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>",he="Fork started \u2014 processing in background";function $t(e){return JSON.stringify(e).includes(q)}function Ht(e){return e<U}function zt(e,t){let n=[...e.parentMessages],o=e.worktreePath?`
21
21
 
22
22
  Your working directory is: ${e.worktreePath}
23
23
  All file paths should be relative to this directory.`:"",r={role:"user",content:[{type:"text",text:`${q}
@@ -0,0 +1 @@
1
+ var V="1.0.0",W={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},F={REQUEST:"tool.approval.request",RESPONSE:"tool.approval.response"};function S(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 P(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 T(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function B(e){let t;try{t=JSON.parse(e)}catch{return null}return P(t)||S(t)||T(t)?t:null}var j=["session.list","session.get","session.create","session.update","session.delete","session.archive","session.getState","session.switchProject","session.getMessages","project.list","project.create","project.delete","project.rename","project.archive","project.unarchive","project.archiveByGroup","instructions.list","instructions.read","instructions.write","instructions.delete","files.list","files.read","files.create","files.rename","files.delete","files.gitStatus"];var C=["turn.start","turn.delta","turn.end","turn.error","turn.recovery","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.plan_update","turn.suggestions","turn.sidechain_started","turn.subagent_delta","turn.sidechain_completed","turn.task_updated","turn.todos_updated","turn.exec_progress","turn.usage_update","team.member.notification","session.info","memory.updated"],b=["solo.progress","solo.agentDelta","solo.agentUsage","solo.agentDiff","solo.evaluation","product.taskStarted","product.taskOutput","product.taskCompleted","product.taskFailed","product.budgetUpdate","product.checkpointed","product.dagTopology","plan.interrupted"],Y=[...C,...b];var X=1,H={INITIALIZE:"initialize",SESSION_NEW:"session/new",SESSION_PROMPT:"session/prompt",SESSION_END:"session/end",SESSION_SET_CONFIG:"session/set_config_option",SESSION_SET_MODEL:"session/set_model",SESSION_SET_MODE:"session/set_mode",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"},G={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_RESUME:"x/product.resume",PRODUCT_PAUSE:"x/product.pause",PRODUCT_CANCEL:"x/product.cancel",PRODUCT_ROLLBACK:"x/product.rollback",PRODUCT_STATUS:"x/product.status",SOLO_SUBSCRIBE:"x/solo.subscribe",PRODUCT_SUBSCRIBE:"x/product.subscribe",TEAM_DELEGATE:"x/team.delegate"},I={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"},q={X_SUBAGENT_STARTED:"x_subagent_started",X_SUBAGENT_DELTA:"x_subagent_delta",X_SUBAGENT_ENDED:"x_subagent_ended",X_MEDIA_RESULT:"x_media_result",X_MEDIA_PROGRESS:"x_media_progress",X_SKILL_INSTRUCTION:"x_skill_instruction",X_RECOVERY:"x_recovery",X_SIDECHAIN_STARTED:"x_sidechain_started",X_SIDECHAIN_COMPLETED:"x_sidechain_completed",X_SUGGESTIONS:"x_suggestions",X_ASK_USER:"x_ask_user",X_SESSION_INFO:"x_session_info",X_MEMORY_UPDATED:"x_memory_updated",X_TEAM_MEMBER_UPDATE:"x_team_member_update",X_SOLO_STARTED:"x_solo_started",X_SOLO_AGENT_FINISHED:"x_solo_agent_finished",X_SOLO_SELECTED:"x_solo_selected",X_PRODUCT_TASK_STARTED:"x_product_task_started",X_PRODUCT_TASK_COMPLETED:"x_product_task_completed",X_PRODUCT_CHECKPOINT:"x_product_checkpoint"};function v(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&"id"in t}function M(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&typeof t.method=="string"&&!("id"in t)}function h(e){if(!e||typeof e!="object")return!1;let t=e;return t.jsonrpc==="2.0"&&"id"in t&&!("method"in t)}function z(e){let t;try{t=JSON.parse(e)}catch{return null}return h(t)||v(t)||M(t)?t:null}function J(e){return Object.values(I).includes(e)}function $(e){return e.startsWith("x_")}var A=["gatewayVersion","toolNamespaces","workspaceIds","installedCapabilities","enabledCapabilities","features","approvalMode","toolManifests","skillManifests","pluginManifests","mcpManifests","approvalPolicy","workspaceSummaries"];function d(e){return e?e.map(t=>({...t})):void 0}function m(e){return e?e.map(t=>({...t})):void 0}function Q(e){return e?[...e]:void 0}function k(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].sort((t,o)=>t.localeCompare(o))}function g(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:d(e.toolManifests)}:{},...e.skillManifests?{skillManifests:d(e.skillManifests)}:{},...e.pluginManifests?{pluginManifests:d(e.pluginManifests)}:{},...e.mcpManifests?{mcpManifests:d(e.mcpManifests)}:{},...e.approvalPolicy?{approvalPolicy:{...e.approvalPolicy}}:{},...e.workspaceSummaries?{workspaceSummaries:m(e.workspaceSummaries)}:{}}}function Z(e){let{previous:t,update:o}=e;return!(o.syncMode==="diff"&&t&&(!o.baseSnapshotVersion||t.snapshotVersion===o.baseSnapshotVersion))||!t?g(o):{...g(t),snapshotVersion:o.snapshotVersion,updatedAt:o.updatedAt,...o.gatewayVersion!==void 0?{gatewayVersion:o.gatewayVersion}:{},...o.syncMode?{syncMode:o.syncMode}:{},...o.baseSnapshotVersion?{baseSnapshotVersion:o.baseSnapshotVersion}:{},...o.changedSections?{changedSections:[...o.changedSections]}:{},...o.toolNamespaces?{toolNamespaces:[...o.toolNamespaces]}:{},...o.workspaceIds?{workspaceIds:[...o.workspaceIds]}:{},...o.installedCapabilities?{installedCapabilities:[...o.installedCapabilities]}:{},...o.enabledCapabilities?{enabledCapabilities:[...o.enabledCapabilities]}:{},...o.features?{features:[...o.features]}:{},...o.approvalMode?{approvalMode:o.approvalMode}:{},...o.toolManifests?{toolManifests:d(o.toolManifests)}:{},...o.skillManifests?{skillManifests:d(o.skillManifests)}:{},...o.pluginManifests?{pluginManifests:d(o.pluginManifests)}:{},...o.mcpManifests?{mcpManifests:d(o.mcpManifests)}:{},...o.approvalPolicy?{approvalPolicy:{...o.approvalPolicy}}:{},...o.workspaceSummaries?{workspaceSummaries:m(o.workspaceSummaries)}:{}}}function ee(e){return k(e.map(t=>t.name.split(".")[0]??"").filter(Boolean))}function te(e){return k(e.map(t=>t.id))}function oe(e){let{previous:t,current:o}=e;if(!t)return{...g(o),syncMode:"full"};if(t.snapshotVersion===o.snapshotVersion)return null;let i=A.filter(n=>JSON.stringify(t[n])!==JSON.stringify(o[n]));if(i.length===A.length)return{...g(o),syncMode:"full"};let u={snapshotVersion:o.snapshotVersion,updatedAt:o.updatedAt,syncMode:"diff",baseSnapshotVersion:t.snapshotVersion,changedSections:i,toolNamespaces:[...o.toolNamespaces],workspaceIds:[...o.workspaceIds]},p=u;for(let n of i){let r=o[n];if(r!==void 0)switch(n){case"toolNamespaces":case"workspaceIds":case"installedCapabilities":case"enabledCapabilities":case"features":p[n]=Q(r);break;case"approvalPolicy":p[n]={...r};break;case"workspaceSummaries":p[n]=m(r);break;case"toolManifests":case"skillManifests":case"pluginManifests":case"mcpManifests":p[n]=d(r);break;default:p[n]=r;break}}return u}var re=["web_search","web_fetch","deep_research","browser_execution"],ie=["web-intelligence","browser-execution"],ne=["discovery","read-url","multi-source-research","interactive-browser"],se=["stateless","render-backend","interactive-session"],ae=["stateless","stateless-single-step","stateful-session-required"],pe=["required","conditional","none"],ce=["browser-read","browser-authenticated-read","browser-state-changing"],le=["read-page","read-authenticated-page","fill-form","submit-form","download-file","reuse-session"],de=["web_search","web_fetch","deep_research","blocked"],ue=["requires-interaction","requires-login-state","requires-rendered-dom","requires-persistent-session","requires-state-changing-action"],ge=["none","same-capability-once","degrade-only"];var ye=["prefetch","sync_turn","on_pre_compress","on_session_end","on_delegation","on_memory_write"],fe=["turn","sidechain","compress","session-end"],Ae=["observe-only","parent-write","deny"];var me=2,s={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 O(e){return{...e,artifacts:e.artifacts.map(t=>({...t}))}}function Ee(e){return{...e,assetIds:[...e.assetIds]}}function N(){return{[y.desktopDockerBridge]:{id:y.desktopDockerBridge,title:"Desktop Docker Bridge",platform:"any",assetIds:[s.gatewayImage,s.dockerDesktopWin32X64,s.dockerDesktopDarwinX64,s.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:[s.nodeWin32X64,s.ffmpegWin32X64,s.whisperModelTiny],description:"Embedded desktop mode requires the bundled Node/FFmpeg runtimes and the whisper model asset."}}}function D(e,t){return e.assets[t]}function w(e,t){return e.profiles[t]}function Re(e,t){let o=w(e,t);return o?o.assetIds.map(i=>D(e,i)).filter(i=>!!i):[]}function _e(e,t){return e.assets[t.id]=O(t),U(e)}function E(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 U(e){let t=E(e.assets[s.gatewayImage]),o=E(e.assets[s.whisperModelTiny]);return{...e,gateway:t,whisperModel:o}}function x(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 Se(e){let t=e&&typeof e=="object"?e:{},o={},i=t.assets&&typeof t.assets=="object"?t.assets:{};for(let[r,a]of Object.entries(i)){if(!a||typeof a!="object")continue;let l=a;!l.id||!Array.isArray(l.artifacts)||(o[r]=O(l))}if(!o[s.gatewayImage]&&t.gateway&&typeof t.gateway=="object"){let r=x(t.gateway,{id:s.gatewayImage,title:"OpenClaw Gateway Image (Desktop Slim)",kind:"container-image",delivery:"remote",platform:"any",description:"Desktop Docker mode gateway image."});r&&(o[r.id]=r)}if(!o[s.whisperModelTiny]&&t.whisperModel&&typeof t.whisperModel=="object"){let r=x(t.whisperModel,{id:s.whisperModelTiny,title:"Whisper Tiny Model",kind:"model",delivery:"remote",platform:"any",description:"Shared whisper.cpp tiny model asset for embedded desktop speech recognition."});r&&(o[r.id]=r)}let p={...N()},n=t.profiles&&typeof t.profiles=="object"?t.profiles:{};for(let[r,a]of Object.entries(n)){if(!a||typeof a!="object")continue;let l=a;!l.id||!Array.isArray(l.assetIds)||(p[r]=Ee(l))}return U({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:o,profiles:p})}var Pe=["pending","captured","failed","restored"],Te=["file","directory","missing"],Ce=["metadata-only","workspace-copy","shadow-git"];var be=["api-key","oauth","token","aws-sdk"],Ie=["rate_limit","auth","server_error","timeout","network","unknown"],ve=["requiresOpenAiAnthropicToolPayload"];function Me(e,t){return!e||typeof e!="object"||Array.isArray(e)?!1:e[t]===!0}var L="openai-codex";function f(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 K(e){let t=f(e);return t==="volcengine-plan"?"volcengine":t==="byteplus-plan"?"byteplus":t}var he=K,ke={anthropicToolSchemaMode:"native",anthropicToolChoiceMode:"native",providerFamily:"default",preserveAnthropicThinkingSignatures:!0,openAiCompatTurnValidation:!0,providerThoughtSignatureSanitization:!1,transcriptToolCallIdMode:"default",transcriptToolCallIdModelHints:[],providerThoughtSignatureModelHints:[],dropThinkingBlockModelHints:[]},xe={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"},[L]:{providerFamily:"openai"},openrouter:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},opencode:{openAiCompatTurnValidation:!1,providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]},kilocode:{providerThoughtSignatureSanitization:!0,providerThoughtSignatureModelHints:["gemini"]}};function R(e,t){let o=(e??"").toLowerCase();return!!o&&t.some(i=>o.includes(i))}function c(e){let t=f(e??"");return{...ke,...xe[t]}}function Oe(e){return c(e).preserveAnthropicThinkingSignatures}function Ne(e){let t=c(e);return t.anthropicToolSchemaMode!=="native"||t.anthropicToolChoiceMode!=="native"}function De(e){return c(e).anthropicToolSchemaMode==="openai-functions"}function we(e){return c(e).anthropicToolChoiceMode==="openai-string-modes"}function Ue(e){return c(e).openAiCompatTurnValidation}function Le(e){return c(e).providerFamily==="openai"}function Ke(e){return c(e).providerFamily==="anthropic"}function Ve(e){return R(e.modelId,c(e.provider).dropThinkingBlockModelHints)}function We(e){let t=c(e.provider);return t.providerThoughtSignatureSanitization&&R(e.modelId,t.providerThoughtSignatureModelHints)}function Fe(e,t){let o=c(e),i=o.transcriptToolCallIdMode;if(i==="strict9")return i;if(R(t,o.transcriptToolCallIdModelHints))return"strict9"}var _={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"],volcengine:["VOLCANO_ENGINE_API_KEY"],"volcengine-plan":["VOLCANO_ENGINE_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 Be(){return[...new Set(Object.values(_).flat())]}function je(e){let t=f(e.provider),o=e.env??process.env,i=new Set(e.appliedEnvKeys??[]),u=r=>{let a=o[r]?.trim();if(!a)return null;let l=i.has(r)?`shell env: ${r}`:`env: ${r}`;return{apiKey:a,source:l}},p=e.resolveSpecialApiKey?.(t,o,i);if(p)return p;let n=_[t];if(!n||n.length===0)return null;for(let r of n){let a=u(r);if(a)return a}return null}export{G as ACP_EXTENDED_METHODS,q as ACP_EXTENDED_SESSION_UPDATE_TYPES,H as ACP_METHODS,X as ACP_PROTOCOL_VERSION,I as ACP_SESSION_UPDATE_TYPES,F as AGENT_RPC_APPROVAL_METHODS,W as AGENT_RPC_ERROR_CODES,V as AGENT_RPC_PROTOCOL_VERSION,b as AGENT_TEAM_WS_EVENT_NAMES,C as AGENT_WS_EVENT_NAMES,Y as ALL_AGENT_WS_EVENT_NAMES,A as CAPABILITY_MANIFEST_DIFF_SECTIONS,j as GATEWAY_RPC_METHODS,ye as MEMORY_OBSERVATION_HOOK_VALUES,fe as MEMORY_OBSERVATION_SOURCE_VALUES,Ae as MEMORY_WRITE_ACCESS_VALUES,Ce as MUTATION_CHECKPOINT_BACKEND_VALUES,Te as MUTATION_CHECKPOINT_ENTRY_KIND_VALUES,Pe as MUTATION_CHECKPOINT_PHASE_VALUES,be as PROVIDER_RUNTIME_AUTH_MODE_VALUES,ve as PROVIDER_RUNTIME_COMPAT_FLAG_VALUES,_ as PROVIDER_RUNTIME_ENV_API_KEY_CANDIDATES,L as PROVIDER_RUNTIME_OPENAI_CODEX_PROVIDER_ID,Ie as PROVIDER_RUNTIME_VAULT_ERROR_TYPE_VALUES,me as RESOURCE_MANIFEST_SCHEMA_VERSION,s as RUNTIME_ASSET_IDS,y as RUNTIME_PROFILE_IDS,le as WEB_ACTION_SCOPE_VALUES,pe as WEB_APPROVAL_DEFAULT_VALUES,ie as WEB_CAPABILITY_FAMILY_VALUES,re as WEB_CAPABILITY_ID_VALUES,de as WEB_DEGRADATION_TARGET_VALUES,ue as WEB_ESCALATION_REASON_VALUES,se as WEB_EXECUTION_MODE_VALUES,ce as WEB_POLICY_RISK_CLASS_VALUES,ge as WEB_RETRY_POLICY_VALUES,ae as WEB_STATEFULNESS_VALUES,ne as WEB_TASK_MODE_VALUES,g as cloneCapabilityManifestSnapshot,oe as createCapabilityManifestDiffPayload,N as createDefaultRuntimeResourceProfiles,ee as deriveCapabilityToolNamespaces,te as deriveCapabilityWorkspaceIds,E as getManifestShortcutEntry,D as getRuntimeResourceAsset,w as getRuntimeResourceProfile,Re as getRuntimeResourceProfileAssets,M as isAcpJsonRpcNotification,v as isAcpJsonRpcRequest,h as isAcpJsonRpcResponse,T as isAgentRpcNotification,S as isAgentRpcRequest,P as isAgentRpcResponse,Ke as isAnthropicProviderRuntimeFamily,$ as isExtendedSessionUpdateType,Le as isOpenAiProviderRuntimeFamily,J as isStandardSessionUpdateType,Be as listProviderRuntimeEnvApiKeyNames,Z as mergeCapabilityManifestSnapshot,f as normalizeProviderRuntimeId,K as normalizeProviderRuntimeIdForAuth,Se as normalizeRuntimeResourceManifest,z as parseAcpMessage,B as parseAgentRpcMessage,Oe as preservesProviderRuntimeAnthropicThinkingSignatures,Me as readProviderRuntimeCompatFlag,Ne as requiresOpenAiCompatibleAnthropicToolPayloadForProviderRuntime,c as resolveProviderRuntimeCapabilities,je as resolveProviderRuntimeEnvApiKey,he as resolveProviderRuntimeKeyFamily,Fe as resolveProviderRuntimeTranscriptToolCallIdMode,Ve as shouldDropThinkingBlocksForProviderRuntimeModel,We as shouldSanitizeProviderRuntimeThoughtSignaturesForModel,Ue as supportsOpenAiCompatTurnValidationForProviderRuntime,_e as upsertRuntimeResourceAsset,De as usesOpenAiFunctionAnthropicToolSchemaForProviderRuntime,we as usesOpenAiStringModeAnthropicToolChoiceForProviderRuntime};
@@ -109,6 +109,9 @@ export declare const INSTRUCTIONS_MAX_FILE_SIZE: number;
109
109
  export declare const INSTRUCTIONS_MAX_DIR_SIZE: number;
110
110
  /** Max single media file download size (bytes, 500 MB). */
111
111
  export declare const MEDIA_MAX_DOWNLOAD_SIZE: number;
112
+ /** Max file size for direct LLM upload (bytes, 50 MB).
113
+ * Files larger than this should be chunked or summarized before sending to LLM. */
114
+ export declare const MEDIA_MAX_UPLOAD_SIZE: number;
112
115
  /** Media download timeout (ms). */
113
116
  export declare const MEDIA_DOWNLOAD_TIMEOUT_MS = 300000;
114
117
  /** Max retries when spawning an ACP agent process. */
@@ -196,6 +199,7 @@ export interface TunableDefaults {
196
199
  instructionsMaxFileSize: number;
197
200
  instructionsMaxDirSize: number;
198
201
  mediaMaxDownloadSize: number;
202
+ mediaMaxUploadSize: number;
199
203
  mediaDownloadTimeoutMs: number;
200
204
  acpMaxSpawnRetries: number;
201
205
  acpRetryBackoffBase: number;
@@ -1,115 +1,35 @@
1
1
  /**
2
- * Pure agent types zero I/O framework dependencies.
2
+ * Pure agent types 鈥?zero I/O framework dependencies.
3
3
  *
4
- * These types define the contract between:
5
- * - CLI stdio layer Agent class
6
- * - Agent class LLM Provider
7
- * - Agent class ↔ Tool loop
8
- *
9
- * Ported from Hub semantic-turn-shared.ts / semantic-turn-tools.ts,
10
- * with Hub infrastructure (WS/PG/Redis) replaced by DI interfaces.
11
- *
12
- * No imports from express/pg/ioredis/ws.
4
+ * Wire-level types (ChatMessage, ToolDefinition) are canonical in
5
+ * protocol/wire/. This file re-exports them and adds
6
+ * internal-only extensions (e.g. backfillObservableInput on ToolDefinition).
13
7
  */
14
8
  import type { SkillInstruction } from "../orchestration/index.js";
15
9
  import type { HookRegistry } from "../contracts/hooks.js";
16
10
  import type { MediaCapability } from "../llm/provider-def.js";
17
- export type ChatMessageRole = "system" | "user" | "assistant" | "tool";
18
- /** Thinking block from Anthropic Messages API (DeepSeek, Claude, etc.) */
19
- export interface ThinkingBlock {
20
- thinking: string;
21
- signature: string;
22
- }
23
- export interface ChatMessage {
24
- role: ChatMessageRole;
25
- content: string | null;
26
- /** For assistant messages with tool calls */
27
- tool_calls?: ToolCallMessage[];
28
- /** For tool result messages */
29
- tool_call_id?: string;
30
- /** For tool result messages — tool name */
31
- name?: string;
32
- /** Anthropic thinking blocks — must be passed back to API in subsequent requests */
33
- thinkingBlocks?: ThinkingBlock[];
34
- /**
35
- * Image URLs for vision-capable models.
36
- * Transports convert these into the provider's native content block format:
37
- * - OpenAI-chat: [{type:"text",text:...},{type:"image_url",image_url:{url:...}}]
38
- * - Anthropic: [{type:"text",text:...},{type:"image",source:{type:"url",url:...}}]
39
- * Valid on role="user" and role="tool" messages.
40
- * For tool results, images are resolved via FileUploadAdapter before sending to LLM.
41
- */
42
- imageUrls?: string[];
43
- /** Image detail level for vision understanding: 'auto' | 'low' | 'high' | 'xhigh' */
44
- imageDetail?: "auto" | "low" | "high" | "xhigh";
45
- /** Max image pixels budget for vision understanding (Volcengine image_pixel_limit) */
46
- imagePixelLimit?: {
47
- minPixels?: number;
48
- maxPixels?: number;
49
- };
50
- /** Video URLs for video-understanding models. Only valid on role="user" messages. */
51
- videoUrls?: string[];
52
- /** Per-video fps for video understanding (0.2-5, default 1) */
53
- videoFps?: number;
54
- /** Audio format hint for audio understanding: 'mp3' | 'wav' | 'aac' | 'm4a' */
55
- audioFormat?: "mp3" | "wav" | "aac" | "m4a";
56
- /** Audio URLs for audio-understanding models. Only valid on role="user" messages. */
57
- audioUrls?: string[];
58
- /**
59
- * Pre-uploaded file IDs for document/media understanding.
60
- * Used with Files API — each entry is a { id, mimeType } pair.
61
- * Only valid on role="user" messages.
62
- */
63
- fileIds?: Array<{
64
- id: string;
65
- mimeType?: string;
66
- }>;
67
- }
68
- export interface ToolCallMessage {
69
- id: string;
70
- type: "function";
71
- function: {
72
- name: string;
73
- arguments: string;
74
- };
75
- }
76
- export interface ToolDefinition {
77
- type: "function";
78
- function: {
79
- name: string;
80
- description: string;
81
- parameters?: Record<string, unknown>;
82
- };
83
- /** Tool scheduling metadata from host manifest (optional) */
84
- meta?: {
85
- serialOnly?: boolean;
86
- parallelSafe?: boolean;
87
- /** If true, host should request user approval before execution (CC PreToolUse parity) */
88
- requiresApproval?: boolean;
89
- /** Tool is read-only / safe — skip approval even in strict mode */
90
- isReadOnly?: boolean;
91
- /** Tool can cause irreversible side-effects — force approval in default mode */
92
- isDangerous?: boolean;
93
- };
11
+ import type { ChatMessage as WireChatMessage, ChatMessageRole as WireChatMessageRole, ThinkingBlock as WireThinkingBlock, ToolCallMessage as WireToolCallMessage, ToolDefinition as WireToolDefinition, WireTokenUsage } from "../protocol/wire/index.js";
12
+ export type ChatMessageRole = WireChatMessageRole;
13
+ export type ThinkingBlock = WireThinkingBlock;
14
+ export type ToolCallMessage = WireToolCallMessage;
15
+ export type ChatMessage = WireChatMessage;
16
+ export interface ToolDefinition extends WireToolDefinition {
94
17
  /**
95
18
  * Backfill derived/legacy fields onto a shallow copy of the tool input
96
19
  * before hooks and observers see it (CC backfillObservableInput parity).
97
20
  * The original API-bound input is never modified.
21
+ * Internal-only 鈥?never serialized over JSON-RPC.
98
22
  */
99
23
  backfillObservableInput?: (input: Record<string, unknown>) => void;
100
24
  }
101
- export interface TokenUsage {
102
- prompt: number;
103
- completion: number;
104
- /** Reasoning tokens (for models like o1/DeepSeek-R1) */
105
- reasoning?: number;
106
- /** Prompt cache read tokens (CC cache_read_input_tokens parity) */
107
- cacheRead?: number;
108
- /** Prompt cache creation tokens (CC cache_creation_input_tokens parity) */
109
- cacheCreation?: number;
110
- }
111
25
  /**
112
- * Why the previous iteration continued each variant corresponds to one of
26
+ * Token usage 鈥?unified with WireTokenUsage from contracts.
27
+ * No more internal/wire split: all code uses the same field names
28
+ * (inputTokens, outputTokens, reasoningTokens, cacheRead, cacheWrite).
29
+ */
30
+ export type TokenUsage = WireTokenUsage;
31
+ /**
32
+ * Why the previous iteration continued 鈥?each variant corresponds to one of
113
33
  * the 7 `continue` sites in the main while(true) loop.
114
34
  * Tests can assert recovery paths fired without inspecting message contents.
115
35
  */
@@ -194,7 +114,7 @@ export interface TurnConfig {
194
114
  summaryModel?: string;
195
115
  /** Max concurrent tool executions (0 = unlimited). */
196
116
  maxConcurrentTools?: number;
197
- /** Model requires streaming disable non-streaming fallback. */
117
+ /** Model requires streaming 鈥?disable non-streaming fallback. */
198
118
  streamRequired?: boolean;
199
119
  /** Reasoning effort for models that support it (GPT-5.x, o-series). */
200
120
  reasoning?: {
@@ -221,7 +141,7 @@ export interface TurnConfig {
221
141
  /**
222
142
  * User-designated provider+model per media category.
223
143
  * Each entry maps a media type (image/video/music/tts/3d/...) to
224
- * the specific provider and model the user chose. No failover
144
+ * the specific provider and model the user chose. No failover 鈥?
225
145
  * if the designated provider fails, the error propagates directly.
226
146
  */
227
147
  mediaProviders?: Partial<Record<MediaCapability, {
@@ -371,8 +291,12 @@ export interface ToolInvoker {
371
291
  */
372
292
  export interface AgentLogger {
373
293
  info(message: string): void;
294
+ info(obj: Record<string, unknown>, message: string): void;
374
295
  warn(message: string): void;
296
+ warn(obj: Record<string, unknown>, message: string): void;
375
297
  error(message: string): void;
298
+ error(obj: Record<string, unknown>, message: string): void;
376
299
  debug(message: string): void;
300
+ debug(obj: Record<string, unknown>, message: string): void;
377
301
  }
378
302
  export type { HookRegistry };
@@ -311,9 +311,16 @@ export declare class StdioServer {
311
311
  private acpHandleSoloStart;
312
312
  private acpHandleSoloStatus;
313
313
  private acpHandleSoloSelect;
314
+ private acpHandleSoloCancel;
315
+ private acpHandleSoloSubscribe;
316
+ private acpHandleAgentsList;
314
317
  private acpHandleProductCreate;
315
318
  private acpHandleProductResume;
316
319
  private acpHandleProductStatus;
320
+ private acpHandleProductPause;
321
+ private acpHandleProductCancel;
322
+ private acpHandleProductRollback;
323
+ private acpHandleProductSubscribe;
317
324
  private acpHandleTeamDelegate;
318
325
  private handleProjectCreate;
319
326
  private handleProjectList;
@@ -14,6 +14,12 @@ export declare function setGroupSecurityMode(enabled: boolean): void;
14
14
  * falling back to SearXNG. Called from stdio-server per session.
15
15
  */
16
16
  export declare function setProviderToolAPI(api: ProviderToolAPI | undefined): void;
17
+ /** Set callback invoked after LLM-driven project switch. */
18
+ export declare function setProjectSwitchCallback(cb: ((project: {
19
+ id: string;
20
+ name: string;
21
+ workspaceDir: string;
22
+ }) => void) | undefined): void;
17
23
  /**
18
24
  * Set task tool lifecycle hooks. Called from stdio-server when session starts.
19
25
  * Connects planning-task events to the HookRegistry.
@@ -1,8 +1,7 @@
1
1
  /**
2
- * Internal contracts — types internalized from qlogicagent-runtime-contracts.
2
+ * Internal contracts — hooks + todo types.
3
3
  *
4
- * These types are only consumed within qlogicagent itself (agent runtime + hub).
5
- * They were removed from the public npm package to slim the cross-repo API surface.
4
+ * These types are only consumed within qlogicagent itself.
6
5
  */
7
6
  export * from "./todo.js";
8
7
  export * from "./hooks.js";
@@ -107,6 +107,9 @@ export interface ProviderQuirks {
107
107
  filterImageBlocks?: boolean;
108
108
  /** DeepSeek: budget_tokens ignored, use output_config.effort instead */
109
109
  useEffortInsteadOfBudget?: boolean;
110
+ /** Provider natively supports PDF/document content blocks (Anthropic document, Gemini fileData).
111
+ * When false, PDFs are annotated as text labels and the agent must use tools to extract content. */
112
+ supportsDocumentVision?: boolean;
110
113
  /** Provider supports reasoning_effort param (Kimi K2, OpenAI o-series) */
111
114
  supportsReasoningEffort?: boolean;
112
115
  /** Provider has built-in web search (Kimi: builtin_function.$web_search, GLM: web_search) */
@@ -1,14 +1,14 @@
1
1
  /**
2
- * LLMTransport abstract interface for LLM inference calls.
2
+ * LLMTransport 鈥?abstract interface for LLM inference calls.
3
3
  *
4
4
  * Aligned with Hermes `ProviderTransport` ABC:
5
- * stream(request, apiKey, signal) AsyncGenerator<LLMChunk>
5
+ * stream(request, apiKey, signal) 鈫?AsyncGenerator<LLMChunk>
6
6
  *
7
7
  * Two concrete implementations:
8
8
  * - OpenAI Chat Completions (covers 95% of providers)
9
9
  * - Anthropic Messages API
10
10
  */
11
- import type { ChatMessage, ToolDefinition } from "../agent/types.js";
11
+ import type { ChatMessage, ToolDefinition } from "../protocol/wire/index.js";
12
12
  export type StructuredOutputConfig = {
13
13
  mode: "json_object";
14
14
  } | {
@@ -19,7 +19,7 @@ export type StructuredOutputConfig = {
19
19
  };
20
20
  export interface CachingConfig {
21
21
  type: "enabled" | "disabled";
22
- /** Enable prefix caching mode (§20.3). Requires store=true and stream=false. */
22
+ /** Enable prefix caching mode (20.3). Requires store=true and stream=false. */
23
23
  prefix?: boolean;
24
24
  }
25
25
  export type ContextEdit = {
@@ -58,10 +58,10 @@ export interface LLMRequest {
58
58
  maxTokens?: number;
59
59
  reasoning?: {
60
60
  effort: "minimal" | "low" | "medium" | "high" | "xhigh";
61
- /** Request encrypted original reasoning content (Volcengine §17.7). */
61
+ /** Request encrypted original reasoning content (Volcengine 17.7). */
62
62
  includeEncryptedReasoning?: boolean;
63
63
  };
64
- /** Volcengine: max builtin tool calls per turn (§19.15). */
64
+ /** Volcengine: max builtin tool calls per turn (19.15). */
65
65
  maxToolCalls?: number;
66
66
  /**
67
67
  * DeepSeek prefix completion: force model to continue from this prefix.
@@ -69,7 +69,7 @@ export interface LLMRequest {
69
69
  */
70
70
  prefixMessage?: string;
71
71
  /**
72
- * Model requires streaming disable non-streaming fallback in transports.
72
+ * Model requires streaming 鈥?disable non-streaming fallback in transports.
73
73
  * When true, transports must NOT fall back to non-streaming requests on failure.
74
74
  * Set for models like QwQ/Omni where the provider rejects non-streaming calls.
75
75
  */
@@ -89,49 +89,49 @@ export interface LLMRequest {
89
89
  config?: Record<string, unknown>;
90
90
  }>;
91
91
  /**
92
- * Server-side context continuation via response chain (§5).
92
+ * Server-side context continuation via response chain (5).
93
93
  * When set, the server automatically includes previous context,
94
94
  * so messages[] only needs to contain the NEW user message.
95
95
  */
96
96
  previousResponseId?: string;
97
97
  /**
98
- * Control server-side storage of this request's input/output (§5.1).
98
+ * Control server-side storage of this request's input/output (5.1).
99
99
  * Default: true (server stores for 3 days).
100
100
  */
101
101
  store?: boolean;
102
102
  /** Expiration time for stored response (Unix seconds, max 7 days from now) */
103
103
  storeExpireAt?: number;
104
104
  /**
105
- * Per-turn system instruction augmentation (§8).
105
+ * Per-turn system instruction augmentation (8).
106
106
  * Temporarily overlays persona or adds constraints for this turn only.
107
- * NOTE: Incompatible with caching do not use both together.
107
+ * NOTE: Incompatible with caching 鈥?do not use both together.
108
108
  */
109
109
  instructions?: string;
110
110
  /**
111
- * Structured output format (§16).
111
+ * Structured output format (16).
112
112
  * Forces model to produce JSON conforming to the specified schema.
113
113
  */
114
114
  structuredOutput?: StructuredOutputConfig;
115
115
  /**
116
- * Caching configuration (§20).
116
+ * Caching configuration (20).
117
117
  * Controls prefix/session caching behavior.
118
118
  * NOTE: Incompatible with instructions, json_schema, and builtin tools.
119
119
  */
120
120
  caching?: CachingConfig;
121
121
  /**
122
- * Context management edits (§21, beta).
122
+ * Context management edits (21, beta).
123
123
  * Server-side trimming of historical thinking chains and tool call traces.
124
124
  */
125
125
  contextManagement?: ContextManagementConfig;
126
126
  /**
127
- * Gemini explicit cache reference (gemini-ProviderMax §8).
127
+ * Gemini explicit cache reference (gemini-ProviderMax 8).
128
128
  * Passes a pre-created cache name (e.g. "cachedContents/abc123") to
129
129
  * generateContent so the server uses cached tokens instead of re-processing.
130
130
  * Create caches via GeminiCacheAPI.createCache() first.
131
131
  */
132
132
  cachedContent?: string;
133
133
  /**
134
- * Predicted output for speculative decoding (openai-ProviderMax §11).
134
+ * Predicted output for speculative decoding (openai-ProviderMax 11).
135
135
  * When editing code, pass the existing content so the model can diff efficiently.
136
136
  * Reduces latency by 3-5x when prediction matches. Falls back when it doesn't.
137
137
  * Works with OpenAI GPT-5.x models via Responses API and Chat Completions.
@@ -141,24 +141,24 @@ export interface LLMRequest {
141
141
  content: string;
142
142
  };
143
143
  /**
144
- * Prompt cache bucketing key (openai-ProviderMax §11).
144
+ * Prompt cache bucketing key (openai-ProviderMax 11).
145
145
  * Replaces the deprecated `user` field. Helps OpenAI group similar requests
146
146
  * for higher cache hit rates.
147
147
  */
148
148
  promptCacheKey?: string;
149
149
  /**
150
- * Prompt cache retention policy (openai-ProviderMax §11).
150
+ * Prompt cache retention policy (openai-ProviderMax 11).
151
151
  * "in_memory" = default 5-10 min, "24h" = extended up to 24 hours.
152
152
  */
153
153
  promptCacheRetention?: "in_memory" | "24h";
154
154
  /**
155
- * Service tier for request scheduling (openai-ProviderMax §14).
155
+ * Service tier for request scheduling (openai-ProviderMax 14).
156
156
  * "auto" = project default, "flex" = 50% cheaper / higher latency,
157
157
  * "priority" = guaranteed low latency.
158
158
  */
159
159
  serviceTier?: "auto" | "default" | "flex" | "priority";
160
160
  /**
161
- * OpenAI Responses API built-in tools (openai-ProviderMax §7).
161
+ * OpenAI Responses API built-in tools (openai-ProviderMax 7).
162
162
  * Platform-executed tools like web_search, file_search, code_interpreter, etc.
163
163
  */
164
164
  openaiBuiltinTools?: Array<{
@@ -166,8 +166,8 @@ export interface LLMRequest {
166
166
  [key: string]: unknown;
167
167
  }>;
168
168
  /**
169
- * OpenAI Responses API conversation ID (openai-ProviderMax §2.1).
170
- * Alternative to previous_response_id persistent server-side conversation.
169
+ * OpenAI Responses API conversation ID (openai-ProviderMax 2.1).
170
+ * Alternative to previous_response_id 鈥?persistent server-side conversation.
171
171
  * Cannot be used together with previousResponseId.
172
172
  */
173
173
  conversationId?: string;
@@ -177,13 +177,13 @@ export interface LLMRequest {
177
177
  */
178
178
  parallelToolCalls?: boolean;
179
179
  /**
180
- * Text output verbosity hint (openai-ProviderMax §5).
180
+ * Text output verbosity hint (openai-ProviderMax 5).
181
181
  * Controls how detailed the model's textual output should be.
182
182
  */
183
183
  textVerbosity?: "low" | "medium" | "high";
184
184
  }
185
185
  /**
186
- * FIM completion request DeepSeek Beta Completions API.
186
+ * FIM completion request 鈥?DeepSeek Beta Completions API.
187
187
  * POST /beta/v1/completions with prompt + suffix.
188
188
  * Only works with non-thinking mode.
189
189
  */
@@ -267,7 +267,7 @@ export interface LLMTransport {
267
267
  */
268
268
  stream(request: LLMRequest, apiKey: string, signal?: AbortSignal): AsyncGenerator<LLMChunk>;
269
269
  /**
270
- * FIM (Fill-In-Middle) completion optional capability.
270
+ * FIM (Fill-In-Middle) completion 鈥?optional capability.
271
271
  * Only implemented by providers that support it (DeepSeek /beta endpoint).
272
272
  */
273
273
  complete?(request: FIMRequest, apiKey: string, signal?: AbortSignal): AsyncGenerator<FIMChunk>;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Anthropic Messages Transport SSE streaming for Claude API.
2
+ * Anthropic Messages Transport 鈥?SSE streaming for Claude API.
3
3
  *
4
4
  * Aligned with CC (claude-code-haha) src/services/api/claude.ts:
5
5
  * - cache_control ephemeral injection on system prompt blocks
@@ -26,7 +26,7 @@ export interface AnthropicTransportConfig {
26
26
  enablePromptCaching?: boolean;
27
27
  /** Max retry attempts on transient errors (default 3) */
28
28
  maxRetries?: number;
29
- /** Omit temperature when it equals 0 MiniMax rejects temperature=0 */
29
+ /** Omit temperature when it equals 0 鈥?MiniMax rejects temperature=0 */
30
30
  omitZeroTemperature?: boolean;
31
31
  /** Provider-specific quirks for conditional logic (CC/altcode parity) */
32
32
  quirks?: ProviderQuirks;
@@ -1,10 +1,10 @@
1
1
  /**
2
- * Gemini generateContent Transport Native Gemini API streaming implementation.
2
+ * Gemini generateContent Transport 鈥?Native Gemini API streaming implementation.
3
3
  *
4
4
  * Targets Gemini 3 series exclusively (3.1 Pro, 3 Flash, 3.1 Flash-Lite).
5
5
  * Uses the native Gemini REST API instead of the OpenAI compatibility layer,
6
6
  * unlocking Gemini-exclusive features unavailable via the compat endpoint:
7
- * - thinkingConfig (thinkingLevel G3 native control)
7
+ * - thinkingConfig (thinkingLevel 鈥?G3 native control)
8
8
  * - Google Search / Maps Grounding
9
9
  * - Code Execution
10
10
  * - Safety Settings fine-grained control
@@ -1,5 +1,5 @@
1
1
  /**
2
- * OpenAI Chat Completions Transport SSE streaming implementation.
2
+ * OpenAI Chat Completions Transport 鈥?SSE streaming implementation.
3
3
  *
4
4
  * Covers all OpenAI-compatible providers:
5
5
  * DeepSeek, Qwen, Minimax, Moonshot, OpenRouter, etc.
@@ -70,7 +70,7 @@ export declare class OpenAIChatTransport implements LLMTransport {
70
70
  bytes: number;
71
71
  }>;
72
72
  /**
73
- * Get file content/status GET /v1/files/{file_id}
73
+ * Get file content/status 鈥?GET /v1/files/{file_id}
74
74
  */
75
75
  getFileInfo(fileId: string, apiKey: string, signal?: AbortSignal): Promise<{
76
76
  id: string;
@@ -1,5 +1,5 @@
1
1
  /**
2
- * OpenAI Responses API Transport SSE streaming implementation.
2
+ * OpenAI Responses API Transport 鈥?SSE streaming implementation.
3
3
  *
4
4
  * Implements the OpenAI Responses API (`POST /v1/responses`),
5
5
  * the officially recommended path for GPT-5.x text generation.
@@ -49,14 +49,14 @@ export declare class OpenAIResponsesTransport implements LLMTransport {
49
49
  *
50
50
  * Event format: "event: <type>\ndata: <json>\n\n"
51
51
  * Key events:
52
- * - response.output_text.delta text content delta
53
- * - response.reasoning_summary_text.delta reasoning summary text
54
- * - response.function_call_arguments.delta tool call arguments streaming
55
- * - response.output_item.added new output item started
56
- * - response.output_item.done output item completed
57
- * - response.content_part.done content part completed (annotations)
58
- * - response.completed full response complete with usage
59
- * - response.failed error
52
+ * - response.output_text.delta 鈫?text content delta
53
+ * - response.reasoning_summary_text.delta 鈫?reasoning summary text
54
+ * - response.function_call_arguments.delta 鈫?tool call arguments streaming
55
+ * - response.output_item.added 鈫?new output item started
56
+ * - response.output_item.done 鈫?output item completed
57
+ * - response.content_part.done 鈫?content part completed (annotations)
58
+ * - response.completed 鈫?full response complete with usage
59
+ * - response.failed 鈫?error
60
60
  */
61
61
  private parseSSEStream;
62
62
  private processEvent;