goatchain-cli 0.0.3-beta.10 → 0.0.3-beta.11

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.js CHANGED
@@ -32,7 +32,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
32
32
  `;break;case`id`:s=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.test(t)?r(parseInt(t,10)):n(new Of(`Invalid \`retry\` value: "${t}"`,{type:`invalid-retry`,value:t,line:i}));break;default:n(new Of(`Unknown field "${e.length>20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}));break}}function p(){c.length>0&&t({id:s,event:l||void 0,data:c.endsWith(`
33
33
  `)?c.slice(0,-1):c}),s=void 0,c=``,l=``}function m(e={}){a&&e.consume&&d(a),o=!0,s=void 0,c=``,l=``,a=``}return{feed:u,reset:m}}function jf(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
34
34
  `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
35
- `&&r++}}return[t,n]}var Mf=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Af({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const Nf={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Pf=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Ff=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=md(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Nf}async _authThenStart(){if(!this._authProvider)throw new Zd(`No auth provider`);let e;try{e=await cf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Zd;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=pd(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new Pf(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Mf({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=is.parse(JSON.parse(e.data));ts(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Zd(`No auth provider`);if(await cf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Zd(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Zo(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Pf(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=ff(o);if(this._resourceMetadataUrl=t,this._scope=n,await cf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Zd;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=ff(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Pf(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await cf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Zd;return this.send(e)}}throw new Pf(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),bs(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>is.parse(e)):[is.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Pf(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Pf(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},If=class{registry;accessRef;servers=new Map;constructor(e){this.registry=e.registry,this.accessRef=e.accessRef}allowNetwork(){return a(r(this.accessRef?.get()?.approvalMode)).allowNetwork}normalizeToolName(e,t){let n=e=>e.trim().replace(/[^\w-]+/g,`_`).replace(/^_+|_+$/g,``),r=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=t*16777619>>>0;return t>>>0},i=`mcp__${n(e)}__${n(t)}`||`mcp__tool`;if(i.length<=64)return i;let a=r(`${e}\u0000${t}`).toString(36).slice(0,8);return`${i.slice(0,Math.max(1,64-(1+a.length)))}_${a}`.slice(0,64)}unregisterServerTools(e){for(let t of e.registeredToolNames)try{this.registry.unregister(t)}catch{}e.registeredToolNames=[],e.remoteTools=[]}async connectServer(e){let t=String(e?.name??``).trim();if(!t)throw Error(`MCP server missing name`);if(e.enabled===!1)return{toolCount:0};let n=this.servers.get(t);if(n){this.unregisterServerTools(n);let e=await n.client.listTools();return this.registerTools({serverName:t,state:n,tools:e}),{toolCount:n.registeredToolNames.length}}let r=await this.createTransport(e),i=new Ku({name:`GoatChain CLI`,version:`0.0.0`});await i.connect(r);let a=await i.listTools(),o={config:e,client:i,transport:r,registeredToolNames:[],remoteTools:[]};return this.servers.set(t,o),this.registerTools({serverName:t,state:o,tools:a}),{toolCount:o.registeredToolNames.length}}async disconnectServer(e){let t=String(e??``).trim(),n=this.servers.get(t);if(n){this.unregisterServerTools(n);try{await n.transport.close()}catch{}this.servers.delete(t)}}async disconnectAll(){let e=[...this.servers.keys()];for(let t of e)await this.disconnectServer(t)}listConnected(){let e=[];for(let[t,n]of this.servers.entries())e.push({name:t,toolCount:n.registeredToolNames.length,transport:this.serverTransportName(n.config)});return e}listRegisteredTools(){let e=[];for(let t of this.servers.values())e.push(...t.registeredToolNames);return e}listRemoteTools(e){let t=String(e??``).trim(),n=this.servers.get(t);return n?[...n.remoteTools]:[]}async connectFromConfig(e){let t=Array.isArray(e?.servers)?e.servers:[],n=0,r=0;for(let e of t){let t=String(e?.name??``).trim();try{let i=await this.connectServer(e);t&&this.servers.has(t)&&n++,r+=i.toolCount}catch{}}return{connected:n,toolCount:r}}async createTransport(e){if((e.transport??`stdio`)===`http`){if(!this.allowNetwork())throw Error(`MCP HTTP transport requires Approval Mode: Agent (full access)`);let t=String(e.url??``).trim();if(!t)throw Error(`MCP http server missing url`);let n=e.headers??{},r=Object.keys(n).length>0?{headers:n}:void 0;return new Ff(new URL(t),{requestInit:r})}let t=String(e.command??``).trim();if(!t)throw Error(`MCP stdio server missing command`);return new dd({command:t,args:Array.isArray(e.args)?e.args.map(String):void 0,env:e.env??void 0,cwd:typeof e.cwd==`string`?String(e.cwd):void 0})}serverTransportName(e){return e.transport===`http`?`http`:`stdio`}registerTools(e){let t=Array.isArray(e.tools?.tools)?e.tools.tools:[];e.state.remoteTools=t;for(let n of t){let t=String(n.name??``).trim();if(!t)continue;let r=this.normalizeToolName(e.serverName,t);if(typeof this.registry?.has==`function`&&this.registry.has(r))try{this.registry.unregister(r)}catch{}let i=`[mcp:${e.serverName}/${t}]\n${String(n.description??``).trim()}`,a=n.inputSchema??{type:`object`},o=String(n?.annotations?.riskLevel??`high`).trim().toLowerCase(),s=o===`safe`||o===`low`||o===`medium`||o===`high`||o===`critical`?o:`high`;this.registry.register({name:r,description:i,parameters:a,riskLevel:s,execute:async n=>{let r=await e.state.client.callTool({name:t,arguments:n??{}});return r.content?r:{content:[],isError:r.isError,_meta:r._meta}}}),e.state.registeredToolNames.push(r)}}};function Lf(){return x()}function Rf(e){let t=h.resolve(e).split(h.sep).filter(e=>e.length>0);return t.length>0&&t[0].endsWith(`:`)&&(t[0]=t[0].slice(0,-1)),t.join(`-`)}function zf(e){let t=Lf(),n=Rf(e),r=h.join(t,`.goatchain`),i=h.join(r,`session`,n);return{workspaceCwd:e,workspaceName:n,cacheDir:i,sessionsDir:h.join(i,`sessions`),configPath:h.join(r,`config.json`)}}async function Bf(e){await l(e,{recursive:!0})}async function Vf(e){try{let t=await u(e,`utf8`);return JSON.parse(t)}catch(e){if(e&&typeof e==`object`&&e.code===`ENOENT`)return;throw e}}async function Hf(e,t){await Bf(h.dirname(e));let n=`${e}.tmp.${c()}`;await m(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),await f(n,e)}async function Uf(e){let t=await Vf(e.configPath);return!t||typeof t!=`object`?{schemaVersion:1}:t}async function Wf(e,t){let n={schemaVersion:1,...t,updatedAt:Date.now()};return await Hf(e.configPath,n),n}function Gf(e,t){return h.join(e.sessionsDir,`${t}.json`)}async function Kf(e,t){let n=await Vf(Gf(e,t));if(!n||typeof n!=`object`)return;let r=Array.isArray(n.messages)?n.messages:[];return{sessionId:typeof n.sessionId==`string`?n.sessionId:t,createdAt:typeof n.createdAt==`number`?n.createdAt:Date.now(),updatedAt:typeof n.updatedAt==`number`?n.updatedAt:Date.now(),modelId:typeof n.modelId==`string`?n.modelId:void 0,systemPrompt:typeof n.systemPrompt==`string`?n.systemPrompt:void 0,title:typeof n.title==`string`?n.title:void 0,summary:typeof n.summary==`string`?n.summary:void 0,pinned:!!n.pinned,messages:r}}const qf=[`ToolRegistry`,`WriteTool`,`ReadTool`,`EditTool`,`GlobTool`,`GrepTool`,`AstGrepSearchTool`,`TodoWriteTool`,`WebSearchTool`];function Jf(e){return qf.every(t=>typeof e?.[t]==`function`)}async function Yf(){try{let e=h.dirname(y(import.meta.url)),t=[h.resolve(e,`../../../src/index.ts`)];for(let e of t)if(v(e))try{return await import(b(e).href)}catch{}}catch{}}async function Xf(){try{return await import(`./src-B_9q8eah.js`)}catch(e){let t=e instanceof Error?e.message:String(e);try{let e=h.dirname(y(import.meta.url)),t=[h.resolve(e,`../../dist/index`),h.resolve(e,`../../../dist/index`)];for(let e of t)try{return await import(b(e).href)}catch{}}catch{}throw Error(["Failed to load `goatchain`.","If you are running from the repo, run `pnpm -r -s build` first.","If this is a workspace setup, ensure `packages/cli` depends on `goatchain` and run `pnpm install`.",`cause: ${t}`].join(`
35
+ `&&r++}}return[t,n]}var Mf=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n}={}){let r;super({start(i){r=Af({onEvent:e=>{i.enqueue(e)},onError(t){e===`terminate`?i.error(t):typeof e==`function`&&e(t)},onRetry:t,onComment:n})},transform(e){r.feed(e)}})}};const Nf={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};var Pf=class extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}},Ff=class{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=md(t?.fetch,t?.requestInit),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??Nf}async _authThenStart(){if(!this._authProvider)throw new Zd(`No auth provider`);let e;try{e=await cf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(e){throw this.onerror?.(e),e}if(e!==`AUTHORIZED`)throw new Zd;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let e={};if(this._authProvider){let t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e[`mcp-session-id`]=this._sessionId),this._protocolVersion&&(e[`mcp-protocol-version`]=this._protocolVersion);let t=pd(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){let{resumptionToken:t}=e;try{let n=await this._commonHeaders();n.set(`Accept`,`text/event-stream`),t&&n.set(`last-event-id`,t);let r=await(this._fetch??fetch)(this._url,{method:`GET`,headers:n,signal:this._abortController?.signal});if(!r.ok){if(await r.body?.cancel(),r.status===401&&this._authProvider)return await this._authThenStart();if(r.status===405)return;throw new Pf(r.status,`Failed to open SSE stream: ${r.statusText}`)}this._handleSseStream(r.body,e,!0)}catch(e){throw this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`));return}let r=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(n=>{this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`)),this._scheduleReconnection(e,t+1)})},r)}_handleSseStream(e,t,n){if(!e)return;let{onresumptiontoken:r,replayMessageId:i}=t,a,o=!1,s=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Mf({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(a=e.id,o=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=is.parse(JSON.parse(e.data));ts(t)&&(s=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||o)&&!s&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:a,onresumptiontoken:r,replayMessageId:i},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`))}}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Zd(`No auth provider`);if(await cf(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Zd(`Failed to authorize`)}async close(){this._reconnectionTimeout&&=(clearTimeout(this._reconnectionTimeout),void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{let{resumptionToken:n,onresumptiontoken:r}=t||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:Zo(e)?e.id:void 0}).catch(e=>this.onerror?.(e));return}let i=await this._commonHeaders();i.set(`content-type`,`application/json`),i.set(`accept`,`application/json, text/event-stream`);let a={...this._requestInit,method:`POST`,headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},o=await(this._fetch??fetch)(this._url,a),s=o.headers.get(`mcp-session-id`);if(s&&(this._sessionId=s),!o.ok){let t=await o.text().catch(()=>null);if(o.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new Pf(401,`Server returned 401 after successful authentication`);let{resourceMetadataUrl:t,scope:n}=ff(o);if(this._resourceMetadataUrl=t,this._scope=n,await cf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!==`AUTHORIZED`)throw new Zd;return this._hasCompletedAuthFlow=!0,this.send(e)}if(o.status===403&&this._authProvider){let{resourceMetadataUrl:t,scope:n,error:r}=ff(o);if(r===`insufficient_scope`){let r=o.headers.get(`WWW-Authenticate`);if(this._lastUpscopingHeader===r)throw new Pf(403,`Server returned 403 after trying upscoping`);if(n&&(this._scope=n),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=r??void 0,await cf(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!==`AUTHORIZED`)throw new Zd;return this.send(e)}}throw new Pf(o.status,`Error POSTing to endpoint: ${t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,o.status===202){await o.body?.cancel(),bs(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let c=(Array.isArray(e)?e:[e]).filter(e=>`method`in e&&`id`in e&&e.id!==void 0).length>0,l=o.headers.get(`content-type`);if(c)if(l?.includes(`text/event-stream`))this._handleSseStream(o.body,{onresumptiontoken:r},!1);else if(l?.includes(`application/json`)){let e=await o.json(),t=Array.isArray(e)?e.map(e=>is.parse(e)):[is.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await o.body?.cancel(),new Pf(-1,`Unexpected content type: ${l}`);else await o.body?.cancel()}catch(e){throw this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await(this._fetch??fetch)(this._url,t);if(await n.body?.cancel(),!n.ok&&n.status!==405)throw new Pf(n.status,`Failed to terminate session: ${n.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},If=class{registry;accessRef;servers=new Map;constructor(e){this.registry=e.registry,this.accessRef=e.accessRef}allowNetwork(){return a(r(this.accessRef?.get()?.approvalMode)).allowNetwork}normalizeToolName(e,t){let n=e=>e.trim().replace(/[^\w-]+/g,`_`).replace(/^_+|_+$/g,``),r=e=>{let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=t*16777619>>>0;return t>>>0},i=`mcp__${n(e)}__${n(t)}`||`mcp__tool`;if(i.length<=64)return i;let a=r(`${e}\u0000${t}`).toString(36).slice(0,8);return`${i.slice(0,Math.max(1,64-(1+a.length)))}_${a}`.slice(0,64)}unregisterServerTools(e){for(let t of e.registeredToolNames)try{this.registry.unregister(t)}catch{}e.registeredToolNames=[],e.remoteTools=[]}async connectServer(e){let t=String(e?.name??``).trim();if(!t)throw Error(`MCP server missing name`);if(e.enabled===!1)return{toolCount:0};let n=this.servers.get(t);if(n){this.unregisterServerTools(n);let e=await n.client.listTools();return this.registerTools({serverName:t,state:n,tools:e}),{toolCount:n.registeredToolNames.length}}let r=await this.createTransport(e),i=new Ku({name:`GoatChain CLI`,version:`0.0.0`});await i.connect(r);let a=await i.listTools(),o={config:e,client:i,transport:r,registeredToolNames:[],remoteTools:[]};return this.servers.set(t,o),this.registerTools({serverName:t,state:o,tools:a}),{toolCount:o.registeredToolNames.length}}async disconnectServer(e){let t=String(e??``).trim(),n=this.servers.get(t);if(n){this.unregisterServerTools(n);try{await n.transport.close()}catch{}this.servers.delete(t)}}async disconnectAll(){let e=[...this.servers.keys()];for(let t of e)await this.disconnectServer(t)}listConnected(){let e=[];for(let[t,n]of this.servers.entries())e.push({name:t,toolCount:n.registeredToolNames.length,transport:this.serverTransportName(n.config)});return e}listRegisteredTools(){let e=[];for(let t of this.servers.values())e.push(...t.registeredToolNames);return e}listRemoteTools(e){let t=String(e??``).trim(),n=this.servers.get(t);return n?[...n.remoteTools]:[]}async connectFromConfig(e){let t=Array.isArray(e?.servers)?e.servers:[],n=0,r=0;for(let e of t){let t=String(e?.name??``).trim();try{let i=await this.connectServer(e);t&&this.servers.has(t)&&n++,r+=i.toolCount}catch{}}return{connected:n,toolCount:r}}async createTransport(e){if((e.transport??`stdio`)===`http`){if(!this.allowNetwork())throw Error(`MCP HTTP transport requires Approval Mode: Agent (full access)`);let t=String(e.url??``).trim();if(!t)throw Error(`MCP http server missing url`);let n=e.headers??{},r=Object.keys(n).length>0?{headers:n}:void 0;return new Ff(new URL(t),{requestInit:r})}let t=String(e.command??``).trim();if(!t)throw Error(`MCP stdio server missing command`);return new dd({command:t,args:Array.isArray(e.args)?e.args.map(String):void 0,env:e.env??void 0,cwd:typeof e.cwd==`string`?String(e.cwd):void 0})}serverTransportName(e){return e.transport===`http`?`http`:`stdio`}registerTools(e){let t=Array.isArray(e.tools?.tools)?e.tools.tools:[];e.state.remoteTools=t;for(let n of t){let t=String(n.name??``).trim();if(!t)continue;let r=this.normalizeToolName(e.serverName,t);if(typeof this.registry?.has==`function`&&this.registry.has(r))try{this.registry.unregister(r)}catch{}let i=`[mcp:${e.serverName}/${t}]\n${String(n.description??``).trim()}`,a=n.inputSchema??{type:`object`},o=String(n?.annotations?.riskLevel??`high`).trim().toLowerCase(),s=o===`safe`||o===`low`||o===`medium`||o===`high`||o===`critical`?o:`high`;this.registry.register({name:r,description:i,parameters:a,riskLevel:s,execute:async n=>{let r=await e.state.client.callTool({name:t,arguments:n??{}});return r.content?r:{content:[],isError:r.isError,_meta:r._meta}}}),e.state.registeredToolNames.push(r)}}};function Lf(){return x()}function Rf(e){let t=h.resolve(e).split(h.sep).filter(e=>e.length>0);return t.length>0&&t[0].endsWith(`:`)&&(t[0]=t[0].slice(0,-1)),t.join(`-`)}function zf(e){let t=Lf(),n=Rf(e),r=h.join(t,`.goatchain`),i=h.join(r,`session`,n);return{workspaceCwd:e,workspaceName:n,cacheDir:i,sessionsDir:h.join(i,`sessions`),configPath:h.join(r,`config.json`)}}async function Bf(e){await l(e,{recursive:!0})}async function Vf(e){try{let t=await u(e,`utf8`);return JSON.parse(t)}catch(e){if(e&&typeof e==`object`&&e.code===`ENOENT`)return;throw e}}async function Hf(e,t){await Bf(h.dirname(e));let n=`${e}.tmp.${c()}`;await m(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),await f(n,e)}async function Uf(e){let t=await Vf(e.configPath);return!t||typeof t!=`object`?{schemaVersion:1}:t}async function Wf(e,t){let n={schemaVersion:1,...t,updatedAt:Date.now()};return await Hf(e.configPath,n),n}function Gf(e,t){return h.join(e.sessionsDir,`${t}.json`)}async function Kf(e,t){let n=await Vf(Gf(e,t));if(!n||typeof n!=`object`)return;let r=Array.isArray(n.messages)?n.messages:[];return{sessionId:typeof n.sessionId==`string`?n.sessionId:t,createdAt:typeof n.createdAt==`number`?n.createdAt:Date.now(),updatedAt:typeof n.updatedAt==`number`?n.updatedAt:Date.now(),modelId:typeof n.modelId==`string`?n.modelId:void 0,systemPrompt:typeof n.systemPrompt==`string`?n.systemPrompt:void 0,title:typeof n.title==`string`?n.title:void 0,summary:typeof n.summary==`string`?n.summary:void 0,pinned:!!n.pinned,messages:r}}const qf=[`ToolRegistry`,`WriteTool`,`ReadTool`,`EditTool`,`GlobTool`,`GrepTool`,`AstGrepSearchTool`,`TodoWriteTool`,`WebSearchTool`];function Jf(e){return qf.every(t=>typeof e?.[t]==`function`)}async function Yf(){try{let e=h.dirname(y(import.meta.url)),t=[h.resolve(e,`../../../src/index.ts`)];for(let e of t)if(v(e))try{return await import(b(e).href)}catch{}}catch{}}async function Xf(){try{return await import(`./src-CMdXdryc.js`)}catch(e){let t=e instanceof Error?e.message:String(e);try{let e=h.dirname(y(import.meta.url)),t=[h.resolve(e,`../../dist/index`),h.resolve(e,`../../../dist/index`)];for(let e of t)try{return await import(b(e).href)}catch{}}catch{}throw Error(["Failed to load `goatchain`.","If you are running from the repo, run `pnpm -r -s build` first.","If this is a workspace setup, ensure `packages/cli` depends on `goatchain` and run `pnpm install`.",`cause: ${t}`].join(`
36
36
  `))}}function Zf(e,t){return{get modelId(){return e.modelId},...typeof e?.setModelId==`function`?{setModelId(t){e.setModelId(t)}}:{},stream:n=>e.stream({...t,...n}),...typeof e?.run==`function`?{run:n=>e.run({...t,...n})}:{}}}function Qf(e,t,n,i){if(!Jf(e))throw Error(["Missing builtin tool exports from `goatchain`.","Reinstall the package, or rebuild it from the repo (`pnpm -r -s build`)."].join(`
37
37
  `));let{ToolRegistry:o,WriteTool:s,ReadTool:c,EditTool:l,GlobTool:u,GrepTool:d,AstGrepSearchTool:f,AstGrepReplaceTool:p,TodoWriteTool:m,WebSearchTool:g,AskUserTool:_}=e,v=e?.BashTool,y=h.join(t,`.goatchain`),b=()=>i?a(r(i.get()?.approvalMode)):{allowOutsideWorkspace:!0,allowNetwork:!0},x=(e,t)=>{let n=h.relative(h.resolve(e),h.resolve(t));return n===``?!0:n===`..`?!1:!n.startsWith(`..${h.sep}`)&&!h.isAbsolute(n)},ee=e=>{if(x(y,e))throw Error(`Access denied: ${e}\nRestricted: ${y}`)},S=e=>{let n=h.isAbsolute(e)?e:h.resolve(t,e),{allowOutsideWorkspace:r}=b();if(!r&&!x(t,n))throw Error(`Access denied: ${n}\nAllowed directory: ${t}`);return ee(n),n},C=e=>{let n=h.isAbsolute(e)?e:h.resolve(t,e),{allowOutsideWorkspace:r}=b();if(!r&&!x(t,n))throw Error(`Access denied: ${n}\nAllowed directory: ${t}`);return ee(n),n},w=new o,T=new s({cwd:t});w.register({name:T.name,description:T.description,parameters:T.parameters,riskLevel:T.riskLevel,execute:e=>(e&&typeof e==`object`&&`file_path`in e&&S(e.file_path),T.execute(e))});let E=new c({cwd:t});w.register({name:E.name,description:E.description,parameters:E.parameters,riskLevel:E.riskLevel,execute:e=>(e&&typeof e==`object`&&`file_path`in e&&S(e.file_path),E.execute(e))});let D=new l({cwd:t});w.register({name:D.name,description:D.description,parameters:D.parameters,riskLevel:D.riskLevel,execute:e=>(e&&typeof e==`object`&&`file_path`in e&&S(e.file_path),D.execute(e))});let O=new u({cwd:t});w.register({name:O.name,description:O.description,parameters:O.parameters,riskLevel:O.riskLevel,execute:e=>(e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&e.path.trim()&&C(e.path),O.execute(e))});let te=new d({cwd:t});w.register({name:te.name,description:te.description,parameters:te.parameters,riskLevel:te.riskLevel,execute:e=>(e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&e.path.trim()&&C(e.path),te.execute(e))});let ne=new f({cwd:t});w.register({name:ne.name,description:ne.description,parameters:ne.parameters,riskLevel:ne.riskLevel,execute:e=>{if(e&&typeof e==`object`&&Array.isArray(e.paths))for(let t of e.paths)typeof t==`string`&&t.trim()&&C(t);return ne.execute(e)}});let re=new p({cwd:t});w.register({name:re.name,description:re.description,parameters:re.parameters,riskLevel:re.riskLevel,execute:e=>{if(e&&typeof e==`object`&&Array.isArray(e.paths))for(let t of e.paths)typeof t==`string`&&t.trim()&&C(t);return re.execute(e)}});let k=new v({cwd:t});w.register({name:k.name,description:k.description,parameters:k.parameters,riskLevel:k.riskLevel,execute:e=>k.execute(e)});let ie=()=>{let e=n?.get(),t=process.env.GOATCHAIN_SERPER_API_KEY??process.env.SERPER_API_KEY,r=process.env.GOATCHAIN_SERPER_API_ENDPOINT??process.env.SERPER_API_ENDPOINT,i=process.env.GOATCHAIN_SERPER_NUM_RESULTS??process.env.SERPER_NUM_RESULTS,a=typeof i==`string`&&i.trim()?Number.parseInt(i.trim(),10):void 0;return{apiKey:e?.webSearch?.apiKey??t??``,apiEndpoint:e?.webSearch?.apiEndpoint??r,numResults:e?.webSearch?.numResults??(Number.isFinite(a)?a:void 0)}},A=new g;w.register({name:A.name,description:A.description,parameters:A.parameters,riskLevel:A.riskLevel,execute:async e=>{if(!b().allowNetwork)return{content:[{type:`text`,text:[`Access denied: WebSearch requires network access.`,`Switch to Approval Mode: Read Only (prompt) or Agent (full access) via /approvals.`,`Or set GOATCHAIN_APPROVAL_MODE=read_only|full_access.`].join(`
38
38
  `)}],isError:!0};let{apiKey:t,apiEndpoint:n,numResults:r}=ie();if(!t)return{content:[{type:`text`,text:[`Missing Serper API key for WebSearch.`,`Set it via one of:`,`- /web-search-key <key> (interactive)`,`- env: SERPER_API_KEY or GOATCHAIN_SERPER_API_KEY`,`- config: ./.goatchain/config.json -> tools.webSearch.apiKey`].join(`
@@ -144,4 +144,4 @@ When referencing specific functions or pieces of code include the pattern \`file
144
144
  user: Where are errors from the client handled?
145
145
  assistant: Clients are marked as failed in the \`connectToServer\` function in src/services/process.ts:712.
146
146
  </example>`,model:g,tools:h.registry,stateStore:_,...y.length>0?{middleware:y}:{}});return{agent:b,model:g,tools:h,stateStore:_,sessionManager:b.sessionManager}}const tp=S(ee);async function np(e){try{if(e===`0.0.0`)return{hasUpdate:!1,currentVersion:e};let{stdout:t}=await tp(`npm view goatchain-cli version`,{timeout:3e3,encoding:`utf8`}),n=t.trim();return{hasUpdate:rp(n,e)>0,currentVersion:e,latestVersion:n}}catch(t){return{hasUpdate:!1,currentVersion:e,error:t instanceof Error?t.message:String(t)}}}function rp(e,t){let n=ip(e),r=ip(t);for(let e=0;e<3;e++){if(n[e]>r[e])return 1;if(n[e]<r[e])return-1}return 0}function ip(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)/);return t?[Number.parseInt(t[1],10),Number.parseInt(t[2],10),Number.parseInt(t[3],10)]:[0,0,0]}function ap(e){if(!e.hasUpdate||!e.latestVersion)return;let t={yellow:`\x1B[33m`,green:`\x1B[32m`,reset:`\x1B[0m`,bold:`\x1B[1m`};console.log(),console.log(`${t.yellow}${t.bold}┌${`─`.repeat(60)}┐${t.reset}`),console.log(`${t.yellow}${t.bold}│${t.reset} 🎉 New version available! ${t.yellow}${t.bold}│${t.reset}`),console.log(`${t.yellow}${t.bold}│${t.reset} ${t.yellow}${t.bold}│${t.reset}`),console.log(`${t.yellow}${t.bold}│${t.reset} Current: ${t.yellow}${e.currentVersion}${t.reset} ${t.yellow}${t.bold}│${t.reset}`),console.log(`${t.yellow}${t.bold}│${t.reset} Latest: ${t.green}${e.latestVersion}${t.reset} ${t.yellow}${t.bold}│${t.reset}`),console.log(`${t.yellow}${t.bold}│${t.reset} ${t.yellow}${t.bold}│${t.reset}`),console.log(`${t.yellow}${t.bold}│${t.reset} Run: ${t.green}${t.bold}npm i -g goatchain-cli${t.reset} ${t.yellow}${t.bold}│${t.reset}`),console.log(`${t.yellow}${t.bold}└${`─`.repeat(60)}┘${t.reset}`),console.log()}function op(e){let t=e?.tools?.webSearch??e?.webSearch??{};return t&&typeof t==`object`?t:{}}function sp(e,t){let n={...op(e),...t};for(let e of Object.keys(n))n[e]===void 0&&delete n[e];return{...e??{},tools:{...e?.tools??{},webSearch:n}}}async function cp(){try{let{readFile:e}=await import(`node:fs/promises`),t=await import(`node:path`),{fileURLToPath:n}=await import(`node:url`),r=t.dirname(n(import.meta.url)),i=[t.join(r,`..`,`package.json`),t.join(r,`../../package.json`)];for(let t of i)try{let n=await e(t,`utf8`),r=JSON.parse(n);if(typeof r?.version==`string`&&r.name===`goatchain-cli`)return r.version}catch{continue}return`0.0.0`}catch{return`0.0.0`}}async function lp(e){let{agent:t}=e,n=[],i=await t.createSession({maxIterations:s});i.messages=n;let a=o({mode:r(e.approvalMode??`read_only`),envAutoApprove:process.env.GOATCHAIN_AUTO_APPROVE}),c=e.autoApproval??a.autoApprove;i.send(e.prompt,{toolContext:{approval:{strategy:a.strategy,autoApprove:c}}});for await(let e of i.receive())if(e.type===`text_delta`)process.stdout.write(e.delta);else if(e.type===`requires_action`){process.stderr.write(`\n[requires action] ${e.kind??``} (${e.toolName??`unknown tool`})\n`);break}else if(e.type===`done`)break;process.stdout.write(`
147
- `)}async function up(e){let t=await cp(),n=i(e,t),a=process.cwd(),o=zf(a),s=await Uf(o);n.apiKey&&(s={...s,openai:{...s?.openai??{},apiKey:n.apiKey}}),n.baseUrl&&(s={...s,openai:{...s?.openai??{},baseUrl:n.baseUrl}}),n.modelId&&(s={...s,defaults:{...s?.defaults??{},modelId:n.modelId}});let l=n.apiKey,u=n.modelId??process.env.GOATCHAIN_MODEL??s?.defaults?.modelId??`glm-4.7`,d=n.system,f=n.baseUrl??process.env.GOATCHAIN_OPENAI_BASE_URL??s?.openai?.baseUrl,m={},g=(e,t)=>{let n={...e?.defaults?.requestDefaults??{}};typeof t?.temperature==`number`&&(n.temperature=t.temperature),typeof t?.maxTokens==`number`&&(n.maxOutputTokens=t.maxTokens),typeof t?.topP==`number`&&(n.topP=t.topP),typeof t?.presencePenalty==`number`&&(n.presencePenalty=t.presencePenalty),typeof t?.frequencyPenalty==`number`&&(n.frequencyPenalty=t.frequencyPenalty),typeof t?.seed==`number`&&(n.seed=t.seed),typeof t?.timeoutMs==`number`&&(n.timeoutMs=t.timeoutMs),typeof n.temperature!=`number`&&(n.temperature=.3),typeof n.maxOutputTokens!=`number`&&(n.maxOutputTokens=8192),typeof n.maxContextTokens!=`number`&&(n.maxContextTokens=128e3);for(let e of Object.keys(m))delete m[e];Object.assign(m,n)};g(s,n);let _=()=>l??process.env.OPENAI_API_KEY??s?.openai?.apiKey,v=e=>{let t=e?.tools?.webSearch??e?.webSearch??{},n=typeof t.apiKey==`string`?t.apiKey:typeof t.serperApiKey==`string`?t.serperApiKey:void 0,r=typeof t.apiEndpoint==`string`?t.apiEndpoint:void 0,i=typeof t.numResults==`number`?t.numResults:void 0;return{webSearch:{...n?{apiKey:n}:{},...r?{apiEndpoint:r}:{},...typeof i==`number`?{numResults:i}:{}}}};(n.webSearchApiKey||n.webSearchApiEndpoint||typeof n.webSearchNumResults==`number`)&&(s=sp(s,{...n.webSearchApiKey?{apiKey:n.webSearchApiKey}:{},...n.webSearchApiEndpoint?{apiEndpoint:n.webSearchApiEndpoint}:{},...typeof n.webSearchNumResults==`number`?{numResults:n.webSearchNumResults}:{}}));let y={},b=e=>{let t=e?.openai?.compat,n={interleavedThinking:typeof t?.interleavedThinking==`boolean`?t.interleavedThinking:typeof t?.requireReasoningContentForToolCalls==`boolean`?t.requireReasoningContentForToolCalls:void 0};for(let e of Object.keys(y))delete y[e];Object.assign(y,n)};b(s);let x={},ee=e=>{let t=process.env.GOATCHAIN_EMOJI,n=t===`1`?!0:t===`0`?!1:process.stdout.isTTY&&process.env.TERM!==`dumb`,i={toolStyle:e?.ui?.toolStyle??process.env.GOATCHAIN_TOOL_STYLE??`inline`,showTools:typeof e?.ui?.showTools==`boolean`?e.ui.showTools:process.env.GOATCHAIN_SHOW_TOOLS!==`0`,showStatus:typeof e?.ui?.showStatus==`boolean`?e.ui.showStatus:process.env.GOATCHAIN_SHOW_STATUS!==`0`,showStatusLine:typeof e?.ui?.showStatusLine==`boolean`?e.ui.showStatusLine:process.env.GOATCHAIN_SHOW_STATUSLINE!==`0`,showFileChanges:typeof e?.ui?.showFileChanges==`boolean`?e.ui.showFileChanges:process.env.GOATCHAIN_SHOW_FILE_CHANGES!==`0`,promptContinue:typeof e?.ui?.promptContinue==`boolean`?e.ui.promptContinue:process.env.GOATCHAIN_PROMPT_CONTINUE!==`0`,autoContinue:typeof e?.ui?.autoContinue==`boolean`?e.ui.autoContinue:process.env.GOATCHAIN_AUTO_CONTINUE===`1`,planMode:typeof e?.ui?.planMode==`boolean`?e.ui.planMode:process.env.GOATCHAIN_PLAN_MODE===`1`,sessionsUi:e?.ui?.sessionsUi??process.env.GOATCHAIN_SESSIONS_UI??`auto`,approvalMode:r(process.env.GOATCHAIN_APPROVAL_MODE??e?.ui?.approvalMode??`read_only`),emoji:typeof e?.ui?.emoji==`boolean`?e.ui.emoji:n,theme:(()=>{let t=e?.ui?.theme;if(t!==void 0)return t;let n=process.env.GOATCHAIN_THEME;return typeof n==`string`&&n.trim()?n.trim():`dark`})(),attachImages:(()=>{let t=e?.ui?.attachImages??{},n=process.env.GOATCHAIN_ATTACH_IMAGES_MAX_DATA_URL_CHARS,r=typeof n==`string`&&n.trim()?Number(n):void 0,i=typeof t.maxDataUrlChars==`number`&&Number.isFinite(t.maxDataUrlChars)?t.maxDataUrlChars:typeof r==`number`&&Number.isFinite(r)?r:void 0;return{noteTemplate:typeof t.noteTemplate==`string`?t.noteTemplate:void 0,notePosition:typeof t.notePosition==`string`?t.notePosition:void 0,imagesPosition:typeof t.imagesPosition==`string`?t.imagesPosition:void 0,dataUrlMode:typeof t.dataUrlMode==`string`?t.dataUrlMode:void 0,maxDataUrlChars:i}})()};for(let e of Object.keys(x))delete x[e];Object.assign(x,i)};if(ee(s),n.saveConfigOnly){await Wf(o,{...s,openai:{...s?.openai??{},baseUrl:f,apiKey:_()},defaults:{...s?.defaults??{},modelId:u,requestDefaults:m},ui:x}),console.log(`Configuration saved to: ${o.configPath}`),console.log(`Model: ${u}`),console.log(`Base URL: ${f??`(default)`}`),console.log(`API Key: ${_()?`***${_().slice(-4)}`:`(not set)`}`);return}if(n.prompt){let{agent:e}=await ep({getApiKey:_,modelId:u,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:{get:()=>v(s)},accessRef:{get:()=>({approvalMode:x.approvalMode})}});await lp({agent:e,prompt:n.prompt,approvalMode:x.approvalMode,autoApproval:n.autoApproval});return}let S=n.sessionId??s?.lastSessionId??c(),C=[],w=[],T=Date.now(),E,D,O=!1,te={get:()=>v(s)},ne={get:()=>({approvalMode:x.approvalMode})},{agent:re,model:k,tools:ie,sessionManager:A}=await ep({getApiKey:_,modelId:u,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:te,accessRef:ne}),j=null,M=async()=>{if(r(x.approvalMode)===`read_only`)return;let e=s?.mcp??{};e.autoConnect!==!1&&(Array.isArray(e.servers)?e.servers:[]).length!==0&&(j||=new If({registry:ie.registry,accessRef:ne}),await j.connectFromConfig(e))};await M();let ae=await A.get(S);if(ae){T=ae.createdAt,C=ae.messages;let e=ae.metadata;if(e){E=typeof e.title==`string`?e.title:void 0,D=typeof e.summary==`string`?e.summary:void 0,O=!!e.pinned,w=Array.isArray(e.inputs)?e.inputs.map(e=>String(e??``)).filter(e=>e.trim().length>0):[];let t=typeof e.modelId==`string`?e.modelId:void 0;t&&typeof k?.setModelId==`function`&&k.setModelId(t)}}else{let e=await Kf(o,S);if(e){T=e.createdAt??T,E=e.title,D=e.summary,O=!!e.pinned,C=Array.isArray(e.messages)?e.messages:[],e.modelId&&typeof k?.setModelId==`function`&&k.setModelId(e.modelId);let t=await A.create(S);t.messages=C,t.metadata={title:E,summary:D,pinned:O,modelId:e.modelId},await t.save()}}let oe=async(e={})=>{s=await Wf(o,{...s,...e,openai:{...s?.openai??{},baseUrl:f,apiKey:_()},defaults:{...s?.defaults??{},modelId:k.modelId,requestDefaults:m},ui:x})},se=async()=>{let e=await A.get(S);if(e)e.messages=C,e.metadata={title:E,summary:D,pinned:O,modelId:k.modelId,inputs:w},await e.save();else{let e=await A.create(S);e.messages=C,e.metadata={title:E,summary:D,pinned:O,modelId:k.modelId,inputs:w},await e.save()}await oe({lastSessionId:S})},ce=Promise.resolve(),le=()=>{let e=()=>se();return ce=ce.then(e,e),ce};await le(),np(t).then(e=>{e.hasUpdate&&ap(e)}).catch(()=>{});let{runRepl:ue}=await import(`./repl-Bqi7c_eT.js`);await ue({version:t,provider:`openai`,system:d,agentRef:{get:()=>re},modelRef:{get:()=>k},toolsInfo:ie,requestDefaults:m,openaiCompat:y,baseUrlRef:{get:()=>f},setBaseUrl:async e=>{if(f=e,typeof k?.setBaseUrl==`function`){k.setBaseUrl(f),await le();return}({agent:re,model:k,tools:ie}=await ep({getApiKey:_,modelId:k.modelId,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:te,accessRef:ne})),j&&=(await j.disconnectAll(),null),await M(),await le()},setApiKey:e=>{l=e},setWebSearchConfig:e=>{s=sp(s,e)},saveAll:le,getConfigPath:()=>o.configPath,getLocalConfig:()=>s,getApiKeyStatus:()=>{let e=typeof l==`string`&&!!l.trim(),t=typeof process.env.OPENAI_API_KEY==`string`&&!!process.env.OPENAI_API_KEY.trim(),n=typeof s?.openai?.apiKey==`string`&&!!String(s.openai.apiKey).trim();return{present:e||t||n,source:e?`cli`:t?`env`:n?`config`:null}},listSessions:async()=>(await A.list()).map(e=>({sessionId:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,title:e.title,summary:e.summary,pinned:!!e.metadata?.pinned,inputs:Array.isArray(e.metadata?.inputs)?e.metadata.inputs:void 0,messages:e.messages})),loadSessionById:async e=>{let t=await A.get(e);if(!t)return;let n=t.metadata;return{sessionId:t.id,createdAt:t.createdAt,updatedAt:t.updatedAt,modelId:typeof n?.modelId==`string`?n.modelId:void 0,title:t.title,summary:t.summary,pinned:!!n?.pinned,inputs:Array.isArray(n?.inputs)?n.inputs:void 0,messages:t.messages}},saveSessionByData:async e=>{let t=await A.get(e.sessionId);if(t)t.messages=e.messages,t.metadata={title:e.title,summary:e.summary,pinned:e.pinned,modelId:e.modelId,inputs:e.inputs},await t.save();else{let t=await A.create(e.sessionId);t.messages=e.messages,t.metadata={title:e.title,summary:e.summary,pinned:e.pinned,modelId:e.modelId,inputs:e.inputs},await t.save()}},renameSessionById:async(e,t)=>{let n=await A.get(e);n&&(n.title=t,await n.save())},setPinnedSessionsById:async(e,t)=>{for(let n of e){let e=await A.get(n);if(e){let n=e.metadata||{};n.pinned=t,e.metadata=n,await e.save()}}},deleteSessionById:async e=>{await A.destroy(e)},deleteSessionsById:async e=>{for(let t of e)await A.destroy(t)},uiPrefs:x,mcpManagerRef:{get:()=>j},switchWorkspace:async e=>{let t=h.resolve(process.cwd(),String(e??``));if(!(await p(t)).isDirectory())throw Error(`Not a directory: ${t}`);process.chdir(t),a=process.cwd(),o=zf(a),s=await Uf(o),ee(s),g(s,null),b(s),f=process.env.GOATCHAIN_OPENAI_BASE_URL??s?.openai?.baseUrl??f,S=s?.lastSessionId??c(),C=[],T=Date.now(),E=void 0,D=void 0,O=!1;let n=s?.defaults?.modelId??k.modelId??`glm-4.7`;({agent:re,model:k,tools:ie,sessionManager:A}=await ep({getApiKey:_,modelId:n,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:te,accessRef:ne})),j&&=(await j.disconnectAll(),null),await M();let r=await A.get(S);if(r){T=r.createdAt,C=r.messages;let e=r.metadata;if(e){E=typeof e.title==`string`?e.title:void 0,D=typeof e.summary==`string`?e.summary:void 0,O=!!e.pinned;let t=typeof e.modelId==`string`?e.modelId:void 0;t&&typeof k?.setModelId==`function`&&k.setModelId(t)}}else{let e=await Kf(o,S);if(e){T=e.createdAt??T,E=e.title,D=e.summary,O=!!e.pinned,C=Array.isArray(e.messages)?e.messages:[],e.modelId&&typeof k?.setModelId==`function`&&k.setModelId(e.modelId);let t=await A.create(S);t.messages=C,t.metadata={title:E,summary:D,pinned:O,modelId:e.modelId},await t.save()}}await le()},getWorkspaceCwd:()=>process.cwd(),session:{get sessionId(){return S},set sessionId(e){S=e},get createdAt(){return T},set createdAt(e){T=e},get history(){return C},set history(e){C=e},get inputs(){return w},set inputs(e){w=Array.isArray(e)?e.map(e=>String(e??``)).filter(e=>e.trim().length>0):[]},get title(){return E},set title(e){E=e},get summary(){return D},set summary(e){D=e},get pinned(){return O},set pinned(e){O=!!e}}})}export{up as main};
147
+ `)}async function up(e){let t=await cp(),n=i(e,t),a=process.cwd(),o=zf(a),s=await Uf(o);n.apiKey&&(s={...s,openai:{...s?.openai??{},apiKey:n.apiKey}}),n.baseUrl&&(s={...s,openai:{...s?.openai??{},baseUrl:n.baseUrl}}),n.modelId&&(s={...s,defaults:{...s?.defaults??{},modelId:n.modelId}});let l=n.apiKey,u=n.modelId??process.env.GOATCHAIN_MODEL??s?.defaults?.modelId??`glm-4.7`,d=n.system,f=n.baseUrl??process.env.GOATCHAIN_OPENAI_BASE_URL??s?.openai?.baseUrl,m={},g=(e,t)=>{let n={...e?.defaults?.requestDefaults??{}};typeof t?.temperature==`number`&&(n.temperature=t.temperature),typeof t?.maxTokens==`number`&&(n.maxOutputTokens=t.maxTokens),typeof t?.topP==`number`&&(n.topP=t.topP),typeof t?.presencePenalty==`number`&&(n.presencePenalty=t.presencePenalty),typeof t?.frequencyPenalty==`number`&&(n.frequencyPenalty=t.frequencyPenalty),typeof t?.seed==`number`&&(n.seed=t.seed),typeof t?.timeoutMs==`number`&&(n.timeoutMs=t.timeoutMs),typeof n.temperature!=`number`&&(n.temperature=.3),typeof n.maxOutputTokens!=`number`&&(n.maxOutputTokens=8192),typeof n.maxContextTokens!=`number`&&(n.maxContextTokens=128e3);for(let e of Object.keys(m))delete m[e];Object.assign(m,n)};g(s,n);let _=()=>l??process.env.OPENAI_API_KEY??s?.openai?.apiKey,v=e=>{let t=e?.tools?.webSearch??e?.webSearch??{},n=typeof t.apiKey==`string`?t.apiKey:typeof t.serperApiKey==`string`?t.serperApiKey:void 0,r=typeof t.apiEndpoint==`string`?t.apiEndpoint:void 0,i=typeof t.numResults==`number`?t.numResults:void 0;return{webSearch:{...n?{apiKey:n}:{},...r?{apiEndpoint:r}:{},...typeof i==`number`?{numResults:i}:{}}}};(n.webSearchApiKey||n.webSearchApiEndpoint||typeof n.webSearchNumResults==`number`)&&(s=sp(s,{...n.webSearchApiKey?{apiKey:n.webSearchApiKey}:{},...n.webSearchApiEndpoint?{apiEndpoint:n.webSearchApiEndpoint}:{},...typeof n.webSearchNumResults==`number`?{numResults:n.webSearchNumResults}:{}}));let y={},b=e=>{let t=e?.openai?.compat,n={interleavedThinking:typeof t?.interleavedThinking==`boolean`?t.interleavedThinking:typeof t?.requireReasoningContentForToolCalls==`boolean`?t.requireReasoningContentForToolCalls:void 0};for(let e of Object.keys(y))delete y[e];Object.assign(y,n)};b(s);let x={},ee=e=>{let t=process.env.GOATCHAIN_EMOJI,n=t===`1`?!0:t===`0`?!1:process.stdout.isTTY&&process.env.TERM!==`dumb`,i={toolStyle:e?.ui?.toolStyle??process.env.GOATCHAIN_TOOL_STYLE??`inline`,showTools:typeof e?.ui?.showTools==`boolean`?e.ui.showTools:process.env.GOATCHAIN_SHOW_TOOLS!==`0`,showStatus:typeof e?.ui?.showStatus==`boolean`?e.ui.showStatus:process.env.GOATCHAIN_SHOW_STATUS!==`0`,showStatusLine:typeof e?.ui?.showStatusLine==`boolean`?e.ui.showStatusLine:process.env.GOATCHAIN_SHOW_STATUSLINE!==`0`,showFileChanges:typeof e?.ui?.showFileChanges==`boolean`?e.ui.showFileChanges:process.env.GOATCHAIN_SHOW_FILE_CHANGES!==`0`,promptContinue:typeof e?.ui?.promptContinue==`boolean`?e.ui.promptContinue:process.env.GOATCHAIN_PROMPT_CONTINUE!==`0`,autoContinue:typeof e?.ui?.autoContinue==`boolean`?e.ui.autoContinue:process.env.GOATCHAIN_AUTO_CONTINUE===`1`,planMode:typeof e?.ui?.planMode==`boolean`?e.ui.planMode:process.env.GOATCHAIN_PLAN_MODE===`1`,sessionsUi:e?.ui?.sessionsUi??process.env.GOATCHAIN_SESSIONS_UI??`auto`,approvalMode:r(process.env.GOATCHAIN_APPROVAL_MODE??e?.ui?.approvalMode??`read_only`),emoji:typeof e?.ui?.emoji==`boolean`?e.ui.emoji:n,theme:(()=>{let t=e?.ui?.theme;if(t!==void 0)return t;let n=process.env.GOATCHAIN_THEME;return typeof n==`string`&&n.trim()?n.trim():`dark`})(),attachImages:(()=>{let t=e?.ui?.attachImages??{},n=process.env.GOATCHAIN_ATTACH_IMAGES_MAX_DATA_URL_CHARS,r=typeof n==`string`&&n.trim()?Number(n):void 0,i=typeof t.maxDataUrlChars==`number`&&Number.isFinite(t.maxDataUrlChars)?t.maxDataUrlChars:typeof r==`number`&&Number.isFinite(r)?r:void 0;return{noteTemplate:typeof t.noteTemplate==`string`?t.noteTemplate:void 0,notePosition:typeof t.notePosition==`string`?t.notePosition:void 0,imagesPosition:typeof t.imagesPosition==`string`?t.imagesPosition:void 0,dataUrlMode:typeof t.dataUrlMode==`string`?t.dataUrlMode:void 0,maxDataUrlChars:i}})()};for(let e of Object.keys(x))delete x[e];Object.assign(x,i)};if(ee(s),n.saveConfigOnly){await Wf(o,{...s,openai:{...s?.openai??{},baseUrl:f,apiKey:_()},defaults:{...s?.defaults??{},modelId:u,requestDefaults:m},ui:x}),console.log(`Configuration saved to: ${o.configPath}`),console.log(`Model: ${u}`),console.log(`Base URL: ${f??`(default)`}`),console.log(`API Key: ${_()?`***${_().slice(-4)}`:`(not set)`}`);return}if(n.prompt){let{agent:e}=await ep({getApiKey:_,modelId:u,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:{get:()=>v(s)},accessRef:{get:()=>({approvalMode:x.approvalMode})}});await lp({agent:e,prompt:n.prompt,approvalMode:x.approvalMode,autoApproval:n.autoApproval});return}let S=n.sessionId??s?.lastSessionId??c(),C=[],w=[],T=Date.now(),E,D,O=!1,te={get:()=>v(s)},ne={get:()=>({approvalMode:x.approvalMode})},{agent:re,model:k,tools:ie,sessionManager:A}=await ep({getApiKey:_,modelId:u,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:te,accessRef:ne}),j=null,M=async()=>{if(r(x.approvalMode)===`read_only`)return;let e=s?.mcp??{};e.autoConnect!==!1&&(Array.isArray(e.servers)?e.servers:[]).length!==0&&(j||=new If({registry:ie.registry,accessRef:ne}),await j.connectFromConfig(e))};await M();let ae=await A.get(S);if(ae){T=ae.createdAt,C=ae.messages;let e=ae.metadata;if(e){E=typeof e.title==`string`?e.title:void 0,D=typeof e.summary==`string`?e.summary:void 0,O=!!e.pinned,w=Array.isArray(e.inputs)?e.inputs.map(e=>String(e??``)).filter(e=>e.trim().length>0):[];let t=typeof e.modelId==`string`?e.modelId:void 0;t&&typeof k?.setModelId==`function`&&k.setModelId(t)}}else{let e=await Kf(o,S);if(e){T=e.createdAt??T,E=e.title,D=e.summary,O=!!e.pinned,C=Array.isArray(e.messages)?e.messages:[],e.modelId&&typeof k?.setModelId==`function`&&k.setModelId(e.modelId);let t=await A.create(S);t.messages=C,t.metadata={title:E,summary:D,pinned:O,modelId:e.modelId},await t.save()}}let oe=async(e={})=>{s=await Wf(o,{...s,...e,openai:{...s?.openai??{},baseUrl:f,apiKey:_()},defaults:{...s?.defaults??{},modelId:k.modelId,requestDefaults:m},ui:x})},se=async()=>{let e=await A.get(S);if(e)e.messages=C,e.metadata={title:E,summary:D,pinned:O,modelId:k.modelId,inputs:w},await e.save();else{let e=await A.create(S);e.messages=C,e.metadata={title:E,summary:D,pinned:O,modelId:k.modelId,inputs:w},await e.save()}await oe({lastSessionId:S})},ce=Promise.resolve(),le=()=>{let e=()=>se();return ce=ce.then(e,e),ce};await le(),np(t).then(e=>{e.hasUpdate&&ap(e)}).catch(()=>{});let{runRepl:ue}=await import(`./repl-CmgXaFdL.js`);await ue({version:t,provider:`openai`,system:d,agentRef:{get:()=>re},modelRef:{get:()=>k},toolsInfo:ie,requestDefaults:m,openaiCompat:y,baseUrlRef:{get:()=>f},setBaseUrl:async e=>{if(f=e,typeof k?.setBaseUrl==`function`){k.setBaseUrl(f),await le();return}({agent:re,model:k,tools:ie}=await ep({getApiKey:_,modelId:k.modelId,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:te,accessRef:ne})),j&&=(await j.disconnectAll(),null),await M(),await le()},setApiKey:e=>{l=e},setWebSearchConfig:e=>{s=sp(s,e)},saveAll:le,getConfigPath:()=>o.configPath,getLocalConfig:()=>s,getApiKeyStatus:()=>{let e=typeof l==`string`&&!!l.trim(),t=typeof process.env.OPENAI_API_KEY==`string`&&!!process.env.OPENAI_API_KEY.trim(),n=typeof s?.openai?.apiKey==`string`&&!!String(s.openai.apiKey).trim();return{present:e||t||n,source:e?`cli`:t?`env`:n?`config`:null}},listSessions:async()=>(await A.list()).map(e=>({sessionId:e.id,createdAt:e.createdAt,updatedAt:e.updatedAt,title:e.title,summary:e.summary,pinned:!!e.metadata?.pinned,inputs:Array.isArray(e.metadata?.inputs)?e.metadata.inputs:void 0,messages:e.messages})),loadSessionById:async e=>{let t=await A.get(e);if(!t)return;let n=t.metadata;return{sessionId:t.id,createdAt:t.createdAt,updatedAt:t.updatedAt,modelId:typeof n?.modelId==`string`?n.modelId:void 0,title:t.title,summary:t.summary,pinned:!!n?.pinned,inputs:Array.isArray(n?.inputs)?n.inputs:void 0,messages:t.messages}},saveSessionByData:async e=>{let t=await A.get(e.sessionId);if(t)t.messages=e.messages,t.metadata={title:e.title,summary:e.summary,pinned:e.pinned,modelId:e.modelId,inputs:e.inputs},await t.save();else{let t=await A.create(e.sessionId);t.messages=e.messages,t.metadata={title:e.title,summary:e.summary,pinned:e.pinned,modelId:e.modelId,inputs:e.inputs},await t.save()}},renameSessionById:async(e,t)=>{let n=await A.get(e);n&&(n.title=t,await n.save())},setPinnedSessionsById:async(e,t)=>{for(let n of e){let e=await A.get(n);if(e){let n=e.metadata||{};n.pinned=t,e.metadata=n,await e.save()}}},deleteSessionById:async e=>{await A.destroy(e)},deleteSessionsById:async e=>{for(let t of e)await A.destroy(t)},uiPrefs:x,mcpManagerRef:{get:()=>j},switchWorkspace:async e=>{let t=h.resolve(process.cwd(),String(e??``));if(!(await p(t)).isDirectory())throw Error(`Not a directory: ${t}`);process.chdir(t),a=process.cwd(),o=zf(a),s=await Uf(o),ee(s),g(s,null),b(s),f=process.env.GOATCHAIN_OPENAI_BASE_URL??s?.openai?.baseUrl??f,S=s?.lastSessionId??c(),C=[],T=Date.now(),E=void 0,D=void 0,O=!1;let n=s?.defaults?.modelId??k.modelId??`glm-4.7`;({agent:re,model:k,tools:ie,sessionManager:A}=await ep({getApiKey:_,modelId:n,system:d,baseUrl:f,requestDefaults:m,openaiCompat:y,toolsConfigRef:te,accessRef:ne})),j&&=(await j.disconnectAll(),null),await M();let r=await A.get(S);if(r){T=r.createdAt,C=r.messages;let e=r.metadata;if(e){E=typeof e.title==`string`?e.title:void 0,D=typeof e.summary==`string`?e.summary:void 0,O=!!e.pinned;let t=typeof e.modelId==`string`?e.modelId:void 0;t&&typeof k?.setModelId==`function`&&k.setModelId(t)}}else{let e=await Kf(o,S);if(e){T=e.createdAt??T,E=e.title,D=e.summary,O=!!e.pinned,C=Array.isArray(e.messages)?e.messages:[],e.modelId&&typeof k?.setModelId==`function`&&k.setModelId(e.modelId);let t=await A.create(S);t.messages=C,t.metadata={title:E,summary:D,pinned:O,modelId:e.modelId},await t.save()}}await le()},getWorkspaceCwd:()=>process.cwd(),session:{get sessionId(){return S},set sessionId(e){S=e},get createdAt(){return T},set createdAt(e){T=e},get history(){return C},set history(e){C=e},get inputs(){return w},set inputs(e){w=Array.isArray(e)?e.map(e=>String(e??``)).filter(e=>e.trim().length>0):[]},get title(){return E},set title(e){E=e},get summary(){return D},set summary(e){D=e},get pinned(){return O},set pinned(e){O=!!e}}})}export{up as main};
package/dist/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "goatchain-cli",
3
3
  "type": "module",
4
- "version": "0.0.3-beta.10",
4
+ "version": "0.0.3-beta.11",
5
5
  "description": "GoatChain CLI",
6
6
  "author": "Simon He",
7
7
  "license": "MIT",
@@ -1,4 +1,4 @@
1
- import{a as e,c as t,n,r,s as i,t as a}from"./constants-C3H5Y2lA.js";import{a as o,c as s,i as c,n as l,o as u,r as d,s as f,t as p}from"./ui-h27qws5j.js";import"./openai-Ba5c3VJv.js";import{t as m}from"./theme-CDmxdKhU.js";import{J as h}from"./src-KHMs2spV.js";import{randomUUID as g}from"node:crypto";import{mkdtemp as _,open as v,readFile as y,readdir as b,rm as x,stat as S,writeFile as C}from"node:fs/promises";import w from"node:path";import{Writable as ee}from"node:stream";import te from"node:fs";import{pathToFileURL as ne}from"node:url";import re from"node:os";import{execFile as T}from"node:child_process";import{promisify as E}from"node:util";import ie from"node:readline";import{Buffer as D}from"node:buffer";const ae=[{modelId:`deepseek-v3.1`,hint:`DeepSeek (OpenAI-compatible).`},{modelId:`glm-4.7`,hint:`GLM (OpenAI-compatible).`}];function oe(e){let t=String(e??``).trim(),n=t.toLowerCase(),r=n.includes(`codex`);return{reasoning:/^o\d/i.test(t)||n.includes(`reasoner`)||n.includes(`reasoning`)||n.includes(`deepseek-r1`)||n.includes(`deepseek-reasoner`)||/^gpt-5/i.test(t),vision:n.includes(`vision`)||n.includes(`glm-4v`)||n.includes(`4v`)||n.includes(`4o`)||/^gpt-4\.1/i.test(t)||/^gpt-5/i.test(t),codex:r}}function O(e){return`[${e}]`}function k(e){let t=oe(e);return[t.codex?O(`codex`):``,t.reasoning?O(`reasoning`):``,t.vision?O(`vision`):``].filter(Boolean).join(` `)}function se(e){return String(e??``).toLowerCase()===`openai`?[...ae.map(e=>({modelId:e.modelId,label:e.label||e.modelId,hint:e.hint||``})),{modelId:``,label:`Custom…`,hint:`Enter a model id`}]:[{modelId:``,label:`Custom…`,hint:`Enter a model id`}]}function A(e){let t=String(e??``).trim().toLowerCase();return t===`minimal`||t===`low`||t===`medium`||t===`high`?t:null}function j(e){return e===`auto`?`Let the provider decide (recommended).`:e===`minimal`?`Lowest reasoning; fastest.`:e===`low`?`Less thinking; faster.`:e===`medium`?`Balanced.`:`More thinking; slower but stronger.`}function ce(e){let t=e.env??process.env,n=e.uiPrefsAttachImages??{},r=t.GOATCHAIN_ATTACH_IMAGES_NOTE_TEMPLATE,i=t.GOATCHAIN_ATTACH_IMAGES_NOTE_POSITION,a=t.GOATCHAIN_ATTACH_IMAGES_IMAGES_POSITION,o=t.GOATCHAIN_ATTACH_IMAGES_DATA_URL_MODE,s=t.GOATCHAIN_ATTACH_IMAGES_MAX_DATA_URL_CHARS,c=(e,t)=>{let n=String(e??``).trim().toLowerCase();return[`start`,`before_images`,`after_images`,`before_text`,`after_text`,`end`].includes(n)?n:t},l=(e,t)=>{let n=String(e??``).trim().toLowerCase();return n===`none`||n===`prefix`||n===`full`?n:t},u=(()=>{let e=Number(s??n.maxDataUrlChars);return Number.isFinite(e)?Math.max(0,Math.trunc(e)):void 0})();return{note:{template:typeof r==`string`&&r.trim()?r:typeof n.noteTemplate==`string`?n.noteTemplate:void 0,dataUrlMode:l(o??n.dataUrlMode,`prefix`),maxDataUrlChars:u},notePosition:c(i??n.notePosition,`start`),imagesPosition:c(a??n.imagesPosition,`before_text`)}}const le=E(T);async function M(e,t=1024*1024){if(process.platform!==`darwin`)return null;try{let{stdout:n}=await le(`osascript`,e.flatMap(e=>[`-e`,e]),{encoding:`utf8`,maxBuffer:t});return String(n??``)}catch{return null}}function N(e){let t=String(e??``).trim();if(!t)return[];let n=t.split(/\0|\r?\n/).map(e=>e.trim()).filter(Boolean),r=[];for(let e of n){if(e.startsWith(`file://`))try{let t=new URL(e);if(t.protocol!==`file:`)continue;let n=decodeURIComponent(t.pathname);n&&r.push(n);continue}catch{continue}e.startsWith(`/`)&&r.push(e)}return r}function ue(e){return!Buffer.isBuffer(e)||e.length<12?null:e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?{mime:`image/png`,ext:`.png`}:e[0]===255&&e[1]===216&&e[2]===255?{mime:`image/jpeg`,ext:`.jpg`}:e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56?{mime:`image/gif`,ext:`.gif`}:e.subarray(0,4).toString(`ascii`)===`RIFF`&&e.subarray(8,12).toString(`ascii`)===`WEBP`?{mime:`image/webp`,ext:`.webp`}:e[0]===73&&e[1]===73&&e[2]===42&&e[3]===0||e[0]===77&&e[1]===77&&e[2]===0&&e[3]===42?{mime:`image/tiff`,ext:`.tiff`}:e[0]===66&&e[1]===77?{mime:`image/bmp`,ext:`.bmp`}:null}async function de(){if(process.platform!==`darwin`)return null;try{let{stdout:e}=await le(`pbpaste`,[],{encoding:`utf8`,maxBuffer:2*1024*1024});return String(e??``)}catch{return null}}async function P(){if(process.platform!==`darwin`)return null;let e=await M([`clipboard info`]);return String(e??``).trim()||null}async function fe(e){if(process.platform!==`darwin`)return null;try{let{stdout:t}=await le(`pbpaste`,[`-Prefer`,String(e)],{encoding:`utf8`,maxBuffer:2*1024*1024});return String(t??``)}catch{return null}}async function F(){if(process.platform!==`darwin`)return[];let e=await M([`try`,`set thePaths to {}`,`try`,`set theItems to the clipboard as alias list`,`on error`,`set theItems to {(the clipboard as alias)}`,`end try`,`repeat with a in theItems`,`set end of thePaths to POSIX path of a`,`end repeat`,`set AppleScript's text item delimiters to "\\n"`,`return thePaths as text`,`end try`]),t=String(e??``).trim();return t?t.split(/\r?\n/).map(e=>e.trim()).filter(Boolean):[]}async function pe(){if(process.platform!==`darwin`)return[];let e=await M([`try`,`tell application "Finder"`,`if (count of selection) is 0 then return ""`,`set thePaths to {}`,`repeat with i in selection`,`try`,`set end of thePaths to POSIX path of (i as alias)`,`end try`,`end repeat`,`set AppleScript's text item delimiters to "\\n"`,`return thePaths as text`,`end tell`,`end try`]),t=String(e??``).trim();return t?t.split(/\r?\n/).map(e=>e.trim()).filter(Boolean):[]}async function I(e,t=12*1024*1024){if(process.platform!==`darwin`)return null;try{let{stdout:n}=await le(`pbpaste`,[`-Prefer`,String(e)],{encoding:`buffer`,maxBuffer:t});return!Buffer.isBuffer(n)||n.length<8?null:n}catch{return null}}async function L(e,t){if(process.platform!==`darwin`||!Buffer.isBuffer(e)||e.length===0)return null;let n=String(t??``).toLowerCase()||`.bin`,r=await _(w.join(re.tmpdir(),`goatchain-clip-`)),i=w.join(r,`in${n}`),a=w.join(r,`out.png`);try{await C(i,e),await le(`sips`,[`-s`,`format`,`png`,i,`--out`,a],{encoding:`utf8`,maxBuffer:1024*1024});let t=await y(a),n=ue(t);if(!n||n.mime!==`image/png`)return null;let r=`data:${n.mime};base64,${t.toString(`base64`)}`;return{buf:t,mime:n.mime,ext:n.ext,dataUrl:r}}catch{return null}finally{try{await x(r,{recursive:!0,force:!0})}catch{}}}async function me(e,t=4*1024*1024){let n=await S(e);if(!n.isFile()||n.size>t)return null;let r=await y(e),i=ue(r);if(!i||!i.mime.startsWith(`image/`))return null;let a=`data:${i.mime};base64,${r.toString(`base64`)}`;return{buf:r,mime:i.mime,ext:i.ext,dataUrl:a}}async function he(e=4*1024*1024){if(process.platform!==`darwin`)return[];let t=[],n=await fe(`public.file-url`),r=N(n&&n.trim()?n:await de());if(r.length===0&&(r=await F()),r.length>0)for(let n of r)try{let r=await me(n,e);r&&t.push({source:`file`,absPath:n,...r})}catch{}if(t.length>0)return t;for(let n of[`png`,`public.png`,`jpeg`,`public.jpeg`,`jpg`,`public.jpg`,`public.tiff`,`tiff`,`public.bmp`,`bmp`]){let r=await I(n,Math.max(12*1024*1024,e));if(!r)continue;let i=ue(r);if(!i||!i.mime.startsWith(`image/`))continue;if(i.mime===`image/tiff`||i.mime===`image/bmp`){let e=await L(r,i.ext);if(e){t.push({source:n,absPath:null,...e});break}}let a=`data:${i.mime};base64,${r.toString(`base64`)}`;t.push({source:n,absPath:null,buf:r,mime:i.mime,ext:i.ext,dataUrl:a});break}return t}const ge=new Set([`node_modules`,`.git`,`.goatchain`,`dist`,`tmp`]);function R(e,t){let n=w.relative(w.resolve(e),w.resolve(t));return n===``?!0:n===`..`?!1:!n.startsWith(`..${w.sep}`)&&!w.isAbsolute(n)}function _e(e,t){let n=w.isAbsolute(t)?t:w.resolve(e,t);if(!R(e,n))throw Error(`Access denied: ${n}\nAllowed directory: ${e}`);let r=w.join(e,`.goatchain`);if(R(r,n))throw Error(`Access denied: ${n}\nRestricted: ${r}`);return n}async function ve(e,t={}){let n=typeof t.maxFiles==`number`?t.maxFiles:5e3,r=new Set(t.ignoreDirs??ge),i=[],a=[`.`];for(;a.length>0;){let t=a.shift();if(!t)break;let o=w.resolve(e,t),s;try{s=await b(o,{withFileTypes:!0})}catch{continue}for(let e of s){let o=e.name;if(!o)continue;if(e.isDirectory()){if(r.has(o)||o.startsWith(`.env`))continue;let e=t===`.`?o:w.join(t,o);a.push(e);continue}if(!e.isFile())continue;let s=t===`.`?o:w.join(t,o);if(i.push(s),i.length>=n)return i}}return i}function z(e,t){return t<=0?[]:e.slice(0,Math.min(e.length,t))}function ye(e,t={}){let n=typeof t.headLines==`number`?t.headLines:40,r=typeof t.tailLines==`number`?t.tailLines:20,i=typeof t.maxBytes==`number`?t.maxBytes:6e4,a=String(e??``),o=Buffer.byteLength(a,`utf8`),s=o>i?a.slice(0,Math.max(0,i)):a,c=s.split(`
1
+ import{a as e,c as t,n,r,s as i,t as a}from"./constants-C3H5Y2lA.js";import{a as o,c as s,i as c,n as l,o as u,r as d,s as f,t as p}from"./ui-h27qws5j.js";import"./openai-Ba5c3VJv.js";import{t as m}from"./theme-CDmxdKhU.js";import{J as h}from"./src-DDLca7F5.js";import{randomUUID as g}from"node:crypto";import{mkdtemp as _,open as v,readFile as y,readdir as b,rm as x,stat as S,writeFile as C}from"node:fs/promises";import w from"node:path";import{Writable as ee}from"node:stream";import te from"node:fs";import{pathToFileURL as ne}from"node:url";import re from"node:os";import{execFile as T}from"node:child_process";import{promisify as E}from"node:util";import ie from"node:readline";import{Buffer as D}from"node:buffer";const ae=[{modelId:`deepseek-v3.1`,hint:`DeepSeek (OpenAI-compatible).`},{modelId:`glm-4.7`,hint:`GLM (OpenAI-compatible).`}];function oe(e){let t=String(e??``).trim(),n=t.toLowerCase(),r=n.includes(`codex`);return{reasoning:/^o\d/i.test(t)||n.includes(`reasoner`)||n.includes(`reasoning`)||n.includes(`deepseek-r1`)||n.includes(`deepseek-reasoner`)||/^gpt-5/i.test(t),vision:n.includes(`vision`)||n.includes(`glm-4v`)||n.includes(`4v`)||n.includes(`4o`)||/^gpt-4\.1/i.test(t)||/^gpt-5/i.test(t),codex:r}}function O(e){return`[${e}]`}function k(e){let t=oe(e);return[t.codex?O(`codex`):``,t.reasoning?O(`reasoning`):``,t.vision?O(`vision`):``].filter(Boolean).join(` `)}function se(e){return String(e??``).toLowerCase()===`openai`?[...ae.map(e=>({modelId:e.modelId,label:e.label||e.modelId,hint:e.hint||``})),{modelId:``,label:`Custom…`,hint:`Enter a model id`}]:[{modelId:``,label:`Custom…`,hint:`Enter a model id`}]}function A(e){let t=String(e??``).trim().toLowerCase();return t===`minimal`||t===`low`||t===`medium`||t===`high`?t:null}function j(e){return e===`auto`?`Let the provider decide (recommended).`:e===`minimal`?`Lowest reasoning; fastest.`:e===`low`?`Less thinking; faster.`:e===`medium`?`Balanced.`:`More thinking; slower but stronger.`}function ce(e){let t=e.env??process.env,n=e.uiPrefsAttachImages??{},r=t.GOATCHAIN_ATTACH_IMAGES_NOTE_TEMPLATE,i=t.GOATCHAIN_ATTACH_IMAGES_NOTE_POSITION,a=t.GOATCHAIN_ATTACH_IMAGES_IMAGES_POSITION,o=t.GOATCHAIN_ATTACH_IMAGES_DATA_URL_MODE,s=t.GOATCHAIN_ATTACH_IMAGES_MAX_DATA_URL_CHARS,c=(e,t)=>{let n=String(e??``).trim().toLowerCase();return[`start`,`before_images`,`after_images`,`before_text`,`after_text`,`end`].includes(n)?n:t},l=(e,t)=>{let n=String(e??``).trim().toLowerCase();return n===`none`||n===`prefix`||n===`full`?n:t},u=(()=>{let e=Number(s??n.maxDataUrlChars);return Number.isFinite(e)?Math.max(0,Math.trunc(e)):void 0})();return{note:{template:typeof r==`string`&&r.trim()?r:typeof n.noteTemplate==`string`?n.noteTemplate:void 0,dataUrlMode:l(o??n.dataUrlMode,`prefix`),maxDataUrlChars:u},notePosition:c(i??n.notePosition,`start`),imagesPosition:c(a??n.imagesPosition,`before_text`)}}const le=E(T);async function M(e,t=1024*1024){if(process.platform!==`darwin`)return null;try{let{stdout:n}=await le(`osascript`,e.flatMap(e=>[`-e`,e]),{encoding:`utf8`,maxBuffer:t});return String(n??``)}catch{return null}}function N(e){let t=String(e??``).trim();if(!t)return[];let n=t.split(/\0|\r?\n/).map(e=>e.trim()).filter(Boolean),r=[];for(let e of n){if(e.startsWith(`file://`))try{let t=new URL(e);if(t.protocol!==`file:`)continue;let n=decodeURIComponent(t.pathname);n&&r.push(n);continue}catch{continue}e.startsWith(`/`)&&r.push(e)}return r}function ue(e){return!Buffer.isBuffer(e)||e.length<12?null:e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10?{mime:`image/png`,ext:`.png`}:e[0]===255&&e[1]===216&&e[2]===255?{mime:`image/jpeg`,ext:`.jpg`}:e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56?{mime:`image/gif`,ext:`.gif`}:e.subarray(0,4).toString(`ascii`)===`RIFF`&&e.subarray(8,12).toString(`ascii`)===`WEBP`?{mime:`image/webp`,ext:`.webp`}:e[0]===73&&e[1]===73&&e[2]===42&&e[3]===0||e[0]===77&&e[1]===77&&e[2]===0&&e[3]===42?{mime:`image/tiff`,ext:`.tiff`}:e[0]===66&&e[1]===77?{mime:`image/bmp`,ext:`.bmp`}:null}async function de(){if(process.platform!==`darwin`)return null;try{let{stdout:e}=await le(`pbpaste`,[],{encoding:`utf8`,maxBuffer:2*1024*1024});return String(e??``)}catch{return null}}async function P(){if(process.platform!==`darwin`)return null;let e=await M([`clipboard info`]);return String(e??``).trim()||null}async function fe(e){if(process.platform!==`darwin`)return null;try{let{stdout:t}=await le(`pbpaste`,[`-Prefer`,String(e)],{encoding:`utf8`,maxBuffer:2*1024*1024});return String(t??``)}catch{return null}}async function F(){if(process.platform!==`darwin`)return[];let e=await M([`try`,`set thePaths to {}`,`try`,`set theItems to the clipboard as alias list`,`on error`,`set theItems to {(the clipboard as alias)}`,`end try`,`repeat with a in theItems`,`set end of thePaths to POSIX path of a`,`end repeat`,`set AppleScript's text item delimiters to "\\n"`,`return thePaths as text`,`end try`]),t=String(e??``).trim();return t?t.split(/\r?\n/).map(e=>e.trim()).filter(Boolean):[]}async function pe(){if(process.platform!==`darwin`)return[];let e=await M([`try`,`tell application "Finder"`,`if (count of selection) is 0 then return ""`,`set thePaths to {}`,`repeat with i in selection`,`try`,`set end of thePaths to POSIX path of (i as alias)`,`end try`,`end repeat`,`set AppleScript's text item delimiters to "\\n"`,`return thePaths as text`,`end tell`,`end try`]),t=String(e??``).trim();return t?t.split(/\r?\n/).map(e=>e.trim()).filter(Boolean):[]}async function I(e,t=12*1024*1024){if(process.platform!==`darwin`)return null;try{let{stdout:n}=await le(`pbpaste`,[`-Prefer`,String(e)],{encoding:`buffer`,maxBuffer:t});return!Buffer.isBuffer(n)||n.length<8?null:n}catch{return null}}async function L(e,t){if(process.platform!==`darwin`||!Buffer.isBuffer(e)||e.length===0)return null;let n=String(t??``).toLowerCase()||`.bin`,r=await _(w.join(re.tmpdir(),`goatchain-clip-`)),i=w.join(r,`in${n}`),a=w.join(r,`out.png`);try{await C(i,e),await le(`sips`,[`-s`,`format`,`png`,i,`--out`,a],{encoding:`utf8`,maxBuffer:1024*1024});let t=await y(a),n=ue(t);if(!n||n.mime!==`image/png`)return null;let r=`data:${n.mime};base64,${t.toString(`base64`)}`;return{buf:t,mime:n.mime,ext:n.ext,dataUrl:r}}catch{return null}finally{try{await x(r,{recursive:!0,force:!0})}catch{}}}async function me(e,t=4*1024*1024){let n=await S(e);if(!n.isFile()||n.size>t)return null;let r=await y(e),i=ue(r);if(!i||!i.mime.startsWith(`image/`))return null;let a=`data:${i.mime};base64,${r.toString(`base64`)}`;return{buf:r,mime:i.mime,ext:i.ext,dataUrl:a}}async function he(e=4*1024*1024){if(process.platform!==`darwin`)return[];let t=[],n=await fe(`public.file-url`),r=N(n&&n.trim()?n:await de());if(r.length===0&&(r=await F()),r.length>0)for(let n of r)try{let r=await me(n,e);r&&t.push({source:`file`,absPath:n,...r})}catch{}if(t.length>0)return t;for(let n of[`png`,`public.png`,`jpeg`,`public.jpeg`,`jpg`,`public.jpg`,`public.tiff`,`tiff`,`public.bmp`,`bmp`]){let r=await I(n,Math.max(12*1024*1024,e));if(!r)continue;let i=ue(r);if(!i||!i.mime.startsWith(`image/`))continue;if(i.mime===`image/tiff`||i.mime===`image/bmp`){let e=await L(r,i.ext);if(e){t.push({source:n,absPath:null,...e});break}}let a=`data:${i.mime};base64,${r.toString(`base64`)}`;t.push({source:n,absPath:null,buf:r,mime:i.mime,ext:i.ext,dataUrl:a});break}return t}const ge=new Set([`node_modules`,`.git`,`.goatchain`,`dist`,`tmp`]);function R(e,t){let n=w.relative(w.resolve(e),w.resolve(t));return n===``?!0:n===`..`?!1:!n.startsWith(`..${w.sep}`)&&!w.isAbsolute(n)}function _e(e,t){let n=w.isAbsolute(t)?t:w.resolve(e,t);if(!R(e,n))throw Error(`Access denied: ${n}\nAllowed directory: ${e}`);let r=w.join(e,`.goatchain`);if(R(r,n))throw Error(`Access denied: ${n}\nRestricted: ${r}`);return n}async function ve(e,t={}){let n=typeof t.maxFiles==`number`?t.maxFiles:5e3,r=new Set(t.ignoreDirs??ge),i=[],a=[`.`];for(;a.length>0;){let t=a.shift();if(!t)break;let o=w.resolve(e,t),s;try{s=await b(o,{withFileTypes:!0})}catch{continue}for(let e of s){let o=e.name;if(!o)continue;if(e.isDirectory()){if(r.has(o)||o.startsWith(`.env`))continue;let e=t===`.`?o:w.join(t,o);a.push(e);continue}if(!e.isFile())continue;let s=t===`.`?o:w.join(t,o);if(i.push(s),i.length>=n)return i}}return i}function z(e,t){return t<=0?[]:e.slice(0,Math.min(e.length,t))}function ye(e,t={}){let n=typeof t.headLines==`number`?t.headLines:40,r=typeof t.tailLines==`number`?t.tailLines:20,i=typeof t.maxBytes==`number`?t.maxBytes:6e4,a=String(e??``),o=Buffer.byteLength(a,`utf8`),s=o>i?a.slice(0,Math.max(0,i)):a,c=s.split(`
2
2
  `);if(c.length<=n+r)return{text:s,truncated:o>i};let l=z(c,n),u=c.slice(Math.max(n,c.length-r));return{text:`${l.join(`
3
3
  `)}\n…\n${u.join(`
4
4
  `)}`,truncated:!0}}async function B(e,t,n){let r=Math.max(0,Math.min(Number(t)||0,n)),i=await v(e,`r`);try{let e=Buffer.allocUnsafe(r),{bytesRead:a}=await i.read(e,0,r,0);return{text:e.subarray(0,a).toString(`utf8`),truncated:n>t,bytes:n}}finally{await i.close()}}function V(e){let t=String(e??``),n=[],r=/@file(?:\((path|summary|full)\))?:(\S+)/g,i;for(;(i=r.exec(t))!=null;){let e=i[0],t=i[1]===`path`||i[1]===`summary`||i[1]===`full`?i[1]:`summary`,r=i[2]??``;n.push({raw:e,mode:t,filePath:r})}return n}async function be(e,t,n={}){let r=typeof n.maxTotalBytes==`number`?n.maxTotalBytes:22e4,i=typeof n.maxBytesPerFile==`number`?n.maxBytesPerFile:12e4,a=typeof n.maxBytesPerFileSummary==`number`?n.maxBytesPerFileSummary:4e4,o=typeof n.headLines==`number`?n.headLines:60,s=typeof n.tailLines==`number`?n.tailLines:20,c=V(t);if(c.length===0)return{text:String(t??``),files:[],omitted:[]};let l=new Map;for(let e of c){let t=`${e.mode}:${e.filePath}`;l.has(t)||l.set(t,e)}let u=[],d=[],f=0,p=[...l.values()];for(let t=0;t<p.length;t++){let n=p[t],c=_e(e,n.filePath),l=await S(c);if(!l.isFile()){d.push({mode:n.mode,filePath:n.filePath,reason:`not_file`});continue}if(n.mode===`path`){u.push({mode:`path`,relPath:w.relative(e,c),absPath:c,bytes:l.size,truncated:!1});continue}let m=Math.max(0,r-f);if(m<=0){d.push({mode:n.mode,filePath:n.filePath,reason:`budget`});for(let e=t+1;e<p.length;e++){let t=p[e];d.push({mode:t.mode,filePath:t.filePath,reason:`budget`})}break}let h=n.mode===`summary`?a:i,g=Math.min(h,m),_=await B(c,g,l.size);if(f+=Math.min(_.bytes,g),n.mode===`full`)u.push({mode:`full`,relPath:w.relative(e,c),absPath:c,bytes:_.bytes,truncated:_.truncated,content:_.text});else{let t=ye(_.text,{headLines:o,tailLines:s,maxBytes:g});u.push({mode:`summary`,relPath:w.relative(e,c),absPath:c,bytes:_.bytes,truncated:_.truncated||t.truncated,content:t.text})}}let m=String(t??``);for(let e of c)m=m.replace(e.raw,``).replace(/\s{2,}/g,` `);m=m.trim();let h=u.filter(e=>e.mode!==`path`).map(e=>`${`---\nfile: ${`[${e.relPath}](${e.absPath})`}\nmode: ${e.mode}${e.truncated?` (truncated)`:``}\n---\n`}${String(e.content??``)}`.trimEnd()),g=u.filter(e=>e.mode===`path`).map(e=>`[${e.relPath}](${e.absPath})`),_=[h.length>0||g.length>0?`[attached files]`:``,g.length>0?`paths: ${g.join(`, `)}`:``].filter(Boolean).join(`
@@ -7,7 +7,7 @@ import{a as e,c as t,n,r,s as i,t as a}from"./constants-C3H5Y2lA.js";import{a as
7
7
  `),files:u,omitted:d}}function H(e,t){let n=w.relative(w.resolve(e),w.resolve(t));return n===``?!0:n===`..`?!1:!n.startsWith(`..${w.sep}`)&&!w.isAbsolute(n)}function xe(e){let t=String(e??``).trim();if(!t)return``;if(t=t.replace(/^\s*[>❯]\s+(?=["'`/~]|file:\/\/)/u,``),t.startsWith(`\x1B[200~`)&&(t=t.slice(6)),t.endsWith(`\x1B[201~`)&&(t=t.slice(0,-6)),t=t.trim(),t=t.replaceAll(`​`,``).replaceAll(`‌`,``).replaceAll(`‍`,``).replaceAll(``,``),t=t.replace(/^["'`]+|["'`]+$/g,``).trim(),t.startsWith(`file://`))try{let e=new URL(t);if(e.protocol===`file:`){let n=decodeURIComponent(e.pathname);n&&(t=n)}}catch{}return t===`~`?t=re.homedir():t.startsWith(`~/`)&&(t=w.join(re.homedir(),t.slice(2))),t=t.replace(/\\(.)/g,`$1`),t}function Se(e,t){let n=xe(t);if(!n)throw Error(`Missing path`);if(w.isAbsolute(n)){let t=w.resolve(n);return{absPath:t,withinWorkspace:H(e,t)}}return{absPath:_e(e,n),withinWorkspace:!0}}function Ce(e){if(!e||typeof e!=`object`)return!1;let t=e,n=typeof t.name==`string`?t.name:``;return n===`ExitPromptError`||n===`AbortError`||(typeof t.code==`string`?t.code:``)===`ERR_PROMPT_CANCELED`}async function we(){try{let e=await import(`@inquirer/prompts`);return e&&typeof e.select==`function`?e:null}catch{return null}}async function Te({message:e,options:t,initialValue:n}){let r=typeof n==`number`?t[n]?.value:n,i=await we();if(!i)return{ok:!1,reason:`missing`};try{let n=await i.select({message:e,choices:t.map(e=>({value:e.value,name:e.label,description:e.hint,disabled:e.disabled})),default:r});return{ok:!0,value:String(n)}}catch(e){if(Ce(e))return{ok:!1,reason:`cancel`};throw e}}async function Ee({message:e,options:t,required:n=!1}){let r=await we();if(!r)return{ok:!1,reason:`missing`};if(typeof r.checkbox!=`function`)return{ok:!1,reason:`unsupported`};try{let i=await r.checkbox({message:e,choices:t.map(e=>({value:e.value,name:e.label,description:e.hint,disabled:e.disabled})),required:n});return{ok:!0,value:Array.isArray(i)?i.map(String):[]}}catch(e){if(Ce(e))return{ok:!1,reason:`cancel`};throw e}}async function De({message:e,initialValue:t=!1}){let n=await we();if(!n)return{ok:!1,reason:`missing`};try{let r=[{value:`yes`,label:`Yes`},{value:`no`,label:`No`}],i=t?`yes`:`no`;if(typeof n.select!=`function`)return{ok:!1,reason:`unsupported`};let a=await n.select({message:e,choices:r.map(e=>({value:e.value,name:e.label})),default:i});return{ok:!0,value:String(a)===`yes`}}catch(e){if(Ce(e))return{ok:!1,reason:`cancel`};throw e}}async function Oe({message:e,placeholder:t}){let n=await we();if(!n)return{ok:!1,reason:`missing`};if(typeof n.input!=`function`)return{ok:!1,reason:`unsupported`};try{let r=await n.input({message:e,default:t});return{ok:!0,value:String(r??``)}}catch(e){if(Ce(e))return{ok:!1,reason:`cancel`};throw e}}async function ke({message:e,placeholder:t}){let n=await we();if(!n)return{ok:!1,reason:`missing`};if(typeof n.password!=`function`)return{ok:!1,reason:`unsupported`};try{let t=await n.password({message:e,mask:`*`});return{ok:!0,value:String(t??``)}}catch(e){if(Ce(e))return{ok:!1,reason:`cancel`};throw e}}function Ae(e){return Number.isFinite(e)?e>=4352&&(e<=4447||e===9001||e===9002||e>=11904&&e<=42191&&e!==12351||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65135||e>=65280&&e<=65376||e>=65504&&e<=65510||e>=127744&&e<=129791||e>=131072&&e<=262141):!1}function U(e){return e>=0&&e<32||e>=127&&e<=159}const je=/\p{Mark}/u;function Me(e){if(!Number.isFinite(e)||U(e))return 0;try{if(je.test(String.fromCodePoint(e)))return 0}catch{}return Ae(e)?2:1}function Ne(e){let t=0;for(let n of String(e??``)){let e=n.codePointAt(0)??0;t+=Me(e)}return t}function Pe(e){let t=String(e??``),n=``,r=0;for(;r<t.length;){let e=t[r];if(W(e)){r=Le(t,r);continue}let i=t.codePointAt(r)??0;n+=String.fromCodePoint(i),r+=i>65535?2:1}return n}function Fe(e,t){let n=String(e??``),r=Number.isFinite(t)?Math.max(0,Math.min(n.length,t)):n.length;if(r>0&&r<n.length){let e=n.charCodeAt(r-1),t=n.charCodeAt(r);e>=55296&&e<=56319&&t>=56320&&t<=57343&&r++}return r}function Ie(e,t){let n=String(e??``),r=Math.max(0,Number(t)||0);if(r===0)return{start:n.length,text:``};let i=0,a=n.length;for(;a>0;){let e=a-1,t=n.charCodeAt(e);if(t>=56320&&t<=57343&&e>0){let t=n.charCodeAt(e-1);t>=55296&&t<=56319&&e--}let o=Me(n.codePointAt(e)??0);if(i+o>r)break;i+=o,a=e}return{start:a,text:n.slice(a)}}function W(e){return e===`\x1B`}function Le(e,t){let n=t;if(n>=e.length||e[n]!==`\x1B`)return t;let r=e[n+1];if(r===`[`){let t=n+2;for(;t<e.length;){let n=e.charCodeAt(t);if(n>=64&&n<=126)return t+1;t++}return e.length}if(r===`]`){let t=n+2;for(;t<e.length;){let n=e[t];if(n===`\x07`)return t+1;if(n===`\x1B`&&e[t+1]===`\\`)return t+2;t++}return e.length}return Math.min(e.length,n+2)}function Re(e,t){let n=String(e??``),r=Math.max(0,Number(t)||0);if(r===0)return``;let i=``,a=0,o=0;for(;o<n.length&&a<r;){let e=n[o];if(W(e)){let e=Le(n,o);i+=n.slice(o,e),o=e;continue}let t=n.codePointAt(o)??0,s=Me(t);if(a+s>r)break;i+=String.fromCodePoint(t),a+=s,o+=t>65535?2:1}for(;o<n.length&&W(n[o]);){let e=Le(n,o);i+=n.slice(o,e),o=e}return`${i}\u001B[0m`}function G(e){return e.startsWith(`\x1B[`)&&e.endsWith(`m`)}function ze(e){if(e===`\x1B[m`)return!0;let t=e.slice(2,-1);return t?t.split(`;`).map(e=>e.trim()).filter(Boolean).includes(`0`):!0}function Be(e){if(!e.startsWith(`\x1B]8;;`))return null;let t=e.slice(5);return t.endsWith(`\x07`)?t=t.slice(0,-1):t.endsWith(`\x1B\\`)&&(t=t.slice(0,-2)),t}function Ve(e,t){let n=String(e??``),r=Math.max(1,Number(t)||0);if(!n)return[``];let i=`\x1B]8;;\x07`,a=[],o=``,s=0,c=0,l=``,u=``,d=()=>{u?a.push(`${o}${i}`):a.push(o),o=`${l}${u}`,s=0};for(;c<n.length;){let e=n[c];if(W(e)){let e=Le(n,c),t=n.slice(c,e);o+=t,G(t)&&(l=ze(t)?``:`${l}${t}`);let r=Be(t);r!==null&&(u=r?t:``),c=e;continue}let t=n.codePointAt(c)??0,i=Me(t),a=String.fromCodePoint(t);s>0&&s+i>r&&d(),o+=a,s+=i,c+=t>65535?2:1}return o.length===0?a.push(``):u?a.push(`${o}${i}`):a.push(o),a}function He(e){return e===`~`?re.homedir():e.startsWith(`~/`)||e.startsWith(`~\\`)?w.join(re.homedir(),e.slice(2)):e}function K(e){return e.includes(`\\`)&&!e.includes(`/`)?`\\`:`/`}function Ue(e,t){let n=String(e??``),r=K(n);if(n===`~`)return[`~${r}`];let i=n.lastIndexOf(`/`),a=n.lastIndexOf(`\\`),o=Math.max(i,a),s=o>=0?n.slice(0,o+1):``,c=o>=0?n.slice(o+1):n,l=He(s),u=w.isAbsolute(l)?l:w.resolve(t.cwd,l||`.`),d=typeof t.limit==`number`&&t.limit>0?t.limit:200,f=c.startsWith(`.`),p=c.toLowerCase(),m=[],h=null;try{for(h=te.opendirSync(u);m.length<d;){let e=h.readSync();if(!e)break;if(t.onlyDirs&&!e.isDirectory())continue;let n=e.name;!f&&n.startsWith(`.`)||c&&!n.toLowerCase().startsWith(p)||m.push(`${s}${n}${e.isDirectory()?r:``}`)}}catch{return[]}finally{try{h?.closeSync()}catch{}}return m.sort((e,t)=>e.localeCompare(t)),m.slice(0,d)}function We(e){let t=String(e??``).toLowerCase();return t.endsWith(`.png`)?`image/png`:t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)?`image/jpeg`:t.endsWith(`.webp`)?`image/webp`:t.endsWith(`.gif`)?`image/gif`:`application/octet-stream`}async function Ge(e){let t=e.pendingImages.get();if(e.autoAttachState.clipboardAttachInFlight&&t.length===0){e.showInlineHint(`Attaching image from clipboard… (try again in a moment)`);return}if(t.length===0){let t=e.autoAttachState.lastPastedImageName&&Date.now()-e.autoAttachState.lastPastedImageName.at<6e4?e.autoAttachState.lastPastedImageName:null;if(!e.useClack()&&process.stdout.isTTY){await Ke(e,{allowSendNow:!1});return}if(!e.useClack()||!process.stdout.isTTY){t?e.showInlineHint(`No pending attachments. Last pasted: ${t.name} (use /images, or paste/drag a full path)`):e.showInlineHint(`No pending attachments.`);return}await e.withClack(async()=>{let n=await e.selectWithClack({message:t?`Attachments (last pasted: ${t.name})`:`Attachments`,options:[{value:`images`,label:`Attach image(s) from workspace…`},{value:`path`,label:`Attach image by path…`},{value:`cancel`,label:`Cancel`}],initialValue:0});if(!(!n.ok||n.value===`cancel`)){if(n.value===`images`){await Ke(e);return}if(n.value===`path`){let t=await e.textWithClack({message:`Image path`,placeholder:`/Users/you/Desktop/image.png (you can drag & drop here)`});if(!t.ok)return;let n=String(t.value??``).trim();if(!n)return;let r=e.normalizeUserProvidedPathToken(n),{absPath:i,withinWorkspace:a}=e.resolveUserProvidedPathForRead(e.workspaceCwd(),r),o=await e.readImageFileAsDataUrl(i);if(!o?.dataUrl){e.showInlineHint(`Not a supported image path.`);return}e.pendingImages.push({name:w.basename(i),mime:String(o.mime),bytes:D.isBuffer(o.buf)?o.buf.byteLength:0,dataUrl:String(o.dataUrl),source:w.isAbsolute(r)&&!a?`paste`:`path`}),e.setPromptForMode(),e.refreshPrompt(),e.showInlineHint(`Attached image: ${w.basename(i)}`)}}});return}if(!e.useClack()){let n=await e.question(`Remove which attachments? (e.g. 1,3) or 'a' to clear all: `),r=String(n??``).trim().toLowerCase();if(!r)return;if(r===`a`||r===`all`||r===`clear`){e.pendingImages.set([]),e.clearPasteBuffers(),e.setPromptForMode(),e.refreshPrompt(),e.showInlineHint(`Cleared pending attachments.`);return}let i=r.split(/[, ]+/).map(e=>Number.parseInt(e,10)).filter(e=>Number.isFinite(e)),a=new Set(i.map(e=>e-1).filter(e=>e>=0&&e<t.length));if(a.size===0)return;e.pendingImages.set(t.filter((e,t)=>!a.has(t))),e.setPromptForMode(),e.refreshPrompt();return}await e.withClack(async()=>{let n=t.map((t,n)=>{let r=t.bytes?` (${e.humanBytes(t.bytes)})`:``;return{value:String(n),label:`${t.name}${r}`}}),r=await e.multiselectWithClack({message:`Select attachments to remove`,options:n,required:!1});if(!r.ok)return;let i=Array.isArray(r.value)?r.value.map(String):[],a=new Set(i.map(e=>Number.parseInt(e,10)).filter(e=>Number.isFinite(e)));a.size!==0&&(e.pendingImages.set(t.filter((e,t)=>!a.has(t))),e.setPromptForMode(),e.refreshPrompt())})}async function Ke(e,t={}){let n=t.allowSendNow!==!1;if(!e.useClack()){if(process.stdout.isTTY){let t=await e.question(`Image paths (space-separated; absolute or workspace-relative): `),r=String(t??``).trim();if(!r)return;let i=r.split(/\s+/).filter(Boolean),a=[];for(let t of i)try{let n=e.normalizeUserProvidedPathToken(t),{absPath:r,withinWorkspace:i}=e.resolveUserProvidedPathForRead(e.workspaceCwd(),n),o=await e.readImageFileAsDataUrl(r);if(!o?.dataUrl){e.showInlineHint(`Not a supported image path.`);return}a.push({name:w.basename(r),mime:String(o.mime),bytes:D.isBuffer(o.buf)?o.buf.byteLength:0,dataUrl:String(o.dataUrl),source:w.isAbsolute(n)&&!i?`paste`:`path`})}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`);return}if(a.length===0)return;if(e.pendingImages.push(...a),e.setPromptForMode(),e.refreshPrompt(),e.showInlineHint(`Attached ${a.length} image(s).`),n){let t=await e.question(`Send now? [y/N] `),n=String(t??``).trim().toLowerCase();if(n===`y`||n===`yes`){let t=await e.question(`Message (optional): `);await e.runChatTurn(String(t??``).trim())}}return}process.stdout.write([`Attach images:`,`- Paste from iTerm2 to attach (cmd+v).`,`- Or run /images to pick images (TTY + interactive UI).`,`- Ctrl+O manages pending attachments.`,``].join(`
8
8
  `));return}let r=await e.withClack(async()=>{let t=await e.getWorkspaceImages();if(t.length===0)return process.stdout.write(`[no images found]
9
9
  `),null;let r=await e.textWithClack({message:`Search images (substring)`,placeholder:`e.g. assets/logo.png`});if(!r.ok)return null;let i=String(r.value??``).trim().toLowerCase(),a=i?t.filter(e=>String(e).toLowerCase().includes(i)):t;if(a.length===0)return process.stdout.write(`[no matches]
10
- `),null;let o=a.slice(0,160),s=await e.multiselectWithClack({message:`Select images (${o.length}${a.length>160?`/${a.length}`:``})`,options:o.map(e=>({value:e,label:e})),required:!0});if(!s.ok)return null;let c=Array.isArray(s.value)?s.value.map(String).filter(Boolean):[];if(c.length===0)return null;let l=[];for(let t of c){let n=e.ensureAllowedFile(e.workspaceCwd(),t),r=await e.readFile(n);if(r.byteLength>4194304)return process.stdout.write(`Image too large: ${t} (${e.humanBytes(r.byteLength)})\n`),null;let i=r.toString(`base64`),a=We(t),o=`data:${a};base64,${i}`;l.push({name:w.relative(e.workspaceCwd(),n),mime:a,bytes:r.byteLength,dataUrl:o,source:`path`})}if(l.length===0)return null;if(!n)return{action:{kind:`attach`},toAdd:l};let u=await e.selectWithClack({message:`Apply`,options:[{value:`attach`,label:`Attach (keep editing)`},{value:`send`,label:`Attach and send now`}],initialValue:0});if(!u.ok)return null;if(u.value===`send`){let t=await e.textWithClack({message:`Message`,placeholder:`Optional message to send with images`});if(!t.ok)return null;let n=String(t.value??``).trim();return n?{action:{kind:`send`,line:n},toAdd:l}:{action:{kind:`attach`},toAdd:l}}return{action:{kind:`attach`},toAdd:l}});r&&(r.toAdd.length>0&&(e.pendingImages.push(...r.toAdd),e.setPromptForMode(),e.refreshPrompt()),r.action.kind===`send`&&await e.runChatTurn(r.action.line))}const qe=async({ctx:n,arg:r})=>{let i=t(n.uiPrefs?.approvalMode??`read_only`),a=async t=>{n.uiPrefs.approvalMode=t,await n.saveAll(),process.stdout.write(`${n.icon(`🛡️`)}approval mode: ${e(t)}\n`)};if(!r){if(n.useClack()&&n.stdoutIsTTY){await n.withClack(async()=>{let r=await n.selectWithClack({message:`Approval mode (${e(i)})`,options:[{value:`read_only`,label:`Read Only`,hint:`Requires approval for high-risk tools`},{value:`agent`,label:`Agent (current)`,hint:`Auto-approve tools (workspace only)`},{value:`full_access`,label:`Agent (full access)`,hint:`Auto-approve + allow outside workspace + network`},{value:`cancel`,label:`Cancel`}],initialValue:i===`read_only`?0:i===`agent`?1:2});if(!r.ok)return;let o=String(r.value);o!==`cancel`&&await a(t(o))});return}process.stdout.write(`${n.icon(`🛡️`)}approval mode: ${e(i)}\n`),process.stdout.write(`${n.ansi.dim(`Set with: /approvals read_only|agent|full_access`)}\n`);return}await a(t(r))},Je=async({ctx:e})=>{let t=await he(),n=await P(),r=await de(),i=await pe(),a=String(r??``).split(/\r?\n/).find(Boolean)??``;if(n&&process.stdout.write(`${e.icon(`📋`)}clipboard types: ${n}\n`),a&&process.stdout.write(`${e.icon(`📋`)}clipboard text: ${o(a,120)}\n`),Array.isArray(i)&&i.length>0&&process.stdout.write(`${e.icon(`🗂️`)}finder selection: ${i.slice(0,3).map(e=>w.basename(String(e))).join(`, `)}\n`),!Array.isArray(t)||t.length===0){process.stdout.write(`${e.icon(`📋`)}clipboard: no attachable image found\n`),process.stdout.write(`${e.icon(`💡`)}tip: clipboard is text-only. If you have the file selected in Finder, try pasting again (CLI can use Finder selection); otherwise drag & drop or use /images.\n`);return}process.stdout.write(`${e.icon(`🖼️`)}clipboard images: ${t.length} candidate(s)\n`);for(let n of t.slice(0,6)){let t=n?.source?String(n.source):`unknown`,r=n?.absPath?w.basename(String(n.absPath)):``,i=n?.mime?String(n.mime):``,a=Buffer.isBuffer(n?.buf)?n.buf.byteLength:0;process.stdout.write(`- ${t}${r?` ${r}`:``}${i?` ${i}`:``}${a?` (${e.humanBytes(a)})`:``}\n`)}t.length>6&&process.stdout.write(`… (+${t.length-6})\n`)},Ye=async({ctx:e})=>{if(e.isBusy()){process.stdout.write(`${e.icon(`⏳`)}busy (Ctrl+C to cancel)\n`);return}if(e.getUiMode()===`select_session`){process.stdout.write(`${e.icon(`ℹ️`)}Exit session picker first.\n`);return}let t=e.agentRef.get(),n=e.modelRef.get();if(!t){process.stdout.write(`${e.icon(`❌`)}Agent not available\n`);return}if(!n){process.stdout.write(`${e.icon(`❌`)}Model not available\n`);return}let r=t.stateStore;if(!r){process.stdout.write(`${e.icon(`❌`)}State store not available (agent has no stateStore)\n`);return}let i=Array.isArray(e.options.session.history)?e.options.session.history:[];if(i.length===0){process.stdout.write(`${e.icon(`ℹ️`)}No messages in current session to compress\n`);return}let a=e.options.session.sessionId;if(!a){process.stdout.write(`${e.icon(`❌`)}No active session\n`);return}try{process.stdout.write(`${e.icon(`🗜️`)}Starting manual compression for session ${a}...\n`);let{compressSessionManually:t}=await import(`./src-B_9q8eah.js`);if(typeof t!=`function`){process.stdout.write(`${e.icon(`❌`)}compressSessionManually not available in SDK\n`);return}let o=await t({sessionId:a,fullMessages:i,model:n,stateStore:r});if(o.summary.length===0){process.stdout.write(`${e.icon(`ℹ️`)}No summary generated (no content to summarize)\n`);return}process.stdout.write(`${e.icon(`✅`)}Compression completed:\n`),process.stdout.write(` 📊 Messages processed: ${o.messageCount}\n`),o.toolOutputCount>0?process.stdout.write(` 🔧 Tool outputs: ${o.toolOutputCount}\n`):process.stdout.write(` 💬 Conversation messages summarized
10
+ `),null;let o=a.slice(0,160),s=await e.multiselectWithClack({message:`Select images (${o.length}${a.length>160?`/${a.length}`:``})`,options:o.map(e=>({value:e,label:e})),required:!0});if(!s.ok)return null;let c=Array.isArray(s.value)?s.value.map(String).filter(Boolean):[];if(c.length===0)return null;let l=[];for(let t of c){let n=e.ensureAllowedFile(e.workspaceCwd(),t),r=await e.readFile(n);if(r.byteLength>4194304)return process.stdout.write(`Image too large: ${t} (${e.humanBytes(r.byteLength)})\n`),null;let i=r.toString(`base64`),a=We(t),o=`data:${a};base64,${i}`;l.push({name:w.relative(e.workspaceCwd(),n),mime:a,bytes:r.byteLength,dataUrl:o,source:`path`})}if(l.length===0)return null;if(!n)return{action:{kind:`attach`},toAdd:l};let u=await e.selectWithClack({message:`Apply`,options:[{value:`attach`,label:`Attach (keep editing)`},{value:`send`,label:`Attach and send now`}],initialValue:0});if(!u.ok)return null;if(u.value===`send`){let t=await e.textWithClack({message:`Message`,placeholder:`Optional message to send with images`});if(!t.ok)return null;let n=String(t.value??``).trim();return n?{action:{kind:`send`,line:n},toAdd:l}:{action:{kind:`attach`},toAdd:l}}return{action:{kind:`attach`},toAdd:l}});r&&(r.toAdd.length>0&&(e.pendingImages.push(...r.toAdd),e.setPromptForMode(),e.refreshPrompt()),r.action.kind===`send`&&await e.runChatTurn(r.action.line))}const qe=async({ctx:n,arg:r})=>{let i=t(n.uiPrefs?.approvalMode??`read_only`),a=async t=>{n.uiPrefs.approvalMode=t,await n.saveAll(),process.stdout.write(`${n.icon(`🛡️`)}approval mode: ${e(t)}\n`)};if(!r){if(n.useClack()&&n.stdoutIsTTY){await n.withClack(async()=>{let r=await n.selectWithClack({message:`Approval mode (${e(i)})`,options:[{value:`read_only`,label:`Read Only`,hint:`Requires approval for high-risk tools`},{value:`agent`,label:`Agent (current)`,hint:`Auto-approve tools (workspace only)`},{value:`full_access`,label:`Agent (full access)`,hint:`Auto-approve + allow outside workspace + network`},{value:`cancel`,label:`Cancel`}],initialValue:i===`read_only`?0:i===`agent`?1:2});if(!r.ok)return;let o=String(r.value);o!==`cancel`&&await a(t(o))});return}process.stdout.write(`${n.icon(`🛡️`)}approval mode: ${e(i)}\n`),process.stdout.write(`${n.ansi.dim(`Set with: /approvals read_only|agent|full_access`)}\n`);return}await a(t(r))},Je=async({ctx:e})=>{let t=await he(),n=await P(),r=await de(),i=await pe(),a=String(r??``).split(/\r?\n/).find(Boolean)??``;if(n&&process.stdout.write(`${e.icon(`📋`)}clipboard types: ${n}\n`),a&&process.stdout.write(`${e.icon(`📋`)}clipboard text: ${o(a,120)}\n`),Array.isArray(i)&&i.length>0&&process.stdout.write(`${e.icon(`🗂️`)}finder selection: ${i.slice(0,3).map(e=>w.basename(String(e))).join(`, `)}\n`),!Array.isArray(t)||t.length===0){process.stdout.write(`${e.icon(`📋`)}clipboard: no attachable image found\n`),process.stdout.write(`${e.icon(`💡`)}tip: clipboard is text-only. If you have the file selected in Finder, try pasting again (CLI can use Finder selection); otherwise drag & drop or use /images.\n`);return}process.stdout.write(`${e.icon(`🖼️`)}clipboard images: ${t.length} candidate(s)\n`);for(let n of t.slice(0,6)){let t=n?.source?String(n.source):`unknown`,r=n?.absPath?w.basename(String(n.absPath)):``,i=n?.mime?String(n.mime):``,a=Buffer.isBuffer(n?.buf)?n.buf.byteLength:0;process.stdout.write(`- ${t}${r?` ${r}`:``}${i?` ${i}`:``}${a?` (${e.humanBytes(a)})`:``}\n`)}t.length>6&&process.stdout.write(`… (+${t.length-6})\n`)},Ye=async({ctx:e})=>{if(e.isBusy()){process.stdout.write(`${e.icon(`⏳`)}busy (Ctrl+C to cancel)\n`);return}if(e.getUiMode()===`select_session`){process.stdout.write(`${e.icon(`ℹ️`)}Exit session picker first.\n`);return}let t=e.agentRef.get(),n=e.modelRef.get();if(!t){process.stdout.write(`${e.icon(`❌`)}Agent not available\n`);return}if(!n){process.stdout.write(`${e.icon(`❌`)}Model not available\n`);return}let r=t.stateStore;if(!r){process.stdout.write(`${e.icon(`❌`)}State store not available (agent has no stateStore)\n`);return}let i=Array.isArray(e.options.session.history)?e.options.session.history:[];if(i.length===0){process.stdout.write(`${e.icon(`ℹ️`)}No messages in current session to compress\n`);return}let a=e.options.session.sessionId;if(!a){process.stdout.write(`${e.icon(`❌`)}No active session\n`);return}try{process.stdout.write(`${e.icon(`🗜️`)}Starting manual compression for session ${a}...\n`);let{compressSessionManually:t}=await import(`./src-CMdXdryc.js`);if(typeof t!=`function`){process.stdout.write(`${e.icon(`❌`)}compressSessionManually not available in SDK\n`);return}let o=await t({sessionId:a,fullMessages:i,model:n,stateStore:r});if(o.summary.length===0){process.stdout.write(`${e.icon(`ℹ️`)}No summary generated (no content to summarize)\n`);return}process.stdout.write(`${e.icon(`✅`)}Compression completed:\n`),process.stdout.write(` 📊 Messages processed: ${o.messageCount}\n`),o.toolOutputCount>0?process.stdout.write(` 🔧 Tool outputs: ${o.toolOutputCount}\n`):process.stdout.write(` 💬 Conversation messages summarized
11
11
  `),process.stdout.write(` 📝 Summary length: ${o.summary.length} chars\n`),process.stdout.write(` 💾 Summary saved to CompressionState
12
12
  `),process.stdout.write(`\n${e.icon(`💡`)}The summary will be automatically loaded in the next turn.\n`)}catch(t){let n=t instanceof Error?t.message:String(t);process.stdout.write(`${e.icon(`❌`)}Compression failed: ${n}\n`)}},Xe=async({ctx:e,arg:t})=>{if(!t){process.stdout.write(`${e.icon(`❌`)}Missing key (try /help)\n`);return}e.setApiKey(t);let n=e.modelRef.get();typeof n?.resetClient==`function`&&n.resetClient(),await e.saveAll(),process.stdout.write(`${e.icon(`🔑`)}api key set\n`)},q=async({ctx:e,arg:t})=>{if(!t){process.stdout.write(`${e.icon(`❌`)}Missing key (try /help)\n`);return}if(typeof e.setWebSearchConfig!=`function`){process.stdout.write(`${e.icon(`❌`)}webSearch config is not supported in this build.\n`);return}e.setWebSearchConfig({apiKey:t}),await e.saveAll(),process.stdout.write(`${e.icon(`🔎`)}web search key set\n`)},Ze=async({ctx:e,arg:t})=>{if(!t){process.stdout.write(`${e.icon(`❌`)}Missing url (try /help)\n`);return}await e.setBaseUrl(t),process.stdout.write(`${e.icon(`🌐`)}baseUrl set: ${e.baseUrlRef.get()??``}\n`)},Qe=async({ctx:e})=>{typeof e.setCurrentMode==`function`&&e.setCurrentMode(`agent`),e.uiPrefs.planMode=!1,await e.saveAll(),process.stdout.write(`${e.icon(`🤖`)}agent mode: on\n`),process.stdout.write(`${e.ansi.dim(`Note: Mode changes take effect next turn.`)}\n`)},$e=async({ctx:e})=>{typeof e.setCurrentMode==`function`&&e.setCurrentMode(`plan`),e.uiPrefs.planMode=!0,await e.saveAll(),process.stdout.write(`${e.icon(`🧭`)}plan mode: on\n`),process.stdout.write(`${e.ansi.dim(`Note: Mode changes take effect next turn.`)}\n`)},et=async({ctx:e})=>{if(e.isBusy()){process.stdout.write(`${e.icon(`⏳`)}busy (Ctrl+C to cancel)\n`);return}if(e.getUiMode()===`select_session`){process.stdout.write(`${e.icon(`ℹ️`)}Exit session picker first.\n`);return}e.setMultiline({lines:[]}),e.setPromptForMode(),e.showInlineHint(`Multiline mode: type .send to send, .cancel to cancel.`)},tt=async({ctx:e})=>{if(e.isBusy()){process.stdout.write(`${e.icon(`⏳`)}busy (Ctrl+C to cancel)\n`);return}if(e.getUiMode()===`select_session`){process.stdout.write(`${e.icon(`ℹ️`)}Exit session picker first.\n`);return}await e.openEditorFlow()};function nt(e){return e===`user`||e===`assistant`||e===`tool`||e===`system`}function rt(e){if(typeof e==`string`)return e;try{return JSON.stringify(e,null,2)}catch{return String(e??``)}}function it(e){return Array.isArray(e)?e.filter(Boolean):[]}const at=async({ctx:e,arg:t})=>{let n=it(e.options?.session?.history);if(n.length===0){process.stdout.write(`[no history]
13
13
  `);return}let r=String(t??``).trim().split(/\s+/).filter(Boolean),i=new Set(r.map(e=>e.toLowerCase())),a=r.map(e=>e.toLowerCase()).filter(nt),o=a.length>0?a:[`user`,`assistant`,`tool`],s=i.has(`preview`),c=i.has(`all`)||i.has(`full`),l=r.find(e=>/^\d+$/.test(e)),u=l?Math.max(1,Number.parseInt(l,10)):void 0,d=n.filter(e=>o.includes(String(e?.role??``)));if(d.length===0){process.stdout.write(`[no matching history]
@@ -53,7 +53,7 @@ The model seems to have stopped before implementing.`)} Continue? [Y/n] `),n=Str
53
53
  `))}return we(e.session.inputs,e.session.history),!0},Cn=async e=>String(e??``),wn=async e=>String(e??``),On=async e=>{let t=String(e??``).trim(),n=t;if(n=await Cn(n),n=await wn(n),n.includes(`@file`))try{n=(await be(Z(),n,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30})).text}catch{}let r=await $t({inputText:n,workspaceCwd:Z(),pendingImages:q,attachImagesOptions:Yt()});return{rawInput:t,cleanedText:r.cleanedText,historyContent:r.historyContent,modelInput:r.modelInput,blocksSummary:ct(r.modelInput),pendingImages:q.map(e=>({name:String(e.name??``),mime:String(e.mime??``),bytes:Number(e.bytes??0)||0,source:String(e.source??``)}))}},An=()=>{let t={version:u,provider:p,modelId:_.get().modelId,sessionId:e.session.sessionId,history:e.session.history,usage:tt.get(e.session.sessionId),baseUrl:S.get(),requestDefaults:b,workspaceCwd:Z(),emoji:M?.emoji};if(P&&J&&process.stdout.isTTY){Bt({kind:`status`,title:`Status`,lines:Xn(t)},15e3);return}Zn(t)},Pn=async()=>{},Fn=async()=>{},In=async()=>{},Ln=async()=>{},zn={ansi:R,icon:F,label:L,uiPrefs:M,options:e,requestDefaults:b,provider:p,version:u,agentRef:h,modelRef:_,baseUrlRef:S,setBaseUrl:C,setApiKey:T,setWebSearchConfig:E,saveAll:D,workspaceCwd:Z,stdoutIsTTY:!!process.stdout.isTTY,useClack:I,withClack:Wt,selectWithClack:Te,multiselectWithClack:Ee,confirmWithClack:De,textWithClack:Oe,passwordWithClack:ke,question:e=>new Promise(t=>B.question(e,t)),isBusy:()=>G,getUiMode:()=>U,setUiMode:e=>{U=e,e!==`select_session`&&(je=null)},setCurrentMode:e=>{We=e},setPromptForMode:$,showInlineHint:X,clearAttachments:Rt,setMultiline:e=>{it=e},openEditorFlow:()=>Pn(),exit:dn,leaveSessionPickerUi:un,openSessionPicker:hn,humanBytes:Jn,openCommandPalette:lr,printConfig:Ut,printStatus:An,prepareOutgoingPreview:On,openWorkspaceFlow:ar,openFilesFlow:rr,openImagesFlow:cr,openSettingsFlow:()=>Fn(),openOutputFlow:()=>In(),openDiagnosticsFlow:()=>Ln(),resetToNewSession:gn,useSessionById:_n,listSessions:oe,loadSessionById:O,saveSessionByData:k,renameSessionById:se,setPinnedSessionsById:A,deleteSessionById:j,deleteSessionsById:le,debugSendPayload:{get:()=>Nt,set:e=>{Nt=e}},debugToolIds:{get:()=>Pt,set:e=>{Pt=e}}},Bn=()=>{ge=m(M?.theme),R=ge.ansi,zn.ansi=R},Vn=Vt(zn),Hn=async e=>{let[t,...n]=e.trim().split(/\s+/),r=t.slice(1).toLowerCase(),i=r,a=n.join(` `).trim(),o=vn(r);if(o.kind===`prefix`)i=o.cmd;else if(o.kind===`ambiguous`){process.stdout.write(`${F(`❓`)}ambiguous command: ${t} (did you mean ${o.matches.map(e=>`/${e}`).join(`, `)}?)\n`);return}let s=Vn.get(i);if(s){await s({cmd:i,arg:a,raw:e,ctx:zn});return}let c=vn(r);if(c.kind===`fuzzy`||c.kind===`contains`){process.stdout.write(`${F(`❓`)}unknown command: ${t} (did you mean ${c.matches.map(e=>`/${e}`).join(`, `)}?)\n`);return}process.stdout.write(`${F(`❓`)}unknown command: ${t} (try /help)\n`)};if(!P){process.stdout.write(`${F(`💡`)}/help · Tab mode · Ctrl+K palette · Ctrl+C exit\n`);let e=We===`plan`?`🧭`:`🤖`,t=We===`plan`?`PLAN`:`AGENT`;process.stdout.write(`${F(e)}Current mode: ${R.bold(t)} ${R.dim(`(Tab, /plan, /agent)`)}\n`)}if(e.session.history.length>0){let t=e.session.title??c(e.session.history),n=e.session.summary??d(e.session.history);process.stdout.write(`${F(`🗂️`)}Restored session: ${e.session.sessionId}\n`),process.stdout.write(`Title: ${t}\n`),n&&process.stdout.write(`Summary: ${n}\n`),s(e.session.history.filter(e=>e&&typeof e==`object`&&e.role!==`system`&&e.role!==`tool`),{maxMessages:20,maxCharsPerMessage:600,multiline:!0,maxLinesPerMessage:40,emoji:M?.emoji,ansi:R,formatRoleHeader:(e,t)=>e===`assistant`||e===`user`||e===`tool`||e===`system`?ge.roleHeader(e,t):`[${e}]`}),process.stdout.write(R.dim(`Tip: use /history all (or /history user) to expand
54
54
  `)),process.stdout.write(`
55
55
  `)}we(e.session.inputs,e.session.history),B.prompt();let Un=(e,t)=>{let n=String(t??`summary`).trim().toLowerCase();return n!==`path`&&n!==`summary`&&n!==`full`?String(e??``):String(e??``).replace(/@file(?:\((?:path|summary|full)\))?:/g,`@file(${n}):`)};Cn=async e=>{let t=String(e??``);if(!t.includes(`@`))return t;(!Ye||Date.now()-Ye.at>=3e4)&&await Kn();let n=Ye;if(!n)return t;let r=new Set(n.files),i=new Set(n.dirs.map(e=>e.replace(/\/+$/,``)));return t.replace(/(^|[\s,,。!??::;;、()[\]{}"'“”‘’])@([^\s,,。!??::;;、()[\]{}"'“”‘’]+)/g,(e,t,n)=>{let a=String(n??``).trim();if(!a)return e;let o=a.toLowerCase();if(o.startsWith(`file(`)||o.startsWith(`file:`)||o.startsWith(`dir(`)||o.startsWith(`dir:`))return e;let s=a.replace(/^\.\/+/,``).replace(/\\/g,`/`),c=s.endsWith(`.`)?s.slice(0,-1):s,l=c.replace(/\/+$/,``);return r.has(c)?`${String(t??``)}@file(summary):${c}`:i.has(l)?`${String(t??``)}@dir(summary):${l}`:e})},wn=async e=>{let t=String(e??``);if(!t.includes(`@dir`))return t;(!Ye||Date.now()-Ye.at>=3e4)&&await Kn();let n=Ye;if(!n)return t;let r=n.files;return t.replace(/@dir(?:\((path|summary|full)\))?:(\S+)/g,(e,t,n)=>{let i=t===`path`||t===`summary`||t===`full`?t:`summary`,a=String(n??``).replace(/\\/g,`/`).replace(/\/+$/,``);if(!a)return e;try{_e(Z(),a)}catch{return e}let o=`${a}/`,s=r.filter(e=>e===a||e.startsWith(o)).slice(0,40);return s.length===0?e:s.map(e=>`@file(${i}):${e}`).join(` `)})};let Wn=async n=>{G=!0,P&&(St=!0,Q()),W=new AbortController;let r=String(n??``).trim(),o=r,s=z?z():null;if(s&&!s.present){process.stderr.write(`${R.red(`${F(`✖`)}Missing OPENAI_API_KEY (required for chatting)`)}\n`),process.stderr.write(R.dim("Set `OPENAI_API_KEY` in your environment or run `/api-key <key>` in the CLI.\n")),G=!1,W=null,P&&Q();return}P&&(process.stdout.write(`${ge.roleHeader(`user`,{emoji:fe()})}\n`),process.stdout.write(`${r}\n`));let c=e.session.history.length;Array.isArray(e.session.inputs)||(e.session.inputs=[]);let l=e.session.inputs.length;r&&e.session.inputs.push(r);let u=c,d=(e,t)=>{let n=String(e??``),r=String(t??``).trim();if(!r)return n;let i=n.indexOf(r);if(i<0)return n;let a=i===0?``:n[i-1],o=i+r.length>=n.length?``:n[i+r.length],s=!a||/[\s,,。.!??::;;、()[\]{}"'“”‘’]/.test(a),c=!o||/[\s,,。.!??::;;、()[\]{}"'“”‘’]/.test(o);return!s||!c?n:`${n.slice(0,i)} ${n.slice(i+r.length)}`.replace(/\s{2,}/g,` `).trim()},f=()=>{let e=r.match(/(^|\s)([^\s/\\]+?)\s*\.\s*(png|jpg|jpeg|webp|gif|bmp|tiff?|heic)(?=[\s,,。.!??::;;、()[\]{}"'“”‘’]|$)/i);if(!e)return null;let t=String(e[2]??``).trim(),n=String(e[3]??``).trim().toLowerCase();return!t||!n||r.includes(`@`)?null:`${t}.${n}`};if(q.length===0){let e=f();if(e){let t=await he(),n=e.toLowerCase(),r=Array.isArray(t)&&t.length>0?t.find(e=>e?.absPath&&w.basename(String(e.absPath)).toLowerCase()===n)??t[0]:null;if(!r)process.stdout.isTTY&&process.stdout.write(R.dim(`(no image found in clipboard; send text only — use cmd+v in iTerm2 or /images to attach)
56
- `));else if(typeof r.dataUrl==`string`&&r.dataUrl.startsWith(`data:image/`)){let t=!0;if(process.stdout.isTTY)if(I())await Wt(async()=>{let n=await De({message:`Attach image from clipboard as “${e}”?`,initialValue:!0});t=!!(n.ok&&n.value)});else{let n=await new Promise(t=>B.question(`Attach image from clipboard as "${e}"? [Y/n] `,t)),r=String(n??``).trim().toLowerCase();t=r===``||r===`y`||r===`yes`}t&&(q.push({name:e,mime:r.mime,bytes:Buffer.isBuffer(r.buf)?r.buf.byteLength:0,dataUrl:r.dataUrl,source:`paste`}),o=d(o,e),$(),H())}}}if(o=await Cn(o),o=await wn(o),o.includes(`@file`))try{let e=await be(Z(),o,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30}),t=(Array.isArray(e.omitted)?e.omitted:[]).some(e=>e&&e.reason===`budget`),n=(Array.isArray(e.files)?e.files:[]).some(e=>e&&e.mode===`full`&&e.truncated);if((t||n)&&process.stdout.isTTY){let t=`proceed`;if(I())await Wt(async()=>{let e=await Te({message:`File attachments exceed budget`,options:[{value:`proceed`,label:`Proceed (some may be truncated/omitted)`},{value:`summary`,label:`Downgrade to Summary`},{value:`path`,label:`Paths only (no content)`},{value:`cancel`,label:`Cancel send`}],initialValue:1});if(!e.ok){t=`cancel`;return}t=String(e.value)});else{let e=await new Promise(e=>B.question(`Attachments exceed budget. Use Summary instead? [Y/n] `,e)),n=String(e??``).trim().toLowerCase();t=n===``||n===`y`||n===`yes`?`summary`:`proceed`}if(t===`cancel`){G=!1,W=null,P&&Q();return}if(t===`summary`){let t=Un(o,`summary`);e=await be(Z(),t,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30})}else if(t===`path`){let t=Un(o,`path`);e=await be(Z(),t,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30})}}o=e.text;let r=Array.isArray(e.files)?e.files.length:0;r>0&&process.stdout.write(R.dim(`(${F(`📎`)}attached ${r} file(s))\n`))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),G=!1,W=null,P&&Q();return}let p=o,m=o,g=q.length>0?[...q]:[],_=0;try{let e=await $t({inputText:o,workspaceCwd:Z(),pendingImages:q,attachImagesOptions:Yt()});p=e.modelInput,m=e.historyContent,_=e.imageCount,_>0&&process.stdout.write(R.dim(`(${F(`🖼️`)}attached ${_} image(s))\n`))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),G=!1,W=null,P&&Q();return}Nt&&_>0&&Kt({historyContent:m,modelInput:p}),e.session.history.push({role:`user`,content:m});let v=q;g.length>0&&(q=[],$());try{let n=t=>{if(!t?.usage)return;let n=e.session.sessionId,r=tt.get(n)??nt();tt.set(n,{promptTokens:r.promptTokens+t.usage.promptTokens,completionTokens:r.completionTokens+t.usage.completionTokens,totalTokens:r.totalTokens+t.usage.totalTokens})},r=async n=>{let r=i({mode:t(M?.approvalMode??`read_only`),envAutoApprove:process.env.GOATCHAIN_AUTO_APPROVE});return qn({agent:h.get(),sessionId:e.session.sessionId,history:n.history,input:n.input,theme:M?.theme,signal:W?.signal??new AbortController().signal,approvalStrategy:r.strategy,autoApprove:r.autoApprove,debugToolIds:Pt,askApproval:async e=>{let t=String(e??``);if(I()&&process.stdout.isTTY){let e=Pe(t).trim(),n=/\[Y\/n\]/.test(e)||/\(Y\/n\)/.test(e),r=/\[y\/N\]/.test(e)||/\(y\/N\)/.test(e),i=e.replace(/\s*(?:\[Y\/N\]|\(Y\/N\))\s*$/i,``).trim()||(r?`Allow?`:`Continue?`),a=n||!r;return await Wt(async()=>{let e=await De({message:i,initialValue:a});a=!!(e.ok&&e.value)}),a?`y`:`n`}return await new Promise(e=>B.question(t,e))},askApprovalForTool:I()&&process.stdout.isTTY?async({toolCallId:e,toolName:t,riskLevel:n,display:r})=>{let i=n?` (${n})`:``,a=r?.lines&&Array.isArray(r.lines)?r.lines:[];process.stdout.write(`\n${R.bold(`Approval required:`)} ${String(t??`tool`)}${i}${e?` ${R.dim(`(${e})`)}`:``}\n`);for(let e of a.slice(0,10))process.stdout.write(`${R.dim(`- ${e}`)}\n`);a.length>10&&process.stdout.write(`${R.dim(`… (+${a.length-10})`)}\n`);let o=await Wt(()=>Te({message:`Allow this tool?`,options:[{value:`approve`,label:L(`✅`,`Approve (once)`)},{value:`approve_all`,label:L(`🧷`,`Approve all tools (this turn)`)},{value:`deny`,label:L(`❌`,`Deny`)},{value:`abort`,label:L(`🛑`,`Abort turn`)}],initialValue:2}));return o.ok?String(o.value):`deny`}:void 0,askUserQuestions:I()&&process.stdout.isTTY?async({toolCallId:e,questions:t})=>{process.stdout.write(`\n${R.bold(`Agent needs your input:`)} ${R.dim(`(${e})`)}\n`);let n={};for(let e=0;e<t.length;e++){let r=t[e];process.stdout.write(`\n${R.cyan(`[${r.header}]`)} ${r.question}\n`);let i=[...r.options.map(e=>({value:e.label,label:e.label,hint:e.description})),{value:`__other__`,label:`Other (custom text)`,hint:`Enter your own answer`}];if(r.multiSelect){let t=await Wt(()=>Ee({message:`Select your answers for "${r.header}"`,options:i,required:!1}));if(!t.ok)throw Error(`User cancelled question prompt`);let a=Array.isArray(t.value)?t.value:[t.value];if(a.includes(`__other__`)){let t=await Wt(()=>Oe({message:`Enter your custom answer for "${r.header}"`,placeholder:`Type your answer...`}));if(!t.ok)throw Error(`User cancelled text input`);n[String(e)]=[...a.filter(e=>e!==`__other__`),String(t.value??``)].filter(e=>e.trim()!==``)}else n[String(e)]=a.map(String)}else{let t=await Wt(()=>Te({message:`Select your answer for "${r.header}"`,options:i,initialValue:0}));if(!t.ok)throw Error(`User cancelled question prompt`);if(t.value===`__other__`){let t=await Wt(()=>Oe({message:`Enter your custom answer for "${r.header}"`,placeholder:`Type your answer...`}));if(!t.ok)throw Error(`User cancelled text input`);n[String(e)]=String(t.value??``)}else n[String(e)]=String(t.value??``)}}return n}:void 0,showTools:typeof M?.showTools==`boolean`?M.showTools:void 0,toolStyle:typeof M?.toolStyle==`string`?M.toolStyle:void 0,showStatus:typeof M?.showStatus==`boolean`?M.showStatus:void 0,showStatusLine:typeof M?.showStatusLine==`boolean`?M.showStatusLine:void 0,showFileChanges:typeof M?.showFileChanges==`boolean`?M.showFileChanges:void 0,emoji:typeof M?.emoji==`boolean`?M.emoji:void 0,promptContinue:n.promptContinue,autoContinue:n.autoContinue,hooks:n.hooks})},o=h.get();if(We===`plan`){let e=o?.getMiddlewares?.()??[],t=e.some(e=>e.name===`plan-mode`),n=e.some(e=>e.name===`parallel-subagent`);if((!t||!n)&&typeof o?.use==`function`)try{let e=await import(`./src-B_9q8eah.js`);if(!t&&typeof e.createPlanModeMiddleware==`function`){let t=e.createPlanModeMiddleware({insertEveryIteration:!0});o.use(t,`plan-mode`)}if(!n&&typeof e.createParallelSubagentMiddleware==`function`){let{fileSearchSpecialist:t,fileSearchSpecialistPrompt:n}=e;if(t&&n){let r=e.createParallelSubagentMiddleware({subagents:[t],executor:async(r,i)=>{if(r.subagent_type!==t.name)throw Error(`Unknown subagent type: ${r.subagent_type}`);let{ToolRegistry:o,Agent:s}=e,c=new o,l=h.get()?.tools,u=new Set(t.blockedTools||[]);for(let e of t.tools||[]){if(u.has(e))continue;let t=l?.get?.(e);t&&c.register(t)}let d=new s({name:r.subagent_type,systemPrompt:`${n}\n\nYour task: ${r.prompt}\n\nProvide a concise summary of your findings.`,model:h.get()?.model,tools:c}),f=await d.createSession({sessionId:i?.sessionId,maxIterations:a});u.size>0&&f.disableTools(Array.from(u)),f.send(r.prompt);let p=``;for await(let e of f.receive())if(e.type===`done`){p=e.finalResponse||``;break}return{agentId:d.id,data:p}}});o.use(r,`parallel-subagent`)}}}catch{}}else typeof o?.removeMiddleware==`function`&&(o.removeMiddleware(`plan-mode`),o.removeMiddleware(`parallel-subagent`));let{messagesToAppend:s,meta:c}=await r({input:p,history:e.session.history.slice(0,-1),promptContinue:typeof M?.promptContinue==`boolean`?M.promptContinue:void 0,autoContinue:typeof M?.autoContinue==`boolean`?M.autoContinue:void 0});if(W.signal.aborted)throw Error(typeof W.signal?.reason==`string`?W.signal.reason:`sigint`);c.exitedPlanMode&&We===`plan`&&(We=`agent`,M.planMode=!1,process.stdout.write(`${F(`🤖`)}${R.green(`Auto-switched to agent mode`)} ${R.dim(`(ExitPlanMode detected)`)}\n`));let l=c;n(c),e.session.history.push(...s),await D(),K=l??K}catch(t){let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.name:``;Le>0&&Date.now()-Le<2e3&&(r===`AgentAbortError`||r===`AbortError`||n===`sigint`||n===`Canceled`)?(process.stdout.write(`${R.dim(`${F(`⛔`)}Canceled.`)}\n`),Le=0):process.stderr.write(`${n}\n`),e.session.history.splice(u),e.session.inputs.splice(l),g.length>0&&(q=v,$())}finally{G=!1,W=null,P&&Q()}};Pn=async()=>{let e=process.env.VISUAL||process.env.EDITOR||`vi`,{tmpdir:t}=await import(`node:os`),{spawnSync:n}=await import(`node:child_process`),{mkdtemp:r,readFile:i,rm:a,writeFile:o}=await import(`node:fs/promises`),s=e=>process.platform===`win32`?`"${String(e).replace(/"/g,`\\"`)}"`:`'${String(e).replace(/'/g,`'\\''`)}'`,c=await r(w.join(t(),`goatchain-edit-`)),l=w.join(c,`message.md`);await o(l,``,`utf8`);let u=!!V.paused;u||B.pause();try{let t=n(`${e} ${s(l)}`,{stdio:`inherit`,shell:!0});if(typeof t.status==`number`&&t.status!==0){process.stdout.write(`${F(`❌`)}Editor exited with status ${t.status}\n`);return}let r=String(await i(l,`utf8`)??``).replace(/\r\n/g,`
56
+ `));else if(typeof r.dataUrl==`string`&&r.dataUrl.startsWith(`data:image/`)){let t=!0;if(process.stdout.isTTY)if(I())await Wt(async()=>{let n=await De({message:`Attach image from clipboard as “${e}”?`,initialValue:!0});t=!!(n.ok&&n.value)});else{let n=await new Promise(t=>B.question(`Attach image from clipboard as "${e}"? [Y/n] `,t)),r=String(n??``).trim().toLowerCase();t=r===``||r===`y`||r===`yes`}t&&(q.push({name:e,mime:r.mime,bytes:Buffer.isBuffer(r.buf)?r.buf.byteLength:0,dataUrl:r.dataUrl,source:`paste`}),o=d(o,e),$(),H())}}}if(o=await Cn(o),o=await wn(o),o.includes(`@file`))try{let e=await be(Z(),o,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30}),t=(Array.isArray(e.omitted)?e.omitted:[]).some(e=>e&&e.reason===`budget`),n=(Array.isArray(e.files)?e.files:[]).some(e=>e&&e.mode===`full`&&e.truncated);if((t||n)&&process.stdout.isTTY){let t=`proceed`;if(I())await Wt(async()=>{let e=await Te({message:`File attachments exceed budget`,options:[{value:`proceed`,label:`Proceed (some may be truncated/omitted)`},{value:`summary`,label:`Downgrade to Summary`},{value:`path`,label:`Paths only (no content)`},{value:`cancel`,label:`Cancel send`}],initialValue:1});if(!e.ok){t=`cancel`;return}t=String(e.value)});else{let e=await new Promise(e=>B.question(`Attachments exceed budget. Use Summary instead? [Y/n] `,e)),n=String(e??``).trim().toLowerCase();t=n===``||n===`y`||n===`yes`?`summary`:`proceed`}if(t===`cancel`){G=!1,W=null,P&&Q();return}if(t===`summary`){let t=Un(o,`summary`);e=await be(Z(),t,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30})}else if(t===`path`){let t=Un(o,`path`);e=await be(Z(),t,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30})}}o=e.text;let r=Array.isArray(e.files)?e.files.length:0;r>0&&process.stdout.write(R.dim(`(${F(`📎`)}attached ${r} file(s))\n`))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),G=!1,W=null,P&&Q();return}let p=o,m=o,g=q.length>0?[...q]:[],_=0;try{let e=await $t({inputText:o,workspaceCwd:Z(),pendingImages:q,attachImagesOptions:Yt()});p=e.modelInput,m=e.historyContent,_=e.imageCount,_>0&&process.stdout.write(R.dim(`(${F(`🖼️`)}attached ${_} image(s))\n`))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),G=!1,W=null,P&&Q();return}Nt&&_>0&&Kt({historyContent:m,modelInput:p}),e.session.history.push({role:`user`,content:m});let v=q;g.length>0&&(q=[],$());try{let n=t=>{if(!t?.usage)return;let n=e.session.sessionId,r=tt.get(n)??nt();tt.set(n,{promptTokens:r.promptTokens+t.usage.promptTokens,completionTokens:r.completionTokens+t.usage.completionTokens,totalTokens:r.totalTokens+t.usage.totalTokens})},r=async n=>{let r=i({mode:t(M?.approvalMode??`read_only`),envAutoApprove:process.env.GOATCHAIN_AUTO_APPROVE});return qn({agent:h.get(),sessionId:e.session.sessionId,history:n.history,input:n.input,theme:M?.theme,signal:W?.signal??new AbortController().signal,approvalStrategy:r.strategy,autoApprove:r.autoApprove,debugToolIds:Pt,askApproval:async e=>{let t=String(e??``);if(I()&&process.stdout.isTTY){let e=Pe(t).trim(),n=/\[Y\/n\]/.test(e)||/\(Y\/n\)/.test(e),r=/\[y\/N\]/.test(e)||/\(y\/N\)/.test(e),i=e.replace(/\s*(?:\[Y\/N\]|\(Y\/N\))\s*$/i,``).trim()||(r?`Allow?`:`Continue?`),a=n||!r;return await Wt(async()=>{let e=await De({message:i,initialValue:a});a=!!(e.ok&&e.value)}),a?`y`:`n`}return await new Promise(e=>B.question(t,e))},askApprovalForTool:I()&&process.stdout.isTTY?async({toolCallId:e,toolName:t,riskLevel:n,display:r})=>{let i=n?` (${n})`:``,a=r?.lines&&Array.isArray(r.lines)?r.lines:[];process.stdout.write(`\n${R.bold(`Approval required:`)} ${String(t??`tool`)}${i}${e?` ${R.dim(`(${e})`)}`:``}\n`);for(let e of a.slice(0,10))process.stdout.write(`${R.dim(`- ${e}`)}\n`);a.length>10&&process.stdout.write(`${R.dim(`… (+${a.length-10})`)}\n`);let o=await Wt(()=>Te({message:`Allow this tool?`,options:[{value:`approve`,label:L(`✅`,`Approve (once)`)},{value:`approve_all`,label:L(`🧷`,`Approve all tools (this turn)`)},{value:`deny`,label:L(`❌`,`Deny`)},{value:`abort`,label:L(`🛑`,`Abort turn`)}],initialValue:2}));return o.ok?String(o.value):`deny`}:void 0,askUserQuestions:I()&&process.stdout.isTTY?async({toolCallId:e,questions:t})=>{process.stdout.write(`\n${R.bold(`Agent needs your input:`)} ${R.dim(`(${e})`)}\n`);let n={};for(let e=0;e<t.length;e++){let r=t[e];process.stdout.write(`\n${R.cyan(`[${r.header}]`)} ${r.question}\n`);let i=[...r.options.map(e=>({value:e.label,label:e.label,hint:e.description})),{value:`__other__`,label:`Other (custom text)`,hint:`Enter your own answer`}];if(r.multiSelect){let t=await Wt(()=>Ee({message:`Select your answers for "${r.header}"`,options:i,required:!1}));if(!t.ok)throw Error(`User cancelled question prompt`);let a=Array.isArray(t.value)?t.value:[t.value];if(a.includes(`__other__`)){let t=await Wt(()=>Oe({message:`Enter your custom answer for "${r.header}"`,placeholder:`Type your answer...`}));if(!t.ok)throw Error(`User cancelled text input`);n[String(e)]=[...a.filter(e=>e!==`__other__`),String(t.value??``)].filter(e=>e.trim()!==``)}else n[String(e)]=a.map(String)}else{let t=await Wt(()=>Te({message:`Select your answer for "${r.header}"`,options:i,initialValue:0}));if(!t.ok)throw Error(`User cancelled question prompt`);if(t.value===`__other__`){let t=await Wt(()=>Oe({message:`Enter your custom answer for "${r.header}"`,placeholder:`Type your answer...`}));if(!t.ok)throw Error(`User cancelled text input`);n[String(e)]=String(t.value??``)}else n[String(e)]=String(t.value??``)}}return n}:void 0,showTools:typeof M?.showTools==`boolean`?M.showTools:void 0,toolStyle:typeof M?.toolStyle==`string`?M.toolStyle:void 0,showStatus:typeof M?.showStatus==`boolean`?M.showStatus:void 0,showStatusLine:typeof M?.showStatusLine==`boolean`?M.showStatusLine:void 0,showFileChanges:typeof M?.showFileChanges==`boolean`?M.showFileChanges:void 0,emoji:typeof M?.emoji==`boolean`?M.emoji:void 0,promptContinue:n.promptContinue,autoContinue:n.autoContinue,hooks:n.hooks})},o=h.get();if(We===`plan`){let e=o?.getMiddlewares?.()??[],t=e.some(e=>e.name===`plan-mode`),n=e.some(e=>e.name===`parallel-subagent`);if((!t||!n)&&typeof o?.use==`function`)try{let e=await import(`./src-CMdXdryc.js`);if(!t&&typeof e.createPlanModeMiddleware==`function`){let t=e.createPlanModeMiddleware({insertEveryIteration:!0});o.use(t,`plan-mode`)}if(!n&&typeof e.createParallelSubagentMiddleware==`function`){let{fileSearchSpecialist:t,fileSearchSpecialistPrompt:n}=e;if(t&&n){let r=e.createParallelSubagentMiddleware({subagents:[t],executor:async(r,i)=>{if(r.subagent_type!==t.name)throw Error(`Unknown subagent type: ${r.subagent_type}`);let{ToolRegistry:o,Agent:s}=e,c=new o,l=h.get()?.tools,u=new Set(t.blockedTools||[]);for(let e of t.tools||[]){if(u.has(e))continue;let t=l?.get?.(e);t&&c.register(t)}let d=new s({name:r.subagent_type,systemPrompt:`${n}\n\nYour task: ${r.prompt}\n\nProvide a concise summary of your findings.`,model:h.get()?.model,tools:c}),f=await d.createSession({sessionId:i?.sessionId,maxIterations:a});u.size>0&&f.disableTools(Array.from(u)),f.send(r.prompt);let p=``;for await(let e of f.receive())if(e.type===`done`){p=e.finalResponse||``;break}return{agentId:d.id,data:p}}});o.use(r,`parallel-subagent`)}}}catch{}}else typeof o?.removeMiddleware==`function`&&(o.removeMiddleware(`plan-mode`),o.removeMiddleware(`parallel-subagent`));let{messagesToAppend:s,meta:c}=await r({input:p,history:e.session.history.slice(0,-1),promptContinue:typeof M?.promptContinue==`boolean`?M.promptContinue:void 0,autoContinue:typeof M?.autoContinue==`boolean`?M.autoContinue:void 0});if(W.signal.aborted)throw Error(typeof W.signal?.reason==`string`?W.signal.reason:`sigint`);c.exitedPlanMode&&We===`plan`&&(We=`agent`,M.planMode=!1,process.stdout.write(`${F(`🤖`)}${R.green(`Auto-switched to agent mode`)} ${R.dim(`(ExitPlanMode detected)`)}\n`));let l=c;n(c),e.session.history.push(...s),await D(),K=l??K}catch(t){let n=t instanceof Error?t.message:String(t),r=t instanceof Error?t.name:``;Le>0&&Date.now()-Le<2e3&&(r===`AgentAbortError`||r===`AbortError`||n===`sigint`||n===`Canceled`)?(process.stdout.write(`${R.dim(`${F(`⛔`)}Canceled.`)}\n`),Le=0):process.stderr.write(`${n}\n`),e.session.history.splice(u),e.session.inputs.splice(l),g.length>0&&(q=v,$())}finally{G=!1,W=null,P&&Q()}};Pn=async()=>{let e=process.env.VISUAL||process.env.EDITOR||`vi`,{tmpdir:t}=await import(`node:os`),{spawnSync:n}=await import(`node:child_process`),{mkdtemp:r,readFile:i,rm:a,writeFile:o}=await import(`node:fs/promises`),s=e=>process.platform===`win32`?`"${String(e).replace(/"/g,`\\"`)}"`:`'${String(e).replace(/'/g,`'\\''`)}'`,c=await r(w.join(t(),`goatchain-edit-`)),l=w.join(c,`message.md`);await o(l,``,`utf8`);let u=!!V.paused;u||B.pause();try{let t=n(`${e} ${s(l)}`,{stdio:`inherit`,shell:!0});if(typeof t.status==`number`&&t.status!==0){process.stdout.write(`${F(`❌`)}Editor exited with status ${t.status}\n`);return}let r=String(await i(l,`utf8`)??``).replace(/\r\n/g,`
57
57
  `).trim();if(!r){X(`Canceled (empty message).`);return}await Wn(r)}finally{u||B.resume(),await a(c,{recursive:!0,force:!0})}};let Gn=async()=>{let e=_.get(),t=e?.modelId?String(e.modelId):``,n=String(process.env.GOATCHAIN_MODEL_PRESETS??``).split(`,`).map(e=>e.trim()).filter(Boolean),r=ae.map(e=>e.modelId),i=[t,...n,...r].filter(Boolean),a=[...new Set(i)].slice(0,20);if(!I()){if(!process.stdout.isTTY){process.stdout.write([`model: ${p}/${e?.modelId??``}`,`Set with: /model <id>`,``].join(`
58
58
  `));return}let n=await new Promise(e=>B.question(`Model id (current: ${t||`∅`}): `,e)),r=String(n??``).trim();if(!r)return;typeof e?.setModelId==`function`&&e.setModelId(r),await D(),process.stdout.write(`${F(`🤖`)}model set: ${p}/${e.modelId}\n`);return}await Wt(async()=>{let t=await Te({message:`Select model`,options:[...a.map(e=>({value:e,label:e})),{value:`__custom__`,label:`Custom…`}],initialValue:0});if(!t.ok)return;let n=String(t.value);if(n===`__custom__`){let e=await Oe({message:`Model id`,placeholder:`e.g. gpt-4o-mini`});if(!e.ok)return;n=String(e.value).trim()}n&&(typeof e?.setModelId==`function`&&e.setModelId(n),await D(),process.stdout.write(`${F(`🤖`)}model set: ${p}/${e.modelId}\n`))})};Fn=async()=>{let e=_.get();if(!I()){if(!process.stdout.isTTY){process.stdout.write([`Settings:`,`- /base-url <url>`,`- /api-key <key>`,`- /web-search-key <key> (Serper)`,`- /set maxTokens <n>`,`- Set env GOATCHAIN_AUTO_APPROVE=1 to skip approval prompts.`,``].join(`
59
59
  `));return}for(;;){let e=await new Promise(e=>B.question(`Settings: [1] base-url [2] api-key [3] webSearch [4] temperature [5] contextLimit [6] outputLimit [7] interleavedThinking [8] autoApprove (empty=cancel): `,e)),t=String(e??``).trim();if(!t)return;if(t===`1`||t.toLowerCase()===`base-url`){let e=await new Promise(e=>B.question(`Base URL: `,e)),t=String(e??``).trim();if(!t)continue;await C(t),process.stdout.write(`${F(`🌐`)}baseUrl set: ${S.get()??``}\n`);continue}if(t===`2`||t.toLowerCase()===`api-key`){process.stdout.write(`For security, use /api-key <key> (note: your shell history may record it) or set OPENAI_API_KEY.
@@ -1 +1 @@
1
- import"./openai-Ba5c3VJv.js";import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as m,P as h,R as g,S as _,T as v,U as y,V as b,W as x,X as S,Y as C,_ as w,a as T,b as E,c as D,d as O,f as k,g as A,h as j,i as M,j as N,k as P,l as F,m as I,n as L,o as R,p as z,q as B,r as V,s as H,t as U,u as W,v as G,w as K,x as q,y as J,z as Y}from"./src-KHMs2spV.js";export{V as ACPAgent,i as Agent,t as AgentAbortError,b as AgentMaxIterationsError,q as AskUserTool,E as AstGrepReplaceTool,J as AstGrepSearchTool,Y as BaseHook,x as BaseSession,y as BaseSessionManager,_ as BaseTool,G as BashTool,w as EditTool,m as FileStateStore,L as FilteredToolRegistry,A as GlobTool,j as GrepTool,g as HookManager,h as InMemoryModelHealth,r as InMemoryStateStore,a as ModelError,T as ProtocolConverter,I as ReadTool,p as RetryPolicy,e as Session,M as SessionRouter,l as StateKeys,P as StateStore,z as TodoPlanTool,k as TodoWriteTool,U as ToolRegistry,O as WebSearchTool,W as WriteTool,d as compose,o as compressSessionManually,u as createContextCompressionMiddleware,c as createInitialLoopState,f as createModel,N as createOpenAIAdapter,D as createParallelSubagentMiddleware,F as createPlanModeMiddleware,s as ensureNotAborted,n as errorContent,R as fileSearchSpecialist,H as fileSearchSpecialistPrompt,C as fromLoopCheckpoint,K as imageContent,B as injectSystemReminderToLastUserMessage,v as textContent,S as toLoopCheckpoint};
1
+ import"./openai-Ba5c3VJv.js";import{A as e,B as t,C as n,D as r,E as i,F as a,G as o,H as s,I as c,J as l,K as u,L as d,M as f,N as p,O as m,P as h,R as g,S as _,T as v,U as y,V as b,W as x,X as S,Y as C,_ as w,a as T,b as E,c as D,d as O,f as k,g as A,h as j,i as M,j as N,k as P,l as F,m as I,n as L,o as R,p as z,q as B,r as V,s as H,t as U,u as W,v as G,w as K,x as q,y as J,z as Y}from"./src-DDLca7F5.js";export{V as ACPAgent,i as Agent,t as AgentAbortError,b as AgentMaxIterationsError,q as AskUserTool,E as AstGrepReplaceTool,J as AstGrepSearchTool,Y as BaseHook,x as BaseSession,y as BaseSessionManager,_ as BaseTool,G as BashTool,w as EditTool,m as FileStateStore,L as FilteredToolRegistry,A as GlobTool,j as GrepTool,g as HookManager,h as InMemoryModelHealth,r as InMemoryStateStore,a as ModelError,T as ProtocolConverter,I as ReadTool,p as RetryPolicy,e as Session,M as SessionRouter,l as StateKeys,P as StateStore,z as TodoPlanTool,k as TodoWriteTool,U as ToolRegistry,O as WebSearchTool,W as WriteTool,d as compose,o as compressSessionManually,u as createContextCompressionMiddleware,c as createInitialLoopState,f as createModel,N as createOpenAIAdapter,D as createParallelSubagentMiddleware,F as createPlanModeMiddleware,s as ensureNotAborted,n as errorContent,R as fileSearchSpecialist,H as fileSearchSpecialistPrompt,C as fromLoopCheckpoint,K as imageContent,B as injectSystemReminderToLastUserMessage,v as textContent,S as toLoopCheckpoint};
@@ -109,7 +109,7 @@ Messages to summarize:
109
109
  ---
110
110
 
111
111
  `),r)}],a=``;for await(let e of t.stream({messages:i,maxOutputTokens:1e3}))if(e.type===`delta`&&e.chunk.kind===`text`)a+=e.chunk.text;else if(e.type===`response_end`)break;return a}function he(e,t,n){let r=e.includes(`{{toolOutputs}}`),i=e.includes(`{{existingSummary}}`),a=n??``;return r||i?e.split(`{{toolOutputs}}`).join(t).split(`{{existingSummary}}`).join(a):`${e}\n\n${a.length>0?`Existing summary:\n${a}\n\nTool outputs to summarize:\n${t}`:`Tool outputs to summarize:\n${t}`}`}async function ge(e){let{sessionId:t,fullMessages:n,model:r,stateStore:i,summaryPrompt:a=ae}=e,o=[];for(let e of n)if(e.role===`tool`){let t=e,n=typeof t.content==`string`?t.content:JSON.stringify(t.content);o.push({name:t.name,content:n})}let s=o;if(o.length===0){let e=[];for(let t of n)if(t.role===`user`||t.role===`assistant`){let n;n=typeof t.content==`string`?t.content:Array.isArray(t.content)?t.content.map(e=>e.type===`text`?e.text:e.type===`image`?`[Image]`:`[Other content]`).join(`
112
- `):JSON.stringify(t.content),e.push({name:t.role===`user`?`user_message`:`assistant_message`,content:`${t.role===`user`?`User`:`Assistant`}: ${n}`})}if(e.length===0)return{summary:``,messageCount:n.length,toolOutputCount:0};s=e}let c=(await me(s,r,a,void 0)).trim();if(c.length===0)return{summary:``,messageCount:n.length,toolOutputCount:o.length};let l=await i.load(t,I.COMPRESSION),u=Date.now(),d={lastStats:l?.lastStats,history:l?.history??[],summary:c,updatedAt:u};return await i.save(t,I.COMPRESSION,d),{summary:c,messageCount:n.length,toolOutputCount:o.length}}var _e=class{setModelOverride(e){this.configOverride||={},this.configOverride.model=e,this.updatedAt=Date.now()}clearModelOverride(){this.configOverride&&(delete this.configOverride.model,this.updatedAt=Date.now())}setSystemPromptOverride(e){this.configOverride||={},this.configOverride.systemPromptOverride=e,this.updatedAt=Date.now()}clearSystemPromptOverride(){this.configOverride&&(delete this.configOverride.systemPromptOverride,this.updatedAt=Date.now())}disableTools(e){this.configOverride||={},this.configOverride.disabledTools=[...this.configOverride.disabledTools??[],...e],this.updatedAt=Date.now()}enableAllTools(){this.configOverride&&(delete this.configOverride.disabledTools,this.updatedAt=Date.now())}setStatus(e,t){this.status=e,this.errorMessage=t,this.updatedAt=Date.now()}markActive(){this.lastActiveAt=Date.now(),this.updatedAt=Date.now()}addMessage(e){this.messages.push(e),this.markActive()}getLastMessagePreview(e=100){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1],n=typeof t.content==`string`?t.content:JSON.stringify(t.content);return n.length>e?`${n.substring(0,e)}...`:n}addUsage(e){this.usage.promptTokens+=e.promptTokens,this.usage.completionTokens+=e.completionTokens,this.usage.totalTokens+=e.totalTokens,this.updatedAt=Date.now()}recordResponse(e){let t=(this.avgResponseTime??0)*this.responseCount;this.responseCount++,this.avgResponseTime=(t+e)/this.responseCount,this.updatedAt=Date.now()}incrementToolCallCount(){this.toolCallCount++,this.updatedAt=Date.now()}toSnapshot(){let e={status:this.status,updatedAt:this.updatedAt,lastActiveAt:this.lastActiveAt,title:this.title,errorMessage:this.errorMessage},t={messages:[...this.messages],messageCount:this.messages.length,lastMessagePreview:this.getLastMessagePreview(),toolCallCount:this.toolCallCount},n={usage:{...this.usage},responseCount:this.responseCount,avgResponseTime:this.avgResponseTime};return{id:this.id,createdAt:this.createdAt,state:e,configOverride:this.configOverride?{...this.configOverride}:void 0,context:t,stats:n}}restoreFromSnapshot(e){this.status=e.state.status,this.updatedAt=e.state.updatedAt,this.lastActiveAt=e.state.lastActiveAt,this.title=e.state.title,this.errorMessage=e.state.errorMessage,this.configOverride=e.configOverride?{...e.configOverride}:void 0,this.messages=[...e.context.messages],this.toolCallCount=e.context.toolCallCount,this.usage={...e.stats.usage},this.responseCount=e.stats.responseCount,this.avgResponseTime=e.stats.avgResponseTime}},ve=class{},L=class extends Error{constructor(e=`Agent execution aborted`){super(e),this.name=`AgentAbortError`}},ye=class extends Error{iterations;constructor(e,t){super(t??`Agent exceeded maximum iterations (${e})`),this.name=`AgentMaxIterationsError`,this.iterations=e}},be=class extends Error{constructor(e=`Agent execution paused`){super(e),this.name=`AgentPauseError`}};function R(e,t){if(!e?.aborted)return;let n=e?.reason;throw n instanceof Error?n:new L(typeof n==`string`?n:t?`${t} aborted`:`Agent execution aborted`)}var xe=class{},Se=class{hooks;constructor(e){this.hooks=e??{}}async executePreToolUse(e){let t=this.hooks.preToolUse;if(!t||t.length===0)return{allow:!0};let n=e.toolCall;for(let r of t){let t=await r({...e,toolCall:n});if(!t.allow)return{allow:!1,modifiedToolCall:t.modifiedToolCall};t.modifiedToolCall&&(n=t.modifiedToolCall)}return n===e.toolCall?{allow:!0}:{allow:!0,modifiedToolCall:n}}async executePostToolUse(e,t){let n=this.hooks.postToolUse;if(!(!n||n.length===0))for(let r of n)await r(e,t)}async executePostToolUseFailure(e,t){let n=this.hooks.postToolUseFailure;if(!(!n||n.length===0))for(let r of n)await r(e,t)}};function Ce(e){return(t,n)=>{let r=-1,i=async(t,a)=>{if(t<=r)throw Error(`next() called multiple times`);if(r=t,t===e.length)return n?await n(a):a;let o=e[t];return o(a,e=>i(t+1,e))};return i(0,t)}}function we(e,t,n){let r=[{role:`system`,content:n},...e.messages??[],{role:`user`,content:e.input}];return{sessionId:e.sessionId??``,agentId:t,messages:r,iteration:0,pendingToolCalls:[],currentResponse:``,shouldContinue:!0,usage:{promptTokens:0,completionTokens:0,totalTokens:0},metadata:{}}}var z=class extends Error{code;retryable;status;constructor(e,t){super(e),this.name=`ModelError`,this.code=t.code,this.retryable=t.retryable??!1,this.status=t.status}},Te=class{state=new Map;get(e){return this.state.get(this.keyOf(e))||{failures:0,nextRetryAt:0}}markSuccess(e){this.state.set(this.keyOf(e),{failures:0,nextRetryAt:0})}markFailure(e,t){let n=this.get(e).failures+1,r=Math.min(t.maxDelayMs,t.baseDelayMs*2**Math.min(8,n-1));this.state.set(this.keyOf(e),{failures:n,nextRetryAt:t.now+r,lastError:{code:t.code,message:t.message}})}isAvailable(e,t){return this.get(e).nextRetryAt<=t}keyOf(e){return`${e.provider}:${e.modelId}`}},Ee=class extends Te{},De=class{constructor(e,t){this.health=e,this.fallbackOrder=t}select(e){let{now:t}=e,n=this.fallbackOrder.filter(e=>this.health.isAvailable(e,t));return n.length?n:this.fallbackOrder}},Oe=class{static isRetryableStatus(e){return e===408||e===409||e===429||e>=500&&e<=599}static async sleep(e,t){return e<=0?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{a(),n()},e);function a(){clearTimeout(i),t&&t.removeEventListener(`abort`,o)}function o(){a(),r(Error(`Aborted`))}if(t){if(t.aborted)return o();t.addEventListener(`abort`,o)}})}};function ke(e=`req`){let t=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${t}`}var Ae=class e{maxAttempts;baseDelayMs;maxDelayMs;strategy;jitter;multiplier;_previousDelay;constructor(e={}){this.maxAttempts=e.maxAttempts??3,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.strategy=e.strategy??`exponential`,this.jitter=e.jitter??`equal`,this.multiplier=e.multiplier??2,this._previousDelay=this.baseDelayMs}getDelay(e){let t;switch(this.strategy){case`exponential`:t=this.baseDelayMs*this.multiplier**(e-1);break;case`linear`:t=this.baseDelayMs*e;break;case`fixed`:t=this.baseDelayMs;break}return t=Math.min(t,this.maxDelayMs),t=this.applyJitter(t),this._previousDelay=t,Math.floor(t)}applyJitter(e){switch(this.jitter){case`full`:return Math.random()*e;case`equal`:return e/2+Math.random()*e/2;case`decorrelated`:return Math.min(this.maxDelayMs,Math.random()*(this._previousDelay*3-this.baseDelayMs)+this.baseDelayMs);case`none`:default:return e}}canRetry(e){return e<this.maxAttempts}reset(){this._previousDelay=this.baseDelayMs}toString(){return`RetryPolicy(${this.strategy}, max=${this.maxAttempts}, base=${this.baseDelayMs}ms, cap=${this.maxDelayMs}ms, jitter=${this.jitter})`}static default=new e;static aggressive=new e({maxAttempts:5,baseDelayMs:1e3,maxDelayMs:6e4});static gentle=new e({maxAttempts:3,baseDelayMs:2e3,maxDelayMs:3e4,jitter:`full`})};function je(e){let t=e.adapters??(e.adapter?[e.adapter]:void 0);if(!t||t.length===0)throw new z("Missing adapter(s). Provide `adapter` for the simple case, or `adapters` for multi-provider routing.",{code:`missing_adapter`,retryable:!1});if(e.adapter&&e.adapters)throw new z("Provide either `adapter` or `adapters`, not both.",{code:`invalid_options`,retryable:!1});let n=new Map(t.map(e=>[e.provider,e])),r=e.health??new Ee,i=e.fallback?.onPartialOutput??`stop`,a=e.fallback?.onPartialToolCalls??`stop`,o=e.routing?.fallbackOrder??(()=>{let e=[];for(let n of t)n.defaultModelId&&e.push({provider:n.provider,modelId:n.defaultModelId});if(e.length===0)throw new z(`No routing configuration and no adapter with defaultModelId provided. Either provide options.routing.fallbackOrder or set defaultModelId on your adapters.`,{code:`missing_routing`,retryable:!1});return e})(),s=new De(r,o),c=new Ae({maxAttempts:e.retry?.maxAttemptsPerModel??3,baseDelayMs:e.retry?.baseDelayMs??500,maxDelayMs:e.retry?.maxDelayMs??3e4,strategy:e.retry?.strategy??`exponential`,jitter:e.retry?.jitter??`equal`}),l=e.timeoutMs??6e4;function u(e){let t=n.get(e.provider);if(!t)throw new z(`No adapter for provider: ${e.provider}`,{code:`adapter_missing`,retryable:!1});return t}async function*d(t){let n=Date.now(),o=t.requestId||ke(`req`),{model:d,...f}=t,p=t.model?[t.model]:s.select({now:n}),m;for(let n of p){let s=u(n),d=t.timeoutMs??l,p=!1,h=!1,g=0,_=new AbortController,v=t.signal,y=setTimeout(()=>_.abort(),d),b=()=>_.abort();v&&(v.aborted?_.abort():v.addEventListener(`abort`,b));let x={...f,requestId:o,model:n,stream:t.stream??!0,signal:_.signal,timeoutMs:d};try{for(let t=1;t<=c.maxAttempts;t++){g=t;try{for await(let e of s.stream({request:x}))e.type===`delta`&&(p=!0,e.chunk.kind===`tool_call_delta`&&(h=!0)),yield e;r.markSuccess(n);return}catch(r){m=r;let i=Me(r),a=i.retryable;if(p||!a||!c.canRetry(t))throw i;let o=c.getDelay(t);e.retry?.onRetry?.({attempt:t,maxAttempts:c.maxAttempts,delayMs:o,error:{code:i.code,message:i.message,retryable:i.retryable},model:n,request:x}),await Oe.sleep(o,_.signal)}}}catch(e){let t=Me(e);r.markFailure(n,{now:Date.now(),baseDelayMs:c.baseDelayMs,maxDelayMs:c.maxDelayMs,code:t.code,message:t.message});let s=!(h&&a===`stop`||p&&i===`stop`);if(yield{type:`error`,requestId:o,terminal:!s,model:n,attempt:g||1,source:`client`,error:{code:t.code,message:t.message,retryable:t.retryable}},!s)throw t;m=t;continue}finally{clearTimeout(y),v&&v.removeEventListener(`abort`,b)}}throw Me(m||new z(`All models failed`,{code:`all_models_failed`}))}async function f(e){let t=``,n=``,r=`error`,i,a,o=e.requestId||``,s=!1;for await(let c of d({...e,stream:!0}))c.type===`response_start`?(s=!0,o=c.requestId,a=c.model,t=``):c.type===`delta`&&c.chunk.kind===`text`?t+=c.chunk.text:c.type===`response_end`?(n=t,r=c.stopReason,i=c.usage):c.type===`error`&&(r=`error`);if(!a)throw new z(`Missing response_start from adapter`,{code:`protocol_error`,retryable:!1});return{requestId:o,model:a,text:s?n:t,stopReason:r,usage:i}}return{get modelId(){return o[0]?.modelId??`unknown`},get modelRef(){return o[0]},get modelRefs(){return[...o]},setModelId(e){let t=o[0];if(!t)throw new z(`No primary model to update`,{code:`no_primary_model`,retryable:!1});o[0]={provider:t.provider,modelId:e}},stream:d,run:f}}function Me(e){if(e instanceof z)return e;if(e&&typeof e==`object`){let t=typeof e.status==`number`?e.status:void 0,n=typeof e.code==`string`?e.code:t?`http_${t}`:`unknown_error`;return new z(typeof e.message==`string`?e.message:`Unknown error`,{code:n,retryable:t?Oe.isRetryableStatus(t):!1,status:t})}return new z(String(e||`Unknown error`),{code:`unknown_error`,retryable:!1})}function Ne(e){function t(e,t){if(typeof e!=`string`)return``;let n=e.trim();return n?/^data:/i.test(n)||/^https?:\/\//i.test(n)?n:typeof t==`string`&&t.trim()?`data:${t.trim()};base64,${n}`:n:``}if(typeof e==`string`)return e.trim().length===0?``:e;if(e==null)return``;if(typeof e==`object`&&`type`in e){let n=e;if(n.type===`text`&&n.text)return n.text;if(n.type===`image`){let e=t(n.data??n.source?.data,n.mimeType??n.source?.media_type??n.source?.mimeType);return e?[{type:`image_url`,image_url:{url:e}}]:``}}if(Array.isArray(e)){let n=[];for(let r of e)if(typeof r==`string`)n.push({type:`text`,text:r});else if(r&&typeof r==`object`&&`type`in r){let e=r;if(e.type===`text`&&e.text)n.push({type:`text`,text:e.text});else if(e.type===`image`){let r=t(e.data??e.source?.data,e.mimeType??e.source?.media_type??e.source?.mimeType);r&&n.push({type:`image_url`,image_url:{url:r}})}}return n.length>0?n:``}return String(e)}function Pe(e){return{...e,content:Ne(e.content)}}function Fe(e,t){return typeof t==`string`&&/deepseek/i.test(t)?!0:/^deepseek-/i.test(e)}function Ie(e={}){let t=e.baseUrl;function n(){if(typeof e.apiKey==`function`){let t=e.apiKey();if(typeof t==`string`){let e=t.trim();if(!e)throw new z(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return e}if(t!=null)throw new z(`Invalid apiKey provider`,{code:`invalid_api_key`,retryable:!1})}if(typeof e.apiKey==`string`){let t=e.apiKey.trim();if(!t)throw new z(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return t}let t=typeof process<`u`?process.env?.OPENAI_API_KEY:void 0;if(typeof t!=`string`||!t.trim())throw new z(`Missing OPENAI_API_KEY`,{code:`missing_api_key`,retryable:!1});return t.trim()}function i(){let i=n();return typeof t==`string`&&/\/chat\/completions\/?$/.test(t)?new r({apiKey:i,organization:e.organization,project:e.project,baseURL:`https://api.openai.com/v1`,fetch:(e,n)=>fetch(t,n)}):new r({apiKey:i,organization:e.organization,project:e.project,baseURL:t||void 0})}function a(e){return{provider:`openai`,modelId:e.model.modelId}}function o(e){if(e instanceof z)return e;let t=typeof e?.status==`number`?e.status:void 0;return new z(typeof e?.message==`string`?e.message:`OpenAI error`,{code:typeof e?.code==`string`?e.code:t?`openai_http_${t}`:`openai_error`,retryable:t?Oe.isRetryableStatus(t):!1,status:t})}async function*s(n){let{request:r}=n,s=r.requestId||ke(`req`),c=i(),l=r.model.modelId,u=e.compat?.interleavedThinking,d=typeof u==`boolean`?u:Fe(l,t),f=r.stream!==!1,p=[];if(r.messages&&Array.isArray(r.messages))for(let e of r.messages){let t=Pe(e);if(!d&&t&&typeof t==`object`)`reasoning_content`in t&&delete t.reasoning_content;else if(d&&t?.role===`assistant`&&Array.isArray(t?.tool_calls)&&t.tool_calls.length>0){let e=t.reasoning_content;(typeof e!=`string`||e.length===0)&&(t.reasoning_content=`.`)}p.push(t)}else typeof r.instructions==`string`&&r.instructions.length>0&&p.push({role:`system`,content:r.instructions}),p.push({role:`user`,content:r.input});let m=(()=>{let e=r.reasoning?.effort;if(typeof e==`string`&&(e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`))return e})(),h={model:l,messages:p,stream:f,stream_options:f?{include_usage:!0}:void 0,metadata:r.metadata??void 0,reasoning_effort:m,max_completion_tokens:r.maxOutputTokens??void 0,stop:r.stop??void 0,temperature:r.temperature??void 0,top_p:r.topP??1};r.tools&&Array.isArray(r.tools)&&r.tools.length>0&&(h.tools=r.tools);try{if(yield{type:`response_start`,requestId:s,model:a(r)},!f){let e=await c.chat.completions.create({...h,stream:!1},{signal:r.signal,timeout:r.timeoutMs}),t=Array.isArray(e?.choices)?e.choices[0]:void 0,n=t?.message,i=typeof n?.reasoning_content==`string`?n.reasoning_content:``;i.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:i}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:i}});let a=typeof n?.content==`string`?n.content:``;a.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:a}});let o=Array.isArray(n?.tool_calls)?n.tool_calls:[];for(let e=0;e<o.length;e++){let t=o[e],n=typeof t?.id==`string`?t.id:`call_${e}`,r=typeof t?.function?.name==`string`?t.function.name:void 0,i=typeof t?.function?.arguments==`string`?t.function.arguments:void 0;(i||r)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:i}})}yield{type:`response_end`,requestId:s,stopReason:Le(t?.finish_reason),usage:e?.usage};return}let e=await c.chat.completions.create({...h,stream:!0},{signal:r.signal,timeout:r.timeoutMs}),t=null,n,i=new Map,o=!1,l=``;for await(let r of e){r?.usage!=null&&(n=r.usage);let e=Array.isArray(r?.choices)?r.choices:[];for(let n of e){n?.finish_reason!=null&&(t=n.finish_reason);let e=n?.delta,r=e?.reasoning_content;typeof r==`string`&&r.length>0&&(o||(o=!0,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}}),l+=r,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:r}});let a=e?.content;typeof a==`string`&&a.length>0&&(o&&(o=!1,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:a}});let c=Array.isArray(e?.tool_calls)?e.tool_calls:[];for(let e of c){let t=typeof e?.index==`number`?e.index:0,n=i.get(t)||(typeof e?.id==`string`?e.id:`call_${t}`);i.set(t,n);let r=typeof e?.function?.name==`string`?e.function.name:void 0,a=typeof e?.function?.arguments==`string`?e.function.arguments:void 0;(r||a)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:a}})}}}o&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`response_end`,requestId:s,stopReason:Le(t),usage:n}}catch(e){throw e?.name===`AbortError`?new z(`Aborted`,{code:`aborted`,retryable:!1}):o(e)}}return{provider:`openai`,defaultModelId:e.defaultModelId,stream:s}}function Le(e){return e===`tool_calls`||e===`function_call`?`tool_call`:e===`length`?`length`:e===`content_filter`?`error`:`final`}function Re(e){if(e){if(e instanceof z)return{code:e.code,message:e.message,status:e.status,retryable:e.retryable};if(e instanceof Error){let t=e,n=typeof t.code==`string`?t.code:void 0,r=typeof t.status==`number`?t.status:void 0,i=typeof t.retryable==`boolean`?t.retryable:void 0;return{code:n,message:e.message,status:r,retryable:i}}return{message:String(e)}}}function ze(e){let t=e?.function?.arguments;if(typeof t==`string`)try{return JSON.parse(t),e}catch(n){let r=n instanceof Error?n.message:String(n);return{...e,function:{...e.function,arguments:JSON.stringify({_raw:t,_parseError:r})}}}return t&&typeof t==`object`?{...e,function:{...e.function,arguments:JSON.stringify(t)}}:{...e,function:{...e.function,arguments:JSON.stringify(t??null)}}}function Be(e){let t=!1,n=e.map(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return e;let n=e.tool_calls;if(!Array.isArray(n)||n.length===0)return e;let r=!1,i=n.map(e=>{let t=ze(e);return t!==e&&(r=!0),t});return r?(t=!0,{...e,tool_calls:i}):e});return t?n:e}var B=class e extends _e{id;agentId;createdAt;status;title;updatedAt;lastActiveAt;errorMessage;configOverride;messages;toolCallCount;usage;responseCount;avgResponseTime;_stateStore;toolEventQueue=[];_autoSave;_modelClient;_tools;_middlewares;_systemPrompt;_agentName;_onUsage;_hasCheckpoint;_checkpointRestored=!1;_pendingInput=null;_isReceiving=!1;_hooks;_modelOverride;_maxIterations;_requestParams;_emitSessionCreatedEvent;_sessionCreatedEventEmitted=!1;getDisabledToolNames(){let e=this.configOverride?.disabledTools;return!e||e.length===0?new Set:new Set(e)}isToolDisabled(e){return this.getDisabledToolNames().has(e)}collectBlockedTools(e){let t=new Set;for(let n of this._middlewares)if(typeof n.__getBlockedTools==`function`){let r=n.__getBlockedTools(e);(Array.isArray(r)?r:Array.from(r)).forEach(e=>t.add(e))}return t}isToolBlocked(e,t){let n=e.metadata?.blockedTools;return n?n instanceof Set?n.has(t):Array.isArray(n)?n.includes(t):!1:!1}getToolsForModel(e){let t=this._tools?.toOpenAIFormat();if(!t||t.length===0)return;let n=this.getDisabledToolNames(),r=n.size===0?t:t.filter(e=>!n.has(e.function.name)),i=e.metadata?.blockedTools;return i&&i.size>0&&(r=r.filter(e=>!i.has(e.function.name))),r.length>0?r:void 0}getEffectiveSystemPrompt(){let e=this.configOverride?.systemPromptOverride;return typeof e==`string`?e:this._systemPrompt}constructor(e,t,n,r){if(super(),this._stateStore=e,this.id=t,n)this.createdAt=n.createdAt,this.restoreFromSnapshot(n);else{let e=Date.now();this.createdAt=e,this.status=`active`,this.updatedAt=e,this.lastActiveAt=e,this.messages=[],this.toolCallCount=0,this.usage={promptTokens:0,completionTokens:0,totalTokens:0},this.responseCount=0}this._autoSave=!0,this._modelClient=r?.modelClient,this._tools=r?.tools,this._middlewares=r?.middlewares??[],this._systemPrompt=r?.systemPrompt,this._agentName=r?.agentName,this._onUsage=r?.onUsage,this._hasCheckpoint=r?.hasCheckpoint??!1,this._hooks=r?.hooks,this._modelOverride=r?.model,this._maxIterations=r?.maxIterations,this._requestParams=r?.requestParams,this._emitSessionCreatedEvent=r?.emitSessionCreatedEvent===!0}get hasCheckpoint(){return this._hasCheckpoint}send(e,t){if(this._ensureRuntimeConfigured(!0),this._isReceiving)throw Error(`Cannot send while receiving messages`);if(this._pendingInput)throw Error(`Pending input already exists; call receive() to consume it before sending another message`);this._pendingInput={input:e,options:t}}async*receive(e){if(this._isReceiving)throw Error(`Cannot receive concurrently`);if(!this._hasCheckpoint&&!this._pendingInput)throw Error(`Nothing to receive; call send() first (or resume from a session that has a checkpoint)`);this._isReceiving=!0;try{if(this._emitSessionCreatedEvent&&!this._sessionCreatedEventEmitted&&(this._sessionCreatedEventEmitted=!0,yield{type:`session_created`,agentId:this.agentId,sessionId:this.id}),!this._hasCheckpoint&&this._pendingInput&&this._stateStore)try{let e=await this._stateStore.loadCheckpoint(this.id);e&&Array.isArray(e.pendingToolCalls)&&e.pendingToolCalls.length>0&&(this._hasCheckpoint=!0,this._checkpointRestored=!1)}catch{}if(this._hasCheckpoint&&!this._checkpointRestored&&this._pendingInput){let{input:t,options:n}=this._pendingInput;this._pendingInput=null;let r=await this._stateStore.loadCheckpoint(this.id);if(!r)throw Error(`Checkpoint not found for sessionId: ${this.id}`);let i=A(r);i.sessionId!==this.id&&(i.sessionId=this.id),i.metadata={...i.metadata,_pendingUserInput:t};let a=this._requestParams??r.requestParams,o=n??e;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:o?.signal,model:this.getRuntimeModelOverride(),toolContext:o?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,Date.now()),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(this._hasCheckpoint&&!this._checkpointRestored){let t=e??this._pendingInput?.options;if(yield*this._stream(void 0,t),!this._pendingInput)return}if(this._pendingInput){let{input:e,options:t}=this._pendingInput;this._pendingInput=null,yield*this._stream(e,t)}}finally{this._isReceiving=!1}}async*receiveWithApprovals(e,t){let n=t?.toolContext,r={...n??{},approval:{...n?.approval??{},decisions:{...n?.approval?.decisions??{},...e}}};yield*this.receive({...t,toolContext:r})}async*_stream(e,t){this._ensureRuntimeConfigured(e!==void 0);let n=Date.now(),r=this.getRuntimeModelOverride(),i;if(this._hasCheckpoint&&!this._checkpointRestored){let e=await this._stateStore.loadCheckpoint(this.id);if(!e)throw Error(`Checkpoint not found for sessionId: ${this.id}`);i=A(e),i.sessionId!==this.id&&(i.sessionId=this.id);let a=this._requestParams??e.requestParams;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,n),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(e===void 0)throw Error(`Input is required to stream`);if(!this.title&&this.messages.length===0){let t=this.extractTextFromContent(e);t&&(this.title=this.createTitle(t))}let a=this.messages.filter(e=>e.role!==`system`);i=we({sessionId:this.id,input:e,messages:a},this.agentId,this.getEffectiveSystemPrompt()??``),yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:this._requestParams}),await this._finalizeRun(i,n)}resolveModelRef(e){if(e.provider)return{provider:e.provider,modelId:e.modelId};let t=(this._modelClient?.modelRefs??[]).find(t=>t.modelId===e.modelId);if(t)return t;let n=this._modelClient?.modelRef?.provider;if(n)return{provider:n,modelId:e.modelId}}getRuntimeModelOverride(){if(this.configOverride?.model){let e=this.resolveModelRef(this.configOverride.model);if(e)return e}return this._modelOverride}_ensureRuntimeConfigured(e){if(!this._modelClient)throw Error(`Session is not configured with a model client`);if(e&&this.getEffectiveSystemPrompt()===void 0)throw Error(`Session is not configured with a system prompt`)}extractTextFromContent(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text).join(` `):e&&typeof e==`object`&&e.type===`text`&&e.text||``}createTitle(e,t=50){let n=e.trim();return n.length<=t?n:`${n.substring(0,t).trim()}...`}_recordUsage(e){this._onUsage&&this._onUsage(e)}async executeModelStream(e,t,n,r,i){if(!this._modelClient)throw Error(`Session is not configured with a model client`);let a=[],o=e.sessionId,s=new Map,c=!1,l=!1,u=e=>{let t=s.get(e);if(t)return t;let n={argsText:``,started:!1};return s.set(e,n),n},d=(e,t)=>{let n=u(e);t&&!n.toolName&&(n.toolName=t),n.started||(n.started=!0,a.push({type:`tool_call_start`,callId:e,toolName:n.toolName,sessionId:o}))},f=(e,t,n)=>{let r=u(e);t&&!r.toolName&&(r.toolName=t),typeof n==`string`&&n.length>0&&(r.argsText+=n),d(e,r.toolName),a.push({type:`tool_call_delta`,callId:e,toolName:r.toolName,argsTextDelta:n,sessionId:o})},p=()=>{c||(c=!0,a.push({type:`text_start`,sessionId:o}))},m=()=>{!c||l||(l=!0,a.push({type:`text_end`,content:e.currentResponse,sessionId:o}))},h=()=>{for(let[t,n]of s){if(!n.toolName)continue;let r={id:t,type:`function`,function:{name:n.toolName,arguments:n.argsText}};this._tools&&e.pendingToolCalls.push({toolCall:r}),a.push({type:`tool_call_end`,toolCall:r,sessionId:o})}s.clear()},g=(()=>{if(!i)return;let e={...i};return typeof e.maxOutputTokens!=`number`&&typeof i.maxTokens==`number`&&(e.maxOutputTokens=i.maxTokens),delete e.maxTokens,e})(),_=r?{model:r,messages:Be(e.messages),tools:n,signal:t,...g??{}}:{messages:Be(e.messages),tools:n,signal:t,...g??{}};try{for await(let n of this._modelClient.stream(_))if(R(t,`Session streaming`),n.type===`delta`)if(n.chunk.kind===`text`)p(),e.currentResponse+=n.chunk.text,a.push({type:`text_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_start`)a.push({type:`thinking_start`,sessionId:o});else if(n.chunk.kind===`thinking_delta`)e.currentThinking=(e.currentThinking??``)+n.chunk.text,a.push({type:`thinking_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_end`){let t=typeof n.chunk.text==`string`?n.chunk.text:``;t&&typeof e.currentThinking!=`string`&&(e.currentThinking=t);let r=typeof e.currentThinking==`string`?e.currentThinking:t;a.push({type:`thinking_end`,sessionId:o,...r?{content:r}:{}})}else n.chunk.kind===`tool_call_delta`&&f(n.chunk.callId,n.chunk.toolId,n.chunk.argsTextDelta);else if(n.type===`response_end`){m(),h(),e.lastModelStopReason=n.stopReason;let t=n.usage;if(t&&typeof t==`object`){let n=t;if(n.prompt_tokens||n.completion_tokens||n.total_tokens){let t={promptTokens:n.prompt_tokens??0,completionTokens:n.completion_tokens??0,totalTokens:n.total_tokens??0};e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.totalTokens+=t.totalTokens,this._recordUsage(t)}}}else if(n.type===`error`&&n.terminal!==!1){let t=n.error?.code??`model_error`;e.error=new z(n.error?.message??`Model error`,{code:t,retryable:n.error?.retryable}),e.shouldContinue=!1,e.stopReason=`error`}}catch(n){if(n instanceof L)throw n;if(t?.aborted)throw new L(typeof t?.reason==`string`?t.reason:`Agent execution aborted`);e.error=n instanceof Error?n:Error(String(n)),e.shouldContinue=!1,e.stopReason=`error`}finally{m(),s.size>0&&h()}return a}async executeToolCall(e,t,n,r){R(n,`Tool execution: ${e.toolCall.function.name}`);let i=r?new Se(r):void 0,a=e.toolCall.id,o=e.toolCall,s=o,c=e=>({sessionId:t.sessionId,agentId:t.agentId,toolCall:e,toolContext:t});if(i){let n=await i.executePreToolUse(c(s));if(!n.allow)return e.result=`Tool execution blocked by PreToolUse hook`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};n.modifiedToolCall&&(s={...n.modifiedToolCall,id:a,type:o.type})}let l=this._tools?.get(s.function.name);if(!l)return e.result=`Tool not found: ${s.function.name}`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};try{let n=typeof s.function.arguments==`string`?JSON.parse(s.function.arguments):s.function.arguments;return e.result=await l.execute(n,t),e.isError=!1,i&&await i.executePostToolUse(c(s),e.result),{type:`tool_result`,tool_call_id:a,result:e.result,sessionId:t.sessionId}}catch(n){let r=n instanceof Error?n:Error(String(n));return e.result=r.message,e.isError=!0,i&&await i.executePostToolUseFailure(c(s),r),{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId}}}createToolExecutionContext(e,t){return{sessionId:e.sessionId,agentId:e.agentId,signal:t,usage:e.usage,emitEvent:t=>{this.toolEventQueue.push({...t,sessionId:e.sessionId})}}}mergeStateResults(e,t){e.currentResponse=t.currentResponse,e.currentThinking=t.currentThinking,e.pendingToolCalls=t.pendingToolCalls,e.usage=t.usage,e.metadata=t.metadata}addToolResultToHistory(e,t){let n=t.result,r,i=t.isError;if(typeof n==`string`)r=n;else if(n&&typeof n==`object`&&`content`in n){let e=n;r=JSON.stringify(e.content),e.isError===!0&&(i=!0)}else r=JSON.stringify(n);e.messages.push({role:`tool`,tool_call_id:t.toolCall.id,content:r,...i?{isError:!0}:{}})}addAssistantMessageWithToolCalls(e){let t=typeof e.currentThinking==`string`?e.currentThinking:void 0;e.messages.push({role:`assistant`,content:e.currentResponse||``,tool_calls:e.pendingToolCalls.map(e=>ze(e.toolCall)),...t&&t.length>0?{reasoning_content:t}:{}})}addFinalAssistantMessage(e){e.currentResponse&&e.messages.push({role:`assistant`,content:e.currentResponse})}async*_streamWithState(e,t){let n=t.maxIterations??30,r=t.signal,i=Ce(this._middlewares),a=this.createToolExecutionContext(e,r),o=this._stateStore,s=o?.savePoint??`before`,c=o?.deleteOnComplete??!0,l=t.model?{modelId:t.model.modelId,provider:t.model.provider}:this._modelClient?{modelId:this._modelClient.modelId}:void 0;for(;e.shouldContinue;){if(R(r,`Session iteration ${e.iteration}`),e.iteration>=n){e.shouldContinue=!1,e.stopReason=`max_iterations`,yield{type:`done`,finalResponse:e.currentResponse,stopReason:`max_iterations`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId};break}if(yield{type:`iteration_start`,iteration:e.iteration,sessionId:e.sessionId},e.pendingToolCalls.length>0){try{yield*this.handleToolCalls(e,a,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:o,checkpointModelConfig:l,requestParams:t.requestParams})}catch(e){if(e instanceof be)return;throw e}if(e.metadata?._pendingUserInput){let t=e.metadata._pendingUserInput;delete e.metadata._pendingUserInput,e.messages.push({role:`user`,content:t})}continue}if(e.currentResponse=``,e.currentThinking=void 0,e.pendingToolCalls=[],e.lastModelStopReason=void 0,o&&(s===`before`||s===`both`)){let n=k(e,{agentName:this._agentName,modelConfig:l,requestParams:t.requestParams});await o.saveCheckpoint(n)}let u=[],d=await i(e,async e=>{R(r,`Session model call`);let n=this.collectBlockedTools(e);e.metadata.blockedTools=n;let i=this.getToolsForModel(e);return u=await this.executeModelStream(e,r,i,t.model,t.requestParams),e});if(this.mergeStateResults(e,d),o&&(s===`after`||s===`both`)){let n=k(e,{agentName:this._agentName,modelConfig:l,requestParams:t.requestParams});await o.saveCheckpoint(n)}for(let e of u)yield e;if(R(r,`Session iteration ${e.iteration}`),e.stopReason===`error`){yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:e.pendingToolCalls.length,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`error`,modelStopReason:e.lastModelStopReason,error:Re(e.error),usage:{...e.usage},sessionId:e.sessionId};break}if(e.pendingToolCalls.length>0)try{yield*this.handleToolCalls(e,a,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:o,checkpointModelConfig:l,requestParams:t.requestParams})}catch(e){if(e instanceof be)return;throw e}else yield*this.handleFinalResponse(e);if(!e.shouldContinue){o&&c&&await o.deleteCheckpoint(e.sessionId);break}}}static APPROVAL_REQUIRED_LEVELS=new Set([`high`,`critical`]);requiresApproval(t){return e.APPROVAL_REQUIRED_LEVELS.has(t)}async*handleToolCalls(e,t,n){let r=e.pendingToolCalls.length,i=n?.signal,a=n?.toolContextInput,o=a?.approval,s=o?.strategy??`high_risk`,c=o?.autoApprove!==!0,l=o?.decisions??{},u=e=>c?s===`all`?!0:this.requiresApproval(e):!1,d=t=>e.messages.some(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return!1;let n=e.tool_calls;return Array.isArray(n)&&n.some(e=>e?.id===t)}),f=t=>{d(t)||this.addAssistantMessageWithToolCalls(e)},p=t=>e.messages.some(e=>e&&typeof e==`object`&&e.role===`tool`&&e.tool_call_id===t),m=new Set,h=e=>{try{return typeof e.function.arguments==`string`?JSON.parse(e.function.arguments):e.function.arguments}catch(t){let n=t instanceof Error?t.message:String(t);return{_raw:e.function.arguments,_parseError:n}}},g=t=>{let n=[];for(let r=t;r<e.pendingToolCalls.length;r++){let t=e.pendingToolCalls[r];if(p(t.toolCall.id)||m.has(t.toolCall.id)||l[t.toolCall.id])continue;let i=this._tools?.get(t.toolCall.function.name),a=i?.riskLevel??`safe`;i&&this.isToolDisabled(t.toolCall.function.name)||i&&this.isToolBlocked(e,t.toolCall.function.name)||!i||!u(a)||(m.add(t.toolCall.id),n.push({type:`tool_approval_requested`,tool_call_id:t.toolCall.id,toolName:t.toolCall.function.name,riskLevel:a,args:h(t.toolCall),sessionId:e.sessionId}))}return n};if(e.metadata?.parallelMode===!0){let r=e.pendingToolCalls.filter(e=>{let t=e.toolCall.function.name;return t===`Task`||t.endsWith(`:Task`)});r.length>1&&(yield*this.executeTasksInParallel(r,e,t,n),e.pendingToolCalls=e.pendingToolCalls.filter(e=>!r.includes(e)))}for(let r=0;r<e.pendingToolCalls.length;r++){let o=e.pendingToolCalls[r];if(p(o.toolCall.id)){e.pendingToolCalls.splice(r,1),r--;continue}let s=o.toolCall.function.name,c=this._tools?.get(s),d=c?.riskLevel??`safe`;if(c&&this.isToolBlocked(e,s)){let t=`Tool "${s}" is blocked by middleware`;o.result=`Tool execution skipped: ${t}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:s,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}if(c&&this.isToolDisabled(s)){let t=`Tool "${s}" is disabled for this session`;o.result=`Tool execution skipped: ${t}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:s,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}if(c&&u(d)){let t=l[o.toolCall.id];if(!t){e.stopReason=`approval_required`;for(let e of g(r))yield e;let t=k(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for approval: ${s}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(t),yield{type:`requires_action`,kind:`tool_approval`,checkpoint:n?.stateStore?void 0:t,checkpointRef:n?.stateStore?{sessionId:t.sessionId,agentId:t.agentId}:void 0,sessionId:e.sessionId},this.messages=e.messages.filter(e=>e.role!==`system`),await this.save(),yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new be}if(!t.approved){let n=t.reason??`User denied approval`;o.result=`Tool execution skipped: ${n}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:o.toolCall.function.name,reason:n,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}}f(o.toolCall.id),this.toolEventQueue=[];let m=await this.executeToolCall(o,t,i,n?.hooks);for(let e of this.toolEventQueue)yield e;this.toolEventQueue=[];let h=m.type===`tool_result`&&(m.isError||m.result&&typeof m.result==`object`&&m.result.isError===!0);if(c&&c.name===`AskUserQuestion`&&h){let s=a?.askUser?.answers?.[o.toolCall.id];if(s){let a={...typeof o.toolCall.function.arguments==`string`?JSON.parse(o.toolCall.function.arguments):o.toolCall.function.arguments,answers:s};o.toolCall.function.arguments=JSON.stringify(a),this.toolEventQueue=[];let c=await this.executeToolCall(o,t,i,n?.hooks);for(let e of this.toolEventQueue)yield e;this.toolEventQueue=[],yield c,this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}else{yield m,e.stopReason=`approval_required`;let t=(typeof o.toolCall.function.arguments==`string`?JSON.parse(o.toolCall.function.arguments):o.toolCall.function.arguments)?.questions||[],r=k(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for user answers: ${c.name}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(r),this.messages=e.messages.filter(e=>e.role!==`system`),await this.save(),yield{type:`requires_action`,kind:`ask_user`,toolCallId:o.toolCall.id,questions:t,checkpoint:n?.stateStore?void 0:r,checkpointRef:n?.stateStore?{sessionId:r.sessionId,agentId:r.agentId}:void 0,sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new be}}yield m,this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--}e.pendingToolCalls=[],e.iteration++,yield{type:`iteration_end`,iteration:e.iteration-1,willContinue:!0,toolCallCount:r,usage:{...e.usage},sessionId:e.sessionId}}async*executeTasksInParallel(e,t,n,r){this.toolEventQueue=[];let i=[],a=!1,o=e.map(async e=>{let r=e.toolCall.function.name,a=this._tools?.get(r);if(!a)return{tc:e,result:`Tool "${r}" not found`,isError:!0,events:[]};try{let r=typeof e.toolCall.function.arguments==`string`?JSON.parse(e.toolCall.function.arguments):e.toolCall.function.arguments,o=`${t.sessionId}:subagent:${crypto.randomUUID()}`,s=[],c={...n,sessionId:o,emitEvent:e=>{let n={...e,sessionId:t.sessionId};s.push(n),i.push(n)}};return{tc:e,result:await a.execute(r,c),isError:!1,events:s}}catch(t){return{tc:e,result:`Task execution failed: ${t instanceof Error?t.message:String(t)}`,isError:!0,events:[]}}}),s=Promise.allSettled(o).then(e=>(a=!0,e));for(;!a||i.length>0;)if(i.length>0){let e=i.shift();e&&(yield e)}else a||await new Promise(e=>setTimeout(e,5));let c=await s;for(let[n,r]of c.entries()){let i=e[n];if(r.status===`fulfilled`){let{result:e,isError:t}=r.value;i.result=e,i.isError=t}else i.result=`Task execution rejected: ${r.reason}`,i.isError=!0;this.hasAssistantToolCallMessage(t,i.toolCall.id)||this.addAssistantMessageWithToolCalls(t),yield{type:`tool_result`,tool_call_id:i.toolCall.id,result:i.result,isError:i.isError,sessionId:t.sessionId},this.addToolResultToHistory(t,i)}}hasAssistantToolCallMessage(e,t){return e.messages.some(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return!1;let n=e.tool_calls;return Array.isArray(n)&&n.some(e=>e?.id===t)})}async*handleFinalResponse(e){e.shouldContinue=!1,e.stopReason=`final_response`,this.addFinalAssistantMessage(e),yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:0,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`final_response`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId}}async _finalizeRun(e,t){this.messages=e.messages.filter(e=>e.role!==`system`),e.usage.totalTokens>0&&this.addUsage(e.usage);let n=Date.now()-t;this.recordResponse(n),await this.save()}async save(){let e=this.toSnapshot();await this._stateStore.save(this.id,I.SESSION,e)}async load(){let e=await this._stateStore.load(this.id,I.SESSION);return e?(this.restoreFromSnapshot(e),!0):!1}setStatus(e,t){super.setStatus(e,t),this._autoSave&&this.save().catch(()=>{})}markActive(){super.markActive(),this._autoSave&&this.save().catch(()=>{})}addMessage(e){super.addMessage(e),this._autoSave&&this.save().catch(()=>{})}addUsage(e){super.addUsage(e),this._autoSave&&this.save().catch(()=>{})}recordResponse(e){super.recordResponse(e),this._autoSave&&this.save().catch(()=>{})}incrementToolCallCount(){super.incrementToolCallCount(),this._autoSave&&this.save().catch(()=>{})}setModelOverride(e){super.setModelOverride(e),this._modelOverride=this.resolveModelRef(e)??this._modelOverride,this._autoSave&&this.save().catch(()=>{})}clearModelOverride(){super.clearModelOverride(),this._modelOverride=void 0,this._autoSave&&this.save().catch(()=>{})}setSystemPromptOverride(e){super.setSystemPromptOverride(e),this._autoSave&&this.save().catch(()=>{})}clearSystemPromptOverride(){super.clearSystemPromptOverride(),this._autoSave&&this.save().catch(()=>{})}disableTools(e){super.disableTools(e),this._autoSave&&this.save().catch(()=>{})}enableAllTools(){super.enableAllTools(),this._autoSave&&this.save().catch(()=>{})}setAutoSave(e){this._autoSave=e}},Ve=class extends ve{_stateStore;constructor(e){super(),this._stateStore=e}async create(e){let t=e??a(),n=Date.now(),r={id:t,createdAt:n,state:{status:`active`,updatedAt:n,lastActiveAt:n},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0}},i=new B(this._stateStore,t,r);return await i.save(),i}async get(e){let t=await this._stateStore.load(e,I.SESSION);if(t)return new B(this._stateStore,e,t)}async list(){let e=await this._stateStore.listSessions(),t=[];for(let n of e){let e=await this._stateStore.load(n,I.SESSION);if(e){let r=new B(this._stateStore,n,e);t.push(r)}}return t}async destroy(e){await this._stateStore.deleteSession(e)}},He=class{savePoint;deleteOnComplete;constructor(e){this.savePoint=e?.savePoint??`before`,this.deleteOnComplete=e?.deleteOnComplete??!0}assertValidStorageSegment(e,t){if(!t)throw Error(`${e} must be a non-empty string`);if(t===`.`||t===`..`)throw Error(`${e} must not be "." or ".."`);if(t.includes(`/`)||t.includes(`\\`))throw Error(`${e} must not contain path separators`);if(t.includes(`\0`))throw Error(`${e} must not contain NUL bytes`)}async save(e,t,n){let r=this.buildPath(e,t),i=JSON.stringify(n,null,2);await this._write(r,i)}async load(e,t){let n=this.buildPath(e,t),r=await this._read(n);if(r!==void 0)try{return JSON.parse(r)}catch{return}}async delete(e,t){let n=this.buildPath(e,t);await this._delete(n)}async deleteSession(e){let t=this.buildPrefix(e),n=await this._list(t);await Promise.all(n.map(e=>this._delete(e)))}async listKeys(e){let t=this.buildPrefix(e);return(await this._list(t)).map(t=>this.extractKey(e,t))}async exists(e,t){let n=this.buildPath(e,t);return this._exists(n)}async saveCheckpoint(e){let t={_meta:{description:`GoatChain Agent Loop Checkpoint - DO NOT EDIT MANUALLY`,savedAt:new Date().toISOString(),agentId:e.agentId,agentName:e.agentName,sessionId:e.sessionId,iteration:e.iteration,phase:e.phase,status:e.status,messageCount:e.messages.length,toolCallsPending:e.pendingToolCalls?.length??0},checkpoint:e};await this.save(e.sessionId,I.CHECKPOINT,t)}async loadCheckpoint(e){return(await this.load(e,I.CHECKPOINT))?.checkpoint}async deleteCheckpoint(e){await this.delete(e,I.CHECKPOINT)}async listCheckpoints(){let e=await this.listSessions(),t=[];for(let n of e){let e=await this.loadCheckpoint(n);e&&t.push(e)}return t}async listSessions(){let e=await this._list(``),t=new Set;for(let n of e){let e=this.extractSessionId(n);e&&t.add(e)}return Array.from(t)}buildPath(e,t){return this.assertValidStorageSegment(`sessionId`,e),this.assertValidStorageSegment(`key`,t),`${e}/${t}`}buildPrefix(e){return this.assertValidStorageSegment(`sessionId`,e),`${e}/`}extractKey(e,t){let n=this.buildPrefix(e);return t.startsWith(n)?t.slice(n.length):t}extractSessionId(e){let t=e.split(`/`);return t.length>0?t[0]:void 0}},Ue=class extends He{baseDir;constructor(e){super(e),this.baseDir=m.resolve(e.dir),this.ensureDir(this.baseDir)}async _write(e,t){let n=this.toFilePath(e);this.ensureDir(m.dirname(n)),w(n,t,`utf-8`)}async _read(e){let t=this.toFilePath(e);try{return _(t)?y(t,`utf-8`):void 0}catch{return}}async _delete(e){let t=this.toFilePath(e);_(t)&&x(t);let n=m.dirname(t);if(_(n))try{b(n).length===0&&x(n,{recursive:!0})}catch{}}async _exists(e){return _(this.toFilePath(e))}async _list(e){let t=[];if(!_(this.baseDir))return t;let n=b(this.baseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let r of n){if(e&&!r.startsWith(e.split(`/`)[0]))continue;let n=m.join(this.baseDir,r),i=this.listJsonFiles(n);for(let n of i){let i=`${r}/${m.basename(n,`.json`)}`;(!e||i.startsWith(e))&&t.push(i)}}return t}toFilePath(e){return m.join(this.baseDir,`${e}.json`)}ensureDir(e){_(e)||v(e,{recursive:!0})}listJsonFiles(e){return _(e)?b(e).filter(e=>e.endsWith(`.json`)).map(t=>m.join(e,t)):[]}getBaseDir(){return this.baseDir}clear(){_(this.baseDir)&&(x(this.baseDir,{recursive:!0}),v(this.baseDir,{recursive:!0}))}},We=class extends He{store=new Map;constructor(e){super(e)}async _write(e,t){this.store.set(e,t)}async _read(e){return this.store.get(e)}async _delete(e){this.store.delete(e)}async _exists(e){return this.store.has(e)}async _list(e){let t=[];for(let n of this.store.keys())(e===``||n.startsWith(e))&&t.push(n);return t}clear(){this.store.clear()}stats(){let e=new Set;for(let t of this.store.keys()){let n=this.extractSessionId(t);n&&e.add(n)}return{entryCount:this.store.size,sessionCount:e.size}}},Ge=class{id;name;systemPrompt;createdAt;_model;_modelOverride;_tools;_stateStore;_sessionManager;_middlewares=[];_middlewareCounter=0;_middlewareTools=new Map;constructor(e){this.id=e.id??crypto.randomUUID(),this.name=e.name,this.systemPrompt=e.systemPrompt,this.createdAt=Date.now(),this._model=e.model,this._tools=e.tools,this._stateStore=e.stateStore??new We({savePoint:`before`}),this._sessionManager=new Ve(this._stateStore)}get model(){return this._model}get modelId(){return this.modelRef?.modelId??this._model.modelId}get modelRef(){return this._modelOverride??this._model.modelRef}get modelRefs(){let e=this._model.modelRefs;if(Array.isArray(e))return e;let t=this._model.modelRef;return t?[t]:[]}get tools(){return this._tools}get stateStore(){return this._stateStore}get sessionManager(){return this._sessionManager}async createSession(e){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let t=await this._sessionManager.create(e?.sessionId);if(!this._stateStore)throw Error(`StateStore is required to create sessions`);let n=t.toSnapshot();return new B(this._stateStore,t.id,n,{...e,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map(e=>e.fn),hasCheckpoint:!1,emitSessionCreatedEvent:!0})}async resumeSession(e,t){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let n=await this._sessionManager.get(e);if(!n)throw Error(`Session not found: ${e}`);let r=!!await this._stateStore?.loadCheckpoint(e);if(!this._stateStore)throw Error(`StateStore is required to resume sessions`);let i=n.toSnapshot();return new B(this._stateStore,n.id,i,{...t,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map(e=>e.fn),hasCheckpoint:r,emitSessionCreatedEvent:!1})}use(e,t){let n=t??e.__middlewareName??`middleware_${this._middlewareCounter++}`;if(this._middlewares.some(e=>e.name===n))throw Error(`Middleware with name "${n}" already exists`);let r={name:n,fn:e};return this._middlewares.push(r),e.__createTools&&typeof e.__createTools==`function`&&this._registerMiddlewareTools(n,e.__createTools),()=>{this.removeMiddleware(n)}}removeMiddleware(e){let t=-1,n;return typeof e==`string`?(t=this._middlewares.findIndex(t=>t.name===e),n=e):(t=this._middlewares.findIndex(t=>t.fn===e),t>-1&&(n=this._middlewares[t].name)),t>-1&&n?(this._unregisterMiddlewareTools(n),this._middlewares.splice(t,1),!0):!1}clearMiddlewares(){for(let e of this._middlewareTools.keys())this._unregisterMiddlewareTools(e);this._middlewares=[]}get middlewares(){return[...this._middlewares]}get middlewareNames(){return this._middlewares.map(e=>e.name)}setModel(e){(e=>!!(e&&typeof e==`object`&&typeof e.provider==`string`&&typeof e.modelId==`string`&&typeof e.stream!=`function`))(e)?this._modelOverride=e:(this._model=e,this._modelOverride=void 0)}_getNamespacedToolName(e,t){return`${e}:${t}`}_registerMiddlewareTools(e,t){if(!this._tools)return;let n=t(),r=[];for(let t of n){let n=this._getNamespacedToolName(e,t.name),i=Object.create(Object.getPrototypeOf(t));Object.assign(i,t),Object.defineProperty(i,`name`,{value:n,writable:!1,configurable:!0});try{this._tools.register(i),r.push(n)}catch(e){console.warn(`Failed to register tool ${n}:`,e)}}r.length>0&&this._middlewareTools.set(e,r)}_unregisterMiddlewareTools(e){if(!this._tools)return;let t=this._middlewareTools.get(e);if(t){for(let e of t)this._tools.unregister(e);this._middlewareTools.delete(e)}}};function Ke(e){return{content:[{type:`text`,text:e}]}}function V(e){return{content:[{type:`text`,text:e}],isError:!0}}function qe(e,t){return{content:[{type:`image`,data:e,mimeType:t}]}}var H=class{riskLevel=`safe`},Je=class extends H{name=`AskUserQuestion`;riskLevel=`safe`;description=`Use this tool when you need to ask the user questions during execution. This allows you to:
112
+ `):JSON.stringify(t.content),e.push({name:t.role===`user`?`user_message`:`assistant_message`,content:`${t.role===`user`?`User`:`Assistant`}: ${n}`})}if(e.length===0)return{summary:``,messageCount:n.length,toolOutputCount:0};s=e}let c=(await me(s,r,a,void 0)).trim();if(c.length===0)return{summary:``,messageCount:n.length,toolOutputCount:o.length};let l=await i.load(t,I.COMPRESSION),u=Date.now(),d={lastStats:l?.lastStats,history:l?.history??[],summary:c,updatedAt:u};return await i.save(t,I.COMPRESSION,d),{summary:c,messageCount:n.length,toolOutputCount:o.length}}var _e=class{setModelOverride(e){this.configOverride||={},this.configOverride.model=e,this.updatedAt=Date.now()}clearModelOverride(){this.configOverride&&(delete this.configOverride.model,this.updatedAt=Date.now())}setSystemPromptOverride(e){this.configOverride||={},this.configOverride.systemPromptOverride=e,this.updatedAt=Date.now()}clearSystemPromptOverride(){this.configOverride&&(delete this.configOverride.systemPromptOverride,this.updatedAt=Date.now())}disableTools(e){this.configOverride||={},this.configOverride.disabledTools=[...this.configOverride.disabledTools??[],...e],this.updatedAt=Date.now()}enableAllTools(){this.configOverride&&(delete this.configOverride.disabledTools,this.updatedAt=Date.now())}setStatus(e,t){this.status=e,this.errorMessage=t,this.updatedAt=Date.now()}markActive(){this.lastActiveAt=Date.now(),this.updatedAt=Date.now()}addMessage(e){this.messages.push(e),this.markActive()}getLastMessagePreview(e=100){if(this.messages.length===0)return;let t=this.messages[this.messages.length-1],n=typeof t.content==`string`?t.content:JSON.stringify(t.content);return n.length>e?`${n.substring(0,e)}...`:n}addUsage(e){this.usage.promptTokens+=e.promptTokens,this.usage.completionTokens+=e.completionTokens,this.usage.totalTokens+=e.totalTokens,this.updatedAt=Date.now()}recordResponse(e){let t=(this.avgResponseTime??0)*this.responseCount;this.responseCount++,this.avgResponseTime=(t+e)/this.responseCount,this.updatedAt=Date.now()}incrementToolCallCount(){this.toolCallCount++,this.updatedAt=Date.now()}toSnapshot(){let e={status:this.status,updatedAt:this.updatedAt,lastActiveAt:this.lastActiveAt,title:this.title,errorMessage:this.errorMessage},t={messages:[...this.messages],messageCount:this.messages.length,lastMessagePreview:this.getLastMessagePreview(),toolCallCount:this.toolCallCount},n={usage:{...this.usage},responseCount:this.responseCount,avgResponseTime:this.avgResponseTime};return{id:this.id,createdAt:this.createdAt,state:e,configOverride:this.configOverride?{...this.configOverride}:void 0,context:t,stats:n}}restoreFromSnapshot(e){this.status=e.state.status,this.updatedAt=e.state.updatedAt,this.lastActiveAt=e.state.lastActiveAt,this.title=e.state.title,this.errorMessage=e.state.errorMessage,this.configOverride=e.configOverride?{...e.configOverride}:void 0,this.messages=[...e.context.messages],this.toolCallCount=e.context.toolCallCount,this.usage={...e.stats.usage},this.responseCount=e.stats.responseCount,this.avgResponseTime=e.stats.avgResponseTime}},ve=class{},L=class extends Error{constructor(e=`Agent execution aborted`){super(e),this.name=`AgentAbortError`}},ye=class extends Error{iterations;constructor(e,t){super(t??`Agent exceeded maximum iterations (${e})`),this.name=`AgentMaxIterationsError`,this.iterations=e}},be=class extends Error{constructor(e=`Agent execution paused`){super(e),this.name=`AgentPauseError`}};function R(e,t){if(!e?.aborted)return;let n=e?.reason;throw n instanceof Error?n:new L(typeof n==`string`?n:t?`${t} aborted`:`Agent execution aborted`)}var xe=class{},Se=class{hooks;constructor(e){this.hooks=e??{}}async executePreToolUse(e){let t=this.hooks.preToolUse;if(!t||t.length===0)return{allow:!0};let n=e.toolCall;for(let r of t){let t=await r({...e,toolCall:n});if(!t.allow)return{allow:!1,modifiedToolCall:t.modifiedToolCall};t.modifiedToolCall&&(n=t.modifiedToolCall)}return n===e.toolCall?{allow:!0}:{allow:!0,modifiedToolCall:n}}async executePostToolUse(e,t){let n=this.hooks.postToolUse;if(!(!n||n.length===0))for(let r of n)await r(e,t)}async executePostToolUseFailure(e,t){let n=this.hooks.postToolUseFailure;if(!(!n||n.length===0))for(let r of n)await r(e,t)}};function Ce(e){return(t,n)=>{let r=-1,i=async(t,a)=>{if(t<=r)throw Error(`next() called multiple times`);if(r=t,t===e.length)return n?await n(a):a;let o=e[t];return o(a,e=>i(t+1,e))};return i(0,t)}}function we(e,t,n){let r=[{role:`system`,content:n},...e.messages??[],{role:`user`,content:e.input}];return{sessionId:e.sessionId??``,agentId:t,messages:r,iteration:0,pendingToolCalls:[],currentResponse:``,shouldContinue:!0,usage:{promptTokens:0,completionTokens:0,totalTokens:0},metadata:{}}}var z=class extends Error{code;retryable;status;constructor(e,t){super(e),this.name=`ModelError`,this.code=t.code,this.retryable=t.retryable??!1,this.status=t.status}},Te=class{state=new Map;get(e){return this.state.get(this.keyOf(e))||{failures:0,nextRetryAt:0}}markSuccess(e){this.state.set(this.keyOf(e),{failures:0,nextRetryAt:0})}markFailure(e,t){let n=this.get(e).failures+1,r=Math.min(t.maxDelayMs,t.baseDelayMs*2**Math.min(8,n-1));this.state.set(this.keyOf(e),{failures:n,nextRetryAt:t.now+r,lastError:{code:t.code,message:t.message}})}isAvailable(e,t){return this.get(e).nextRetryAt<=t}keyOf(e){return`${e.provider}:${e.modelId}`}},Ee=class extends Te{},De=class{constructor(e,t){this.health=e,this.fallbackOrder=t}select(e){let{now:t}=e,n=this.fallbackOrder.filter(e=>this.health.isAvailable(e,t));return n.length?n:this.fallbackOrder}},Oe=class{static isRetryableStatus(e){return e===408||e===409||e===429||e>=500&&e<=599}static async sleep(e,t){return e<=0?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{a(),n()},e);function a(){clearTimeout(i),t&&t.removeEventListener(`abort`,o)}function o(){a(),r(Error(`Aborted`))}if(t){if(t.aborted)return o();t.addEventListener(`abort`,o)}})}};function ke(e=`req`){let t=Math.random().toString(16).slice(2);return`${e}_${Date.now().toString(16)}_${t}`}var Ae=class e{maxAttempts;baseDelayMs;maxDelayMs;strategy;jitter;multiplier;_previousDelay;constructor(e={}){this.maxAttempts=e.maxAttempts??3,this.baseDelayMs=e.baseDelayMs??500,this.maxDelayMs=e.maxDelayMs??3e4,this.strategy=e.strategy??`exponential`,this.jitter=e.jitter??`equal`,this.multiplier=e.multiplier??2,this._previousDelay=this.baseDelayMs}getDelay(e){let t;switch(this.strategy){case`exponential`:t=this.baseDelayMs*this.multiplier**(e-1);break;case`linear`:t=this.baseDelayMs*e;break;case`fixed`:t=this.baseDelayMs;break}return t=Math.min(t,this.maxDelayMs),t=this.applyJitter(t),this._previousDelay=t,Math.floor(t)}applyJitter(e){switch(this.jitter){case`full`:return Math.random()*e;case`equal`:return e/2+Math.random()*e/2;case`decorrelated`:return Math.min(this.maxDelayMs,Math.random()*(this._previousDelay*3-this.baseDelayMs)+this.baseDelayMs);case`none`:default:return e}}canRetry(e){return e<this.maxAttempts}reset(){this._previousDelay=this.baseDelayMs}toString(){return`RetryPolicy(${this.strategy}, max=${this.maxAttempts}, base=${this.baseDelayMs}ms, cap=${this.maxDelayMs}ms, jitter=${this.jitter})`}static default=new e;static aggressive=new e({maxAttempts:5,baseDelayMs:1e3,maxDelayMs:6e4});static gentle=new e({maxAttempts:3,baseDelayMs:2e3,maxDelayMs:3e4,jitter:`full`})};function je(e){let t=e.adapters??(e.adapter?[e.adapter]:void 0);if(!t||t.length===0)throw new z("Missing adapter(s). Provide `adapter` for the simple case, or `adapters` for multi-provider routing.",{code:`missing_adapter`,retryable:!1});if(e.adapter&&e.adapters)throw new z("Provide either `adapter` or `adapters`, not both.",{code:`invalid_options`,retryable:!1});let n=new Map(t.map(e=>[e.provider,e])),r=e.health??new Ee,i=e.fallback?.onPartialOutput??`stop`,a=e.fallback?.onPartialToolCalls??`stop`,o=e.routing?.fallbackOrder??(()=>{let e=[];for(let n of t)n.defaultModelId&&e.push({provider:n.provider,modelId:n.defaultModelId});if(e.length===0)throw new z(`No routing configuration and no adapter with defaultModelId provided. Either provide options.routing.fallbackOrder or set defaultModelId on your adapters.`,{code:`missing_routing`,retryable:!1});return e})(),s=new De(r,o),c=new Ae({maxAttempts:e.retry?.maxAttemptsPerModel??3,baseDelayMs:e.retry?.baseDelayMs??500,maxDelayMs:e.retry?.maxDelayMs??3e4,strategy:e.retry?.strategy??`exponential`,jitter:e.retry?.jitter??`equal`}),l=e.timeoutMs??6e4;function u(e){let t=n.get(e.provider);if(!t)throw new z(`No adapter for provider: ${e.provider}`,{code:`adapter_missing`,retryable:!1});return t}async function*d(t){let n=Date.now(),o=t.requestId||ke(`req`),{model:d,...f}=t,p=t.model?[t.model]:s.select({now:n}),m;for(let n of p){let s=u(n),d=t.timeoutMs??l,p=!1,h=!1,g=0,_=new AbortController,v=t.signal,y=setTimeout(()=>_.abort(),d),b=()=>_.abort();v&&(v.aborted?_.abort():v.addEventListener(`abort`,b));let x={...f,requestId:o,model:n,stream:t.stream??!0,signal:_.signal,timeoutMs:d};try{for(let t=1;t<=c.maxAttempts;t++){g=t;try{for await(let e of s.stream({request:x}))e.type===`delta`&&(p=!0,e.chunk.kind===`tool_call_delta`&&(h=!0)),yield e;r.markSuccess(n);return}catch(r){m=r;let i=Me(r),a=i.retryable;if(p||!a||!c.canRetry(t))throw i;let o=c.getDelay(t);e.retry?.onRetry?.({attempt:t,maxAttempts:c.maxAttempts,delayMs:o,error:{code:i.code,message:i.message,retryable:i.retryable},model:n,request:x}),await Oe.sleep(o,_.signal)}}}catch(e){let t=Me(e);r.markFailure(n,{now:Date.now(),baseDelayMs:c.baseDelayMs,maxDelayMs:c.maxDelayMs,code:t.code,message:t.message});let s=!(h&&a===`stop`||p&&i===`stop`);if(yield{type:`error`,requestId:o,terminal:!s,model:n,attempt:g||1,source:`client`,error:{code:t.code,message:t.message,retryable:t.retryable}},!s)throw t;m=t;continue}finally{clearTimeout(y),v&&v.removeEventListener(`abort`,b)}}throw Me(m||new z(`All models failed`,{code:`all_models_failed`}))}async function f(e){let t=``,n=``,r=`error`,i,a,o=e.requestId||``,s=!1;for await(let c of d({...e,stream:!0}))c.type===`response_start`?(s=!0,o=c.requestId,a=c.model,t=``):c.type===`delta`&&c.chunk.kind===`text`?t+=c.chunk.text:c.type===`response_end`?(n=t,r=c.stopReason,i=c.usage):c.type===`error`&&(r=`error`);if(!a)throw new z(`Missing response_start from adapter`,{code:`protocol_error`,retryable:!1});return{requestId:o,model:a,text:s?n:t,stopReason:r,usage:i}}return{get modelId(){return o[0]?.modelId??`unknown`},get modelRef(){return o[0]},get modelRefs(){return[...o]},setModelId(e){let t=o[0];if(!t)throw new z(`No primary model to update`,{code:`no_primary_model`,retryable:!1});o[0]={provider:t.provider,modelId:e}},stream:d,run:f}}function Me(e){if(e instanceof z)return e;if(e&&typeof e==`object`){let t=typeof e.status==`number`?e.status:void 0,n=typeof e.code==`string`?e.code:t?`http_${t}`:`unknown_error`;return new z(typeof e.message==`string`?e.message:`Unknown error`,{code:n,retryable:t?Oe.isRetryableStatus(t):!1,status:t})}return new z(String(e||`Unknown error`),{code:`unknown_error`,retryable:!1})}function Ne(e){function t(e,t){if(typeof e!=`string`)return``;let n=e.trim();return n?/^data:/i.test(n)||/^https?:\/\//i.test(n)?n:typeof t==`string`&&t.trim()?`data:${t.trim()};base64,${n}`:n:``}if(typeof e==`string`)return e.trim().length===0?``:e;if(e==null)return``;if(typeof e==`object`&&`type`in e){let n=e;if(n.type===`text`&&n.text)return n.text;if(n.type===`image`){let e=t(n.data??n.source?.data,n.mimeType??n.source?.media_type??n.source?.mimeType);return e?[{type:`image_url`,image_url:{url:e}}]:``}}if(Array.isArray(e)){let n=[];for(let r of e)if(typeof r==`string`)n.push({type:`text`,text:r});else if(r&&typeof r==`object`&&`type`in r){let e=r;if(e.type===`text`&&e.text)n.push({type:`text`,text:e.text});else if(e.type===`image`){let r=t(e.data??e.source?.data,e.mimeType??e.source?.media_type??e.source?.mimeType);r&&n.push({type:`image_url`,image_url:{url:r}})}}return n.length>0?n:``}return String(e)}function Pe(e){return{...e,content:Ne(e.content)}}function Fe(e,t){return typeof t==`string`&&/deepseek/i.test(t)?!0:/^deepseek-/i.test(e)}function Ie(e={}){let t=e.baseUrl;function n(){if(typeof e.apiKey==`function`){let t=e.apiKey();if(typeof t==`string`){let e=t.trim();if(!e)throw new z(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return e}if(t!=null)throw new z(`Invalid apiKey provider`,{code:`invalid_api_key`,retryable:!1})}if(typeof e.apiKey==`string`){let t=e.apiKey.trim();if(!t)throw new z(`Missing apiKey`,{code:`missing_api_key`,retryable:!1});return t}let t=typeof process<`u`?process.env?.OPENAI_API_KEY:void 0;if(typeof t!=`string`||!t.trim())throw new z(`Missing OPENAI_API_KEY`,{code:`missing_api_key`,retryable:!1});return t.trim()}function i(){let i=n();return typeof t==`string`&&/\/chat\/completions\/?$/.test(t)?new r({apiKey:i,organization:e.organization,project:e.project,baseURL:`https://api.openai.com/v1`,fetch:(e,n)=>fetch(t,n)}):new r({apiKey:i,organization:e.organization,project:e.project,baseURL:t||void 0})}function a(e){return{provider:`openai`,modelId:e.model.modelId}}function o(e){if(e instanceof z)return e;let t=typeof e?.status==`number`?e.status:void 0;return new z(typeof e?.message==`string`?e.message:`OpenAI error`,{code:typeof e?.code==`string`?e.code:t?`openai_http_${t}`:`openai_error`,retryable:t?Oe.isRetryableStatus(t):!1,status:t})}async function*s(n){let{request:r}=n,s=r.requestId||ke(`req`),c=i(),l=r.model.modelId,u=e.compat?.interleavedThinking,d=typeof u==`boolean`?u:Fe(l,t),f=r.stream!==!1,p=[];if(r.messages&&Array.isArray(r.messages))for(let e of r.messages){let t=Pe(e);if(!d&&t&&typeof t==`object`)`reasoning_content`in t&&delete t.reasoning_content;else if(d&&t?.role===`assistant`&&Array.isArray(t?.tool_calls)&&t.tool_calls.length>0){let e=t.reasoning_content;(typeof e!=`string`||e.length===0)&&(t.reasoning_content=`.`)}p.push(t)}else typeof r.instructions==`string`&&r.instructions.length>0&&p.push({role:`system`,content:r.instructions}),p.push({role:`user`,content:r.input});let m=(()=>{let e=r.reasoning?.effort;if(typeof e==`string`&&(e===`none`||e===`minimal`||e===`low`||e===`medium`||e===`high`||e===`xhigh`))return e})(),h={model:l,messages:p,stream:f,stream_options:f?{include_usage:!0}:void 0,metadata:r.metadata??void 0,reasoning_effort:m,max_completion_tokens:r.maxOutputTokens??void 0,stop:r.stop??void 0,temperature:r.temperature??void 0,top_p:r.topP??1};r.tools&&Array.isArray(r.tools)&&r.tools.length>0&&(h.tools=r.tools);try{if(yield{type:`response_start`,requestId:s,model:a(r)},!f){let e=await c.chat.completions.create({...h,stream:!1},{signal:r.signal,timeout:r.timeoutMs}),t=Array.isArray(e?.choices)?e.choices[0]:void 0,n=t?.message,i=typeof n?.reasoning_content==`string`?n.reasoning_content:``;i.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:i}},yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:i}});let a=typeof n?.content==`string`?n.content:``;a.length>0&&(yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:a}});let o=Array.isArray(n?.tool_calls)?n.tool_calls:[];for(let e=0;e<o.length;e++){let t=o[e],n=typeof t?.id==`string`?t.id:`call_${e}`,r=typeof t?.function?.name==`string`?t.function.name:void 0,i=typeof t?.function?.arguments==`string`?t.function.arguments:void 0;(i||r)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:i}})}yield{type:`response_end`,requestId:s,stopReason:Le(t?.finish_reason),usage:e?.usage};return}let e=await c.chat.completions.create({...h,stream:!0},{signal:r.signal,timeout:r.timeoutMs}),t=null,n,i=new Map,o=!1,l=``;for await(let r of e){r?.usage!=null&&(n=r.usage);let e=Array.isArray(r?.choices)?r.choices:[];for(let n of e){n?.finish_reason!=null&&(t=n.finish_reason);let e=n?.delta,r=e?.reasoning_content;typeof r==`string`&&r.length>0&&(o||(o=!0,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_start`}}),l+=r,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_delta`,text:r}});let a=e?.content;typeof a==`string`&&a.length>0&&(o&&(o=!1,yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`delta`,requestId:s,chunk:{kind:`text`,text:a}});let c=Array.isArray(e?.tool_calls)?e.tool_calls:[];for(let e of c){let t=typeof e?.index==`number`?e.index:0,n=i.get(t)||(typeof e?.id==`string`?e.id:`call_${t}`);i.set(t,n);let r=typeof e?.function?.name==`string`?e.function.name:void 0,a=typeof e?.function?.arguments==`string`?e.function.arguments:void 0;(r||a)&&(yield{type:`delta`,requestId:s,chunk:{kind:`tool_call_delta`,callId:n,toolId:r,argsTextDelta:a}})}}}o&&(yield{type:`delta`,requestId:s,chunk:{kind:`thinking_end`,text:l||void 0}}),yield{type:`response_end`,requestId:s,stopReason:Le(t),usage:n}}catch(e){throw e?.name===`AbortError`?new z(`Aborted`,{code:`aborted`,retryable:!1}):o(e)}}return{provider:`openai`,defaultModelId:e.defaultModelId,stream:s}}function Le(e){return e===`tool_calls`||e===`function_call`?`tool_call`:e===`length`?`length`:e===`content_filter`?`error`:`final`}function Re(e){if(e){if(e instanceof z)return{code:e.code,message:e.message,status:e.status,retryable:e.retryable};if(e instanceof Error){let t=e,n=typeof t.code==`string`?t.code:void 0,r=typeof t.status==`number`?t.status:void 0,i=typeof t.retryable==`boolean`?t.retryable:void 0;return{code:n,message:e.message,status:r,retryable:i}}return{message:String(e)}}}function ze(e){let t=e?.function?.arguments;if(typeof t==`string`)try{return JSON.parse(t),e}catch(n){let r=n instanceof Error?n.message:String(n);return{...e,function:{...e.function,arguments:JSON.stringify({_raw:t,_parseError:r})}}}return t&&typeof t==`object`?{...e,function:{...e.function,arguments:JSON.stringify(t)}}:{...e,function:{...e.function,arguments:JSON.stringify(t??null)}}}function Be(e){let t=!1,n=e.map(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return e;let n=e.tool_calls;if(!Array.isArray(n)||n.length===0)return e;let r=!1,i=n.map(e=>{let t=ze(e);return t!==e&&(r=!0),t});return r?(t=!0,{...e,tool_calls:i}):e});return t?n:e}var B=class e extends _e{id;agentId;createdAt;status;title;updatedAt;lastActiveAt;errorMessage;configOverride;messages;toolCallCount;usage;responseCount;avgResponseTime;_stateStore;toolEventQueue=[];_autoSave;_modelClient;_tools;_middlewares;_systemPrompt;_agentName;_onUsage;_hasCheckpoint;_checkpointRestored=!1;_pendingInput=null;_isReceiving=!1;_hooks;_modelOverride;_maxIterations;_requestParams;_emitSessionCreatedEvent;_sessionCreatedEventEmitted=!1;getDisabledToolNames(){let e=this.configOverride?.disabledTools;return!e||e.length===0?new Set:new Set(e)}isToolDisabled(e){return this.getDisabledToolNames().has(e)}collectBlockedTools(e){let t=new Set;for(let n of this._middlewares)if(typeof n.__getBlockedTools==`function`){let r=n.__getBlockedTools(e);(Array.isArray(r)?r:Array.from(r)).forEach(e=>t.add(e))}return t}isToolBlocked(e,t){let n=e.metadata?.blockedTools;return n?n instanceof Set?n.has(t):Array.isArray(n)?n.includes(t):!1:!1}getToolsForModel(e){let t=this._tools?.toOpenAIFormat();if(!t||t.length===0)return;let n=this.getDisabledToolNames(),r=n.size===0?t:t.filter(e=>!n.has(e.function.name)),i=e.metadata?.blockedTools;return i&&i.size>0&&(r=r.filter(e=>!i.has(e.function.name))),r.length>0?r:void 0}getEffectiveSystemPrompt(){let e=this.configOverride?.systemPromptOverride;return typeof e==`string`?e:this._systemPrompt}constructor(e,t,n,r){if(super(),this._stateStore=e,this.id=t,n)this.createdAt=n.createdAt,this.restoreFromSnapshot(n);else{let e=Date.now();this.createdAt=e,this.status=`active`,this.updatedAt=e,this.lastActiveAt=e,this.messages=[],this.toolCallCount=0,this.usage={promptTokens:0,completionTokens:0,totalTokens:0},this.responseCount=0}this._autoSave=!0,this._modelClient=r?.modelClient,this._tools=r?.tools,this._middlewares=r?.middlewares??[],this._systemPrompt=r?.systemPrompt,this._agentName=r?.agentName,this._onUsage=r?.onUsage,this._hasCheckpoint=r?.hasCheckpoint??!1,this._hooks=r?.hooks,this._modelOverride=r?.model,this._maxIterations=r?.maxIterations,this._requestParams=r?.requestParams,this._emitSessionCreatedEvent=r?.emitSessionCreatedEvent===!0}get hasCheckpoint(){return this._hasCheckpoint}send(e,t){if(this._ensureRuntimeConfigured(!0),this._isReceiving)throw Error(`Cannot send while receiving messages`);if(this._pendingInput)throw Error(`Pending input already exists; call receive() to consume it before sending another message`);this._pendingInput={input:e,options:t}}async*receive(e){if(this._isReceiving)throw Error(`Cannot receive concurrently`);if(!this._hasCheckpoint&&!this._pendingInput)throw Error(`Nothing to receive; call send() first (or resume from a session that has a checkpoint)`);this._isReceiving=!0;try{if(this._emitSessionCreatedEvent&&!this._sessionCreatedEventEmitted&&(this._sessionCreatedEventEmitted=!0,yield{type:`session_created`,agentId:this.agentId,sessionId:this.id}),!this._hasCheckpoint&&this._pendingInput&&this._stateStore)try{let e=await this._stateStore.loadCheckpoint(this.id);e&&Array.isArray(e.pendingToolCalls)&&e.pendingToolCalls.length>0&&(this._hasCheckpoint=!0,this._checkpointRestored=!1)}catch{}if(this._hasCheckpoint&&!this._checkpointRestored&&this._pendingInput){let{input:t,options:n}=this._pendingInput;this._pendingInput=null;let r=await this._stateStore.loadCheckpoint(this.id);if(!r)throw Error(`Checkpoint not found for sessionId: ${this.id}`);let i=A(r);i.sessionId!==this.id&&(i.sessionId=this.id),i.metadata={...i.metadata,_pendingUserInput:t};let a=this._requestParams??r.requestParams,o=n??e;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:o?.signal,model:this.getRuntimeModelOverride(),toolContext:o?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,Date.now()),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(this._hasCheckpoint&&!this._checkpointRestored){let t=e??this._pendingInput?.options;if(yield*this._stream(void 0,t),!this._pendingInput)return}if(this._pendingInput){let{input:e,options:t}=this._pendingInput;this._pendingInput=null,yield*this._stream(e,t)}}finally{this._isReceiving=!1}}async*receiveWithApprovals(e,t){let n=t?.toolContext,r={...n??{},approval:{...n?.approval??{},decisions:{...n?.approval?.decisions??{},...e}}};yield*this.receive({...t,toolContext:r})}async*_stream(e,t){this._ensureRuntimeConfigured(e!==void 0);let n=Date.now(),r=this.getRuntimeModelOverride(),i;if(this._hasCheckpoint&&!this._checkpointRestored){let e=await this._stateStore.loadCheckpoint(this.id);if(!e)throw Error(`Checkpoint not found for sessionId: ${this.id}`);i=A(e),i.sessionId!==this.id&&(i.sessionId=this.id);let a=this._requestParams??e.requestParams;yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:a}),await this._finalizeRun(i,n),this._checkpointRestored=!0,this._hasCheckpoint=!1;return}if(e===void 0)throw Error(`Input is required to stream`);if(!this.title&&this.messages.length===0){let t=this.extractTextFromContent(e);t&&(this.title=this.createTitle(t))}let a=this.messages.filter(e=>e.role!==`system`);i=we({sessionId:this.id,input:e,messages:a},this.agentId,this.getEffectiveSystemPrompt()??``),yield*this._streamWithState(i,{maxIterations:this._maxIterations,signal:t?.signal,model:r,toolContext:t?.toolContext,hooks:this._hooks,requestParams:this._requestParams}),await this._finalizeRun(i,n)}resolveModelRef(e){if(e.provider)return{provider:e.provider,modelId:e.modelId};let t=(this._modelClient?.modelRefs??[]).find(t=>t.modelId===e.modelId);if(t)return t;let n=this._modelClient?.modelRef?.provider;if(n)return{provider:n,modelId:e.modelId}}getRuntimeModelOverride(){if(this.configOverride?.model){let e=this.resolveModelRef(this.configOverride.model);if(e)return e}return this._modelOverride}_ensureRuntimeConfigured(e){if(!this._modelClient)throw Error(`Session is not configured with a model client`);if(e&&this.getEffectiveSystemPrompt()===void 0)throw Error(`Session is not configured with a system prompt`)}extractTextFromContent(e){return typeof e==`string`?e:Array.isArray(e)?e.filter(e=>e.type===`text`).map(e=>e.text).join(` `):e&&typeof e==`object`&&e.type===`text`&&e.text||``}createTitle(e,t=50){let n=e.trim();return n.length<=t?n:`${n.substring(0,t).trim()}...`}_recordUsage(e){this._onUsage&&this._onUsage(e)}async executeModelStream(e,t,n,r,i){if(!this._modelClient)throw Error(`Session is not configured with a model client`);let a=[],o=e.sessionId,s=new Map,c=!1,l=!1,u=e=>{let t=s.get(e);if(t)return t;let n={argsText:``,started:!1};return s.set(e,n),n},d=(e,t)=>{let n=u(e);t&&!n.toolName&&(n.toolName=t),n.started||(n.started=!0,a.push({type:`tool_call_start`,callId:e,toolName:n.toolName,sessionId:o}))},f=(e,t,n)=>{let r=u(e);t&&!r.toolName&&(r.toolName=t),typeof n==`string`&&n.length>0&&(r.argsText+=n),d(e,r.toolName),a.push({type:`tool_call_delta`,callId:e,toolName:r.toolName,argsTextDelta:n,sessionId:o})},p=()=>{c||(c=!0,a.push({type:`text_start`,sessionId:o}))},m=()=>{!c||l||(l=!0,a.push({type:`text_end`,content:e.currentResponse,sessionId:o}))},h=()=>{for(let[t,n]of s){if(!n.toolName)continue;let r={id:t,type:`function`,function:{name:n.toolName,arguments:n.argsText}};this._tools&&e.pendingToolCalls.push({toolCall:r}),a.push({type:`tool_call_end`,toolCall:r,sessionId:o})}s.clear()},g=(()=>{if(!i)return;let e={...i};return typeof e.maxOutputTokens!=`number`&&typeof i.maxTokens==`number`&&(e.maxOutputTokens=i.maxTokens),delete e.maxTokens,e})(),_=r?{model:r,messages:Be(e.messages),tools:n,signal:t,...g??{}}:{messages:Be(e.messages),tools:n,signal:t,...g??{}};try{for await(let n of this._modelClient.stream(_))if(R(t,`Session streaming`),n.type===`delta`)if(n.chunk.kind===`text`)p(),e.currentResponse+=n.chunk.text,a.push({type:`text_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_start`)a.push({type:`thinking_start`,sessionId:o});else if(n.chunk.kind===`thinking_delta`)e.currentThinking=(e.currentThinking??``)+n.chunk.text,a.push({type:`thinking_delta`,delta:n.chunk.text,sessionId:o});else if(n.chunk.kind===`thinking_end`){let t=typeof n.chunk.text==`string`?n.chunk.text:``;t&&typeof e.currentThinking!=`string`&&(e.currentThinking=t);let r=typeof e.currentThinking==`string`?e.currentThinking:t;a.push({type:`thinking_end`,sessionId:o,...r?{content:r}:{}})}else n.chunk.kind===`tool_call_delta`&&f(n.chunk.callId,n.chunk.toolId,n.chunk.argsTextDelta);else if(n.type===`response_end`){m(),h(),e.lastModelStopReason=n.stopReason;let t=n.usage;if(t&&typeof t==`object`){let n=t;if(n.prompt_tokens||n.completion_tokens||n.total_tokens){let t={promptTokens:n.prompt_tokens??0,completionTokens:n.completion_tokens??0,totalTokens:n.total_tokens??0};e.usage.promptTokens+=t.promptTokens,e.usage.completionTokens+=t.completionTokens,e.usage.totalTokens+=t.totalTokens,this._recordUsage(t)}}}else if(n.type===`error`&&n.terminal!==!1){let t=n.error?.code??`model_error`;e.error=new z(n.error?.message??`Model error`,{code:t,retryable:n.error?.retryable}),e.shouldContinue=!1,e.stopReason=`error`}}catch(n){if(n instanceof L)throw n;if(t?.aborted)throw new L(typeof t?.reason==`string`?t.reason:`Agent execution aborted`);e.error=n instanceof Error?n:Error(String(n)),e.shouldContinue=!1,e.stopReason=`error`}finally{m(),s.size>0&&h()}return a}async executeToolCall(e,t,n,r){R(n,`Tool execution: ${e.toolCall.function.name}`);let i=r?new Se(r):void 0,a=e.toolCall.id,o=e.toolCall,s=o,c=e=>({sessionId:t.sessionId,agentId:t.agentId,toolCall:e,toolContext:t});if(i){let n=await i.executePreToolUse(c(s));if(!n.allow)return e.result=`Tool execution blocked by PreToolUse hook`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};n.modifiedToolCall&&(s={...n.modifiedToolCall,id:a,type:o.type})}let l=this._tools?.get(s.function.name);if(!l)return e.result=`Tool not found: ${s.function.name}`,e.isError=!0,{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId};try{let n=typeof s.function.arguments==`string`?JSON.parse(s.function.arguments):s.function.arguments;return e.result=await l.execute(n,t),e.isError=!1,i&&await i.executePostToolUse(c(s),e.result),{type:`tool_result`,tool_call_id:a,result:e.result,sessionId:t.sessionId}}catch(n){let r=n instanceof Error?n:Error(String(n));return e.result=r.message,e.isError=!0,i&&await i.executePostToolUseFailure(c(s),r),{type:`tool_result`,tool_call_id:a,result:e.result,isError:!0,sessionId:t.sessionId}}}createToolExecutionContext(e,t){return{sessionId:e.sessionId,agentId:e.agentId,signal:t,usage:e.usage,emitEvent:t=>{this.toolEventQueue.push({...t,sessionId:e.sessionId})}}}mergeStateResults(e,t){e.currentResponse=t.currentResponse,e.currentThinking=t.currentThinking,e.pendingToolCalls=t.pendingToolCalls,e.usage=t.usage,e.metadata=t.metadata}addToolResultToHistory(e,t){let n=t.result,r,i=t.isError;if(typeof n==`string`)r=n;else if(n&&typeof n==`object`&&`content`in n){let e=n;r=JSON.stringify(e.content),e.isError===!0&&(i=!0)}else r=JSON.stringify(n);e.messages.push({role:`tool`,tool_call_id:t.toolCall.id,content:r,...i?{isError:!0}:{}})}addAssistantMessageWithToolCalls(e){let t=typeof e.currentThinking==`string`?e.currentThinking:void 0;e.messages.push({role:`assistant`,content:e.currentResponse||``,tool_calls:e.pendingToolCalls.map(e=>ze(e.toolCall)),...t&&t.length>0?{reasoning_content:t}:{}})}addFinalAssistantMessage(e){e.currentResponse&&e.messages.push({role:`assistant`,content:e.currentResponse})}async*_streamWithState(e,t){let n=t.maxIterations??30,r=t.signal,i=Ce(this._middlewares),a=this.createToolExecutionContext(e,r),o=this._stateStore,s=o?.savePoint??`before`,c=o?.deleteOnComplete??!0,l=t.model?{modelId:t.model.modelId,provider:t.model.provider}:this._modelClient?{modelId:this._modelClient.modelId}:void 0;for(;e.shouldContinue;){if(R(r,`Session iteration ${e.iteration}`),e.iteration>=n){e.shouldContinue=!1,e.stopReason=`max_iterations`,yield{type:`done`,finalResponse:e.currentResponse,stopReason:`max_iterations`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId};break}if(yield{type:`iteration_start`,iteration:e.iteration,sessionId:e.sessionId},e.pendingToolCalls.length>0){try{yield*this.handleToolCalls(e,a,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:o,checkpointModelConfig:l,requestParams:t.requestParams})}catch(e){if(e instanceof be)return;throw e}if(e.metadata?._pendingUserInput){let t=e.metadata._pendingUserInput;delete e.metadata._pendingUserInput,e.messages.push({role:`user`,content:t})}continue}if(e.currentResponse=``,e.currentThinking=void 0,e.pendingToolCalls=[],e.lastModelStopReason=void 0,o&&(s===`before`||s===`both`)){let n=k(e,{agentName:this._agentName,modelConfig:l,requestParams:t.requestParams});await o.saveCheckpoint(n)}let u=[],d=await i(e,async e=>{R(r,`Session model call`);let n=this.collectBlockedTools(e);e.metadata.blockedTools=n;let i=this.getToolsForModel(e);return u=await this.executeModelStream(e,r,i,t.model,t.requestParams),e});if(this.mergeStateResults(e,d),o&&(s===`after`||s===`both`)){let n=k(e,{agentName:this._agentName,modelConfig:l,requestParams:t.requestParams});await o.saveCheckpoint(n)}for(let e of u)yield e;if(R(r,`Session iteration ${e.iteration}`),e.stopReason===`error`){yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:e.pendingToolCalls.length,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`error`,modelStopReason:e.lastModelStopReason,error:Re(e.error),usage:{...e.usage},sessionId:e.sessionId};break}if(e.pendingToolCalls.length>0)try{yield*this.handleToolCalls(e,a,{signal:r,toolContextInput:t.toolContext,hooks:t.hooks,stateStore:o,checkpointModelConfig:l,requestParams:t.requestParams})}catch(e){if(e instanceof be)return;throw e}else yield*this.handleFinalResponse(e);if(!e.shouldContinue){o&&c&&await o.deleteCheckpoint(e.sessionId);break}}}static APPROVAL_REQUIRED_LEVELS=new Set([`high`,`critical`]);requiresApproval(t){return e.APPROVAL_REQUIRED_LEVELS.has(t)}async*handleToolCalls(e,t,n){let r=e.pendingToolCalls.length,i=n?.signal,a=n?.toolContextInput,o=a?.approval,s=o?.strategy??`high_risk`,c=o?.autoApprove!==!0,l=o?.decisions??{},u=e=>c?s===`all`?!0:this.requiresApproval(e):!1,d=t=>e.messages.some(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return!1;let n=e.tool_calls;return Array.isArray(n)&&n.some(e=>e?.id===t)}),f=t=>{d(t)||this.addAssistantMessageWithToolCalls(e)},p=t=>e.messages.some(e=>e&&typeof e==`object`&&e.role===`tool`&&e.tool_call_id===t),m=new Set,h=e=>{try{return typeof e.function.arguments==`string`?JSON.parse(e.function.arguments):e.function.arguments}catch(t){let n=t instanceof Error?t.message:String(t);return{_raw:e.function.arguments,_parseError:n}}},g=t=>{let n=[];for(let r=t;r<e.pendingToolCalls.length;r++){let t=e.pendingToolCalls[r];if(p(t.toolCall.id)||m.has(t.toolCall.id)||l[t.toolCall.id])continue;let i=this._tools?.get(t.toolCall.function.name),a=i?.riskLevel??`safe`;i&&this.isToolDisabled(t.toolCall.function.name)||i&&this.isToolBlocked(e,t.toolCall.function.name)||!i||!u(a)||(m.add(t.toolCall.id),n.push({type:`tool_approval_requested`,tool_call_id:t.toolCall.id,toolName:t.toolCall.function.name,riskLevel:a,args:h(t.toolCall),sessionId:e.sessionId}))}return n};if(e.metadata?.parallelMode===!0){let r=e.pendingToolCalls.filter(e=>{let t=e.toolCall.function.name;return t===`Task`||t.endsWith(`:Task`)});r.length>1&&(yield*this.executeTasksInParallel(r,e,t,n),e.pendingToolCalls=e.pendingToolCalls.filter(e=>!r.includes(e)))}for(let r=0;r<e.pendingToolCalls.length;r++){let o=e.pendingToolCalls[r];if(p(o.toolCall.id)){e.pendingToolCalls.splice(r,1),r--;continue}let s=o.toolCall.function.name,c=this._tools?.get(s),d=c?.riskLevel??`safe`;if(c&&this.isToolBlocked(e,s)){let t=`Tool "${s}" is blocked by middleware`;o.result=`Tool execution skipped: ${t}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:s,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}if(c&&this.isToolDisabled(s)){let t=`Tool "${s}" is disabled for this session`;o.result=`Tool execution skipped: ${t}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:s,reason:t,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}if(c&&u(d)){let t=l[o.toolCall.id];if(!t){e.stopReason=`approval_required`;for(let e of g(r))yield e;let t=k(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for approval: ${s}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(t),yield{type:`requires_action`,kind:`tool_approval`,checkpoint:n?.stateStore?void 0:t,checkpointRef:n?.stateStore?{sessionId:t.sessionId,agentId:t.agentId}:void 0,sessionId:e.sessionId},this.messages=e.messages.filter(e=>e.role!==`system`),await this.save(),yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new be}if(!t.approved){let n=t.reason??`User denied approval`;o.result=`Tool execution skipped: ${n}`,o.isError=!0,f(o.toolCall.id),yield{type:`tool_skipped`,tool_call_id:o.toolCall.id,toolName:o.toolCall.function.name,reason:n,sessionId:e.sessionId},yield{type:`tool_result`,tool_call_id:o.toolCall.id,result:o.result,isError:!0,sessionId:e.sessionId},this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}}f(o.toolCall.id),this.toolEventQueue=[];let m=await this.executeToolCall(o,t,i,n?.hooks);for(let e of this.toolEventQueue)yield e;this.toolEventQueue=[];let h=m.type===`tool_result`&&(m.isError||m.result&&typeof m.result==`object`&&m.result.isError===!0);if(c&&c.name===`AskUserQuestion`&&h){let s=a?.askUser?.answers?.[o.toolCall.id];if(s){let a={...typeof o.toolCall.function.arguments==`string`?JSON.parse(o.toolCall.function.arguments):o.toolCall.function.arguments,answers:s};o.toolCall.function.arguments=JSON.stringify(a),this.toolEventQueue=[];let c=await this.executeToolCall(o,t,i,n?.hooks);for(let e of this.toolEventQueue)yield e;this.toolEventQueue=[],yield c,this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--;continue}else{yield m,e.stopReason=`approval_required`;let t=(typeof o.toolCall.function.arguments==`string`?JSON.parse(o.toolCall.function.arguments):o.toolCall.function.arguments)?.questions||[],r=k(e,{agentName:this._agentName,phase:`approval_pending`,status:`Waiting for user answers: ${c.name}`,modelConfig:n?.checkpointModelConfig,requestParams:n?.requestParams});throw n?.stateStore&&await n.stateStore.saveCheckpoint(r),this.messages=e.messages.filter(e=>e.role!==`system`),await this.save(),yield{type:`requires_action`,kind:`ask_user`,toolCallId:o.toolCall.id,questions:t,checkpoint:n?.stateStore?void 0:r,checkpointRef:n?.stateStore?{sessionId:r.sessionId,agentId:r.agentId}:void 0,sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`approval_required`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId},new be}}yield m,this.addToolResultToHistory(e,o),e.pendingToolCalls.splice(r,1),r--}e.pendingToolCalls=[],e.iteration++,yield{type:`iteration_end`,iteration:e.iteration-1,willContinue:!0,toolCallCount:r,usage:{...e.usage},sessionId:e.sessionId}}async*executeTasksInParallel(e,t,n,r){this.toolEventQueue=[];let i=[],a=!1,o=e.map(async e=>{let r=e.toolCall.function.name,a=this._tools?.get(r);if(!a)return{tc:e,result:`Tool "${r}" not found`,isError:!0,events:[]};try{let r=typeof e.toolCall.function.arguments==`string`?JSON.parse(e.toolCall.function.arguments):e.toolCall.function.arguments,o=`${t.sessionId}:subagent:${crypto.randomUUID()}`,s=[],c={...n,sessionId:o,emitEvent:e=>{let n={...e,sessionId:t.sessionId};s.push(n),i.push(n)}};return{tc:e,result:await a.execute(r,c),isError:!1,events:s}}catch(t){return{tc:e,result:`Task execution failed: ${t instanceof Error?t.message:String(t)}`,isError:!0,events:[]}}}),s=Promise.allSettled(o).then(e=>(a=!0,e));for(;!a||i.length>0;)if(i.length>0){let e=i.shift();e&&(yield e)}else a||await new Promise(e=>setTimeout(e,5));let c=await s;for(let[n,r]of c.entries()){let i=e[n];if(r.status===`fulfilled`){let{result:e,isError:t}=r.value;i.result=e,i.isError=t}else i.result=`Task execution rejected: ${r.reason}`,i.isError=!0;this.hasAssistantToolCallMessage(t,i.toolCall.id)||this.addAssistantMessageWithToolCalls(t),yield{type:`tool_result`,tool_call_id:i.toolCall.id,result:i.result,isError:i.isError,sessionId:t.sessionId},this.addToolResultToHistory(t,i)}}hasAssistantToolCallMessage(e,t){return e.messages.some(e=>{if(!e||typeof e!=`object`||e.role!==`assistant`)return!1;let n=e.tool_calls;return Array.isArray(n)&&n.some(e=>e?.id===t)})}async*handleFinalResponse(e){e.shouldContinue=!1,e.stopReason=`final_response`,this.addFinalAssistantMessage(e),yield{type:`iteration_end`,iteration:e.iteration,willContinue:!1,toolCallCount:0,usage:{...e.usage},sessionId:e.sessionId},yield{type:`done`,finalResponse:e.currentResponse,stopReason:`final_response`,modelStopReason:e.lastModelStopReason,usage:{...e.usage},sessionId:e.sessionId}}async _finalizeRun(e,t){this.messages=e.messages.filter(e=>e.role!==`system`),e.usage.totalTokens>0&&this.addUsage(e.usage);let n=Date.now()-t;this.recordResponse(n),await this.save()}async save(){let e=this.toSnapshot();await this._stateStore.save(this.id,I.SESSION,e)}async load(){let e=await this._stateStore.load(this.id,I.SESSION);return e?(this.restoreFromSnapshot(e),!0):!1}setStatus(e,t){super.setStatus(e,t),this._autoSave&&this.save().catch(()=>{})}markActive(){super.markActive(),this._autoSave&&this.save().catch(()=>{})}addMessage(e){super.addMessage(e),this._autoSave&&this.save().catch(()=>{})}addUsage(e){super.addUsage(e),this._autoSave&&this.save().catch(()=>{})}recordResponse(e){super.recordResponse(e),this._autoSave&&this.save().catch(()=>{})}incrementToolCallCount(){super.incrementToolCallCount(),this._autoSave&&this.save().catch(()=>{})}setModelOverride(e){super.setModelOverride(e),this._modelOverride=this.resolveModelRef(e)??this._modelOverride,this._autoSave&&this.save().catch(()=>{})}clearModelOverride(){super.clearModelOverride(),this._modelOverride=void 0,this._autoSave&&this.save().catch(()=>{})}setSystemPromptOverride(e){super.setSystemPromptOverride(e),this._autoSave&&this.save().catch(()=>{})}clearSystemPromptOverride(){super.clearSystemPromptOverride(),this._autoSave&&this.save().catch(()=>{})}disableTools(e){super.disableTools(e),this._autoSave&&this.save().catch(()=>{})}enableAllTools(){super.enableAllTools(),this._autoSave&&this.save().catch(()=>{})}setAutoSave(e){this._autoSave=e}},Ve=class extends ve{_stateStore;constructor(e){super(),this._stateStore=e}async create(e){let t=e??a(),n=Date.now(),r={id:t,createdAt:n,state:{status:`active`,updatedAt:n,lastActiveAt:n},context:{messages:[],messageCount:0,toolCallCount:0},stats:{usage:{promptTokens:0,completionTokens:0,totalTokens:0},responseCount:0}},i=new B(this._stateStore,t,r);return await i.save(),i}async get(e){let t=await this._stateStore.load(e,I.SESSION);if(t)return new B(this._stateStore,e,t)}async list(){let e=await this._stateStore.listSessions(),t=[];for(let n of e){let e=await this._stateStore.load(n,I.SESSION);if(e){let r=new B(this._stateStore,n,e);t.push(r)}}return t}async destroy(e){await this._stateStore.deleteSession(e)}},He=class{savePoint;deleteOnComplete;constructor(e){this.savePoint=e?.savePoint??`before`,this.deleteOnComplete=e?.deleteOnComplete??!0}assertValidStorageSegment(e,t){if(!t)throw Error(`${e} must be a non-empty string`);if(t===`.`||t===`..`)throw Error(`${e} must not be "." or ".."`);if(t.includes(`/`)||t.includes(`\\`))throw Error(`${e} must not contain path separators`);if(t.includes(`\0`))throw Error(`${e} must not contain NUL bytes`)}async save(e,t,n){let r=this.buildPath(e,t),i=JSON.stringify(n,null,2);await this._write(r,i)}async load(e,t){let n=this.buildPath(e,t),r=await this._read(n);if(r!==void 0)try{return JSON.parse(r)}catch{return}}async delete(e,t){let n=this.buildPath(e,t);await this._delete(n)}async deleteSession(e){let t=this.buildPrefix(e),n=await this._list(t);await Promise.all(n.map(e=>this._delete(e)))}async listKeys(e){let t=this.buildPrefix(e);return(await this._list(t)).map(t=>this.extractKey(e,t))}async exists(e,t){let n=this.buildPath(e,t);return this._exists(n)}async saveCheckpoint(e){let t={_meta:{description:`GoatChain Agent Loop Checkpoint - DO NOT EDIT MANUALLY`,savedAt:new Date().toISOString(),agentId:e.agentId,agentName:e.agentName,sessionId:e.sessionId,iteration:e.iteration,phase:e.phase,status:e.status,messageCount:e.messages.length,toolCallsPending:e.pendingToolCalls?.length??0},checkpoint:e};await this.save(e.sessionId,I.CHECKPOINT,t)}async loadCheckpoint(e){return(await this.load(e,I.CHECKPOINT))?.checkpoint}async deleteCheckpoint(e){await this.delete(e,I.CHECKPOINT)}async listCheckpoints(){let e=await this.listSessions(),t=[];for(let n of e){let e=await this.loadCheckpoint(n);e&&t.push(e)}return t}async listSessions(){let e=await this._list(``),t=new Set;for(let n of e){let e=this.extractSessionId(n);e&&t.add(e)}return Array.from(t)}buildPath(e,t){return this.assertValidStorageSegment(`sessionId`,e),this.assertValidStorageSegment(`key`,t),`${e}/${t}`}buildPrefix(e){return this.assertValidStorageSegment(`sessionId`,e),`${e}/`}extractKey(e,t){let n=this.buildPrefix(e);return t.startsWith(n)?t.slice(n.length):t}extractSessionId(e){let t=e.split(`/`);return t.length>0?t[0]:void 0}},Ue=class extends He{baseDir;constructor(e){super(e),this.baseDir=m.resolve(e.dir),this.ensureDir(this.baseDir)}async _write(e,t){let n=this.toFilePath(e);this.ensureDir(m.dirname(n)),w(n,t,`utf-8`)}async _read(e){let t=this.toFilePath(e);try{return _(t)?y(t,`utf-8`):void 0}catch{return}}async _delete(e){let t=this.toFilePath(e);_(t)&&x(t);let n=m.dirname(t);if(_(n))try{b(n).length===0&&x(n,{recursive:!0})}catch{}}async _exists(e){return _(this.toFilePath(e))}async _list(e){let t=[];if(!_(this.baseDir))return t;let n=b(this.baseDir,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name);for(let r of n){if(e&&!r.startsWith(e.split(`/`)[0]))continue;let n=m.join(this.baseDir,r),i=this.listJsonFiles(n);for(let n of i){let i=`${r}/${m.basename(n,`.json`)}`;(!e||i.startsWith(e))&&t.push(i)}}return t}toFilePath(e){return m.join(this.baseDir,`${e}.json`)}ensureDir(e){_(e)||v(e,{recursive:!0})}listJsonFiles(e){return _(e)?b(e).filter(e=>e.endsWith(`.json`)).map(t=>m.join(e,t)):[]}getBaseDir(){return this.baseDir}clear(){_(this.baseDir)&&(x(this.baseDir,{recursive:!0}),v(this.baseDir,{recursive:!0}))}},We=class extends He{store=new Map;constructor(e){super(e)}async _write(e,t){this.store.set(e,t)}async _read(e){return this.store.get(e)}async _delete(e){this.store.delete(e)}async _exists(e){return this.store.has(e)}async _list(e){let t=[];for(let n of this.store.keys())(e===``||n.startsWith(e))&&t.push(n);return t}clear(){this.store.clear()}stats(){let e=new Set;for(let t of this.store.keys()){let n=this.extractSessionId(t);n&&e.add(n)}return{entryCount:this.store.size,sessionCount:e.size}}},Ge=class{id;name;systemPrompt;createdAt;_model;_modelOverride;_tools;_stateStore;_sessionManager;_middlewares=[];_middlewareCounter=0;_middlewareTools=new Map;constructor(e){this.id=e.id??crypto.randomUUID(),this.name=e.name,this.systemPrompt=e.systemPrompt,this.createdAt=Date.now(),this._model=e.model,this._tools=e.tools,this._stateStore=e.stateStore??new We({savePoint:`before`}),this._sessionManager=new Ve(this._stateStore);let t=e.middleware??[];for(let e of t)this.use(e)}get model(){return this._model}get modelId(){return this.modelRef?.modelId??this._model.modelId}get modelRef(){return this._modelOverride??this._model.modelRef}get modelRefs(){let e=this._model.modelRefs;if(Array.isArray(e))return e;let t=this._model.modelRef;return t?[t]:[]}get tools(){return this._tools}get stateStore(){return this._stateStore}get sessionManager(){return this._sessionManager}async createSession(e){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let t=await this._sessionManager.create(e?.sessionId);if(!this._stateStore)throw Error(`StateStore is required to create sessions`);let n=t.toSnapshot();return new B(this._stateStore,t.id,n,{...e,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map(e=>e.fn),hasCheckpoint:!1,emitSessionCreatedEvent:!0})}async resumeSession(e,t){if(!this._sessionManager)throw Error(`SessionManager is not configured`);let n=await this._sessionManager.get(e);if(!n)throw Error(`Session not found: ${e}`);let r=!!await this._stateStore?.loadCheckpoint(e);if(!this._stateStore)throw Error(`StateStore is required to resume sessions`);let i=n.toSnapshot();return new B(this._stateStore,n.id,i,{...t,modelClient:this._model,systemPrompt:this.systemPrompt,agentName:this.name,tools:this._tools,middlewares:this._middlewares.map(e=>e.fn),hasCheckpoint:r,emitSessionCreatedEvent:!1})}use(e,t){let n=t??e.__middlewareName??`middleware_${this._middlewareCounter++}`;if(this._middlewares.some(e=>e.name===n))throw Error(`Middleware with name "${n}" already exists`);let r={name:n,fn:e};return this._middlewares.push(r),e.__createTools&&typeof e.__createTools==`function`&&this._registerMiddlewareTools(n,e.__createTools),()=>{this.removeMiddleware(n)}}removeMiddleware(e){let t=-1,n;return typeof e==`string`?(t=this._middlewares.findIndex(t=>t.name===e),n=e):(t=this._middlewares.findIndex(t=>t.fn===e),t>-1&&(n=this._middlewares[t].name)),t>-1&&n?(this._unregisterMiddlewareTools(n),this._middlewares.splice(t,1),!0):!1}clearMiddlewares(){for(let e of this._middlewareTools.keys())this._unregisterMiddlewareTools(e);this._middlewares=[]}get middlewares(){return[...this._middlewares]}get middlewareNames(){return this._middlewares.map(e=>e.name)}setModel(e){(e=>!!(e&&typeof e==`object`&&typeof e.provider==`string`&&typeof e.modelId==`string`&&typeof e.stream!=`function`))(e)?this._modelOverride=e:(this._model=e,this._modelOverride=void 0)}_getNamespacedToolName(e,t){return`${e}:${t}`}_registerMiddlewareTools(e,t){if(!this._tools)return;let n=t(),r=[];for(let t of n){let n=this._getNamespacedToolName(e,t.name),i=Object.create(Object.getPrototypeOf(t));Object.assign(i,t),Object.defineProperty(i,`name`,{value:n,writable:!1,configurable:!0});try{this._tools.register(i),r.push(n)}catch(e){console.warn(`Failed to register tool ${n}:`,e)}}r.length>0&&this._middlewareTools.set(e,r)}_unregisterMiddlewareTools(e){if(!this._tools)return;let t=this._middlewareTools.get(e);if(t){for(let e of t)this._tools.unregister(e);this._middlewareTools.delete(e)}}};function Ke(e){return{content:[{type:`text`,text:e}]}}function V(e){return{content:[{type:`text`,text:e}],isError:!0}}function qe(e,t){return{content:[{type:`image`,data:e,mimeType:t}]}}var H=class{riskLevel=`safe`},Je=class extends H{name=`AskUserQuestion`;riskLevel=`safe`;description=`Use this tool when you need to ask the user questions during execution. This allows you to:
113
113
  1. Gather user preferences or requirements
114
114
  2. Clarify ambiguous instructions
115
115
  3. Get decisions on implementation choices as you work
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "goatchain-cli",
3
3
  "type": "module",
4
- "version": "0.0.3-beta.10",
4
+ "version": "0.0.3-beta.11",
5
5
  "description": "GoatChain CLI",
6
6
  "author": "Simon He",
7
7
  "license": "MIT",