@abacus-ai/cli 2.5.1-canary.0 → 2.5.1-canary.1
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/index.mjs +3 -3
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -75104,9 +75104,9 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
|
|
|
75104
75104
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
75105
75105
|
`,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,a=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(a=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(a.push(this.sourceToken),e.items.push({start:a,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey)if(!t.sep)if(i(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=c(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(i(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(o(t.key)&&!i(t.sep,`newline`)){let e=c(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken);else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):i(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:a,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!i(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:a});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||i(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=c(s(t));l(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
|
|
75106
75106
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
75107
|
-
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Gke=G((e=>{var t=$q(),n=Wq(),r=Gq(),i=Cq(),a=lq(),o=nJ(),s=rJ();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Kke=G((e=>{var t=$q(),n=Wq(),r=Uq(),i=Gq(),a=gq(),o=lq(),s=Eq(),c=_q(),l=Oq(),u=Aq();eJ();var d=tJ(),f=nJ(),p=rJ(),m=Gke(),h=uq();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();function qke(e){let t=e.trimStart();if(!t.startsWith(`---`))return{data:{},body:e};let n=t.match(/\r?\n---\s*(?:\r?\n|$)/);if(!n||n.index===void 0)return{data:{},body:e};let r=n.index,i=t.slice(3,r).trim(),a=t.slice(r+n[0].length).trim();try{let e=(0,Kke.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function Jke(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const Yke=dt([`codellm`,`agent`,`skills`]),iJ=new class{skills=new Map;async loadSkills(e,t){let r=await zwe(t??`cli`),i=P.join(n.homedir(),hn.configDirName,`skills`),a=e?P.join(e,hn.localConfigDirName,`skills`):void 0,o=await this.discoverSkills(r,`builtin`),s=await this.discoverSkills(i,`global`),c=a?await this.discoverSkills(a,`project`):[];this.skills.clear();for(let e of o)this.skills.set(e.id,e);for(let e of s)this.skills.set(e.id,e);for(let e of c)this.skills.set(e.id,e);Yke.info`skills loaded: builtin=${o.length} global=${s.length} project=${c.length} clientKind=${t??`cli`}`}async discoverSkills(e,t){let n=[],r;try{r=await Te.readdir(e,{withFileTypes:!0})}catch{return n}r.sort((e,t)=>e.name.localeCompare(t.name));for(let i of r)if(i.isFile()&&i.name.endsWith(`.md`)){let r=P.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=P.join(e,i.name,`SKILL.md`);try{await Te.access(r);let e=await this.parseSkillFile(r,!0,t);e&&n.push(e)}catch{}}return n}async parseSkillFile(e,t,n){try{let{data:r}=qke(await Te.readFile(e,`utf-8`)),i=Jke(t?P.basename(P.dirname(e)):P.basename(e,`.md`));return i?this.buildSkill(i,r,e,t,n):null}catch{return null}}buildSkill(e,t,n,r,i){let a=t.name,o=t.description,s=typeof a==`string`&&a.trim()?a.trim():e,c=typeof o==`string`&&o.trim()?o.trim():void 0;if(!c)return null;let l={name:s,description:c};typeof t[`argument-hint`]==`string`&&(l[`argument-hint`]=t[`argument-hint`]),typeof t[`disable-model-invocation`]==`boolean`&&(l[`disable-model-invocation`]=t[`disable-model-invocation`]),typeof t[`user-invocable`]==`boolean`&&(l[`user-invocable`]=t[`user-invocable`]),Array.isArray(t[`allowed-tools`])&&(l[`allowed-tools`]=t[`allowed-tools`].filter(e=>typeof e==`string`)),typeof t.license==`string`&&(l.license=t.license),typeof t.compatibility==`string`&&(l.compatibility=t.compatibility);let u=t.metadata;if(u&&typeof u==`object`&&!Array.isArray(u)){let e={};for(let[t,n]of Object.entries(u))typeof n==`string`&&(e[t]=n);Object.keys(e).length>0&&(l.metadata=e)}return{id:e,frontmatter:l,path:n,isDirectory:r,source:i}}get(e){return this.skills.get(e)}getAll(){return Array.from(this.skills.values()).filter(e=>e.frontmatter[`user-invocable`]!==!1)}getAllMetadata(){return this.getAll().map(e=>({id:e.id,name:e.frontmatter.name,description:e.frontmatter.description,location:e.path}))}search(e){let t=e.toLowerCase();return this.getAll().filter(e=>e.id.toLowerCase().includes(t)||e.frontmatter.name.toLowerCase().includes(t)||e.frontmatter.description.toLowerCase().includes(t))}matchSkill(e){if(!e.startsWith(`/`))return null;let t=e.slice(1).split(/\s+/);if(t.length===0)return null;let[n,...r]=t;if(!n)return null;let i=this.skills.get(n);return!i||i.frontmatter[`user-invocable`]===!1?null:{skill:i,args:r.join(` `)}}},aJ=dt([`codellm`,`agent`,`tools`,`diagnostics`]);var Xke=class e extends lH{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=GR({uri:Y().optional().describe(`Optional file URI to get diagnostics for. If not provided, gets diagnostics for all files.`)});parameters=e.Parameters;constructor(e){super(),this._provider=e}needsPermission(){return!1}async execute(e,t){let n=e.uri?[e.uri]:void 0;aJ.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return aJ.debug`Found ${r.length} diagnostics`,{type:`get_diagnostics`,diagnostics:r,total:r.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=gz(e);if(t.rejected)return{phase:`rejected`,toolType:`get_diagnostics`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.status===`error`?`error`:`success`,r=t.diagnostics?.filter(e=>e.severity===`error`).length??0,i=t.diagnostics?.filter(e=>e.severity===`warning`).length??0,a=[];return r>0&&a.push(`${r} error${r===1?``:`s`}`),i>0&&a.push(`${i} warning${i===1?``:`s`}`),{phase:n,toolType:`get_diagnostics`,data:t,summary:a.length>0?a.join(`, `):`${t.total??0} diagnostics`}}catch{return{phase:`success`,toolType:`get_diagnostics`,data:{},summary:`Completed`}}}},Zke=class extends yz{includeInApiDefinitions=!1};const oJ=dt([`codellm`,`agent`,`tools`,`mcp`]);var Qke=class extends Zke{name;displayName;description;parameters;isReadonly=!1;mcpToolDefinition;constructor(e){super(),this.mcpToolDefinition=e,this.name=e.name,this.displayName=e.name,this.description=e.description||`MCP tool: ${e.name}`,this.parameters=this.createZodSchemaFromMCPSchema(e.inputSchema)}createZodSchemaFromMCPSchema(e){let t=e?.properties||{},n=e?.required||[],r={};for(let[e,i]of Object.entries(t)){let t=i,a=n.includes(e),o=this.jsonSchemaToZod(t);a||(o=o.optional()),r[e]=o}return GR(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?tz(e.enum):Y();case`number`:case`integer`:return kSe;case`boolean`:return Ez;case`array`:return e.items?UR(this.jsonSchemaToZod(e.items)):UR(VR());case`object`:if(e.properties){let t={},n=e.required||[];for(let[r,i]of Object.entries(e.properties)){let e=this.jsonSchemaToZod(i);n.includes(r)||(e=e.optional()),t[r]=e}return GR(t)}return $R(Y(),VR());case`null`:return BR();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):VR()}}async execute(e,t){if(oJ.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return oJ.warn`MCP service not available for tool: ${this.name}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP service not available`,isError:!0};try{let n=(await t.mcpService.listAllToolDefinitions()).find(e=>e.name===this.name);if(!n)throw Error(`MCP tool '${this.name}' not found`);let r=await t.mcpService.callTool(n.serverId,n.originalName||this.name,e);return{type:`mcp`,serverId:n.serverId,toolName:this.name,content:r.content||r,isError:r.isError||!1}}catch(e){return pu(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),oJ.error`MCP tool execution failed: ${this.name}: ${e instanceof Error?e.message:String(e)}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP tool execution failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}format(e,t){return JSON.stringify({type:`mcp`,status:e.isError?`error`:`success`,serverId:e.serverId,toolName:e.toolName,content:e.content})}parse(e){let t=gz(e);if(t.rejected)return{phase:`rejected`,toolType:`mcp`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.isError?{phase:`error`,toolType:`mcp`,data:t,summary:`Error`,errorMessage:typeof t.content==`string`?t.content:`MCP error`}:{phase:`success`,toolType:`mcp`,data:t,summary:`Executed successfully`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`mcp`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`mcp`,data:{},summary:`Executed successfully`}}};function $ke(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var eAe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=P.join(n.homedir(),hn.configDirName,`tmp`);m.mkdirSync(e,{recursive:!0}),this._tmpDir=m.mkdtempSync(P.join(e,`codellm-prompt-`))}return this._tmpDir}savePrompt(e){let t=this._ensureDir();this._counter++;let n=P.join(t,`prompt-${this._counter}.txt`);return m.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{m.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const tAe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},nAe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function sJ(e){let t=tAe[e.name];t&&(e.name=t);let n=nAe[e.name];if(n&&e.input&&typeof e.input==`object`){let t=e.input;for(let[e,r]of Object.entries(n))e in t&&!(r in t)&&(t[r]=t[e],delete t[e])}}function cJ(e){if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let t=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of t)sJ(e)}if(Array.isArray(e.segments))for(let t of e.segments)cJ(t)}function rAe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)sJ(t)}if(Array.isArray(t.segments))for(let e of t.segments)cJ(e)}}var lJ=class{sessionId;_logger=dt([`codellm`,`agent`,`session`]);_workspace;_terminalService;_registry;_mcpService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_agentsMdContent=void 0;_agentsMdSentInConversation=!1;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];_promptFileManager=new eAe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=XF(JF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>XF(JF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??Pd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new qTe(t),this._terminalService=new Cke(t),this._terminalService.onBackgroundComplete=(e,t,n)=>{let r=`Background process (id=${e}) running \`${t}\` has ${n===0?`completed successfully`:`exited with code ${n}`}.`;this.nq(r,{hidden:!0}),!this._running&&this.onAutoRestart&&this.onAutoRestart(r)},this._registry=kH(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new Xke(e.diagnosticsProvider)),this._mcpService=new sq;let r=e.config?.get(`permissions`)??{},i={allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]};this._rulesEngine=new fTe({rules:i,cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(!this._initialized){if(this._initialized=!0,this._logger.debug(`Initializing session`),this._config.config){if(await this._config.config.load(),this._config.clientType===void 0||this._config.sendAgentMd===void 0){let e=this._config.config.get(`client`);this._config.clientType??=e,this._config.sendAgentMd??=e===nt.CLOUD}let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=XF(JF(e));if(!this._config.allowedDirectories.includes(t)){this._config.allowedDirectories.push(t);let e=t.endsWith(`/`)?t:t+`/`;this._rulesEngine.addAllowRule(`Bash(cd ${e}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${t})`)}}}await Promise.all([this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired),this._config.enableSkills?iJ.loadSkills(this._config.primaryWorkspace,this._config.clientType?.toLowerCase()):Promise.resolve(),this._config.sendAgentMd?this._loadAgentMd():Promise.resolve()])}}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},authenticateServer:(e,t)=>this._mcpService.authenticateServer(e,t)}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{this._rules=[],this._markdownContext=``}}}async _loadAgentMd(){let e=this._config.primaryWorkspace;try{let t=(await Te.readdir(e)).find(e=>e.toLowerCase()===`agents.md`);t&&(this._agentsMdContent=await Te.readFile(P.join(e,t),`utf-8`))}catch{}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!OH.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)};switch(e.name){case`read`:{let t=JF(e.input.filePath??``),r=XF(P.isAbsolute(t)?t:P.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:P.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=XF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}if(r?.error)return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:``,newContent:``};let i=r?.currentContent??``,a=r?.newContent??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:i,newContent:a}}case`write`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=XF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t),isNewFile:!r?.fileExists}}return{type:`write_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:r?.currentContent??``,content:e.input.content??``,isNewFile:!r?.fileExists}}case`bash`:{let t=e.input.command??``;return{type:`run_terminal`,tool:e,displayName:n,command:t,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1),unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(t,this._config.primaryWorkspace)}}case`exit_plan_mode`:{let r=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(r?.planContent??``)}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};case`notebook_edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=XF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}let i=r?.notebook,a=e.input.cellId,o=e.input.editMode??`replace`,s=``;if(a&&i?.cells){let e=i.cells.find(e=>e.id===a||e.metadata?.id===a);e&&(s=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:n,notebookPath:e.input.notebookPath??``,cellId:a,editMode:o,cellType:e.input.cellType,originalContent:s,newContent:e.input.newSource??``}}default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let a=new AbortController,o=()=>a.abort(`interrupted`);n&&(n.aborted?a.abort(`interrupted`):n.addEventListener(`abort`,o,{once:!0}));let s=[],c=(e,t,n)=>{let r=n?.storageContent??t;return{id:e.id,content:t,...n?.rejected&&{rejected:!0},parsedResult:r.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:r,errorMessage:r}:this._registry.parse(e.name,r)}};try{let o=async t=>{if(a.signal.aborted)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0})};let o={workspace:this._workspace,terminalService:this._terminalService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:t.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:a,permissionProvider:this._config.permissionProvider,rulesEngine:this._rulesEngine,getAgentMode:()=>this._mode,setAgentMode:e=>{this._mode=e},mcpService:{listAllToolDefinitions:async()=>this._mcpService.getAbacusMcpTools(),callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),reloadConnections:async()=>{await this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},getServerStatus:e=>{let t=this._mcpService.getConnectedServers().find(t=>t.config.id===e);return t?t.status===`connected`?`running`:`error`:`stopped`}},...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory},...this._config.clientType&&{clientType:this._config.clientType},...r&&{emitEvent:r},...r&&{onOutputUpdate:(e,t)=>{r({type:`tool_output_update`,toolCallId:e,output:t})}}};try{if(this._registry.isDisabled(t.name))return{resolved:!0,result:c(t,`Error: tool '${t.name}' is disabled in this environment`)};r?.({type:`tool_execution_start`,tool:t});let e=this._registry.createToolInstance(t.name,t.input??{},o);if(await e.prepare(),t.name===`edit`&&OH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,a=o.workspacePath,s=o.plansDir??P.join(i(),hn.configDirName,`plans`),c=QF(P.resolve(a,t.input.filePath??``),P.resolve(a,s)),l={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:c,isNewFile:!(n?.fileExists??!0)},u={type:`tool_display_data`,toolCallId:t.id,data:l};r?.(u),this._toolEventBuffer.push(u)}if(t.name===`notebook_edit`&&OH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult?.notebook,i=t.input.cellId,a=``;if(i&&n?.cells){let e=n.cells.find(e=>e.id===i||e.metadata?.id===i);e&&(a=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}let o={originalContent:a,newContent:t.input.newSource??``},s={type:`tool_display_data`,toolCallId:t.id,data:o};r?.(s),this._toolEventBuffer.push(s)}if(t.name===`write`&&OH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i={originalContent:n?.currentContent??``,newContent:t.input.content??``,isNewFile:!(n?.fileExists??!0)},a={type:`tool_display_data`,toolCallId:t.id,data:i};r?.(a),this._toolEventBuffer.push(a)}let a=this._mode===Pd.Yolo&&t.name!==`ask_user_question`;if(!a&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,a=LH(t),s=this._rulesEngine.evaluate(i,a,this._config.primaryWorkspace);if(s===`deny`)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.REJECTED}),{rejected:!0})};if(s!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let a={type:`status_changed`,status:Fd.WaitingForToolPermission};r?.(a),this._toolEventBuffer.push(a);let s;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{s=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else s=await e}catch{return{resolved:!0,result:c(t,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Fd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Fd.ExecutingTool}),s===`reject`)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.REJECTED}),{rejected:!0})};if(typeof s==`object`&&s.type===`reject_with_message`)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.USER_MESSAGE,message:s.message}),{rejected:!0})};if(s===`allowAlways`||s===`allowYolo`||s===`accept`){if(s===`allowAlways`&&(i.type===`read_outside_directory`||i.type===`write_outside_directory`||i.type===`edit_outside_directory`||i.type===`notebook_edit_outside_directory`)){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(t.name===`exit_plan_mode`){let e=s===`allowYolo`?Pd.Yolo:s===`allowAlways`?Pd.AcceptEdits:Pd.Normal;this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(s===`allowAlways`){let e=Bd(i.type);this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof s==`object`&&s.type===`accept_with_message`&&this.nq(s.message),typeof s==`object`&&s.type===`question_answers`&&e.mergeParams({answers:s.answers}),typeof s==`object`&&s.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(s.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],s.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof s==`object`&&s.type===`allow_always_with_rules`){for(let e of s.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...s.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=Pd.PlanMode,o.agentMode=Pd.PlanMode,r?.({type:`mode_changed`,mode:Pd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.PlanMode})),t.name===`exit_plan_mode`&&a&&(this._mode=Pd.Normal,o.agentMode=Pd.Normal,r?.({type:`mode_changed`,mode:Pd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.Normal})),{resolved:!1,call:t,instance:e,ctx:o}}catch(e){return a.signal.aborted?{resolved:!0,result:c(t,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:c(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},l=async e=>{try{if(await e.instance.execute(),a.signal.aborted)return c(e.call,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return c(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(a.signal.aborted)return c(e.call,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return c(e.call,`Error: ${n}`)}},u=0,d=!1;for(;u<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(d){let n=t[u],i=!!e(n),a=this._registry.get(n.name),o=a?!a.isReadonly:!1;if(i||o){let e=c(n,vz);s.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),u++;continue}}if(e(t[u])){let n=u+1;for(;n<t.length&&e(t[n]);)n++;if(n-u>1){let i=t.slice(u,n),a=i.map(e);u=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=a[e],n=f[f.length-1],r=p[p.length-1];typeof t==`string`&&r.has(t)&&(f.push([]),p.push(new Set),n=f[f.length-1],r=p[p.length-1]),typeof t==`string`&&r.add(t),n.push(e)}let m=new Map,h=new Map,g=!1;for(let e of f){if(g){for(let t of e){let e=c(i[t],vz);s.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await o(i[t]));for(let t of e){let e=m.get(t);e.resolved&&r?.({type:`tool_execution_complete`,tool:i[t],result:e.result})}let t=e.filter(e=>!m.get(e).resolved).map(async e=>{let t=m.get(e);if(!t.resolved){let n=await l(t);h.set(e,n),r?.({type:`tool_execution_complete`,tool:i[e],result:n})}});for(let e=0;e<t.length;e+=10)await Promise.all(t.slice(e,e+10));for(let t of e){let e=m.get(t),n=e.resolved?e.result:h.get(t);s.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(d=!0);continue}}let n=t[u];u++;let i=await o(n);if(i.resolved){s.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let a=await l(i);s.push(a),r?.({type:`tool_execution_complete`,tool:n,result:a})}return s}finally{n&&n.removeEventListener(`abort`,o)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(this._config.isPrintMode?hn.nonInteractiveAgentType:hn.agentType,this._config.clientType);if(e?.success===!1&&e.error)throw Error(e.error);let t=e?.result?.deploymentConversationId;if(!t)throw Error(`Failed to create conversation: no deployment conversation ID returned`);return this._conversationId=t,t}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0;rAe(n);let i=this._hydrateHistory(n),a;for(let e=n.length-1;e>=0;e--){let t=n[e]?.inputParams?.llmName;if(t){a=t;break}}return{...r!==void 0&&{title:r},...a!==void 0&&{llmName:a},segments:i}}switchConversation(e){return this._conversationId=e,this._uploadedDocs.clear(),Promise.resolve()}resetConversation(){this._conversationId=null,this._uploadedDocs.clear(),this._agentsMdSentInConversation=!1}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null,this._uploadedDocs.clear(),this._agentsMdSentInConversation=!1)}async listConversations(){return((await this._config.apiClient.getConversationsList(this._config.isPrintMode?hn.nonInteractiveAgentType:hn.agentType))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=gz(i);r.toolUseResult={id:r.toolUseRequest.id,content:i,...o.rejected&&{rejected:!0}};let s=this._registry.parse(a,i);o.rejected&&(s.phase=`rejected`,o.userNote!==void 0&&(s.userNote=o.userNote)),r.parsedResult=s,r.toolPhase=s.phase}}_detectAbandonedTools(e){let t=new Set([`todo_write`]);for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`tool_call`&&!r.toolUseResult&&!t.has(r.toolUseRequest.name)){let t=e.slice(n+1).some(e=>e.type===`text`||e.type===`tool_call`),i=t?`abandoned`:`abandoned_last`;r.toolPhase=i,r.parsedResult={phase:i,toolType:r.toolUseRequest.name,data:{},summary:t?`Abandoned`:`Abandoned · What should I do next?`}}}}_rewriteIfLargePrompt(e){return $ke(e)?`The large prompt is saved in ${this._promptFileManager.savePrompt(e)} file. Follow the instructions in it.`:e}async*send(e,t){if(await this._ensureInitialized(),this._logger.info(`Sending message (conversationId={conversationId}, mode={mode}, model={model})`,{conversationId:this._conversationId,mode:this._mode,model:this._model}),!this._conversationId)for(let e=0;e<8;e++)try{await this.createConversation();break}catch(t){if(!Du(t)||e>=7)throw t;let n=Math.min((e+1)*2e3,1e4);yield{type:`retry`,attempt:e+1,maxAttempts:8,delayMs:n,isNetworkError:!0},await Iz(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Fd.Submitted};let r=this._rewriteIfLargePrompt(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new Qke(e)));let a=this._registry.getApiToolDefinitions(),o=this._config.isPrintMode?a.filter(e=>e.name!==`ask_user_question`):a,s={apiClient:this._config.apiClient,conversationId:this._conversationId,model:this._model,workspacePath:this._config.primaryWorkspace,...this._swapFolder&&{swapFolder:this._swapFolder},...this._setFolder&&{setFolder:this._setFolder},uploadedDocs:this._uploadedDocs,supportedTools:o,supportedSubAgents:Pz().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.sendAgentMd&&!this._agentsMdSentInConversation&&this._agentsMdContent!==void 0&&{agentsMd:this._agentsMdContent},...this._config.enableSkills&&(()=>{let e=iJ.getAllMetadata();return e.length>0?{availableSkills:e}:{}})(),...this._config.enableSkills&&t?.activeSkills&&t.activeSkills.length>0&&{activeSkills:t.activeSkills},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.config?.get(`client`)&&{client:this._config.config.get(`client`)},...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:P.isAbsolute(t.currentFile)?t.currentFile:P.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,getConcurrency:e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},dequeueAllQueuedMessage:e=>{let t=this.dq(e);return t.length===0?null:{message:this._rewriteIfLargePrompt(t.map(e=>e.message).join(`
|
|
75107
|
+
`,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=c(s(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=c(s(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}})),Gke=G((e=>{var t=$q(),n=Wq(),r=Gq(),i=Cq(),a=lq(),o=nJ(),s=rJ();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),Kke=G((e=>{var t=$q(),n=Wq(),r=Uq(),i=Gq(),a=gq(),o=lq(),s=Eq(),c=_q(),l=Oq(),u=Aq();eJ();var d=tJ(),f=nJ(),p=rJ(),m=Gke(),h=uq();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync}))();function qke(e){let t=e.trimStart();if(!t.startsWith(`---`))return{data:{},body:e};let n=t.match(/\r?\n---\s*(?:\r?\n|$)/);if(!n||n.index===void 0)return{data:{},body:e};let r=n.index,i=t.slice(3,r).trim(),a=t.slice(r+n[0].length).trim();try{let e=(0,Kke.parse)(i);return e&&typeof e==`object`&&!Array.isArray(e)?{data:e,body:a}:{data:{},body:a}}catch{return{data:{},body:e}}}function Jke(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)}const Yke=dt([`codellm`,`agent`,`skills`]),iJ=new class{skills=new Map;async loadSkills(e,t){let r=await zwe(t??`cli`),i=P.join(n.homedir(),hn.configDirName,`skills`),a=e?P.join(e,hn.localConfigDirName,`skills`):void 0,o=await this.discoverSkills(r,`builtin`),s=await this.discoverSkills(i,`global`),c=a?await this.discoverSkills(a,`project`):[];this.skills.clear();for(let e of o)this.skills.set(e.id,e);for(let e of s)this.skills.set(e.id,e);for(let e of c)this.skills.set(e.id,e);Yke.info`skills loaded: builtin=${o.length} global=${s.length} project=${c.length} clientKind=${t??`cli`}`}async discoverSkills(e,t){let n=[],r;try{r=await Te.readdir(e,{withFileTypes:!0})}catch{return n}r.sort((e,t)=>e.name.localeCompare(t.name));for(let i of r)if(i.isFile()&&i.name.endsWith(`.md`)){let r=P.join(e,i.name),a=await this.parseSkillFile(r,!1,t);a&&n.push(a)}else if(i.isDirectory()){let r=P.join(e,i.name,`SKILL.md`);try{await Te.access(r);let e=await this.parseSkillFile(r,!0,t);e&&n.push(e)}catch{}}return n}async parseSkillFile(e,t,n){try{let{data:r}=qke(await Te.readFile(e,`utf-8`)),i=Jke(t?P.basename(P.dirname(e)):P.basename(e,`.md`));return i?this.buildSkill(i,r,e,t,n):null}catch{return null}}buildSkill(e,t,n,r,i){let a=t.name,o=t.description,s=typeof a==`string`&&a.trim()?a.trim():e,c=typeof o==`string`&&o.trim()?o.trim():void 0;if(!c)return null;let l={name:s,description:c};typeof t[`argument-hint`]==`string`&&(l[`argument-hint`]=t[`argument-hint`]),typeof t[`disable-model-invocation`]==`boolean`&&(l[`disable-model-invocation`]=t[`disable-model-invocation`]),typeof t[`user-invocable`]==`boolean`&&(l[`user-invocable`]=t[`user-invocable`]),Array.isArray(t[`allowed-tools`])&&(l[`allowed-tools`]=t[`allowed-tools`].filter(e=>typeof e==`string`)),typeof t.license==`string`&&(l.license=t.license),typeof t.compatibility==`string`&&(l.compatibility=t.compatibility);let u=t.metadata;if(u&&typeof u==`object`&&!Array.isArray(u)){let e={};for(let[t,n]of Object.entries(u))typeof n==`string`&&(e[t]=n);Object.keys(e).length>0&&(l.metadata=e)}return{id:e,frontmatter:l,path:n,isDirectory:r,source:i}}get(e){return this.skills.get(e)}getAll(){return Array.from(this.skills.values()).filter(e=>e.frontmatter[`user-invocable`]!==!1)}getAllMetadata(){return this.getAll().map(e=>({id:e.id,name:e.frontmatter.name,description:e.frontmatter.description,location:e.path}))}search(e){let t=e.toLowerCase();return this.getAll().filter(e=>e.id.toLowerCase().includes(t)||e.frontmatter.name.toLowerCase().includes(t)||e.frontmatter.description.toLowerCase().includes(t))}matchSkill(e){if(!e.startsWith(`/`))return null;let t=e.slice(1).split(/\s+/);if(t.length===0)return null;let[n,...r]=t;if(!n)return null;let i=this.skills.get(n);return!i||i.frontmatter[`user-invocable`]===!1?null:{skill:i,args:r.join(` `)}}},aJ=dt([`codellm`,`agent`,`tools`,`diagnostics`]);var Xke=class e extends lH{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=GR({uri:Y().optional().describe(`Optional file URI to get diagnostics for. If not provided, gets diagnostics for all files.`)});parameters=e.Parameters;constructor(e){super(),this._provider=e}needsPermission(){return!1}async execute(e,t){let n=e.uri?[e.uri]:void 0;aJ.debug`Getting diagnostics${e.uri?` for ${e.uri}`:` for all files`}`;let r=await this._provider.getDiagnostics(n);return aJ.debug`Found ${r.length} diagnostics`,{type:`get_diagnostics`,diagnostics:r,total:r.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=gz(e);if(t.rejected)return{phase:`rejected`,toolType:`get_diagnostics`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.status===`error`?`error`:`success`,r=t.diagnostics?.filter(e=>e.severity===`error`).length??0,i=t.diagnostics?.filter(e=>e.severity===`warning`).length??0,a=[];return r>0&&a.push(`${r} error${r===1?``:`s`}`),i>0&&a.push(`${i} warning${i===1?``:`s`}`),{phase:n,toolType:`get_diagnostics`,data:t,summary:a.length>0?a.join(`, `):`${t.total??0} diagnostics`}}catch{return{phase:`success`,toolType:`get_diagnostics`,data:{},summary:`Completed`}}}},Zke=class extends yz{includeInApiDefinitions=!1};const oJ=dt([`codellm`,`agent`,`tools`,`mcp`]);var Qke=class extends Zke{name;displayName;description;parameters;isReadonly=!1;mcpToolDefinition;constructor(e){super(),this.mcpToolDefinition=e,this.name=e.name,this.displayName=e.name,this.description=e.description||`MCP tool: ${e.name}`,this.parameters=this.createZodSchemaFromMCPSchema(e.inputSchema)}createZodSchemaFromMCPSchema(e){let t=e?.properties||{},n=e?.required||[],r={};for(let[e,i]of Object.entries(t)){let t=i,a=n.includes(e),o=this.jsonSchemaToZod(t);a||(o=o.optional()),r[e]=o}return GR(r)}jsonSchemaToZod(e){switch(e.type){case`string`:return e.enum?tz(e.enum):Y();case`number`:case`integer`:return kSe;case`boolean`:return Ez;case`array`:return e.items?UR(this.jsonSchemaToZod(e.items)):UR(VR());case`object`:if(e.properties){let t={},n=e.required||[];for(let[r,i]of Object.entries(e.properties)){let e=this.jsonSchemaToZod(i);n.includes(r)||(e=e.optional()),t[r]=e}return GR(t)}return $R(Y(),VR());case`null`:return BR();default:return e.oneOf?this.jsonSchemaToZod(e.oneOf[0]):VR()}}async execute(e,t){if(oJ.debug`Executing MCP tool: ${this.name} (server=${this.mcpToolDefinition.serverId})`,!t.mcpService)return oJ.warn`MCP service not available for tool: ${this.name}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP service not available`,isError:!0};try{let n=(await t.mcpService.listAllToolDefinitions()).find(e=>e.name===this.name);if(!n)throw Error(`MCP tool '${this.name}' not found`);let r=await t.mcpService.callTool(n.serverId,n.originalName||this.name,e);return{type:`mcp`,serverId:n.serverId,toolName:this.name,content:r.content||r,isError:r.isError||!1}}catch(e){return pu(e instanceof Error?e:Error(String(e)),{context:`mcp-tool-execution`}),oJ.error`MCP tool execution failed: ${this.name}: ${e instanceof Error?e.message:String(e)}`,{type:`mcp`,serverId:this.mcpToolDefinition.serverId,toolName:this.name,content:`MCP tool execution failed: ${e instanceof Error?e.message:String(e)}`,isError:!0}}}format(e,t){return JSON.stringify({type:`mcp`,status:e.isError?`error`:`success`,serverId:e.serverId,toolName:e.toolName,content:e.content})}parse(e){let t=gz(e);if(t.rejected)return{phase:`rejected`,toolType:`mcp`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.isError?{phase:`error`,toolType:`mcp`,data:t,summary:`Error`,errorMessage:typeof t.content==`string`?t.content:`MCP error`}:{phase:`success`,toolType:`mcp`,data:t,summary:`Executed successfully`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`mcp`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`mcp`,data:{},summary:`Executed successfully`}}};function $ke(e){return e.length>1e4?!0:e.split(/\r\n|\r|\n/).length>5e3}var eAe=class{_tmpDir=null;_counter=0;_ensureDir(){if(!this._tmpDir){let e=P.join(n.homedir(),hn.configDirName,`tmp`);m.mkdirSync(e,{recursive:!0}),this._tmpDir=m.mkdtempSync(P.join(e,`codellm-prompt-`))}return this._tmpDir}savePrompt(e){let t=this._ensureDir();this._counter++;let n=P.join(t,`prompt-${this._counter}.txt`);return m.writeFileSync(n,e,`utf-8`),n}cleanup(){if(this._tmpDir){try{m.rmSync(this._tmpDir,{recursive:!0,force:!0})}catch{}this._tmpDir=null,this._counter=0}}};const tAe={run_in_terminal:`bash`,get_terminal_output:`bash_output`,fetch_url:`web_fetch`},nAe={bash:{id:`shellId`,isBackground:`runInBackground`},bash_output:{id:`shellId`}};function sJ(e){let t=tAe[e.name];t&&(e.name=t);let n=nAe[e.name];if(n&&e.input&&typeof e.input==`object`){let t=e.input;for(let[e,r]of Object.entries(n))e in t&&!(r in t)&&(t[r]=t[e],delete t[e])}}function cJ(e){if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let t=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of t)sJ(e)}if(Array.isArray(e.segments))for(let t of e.segments)cJ(t)}function rAe(e){for(let t of e){if(t.toolUseRequest){let e=Array.isArray(t.toolUseRequest)?t.toolUseRequest:[t.toolUseRequest];for(let t of e)sJ(t)}if(Array.isArray(t.segments))for(let e of t.segments)cJ(e)}}var lJ=class{sessionId;_logger=dt([`codellm`,`agent`,`session`]);_workspace;_terminalService;_registry;_mcpService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_agentsMdContent=void 0;_agentsMdSentInConversation=!1;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];_promptFileManager=new eAe;_swapFolder=null;_setFolder=null;onAutoRestart=null;mcp;rules;constructor(e){let t=XF(JF(e.primaryWorkspace)),n=Array.from(new Set([t,...e.allowedDirectories.map(e=>XF(JF(e)))]));this._config={...e,primaryWorkspace:t,allowedDirectories:n},this.sessionId=crypto.randomUUID(),this._mode=e.mode??Pd.Normal,this._model=e.model??``,this._logger.info(`Creating AgentSession (workspace={workspace}, mode={mode})`,{workspace:t,mode:this._mode}),this._workspace=new qTe(t),this._terminalService=new Cke(t),this._terminalService.onBackgroundComplete=(e,t,n)=>{let r=`Background process (id=${e}) running \`${t}\` has ${n===0?`completed successfully`:`exited with code ${n}`}.`;this.nq(r,{hidden:!0}),!this._running&&this.onAutoRestart&&this.onAutoRestart(r)},this._registry=kH(),e.disabledBuiltinTools?.length&&this._registry.setDisabledTools(e.disabledBuiltinTools),e.diagnosticsProvider&&this._registry.register(new Xke(e.diagnosticsProvider)),this._mcpService=new sq;let r=e.config?.get(`permissions`)??{},i={allow:[...r.allow??[],...e.permissionRules?.allow??[]],deny:[...r.deny??[],...e.permissionRules?.deny??[]],ask:[...r.ask??[],...e.permissionRules?.ask??[]]};this._rulesEngine=new fTe({rules:i,cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(!this._initialized){if(this._initialized=!0,this._logger.debug(`Initializing session`),this._config.config){await this._config.config.load(),this._config.clientType??=this._config.config.get(`client`),this._config.sendAgentMd??=this._config.config.get(`autoLoadAgentsMd`);let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=XF(JF(e));if(!this._config.allowedDirectories.includes(t)){this._config.allowedDirectories.push(t);let e=t.endsWith(`/`)?t:t+`/`;this._rulesEngine.addAllowRule(`Bash(cd ${e}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${t})`)}}}await Promise.all([this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired),this._config.enableSkills?iJ.loadSkills(this._config.primaryWorkspace,this._config.clientType?.toLowerCase()):Promise.resolve(),this._config.sendAgentMd?this._loadAgentMd():Promise.resolve()])}}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},authenticateServer:(e,t)=>this._mcpService.authenticateServer(e,t)}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{this._rules=[],this._markdownContext=``}}}async _loadAgentMd(){let e=this._config.primaryWorkspace;try{let t=(await Te.readdir(e)).find(e=>e.toLowerCase()===`agents.md`);t&&(this._agentsMdContent=await Te.readFile(P.join(e,t),`utf-8`))}catch{}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!OH.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)};switch(e.name){case`read`:{let t=JF(e.input.filePath??``),r=XF(P.isAbsolute(t)?t:P.resolve(this._config.primaryWorkspace,t));return{type:`read_outside_directory`,tool:e,displayName:n,filePath:r,resolvedPath:r,deducedDirectory:P.dirname(r)}}case`edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=XF(r.resolvedPath??e.input.filePath??``);return{type:`edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}if(r?.error)return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:``,newContent:``};let i=r?.currentContent??``,a=r?.newContent??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:i,newContent:a}}case`write`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=XF(r.resolvedPath??e.input.filePath??``);return{type:`write_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t),isNewFile:!r?.fileExists}}return{type:`write_file`,tool:e,displayName:n,filePath:e.input.filePath??``,originalContent:r?.currentContent??``,content:e.input.content??``,isNewFile:!r?.fileExists}}case`bash`:{let t=e.input.command??``;return{type:`run_terminal`,tool:e,displayName:n,command:t,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1),unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(t,this._config.primaryWorkspace)}}case`exit_plan_mode`:{let r=t._prepareResult;return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(r?.planContent??``)}}case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};case`notebook_edit`:{let r=t._prepareResult;if(r?.outsideWorkspace){let t=XF(r.resolvedPath??e.input.notebookPath??``);return{type:`notebook_edit_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:t,deducedDirectory:P.dirname(t)}}let i=r?.notebook,a=e.input.cellId,o=e.input.editMode??`replace`,s=``;if(a&&i?.cells){let e=i.cells.find(e=>e.id===a||e.metadata?.id===a);e&&(s=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}return{type:`notebook_edit`,tool:e,displayName:n,notebookPath:e.input.notebookPath??``,cellId:a,editMode:o,cellType:e.input.cellType,originalContent:s,newContent:e.input.newSource??``}}default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let a=new AbortController,o=()=>a.abort(`interrupted`);n&&(n.aborted?a.abort(`interrupted`):n.addEventListener(`abort`,o,{once:!0}));let s=[],c=(e,t,n)=>{let r=n?.storageContent??t;return{id:e.id,content:t,...n?.rejected&&{rejected:!0},parsedResult:r.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:r,errorMessage:r}:this._registry.parse(e.name,r)}};try{let o=async t=>{if(a.signal.aborted)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0})};let o={workspace:this._workspace,terminalService:this._terminalService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:t.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:a,permissionProvider:this._config.permissionProvider,rulesEngine:this._rulesEngine,getAgentMode:()=>this._mode,setAgentMode:e=>{this._mode=e},mcpService:{listAllToolDefinitions:async()=>this._mcpService.getAbacusMcpTools(),callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),reloadConnections:async()=>{await this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)},getServerStatus:e=>{let t=this._mcpService.getConnectedServers().find(t=>t.config.id===e);return t?t.status===`connected`?`running`:`error`:`stopped`}},...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory},...this._config.clientType&&{clientType:this._config.clientType},...r&&{emitEvent:r},...r&&{onOutputUpdate:(e,t)=>{r({type:`tool_output_update`,toolCallId:e,output:t})}}};try{if(this._registry.isDisabled(t.name))return{resolved:!0,result:c(t,`Error: tool '${t.name}' is disabled in this environment`)};r?.({type:`tool_execution_start`,tool:t});let e=this._registry.createToolInstance(t.name,t.input??{},o);if(await e.prepare(),t.name===`edit`&&OH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,a=o.workspacePath,s=o.plansDir??P.join(i(),hn.configDirName,`plans`),c=QF(P.resolve(a,t.input.filePath??``),P.resolve(a,s)),l={originalContent:n?.currentContent??``,newContent:n?.newContent??``,isPlanFile:c,isNewFile:!(n?.fileExists??!0)},u={type:`tool_display_data`,toolCallId:t.id,data:l};r?.(u),this._toolEventBuffer.push(u)}if(t.name===`notebook_edit`&&OH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult?.notebook,i=t.input.cellId,a=``;if(i&&n?.cells){let e=n.cells.find(e=>e.id===i||e.metadata?.id===i);e&&(a=Array.isArray(e.source)?e.source.join(``):String(e.source??``))}let o={originalContent:a,newContent:t.input.newSource??``},s={type:`tool_display_data`,toolCallId:t.id,data:o};r?.(s),this._toolEventBuffer.push(s)}if(t.name===`write`&&OH.isBuiltinRequest(t)&&!e._prepareResult?.error){let n=e._prepareResult,i={originalContent:n?.currentContent??``,newContent:t.input.content??``,isNewFile:!(n?.fileExists??!0)},a={type:`tool_display_data`,toolCallId:t.id,data:i};r?.(a),this._toolEventBuffer.push(a)}let a=this._mode===Pd.Yolo&&t.name!==`ask_user_question`;if(!a&&e.needsPermission()){let i=this._registry.get(t.name)?.displayName??t.name,a=LH(t),s=this._rulesEngine.evaluate(i,a,this._config.primaryWorkspace);if(s===`deny`)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.REJECTED}),{rejected:!0})};if(s!==`allow`){let i=this._buildPermissionRequest(t,e);if(this._config.permissionProvider.needsPermission(i)){let a={type:`status_changed`,status:Fd.WaitingForToolPermission};r?.(a),this._toolEventBuffer.push(a);let s;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{s=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else s=await e}catch{return{resolved:!0,result:c(t,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0})}}if(r?.({type:`status_changed`,status:Fd.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Fd.ExecutingTool}),s===`reject`)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.REJECTED}),{rejected:!0})};if(typeof s==`object`&&s.type===`reject_with_message`)return{resolved:!0,result:c(t,JSON.stringify({reason:mz.USER_MESSAGE,message:s.message}),{rejected:!0})};if(s===`allowAlways`||s===`allowYolo`||s===`accept`){if(s===`allowAlways`&&(i.type===`read_outside_directory`||i.type===`write_outside_directory`||i.type===`edit_outside_directory`||i.type===`notebook_edit_outside_directory`)){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(t.name===`exit_plan_mode`){let e=s===`allowYolo`?Pd.Yolo:s===`allowAlways`?Pd.AcceptEdits:Pd.Normal;this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else if(s===`allowAlways`){let e=Bd(i.type);this._mode=e,o.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}}if(typeof s==`object`&&s.type===`accept_with_message`&&this.nq(s.message),typeof s==`object`&&s.type===`question_answers`&&e.mergeParams({answers:s.answers}),typeof s==`object`&&s.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(s.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],s.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}if(typeof s==`object`&&s.type===`allow_always_with_rules`){for(let e of s.rules)this._rulesEngine.addAllowRule(e);if(this._config.config){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],...s.rules];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}}return t.name===`enter_plan_mode`&&(this._mode=Pd.PlanMode,o.agentMode=Pd.PlanMode,r?.({type:`mode_changed`,mode:Pd.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.PlanMode})),t.name===`exit_plan_mode`&&a&&(this._mode=Pd.Normal,o.agentMode=Pd.Normal,r?.({type:`mode_changed`,mode:Pd.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:Pd.Normal})),{resolved:!1,call:t,instance:e,ctx:o}}catch(e){return a.signal.aborted?{resolved:!0,result:c(t,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0})}:{resolved:!0,result:c(t,`Error: ${e instanceof Error?e.message:String(e)}`)}}},l=async e=>{try{if(await e.instance.execute(),a.signal.aborted)return c(e.call,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0});let t=e.instance.formatResultForLLM(),n=e.instance.formatResult(),r=typeof t==`string`?t:JSON.stringify(t);return c(e.call,r,{storageContent:n===r?void 0:n})}catch(t){if(a.signal.aborted)return c(e.call,JSON.stringify({reason:mz.INTERRUPTED}),{rejected:!0});let n=t instanceof Error?t.message:String(t);return c(e.call,`Error: ${n}`)}},u=0,d=!1;for(;u<t.length;){let e=e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1;if(d){let n=t[u],i=!!e(n),a=this._registry.get(n.name),o=a?!a.isReadonly:!1;if(i||o){let e=c(n,vz);s.push(e),r?.({type:`tool_execution_complete`,tool:n,result:e}),u++;continue}}if(e(t[u])){let n=u+1;for(;n<t.length&&e(t[n]);)n++;if(n-u>1){let i=t.slice(u,n),a=i.map(e);u=n;let f=[[]],p=[new Set];for(let e=0;e<i.length;e++){let t=a[e],n=f[f.length-1],r=p[p.length-1];typeof t==`string`&&r.has(t)&&(f.push([]),p.push(new Set),n=f[f.length-1],r=p[p.length-1]),typeof t==`string`&&r.add(t),n.push(e)}let m=new Map,h=new Map,g=!1;for(let e of f){if(g){for(let t of e){let e=c(i[t],vz);s.push(e),r?.({type:`tool_execution_complete`,tool:i[t],result:e})}continue}for(let t of e)m.set(t,await o(i[t]));for(let t of e){let e=m.get(t);e.resolved&&r?.({type:`tool_execution_complete`,tool:i[t],result:e.result})}let t=e.filter(e=>!m.get(e).resolved).map(async e=>{let t=m.get(e);if(!t.resolved){let n=await l(t);h.set(e,n),r?.({type:`tool_execution_complete`,tool:i[e],result:n})}});for(let e=0;e<t.length;e+=10)await Promise.all(t.slice(e,e+10));for(let t of e){let e=m.get(t),n=e.resolved?e.result:h.get(t);s.push(n),!g&&!n.rejected&&n.content.startsWith(`Error:`)&&(g=!0)}}g&&(d=!0);continue}}let n=t[u];u++;let i=await o(n);if(i.resolved){s.push(i.result),r?.({type:`tool_execution_complete`,tool:n,result:i.result});continue}let a=await l(i);s.push(a),r?.({type:`tool_execution_complete`,tool:n,result:a})}return s}finally{n&&n.removeEventListener(`abort`,o)}}}async createConversation(){let e=await this._config.apiClient.createCodellmDeploymentConversation(this._config.isPrintMode?hn.nonInteractiveAgentType:hn.agentType,this._config.clientType);if(e?.success===!1&&e.error)throw Error(e.error);let t=e?.result?.deploymentConversationId;if(!t)throw Error(`Failed to create conversation: no deployment conversation ID returned`);return this._conversationId=t,t}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0;rAe(n);let i=this._hydrateHistory(n),a;for(let e=n.length-1;e>=0;e--){let t=n[e]?.inputParams?.llmName;if(t){a=t;break}}return{...r!==void 0&&{title:r},...a!==void 0&&{llmName:a},segments:i}}switchConversation(e){return this._conversationId=e,this._uploadedDocs.clear(),Promise.resolve()}resetConversation(){this._conversationId=null,this._uploadedDocs.clear(),this._agentsMdSentInConversation=!1}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null,this._uploadedDocs.clear(),this._agentsMdSentInConversation=!1)}async listConversations(){return((await this._config.apiClient.getConversationsList(this._config.isPrintMode?hn.nonInteractiveAgentType:hn.agentType))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=gz(i);r.toolUseResult={id:r.toolUseRequest.id,content:i,...o.rejected&&{rejected:!0}};let s=this._registry.parse(a,i);o.rejected&&(s.phase=`rejected`,o.userNote!==void 0&&(s.userNote=o.userNote)),r.parsedResult=s,r.toolPhase=s.phase}}_detectAbandonedTools(e){let t=new Set([`todo_write`]);for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`tool_call`&&!r.toolUseResult&&!t.has(r.toolUseRequest.name)){let t=e.slice(n+1).some(e=>e.type===`text`||e.type===`tool_call`),i=t?`abandoned`:`abandoned_last`;r.toolPhase=i,r.parsedResult={phase:i,toolType:r.toolUseRequest.name,data:{},summary:t?`Abandoned`:`Abandoned · What should I do next?`}}}}_rewriteIfLargePrompt(e){return $ke(e)?`The large prompt is saved in ${this._promptFileManager.savePrompt(e)} file. Follow the instructions in it.`:e}async*send(e,t){if(await this._ensureInitialized(),this._logger.info(`Sending message (conversationId={conversationId}, mode={mode}, model={model})`,{conversationId:this._conversationId,mode:this._mode,model:this._model}),!this._conversationId)for(let e=0;e<8;e++)try{await this.createConversation();break}catch(t){if(!Du(t)||e>=7)throw t;let n=Math.min((e+1)*2e3,1e4);yield{type:`retry`,attempt:e+1,maxAttempts:8,delayMs:n,isNetworkError:!0},await Iz(n)}this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Fd.Submitted};let r=this._rewriteIfLargePrompt(e),i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools();e.length>0&&this._registry.registerMCPTools(e.map(e=>new Qke(e)));let a=this._registry.getApiToolDefinitions(),o=this._config.isPrintMode?a.filter(e=>e.name!==`ask_user_question`):a,s={apiClient:this._config.apiClient,conversationId:this._conversationId,model:this._model,workspacePath:this._config.primaryWorkspace,...this._swapFolder&&{swapFolder:this._swapFolder},...this._setFolder&&{setFolder:this._setFolder},uploadedDocs:this._uploadedDocs,supportedTools:o,supportedSubAgents:Pz().map(e=>({name:e})),...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.sendAgentMd&&!this._agentsMdSentInConversation&&this._agentsMdContent!==void 0&&{agentsMd:this._agentsMdContent},...this._config.enableSkills&&(()=>{let e=iJ.getAllMetadata();return e.length>0?{availableSkills:e}:{}})(),...this._config.enableSkills&&t?.activeSkills&&t.activeSkills.length>0&&{activeSkills:t.activeSkills},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.config?.get(`client`)&&{client:this._config.config.get(`client`)},...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:P.isAbsolute(t.currentFile)?t.currentFile:P.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,getConcurrency:e=>this._registry.get(e.name)?.concurrency(e.input,this._config.primaryWorkspace)??!1,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},dequeueAllQueuedMessage:e=>{let t=this.dq(e);return t.length===0?null:{message:this._rewriteIfLargePrompt(t.map(e=>e.message).join(`
|
|
75108
75108
|
`)),allHidden:t.every(e=>e.hidden)}}};this._swapFolder=null,this._setFolder=null,s.agentsMd!==void 0&&(this._agentsMdSentInConversation=!0);let c=Vz(s,r,this._abortController.signal),l=!1,u;for(;!(u=await c.next()).done;){let e=u.value;e.type===`text_delta`&&!l?(l=!0,yield{type:`status_changed`,status:Fd.Streaming}):e.type===`tool_requested`&&(yield{type:`status_changed`,status:Fd.ExecutingTool}),yield e,e.type===`mode_changed`&&(this._mode=e.mode)}if(i=!1,this._messageQueue.length===0||this._abortController.signal.aborted)break;let d=this.dq({includeHidden:!0});if(d.length===0)break;let f=d.every(e=>e.hidden);r=this._rewriteIfLargePrompt(d.map(e=>e.message).join(`
|
|
75109
|
-
`)),f||(yield{type:`user_message_dequeued`,content:r})}}finally{this._running=!1,this._abortController=null,this._toolEventBuffer.length=0,this._uploadedDocs.clear(),this._promptFileManager.cleanup(),this._logger.debug(`Send completed, session idle`),yield{type:`status_changed`,status:Fd.Idle}}}stop(){this._abortController?.abort()}dispose(){this._abortController?.abort(),this._promptFileManager.cleanup(),this._terminalService.dispose()}nq(e,t){let n={id:crypto.randomUUID(),message:e,...t?.hidden?{hidden:!0}:{}};return this._messageQueue.push(n),{...n}}getQueue(e){return this.getQueueEntries(e).map(e=>e.message)}getQueueEntries(e){return e?.includeHidden??!1?this._messageQueue.map(e=>({...e})):this._messageQueue.filter(e=>e.hidden!==!0).map(e=>({...e}))}dq(e){let t=e?.includeHidden??!1,n=e?.id;if(n!==void 0){let e=this._messageQueue.findIndex(e=>e.id===n?t||e.hidden!==!0:!1);if(e===-1)return[];let[r]=this._messageQueue.splice(e,1);return r?[{...r}]:[]}if(t){let e=this._messageQueue.map(e=>({...e}));return this._messageQueue.length=0,e}let r=[],i=[];for(let e of this._messageQueue)e.hidden===!0?i.push(e):r.push({...e});return this._messageQueue=i,r}setContent(e,t){let n=typeof e==`string`?e:e.id,r=this._messageQueue.find(e=>e.id===n);return r?(r.message=t,{...r}):null}setText(e,t){return this.setContent(e,t)}remove(e,t){let n=typeof e==`string`?e:e.id,r=t?.includeHidden??!1,i=this._messageQueue.findIndex(e=>e.id===n&&(r||e.hidden!==!0));i!==-1&&this._messageQueue.splice(i,1)}clearQueue(e){if(e?.includeHidden===!0){this._messageQueue.length=0;return}this._messageQueue=this._messageQueue.filter(e=>e.hidden===!0)}addUploadedDoc(e){this._uploadedDocs.add(e)}clearUploadedDocs(){this._uploadedDocs.clear()}isDirectoryAllowed(e){let t=XF(JF(e));for(let e of this._config.allowedDirectories)if(QF(t,e))return{allowed:!0,coveredBy:e};return{allowed:!1}}addAllowedDirectory(e,t){let n=XF(JF(e));for(let e of this._config.allowedDirectories)if(QF(n,e))return{status:`already-allowed`,coveredBy:e};this._config.allowedDirectories.push(n);let r=n.endsWith(`/`)?n:n+`/`;if(this._rulesEngine.addAllowRule(`Bash(cd ${r}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${n})`),t?.persist&&this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(n)||this._config.config.set(`additionalDirectories`,[...e,n],`local`)}return{status:`added`}}setMode(e){this._mode=e}refreshPermissionRequest(e){return e.type===`run_terminal`?{...e,cwd:this._config.primaryWorkspace,unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(e.command,this._config.primaryWorkspace)}:e}setModel(e){this._model=e}setWorkspace(e){let t=XF(JF(e));if(this._config.primaryWorkspace=t,!this._config.allowedDirectories.includes(t)){this._config.allowedDirectories.push(t);let e=t.endsWith(`/`)?t:t+`/`;this._rulesEngine.addAllowRule(`Bash(cd ${e}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${t})`)}this._swapFolder=t,this._setFolder=t,this._workspace.setCwd(t),this._terminalService.setCwd(t)}getMode(){return this._mode}getConversationId(){return this._conversationId}isRunning(){return this._running}listTerminalSessions(){return this._terminalService.listSessions()}getTerminalSessionOutput(e){let t=this._terminalService.getLiveOutput(e);if(t)return t.output;let n=this._terminalService.getOutput(e);return n.length>0?n[n.length-1].output:``}async stopTerminalSession(e){return this._terminalService.stopCommand(e)}},iAe=class{needsPermission(e){return!1}async requestPermission(e){return`accept`}},aAe=class{handler;_needsPermission;constructor(e,t){this.handler=e,this._needsPermission=t}needsPermission(e){return this._needsPermission?this._needsPermission(e):!0}async requestPermission(e){return this.handler(e)}};const oAe={cli:nt.CLI,extension:nt.EXTENSION,cowork:nt.COWORK,desktop:nt.COWORK,cloud:nt.CLOUD};function sAe(e){return oAe[e.trim().toLowerCase().replaceAll(/[_\s-]+/g,``)]}var cAe=class{async read(){let e={},t=hn.envPrefix,n=hn.internalEnvPrefix,r=process.env[`${t}BASE_URL`],i=process.env[`${t}MODEL`],a=process.env[`${n}LOG_LEVEL`],o=process.env[`${t}MAX_TURNS`],s=process.env[`${t}AUTO_UPDATE`],c=process.env[`${n}CHANNEL`],l=process.env[`${n}CLIENT_KIND`];if(r&&(e.baseUrl=r),i&&(e.model=i),a&&(e.logLevel=a),o&&(e.maxTurns=parseInt(o,10)),c&&(e.updateChannel=c),l){let t=sAe(l);t&&(e.client=t)}if(s!==void 0){let t=Dz.safeParse(s);t.success&&t.data!==void 0&&(e.autoUpdate=t.data)}return e}},lAe=class{configPath;constructor(){this.configPath=P.join(i(),hn.configDirName,hn.configFileName)}async read(){try{let e=await b.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=P.dirname(this.configPath);await b.mkdir(t,{recursive:!0}),await b.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}},uAe=class{configPath;constructor(e){this.configPath=P.join(e,hn.localConfigDirName,hn.configFileName)}async read(){try{let e=await b.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=P.dirname(this.configPath);await b.mkdir(t,{recursive:!0}),await b.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}};const dAe=dt([`codellm`,`agent`,`config`]);function uJ(e,...t){let n={...e};for(let e of t)for(let t of Object.keys(e)){let r=e[t];r!==void 0&&(typeof r==`object`&&r&&!Array.isArray(r)&&typeof n[t]==`object`&&n[t]!==null?n[t]=uJ(n[t],r):n[t]=r)}return n}const dJ={allowedDirectories:[],primaryWorkspace:``,logLevel:`info`};var fJ=class{sources;cache=null;constructor(e){this.sources=[new lAe,new uAe(e.cwd),...e.extraSources??[],new cAe]}async load(){let e={...dJ};for(let t of this.sources){let n=await t.read();e=uJ(e,n)}this.cache=e,dAe.info`config loaded from ${this.sources.length} sources`}get(e){return this.cache?this.cache[e]??dJ[e]:dJ[e]}getAll(){return this.cache??dJ}async set(e,t,n=`global`){let r=n===`global`?this.sources[0]:this.sources[1];if(r?.write){let n=await r.read();await r.write({...n,[e]:t})}this.cache&&(this.cache[e]=t)}};const pJ=dt([`codellm`,`agent`,`native-notifier`]),fAe={complete:`Glass`,"action-required":`Ping`},pAe={complete:`complete`,"action-required":`dialog-warning`};function mJ(e){try{oe(e,{windowsHide:!0},e=>{e&&(pJ.warn`Notification sound command failed: ${e}`,pu(e,{context:`native-notifier`,phase:`play-sound`}))})}catch(e){pJ.warn`Notification sound exec threw synchronously: ${e}`,pu(e instanceof Error?e:Error(String(e)),{context:`native-notifier`,phase:`play-sound-sync`})}}function mAe(e){let t=process.platform;if(t===`darwin`)mJ(`afplay /System/Library/Sounds/${fAe[e]}.aiff`);else if(t===`win32`)mJ(`powershell -NoProfile -c "[console]::beep(${e===`complete`?880:440},400)"`);else{let t=pAe[e];mJ(`paplay /usr/share/sounds/freedesktop/stereo/${t}.oga 2>/dev/null || aplay /usr/share/sounds/freedesktop/stereo/${t}.oga 2>/dev/null || true`)}}function hAe(e,t,n,r){let i={title:e,message:t,sound:!1,...r?.iconPath&&{icon:r.iconPath},...r?.activateBundleId&&{activate:r.activateBundleId}},a=e=>{e&&(pJ.warn`OS notification failed: ${e}`,pu(e instanceof Error?e:Error(String(e)),{context:`native-notifier`,phase:`send-notification`,platform:process.platform,arch:process.arch}))};Promise.resolve().then(()=>{U.notify(i,e=>a(e))}).catch(a)}dt([`codellm`,`agent`,`history`]);var hJ=class{source;maxEntries;filePath;entries=[];navIndex=-1;loaded=!1;writeQueue=Promise.resolve();constructor(e,t){this.source=e,this.maxEntries=t?.maxEntries??1e4,this.filePath=t?.filePath??te(i(),hn.configDirName,`history.jsonl`)}async load(){if(!this.loaded){this.loaded=!0;try{let e=this.maxEntries*2048,t=await De(this.filePath,`r`);try{let{size:n}=await t.stat(),r=Math.max(0,n-e),i=Buffer.allocUnsafe(n-r);await t.read(i,0,i.length,r);let a=i.toString(`utf-8`),o=r===0?0:a.indexOf(`
|
|
75109
|
+
`)),f||(yield{type:`user_message_dequeued`,content:r})}}finally{this._running=!1,this._abortController=null,this._toolEventBuffer.length=0,this._uploadedDocs.clear(),this._promptFileManager.cleanup(),this._logger.debug(`Send completed, session idle`),yield{type:`status_changed`,status:Fd.Idle}}}stop(){this._abortController?.abort()}dispose(){this._abortController?.abort(),this._promptFileManager.cleanup(),this._terminalService.dispose()}nq(e,t){let n={id:crypto.randomUUID(),message:e,...t?.hidden?{hidden:!0}:{}};return this._messageQueue.push(n),{...n}}getQueue(e){return this.getQueueEntries(e).map(e=>e.message)}getQueueEntries(e){return e?.includeHidden??!1?this._messageQueue.map(e=>({...e})):this._messageQueue.filter(e=>e.hidden!==!0).map(e=>({...e}))}dq(e){let t=e?.includeHidden??!1,n=e?.id;if(n!==void 0){let e=this._messageQueue.findIndex(e=>e.id===n?t||e.hidden!==!0:!1);if(e===-1)return[];let[r]=this._messageQueue.splice(e,1);return r?[{...r}]:[]}if(t){let e=this._messageQueue.map(e=>({...e}));return this._messageQueue.length=0,e}let r=[],i=[];for(let e of this._messageQueue)e.hidden===!0?i.push(e):r.push({...e});return this._messageQueue=i,r}setContent(e,t){let n=typeof e==`string`?e:e.id,r=this._messageQueue.find(e=>e.id===n);return r?(r.message=t,{...r}):null}setText(e,t){return this.setContent(e,t)}remove(e,t){let n=typeof e==`string`?e:e.id,r=t?.includeHidden??!1,i=this._messageQueue.findIndex(e=>e.id===n&&(r||e.hidden!==!0));i!==-1&&this._messageQueue.splice(i,1)}clearQueue(e){if(e?.includeHidden===!0){this._messageQueue.length=0;return}this._messageQueue=this._messageQueue.filter(e=>e.hidden===!0)}addUploadedDoc(e){this._uploadedDocs.add(e)}clearUploadedDocs(){this._uploadedDocs.clear()}isDirectoryAllowed(e){let t=XF(JF(e));for(let e of this._config.allowedDirectories)if(QF(t,e))return{allowed:!0,coveredBy:e};return{allowed:!1}}addAllowedDirectory(e,t){let n=XF(JF(e));for(let e of this._config.allowedDirectories)if(QF(n,e))return{status:`already-allowed`,coveredBy:e};this._config.allowedDirectories.push(n);let r=n.endsWith(`/`)?n:n+`/`;if(this._rulesEngine.addAllowRule(`Bash(cd ${r}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${n})`),t?.persist&&this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(n)||this._config.config.set(`additionalDirectories`,[...e,n],`local`)}return{status:`added`}}setMode(e){this._mode=e}refreshPermissionRequest(e){return e.type===`run_terminal`?{...e,cwd:this._config.primaryWorkspace,unmatchedPatterns:this._rulesEngine.getUnmatchedBashSegments(e.command,this._config.primaryWorkspace)}:e}setModel(e){this._model=e}setWorkspace(e){let t=XF(JF(e));if(this._config.primaryWorkspace=t,!this._config.allowedDirectories.includes(t)){this._config.allowedDirectories.push(t);let e=t.endsWith(`/`)?t:t+`/`;this._rulesEngine.addAllowRule(`Bash(cd ${e}*)`),this._rulesEngine.addAllowRule(`Bash(cd ${t})`)}this._swapFolder=t,this._setFolder=t,this._workspace.setCwd(t),this._terminalService.setCwd(t)}getMode(){return this._mode}getConversationId(){return this._conversationId}isRunning(){return this._running}listTerminalSessions(){return this._terminalService.listSessions()}getTerminalSessionOutput(e){let t=this._terminalService.getLiveOutput(e);if(t)return t.output;let n=this._terminalService.getOutput(e);return n.length>0?n[n.length-1].output:``}async stopTerminalSession(e){return this._terminalService.stopCommand(e)}},iAe=class{needsPermission(e){return!1}async requestPermission(e){return`accept`}},aAe=class{handler;_needsPermission;constructor(e,t){this.handler=e,this._needsPermission=t}needsPermission(e){return this._needsPermission?this._needsPermission(e):!0}async requestPermission(e){return this.handler(e)}};const oAe={cli:nt.CLI,extension:nt.EXTENSION,cowork:nt.COWORK,desktop:nt.COWORK,cloud:nt.CLOUD};function sAe(e){return oAe[e.trim().toLowerCase().replaceAll(/[_\s-]+/g,``)]}var cAe=class{async read(){let e={},t=hn.envPrefix,n=hn.internalEnvPrefix,r=process.env[`${t}BASE_URL`],i=process.env[`${t}MODEL`],a=process.env[`${n}LOG_LEVEL`],o=process.env[`${t}MAX_TURNS`],s=process.env[`${t}AUTO_UPDATE`],c=process.env[`${n}CHANNEL`],l=process.env[`${n}CLIENT_KIND`],u=Dz.parse(process.env[`${t}AUTO_LOAD_AGENTS_MD`]);if(r&&(e.baseUrl=r),i&&(e.model=i),a&&(e.logLevel=a),o&&(e.maxTurns=parseInt(o,10)),c&&(e.updateChannel=c),u&&(e.autoLoadAgentsMd=u),l){let t=sAe(l);t&&(e.client=t)}if(s!==void 0){let t=Dz.safeParse(s);t.success&&t.data!==void 0&&(e.autoUpdate=t.data)}return e}},lAe=class{configPath;constructor(){this.configPath=P.join(i(),hn.configDirName,hn.configFileName)}async read(){try{let e=await b.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=P.dirname(this.configPath);await b.mkdir(t,{recursive:!0}),await b.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}},uAe=class{configPath;constructor(e){this.configPath=P.join(e,hn.localConfigDirName,hn.configFileName)}async read(){try{let e=await b.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=P.dirname(this.configPath);await b.mkdir(t,{recursive:!0}),await b.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}};const dAe=dt([`codellm`,`agent`,`config`]);function uJ(e,...t){let n={...e};for(let e of t)for(let t of Object.keys(e)){let r=e[t];r!==void 0&&(typeof r==`object`&&r&&!Array.isArray(r)&&typeof n[t]==`object`&&n[t]!==null?n[t]=uJ(n[t],r):n[t]=r)}return n}const dJ={allowedDirectories:[],primaryWorkspace:``,logLevel:`info`};var fJ=class{sources;cache=null;constructor(e){this.sources=[new lAe,new uAe(e.cwd),...e.extraSources??[],new cAe]}async load(){let e={...dJ};for(let t of this.sources){let n=await t.read();e=uJ(e,n)}this.cache=e,dAe.info`config loaded from ${this.sources.length} sources`}get(e){return this.cache?this.cache[e]??dJ[e]:dJ[e]}getAll(){return this.cache??dJ}async set(e,t,n=`global`){let r=n===`global`?this.sources[0]:this.sources[1];if(r?.write){let n=await r.read();await r.write({...n,[e]:t})}this.cache&&(this.cache[e]=t)}};const pJ=dt([`codellm`,`agent`,`native-notifier`]),fAe={complete:`Glass`,"action-required":`Ping`},pAe={complete:`complete`,"action-required":`dialog-warning`};function mJ(e){try{oe(e,{windowsHide:!0},e=>{e&&(pJ.warn`Notification sound command failed: ${e}`,pu(e,{context:`native-notifier`,phase:`play-sound`}))})}catch(e){pJ.warn`Notification sound exec threw synchronously: ${e}`,pu(e instanceof Error?e:Error(String(e)),{context:`native-notifier`,phase:`play-sound-sync`})}}function mAe(e){let t=process.platform;if(t===`darwin`)mJ(`afplay /System/Library/Sounds/${fAe[e]}.aiff`);else if(t===`win32`)mJ(`powershell -NoProfile -c "[console]::beep(${e===`complete`?880:440},400)"`);else{let t=pAe[e];mJ(`paplay /usr/share/sounds/freedesktop/stereo/${t}.oga 2>/dev/null || aplay /usr/share/sounds/freedesktop/stereo/${t}.oga 2>/dev/null || true`)}}function hAe(e,t,n,r){let i={title:e,message:t,sound:!1,...r?.iconPath&&{icon:r.iconPath},...r?.activateBundleId&&{activate:r.activateBundleId}},a=e=>{e&&(pJ.warn`OS notification failed: ${e}`,pu(e instanceof Error?e:Error(String(e)),{context:`native-notifier`,phase:`send-notification`,platform:process.platform,arch:process.arch}))};Promise.resolve().then(()=>{U.notify(i,e=>a(e))}).catch(a)}dt([`codellm`,`agent`,`history`]);var hJ=class{source;maxEntries;filePath;entries=[];navIndex=-1;loaded=!1;writeQueue=Promise.resolve();constructor(e,t){this.source=e,this.maxEntries=t?.maxEntries??1e4,this.filePath=t?.filePath??te(i(),hn.configDirName,`history.jsonl`)}async load(){if(!this.loaded){this.loaded=!0;try{let e=this.maxEntries*2048,t=await De(this.filePath,`r`);try{let{size:n}=await t.stat(),r=Math.max(0,n-e),i=Buffer.allocUnsafe(n-r);await t.read(i,0,i.length,r);let a=i.toString(`utf-8`),o=r===0?0:a.indexOf(`
|
|
75110
75110
|
`)+1,s=a.slice(o).split(`
|
|
75111
75111
|
`).filter(Boolean);for(let e of s)try{let t=JSON.parse(e);t.message&&t.source&&this.entries.push(t)}catch{}this.entries.length>this.maxEntries&&(this.entries=this.entries.slice(-this.maxEntries))}finally{await t.close()}}catch{}}}append(e){let t=e.trimStart();if(!t)return;let n={ts:new Date().toISOString(),source:this.source,message:t,multiline:t.includes(`
|
|
75112
75112
|
`)};this.entries.push(n),this.entries.length>this.maxEntries?(this.entries=this.entries.slice(-this.maxEntries),this.enqueueWrite(()=>this.rewriteFile())):this.enqueueWrite(()=>this.appendLine(n))}isNavigating(){return this.navIndex!==-1}navigateUp(){if(this.entries.length===0)return null;if(this.navIndex===-1)this.navIndex=this.entries.length-1;else if(this.navIndex>0)this.navIndex--;else return null;return this.entries[this.navIndex]??null}navigateDown(){return this.navIndex===-1?null:(this.navIndex++,this.navIndex>=this.entries.length?(this.navIndex=-1,null):this.entries[this.navIndex]??null)}resetNavigation(){this.navIndex=-1}getEntries(){return this.entries}enqueueWrite(e){this.writeQueue=this.writeQueue.then(e).catch(()=>{})}async appendLine(e){try{await Ee(ee(this.filePath),{recursive:!0});let t=await De(this.filePath,`a`);try{await t.write(JSON.stringify(e)+`
|
|
@@ -75178,7 +75178,7 @@ No matching component was found for:
|
|
|
75178
75178
|
* This source code is licensed under the MIT license found in the
|
|
75179
75179
|
* LICENSE file in the root directory of this source tree.
|
|
75180
75180
|
*/
|
|
75181
|
-
var uPe=G((e=>{var t=NY().__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){return t.H.useMemoCache(e)}})),_Q=G(((e,t)=>{t.exports=uPe()}))();function $(e){let t=(0,_Q.c)(14),{color:n,backgroundColor:r,dimColor:i,bold:a,italic:o,underline:s,strikethrough:c,inverse:l,wrap:u,transform:d,children:f}=e,p=i===void 0?!1:i,m=a===void 0?!1:a,h=o===void 0?!1:o,g=s===void 0?!1:s,_=c===void 0?!1:c,v=l===void 0?!1:l,y=u===void 0?`wrap`:u;if(f==null)return null;let b;t[0]!==r||t[1]!==m||t[2]!==n||t[3]!==p||t[4]!==v||t[5]!==h||t[6]!==_||t[7]!==g||t[8]!==d?(b=e=>(p&&(e=aQ().dim().render(e)),n&&(e=iQ(e,n,`foreground`)),r&&(e=iQ(e,r,`background`)),m&&(e=aQ().bold().render(e)),h&&(e=aQ().italic().render(e)),g&&(e=aQ().underline().render(e)),_&&(e=aQ().strikethrough().render(e)),v&&(e=aQ().reverse().render(e)),d&&(e=d(e)),e),t[0]=r,t[1]=m,t[2]=n,t[3]=p,t[4]=v,t[5]=h,t[6]=_,t[7]=g,t[8]=d,t[9]=b):b=t[9];let x=b,S;return t[10]!==f||t[11]!==x||t[12]!==y?(S=(0,Z.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:y},internal_transform:x,children:f}),t[10]=f,t[11]=x,t[12]=y,t[13]=S):S=t[13],S}const dPe=/\x1b\[[\d:]*;(\d+)/;function fPe(e){let t=dPe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const vQ={upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageDown:!1,pageUp:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1,super:!1,paste:!1,raw:``},yQ=(e,t={})=>{let{addInputListener:n}=(0,X.use)(MZ),r=(0,X.useRef)(e);r.current=e,(0,X.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if(uX(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);vQ.upArrow=!1,vQ.downArrow=!1,vQ.leftArrow=!1,vQ.rightArrow=!1,vQ.pageDown=!1,vQ.pageUp=!1,vQ.home=!1,vQ.end=!1,vQ.return=!1,vQ.escape=!1,vQ.ctrl=!1,vQ.shift=!1,vQ.tab=!1,vQ.backspace=!1,vQ.delete=!1,vQ.meta=!1,vQ.super=!1,vQ.paste=!0,vQ.raw=e,r.current(n,{...vQ});return}let t=yMe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);vQ.upArrow=i===`up`,vQ.downArrow=i===`down`,vQ.leftArrow=i===`left`,vQ.rightArrow=i===`right`,vQ.pageDown=i===`pagedown`,vQ.pageUp=i===`pageup`,vQ.home=i===`home`,vQ.end=i===`end`,vQ.return=i===`return`||i===`enter`,vQ.escape=i===`escape`,vQ.ctrl=a,vQ.shift=o,vQ.tab=i===`tab`,vQ.backspace=i===`backspace`,vQ.delete=i===`delete`,vQ.meta=s,vQ.super=fPe(e),vQ.paste=!1,vQ.raw=e;let c=vQ,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let t=SMe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},pPe=()=>{let e=(0,X.use)(NZ);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},bQ=e=>{let t=(0,_Q.c)(23),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{isActive:r,autoFocus:i,id:a}=n,o=r===void 0?!0:r,s=i===void 0?!1:i,{activeId:c,add:l,remove:u,activate:d,deactivate:f,focus:p}=(0,X.use)(AZ),m;t[2]===a?m=t[3]:(m=a??Math.random().toString().slice(2,7),t[2]=a,t[3]=m);let h=m,g;t[4]!==l||t[5]!==s||t[6]!==h||t[7]!==u?(g=()=>(l(h,{autoFocus:s}),()=>{u(h)}),t[4]=l,t[5]=s,t[6]=h,t[7]=u,t[8]=g):g=t[8];let _;t[9]!==s||t[10]!==h?(_=[h,s],t[9]=s,t[10]=h,t[11]=_):_=t[11],(0,X.useEffect)(g,_);let v;t[12]!==d||t[13]!==f||t[14]!==h||t[15]!==o?(v=()=>{o?d(h):f(h)},t[12]=d,t[13]=f,t[14]=h,t[15]=o,t[16]=v):v=t[16];let y;t[17]!==h||t[18]!==o?(y=[o,h],t[17]=h,t[18]=o,t[19]=y):y=t[19],(0,X.useEffect)(v,y);let b=!!h&&c===h,x;return t[20]!==p||t[21]!==b?(x={isFocused:b,focus:p},t[20]=p,t[21]=b,t[22]=x):x=t[22],x};function xQ(){return(0,X.use)(jZ)}const SQ=()=>{let e=(0,X.use)(PZ);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},CQ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function mPe(){return new RegExp(CQ.source,`g`)}function hPe(e){return e.replace(CQ,``)}function gPe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function wQ(e){return`\x1B]2;`+gPe(e)+`\x07`}var TQ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.5.1-canary.0`,private:!0,bin:{abacusai:`dist/index.mjs`},files:[`dist`,`LICENSE.txt`],type:`module`,scripts:{"prepare-publish":`bun ./scripts/prepare-publish.ts`,build:`tsdown`,"check-types":`tsgo -b --noEmit`,test:`FORCE_COLOR=1 vitest run`,"test:watch":`FORCE_COLOR=1 vitest`,"test:ui":`FORCE_COLOR=1 vitest --ui`,"test:coverage":`FORCE_COLOR=1 vitest run --coverage`},dependencies:{"@clack/prompts":`^0.11.0`,"@codellm/agent":`workspace:*`,"@codellm/api":`workspace:*`,"@codellm/auth":`workspace:*`,"@codellm/comms":`workspace:*`,"@codellm/jar":`workspace:*`,"@codellm/logging":`workspace:*`,"@codellm/product":`workspace:*`,"@logtape/logtape":`catalog:`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`catalog:`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`catalog:`,"@vscode/ripgrep":`catalog:`,"ansi-styles":`catalog:`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`catalog:`,"cli-highlight":`^2.1.11`,conf:`catalog:`,diff:`catalog:`,fzf:`catalog:`,"gradient-string":`^3.0.0`,immer:`catalog:`,"isomorphic-git":`catalog:`,marked:`^17.0.6`,"node-notifier":`catalog:`,"patchright-core":`catalog:`,react:`catalog:react`,"react-compiler-runtime":`^1.0.0`,remend:`^1.3.0`,semver:`catalog:`,"shell-history":`^2.0.1`,"string-width":`catalog:`,"strip-ansi":`catalog:`,trash:`catalog:`,zod:`catalog:`},devDependencies:{"@babel/core":`catalog:infra`,"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@rolldown/plugin-babel":`catalog:infra`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`catalog:react`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:infra`,"@vitejs/plugin-react":`catalog:infra`,"@vitest/coverage-v8":`^4.1.5`,"@vitest/ui":`^4.1.5`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`catalog:infra`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`catalog:infra`,vite:`catalog:infra`,vitest:`catalog:infra`,zigpty:`^0.1.6`},engines:{node:`>=18`}}})),EQ=$e(TQ(),1);let DQ=null;function OQ(e){let t=(0,vY.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function kQ(e){if(!e)return``;try{return T(e)}catch{return e}}function AQ(){return{invokedPath:kQ(process.argv[1]??``),execPath:kQ(process.execPath??process.argv[0]??``)}}function jQ(e){let t=hn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function MQ(e){return/[/\\]node_modules[/\\]/.test(e)||/[/\\]\._npx[/\\]/.test(e)||/[/\\]_npx[/\\]/.test(e)||/[/\\]\.?npm[/\\]/.test(e)||/[/\\]\.?pnpm[/\\]/.test(e)||/[/\\]\.?yarn[/\\]/.test(e)||/[/\\]\.bun[/\\]/.test(e)}function NQ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=AQ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function PQ(){let e=process.env.npm_config_user_agent;if(e){let t=e.split(`/`)[0];if(t===`yarn`||t===`pnpm`||t===`bun`||t===`npm`)return t}let{invokedPath:t,execPath:n}=AQ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!jQ(n)?`bun`:`npm`}function _Pe(){let{execPath:e,invokedPath:t}=AQ();return MQ(t)||MQ(e)?!1:jQ(e)||jQ(t)}function FQ(){let e=`${hn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=AQ();return!(jQ(r)||jQ(n)||MQ(n)||MQ(r)||process.env.npm_config_user_agent)}function vPe(){let{execPath:e}=AQ(),t=PQ(),n=NQ();return FQ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:_Pe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function yPe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function bPe(e){let t=Date.now();if(DQ&&t-DQ.timestamp<6e4)return DQ.tags;let n=await fetch(`https://registry.npmjs.org/${e}`,{signal:AbortSignal.timeout(1e4),headers:{accept:`application/json`}});if(!n.ok)throw Error(`Registry returned ${n.status}`);let r=(await n.json())[`dist-tags`]??{};return DQ={tags:r,timestamp:t},r}async function xPe(e,t,n,r){let i=t??OQ(e),a=(r??`https://apps.abacus.ai`).replace(/\/$/,``),o=new URL(`${a}/api/v0/_getCodellmCliVersion`);o.searchParams.set(`channel`,i),n&&o.searchParams.set(`platform`,n),o.searchParams.set(`cli_version`,e);let s=await fetch(o.toString(),{signal:AbortSignal.timeout(1e4)});if(s.status===204)return null;if(!s.ok)throw Error(`API returned ${s.status}`);let c=await s.json(),l=c&&`result`in c&&c.result?c.result:c??{};if(!l.version||!l.channel)throw Error(`API returned invalid payload`);return{currentVersion:e,latestVersion:l.version,tag:l.channel,packageManager:PQ(),isEphemeral:NQ(),installationType:`native`,downloadUrl:l.url}}async function SPe(e,t){let n=t??OQ(e),r=PQ(),i=NQ(),a=(await bPe(gn.publishName))[n];return!a&&n!==`latest`||!a||a===e?null:{currentVersion:e,latestVersion:a,tag:n,packageManager:r,isEphemeral:i,installationType:`package-manager`}}async function IQ(e,t,n,r){let i=vPe();if(i.installationType===`native`)try{return await xPe(e,t,yPe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await SPe(e,t)}function LQ(e){if(e.installationType===`native`)return`${hn.binName} upgrade`;let t=`${gn.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function RQ(e){try{return{ok:!0,output:le(LQ(e),{stdio:`pipe`,encoding:`utf-8`}).trim()}}catch(e){return{ok:!1,output:e instanceof Error&&`stderr`in e?String(e.stderr).trim():e instanceof Error?e.message:`Unknown error`}}}function CPe(){let e=N.join(t.homedir(),hn.configDirName,`bin`);try{let n=N.dirname(kQ(process.execPath));return!n||n.toLowerCase().startsWith(t.tmpdir().toLowerCase())?e:n}catch{return e}}async function zQ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let n=N.join(t.tmpdir(),`abacusai-update-${Date.now()}`),r=process.platform===`win32`,i=r?`${hn.binName}.exe`:hn.binName,a=CPe();try{await we.mkdir(n,{recursive:!0}),await we.mkdir(a,{recursive:!0});let t=N.join(n,r?`update.zip`:`update.tar.gz`),o=await fetch(e.downloadUrl);if(!o.ok)throw Error(`Download failed: ${o.status}`);let s=Buffer.from(await o.arrayBuffer());await we.writeFile(t,s),le(r?`powershell -Command "Expand-Archive -Path '${t}' -DestinationPath '${n}' -Force"`:`tar -xzf "${t}" -C "${n}"`,{stdio:`pipe`});let c=N.join(n,i),l=N.join(a,i);if(r){let e=`${l}.old`;await we.rm(e,{force:!0}).catch(()=>{}),await we.rename(l,e).catch(()=>{}),await we.copyFile(c,l),await we.rm(e,{force:!0}).catch(()=>{})}else await we.copyFile(c,l),await we.chmod(l,493);return{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}function wPe(e,t){let n=e=>{let n=e.toLowerCase();if(n===t)return 1e3;if(n.startsWith(t))return 900;let r=0,i=-1;for(let e of t){let t=n.indexOf(e,i+1);if(t===-1)return 0;r+=100-(t-i),i=t}return r+=Math.max(0,50-n.length),r},r=null,i=0;for(let t of e){let e=Math.max(n(t.name??``),n(t.llmName));e>i&&(i=e,r=t.llmName)}return i>=100?r:null}async function BQ(e,t,n=nt.CLI){let r=(await e.listLLMModels({coworkV2:n===nt.COWORK}))?.result??[];return r.length||(process.stderr.write(`Error: No models available.
|
|
75181
|
+
var uPe=G((e=>{var t=NY().__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;e.c=function(e){return t.H.useMemoCache(e)}})),_Q=G(((e,t)=>{t.exports=uPe()}))();function $(e){let t=(0,_Q.c)(14),{color:n,backgroundColor:r,dimColor:i,bold:a,italic:o,underline:s,strikethrough:c,inverse:l,wrap:u,transform:d,children:f}=e,p=i===void 0?!1:i,m=a===void 0?!1:a,h=o===void 0?!1:o,g=s===void 0?!1:s,_=c===void 0?!1:c,v=l===void 0?!1:l,y=u===void 0?`wrap`:u;if(f==null)return null;let b;t[0]!==r||t[1]!==m||t[2]!==n||t[3]!==p||t[4]!==v||t[5]!==h||t[6]!==_||t[7]!==g||t[8]!==d?(b=e=>(p&&(e=aQ().dim().render(e)),n&&(e=iQ(e,n,`foreground`)),r&&(e=iQ(e,r,`background`)),m&&(e=aQ().bold().render(e)),h&&(e=aQ().italic().render(e)),g&&(e=aQ().underline().render(e)),_&&(e=aQ().strikethrough().render(e)),v&&(e=aQ().reverse().render(e)),d&&(e=d(e)),e),t[0]=r,t[1]=m,t[2]=n,t[3]=p,t[4]=v,t[5]=h,t[6]=_,t[7]=g,t[8]=d,t[9]=b):b=t[9];let x=b,S;return t[10]!==f||t[11]!==x||t[12]!==y?(S=(0,Z.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:0,flexDirection:`row`,textWrap:y},internal_transform:x,children:f}),t[10]=f,t[11]=x,t[12]=y,t[13]=S):S=t[13],S}const dPe=/\x1b\[[\d:]*;(\d+)/;function fPe(e){let t=dPe.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const vQ={upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageDown:!1,pageUp:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1,super:!1,paste:!1,raw:``},yQ=(e,t={})=>{let{addInputListener:n}=(0,X.use)(MZ),r=(0,X.useRef)(e);r.current=e,(0,X.useEffect)(()=>{if(t.isActive!==!1)return n(e=>{if(uX(e))return;if(e.startsWith(`\x1B[200~`)){let t=e.indexOf(`\x1B[201~`),n=t===-1?e.slice(6):e.slice(6,t);vQ.upArrow=!1,vQ.downArrow=!1,vQ.leftArrow=!1,vQ.rightArrow=!1,vQ.pageDown=!1,vQ.pageUp=!1,vQ.home=!1,vQ.end=!1,vQ.return=!1,vQ.escape=!1,vQ.ctrl=!1,vQ.shift=!1,vQ.tab=!1,vQ.backspace=!1,vQ.delete=!1,vQ.meta=!1,vQ.super=!1,vQ.paste=!0,vQ.raw=e,r.current(n,{...vQ});return}let t=yMe(e),n=t?t.split(`+`):[],i=n[n.length-1]??``,a=n.includes(`ctrl`),o=n.includes(`shift`),s=n.includes(`alt`);vQ.upArrow=i===`up`,vQ.downArrow=i===`down`,vQ.leftArrow=i===`left`,vQ.rightArrow=i===`right`,vQ.pageDown=i===`pagedown`,vQ.pageUp=i===`pageup`,vQ.home=i===`home`,vQ.end=i===`end`,vQ.return=i===`return`||i===`enter`,vQ.escape=i===`escape`,vQ.ctrl=a,vQ.shift=o,vQ.tab=i===`tab`,vQ.backspace=i===`backspace`,vQ.delete=i===`delete`,vQ.meta=s,vQ.super=fPe(e),vQ.paste=!1,vQ.raw=e;let c=vQ,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let t=SMe(e);t===void 0?e.length===1?l=e:i.length===1&&(l=i):l=t}r.current(l,{...c})})},[t.isActive,n])},pPe=()=>{let e=(0,X.use)(NZ);if(!e)throw Error(`useApp must be used within a jar render context`);return{exit:e.exit,requestFullRedraw:e.requestFullRedraw}},bQ=e=>{let t=(0,_Q.c)(23),n;t[0]===e?n=t[1]:(n=e===void 0?{}:e,t[0]=e,t[1]=n);let{isActive:r,autoFocus:i,id:a}=n,o=r===void 0?!0:r,s=i===void 0?!1:i,{activeId:c,add:l,remove:u,activate:d,deactivate:f,focus:p}=(0,X.use)(AZ),m;t[2]===a?m=t[3]:(m=a??Math.random().toString().slice(2,7),t[2]=a,t[3]=m);let h=m,g;t[4]!==l||t[5]!==s||t[6]!==h||t[7]!==u?(g=()=>(l(h,{autoFocus:s}),()=>{u(h)}),t[4]=l,t[5]=s,t[6]=h,t[7]=u,t[8]=g):g=t[8];let _;t[9]!==s||t[10]!==h?(_=[h,s],t[9]=s,t[10]=h,t[11]=_):_=t[11],(0,X.useEffect)(g,_);let v;t[12]!==d||t[13]!==f||t[14]!==h||t[15]!==o?(v=()=>{o?d(h):f(h)},t[12]=d,t[13]=f,t[14]=h,t[15]=o,t[16]=v):v=t[16];let y;t[17]!==h||t[18]!==o?(y=[o,h],t[17]=h,t[18]=o,t[19]=y):y=t[19],(0,X.useEffect)(v,y);let b=!!h&&c===h,x;return t[20]!==p||t[21]!==b?(x={isFocused:b,focus:p},t[20]=p,t[21]=b,t[22]=x):x=t[22],x};function xQ(){return(0,X.use)(jZ)}const SQ=()=>{let e=(0,X.use)(PZ);if(!e)throw Error(`useTerminal must be used within a jar render context`);return e.output},CQ=RegExp(`[\\x1b\\x9b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\\x1b\\][\\s\\S]*?(?:\\x07|\\x1b\\\\)`,`g`);function mPe(){return new RegExp(CQ.source,`g`)}function hPe(e){return e.replace(CQ,``)}function gPe(e){return e.replace(/[\x07\x1b\x9c]/g,``)}function wQ(e){return`\x1B]2;`+gPe(e)+`\x07`}var TQ=G(((e,t)=>{t.exports={name:`@codellm/cli`,version:`2.5.1-canary.1`,private:!0,bin:{abacusai:`dist/index.mjs`},files:[`dist`,`LICENSE.txt`],type:`module`,scripts:{"prepare-publish":`bun ./scripts/prepare-publish.ts`,build:`tsdown`,"check-types":`tsgo -b --noEmit`,test:`FORCE_COLOR=1 vitest run`,"test:watch":`FORCE_COLOR=1 vitest`,"test:ui":`FORCE_COLOR=1 vitest --ui`,"test:coverage":`FORCE_COLOR=1 vitest run --coverage`},dependencies:{"@clack/prompts":`^0.11.0`,"@codellm/agent":`workspace:*`,"@codellm/api":`workspace:*`,"@codellm/auth":`workspace:*`,"@codellm/comms":`workspace:*`,"@codellm/jar":`workspace:*`,"@codellm/logging":`workspace:*`,"@codellm/product":`workspace:*`,"@logtape/logtape":`catalog:`,"@orpc/client":`catalog:`,"@orpc/contract":`catalog:`,"@orpc/server":`catalog:`,"@sentry/node-core":`catalog:`,"@slack/web-api":`^7.0.0`,"@tanstack/react-query":`catalog:`,"@vscode/ripgrep":`catalog:`,"ansi-styles":`catalog:`,"beautiful-mermaid":`^1.1.3`,"cli-boxes":`catalog:`,"cli-highlight":`^2.1.11`,conf:`catalog:`,diff:`catalog:`,fzf:`catalog:`,"gradient-string":`^3.0.0`,immer:`catalog:`,"isomorphic-git":`catalog:`,marked:`^17.0.6`,"node-notifier":`catalog:`,"patchright-core":`catalog:`,react:`catalog:react`,"react-compiler-runtime":`^1.0.0`,remend:`^1.3.0`,semver:`catalog:`,"shell-history":`^2.0.1`,"string-width":`catalog:`,"strip-ansi":`catalog:`,trash:`catalog:`,zod:`catalog:`},devDependencies:{"@babel/core":`catalog:infra`,"@codellm/configs":`workspace:*`,"@playwright/mcp":`^0.0.68`,"@rolldown/plugin-babel":`catalog:infra`,"@types/diff":`^8.0.0`,"@types/node":`catalog:`,"@types/react":`catalog:react`,"@types/semver":`^7.7.1`,"@typescript/native-preview":`catalog:infra`,"@vitejs/plugin-react":`catalog:infra`,"@vitest/coverage-v8":`^4.1.5`,"@vitest/ui":`^4.1.5`,"@xterm/addon-serialize":`^0.14.0`,"@xterm/headless":`^6.0.0`,"babel-plugin-react-compiler":`catalog:infra`,"cli-testing-library":`^3.0.1`,jsdom:`^27.4.0`,"react-devtools-core":`^6.1.5`,"svg-term-cli":`^2.1.1`,tsdown:`catalog:infra`,vite:`catalog:infra`,vitest:`catalog:infra`,zigpty:`^0.1.6`},engines:{node:`>=18`}}})),EQ=$e(TQ(),1);let DQ=null;function OQ(e){let t=(0,vY.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function kQ(e){if(!e)return``;try{return T(e)}catch{return e}}function AQ(){return{invokedPath:kQ(process.argv[1]??``),execPath:kQ(process.execPath??process.argv[0]??``)}}function jQ(e){let t=hn.configDirName.replace(/^\./,``).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return RegExp(`[/\\\\]\\.?${t}[/\\\\]bin[/\\\\]`,`i`).test(e)}function MQ(e){return/[/\\]node_modules[/\\]/.test(e)||/[/\\]\._npx[/\\]/.test(e)||/[/\\]_npx[/\\]/.test(e)||/[/\\]\.?npm[/\\]/.test(e)||/[/\\]\.?pnpm[/\\]/.test(e)||/[/\\]\.?yarn[/\\]/.test(e)||/[/\\]\.bun[/\\]/.test(e)}function NQ(){let e=(process.env.npm_command??``).toLowerCase();if(e===`exec`||e===`dlx`)return!0;let{invokedPath:t,execPath:n}=AQ();return/[/\\]_npx[/\\]|[/\\]dlx[/\\]|[/\\]\.cache[/\\]/.test(t+`|`+n)}function PQ(){let e=process.env.npm_config_user_agent;if(e){let t=e.split(`/`)[0];if(t===`yarn`||t===`pnpm`||t===`bun`||t===`npm`)return t}let{invokedPath:t,execPath:n}=AQ(),r=`${t}|${n}`;return/[/\\]\.?yarn[/\\]/.test(r)?`yarn`:/[/\\]\.?pnpm[/\\]/.test(r)?`pnpm`:/[/\\]\.bun[/\\]/.test(r)||process.versions.bun!==void 0&&!jQ(n)?`bun`:`npm`}function _Pe(){let{execPath:e,invokedPath:t}=AQ();return MQ(t)||MQ(e)?!1:jQ(e)||jQ(t)}function FQ(){let e=`${hn.internalEnvPrefix}DEV`,t=process.env[e];if(t===`1`||t===`true`)return!0;let{invokedPath:n,execPath:r}=AQ();return!(jQ(r)||jQ(n)||MQ(n)||MQ(r)||process.env.npm_config_user_agent)}function vPe(){let{execPath:e}=AQ(),t=PQ(),n=NQ();return FQ()?{installationType:`development`,packageManager:t,isEphemeral:n,execPath:e}:_Pe()?{installationType:`native`,packageManager:t,isEphemeral:n,execPath:e}:{installationType:`package-manager`,packageManager:t,isEphemeral:n,execPath:e}}function yPe(){return`${process.platform===`win32`?`win32`:process.platform===`darwin`?`darwin`:`linux`}-${process.arch===`arm64`?`arm64`:`x64`}`}async function bPe(e){let t=Date.now();if(DQ&&t-DQ.timestamp<6e4)return DQ.tags;let n=await fetch(`https://registry.npmjs.org/${e}`,{signal:AbortSignal.timeout(1e4),headers:{accept:`application/json`}});if(!n.ok)throw Error(`Registry returned ${n.status}`);let r=(await n.json())[`dist-tags`]??{};return DQ={tags:r,timestamp:t},r}async function xPe(e,t,n,r){let i=t??OQ(e),a=(r??`https://apps.abacus.ai`).replace(/\/$/,``),o=new URL(`${a}/api/v0/_getCodellmCliVersion`);o.searchParams.set(`channel`,i),n&&o.searchParams.set(`platform`,n),o.searchParams.set(`cli_version`,e);let s=await fetch(o.toString(),{signal:AbortSignal.timeout(1e4)});if(s.status===204)return null;if(!s.ok)throw Error(`API returned ${s.status}`);let c=await s.json(),l=c&&`result`in c&&c.result?c.result:c??{};if(!l.version||!l.channel)throw Error(`API returned invalid payload`);return{currentVersion:e,latestVersion:l.version,tag:l.channel,packageManager:PQ(),isEphemeral:NQ(),installationType:`native`,downloadUrl:l.url}}async function SPe(e,t){let n=t??OQ(e),r=PQ(),i=NQ(),a=(await bPe(gn.publishName))[n];return!a&&n!==`latest`||!a||a===e?null:{currentVersion:e,latestVersion:a,tag:n,packageManager:r,isEphemeral:i,installationType:`package-manager`}}async function IQ(e,t,n,r){let i=vPe();if(i.installationType===`native`)try{return await xPe(e,t,yPe(),n)}catch{return null}return i.installationType===`development`&&!r?.includeDev?null:await SPe(e,t)}function LQ(e){if(e.installationType===`native`)return`${hn.binName} upgrade`;let t=`${gn.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function RQ(e){try{return{ok:!0,output:le(LQ(e),{stdio:`pipe`,encoding:`utf-8`}).trim()}}catch(e){return{ok:!1,output:e instanceof Error&&`stderr`in e?String(e.stderr).trim():e instanceof Error?e.message:`Unknown error`}}}function CPe(){let e=N.join(t.homedir(),hn.configDirName,`bin`);try{let n=N.dirname(kQ(process.execPath));return!n||n.toLowerCase().startsWith(t.tmpdir().toLowerCase())?e:n}catch{return e}}async function zQ(e){if(!e.downloadUrl)return{ok:!1,output:`No download URL`};let n=N.join(t.tmpdir(),`abacusai-update-${Date.now()}`),r=process.platform===`win32`,i=r?`${hn.binName}.exe`:hn.binName,a=CPe();try{await we.mkdir(n,{recursive:!0}),await we.mkdir(a,{recursive:!0});let t=N.join(n,r?`update.zip`:`update.tar.gz`),o=await fetch(e.downloadUrl);if(!o.ok)throw Error(`Download failed: ${o.status}`);let s=Buffer.from(await o.arrayBuffer());await we.writeFile(t,s),le(r?`powershell -Command "Expand-Archive -Path '${t}' -DestinationPath '${n}' -Force"`:`tar -xzf "${t}" -C "${n}"`,{stdio:`pipe`});let c=N.join(n,i),l=N.join(a,i);if(r){let e=`${l}.old`;await we.rm(e,{force:!0}).catch(()=>{}),await we.rename(l,e).catch(()=>{}),await we.copyFile(c,l),await we.rm(e,{force:!0}).catch(()=>{})}else await we.copyFile(c,l),await we.chmod(l,493);return{ok:!0,output:`Updated to ${e.latestVersion}`}}catch(e){return{ok:!1,output:e instanceof Error?e.message:`Unknown error`}}finally{await we.rm(n,{recursive:!0,force:!0}).catch(()=>{})}}function wPe(e,t){let n=e=>{let n=e.toLowerCase();if(n===t)return 1e3;if(n.startsWith(t))return 900;let r=0,i=-1;for(let e of t){let t=n.indexOf(e,i+1);if(t===-1)return 0;r+=100-(t-i),i=t}return r+=Math.max(0,50-n.length),r},r=null,i=0;for(let t of e){let e=Math.max(n(t.name??``),n(t.llmName));e>i&&(i=e,r=t.llmName)}return i>=100?r:null}async function BQ(e,t,n=nt.CLI){let r=(await e.listLLMModels({coworkV2:n===nt.COWORK}))?.result??[];return r.length||(process.stderr.write(`Error: No models available.
|
|
75182
75182
|
`),process.exit(1)),t?wPe(r,t.toLowerCase())||(process.stderr.write(`Warning: Model "${t}" not found. Using default: ${r[0].llmName}\n`),r[0].llmName):r[0].llmName}const VQ=dt([`codellm`,`cli`,`exit`]),HQ=new Set,UQ=new Set,WQ=new Set;let GQ=!1,KQ=!1,qQ=null,JQ;async function TPe(e){let t=e.map(e=>new Promise(t=>{let n=`writableLength`in e?e.writableLength:0;if((`bufferSize`in e?e.bufferSize:n)===0){t();return}let r=e.write.bind(e),i=!1,a=()=>{let n=`writableLength`in e?e.writableLength:0;(`bufferSize`in e?e.bufferSize:n)===0&&!i&&(i=!0,e.write=r,t())};e.once(`drain`,a),e.write(``,`utf-8`,()=>{a()}),e.write=function(){return!1}}));await Promise.all(t)}async function YQ(e,t,n,r){if(GQ)return;r?.debug?.(`Executing exit handlers`,{shouldManuallyExit:e,isSynchronous:t,signal:n,asyncCallbacks:HQ.size,syncCallbacks:UQ.size}),GQ=!0,HQ.size>0&&t&&VQ.error`SYNCHRONOUS TERMINATION NOTICE: When explicitly exiting the process via process.exit or via a parent process, asynchronous tasks in your exitHooks will not run. Either remove these tasks, use gracefulExit() instead of process.exit(), or ensure your parent process sends a SIGINT to the process running this code.`;let i=0;n>0?i=128+n:JQ===void 0?(typeof H.exitCode==`number`||typeof H.exitCode==`string`)&&(i=Number(H.exitCode)):i=JQ;let a=(t=!1)=>{(t||e)&&(qQ?qQ.call(H,i):H.exit(i))};for(let e of UQ)try{e(i)}catch(e){VQ.error`Error in synchronous exit hook: ${e}`}if(t){a();return}let o=[],s=0;for(let[e,t]of HQ)s=Math.max(s,t),o.push(Promise.resolve(e(i)).catch(e=>{VQ.error`Error in asynchronous exit hook: ${e}`}));let c=Array.from(WQ);c.length>0&&o.push(TPe(c));let l=setTimeout(()=>{a(!0)},s);try{await Promise.all(o),clearTimeout(l),a()}catch(e){clearTimeout(l),VQ.error`Error during exit cleanup: ${e}`,a(!0)}}function EPe(){KQ||(KQ=!0,H.once(`beforeExit`,()=>{YQ(!0,!1,-128)}),H.once(`SIGINT`,()=>{YQ(!0,!1,2)}),H.once(`SIGTERM`,()=>{YQ(!0,!1,15)}),H.once(`exit`,()=>{YQ(!1,!0,0)}),H.on(`message`,e=>{e===`shutdown`&&YQ(!0,!0,-128)}),qQ||(qQ=H.exit.bind(H),H.exit=function(e){if(JQ===void 0&&(JQ=e??0),HQ.size===0&&WQ.size===0){if(qQ){qQ(e??0);return}H.exit(e??0)}YQ(!0,!1,-128).catch(e=>{VQ.error`Error during exit: ${e}`,qQ?qQ(1):H.exit(1)})}))}function XQ(e,t){if(typeof e!=`function`)throw TypeError(`callback must be a function`);if(GQ)throw Error(`Cannot install exit hook while exit handlers are running`);t?.logger?.debug?.(`Registering exit hook`,{wait:t?.wait,hasStreams:t?.streams!==void 0}),EPe();let n=t?.wait??0,r=t?.streams??[H.stdout,H.stderr];if(n>0){let t=[e,n];HQ.add(t);for(let e of r)WQ.add(e);return()=>{HQ.delete(t);for(let e of r)WQ.delete(e)}}return UQ.add(e),()=>{UQ.delete(e)}}function ZQ(e){e!==void 0&&(H.exitCode=e),YQ(!0,!1,-128)}function QQ(e){process.stdout.write(JSON.stringify(e)+`
|
|
75183
75183
|
`)}function DPe(e){try{return JSON.parse(e)}catch{return null}}async function OPe({agentArgs:e}){gu(`ndjson IPC host started`,`cli`);let t=await jY.create(),n=new ku(t,Sn(),gn.userAgentNames.desktop,EQ.default.version);if(!t.isAuthenticated())try{(await n.getUserInfo())?.result?.email||(process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
|
|
75184
75184
|
`),process.exit(1))}catch{process.stderr.write(`Error: Not authenticated. Set ABACUS_DEVICE_CODE environment variable.
|