goatchip 0.0.2-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +4 -0
- package/dist/index.js +5 -0
- package/dist/openai-muUR2FyU.js +16 -0
- package/dist/repl-DPVyIucO.js +47 -0
- package/dist/ui-8G7VzOtK.js +3 -0
- package/package.json +42 -0
package/dist/cli.mjs
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{i as e,r as t,u as n}from"./ui-8G7VzOtK.js";import{randomUUID as r}from"node:crypto";import{mkdir as i,readFile as a,readdir as o,rename as s,stat as c,unlink as l,writeFile as u}from"node:fs/promises";import d from"node:path";import{fileURLToPath as f,pathToFileURL as p}from"node:url";async function m(){try{return await import(`goatchain`)}catch(e){let t=e instanceof Error?e.message:String(e);try{let e=d.dirname(f(import.meta.url)),t=[d.resolve(e,`../../dist/index`),d.resolve(e,`../../../dist/index`)];for(let e of t)try{return await import(p(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(`
|
|
2
|
+
`))}}function h(e,t){return{get modelId(){return e.modelId},...typeof e?.setModelId==`function`?{setModelId(t){e.setModelId(t)}}:{},async invoke(t,n){return e.invoke(t,n)},stream:(n,r)=>Array.isArray(n)?e.stream(n,r):e.stream({...t,...n}),...typeof e?.run==`function`?{run:n=>e.run({...t,...n})}:{}}}function g(e,t){let{ToolRegistry:n,WriteTool:r,ReadTool:i,EditTool:a,GlobTool:o,GrepTool:s,WebSearchTool:c}=e;if(![n,r,i,a,o,s,c].every(e=>typeof e==`function`))throw Error(["Missing builtin tool exports from `goatchain`.","Reinstall the package, or rebuild it from the repo (`pnpm -r -s build`)."].join(`
|
|
3
|
+
`));let l=d.join(t,`.goatchain`),u=(e,t)=>{let n=d.relative(d.resolve(e),d.resolve(t));return n===``?!0:n===`..`?!1:!n.startsWith(`..${d.sep}`)&&!d.isAbsolute(n)},f=e=>{if(u(l,e))throw Error(`Access denied: ${e}\nRestricted: ${l}`)},p=e=>{let n=d.isAbsolute(e)?e:d.resolve(t,e);if(!u(t,n))throw Error(`Access denied: ${n}\nAllowed directory: ${t}`);return f(n),n},m=e=>{let n=d.isAbsolute(e)?e:d.resolve(t,e);if(!u(t,n))throw Error(`Access denied: ${n}\nAllowed directory: ${t}`);return f(n),n},h=new n,g=new r({cwd:t,allowedDirectory:t});h.register({name:g.name,description:g.description,parameters:g.parameters,riskLevel:g.riskLevel,execute:e=>(e&&typeof e==`object`&&`file_path`in e&&p(e.file_path),g.execute(e))});let _=new i({cwd:t,allowedDirectory:t});h.register({name:_.name,description:_.description,parameters:_.parameters,riskLevel:_.riskLevel,execute:e=>(e&&typeof e==`object`&&`file_path`in e&&p(e.file_path),_.execute(e))});let v=new a({cwd:t});h.register({name:v.name,description:v.description,parameters:v.parameters,riskLevel:v.riskLevel,execute:e=>(e&&typeof e==`object`&&`file_path`in e&&p(e.file_path),v.execute(e))});let y=new o({cwd:t});h.register({name:y.name,description:y.description,parameters:y.parameters,riskLevel:y.riskLevel,execute:e=>(e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&e.path.trim()&&m(e.path),y.execute(e))});let b=new s({cwd:t});if(h.register({name:b.name,description:b.description,parameters:b.parameters,riskLevel:b.riskLevel,execute:e=>(e&&typeof e==`object`&&`path`in e&&typeof e.path==`string`&&e.path.trim()&&m(e.path),b.execute(e))}),process.env.SERPER_API_KEY){let e=new c({apiKey:process.env.SERPER_API_KEY});h.register({name:e.name,description:e.description,parameters:e.parameters,riskLevel:e.riskLevel,execute:t=>e.execute(t)})}return{registry:h,workspaceCwd:t}}async function _(e,{getApiKey:t,modelId:n,baseUrl:r,requestDefaults:i}){let{createModel:a,createOpenAIAdapter:o}=e;if(typeof a==`function`&&typeof o==`function`)return h(a({adapters:[o({defaultModelId:n,baseUrl:r,apiKeySecretName:`OPENAI_API_KEY`,secretProvider:{get:e=>e===`OPENAI_API_KEY`?t():process.env[e]}})]}),i);let{default:s}=await import(`./openai-muUR2FyU.js`),c=null,l=n,u=r,d=()=>{if(c)return c;let e=t()??process.env.OPENAI_API_KEY;if(!e)throw Error(`Missing OPENAI_API_KEY (required for chatting)`);return c=new s({apiKey:e,baseURL:u||void 0}),c};return{get modelId(){return l},setModelId(e){l=e},setBaseUrl(e){u=e,c=null},resetClient(){c=null},async invoke(e){let t=await d().chat.completions.create({model:l,messages:e,stream:!1,max_completion_tokens:i.maxOutputTokens??void 0,temperature:i.temperature??void 0,top_p:i.topP??void 0,presence_penalty:i.presencePenalty??void 0,frequency_penalty:i.frequencyPenalty??void 0,seed:i.seed??void 0}),n=Array.isArray(t?.choices)?t.choices[0]:void 0;return{message:{role:`assistant`,content:typeof n?.message?.content==`string`?n.message.content:``}}},stream:async function*(e,t){let n=d(),r=Array.isArray(e),a=r?e:e?.messages??[],o=r?t?.tools:e?.tools,s=r?void 0:e?.signal,c=r?l:e?.model?.modelId??l,u=await n.chat.completions.create({model:c,messages:a,tools:o,stream:!0,stream_options:{include_usage:!0},max_completion_tokens:i.maxOutputTokens??void 0,temperature:i.temperature??void 0,top_p:i.topP??void 0,presence_penalty:i.presencePenalty??void 0,frequency_penalty:i.frequencyPenalty??void 0,seed:i.seed??void 0},{signal:s,timeout:typeof i.timeoutMs==`number`?i.timeoutMs:void 0});for await(let e of u){let t=e?.choices?.[0]?.delta?.content;typeof t==`string`&&t.length>0&&(yield{type:`text_delta`,delta:t});let n=e?.usage;n&&typeof n==`object`&&(yield{type:`usage`,usage:{promptTokens:n.prompt_tokens??0,completionTokens:n.completion_tokens??0,totalTokens:n.total_tokens??0}})}yield{type:`done`}}}}async function v({getApiKey:e,modelId:t,system:n,baseUrl:r,requestDefaults:i}){let a=await m(),{Agent:o,FileStateStore:s}=a,c=process.cwd(),l=g(a,c),u=await _(a,{getApiKey:e,modelId:t,baseUrl:r,requestDefaults:i}),f=new s({dir:d.join(c,`.goatchain`),savePoint:`both`,deleteOnComplete:!1}),p=[`You are a helpful assistant.`,`If you need to inspect the local project (files, folders, code), you MUST use the provided tools (Read/Glob/Grep) and must not claim you did unless a tool was actually called.`,`When your plan depends on inspecting the project, call the tool(s) immediately instead of stopping after saying you will.`,`After using tools, continue and produce a user-visible result in the SAME run (do not stop right after inspection).`,`For coding or file-creation tasks, you MUST implement by creating/editing files in the workspace using Write/Edit, then briefly summarize what you changed and where.`,`Write/Edit may require user approval in the CLI; still call them when needed (the CLI will prompt the user).`,`Do NOT end your response right after saying "I will create/implement …" — either ask a necessary clarifying question or start writing files with tools.`].join(`
|
|
4
|
+
`);return{agent:new o({name:`GoatChain CLI`,systemPrompt:n??p,model:u,tools:l.registry,stateStore:f}),model:u,tools:l,stateStore:f}}function y(e){let t=d.join(e,`.goatchain`);return{workspaceCwd:e,cacheDir:t,sessionsDir:d.join(t,`sessions`),configPath:d.join(t,`config.json`)}}async function b(e){await i(e,{recursive:!0})}async function x(e){try{let t=await a(e,`utf8`);return JSON.parse(t)}catch(e){if(e&&typeof e==`object`&&e.code===`ENOENT`)return;throw e}}async function S(e,t){await b(d.dirname(e));let n=`${e}.tmp.${r()}`;await u(n,`${JSON.stringify(t,null,2)}\n`,{mode:384}),await s(n,e)}async function C(e){let t=await x(e.configPath);return!t||typeof t!=`object`?{schemaVersion:1}:t}async function w(e,t){let n={schemaVersion:1,...t,updatedAt:Date.now()};return await S(e.configPath,n),n}function T(e,t){return d.join(e.sessionsDir,`${t}.json`)}async function E(e,t){let n=await x(T(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}}async function D(n,r){let i=T(n,r.sessionId),a=Array.isArray(r.messages)?r.messages:[],o=typeof r.title==`string`&&r.title.trim()?r.title.trim():e(a),s=typeof r.summary==`string`&&r.summary.trim()?r.summary.trim():t(a),c=typeof r.pinned==`boolean`?r.pinned:!1,l={schemaVersion:1,sessionId:r.sessionId,createdAt:r.createdAt??Date.now(),updatedAt:Date.now(),modelId:r.modelId,systemPrompt:r.systemPrompt,title:o,summary:s,pinned:c,messages:a};return await S(i,l),l}async function O(e){await b(e.sessionsDir);let t=await o(e.sessionsDir),n=[];for(let r of t)if(r.endsWith(`.json`))try{let t=await E(e,r.slice(0,-5));t&&n.push(t)}catch{}return n.sort((e,t)=>{let n=e.pinned?1:0,r=t.pinned?1:0;return r===n?(t.updatedAt??0)-(e.updatedAt??0):r-n}),n}async function k(e,t,n){let r=await E(e,t);if(!r)return;let i=typeof n==`string`?n.trim():``;return D(e,{sessionId:r.sessionId,createdAt:r.createdAt,modelId:r.modelId,systemPrompt:r.systemPrompt,title:i,summary:r.summary,pinned:r.pinned,messages:r.messages})}async function A(e,t,n){let r=await E(e,t);if(r)return D(e,{sessionId:r.sessionId,createdAt:r.createdAt,modelId:r.modelId,systemPrompt:r.systemPrompt,title:r.title,summary:r.summary,pinned:!!n,messages:r.messages})}async function j(e,t,n){let r=Array.isArray(t)?t:[],i=[];for(let t of r){if(!t||typeof t!=`string`)continue;let r=await A(e,t,n);i.push({sessionId:t,pinned:!!n,updated:!!r})}return i}async function M(e,t){let n=T(e,t);try{return await l(n),!0}catch{return!1}}async function N(e,t){let n=Array.isArray(t)?t:[],r=[];for(let t of n){if(!t||typeof t!=`string`)continue;let n=await M(e,t);r.push({sessionId:t,deleted:n})}return r}async function P(){try{let e=new URL(`../package.json`,import.meta.url),{readFile:t}=await import(`node:fs/promises`),n=JSON.parse(await t(e,`utf8`));return typeof n?.version==`string`?n.version:`0.0.0`}catch{return`0.0.0`}}async function F({agent:e,prompt:t}){let n=[],i=r();for await(let r of e.stream({sessionId:i,input:t,messages:n,toolContext:{approval:{strategy:`high_risk`,autoApprove:process.env.GOATCHAIN_AUTO_APPROVE===`1`}}}))if(r.type===`text_delta`)process.stdout.write(r.delta);else if(r.type===`requires_action`){process.stderr.write(`\n[requires action] ${r.kind??``} (${r.toolName??`unknown tool`})\n`);break}else if(r.type===`done`)break;process.stdout.write(`
|
|
5
|
+
`)}async function I(e){let t=await P(),i=n(e,t),a=process.cwd(),o=y(a),s=await C(o),l=i.apiKey,u=i.modelId??process.env.GOATCHAIN_MODEL??s?.defaults?.modelId??`gpt-4o`,f=i.system,p=i.baseUrl??process.env.GOATCHAIN_OPENAI_BASE_URL??s?.openai?.baseUrl,m={},h=(e,t)=>{let n={...e?.defaults?.requestDefaults??{},temperature:t?.temperature??e?.defaults?.requestDefaults?.temperature,maxOutputTokens:t?.maxTokens??e?.defaults?.requestDefaults?.maxOutputTokens,topP:t?.topP??e?.defaults?.requestDefaults?.topP,presencePenalty:t?.presencePenalty??e?.defaults?.requestDefaults?.presencePenalty,frequencyPenalty:t?.frequencyPenalty??e?.defaults?.requestDefaults?.frequencyPenalty,seed:t?.seed??e?.defaults?.requestDefaults?.seed,timeoutMs:t?.timeoutMs??e?.defaults?.requestDefaults?.timeoutMs};for(let e of Object.keys(m))delete m[e];Object.assign(m,n)};h(s,i);let g=()=>l??process.env.OPENAI_API_KEY??s?.openai?.apiKey,_={},b=e=>{let t=process.env.GOATCHAIN_EMOJI,n=t===`1`?!0:t===`0`?!1:process.stdout.isTTY&&process.env.TERM!==`dumb`,r={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`,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`,sessionsUi:e?.ui?.sessionsUi??process.env.GOATCHAIN_SESSIONS_UI??`auto`,emoji:typeof e?.ui?.emoji==`boolean`?e.ui.emoji:n};for(let e of Object.keys(_))delete _[e];Object.assign(_,r)};if(b(s),i.prompt){let{agent:e}=await v({getApiKey:g,modelId:u,system:f,baseUrl:p,requestDefaults:m});await F({agent:e,prompt:i.prompt});return}let x=i.sessionId??s?.lastSessionId??r(),S=[],T=Date.now(),A,I,L=!1,{agent:R,model:z,tools:B}=await v({getApiKey:g,modelId:u,system:f,baseUrl:p,requestDefaults:m}),V=await E(o,x);V&&(T=V.createdAt??T,A=V.title,I=V.summary,L=!!V.pinned,S=Array.isArray(V.messages)?V.messages:[]),V?.modelId&&typeof z?.setModelId==`function`&&z.setModelId(V.modelId);let H=async(e={})=>{s=await w(o,{...s,...e,openai:{...s?.openai??{},baseUrl:p,apiKey:g()},defaults:{...s?.defaults??{},modelId:z.modelId,requestDefaults:m},ui:_})},U=async()=>{let e=await D(o,{sessionId:x,createdAt:T,modelId:z.modelId,systemPrompt:f,title:A,summary:I,pinned:L,messages:S});A=e?.title??A,I=e?.summary??I,L=!!e?.pinned,await H({lastSessionId:x})},W=Promise.resolve(),G=()=>{let e=()=>U();return W=W.then(e,e),W};await G();let{runRepl:K}=await import(`./repl-DPVyIucO.js`);await K({version:t,provider:`openai`,system:f,agentRef:{get:()=>R},modelRef:{get:()=>z},toolsInfo:B,requestDefaults:m,baseUrlRef:{get:()=>p},setBaseUrl:async e=>{if(p=e,typeof z?.setBaseUrl==`function`){z.setBaseUrl(p),await G();return}({agent:R,model:z,tools:B}=await v({getApiKey:g,modelId:z.modelId,system:f,baseUrl:p,requestDefaults:m})),await G()},setApiKey:e=>{l=e},saveAll:G,listSessions:()=>O(o),loadSessionById:e=>E(o,e),saveSessionByData:e=>D(o,e),renameSessionById:(e,t)=>k(o,e,t),setPinnedSessionsById:(e,t)=>j(o,e,t),deleteSessionById:e=>M(o,e),deleteSessionsById:e=>N(o,e),uiPrefs:_,switchWorkspace:async e=>{let t=d.resolve(process.cwd(),String(e??``));if(!(await c(t)).isDirectory())throw Error(`Not a directory: ${t}`);process.chdir(t),a=process.cwd(),o=y(a),s=await C(o),b(s),h(s,null),p=process.env.GOATCHAIN_OPENAI_BASE_URL??s?.openai?.baseUrl??p,x=s?.lastSessionId??r(),S=[],T=Date.now(),A=void 0,I=void 0,L=!1;let n=s?.defaults?.modelId??z.modelId??`gpt-4o`;({agent:R,model:z,tools:B}=await v({getApiKey:g,modelId:n,system:f,baseUrl:p,requestDefaults:m}));let i=await E(o,x);i&&(T=i.createdAt??T,A=i.title,I=i.summary,L=!!i.pinned,S=Array.isArray(i.messages)?i.messages:[]),i?.modelId&&typeof z?.setModelId==`function`&&z.setModelId(i.modelId),await G()},getWorkspaceCwd:()=>process.cwd(),session:{get sessionId(){return x},set sessionId(e){x=e},get createdAt(){return T},set createdAt(e){T=e},get history(){return S},set history(e){S=e},get title(){return A},set title(e){A=e},get summary(){return I},set summary(e){I=e},get pinned(){return L},set pinned(e){L=!!e}}})}export{I as main};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
function e(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function t(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let n=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return n=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function r(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const i=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var a=class extends Error{},o=class e extends a{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,a){if(!t||!a)return new c({message:r,cause:i(n)});let o=n?.error;return t===400?new u(t,o,r,a):t===401?new d(t,o,r,a):t===403?new f(t,o,r,a):t===404?new p(t,o,r,a):t===409?new m(t,o,r,a):t===422?new h(t,o,r,a):t===429?new g(t,o,r,a):t>=500?new _(t,o,r,a):new e(t,o,r,a)}},s=class extends o{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},c=class extends o{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},l=class extends c{constructor({message:e}={}){super({message:e??`Request timed out.`})}},u=class extends o{},d=class extends o{},f=class extends o{},p=class extends o{},m=class extends o{},h=class extends o{},g=class extends o{},_=class extends o{},v=class extends a{constructor(){super(`Could not parse response content as the length limit was reached`)}},y=class extends a{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},b=class extends Error{constructor(e){super(e)}};const ee=/^[a-z][a-z0-9+.-]*:/i,te=e=>ee.test(e);let x=e=>(x=Array.isArray,x(e)),S=x;function C(e){return typeof e==`object`?e??{}:{}}function ne(e){if(!e)return!0;for(let t in e)return!1;return!0}function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ae=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new a(`${e} must be an integer`);if(t<0)throw new a(`${e} must be a positive integer`);return t},oe=e=>{try{return JSON.parse(e)}catch{return}},se=e=>new Promise(t=>setTimeout(t,e)),w=`6.14.0`,ce=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function le(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const ue=()=>{let e=le();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":pe(Deno.build.os),"X-Stainless-Arch":fe(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":pe(globalThis.process.platform??`unknown`),"X-Stainless-Arch":fe(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=de();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function de(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const fe=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,pe=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let me;const he=()=>me??=ue();function ge(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function _e(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ve(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return _e({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ye(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function be(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const xe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Se=`RFC3986`,Ce=e=>String(e),we={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Ce};let Te=(e,t)=>(Te=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Te(e,t));const T=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Ee=1024,De=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Ee){let t=a.length>=Ee?a.slice(e,e+Ee):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=T[r];continue}if(r<2048){n[n.length]=T[192|r>>6]+T[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=T[224|r>>12]+T[128|r>>6&63]+T[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=T[240|r>>18]+T[128|r>>12&63]+T[128|r>>6&63]+T[128|r&63]}o+=n.join(``)}return o};function Oe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ke(e,t){if(x(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ae={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},je=function(e,t){Array.prototype.push.apply(e,x(t)?t:[t])};let Me;const E={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:De,encodeValuesOnly:!1,format:Se,formatter:Ce,indices:!1,serializeDate(e){return(Me??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Ne(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const Pe={};function Fe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(Pe))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(Pe)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&x(v)&&(v=ke(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,E.encoder,g,`key`,p):t;v=``}if(Ne(v)||Oe(v)){if(c){let e=h?t:c(t,E.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,E.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let S;if(n===`comma`&&x(v))h&&c&&(v=ke(v,c)),S=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(x(l))S=l;else{let e=Object.keys(v);S=u?e.sort(u):e}let C=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&x(v)&&v.length===1?C+`[]`:C;if(i&&x(v)&&v.length===0)return ne+`[]`;for(let t=0;t<S.length;++t){let y=S[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let C=d&&s?y.replace(/\./g,`%2E`):y,re=x(v)?typeof n==`function`?n(ne,C):ne:ne+(d?`.`+C:`[`+C+`]`);_.set(e,b);let ie=new WeakMap;ie.set(Pe,_),je(te,Fe(ee,re,n,r,i,a,o,s,n===`comma`&&h&&x(v)?null:c,l,u,d,f,p,m,h,g,ie))}return te}function Ie(e=E){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||E.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Se;if(e.format!==void 0){if(!Te(we,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=we[n],i=E.filter;(typeof e.filter==`function`||x(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ae?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:E.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:E.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:E.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:E.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:E.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?E.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:E.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:E.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:E.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:E.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:E.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:E.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:E.strictNullHandling}}function Le(e,t={}){let n=e,r=Ie(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):x(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ae[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||je(o,Fe(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Re(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let ze;function Be(e){let t;return(ze??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let Ve;function He(e){let t;return(Ve??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var D,O,Ue=class{constructor(){D.set(this,void 0),O.set(this,void 0),e(this,D,new Uint8Array,`f`),e(this,O,null,`f`)}decode(n){if(n==null)return[];let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Be(n):n;e(this,D,Re([t(this,D,`f`),r]),`f`);let i=[],a;for(;(a=We(t(this,D,`f`),t(this,O,`f`)))!=null;){if(a.carriage&&t(this,O,`f`)==null){e(this,O,a.index,`f`);continue}if(t(this,O,`f`)!=null&&(a.index!==t(this,O,`f`)+1||a.carriage)){i.push(He(t(this,D,`f`).subarray(0,t(this,O,`f`)-1))),e(this,D,t(this,D,`f`).subarray(t(this,O,`f`)),`f`),e(this,O,null,`f`);continue}let n=t(this,O,`f`)===null?a.preceding:a.preceding-1,r=He(t(this,D,`f`).subarray(0,n));i.push(r),e(this,D,t(this,D,`f`).subarray(a.index),`f`),e(this,O,null,`f`)}return i}flush(){return t(this,D,`f`).length?this.decode(`
|
|
2
|
+
`):[]}};D=new WeakMap,O=new WeakMap,Ue.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,`\r`]),Ue.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function We(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ge(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const Ke={off:0,error:200,warn:300,info:400,debug:500},qe=(e,t,n)=>{if(e){if(re(Ke,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ke))}`)}};function Je(){}function Ye(e,t,n){return!t||Ke[e]>Ke[n]?Je:t[e].bind(t)}const Xe={error:Je,warn:Je,info:Je,debug:Je};let Ze=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Xe;let r=Ze.get(t);if(r&&r[0]===n)return r[1];let i={error:Ye(`error`,t,n),warn:Ye(`warn`,t,n),info:Ye(`info`,t,n),debug:Ye(`debug`,t,n)};return Ze.set(t,[n,i]),i}const A=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var Qe,$e=class n{constructor(t,n,r){this.iterator=t,Qe.set(this,void 0),this.controller=n,e(this,Qe,r,`f`)}static fromSSEResponse(e,t,i){let s=!1,c=i?k(i):console;async function*l(){if(s)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(let r of et(e,t))if(!n){if(r.data.startsWith(`[DONE]`)){n=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let t;try{t=JSON.parse(r.data)}catch(e){throw c.error(`Could not parse message into JSON:`,r.data),c.error(`From chunk:`,r.raw),e}if(t&&t.error)throw new o(void 0,t.error,void 0,e.headers);yield t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new o(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}n=!0}catch(e){if(r(e))return;throw e}finally{n||t.abort()}}return new n(l,t,i)}static fromReadableStream(e,t,i){let o=!1;async function*s(){let t=new Ue,n=ye(e);for await(let e of n)for(let n of t.decode(e))yield n;for(let e of t.flush())yield e}async function*c(){if(o)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let e=!1;try{for await(let t of s())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(r(e))return;throw e}finally{e||t.abort()}}return new n(c,t,i)}[(Qe=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],i=this.iterator(),a=t=>({next:()=>{if(t.length===0){let t=i.next();e.push(t),r.push(t)}return t.shift()}});return[new n(()=>a(e),this.controller,t(this,Qe,`f`)),new n(()=>a(r),this.controller,t(this,Qe,`f`))]}toReadableStream(){let e=this,t;return _e({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Be(JSON.stringify(n)+`
|
|
4
|
+
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*et(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);let n=new nt,r=new Ue,i=ye(e.body);for await(let e of tt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*tt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Be(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ge(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var nt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=rt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function rt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function it(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):$e.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?at(await n.json(),n):await n.text()})();return k(e).debug(`[${r}] response parsed`,A({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function at(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`x-request-id`),enumerable:!1})}var ot,st=class n extends Promise{constructor(t,n,r=it){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,ot.set(this,void 0),e(this,ot,t,`f`)}_thenUnwrap(e){return new n(t(this,ot,`f`),this.responsePromise,async(t,n)=>at(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(t(this,ot,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};ot=new WeakMap;var ct,lt=class{constructor(t,n,r,i){ct.set(this,void 0),e(this,ct,t,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,ct,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ct=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},ut=class extends st{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await it(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},dt=class extends lt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},j=class extends lt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...C(this.options.query),after:t}}:null}},ft=class extends lt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...C(this.options.query),after:e}}:null}};const pt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function mt(e,t,n){return pt(),new File(e,t??`unknown_file`,n)}function ht(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const gt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,_t=async(e,t)=>Ct(e.body)?{...e,body:await bt(e.body,t)}:e,M=async(e,t)=>({...e,body:await bt(e.body,t)}),vt=new WeakMap;function yt(e){let t=typeof e==`function`?e:e.fetch,n=vt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return vt.set(t,r),r}const bt=async(e,t)=>{if(!await yt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>wt(n,e,t))),n},xt=e=>e instanceof Blob&&`name`in e,St=e=>typeof e==`object`&&!!e&&(e instanceof Response||gt(e)||xt(e)),Ct=e=>{if(St(e))return!0;if(Array.isArray(e))return e.some(Ct);if(e&&typeof e==`object`){for(let t in e)if(Ct(e[t]))return!0}return!1},wt=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,mt([await n.blob()],ht(n)));else if(gt(n))e.append(t,mt([await new Response(ve(n)).blob()],ht(n)));else if(xt(n))e.append(t,n,ht(n));else if(Array.isArray(n))await Promise.all(n.map(n=>wt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>wt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Tt=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Et=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Tt(e),Dt=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Ot(e,t,n){if(pt(),e=await e,Et(e))return e instanceof File?e:mt([await e.arrayBuffer()],e.name);if(Dt(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),mt(await kt(r),t,n)}let r=await kt(e);if(t||=ht(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return mt(r,t,n)}async function kt(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Tt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(gt(e))for await(let n of e)t.push(...await kt(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${At(e)}`)}return t}function At(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var N=class{constructor(e){this._client=e}};function jt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Mt=Object.freeze(Object.create(null)),P=((e=jt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Mt)??Mt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
6
|
+
`)}\n${o}\n${t}`)}return o})(jt);var Nt=class extends N{list(e,t={},n){return this._client.getAPIList(P`/chat/completions/${e}/messages`,j,{query:t,...n})}};function Pt(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Ft(e){return e?.$brand===`auto-parseable-response-format`}function It(e){return e?.$brand===`auto-parseable-tool`}function Lt(e,t){return!t||!Ht(t)?{...e,choices:e.choices.map(e=>(Ut(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Rt(e,t)}function Rt(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new v;if(e.finish_reason===`content_filter`)throw new y;return Ut(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Bt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?zt(t,e.message.content):null}}});return{...e,choices:n}}function zt(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Bt(e,t){let n=e.tools?.find(e=>Pt(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:It(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Vt(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Pt(e)&&e.function?.name===t.function.name);return Pt(n)&&(It(n)||n?.function.strict||!1)}function Ht(e){return Ft(e.response_format)?!0:e.tools?.some(e=>It(e)||e.type===`function`&&e.function.strict===!0)??!1}function Ut(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Wt(e){for(let t of e??[]){if(t.type!==`function`)throw new a(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new a(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Gt=e=>e?.role===`assistant`,Kt=e=>e?.role===`tool`;var qt,Jt,Yt,Xt,Zt,Qt,$t,F,en,tn,nn,I,rn,an=class{constructor(){qt.add(this),this.controller=new AbortController,Jt.set(this,void 0),Yt.set(this,()=>{}),Xt.set(this,()=>{}),Zt.set(this,void 0),Qt.set(this,()=>{}),$t.set(this,()=>{}),F.set(this,{}),en.set(this,!1),tn.set(this,!1),nn.set(this,!1),I.set(this,!1),e(this,Jt,new Promise((t,n)=>{e(this,Yt,t,`f`),e(this,Xt,n,`f`)}),`f`),e(this,Zt,new Promise((t,n)=>{e(this,Qt,t,`f`),e(this,$t,n,`f`)}),`f`),t(this,Jt,`f`).catch(()=>{}),t(this,Zt,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,qt,`m`,rn).bind(this))},0)}_connected(){this.ended||(t(this,Yt,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,en,`f`)}get errored(){return t(this,tn,`f`)}get aborted(){return t(this,nn,`f`)}abort(){this.controller.abort()}on(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n}),this}off(e,n){let r=t(this,F,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{e(this,I,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,I,!0,`f`),await t(this,Zt,`f`)}_emit(n,...r){if(t(this,en,`f`))return;n===`end`&&(e(this,en,!0,`f`),t(this,Qt,`f`).call(this));let i=t(this,F,`f`)[n];if(i&&(t(this,F,`f`)[n]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),n===`abort`){let e=r[0];!t(this,I,`f`)&&!i?.length&&Promise.reject(e),t(this,Xt,`f`).call(this,e),t(this,$t,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,I,`f`)&&!i?.length&&Promise.reject(e),t(this,Xt,`f`).call(this,e),t(this,$t,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Jt=new WeakMap,Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,F=new WeakMap,en=new WeakMap,tn=new WeakMap,nn=new WeakMap,I=new WeakMap,qt=new WeakSet,rn=function(t){if(e(this,tn,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,nn,!0,`f`),this._emit(`abort`,t);if(t instanceof a)return this._emit(`error`,t);if(t instanceof Error){let e=new a(t.message);return e.cause=t,this._emit(`error`,e)}return this._emit(`error`,new a(String(t)))};function on(e){return typeof e.parse==`function`}var L,sn,cn,ln,un,dn,fn,pn,mn=class extends an{constructor(){super(...arguments),L.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Kt(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Gt(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),t(this,L,`m`,sn).call(this)}async finalMessage(){return await this.done(),t(this,L,`m`,cn).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,L,`m`,ln).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,L,`m`,un).call(this)}async totalUsage(){return await this.done(),t(this,L,`m`,dn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let n=t(this,L,`m`,cn).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,L,`m`,sn).call(this);r&&this._emit(`finalContent`,r);let i=t(this,L,`m`,ln).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,L,`m`,un).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,L,`m`,dn).call(this))}async _createChatCompletion(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,L,`m`,fn).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Rt(a,n))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,n,r){let i=`tool`,{tool_choice:o=`auto`,stream:s,...c}=n,l=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:u=10}=r||{},d=n.tools.map(e=>{if(It(e)){if(!e.$callback)throw new a("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in n?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of n.messages)this._addMessage(e,!1);for(let n=0;n<u;++n){let n=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!n)throw new a(`missing message in ChatCompletion response`);if(!n.tool_calls?.length)return;for(let e of n.tool_calls){if(e.type!==`function`)continue;let n=e.id,{name:r,arguments:a}=e.function,o=f[r];if(o){if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}}else{let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}let s;try{s=on(o)?await o.parse(a):a}catch(e){let t=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:n,content:t});continue}let c=await o.function(s,this),u=t(this,L,`m`,pn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};L=new WeakSet,sn=function(){return t(this,L,`m`,cn).call(this).content??null},cn=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Gt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},ln=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Gt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},un=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Kt(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},dn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},fn=function(e){if(e.n!=null&&e.n>1)throw new a(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},pn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var hn=class e extends mn{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Gt(e)&&e.content&&this._emit(`content`,e.content)}};const R={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};var gn=class extends Error{},_n=class extends Error{};function vn(e,t=R.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return yn(e.trim(),t)}const yn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new gn(`${e} at position ${r}`)},a=e=>{throw new _n(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||R.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||R.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||R.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||R.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||R.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||R.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(R.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&R.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(R.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(R.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(R.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&R.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(R.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(R.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&R.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
7
|
+
\r `.includes(e[r]);)r++};return o()},bn=e=>vn(e,R.ALL^R.NUM);var z,B,V,H,xn,Sn,Cn,wn,Tn,En,Dn,On,kn=class n extends mn{constructor(t){super(),z.add(this),B.set(this,void 0),V.set(this,void 0),H.set(this,void 0),e(this,B,t,`f`),e(this,V,[],`f`)}get currentChatCompletionSnapshot(){return t(this,H,`f`)}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let i=new n(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,n,r){super._createChatCompletion;let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,z,`m`,xn).call(this);let a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of a)t(this,z,`m`,Cn).call(this,e);if(a.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,z,`m`,En).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),t(this,z,`m`,xn).call(this),this._connected();let i=$e.fromReadableStream(e,this.controller),a;for await(let e of i)a&&a!==e.id&&this._addChatCompletion(t(this,z,`m`,En).call(this)),t(this,z,`m`,Cn).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,z,`m`,En).call(this))}[(B=new WeakMap,V=new WeakMap,H=new WeakMap,z=new WeakSet,xn=function(){this.ended||e(this,H,void 0,`f`)},Sn=function(e){let n=t(this,V,`f`)[e.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},t(this,V,`f`)[e.index]=n,n)},Cn=function(e){if(this.ended)return;let n=t(this,z,`m`,On).call(this,e);this._emit(`chunk`,e,n);for(let r of e.choices){let e=n.choices[r.index];r.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.delta.content,e.message.content),this._emit(`content.delta`,{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),r.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=t(this,z,`m`,Sn).call(this,e);e.finish_reason&&(t(this,z,`m`,Tn).call(this,e),i.current_tool_call_index!=null&&t(this,z,`m`,wn).call(this,e,i.current_tool_call_index));for(let n of r.delta.tool_calls??[])i.current_tool_call_index!==n.index&&(t(this,z,`m`,Tn).call(this,e),i.current_tool_call_index!=null&&t(this,z,`m`,wn).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=n.index;for(let t of r.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},wn=function(e,n){if(t(this,z,`m`,Sn).call(this,e).done_tool_calls.has(n))return;let r=e.message.tool_calls?.[n];if(!r)throw Error(`no tool call snapshot`);if(!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let e=t(this,B,`f`)?.tools?.find(e=>Pt(e)&&e.function.name===r.function.name);this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:n,arguments:r.function.arguments,parsed_arguments:It(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Tn=function(e){let n=t(this,z,`m`,Sn).call(this,e);if(e.message.content&&!n.content_done){n.content_done=!0;let r=t(this,z,`m`,Dn).call(this);this._emit(`content.done`,{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},En=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,H,`f`);if(!n)throw new a(`request ended without sending any chunks`);return e(this,H,void 0,`f`),e(this,V,[],`f`),An(n,t(this,B,`f`))},Dn=function(){let e=t(this,B,`f`)?.response_format;return Ft(e)?e:null},On=function(n){var r,i,a,o;let s=t(this,H,`f`),{choices:c,...l}=n;s?Object.assign(s,l):s=e(this,H,{...l,choices:[]},`f`);for(let{delta:e,finish_reason:c,index:l,logprobs:u=null,...d}of n.choices){let n=s.choices[l];if(n||=s.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d},u)if(!n.logprobs)n.logprobs=Object.assign({},u);else{let{content:e,refusal:t,...a}=u;Object.assign(n.logprobs,a),e&&((r=n.logprobs).content??(r.content=[]),n.logprobs.content.push(...e)),t&&((i=n.logprobs).refusal??(i.refusal=[]),n.logprobs.refusal.push(...t))}if(c&&(n.finish_reason=c,t(this,B,`f`)&&Ht(t(this,B,`f`)))){if(c===`length`)throw new v;if(c===`content_filter`)throw new y}if(Object.assign(n,d),!e)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,..._}=e;if(Object.assign(n.message,_),p&&(n.message.refusal=(n.message.refusal||``)+p),h&&(n.message.role=h),m&&(n.message.function_call?(m.name&&(n.message.function_call.name=m.name),m.arguments&&((a=n.message.function_call).arguments??(a.arguments=``),n.message.function_call.arguments+=m.arguments)):n.message.function_call=m),f&&(n.message.content=(n.message.content||``)+f,!n.message.refusal&&t(this,z,`m`,Dn).call(this)&&(n.message.parsed=bn(n.message.content))),g){n.message.tool_calls||(n.message.tool_calls=[]);for(let{index:e,id:r,type:i,function:a,...s}of g){let c=(o=n.message.tool_calls)[e]??(o[e]={});Object.assign(c,s),r&&(c.id=r),i&&(c.type=i),a&&(c.function??={name:a.name??``,arguments:``}),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Vt(t(this,B,`f`),c)&&(c.function.parsed_arguments=bn(c.function.arguments)))}}}return s},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new $e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function An(e,t){let{id:n,choices:r,created:i,model:o,system_fingerprint:s,...c}=e;return Lt({...c,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...o})=>{if(!n)throw new a(`missing finish_reason for choice ${r}`);let{content:s=null,function_call:c,tool_calls:l,...u}=t,d=t.role;if(!d)throw new a(`missing role for choice ${r}`);if(c){let{arguments:e,name:l}=c;if(e==null)throw new a(`missing function_call.arguments for choice ${r}`);if(!l)throw new a(`missing function_call.name for choice ${r}`);return{...o,message:{content:s,function_call:{arguments:e,name:l},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return l?{...o,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:i,type:o,id:s,...c}=t,{arguments:l,name:u,...d}=i||{};if(s==null)throw new a(`missing choices[${r}].tool_calls[${n}].id\n${jn(e)}`);if(o==null)throw new a(`missing choices[${r}].tool_calls[${n}].type\n${jn(e)}`);if(u==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.name\n${jn(e)}`);if(l==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.arguments\n${jn(e)}`);return{...c,id:s,type:o,function:{...d,name:u,arguments:l}}})}}:{...o,message:{...u,content:s,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function jn(e){return JSON.stringify(e)}var Mn=class e extends kn{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},Nn=class extends N{constructor(){super(...arguments),this.messages=new Nt(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(P`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(P`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/chat/completions/${e}`,t)}parse(e,t){return Wt(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>Rt(t,e))}runTools(e,t){return e.stream?Mn.runTools(this._client,e,t):hn.runTools(this._client,e,t)}stream(e,t){return kn.createChatCompletion(this._client,e,t)}};Nn.Messages=Nt;var Pn=class extends N{constructor(){super(...arguments),this.completions=new Nn(this._client)}};Pn.Completions=Nn;const Fn=Symbol(`brand.privateNullableHeaders`);function*In(e){if(!e)return;if(Fn in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():S(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=S(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const U=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of In(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Fn]:!0,values:t,nulls:n}};var Ln=class extends N{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:U([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},Rn=class extends N{create(e,t){return this._client.post(`/audio/transcriptions`,M({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},zn=class extends N{create(e,t){return this._client.post(`/audio/translations`,M({body:e,...t,__metadata:{model:e.model}},this._client))}},Bn=class extends N{constructor(){super(...arguments),this.transcriptions=new Rn(this._client),this.translations=new zn(this._client),this.speech=new Ln(this._client)}};Bn.Transcriptions=Rn,Bn.Translations=zn,Bn.Speech=Ln;var Vn=class extends N{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/batches/${e}/cancel`,t)}},Hn=class extends N{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/assistants/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/assistants/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,j,{query:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/assistants/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Un=class extends N{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Wn=class extends N{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Gn=class extends N{constructor(){super(...arguments),this.sessions=new Un(this._client),this.transcriptionSessions=new Wn(this._client)}};Gn.Sessions=Un,Gn.TranscriptionSessions=Wn;var Kn=class extends N{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(P`/chatkit/sessions/${e}/cancel`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},qn=class extends N{retrieve(e,t){return this._client.get(P`/chatkit/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,ft,{query:e,...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(P`/chatkit/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(P`/chatkit/threads/${e}/items`,ft,{query:t,...n,headers:U([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},Jn=class extends N{constructor(){super(...arguments),this.sessions=new Kn(this._client),this.threads=new qn(this._client)}};Jn.Sessions=Kn,Jn.Threads=qn;var Yn=class extends N{create(e,t,n){return this._client.post(P`/threads/${e}/messages`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/messages/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/messages`,j,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(P`/threads/${r}/messages/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},Xn=class extends N{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(P`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(P`/threads/${r}/runs/${e}/steps`,j,{query:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};const Zn=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},W=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()};var G,K,Qn,q,$n,J,Y,er,X,tr,Z,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr=class extends an{constructor(){super(...arguments),G.add(this),Qn.set(this,[]),q.set(this,{}),$n.set(this,{}),J.set(this,void 0),Y.set(this,void 0),er.set(this,void 0),X.set(this,void 0),tr.set(this,void 0),Z.set(this,void 0),nr.set(this,void 0),rr.set(this,void 0),ir.set(this,void 0)}[(Qn=new WeakMap,q=new WeakMap,$n=new WeakMap,J=new WeakMap,Y=new WeakMap,er=new WeakMap,X=new WeakMap,tr=new WeakMap,Z=new WeakMap,nr=new WeakMap,rr=new WeakMap,ir=new WeakMap,G=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new K;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let i=$e.fromReadableStream(e,this.controller);for await(let e of i)t(this,G,`m`,ar).call(this,e);if(i.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,or).call(this))}toReadableStream(){return new $e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new K;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.submitToolOutputs(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,G,`m`,ar).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,or).call(this))}static createThreadAssistantStream(e,t,n){let r=new K;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new K;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return t(this,nr,`f`)}currentRun(){return t(this,rr,`f`)}currentMessageSnapshot(){return t(this,J,`f`)}currentRunStepSnapshot(){return t(this,ir,`f`)}async finalRunSteps(){return await this.done(),Object.values(t(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(t(this,$n,`f`))}async finalRun(){if(await this.done(),!t(this,Y,`f`))throw Error(`Final run was not received.`);return t(this,Y,`f`)}async _createThreadAssistantStream(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)t(this,G,`m`,ar).call(this,e);if(o.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,or).call(this))}async _createAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.create(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,G,`m`,ar).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,G,`m`,or).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ie(t)&&ie(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ie(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};K=mr,ar=function(n){if(!this.ended)switch(e(this,nr,n,`f`),t(this,G,`m`,lr).call(this,n),n.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:t(this,G,`m`,pr).call(this,n);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:t(this,G,`m`,cr).call(this,n);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:t(this,G,`m`,sr).call(this,n);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},or=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);if(!t(this,Y,`f`))throw Error(`Final run has not been received`);return t(this,Y,`f`)},sr=function(n){let[r,i]=t(this,G,`m`,dr).call(this,n,t(this,J,`f`));e(this,J,r,`f`),t(this,$n,`f`)[r.id]=r;for(let e of i){let t=r.content[e.index];t?.type==`text`&&this._emit(`textCreated`,t.text)}switch(n.event){case`thread.message.created`:this._emit(`messageCreated`,n.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,n.data.delta,r),n.data.delta.content)for(let i of n.data.delta.content){if(i.type==`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type==`text`)this._emit(`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!=t(this,er,`f`)){if(t(this,X,`f`))switch(t(this,X,`f`).type){case`text`:this._emit(`textDone`,t(this,X,`f`).text,t(this,J,`f`));break;case`image_file`:this._emit(`imageFileDone`,t(this,X,`f`).image_file,t(this,J,`f`));break}e(this,er,i.index,`f`)}e(this,X,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(t(this,er,`f`)!==void 0){let e=n.data.content[t(this,er,`f`)];if(e)switch(e.type){case`image_file`:this._emit(`imageFileDone`,e.image_file,t(this,J,`f`));break;case`text`:this._emit(`textDone`,e.text,t(this,J,`f`));break}}t(this,J,`f`)&&this._emit(`messageDone`,n.data),e(this,J,void 0,`f`)}},cr=function(n){let r=t(this,G,`m`,ur).call(this,n);switch(e(this,ir,r,`f`),n.event){case`thread.run.step.created`:this._emit(`runStepCreated`,n.data);break;case`thread.run.step.delta`:let i=n.data.delta;if(i.step_details&&i.step_details.type==`tool_calls`&&i.step_details.tool_calls&&r.step_details.type==`tool_calls`)for(let n of i.step_details.tool_calls)n.index==t(this,tr,`f`)?this._emit(`toolCallDelta`,n,r.step_details.tool_calls[n.index]):(t(this,Z,`f`)&&this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,tr,n.index,`f`),e(this,Z,r.step_details.tool_calls[n.index],`f`),t(this,Z,`f`)&&this._emit(`toolCallCreated`,t(this,Z,`f`)));this._emit(`runStepDelta`,n.data.delta,r);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:e(this,ir,void 0,`f`),n.data.step_details.type==`tool_calls`&&t(this,Z,`f`)&&(this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,Z,void 0,`f`)),this._emit(`runStepDone`,n.data,r);break;case`thread.run.step.in_progress`:break}},lr=function(e){t(this,Qn,`f`).push(e),this._emit(`event`,e)},ur=function(e){switch(e.event){case`thread.run.step.created`:return t(this,q,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let n=t(this,q,`f`)[e.data.id];if(!n)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data;if(r.delta){let i=K.accumulateDelta(n,r.delta);t(this,q,`f`)[e.data.id]=i}return t(this,q,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:t(this,q,`f`)[e.data.id]=e.data;break}if(t(this,q,`f`)[e.data.id])return t(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},dr=function(e,n){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:if(!n)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content)for(let e of i.delta.content)if(e.index in n.content){let r=n.content[e.index];n.content[e.index]=t(this,G,`m`,fr).call(this,e,r)}else n.content[e.index]=e,r.push(e);return[n,r];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(n)return[n,r];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},fr=function(e,t){return K.accumulateDelta(t,e)},pr=function(n){switch(e(this,rr,n.data,`f`),n.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:e(this,Y,n.data,`f`),t(this,Z,`f`)&&(this._emit(`toolCallDone`,t(this,Z,`f`)),e(this,Z,void 0,`f`));break;case`thread.run.cancelling`:break}};var hr=class extends N{constructor(){super(...arguments),this.steps=new Xn(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/runs/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/runs`,j,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(P`/threads/${r}/runs/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return mr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=U([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return mr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return mr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};hr.Steps=Xn;var gr=class extends N{constructor(){super(...arguments),this.runs=new hr(this._client),this.messages=new Yn(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/threads/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(P`/threads/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return mr.createThreadAssistantStream(e,this._client.beta.threads,t)}};gr.Runs=hr,gr.Messages=Yn;var _r=class extends N{constructor(){super(...arguments),this.realtime=new Gn(this._client),this.chatkit=new Jn(this._client),this.assistants=new Hn(this._client),this.threads=new gr(this._client)}};_r.Realtime=Gn,_r.ChatKit=Jn,_r.Assistants=Hn,_r.Threads=gr;var vr=class extends N{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},yr=class extends N{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}/content`,{...n,headers:U([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},br=class extends N{constructor(){super(...arguments),this.content=new yr(this._client)}create(e,t,n){return this._client.post(P`/containers/${e}/files`,M({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/containers/${e}/files`,j,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(P`/containers/${r}/files/${e}`,{...n,headers:U([{Accept:`*/*`},n?.headers])})}};br.Content=yr;var xr=class extends N{constructor(){super(...arguments),this.files=new br(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/containers/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}};xr.Files=br;var Sr=class extends N{create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(P`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(P`/conversations/${e}/items`,ft,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(P`/conversations/${r}/items/${e}`,n)}},Cr=class extends N{constructor(){super(...arguments),this.items=new Sr(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/conversations/${e}`,t)}update(e,t,n){return this._client.post(P`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(P`/conversations/${e}`,t)}};Cr.Items=Sr;var wr=class extends N{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(k(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=Zn(t)}),e)))}},Tr=class extends N{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(P`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(P`/evals/${r}/runs/${e}/output_items`,j,{query:i,...n})}},Er=class extends N{constructor(){super(...arguments),this.outputItems=new Tr(this._client)}create(e,t,n){return this._client.post(P`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(P`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/evals/${e}/runs`,j,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(P`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(P`/evals/${r}/runs/${e}`,n)}};Er.OutputItems=Tr;var Dr=class extends N{constructor(){super(...arguments),this.runs=new Er(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/evals/${e}`,t)}update(e,t,n){return this._client.post(P`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/evals/${e}`,t)}};Dr.Runs=Er;var Or=class extends N{create(e,t){return this._client.post(`/files`,M({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/files/${e}`,t)}content(e,t){return this._client.get(P`/files/${e}/content`,{...t,headers:U([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await se(t),a=await this.retrieve(e),Date.now()-i>n)throw new l({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},kr=class extends N{},Ar=class extends N{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}},jr=class extends N{constructor(){super(...arguments),this.graders=new Ar(this._client)}};jr.Graders=Ar;var Mr=class extends N{create(e,t,n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,dt,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(P`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(P`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},Nr=class extends N{constructor(){super(...arguments),this.permissions=new Mr(this._client)}};Nr.Permissions=Mr;var Pr=class extends N{list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/checkpoints`,j,{query:t,...n})}},Fr=class extends N{constructor(){super(...arguments),this.checkpoints=new Pr(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/events`,j,{query:t,...n})}pause(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/resume`,t)}};Fr.Checkpoints=Pr;var Ir=class extends N{constructor(){super(...arguments),this.methods=new kr(this._client),this.jobs=new Fr(this._client),this.checkpoints=new Nr(this._client),this.alpha=new jr(this._client)}};Ir.Methods=kr,Ir.Jobs=Fr,Ir.Checkpoints=Nr,Ir.Alpha=jr;var Lr=class extends N{},Rr=class extends N{constructor(){super(...arguments),this.graderModels=new Lr(this._client)}};Rr.GraderModels=Lr;var zr=class extends N{createVariation(e,t){return this._client.post(`/images/variations`,M({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,M({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}},Br=class extends N{retrieve(e,t){return this._client.get(P`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,dt,e)}delete(e,t){return this._client.delete(P`/models/${e}`,t)}},Vr=class extends N{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},Hr=class extends N{accept(e,t,n){return this._client.post(P`/realtime/calls/${e}/accept`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(P`/realtime/calls/${e}/hangup`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(P`/realtime/calls/${e}/refer`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(P`/realtime/calls/${e}/reject`,{body:t,...n,headers:U([{Accept:`*/*`},n?.headers])})}},Ur=class extends N{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},Wr=class extends N{constructor(){super(...arguments),this.clientSecrets=new Ur(this._client),this.calls=new Hr(this._client)}};Wr.ClientSecrets=Ur,Wr.Calls=Hr;function Gr(e,t){return!t||!Jr(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:Kr(e,t)}function Kr(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:Zr(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:qr(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||Qr(r),Object.defineProperty(r,`output_parsed`,{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function qr(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function Jr(e){return!!Ft(e.text?.format)}function Yr(e){return e?.$brand===`auto-parseable-tool`}function Xr(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function Zr(e,t){let n=Xr(e.tools??[],t.name);return{...t,...t,parsed_arguments:Yr(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function Qr(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var $r,ei,Q,ti,ni,ri,ii,ai,oi=class n extends an{constructor(t){super(),$r.add(this),ei.set(this,void 0),Q.set(this,void 0),ti.set(this,void 0),e(this,ei,t,`f`)}static createResponse(e,t,r){let i=new n(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,$r,`m`,ni).call(this);let a,o=null;`response_id`in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of a)t(this,$r,`m`,ri).call(this,e,o);if(a.controller.signal?.aborted)throw new s;return t(this,$r,`m`,ii).call(this)}[(ei=new WeakMap,Q=new WeakMap,ti=new WeakMap,$r=new WeakSet,ni=function(){this.ended||e(this,Q,void 0,`f`)},ri=function(e,n){if(this.ended)return;let r=(e,t)=>{(n==null||t.sequence_number>n)&&this._emit(e,t)},i=t(this,$r,`m`,ai).call(this,e);switch(r(`event`,e),e.type){case`response.output_text.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);if(t.type===`message`){let n=t.content[e.content_index];if(!n)throw new a(`missing content at index ${e.content_index}`);if(n.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${n.type}`);r(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);t.type===`function_call`&&r(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:r(e.type,e);break}},ii=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,Q,`f`);if(!n)throw new a(`request ended without sending any events`);e(this,Q,void 0,`f`);let r=si(n,t(this,ei,`f`));return e(this,ti,r,`f`),r},ai=function(n){let r=t(this,Q,`f`);if(!r){if(n.type!==`response.created`)throw new a(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=e(this,Q,n.response,`f`),r}switch(n.type){case`response.output_item.added`:r.output.push(n.item);break;case`response.content_part.added`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);let t=e.type,i=n.part;t===`message`&&i.type!==`reasoning_text`?e.content.push(i):t===`reasoning`&&i.type===`reasoning_text`&&(e.content||=[],e.content.push(i));break}case`response.output_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`message`){let t=e.content[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${t.type}`);t.text+=n.delta}break}case`response.function_call_arguments.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);e.type===`function_call`&&(e.arguments+=n.delta);break}case`response.reasoning_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`reasoning`){let t=e.content?.[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`reasoning_text`)throw new a(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=n.delta}break}case`response.completed`:e(this,Q,n.response,`f`);break}return r},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=t(this,ti,`f`);if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}};function si(e,t){return Gr(e,t)}var ci=class extends N{list(e,t={},n){return this._client.getAPIList(P`/responses/${e}/input_items`,j,{query:t,...n})}},li=class extends N{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},ui=class extends N{constructor(){super(...arguments),this.inputItems=new ci(this._client),this.inputTokens=new li(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&Qr(e),e))}retrieve(e,t={},n){return this._client.get(P`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&Qr(e),e))}delete(e,t){return this._client.delete(P`/responses/${e}`,{...t,headers:U([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>Kr(t,e))}stream(e,t){return oi.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(P`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};ui.InputItems=ci,ui.InputTokens=li;var di=class extends N{create(e,t,n){return this._client.post(P`/uploads/${e}/parts`,M({body:t,...n},this._client))}},fi=class extends N{constructor(){super(...arguments),this.parts=new di(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(P`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(P`/uploads/${e}/complete`,{body:t,...n})}};fi.Parts=di;const pi=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r};var mi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/file_batches`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/file_batches/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(P`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(P`/vector_stores/${r}/file_batches/${e}/files`,j,{query:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=U([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await pi(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},hi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/files`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/files/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(P`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/vector_stores/${e}/files`,j,{query:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(P`/vector_stores/${r}/files/${e}`,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=U([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(P`/vector_stores/${r}/files/${e}/content`,dt,{...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},gi=class extends N{constructor(){super(...arguments),this.files=new hi(this._client),this.fileBatches=new mi(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/vector_stores/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/vector_stores/${e}`,{body:t,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,j,{query:e,...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/vector_stores/${e}`,{...t,headers:U([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(P`/vector_stores/${e}/search`,dt,{body:t,method:`post`,...n,headers:U([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};gi.Files=hi,gi.FileBatches=mi;var _i=class extends N{create(e,t){return this._client.post(`/videos`,_t({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,ft,{query:e,...t})}delete(e,t){return this._client.delete(P`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(P`/videos/${e}/content`,{query:t,...n,headers:U([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(P`/videos/${e}/remix`,_t({body:t,...n},this._client))}},vi,yi,bi,xi=class extends N{constructor(){super(...arguments),vi.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,i=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");t(this,vi,`m`,yi).call(this,r);let a=U([n]).values,o=t(this,vi,`m`,bi).call(this,a,`webhook-signature`),s=t(this,vi,`m`,bi).call(this,a,`webhook-timestamp`),c=t(this,vi,`m`,bi).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new b(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new b(`Webhook timestamp is too old`);if(l>u+i)throw new b(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=r.startsWith(`whsec_`)?Buffer.from(r.replace(`whsec_`,``),`base64`):Buffer.from(r,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new b(`The given webhook signature does not match the expected signature`)}};vi=new WeakSet,yi=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},bi=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var Si,Ci,wi,Ti,$=class{constructor({baseURL:t=W(`OPENAI_BASE_URL`),apiKey:n=W(`OPENAI_API_KEY`),organization:r=W(`OPENAI_ORG_ID`)??null,project:i=W(`OPENAI_PROJECT_ID`)??null,webhookSecret:o=W(`OPENAI_WEBHOOK_SECRET`)??null,...s}={}){if(Si.add(this),wi.set(this,void 0),this.completions=new vr(this),this.chat=new Pn(this),this.embeddings=new wr(this),this.files=new Or(this),this.images=new zr(this),this.audio=new Bn(this),this.moderations=new Vr(this),this.models=new Br(this),this.fineTuning=new Ir(this),this.graders=new Rr(this),this.vectorStores=new gi(this),this.webhooks=new xi(this),this.beta=new _r(this),this.batches=new Vn(this),this.uploads=new fi(this),this.responses=new ui(this),this.realtime=new Wr(this),this.conversations=new Cr(this),this.evals=new Dr(this),this.containers=new xr(this),this.videos=new _i(this),n===void 0)throw new a("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let c={apiKey:n,organization:r,project:i,webhookSecret:o,...s,baseURL:t||`https://api.openai.com/v1`};if(!c.dangerouslyAllowBrowser&&ce())throw new a(`It looks like you're running in a browser-like environment.
|
|
8
|
+
|
|
9
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
10
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
11
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
12
|
+
|
|
13
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
14
|
+
|
|
15
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
16
|
+
`);this.baseURL=c.baseURL,this.timeout=c.timeout??Ci.DEFAULT_TIMEOUT,this.logger=c.logger??console;let l=`warn`;this.logLevel=l,this.logLevel=qe(c.logLevel,`ClientOptions.logLevel`,this)??qe(W(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??l,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??ge(),e(this,wi,xe,`f`),this._options=c,this.apiKey=typeof n==`string`?n:`Missing Key`,this.organization=r,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return U([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Le(e,{arrayFormat:`brackets`})}getUserAgent(){return`${this.constructor.name}/JS ${w}`}defaultIdempotencyKey(){return`stainless-node-retry-${n()}`}makeStatusError(e,t,n,r){return o.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof a?e:new a(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new a(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,n,r){let i=!t(this,Si,`m`,Ti).call(this)&&r||this.baseURL,a=te(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery();return ne(o)||(n={...o,...n}),typeof n==`object`&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new st(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let a=await e,o=a.maxRetries??this.maxRetries;t??=o,await this.prepareOptions(a);let{req:u,url:d,timeout:f}=await this.buildRequest(a,{retryCount:o-t});await this.prepareRequest(u,{url:d,options:a});let p=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),m=n===void 0?``:`, retryOf: ${n}`,h=Date.now();if(k(this).debug(`[${p}] sending request`,A({retryOfRequestLogID:n,method:a.method,url:d,options:a,headers:u.headers})),a.signal?.aborted)throw new s;let g=new AbortController,_=await this.fetchWithTimeout(d,u,f,g).catch(i),v=Date.now();if(_ instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(a.signal?.aborted)throw new s;let i=r(_)||/timed? ?out/i.test(String(_)+(`cause`in _?String(_.cause):``));if(t)return k(this).info(`[${p}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (${e})`,A({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),this.retryRequest(a,t,n??p);throw k(this).info(`[${p}] connection ${i?`timed out`:`failed`} - error; no more retries left`),k(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,A({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),i?new l:new c({cause:_})}let y=`[${p}${m}${[..._.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${u.method} ${d} ${_.ok?`succeeded`:`failed`} with status ${_.status} in ${v-h}ms`;if(!_.ok){let e=await this.shouldRetry(_);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await be(_.body),k(this).info(`${y} - ${e}`),k(this).debug(`[${p}] response error (${e})`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),this.retryRequest(a,t,n??p,_.headers)}let r=e?`error; no more retries left`:`error; not retryable`;k(this).info(`${y} - ${r}`);let o=await _.text().catch(e=>i(e).message),s=oe(o),c=s?void 0:o;throw k(this).debug(`[${p}] response error (${r})`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:c,durationMs:Date.now()-h})),this.makeStatusError(_.status,s,c,_.headers)}return k(this).info(y),k(this).debug(`[${p}] response start`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),{response:_,options:a,controller:g,requestLogID:p,retryOfRequestLogID:n,startTime:h}}getAPIList(e,t,n){return this.requestAPIList(t,{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new ut(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{};i&&i.addEventListener(`abort`,()=>r.abort());let s=setTimeout(()=>r.abort(),n),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,l={signal:r.signal,...c?{duplex:`half`}:{},method:`GET`,...o};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(s)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(!(i&&0<=i&&i<60*1e3)){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await se(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ae(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=U([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...he(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=U([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&r.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:ve(e)}:t(this,wi,`f`).call(this,{body:e,headers:r})}};Ci=$,wi=new WeakMap,Si=new WeakSet,Ti=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=Ci,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=a,$.APIError=o,$.APIConnectionError=c,$.APIConnectionTimeoutError=l,$.APIUserAbortError=s,$.NotFoundError=p,$.ConflictError=m,$.RateLimitError=g,$.BadRequestError=u,$.AuthenticationError=d,$.InternalServerError=_,$.PermissionDeniedError=f,$.UnprocessableEntityError=h,$.InvalidWebhookSignatureError=b,$.toFile=Ot,$.Completions=vr,$.Chat=Pn,$.Embeddings=wr,$.Files=Or,$.Images=zr,$.Audio=Bn,$.Moderations=Vr,$.Models=Br,$.FineTuning=Ir,$.Graders=Rr,$.VectorStores=gi,$.Webhooks=xi,$.Beta=_r,$.Batches=Vn,$.Uploads=fi,$.Responses=ui,$.Realtime=Wr,$.Conversations=Cr,$.Evals=Dr,$.Containers=xr,$.Videos=_i;export{c as APIConnectionError,l as APIConnectionTimeoutError,o as APIError,st as APIPromise,s as APIUserAbortError,d as AuthenticationError,u as BadRequestError,m as ConflictError,_ as InternalServerError,b as InvalidWebhookSignatureError,p as NotFoundError,$ as OpenAI,$ as default,a as OpenAIError,ut as PagePromise,f as PermissionDeniedError,g as RateLimitError,h as UnprocessableEntityError,Ot as toFile};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c}from"./ui-8G7VzOtK.js";import{randomUUID as l}from"node:crypto";import{mkdtemp as u,open as d,readFile as f,readdir as p,rm as m,stat as h,writeFile as g}from"node:fs/promises";import _ from"node:path";import v from"node:readline";import{execFile as y}from"node:child_process";import{promisify as ee}from"node:util";import b from"node:os";async function x({agent:t,sessionId:n,history:r,input:i,signal:a,askApproval:o,askApprovalForTool:s,approvalStrategy:l=`high_risk`,autoApprove:u=!1,emoji:d=process.env.GOATCHAIN_EMOJI!==`0`,showTools:f=process.env.GOATCHAIN_SHOW_TOOLS!==`0`,toolStyle:p=process.env.GOATCHAIN_TOOL_STYLE===`box`?`box`:`inline`,showStatus:m=process.env.GOATCHAIN_SHOW_STATUS!==`0`,showActivity:h=process.env.GOATCHAIN_SHOW_ACTIVITY!==`0`,showStatusLine:g=process.env.GOATCHAIN_SHOW_STATUSLINE!==`0`,promptContinue:v=process.env.GOATCHAIN_PROMPT_CONTINUE!==`0`,autoContinue:y=process.env.GOATCHAIN_AUTO_CONTINUE===`1`,write:ee=e=>process.stdout.write(e)}){let b=!!d&&process.stdout.isTTY&&process.env.TERM!==`dumb`,x=e=>b?`${e} `:``,S=!0,C=null,w=e=>{C?.onOutput();let t=String(e??``);ee(t);let n=t.lastIndexOf(`
|
|
2
|
+
`);if(n===-1){S=!1;return}S=n===t.length-1},T=()=>{S||w(`
|
|
3
|
+
`)},E=[],D={text:``,toolCalls:[],flushedToolCallAssistant:!1},O=new Map,k=new Map,A=new Set,j=new Set,M={tools:[]},te=!1,ne=e=>{try{return Buffer.byteLength(String(e??``),`utf8`)}catch{return String(e??``).length}},re=e=>{let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(2)} KB`:`${(t/(1024*1024)).toFixed(2)} MB`},N=e=>e.filter(e=>!!e),P=(t,n)=>{let r=String(t??``),i=n&&typeof n==`object`?n:{};if(r===`Write`){let e=typeof i.file_path==`string`?i.file_path:``,t=typeof i.content==`string`?re(ne(i.content)):``;return{summary:`${e}${t?` (content ${t})`:``}`,lines:N([e?`file: ${e}`:void 0,t?`content: ${t}`:void 0])}}if(r===`Edit`){let t=typeof i.file_path==`string`?i.file_path:``,n=Array.isArray(i.edits)?i.edits:[],r=n[0]&&typeof n[0]==`object`?n[0]:void 0,a=r&&typeof r.oldText==`string`?r.oldText:``,o=r&&typeof r.newText==`string`?r.newText:``,s=a||o?`first edit: ${e(a,60)} → ${e(o,60)}`:void 0;return{summary:`${t}${n.length?` (${n.length} edits)`:``}`,lines:N([t?`file: ${t}`:void 0,n.length?`edits: ${n.length}`:void 0,s])}}if(r===`Read`){let e=typeof i.file_path==`string`?i.file_path:``,t=typeof i.offset==`number`?i.offset:void 0,n=typeof i.limit==`number`?i.limit:void 0;return{summary:`${e}${t||n?` (${t?`from ${t}`:``}${t&&n?`, `:``}${n?`limit ${n}`:``})`:``}`,lines:N([e?`file: ${e}`:void 0,t?`offset: ${t}`:void 0,n?`limit: ${n}`:void 0])}}if(r===`Glob`){let e=typeof i.pattern==`string`?i.pattern:``;return{summary:e,lines:N([e?`pattern: ${e}`:void 0])}}if(r===`Grep`){let t=typeof i.pattern==`string`?i.pattern:``,n=typeof i.output_mode==`string`?i.output_mode:``,r=typeof i.path==`string`?i.path:``;return{summary:`${t}${r?` in ${r}`:``}`,lines:N([t?`pattern: ${e(t,120)}`:void 0,r?`path: ${r}`:void 0,n?`mode: ${n}`:void 0])}}if(r===`WebSearch`){let t=typeof i.query==`string`?i.query:``;return{summary:e(t,120),lines:N([t?`query: ${e(t,200)}`:void 0])}}let a=Object.keys(i),o=a.slice(0,6).join(`, `);return{summary:o?`{${o}${a.length>6?`, …`:``}}`:`{}`,lines:o?[`args: { ${o}${a.length>6?`, …`:``} }`]:[]}},ie=()=>{if(!h&&!g||!process.stdout.isTTY)return null;let t=process.env.GOATCHAIN_TITLE??`GoatChain`,n=`working`,r=``,i=0,a=null,o=!1,s=Date.now(),l=()=>(i=(i+1)%4,`.`.repeat(i)),u=e=>b?e===`thinking`?`🤔`:e===`tool_call`?`🛠️`:e===`responding`?`✍️`:e===`working`?`…`:``:``,d=()=>{let e=u(n),t=e?`${e} ${n}`:n;return r?`${t}: ${r}`:t},f=e=>{h&&process.stdout.write(`\u001B]0;${e}\u0007`)},p=()=>{if(!g||Date.now()-s<450)return;o||=(S||=(process.stdout.write(`
|
|
4
|
+
`),!0),!0);let t=l(),n=`${d()}${t}`;process.stdout.write(`\r\u001B[2K${c.dim(e(n,120))}`),S=!1},m=()=>{o&&(process.stdout.write(`\r\x1B[2K`),o=!1,S=!0)},_=()=>{let e=l();f(`${t} — ${d()}${e}`),p()};return{start:()=>{a||(_(),a=setInterval(_,250),typeof a?.unref==`function`&&a.unref())},stop:()=>{a&&=(clearInterval(a),null),m(),f(t)},set(e,t){n=String(e??`working`),r=String(t??``)},onOutput(){s=Date.now(),m()},onPauseForInput(){m()}}},F=()=>{D={text:``,toolCalls:[],flushedToolCallAssistant:!1},O=new Map,k=new Map,A=new Set},I=()=>{D.flushedToolCallAssistant||!Array.isArray(D.toolCalls)||D.toolCalls.length===0||(E.push({role:`assistant`,content:D.text||``,tool_calls:D.toolCalls}),D.flushedToolCallAssistant=!0)},ae=(e,t)=>{let n=typeof t==`string`?t:JSON.stringify(t);E.push({role:`tool`,tool_call_id:e,content:n})},oe=t=>{try{if(t&&typeof t==`object`){let n=t,r=n.structuredContent&&typeof n.structuredContent==`object`?n.structuredContent:null;if(r&&`totalMatches`in r&&`files`in r&&Array.isArray(r.files)){let e=r.files,t=Number(r.totalMatches??e.length),n=e.length,i=r.truncated===!0;return[`Found ${Number.isFinite(t)?t:n} file(s)`,i?`(showing ${n})`:n===t?``:`(showing ${n})`].filter(Boolean).join(` `)}if(r&&`fileSize`in r&&(`totalLines`in r||`linesReturned`in r)){let e=Number(r.totalLines??0),t=Number(r.linesReturned??0),n=r.truncated===!0,i=Number(r.fileSize??0);return[`Read file`,Number.isFinite(t)&&Number.isFinite(e)&&e>0?`(${t}/${e} lines)`:t>0?`(${t} lines)`:``,Number.isFinite(i)&&i>0?`(${re(i)})`:``,n?`(truncated)`:``].filter(Boolean).join(` `)}if(r&&`bytesWritten`in r&&`filePath`in r){let e=String(r.filePath??``),t=Number(r.bytesWritten??0);return[r.overwritten===!0?`Overwrote`:`Wrote`,e||`file`,t>0?`(${re(t)})`:``].filter(Boolean).join(` `)}let i=n.content;if(Array.isArray(i)){let t=i.find(e=>{if(!e||typeof e!=`object`)return!1;let t=e;return t.type===`text`&&typeof t.text==`string`});if(t&&typeof t.text==`string`)return e(t.text,200)}}return e(typeof t==`string`?t:JSON.stringify(t),200)}catch{return``}},se=async e=>{if(te)return{approved:!0};if(typeof s==`function`){let t=e.toolName,n=P(t,e.args),r=await s({toolName:t,riskLevel:e.riskLevel,args:e.args,display:n});if(typeof r==`boolean`)return{approved:r};let i=String(r??``).trim().toLowerCase();if(i===`approve_all`||i===`all`)return te=!0,{approved:!0};if(i===`approve`||i===`yes`||i===`y`)return{approved:!0};if(i===`abort`)throw Error(`Aborted by user`);return{approved:!1}}if(!o)return{approved:!1,reason:`No approval handler available`};let t=e.toolName,n=e.riskLevel?` (${String(e.riskLevel)})`:``,r=P(t,e.args),i=`${c.highlight(` approval required `)}${b?` ${x(`🛑`).trimEnd()}`:``} ${c.bold(String(t??`tool`))}${n}\n`,a=(r.lines.length>0?r.lines:[`(no args)`]).map(e=>`- ${e}`).join(`
|
|
5
|
+
`),l=await o(`\n${i}${c.dim(a)}\n${c.bold(`${x(`✅`).trimEnd()}Allow?`)} [y/N] `),u=String(l??``).trim().toLowerCase();return{approved:u===`y`||u===`yes`}},ce=(e,t,n=!1)=>{if(f){T(),w(`${c.dim(`┌─ ${b?`🛠️ `:``}${e}`)}\n`);for(let e of t)e&&w(`${c.dim(`│ ${e}`)}\n`);w(`${c.dim(`└─`)}\n`),n&&w(`
|
|
6
|
+
`)}},le=t=>{let n=String(t??``);if(!n)return``;try{return e(n.startsWith(`/`)?_.relative(process.cwd(),n):n,80)}catch{return e(n,80)}},L=(e,t)=>{if(!f)return;T();let n=c.bold(String(e??`tool`)),r=String(t??``).trim(),i=b?`${x(`🛠️`).trimEnd()} [tool]`:`[tool]`,a=[c.dim(i),n,r?c.dim(r):``].filter(Boolean).join(` `);w(`${c.dim(`•`)} ${a}\n`)},R=e=>{if(!f)return;let t=String(e??``).trim()||`[no output]`;w(`${c.dim(` └`)} ${c.dim(`${b?`📄 `:``}${t}`)}\n`)},ue=e=>{if(!b)return``;if(e&&typeof e==`object`){let t=e;if(t.isError===!0)return`❌`;let n=t.structuredContent&&typeof t.structuredContent==`object`?t.structuredContent:null;if(n&&n.truncated===!0)return`⚠️`}return`✅`},de=e=>{let t=String(e??``).trim();return!t||/[。.!??!]$/.test(t)?!1:!!(/(我将|我會|我会|接下来|下一步|然后|让我|开始创建|我将创建|我会创建)/.test(t)||/(\.html|\.ts|tank-battle)/i.test(t)&&/(创建|写入|生成|create|write|implement)/i.test(t))},z=async e=>{let n=``,r=``;C=ie(),C?.start();try{for await(let i of e)if(i.type===`thinking_start`)C?.set(`thinking`,``);else if(i.type===`thinking_end`)C?.set(`working`,``);else if(i.type===`iteration_start`)F(),C?.set(`thinking`,``);else if(i.type===`text_delta`)D.text+=i.delta,w(i.delta),C?.set(`responding`,``);else if(i.type===`tool_call_start`)C?.set(`tool_call`,i.toolName??``);else if(i.type===`tool_call_end`){D.toolCalls.push(i.toolCall);let e=i.toolCall?.function?.name??`unknown`;i.toolCall?.id&&O.set(i.toolCall.id,e);let t={};try{let e=i.toolCall?.function?.arguments;t=typeof e==`string`?JSON.parse(e):e&&typeof e==`object`?e:{}}catch{t={_raw:i.toolCall?.function?.arguments}}let n=P(e,t);if(i.toolCall?.id)if(e===`Read`||e===`Write`||e===`Edit`){let n=typeof t.file_path==`string`?t.file_path:``;if(e===`Write`){let e=typeof t.content==`string`?re(ne(t.content)):``;k.set(i.toolCall.id,`${le(n)}${e?` (${e})`:``}`.trim())}else if(e===`Edit`){let e=Array.isArray(t.edits)?t.edits.length:0;k.set(i.toolCall.id,`${le(n)}${e?` (${e} edits)`:``}`.trim())}else k.set(i.toolCall.id,le(n)||``)}else k.set(i.toolCall.id,n.summary||``);if(p===`box`)ce(`${c.bold(e)}${n.summary?` ${c.dim(n.summary)}`:``}`,n.lines.length?n.lines:[n.summary||`(no args)`]);else if(i.toolCall?.id&&!A.has(i.toolCall.id)){A.add(i.toolCall.id);let t=k.get(i.toolCall.id)??``;L(e,t||n.summary||``),M.tools.push({toolName:e,argsSummary:t||n.summary||``})}C?.set(`tool_call`,i.toolCall?.function?.name??``)}else if(i.type===`tool_result`){I(),ae(i.tool_call_id,i.result);let e=oe(i.result),t=O.get(i.tool_call_id);if(t&&j.add(t),p!==`box`){if(t&&!A.has(i.tool_call_id)){A.add(i.tool_call_id);let e=k.get(i.tool_call_id)??``;L(t,e),M.tools.push({toolName:t,argsSummary:e})}let n=k.get(i.tool_call_id)??``,r=ue(i.result);if(R(`${r?`${r} `:``}${e||`[no output]`}`),t){let r=M.tools.slice().reverse().find(e=>e.toolName===t&&!e.resultSummary);r?r.resultSummary=e||`[no output]`:M.tools.push({toolName:t,argsSummary:n,resultSummary:e||`[no output]`})}}else{let n=ue(i.result);ce(t?`tool result ${c.bold(t)}${n?` ${n}`:``}`:`tool result${n?` ${n}`:``}`,[e||`[no output]`])}C?.set(`thinking`,``)}else if(i.type===`requires_action`&&i.kind===`tool_approval`){I(),C?.stop(),C=null,T();let e=await se(i),n=i.checkpoint;if(!n)throw Error(`Approval requested but no checkpoint provided; configure a checkpoint store or enable inline checkpoint`);if(typeof t.streamFromCheckpoint!=`function`)throw Error("Approval requested but `agent.streamFromCheckpoint` is not available; update the agent implementation to support checkpoint resume.");return z(t.streamFromCheckpoint({checkpoint:n,signal:a,toolContext:{approval:{decisions:{[i.tool_call_id]:e}}}}))}else if(i.type===`iteration_end`)i.willContinue===!1&&E.push({role:`assistant`,content:D.text||``});else if(i.type===`done`){n=i.stopReason?String(i.stopReason):``,r=i.modelStopReason?String(i.modelStopReason):``;break}else if(i.type===`error`){let e=i.error instanceof Error?i.error.message:String(i.error);T(),w(`${c.red(`${x(`❌`).trimEnd()}[error] ${e}`)}\n`),n=`error`;break}}finally{C?.stop(),C=null}return{doneReason:n,modelStopReason:r}},B=``,V=``,H=await z(t.stream({sessionId:n,input:i,messages:r,signal:a,toolContext:{approval:{strategy:l,autoApprove:u}}}));B=H.doneReason,V=H.modelStopReason;let U=[...E].reverse().find(e=>e&&typeof e==`object`&&e.role===`assistant`),fe=typeof U?.content==`string`?U.content:``,pe=y;if((pe||v&&typeof o==`function`)&&!j.has(`Write`)&&!j.has(`Edit`)&&de(fe)){let e=pe;if(!e){if(typeof o!=`function`)throw Error(`promptContinue enabled but no askApproval handler provided`);let t=await o(`${c.dim(`
|
|
7
|
+
The model seems to have stopped before implementing.`)} Continue? [Y/n] `),n=String(t??``).trim().toLowerCase();e=n===``||n===`y`||n===`yes`}if(e){let e=`继续。不要只说计划:请立刻开始实现,使用 Write/Edit 创建或修改文件。`;E.push({role:`user`,content:e});let o={role:`user`,content:i},s=[...r,o,...E.slice(0,-1)],c=await z(t.stream({sessionId:n,input:e,messages:s,signal:a,toolContext:{approval:{strategy:l,autoApprove:u}}}));B=c.doneReason,V=c.modelStopReason}}if(M.stopReason=B,M.modelStopReason=V,m){T();let e=[];B&&B!==`final_response`&&e.push(`stopReason=${B}`),V&&V!==`final`&&e.push(`modelStopReason=${V}`);let t=`${x(`✅`).trimEnd()}done${e.length?` (${e.join(` `)})`:``}`;if(w(`${c.dim(`─ ${t} ─`)}\n`),V===`length`)w(`${c.dim(`${x(`💡`).trimEnd()}hint: increase maxTokens via /set maxTokens 2048 if output is truncated`)}\n`);else{let e=[...E].reverse().find(e=>e&&typeof e==`object`&&e.role===`assistant`),t=typeof e?.content==`string`?e.content:``;!j.has(`Write`)&&!j.has(`Edit`)&&de(t||D.text||``)&&w(`${c.dim(`${x(`💡`).trimEnd()}hint: response ended before any Write/Edit; ask “继续并开始写文件” or increase maxTokens`)}\n`)}}return T(),w(`
|
|
8
|
+
`),{messagesToAppend:E,meta:M}}async function S(){try{let e=await import(`@clack/prompts`);return e&&typeof e.select==`function`?e:null}catch{return null}}async function C({message:e,options:t,initialValue:n}){let r=await S();if(!r)return{ok:!1,reason:`missing`};let i=typeof n==`number`?t[n]?.value:n,a=await r.select({message:e,options:t,initialValue:i});return r.isCancel(a)?{ok:!1,reason:`cancel`}:{ok:!0,value:a}}async function w({message:e,options:t,required:n=!1}){let r=await S();if(!r)return{ok:!1,reason:`missing`};if(typeof r.multiselect!=`function`)return{ok:!1,reason:`unsupported`};let i=await r.multiselect({message:e,options:t,required:n});return r.isCancel(i)?{ok:!1,reason:`cancel`}:{ok:!0,value:i}}async function T({message:e,initialValue:t=!1}){let n=await S();if(!n)return{ok:!1,reason:`missing`};if(typeof n.confirm!=`function`)return{ok:!1,reason:`unsupported`};let r=await n.confirm({message:e,initialValue:t});return n.isCancel(r)?{ok:!1,reason:`cancel`}:{ok:!0,value:!!r}}async function E({message:e,placeholder:t}){let n=await S();if(!n)return{ok:!1,reason:`missing`};if(typeof n.text!=`function`)return{ok:!1,reason:`unsupported`};let r=await n.text({message:e,placeholder:t});return n.isCancel(r)?{ok:!1,reason:`cancel`}:{ok:!0,value:String(r??``)}}async function D({message:e,placeholder:t}){let n=await S();if(!n)return{ok:!1,reason:`missing`};if(typeof n.password!=`function`)return{ok:!1,reason:`unsupported`};let r=await n.password({message:e});return n.isCancel(r)?{ok:!1,reason:`cancel`}:{ok:!0,value:String(r??``)}}const O=new Set([`node_modules`,`.git`,`.goatchain`,`dist`,`tmp`]);function k(e,t){let n=_.relative(_.resolve(e),_.resolve(t));return n===``?!0:n===`..`?!1:!n.startsWith(`..${_.sep}`)&&!_.isAbsolute(n)}function A(e,t){let n=_.isAbsolute(t)?t:_.resolve(e,t);if(!k(e,n))throw Error(`Access denied: ${n}\nAllowed directory: ${e}`);let r=_.join(e,`.goatchain`);if(k(r,n))throw Error(`Access denied: ${n}\nRestricted: ${r}`);return n}async function j(e,t={}){let n=typeof t.maxFiles==`number`?t.maxFiles:5e3,r=new Set(t.ignoreDirs??O),i=[],a=[`.`];for(;a.length>0;){let t=a.shift();if(!t)break;let o=_.resolve(e,t),s;try{s=await p(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:_.join(t,o);a.push(e);continue}if(!e.isFile())continue;let s=t===`.`?o:_.join(t,o);if(i.push(s),i.length>=n)return i}}return i}function M(e,t){return t<=0?[]:e.slice(0,Math.min(e.length,t))}function te(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(`
|
|
9
|
+
`);if(c.length<=n+r)return{text:s,truncated:o>i};let l=M(c,n),u=c.slice(Math.max(n,c.length-r));return{text:`${l.join(`
|
|
10
|
+
`)}\n…\n${u.join(`
|
|
11
|
+
`)}`,truncated:!0}}async function ne(e,t,n){let r=Math.max(0,Math.min(Number(t)||0,n)),i=await d(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 re(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 N(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=re(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=A(e,n.filePath),l=await h(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:_.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 g=n.mode===`summary`?a:i,v=Math.min(g,m),y=await ne(c,v,l.size);if(f+=Math.min(y.bytes,v),n.mode===`full`)u.push({mode:`full`,relPath:_.relative(e,c),absPath:c,bytes:y.bytes,truncated:y.truncated,content:y.text});else{let t=te(y.text,{headLines:o,tailLines:s,maxBytes:v});u.push({mode:`summary`,relPath:_.relative(e,c),absPath:c,bytes:y.bytes,truncated:y.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 g=u.filter(e=>e.mode!==`path`).map(e=>`${`---\nfile: ${e.relPath}\nmode: ${e.mode}${e.truncated?` (truncated)`:``}\n---\n`}${String(e.content??``)}`.trimEnd()),v=u.filter(e=>e.mode===`path`).map(e=>e.relPath),y=[g.length>0||v.length>0?`[attached files]`:``,v.length>0?`paths: ${v.join(`, `)}`:``].filter(Boolean).join(`
|
|
12
|
+
`);return{text:[m,y,...g].filter(Boolean).join(`
|
|
13
|
+
|
|
14
|
+
`),files:u,omitted:d}}const P=ee(y);async function ie(e,t=1024*1024){if(process.platform!==`darwin`)return null;try{let{stdout:n}=await P(`osascript`,e.flatMap(e=>[`-e`,e]),{encoding:`utf8`,maxBuffer:t});return String(n??``)}catch{return null}}function F(e){let t=String(e??``).trim();if(!t)return[];let n=t.split(/\u0000|\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 I(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 ae(){if(process.platform!==`darwin`)return null;try{let{stdout:e}=await P(`pbpaste`,[],{encoding:`utf8`,maxBuffer:2*1024*1024});return String(e??``)}catch{return null}}async function oe(){if(process.platform!==`darwin`)return null;let e=await ie([`clipboard info`]);return String(e??``).trim()||null}async function se(e){if(process.platform!==`darwin`)return null;try{let{stdout:t}=await P(`pbpaste`,[`-Prefer`,String(e)],{encoding:`utf8`,maxBuffer:2*1024*1024});return String(t??``)}catch{return null}}async function ce(){if(process.platform!==`darwin`)return[];let e=await ie([`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 le(){if(process.platform!==`darwin`)return[];let e=await ie([`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 L(e,t=12*1024*1024){if(process.platform!==`darwin`)return null;try{let{stdout:n}=await P(`pbpaste`,[`-Prefer`,String(e)],{encoding:`buffer`,maxBuffer:t});return!Buffer.isBuffer(n)||n.length<8?null:n}catch{return null}}async function R(e,t){if(process.platform!==`darwin`||!Buffer.isBuffer(e)||e.length===0)return null;let n=String(t??``).toLowerCase()||`.bin`,r=await u(_.join(b.tmpdir(),`goatchain-clip-`)),i=_.join(r,`in${n}`),a=_.join(r,`out.png`);try{await g(i,e),await P(`sips`,[`-s`,`format`,`png`,i,`--out`,a],{encoding:`utf8`,maxBuffer:1024*1024});let t=await f(a),n=I(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 m(r,{recursive:!0,force:!0})}catch{}}}async function ue(e,t=4*1024*1024){let n=await h(e);if(!n.isFile()||n.size>t)return null;let r=await f(e),i=I(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 de(e=4*1024*1024){if(process.platform!==`darwin`)return[];let t=[],n=await se(`public.file-url`),r=F(n&&n.trim()?n:await ae());if(r.length===0&&(r=await ce()),r.length>0)for(let n of r)try{let r=await ue(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 L(n,Math.max(12*1024*1024,e));if(!r)continue;let i=I(r);if(!i||!i.mime.startsWith(`image/`))continue;if(i.mime===`image/tiff`||i.mime===`image/bmp`){let e=await R(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 z=`\x1B]1337;File=`;function B(e,t){let n=e.indexOf(`\x07`,t),r=e.indexOf(`\x1B\\`,t);return n===-1&&r===-1?{idx:-1,len:0}:n===-1?{idx:r,len:2}:r===-1||n<r?{idx:n,len:1}:{idx:r,len:2}}function V(e){try{return Buffer.from(String(e??``),`base64`).toString(`utf8`)}catch{return``}}function H(e){try{let t=Buffer.from(String(e??``).slice(0,96),`base64`);if(t.length>=8){if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10)return{mime:`image/png`,ext:`.png`};if(t[0]===255&&t[1]===216&&t[2]===255)return{mime:`image/jpeg`,ext:`.jpg`};if(t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56)return{mime:`image/gif`,ext:`.gif`};if(t.length>=12){let e=t.subarray(0,4).toString(`ascii`),n=t.subarray(8,12).toString(`ascii`);if(e===`RIFF`&&n===`WEBP`)return{mime:`image/webp`,ext:`.webp`}}}}catch{}return{mime:`application/octet-stream`,ext:``}}function U(e,t){let n=String(e??``).toLowerCase();return n.endsWith(`.png`)?{mime:`image/png`,ext:`.png`}:n.endsWith(`.jpg`)||n.endsWith(`.jpeg`)?{mime:`image/jpeg`,ext:`.jpg`}:n.endsWith(`.webp`)?{mime:`image/webp`,ext:`.webp`}:n.endsWith(`.gif`)?{mime:`image/gif`,ext:`.gif`}:H(t)}function fe(e){let t=e.indexOf(z);if(t<0)return null;let n=(e.endsWith(`\x07`)?e.slice(0,-1):e.endsWith(`\x1B\\`)?e.slice(0,-2):e).slice(t+12),r=n.indexOf(`:`);if(r<0)return null;let i=n.slice(0,r),a=n.slice(r+1).replace(/\s+/g,``);if(!a)return null;let o={};for(let e of i.split(`;`)){let[t,...n]=e.split(`=`);t&&(o[t]=n.join(`=`))}let s=o.name?V(o.name):``,c=s?_.basename(s):``,l=o.size?Number(o.size):void 0,{mime:u,ext:d}=U(c,a);return{name:c||`pasted-image${d||``}`,mime:u,bytes:typeof l==`number`&&Number.isFinite(l)?l:(()=>{try{return Buffer.from(a,`base64`).byteLength}catch{return 0}})(),dataUrl:`data:${u};base64,${a}`}}function pe(e,t=``){let n=`${String(t??``)}${String(e??``)}`;if(!n.includes(z))return{text:String(e??``),files:[],buffer:``};let r=``,i=[],a=0;for(;;){let e=n.indexOf(z,a);if(e===-1){r+=n.slice(a);break}r+=n.slice(a,e);let t=B(n,e);if(t.idx===-1)return{text:r,files:i,buffer:n.slice(e)};let o=fe(n.slice(e,t.idx+t.len));o&&i.push(o),a=t.idx+t.len}return{text:r,files:i,buffer:``}}function W(e){if(typeof e==`string`)return e;try{return JSON.stringify(e??``)}catch{return String(e??``)}}function me(e,t){let n=new Set(Array.isArray(t)?t.map(String):[]);return(Array.isArray(e)?e:[]).filter(e=>e&&n.has(String(e.sessionId)))}function he(e){let t=Array.isArray(e)?e:[];return{schemaVersion:1,exportedAt:Date.now(),sessions:t.map(e=>({sessionId:typeof e?.sessionId==`string`?e.sessionId:l(),createdAt:typeof e?.createdAt==`number`?e.createdAt:void 0,updatedAt:typeof e?.updatedAt==`number`?e.updatedAt:void 0,modelId:typeof e?.modelId==`string`?e.modelId:void 0,systemPrompt:typeof e?.systemPrompt==`string`?e.systemPrompt:void 0,title:typeof e?.title==`string`?e.title:void 0,summary:typeof e?.summary==`string`?e.summary:void 0,pinned:!!e?.pinned,messages:Array.isArray(e?.messages)?e.messages:[]}))}}function ge(e,t={}){let n=typeof t.exportedAt==`string`?t.exportedAt:new Date().toISOString(),r=Array.isArray(e)?e:[],i=[];i.push(`# Sessions export`),i.push(``),i.push(`exportedAt: ${n}`),i.push(``);for(let e of r){i.push(`---`),i.push(`## ${e?.title??`New session`}`),i.push(`- id: ${e?.sessionId??``}`),e?.modelId&&i.push(`- model: ${String(e.modelId)}`),i.push(`- pinned: ${!!e?.pinned}`),e?.summary&&i.push(`- summary: ${String(e.summary).replace(/\n/g,` `)}`),i.push(``),i.push(`### Messages`);let t=Array.isArray(e?.messages)?e.messages:[];for(let e of t){let t=e?.role?String(e.role):`message`,n=W(e?.content).replace(/\n/g,`\\n`);i.push(`- ${t}: ${n}`)}i.push(``)}return`${i.join(`
|
|
15
|
+
`)}\n`}function _e(e){if(Array.isArray(e))return e;if(e&&typeof e==`object`){let t=e;if(Array.isArray(t.sessions))return t.sessions;if(typeof t.sessionId==`string`)return[e]}return[]}async function ve(e,t={}){let n=String(t?.conflict??`new_ids`),r=typeof t?.exists==`function`?t.exists:async()=>!1,i=typeof t?.makeId==`function`?t.makeId:()=>l(),a=[],o=Array.isArray(e)?e:[];for(let e of o){if(!e||typeof e!=`object`)continue;let t=e,o=typeof t.sessionId==`string`&&t.sessionId.trim()?t.sessionId.trim():i();if(await r(o)){if(n===`skip`)continue;n===`new_ids`&&(o=i())}a.push({sessionId:o,session:{sessionId:o,createdAt:typeof t.createdAt==`number`?t.createdAt:Date.now(),updatedAt:typeof t.updatedAt==`number`?t.updatedAt:Date.now(),modelId:typeof t.modelId==`string`?t.modelId:void 0,systemPrompt:typeof t.systemPrompt==`string`?t.systemPrompt:void 0,title:typeof t.title==`string`?t.title:void 0,summary:typeof t.summary==`string`?t.summary:void 0,pinned:!!t.pinned,messages:Array.isArray(t.messages)?t.messages:[]}})}return a}const ye=`help.exit.quit.tools.status.model.edit.multiline.ml.params.set.unset.api-key.key.base-url.save.new.workspace.files.images.settings.output.diag.diagnostics.sessions.use.rm.delete.clipboard.compact`.split(`.`),be=[`@`,`@continue`,`@sessions`,`@workspace`,`@model`,`@settings`,`@file`,`@image`,`@img`,`@clear`];function xe(e){let t=String(e||``).trim();if(!t)return``;let n=t.toLowerCase();return n===`maxtokens`||n===`max_tokens`?`maxOutputTokens`:n===`top_p`||n===`topp`?`topP`:n===`presence_penalty`?`presencePenalty`:n===`frequency_penalty`?`frequencyPenalty`:n===`timeout`||n===`timeoutms`?`timeoutMs`:t}function Se(e,t){let n=xe(e),r=String(t??``).trim();if(!n)return{ok:!1,error:`Missing key`};if(r.length===0)return{ok:!1,error:`Missing value`};let i=e=>{let t=Number(r);return Number.isFinite(t)?{ok:!0,value:t}:{ok:!1,error:`Invalid ${e}: ${r}`}},a=e=>{let t=Number.parseInt(r,10);return Number.isFinite(t)?{ok:!0,value:t}:{ok:!1,error:`Invalid ${e}: ${r}`}};return n===`maxOutputTokens`?a(`maxTokens`):n===`timeoutMs`||n===`seed`?a(n):n===`temperature`||n===`topP`||n===`presencePenalty`||n===`frequencyPenalty`?i(n):{ok:!1,error:`Unknown param: ${e}`}}function Ce(e){let{version:t,provider:n,modelId:r,sessionId:i,history:a,agent:o,baseUrl:s,requestDefaults:c,workspaceCwd:l,emoji:u}=e,d=!!u&&process.stdout.isTTY&&process.env.TERM!==`dumb`,f=(e,t)=>d?`${e} ${t}`:t,p=Math.floor(a.length/2),m=o?.stats?.totalUsage??{promptTokens:0,completionTokens:0,totalTokens:0},h=c??{},g=[typeof h.maxOutputTokens==`number`?`maxTokens=${h.maxOutputTokens}`:void 0,typeof h.temperature==`number`?`temperature=${h.temperature}`:void 0,typeof h.topP==`number`?`topP=${h.topP}`:void 0,typeof h.presencePenalty==`number`?`presencePenalty=${h.presencePenalty}`:void 0,typeof h.frequencyPenalty==`number`?`frequencyPenalty=${h.frequencyPenalty}`:void 0,typeof h.seed==`number`?`seed=${h.seed}`:void 0,typeof h.timeoutMs==`number`?`timeoutMs=${h.timeoutMs}`:void 0].filter(Boolean);process.stdout.write([f(`🧾`,`version: ${t}`),f(`🗂️`,`session: ${i}`),f(`🤖`,`model: ${n}/${r}`),f(`🌐`,`baseUrl: ${s??``}`),f(`⚙️`,`params: ${g.join(` `)}`),f(`🔁`,`turns: ${p}`),f(`💬`,`messages: ${a.length}`),f(`📊`,`usage: prompt=${m.promptTokens} completion=${m.completionTokens} total=${m.totalTokens}`),f(`📁`,`workspace: ${l}`),``].join(`
|
|
16
|
+
`))}function G(){return!(!process.stdout.isTTY||process.env.TERM===`dumb`||process.env.GOATCHAIN_NO_ALT_SCREEN===`1`)}function we(){return G()?(process.stdout.write(`\x1B[?1049h\x1B[2J\x1B[H\x1B[?25l`),!0):!1}function Te(){process.stdout.isTTY&&process.stdout.write(`\x1B[?25h\x1B[0m\x1B[?1049l`)}function Ee(e,t){let n=String(e??``),r=String(t??``),i=n.length,a=r.length;if(i===0)return a;if(a===0)return i;let o=Array(a+1),s=Array(a+1);for(let e=0;e<=a;e++)o[e]=e;for(let e=1;e<=i;e++){s[0]=e;let t=n.charCodeAt(e-1);for(let e=1;e<=a;e++){let n=t===r.charCodeAt(e-1)?0:1;s[e]=Math.min(o[e]+1,s[e-1]+1,o[e-1]+n)}for(let e=0;e<=a;e++)o[e]=s[e]}return o[a]}function De(e){return/^[a-z0-9][a-z0-9_-]*$/.test(e)}function Oe(e){let t=String(e??``).trim().toLowerCase();if(!t)return{kind:`empty`,cmd:``};if(!De(t))return{kind:`none`,cmd:``};if(ye.includes(t))return{kind:`exact`,cmd:t};let n=ye.filter(e=>e.startsWith(t));if(n.length===1)return{kind:`prefix`,cmd:n[0],matches:n};if(n.length>1)return{kind:`ambiguous`,cmd:``,matches:n};let r=t.length<=4?1:2,i=ye.filter(e=>e[0]===t[0]).map(e=>({c:e,d:Ee(t,e)})).filter(e=>e.d<=r).sort((e,t)=>e.d-t.d||e.c.localeCompare(t.c)).slice(0,5).map(e=>e.c);if(i.length>0)return{kind:`fuzzy`,cmd:``,matches:i};if(t.length>=3){let e=ye.filter(e=>e.includes(t)).slice(0,5);if(e.length>0)return{kind:`contains`,cmd:``,matches:e}}return{kind:`none`,cmd:``}}function ke(e,t){let n=String(t??``).trim().toLowerCase();return n?e.filter(e=>`${e.title??``} ${e.summary??``} ${e.sessionId??``}`.toLowerCase().includes(n)):e}function Ae(e,t){let n=String(t??``).trim();if(!n)return String(e??``);let r=String(e??``),i=r.toLowerCase().indexOf(n.toLowerCase());return i<0?r:`${r.slice(0,i)}${c.highlight(r.slice(i,i+n.length))}${r.slice(i+n.length)}`}function je(t){let{sessions:n,currentSessionId:r,filter:o,alt:s,emoji:l}=t;s?i():process.stdout.write(`
|
|
17
|
+
`);let u=!!l&&process.stdout.isTTY&&process.env.TERM!==`dumb`,d=String(o??``).trim(),f=ke(n,o),p=process.stdout.isTTY&&typeof process.stdout.columns==`number`&&process.stdout.columns>0?process.stdout.columns:120,m=process.stdout.isTTY&&typeof process.stdout.rows==`number`&&process.stdout.rows>0?process.stdout.rows:24,h=e(`${u?`🗂️ `:``}Sessions ${f.length}/${n.length} filter: ${d||`∅`} (# open · text filter · empty cancel)`,Math.max(20,p-2)),g=Math.min(f.length,Math.max(8,m-6)),_=String(Math.min(f.length,g)||1).length,v=Math.min(38,Math.max(26,Math.floor(p*.25))),y=Math.min(52,Math.max(22,Math.floor(p*.32))),ee=Math.max(0,p-(6+_+v+y)),b=[c.header(` ${h} `),``];for(let t=0;t<Math.min(f.length,g);t++){let n=f[t],i=n.sessionId===r,o=i?c.green(u?`▶️`:`▶`):` `,s=n.pinned?c.yellow(`★`):` `,l=Array.isArray(n.messages)?n.messages.length:0,p=e(n.title??`New session`,y),m=i?c.bold(p):Ae(p,d),h=a(n.updatedAt),g=typeof n.sessionId==`string`?n.sessionId.slice(-8):``,x=e(`(${l} msgs · ${h}${g?` · ${g}`:``})`,v),S=c.dim(x),C=ee>=20?e(n.summary??``,ee):``,w=C?` ${c.gray(`— ${C}`)}`:``,T=c.yellow(`[${String(t+1).padStart(_,` `)}]`);b.push(`${o}${s} ${T} ${m} ${S}${w}`)}return f.length>g&&b.push(c.dim(`… and ${f.length-g} more (refine with filter text)`)),b.push(``),process.stdout.write(`${b.join(`
|
|
18
|
+
`)}\n`),{filtered:f}}async function Me(i){let{version:u,provider:d,agentRef:p,modelRef:m,toolsInfo:h,requestDefaults:y,baseUrlRef:ee,setBaseUrl:b,setApiKey:S,saveAll:O,listSessions:k,loadSessionById:M,saveSessionByData:te,renameSessionById:ne,setPinnedSessionsById:re,deleteSessionById:P,deleteSessionsById:ie,uiPrefs:F,switchWorkspace:I,getWorkspaceCwd:se}=i,ce=()=>!!F?.emoji&&process.stdout.isTTY&&process.env.TERM!==`dumb`,L=e=>ce()?`${e} `:``,R=(e,t)=>{let n=process.env.GOATCHAIN_CLACK_EMOJI===`1`;return ce()&&(n||!Y())?`${e} ${t}`:t},z=v.createInterface({input:process.stdin,output:process.stdout,prompt:`> `,completer:e=>{let t=String(e??``),n=t.trimStart();if(/\s/.test(n))return[[],t];if(n.startsWith(`/`)){let e=n.slice(1).toLowerCase();return[ye.filter(t=>t.startsWith(e)).map(e=>`/${e}`),t]}if(n.startsWith(`@`)){let e=n.toLowerCase();return[be.filter(t=>t.startsWith(e)).filter(t=>!(e===`@`&&t===`@`)),t]}return[[],t]}}),B=z,V=Promise.resolve(),H=`normal`,U=null,fe=!1,W=null,G=!1,Ee=0,De=!1,Ae=!1,Me={tools:[]},Ne=null,Pe=null,K=[],Fe=``,Ie=0,Le=0,Re=null,ze=null,Be=!1,Ve=``,q=null,J=e=>{if(process.stdout.isTTY)try{B.output.write(`\n${c.dim(e)}\n`),z.prompt(!0)}catch{}},Y=()=>{let e=(process.env.GOATCHAIN_UI??`auto`).toLowerCase();return process.stdout.isTTY&&e!==`legacy`},X=()=>{if(typeof se==`function`){let e=se();if(typeof e==`string`&&e.trim())return e}return h?.workspaceCwd??process.cwd()},Z=async e=>{Ee++;let t=!!B.paused;t||z.pause(),!(B.__savedReadlineFns??null)&&Ee===1&&(B.__savedReadlineFns={ttyWrite:B._ttyWrite,refreshLine:B._refreshLine},B._ttyWrite=()=>{},B._refreshLine=()=>{});try{return await e()}finally{let e=B.__savedReadlineFns??null;e&&Ee===1&&(B._ttyWrite=e.ttyWrite,B._refreshLine=e.refreshLine,B.__savedReadlineFns=null),t||z.resume(),Ee=Math.max(0,Ee-1)}},He=e=>{let t=String(e??``).trimStart();if(/\s/.test(t))return[];if(t.startsWith(`/`)){let e=t.slice(1).toLowerCase();return ye.filter(t=>t.startsWith(e)).map(e=>`/${e}`)}if(t.startsWith(`@`)){let e=t.toLowerCase();return be.filter(t=>t.startsWith(e)).filter(t=>!(e===`@`&&t===`@`))}return[]},Ue=e=>{let t=Number(e);return!Number.isFinite(t)||t<0?``:t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(2)} KB`:`${(t/(1024*1024)).toFixed(2)} MB`},Q=()=>{try{B._refreshLine?.()}catch{}};(()=>{if(!process.stdin.isTTY)return;let e=B._ttyWrite?.bind(z);if(typeof e!=`function`)return;let t=null,n=0,r=()=>{t=null},i=()=>{let e=Date.now(),n=String(B.line??``).trimStart();if(!n)return!1;if(!t||e-t.lastAt>2500){let r=He(n);if(r.length===0)return!1;t={prefix:n,options:r,index:-1,lastAt:e}}else{let n=He(t.prefix);t.options=n.length>0?n:t.options,t.lastAt=e}return t.index=(t.index+1)%t.options.length,B.line=t.options[t.index]??n,B.cursor=String(B.line??``).length,B._refreshLine?.(),!0},a=(e,t)=>{if(!Array.isArray(e)||e.length===0)return;let n=e=>{let t=String(e??``);return t===`image/png`?`.png`:t===`image/jpeg`?`.jpg`:t===`image/webp`?`.webp`:t===`image/gif`?`.gif`:``};for(let r of e){if(!r||typeof r!=`object`)continue;let e=typeof r.name==`string`?r.name:`pasted-image`,i=typeof r.mime==`string`?r.mime:`application/octet-stream`,a=typeof r.bytes==`number`?r.bytes:0,o=typeof r.dataUrl==`string`?r.dataUrl:``;if(!o)continue;if(!i.startsWith(`image/`)){queueMicrotask(()=>J(`Ignored non-image paste: ${e} (${i})`));continue}let s=e;if(t===`paste`){let t=e.toLowerCase(),r=K.some(e=>e&&typeof e.name==`string`&&e.name.toLowerCase()===t);if(!e||e===`pasted-image`){let e=n(i);s=`pasted-image-${++Ie}${e}`}else if(r){let t=_.parse(e),r=t.ext||n(i);s=`${t.name||e}-${++Ie}${r}`}}K.push({name:s,mime:i,bytes:a,dataUrl:o,source:t})}$(),Q()},o=e=>{let t=String(e??``).trim();if(!t||t.length>260||(t=t.replace(/^\u001B\[200~/,``).replace(/\u001B\[201~$/,``).trim(),t=t.replace(/[\u200B\u200C\u200D\uFEFF]/g,``),t.includes(`
|
|
19
|
+
`)||t.includes(`\r`))||t.includes(`/`)||t.includes(`\\`))return null;t=t.replace(/^["'`]+|["'`]+$/g,``).trim();let n=t.match(/^(.*?)(?:\s*\.\s*)(png|jpe?g|webp|gif|bmp|tiff?|heic)$/i);if(!n)return null;let r=String(n[1]??``).trim(),i=String(n[2]??``).trim().toLowerCase();return r?`${r}.${i}`:null},s=e=>{let t=String(B.line??``),n=String(e??``).trim();if(!n)return!1;let r=t.indexOf(n);if(r<0)return!1;let i=r===0?``:t[r-1],a=r+n.length>=t.length?``:t[r+n.length],o=!i||/\s|[,,。.!??::;;、()[\]{}"'“”‘’]/.test(i),s=r===0||!a||/\s|[,,。.!??::;;、()[\]{}"'“”‘’]/.test(a);if(!o||!s)return!1;let c=`${t.slice(0,r)} ${t.slice(r+n.length)}`.replace(/\s{2,}/g,` `).trimStart();return B.line=c,B.cursor=c.length,!0},c=()=>{let e=String(B.line??``),t=e.match(/^\s*(.*?)(?:\s*\.\s*)(png|jpe?g|webp|gif|bmp|tiff?|heic)(?=\s|[,,。.!??::;;、()[\]{}"'“”‘’]|$)\s*/i);if(!t)return!1;let n=String(t[0]??``);return n?(B.line=e.slice(n.length).trimStart(),B.cursor=String(B.line??``).length,!0):!1},l=e=>{let t=Date.now();if(t-Le<700)return;Le=t;let n=o(e);n&&(ze={name:n,at:Date.now()},!Re&&(Re={name:n,startedAt:t},$(),Q(),queueMicrotask(async()=>{let e=!1;try{let t=await de();if(!Array.isArray(t)||t.length===0){let t=await tt(),r=n.toLowerCase(),i=t.filter(e=>_.basename(String(e)).toLowerCase()===r).slice(0,8);if(i.length===1){let t=String(i[0]),r=await ue(A(X(),t));r?.dataUrl&&String(r.mime).startsWith(`image/`)&&(a([{name:_.basename(t),mime:String(r.mime),bytes:Buffer.isBuffer(r.buf)?r.buf.byteLength:0,dataUrl:String(r.dataUrl)}],`path`),e=!0,(s(n)||c())&&B._refreshLine?.(),J(`Attached image from workspace: ${_.basename(t)}`))}if(e)return;let o=await le();if(Array.isArray(o)&&o.length>0){let t=o.find(e=>_.basename(String(e)).toLowerCase()===r)??(o.length===1?o[0]:null);if(t){let r=await ue(String(t));r?.dataUrl&&String(r.mime).startsWith(`image/`)&&(a([{name:_.basename(String(t)),mime:String(r.mime),bytes:Buffer.isBuffer(r.buf)?r.buf.byteLength:0,dataUrl:String(r.dataUrl)}],`paste`),e=!0,(s(n)||c())&&B._refreshLine?.(),J(`Attached image from Finder selection: ${_.basename(String(t))}`))}}return}let r=n.toLowerCase(),i=t.filter(e=>e?.source===`file`&&e?.absPath),o=i.find(e=>_.basename(String(e.absPath)).toLowerCase()===r)??(i.length===1?i[0]:null)??(t.length===1?t[0]:null);if(!o||!o?.dataUrl||typeof o.dataUrl!=`string`||!o.dataUrl.startsWith(`data:image/`))return;a([{name:_.basename(String(o.absPath??n)),mime:String(o.mime??`image/png`),bytes:Buffer.isBuffer(o.buf)?o.buf.byteLength:0,dataUrl:String(o.dataUrl)}],`paste`),e=!0,(s(n)||c())&&B._refreshLine?.(),J(`Attached image: ${_.basename(String(o.absPath??n))}`)}catch{}finally{e||queueMicrotask(()=>J(`${L(`💡`)}Tip: clipboard is text-only. In Finder, select the file (not rename text) then Cmd+C; or drag & drop; or use @image.`)),Re=null,$(),Q()}})))};B._ttyWrite=(t,s)=>{if(s?.ctrl&&s?.name===`o`){if(Ee>0)return;if(G){queueMicrotask(()=>J(`busy (wait for current turn to finish)`));return}queueMicrotask(()=>{ot()});return}if(s?.ctrl&&s?.name===`g`&&K.length>0){K=[],Fe=``,Re=null,$(),Q(),queueMicrotask(()=>J(`Cleared pending attachments.`));return}if(typeof t==`string`&&(Be||t.includes(`\x1B[200~`)||t.includes(`\x1B[201~`))){r();let n=B.line,i=t,a=``;for(;i.length>0;){if(!Be){let e=i.indexOf(`\x1B[200~`);if(e===-1){a+=i,i=``;break}a+=i.slice(0,e),i=i.slice(e+6),Be=!0,Ve=``;continue}let e=i.indexOf(`\x1B[201~`);if(e===-1){Ve+=i,a+=i,i=``;break}let t=i.slice(0,e);if(Ve+=t,a+=t,i=i.slice(e+6),Be=!1,String(n??``).trim()===``){let e=o(Ve);e&&l(e)}Ve=``}return a?e(a,s):void 0}if(!s&&typeof t==`string`){r();let n=B.line,i=pe(t,Fe);if(Fe=i.buffer,Array.isArray(i.files)&&i.files.length>0&&queueMicrotask(()=>a(i.files,`paste`)),i.text&&(!Fe||i.text.trim().length>0)){let t=i.text,r=e(t,s);if(String(n??``).trim()===``){let e=o(t);e&&l(e)}return r}if(Fe)return}if(typeof t==`string`&&t.length>1&&!s?.ctrl&&!s?.meta&&!s?.alt){r();let n=B.line,i=e(t,s);if(String(n??``).trim()===``){let e=o(t);e&&l(e)}return i}if(s?.ctrl&&s?.name===`k`){if(Ee>0||De)return;if(G){queueMicrotask(()=>J(`busy (wait for current turn to finish)`));return}queueMicrotask(()=>{ct()});return}if(t===`@`&&String(B.line??``).trim()===``&&Date.now()-n>2e3&&(n=Date.now(),queueMicrotask(()=>J(`${L(`💡`)}Mentions: @continue @sessions @workspace @file @image/@img @clear @model @settings (Tab to cycle)`))),t===`/`&&String(B.line??``).trim()===``&&Date.now()-n>2e3&&(n=Date.now(),queueMicrotask(()=>J(`${L(`💡`)}Commands: /help /sessions /workspace /files /images /settings /output /diag /edit /multiline /model /set … (Tab to cycle)`))),s?.name===`tab`){if(i())return}else s?.name!==`shift`&&s?.name!==`ctrl`&&s?.name!==`alt`&&r();return e(t,s)}})();let $=()=>{let e=H===`select_session`?`session> `:q?`... `:`> `;if(H!==`select_session`&&(K.length>0||Re||q)&&process.stdout.isTTY){let t=K.slice(0,4).map((e,t)=>{let n=e.bytes?` (${Ue(e.bytes)})`:``;return`[${t+1}] ${e.name}${n}`}),n=K.length>4?` …(+${K.length-4})`:``,r=Re?`attaching: ${Re.name}…`:``,i=K.length>0?`images: ${t.join(` `)}${n}`:r,a=q?`multiline: .send · .cancel`:`Ctrl+O manage · Ctrl+G clear`,o=q&&K.length>0?`Ctrl+O manage · Ctrl+G clear`:``,s=i||a,c=i?a:o;z.setPrompt(c?`${s}\n${c}\n${e}`:`${s}\n${e}`);return}z.setPrompt(e)};$();let We=()=>{fe&&=(Te(),!1)},Ge=()=>{W&&W.abort(`cli_exit`),We(),Ae=!0,O().finally(()=>z.close())};process.on(`SIGINT`,()=>{if(W){W.abort(`sigint`);return}process.stdout.write(`
|
|
20
|
+
`),Ge()}),z.on(`close`,()=>{Ae=!0,V.finally(()=>O()).finally(()=>{process.stdout.write(`
|
|
21
|
+
`),process.exit(0)})});let Ke=async t=>{let[r,...h]=t.trim().split(/\s+/),v=r.slice(1).toLowerCase(),x=v,D=h.join(` `).trim(),A=p.get(),j=m.get(),N=async()=>{i.session.sessionId=l(),i.session.createdAt=Date.now(),i.session.title=void 0,i.session.summary=void 0,i.session.pinned=!1,i.session.history=[],await O(),process.stdout.write(`${c.green(`${L(`🆕`)}new session:`)} ${i.session.sessionId}\n`)},I=async e=>{if(!e)return process.stdout.write(`${L(`❌`)}Missing sessionId (try /sessions)\n`),!1;let t=await M(e);if(!t)return process.stdout.write(`${L(`❌`)}Session not found: ${e}\n`),!1;if(We(),i.session.sessionId=t.sessionId,i.session.createdAt=t.createdAt??Date.now(),i.session.title=t.title,i.session.summary=t.summary,i.session.pinned=!!t.pinned,i.session.history=Array.isArray(t.messages)?t.messages:[],t.modelId&&typeof j?.setModelId==`function`&&j.setModelId(t.modelId),await O(),H=`normal`,U=null,$(),process.stdout.write(`
|
|
22
|
+
`),process.stdout.write(`${c.green(`${L(`🗂️`)}using session:`)} ${i.session.sessionId}\n`),i.session.history.length>0){let e=i.session.title??n(i.session.history),t=i.session.summary??o(i.session.history);process.stdout.write(`${c.bold(`Title:`)} ${e}\n`),t&&process.stdout.write(`${c.bold(`Summary:`)} ${t}\n`),s(i.session.history,{maxMessages:12,maxCharsPerMessage:400,emoji:F?.emoji})}return!0},se=Oe(v);if(se.kind===`prefix`)x=se.cmd;else if(se.kind===`ambiguous`){process.stdout.write(`${L(`❓`)}ambiguous command: ${r} (did you mean ${se.matches.map(e=>`/${e}`).join(`, `)}?)\n`);return}if(x===`help`){await ct();return}if(x===`multiline`||x===`ml`){if(G){process.stdout.write(`${L(`⏳`)}busy (Ctrl+C to cancel)\n`);return}if(H===`select_session`){process.stdout.write(`${L(`ℹ️`)}Exit session picker first.\n`);return}q={lines:[]},$(),J(`Multiline mode: type .send to send, .cancel to cancel.`);return}if(x===`edit`){if(G){process.stdout.write(`${L(`⏳`)}busy (Ctrl+C to cancel)\n`);return}if(H===`select_session`){process.stdout.write(`${L(`ℹ️`)}Exit session picker first.\n`);return}await Ye();return}if(x===`exit`||x===`quit`){Ge();return}if(x===`tools`){let e=typeof A?.tools?.list==`function`?A.tools.list():[];process.stdout.write(`${L(`🧰`)}${e.map(e=>e.name).join(`, `)}\n`);return}if(x===`status`){Ce({version:u,provider:d,modelId:j.modelId,sessionId:i.session.sessionId,history:i.session.history,agent:A,baseUrl:ee.get(),requestDefaults:y,workspaceCwd:X(),emoji:F?.emoji});return}if(x===`model`){if(!D){process.stdout.write(`${L(`🤖`)}model: ${d}/${j.modelId}\n`);return}typeof j?.setModelId==`function`&&j.setModelId(D),await O(),process.stdout.write(`${L(`🤖`)}model set: ${d}/${j.modelId}\n`);return}if(x===`params`){let e=y??{},t=[typeof e.maxOutputTokens==`number`?`maxTokens=${e.maxOutputTokens}`:void 0,typeof e.temperature==`number`?`temperature=${e.temperature}`:void 0,typeof e.topP==`number`?`topP=${e.topP}`:void 0,typeof e.presencePenalty==`number`?`presencePenalty=${e.presencePenalty}`:void 0,typeof e.frequencyPenalty==`number`?`frequencyPenalty=${e.frequencyPenalty}`:void 0,typeof e.seed==`number`?`seed=${e.seed}`:void 0,typeof e.timeoutMs==`number`?`timeoutMs=${e.timeoutMs}`:void 0].filter(Boolean);process.stdout.write(`${L(`⚙️`)}${t.join(` `)}\n`);return}if(x===`set`){let[e,...t]=D.split(/\s+/),n=Se(e,t.join(` `));if(!n.ok){process.stdout.write(`${L(`❌`)}${n.error} (try /help)\n`);return}let r=xe(e);y[r]=n.value,await O(),process.stdout.write(`${L(`⚙️`)}set ${r}=${n.value}\n`);return}if(x===`unset`){let e=xe(D);if(!e){process.stdout.write(`${L(`❌`)}Missing key (try /help)\n`);return}if(!(e in y)){process.stdout.write(`${L(`❌`)}unknown key: ${D}\n`);return}delete y[e],await O(),process.stdout.write(`${L(`⚙️`)}unset ${e}\n`);return}if(x===`api-key`||x===`key`){if(!D){process.stdout.write(`${L(`❌`)}Missing key (try /help)\n`);return}S(D),typeof j?.resetClient==`function`&&j.resetClient(),await O(),process.stdout.write(`${L(`🔑`)}api key set\n`);return}if(x===`base-url`){if(!D){process.stdout.write(`${L(`❌`)}Missing url (try /help)\n`);return}await b(D),process.stdout.write(`${L(`🌐`)}baseUrl set: ${ee.get()??``}\n`);return}if(x===`save`){await O(),process.stdout.write(`${L(`💾`)}saved\n`);return}if(x===`workspace`){await rt();return}if(x===`files`){await nt();return}if(x===`images`){await st();return}if(x===`settings`){await Ze();return}if(x===`output`){await Qe();return}if(x===`diag`||x===`diagnostics`){await $e();return}if(x===`clipboard`){let t=await de(),n=await oe(),r=await ae(),i=await le(),a=String(r??``).split(/\r?\n/).find(Boolean)??``;if(n&&process.stdout.write(`${L(`📋`)}clipboard types: ${n}\n`),a&&process.stdout.write(`${L(`📋`)}clipboard text: ${e(a,120)}\n`),Array.isArray(i)&&i.length>0&&process.stdout.write(`${L(`🗂️`)}finder selection: ${i.slice(0,3).map(e=>_.basename(String(e))).join(`, `)}\n`),!Array.isArray(t)||t.length===0){process.stdout.write(`${L(`📋`)}clipboard: no attachable image found\n`),process.stdout.write(`${L(`💡`)}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 @image.\n`);return}process.stdout.write(`${L(`🖼️`)}clipboard images: ${t.length} candidate(s)\n`);for(let e of t.slice(0,6)){let t=e?.source?String(e.source):`unknown`,n=e?.absPath?_.basename(String(e.absPath)):``,r=e?.mime?String(e.mime):``,i=Buffer.isBuffer(e?.buf)?e.buf.byteLength:0;process.stdout.write(`- ${t}${n?` ${n}`:``}${r?` ${r}`:``}${i?` (${Ue(i)})`:``}\n`)}t.length>6&&process.stdout.write(`… (+${t.length-6})\n`);return}if(x===`compact`){if(G){process.stdout.write(`${L(`⏳`)}busy (Ctrl+C to cancel)\n`);return}if(H===`select_session`){process.stdout.write(`${L(`ℹ️`)}Exit session picker first.\n`);return}if(!A){process.stdout.write(`${L(`❌`)}Agent not available\n`);return}if(!j){process.stdout.write(`${L(`❌`)}Model not available\n`);return}let e=A.stateStore;if(!e){process.stdout.write(`${L(`❌`)}State store not available (agent has no stateStore)\n`);return}let t=Array.isArray(i.session.history)?i.session.history:[];if(t.length===0){process.stdout.write(`${L(`ℹ️`)}No messages in current session to compress\n`);return}let n=i.session.sessionId;if(!n){process.stdout.write(`${L(`❌`)}No active session\n`);return}try{process.stdout.write(`${L(`🗜️`)}Starting manual compression for session ${n}...\n`);let{compressSessionManually:r}=await import(`goatchain`);if(typeof r!=`function`){process.stdout.write(`${L(`❌`)}compressSessionManually not available in SDK\n`);return}let i=await r({sessionId:n,fullMessages:t,model:j,stateStore:e});if(i.summary.length===0){process.stdout.write(`${L(`ℹ️`)}No summary generated (no content to summarize)\n`);return}process.stdout.write(`${L(`✅`)}Compression completed:\n`),process.stdout.write(` 📊 Messages processed: ${i.messageCount}\n`),i.toolOutputCount>0?process.stdout.write(` 🔧 Tool outputs: ${i.toolOutputCount}\n`):process.stdout.write(` 💬 Conversation messages summarized
|
|
23
|
+
`),process.stdout.write(` 📝 Summary length: ${i.summary.length} chars\n`),process.stdout.write(` 💾 Summary saved to CompressionState
|
|
24
|
+
`),process.stdout.write(`\n${L(`💡`)}The summary will be automatically loaded in the next turn.\n`)}catch(e){let t=e instanceof Error?e.message:String(e);process.stdout.write(`${L(`❌`)}Compression failed: ${t}\n`)}return}if(x===`new`){await N(),We(),H=`normal`,U=null,$();return}if(x===`sessions`){let t=await k();if(t.length===0){process.stdout.write(`${L(`ℹ️`)}[no sessions]\n`);return}let n=(F?.sessionsUi??process.env.GOATCHAIN_SESSIONS_UI??`auto`).toLowerCase();if(process.stdout.isTTY&&n!==`legacy`&&Y()){await Z(async()=>{let n=await C({message:`Sessions`,options:[{value:`open`,label:R(`🗂️`,`Open a session`)},{value:`rename`,label:R(`✏️`,`Rename a session…`)},{value:`pin`,label:R(`📌`,`Pin session(s)…`)},{value:`unpin`,label:R(`📍`,`Unpin session(s)…`)},{value:`export`,label:R(`📤`,`Export session(s)…`)},{value:`import`,label:R(`📥`,`Import session(s) from JSON…`)},{value:`delete`,label:R(`🗑️`,`Delete session(s)…`)}],initialValue:0});if(!n.ok)return;let r=process.stdout.isTTY&&typeof process.stdout.columns==`number`&&process.stdout.columns>0?process.stdout.columns:120,o=Math.max(18,Math.min(52,Math.floor(r*.4))),s=Math.max(0,r-(8+o+22)),u=t.slice(0,120).map(t=>{let n=Array.isArray(t.messages)?t.messages.length:0,r=t.pinned?`★ `:``,i=`${r}${e(t.title??`New session`,Math.max(6,o-r.length))}`,c=a(t.updatedAt),l=typeof t.sessionId==`string`?t.sessionId.slice(-8):``,u=e(`${n} msgs · ${c}${l?` · ${l}`:``}`,26),d=s>=18?e(t.summary??``,s):``,f=`${i} (${u})${d?` — ${d}`:``}`;return{value:t.sessionId,label:f}});if(n.value===`open`){let e=t.findIndex(e=>e.sessionId===i.session.sessionId),n=await C({message:`Select a session`,options:u,initialValue:e>=0?e:0});n.ok&&await I(String(n.value));return}if(n.value===`rename`){if(!ne){process.stdout.write(`${L(`❌`)}Rename is not configured (missing renameSessionById)\n`);return}let e=t.findIndex(e=>e.sessionId===i.session.sessionId),n=await C({message:`Select a session to rename`,options:u,initialValue:e>=0?e:0});if(!n.ok)return;let r=String(n.value),a=await E({message:`New title`,placeholder:t.find(e=>e.sessionId===r)?.title??`New session`});if(!a.ok)return;let o=String(a.value??``).trim();await ne(r,o),r===i.session.sessionId&&(i.session.title=o,await O()),process.stdout.write(`${c.green(`${L(`✏️`)}renamed:`)} ${r}\n`);return}if(n.value===`pin`||n.value===`unpin`){if(!re){process.stdout.write(`${L(`❌`)}Pin is not configured (missing setPinnedSessionsById)\n`);return}let e=await w({message:n.value===`pin`?`Select sessions to pin`:`Select sessions to unpin`,options:u,required:!0});if(!e.ok)return;let t=Array.isArray(e.value)?e.value.map(String):[];if(t.length===0)return;let r=n.value===`pin`;await re(t,r),t.includes(i.session.sessionId)&&(i.session.pinned=r,await O()),process.stdout.write(`${c.green(`${L(r?`📌`:`📍`)}${r?`pinned:`:`unpinned:`}`)} ${t.length} session(s)\n`);return}if(n.value===`export`){let e=await w({message:`Select sessions to export`,options:u,required:!0});if(!e.ok)return;let n=Array.isArray(e.value)?e.value.map(String):[];if(n.length===0)return;let r=await C({message:`Export format`,options:[{value:`json`,label:`JSON (bundle)`},{value:`md`,label:`Markdown`}],initialValue:0});if(!r.ok)return;let i=String(r.value),a=`sessions-export-${new Date().toISOString().replace(/[:.]/g,`-`)}.${i===`md`?`md`:`json`}`,o=await E({message:`Output file (workspace-relative)`,placeholder:a});if(!o.ok)return;let s=String(o.value??``).trim()||a,l=_.resolve(X(),s),d=_.relative(X(),l);if(d.startsWith(`..`)||_.isAbsolute(d)){process.stdout.write(`${L(`❌`)}Export path must be inside the workspace\n`);return}let f=await T({message:`Write ${s}?`,initialValue:!0});if(!f.ok||!f.value)return;let p=me(t,n);if(i===`md`)await g(l,ge(p),`utf8`);else{let e=he(p);await g(l,`${JSON.stringify(e,null,2)}\n`,`utf8`)}process.stdout.write(`${c.green(`${L(`📤`)}exported:`)} ${n.length} session(s) -> ${s}\n`);return}if(n.value===`import`){if(!te){process.stdout.write(`${L(`❌`)}Import is not configured (missing saveSessionByData)\n`);return}let e=await E({message:`JSON file to import (workspace-relative)`,placeholder:`sessions-export.json`});if(!e.ok)return;let t=String(e.value??``).trim();if(!t)return;let n=_.resolve(X(),t),r=_.relative(X(),n);if(r.startsWith(`..`)||_.isAbsolute(r)){process.stdout.write(`${L(`❌`)}Import path must be inside the workspace\n`);return}let i;try{i=JSON.parse(await f(n,`utf8`))}catch(e){process.stdout.write(`${L(`❌`)}Failed to read JSON: ${e instanceof Error?e.message:String(e)}\n`);return}let a=_e(i);if(a.length===0){process.stdout.write(`${L(`ℹ️`)}No sessions found in JSON\n`);return}let o=await C({message:`On sessionId conflict`,options:[{value:`new_ids`,label:`Create new IDs`},{value:`overwrite`,label:`Overwrite`},{value:`skip`,label:`Skip conflicts`}],initialValue:0});if(!o.ok)return;let s=`new_ids`,u=String(o.value??``);(u===`new_ids`||u===`overwrite`||u===`skip`)&&(s=u);let d=await ve(a,{conflict:s,exists:async e=>!!await M(e),makeId:()=>l()});for(let e of d)await te(e.session);process.stdout.write(`${c.green(`${L(`📥`)}imported:`)} ${d.length} session(s)\n`);return}if(n.value===`delete`){if(!ie&&!P){process.stdout.write(`${L(`❌`)}Delete is not configured (missing deleteSessionsById)\n`);return}let e=await w({message:`Select sessions to delete`,options:u,required:!0});if(!e.ok)return;let t=Array.isArray(e.value)?e.value.map(String):[];if(t.length===0)return;let n=await T({message:`Delete ${t.length} session(s)? This cannot be undone.`,initialValue:!1});if(!n.ok||!n.value)return;if(ie)await ie(t);else for(let e of t)await P(e);if(process.stdout.write(`${c.yellow(`${L(`🗑️`)}deleted:`)} ${t.length} session(s)\n`),t.includes(i.session.sessionId)){let e=await k();e.length>0?await I(e[0].sessionId):await N()}return}});return}H=`select_session`,U={sessions:t,filter:``},fe||=we(),$(),je({sessions:t,currentSessionId:i.session.sessionId,filter:``,alt:fe,emoji:F?.emoji});return}if(x===`rm`||x===`delete`){let t=D.split(/\s+/).filter(Boolean);if(t.length===0){process.stdout.write(`${L(`ℹ️`)}Usage: /rm <sessionId...>\n`);return}if(!ie&&!P){process.stdout.write(`${L(`❌`)}Delete is not configured\n`);return}if(Y()&&process.stdout.isTTY){let r=[...new Set(t)],i=await Promise.all(r.map(async e=>{try{let t=await M(e);if(!t)return{id:e,missing:!0};let r=Array.isArray(t.messages)?t.messages:[];return{id:e,title:t.title??n(r),summary:t.summary??o(r),missing:!1}}catch{return{id:e,missing:!0}}}));process.stdout.write(`${c.bold(`About to delete:`)}\n`);for(let t of i.slice(0,12)){if(t.missing){process.stdout.write(`- ${t.id} (not found)\n`);continue}let n=t.title?e(String(t.title),80):``;process.stdout.write(`- ${t.id}${n?` — ${n}`:``}\n`)}i.length>12&&process.stdout.write(`… (+${i.length-12})\n`);let a=await Z(()=>T({message:`Delete ${r.length} session(s)? This cannot be undone.`,initialValue:!1}));if(!a.ok||!a.value)return}else{let e=`Delete ${t.length} session(s)? [y/N] `,n=await new Promise(t=>z.question(e,t)),r=String(n??``).trim().toLowerCase();if(!(r===`y`||r===`yes`))return}if(ie)await ie(t);else for(let e of t)await P(e);if(process.stdout.write(`${c.yellow(`${L(`🗑️`)}deleted:`)} ${t.length} session(s)\n`),t.includes(i.session.sessionId)){let e=await k();e.length>0?await I(e[0].sessionId):await N()}return}if(x===`use`){await I(D);return}let ce=Oe(v);if(ce.kind===`fuzzy`||ce.kind===`contains`){process.stdout.write(`${L(`❓`)}unknown command: ${r} (did you mean ${ce.matches.map(e=>`/${e}`).join(`, `)}?)\n`);return}process.stdout.write(`${L(`❓`)}unknown command: ${r} (try /help)\n`)};if(process.stdout.write(`${L(`💡`)}Type /help for commands. Ctrl+K for palette. Ctrl+C to cancel/exit.\n`),i.session.history.length>0){let e=i.session.title??n(i.session.history),t=i.session.summary??o(i.session.history);process.stdout.write(`${L(`🗂️`)}Restored session: ${i.session.sessionId}\n`),process.stdout.write(`Title: ${e}\n`),t&&process.stdout.write(`Summary: ${t}\n`),s(i.session.history,{maxMessages:8,maxCharsPerMessage:240,emoji:F?.emoji}),process.stdout.write(`
|
|
25
|
+
`)}z.prompt();let qe=(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}):`)},Je=async e=>{G=!0,W=new AbortController;let t=String(e??``).trim(),n=t,r=!1,a=(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()},o=()=>{let e=t.match(/(^|\s)([^\s/\\]+?)(?:\s*\.\s*)(png|jpg|jpeg|webp|gif|bmp|tiff?|heic)(?=\s|[,,。.!??::;;、()[\]{}"'“”‘’]|$)/i);if(!e)return null;let n=String(e[2]??``).trim(),r=String(e[3]??``).trim().toLowerCase();return!n||!r||t.includes(`@image`)||t.includes(`@img`)?null:`${n}.${r}`};if(K.length===0){let e=o();if(e){let t=await de(),r=e.toLowerCase(),i=Array.isArray(t)&&t.length>0?t.find(e=>e?.absPath&&_.basename(String(e.absPath)).toLowerCase()===r)??t[0]:null;if(!i)process.stdout.isTTY&&process.stdout.write(c.dim(`(no image found in clipboard; send text only — use cmd+v in iTerm2 or @image to attach)
|
|
26
|
+
`));else if(typeof i.dataUrl==`string`&&i.dataUrl.startsWith(`data:image/`)){let t=!0;if(process.stdout.isTTY)if(Y())await Z(async()=>{let n=await T({message:`Attach image from clipboard as “${e}”?`,initialValue:!0});t=!!(n.ok&&n.value)});else{let n=await new Promise(t=>z.question(`Attach image from clipboard as "${e}"? [Y/n] `,t)),r=String(n??``).trim().toLowerCase();t=r===``||r===`y`||r===`yes`}t&&(K.push({name:e,mime:i.mime,bytes:Buffer.isBuffer(i.buf)?i.buf.byteLength:0,dataUrl:i.dataUrl,source:`paste`}),n=a(n,e),$(),Q())}}}if(n.includes(`@file`))try{let e=await N(X(),n,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30}),t=(Array.isArray(e.omitted)?e.omitted:[]).some(e=>e&&e.reason===`budget`),r=(Array.isArray(e.files)?e.files:[]).some(e=>e&&e.mode===`full`&&e.truncated);if((t||r)&&process.stdout.isTTY){let t=`proceed`;if(Y())await Z(async()=>{let e=await C({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=>z.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;return}if(t===`summary`){let t=qe(n,`summary`);e=await N(X(),t,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30})}else if(t===`path`){let t=qe(n,`path`);e=await N(X(),t,{maxTotalBytes:22e4,maxBytesPerFile:12e4,maxBytesPerFileSummary:4e4,headLines:80,tailLines:30})}}n=e.text;let i=Array.isArray(e.files)?e.files.length:0;i>0&&process.stdout.write(c.dim(`(${L(`📎`)}attached ${i} file(s))\n`))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),G=!1,W=null;return}let s=n.includes(`@image`)||n.includes(`@img`),l=K.length>0,u=(e,t)=>{let n=String(e??``).match(/^data:([^;]+);base64,(.+)$/);if(!n)return null;let r=String(n[1]??t??`application/octet-stream`),i=String(n[2]??``);return!r||!i?null:{type:`image`,mimeType:r,data:i}},d=n,f=n,m=l?[...K]:[];if(s||l)try{let e=n,t=[],r=[];if(s){let i=await at(n);e=i.cleanedText,r=Array.isArray(i.images)?i.images:[],t=Array.isArray(i.blocks)?i.blocks:e?[{type:`text`,text:e}]:[]}else t=e?[{type:`text`,text:e}]:[];for(let e of m){if(!e?.dataUrl)continue;let n=u(e.dataUrl,e.mime);n&&t.push(n)}let i=[...r.map(e=>String(e?.relPath??e?.name??``).trim()).filter(Boolean),...m.map(e=>String(e?.name??``).trim()).filter(Boolean)];f=i.length>0?[e,`[attached images]`,...i.map(e=>`- ${e}`)].filter(Boolean).join(`
|
|
27
|
+
`):e,d=t.length>0?t:e;let a=i.length;a>0&&process.stdout.write(c.dim(`(${L(`🖼️`)}attached ${a} image(s))\n`))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),G=!1,W=null;return}i.session.history.push({role:`user`,content:f}),r=!0;let h=K;m.length>0&&(K=[],$());try{let{messagesToAppend:e,meta:t}=await x({agent:p.get(),sessionId:i.session.sessionId,history:i.session.history.slice(0,-1),input:d,signal:W.signal,approvalStrategy:`high_risk`,autoApprove:process.env.GOATCHAIN_AUTO_APPROVE===`1`,askApproval:e=>new Promise(t=>z.question(e,t)),askApprovalForTool:Y()&&process.stdout.isTTY?async({toolName:e,riskLevel:t,display:n})=>{let r=t?` (${t})`:``,i=n?.lines&&Array.isArray(n.lines)?n.lines:[];process.stdout.write(`\n${c.bold(`Approval required:`)} ${String(e??`tool`)}${r}\n`);for(let e of i.slice(0,10))process.stdout.write(`${c.dim(`- ${e}`)}\n`);i.length>10&&process.stdout.write(`${c.dim(`… (+${i.length-10})`)}\n`);let a=await Z(()=>C({message:`Allow this tool?`,options:[{value:`approve`,label:R(`✅`,`Approve (once)`)},{value:`approve_all`,label:R(`🧷`,`Approve all tools (this turn)`)},{value:`deny`,label:R(`❌`,`Deny`)},{value:`abort`,label:R(`🛑`,`Abort turn`)}],initialValue:2}));return a.ok?String(a.value):`deny`}:void 0,showTools:typeof F?.showTools==`boolean`?F.showTools:void 0,toolStyle:typeof F?.toolStyle==`string`?F.toolStyle:void 0,showStatus:typeof F?.showStatus==`boolean`?F.showStatus:void 0,showStatusLine:typeof F?.showStatusLine==`boolean`?F.showStatusLine:void 0,emoji:typeof F?.emoji==`boolean`?F.emoji:void 0,promptContinue:typeof F?.promptContinue==`boolean`?F.promptContinue:void 0,autoContinue:typeof F?.autoContinue==`boolean`?F.autoContinue:void 0});Me=t??Me,i.session.history.push(...e),await O()}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),r&&i.session.history.pop(),m.length>0&&(K=h,$())}finally{G=!1,W=null}},Ye=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(_.join(t(),`goatchain-edit-`)),l=_.join(c,`message.md`);await o(l,``,`utf8`);let u=!!B.paused;u||z.pause();try{let t=n(`${e} ${s(l)}`,{stdio:`inherit`,shell:!0});if(typeof t.status==`number`&&t.status!==0){process.stdout.write(`${L(`❌`)}Editor exited with status ${t.status}\n`);return}let r=String(await i(l,`utf8`)??``).replace(/\r\n/g,`
|
|
28
|
+
`).trim();if(!r){J(`Canceled (empty message).`);return}await Je(r)}finally{u||z.resume(),await a(c,{recursive:!0,force:!0})}},Xe=async()=>{let e=m.get(),t=e?.modelId?String(e.modelId):``,n=String(process.env.GOATCHAIN_MODEL_PRESETS??``).split(`,`).map(e=>e.trim()).filter(Boolean),r=[`deepseek-v3.1`,`gpt-4o`,`gpt-4o-mini`],i=[t,...n,...r].filter(Boolean),a=[...new Set(i)].slice(0,20);if(!Y()){if(!process.stdout.isTTY){process.stdout.write([`model: ${d}/${e?.modelId??``}`,`Set with: /model <id>`,``].join(`
|
|
29
|
+
`));return}let n=await new Promise(e=>z.question(`Model id (current: ${t||`∅`}): `,e)),r=String(n??``).trim();if(!r)return;typeof e?.setModelId==`function`&&e.setModelId(r),await O(),process.stdout.write(`${L(`🤖`)}model set: ${d}/${e.modelId}\n`);return}await Z(async()=>{let t=await C({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 E({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 O(),process.stdout.write(`${L(`🤖`)}model set: ${d}/${e.modelId}\n`))})},Ze=async()=>{let e=m.get();if(!Y()){if(!process.stdout.isTTY){process.stdout.write([`Settings:`,`- /base-url <url>`,`- /api-key <key>`,`- /set maxTokens <n>`,`- Set env GOATCHAIN_AUTO_APPROVE=1 to skip approval prompts.`,``].join(`
|
|
30
|
+
`));return}let e=await new Promise(e=>z.question(`Settings: [1] base-url [2] api-key [3] maxTokens [4] autoApprove info (empty cancel): `,e)),t=String(e??``).trim();if(!t)return;if(t===`1`||t.toLowerCase()===`base-url`){let e=await new Promise(e=>z.question(`Base URL: `,e)),t=String(e??``).trim();if(!t)return;await b(t),process.stdout.write(`${L(`🌐`)}baseUrl set: ${ee.get()??``}\n`);return}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.
|
|
31
|
+
`);return}if(t===`3`||t.toLowerCase()===`maxtokens`){let e=await new Promise(e=>z.question(`Max tokens (current: ${String(y.maxOutputTokens??``)||`∅`}): `,e)),t=Number.parseInt(String(e??``).trim(),10);if(!Number.isFinite(t)||t<=0){process.stdout.write(`Invalid maxTokens
|
|
32
|
+
`);return}y.maxOutputTokens=t,await O(),process.stdout.write(`${L(`⚙️`)}set maxTokens=${t}\n`);return}if(t===`4`||t.toLowerCase()===`autoapprove`){process.stdout.write(`Set env GOATCHAIN_AUTO_APPROVE=1 to skip approval prompts.
|
|
33
|
+
`);return}return}await Z(async()=>{let t=await C({message:`Settings`,options:[{value:`baseUrl`,label:R(`🌐`,`Base URL`)},{value:`apiKey`,label:R(`🔑`,`API key`)},{value:`maxTokens`,label:R(`⚙️`,`Max tokens`)},{value:`autoApprove`,label:R(`🧷`,`Auto approve tools (env)`)}],initialValue:0});if(t.ok){if(t.value===`baseUrl`){let e=await E({message:`Base URL`,placeholder:ee.get()??`https://…/v1`});if(!e.ok)return;let t=String(e.value).trim();if(!t)return;await b(t),process.stdout.write(`${L(`🌐`)}baseUrl set: ${ee.get()??``}\n`);return}if(t.value===`apiKey`){let t=await D({message:`API key`,placeholder:`sk-…`});if(!t.ok)return;let n=String(t.value).trim();if(!n)return;S(n),typeof e?.resetClient==`function`&&e.resetClient(),await O(),process.stdout.write(`${L(`🔑`)}api key set\n`);return}if(t.value===`maxTokens`){let e=await E({message:`Max tokens`,placeholder:String(y.maxOutputTokens??``)});if(!e.ok)return;let t=Number.parseInt(String(e.value).trim(),10);if(!Number.isFinite(t)||t<=0){process.stdout.write(`Invalid maxTokens
|
|
34
|
+
`);return}y.maxOutputTokens=t,await O(),process.stdout.write(`${L(`⚙️`)}set maxTokens=${t}\n`);return}t.value===`autoApprove`&&process.stdout.write(`Set env GOATCHAIN_AUTO_APPROVE=1 to skip approval prompts.
|
|
35
|
+
`)}})},Qe=async()=>{if(!Y()){if(!process.stdout.isTTY){process.stdout.write([`Output / UX:`,`- Enable clack UI (default) or set GOATCHAIN_UI=legacy to disable.`,`- Current settings are persisted in .goatchain config.`,``].join(`
|
|
36
|
+
`));return}process.stdout.write([`Output / UX:`,`1) showTools: ${F?.showTools?`on`:`off`}`,`2) toolStyle: ${F?.toolStyle??`inline`}`,`3) statusLine: ${F?.showStatusLine?`on`:`off`}`,`4) doneLine: ${F?.showStatus?`on`:`off`}`,`5) emoji: ${F?.emoji?`on`:`off`}`,`6) promptContinue: ${F?.promptContinue?`on`:`off`}`,`7) autoContinue: ${F?.autoContinue?`on`:`off`}`,``].join(`
|
|
37
|
+
`));let e=await new Promise(e=>z.question(`Toggle which? (1-7, empty cancel): `,e)),t=String(e??``).trim();if(!t)return;if(t===`1`)F.showTools=!F.showTools;else if(t===`2`){let e=await new Promise(e=>z.question(`Tool style [inline/box]: `,e)),t=String(e??``).trim().toLowerCase();if(t!==`inline`&&t!==`box`)return;F.toolStyle=t}else if(t===`3`)F.showStatusLine=!F.showStatusLine;else if(t===`4`)F.showStatus=!F.showStatus;else if(t===`5`)F.emoji=!F.emoji;else if(t===`6`)F.promptContinue=!F.promptContinue;else if(t===`7`)F.autoContinue=!F.autoContinue;else return;await O(),process.stdout.write(`${L(`💾`)}saved\n`);return}await Z(async()=>{let e=await C({message:`Output / UX`,options:[{value:`showTools`,label:R(`🛠️`,`Show tools: ${F?.showTools?`on`:`off`}`)},{value:`toolStyle`,label:R(`🎛️`,`Tool style: ${F?.toolStyle??`inline`}`)},{value:`statusLine`,label:R(`…`,`Status line: ${F?.showStatusLine?`on`:`off`}`)},{value:`doneLine`,label:R(`✅`,`Done line: ${F?.showStatus?`on`:`off`}`)},{value:`emoji`,label:R(`🙂`,`Emoji: ${F?.emoji?`on`:`off`}`)},{value:`promptContinue`,label:R(`💬`,`Prompt continue: ${F?.promptContinue?`on`:`off`}`)},{value:`autoContinue`,label:R(`⏭️`,`Auto continue: ${F?.autoContinue?`on`:`off`}`)}],initialValue:0});if(e.ok){if(e.value===`showTools`)F.showTools=!F.showTools;else if(e.value===`statusLine`)F.showStatusLine=!F.showStatusLine;else if(e.value===`doneLine`)F.showStatus=!F.showStatus;else if(e.value===`emoji`)F.emoji=!F.emoji;else if(e.value===`promptContinue`)F.promptContinue=!F.promptContinue;else if(e.value===`autoContinue`)F.autoContinue=!F.autoContinue;else if(e.value===`toolStyle`){let e=await C({message:`Tool style`,options:[{value:`inline`,label:`inline (compact)`},{value:`box`,label:`box (verbose)`}],initialValue:F.toolStyle===`box`?1:0});if(!e.ok)return;F.toolStyle=String(e.value)}await O(),process.stdout.write(`${L(`💾`)}saved\n`)}})},$e=async()=>{process.stdout.write(`${c.bold(`Last turn:`)}\n`);let e=Me?.stopReason?String(Me.stopReason):``,t=Me?.modelStopReason?String(Me.modelStopReason):``;process.stdout.write(`stopReason: ${e||`∅`}\n`),process.stdout.write(`modelStopReason: ${t||`∅`}\n`);let n=Array.isArray(Me?.tools)?Me.tools:[];if(n.length>0){process.stdout.write(`${c.bold(`tools:`)}\n`);for(let e of n.slice(-12)){let t=e?.toolName?String(e.toolName):`tool`,n=e?.argsSummary?String(e.argsSummary):``,r=e?.resultSummary?String(e.resultSummary):``;process.stdout.write(`- ${t}${n?` ${n}`:``}${r?` -> ${r}`:``}\n`)}}process.stdout.write(`
|
|
38
|
+
`)};async function et(){let e=Date.now();if(Ne&&e-Ne.at<3e4)return Ne.files;let t=await j(X(),{maxFiles:8e3});return Ne={at:e,files:t},t}async function tt(){let e=Date.now();if(Pe&&e-Pe.at<3e4)return Pe.files;let t=(await j(X(),{maxFiles:8e3})).filter(e=>{let t=String(e).toLowerCase();return t.endsWith(`.png`)||t.endsWith(`.jpg`)||t.endsWith(`.jpeg`)||t.endsWith(`.webp`)||t.endsWith(`.gif`)});return Pe={at:e,files:t},t}async function nt(){if(!Y()){if(process.stdout.isTTY){let e=await new Promise(e=>z.question(`Attach mode [path/summary/full] (default summary): `,e)),t=String(e??``).trim().toLowerCase(),n=t===`path`||t===`full`?t:`summary`,r=await new Promise(e=>z.question(`File paths (space-separated, workspace-relative): `,e)),i=String(r??``).trim();if(!i)return;let a=i.split(/\s+/).filter(Boolean),o=[];for(let e of a)try{let t=A(X(),e);o.push(_.relative(X(),t))}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`);return}let s=o.map(e=>`@file(${n}):${e}`).join(` `),c=await new Promise(e=>z.question(`Apply [i]nsert / [s]end now? (default insert): `,e)),l=String(c??``).trim().toLowerCase();if(l===`s`||l===`send`){let e=await new Promise(e=>z.question(`Message (optional): `,e)),t=`${String(e??``).trim()} ${s}`.trim();if(!t)return;await Je(t);return}let u=String(B.line??``).trim();B.line=u?`${u} ${s}`:`${s} `,B.cursor=String(B.line??``).length,B._refreshLine?.(),J(`Inserted @file markers (send the prompt to attach files).`);return}process.stdout.write([`Attach files:`,`- Use @file(summary):path/to/file (default summary)`,`- Or run @file to pick files (TTY + clack)`,``].join(`
|
|
39
|
+
`));return}let e=await Z(async()=>{let e=await et();if(e.length===0)return process.stdout.write(`[no files found]
|
|
40
|
+
`),null;let t=await E({message:`Search files (substring)`,placeholder:`e.g. src/agent or cli/repl`});if(!t.ok)return null;let n=String(t.value??``).trim().toLowerCase(),r=n?e.filter(e=>String(e).toLowerCase().includes(n)):e;if(r.length===0)return process.stdout.write(`[no matches]
|
|
41
|
+
`),null;let i=r.slice(0,240),a=await w({message:`Select files (${i.length}${r.length>240?`/${r.length}`:``})`,options:i.map(e=>({value:e,label:e})),required:!0});if(!a.ok)return null;let o=Array.isArray(a.value)?a.value.map(String).filter(Boolean):[];if(o.length===0)return null;let s=await C({message:`Attach mode`,options:[{value:`path`,label:`Paths only`},{value:`summary`,label:`Summary (head/tail excerpt)`},{value:`full`,label:`Full (size-limited)`}],initialValue:1});if(!s.ok)return null;let c=String(s.value),l=o.map(e=>`@file(${c}):${e}`).join(` `),u=await C({message:`Apply`,options:[{value:`insert`,label:`Insert into prompt`},{value:`send`,label:`Send now`}],initialValue:0});if(!u.ok)return null;if(u.value===`send`){let e=await E({message:`Message`,placeholder:`Optional message to send with attachments`});if(!e.ok)return null;let t=`${String(e.value??``).trim()} ${l}`.trim();return t?{kind:`send`,line:t}:null}return{kind:`insert`,markers:l}});if(!e)return;if(e.kind===`send`){await Je(e.line);return}let t=String(B.line??``).trim();B.line=t?`${t} ${e.markers}`:`${e.markers} `,B.cursor=String(B.line??``).length,B._refreshLine?.(),J(`Inserted @file markers (send the prompt to attach files).`)}async function rt(){if(typeof I!=`function`){process.stdout.write(`Workspace switching is not configured (missing switchWorkspace)
|
|
42
|
+
`);return}if(!Y()){let e=await new Promise(e=>z.question(`Workspace path (current: ${X()}): `,e)),t=String(e??``).trim();if(!t)return;let n=_.resolve(X(),t);try{await I(n),Ne=null,Pe=null,process.stdout.write(`${c.green(`workspace:`)} ${X()}\n`)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`)}return}await Z(async()=>{let e=await E({message:`Workspace path`,placeholder:X()});if(!e.ok)return;let t=String(e.value??``).trim();if(!t)return;let n=_.resolve(X(),t),r=await T({message:`Switch to ${n}?`,initialValue:!0});if(!(!r.ok||!r.value))try{await I(n),Ne=null,Pe=null,process.stdout.write(`${c.green(`workspace:`)} ${X()}\n`)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`)}})}function it(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 at(e){let t=String(e??``),n=[],r=/@(image|img):([^\s]+)/g,i;for(;(i=r.exec(t))!=null;)n.push({raw:i[0],filePath:i[2]});if(n.length===0)return{cleanedText:t.trim(),images:[],blocks:null};let a=new Map;for(let e of n){let t=e.filePath;a.has(t)||a.set(t,e)}let o=[],s=[];for(let e of a.values()){let t=A(X(),e.filePath),n=await f(t);if(n.byteLength>4*1024*1024)throw Error(`Image too large (${Math.round(n.byteLength/1024)} KB): ${e.filePath}`);let r=n.toString(`base64`),i=it(e.filePath);o.push({relPath:_.relative(X(),t),absPath:t,mime:i,bytes:n.byteLength}),s.push({type:`image`,mimeType:i,data:r})}let c=t;for(let e of n)c=c.replace(e.raw,``).replace(/\s{2,}/g,` `);c=c.trim();let l=[];return c&&l.push({type:`text`,text:c}),l.push(...s),{cleanedText:c,images:o,blocks:l}}async function ot(){if(Re&&K.length===0){J(`Attaching image from clipboard… (try again in a moment)`);return}if(K.length===0){let e=ze&&Date.now()-ze.at<6e4?ze:null;if(!Y()||!process.stdout.isTTY){J(e?`No pending attachments. Last pasted: ${e.name} (use @image, or paste/drag a full path)`:`No pending attachments.`);return}await Z(async()=>{let t=await C({message:e?`Attachments (last pasted: ${e.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(!(!t.ok||t.value===`cancel`)){if(t.value===`images`){await st();return}if(t.value===`path`){let e=await E({message:`Image path`,placeholder:`/Users/you/Desktop/image.png (you can drag & drop here)`});if(!e.ok)return;let t=String(e.value??``).trim();if(!t)return;let n=t.startsWith(`/`)?t:A(X(),t),r=await ue(n);if(!r?.dataUrl){J(`Not a supported image path.`);return}K.push({name:_.basename(n),mime:String(r.mime),bytes:Buffer.isBuffer(r.buf)?r.buf.byteLength:0,dataUrl:String(r.dataUrl),source:t.startsWith(`/`)?`paste`:`path`}),$(),Q(),J(`Attached image: ${_.basename(n)}`)}}});return}if(!Y()){let e=await new Promise(e=>z.question(`Remove which attachments? (e.g. 1,3) or 'a' to clear all: `,e)),t=String(e??``).trim().toLowerCase();if(!t)return;if(t===`a`||t===`all`||t===`clear`){K=[],Fe=``,$(),Q(),J(`Cleared pending attachments.`);return}let n=t.split(/[, ]+/).map(e=>Number.parseInt(e,10)).filter(e=>Number.isFinite(e)),r=new Set(n.map(e=>e-1).filter(e=>e>=0&&e<K.length));if(r.size===0)return;K=K.filter((e,t)=>!r.has(t)),$(),Q();return}await Z(async()=>{let e=await w({message:`Select attachments to remove`,options:K.map((e,t)=>{let n=e.bytes?` (${Ue(e.bytes)})`:``;return{value:String(t),label:`${e.name}${n}`}}),required:!1});if(!e.ok)return;let t=Array.isArray(e.value)?e.value.map(String):[],n=new Set(t.map(e=>Number.parseInt(e,10)).filter(e=>Number.isFinite(e)));n.size!==0&&(K=K.filter((e,t)=>!n.has(t)),$(),Q())})}async function st(){if(!Y()){if(process.stdout.isTTY){let e=await new Promise(e=>z.question(`Image paths (space-separated; absolute or workspace-relative): `,e)),t=String(e??``).trim();if(!t)return;let n=t.split(/\s+/).filter(Boolean),r=[];for(let e of n)try{let t=e.startsWith(`/`)?e:A(X(),e),n=await ue(t);if(!n?.dataUrl){J(`Not a supported image path.`);return}r.push({name:_.basename(t),mime:String(n.mime),bytes:Buffer.isBuffer(n.buf)?n.buf.byteLength:0,dataUrl:String(n.dataUrl),source:e.startsWith(`/`)?`paste`:`path`})}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`);return}if(r.length===0)return;K.push(...r),$(),Q(),J(`Attached ${r.length} image(s).`);let i=await new Promise(e=>z.question(`Send now? [y/N] `,e)),a=String(i??``).trim().toLowerCase();if(a===`y`||a===`yes`){let e=await new Promise(e=>z.question(`Message (optional): `,e));await Je(String(e??``).trim())}return}process.stdout.write([`Attach images:`,`- Paste from iTerm2 to attach (cmd+v).`,`- Or run @image to pick images (TTY + clack).`,`- Ctrl+O manages pending attachments.`,``].join(`
|
|
43
|
+
`));return}let e=await Z(async()=>{let e=await tt();if(e.length===0)return process.stdout.write(`[no images found]
|
|
44
|
+
`),null;let t=await E({message:`Search images (substring)`,placeholder:`e.g. assets/logo.png`});if(!t.ok)return null;let n=String(t.value??``).trim().toLowerCase(),r=n?e.filter(e=>String(e).toLowerCase().includes(n)):e;if(r.length===0)return process.stdout.write(`[no matches]
|
|
45
|
+
`),null;let i=r.slice(0,160),a=await w({message:`Select images (${i.length}${r.length>160?`/${r.length}`:``})`,options:i.map(e=>({value:e,label:e})),required:!0});if(!a.ok)return null;let o=Array.isArray(a.value)?a.value.map(String).filter(Boolean):[];if(o.length===0)return null;let s=[];for(let e of o){let t=A(X(),e),n=await f(t);if(n.byteLength>4194304)return process.stdout.write(`Image too large: ${e} (${Ue(n.byteLength)})\n`),null;let r=n.toString(`base64`),i=it(e),a=`data:${i};base64,${r}`;s.push({name:_.relative(X(),t),mime:i,bytes:n.byteLength,dataUrl:a,source:`path`})}if(s.length===0)return null;let c=await C({message:`Apply`,options:[{value:`attach`,label:`Attach (keep editing)`},{value:`send`,label:`Attach and send now`}],initialValue:0});if(!c.ok)return null;if(c.value===`send`){let e=await E({message:`Message`,placeholder:`Optional message to send with images`});return e.ok?{action:{kind:`send`,line:String(e.value??``).trim()},toAdd:s}:null}return{action:{kind:`attach`},toAdd:s}});e&&(e.toAdd.length>0&&(K.push(...e.toAdd),$(),Q()),e.action.kind===`send`&&await Je(e.action.line))}async function ct(){if(!De){De=!0;try{if(!Y()){t(u).outputHelp(),process.stdout.write(r());return}await Z(async()=>{let e=await C({message:`Command palette`,options:[{value:`continue`,label:R(`▶️`,`Continue (implement now)`)},{value:`edit`,label:R(`📝`,`Compose message in editor…`)},{value:`multiline`,label:R(`✍️`,`Multiline input…`)},{value:`sessions`,label:R(`🗂️`,`Sessions…`)},{value:`workspace`,label:R(`📁`,`Switch workspace…`)},{value:`files`,label:R(`📎`,`Attach file(s)…`)},{value:`images`,label:R(`🖼️`,`Attach image(s)…`)},{value:`model`,label:R(`🤖`,`Switch model…`)},{value:`settings`,label:R(`⚙️`,`Settings…`)},{value:`output`,label:R(`🎛️`,`Output / UX…`)},{value:`diag`,label:R(`🧾`,`Diagnostics`)}],initialValue:0});if(e.ok){if(e.value===`continue`){await Je(`继续。不要只说计划:请立刻开始实现,使用 Write/Edit 创建或修改文件。`);return}if(e.value===`edit`){await Ye();return}if(e.value===`multiline`){q={lines:[]},$(),J(`Multiline mode: type .send to send, .cancel to cancel.`);return}if(e.value===`sessions`){await Ke(`/sessions`);return}if(e.value===`workspace`)return rt();if(e.value===`files`)return nt();if(e.value===`images`)return st();if(e.value===`model`)return Xe();if(e.value===`settings`)return Ze();if(e.value===`output`)return Qe();if(e.value===`diag`)return $e()}})}finally{De=!1}}}let lt=async e=>{let t=String(e??``).trim();if(!t.startsWith(`@`))return!1;let n=t.toLowerCase();return n===`@continue`?(await Je(`继续。不要只说计划:请立刻开始实现,使用 Write/Edit 创建或修改文件。`),!0):n===`@clear`?(K=[],Fe=``,Re=null,$(),Q(),J(`Cleared pending attachments.`),!0):n===`@workspace`?(await rt(),!0):n===`@file`?(await nt(),!0):n===`@image`||n===`@img`?(await st(),!0):Y()?(await Z(async()=>{if(n===`@sessions`){await Ke(`/sessions`);return}if(n===`@model`)return Xe();if(n===`@settings`)return Ze();let e=await C({message:`Quick actions`,options:[{value:`continue`,label:R(`▶️`,`Continue (implement now)`)},{value:`edit`,label:R(`📝`,`Compose message in editor…`)},{value:`multiline`,label:R(`✍️`,`Multiline input…`)},{value:`clear`,label:R(`🧹`,`Clear pending attachments`)},{value:`sessions`,label:R(`🗂️`,`Sessions…`)},{value:`workspace`,label:R(`📁`,`Switch workspace…`)},{value:`files`,label:R(`📎`,`Attach file(s)…`)},{value:`images`,label:R(`🖼️`,`Attach image(s)…`)},{value:`model`,label:R(`🤖`,`Switch model…`)},{value:`settings`,label:R(`⚙️`,`Settings…`)},{value:`output`,label:R(`🎛️`,`Output / UX…`)}],initialValue:0});if(e.ok){if(e.value===`continue`){await Je(`继续。不要只说计划:请立刻开始实现,使用 Write/Edit 创建或修改文件。`);return}if(e.value===`edit`){await Ye();return}if(e.value===`multiline`){q={lines:[]},$(),J(`Multiline mode: type .send to send, .cancel to cancel.`);return}if(e.value===`clear`){K=[],Fe=``,$(),Q(),J(`Cleared pending attachments.`);return}if(e.value===`sessions`)return Ke(`/sessions`);if(e.value===`workspace`)return rt();if(e.value===`files`)return nt();if(e.value===`images`)return st();if(e.value===`model`)return Xe();if(e.value===`settings`)return Ze();if(e.value===`output`)return Qe()}}),!0):(process.stdout.write([`Mentions:`,`- @continue (continue and implement now)`,`- @clear (clear pending attachments)`,`- @workspace (switch workspace root)`,`- @file (attach file(s) to the next prompt)`,`- @image/@img (attach image(s) to the next prompt)`,`- Use /help, /sessions, /model, /set, /base-url, /api-key`,``].join(`
|
|
46
|
+
`)),!0)},ut=async e=>{if(q){if(G){process.stdout.write(`${L(`⏳`)}busy (Ctrl+C to cancel)\n`),z.prompt();return}let t=String(e??``),n=t.trim();if(n===`.cancel`){q=null,$(),J(`Canceled multiline input.`),z.prompt();return}if(n===`.send`){let e=q.lines.join(`
|
|
47
|
+
`).replace(/\s+$/,``);if(q=null,$(),!e.trim()){J(`Canceled (empty message).`),z.prompt();return}await Je(e),$(),z.prompt();return}q.lines.push(t),z.prompt();return}let t=e.trim();if(!t){H===`select_session`&&(We(),H=`normal`,U=null,$()),z.prompt();return}if(G){process.stdout.write(`${L(`⏳`)}busy (Ctrl+C to cancel)\n`),z.prompt();return}if(H===`normal`&&!t.startsWith(`/`)&&!t.startsWith(`@`)&&!/\s/.test(t)){let e=Oe(t);if(e.kind===`exact`){process.stdout.write(`${L(`💡`)}Tip: commands start with '/'. Did you mean /${e.cmd}?\n`),z.prompt();return}if(e.kind===`prefix`){process.stdout.write(`${L(`💡`)}Tip: commands start with '/'. Did you mean /${e.cmd}?\n`),z.prompt();return}if(e.kind===`ambiguous`){process.stdout.write(`${L(`💡`)}Tip: commands start with '/'. Possible matches: ${e.matches.map(e=>`/${e}`).join(`, `)}\n`),z.prompt();return}if(e.kind===`fuzzy`||e.kind===`contains`){process.stdout.write(`${L(`💡`)}Tip: commands start with '/'. Did you mean ${e.matches.map(e=>`/${e}`).join(`, `)}?\n`),z.prompt();return}}if(t.startsWith(`/`)){H===`select_session`&&(We(),H=`normal`,U=null),await Ke(t),$(),z.prompt();return}if(H===`normal`&&t.startsWith(`@`)){let e=t.toLowerCase();if(!/\s/.test(t)&&be.includes(e)&&await lt(e)){$(),z.prompt();return}}if(H===`select_session`&&U){let e=U.sessions,n=ke(e,U.filter),r=Number.parseInt(t,10);if(Number.isFinite(r)&&r>=1&&r<=n.length){We(),await Ke(`/use ${n[r-1].sessionId}`),z.prompt();return}U.filter=t,je({sessions:e,currentSessionId:i.session.sessionId,filter:U.filter,alt:fe,emoji:F?.emoji}),z.prompt();return}await Je(t),z.prompt()};z.on(`line`,e=>{Ae||Ee>0||(V=V.then(()=>ut(e)).catch(e=>{process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`)}))})}export{Oe as resolveCommand,Me as runRepl};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{Command as e,InvalidArgumentError as t}from"commander";function n(){return`,Interactive slash commands:, /help Show help, /model [id] Show/set model id, /workspace Switch workspace root (interactive), /files Attach file(s) (interactive), /images Attach image(s) (interactive), /settings Base URL / API key / tokens, /output Output & UX options, /diag Show diagnostics for last turn, /edit Compose a message in $EDITOR, /multiline Start multiline input (.send/.cancel), /set <k> <v> Set request param (maxTokens/temperature/topP/...), /unset <k> Clear request param, /params Show current request params, /base-url <url> Set base URL (recreates client if needed), /api-key <key> Set API key for this process (not printed), /tools List enabled tools, /sessions List/pick/delete sessions, /use <sessionId> Switch session (restore history), /rm <sessionId...> Delete session(s), /save Save current session/config, /status Show current session/model info, /new Start a new conversation (clears history), /compact Manually compress context (generate summary), /exit Exit,,Mentions:, @ Open quick actions (clack if installed), @clear Clear pending attachments, @file Attach file(s) to the next prompt, @image/@img Attach image(s) to the next prompt, @workspace Switch workspace root (interactive),,Keybindings:, Ctrl+K Open command palette, Ctrl+O Manage attachments, Ctrl+G Clear attachments,`.split(`,`).join(`
|
|
2
|
+
`)}function r(e){return n=>{let r=Number(n);if(!Number.isFinite(r))throw new t(`Invalid ${e}: ${n}`);return r}}function i(e){return n=>{let r=Number.parseInt(n,10);if(!Number.isFinite(r))throw new t(`Invalid ${e}: ${n}`);return r}}function a(t){return new e().name(`goatchain`).description(`A tiny interactive chat CLI built on agent-loop`).argument(`[prompt...]`,`one-shot prompt (omit to start interactive mode)`).option(`-k, --api-key <key>`,`OpenAI API key (or set OPENAI_API_KEY)`).option(`-m, --model <id>`,`Default model id (OpenAI)`).option(`--system <prompt>`,`System prompt`).option(`--base-url <url>`,`Override OpenAI base URL (proxy)`).option(`--max-tokens <n>`,`Max completion tokens`,i(`max-tokens`)).option(`--temperature <n>`,`Temperature (0-2)`,r(`temperature`)).option(`--top-p <n>`,`Top-p (0-1)`,r(`top-p`)).option(`--presence-penalty <n>`,`Presence penalty (-2..2)`,r(`presence-penalty`)).option(`--frequency-penalty <n>`,`Frequency penalty (-2..2)`,r(`frequency-penalty`)).option(`--seed <n>`,`Random seed`,i(`seed`)).option(`--timeout-ms <n>`,`Request timeout in ms`,i(`timeout-ms`)).option(`--session <id>`,`Use a saved session id (optional)`).version(t,`-v, --version`,`Show version`).helpOption(`-h, --help`,`Show help`).showHelpAfterError().showSuggestionAfterError().addHelpText(`after`,n())}function o(e,t){let n=a(t);n.parse(e,{from:`user`});let r=n.opts(),i=Array.isArray(n.args)?n.args.join(` `).trim():``,o=e=>typeof e==`number`&&Number.isFinite(e)?e:void 0,s=e=>typeof e==`number`&&Number.isFinite(e)?Math.trunc(e):void 0;return{apiKey:typeof r.apiKey==`string`&&r.apiKey.trim()?r.apiKey:void 0,modelId:typeof r.model==`string`&&r.model.trim()?r.model:void 0,system:typeof r.system==`string`&&r.system.trim()?r.system:void 0,baseUrl:typeof r.baseUrl==`string`&&r.baseUrl.trim()?r.baseUrl:void 0,maxTokens:s(r.maxTokens),temperature:o(r.temperature),topP:o(r.topP),presencePenalty:o(r.presencePenalty),frequencyPenalty:o(r.frequencyPenalty),seed:s(r.seed),timeoutMs:s(r.timeoutMs),sessionId:typeof r.session==`string`&&r.session.trim()?r.session:void 0,prompt:i}}function s(e,t){let n=String(e??``).replace(/\s+/g,` `).trim();return n.length<=t?n:`${n.slice(0,Math.max(0,t-1))}…`}function c(){return!(!process.stdout.isTTY||process.env.TERM===`dumb`||`NO_COLOR`in process.env)}function l(e,...t){return c()?`${t.join(``)}${String(e??``)}\u001B[0m`:String(e??``)}const u={bold:e=>l(e,`\x1B[1m`),dim:e=>l(e,`\x1B[2m`),gray:e=>l(e,`\x1B[90m`),red:e=>l(e,`\x1B[31m`),green:e=>l(e,`\x1B[32m`),yellow:e=>l(e,`\x1B[33m`),cyan:e=>l(e,`\x1B[36m`),inverse:e=>l(e,`\x1B[7m`),header:e=>l(e,`\x1B[1m`,`\x1B[7m`),highlight:e=>l(e,`\x1B[30m`,`\x1B[43m`)};function d(e){if(!e||typeof e!=`object`)return``;let t=e.content;if(typeof t==`string`)return t;try{return JSON.stringify(t)}catch{return String(t)}}function f(e){let t=Array.isArray(e)?e.find(e=>e&&typeof e==`object`&&e.role===`user`&&s(d(e),999).length>0):void 0;return s((t?d(t):``)||`New session`,60)||`New session`}function p(e){let t=Array.isArray(e)?e:[],n=t.find(e=>e&&typeof e==`object`&&e.role===`user`),r=[...t].reverse().find(e=>e&&typeof e==`object`&&e.role===`user`),i=[...t].reverse().find(e=>e&&typeof e==`object`&&e.role===`assistant`),a=s(n?d(n):``,80),o=s(r?d(r):``,80),c=s(i?d(i):``,80);return s([a?`first: ${a}`:``,o&&o!==a?`last user: ${o}`:``,c?`last assistant: ${c}`:``].filter(Boolean).join(` | `),160)}function m(e){if(typeof e!=`number`||!Number.isFinite(e))return``;try{let t=new Date(e),n=e=>String(e).padStart(2,`0`),r=t.getFullYear(),i=n(t.getMonth()+1),a=n(t.getDate()),o=n(t.getHours()),s=n(t.getMinutes());return r===new Date().getFullYear()?`${i}-${a} ${o}:${s}`:`${r}-${i}-${a} ${o}:${s}`}catch{return``}}function h(e,t={}){let n=Array.isArray(e)?e:[],r=typeof t.maxMessages==`number`?t.maxMessages:12,i=typeof t.maxCharsPerMessage==`number`?t.maxCharsPerMessage:600,a=!!t.emoji&&process.stdout.isTTY&&process.env.TERM!==`dumb`,o=n.filter(e=>e&&typeof e==`object`&&e.role!==`system`);if(o.length===0){process.stdout.write(`[no history]
|
|
3
|
+
`);return}let c=Math.max(0,o.length-r),l=o.slice(c),f=c;f>0&&process.stdout.write(u.dim(`[... ${f} earlier messages omitted ...]\n`));for(let e of l){let t=typeof e.role==`string`?e.role:`unknown`,n=t===`assistant`?`assistant`:t===`user`?`user`:t,r=a?`${a?n===`assistant`?`🤖`:n===`user`?`👤`:n===`tool`?`🛠️`:`📌`:``} ${n}`:n,o=n===`assistant`?u.cyan(r):n===`user`?u.green(r):u.gray(n),c=s(d(e),i);process.stdout.write(`[${o}] ${c}\n`)}}function g(){process.stdout.isTTY&&process.stdout.write(`\x1B[2J\x1B[H`)}export{s as a,a as c,f as i,n as l,g as n,m as o,p as r,h as s,u as t,o as u};
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "goatchip",
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "0.0.2-beta.1",
|
|
5
|
+
"description": "GoatChain CLI",
|
|
6
|
+
"author": "Simon He",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/zjywill/GoatChain.git",
|
|
11
|
+
"directory": "packages/cli"
|
|
12
|
+
},
|
|
13
|
+
"keywords": [
|
|
14
|
+
"ai",
|
|
15
|
+
"agent",
|
|
16
|
+
"cli",
|
|
17
|
+
"goatchain"
|
|
18
|
+
],
|
|
19
|
+
"bin": {
|
|
20
|
+
"goatchain": "./dist/cli.mjs"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist/**/*"
|
|
24
|
+
],
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=18"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@clack/prompts": "^0.11.0",
|
|
30
|
+
"commander": "^12.1.0",
|
|
31
|
+
"goatchain": "^0.0.1"
|
|
32
|
+
},
|
|
33
|
+
"devDependencies": {
|
|
34
|
+
"tsdown": "^0.15.12"
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsdown && node scripts/postbuild.mjs",
|
|
38
|
+
"cli": "pnpm -s build && node dist/cli.mjs",
|
|
39
|
+
"smoke": "pnpm -s build && node dist/cli.mjs --help",
|
|
40
|
+
"bummp": "npx bumpp --tag-prefix cli/v --commit --push"
|
|
41
|
+
}
|
|
42
|
+
}
|