@abacus-ai/cli 2.0.0-canary.5 → 2.0.0-canary.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.mjs +93 -93
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -44,14 +44,14 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
44
44
 
45
45
  \`\`\`
46
46
  `+e.codeEdit.trim()+"\n```":"```\n"+e.codeEdit.trim()+"\n```",o;if(e.startLine!==void 0&&e.endLine!==void 0){let t=i.split(`
47
- `).length,r=Math.max(1,Math.min(e.startLine,t)),a=Math.max(r,Math.min(e.endLine,t));o={[n]:[r,a]}}let s=await t.apiClient.getCodeEdit({message:a,fileContents:{[n]:i},fileSelection:o,rules:t.rules??[]});if(!s?.success||!s.result?.codeChanges)return{skipPermission:!0,error:`Failed to get code edit response`};if(s.result.codeChanges.length===0){if(s=await t.apiClient.getCodeEdit({message:a,fileContents:{[n]:i},fileSelection:o,rules:t.rules??[],llmName:`CLAUDE_V4_SONNET`}),!s?.success||!s.result?.codeChanges)return{skipPermission:!0,error:`Failed to get code edit response with fallback LLM`};if(s.result.codeChanges.length===0)return{skipPermission:!0,error:`Failed to apply changes to the file`}}let c=s.result.codeChanges,l=[],u=0;for(;u<c.length;){let e=c[u];if(!e||!e.type||e.text===void 0){u++;continue}if(e.type===`old`){let t=u+1<c.length?c[u+1]:void 0;t?.type===`new`?(l.push({old:e.text,new:t.text}),u+=2):(l.push({old:e.text,new:``}),u++)}else u++}let d=[];for(let e of l){let t=i.indexOf(e.old);if(t===-1){let t=e.old.length>100?e.old.substring(0,100)+`...`:e.old;d.push(`Could not find exact match for: ${t}`)}else if(t!==i.lastIndexOf(e.old)){let t=e.old.length>100?e.old.substring(0,100)+`...`:e.old;d.push(`String appears multiple times in file (ambiguous match): ${t}`)}}return d.length>0?{skipPermission:!0,error:`Failed to apply edit:\n${d.join(`
48
- `)}`}:{currentContent:i,fileExists:r,codeChanges:s.result.codeChanges}}catch(e){return{skipPermission:!0,error:`Failed to compute diff: ${e instanceof Error?e.message:`Unknown error`}`}}return{currentContent:i,fileExists:r}}needsPermission(e,t,n){if(n?.skipPermission)return!1;if(t.agentMode===xl.PlanMode){let n=t.workspacePath,r=C.resolve(n,e.targetFile),i=t.plansDir??ke.localConfigDirName+`/plans/`,a=C.resolve(n,i),o=a.endsWith(`/`)?a:a+`/`;return!r.startsWith(o)}return t.agentMode!==xl.AcceptEdits}async execute(e,t,n){let{targetFile:r,codeEdit:i,overwriteFile:a,startLine:o,endLine:s}=e;if(n?.error)return{type:`edit`,targetFile:r,operation:`failed`,error:n.error,lineDiff:0,originalLines:0,newLines:0,unchanged:!0};let c=n?.fileExists||!1,l=n?.currentContent||``,u=n?.codeChanges,d=``,f=``,p=[];if(!c)await t.workspace.create(r,i),d=i,f=`created`;else if(a)l?await t.workspace.strReplace(r,l,i,1):(await t.workspace.deleteFile(r),await t.workspace.create(r,i)),d=i,f=`overwritten`;else if(u&&u.length>0){let e=[],n=0;for(;n<u.length;){let t=u[n];if(!t||!t.type||t.text===void 0){n++;continue}if(t.type===`old`){let r=n+1<u.length?u[n+1]:void 0;r?.type===`new`?(e.push({old:t.text,new:r.text}),n+=2):(e.push({old:t.text,new:``}),n++)}else t.type,n++}let i=0;for(let n of e)try{await t.workspace.strReplace(r,n.old,n.new,1),i++}catch{try{await t.workspace.strReplace(r,n.old,n.new,1),i++}catch(e){let t=`Failed to apply replacement: ${e instanceof Error?e.message:String(e)}`;p.push(t)}}if(i===0&&e.length>0){let t=p.length>0?`None of the ${e.length} replacements could be applied to ${r}. Errors:\n${p.join(`
49
- `)}`:`None of the ${e.length} replacements could be applied to ${r}`;throw Error(t)}d=await t.workspace.readRawFile(r),f=o!==void 0&&s!==void 0?`modified (lines ${o}-${s})`:`modified`,p.length>0&&i>0&&(f+=` (${i}/${e.length} replacements applied, ${p.length} failed)`)}else{if(o!==void 0&&s!==void 0){let e=l.split(`
47
+ `).length,r=Math.max(1,Math.min(e.startLine,t)),a=Math.max(r,Math.min(e.endLine,t));o={[n]:[r,a]}}let s=await t.apiClient.getCodeEdit({message:a,fileContents:{[n]:i},fileSelection:o,rules:t.rules??[]});if(!s?.success||!s.result?.codeChanges)return{skipPermission:!0,error:`Failed to get code edit response`};if(s.result.codeChanges.length===0){if(s=await t.apiClient.getCodeEdit({message:a,fileContents:{[n]:i},fileSelection:o,rules:t.rules??[],llmName:`CLAUDE_V4_SONNET`}),!s?.success||!s.result?.codeChanges)return{skipPermission:!0,error:`Failed to get code edit response with fallback LLM`};if(s.result.codeChanges.length===0)return{skipPermission:!0,error:`Failed to apply changes to the file`}}let c=s.result.codeChanges,l=this._computeReplacements(c);await new Promise(e=>setImmediate(e));let u=[];for(let e of l){let t=i.indexOf(e.old);if(t===-1){let t=e.old.length>100?e.old.substring(0,100)+`...`:e.old;u.push(`Could not find exact match for: ${t}`)}else if(t!==i.lastIndexOf(e.old)){let t=e.old.length>100?e.old.substring(0,100)+`...`:e.old;u.push(`String appears multiple times in file (ambiguous match): ${t}`)}}return u.length>0?{skipPermission:!0,error:`Failed to apply edit:\n${u.join(`
48
+ `)}`}:{currentContent:i,fileExists:r,codeChanges:s.result.codeChanges}}catch(e){return{skipPermission:!0,error:`Failed to compute diff: ${e instanceof Error?e.message:`Unknown error`}`}}return{currentContent:i,fileExists:r}}needsPermission(e,t,n){if(n?.skipPermission)return!1;if(t.agentMode===xl.PlanMode){let n=t.workspacePath,r=C.resolve(n,e.targetFile),i=t.plansDir??ke.localConfigDirName+`/plans/`,a=C.resolve(n,i),o=a.endsWith(`/`)?a:a+`/`;return!r.startsWith(o)}return t.agentMode!==xl.AcceptEdits}_computeReplacements(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(!r||!r.type||r.text===void 0){n++;continue}if(r.type===`old`){let i=n+1<e.length?e[n+1]:void 0;i?.type===`new`?(t.push({old:r.text,new:i.text}),n+=2):(t.push({old:r.text,new:``}),n++)}else r.type,n++}return t}async _applyReplacements(e,t,n){let r=[],i=0;for(let a of n){await new Promise(e=>setImmediate(e));try{await e.workspace.strReplace(t,a.old,a.new,1),i++}catch{try{await e.workspace.strReplace(t,a.old,a.new,1),i++}catch(e){let t=`Failed to apply replacement: ${e instanceof Error?e.message:String(e)}`;r.push(t)}}}return{successCount:i,failedReplacements:r}}async execute(e,t,n){let{targetFile:r,codeEdit:i,overwriteFile:a,startLine:o,endLine:s}=e;if(n?.error)return{type:`edit`,targetFile:r,operation:`failed`,error:n.error,lineDiff:0,originalLines:0,newLines:0,unchanged:!0};let c=n?.fileExists||!1,l=n?.currentContent||``,u=n?.codeChanges,d=``,f=``,p=[];if(!c)await t.workspace.create(r,i),d=i,f=`created`;else if(a)l?await t.workspace.strReplace(r,l,i,1):(await t.workspace.deleteFile(r),await t.workspace.create(r,i)),d=i,f=`overwritten`;else if(u&&u.length>0){let e=this._computeReplacements(u);await new Promise(e=>setImmediate(e));let n=await this._applyReplacements(t,r,e);if(p=n.failedReplacements,n.successCount===0&&e.length>0){let t=p.length>0?`None of the ${e.length} replacements could be applied to ${r}. Errors:\n${p.join(`
49
+ `)}`:`None of the ${e.length} replacements could be applied to ${r}`;throw Error(t)}d=await t.workspace.readRawFile(r),f=o!==void 0&&s!==void 0?`modified (lines ${o}-${s})`:`modified`,p.length>0&&n.successCount>0&&(f+=` (${n.successCount}/${e.length} replacements applied, ${p.length} failed)`)}else{if(o!==void 0&&s!==void 0){let e=l.split(`
50
50
  `),n=e.length,a=Math.max(1,Math.min(o,n)),c=Math.max(a,Math.min(s,n)),u=e.slice(a-1,c).join(`
51
51
  `);try{await t.workspace.strReplace(r,u,i,1,a,c),f=`modified (lines ${a}-${c})`}catch{let n=e.slice(0,a-1),o=e.slice(c);d=[...n,...i.split(`
52
52
  `),...o].join(`
53
53
  `),await t.workspace.create(r,d),f=`modified (lines ${a}-${c})`}}else if(l.includes(i))f=`no changes (content already present)`;else{let e=`
54
- `+i;await t.workspace.strReplace(r,l,l+e,1),f=`modified (appended content)`}try{d=await t.workspace.readRawFile(r)}catch{d=l}}let m=l.split(`
54
+ `+i;await t.workspace.strReplace(r,l,l+e,1),f=`modified (appended content)`}try{d=await t.workspace.readRawFile(r)}catch{d=l}}await new Promise(e=>setImmediate(e));let m=l.split(`
55
55
  `).length,h=d.split(`
56
56
  `).length,g=h-m;d!==l&&t.onFileModified&&t.onFileModified?.({original:l,modified:d,filename:r,operation:f,isNewFile:!c});let _={type:`edit`,targetFile:r,operation:f,lineDiff:g,originalLines:m,newLines:h,unchanged:d===l,originalContent:l,finalContent:d,codeChanges:u,isNewFile:!c};return p&&p.length>0&&(_.warnings=p),_}format(e,t){let n=e;return n.error?JSON.stringify({type:`edit`,status:`error`,error:n.error}):n.unchanged?`No changes needed`:n.isNewFile?`Created successfully`:`Updated successfully`}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`edit`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);if(t.status===`error`||t.error)return{phase:`error`,toolType:`edit`,data:t,summary:t.error??`Error`,errorMessage:t.error};if(t.status===`skipped`||t.unchanged)return{phase:`skipped`,toolType:`edit`,data:t,summary:`No changes needed`};let n=t.newLines!=null&&t.originalLines!=null?Math.max(0,t.newLines-t.originalLines):t.lineDiff>0?t.lineDiff:0,r=t.newLines!=null&&t.originalLines!=null?Math.max(0,t.originalLines-t.newLines):t.lineDiff<0?-t.lineDiff:0;return{phase:`success`,toolType:`edit`,data:t,summary:`+${n} -${r} lines`,additions:n,deletions:r}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`edit`,data:{},summary:e,errorMessage:e}:e===`No changes needed`?{phase:`skipped`,toolType:`edit`,data:{},summary:`No changes needed`}:e===`Created successfully`?{phase:`success`,toolType:`edit`,data:{isNewFile:!0},summary:`Created`}:{phase:`success`,toolType:`edit`,data:{},summary:`Updated`}}},Pl=class extends Yc{isReadonly=!0};const Fl=tc({targetFile:J(),startLineOneIndexed:il,endLineOneIndexed:il,startLine:il,endLine:il,shouldReadEntireFile:ol,explanation:J().optional()});var Il=class extends Pl{name=`read_file`;displayName=`Read`;description=`Read a file`;parameters=Fl;needsPermission(e,t){let n=C.isAbsolute(e.targetFile)?e.targetFile:C.resolve(t.workspacePath,e.targetFile);return!(t.allowEditingPaths??[t.workspacePath]).some(e=>{let t=C.resolve(e);if(n===t)return!0;let r=C.relative(t,n);return!r.startsWith(`..`)&&!C.isAbsolute(r)})}async execute(e,t){let{targetFile:n,shouldReadEntireFile:r}=e,i=e.startLineOneIndexed??e.startLine,a=e.endLineOneIndexed??e.endLine,o=i||1;return{type:`read_file`,targetFile:n,content:await t.workspace.readFile(n,o,a||2**53-1,r||!1),startLine:o}}format(e){let t=e;if(t.error)return JSON.stringify({type:`read_file`,status:`error`,error:t.error});let n=(t.content??``).split(`
57
57
  `),r=t.startLine??1;return n.map((e,t)=>`Line${r+t}: ${e}`).join(`
@@ -68,13 +68,13 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
68
68
  `),r=n[0]?.match(/^Found (\d+) files$/),i,a;return r?(i=n.slice(2).filter(e=>e&&!e.startsWith(`...[`)&&!e.startsWith(`[Showing`)),a=`Found ${r[1]} files`):(i=n.filter(e=>e&&!e.startsWith(`...[`)&&!e.startsWith(`[Showing`)),a=i.length===0?`No matches`:`Found ${i.length} matches`),{phase:`success`,toolType:`grep`,data:{matches:i},summary:a}}};const Jl=tc({pattern:J().describe(`The glob pattern to match files against`),path:J().optional().describe(`The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.`)});var Yl=class extends Pl{name=`glob`;displayName=`Search`;description=`Fast file pattern matching tool that works with any codebase size`;parameters=Jl;async execute(e,t){return await t.workspace.glob({pattern:e.pattern,path:e.path})}format(e,t){let n=e,r=n.metadata.totalFiles;if(r===0)return`No files found`;let i=r>100,a=[(i?n.files.slice(0,100):n.files).join(`
69
69
  `)];return i&&a.push(`(Results are truncated. Consider using a more specific path or pattern.)`),a.join(`
70
70
  `)}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`glob`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);if(t.status===`error`||t.error)return{phase:`error`,toolType:`glob`,data:t,summary:t.error??`Error`,errorMessage:t.error};let n=t.data?.totalFiles??t.data?.files?.length??0;return{phase:`success`,toolType:`glob`,data:t.data??t,summary:n===0?`No files found`:`${n} files`}}catch{}if(e.startsWith(`Error:`))return{phase:`error`,toolType:`glob`,data:{},summary:e,errorMessage:e};if(e===`No files found`)return{phase:`success`,toolType:`glob`,data:{files:[]},summary:`No files found`};let n=e.split(`
71
- `).filter(e=>e&&!e.startsWith(`(Results are truncated`)).filter(e=>e.trim()),r=n.length===0?`No files found`:`${n.length} files`;return{phase:`success`,toolType:`glob`,data:{files:n},summary:r}}};const Xl=tc({query:J().describe(`File name pattern to search for`),includePattern:J().optional().describe(`Pattern to include in search`),excludePattern:J().optional().describe(`Pattern to exclude from search`),explanation:J().optional().describe(`Explanation of why this search is needed`)});var Zl=class extends Pl{name=`file_search`;displayName=`Search`;description=`Search for a file`;parameters=Xl;async execute(e,t){let{query:n,includePattern:r,excludePattern:i}=e;if(!n)throw Error(`Query parameter is required for file search`);return{files:await t.workspace.grepFile({query:n,folderIncludes:r?[r]:[],folderExcludes:i?[i]:[]})}}format(e,t){let n=e;return JSON.stringify({type:`file_search`,status:`success`,query:t.query,fileCount:n.files.length,result:n.files})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`file_search`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.error?{phase:`error`,toolType:`file_search`,data:t,summary:t.error??`Error`,errorMessage:t.error}:{phase:`success`,toolType:`file_search`,data:t,summary:`Found ${t.fileCount??t.result?.length??0} files`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`file_search`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`file_search`,data:{},summary:`Completed`}}};const Ql=tc({query:J().describe(`Natural language query for semantic search`),command:J().optional().describe(`Optional command parameter`),explanation:J().optional().describe(`Explanation of why this search is needed`)});var $l=class extends Zc{name=`semantic_search_server`;displayName=`Search`;description=`Search files using semantics (more advanced than grep)`;parameters=Ql;isReadonly=!0;format(e,t){return JSON.stringify({type:`semantic_search`,status:`success`})}parse(e){let t=Jc(e);return t.rejected?{phase:`rejected`,toolType:`semantic_search`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}}:{phase:`success`,toolType:`semantic_search`,data:{},summary:`Completed`}}};const eu=tc({searchTerm:J().describe(`Search query for web search`),query:J().optional().describe(`Alternative query parameter`),explanation:J().optional().describe(`Explanation of why this search is needed`)});var tu=class extends Zc{name=`web_search`;displayName=`WebSearch`;description=`Search on the web`;parameters=eu;isReadonly=!0;format(e,t){return JSON.stringify({type:`web_search`,status:`success`})}parse(e){let t=Jc(e);return t.rejected?{phase:`rejected`,toolType:`web_search`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}}:{phase:`success`,toolType:`web_search`,data:{},summary:`Found results`}}};const nu=tc({url:J().describe(`URL to fetch content from`)});var ru=class extends Zc{name=`fetch_url`;displayName=`Fetch`;description=`Fetch content from a URL`;parameters=nu;isReadonly=!0;format(e,t){return JSON.stringify({type:`fetch_url`,status:`success`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`fetch_url`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.error?{phase:`error`,toolType:`fetch_url`,data:t,summary:t.error??`Error`,errorMessage:t.error}:{phase:`success`,toolType:`fetch_url`,data:t,summary:`Fetched`}}catch{}let n=(e.length/1024).toFixed(1);return{phase:`success`,toolType:`fetch_url`,data:{content:e},summary:`Fetched ${n} KB`}}};function iu(e){return e=e.replace(/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)|[\x20-\x2f]*[\x30-\x7e])/g,e=>/^\x1b\[[\d;:]*m$/.test(e)?e:``),e.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001A\u001C-\u001F\u007F]/g,``)}function au(e){return e.trim()}function ou(e,t){let n=e,r=0;for(;r<t.length;){let e=t[r];if(!e?.type||e.text===void 0){r++;continue}if(e.type===`old`){let i=r+1<t.length?t[r+1]:void 0;if(i?.type===`new`){let t=n.indexOf(e.text);t!==-1&&(n=n.slice(0,t)+i.text+n.slice(t+e.text.length)),r+=2}else{let t=n.indexOf(e.text);t!==-1&&(n=n.slice(0,t)+n.slice(t+e.text.length)),r++}}else r++}return n}function su(e){let t=3e4,n=au(e);if(n.length<=t)return n;let r=1;for(let e=0;e<n.length;e++)n[e]===`
71
+ `).filter(e=>e&&!e.startsWith(`(Results are truncated`)).filter(e=>e.trim()),r=n.length===0?`No files found`:`${n.length} files`;return{phase:`success`,toolType:`glob`,data:{files:n},summary:r}}};const Xl=tc({query:J().describe(`File name pattern to search for`),includePattern:J().optional().describe(`Pattern to include in search`),excludePattern:J().optional().describe(`Pattern to exclude from search`),explanation:J().optional().describe(`Explanation of why this search is needed`)});var Zl=class extends Pl{name=`file_search`;displayName=`Search`;description=`Search for a file`;parameters=Xl;async execute(e,t){let{query:n,includePattern:r,excludePattern:i}=e;if(!n)throw Error(`Query parameter is required for file search`);return{files:await t.workspace.grepFile({query:n,folderIncludes:r?[r]:[],folderExcludes:i?[i]:[]})}}format(e,t){let n=e;return JSON.stringify({type:`file_search`,status:`success`,query:t.query,fileCount:n.files.length,result:n.files})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`file_search`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.error?{phase:`error`,toolType:`file_search`,data:t,summary:t.error??`Error`,errorMessage:t.error}:{phase:`success`,toolType:`file_search`,data:t,summary:`Found ${t.fileCount??t.result?.length??0} files`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`file_search`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`file_search`,data:{},summary:`Completed`}}};const Ql=tc({query:J().describe(`Natural language query for semantic search`),command:J().optional().describe(`Optional command parameter`),explanation:J().optional().describe(`Explanation of why this search is needed`)});var $l=class extends Zc{name=`semantic_search_server`;displayName=`Search`;description=`Search files using semantics (more advanced than grep)`;parameters=Ql;isReadonly=!0;format(e,t){return JSON.stringify({type:`semantic_search`,status:`success`})}parse(e){let t=Jc(e);return t.rejected?{phase:`rejected`,toolType:`semantic_search`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}}:{phase:`success`,toolType:`semantic_search`,data:{},summary:`Completed`}}};const eu=tc({searchTerm:J().describe(`Search query for web search`),query:J().optional().describe(`Alternative query parameter`),explanation:J().optional().describe(`Explanation of why this search is needed`)});var tu=class extends Zc{name=`web_search`;displayName=`WebSearch`;description=`Search on the web`;parameters=eu;isReadonly=!0;format(e,t){return JSON.stringify({type:`web_search`,status:`success`})}parse(e){let t=Jc(e);return t.rejected?{phase:`rejected`,toolType:`web_search`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}}:{phase:`success`,toolType:`web_search`,data:{},summary:`Found results`}}};const nu=tc({url:J().describe(`The URL to fetch content from`),prompt:J().describe(`The prompt to run on the fetched content`)});var ru=class extends Zc{name=`web_fetch`;displayName=`Fetch`;description=`Fetch content from a URL`;parameters=nu;isReadonly=!0;format(e,t){return JSON.stringify({type:`web_fetch`,status:`success`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`web_fetch`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return t.status===`error`||t.error?{phase:`error`,toolType:`web_fetch`,data:t,summary:t.error??`Error`,errorMessage:t.error}:{phase:`success`,toolType:`web_fetch`,data:t,summary:`Fetched`}}catch{}let n=(e.length/1024).toFixed(1);return{phase:`success`,toolType:`web_fetch`,data:{content:e},summary:`Fetched ${n} KB`}}};function iu(e){return e=e.replace(/\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1b\\)|[\x20-\x2f]*[\x30-\x7e])/g,e=>/^\x1b\[[\d;:]*m$/.test(e)?e:``),e.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001A\u001C-\u001F\u007F]/g,``)}function au(e){return e.trim()}function ou(e,t){let n=e,r=0;for(;r<t.length;){let e=t[r];if(!e?.type||e.text===void 0){r++;continue}if(e.type===`old`){let i=r+1<t.length?t[r+1]:void 0;if(i?.type===`new`){let t=n.indexOf(e.text);t!==-1&&(n=n.slice(0,t)+i.text+n.slice(t+e.text.length)),r+=2}else{let t=n.indexOf(e.text);t!==-1&&(n=n.slice(0,t)+n.slice(t+e.text.length)),r++}}else r++}return n}function su(e){let t=3e4,n=au(e);if(n.length<=t)return n;let r=1;for(let e=0;e<n.length;e++)n[e]===`
72
72
  `&&r++;let i=n.substring(0,1e4),a=n.substring(n.length-2e4),o=1;for(let e=0;e<i.length;e++)i[e]===`
73
73
  `&&o++;let s=1;for(let e=0;e<a.length;e++)a[e]===`
74
74
  `&&s++;return`${i}\n\n... [${r-(o+s)} lines / ${n.length-t} chars truncated] ...\n\n${a}`}var cu=class e extends jl{name=`bash`;displayName=`Bash`;description=`Run a command in a minified terminal. Creates a new terminal by default, unless an id is provided to use an existing terminal.`;static DEFAULT_TIMEOUT_MS=12e4;static MAX_TIMEOUT_MS=6e5;static Parameters=tc({command:J().describe(`The command to execute`),explanation:J().optional().describe(`Explanation of what the command does`),runInBackground:ol.describe(`Whether to run the command in the background`),shellId:Wc().optional().describe(`Terminal ID to use (creates new if not provided)`),interactiveMode:ol.describe(`Whether to run in interactive mode`),timeout:Gc().optional().describe(`Timeout in milliseconds (default: 120000, max: 600000)`)});parameters=e.Parameters;needsPermission(e,t,n){return!0}async execute(t,n){let{command:r,runInBackground:i,interactiveMode:a,shellId:o,timeout:s}=t,c=n.terminalService,l=s??e.DEFAULT_TIMEOUT_MS,u=Math.min(l,e.MAX_TIMEOUT_MS),d=n.onOutputUpdate,f=n.abortController?.signal,p=o?parseInt(o):void 0;if(a&&r===`/exit`)return p?(await c.closeTerminal?.(p),{type:`bash`,id:p,command:r,exitCode:0,output:`Terminal closed`,isError:!1,duration:0,runInBackground:!1,interactiveMode:!0,terminated:!0}):{type:`bash`,id:0,command:r,exitCode:1,output:`No terminal ID provided for /exit command`,isError:!0,duration:0,runInBackground:!1,interactiveMode:!0};if(a&&r===`/wait`)if(p){await Ul(3e3);let e=c.getOutput(p),t=e.length>0?e[e.length-1]:null;return{type:`bash`,id:p,command:r,exitCode:0,output:t?.output?iu(t.output):`No output available`,isError:!1,duration:3e3,runInBackground:!1,interactiveMode:!0,message:`Terminal state checked - ready for next command`}}else return{type:`bash`,id:0,command:r,exitCode:1,output:`No terminal ID provided for /wait command`,isError:!0,duration:0,runInBackground:!1,interactiveMode:!0};if(a){let e=await c.executeCommand(r,{terminalId:p,alwaysCreateNew:!o,interactiveMode:!0});await Ul(3e3);let t=e.result.get(),n=iu(t.output||``);return n=su(n),{type:`bash`,id:t.id,command:t.command,exitCode:t.exitCode||0,output:n,isError:t.exitCode!==void 0&&t.exitCode!==0,duration:t.duration||0,runInBackground:!1,interactiveMode:!0,message:`Interactive command executed - terminal ready for next command`}}let m=await c.executeCommand(r,{terminalId:p,alwaysCreateNew:!o});if(i){let e=m.result.get(),t=iu(e.output||``);return t=su(t),{type:`bash`,id:e.id,command:e.command,exitCode:e.exitCode||0,output:t,isError:!1,duration:e.duration||0,runInBackground:!0,message:`Background command started`}}if(m.running){let e=m.result.get().id,t;d&&(t=setInterval(()=>{try{let e=m.result.get();e&&e.output&&d(n.toolCallId,iu(e.output))}catch{}},100));let r=[m.running],i,a=f?new Promise((e,t)=>{f.aborted?t(Error(`interrupted`)):(i=()=>t(Error(`interrupted`)),f.addEventListener(`abort`,i,{once:!0}))}):null;a&&r.push(a);let o=new Promise((e,t)=>{setTimeout(()=>{t(Error(`Terminal command timed out after ${u}ms`))},u)});r.push(o);try{try{await Promise.race(r)}catch(t){if(t instanceof Error&&t.message===`interrupted`){await c.stopCommand(e);let t=m.result.get();return{type:`bash`,id:t.id,command:t.command,exitCode:130,output:iu(t.output||``)+`
75
75
  [Interrupted]`,isError:!0,duration:t.duration||0,runInBackground:!1,terminated:!0}}if(t instanceof Error&&t.message.includes(`timed out`)){let e=m.result.get();return{type:`bash`,id:e.id,command:e.command,exitCode:0,output:`Command running in background with ID: ${e.id}`,isError:!1,duration:e.duration||0,runInBackground:!0,timedOut:!0}}throw t}}finally{t&&clearInterval(t),i&&f&&f.removeEventListener(`abort`,i)}}let h=m.result.get(),g=iu(h.output||``);return g=su(g),{type:`bash`,id:h.id,command:h.command,exitCode:h.exitCode||0,output:g,isError:h.exitCode!==void 0&&h.exitCode!==0,duration:h.duration||0,runInBackground:!1}}format(e,t){let n=e;return JSON.stringify({type:`bash`,status:n.isError?`error`:`success`,id:n.id,command:n.command,exitCode:n.exitCode,output:n.output,duration:n.duration,...n.runInBackground&&{runInBackground:!0},...n.terminated&&{terminated:!0},...n.timedOut&&{timedOut:!0},...n.interactiveMode&&{interactiveMode:!0}})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`bash`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);if(t.terminated)return{phase:`error`,toolType:`bash`,data:t,summary:`Terminated${t.duration==null?``:` \u00b7 ${(t.duration/1e3).toFixed(1)}s`}`,...t.exitCode!=null&&{exitCode:t.exitCode},...t.duration!=null&&{duration:t.duration}};if(t.timedOut)return{phase:`success`,toolType:`bash`,data:t,summary:`Running in background (id: ${t.id??`?`})`,runInBackground:!0};if(t.runInBackground)return{phase:`success`,toolType:`bash`,data:t,summary:`Started in background (id: ${t.id??`?`})`,runInBackground:!0};let n=t.exitCode??0,r=t.duration==null?``:` \u00b7 ${(t.duration/1e3).toFixed(1)}s`,i=n!==0||t.isError||t.status===`error`;return{phase:i?`error`:`success`,toolType:`bash`,data:t,summary:`exit ${n}${r}`,exitCode:n,...t.duration!=null&&{duration:t.duration},...i&&t.output&&{errorMessage:t.output.slice(-200)}}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`bash`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`bash`,data:{},summary:`Completed`}}},lu=class e extends Pl{name=`bash_output`;displayName=`BashOutput`;description=`Get the output of a terminal command`;static Parameters=tc({shellId:Wc().describe(`Terminal ID to get output from`),filter:J().optional().describe(`Optional regular expression to filter the output lines. Only lines matching this regex will be included in the result.`)});parameters=e.Parameters;needsPermission(){return!1}_applyFilter(e,t){let n=new RegExp(t);return e.map(e=>({...e,output:(e.output??``).split(`
76
76
  `).filter(e=>n.test(e)).join(`
77
- `)}))}async execute(e,t){let{shellId:n,filter:r}=e;if(!n)throw Error(`shellId parameter is required for bash_output`);let i=t.terminalService,a=parseInt(n),o=i.getLiveOutput?.(a);if(o){let e=[o];return r&&(e=this._applyFilter(e,r)),{type:`bash_output`,terminalId:n,outputs:e,totalOutputs:1}}let s=i.getOutput(a);return r&&(s=this._applyFilter(s,r)),{type:`bash_output`,terminalId:n,outputs:s,totalOutputs:s.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`bash_output`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return{phase:`success`,toolType:`bash_output`,data:t,summary:`Retrieved ${t.totalOutputs??t.outputs?.length??0} lines`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`bash_output`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`bash_output`,data:{},summary:`Retrieved`}}},uu=class e extends jl{name=`kill_shell`;displayName=`KillShell`;description=`Kills a running background bash shell by its ID. Use this tool when you need to terminate a long-running shell. Shell IDs can be found using the /tasks command.`;static Parameters=tc({shellId:Wc().describe(`The ID of the background shell to kill`)});parameters=e.Parameters;async execute(e,t){let{shellId:n}=e;if(!n)throw Error(`shellId parameter is required for kill_shell`);let r=t.terminalService,i=parseInt(n),a=await r.stopCommand(i);return r.closeTerminal&&await r.closeTerminal(i),{type:`kill_shell`,shellId:n,success:a}}format(e,t){return JSON.stringify({...e,status:e.success?`success`:`failure`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`kill_shell`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return{phase:t.success?`success`:`error`,toolType:`kill_shell`,data:t,summary:t.success?`Killed shell ${t.shellId}`:`Failed to kill shell ${t.shellId}`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`kill_shell`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`kill_shell`,data:{},summary:`Shell killed`}}},du=class{tool;context;params;_prepareResult=null;_executionResult=null;constructor(e,t,n){this.tool=e,this.params=t,this.context=n}getTool(){return this.tool}getParams(){return this.params}mergeParams(e){this.params={...this.params,...e}}getContext(){return this.context}getPrepareResult(){return this._prepareResult}getExecutionResult(){return this._executionResult}async prepare(){return this._prepareResult=await this.tool.prepare(this.params,this.context),this._prepareResult}needsPermission(){return this._prepareResult?.skipPermission?!1:this.tool.needsPermission(this.params,this.context,this._prepareResult)}async execute(){return this._executionResult=await this.tool.execute(this.params,this.context,this._prepareResult),this._executionResult}formatResult(){if(this._executionResult===null)throw Error(`Cannot format result before execution completes`);return this.tool.format(this._executionResult,this.params)}async executeWithPermission(e){if(await this.prepare(),this.needsPermission()){if(!e)throw Error(`Permission check required but no permission callback provided`);if(!await e())throw Error(`Permission denied`)}return await this.execute(),this.formatResult()}},fu=class{tools;context;constructor(){this.tools=new Map}register(e){if(this.tools.has(e.name))throw Error(`Tool '${e.name}' is already registered`);this.tools.set(e.name,e)}registerAll(e){for(let t of e)this.register(t)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getToolNames(){return Array.from(this.tools.keys())}getAllTools(){return Array.from(this.tools.values())}setContext(e){this.context=e}getApiToolDefinitions(e){let t=e??this.context;return Array.from(this.tools.values()).filter(e=>e.includeInApiDefinitions).filter(e=>!t||e.isEnabled(t)).map(e=>e.getToolDefinition())}getMcpToolDefinitions(){return Array.from(this.tools.values()).filter(e=>!e.includeInApiDefinitions).map(e=>e.getToolDefinition())}getReadonlyToolDefinitions(e){return Array.from(this.tools.values()).filter(e=>e.isReadonly&&e.includeInApiDefinitions).filter(t=>!e||t.isEnabled(e)).map(e=>e.getToolDefinition())}registerMCPTools(e){let t=Array.from(this.tools.entries()).filter(([e,t])=>!t.includeInApiDefinitions).map(([e,t])=>e);for(let e of t)this.tools.delete(e);this.registerAll(e)}createToolInstance(e,t,n){let r=this.get(e);if(!r)throw Error(`Tool '${e}' is not registered`);return new du(r,r.validateParams(t),n)}isBuiltinTool(e){let t=this.get(e);return t?t.includeInApiDefinitions:!1}isBuiltinRequest(e){return this.isBuiltinTool(e.name)}unregister(e){return this.tools.delete(e)}parse(e,t){let n=this.tools.get(e);return n?n.parse(t):this._genericParse(e,t)}_genericParse(e,t){let n=Jc(t);if(n.rejected)return{phase:`rejected`,toolType:e,data:{},summary:n.userNote?`Rejected \u00b7 "${n.userNote}"`:`Rejected`,...n.userNote!==void 0&&{userNote:n.userNote}};try{let n=JSON.parse(t),r=`success`;return n.status===`error`?r=`error`:n.status===`skipped`&&(r=`skipped`),{phase:r,toolType:n.type??e,data:n,summary:n.message??n.summary??`Completed`,...n.errorMessage!==void 0&&{errorMessage:n.errorMessage}}}catch{}return t.startsWith(`Error:`)?{phase:`error`,toolType:e,data:{},summary:t,errorMessage:t}:{phase:`success`,toolType:e,data:{},summary:`Completed`}}clear(){this.tools.clear()}};const pu=new fu;pu.register(new Nl),pu.register(new Il),pu.register(new Bl),pu.register(new Hl),pu.register(new Gl),pu.register(new ql),pu.register(new Yl),pu.register(new Zl),pu.register(new $l),pu.register(new tu),pu.register(new ru),pu.register(new cu),pu.register(new lu),pu.register(new uu),pu.register(new gl),pu.register(new _l),pu.register(new vl),pu.register(new yl),pu.register(new bl),pu.register(new dl),pu.register(new pl),pu.register(new ml),pu.register(new hl),pu.register(new Qc),pu.register(new $c),pu.register(new el),pu.register(new sl),pu.register(new cl),pu.register(new ll);function mu(){let e=new fu;return e.register(new Nl),e.register(new Il),e.register(new Bl),e.register(new Hl),e.register(new Gl),e.register(new ql),e.register(new Yl),e.register(new Zl),e.register(new $l),e.register(new tu),e.register(new ru),e.register(new cu),e.register(new lu),e.register(new uu),e.register(new gl),e.register(new _l),e.register(new vl),e.register(new yl),e.register(new bl),e.register(new dl),e.register(new pl),e.register(new ml),e.register(new hl),e.register(new Qc),e.register(new $c),e.register(new el),e.register(new sl),e.register(new cl),e.register(new ll),e}function hu(e){let t=e.indexOf(`(`);if(t===-1)return{displayName:e,pattern:null};let n=e.slice(0,t),r=e.lastIndexOf(`)`);if(r===-1||r<=t)return{displayName:e,pattern:``};let i=e.slice(t+1,r).trim();return i===``||i===`*`?{displayName:n,pattern:null}:{displayName:n,pattern:i}}function gu(e,t,n){return e.displayName===t?e.pattern===null?!0:t===`Bash`?vu(e.pattern,n):e.pattern.startsWith(`domain:`)||e.pattern.startsWith(`//`)||e.pattern.startsWith(`~/`)||_u(t)?xu(e.pattern,n):yu(n,e.pattern):!1}function _u(e){return[`Edit`,`Read`,`Delete`,`LS`,`Upload`].includes(e)}function vu(e,t){let n=bu(t),r=n[0]?.trim();return!r||n.length>1?!1:yu(r,e)}function yu(e,t){let n=`^`,r=0;for(;r<t.length;){let e=t[r];e===`*`?t[r+1]===`*`?(n+=`.*`,r+=2):(n+=`.*`,r++):e===`?`?(n+=`.`,r++):(n+=e.replace(/[.+^${}()|\\[\]]/g,`\\$&`),r++)}n+=`$`;try{return new RegExp(n).test(e)}catch{return e===t}}function bu(e){let t=[],n=``,r=!1,i=!1,a=0;for(;a<e.length;){let o=e[a];if(o===`'`&&!i){r=!r,n+=o,a++;continue}if(o===`"`&&!r){i=!i,n+=o,a++;continue}if(r||i){n+=o,a++;continue}if(o===`&`&&e[a+1]===`&`){n.trim()&&t.push(n.trim()),n=``,a+=2;continue}if(o===`|`&&e[a+1]===`|`){n.trim()&&t.push(n.trim()),n=``,a+=2;continue}if(o===`;`){n.trim()&&t.push(n.trim()),n=``,a++;continue}if(o===`|`){n.trim()&&t.push(n.trim()),n=``,a++;continue}n+=o,a++}return n.trim()&&t.push(n.trim()),t}function xu(e,t){let n=e;n=n.replace(/\\/g,`/`);let r=t.replace(/\\/g,`/`);if(n.startsWith(`//`)){let e=n.slice(2);n=/^[A-Za-z]:/.test(e)?e:`/`+e}if(n.startsWith(`~/`)&&(n=(process.env.HOME??process.env.USERPROFILE??``).replace(/\\/g,`/`)+n.slice(1)),n.startsWith(`domain:`)){let e=n.slice(7);try{let t=new URL(r);return t.hostname===e||t.hostname.endsWith(`.`+e)}catch{return r.includes(e)}}return Su(r,n)}function Su(e,t){let n=`^`,r=0;for(;r<t.length;){let e=t[r];if(e===`*`)t[r+1]===`*`?t[r+2]===`/`?(n+=`(?:.*/)?`,r+=3):(n+=`.*`,r+=2):(n+=`[^/]*`,r++);else if(e===`?`)n+=`[^/]`,r++;else if(e===`[`){let e=t.indexOf(`]`,r);e===-1?(n+=`\\[`,r++):(n+=t.slice(r,e+1),r=e+1)}else n+=e.replace(/[.+^${}()|\\]/g,`\\$&`),r++}n+=`$`;try{return new RegExp(n).test(e)}catch{return e===t}}function Cu(e,t){let n=typeof e==`string`?{id:``,type:``,name:e,input:t??{}}:e;if(!pu.isBuiltinRequest(n)){for(let e of Object.values(n.input))if(typeof e==`string`)return e;return``}switch(n.name){case`edit`:case`read_file`:case`delete_file`:case`upload_image`:return n.input.targetFile??``;case`list_dir`:return n.input.relativeWorkspacePath??``;case`bash`:return n.input.command??``;case`navigate_to`:case`new_tab`:case`fetch_url`:return n.input.url??``;case`web_search`:return n.input.searchTerm??``;case`grep`:return n.input.pattern??``;case`file_search`:case`semantic_search_server`:return n.input.query??``;default:return``}}var wu=class{denyRules;askRules;allowRules;safeCommandRules;constructor(e){let{rules:t,cliAllowed:n,cliDenied:r,safeCommandRules:i}=e;this.denyRules=[...(t.deny??[]).map(hu),...(r??[]).map(hu)],this.askRules=(t.ask??[]).map(hu),this.allowRules=[...(t.allow??[]).map(hu),...(n??[]).map(hu)],this.safeCommandRules=(i??[]).map(hu)}evaluate(e,t){for(let n of this.denyRules)if(gu(n,e,t))return`deny`;for(let n of this.askRules)if(gu(n,e,t))return`ask`;for(let n of this.allowRules)if(gu(n,e,t))return`allow`;for(let n of this.safeCommandRules)if(gu(n,e,t))return`allow`;return null}addAllowRule(e){this.allowRules.push(hu(e))}addDenyRule(e){this.denyRules.push(hu(e))}addAskRule(e){this.askRules.push(hu(e))}getAllowRules(){return this.allowRules.map(e=>e.pattern===null?e.displayName:`${e.displayName}(${e.pattern})`)}};const Tu={"--all":`none`,"--branches":`none`,"--tags":`none`,"--remotes":`none`},Eu={"--since":`string`,"--after":`string`,"--until":`string`,"--before":`string`},Du={"--oneline":`none`,"--graph":`none`,"--decorate":`none`,"--no-decorate":`none`,"--date":`string`,"--relative-date":`none`},Ou={"--max-count":`number`,"-n":`number`},ku={"--stat":`none`,"--numstat":`none`,"--shortstat":`none`,"--name-only":`none`,"--name-status":`none`},Au={"--color":`none`,"--no-color":`none`},ju={"--patch":`none`,"-p":`none`,"--no-patch":`none`,"--no-ext-diff":`none`,"-s":`none`},Mu={"--author":`string`,"--committer":`string`,"--grep":`string`},Nu={"git diff":{safeFlags:{...ku,...Au,"--cached":`none`,"--staged":`none`,"--word-diff":`none`,"--check":`none`,"--full-index":`none`,"--diff-algorithm":`string`,"--histogram":`none`,"--patience":`none`,"--minimal":`none`,"--ignore-space-at-eol":`none`,"--ignore-space-change":`none`,"--ignore-all-space":`none`,"--ignore-blank-lines":`none`,"--exit-code":`none`,"--quiet":`none`,"--no-ext-diff":`none`,"--diff-filter":`string`,"--relative":`string`,"-p":`none`,"-u":`none`,"-s":`none`,"-M":`none`,"-C":`none`}},"git log":{safeFlags:{...Du,...Tu,...Eu,...Ou,...ku,...Au,...ju,...Mu,"--abbrev-commit":`none`,"--full-history":`none`,"--first-parent":`none`,"--merges":`none`,"--no-merges":`none`,"--reverse":`none`,"--skip":`number`,"--follow":`none`,"--topo-order":`none`,"--date-order":`none`,"--pretty":`string`,"--format":`string`,"--diff-filter":`string`,"-S":`string`,"-G":`string`}},"git status":{safeFlags:{"--short":`none`,"-s":`none`,"--branch":`none`,"-b":`none`,"--porcelain":`none`,"--long":`none`,"--verbose":`none`,"-v":`none`,"--untracked-files":`string`,"-u":`string`,"--ignored":`none`}},"git show":{safeFlags:{...Du,...ku,...Au,...ju,"--abbrev-commit":`none`,"--pretty":`string`,"--format":`string`,"--quiet":`none`}},"git blame":{safeFlags:{...Au,"-L":`string`,"--porcelain":`none`,"-p":`none`,"--date":`string`,"-w":`none`,"-n":`none`,"-e":`none`,"-s":`none`}},"git branch":{safeFlags:{"-l":`none`,"--list":`none`,"-a":`none`,"--all":`none`,"-r":`none`,"--remotes":`none`,"-v":`none`,"-vv":`none`,"--verbose":`none`,"--color":`none`,"--no-color":`none`,"--show-current":`none`,"--sort":`string`,"--contains":`string`},additionalCommandIsDangerousCallback:(e,t)=>{let n=t.some(e=>e===`-l`||e===`--list`),r=new Set([`--contains`,`--no-contains`,`--points-at`,`--sort`,`--abbrev`,`--merged`,`--no-merged`]),i=0;for(;i<t.length;){let e=t[i];if(e.startsWith(`-`))e.includes(`=`)||r.has(e)?i+=r.has(e)?2:1:i++;else{if(!n)return!0;i++}}return!1}},"git tag":{safeFlags:{"-l":`none`,"--list":`none`,"-n":`number`,"--contains":`string`,"--sort":`string`,"--format":`string`},additionalCommandIsDangerousCallback:(e,t)=>{let n=t.slice(0,t.findIndex(e=>!e.startsWith(`-`)&&e!==`-l`&&e!==`--list`));return!(n.includes(`-l`)||n.includes(`--list`)||t.length===0)}},"git remote":{safeFlags:{"-v":`none`,"--verbose":`none`},additionalCommandIsDangerousCallback:(e,t)=>t.some(e=>e!==`-v`&&e!==`--verbose`)},"git ls-files":{safeFlags:{"--cached":`none`,"-c":`none`,"--others":`none`,"-o":`none`,"--modified":`none`,"-m":`none`,"--deleted":`none`,"-d":`none`,"--ignored":`none`,"--stage":`none`,"--full-name":`none`,"--exclude-standard":`none`,"-z":`none`}},"git rev-parse":{safeFlags:{"--verify":`none`,"--short":`string`,"--abbrev-ref":`none`,"--show-toplevel":`none`,"--show-cdup":`none`,"--show-prefix":`none`,"--git-dir":`none`,"--is-inside-work-tree":`none`}},"git rev-list":{safeFlags:{...Tu,...Eu,...Ou,...Mu,"--count":`none`,"--reverse":`none`,"--first-parent":`none`,"--merges":`none`,"--no-merges":`none`,"--oneline":`none`,"--pretty":`string`,"--format":`string`}},"git describe":{safeFlags:{"--tags":`none`,"--match":`string`,"--long":`none`,"--abbrev":`number`,"--always":`none`,"--exact-match":`none`}},"git stash list":{safeFlags:{...Du,...Ou}},"git stash show":{safeFlags:{...ku,...Au,...ju}},"git merge-base":{safeFlags:{"--is-ancestor":`none`,"--fork-point":`none`,"--octopus":`none`,"--all":`none`}},"git cat-file":{safeFlags:{"-t":`none`,"-s":`none`,"-p":`none`,"-e":`none`}},"git for-each-ref":{safeFlags:{"--format":`string`,"--sort":`string`,"--count":`number`,"--contains":`string`}},"git worktree list":{safeFlags:{"--porcelain":`none`,"-v":`none`,"--verbose":`none`}},"git config --get":{safeFlags:{"--local":`none`,"--global":`none`,"--system":`none`}},"gh pr view":{safeFlags:{"--json":`string`,"--comments":`none`,"--repo":`string`,"-R":`string`}},"gh pr list":{safeFlags:{"--state":`string`,"-s":`string`,"--author":`string`,"--label":`string`,"--limit":`number`,"-L":`number`,"--json":`string`,"--repo":`string`,"-R":`string`}},"gh pr diff":{safeFlags:{"--color":`string`,"--name-only":`none`,"--repo":`string`,"-R":`string`}},"gh pr checks":{safeFlags:{"--json":`string`,"--repo":`string`,"-R":`string`}},"gh pr status":{safeFlags:{"--json":`string`,"--repo":`string`,"-R":`string`}},"gh issue view":{safeFlags:{"--json":`string`,"--comments":`none`,"--repo":`string`,"-R":`string`}},"gh issue list":{safeFlags:{"--state":`string`,"-s":`string`,"--label":`string`,"--limit":`number`,"-L":`number`,"--json":`string`,"--repo":`string`,"-R":`string`}},"gh repo view":{safeFlags:{"--json":`string`}},"gh run list":{safeFlags:{"--branch":`string`,"--status":`string`,"--workflow":`string`,"--limit":`number`,"-L":`number`,"--json":`string`,"--repo":`string`,"-R":`string`}},"gh run view":{safeFlags:{"--log":`none`,"--log-failed":`none`,"--json":`string`,"--repo":`string`,"-R":`string`,"--job":`string`}},"gh auth status":{safeFlags:{"--active":`none`,"--hostname":`string`,"--json":`string`}},"docker logs":{safeFlags:{"--follow":`none`,"-f":`none`,"--tail":`string`,"-n":`string`,"--timestamps":`none`,"-t":`none`}},"docker inspect":{safeFlags:{"--format":`string`,"-f":`string`,"--type":`string`}},rg:{safeFlags:{"-e":`string`,"-i":`none`,"--ignore-case":`none`,"-F":`none`,"--fixed-strings":`none`,"-w":`none`,"-c":`none`,"--count":`none`,"-l":`none`,"--files-with-matches":`none`,"-n":`none`,"--line-number":`none`,"-A":`number`,"-B":`number`,"-C":`number`,"-g":`string`,"--glob":`string`,"-t":`string`,"--type":`string`,"--hidden":`none`,"-m":`number`,"--max-count":`number`,"--color":`string`,"--json":`none`,"--help":`none`,"--version":`none`}}},Pu=[`docker ps`,`docker images`,`node -v`,`node --version`,`python --version`,`python3 --version`,`npm --version`,`bun --version`,`git --version`,`which`,`whoami`,`pwd`,`date`,`uname`,`uname -a`,`cat /etc/os-release`,`env`,`printenv`,`echo`,`true`,`false`,`test`];function Fu(){let e=[];for(let t of Object.keys(Nu))e.push(`Bash(${t} *)`),e.push(`Bash(${t})`);for(let t of Pu)e.push(`Bash(${t} *)`),e.push(`Bash(${t})`);return e}var Iu=class extends Error{constructor(e){super(e),this.name=`StagehandDomProcessError`}},Lu=class extends Error{constructor(e){super(e),this.name=`StagehandElementNotFoundError`}},Ru=class extends Error{targetUrl;constructor(e,t){super(e),this.targetUrl=t,this.name=`StagehandIframeError`}};const zu=new Set([160,8239,8199,65279]);function Bu(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(!(i>=57344&&i<=63743)){if(zu.has(i)){n||=(t+=` `,!0);continue}t+=e[r],n=e[r]===` `}}return t.trim()}function Vu(e,t=0){let n=` `.repeat(t),r=e.encodedId??e.nodeId,i=e.name?`: ${Bu(e.name)}`:``;return`${n}[${r}] ${e.role}${i}\n`+(e.children?.map(e=>Vu(e,t+1)).join(``)??``)}const Hu=new Map,Uu=e=>{let t=Hu.get(e);return t||(t=e.toLowerCase(),Hu.set(e,t),Hu.size>2048&&Hu.delete(Hu.keys().next().value)),t};async function Wu(e,t,n){let r;if(!n||n===t.mainFrame())r=await t.context().newCDPSession(t);else try{r=await t.context().newCDPSession(n)}catch{r=await t.context().newCDPSession(t)}await r.send(`DOM.enable`,{});try{let{root:i}=await r.send(`DOM.getDocument`,{depth:-1,pierce:!0}),a=i,o=n&&await qu(t,n);if(n&&n!==t.mainFrame()&&r===await t.context().newCDPSession(t)){let t=o,{backendNodeId:n}=await r.send(`DOM.getFrameOwner`,{frameId:t}),s,c=t=>e?t.backendNodeId===n?(s=t,!0):!!(t.shadowRoots?.some(c)||t.children?.some(c)||t.contentDocument&&c(t.contentDocument)):t.backendNodeId===n?(s=t,!0):(t.children?.some(c)??!1)||(t.contentDocument?c(t.contentDocument):!1);if(!c(i)||!s?.contentDocument)throw Error(`iframe element or its contentDocument not found`);a=s.contentDocument,o=s.contentDocument.frameId??t}let s={},c={},l=[{node:a,path:``,fid:o}],u=new Set,d=(e,t)=>e.endsWith(`//`)?`${e}${t}`:`${e}/${t}`;for(;l.length;){let{node:t,path:n,fid:r}=l.pop();if(!t.backendNodeId)continue;let i=`${r??0}-${t.backendNodeId}`;if(u.has(i))continue;if(u.add(i),s[i]=Uu(String(t.nodeName||``)),c[i]=n,Uu(t.nodeName||``)===`iframe`&&t.contentDocument){let e=t.contentDocument.frameId??r;l.push({node:t.contentDocument,path:``,fid:e})}if(t.shadowRoots?.length&&e)for(let e of t.shadowRoots)l.push({node:e,path:`${n}//`,fid:r});let a=t.children??[];if(a.length){let e=[],t={};for(let n of a){let r=Uu(String(n.nodeName)),i=`${n.nodeType}:${r}`,a=t[i]=(t[i]??0)+1;n.nodeType===3?e.push(`text()[${a}]`):n.nodeType===8?e.push(`comment()[${a}]`):e.push(r.includes(`:`)?`*[name()='${r}'][${a}]`:`${r}[${a}]`)}for(let t=a.length-1;t>=0;t--)l.push({node:a[t],path:d(n,e[t]),fid:r})}}return{tagNameMap:s,xpathMap:c}}finally{await r.send(`DOM.disable`,{})}}async function Gu(e,t){if(!e.nodeId||+e.nodeId<0)return null;if(!e.children?.length)return e.role===`generic`||e.role===`none`?null:e;let n=(await Promise.all(e.children.map(e=>Gu(e,t)))).filter(Boolean);if(e.role===`generic`||e.role===`none`){if(n.length===1)return n[0];if(n.length===0)return null}if((e.role===`generic`||e.role===`none`)&&e.encodedId!==void 0){let n=t[e.encodedId];n&&(e.role=n)}e.role===`combobox`&&e.encodedId!==void 0&&t[e.encodedId]===`select`&&(e.role=`select`);let r=td(e,n);return!r.length&&(e.role===`generic`||e.role===`none`)?null:{...e,children:r}}async function Ku(e,t,n,r){let i={},a=new Map,o=[],s=e=>e.role!==`none`&&e.role!==`generic`&&e.role!==`InlineTextBox`,c=new Map;for(let e of Object.keys(t)){let[,t]=e.split(`-`),n=c.get(+t)??[];n.push(e),c.set(+t,n)}for(let t of e){if(!t.nodeId||+t.nodeId<0)continue;let e=nd(t);if(!(t.name?.trim()||t.childIds?.length||s(t)))continue;let n;if(t.backendDOMNodeId!==void 0){let e=c.get(t.backendDOMNodeId)??[];e.length===1&&(n=e[0])}e&&n&&(i[n]=e),a.set(t.nodeId,{encodedId:n,role:t.role,nodeId:t.nodeId,...t.name&&{name:t.name},...t.description&&{description:t.description},...t.value&&{value:t.value},...t.backendDOMNodeId!==void 0&&{backendDOMNodeId:t.backendDOMNodeId}})}for(let t of e){if(t.role===`Iframe`&&o.push({role:t.role,nodeId:t.nodeId}),!t.parentId||!t.nodeId)continue;let e=a.get(t.parentId),n=a.get(t.nodeId);e&&n&&(e.children??=[]).push(n)}let l=e.filter(e=>!e.parentId&&e.nodeId&&a.has(e.nodeId)).map(e=>e.nodeId&&a.get(e.nodeId)).filter(Boolean),u=(await Promise.all(l.map(e=>Gu(e,t)))).filter(Boolean);return{tree:u,simplified:u.map(Vu).join(`
77
+ `)}))}async execute(e,t){let{shellId:n,filter:r}=e;if(!n)throw Error(`shellId parameter is required for bash_output`);let i=t.terminalService,a=parseInt(n),o=i.getLiveOutput?.(a);if(o){let e=[o];return r&&(e=this._applyFilter(e,r)),{type:`bash_output`,terminalId:n,outputs:e,totalOutputs:1}}let s=i.getOutput(a);return r&&(s=this._applyFilter(s,r)),{type:`bash_output`,terminalId:n,outputs:s,totalOutputs:s.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`bash_output`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return{phase:`success`,toolType:`bash_output`,data:t,summary:`Retrieved ${t.totalOutputs??t.outputs?.length??0} lines`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`bash_output`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`bash_output`,data:{},summary:`Retrieved`}}},uu=class e extends jl{name=`kill_shell`;displayName=`KillShell`;description=`Kills a running background bash shell by its ID. Use this tool when you need to terminate a long-running shell. Shell IDs can be found using the /tasks command.`;static Parameters=tc({shellId:Wc().describe(`The ID of the background shell to kill`)});parameters=e.Parameters;async execute(e,t){let{shellId:n}=e;if(!n)throw Error(`shellId parameter is required for kill_shell`);let r=t.terminalService,i=parseInt(n),a=await r.stopCommand(i);return r.closeTerminal&&await r.closeTerminal(i),{type:`kill_shell`,shellId:n,success:a}}format(e,t){return JSON.stringify({...e,status:e.success?`success`:`failure`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`kill_shell`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e);return{phase:t.success?`success`:`error`,toolType:`kill_shell`,data:t,summary:t.success?`Killed shell ${t.shellId}`:`Failed to kill shell ${t.shellId}`}}catch{}return e.startsWith(`Error:`)?{phase:`error`,toolType:`kill_shell`,data:{},summary:e,errorMessage:e}:{phase:`success`,toolType:`kill_shell`,data:{},summary:`Shell killed`}}},du=class{tool;context;params;_prepareResult=null;_executionResult=null;constructor(e,t,n){this.tool=e,this.params=t,this.context=n}getTool(){return this.tool}getParams(){return this.params}mergeParams(e){this.params={...this.params,...e}}getContext(){return this.context}getPrepareResult(){return this._prepareResult}getExecutionResult(){return this._executionResult}async prepare(){return this._prepareResult=await this.tool.prepare(this.params,this.context),this._prepareResult}needsPermission(){return this._prepareResult?.skipPermission?!1:this.tool.needsPermission(this.params,this.context,this._prepareResult)}async execute(){return this._executionResult=await this.tool.execute(this.params,this.context,this._prepareResult),this._executionResult}formatResult(){if(this._executionResult===null)throw Error(`Cannot format result before execution completes`);return this.tool.format(this._executionResult,this.params)}async executeWithPermission(e){if(await this.prepare(),this.needsPermission()){if(!e)throw Error(`Permission check required but no permission callback provided`);if(!await e())throw Error(`Permission denied`)}return await this.execute(),this.formatResult()}},fu=class{tools;context;constructor(){this.tools=new Map}register(e){if(this.tools.has(e.name))throw Error(`Tool '${e.name}' is already registered`);this.tools.set(e.name,e)}registerAll(e){for(let t of e)this.register(t)}get(e){return this.tools.get(e)}has(e){return this.tools.has(e)}getToolNames(){return Array.from(this.tools.keys())}getAllTools(){return Array.from(this.tools.values())}setContext(e){this.context=e}getApiToolDefinitions(e){let t=e??this.context;return Array.from(this.tools.values()).filter(e=>e.includeInApiDefinitions).filter(e=>!t||e.isEnabled(t)).map(e=>e.getToolDefinition())}getMcpToolDefinitions(){return Array.from(this.tools.values()).filter(e=>!e.includeInApiDefinitions).map(e=>e.getToolDefinition())}getReadonlyToolDefinitions(e){return Array.from(this.tools.values()).filter(e=>e.isReadonly&&e.includeInApiDefinitions).filter(t=>!e||t.isEnabled(e)).map(e=>e.getToolDefinition())}registerMCPTools(e){let t=Array.from(this.tools.entries()).filter(([e,t])=>!t.includeInApiDefinitions).map(([e,t])=>e);for(let e of t)this.tools.delete(e);this.registerAll(e)}createToolInstance(e,t,n){let r=this.get(e);if(!r)throw Error(`Tool '${e}' is not registered`);return new du(r,r.validateParams(t),n)}isBuiltinTool(e){let t=this.get(e);return t?t.includeInApiDefinitions:!1}isBuiltinRequest(e){return this.isBuiltinTool(e.name)}unregister(e){return this.tools.delete(e)}parse(e,t){let n=this.tools.get(e);return n?n.parse(t):this._genericParse(e,t)}_genericParse(e,t){let n=Jc(t);if(n.rejected)return{phase:`rejected`,toolType:e,data:{},summary:n.userNote?`Rejected \u00b7 "${n.userNote}"`:`Rejected`,...n.userNote!==void 0&&{userNote:n.userNote}};try{let n=JSON.parse(t),r=`success`;return n.status===`error`?r=`error`:n.status===`skipped`&&(r=`skipped`),{phase:r,toolType:n.type??e,data:n,summary:n.message??n.summary??`Completed`,...n.errorMessage!==void 0&&{errorMessage:n.errorMessage}}}catch{}return t.startsWith(`Error:`)?{phase:`error`,toolType:e,data:{},summary:t,errorMessage:t}:{phase:`success`,toolType:e,data:{},summary:`Completed`}}clear(){this.tools.clear()}};const pu=new fu;pu.register(new Nl),pu.register(new Il),pu.register(new Bl),pu.register(new Hl),pu.register(new Gl),pu.register(new ql),pu.register(new Yl),pu.register(new Zl),pu.register(new $l),pu.register(new tu),pu.register(new ru),pu.register(new cu),pu.register(new lu),pu.register(new uu),pu.register(new gl),pu.register(new _l),pu.register(new vl),pu.register(new yl),pu.register(new bl),pu.register(new dl),pu.register(new pl),pu.register(new ml),pu.register(new hl),pu.register(new Qc),pu.register(new $c),pu.register(new el),pu.register(new sl),pu.register(new cl),pu.register(new ll);function mu(){let e=new fu;return e.register(new Nl),e.register(new Il),e.register(new Bl),e.register(new Hl),e.register(new Gl),e.register(new ql),e.register(new Yl),e.register(new Zl),e.register(new $l),e.register(new tu),e.register(new ru),e.register(new cu),e.register(new lu),e.register(new uu),e.register(new gl),e.register(new _l),e.register(new vl),e.register(new yl),e.register(new bl),e.register(new dl),e.register(new pl),e.register(new ml),e.register(new hl),e.register(new Qc),e.register(new $c),e.register(new el),e.register(new sl),e.register(new cl),e.register(new ll),e}function hu(e){let t=e.indexOf(`(`);if(t===-1)return{displayName:e,pattern:null};let n=e.slice(0,t),r=e.lastIndexOf(`)`);if(r===-1||r<=t)return{displayName:e,pattern:``};let i=e.slice(t+1,r).trim();return i===``||i===`*`?{displayName:n,pattern:null}:{displayName:n,pattern:i}}function gu(e,t,n){return e.displayName===t?e.pattern===null?!0:t===`Bash`?vu(e.pattern,n):e.pattern.startsWith(`domain:`)||e.pattern.startsWith(`//`)||e.pattern.startsWith(`~/`)||_u(t)?xu(e.pattern,n):yu(n,e.pattern):!1}function _u(e){return[`Edit`,`Read`,`Delete`,`LS`,`Upload`].includes(e)}function vu(e,t){let n=bu(t),r=n[0]?.trim();return!r||n.length>1?!1:yu(r,e)}function yu(e,t){let n=`^`,r=0;for(;r<t.length;){let e=t[r];e===`*`?t[r+1]===`*`?(n+=`.*`,r+=2):(n+=`.*`,r++):e===`?`?(n+=`.`,r++):(n+=e.replace(/[.+^${}()|\\[\]]/g,`\\$&`),r++)}n+=`$`;try{return new RegExp(n).test(e)}catch{return e===t}}function bu(e){let t=[],n=``,r=!1,i=!1,a=0;for(;a<e.length;){let o=e[a];if(o===`'`&&!i){r=!r,n+=o,a++;continue}if(o===`"`&&!r){i=!i,n+=o,a++;continue}if(r||i){n+=o,a++;continue}if(o===`&`&&e[a+1]===`&`){n.trim()&&t.push(n.trim()),n=``,a+=2;continue}if(o===`|`&&e[a+1]===`|`){n.trim()&&t.push(n.trim()),n=``,a+=2;continue}if(o===`;`){n.trim()&&t.push(n.trim()),n=``,a++;continue}if(o===`|`){n.trim()&&t.push(n.trim()),n=``,a++;continue}n+=o,a++}return n.trim()&&t.push(n.trim()),t}function xu(e,t){let n=e;n=n.replace(/\\/g,`/`);let r=t.replace(/\\/g,`/`);if(n.startsWith(`//`)){let e=n.slice(2);n=/^[A-Za-z]:/.test(e)?e:`/`+e}if(n.startsWith(`~/`)&&(n=(process.env.HOME??process.env.USERPROFILE??``).replace(/\\/g,`/`)+n.slice(1)),n.startsWith(`domain:`)){let e=n.slice(7);try{let t=new URL(r);return t.hostname===e||t.hostname.endsWith(`.`+e)}catch{return r.includes(e)}}return Su(r,n)}function Su(e,t){let n=`^`,r=0;for(;r<t.length;){let e=t[r];if(e===`*`)t[r+1]===`*`?t[r+2]===`/`?(n+=`(?:.*/)?`,r+=3):(n+=`.*`,r+=2):(n+=`[^/]*`,r++);else if(e===`?`)n+=`[^/]`,r++;else if(e===`[`){let e=t.indexOf(`]`,r);e===-1?(n+=`\\[`,r++):(n+=t.slice(r,e+1),r=e+1)}else n+=e.replace(/[.+^${}()|\\]/g,`\\$&`),r++}n+=`$`;try{return new RegExp(n).test(e)}catch{return e===t}}function Cu(e,t){let n=typeof e==`string`?{id:``,type:``,name:e,input:t??{}}:e;if(!pu.isBuiltinRequest(n)){for(let e of Object.values(n.input))if(typeof e==`string`)return e;return``}switch(n.name){case`edit`:case`read_file`:case`delete_file`:case`upload_image`:return n.input.targetFile??``;case`list_dir`:return n.input.relativeWorkspacePath??``;case`bash`:return n.input.command??``;case`navigate_to`:case`new_tab`:case`web_fetch`:return n.input.url??``;case`web_search`:return n.input.searchTerm??``;case`grep`:return n.input.pattern??``;case`file_search`:case`semantic_search_server`:return n.input.query??``;default:return``}}var wu=class{denyRules;askRules;allowRules;safeCommandRules;constructor(e){let{rules:t,cliAllowed:n,cliDenied:r,safeCommandRules:i}=e;this.denyRules=[...(t.deny??[]).map(hu),...(r??[]).map(hu)],this.askRules=(t.ask??[]).map(hu),this.allowRules=[...(t.allow??[]).map(hu),...(n??[]).map(hu)],this.safeCommandRules=(i??[]).map(hu)}evaluate(e,t){for(let n of this.denyRules)if(gu(n,e,t))return`deny`;for(let n of this.askRules)if(gu(n,e,t))return`ask`;for(let n of this.allowRules)if(gu(n,e,t))return`allow`;for(let n of this.safeCommandRules)if(gu(n,e,t))return`allow`;return null}addAllowRule(e){this.allowRules.push(hu(e))}addDenyRule(e){this.denyRules.push(hu(e))}addAskRule(e){this.askRules.push(hu(e))}getAllowRules(){return this.allowRules.map(e=>e.pattern===null?e.displayName:`${e.displayName}(${e.pattern})`)}};const Tu={"--all":`none`,"--branches":`none`,"--tags":`none`,"--remotes":`none`},Eu={"--since":`string`,"--after":`string`,"--until":`string`,"--before":`string`},Du={"--oneline":`none`,"--graph":`none`,"--decorate":`none`,"--no-decorate":`none`,"--date":`string`,"--relative-date":`none`},Ou={"--max-count":`number`,"-n":`number`},ku={"--stat":`none`,"--numstat":`none`,"--shortstat":`none`,"--name-only":`none`,"--name-status":`none`},Au={"--color":`none`,"--no-color":`none`},ju={"--patch":`none`,"-p":`none`,"--no-patch":`none`,"--no-ext-diff":`none`,"-s":`none`},Mu={"--author":`string`,"--committer":`string`,"--grep":`string`},Nu={"git diff":{safeFlags:{...ku,...Au,"--cached":`none`,"--staged":`none`,"--word-diff":`none`,"--check":`none`,"--full-index":`none`,"--diff-algorithm":`string`,"--histogram":`none`,"--patience":`none`,"--minimal":`none`,"--ignore-space-at-eol":`none`,"--ignore-space-change":`none`,"--ignore-all-space":`none`,"--ignore-blank-lines":`none`,"--exit-code":`none`,"--quiet":`none`,"--no-ext-diff":`none`,"--diff-filter":`string`,"--relative":`string`,"-p":`none`,"-u":`none`,"-s":`none`,"-M":`none`,"-C":`none`}},"git log":{safeFlags:{...Du,...Tu,...Eu,...Ou,...ku,...Au,...ju,...Mu,"--abbrev-commit":`none`,"--full-history":`none`,"--first-parent":`none`,"--merges":`none`,"--no-merges":`none`,"--reverse":`none`,"--skip":`number`,"--follow":`none`,"--topo-order":`none`,"--date-order":`none`,"--pretty":`string`,"--format":`string`,"--diff-filter":`string`,"-S":`string`,"-G":`string`}},"git status":{safeFlags:{"--short":`none`,"-s":`none`,"--branch":`none`,"-b":`none`,"--porcelain":`none`,"--long":`none`,"--verbose":`none`,"-v":`none`,"--untracked-files":`string`,"-u":`string`,"--ignored":`none`}},"git show":{safeFlags:{...Du,...ku,...Au,...ju,"--abbrev-commit":`none`,"--pretty":`string`,"--format":`string`,"--quiet":`none`}},"git blame":{safeFlags:{...Au,"-L":`string`,"--porcelain":`none`,"-p":`none`,"--date":`string`,"-w":`none`,"-n":`none`,"-e":`none`,"-s":`none`}},"git branch":{safeFlags:{"-l":`none`,"--list":`none`,"-a":`none`,"--all":`none`,"-r":`none`,"--remotes":`none`,"-v":`none`,"-vv":`none`,"--verbose":`none`,"--color":`none`,"--no-color":`none`,"--show-current":`none`,"--sort":`string`,"--contains":`string`},additionalCommandIsDangerousCallback:(e,t)=>{let n=t.some(e=>e===`-l`||e===`--list`),r=new Set([`--contains`,`--no-contains`,`--points-at`,`--sort`,`--abbrev`,`--merged`,`--no-merged`]),i=0;for(;i<t.length;){let e=t[i];if(e.startsWith(`-`))e.includes(`=`)||r.has(e)?i+=r.has(e)?2:1:i++;else{if(!n)return!0;i++}}return!1}},"git tag":{safeFlags:{"-l":`none`,"--list":`none`,"-n":`number`,"--contains":`string`,"--sort":`string`,"--format":`string`},additionalCommandIsDangerousCallback:(e,t)=>{let n=t.slice(0,t.findIndex(e=>!e.startsWith(`-`)&&e!==`-l`&&e!==`--list`));return!(n.includes(`-l`)||n.includes(`--list`)||t.length===0)}},"git remote":{safeFlags:{"-v":`none`,"--verbose":`none`},additionalCommandIsDangerousCallback:(e,t)=>t.some(e=>e!==`-v`&&e!==`--verbose`)},"git ls-files":{safeFlags:{"--cached":`none`,"-c":`none`,"--others":`none`,"-o":`none`,"--modified":`none`,"-m":`none`,"--deleted":`none`,"-d":`none`,"--ignored":`none`,"--stage":`none`,"--full-name":`none`,"--exclude-standard":`none`,"-z":`none`}},"git rev-parse":{safeFlags:{"--verify":`none`,"--short":`string`,"--abbrev-ref":`none`,"--show-toplevel":`none`,"--show-cdup":`none`,"--show-prefix":`none`,"--git-dir":`none`,"--is-inside-work-tree":`none`}},"git rev-list":{safeFlags:{...Tu,...Eu,...Ou,...Mu,"--count":`none`,"--reverse":`none`,"--first-parent":`none`,"--merges":`none`,"--no-merges":`none`,"--oneline":`none`,"--pretty":`string`,"--format":`string`}},"git describe":{safeFlags:{"--tags":`none`,"--match":`string`,"--long":`none`,"--abbrev":`number`,"--always":`none`,"--exact-match":`none`}},"git stash list":{safeFlags:{...Du,...Ou}},"git stash show":{safeFlags:{...ku,...Au,...ju}},"git merge-base":{safeFlags:{"--is-ancestor":`none`,"--fork-point":`none`,"--octopus":`none`,"--all":`none`}},"git cat-file":{safeFlags:{"-t":`none`,"-s":`none`,"-p":`none`,"-e":`none`}},"git for-each-ref":{safeFlags:{"--format":`string`,"--sort":`string`,"--count":`number`,"--contains":`string`}},"git worktree list":{safeFlags:{"--porcelain":`none`,"-v":`none`,"--verbose":`none`}},"git config --get":{safeFlags:{"--local":`none`,"--global":`none`,"--system":`none`}},"gh pr view":{safeFlags:{"--json":`string`,"--comments":`none`,"--repo":`string`,"-R":`string`}},"gh pr list":{safeFlags:{"--state":`string`,"-s":`string`,"--author":`string`,"--label":`string`,"--limit":`number`,"-L":`number`,"--json":`string`,"--repo":`string`,"-R":`string`}},"gh pr diff":{safeFlags:{"--color":`string`,"--name-only":`none`,"--repo":`string`,"-R":`string`}},"gh pr checks":{safeFlags:{"--json":`string`,"--repo":`string`,"-R":`string`}},"gh pr status":{safeFlags:{"--json":`string`,"--repo":`string`,"-R":`string`}},"gh issue view":{safeFlags:{"--json":`string`,"--comments":`none`,"--repo":`string`,"-R":`string`}},"gh issue list":{safeFlags:{"--state":`string`,"-s":`string`,"--label":`string`,"--limit":`number`,"-L":`number`,"--json":`string`,"--repo":`string`,"-R":`string`}},"gh repo view":{safeFlags:{"--json":`string`}},"gh run list":{safeFlags:{"--branch":`string`,"--status":`string`,"--workflow":`string`,"--limit":`number`,"-L":`number`,"--json":`string`,"--repo":`string`,"-R":`string`}},"gh run view":{safeFlags:{"--log":`none`,"--log-failed":`none`,"--json":`string`,"--repo":`string`,"-R":`string`,"--job":`string`}},"gh auth status":{safeFlags:{"--active":`none`,"--hostname":`string`,"--json":`string`}},"docker logs":{safeFlags:{"--follow":`none`,"-f":`none`,"--tail":`string`,"-n":`string`,"--timestamps":`none`,"-t":`none`}},"docker inspect":{safeFlags:{"--format":`string`,"-f":`string`,"--type":`string`}},rg:{safeFlags:{"-e":`string`,"-i":`none`,"--ignore-case":`none`,"-F":`none`,"--fixed-strings":`none`,"-w":`none`,"-c":`none`,"--count":`none`,"-l":`none`,"--files-with-matches":`none`,"-n":`none`,"--line-number":`none`,"-A":`number`,"-B":`number`,"-C":`number`,"-g":`string`,"--glob":`string`,"-t":`string`,"--type":`string`,"--hidden":`none`,"-m":`number`,"--max-count":`number`,"--color":`string`,"--json":`none`,"--help":`none`,"--version":`none`}}},Pu=[`docker ps`,`docker images`,`node -v`,`node --version`,`python --version`,`python3 --version`,`npm --version`,`bun --version`,`git --version`,`which`,`whoami`,`pwd`,`date`,`uname`,`uname -a`,`cat /etc/os-release`,`env`,`printenv`,`echo`,`true`,`false`,`test`];function Fu(){let e=[];for(let t of Object.keys(Nu))e.push(`Bash(${t} *)`),e.push(`Bash(${t})`);for(let t of Pu)e.push(`Bash(${t} *)`),e.push(`Bash(${t})`);return e}var Iu=class extends Error{constructor(e){super(e),this.name=`StagehandDomProcessError`}},Lu=class extends Error{constructor(e){super(e),this.name=`StagehandElementNotFoundError`}},Ru=class extends Error{targetUrl;constructor(e,t){super(e),this.targetUrl=t,this.name=`StagehandIframeError`}};const zu=new Set([160,8239,8199,65279]);function Bu(e){let t=``,n=!1;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);if(!(i>=57344&&i<=63743)){if(zu.has(i)){n||=(t+=` `,!0);continue}t+=e[r],n=e[r]===` `}}return t.trim()}function Vu(e,t=0){let n=` `.repeat(t),r=e.encodedId??e.nodeId,i=e.name?`: ${Bu(e.name)}`:``;return`${n}[${r}] ${e.role}${i}\n`+(e.children?.map(e=>Vu(e,t+1)).join(``)??``)}const Hu=new Map,Uu=e=>{let t=Hu.get(e);return t||(t=e.toLowerCase(),Hu.set(e,t),Hu.size>2048&&Hu.delete(Hu.keys().next().value)),t};async function Wu(e,t,n){let r;if(!n||n===t.mainFrame())r=await t.context().newCDPSession(t);else try{r=await t.context().newCDPSession(n)}catch{r=await t.context().newCDPSession(t)}await r.send(`DOM.enable`,{});try{let{root:i}=await r.send(`DOM.getDocument`,{depth:-1,pierce:!0}),a=i,o=n&&await qu(t,n);if(n&&n!==t.mainFrame()&&r===await t.context().newCDPSession(t)){let t=o,{backendNodeId:n}=await r.send(`DOM.getFrameOwner`,{frameId:t}),s,c=t=>e?t.backendNodeId===n?(s=t,!0):!!(t.shadowRoots?.some(c)||t.children?.some(c)||t.contentDocument&&c(t.contentDocument)):t.backendNodeId===n?(s=t,!0):(t.children?.some(c)??!1)||(t.contentDocument?c(t.contentDocument):!1);if(!c(i)||!s?.contentDocument)throw Error(`iframe element or its contentDocument not found`);a=s.contentDocument,o=s.contentDocument.frameId??t}let s={},c={},l=[{node:a,path:``,fid:o}],u=new Set,d=(e,t)=>e.endsWith(`//`)?`${e}${t}`:`${e}/${t}`;for(;l.length;){let{node:t,path:n,fid:r}=l.pop();if(!t.backendNodeId)continue;let i=`${r??0}-${t.backendNodeId}`;if(u.has(i))continue;if(u.add(i),s[i]=Uu(String(t.nodeName||``)),c[i]=n,Uu(t.nodeName||``)===`iframe`&&t.contentDocument){let e=t.contentDocument.frameId??r;l.push({node:t.contentDocument,path:``,fid:e})}if(t.shadowRoots?.length&&e)for(let e of t.shadowRoots)l.push({node:e,path:`${n}//`,fid:r});let a=t.children??[];if(a.length){let e=[],t={};for(let n of a){let r=Uu(String(n.nodeName)),i=`${n.nodeType}:${r}`,a=t[i]=(t[i]??0)+1;n.nodeType===3?e.push(`text()[${a}]`):n.nodeType===8?e.push(`comment()[${a}]`):e.push(r.includes(`:`)?`*[name()='${r}'][${a}]`:`${r}[${a}]`)}for(let t=a.length-1;t>=0;t--)l.push({node:a[t],path:d(n,e[t]),fid:r})}}return{tagNameMap:s,xpathMap:c}}finally{await r.send(`DOM.disable`,{})}}async function Gu(e,t){if(!e.nodeId||+e.nodeId<0)return null;if(!e.children?.length)return e.role===`generic`||e.role===`none`?null:e;let n=(await Promise.all(e.children.map(e=>Gu(e,t)))).filter(Boolean);if(e.role===`generic`||e.role===`none`){if(n.length===1)return n[0];if(n.length===0)return null}if((e.role===`generic`||e.role===`none`)&&e.encodedId!==void 0){let n=t[e.encodedId];n&&(e.role=n)}e.role===`combobox`&&e.encodedId!==void 0&&t[e.encodedId]===`select`&&(e.role=`select`);let r=td(e,n);return!r.length&&(e.role===`generic`||e.role===`none`)?null:{...e,children:r}}async function Ku(e,t,n,r){let i={},a=new Map,o=[],s=e=>e.role!==`none`&&e.role!==`generic`&&e.role!==`InlineTextBox`,c=new Map;for(let e of Object.keys(t)){let[,t]=e.split(`-`),n=c.get(+t)??[];n.push(e),c.set(+t,n)}for(let t of e){if(!t.nodeId||+t.nodeId<0)continue;let e=nd(t);if(!(t.name?.trim()||t.childIds?.length||s(t)))continue;let n;if(t.backendDOMNodeId!==void 0){let e=c.get(t.backendDOMNodeId)??[];e.length===1&&(n=e[0])}e&&n&&(i[n]=e),a.set(t.nodeId,{encodedId:n,role:t.role,nodeId:t.nodeId,...t.name&&{name:t.name},...t.description&&{description:t.description},...t.value&&{value:t.value},...t.backendDOMNodeId!==void 0&&{backendDOMNodeId:t.backendDOMNodeId}})}for(let t of e){if(t.role===`Iframe`&&o.push({role:t.role,nodeId:t.nodeId}),!t.parentId||!t.nodeId)continue;let e=a.get(t.parentId),n=a.get(t.nodeId);e&&n&&(e.children??=[]).push(n)}let l=e.filter(e=>!e.parentId&&e.nodeId&&a.has(e.nodeId)).map(e=>e.nodeId&&a.get(e.nodeId)).filter(Boolean),u=(await Promise.all(l.map(e=>Gu(e,t)))).filter(Boolean);return{tree:u,simplified:u.map(Vu).join(`
78
78
  `),iframes:o,idToUrl:i,xpathMap:r??{}}}async function qu(e,t){if(!t||t===e.mainFrame())return;let{frameTree:n}=await(await e.context().newCDPSession(e)).send(`Page.getFrameTree`),r=t.url(),i=0;for(let e=t.parentFrame();e;e=e.parentFrame())i++;let a=e=>e.url+(e.urlFragment??``),o=(e,t=0)=>{if(t===i&&a(e.frame)===r)return e.frame.id;for(let n of e.childFrames??[]){let e=o(n,t+1);if(e)return e}},s=o(n);if(s)return s;try{let{frameTree:n}=await(await e.context().newCDPSession(t)).send(`Page.getFrameTree`);return n.frame.id}catch(e){throw new Ru(r,String(e))}}async function Ju(e,t,n,r,i){let{tagNameMap:a,xpathMap:o}=await Wu(e,t,i),s=await t.context().newCDPSession(t);await s.send(`Accessibility.enable`,{});try{let e={};if(i&&i!==t.mainFrame()){let r=!0;try{await t.context().newCDPSession(i)}catch{r=!1}if(r)n({message:`OOPIF iframe: starting new CDP session`,level:1}),e={};else{let r=await qu(t,i);n({message:`same-proc iframe: frameId=${r}. Using existing CDP session.`,level:1}),r&&(e={frameId:r})}}let{nodes:c}=await s.send(`Accessibility.getFullAXTree`,e),l=await Zu(t,i),u=c;r&&(u=await Yu(t,c,r,i));let d=Date.now(),f=await Ku(Xu(u,l),a,n,o);return n({category:`observation`,message:`got accessibility tree in ${Date.now()-d} ms`,level:1}),f}finally{await s.send(`Accessibility.disable`,{})}}async function Yu(e,t,n,r){let i=await Qu(e,n,r),{node:a}=await(await e.context().newCDPSession(e)).send(`DOM.describeNode`,{objectId:i??void 0});if(!a?.backendNodeId)throw new Iu(`Unable to resolve backendNodeId for "${n}"`);let o=t.find(e=>e.backendDOMNodeId===a.backendNodeId),s=new Set([o.nodeId]),c=[o];for(;c.length;){let e=c.shift();for(let n of e.childIds??[]){if(s.has(n))continue;s.add(n);let e=t.find(e=>e.nodeId===n);e&&c.push(e)}}return t.filter(e=>s.has(e.nodeId)).map(e=>e.nodeId===o.nodeId?{...e,parentId:void 0}:e)}function Xu(e,t){return e.map(e=>{let n=e.role?.value??``;return t.has(e.backendDOMNodeId)&&(n=n&&n!==`generic`&&n!==`none`?`scrollable, ${n}`:`scrollable`),{role:n,name:e.name?.value,description:e.description?.value,value:e.value?.value,nodeId:e.nodeId,backendDOMNodeId:e.backendDOMNodeId,parentId:e.parentId,childIds:e.childIds,properties:e.properties}})}async function Zu(e,t){let n=t?await t.evaluate(()=>window.getScrollableElementXpaths?.()??[]):await e.evaluate(()=>window.getScrollableElementXpaths?.()??[]),r=new Set;for(let i of n){if(!i)continue;let n=await Qu(e,i,t);if(n){let{node:t}=await(await e.context().newCDPSession(e)).send(`DOM.describeNode`,{objectId:n});t?.backendNodeId&&r.add(t.backendNodeId)}}return r}async function Qu(e,t,n){let r=await $u(e,n),{result:i}=await(await e.context().newCDPSession(e)).send(`Runtime.evaluate`,{expression:`
79
79
  (() => {
80
80
  const res = document.evaluate(
@@ -12492,7 +12492,7 @@ const cx={216:`O`,223:`s`,248:`o`,273:`d`,295:`h`,305:`i`,320:`l`,322:`l`,359:`t
12492
12492
 
12493
12493
  `)}async readAgentMd(e){for(let t of[`AGENTS.md`,`CLAUDE.md`,`agent.md`,`claude.md`]){let n=C.join(e,t);try{return(await F.readFile(n,`utf-8`)).trim()}catch{}}return null}async loadMdcRules(e,t=!1){let n=[C.join(e,ke.localConfigDirName,`rules`),C.join(e,`.cursor`,`rules`)],r=[];for(let e of n)try{let t=await F.readdir(e,{withFileTypes:!0});for(let n of t){if(!n.isFile()||!n.name.endsWith(`.mdc`))continue;let t=C.join(e,n.name);try{let e=await this.parseMdcFile(t,n.name);e&&r.push(e)}catch{}}}catch{}return t?r.filter(e=>e.alwaysApply):r}async getRulesForFile(e,t){return(await this.loadMdcRules(e)).filter(e=>e.alwaysApply||this.matchesRule(t,e))}matchesRule(e,t){if(!t.globs)return!1;let n=dk.get(t);return n||(n=t.globs.split(`,`).map(e=>e.trim()).filter(Boolean).map(e=>(0,pS.default)(e)),dk.set(t,n)),n.some(t=>t(e))}async parseMdcFile(e,t){let n=(await F.readFile(e,`utf-8`)).match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!n)return null;let r=n[1]??``,i=(n[2]??``).trim(),a=e=>{let t=r.match(RegExp(`^${e}:\\s*(.*)$`,`im`));return t?t[1].trim():``};return{uri:e,name:t,description:a(`description`),globs:a(`globs`),alwaysApply:a(`alwaysApply`).toLowerCase()===`true`,content:i}}};new fk;async function pk(e){return new Promise(t=>setTimeout(t,e))}const mk=[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`];var hk=class{_sessions=new Map;_outputs=new Map;_nextId=1;_cwd;_signalHandlers=new Map;constructor(e){this._cwd=e,this._setupSignalForwarding()}_setupSignalForwarding(){for(let e of mk){let t=()=>{for(let[,t]of this._sessions)if(t.process&&t.isRunning&&!t.process.killed&&t.process.exitCode===null)try{t.process.kill(e)}catch{}};this._signalHandlers.set(e,t),process.on(e,t)}}async executeCommand(e,t={}){let{terminalId:n,interactiveMode:r=!1}=t;if(r){if(e===`/exit`&&n)return await this.closeTerminal(n),{running:Promise.resolve(),result:{get:()=>({id:n,command:e,output:`Terminal closed`,exitCode:0,cwd:this._cwd,duration:0})}};if(e===`/wait`&&n){await pk(3e3);let t=this._sessions.get(n)?.output||`No output available`;return{running:Promise.resolve(),result:{get:()=>({id:n,command:e,output:t,exitCode:0,cwd:this._cwd,duration:3e3})}}}}if(r&&n){let t=this._sessions.get(n);if(t&&t.isRunning&&t.isInteractive)return this._sendInputToSession(t,e)}let i=n||this._nextId++,a=Date.now(),o,s=new Promise(e=>{o=e}),c={id:i,command:e,output:``,exitCode:void 0,cwd:this._cwd,duration:void 0},l={id:i,process:null,command:e,output:``,exitCode:void 0,cwd:this._cwd,startTime:a,isRunning:!0,runInBackground:!1,isInteractive:r,timeouts:new Set};this._sessions.set(i,l);let d=u(r?`bash`:e,{cwd:this._cwd,stdio:r?[`pipe`,`pipe`,`pipe`]:[`ignore`,`pipe`,`pipe`],shell:!r,env:{...process.env}});l.process=d;let f=10*1024*1024,p=``,m=``,h=!1;if(d.stdout?.on(`data`,e=>{let t=e.toString();r&&!h||(p+=t,p.length>f&&(p=p.slice(p.length-f)),l.output=p+(m?`\nSTDERR:\n${m}`:``),c={...c,output:l.output})}),d.stderr?.on(`data`,e=>{let t=e.toString();m+=t,m.length>f&&(m=m.slice(m.length-f)),l.output=p+(m?`\nSTDERR:\n${m}`:``),c={...c,output:l.output}}),d.on(`close`,t=>{let n=Date.now(),r=n-a;l.exitCode=t||0,l.endTime=n,l.isRunning=!1,l.output=p+(m?`\nSTDERR:\n${m}`:``),c={id:i,command:e,output:l.output,exitCode:l.exitCode,cwd:l.cwd,duration:r},this._addToOutputHistory(i,c),o()}),d.on(`error`,t=>{l.isRunning=!1,l.exitCode=1,c={id:i,command:e,output:`Command execution failed: ${t.message}`,exitCode:1,cwd:l.cwd,duration:Date.now()-a},this._addToOutputHistory(i,c),o()}),r&&d.stdin){let t=setTimeout(()=>{l.timeouts.delete(t),h=!0,d.stdin?.write(e+`
12494
12494
  `)},1500);l.timeouts.add(t)}let g={running:s,result:{get:()=>c}},_=this._outputs.get(i)||[];return this._outputs.set(i,_),g}getOutput(e){return this._outputs.get(e)||[]}getLiveOutput(e){let t=this._sessions.get(e);return t?{id:t.id,command:t.command,output:t.output,exitCode:t.exitCode,cwd:t.cwd,duration:t.endTime?t.endTime-t.startTime:Date.now()-t.startTime}:null}_killProcessGracefully(e,t=5e3){try{e.kill(`SIGTERM`);let n=setTimeout(()=>{e&&!e.killed&&e.kill(`SIGKILL`)},t);n.unref&&n.unref()}catch{}}async stopCommand(e){let t=this._sessions.get(e);return!t||!t.process||!t.isRunning?!1:(this._killProcessGracefully(t.process),t.isRunning=!1,!0)}_addToOutputHistory(e,t){this._outputs.has(e)||this._outputs.set(e,[]);let n=this._outputs.get(e);n.push(t),n.length>50&&n.shift()}async _sendInputToSession(e,t){let n=Date.now(),r,i=new Promise(e=>{r=e}),a={id:e.id,command:t,output:e.output,exitCode:void 0,cwd:e.cwd,duration:void 0};if(e.process&&e.process.stdin){e.process.stdin.write(t+`
12495
- `);let i=setTimeout(()=>{e.timeouts.delete(i),a={...a,output:e.output,duration:Date.now()-n},this._addToOutputHistory(e.id,a),r()},3e3);e.timeouts.add(i)}else a={...a,output:`Error: Terminal session not available`,exitCode:1,duration:Date.now()-n},r();return{running:i,result:{get:()=>a}}}async closeTerminal(e){let t=this._sessions.get(e);if(t){for(let e of t.timeouts)clearTimeout(e);t.timeouts.clear(),t.process&&t.isRunning&&this._killProcessGracefully(t.process),t.isRunning=!1,this._sessions.delete(e),this._outputs.delete(e)}}dispose(){for(let[e,t]of this._signalHandlers)process.removeListener(e,t);this._signalHandlers.clear();for(let[,e]of this._sessions){for(let t of e.timeouts)clearTimeout(t);e.timeouts.clear(),e.process&&e.isRunning&&this._killProcessGracefully(e.process)}this._sessions.clear(),this._outputs.clear()}},gk=class e extends Pl{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=tc({uri:J().optional().describe(`Optional file URI to get diagnostics for. If not provided, gets diagnostics for all files.`)});parameters=e.Parameters;constructor(e){super(),this._provider=e}needsPermission(){return!1}async execute(e,t){let n=e.uri?[e.uri]:void 0,r=await this._provider.getDiagnostics(n);return{type:`get_diagnostics`,diagnostics:r,total:r.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`get_diagnostics`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.status===`error`?`error`:`success`,r=t.diagnostics?.filter(e=>e.severity===`error`).length??0,i=t.diagnostics?.filter(e=>e.severity===`warning`).length??0,a=[];return r>0&&a.push(`${r} error${r===1?``:`s`}`),i>0&&a.push(`${i} warning${i===1?``:`s`}`),{phase:n,toolType:`get_diagnostics`,data:t,summary:a.length>0?a.join(`, `):`${t.total??0} diagnostics`}}catch{return{phase:`success`,toolType:`get_diagnostics`,data:{},summary:`Completed`}}}};const _k=new Set([`read_file`,`list_dir`,`ls`,`grep`,`file_search`,`glob_file_search`,`codebase_search`,`semantic_search`,`semantic_search_server`,`web_search`,`fetch_url`,`bash_output`,`kill_shell`,`get_diagnostics`,`upload_image`]),vk=new Set([`navigate_to`,`new_tab`,`close_tab`,`switch_active_tab`,`refresh_tab`,`get_tab_content`,`get_interactive_elements`,`perform_interactive_element_action`,`computer`]);function yk(e){if(e.type!==`tool_call`)return null;let t=e.toolUseRequest.name;return _k.has(t)?`read_search`:vk.has(t)?`browser`:e.parsedResult?.data&&e.parsedResult.data.serverId?`mcp`:null}function bk(e){if(e.type!==`tool_call`)return null;let t=e.parsedResult?.data;return t?.serverId?`${t.serverId}:${e.toolUseRequest.name}`:null}function xk(e,t){if(t===`mcp`){let t=e[0];if(t?.type===`tool_call`){let n=t.toolUseRequest.name,r=t.parsedResult?.data?.serverId??`mcp`;return`${n} \u00d7 ${e.length} (${r})`}}let n=new Map;for(let t of e){if(t.type!==`tool_call`)continue;let e=t.toolUseRequest.name;n.set(e,(n.get(e)??0)+1)}let r=[];for(let[e,t]of n){let n=Sk(e);r.push(t>1?`${n} ${t} ${Ck(e,t)}`:`${n} 1 ${Ck(e,1)}`)}return r.join(`, `)}function Sk(e){switch(e){case`read_file`:return`read`;case`list_dir`:case`ls`:return`listed`;case`grep`:return`searched`;case`file_search`:case`glob_file_search`:case`codebase_search`:return`searched`;case`semantic_search`:case`semantic_search_server`:return`searched`;case`web_search`:return`web searched`;case`fetch_url`:return`fetched`;case`bash_output`:return`got output from`;case`kill_shell`:return`killed`;case`get_diagnostics`:return`got diagnostics from`;case`upload_image`:return`uploaded`;case`navigate_to`:return`navigated`;case`new_tab`:return`opened`;case`close_tab`:return`closed`;case`switch_active_tab`:return`switched`;case`refresh_tab`:return`refreshed`;case`get_tab_content`:return`got content from`;case`get_interactive_elements`:return`found elements on`;case`perform_interactive_element_action`:return`clicked`;case`computer`:return`performed`;default:return e}}function Ck(e,t){let n=t===1?``:`s`;switch(e){case`read_file`:return`file${n}`;case`list_dir`:case`ls`:return`director${t===1?`y`:`ies`}`;case`grep`:return`pattern${n}`;case`file_search`:case`glob_file_search`:case`codebase_search`:return`quer${t===1?`y`:`ies`}`;case`semantic_search`:case`semantic_search_server`:return`quer${t===1?`y`:`ies`}`;case`web_search`:return`quer${t===1?`y`:`ies`}`;case`fetch_url`:return`URL${n}`;case`kill_shell`:return`shell${n}`;case`navigate_to`:return`page${n}`;case`new_tab`:return`tab${n}`;case`close_tab`:return`tab${n}`;case`get_tab_content`:return`tab${n}`;case`get_interactive_elements`:return`tab${n}`;case`perform_interactive_element_action`:return`element${n}`;case`computer`:return`action${n}`;default:return`call${n}`}}function wk(e){let t=[],n=[],r=null,i=null;function a(){n.length!==0&&(n.length===1?t.push(n[0]):t.push({type:`tool_group`,id:crypto.randomUUID(),tools:n,category:r,summary:xk(n,r)}),n=[],r=null,i=null)}for(let o of e){let e=yk(o);if(e===null){a(),t.push(o);continue}let s=e===`mcp`?bk(o):null,c=o.type===`tool_call`&&o.toolPhase===`error`;(e!==r||e===`mcp`&&s!==i)&&(a(),r=e,i=s),n.push(o),c&&a()}return a(),t}function Tk(e){if(!e)return null;if(typeof e==`string`)return e;if(typeof e==`object`&&e){let t=e;if(t.text)return t.text;if(t.segment)return Tk(t.segment)}return null}function Ek(e){return Math.min((e+1)*2e3,1e4)}function Dk(e){return 2**(e+1)*1e3}function*Ok(e,t,n){if(e.error){let t=e.error,r=typeof t==`string`?t:JSON.stringify(t);r.includes(`Credit limit`)||r.includes(`no_usage_points`)||r.includes(`compute_point_budgeting`)||r.includes(`limit_exceeded`)||r.includes(`exhausted`)||r.includes(`purchase more credits`)?yield{__error:new wl({...n.pendingCreditLimitSegment??void 0,message:r})}:yield{__error:new Cl(r)};return}if(e.type===`no_usage_points`||e.type===`compute_point_budgeting`||e.type===`limit_exceeded`){n.pendingCreditLimitSegment=e;return}if(e.type===`collapsible_component`&&e.isThoughts===!0){let t=e.title||`Thinking`,n=Tk(e.segment)??``;n&&(yield{type:`thinking_delta`,content:n,title:t}),e.isSpinny===!1&&(yield{type:`thinking_complete`});return}if(e.type===`code_llm_notification`){let t=e.message||Tk(e.segment)||`Notification`;yield{...e,type:`notification`,message:t,severity:e.severity??`info`};return}if(e.toolUseRequest){let n=(Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest]).map(e=>{if(e.name===`edit`){let t=e.input;if(`startLineOneIndexed`in t||`endLineOneIndexed`in t)return{...e,input:{...t,startLine:t.startLineOneIndexed??t.startLine,endLine:t.endLineOneIndexed??t.endLine}}}return e});t.push(...n);for(let e of n)yield{type:`tool_requested`,tool:e};return}if(e.segment){let t=Tk(e.segment);t&&(yield{type:`text_delta`,content:t})}}async function*kk(e){let t=crypto.randomUUID(),n=!1;for(let r=0;r<8;r++){let i=t,a=!1;if(r>0)try{let t=await e.apiClient.getPendingRequestIdForConversation(e.conversationId);t?.success&&t.result?.requestId&&(i=t.result.requestId,a=!0)}catch{}let o=[],s={pendingCreditLimitSegment:null};try{let t=e.apiClient.streamAgentMessage({deploymentConversationId:e.conversationId,message:e.message,supportedTools:e.supportedTools,mcpTools:e.isPrintMode?[]:e.mcpTools??[],workspacePath:e.workspacePath,llmName:e.model,rules:e.rules??[],requestId:i,docInfos:e.uploadedDocs?Array.from(e.uploadedDocs):[],toolUseResult:e.toolResult,supportsV2:!0,supportsThoughtStreaming:e.supportsThoughtStreaming??!0,supportsAbsolutePath:!1,supportsParallelToolUse:!0,isPrintMode:e.isPrintMode??!1,enablePromptRewrite:e.enablePromptRewrite??!1,agentMode:e.agentMode,currentFile:e.currentFile,selectionStartLine:e.selectionStartLine,selectionEndLine:e.selectionEndLine,gitBranch:e.gitBranch,gitMain:e.gitMain,gitStatus:e.gitStatus,gitCommits:e.gitCommits,diagnosticIssues:e.diagnosticIssues,reconnect:a,signal:e.signal});for await(let n of t){if(e.signal?.aborted)break;for(let e of Ok(n,o,s)){if(`__error`in e)throw e.__error;yield e}}n&&=(yield{type:`network_status`,online:!0},!1),yield{type:`turn_complete_with_tools`,toolCalls:o};return}catch(t){let i=t instanceof Error?t:Error(String(t));if(i instanceof Se||i instanceof wl)throw i;let a=Ee(i),o=a?8:5;if(r<o-1&&!e.signal?.aborted){let e=a?Ek(r):Dk(r);a&&!n&&(n=!0,yield{type:`network_status`,online:!1}),yield{type:`retry`,attempt:r+1,maxAttempts:o,delayMs:e,isNetworkError:a},await Ul(e);continue}throw Ee(i)?i instanceof Ce?i:new Ce(i.message,i):i}}}function Ak(e){let t=e.toUpperCase();return t.includes(`CLAUDE`)||t.includes(`OPENAI`)}async function*jk(e,t,n){let r=e.maxTurns??2**53-1,i=t,a,o=0,s=0,c=[],l=e.agentMode;try{for(;o<r;){if(n?.aborted)return{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:Error(`Execution cancelled`)};o++;let t={...e,agentMode:l,message:i,...a!==void 0&&{toolResult:a},...n!==void 0&&{signal:n}},r=[];for await(let e of kk(t)){if(e.type===`turn_complete_with_tools`){r=e.toolCalls;continue}e.type===`text_delta`&&c.push(e.content),yield e}if(r.length===0){yield{type:`turn_complete`};break}s+=r.length;let u=[],d=await e.executeTools(r,n,e=>u.push(e));for(let e of u)e.type===`mode_changed`&&(l=e.mode),yield e;for(let e=0;e<d.length;e++){let t=r[e],n=d[e];t&&n&&(yield{type:`tool_execution_complete`,tool:t,result:n})}for(let t of e.drainEvents?.()??[])t.type===`mode_changed`&&(l=t.mode),yield t;let f=d.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===Kc.REJECTED}catch{return!1}}),p=d.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===Kc.INTERRUPTED}catch{return!1}}),m=d.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===Kc.USER_MESSAGE}catch{return!1}});if((f||p)&&!m){yield{type:`turn_complete`};break}let h=d.map(({parsedResult:e,...t})=>t);a=h.length===1?h[0]:h;let g=r.some(e=>e.name===`exit_plan_mode`)&&d.some(e=>{if(e.rejected)return!1;try{return JSON.parse(e.content).type===`exit_plan_mode`}catch{return!1}}),_=`I want you to start implementing the plan now as you have outlined in your plan.`,v=e.getQueuedMessage?.();if(v)if(Ak(e.model))i=g?`${_} ${v}`:v,e.clearQueuedMessage?.(),yield{type:`user_message_dequeued`,content:v};else{yield{type:`turn_complete`};break}else i=g?_:``;yield{type:`turn_complete`}}if(o>=r){let e=Error(`Maximum turns (${r}) exceeded`);return yield{type:`error`,error:e},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:e}}return{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!0}}catch(e){let t=e instanceof Error?e:Error(String(e));return yield{type:`error`,error:t},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:t}}}var Mk=class{sessionId;_workspace;_terminalService;_browserService;_registry;_mcpService;_rulesService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];mcp;rules;constructor(e){this._config={...e,allowedDirectories:[...e.allowedDirectories]},this.sessionId=crypto.randomUUID(),this._mode=e.mode??xl.Normal,this._model=e.model??``,this._workspace=new xS(e.primaryWorkspace),this._terminalService=new hk(e.primaryWorkspace),this._browserService=new Fg,this._registry=mu(),e.diagnosticsProvider&&this._registry.register(new gk(e.diagnosticsProvider)),this._mcpService=new uk,this._rulesService=new fk;let t=e.config?.get(`permissions`)??{};this._rulesEngine=new wu({rules:{allow:[...t.allow??[],...e.permissionRules?.allow??[]],deny:[...t.deny??[],...e.permissionRules?.deny??[]],ask:[...t.ask??[],...e.permissionRules?.ask??[]]},cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools,safeCommandRules:Fu()}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(this._initialized)return;if(this._initialized=!0,this._config.config){await this._config.config.load();let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=C.resolve(e);this._config.allowedDirectories.includes(t)||this._config.allowedDirectories.push(t)}}let[e]=await Promise.all([this._rulesService.loadAllRules(this._config.primaryWorkspace),this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)]);this._rules=e.rules,this._markdownContext=e.markdownContext}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)}}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{let e=await this._rulesService.loadAllRules(this._config.primaryWorkspace);this._rules=e.rules,this._markdownContext=e.markdownContext}}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!pu.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)};switch(e.name){case`read_file`:{let t=e.input.targetFile??``,r=C.isAbsolute(t)?t:C.resolve(this._config.primaryWorkspace,t);return{type:`read_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:r,deducedDirectory:C.dirname(r)}}case`edit`:{let r=t._prepareResult,i=r?.currentContent??``,a=r?.codeChanges,o=a&&a.length>0&&i?ou(i,a):e.input.codeEdit??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.targetFile??``,originalContent:i,newContent:o,diffContent:``}}case`delete_file`:return{type:`delete_file`,tool:e,displayName:n,filePath:e.input.targetFile??``};case`bash`:return{type:`run_terminal`,tool:e,displayName:n,command:e.input.command??``,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1)};case`exit_plan_mode`:return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(t._prepareResult?.planContent??``)};case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let i=new AbortController,a=()=>i.abort(`interrupted`);n&&(n.aborted?i.abort(`interrupted`):n.addEventListener(`abort`,a,{once:!0}));let o=[],s=(e,t,n)=>({id:e.id,content:t,...n&&{rejected:!0},parsedResult:t.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:t,errorMessage:t}:this._registry.parse(e.name,t)});try{for(let a of t){if(i.signal.aborted){o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}let t={workspace:this._workspace,terminalService:this._terminalService,abacusBrowserService:this._browserService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:a.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:i,...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory}};try{r?.({type:`tool_execution_start`,tool:a});let e=this._registry.createToolInstance(a.name,a.input??{},t);if(await e.prepare(),a.name===`edit`&&pu.isBuiltinRequest(a)){let n=e._prepareResult,i=t.workspacePath,o=t.plansDir??ke.localConfigDirName+`/plans/`,s=C.resolve(i,a.input.targetFile??``),c=C.resolve(i,o),l=c.endsWith(`/`)?c:c+`/`,u=s.startsWith(l),d=n?.currentContent??``,f=n?.codeChanges,p={originalContent:d,newContent:f&&f.length>0&&d?ou(d,f):a.input.codeEdit??``,isPlanFile:u,isNewFile:!(n?.fileExists??!0)},m={type:`tool_display_data`,toolCallId:a.id,data:p};r?.(m),this._toolEventBuffer.push(m)}let c=this._mode===xl.Yolo&&a.name!==`ask_user_question`;if(!c&&e.needsPermission()){let i=this._registry.get(a.name)?.displayName??a.name,c=Cu(a),l=this._rulesEngine.evaluate(i,c);if(l===`deny`){o.push(s(a,JSON.stringify({reason:Kc.REJECTED}),!0));continue}if(l!==`allow`){let i=this._buildPermissionRequest(a,e);if(this._config.permissionProvider.needsPermission(i)){let c={type:`status_changed`,status:Sl.WaitingForToolPermission};r?.(c),this._toolEventBuffer.push(c);let l;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{l=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else l=await e}catch{o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}if(r?.({type:`status_changed`,status:Sl.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Sl.ExecutingTool}),l===`reject`){o.push(s(a,JSON.stringify({reason:Kc.REJECTED}),!0));continue}if(typeof l==`object`&&l.type===`reject_with_message`){o.push(s(a,JSON.stringify({reason:Kc.USER_MESSAGE,message:l.message}),!0));continue}if(l===`allowAlways`||l===`accept`)if(l===`allowAlways`&&i.type===`read_outside_directory`){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(a.name===`exit_plan_mode`){let e=l===`allowAlways`?xl.AcceptEdits:xl.Normal;this._mode=e,t.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else l===`allowAlways`&&(a.name===`edit`||a.name===`write`?(this._mode=xl.AcceptEdits,t.agentMode=xl.AcceptEdits,r?.({type:`mode_changed`,mode:xl.AcceptEdits}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.AcceptEdits})):(this._mode=xl.Yolo,t.agentMode=xl.Yolo,r?.({type:`mode_changed`,mode:xl.Yolo}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.Yolo})));if(typeof l==`object`&&l.type===`accept_with_message`&&this._messageQueue.push(l.message),typeof l==`object`&&l.type===`question_answers`&&e.mergeParams({answers:l.answers}),typeof l==`object`&&l.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(l.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],l.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}if(a.name===`enter_plan_mode`&&(this._mode=xl.PlanMode,t.agentMode=xl.PlanMode,r?.({type:`mode_changed`,mode:xl.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.PlanMode})),a.name===`exit_plan_mode`&&c&&(this._mode=xl.Normal,t.agentMode=xl.Normal,r?.({type:`mode_changed`,mode:xl.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.Normal})),await e.execute(),i.signal.aborted){o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}let l=e.formatResult(),u=typeof l==`string`?l:JSON.stringify(l);o.push(s(a,u))}catch(e){if(i.signal.aborted){o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}let t=e instanceof Error?e.message:String(e);o.push(s(a,`Error: ${t}`))}}return o}finally{n&&n.removeEventListener(`abort`,a)}}}async createConversation(){let e=(await this._config.apiClient.createCodellmDeploymentConversation(`CODE_LLM_AGENT`))?.result?.deploymentConversationId??crypto.randomUUID();return this._conversationId=e,e}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0,i=wk(this._hydrateHistory(n));return{...r!==void 0&&{title:r},segments:i}}switchConversation(e){return this._conversationId=e,Promise.resolve()}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null)}async listConversations(){return((await this._config.apiClient.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=Jc(i);r.toolUseResult={id:r.toolUseRequest.id,content:i,...o.rejected&&{rejected:!0}};let s=this._registry.parse(a,i);o.rejected&&(s.phase=`rejected`,o.userNote!==void 0&&(s.userNote=o.userNote)),r.parsedResult=s,r.toolPhase=s.phase}}_detectAbandonedTools(e){let t=new Set([`todo_write`]);for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`tool_call`&&!r.toolUseResult&&!t.has(r.toolUseRequest.name)){let t=e.slice(n+1).some(e=>e.type===`text`||e.type===`tool_call`),i=t?`abandoned`:`abandoned_last`;r.toolPhase=i,r.parsedResult={phase:i,toolType:r.toolUseRequest.name,data:{},summary:t?`Abandoned`:`Abandoned · What should I do next?`}}}}async*send(e,t){await this._ensureInitialized(),this._conversationId||await this.createConversation(),this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Sl.Submitted};let r=e,i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools(),a=this._registry.getApiToolDefinitions(),o=jk({apiClient:this._config.apiClient,conversationId:this._conversationId,model:this._model,workspacePath:this._config.primaryWorkspace,supportedTools:a,...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:C.isAbsolute(t.currentFile)?t.currentFile:C.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},getQueuedMessage:()=>this._messageQueue.length>0?this._messageQueue.join(`
12495
+ `);let i=setTimeout(()=>{e.timeouts.delete(i),a={...a,output:e.output,duration:Date.now()-n},this._addToOutputHistory(e.id,a),r()},3e3);e.timeouts.add(i)}else a={...a,output:`Error: Terminal session not available`,exitCode:1,duration:Date.now()-n},r();return{running:i,result:{get:()=>a}}}async closeTerminal(e){let t=this._sessions.get(e);if(t){for(let e of t.timeouts)clearTimeout(e);t.timeouts.clear(),t.process&&t.isRunning&&this._killProcessGracefully(t.process),t.isRunning=!1,this._sessions.delete(e),this._outputs.delete(e)}}dispose(){for(let[e,t]of this._signalHandlers)process.removeListener(e,t);this._signalHandlers.clear();for(let[,e]of this._sessions){for(let t of e.timeouts)clearTimeout(t);e.timeouts.clear(),e.process&&e.isRunning&&this._killProcessGracefully(e.process)}this._sessions.clear(),this._outputs.clear()}},gk=class e extends Pl{name=`get_diagnostics`;displayName=`GetDiagnostics`;description=`Get IDE diagnostics (errors, warnings, info) for a file or all open files.`;_provider;static Parameters=tc({uri:J().optional().describe(`Optional file URI to get diagnostics for. If not provided, gets diagnostics for all files.`)});parameters=e.Parameters;constructor(e){super(),this._provider=e}needsPermission(){return!1}async execute(e,t){let n=e.uri?[e.uri]:void 0,r=await this._provider.getDiagnostics(n);return{type:`get_diagnostics`,diagnostics:r,total:r.length}}format(e,t){return JSON.stringify({...e,status:`success`})}parse(e){let t=Jc(e);if(t.rejected)return{phase:`rejected`,toolType:`get_diagnostics`,data:{},summary:t.userNote?`Rejected \u00b7 "${t.userNote}"`:`Rejected`,...t.userNote!==void 0&&{userNote:t.userNote}};try{let t=JSON.parse(e),n=t.status===`error`?`error`:`success`,r=t.diagnostics?.filter(e=>e.severity===`error`).length??0,i=t.diagnostics?.filter(e=>e.severity===`warning`).length??0,a=[];return r>0&&a.push(`${r} error${r===1?``:`s`}`),i>0&&a.push(`${i} warning${i===1?``:`s`}`),{phase:n,toolType:`get_diagnostics`,data:t,summary:a.length>0?a.join(`, `):`${t.total??0} diagnostics`}}catch{return{phase:`success`,toolType:`get_diagnostics`,data:{},summary:`Completed`}}}};const _k=new Set([`read_file`,`list_dir`,`ls`,`grep`,`file_search`,`glob_file_search`,`codebase_search`,`semantic_search`,`semantic_search_server`,`web_search`,`web_fetch`,`bash_output`,`kill_shell`,`get_diagnostics`,`upload_image`]),vk=new Set([`navigate_to`,`new_tab`,`close_tab`,`switch_active_tab`,`refresh_tab`,`get_tab_content`,`get_interactive_elements`,`perform_interactive_element_action`,`computer`]);function yk(e){if(e.type!==`tool_call`)return null;let t=e.toolUseRequest.name;return _k.has(t)?`read_search`:vk.has(t)?`browser`:e.parsedResult?.data&&e.parsedResult.data.serverId?`mcp`:null}function bk(e){if(e.type!==`tool_call`)return null;let t=e.parsedResult?.data;return t?.serverId?`${t.serverId}:${e.toolUseRequest.name}`:null}function xk(e,t){if(t===`mcp`){let t=e[0];if(t?.type===`tool_call`){let n=t.toolUseRequest.name,r=t.parsedResult?.data?.serverId??`mcp`;return`${n} \u00d7 ${e.length} (${r})`}}let n=new Map;for(let t of e){if(t.type!==`tool_call`)continue;let e=t.toolUseRequest.name;n.set(e,(n.get(e)??0)+1)}let r=[];for(let[e,t]of n){let n=Sk(e);r.push(t>1?`${n} ${t} ${Ck(e,t)}`:`${n} 1 ${Ck(e,1)}`)}return r.join(`, `)}function Sk(e){switch(e){case`read_file`:return`read`;case`list_dir`:case`ls`:return`listed`;case`grep`:return`searched`;case`file_search`:case`glob_file_search`:case`codebase_search`:return`searched`;case`semantic_search`:case`semantic_search_server`:return`searched`;case`web_search`:return`web searched`;case`web_fetch`:return`fetched`;case`bash_output`:return`got output from`;case`kill_shell`:return`killed`;case`get_diagnostics`:return`got diagnostics from`;case`upload_image`:return`uploaded`;case`navigate_to`:return`navigated`;case`new_tab`:return`opened`;case`close_tab`:return`closed`;case`switch_active_tab`:return`switched`;case`refresh_tab`:return`refreshed`;case`get_tab_content`:return`got content from`;case`get_interactive_elements`:return`found elements on`;case`perform_interactive_element_action`:return`clicked`;case`computer`:return`performed`;default:return e}}function Ck(e,t){let n=t===1?``:`s`;switch(e){case`read_file`:return`file${n}`;case`list_dir`:case`ls`:return`director${t===1?`y`:`ies`}`;case`grep`:return`pattern${n}`;case`file_search`:case`glob_file_search`:case`codebase_search`:return`quer${t===1?`y`:`ies`}`;case`semantic_search`:case`semantic_search_server`:return`quer${t===1?`y`:`ies`}`;case`web_search`:return`quer${t===1?`y`:`ies`}`;case`web_fetch`:return`URL${n}`;case`kill_shell`:return`shell${n}`;case`navigate_to`:return`page${n}`;case`new_tab`:return`tab${n}`;case`close_tab`:return`tab${n}`;case`get_tab_content`:return`tab${n}`;case`get_interactive_elements`:return`tab${n}`;case`perform_interactive_element_action`:return`element${n}`;case`computer`:return`action${n}`;default:return`call${n}`}}function wk(e){let t=[],n=[],r=null,i=null;function a(){n.length!==0&&(n.length===1?t.push(n[0]):t.push({type:`tool_group`,id:crypto.randomUUID(),tools:n,category:r,summary:xk(n,r)}),n=[],r=null,i=null)}for(let o of e){let e=yk(o);if(e===null){a(),t.push(o);continue}let s=e===`mcp`?bk(o):null,c=o.type===`tool_call`&&o.toolPhase===`error`;(e!==r||e===`mcp`&&s!==i)&&(a(),r=e,i=s),n.push(o),c&&a()}return a(),t}function Tk(e){if(!e)return null;if(typeof e==`string`)return e;if(typeof e==`object`&&e){let t=e;if(t.text)return t.text;if(t.segment)return Tk(t.segment)}return null}function Ek(e){return Math.min((e+1)*2e3,1e4)}function Dk(e){return 2**(e+1)*1e3}function*Ok(e,t,n){if(e.error){let t=e.error,r=typeof t==`string`?t:JSON.stringify(t);r.includes(`Credit limit`)||r.includes(`no_usage_points`)||r.includes(`compute_point_budgeting`)||r.includes(`limit_exceeded`)||r.includes(`exhausted`)||r.includes(`purchase more credits`)?yield{__error:new wl({...n.pendingCreditLimitSegment??void 0,message:r})}:yield{__error:new Cl(r)};return}if(e.type===`no_usage_points`||e.type===`compute_point_budgeting`||e.type===`limit_exceeded`){n.pendingCreditLimitSegment=e;return}if(e.type===`collapsible_component`&&e.isThoughts===!0){let t=e.title||`Thinking`,n=Tk(e.segment)??``;n&&(yield{type:`thinking_delta`,content:n,title:t}),e.isSpinny===!1&&(yield{type:`thinking_complete`});return}if(e.type===`code_llm_notification`){let t=e.message||Tk(e.segment)||`Notification`;yield{...e,type:`notification`,message:t,severity:e.severity??`info`};return}if(e.toolUseRequest){let n=(Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest]).map(e=>{if(e.name===`edit`){let t=e.input;if(`startLineOneIndexed`in t||`endLineOneIndexed`in t)return{...e,input:{...t,startLine:t.startLineOneIndexed??t.startLine,endLine:t.endLineOneIndexed??t.endLine}}}return e});t.push(...n);for(let e of n)yield{type:`tool_requested`,tool:e};return}if(e.segment){let t=Tk(e.segment);t&&(yield{type:`text_delta`,content:t})}}async function*kk(e){let t=crypto.randomUUID(),n=!1;for(let r=0;r<8;r++){let i=t,a=!1;if(r>0)try{let t=await e.apiClient.getPendingRequestIdForConversation(e.conversationId);t?.success&&t.result?.requestId&&(i=t.result.requestId,a=!0)}catch{}let o=[],s={pendingCreditLimitSegment:null};try{let t=e.apiClient.streamAgentMessage({deploymentConversationId:e.conversationId,message:e.message,supportedTools:e.supportedTools,mcpTools:e.isPrintMode?[]:e.mcpTools??[],workspacePath:e.workspacePath,llmName:e.model,rules:e.rules??[],requestId:i,docInfos:e.uploadedDocs?Array.from(e.uploadedDocs):[],toolUseResult:e.toolResult,supportsV2:!0,supportsThoughtStreaming:e.supportsThoughtStreaming??!0,supportsAbsolutePath:!1,supportsParallelToolUse:!0,isPrintMode:e.isPrintMode??!1,enablePromptRewrite:e.enablePromptRewrite??!1,agentMode:e.agentMode,currentFile:e.currentFile,selectionStartLine:e.selectionStartLine,selectionEndLine:e.selectionEndLine,gitBranch:e.gitBranch,gitMain:e.gitMain,gitStatus:e.gitStatus,gitCommits:e.gitCommits,diagnosticIssues:e.diagnosticIssues,reconnect:a,signal:e.signal});for await(let n of t){if(e.signal?.aborted)break;for(let e of Ok(n,o,s)){if(`__error`in e)throw e.__error;yield e}}n&&=(yield{type:`network_status`,online:!0},!1),yield{type:`turn_complete_with_tools`,toolCalls:o};return}catch(t){let i=t instanceof Error?t:Error(String(t));if(i instanceof Se||i instanceof wl)throw i;let a=Ee(i),o=a?8:5;if(r<o-1&&!e.signal?.aborted){let e=a?Ek(r):Dk(r);a&&!n&&(n=!0,yield{type:`network_status`,online:!1}),yield{type:`retry`,attempt:r+1,maxAttempts:o,delayMs:e,isNetworkError:a},await Ul(e);continue}throw Ee(i)?i instanceof Ce?i:new Ce(i.message,i):i}}}function Ak(e){let t=e.toUpperCase();return t.includes(`CLAUDE`)||t.includes(`OPENAI`)}async function*jk(e,t,n){let r=e.maxTurns??2**53-1,i=t,a,o=0,s=0,c=[],l=e.agentMode;try{for(;o<r;){if(n?.aborted)return{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:Error(`Execution cancelled`)};o++;let t={...e,agentMode:l,message:i,...a!==void 0&&{toolResult:a},...n!==void 0&&{signal:n}},r=[];for await(let e of kk(t)){if(e.type===`turn_complete_with_tools`){r=e.toolCalls;continue}e.type===`text_delta`&&c.push(e.content),yield e}if(r.length===0){yield{type:`turn_complete`};break}s+=r.length;let u=[],d=await e.executeTools(r,n,e=>u.push(e));for(let e of u)e.type===`mode_changed`&&(l=e.mode),yield e;for(let e=0;e<d.length;e++){let t=r[e],n=d[e];t&&n&&(yield{type:`tool_execution_complete`,tool:t,result:n})}for(let t of e.drainEvents?.()??[])t.type===`mode_changed`&&(l=t.mode),yield t;let f=d.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===Kc.REJECTED}catch{return!1}}),p=d.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===Kc.INTERRUPTED}catch{return!1}}),m=d.some(e=>{if(!e.rejected)return!1;try{return JSON.parse(e.content).reason===Kc.USER_MESSAGE}catch{return!1}});if((f||p)&&!m){yield{type:`turn_complete`};break}let h=d.map(({parsedResult:e,...t})=>t);a=h.length===1?h[0]:h;let g=r.some(e=>e.name===`exit_plan_mode`)&&d.some(e=>{if(e.rejected)return!1;try{return JSON.parse(e.content).type===`exit_plan_mode`}catch{return!1}}),_=`I want you to start implementing the plan now as you have outlined in your plan.`,v=e.getQueuedMessage?.();if(v)if(Ak(e.model))i=g?`${_} ${v}`:v,e.clearQueuedMessage?.(),yield{type:`user_message_dequeued`,content:v};else{yield{type:`turn_complete`};break}else i=g?_:``;yield{type:`turn_complete`}}if(o>=r){let e=Error(`Maximum turns (${r}) exceeded`);return yield{type:`error`,error:e},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:e}}return{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!0}}catch(e){let t=e instanceof Error?e:Error(String(e));return yield{type:`error`,error:t},{content:c.join(``),numTurns:o,toolCallsExecuted:s,success:!1,error:t}}}var Mk=class{sessionId;_workspace;_terminalService;_browserService;_registry;_mcpService;_rulesService;_config;_conversationId=null;_mode;_model;_running=!1;_abortController=null;_initialized=!1;_uploadedDocs=new Set;_rules=[];_markdownContext=``;_rulesEngine;_toolEventBuffer=[];_messageQueue=[];mcp;rules;constructor(e){this._config={...e,allowedDirectories:[...e.allowedDirectories]},this.sessionId=crypto.randomUUID(),this._mode=e.mode??xl.Normal,this._model=e.model??``,this._workspace=new xS(e.primaryWorkspace),this._terminalService=new hk(e.primaryWorkspace),this._browserService=new Fg,this._registry=mu(),e.diagnosticsProvider&&this._registry.register(new gk(e.diagnosticsProvider)),this._mcpService=new uk,this._rulesService=new fk;let t=e.config?.get(`permissions`)??{};this._rulesEngine=new wu({rules:{allow:[...t.allow??[],...e.permissionRules?.allow??[]],deny:[...t.deny??[],...e.permissionRules?.deny??[]],ask:[...t.ask??[],...e.permissionRules?.ask??[]]},cliAllowed:e.cliAllowedTools,cliDenied:e.cliDisallowedTools,safeCommandRules:Fu()}),this.mcp=this._buildMcpManager(),this.rules=this._buildRulesManager()}async _ensureInitialized(){if(this._initialized)return;if(this._initialized=!0,this._config.config){await this._config.config.load();let e=this._config.config.get(`baseUrl`);e&&(this._config.apiClient.setUrl(e),this._config.apiClient.resetEndpoints(),await this._config.apiClient.getApiEndpoint());let t=this._config.config.get(`permissions`);if(t){for(let e of t.allow??[])this._rulesEngine.addAllowRule(e);for(let e of t.deny??[])this._rulesEngine.addDenyRule(e);for(let e of t.ask??[])this._rulesEngine.addAskRule(e)}let n=this._config.config.get(`additionalDirectories`);if(n)for(let e of n){let t=C.resolve(e);this._config.allowedDirectories.includes(t)||this._config.allowedDirectories.push(t)}}let[e]=await Promise.all([this._rulesService.loadAllRules(this._config.primaryWorkspace),this._mcpService.initialize(this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)]);this._rules=e.rules,this._markdownContext=e.markdownContext}_buildMcpManager(){return{listServers:()=>this._mcpService.getConnectedServers(),addServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config);return this._mcpService.initialize(this._config.primaryWorkspace,[...t,e],this._config.onMcpAuthRequired)},removeServer:async e=>{let t=this._mcpService.getConnectedServers().map(e=>e.config).filter(t=>t.id!==e);await this._mcpService.initialize(this._config.primaryWorkspace,t,this._config.onMcpAuthRequired)},callTool:(e,t,n)=>this._mcpService.callTool(e,t,n),getTools:()=>this._mcpService.getAbacusMcpTools(),refresh:async e=>{await this._mcpService.initialize(e??this._config.primaryWorkspace,this._config.mcpServers,this._config.onMcpAuthRequired)}}}_buildRulesManager(){return{getAll:()=>this._rules,getMarkdownContext:()=>this._markdownContext,reload:async()=>{let e=await this._rulesService.loadAllRules(this._config.primaryWorkspace);this._rules=e.rules,this._markdownContext=e.markdownContext}}}_buildBrowserActionDescription(e){switch(e.name){case`perform_interactive_element_action`:{let{action:t,id:n,text:r}=e.input,i=t??`interact with`,a={click:`Click`,type:`Type`,hover:`Hover`,scroll:`Scroll`,focus:`Focus`,select:`Select`}[i]??i;return i===`type`&&r&&n?`Type "${r}" into element ${n}`:i===`select`&&r&&n?`Select "${r}" in element ${n}`:n?`${a} element ${n}`:a}case`computer`:{let{action:t,coordinate:n,text:r}=e.input,i=t??``;return i===`screenshot`?`Screenshot`:i===`key`&&r?`Key: ${r}`:i===`type`&&r?`Type "${r}"`:n?`${i} at (${String(n[0])}, ${String(n[1])})`:i||`Computer action`}case`navigate_to`:return`Navigate to ${e.input.url??``}`;case`new_tab`:return`Open new tab${e.input.url?`: ${e.input.url}`:``}`;case`switch_active_tab`:return`Switch to tab ${String(e.input.id??``)}`;case`close_tab`:return`Close tab ${String(e.input.id??``)}`;case`refresh_tab`:return`Refresh tab`;case`get_tab_content`:return`Get tab content`;case`get_interactive_elements`:return`Get interactive elements`;default:return e.name}}_buildPermissionRequest(e,t){let n=this._registry.get(e.name)?.displayName??e.name;if(!pu.isBuiltinRequest(e))return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)};switch(e.name){case`read_file`:{let t=e.input.targetFile??``,r=C.isAbsolute(t)?t:C.resolve(this._config.primaryWorkspace,t);return{type:`read_outside_directory`,tool:e,displayName:n,filePath:t,resolvedPath:r,deducedDirectory:C.dirname(r)}}case`edit`:{let r=t._prepareResult,i=r?.currentContent??``,a=r?.codeChanges,o=a&&a.length>0&&i?ou(i,a):e.input.codeEdit??``;return{type:`edit_file`,tool:e,displayName:n,filePath:e.input.targetFile??``,originalContent:i,newContent:o,diffContent:``}}case`delete_file`:return{type:`delete_file`,tool:e,displayName:n,filePath:e.input.targetFile??``};case`bash`:return{type:`run_terminal`,tool:e,displayName:n,command:e.input.command??``,cwd:this._config.primaryWorkspace,background:!!(e.input.runInBackground??!1)};case`exit_plan_mode`:return{type:`exit_plan_mode`,tool:e,displayName:n,planFilePath:e.input.planFilePath??``,planContent:String(t._prepareResult?.planContent??``)};case`ask_user_question`:return{type:`ask_user_question`,tool:e,displayName:n,questions:Array.isArray(e.input.questions)?e.input.questions:[]};case`navigate_to`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,url:e.input.url,description:this._buildBrowserActionDescription(e)};case`computer`:case`perform_interactive_element_action`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:case`new_tab`:return{type:`browser_action`,tool:e,displayName:n,action:e.name,description:this._buildBrowserActionDescription(e)};default:return{type:`generic`,tool:e,displayName:n,toolName:n,inputSummary:JSON.stringify(e.input).slice(0,200)}}}_buildExecuteTools(e){return async(t,n,r)=>{let i=new AbortController,a=()=>i.abort(`interrupted`);n&&(n.aborted?i.abort(`interrupted`):n.addEventListener(`abort`,a,{once:!0}));let o=[],s=(e,t,n)=>({id:e.id,content:t,...n&&{rejected:!0},parsedResult:t.startsWith(`Error:`)?{phase:`error`,toolType:e.name,data:{},summary:t,errorMessage:t}:this._registry.parse(e.name,t)});try{for(let a of t){if(i.signal.aborted){o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}let t={workspace:this._workspace,terminalService:this._terminalService,abacusBrowserService:this._browserService,apiClient:this._config.apiClient,workspacePath:this._config.primaryWorkspace,conversationId:e,agentMode:this._mode,toolCallId:a.id,status:`executing`,uploadedDocs:this._uploadedDocs,allowEditingPaths:this._config.allowedDirectories,abortController:i,...this._rules.length>0&&{rules:this._rules},...this._config.planDirectory!==void 0&&{plansDir:this._config.planDirectory}};try{r?.({type:`tool_execution_start`,tool:a});let e=this._registry.createToolInstance(a.name,a.input??{},t);if(await e.prepare(),a.name===`edit`&&pu.isBuiltinRequest(a)){let n=e._prepareResult,i=t.workspacePath,o=t.plansDir??ke.localConfigDirName+`/plans/`,s=C.resolve(i,a.input.targetFile??``),c=C.resolve(i,o),l=c.endsWith(`/`)?c:c+`/`,u=s.startsWith(l),d=n?.currentContent??``,f=n?.codeChanges,p={originalContent:d,newContent:f&&f.length>0&&d?ou(d,f):a.input.codeEdit??``,isPlanFile:u,isNewFile:!(n?.fileExists??!0)},m={type:`tool_display_data`,toolCallId:a.id,data:p};r?.(m),this._toolEventBuffer.push(m)}let c=this._mode===xl.Yolo&&a.name!==`ask_user_question`;if(!c&&e.needsPermission()){let i=this._registry.get(a.name)?.displayName??a.name,c=Cu(a),l=this._rulesEngine.evaluate(i,c);if(l===`deny`){o.push(s(a,JSON.stringify({reason:Kc.REJECTED}),!0));continue}if(l!==`allow`){let i=this._buildPermissionRequest(a,e);if(this._config.permissionProvider.needsPermission(i)){let c={type:`status_changed`,status:Sl.WaitingForToolPermission};r?.(c),this._toolEventBuffer.push(c);let l;try{let e=this._config.permissionProvider.requestPermission(i);if(n){let t,r=new Promise((e,r)=>{n.aborted?r(Error(`interrupted`)):(t=()=>r(Error(`interrupted`)),n.addEventListener(`abort`,t,{once:!0}))});try{l=await Promise.race([e,r])}finally{t&&n.removeEventListener(`abort`,t)}}else l=await e}catch{o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}if(r?.({type:`status_changed`,status:Sl.ExecutingTool}),this._toolEventBuffer.push({type:`status_changed`,status:Sl.ExecutingTool}),l===`reject`){o.push(s(a,JSON.stringify({reason:Kc.REJECTED}),!0));continue}if(typeof l==`object`&&l.type===`reject_with_message`){o.push(s(a,JSON.stringify({reason:Kc.USER_MESSAGE,message:l.message}),!0));continue}if(l===`allowAlways`||l===`accept`)if(l===`allowAlways`&&i.type===`read_outside_directory`){if(this.addAllowedDirectory(i.deducedDirectory),this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(i.deducedDirectory)||this._config.config.set(`additionalDirectories`,[...e,i.deducedDirectory],`local`)}}else if(a.name===`exit_plan_mode`){let e=l===`allowAlways`?xl.AcceptEdits:xl.Normal;this._mode=e,t.agentMode=e,r?.({type:`mode_changed`,mode:e}),this._toolEventBuffer.push({type:`mode_changed`,mode:e})}else l===`allowAlways`&&(a.name===`edit`||a.name===`write`?(this._mode=xl.AcceptEdits,t.agentMode=xl.AcceptEdits,r?.({type:`mode_changed`,mode:xl.AcceptEdits}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.AcceptEdits})):(this._mode=xl.Yolo,t.agentMode=xl.Yolo,r?.({type:`mode_changed`,mode:xl.Yolo}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.Yolo})));if(typeof l==`object`&&l.type===`accept_with_message`&&this._messageQueue.push(l.message),typeof l==`object`&&l.type===`question_answers`&&e.mergeParams({answers:l.answers}),typeof l==`object`&&l.type===`allow_always_with_rule`&&(this._rulesEngine.addAllowRule(l.rule),this._config.config)){let e=this._config.config.get(`permissions`)??{},t=[...e.allow??[],l.rule];this._config.config.set(`permissions`,{...e,allow:t},`local`)}}}}if(a.name===`enter_plan_mode`&&(this._mode=xl.PlanMode,t.agentMode=xl.PlanMode,r?.({type:`mode_changed`,mode:xl.PlanMode}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.PlanMode})),a.name===`exit_plan_mode`&&c&&(this._mode=xl.Normal,t.agentMode=xl.Normal,r?.({type:`mode_changed`,mode:xl.Normal}),this._toolEventBuffer.push({type:`mode_changed`,mode:xl.Normal})),await e.execute(),i.signal.aborted){o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}let l=e.formatResult(),u=typeof l==`string`?l:JSON.stringify(l);o.push(s(a,u))}catch(e){if(i.signal.aborted){o.push(s(a,JSON.stringify({reason:Kc.INTERRUPTED}),!0));continue}let t=e instanceof Error?e.message:String(e);o.push(s(a,`Error: ${t}`))}}return o}finally{n&&n.removeEventListener(`abort`,a)}}}async createConversation(){let e=(await this._config.apiClient.createCodellmDeploymentConversation(`CODE_LLM_AGENT`))?.result?.deploymentConversationId??crypto.randomUUID();return this._conversationId=e,e}async loadConversation(e){this._conversationId=e;let t=await this._config.apiClient.getDeploymentConversation({deploymentConversationId:e}),n=t?.result?.history??[],r=t?.result?.name??void 0,i=wk(this._hydrateHistory(n));return{...r!==void 0&&{title:r},segments:i}}switchConversation(e){return this._conversationId=e,Promise.resolve()}async deleteConversation(e){await this._config.apiClient.deleteDeploymentConversation?.({deploymentConversationId:e}),this._conversationId===e&&(this._conversationId=null)}async listConversations(){return((await this._config.apiClient.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).map(e=>({id:e.deploymentConversationId??``,createdAt:new Date(e.createdAt??Date.now()),updatedAt:new Date(e.lastEventCreatedAt??e.createdAt??Date.now()),...e.name!==void 0&&{title:e.name}}))}_hydrateHistory(e){let t=[],n=[];for(let r of e){if(r.role===`USER`){let e=this._extractParallelToolResponses(r);e.length>0&&this._attachToolResults(n,e),n=[];let i=(r.prompt??r.text??``).trim();i&&t.push({type:`text`,id:crypto.randomUUID(),source:`user`,content:i});continue}n=[];for(let e of r.segments??[]){if(e.isThoughts){let n=typeof e.segment==`string`?e.segment:e.segment?.segment??``;t.push({type:`thinking`,id:crypto.randomUUID(),content:n,isSpinny:!1});continue}if(e.type===`code_llm_agent_tool_request`&&e.toolUseRequest){let r=Array.isArray(e.toolUseRequest)?e.toolUseRequest:[e.toolUseRequest];for(let e of r){let r={type:`tool_call`,id:crypto.randomUUID(),toolUseRequest:e,toolPhase:`unknown`};t.push(r),n.push(r)}continue}if(e.type===`code_llm_notification`){t.push({type:`notification`,id:crypto.randomUUID(),message:e.message??(typeof e.segment==`string`?e.segment:``)??``,severity:e.severity??`info`,...e.actions!==void 0&&{actions:e.actions}});continue}let r=typeof e.segment==`string`?e.segment:e.segment?.segment;r&&t.push({type:`text`,id:crypto.randomUUID(),source:`bot`,content:r})}}return this._detectAbandonedTools(t),t}_extractParallelToolResponses(e){if(Array.isArray(e.parallelToolResponses))return e.parallelToolResponses;for(let t of e.segments??[])if(Array.isArray(t.parallelToolResponses)&&t.parallelToolResponses.length>0)return t.parallelToolResponses;return[]}_attachToolResults(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=e[n],i=t[n],a=r.toolUseRequest.name,o=Jc(i);r.toolUseResult={id:r.toolUseRequest.id,content:i,...o.rejected&&{rejected:!0}};let s=this._registry.parse(a,i);o.rejected&&(s.phase=`rejected`,o.userNote!==void 0&&(s.userNote=o.userNote)),r.parsedResult=s,r.toolPhase=s.phase}}_detectAbandonedTools(e){let t=new Set([`todo_write`]);for(let n=0;n<e.length;n++){let r=e[n];if(r.type===`tool_call`&&!r.toolUseResult&&!t.has(r.toolUseRequest.name)){let t=e.slice(n+1).some(e=>e.type===`text`||e.type===`tool_call`),i=t?`abandoned`:`abandoned_last`;r.toolPhase=i,r.parsedResult={phase:i,toolType:r.toolUseRequest.name,data:{},summary:t?`Abandoned`:`Abandoned · What should I do next?`}}}}async*send(e,t){await this._ensureInitialized(),this._conversationId||await this.createConversation(),this._running=!0,this._abortController=new AbortController;let n=this._buildExecuteTools(this._conversationId);try{yield{type:`status_changed`,status:Sl.Submitted};let r=e,i=!0;for(;;){let e=this._mcpService.getAbacusMcpTools(),a=this._registry.getApiToolDefinitions(),o=jk({apiClient:this._config.apiClient,conversationId:this._conversationId,model:this._model,workspacePath:this._config.primaryWorkspace,supportedTools:a,...e.length>0&&{mcpTools:e},...this._rules.length>0&&{rules:this._rules},...this._config.isPrintMode!==void 0&&{isPrintMode:this._config.isPrintMode},...this._config.enablePromptRewrite!==void 0&&{enablePromptRewrite:this._config.enablePromptRewrite},...this._config.supportsThoughtStreaming!==void 0&&{supportsThoughtStreaming:this._config.supportsThoughtStreaming},agentMode:this._mode,...this._config.maxTurns!==void 0&&{maxTurns:this._config.maxTurns},...i&&t?.diagnosticIssues!==void 0&&{diagnosticIssues:t.diagnosticIssues},...i&&t?.currentFile!==void 0&&{currentFile:C.isAbsolute(t.currentFile)?t.currentFile:C.resolve(this._config.primaryWorkspace,t.currentFile)},...i&&t?.selectionStartLine!==void 0&&{selectionStartLine:t.selectionStartLine},...i&&t?.selectionEndLine!==void 0&&{selectionEndLine:t.selectionEndLine},executeTools:n,drainEvents:()=>{let e=this._toolEventBuffer.slice();return this._toolEventBuffer.length=0,e},getQueuedMessage:()=>this._messageQueue.length>0?this._messageQueue.join(`
12496
12496
  `):null,clearQueuedMessage:()=>{this._messageQueue.length=0}},r,this._abortController.signal),s=!1,c;for(;!(c=await o.next()).done;){let e=c.value;e.type===`text_delta`&&!s?(s=!0,yield{type:`status_changed`,status:Sl.Streaming}):e.type===`tool_requested`&&(yield{type:`status_changed`,status:Sl.ExecutingTool}),yield e,e.type===`mode_changed`&&(this._mode=e.mode)}if(i=!1,this._messageQueue.length===0||this._abortController.signal.aborted)break;r=this._messageQueue.join(`
12497
12497
  `),this._messageQueue.length=0,yield{type:`user_message_dequeued`,content:r}}}finally{this._running=!1,this._abortController=null,this._toolEventBuffer.length=0,yield{type:`status_changed`,status:Sl.Idle}}}stop(){this._abortController?.abort()}dispose(){this._abortController?.abort(),this._terminalService.dispose()}enqueue(e){this._messageQueue.push(e)}getQueue(){return this._messageQueue.slice()}dequeue(){return this._messageQueue.shift()??null}clearQueue(){this._messageQueue.length=0}removeAt(e){this._messageQueue.splice(e,1)}addUploadedDoc(e){this._uploadedDocs.add(e)}clearUploadedDocs(){this._uploadedDocs.clear()}addAllowedDirectory(e,t){let n=C.resolve(e);if(this._config.allowedDirectories.includes(n)||this._config.allowedDirectories.push(n),t?.persist&&this._config.config){let e=this._config.config.get(`additionalDirectories`)??[];e.includes(n)||this._config.config.set(`additionalDirectories`,[...e,n],`local`)}}setMode(e){this._mode=e}setModel(e){this._model=e}getMode(){return this._mode}getConversationId(){return this._conversationId}isRunning(){return this._running}},Nk=class{needsPermission(e){return!1}async requestPermission(e){return`accept`}},Pk=class{handler;_needsPermission;constructor(e,t){this.handler=e,this._needsPermission=t}needsPermission(e){return this._needsPermission?this._needsPermission(e):!0}async requestPermission(e){return this.handler(e)}},Fk=class{async read(){let e={},t=ke.envPrefix,n=ke.internalEnvPrefix,r=process.env[`${t}BASE_URL`],i=process.env[`${t}MODEL`],a=process.env[`${n}LOG_LEVEL`],o=process.env[`${t}MAX_TURNS`],s=process.env[`${t}AUTO_UPDATE`];if(r&&(e.baseUrl=r),i&&(e.model=i),a&&(e.logLevel=a),o&&(e.maxTurns=parseInt(o,10)),s!==void 0){let t=ol.safeParse(s);t.success&&t.data!==void 0&&(e.autoUpdate=t.data)}return e}},Ik=class{configPath;constructor(){this.configPath=C.join(r(),ke.configDirName,ke.configFileName)}async read(){try{let e=await v.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=C.dirname(this.configPath);await v.mkdir(t,{recursive:!0}),await v.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}},Lk=class{configPath;constructor(e){this.configPath=C.join(e,ke.localConfigDirName,ke.configFileName)}async read(){try{let e=await v.readFile(this.configPath,`utf-8`);return JSON.parse(e)}catch{return{}}}async write(e){let t=C.dirname(this.configPath);await v.mkdir(t,{recursive:!0}),await v.writeFile(this.configPath,JSON.stringify(e,null,2),`utf-8`)}};function Rk(e,...t){let n={...e};for(let e of t)for(let t of Object.keys(e)){let r=e[t];r!==void 0&&(typeof r==`object`&&r&&!Array.isArray(r)&&typeof n[t]==`object`&&n[t]!==null?n[t]=Rk(n[t],r):n[t]=r)}return n}const zk={allowedDirectories:[],primaryWorkspace:``,logLevel:`info`};var Bk=class{sources;cache=null;constructor(e){this.sources=[new Ik,new Lk(e.cwd),...e.extraSources??[],new Fk]}async load(){let e={...zk};for(let t of this.sources){let n=await t.read();e=Rk(e,n)}this.cache=e}get(e){return this.cache?this.cache[e]??zk[e]:zk[e]}getAll(){return this.cache??zk}async set(e,t,n=`global`){let r=n===`global`?this.sources[0]:this.sources[1];if(r?.write){let n=await r.read();await r.write({...n,[e]:t})}this.cache&&(this.cache[e]=t)}},Vk=class{source;maxEntries;filePath;entries=[];navIndex=-1;loaded=!1;writeQueue=Promise.resolve();constructor(e,t){this.source=e,this.maxEntries=t?.maxEntries??1e4,this.filePath=t?.filePath??T(r(),ke.configDirName,`history.jsonl`)}async load(){if(!this.loaded){this.loaded=!0;try{let e=this.maxEntries*2048,t=await z(this.filePath,`r`);try{let{size:n}=await t.stat(),r=Math.max(0,n-e),i=Buffer.allocUnsafe(n-r);await t.read(i,0,i.length,r);let a=i.toString(`utf-8`),o=r===0?0:a.indexOf(`
12498
12498
  `)+1,s=a.slice(o).split(`
@@ -12504,7 +12504,7 @@ const cx={216:`O`,223:`s`,248:`o`,273:`d`,295:`h`,305:`i`,320:`l`,322:`l`,359:`t
12504
12504
  `:`
12505
12505
  `)+n,i=r+1,r=e.indexOf(`
12506
12506
  `,i)}while(r!==-1);return a+=e.slice(i),a}const{stdout:vA,stderr:yA}=hA,bA=Symbol(`GENERATOR`),xA=Symbol(`STYLER`),SA=Symbol(`IS_EMPTY`),CA=[`ansi`,`ansi`,`ansi256`,`ansi16m`],wA=Object.create(null),TA=(e,t={})=>{if(t.level&&!(Number.isInteger(t.level)&&t.level>=0&&t.level<=3))throw Error("The `level` option should be an integer from 0 to 3");let n=vA?vA.level:0;e.level=t.level===void 0?n:t.level},EA=e=>{let t=(...e)=>e.join(` `);return TA(t,e),Object.setPrototypeOf(t,DA.prototype),t};function DA(e){return EA(e)}Object.setPrototypeOf(DA.prototype,Function.prototype);for(let[e,t]of Object.entries(sA))wA[e]={get(){let n=jA(this,AA(t.open,t.close,this[xA]),this[SA]);return Object.defineProperty(this,e,{value:n}),n}};wA.visible={get(){let e=jA(this,this[xA],!0);return Object.defineProperty(this,`visible`,{value:e}),e}};const OA=(e,t,n,...r)=>e===`rgb`?t===`ansi16m`?sA[n].ansi16m(...r):t===`ansi256`?sA[n].ansi256(sA.rgbToAnsi256(...r)):sA[n].ansi(sA.rgbToAnsi(...r)):e===`hex`?OA(`rgb`,t,n,...sA.hexToRgb(...r)):sA[n][e](...r);for(let e of[`rgb`,`hex`,`ansi256`]){wA[e]={get(){let{level:t}=this;return function(...n){let r=AA(OA(e,CA[t],`color`,...n),sA.color.close,this[xA]);return jA(this,r,this[SA])}}};let t=`bg`+e[0].toUpperCase()+e.slice(1);wA[t]={get(){let{level:t}=this;return function(...n){let r=AA(OA(e,CA[t],`bgColor`,...n),sA.bgColor.close,this[xA]);return jA(this,r,this[SA])}}}}const kA=Object.defineProperties(()=>{},{...wA,level:{enumerable:!0,get(){return this[bA].level},set(e){this[bA].level=e}}}),AA=(e,t,n)=>{let r,i;return n===void 0?(r=e,i=t):(r=n.openAll+e,i=t+n.closeAll),{open:e,close:t,openAll:r,closeAll:i,parent:n}},jA=(e,t,n)=>{let r=(...e)=>MA(r,e.length===1?``+e[0]:e.join(` `));return Object.setPrototypeOf(r,kA),r[bA]=e,r[xA]=t,r[SA]=n,r},MA=(e,t)=>{if(e.level<=0||!t)return e[SA]?``:t;let n=e[xA];if(n===void 0)return t;let{openAll:r,closeAll:i}=n;if(t.includes(`\x1B`))for(;n!==void 0;)t=gA(t,n.close,n.open),n=n.parent;let a=t.indexOf(`
12507
- `);return a!==-1&&(t=_A(t,i,r,a)),r+t+i};Object.defineProperties(DA.prototype,wA);const NA=DA();DA({level:yA?yA.level:0});var PA=`2.0.0-canary.5`,FA=W(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),IA=W(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),LA=W(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=FA(),a=IA();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),RA=W(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),zA=W(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),BA=W(((e,t)=>{let n=IA(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=FA(),{safeRe:a,t:o}=LA(),s=RA(),{compareIdentifiers:c}=zA();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),VA=W(((e,t)=>{let n=BA();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),HA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),UA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),WA=W(((e,t)=>{let n=BA();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),GA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),KA=W(((e,t)=>{let n=BA();t.exports=(e,t)=>new n(e,t).major})),qA=W(((e,t)=>{let n=BA();t.exports=(e,t)=>new n(e,t).minor})),JA=W(((e,t)=>{let n=BA();t.exports=(e,t)=>new n(e,t).patch})),YA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),XA=W(((e,t)=>{let n=BA();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),ZA=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(t,e,r)})),QA=W(((e,t)=>{let n=XA();t.exports=(e,t)=>n(e,t,!0)})),$A=W(((e,t)=>{let n=BA();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),ej=W(((e,t)=>{let n=$A();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),tj=W(((e,t)=>{let n=$A();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),nj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)>0})),rj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)<0})),ij=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)===0})),aj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)!==0})),oj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)>=0})),sj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)<=0})),cj=W(((e,t)=>{let n=ij(),r=aj(),i=nj(),a=oj(),o=rj(),s=sj();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),lj=W(((e,t)=>{let n=BA(),r=VA(),{safeRe:i,t:a}=LA();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),uj=W(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),dj=W(((e,t)=>{let n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,O(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k(this.set[t],e,this.options))return!0;return!1}};let r=new(uj()),i=RA(),a=fj(),o=IA(),s=BA(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=LA(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=FA(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=S(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=w(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(` `),x=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},S=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(` `),C=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},w=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>T(e,t)).join(` `)),T=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),O=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),k=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),fj=W(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=RA(),{safeRe:i,t:a}=LA(),o=cj(),s=IA(),c=BA(),l=dj()})),pj=W(((e,t)=>{let n=dj();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),mj=W(((e,t)=>{let n=dj();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),hj=W(((e,t)=>{let n=BA(),r=dj();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),gj=W(((e,t)=>{let n=BA(),r=dj();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),_j=W(((e,t)=>{let n=BA(),r=dj(),i=nj();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),vj=W(((e,t)=>{let n=dj();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),yj=W(((e,t)=>{let n=BA(),r=fj(),{ANY:i}=r,a=dj(),o=pj(),s=nj(),c=rj(),l=sj(),u=oj();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),bj=W(((e,t)=>{let n=yj();t.exports=(e,t,r)=>n(e,t,`>`,r)})),xj=W(((e,t)=>{let n=yj();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Sj=W(((e,t)=>{let n=dj();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),Cj=W(((e,t)=>{let n=pj(),r=XA();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),wj=W(((e,t)=>{let n=dj(),r=fj(),{ANY:i}=r,a=pj(),o=XA(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),Tj=W(((e,t)=>{let n=LA(),r=FA(),i=BA(),a=zA();t.exports={parse:VA(),valid:HA(),clean:UA(),inc:WA(),diff:GA(),major:KA(),minor:qA(),patch:JA(),prerelease:YA(),compare:XA(),rcompare:ZA(),compareLoose:QA(),compareBuild:$A(),sort:ej(),rsort:tj(),gt:nj(),lt:rj(),eq:ij(),neq:aj(),gte:oj(),lte:sj(),cmp:cj(),coerce:lj(),Comparator:fj(),Range:dj(),satisfies:pj(),toComparators:mj(),maxSatisfying:hj(),minSatisfying:gj(),minVersion:_j(),validRange:vj(),outside:yj(),gtr:bj(),ltr:xj(),intersects:Sj(),simplifyRange:Cj(),subset:wj(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}}))();let Ej=null;function Dj(e){let t=(0,Tj.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function Oj(){let e=process.env.npm_command;if(e===`exec`||e===`dlx`)return!0;let t=process.argv[1]??``;return!!/_npx[/\\]|[/\\]dlx[/\\]|\.cache[/\\]/.test(t)}function kj(){let e=process.env.npm_config_user_agent;if(e){let t=e.split(`/`)[0];if(t===`yarn`||t===`pnpm`||t===`bun`||t===`npm`)return t}let t=process.argv[1]??``;return t.includes(`yarn`)?`yarn`:t.includes(`pnpm`)?`pnpm`:t.includes(`bun`)?`bun`:`npm`}async function Aj(e){let t=Date.now();if(Ej&&t-Ej.timestamp<6e4)return Ej.tags;let n=await fetch(`https://registry.npmjs.org/${e}`,{signal:AbortSignal.timeout(1e4),headers:{accept:`application/json`}});if(!n.ok)throw Error(`Registry returned ${n.status}`);let r=(await n.json())[`dist-tags`]??{};return Ej={tags:r,timestamp:t},r}async function jj(e){let t=Dj(e),n=kj(),r=Oj(),i=(await Aj(Ae.publishName))[t];return!i&&t!==`latest`||!i||i===e?null:{currentVersion:e,latestVersion:i,tag:t,packageManager:n,isEphemeral:r}}function Mj(){return`${ke.binName} upgrade`}function Nj(e){let t=`${Ae.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function Pj(e){try{return l(Nj(e),{stdio:`pipe`}),!0}catch{return!1}}const Fj=C.join(r(),ke.configDirName,ke.logsDirName),Ij=C.join(Fj,`cli.log`);let Lj=!1;function Rj(){if(!Lj)try{g(Fj)||_(Fj,{recursive:!0}),Lj=!0}catch{}}function zj(e){return e.length===0?``:` `+e.map(e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `)}function Bj(e,t,n){Rj();let r=`[${new Date().toISOString()}] [${e}] ${t instanceof Error?`${t.message}${t.stack?`
12507
+ `);return a!==-1&&(t=_A(t,i,r,a)),r+t+i};Object.defineProperties(DA.prototype,wA);const NA=DA();DA({level:yA?yA.level:0});var PA=`2.0.0-canary.6`,FA=W(((e,t)=>{t.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:2**53-1||9007199254740991,RELEASE_TYPES:[`major`,`premajor`,`minor`,`preminor`,`patch`,`prepatch`,`prerelease`],SEMVER_SPEC_VERSION:`2.0.0`,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}})),IA=W(((e,t)=>{t.exports=typeof process==`object`&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error(`SEMVER`,...e):()=>{}})),LA=W(((e,t)=>{let{MAX_SAFE_COMPONENT_LENGTH:n,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:i}=FA(),a=IA();e=t.exports={};let o=e.re=[],s=e.safeRe=[],c=e.src=[],l=e.safeSrc=[],u=e.t={},d=0,f=`[a-zA-Z0-9-]`,p=[[`\\s`,1],[`\\d`,i],[f,r]],m=e=>{for(let[t,n]of p)e=e.split(`${t}*`).join(`${t}{0,${n}}`).split(`${t}+`).join(`${t}{1,${n}}`);return e},h=(e,t,n)=>{let r=m(t),i=d++;a(e,i,t),u[e]=i,c[i]=t,l[i]=r,o[i]=new RegExp(t,n?`g`:void 0),s[i]=new RegExp(r,n?`g`:void 0)};h(`NUMERICIDENTIFIER`,`0|[1-9]\\d*`),h(`NUMERICIDENTIFIERLOOSE`,`\\d+`),h(`NONNUMERICIDENTIFIER`,`\\d*[a-zA-Z-]${f}*`),h(`MAINVERSION`,`(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})\\.(${c[u.NUMERICIDENTIFIER]})`),h(`MAINVERSIONLOOSE`,`(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})\\.(${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASEIDENTIFIER`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIER]})`),h(`PRERELEASEIDENTIFIERLOOSE`,`(?:${c[u.NONNUMERICIDENTIFIER]}|${c[u.NUMERICIDENTIFIERLOOSE]})`),h(`PRERELEASE`,`(?:-(${c[u.PRERELEASEIDENTIFIER]}(?:\\.${c[u.PRERELEASEIDENTIFIER]})*))`),h(`PRERELEASELOOSE`,`(?:-?(${c[u.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[u.PRERELEASEIDENTIFIERLOOSE]})*))`),h(`BUILDIDENTIFIER`,`${f}+`),h(`BUILD`,`(?:\\+(${c[u.BUILDIDENTIFIER]}(?:\\.${c[u.BUILDIDENTIFIER]})*))`),h(`FULLPLAIN`,`v?${c[u.MAINVERSION]}${c[u.PRERELEASE]}?${c[u.BUILD]}?`),h(`FULL`,`^${c[u.FULLPLAIN]}$`),h(`LOOSEPLAIN`,`[v=\\s]*${c[u.MAINVERSIONLOOSE]}${c[u.PRERELEASELOOSE]}?${c[u.BUILD]}?`),h(`LOOSE`,`^${c[u.LOOSEPLAIN]}$`),h(`GTLT`,`((?:<|>)?=?)`),h(`XRANGEIDENTIFIERLOOSE`,`${c[u.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),h(`XRANGEIDENTIFIER`,`${c[u.NUMERICIDENTIFIER]}|x|X|\\*`),h(`XRANGEPLAIN`,`[v=\\s]*(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:\\.(${c[u.XRANGEIDENTIFIER]})(?:${c[u.PRERELEASE]})?${c[u.BUILD]}?)?)?`),h(`XRANGEPLAINLOOSE`,`[v=\\s]*(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[u.XRANGEIDENTIFIERLOOSE]})(?:${c[u.PRERELEASELOOSE]})?${c[u.BUILD]}?)?)?`),h(`XRANGE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAIN]}$`),h(`XRANGELOOSE`,`^${c[u.GTLT]}\\s*${c[u.XRANGEPLAINLOOSE]}$`),h(`COERCEPLAIN`,`(^|[^\\d])(\\d{1,${n}})(?:\\.(\\d{1,${n}}))?(?:\\.(\\d{1,${n}}))?`),h(`COERCE`,`${c[u.COERCEPLAIN]}(?:$|[^\\d])`),h(`COERCEFULL`,c[u.COERCEPLAIN]+`(?:${c[u.PRERELEASE]})?(?:${c[u.BUILD]})?(?:$|[^\\d])`),h(`COERCERTL`,c[u.COERCE],!0),h(`COERCERTLFULL`,c[u.COERCEFULL],!0),h(`LONETILDE`,`(?:~>?)`),h(`TILDETRIM`,`(\\s*)${c[u.LONETILDE]}\\s+`,!0),e.tildeTrimReplace=`$1~`,h(`TILDE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAIN]}$`),h(`TILDELOOSE`,`^${c[u.LONETILDE]}${c[u.XRANGEPLAINLOOSE]}$`),h(`LONECARET`,`(?:\\^)`),h(`CARETTRIM`,`(\\s*)${c[u.LONECARET]}\\s+`,!0),e.caretTrimReplace=`$1^`,h(`CARET`,`^${c[u.LONECARET]}${c[u.XRANGEPLAIN]}$`),h(`CARETLOOSE`,`^${c[u.LONECARET]}${c[u.XRANGEPLAINLOOSE]}$`),h(`COMPARATORLOOSE`,`^${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]})$|^$`),h(`COMPARATOR`,`^${c[u.GTLT]}\\s*(${c[u.FULLPLAIN]})$|^$`),h(`COMPARATORTRIM`,`(\\s*)${c[u.GTLT]}\\s*(${c[u.LOOSEPLAIN]}|${c[u.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace=`$1$2$3`,h(`HYPHENRANGE`,`^\\s*(${c[u.XRANGEPLAIN]})\\s+-\\s+(${c[u.XRANGEPLAIN]})\\s*$`),h(`HYPHENRANGELOOSE`,`^\\s*(${c[u.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[u.XRANGEPLAINLOOSE]})\\s*$`),h(`STAR`,`(<|>)?=?\\s*\\*`),h(`GTE0`,`^\\s*>=\\s*0\\.0\\.0\\s*$`),h(`GTE0PRE`,`^\\s*>=\\s*0\\.0\\.0-0\\s*$`)})),RA=W(((e,t)=>{let n=Object.freeze({loose:!0}),r=Object.freeze({});t.exports=e=>e?typeof e==`object`?e:n:r})),zA=W(((e,t)=>{let n=/^[0-9]+$/,r=(e,t)=>{if(typeof e==`number`&&typeof t==`number`)return e===t?0:e<t?-1:1;let r=n.test(e),i=n.test(t);return r&&i&&(e=+e,t=+t),e===t?0:r&&!i?-1:i&&!r?1:e<t?-1:1};t.exports={compareIdentifiers:r,rcompareIdentifiers:(e,t)=>r(t,e)}})),BA=W(((e,t)=>{let n=IA(),{MAX_LENGTH:r,MAX_SAFE_INTEGER:i}=FA(),{safeRe:a,t:o}=LA(),s=RA(),{compareIdentifiers:c}=zA();t.exports=class e{constructor(t,c){if(c=s(c),t instanceof e){if(t.loose===!!c.loose&&t.includePrerelease===!!c.includePrerelease)return t;t=t.version}else if(typeof t!=`string`)throw TypeError(`Invalid version. Must be a string. Got type "${typeof t}".`);if(t.length>r)throw TypeError(`version is longer than ${r} characters`);n(`SemVer`,t,c),this.options=c,this.loose=!!c.loose,this.includePrerelease=!!c.includePrerelease;let l=t.trim().match(c.loose?a[o.LOOSE]:a[o.FULL]);if(!l)throw TypeError(`Invalid Version: ${t}`);if(this.raw=t,this.major=+l[1],this.minor=+l[2],this.patch=+l[3],this.major>i||this.major<0)throw TypeError(`Invalid major version`);if(this.minor>i||this.minor<0)throw TypeError(`Invalid minor version`);if(this.patch>i||this.patch<0)throw TypeError(`Invalid patch version`);l[4]?this.prerelease=l[4].split(`.`).map(e=>{if(/^[0-9]+$/.test(e)){let t=+e;if(t>=0&&t<i)return t}return e}):this.prerelease=[],this.build=l[5]?l[5].split(`.`):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(`.`)}`),this.version}toString(){return this.version}compare(t){if(n(`SemVer.compare`,this.version,this.options,t),!(t instanceof e)){if(typeof t==`string`&&t===this.version)return 0;t=new e(t,this.options)}return t.version===this.version?0:this.compareMain(t)||this.comparePre(t)}compareMain(t){return t instanceof e||(t=new e(t,this.options)),this.major<t.major?-1:this.major>t.major?1:this.minor<t.minor?-1:this.minor>t.minor?1:this.patch<t.patch?-1:this.patch>t.patch?1:0}comparePre(t){if(t instanceof e||(t=new e(t,this.options)),this.prerelease.length&&!t.prerelease.length)return-1;if(!this.prerelease.length&&t.prerelease.length)return 1;if(!this.prerelease.length&&!t.prerelease.length)return 0;let r=0;do{let e=this.prerelease[r],i=t.prerelease[r];if(n(`prerelease compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}compareBuild(t){t instanceof e||(t=new e(t,this.options));let r=0;do{let e=this.build[r],i=t.build[r];if(n(`build compare`,r,e,i),e===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(e===void 0)return-1;if(e===i)continue;return c(e,i)}while(++r)}inc(e,t,n){if(e.startsWith(`pre`)){if(!t&&n===!1)throw Error(`invalid increment argument: identifier is empty`);if(t){let e=`-${t}`.match(this.options.loose?a[o.PRERELEASELOOSE]:a[o.PRERELEASE]);if(!e||e[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case`premajor`:this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(`pre`,t,n);break;case`preminor`:this.prerelease.length=0,this.patch=0,this.minor++,this.inc(`pre`,t,n);break;case`prepatch`:this.prerelease.length=0,this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`prerelease`:this.prerelease.length===0&&this.inc(`patch`,t,n),this.inc(`pre`,t,n);break;case`release`:if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case`major`:(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case`minor`:(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case`patch`:this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case`pre`:{let e=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)typeof this.prerelease[r]==`number`&&(this.prerelease[r]++,r=-2);if(r===-1){if(t===this.prerelease.join(`.`)&&n===!1)throw Error(`invalid increment argument: identifier already exists`);this.prerelease.push(e)}}if(t){let r=[t,e];n===!1&&(r=[t]),c(this.prerelease[0],t)===0?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(`.`)}`),this}}})),VA=W(((e,t)=>{let n=BA();t.exports=(e,t,r=!1)=>{if(e instanceof n)return e;try{return new n(e,t)}catch(e){if(!r)return null;throw e}}})),HA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e,t);return r?r.version:null}})),UA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e.trim().replace(/^[=v]+/,``),t);return r?r.version:null}})),WA=W(((e,t)=>{let n=BA();t.exports=(e,t,r,i,a)=>{typeof r==`string`&&(a=i,i=r,r=void 0);try{return new n(e instanceof n?e.version:e,r).inc(t,i,a).version}catch{return null}}})),GA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e,null,!0),i=n(t,null,!0),a=r.compare(i);if(a===0)return null;let o=a>0,s=o?r:i,c=o?i:r,l=!!s.prerelease.length;if(c.prerelease.length&&!l){if(!c.patch&&!c.minor)return`major`;if(c.compareMain(s)===0)return c.minor&&!c.patch?`minor`:`patch`}let u=l?`pre`:``;return r.major===i.major?r.minor===i.minor?r.patch===i.patch?`prerelease`:u+`patch`:u+`minor`:u+`major`}})),KA=W(((e,t)=>{let n=BA();t.exports=(e,t)=>new n(e,t).major})),qA=W(((e,t)=>{let n=BA();t.exports=(e,t)=>new n(e,t).minor})),JA=W(((e,t)=>{let n=BA();t.exports=(e,t)=>new n(e,t).patch})),YA=W(((e,t)=>{let n=VA();t.exports=(e,t)=>{let r=n(e,t);return r&&r.prerelease.length?r.prerelease:null}})),XA=W(((e,t)=>{let n=BA();t.exports=(e,t,r)=>new n(e,r).compare(new n(t,r))})),ZA=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(t,e,r)})),QA=W(((e,t)=>{let n=XA();t.exports=(e,t)=>n(e,t,!0)})),$A=W(((e,t)=>{let n=BA();t.exports=(e,t,r)=>{let i=new n(e,r),a=new n(t,r);return i.compare(a)||i.compareBuild(a)}})),ej=W(((e,t)=>{let n=$A();t.exports=(e,t)=>e.sort((e,r)=>n(e,r,t))})),tj=W(((e,t)=>{let n=$A();t.exports=(e,t)=>e.sort((e,r)=>n(r,e,t))})),nj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)>0})),rj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)<0})),ij=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)===0})),aj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)!==0})),oj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)>=0})),sj=W(((e,t)=>{let n=XA();t.exports=(e,t,r)=>n(e,t,r)<=0})),cj=W(((e,t)=>{let n=ij(),r=aj(),i=nj(),a=oj(),o=rj(),s=sj();t.exports=(e,t,c,l)=>{switch(t){case`===`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e===c;case`!==`:return typeof e==`object`&&(e=e.version),typeof c==`object`&&(c=c.version),e!==c;case``:case`=`:case`==`:return n(e,c,l);case`!=`:return r(e,c,l);case`>`:return i(e,c,l);case`>=`:return a(e,c,l);case`<`:return o(e,c,l);case`<=`:return s(e,c,l);default:throw TypeError(`Invalid operator: ${t}`)}}})),lj=W(((e,t)=>{let n=BA(),r=VA(),{safeRe:i,t:a}=LA();t.exports=(e,t)=>{if(e instanceof n)return e;if(typeof e==`number`&&(e=String(e)),typeof e!=`string`)return null;t||={};let o=null;if(!t.rtl)o=e.match(t.includePrerelease?i[a.COERCEFULL]:i[a.COERCE]);else{let n=t.includePrerelease?i[a.COERCERTLFULL]:i[a.COERCERTL],r;for(;(r=n.exec(e))&&(!o||o.index+o[0].length!==e.length);)(!o||r.index+r[0].length!==o.index+o[0].length)&&(o=r),n.lastIndex=r.index+r[1].length+r[2].length;n.lastIndex=-1}if(o===null)return null;let s=o[2];return r(`${s}.${o[3]||`0`}.${o[4]||`0`}${t.includePrerelease&&o[5]?`-${o[5]}`:``}${t.includePrerelease&&o[6]?`+${o[6]}`:``}`,t)}})),uj=W(((e,t)=>{t.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}})),dj=W(((e,t)=>{let n=/\s+/g;t.exports=class e{constructor(t,r){if(r=i(r),t instanceof e)return t.loose===!!r.loose&&t.includePrerelease===!!r.includePrerelease?t:new e(t.raw,r);if(t instanceof a)return this.raw=t.value,this.set=[[t]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=t.trim().replace(n,` `),this.set=this.raw.split(`||`).map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let e=this.set[0];if(this.set=this.set.filter(e=>!h(e[0])),this.set.length===0)this.set=[e];else if(this.set.length>1){for(let e of this.set)if(e.length===1&&g(e[0])){this.set=[e];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted=``;for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+=`||`);let t=this.set[e];for(let e=0;e<t.length;e++)e>0&&(this.formatted+=` `),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let t=((this.options.includePrerelease&&p)|(this.options.loose&&m))+`:`+e,n=r.get(t);if(n)return n;let i=this.options.loose,s=i?c[l.HYPHENRANGELOOSE]:c[l.HYPHENRANGE];e=e.replace(s,O(this.options.includePrerelease)),o(`hyphen replace`,e),e=e.replace(c[l.COMPARATORTRIM],u),o(`comparator trim`,e),e=e.replace(c[l.TILDETRIM],d),o(`tilde trim`,e),e=e.replace(c[l.CARETTRIM],f),o(`caret trim`,e);let g=e.split(` `).map(e=>v(e,this.options)).join(` `).split(/\s+/).map(e=>D(e,this.options));i&&(g=g.filter(e=>(o(`loose invalid filter`,e,this.options),!!e.match(c[l.COMPARATORLOOSE])))),o(`range list`,g);let _=new Map,y=g.map(e=>new a(e,this.options));for(let e of y){if(h(e))return[e];_.set(e.value,e)}_.size>1&&_.has(``)&&_.delete(``);let b=[..._.values()];return r.set(t,b),b}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Range is required`);return this.set.some(e=>_(e,n)&&t.set.some(t=>_(t,n)&&e.every(e=>t.every(t=>e.intersects(t,n)))))}test(e){if(!e)return!1;if(typeof e==`string`)try{e=new s(e,this.options)}catch{return!1}for(let t=0;t<this.set.length;t++)if(k(this.set[t],e,this.options))return!0;return!1}};let r=new(uj()),i=RA(),a=fj(),o=IA(),s=BA(),{safeRe:c,t:l,comparatorTrimReplace:u,tildeTrimReplace:d,caretTrimReplace:f}=LA(),{FLAG_INCLUDE_PRERELEASE:p,FLAG_LOOSE:m}=FA(),h=e=>e.value===`<0.0.0-0`,g=e=>e.value===``,_=(e,t)=>{let n=!0,r=e.slice(),i=r.pop();for(;n&&r.length;)n=r.every(e=>i.intersects(e,t)),i=r.pop();return n},v=(e,t)=>(e=e.replace(c[l.BUILD],``),o(`comp`,e,t),e=S(e,t),o(`caret`,e),e=b(e,t),o(`tildes`,e),e=w(e,t),o(`xrange`,e),e=E(e,t),o(`stars`,e),e),y=e=>!e||e.toLowerCase()===`x`||e===`*`,b=(e,t)=>e.trim().split(/\s+/).map(e=>x(e,t)).join(` `),x=(e,t)=>{let n=t.loose?c[l.TILDELOOSE]:c[l.TILDE];return e.replace(n,(t,n,r,i,a)=>{o(`tilde`,e,t,n,r,i,a);let s;return y(n)?s=``:y(r)?s=`>=${n}.0.0 <${+n+1}.0.0-0`:y(i)?s=`>=${n}.${r}.0 <${n}.${+r+1}.0-0`:a?(o(`replaceTilde pr`,a),s=`>=${n}.${r}.${i}-${a} <${n}.${+r+1}.0-0`):s=`>=${n}.${r}.${i} <${n}.${+r+1}.0-0`,o(`tilde return`,s),s})},S=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(` `),C=(e,t)=>{o(`caret`,e,t);let n=t.loose?c[l.CARETLOOSE]:c[l.CARET],r=t.includePrerelease?`-0`:``;return e.replace(n,(t,n,i,a,s)=>{o(`caret`,e,t,n,i,a,s);let c;return y(n)?c=``:y(i)?c=`>=${n}.0.0${r} <${+n+1}.0.0-0`:y(a)?c=n===`0`?`>=${n}.${i}.0${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.0${r} <${+n+1}.0.0-0`:s?(o(`replaceCaret pr`,s),c=n===`0`?i===`0`?`>=${n}.${i}.${a}-${s} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}-${s} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a}-${s} <${+n+1}.0.0-0`):(o(`no pr`),c=n===`0`?i===`0`?`>=${n}.${i}.${a}${r} <${n}.${i}.${+a+1}-0`:`>=${n}.${i}.${a}${r} <${n}.${+i+1}.0-0`:`>=${n}.${i}.${a} <${+n+1}.0.0-0`),o(`caret return`,c),c})},w=(e,t)=>(o(`replaceXRanges`,e,t),e.split(/\s+/).map(e=>T(e,t)).join(` `)),T=(e,t)=>{e=e.trim();let n=t.loose?c[l.XRANGELOOSE]:c[l.XRANGE];return e.replace(n,(n,r,i,a,s,c)=>{o(`xRange`,e,n,r,i,a,s,c);let l=y(i),u=l||y(a),d=u||y(s),f=d;return r===`=`&&f&&(r=``),c=t.includePrerelease?`-0`:``,l?n=r===`>`||r===`<`?`<0.0.0-0`:`*`:r&&f?(u&&(a=0),s=0,r===`>`?(r=`>=`,u?(i=+i+1,a=0,s=0):(a=+a+1,s=0)):r===`<=`&&(r=`<`,u?i=+i+1:a=+a+1),r===`<`&&(c=`-0`),n=`${r+i}.${a}.${s}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${a}.0${c} <${i}.${+a+1}.0-0`),o(`xRange return`,n),n})},E=(e,t)=>(o(`replaceStars`,e,t),e.trim().replace(c[l.STAR],``)),D=(e,t)=>(o(`replaceGTE0`,e,t),e.trim().replace(c[t.includePrerelease?l.GTE0PRE:l.GTE0],``)),O=e=>(t,n,r,i,a,o,s,c,l,u,d,f)=>(n=y(r)?``:y(i)?`>=${r}.0.0${e?`-0`:``}`:y(a)?`>=${r}.${i}.0${e?`-0`:``}`:o?`>=${n}`:`>=${n}${e?`-0`:``}`,c=y(l)?``:y(u)?`<${+l+1}.0.0-0`:y(d)?`<${l}.${+u+1}.0-0`:f?`<=${l}.${u}.${d}-${f}`:e?`<${l}.${u}.${+d+1}-0`:`<=${c}`,`${n} ${c}`.trim()),k=(e,t,n)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(let n=0;n<e.length;n++)if(o(e[n].semver),e[n].semver!==a.ANY&&e[n].semver.prerelease.length>0){let r=e[n].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}})),fj=W(((e,t)=>{let n=Symbol(`SemVer ANY`);t.exports=class e{static get ANY(){return n}constructor(t,i){if(i=r(i),t instanceof e){if(t.loose===!!i.loose)return t;t=t.value}t=t.trim().split(/\s+/).join(` `),s(`comparator`,t,i),this.options=i,this.loose=!!i.loose,this.parse(t),this.semver===n?this.value=``:this.value=this.operator+this.semver.version,s(`comp`,this)}parse(e){let t=this.options.loose?i[a.COMPARATORLOOSE]:i[a.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);this.operator=r[1]===void 0?``:r[1],this.operator===`=`&&(this.operator=``),r[2]?this.semver=new c(r[2],this.options.loose):this.semver=n}toString(){return this.value}test(e){if(s(`Comparator.test`,e,this.options.loose),this.semver===n||e===n)return!0;if(typeof e==`string`)try{e=new c(e,this.options)}catch{return!1}return o(e,this.operator,this.semver,this.options)}intersects(t,n){if(!(t instanceof e))throw TypeError(`a Comparator is required`);return this.operator===``?this.value===``?!0:new l(t.value,n).test(this.value):t.operator===``?t.value===``?!0:new l(this.value,n).test(t.semver):(n=r(n),n.includePrerelease&&(this.value===`<0.0.0-0`||t.value===`<0.0.0-0`)||!n.includePrerelease&&(this.value.startsWith(`<0.0.0`)||t.value.startsWith(`<0.0.0`))?!1:!!(this.operator.startsWith(`>`)&&t.operator.startsWith(`>`)||this.operator.startsWith(`<`)&&t.operator.startsWith(`<`)||this.semver.version===t.semver.version&&this.operator.includes(`=`)&&t.operator.includes(`=`)||o(this.semver,`<`,t.semver,n)&&this.operator.startsWith(`>`)&&t.operator.startsWith(`<`)||o(this.semver,`>`,t.semver,n)&&this.operator.startsWith(`<`)&&t.operator.startsWith(`>`)))}};let r=RA(),{safeRe:i,t:a}=LA(),o=cj(),s=IA(),c=BA(),l=dj()})),pj=W(((e,t)=>{let n=dj();t.exports=(e,t,r)=>{try{t=new n(t,r)}catch{return!1}return t.test(e)}})),mj=W(((e,t)=>{let n=dj();t.exports=(e,t)=>new n(e,t).set.map(e=>e.map(e=>e.value).join(` `).trim().split(` `))})),hj=W(((e,t)=>{let n=BA(),r=dj();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===-1)&&(a=e,o=new n(a,i))}),a}})),gj=W(((e,t)=>{let n=BA(),r=dj();t.exports=(e,t,i)=>{let a=null,o=null,s=null;try{s=new r(t,i)}catch{return null}return e.forEach(e=>{s.test(e)&&(!a||o.compare(e)===1)&&(a=e,o=new n(a,i))}),a}})),_j=W(((e,t)=>{let n=BA(),r=dj(),i=nj();t.exports=(e,t)=>{e=new r(e,t);let a=new n(`0.0.0`);if(e.test(a)||(a=new n(`0.0.0-0`),e.test(a)))return a;a=null;for(let t=0;t<e.set.length;++t){let r=e.set[t],o=null;r.forEach(e=>{let t=new n(e.semver.version);switch(e.operator){case`>`:t.prerelease.length===0?t.patch++:t.prerelease.push(0),t.raw=t.format();case``:case`>=`:(!o||i(t,o))&&(o=t);break;case`<`:case`<=`:break;default:throw Error(`Unexpected operation: ${e.operator}`)}}),o&&(!a||i(a,o))&&(a=o)}return a&&e.test(a)?a:null}})),vj=W(((e,t)=>{let n=dj();t.exports=(e,t)=>{try{return new n(e,t).range||`*`}catch{return null}}})),yj=W(((e,t)=>{let n=BA(),r=fj(),{ANY:i}=r,a=dj(),o=pj(),s=nj(),c=rj(),l=sj(),u=oj();t.exports=(e,t,d,f)=>{e=new n(e,f),t=new a(t,f);let p,m,h,g,_;switch(d){case`>`:p=s,m=l,h=c,g=`>`,_=`>=`;break;case`<`:p=c,m=u,h=s,g=`<`,_=`<=`;break;default:throw TypeError(`Must provide a hilo val of "<" or ">"`)}if(o(e,t,f))return!1;for(let n=0;n<t.set.length;++n){let a=t.set[n],o=null,s=null;if(a.forEach(e=>{e.semver===i&&(e=new r(`>=0.0.0`)),o||=e,s||=e,p(e.semver,o.semver,f)?o=e:h(e.semver,s.semver,f)&&(s=e)}),o.operator===g||o.operator===_||(!s.operator||s.operator===g)&&m(e,s.semver)||s.operator===_&&h(e,s.semver))return!1}return!0}})),bj=W(((e,t)=>{let n=yj();t.exports=(e,t,r)=>n(e,t,`>`,r)})),xj=W(((e,t)=>{let n=yj();t.exports=(e,t,r)=>n(e,t,`<`,r)})),Sj=W(((e,t)=>{let n=dj();t.exports=(e,t,r)=>(e=new n(e,r),t=new n(t,r),e.intersects(t,r))})),Cj=W(((e,t)=>{let n=pj(),r=XA();t.exports=(e,t,i)=>{let a=[],o=null,s=null,c=e.sort((e,t)=>r(e,t,i));for(let e of c)n(e,t,i)?(s=e,o||=e):(s&&a.push([o,s]),s=null,o=null);o&&a.push([o,null]);let l=[];for(let[e,t]of a)e===t?l.push(e):!t&&e===c[0]?l.push(`*`):t?e===c[0]?l.push(`<=${t}`):l.push(`${e} - ${t}`):l.push(`>=${e}`);let u=l.join(` || `),d=typeof t.raw==`string`?t.raw:String(t);return u.length<d.length?u:t}})),wj=W(((e,t)=>{let n=dj(),r=fj(),{ANY:i}=r,a=pj(),o=XA(),s=(e,t,r={})=>{if(e===t)return!0;e=new n(e,r),t=new n(t,r);let i=!1;OUTER:for(let n of e.set){for(let e of t.set){let t=u(n,e,r);if(i||=t!==null,t)continue OUTER}if(i)return!1}return!0},c=[new r(`>=0.0.0-0`)],l=[new r(`>=0.0.0`)],u=(e,t,n)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===i){if(t.length===1&&t[0].semver===i)return!0;e=n.includePrerelease?c:l}if(t.length===1&&t[0].semver===i){if(n.includePrerelease)return!0;t=l}let r=new Set,s,u;for(let t of e)t.operator===`>`||t.operator===`>=`?s=d(s,t,n):t.operator===`<`||t.operator===`<=`?u=f(u,t,n):r.add(t.semver);if(r.size>1)return null;let p;if(s&&u&&(p=o(s.semver,u.semver,n),p>0||p===0&&(s.operator!==`>=`||u.operator!==`<=`)))return null;for(let e of r){if(s&&!a(e,String(s),n)||u&&!a(e,String(u),n))return null;for(let r of t)if(!a(e,String(r),n))return!1;return!0}let m,h,g,_,v=u&&!n.includePrerelease&&u.semver.prerelease.length?u.semver:!1,y=s&&!n.includePrerelease&&s.semver.prerelease.length?s.semver:!1;v&&v.prerelease.length===1&&u.operator===`<`&&v.prerelease[0]===0&&(v=!1);for(let e of t){if(_=_||e.operator===`>`||e.operator===`>=`,g=g||e.operator===`<`||e.operator===`<=`,s){if(y&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===y.major&&e.semver.minor===y.minor&&e.semver.patch===y.patch&&(y=!1),e.operator===`>`||e.operator===`>=`){if(m=d(s,e,n),m===e&&m!==s)return!1}else if(s.operator===`>=`&&!a(s.semver,String(e),n))return!1}if(u){if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),e.operator===`<`||e.operator===`<=`){if(h=f(u,e,n),h===e&&h!==u)return!1}else if(u.operator===`<=`&&!a(u.semver,String(e),n))return!1}if(!e.operator&&(u||s)&&p!==0)return!1}return!(s&&g&&!u&&p!==0||u&&_&&!s&&p!==0||y||v)},d=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r>0?e:r<0||t.operator===`>`&&e.operator===`>=`?t:e},f=(e,t,n)=>{if(!e)return t;let r=o(e.semver,t.semver,n);return r<0?e:r>0||t.operator===`<`&&e.operator===`<=`?t:e};t.exports=s})),Tj=W(((e,t)=>{let n=LA(),r=FA(),i=BA(),a=zA();t.exports={parse:VA(),valid:HA(),clean:UA(),inc:WA(),diff:GA(),major:KA(),minor:qA(),patch:JA(),prerelease:YA(),compare:XA(),rcompare:ZA(),compareLoose:QA(),compareBuild:$A(),sort:ej(),rsort:tj(),gt:nj(),lt:rj(),eq:ij(),neq:aj(),gte:oj(),lte:sj(),cmp:cj(),coerce:lj(),Comparator:fj(),Range:dj(),satisfies:pj(),toComparators:mj(),maxSatisfying:hj(),minSatisfying:gj(),minVersion:_j(),validRange:vj(),outside:yj(),gtr:bj(),ltr:xj(),intersects:Sj(),simplifyRange:Cj(),subset:wj(),SemVer:i,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:r.SEMVER_SPEC_VERSION,RELEASE_TYPES:r.RELEASE_TYPES,compareIdentifiers:a.compareIdentifiers,rcompareIdentifiers:a.rcompareIdentifiers}}))();let Ej=null;function Dj(e){let t=(0,Tj.prerelease)(e);return t&&t.length>0&&typeof t[0]==`string`?t[0]:`latest`}function Oj(){let e=process.env.npm_command;if(e===`exec`||e===`dlx`)return!0;let t=process.argv[1]??``;return!!/_npx[/\\]|[/\\]dlx[/\\]|\.cache[/\\]/.test(t)}function kj(){let e=process.env.npm_config_user_agent;if(e){let t=e.split(`/`)[0];if(t===`yarn`||t===`pnpm`||t===`bun`||t===`npm`)return t}let t=process.argv[1]??``;return t.includes(`yarn`)?`yarn`:t.includes(`pnpm`)?`pnpm`:t.includes(`bun`)?`bun`:`npm`}async function Aj(e){let t=Date.now();if(Ej&&t-Ej.timestamp<6e4)return Ej.tags;let n=await fetch(`https://registry.npmjs.org/${e}`,{signal:AbortSignal.timeout(1e4),headers:{accept:`application/json`}});if(!n.ok)throw Error(`Registry returned ${n.status}`);let r=(await n.json())[`dist-tags`]??{};return Ej={tags:r,timestamp:t},r}async function jj(e){let t=Dj(e),n=kj(),r=Oj(),i=(await Aj(Ae.publishName))[t];return!i&&t!==`latest`||!i||i===e?null:{currentVersion:e,latestVersion:i,tag:t,packageManager:n,isEphemeral:r}}function Mj(){return`${ke.binName} upgrade`}function Nj(e){let t=`${Ae.publishName}@${e.tag}`;switch(e.packageManager){case`yarn`:return`yarn global add ${t}`;case`pnpm`:return`pnpm add -g ${t}`;case`bun`:return`bun add -g ${t}`;default:return`npm install -g ${t}`}}function Pj(e){try{return l(Nj(e),{stdio:`pipe`}),!0}catch{return!1}}const Fj=C.join(r(),ke.configDirName,ke.logsDirName),Ij=C.join(Fj,`cli.log`);let Lj=!1;function Rj(){if(!Lj)try{g(Fj)||_(Fj,{recursive:!0}),Lj=!0}catch{}}function zj(e){return e.length===0?``:` `+e.map(e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `)}function Bj(e,t,n){Rj();let r=`[${new Date().toISOString()}] [${e}] ${t instanceof Error?`${t.message}${t.stack?`
12508
12508
  `+t.stack:``}`:String(t)}${zj(n)}\n`;try{m(Ij,r)}catch{}}const Vj={error(e,...t){Bj(`ERROR`,e,t)},warn(e,...t){Bj(`WARN`,e,t)},info(e,...t){Bj(`INFO`,e,t)},debug(...e){Bj(`DEBUG`,e[0]??``,e.slice(1))},trace(e,...t){Bj(`TRACE`,e,t)}},Hj=new Set,Uj=new Set,Wj=new Set;let Gj=!1,Kj=!1,qj=null,Jj;async function Yj(e){let t=e.map(e=>new Promise(t=>{let n=`writableLength`in e?e.writableLength:0;if((`bufferSize`in e?e.bufferSize:n)===0){t();return}let r=e.write.bind(e),i=!1,a=()=>{let n=`writableLength`in e?e.writableLength:0;(`bufferSize`in e?e.bufferSize:n)===0&&!i&&(i=!0,e.write=r,t())};e.once(`drain`,a),e.write(``,`utf-8`,()=>{a()}),e.write=function(){return!1}}));await Promise.all(t)}async function Xj(e,t,n,r){if(Gj)return;r?.debug?.(`Executing exit handlers`,{shouldManuallyExit:e,isSynchronous:t,signal:n,asyncCallbacks:Hj.size,syncCallbacks:Uj.size}),Gj=!0,Hj.size>0&&t&&console.error([`SYNCHRONOUS TERMINATION NOTICE:`,`When explicitly exiting the process via process.exit or via a parent process,`,`asynchronous tasks in your exitHooks will not run. Either remove these tasks,`,`use gracefulExit() instead of process.exit(), or ensure your parent process`,`sends a SIGINT to the process running this code.`].join(` `));let i=0;n>0?i=128+n:Jj===void 0?(typeof U.exitCode==`number`||typeof U.exitCode==`string`)&&(i=Number(U.exitCode)):i=Jj;let a=(t=!1)=>{(t||e)&&(qj?qj.call(U,i):U.exit(i))};for(let e of Uj)try{e(i)}catch(e){console.error(`Error in synchronous exit hook:`,e)}if(t){a();return}let o=[],s=0;for(let[e,t]of Hj)s=Math.max(s,t),o.push(Promise.resolve(e(i)).catch(e=>{console.error(`Error in asynchronous exit hook:`,e)}));let c=Array.from(Wj);c.length>0&&o.push(Yj(c));let l=setTimeout(()=>{a(!0)},s);try{await Promise.all(o),clearTimeout(l),a()}catch(e){clearTimeout(l),console.error(`Error during exit cleanup:`,e),a(!0)}}function Zj(){Kj||(Kj=!0,U.once(`beforeExit`,()=>{Xj(!0,!1,-128)}),U.once(`SIGINT`,()=>{Xj(!0,!1,2)}),U.once(`SIGTERM`,()=>{Xj(!0,!1,15)}),U.once(`exit`,()=>{Xj(!1,!0,0)}),U.on(`message`,e=>{e===`shutdown`&&Xj(!0,!0,-128)}),qj||(qj=U.exit.bind(U),U.exit=function(e){if(Jj===void 0&&(Jj=e??0),Hj.size===0&&Wj.size===0){if(qj){qj(e??0);return}U.exit(e??0)}Xj(!0,!1,-128).catch(e=>{console.error(`Error during exit:`,e),qj?qj(1):U.exit(1)})}))}function Qj(e,t){if(typeof e!=`function`)throw TypeError(`callback must be a function`);if(Gj)throw Error(`Cannot install exit hook while exit handlers are running`);t?.logger?.debug?.(`Registering exit hook`,{wait:t?.wait,hasStreams:t?.streams!==void 0}),Zj();let n=t?.wait??0,r=t?.streams??[U.stdout,U.stderr];if(n>0){let t=[e,n];Hj.add(t);for(let e of r)Wj.add(e);return()=>{Hj.delete(t);for(let e of r)Wj.delete(e)}}return Uj.add(e),()=>{Uj.delete(e)}}function $j(e){e!==void 0&&(U.exitCode=e),Xj(!0,!1,-128)}async function eM(){let e=await Qk.create();return{apiClient:new Oe(e,{error:(e,...t)=>Vj.error(e,...t),debug:(...e)=>Vj.debug(...e),warn:(e,...t)=>Vj.warn(e,...t)}),authManager:e}}function tM(e){process.stdout.write(JSON.stringify(e)+`
12509
12509
  `)}async function nM(e,t){if(!e.isAuthenticated()){try{if((await t.getUserInfo())?.result?.email)return}catch{}console.error(`Error: Not authenticated. Please set ${ke.envPrefix}API_KEY environment variable.`),console.error(`You can obtain your API key by visiting: https://abacus.ai/app/abacusai-cli`),console.error(`\nUsage: ${ke.envPrefix}API_KEY=your_key_here abacusai --print "your prompt"`),process.exit(1)}}function rM(e,t){let n=e=>{let n=e.toLowerCase();if(n===t)return 1e3;if(n.startsWith(t))return 900;let r=0,i=-1;for(let e of t){let t=n.indexOf(e,i+1);if(t===-1)return 0;r+=100-(t-i),i=t}return r+=Math.max(0,50-n.length),r},r=null,i=0;for(let t of e){let e=Math.max(n(t.name??``),n(t.llmName));e>i&&(i=e,r=t.llmName)}return i>=100?r:null}async function iM(e,t){let n=(await e.listLLMModels())?.result??[];return n.length||(console.error(`Error: No models available. Check your API key and connection.`),process.exit(1)),t?rM(n,t.toLowerCase())||(console.error(`Warning: Model "${t}" not found. Using default: ${n[0].llmName}`),n[0].llmName):n[0].llmName}async function aM(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(`CODE_LLM_AGENT`))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}return e?.conversationId}async function oM({agentArgs:e}){let{apiClient:t,authManager:n}=await eM();jj(PA).then(e=>{if(e){let t=e.isEphemeral?`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag})\n`:`\nUpdate available: ${e.currentVersion} → ${e.latestVersion} (${e.tag}). Run: ${Mj()}\n`;process.stderr.write(t)}}).catch(()=>{}),await nM(n,t);let r=process.cwd(),i=new Bk({cwd:r});await i.load();let a=i.get(`baseUrl`);if(a){try{new URL(a)}catch{console.error(`Invalid baseUrl: ${a}`),process.exit(1)}t.setUrl(a),t.resetEndpoints(),await t.getApiEndpoint()}let o=e?.[`output-format`]??`text`,s=await iM(t,e?.model),c=xl.Yolo,l=e?.[`permission-mode`];if(l)switch(l){case`normal`:c=xl.Normal;break;case`accept-edits`:c=xl.AcceptEdits;break;case`plan`:c=xl.PlanMode;break;default:c=xl.Yolo;break}let u=new Mk({allowedDirectories:[r,...e?.[`add-dir`]?.map(e=>C.isAbsolute(e)?e:C.resolve(r,e))??[]],primaryWorkspace:r,apiClient:t,mode:c,model:s,permissionProvider:new Nk,config:i,isPrintMode:!0,enablePromptRewrite:!1,supportsThoughtStreaming:!0,cliAllowedTools:e?.[`allowed-tools`],cliDisallowedTools:e?.[`disallowed-tools`]});Qj(async()=>{u.stop(),await new Promise(e=>setTimeout(e,200))},{wait:1e3});let d=await aM(e,t);d&&await u.loadConversation(d);let f=e?.prompt??``;process.env.DEEPAGENT_HIGH_QUALITY===`true`&&(f=`
12510
12510
  IMPORTANT INSTRUCTIONS: Your task is to follow the <task_description> EXACTLY and verify the solution within the FIXED TIME LIMIT.
@@ -12589,7 +12589,7 @@ No matching component was found for:
12589
12589
  `).map(e=>IF(e,i)).join(`
12590
12590
  `):t===`truncate-start`&&(r=r.split(`
12591
12591
  `).map(e=>FF(e,i)).join(`
12592
- `))}}r=QF(e,r),e.renderCache={lines:[r],width:n,height:0,left:l,top:u},t.write(l,u,r,d)}else e.renderCache=void 0;e.renderDirty=!1;return}let f=!1;if(e.nodeName===`jar-view`){e.style.backgroundColor&&$F(l,u,e,t),e.style.borderStyle&&qF(l,u,e,t);let n=e.style.overflowX===`hidden`||e.style.overflow===`hidden`,r=e.style.overflowY===`hidden`||e.style.overflow===`hidden`;if(n||r){let i=n?l+XF(e.style,`Left`):void 0,a=n?l+c.getComputedWidth()-XF(e.style,`Right`):void 0,o=r?u+XF(e.style,`Top`):void 0,s=r?u+c.getComputedHeight()-XF(e.style,`Bottom`):void 0;t.clip({x1:i,x2:a,y1:o,y2:s}),f=!0}}if(e.nodeName===`jar-root`||e.nodeName===`jar-view`){let n=f?u+XF(e.style,`Top`):o,r=f?u+c.getComputedHeight()-XF(e.style,`Bottom`):s;for(let i of e.childNodes)eI(i,t,{offsetX:l,offsetY:u,transformers:d,clipY1:n,clipY2:r});f&&t.unclip()}e.renderDirty=!1};var tI=class{rootNode;lastWidth=0;cachedLines=null;output=new BF(0,0);constructor(e){this.rootNode=e}notifyCommit(){this.cachedLines=null}render(e){let t=e!==this.lastWidth;if(t&&(this.clearAllRenderCaches(this.rootNode),this.lastWidth=e),this.cachedLines&&!this.rootNode.renderDirty&&!t)return this.cachedLines;this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,1);let n=Math.ceil(this.rootNode.yogaNode.getComputedHeight());if(n<=0)return this.cachedLines=[],this.cachedLines;this.output.reset(e,n),eI(this.rootNode,this.output,{});let r=this.output.get(),i=!1;for(let t of r)if(RM(t)>e){i=!0;break}return this.cachedLines=i?r.map(t=>RM(t)>e?KM(t,e):t):r,this.cachedLines}invalidate(){this.cachedLines=null,this.clearAllRenderCaches(this.rootNode)}clearAllRenderCaches(e){e.renderDirty=!0,e.renderCache=void 0;for(let t of e.childNodes)t.nodeName!==`#text`&&this.clearAllRenderCaches(t)}},nI=class{tui;terminal;rootNode;bridge;container;exitCallbacks=[];exitPromise;resolveExit;exitOnCtrlC;ownsTui;suspendable;onSuspended;cleanupSuspend;constructor(e={}){this.exitOnCtrlC=e.exitOnCtrlC??!0,this.suspendable=e.suspendable??!1,this.onSuspended=e.onSuspended,e.tui?(this.tui=e.tui,this.terminal=e.tui.terminal,this.ownsTui=!1):e.terminal?(this.terminal=e.terminal,this.tui=new AN(this.terminal),this.ownsTui=!0):(this.terminal=new BN,this.tui=new AN(this.terminal),this.ownsTui=!0),this.rootNode=fF(`jar-root`),this.rootNode.yogaNode.setFlexDirection(0),this.rootNode.yogaNode.setFlexGrow(1),this.rootNode.onRender=()=>{this.bridge.notifyCommit(),this.tui.requestRender(),performance.clearMeasures()},this.bridge=new tI(this.rootNode),this.tui.addChild(this.bridge),this.container=DF.createContainer(this.rootNode,0,null,!1,null,`jar`,()=>{},()=>{},()=>{},()=>{}),this.exitPromise=new Promise(e=>{this.resolveExit=e}),this.exitOnCtrlC&&this.tui.addInputListener(e=>{if(!uN(e)&&_N(e,`ctrl+c`))return this.exit(),{consume:!0}})}render(e){DF.updateContainerSync(e,this.container,null),DF.flushSyncWork()}start(){this.ownsTui&&this.tui.start(),this.suspendable&&(this.cleanupSuspend=this.setupSuspendHandler())}exit(e){for(let t of this.exitCallbacks)t(e);this.unmount()}onExit(e){this.exitCallbacks.push(e)}unmount(){this.cleanupSuspend?.(),DF.updateContainerSync(null,this.container,null),DF.flushSyncWork(),this.tui.removeChild(this.bridge),this.ownsTui&&this.tui.stop(),this.rootNode.yogaNode?.unsetMeasureFunc(),this.rootNode.yogaNode?.free(),this.rootNode.yogaNode=void 0,this.resolveExit()}cleanupTerminal(){this.ownsTui&&(this.cleanupSuspend?.(),this.terminal.write(OF.DISABLE_FOCUS_REPORTING),this.tui.stop(),U.stdout.write(OF.SHOW_CURSOR))}setupSuspendHandler(){if(U.platform===`win32`||!this.ownsTui)return()=>{};let e=!1,t=()=>{e=this.terminal.kittyProtocolActive,U.stdout.isTTY&&(this.terminal.write(OF.DISABLE_FOCUS_REPORTING),this.terminal.write(OF.DISABLE_BRACKETED_PASTE),e&&this.terminal.write(OF.DISABLE_KITTY_KEYBOARD),U.stdout.write(OF.SHOW_CURSOR)),U.stdin.isTTY&&U.stdin.isRaw&&U.stdin.setRawMode(!1),this.onSuspended?.(),U.removeListener(`SIGTSTP`,t),U.kill(U.pid,`SIGTSTP`)},n=()=>{U.stdin.isTTY&&U.stdin.setRawMode(!0),U.stdout.isTTY&&(U.stdout.write(OF.HIDE_CURSOR),this.terminal.write(OF.ENABLE_BRACKETED_PASTE),this.terminal.write(OF.ENABLE_FOCUS_REPORTING),e&&this.terminal.write(OF.ENABLE_KITTY_KEYBOARD)),U.on(`SIGTSTP`,t),this.tui.requestRender(!0)};return U.on(`SIGTSTP`,t),U.on(`SIGCONT`,n),()=>{U.removeListener(`SIGTSTP`,t),U.removeListener(`SIGCONT`,n)}}waitUntilExit(){return this.exitPromise}getRootNode(){return this.rootNode}};function rI(e,t){let n=new nI(t),r=Z.createElement(NF,{tui:n.tui,terminal:n.terminal,exit:e=>n.exit(e),children:e});return n.render(r),n.start(),{rerender(e){let t=Z.createElement(NF,{tui:n.tui,terminal:n.terminal,exit:e=>n.exit(e),children:e});n.render(t)},unmount(){n.unmount()},waitUntilExit(){return n.waitUntilExit()},cleanupTerminal(){n.cleanupTerminal()}}}function Q({children:e,...t}){return(0,X.jsx)(`jar-view`,{style:{flexWrap:`nowrap`,flexDirection:`row`,flexGrow:0,flexShrink:1,...t,overflowX:t.overflowX??t.overflow??`visible`,overflowY:t.overflowY??t.overflow??`visible`},children:e})}function $({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:i=!1,underline:a=!1,strikethrough:o=!1,inverse:s=!1,wrap:c=`wrap`,transform:l,children:u}){if(u==null)return null;let d=(0,Z.useCallback)(c=>(n&&(c=NA.dim(c)),e&&(c=GF(c,e,`foreground`)),t&&(c=GF(c,t,`background`)),r&&(c=NA.bold(c)),i&&(c=NA.italic(c)),a&&(c=NA.underline(c)),o&&(c=NA.strikethrough(c)),s&&(c=NA.inverse(c)),l&&(c=l(c)),c),[e,t,n,r,i,a,o,s,l]);return(0,X.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:1,flexDirection:`row`,textWrap:c},internal_transform:d,children:u})}const iI=/\x1b\[[\d:]*;(\d+)/;function aI(e){let t=iI.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const oI={upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageDown:!1,pageUp:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1,super:!1,paste:!1,raw:``},sI=(e,t={})=>{let{addInputListener:n}=(0,Z.use)(jF);(0,Z.useEffect)(()=>{if(t.isActive!==!1)return n(t=>{if(uN(t))return;if(t.startsWith(`\x1B[200~`)){let n=t.indexOf(`\x1B[201~`),r=n===-1?t.slice(6):t.slice(6,n);oI.upArrow=!1,oI.downArrow=!1,oI.leftArrow=!1,oI.rightArrow=!1,oI.pageDown=!1,oI.pageUp=!1,oI.home=!1,oI.end=!1,oI.return=!1,oI.escape=!1,oI.ctrl=!1,oI.shift=!1,oI.tab=!1,oI.backspace=!1,oI.delete=!1,oI.meta=!1,oI.super=!1,oI.paste=!0,oI.raw=t,e(r,{...oI});return}let n=vN(t),r=n?n.split(`+`):[],i=r[r.length-1]??``,a=r.includes(`ctrl`),o=r.includes(`shift`),s=r.includes(`alt`);oI.upArrow=i===`up`,oI.downArrow=i===`down`,oI.leftArrow=i===`left`,oI.rightArrow=i===`right`,oI.pageDown=i===`pagedown`,oI.pageUp=i===`pageup`,oI.home=i===`home`,oI.end=i===`end`,oI.return=i===`return`||i===`enter`,oI.escape=i===`escape`,oI.ctrl=a,oI.shift=o,oI.tab=i===`tab`,oI.backspace=i===`backspace`,oI.delete=i===`delete`,oI.meta=s,oI.super=aI(t),oI.paste=!1,oI.raw=t;let c=oI,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let e=xN(t);e===void 0?t.length===1?l=t:i.length===1&&(l=i):l=e}e(l,{...c})})},[t.isActive,e,n])},cI=({isActive:e=!0,autoFocus:t=!1,id:n}={})=>{let{activeId:r,add:i,remove:a,activate:o,deactivate:s,focus:c}=(0,Z.use)(kF),l=(0,Z.useMemo)(()=>n??Math.random().toString().slice(2,7),[n]);return(0,Z.useEffect)(()=>(i(l,{autoFocus:t}),()=>{a(l)}),[l,t]),(0,Z.useEffect)(()=>{e?o(l):s(l)},[e,l]),{isFocused:!!l&&r===l,focus:c}};function lI(){return(0,Z.use)(AF)}var uI=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},dI={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},fI=new class{#e=dI;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function pI(e){setTimeout(e,0)}var mI=typeof window>`u`||`Deno`in globalThis;function hI(){}function gI(e,t){return typeof e==`function`?e(t):e}function _I(e){return typeof e==`number`&&e>=0&&e!==1/0}function vI(e,t){return Math.max(e+(t||0)-Date.now(),0)}function yI(e,t){return typeof e==`function`?e(t):e}function bI(e,t){return typeof e==`function`?e(t):e}function xI(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==CI(o,t.options))return!1}else if(!TI(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function SI(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(wI(t.options.mutationKey)!==wI(a))return!1}else if(!TI(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function CI(e,t){return(t?.queryKeyHashFn||wI)(e)}function wI(e){return JSON.stringify(e,(e,t)=>AI(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function TI(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>TI(e[n],t[n])):!1}var EI=Object.prototype.hasOwnProperty;function DI(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=kI(e)&&kI(t);if(!r&&!(AI(e)&&AI(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:EI.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=DI(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function OI(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function kI(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function AI(e){if(!jI(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!jI(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function jI(e){return Object.prototype.toString.call(e)===`[object Object]`}function MI(e){return new Promise(t=>{fI.setTimeout(t,e)})}function NI(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:DI(e,t)}function PI(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function FI(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var II=Symbol();function LI(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===II?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function RI(e,t){return typeof e==`function`?e(...t):!!e}function zI(e,t,n){let r=!1,i;return Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var BI=new class extends uI{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!mI&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}};function VI(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var HI=pI;function UI(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=HI,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var WI=UI(),GI=new class extends uI{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!mI&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function KI(e){return Math.min(1e3*2**e,3e4)}function qI(e){return(e??`online`)===`online`?GI.isOnline():!0}var JI=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function YI(e){let t=!1,n=0,r,i=VI(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new JI(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>BI.isFocused()&&(e.networkMode===`always`||GI.isOnline())&&e.canRun(),u=()=>qI(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(mI?0:3),o=e.retryDelay??KI,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),MI(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var XI=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_I(this.gcTime)&&(this.#e=fI.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(mI?1/0:300*1e3))}clearGcTimeout(){this.#e&&=(fI.clearTimeout(this.#e),void 0)}},ZI=class extends XI{#e;#t;#n;#r;#i;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=eL(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#i?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=eL(this.options);e.data!==void 0&&(this.setState($I(e.data,e.dataUpdatedAt)),this.#e=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#n.remove(this)}setData(e,t){let n=NI(this.state.data,e,this.options);return this.#s({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:`setState`,state:e,setStateOptions:t})}cancel(e){let t=this.#i?.promise;return this.#i?.cancel(e),t?t.then(hI).catch(hI):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>bI(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===II||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>yI(e.options.staleTime,this)===`static`):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!vI(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#i&&(this.#o?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#n.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#i?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},i=()=>{let e=LI(this.options,t),n=(()=>{let e={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#o=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:i};return r(e),e})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#s({type:`fetch`,meta:a.fetchOptions?.meta}),this.#i=YI({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof JI&&e.revert&&this.setState({...this.#t,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#s({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#s({type:`pause`})},onContinue:()=>{this.#s({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#i.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#n.config.onSuccess?.(e,this),this.#n.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof JI){if(e.silent)return this.#i.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#s({type:`error`,error:e}),this.#n.config.onError?.(e,this),this.#n.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#s(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...QI(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...$I(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}})(this.state),WI.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#n.notify({query:this,type:`updated`,action:e})})}};function QI(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:qI(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function $I(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function eL(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var tL=class extends uI{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=VI(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),rL(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return iL(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return iL(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof bI(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!OI(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&aL(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||bI(this.options.enabled,this.#t)!==bI(t.enabled,this.#t)||yI(this.options.staleTime,this.#t)!==yI(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||bI(this.options.enabled,this.#t)!==bI(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return sL(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(hI)),t}#g(){this.#b();let e=yI(this.options.staleTime,this.#t);if(mI||this.#r.isStale||!_I(e))return;let t=vI(this.#r.dataUpdatedAt,e)+1;this.#d=fI.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(mI||bI(this.options.enabled,this.#t)===!1||!_I(this.#p)||this.#p===0)&&(this.#f=fI.setInterval(()=>{(this.options.refetchIntervalInBackground||BI.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d&&=(fI.clearTimeout(this.#d),void 0)}#x(){this.#f&&=(fI.clearInterval(this.#f),void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&rL(e,t),o=i&&aL(e,n,t,r);(a||o)&&(l={...l,...QI(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=NI(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=NI(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:oL(e,t),refetch:this.refetch,promise:this.#o,isEnabled:bI(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=VI())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!OI(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){WI.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function nL(e,t){return bI(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&t.retryOnMount===!1)}function rL(e,t){return nL(e,t)||e.state.data!==void 0&&iL(e,t,t.refetchOnMount)}function iL(e,t,n){if(bI(t.enabled,e)!==!1&&yI(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&oL(e,t)}return!1}function aL(e,t,n,r){return(e!==t||bI(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&oL(e,n)}function oL(e,t){return bI(t.enabled,e)!==!1&&e.isStaleByTime(yI(t.staleTime,e))}function sL(e,t){return!OI(e.getCurrentResult(),t)}function cL(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{zI(e,()=>t.signal,()=>n=!0)},u=LI(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject();if(r==null&&e.pages.length)return Promise.resolve(e);let a=await u((()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})()),{maxPages:o}=t.options,s=i?FI:PI;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?uL:lL,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:lL(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function lL(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function uL(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var dL=class extends XI{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||fL(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=YI({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}})(this.state),WI.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function fL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var pL=class extends uI{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new dL({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=mL(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=mL(e);if(typeof t==`string`){let n=this.#t.get(t);if(n)if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=mL(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}else return!0}runNext(e){let t=mL(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){WI.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>SI(t,e))}findAll(e={}){return this.getAll().filter(t=>SI(e,t))}notify(e){WI.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return WI.batch(()=>Promise.all(e.map(e=>e.continue().catch(hI))))}};function mL(e){return e.options.scope?.id}var hL=class extends uI{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??CI(r,t),a=this.get(i);return a||(a=new ZI({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){WI.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>xI(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>xI(e,t)):t}notify(e){WI.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){WI.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){WI.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},gL=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new hL,this.#t=e.mutationCache||new pL,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=BI.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=GI.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(yI(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=gI(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return WI.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;WI.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return WI.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=WI.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(hI).catch(hI)}invalidateQueries(e,t={}){return WI.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=WI.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(hI)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(hI)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(yI(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(hI).catch(hI)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(hI).catch(hI)}ensureInfiniteQueryData(e){return e.behavior=cL(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return GI.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(wI(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{TI(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(wI(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{TI(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=CI(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===II&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},_L=Z.createContext(void 0),vL=e=>{let t=Z.useContext(_L);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},yL=({client:e,children:t})=>(Z.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,X.jsx)(_L.Provider,{value:e,children:t})),bL=Z.createContext(!1),xL=()=>Z.useContext(bL);bL.Provider;function SL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var CL=Z.createContext(SL()),wL=()=>Z.useContext(CL),TL=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?RI(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},EL=e=>{Z.useEffect(()=>{e.clearReset()},[e])},DL=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||RI(n,[e.error,r])),OL=(e,t)=>t.state.data===void 0,kL=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},AL=(e,t)=>e.isLoading&&e.isFetching&&!t,jL=(e,t)=>e?.suspense&&t.isPending,ML=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function NL(e,t,n){let r=xL(),i=wL(),a=vL(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,kL(o),TL(o,i,s),EL(i);let c=!a.getQueryCache().get(o.queryHash),[l]=Z.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(Z.useSyncExternalStore(Z.useCallback(e=>{let t=d?l.subscribe(WI.batchCalls(e)):hI;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Z.useEffect(()=>{l.setOptions(o)},[o,l]),jL(o,u))throw ML(o,l,i);if(DL({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!mI&&AL(u,r)&&(c?ML(o,l,i):s?.promise)?.catch(hI).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function PL(e,t){return NL({...e,enabled:!0,suspense:!0,throwOnError:OL,placeholderData:void 0},tL,t)}var FL={version:`1.0.0`,default:`catppuccin-mocha`,themes:[{name:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,author:`https://github.com/catppuccin/catppuccin`,source:`base16`,colors:{text:`#cdd6f4`,textMuted:`#585b70`,textSubtle:`#45475a`,textInverse:`#1e1e2e`,background:`#1e1e2e`,backgroundAlt:`#181825`,backgroundSelection:`#313244`,backgroundHover:`#181825`,primary:`#89b4fa`,primaryMuted:`#5e78a8`,secondary:`#cba6f7`,accent:`#f2cdcd`,info:`#94e2d5`,success:`#a6e3a1`,successMuted:`#709473`,error:`#f38ba8`,errorMuted:`#9e5f77`,warning:`#f9e2af`,warningMuted:`#a1947b`,border:`#45475a`,borderFocused:`#89b4fa`,borderSubtle:`#313244`,diffAdded:`#394545`,diffAddedText:`#a6e3a1`,diffAddedHighlight:`#4a5f4f`,diffRemoved:`#493446`,diffRemovedText:`#f38ba8`,diffRemovedHighlight:`#5e3d51`,codeBackground:`#181825`,promptBorder:`#585b70`,suggestion:`#89b4fa`,link:`#89b4fa`,linkVisited:`#cba6f7`,gradientStart:`#89b4fa`,gradientMid:`#cba6f7`,gradientEnd:`#f2cdcd`,syntaxKeyword:`#cba6f7`,syntaxString:`#a6e3a1`,syntaxNumber:`#fab387`,syntaxComment:`#45475a`,syntaxFunction:`#89b4fa`,syntaxVariable:`#f38ba8`,syntaxType:`#f9e2af`,syntaxOperator:`#cdd6f4`,syntaxPunctuation:`#cdd6f4`}},{name:`dracula`,displayName:`Dracula`,type:`dark`,author:`Jamy Golden (http://github.com/JamyGolden), based on Dracula Theme (http://github.com/dracula)`,source:`base16`,colors:{text:`#f8f8f2`,textMuted:`#9ea8c7`,textSubtle:`#6272a4`,textInverse:`#282a36`,background:`#282a36`,backgroundAlt:`#363447`,backgroundSelection:`#44475a`,backgroundHover:`#363447`,primary:`#80bfff`,primaryMuted:`#5d83af`,secondary:`#ff79c6`,accent:`#bd93f9`,info:`#8be9fd`,success:`#50fa7b`,successMuted:`#40a75f`,error:`#ff5555`,errorMuted:`#a94449`,warning:`#f1fa8c`,warningMuted:`#a1a76a`,border:`#6272a4`,borderFocused:`#80bfff`,borderSubtle:`#44475a`,diffAdded:`#305444`,diffAddedText:`#50fa7b`,diffAddedHighlight:`#3d6b56`,diffRemoved:`#53333c`,diffRemovedText:`#ff5555`,diffRemovedHighlight:`#6b3f49`,codeBackground:`#363447`,promptBorder:`#9ea8c7`,suggestion:`#80bfff`,link:`#80bfff`,linkVisited:`#ff79c6`,gradientStart:`#80bfff`,gradientMid:`#ff79c6`,gradientEnd:`#bd93f9`,syntaxKeyword:`#ff79c6`,syntaxString:`#50fa7b`,syntaxNumber:`#ffb86c`,syntaxComment:`#6272a4`,syntaxFunction:`#80bfff`,syntaxVariable:`#ff5555`,syntaxType:`#f1fa8c`,syntaxOperator:`#f8f8f2`,syntaxPunctuation:`#f8f8f2`}},{name:`nord`,displayName:`Nord`,type:`dark`,author:`arcticicestudio`,source:`base16`,colors:{text:`#e5e9f0`,textMuted:`#d8dee9`,textSubtle:`#4c566a`,textInverse:`#2e3440`,background:`#2e3440`,backgroundAlt:`#3b4252`,backgroundSelection:`#434c5e`,backgroundHover:`#3b4252`,primary:`#81a1c1`,primaryMuted:`#60758d`,secondary:`#b48ead`,accent:`#5e81ac`,info:`#88c0d0`,success:`#a3be8c`,successMuted:`#74876e`,error:`#bf616a`,errorMuted:`#854f59`,warning:`#ebcb8b`,warningMuted:`#9f8f6d`,border:`#4c566a`,borderFocused:`#81a1c1`,borderSubtle:`#434c5e`,diffAdded:`#45504f`,diffAddedText:`#a3be8c`,diffAddedHighlight:`#556360`,diffRemoved:`#4b3d48`,diffRemovedText:`#bf616a`,diffRemovedHighlight:`#5f4957`,codeBackground:`#3b4252`,promptBorder:`#d8dee9`,suggestion:`#81a1c1`,link:`#81a1c1`,linkVisited:`#b48ead`,gradientStart:`#81a1c1`,gradientMid:`#b48ead`,gradientEnd:`#5e81ac`,syntaxKeyword:`#b48ead`,syntaxString:`#a3be8c`,syntaxNumber:`#d08770`,syntaxComment:`#4c566a`,syntaxFunction:`#81a1c1`,syntaxVariable:`#bf616a`,syntaxType:`#ebcb8b`,syntaxOperator:`#e5e9f0`,syntaxPunctuation:`#e5e9f0`}},{name:`gruvbox-dark-hard`,displayName:`Gruvbox dark, hard`,type:`dark`,author:`Dawid Kurek (dawikur@gmail.com), morhetz (https://github.com/morhetz/gruvbox)`,source:`base16`,colors:{text:`#d5c4a1`,textMuted:`#bdae93`,textSubtle:`#665c54`,textInverse:`#1d2021`,background:`#1d2021`,backgroundAlt:`#3c3836`,backgroundSelection:`#504945`,backgroundHover:`#3c3836`,primary:`#83a598`,primaryMuted:`#5a7068`,secondary:`#d3869b`,accent:`#d65d0e`,info:`#8ec07c`,success:`#b8bb26`,successMuted:`#7a7d24`,error:`#fb4934`,errorMuted:`#a2392c`,warning:`#fabd2f`,warningMuted:`#a27e29`,border:`#665c54`,borderFocused:`#83a598`,borderSubtle:`#504945`,diffAdded:`#3c3f22`,diffAddedText:`#b8bb26`,diffAddedHighlight:`#4b4f2a`,diffRemoved:`#492825`,diffRemovedText:`#fb4934`,diffRemovedHighlight:`#5c322e`,codeBackground:`#3c3836`,promptBorder:`#bdae93`,suggestion:`#83a598`,link:`#83a598`,linkVisited:`#d3869b`,gradientStart:`#83a598`,gradientMid:`#d3869b`,gradientEnd:`#d65d0e`,syntaxKeyword:`#d3869b`,syntaxString:`#b8bb26`,syntaxNumber:`#fe8019`,syntaxComment:`#665c54`,syntaxFunction:`#83a598`,syntaxVariable:`#fb4934`,syntaxType:`#fabd2f`,syntaxOperator:`#d5c4a1`,syntaxPunctuation:`#d5c4a1`}},{name:`onedark`,displayName:`OneDark`,type:`dark`,author:`Lalit Magant (http://github.com/tilal6991)`,source:`base16`,colors:{text:`#abb2bf`,textMuted:`#565c64`,textSubtle:`#545862`,textInverse:`#282c34`,background:`#282c34`,backgroundAlt:`#353b45`,backgroundSelection:`#3e4451`,backgroundHover:`#353b45`,primary:`#61afef`,primaryMuted:`#4a7ba4`,secondary:`#c678dd`,accent:`#be5046`,info:`#56b6c2`,success:`#98c379`,successMuted:`#6b875d`,error:`#e06c75`,errorMuted:`#96525b`,warning:`#e5c07b`,warningMuted:`#99855f`,border:`#545862`,borderFocused:`#61afef`,borderSubtle:`#3e4451`,diffAdded:`#3e4a42`,diffAddedText:`#98c379`,diffAddedHighlight:`#4c5c50`,diffRemoved:`#4d3941`,diffRemovedText:`#e06c75`,diffRemovedHighlight:`#614750`,codeBackground:`#353b45`,promptBorder:`#565c64`,suggestion:`#61afef`,link:`#61afef`,linkVisited:`#c678dd`,gradientStart:`#61afef`,gradientMid:`#c678dd`,gradientEnd:`#be5046`,syntaxKeyword:`#c678dd`,syntaxString:`#98c379`,syntaxNumber:`#d19a66`,syntaxComment:`#545862`,syntaxFunction:`#61afef`,syntaxVariable:`#e06c75`,syntaxType:`#e5c07b`,syntaxOperator:`#abb2bf`,syntaxPunctuation:`#abb2bf`}},{name:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,author:`Ethan Schoonover (modified by aramisgithub)`,source:`base16`,colors:{text:`#93a1a1`,textMuted:`#839496`,textSubtle:`#657b83`,textInverse:`#002b36`,background:`#002b36`,backgroundAlt:`#073642`,backgroundSelection:`#586e75`,backgroundHover:`#073642`,primary:`#268bd2`,primaryMuted:`#176594`,secondary:`#6c71c4`,accent:`#d33682`,info:`#2aa198`,success:`#859900`,successMuted:`#506d16`,error:`#dc322f`,errorMuted:`#842f32`,warning:`#b58900`,warningMuted:`#6d6316`,border:`#657b83`,borderFocused:`#268bd2`,borderSubtle:`#586e75`,diffAdded:`#1b412b`,diffAddedText:`#859900`,diffAddedHighlight:`#235236`,diffRemoved:`#2c2c35`,diffRemovedText:`#dc322f`,diffRemovedHighlight:`#3a3644`,codeBackground:`#073642`,promptBorder:`#839496`,suggestion:`#268bd2`,link:`#268bd2`,linkVisited:`#6c71c4`,gradientStart:`#268bd2`,gradientMid:`#6c71c4`,gradientEnd:`#d33682`,syntaxKeyword:`#6c71c4`,syntaxString:`#859900`,syntaxNumber:`#cb4b16`,syntaxComment:`#657b83`,syntaxFunction:`#268bd2`,syntaxVariable:`#dc322f`,syntaxType:`#b58900`,syntaxOperator:`#93a1a1`,syntaxPunctuation:`#93a1a1`}},{name:`monokai`,displayName:`Monokai`,type:`dark`,author:`Wimer Hazenberg (http://www.monokai.nl)`,source:`base16`,colors:{text:`#f8f8f2`,textMuted:`#a59f85`,textSubtle:`#75715e`,textInverse:`#272822`,background:`#272822`,backgroundAlt:`#383830`,backgroundSelection:`#49483e`,backgroundHover:`#383830`,primary:`#66d9ef`,primaryMuted:`#4d929d`,secondary:`#ae81ff`,accent:`#cc6633`,info:`#a1efe4`,success:`#a6e22e`,successMuted:`#739829`,error:`#f92672`,errorMuted:`#a52752`,warning:`#f4bf75`,warningMuted:`#a28354`,border:`#75715e`,borderFocused:`#66d9ef`,borderSubtle:`#49483e`,diffAdded:`#404d24`,diffAddedText:`#a6e22e`,diffAddedHighlight:`#50602d`,diffRemoved:`#512832`,diffRemovedText:`#f92672`,diffRemovedHighlight:`#66323f`,codeBackground:`#383830`,promptBorder:`#a59f85`,suggestion:`#66d9ef`,link:`#66d9ef`,linkVisited:`#ae81ff`,gradientStart:`#66d9ef`,gradientMid:`#ae81ff`,gradientEnd:`#cc6633`,syntaxKeyword:`#ae81ff`,syntaxString:`#a6e22e`,syntaxNumber:`#fd971f`,syntaxComment:`#75715e`,syntaxFunction:`#66d9ef`,syntaxVariable:`#f92672`,syntaxType:`#f4bf75`,syntaxOperator:`#f8f8f2`,syntaxPunctuation:`#f8f8f2`}},{name:`tokyo-night-terminal-dark`,displayName:`Tokyo Night Terminal Dark`,type:`dark`,author:`Michaël Ball`,source:`base16`,colors:{text:`#787c99`,textMuted:`#787c99`,textSubtle:`#444b6a`,textInverse:`#16161e`,background:`#16161e`,backgroundAlt:`#1a1b26`,backgroundSelection:`#2f3549`,backgroundHover:`#1a1b26`,primary:`#7aa2f7`,primaryMuted:`#526aa0`,secondary:`#bb9af7`,accent:`#d18616`,info:`#7dcfff`,success:`#41a6b5`,successMuted:`#306c79`,error:`#f7768e`,errorMuted:`#9d5061`,warning:`#e0af68`,warningMuted:`#8f724a`,border:`#444b6a`,borderFocused:`#7aa2f7`,borderSubtle:`#2f3549`,diffAdded:`#1f333c`,diffAddedText:`#41a6b5`,diffAddedHighlight:`#28424c`,diffRemoved:`#432934`,diffRemovedText:`#f7768e`,diffRemovedHighlight:`#563543`,codeBackground:`#1a1b26`,promptBorder:`#787c99`,suggestion:`#7aa2f7`,link:`#7aa2f7`,linkVisited:`#bb9af7`,gradientStart:`#7aa2f7`,gradientMid:`#bb9af7`,gradientEnd:`#d18616`,syntaxKeyword:`#bb9af7`,syntaxString:`#41a6b5`,syntaxNumber:`#ff9e64`,syntaxComment:`#444b6a`,syntaxFunction:`#7aa2f7`,syntaxVariable:`#f7768e`,syntaxType:`#e0af68`,syntaxOperator:`#787c99`,syntaxPunctuation:`#787c99`}},{name:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,author:`Emilia Dunfelt <edun@dunfelt.se>`,source:`base16`,colors:{text:`#e0def4`,textMuted:`#908caa`,textSubtle:`#6e6a86`,textInverse:`#191724`,background:`#191724`,backgroundAlt:`#1f1d2e`,backgroundSelection:`#26233a`,backgroundHover:`#1f1d2e`,primary:`#c4a7e7`,primaryMuted:`#806d99`,secondary:`#f6c177`,accent:`#524f67`,info:`#9ccfd8`,success:`#31748f`,successMuted:`#274f64`,error:`#eb6f92`,errorMuted:`#974c66`,warning:`#ebbcba`,warningMuted:`#977a7e`,border:`#6e6a86`,borderFocused:`#c4a7e7`,borderSubtle:`#26233a`,diffAdded:`#1e2a39`,diffAddedText:`#31748f`,diffAddedHighlight:`#263648`,diffRemoved:`#43293a`,diffRemovedText:`#eb6f92`,diffRemovedHighlight:`#55344a`,codeBackground:`#1f1d2e`,promptBorder:`#908caa`,suggestion:`#c4a7e7`,link:`#c4a7e7`,linkVisited:`#f6c177`,gradientStart:`#c4a7e7`,gradientMid:`#f6c177`,gradientEnd:`#524f67`,syntaxKeyword:`#f6c177`,syntaxString:`#31748f`,syntaxNumber:`#f6c177`,syntaxComment:`#6e6a86`,syntaxFunction:`#c4a7e7`,syntaxVariable:`#eb6f92`,syntaxType:`#ebbcba`,syntaxOperator:`#e0def4`,syntaxPunctuation:`#e0def4`}},{name:`material-darker`,displayName:`Material Darker`,type:`dark`,author:`Nate Peterson`,source:`base16`,colors:{text:`#eeffff`,textMuted:`#b2ccd6`,textSubtle:`#4a4a4a`,textInverse:`#212121`,background:`#212121`,backgroundAlt:`#303030`,backgroundSelection:`#353535`,backgroundHover:`#303030`,primary:`#82aaff`,primaryMuted:`#5b73a6`,secondary:`#c792ea`,accent:`#ff5370`,info:`#89ddff`,success:`#c3e88d`,successMuted:`#829862`,error:`#f07178`,errorMuted:`#9d5155`,warning:`#ffcb6b`,warningMuted:`#a6874d`,border:`#4a4a4a`,borderFocused:`#82aaff`,borderSubtle:`#353535`,diffAdded:`#414937`,diffAddedText:`#c3e88d`,diffAddedHighlight:`#505c44`,diffRemoved:`#4a3132`,diffRemovedText:`#f07178`,diffRemovedHighlight:`#5e3d40`,codeBackground:`#303030`,promptBorder:`#b2ccd6`,suggestion:`#82aaff`,link:`#82aaff`,linkVisited:`#c792ea`,gradientStart:`#82aaff`,gradientMid:`#c792ea`,gradientEnd:`#ff5370`,syntaxKeyword:`#c792ea`,syntaxString:`#c3e88d`,syntaxNumber:`#f78c6c`,syntaxComment:`#4a4a4a`,syntaxFunction:`#82aaff`,syntaxVariable:`#f07178`,syntaxType:`#ffcb6b`,syntaxOperator:`#eeffff`,syntaxPunctuation:`#eeffff`}}]};const IL=FL,LL=(0,Z.createContext)(null);function RL(){let e=(0,Z.use)(LL);if(!e)throw Error(`useTheme must be used within a ThemeProvider`);return e}function zL({children:e,defaultTheme:t}){let[n,r]=(0,Z.useState)(t||IL.default||`catppuccin-mocha`),i=(0,Z.useMemo)(()=>IL.themes.find(e=>e.name===n)||IL.themes.find(e=>e.name===IL.default)||IL.themes[0],[n]),a=(0,Z.useMemo)(()=>({theme:i,colors:i.colors,setTheme:r,availableThemes:IL.themes}),[i]);return(0,X.jsx)(LL.Provider,{value:a,children:e})}function BL(e){return(e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e).replace(/<br\s*\/?>/gi,`
12592
+ `))}}r=QF(e,r),e.renderCache={lines:[r],width:n,height:0,left:l,top:u},t.write(l,u,r,d)}else e.renderCache=void 0;e.renderDirty=!1;return}let f=!1;if(e.nodeName===`jar-view`){e.style.backgroundColor&&$F(l,u,e,t),e.style.borderStyle&&qF(l,u,e,t);let n=e.style.overflowX===`hidden`||e.style.overflow===`hidden`,r=e.style.overflowY===`hidden`||e.style.overflow===`hidden`;if(n||r){let i=n?l+XF(e.style,`Left`):void 0,a=n?l+c.getComputedWidth()-XF(e.style,`Right`):void 0,o=r?u+XF(e.style,`Top`):void 0,s=r?u+c.getComputedHeight()-XF(e.style,`Bottom`):void 0;t.clip({x1:i,x2:a,y1:o,y2:s}),f=!0}}if(e.nodeName===`jar-root`||e.nodeName===`jar-view`){let n=f?u+XF(e.style,`Top`):o,r=f?u+c.getComputedHeight()-XF(e.style,`Bottom`):s;for(let i of e.childNodes)eI(i,t,{offsetX:l,offsetY:u,transformers:d,clipY1:n,clipY2:r});f&&t.unclip()}e.renderDirty=!1};var tI=class{rootNode;lastWidth=0;cachedLines=null;output=new BF(0,0);constructor(e){this.rootNode=e}notifyCommit(){this.cachedLines=null}render(e){let t=e!==this.lastWidth;if(t&&(this.clearAllRenderCaches(this.rootNode),this.lastWidth=e),this.cachedLines&&!this.rootNode.renderDirty&&!t)return this.cachedLines;this.rootNode.yogaNode.setWidth(e),this.rootNode.yogaNode.calculateLayout(void 0,void 0,1);let n=Math.ceil(this.rootNode.yogaNode.getComputedHeight());if(n<=0)return this.cachedLines=[],this.cachedLines;this.output.reset(e,n),eI(this.rootNode,this.output,{});let r=this.output.get(),i=!1;for(let t of r)if(RM(t)>e){i=!0;break}return this.cachedLines=i?r.map(t=>RM(t)>e?KM(t,e):t):r,this.cachedLines}invalidate(){this.cachedLines=null,this.clearAllRenderCaches(this.rootNode)}clearAllRenderCaches(e){e.renderDirty=!0,e.renderCache=void 0;for(let t of e.childNodes)t.nodeName!==`#text`&&this.clearAllRenderCaches(t)}},nI=class{tui;terminal;rootNode;bridge;container;exitCallbacks=[];exitPromise;resolveExit;exitOnCtrlC;ownsTui;suspendable;onSuspended;cleanupSuspend;originalWarningListeners;warningInterceptor;constructor(e={}){this.exitOnCtrlC=e.exitOnCtrlC??!0,this.suspendable=e.suspendable??!1,this.onSuspended=e.onSuspended,e.tui?(this.tui=e.tui,this.terminal=e.tui.terminal,this.ownsTui=!1):e.terminal?(this.terminal=e.terminal,this.tui=new AN(this.terminal),this.ownsTui=!0):(this.terminal=new BN,this.tui=new AN(this.terminal),this.ownsTui=!0),this.rootNode=fF(`jar-root`),this.rootNode.yogaNode.setFlexDirection(0),this.rootNode.yogaNode.setFlexGrow(1),this.rootNode.onRender=()=>{this.bridge.notifyCommit(),this.tui.requestRender(),performance.clearMeasures()},this.bridge=new tI(this.rootNode),this.tui.addChild(this.bridge),this.container=DF.createContainer(this.rootNode,0,null,!1,null,`jar`,()=>{},()=>{},()=>{},()=>{}),this.exitPromise=new Promise(e=>{this.resolveExit=e}),this.exitOnCtrlC&&this.tui.addInputListener(e=>{if(!uN(e)&&_N(e,`ctrl+c`))return this.exit(),{consume:!0}})}render(e){DF.updateContainerSync(e,this.container,null),DF.flushSyncWork()}start(){this.ownsTui&&this.tui.start(),this.setupWarningInterceptor(),this.suspendable&&(this.cleanupSuspend=this.setupSuspendHandler())}exit(e){for(let t of this.exitCallbacks)t(e);this.unmount()}onExit(e){this.exitCallbacks.push(e)}unmount(){if(this.warningInterceptor&&=(U.removeListener(`warning`,this.warningInterceptor),void 0),this.originalWarningListeners){let e=U.listeners(`warning`);for(let t of this.originalWarningListeners)e.includes(t)||U.on(`warning`,t);this.originalWarningListeners=void 0}this.cleanupSuspend?.(),DF.updateContainerSync(null,this.container,null),DF.flushSyncWork(),this.tui.removeChild(this.bridge),this.ownsTui&&this.tui.stop(),this.rootNode.yogaNode?.unsetMeasureFunc(),this.rootNode.yogaNode?.free(),this.rootNode.yogaNode=void 0,this.resolveExit()}cleanupTerminal(){this.ownsTui&&(this.cleanupSuspend?.(),this.terminal.write(OF.DISABLE_FOCUS_REPORTING),this.tui.stop(),U.stdout.write(OF.SHOW_CURSOR))}setupWarningInterceptor(){this.originalWarningListeners||(this.originalWarningListeners=U.rawListeners(`warning`),U.removeAllListeners(`warning`),this.warningInterceptor=()=>{},U.on(`warning`,this.warningInterceptor))}setupSuspendHandler(){if(U.platform===`win32`||!this.ownsTui)return()=>{};let e=!1,t=()=>{e=this.terminal.kittyProtocolActive,U.stdout.isTTY&&(this.terminal.write(OF.DISABLE_FOCUS_REPORTING),this.terminal.write(OF.DISABLE_BRACKETED_PASTE),e&&this.terminal.write(OF.DISABLE_KITTY_KEYBOARD),U.stdout.write(OF.SHOW_CURSOR)),U.stdin.isTTY&&U.stdin.isRaw&&U.stdin.setRawMode(!1),this.onSuspended?.(),U.removeListener(`SIGTSTP`,t),U.kill(U.pid,`SIGTSTP`)},n=()=>{U.stdin.isTTY&&U.stdin.setRawMode(!0),U.stdout.isTTY&&(U.stdout.write(OF.HIDE_CURSOR),this.terminal.write(OF.ENABLE_BRACKETED_PASTE),this.terminal.write(OF.ENABLE_FOCUS_REPORTING),e&&this.terminal.write(OF.ENABLE_KITTY_KEYBOARD)),U.on(`SIGTSTP`,t),this.tui.requestRender(!0)};return U.on(`SIGTSTP`,t),U.on(`SIGCONT`,n),()=>{U.removeListener(`SIGTSTP`,t),U.removeListener(`SIGCONT`,n)}}waitUntilExit(){return this.exitPromise}getRootNode(){return this.rootNode}};function rI(e,t){let n=new nI(t),r=Z.createElement(NF,{tui:n.tui,terminal:n.terminal,exit:e=>n.exit(e),children:e});return n.render(r),n.start(),{rerender(e){let t=Z.createElement(NF,{tui:n.tui,terminal:n.terminal,exit:e=>n.exit(e),children:e});n.render(t)},unmount(){n.unmount()},waitUntilExit(){return n.waitUntilExit()},cleanupTerminal(){n.cleanupTerminal()}}}function Q({children:e,...t}){return(0,X.jsx)(`jar-view`,{style:{flexWrap:`nowrap`,flexDirection:`row`,flexGrow:0,flexShrink:1,...t,overflowX:t.overflowX??t.overflow??`visible`,overflowY:t.overflowY??t.overflow??`visible`},children:e})}function $({color:e,backgroundColor:t,dimColor:n=!1,bold:r=!1,italic:i=!1,underline:a=!1,strikethrough:o=!1,inverse:s=!1,wrap:c=`wrap`,transform:l,children:u}){if(u==null)return null;let d=(0,Z.useCallback)(c=>(n&&(c=NA.dim(c)),e&&(c=GF(c,e,`foreground`)),t&&(c=GF(c,t,`background`)),r&&(c=NA.bold(c)),i&&(c=NA.italic(c)),a&&(c=NA.underline(c)),o&&(c=NA.strikethrough(c)),s&&(c=NA.inverse(c)),l&&(c=l(c)),c),[e,t,n,r,i,a,o,s,l]);return(0,X.jsx)(`jar-text`,{style:{flexGrow:0,flexShrink:1,flexDirection:`row`,textWrap:c},internal_transform:d,children:u})}const iI=/\x1b\[[\d:]*;(\d+)/;function aI(e){let t=iI.exec(e);return t?(parseInt(t[1],10)-1&8)!=0:!1}const oI={upArrow:!1,downArrow:!1,leftArrow:!1,rightArrow:!1,pageDown:!1,pageUp:!1,home:!1,end:!1,return:!1,escape:!1,ctrl:!1,shift:!1,tab:!1,backspace:!1,delete:!1,meta:!1,super:!1,paste:!1,raw:``},sI=(e,t={})=>{let{addInputListener:n}=(0,Z.use)(jF);(0,Z.useEffect)(()=>{if(t.isActive!==!1)return n(t=>{if(uN(t))return;if(t.startsWith(`\x1B[200~`)){let n=t.indexOf(`\x1B[201~`),r=n===-1?t.slice(6):t.slice(6,n);oI.upArrow=!1,oI.downArrow=!1,oI.leftArrow=!1,oI.rightArrow=!1,oI.pageDown=!1,oI.pageUp=!1,oI.home=!1,oI.end=!1,oI.return=!1,oI.escape=!1,oI.ctrl=!1,oI.shift=!1,oI.tab=!1,oI.backspace=!1,oI.delete=!1,oI.meta=!1,oI.super=!1,oI.paste=!0,oI.raw=t,e(r,{...oI});return}let n=vN(t),r=n?n.split(`+`):[],i=r[r.length-1]??``,a=r.includes(`ctrl`),o=r.includes(`shift`),s=r.includes(`alt`);oI.upArrow=i===`up`,oI.downArrow=i===`down`,oI.leftArrow=i===`left`,oI.rightArrow=i===`right`,oI.pageDown=i===`pagedown`,oI.pageUp=i===`pageup`,oI.home=i===`home`,oI.end=i===`end`,oI.return=i===`return`||i===`enter`,oI.escape=i===`escape`,oI.ctrl=a,oI.shift=o,oI.tab=i===`tab`,oI.backspace=i===`backspace`,oI.delete=i===`delete`,oI.meta=s,oI.super=aI(t),oI.paste=!1,oI.raw=t;let c=oI,l=``;if(a&&i)l=i;else if(!c.upArrow&&!c.downArrow&&!c.leftArrow&&!c.rightArrow&&!c.pageDown&&!c.pageUp&&!c.home&&!c.end&&!c.return&&!c.escape&&!c.tab&&!c.backspace&&!c.delete){let e=xN(t);e===void 0?t.length===1?l=t:i.length===1&&(l=i):l=e}e(l,{...c})})},[t.isActive,e,n])},cI=({isActive:e=!0,autoFocus:t=!1,id:n}={})=>{let{activeId:r,add:i,remove:a,activate:o,deactivate:s,focus:c}=(0,Z.use)(kF),l=(0,Z.useMemo)(()=>n??Math.random().toString().slice(2,7),[n]);return(0,Z.useEffect)(()=>(i(l,{autoFocus:t}),()=>{a(l)}),[l,t]),(0,Z.useEffect)(()=>{e?o(l):s(l)},[e,l]),{isFocused:!!l&&r===l,focus:c}};function lI(){return(0,Z.use)(AF)}var uI=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},dI={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},fI=new class{#e=dI;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function pI(e){setTimeout(e,0)}var mI=typeof window>`u`||`Deno`in globalThis;function hI(){}function gI(e,t){return typeof e==`function`?e(t):e}function _I(e){return typeof e==`number`&&e>=0&&e!==1/0}function vI(e,t){return Math.max(e+(t||0)-Date.now(),0)}function yI(e,t){return typeof e==`function`?e(t):e}function bI(e,t){return typeof e==`function`?e(t):e}function xI(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==CI(o,t.options))return!1}else if(!TI(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function SI(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(wI(t.options.mutationKey)!==wI(a))return!1}else if(!TI(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function CI(e,t){return(t?.queryKeyHashFn||wI)(e)}function wI(e){return JSON.stringify(e,(e,t)=>AI(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function TI(e,t){return e===t?!0:typeof e==typeof t&&e&&t&&typeof e==`object`&&typeof t==`object`?Object.keys(t).every(n=>TI(e[n],t[n])):!1}var EI=Object.prototype.hasOwnProperty;function DI(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=kI(e)&&kI(t);if(!r&&!(AI(e)&&AI(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:EI.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=DI(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function OI(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function kI(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function AI(e){if(!jI(e))return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return!(!jI(n)||!n.hasOwnProperty(`isPrototypeOf`)||Object.getPrototypeOf(e)!==Object.prototype)}function jI(e){return Object.prototype.toString.call(e)===`[object Object]`}function MI(e){return new Promise(t=>{fI.setTimeout(t,e)})}function NI(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:DI(e,t)}function PI(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function FI(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var II=Symbol();function LI(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===II?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function RI(e,t){return typeof e==`function`?e(...t):!!e}function zI(e,t,n){let r=!1,i;return Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var BI=new class extends uI{#e;#t;#n;constructor(){super(),this.#n=e=>{if(!mI&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}};function VI(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var HI=pI;function UI(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=HI,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var WI=UI(),GI=new class extends uI{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(!mI&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function KI(e){return Math.min(1e3*2**e,3e4)}function qI(e){return(e??`online`)===`online`?GI.isOnline():!0}var JI=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function YI(e){let t=!1,n=0,r,i=VI(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new JI(t);f(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>BI.isFocused()&&(e.networkMode===`always`||GI.isOnline())&&e.canRun(),u=()=>qI(e.networkMode)&&e.canRun(),d=e=>{a()||(r?.(),i.resolve(e))},f=e=>{a()||(r?.(),i.reject(e))},p=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),m=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(d).catch(r=>{if(a())return;let i=e.retry??(mI?0:3),o=e.retryDelay??KI,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!c){f(r);return}n++,e.onFail?.(n,r),MI(s).then(()=>l()?void 0:p()).then(()=>{t?f(r):m()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:u,start:()=>(u()?m():p().then(m),i)}}var XI=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_I(this.gcTime)&&(this.#e=fI.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(mI?1/0:300*1e3))}clearGcTimeout(){this.#e&&=(fI.clearTimeout(this.#e),void 0)}},ZI=class extends XI{#e;#t;#n;#r;#i;#a;#o;constructor(e){super(),this.#o=!1,this.#a=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#r=e.client,this.#n=this.#r.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#e=eL(this.options),this.state=e.state??this.#e,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#i?.promise}setOptions(e){if(this.options={...this.#a,...e},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=eL(this.options);e.data!==void 0&&(this.setState($I(e.data,e.dataUpdatedAt)),this.#e=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#n.remove(this)}setData(e,t){let n=NI(this.state.data,e,this.options);return this.#s({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e,t){this.#s({type:`setState`,state:e,setStateOptions:t})}cancel(e){let t=this.#i?.promise;return this.#i?.cancel(e),t?t.then(hI).catch(hI):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#e)}isActive(){return this.observers.some(e=>bI(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===II||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(e=>yI(e.options.staleTime,this)===`static`):!1}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!vI(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#i&&(this.#o?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#n.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#s({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#i?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,`signal`,{enumerable:!0,get:()=>(this.#o=!0,n.signal)})},i=()=>{let e=LI(this.options,t),n=(()=>{let e={client:this.#r,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#o=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#r,state:this.state,fetchFn:i};return r(e),e})();this.options.behavior?.onFetch(a,this),this.#t=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#s({type:`fetch`,meta:a.fetchOptions?.meta}),this.#i=YI({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof JI&&e.revert&&this.setState({...this.#t,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#s({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#s({type:`pause`})},onContinue:()=>{this.#s({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#i.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#n.config.onSuccess?.(e,this),this.#n.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof JI){if(e.silent)return this.#i.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#s({type:`error`,error:e}),this.#n.config.onError?.(e,this),this.#n.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#s(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...QI(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...$I(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#t=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}})(this.state),WI.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#n.notify({query:this,type:`updated`,action:e})})}};function QI(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:qI(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function $I(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function eL(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var tL=class extends uI{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=VI(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),rL(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return iL(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return iL(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof bI(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!OI(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&aL(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||bI(this.options.enabled,this.#t)!==bI(t.enabled,this.#t)||yI(this.options.staleTime,this.#t)!==yI(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||bI(this.options.enabled,this.#t)!==bI(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return sL(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(hI)),t}#g(){this.#b();let e=yI(this.options.staleTime,this.#t);if(mI||this.#r.isStale||!_I(e))return;let t=vI(this.#r.dataUpdatedAt,e)+1;this.#d=fI.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(mI||bI(this.options.enabled,this.#t)===!1||!_I(this.#p)||this.#p===0)&&(this.#f=fI.setInterval(()=>{(this.options.refetchIntervalInBackground||BI.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d&&=(fI.clearTimeout(this.#d),void 0)}#x(){this.#f&&=(fI.clearInterval(this.#f),void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&rL(e,t),o=i&&aL(e,n,t,r);(a||o)&&(l={...l,...QI(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=NI(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h)if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=NI(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0,x={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:l.dataUpdateCount>0||l.errorUpdateCount>0,isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:oL(e,t),refetch:this.refetch,promise:this.#o,isEnabled:bI(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=x.data!==void 0,r=x.status===`error`&&!t,i=e=>{r?e.reject(x.error):t&&e.resolve(x.data)},a=()=>{i(this.#o=x.promise=VI())},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||x.data!==o.value)&&a();break;case`rejected`:(!r||x.error!==o.reason)&&a();break}}return x}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!OI(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){WI.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function nL(e,t){return bI(t.enabled,e)!==!1&&e.state.data===void 0&&!(e.state.status===`error`&&t.retryOnMount===!1)}function rL(e,t){return nL(e,t)||e.state.data!==void 0&&iL(e,t,t.refetchOnMount)}function iL(e,t,n){if(bI(t.enabled,e)!==!1&&yI(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&oL(e,t)}return!1}function aL(e,t,n,r){return(e!==t||bI(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&oL(e,n)}function oL(e,t){return bI(t.enabled,e)!==!1&&e.isStaleByTime(yI(t.staleTime,e))}function sL(e,t){return!OI(e.getCurrentResult(),t)}function cL(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{zI(e,()=>t.signal,()=>n=!0)},u=LI(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject();if(r==null&&e.pages.length)return Promise.resolve(e);let a=await u((()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})()),{maxPages:o}=t.options,s=i?FI:PI;return{pages:s(e.pages,a,o),pageParams:s(e.pageParams,r,o)}};if(i&&a.length){let e=i===`backward`,t=e?uL:lL,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:lL(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.options.persister?t.fetchFn=()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):t.fetchFn=l}}}function lL(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function uL(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var dL=class extends XI{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||fL(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=YI({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){this.state=(t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}})(this.state),WI.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function fL(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var pL=class extends uI{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new dL({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=mL(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=mL(e);if(typeof t==`string`){let n=this.#t.get(t);if(n)if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=mL(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}else return!0}runNext(e){let t=mL(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){WI.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>SI(t,e))}findAll(e={}){return this.getAll().filter(t=>SI(e,t))}notify(e){WI.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return WI.batch(()=>Promise.all(e.map(e=>e.continue().catch(hI))))}};function mL(e){return e.options.scope?.id}var hL=class extends uI{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??CI(r,t),a=this.get(i);return a||(a=new ZI({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){WI.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>xI(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>xI(e,t)):t}notify(e){WI.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){WI.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){WI.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},gL=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new hL,this.#t=e.mutationCache||new pL,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=BI.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=GI.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(yI(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=gI(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return WI.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;WI.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return WI.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=WI.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(hI).catch(hI)}invalidateQueries(e,t={}){return WI.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=WI.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(hI)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(hI)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(yI(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(hI).catch(hI)}fetchInfiniteQuery(e){return e.behavior=cL(e.pages),this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(hI).catch(hI)}ensureInfiniteQueryData(e){return e.behavior=cL(e.pages),this.ensureQueryData(e)}resumePausedMutations(){return GI.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(wI(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{TI(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(wI(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{TI(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=CI(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===II&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},_L=Z.createContext(void 0),vL=e=>{let t=Z.useContext(_L);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},yL=({client:e,children:t})=>(Z.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,X.jsx)(_L.Provider,{value:e,children:t})),bL=Z.createContext(!1),xL=()=>Z.useContext(bL);bL.Provider;function SL(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var CL=Z.createContext(SL()),wL=()=>Z.useContext(CL),TL=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?RI(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},EL=e=>{Z.useEffect(()=>{e.clearReset()},[e])},DL=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||RI(n,[e.error,r])),OL=(e,t)=>t.state.data===void 0,kL=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},AL=(e,t)=>e.isLoading&&e.isFetching&&!t,jL=(e,t)=>e?.suspense&&t.isPending,ML=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function NL(e,t,n){let r=xL(),i=wL(),a=vL(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash);o._optimisticResults=r?`isRestoring`:`optimistic`,kL(o),TL(o,i,s),EL(i);let c=!a.getQueryCache().get(o.queryHash),[l]=Z.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&e.subscribed!==!1;if(Z.useSyncExternalStore(Z.useCallback(e=>{let t=d?l.subscribe(WI.batchCalls(e)):hI;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),Z.useEffect(()=>{l.setOptions(o)},[o,l]),jL(o,u))throw ML(o,l,i);if(DL({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,u),o.experimental_prefetchInRender&&!mI&&AL(u,r)&&(c?ML(o,l,i):s?.promise)?.catch(hI).finally(()=>{l.updateResult()}),o.notifyOnChangeProps?u:l.trackResult(u)}function PL(e,t){return NL({...e,enabled:!0,suspense:!0,throwOnError:OL,placeholderData:void 0},tL,t)}var FL={version:`1.0.0`,default:`catppuccin-mocha`,themes:[{name:`catppuccin-mocha`,displayName:`Catppuccin Mocha`,type:`dark`,author:`https://github.com/catppuccin/catppuccin`,source:`base16`,colors:{text:`#cdd6f4`,textMuted:`#585b70`,textSubtle:`#45475a`,textInverse:`#1e1e2e`,background:`#1e1e2e`,backgroundAlt:`#181825`,backgroundSelection:`#313244`,backgroundHover:`#181825`,primary:`#89b4fa`,primaryMuted:`#5e78a8`,secondary:`#cba6f7`,accent:`#f2cdcd`,info:`#94e2d5`,success:`#a6e3a1`,successMuted:`#709473`,error:`#f38ba8`,errorMuted:`#9e5f77`,warning:`#f9e2af`,warningMuted:`#a1947b`,border:`#45475a`,borderFocused:`#89b4fa`,borderSubtle:`#313244`,diffAdded:`#394545`,diffAddedText:`#a6e3a1`,diffAddedHighlight:`#4a5f4f`,diffRemoved:`#493446`,diffRemovedText:`#f38ba8`,diffRemovedHighlight:`#5e3d51`,codeBackground:`#181825`,promptBorder:`#585b70`,suggestion:`#89b4fa`,link:`#89b4fa`,linkVisited:`#cba6f7`,gradientStart:`#89b4fa`,gradientMid:`#cba6f7`,gradientEnd:`#f2cdcd`,syntaxKeyword:`#cba6f7`,syntaxString:`#a6e3a1`,syntaxNumber:`#fab387`,syntaxComment:`#45475a`,syntaxFunction:`#89b4fa`,syntaxVariable:`#f38ba8`,syntaxType:`#f9e2af`,syntaxOperator:`#cdd6f4`,syntaxPunctuation:`#cdd6f4`}},{name:`dracula`,displayName:`Dracula`,type:`dark`,author:`Jamy Golden (http://github.com/JamyGolden), based on Dracula Theme (http://github.com/dracula)`,source:`base16`,colors:{text:`#f8f8f2`,textMuted:`#9ea8c7`,textSubtle:`#6272a4`,textInverse:`#282a36`,background:`#282a36`,backgroundAlt:`#363447`,backgroundSelection:`#44475a`,backgroundHover:`#363447`,primary:`#80bfff`,primaryMuted:`#5d83af`,secondary:`#ff79c6`,accent:`#bd93f9`,info:`#8be9fd`,success:`#50fa7b`,successMuted:`#40a75f`,error:`#ff5555`,errorMuted:`#a94449`,warning:`#f1fa8c`,warningMuted:`#a1a76a`,border:`#6272a4`,borderFocused:`#80bfff`,borderSubtle:`#44475a`,diffAdded:`#305444`,diffAddedText:`#50fa7b`,diffAddedHighlight:`#3d6b56`,diffRemoved:`#53333c`,diffRemovedText:`#ff5555`,diffRemovedHighlight:`#6b3f49`,codeBackground:`#363447`,promptBorder:`#9ea8c7`,suggestion:`#80bfff`,link:`#80bfff`,linkVisited:`#ff79c6`,gradientStart:`#80bfff`,gradientMid:`#ff79c6`,gradientEnd:`#bd93f9`,syntaxKeyword:`#ff79c6`,syntaxString:`#50fa7b`,syntaxNumber:`#ffb86c`,syntaxComment:`#6272a4`,syntaxFunction:`#80bfff`,syntaxVariable:`#ff5555`,syntaxType:`#f1fa8c`,syntaxOperator:`#f8f8f2`,syntaxPunctuation:`#f8f8f2`}},{name:`nord`,displayName:`Nord`,type:`dark`,author:`arcticicestudio`,source:`base16`,colors:{text:`#e5e9f0`,textMuted:`#d8dee9`,textSubtle:`#4c566a`,textInverse:`#2e3440`,background:`#2e3440`,backgroundAlt:`#3b4252`,backgroundSelection:`#434c5e`,backgroundHover:`#3b4252`,primary:`#81a1c1`,primaryMuted:`#60758d`,secondary:`#b48ead`,accent:`#5e81ac`,info:`#88c0d0`,success:`#a3be8c`,successMuted:`#74876e`,error:`#bf616a`,errorMuted:`#854f59`,warning:`#ebcb8b`,warningMuted:`#9f8f6d`,border:`#4c566a`,borderFocused:`#81a1c1`,borderSubtle:`#434c5e`,diffAdded:`#45504f`,diffAddedText:`#a3be8c`,diffAddedHighlight:`#556360`,diffRemoved:`#4b3d48`,diffRemovedText:`#bf616a`,diffRemovedHighlight:`#5f4957`,codeBackground:`#3b4252`,promptBorder:`#d8dee9`,suggestion:`#81a1c1`,link:`#81a1c1`,linkVisited:`#b48ead`,gradientStart:`#81a1c1`,gradientMid:`#b48ead`,gradientEnd:`#5e81ac`,syntaxKeyword:`#b48ead`,syntaxString:`#a3be8c`,syntaxNumber:`#d08770`,syntaxComment:`#4c566a`,syntaxFunction:`#81a1c1`,syntaxVariable:`#bf616a`,syntaxType:`#ebcb8b`,syntaxOperator:`#e5e9f0`,syntaxPunctuation:`#e5e9f0`}},{name:`gruvbox-dark-hard`,displayName:`Gruvbox dark, hard`,type:`dark`,author:`Dawid Kurek (dawikur@gmail.com), morhetz (https://github.com/morhetz/gruvbox)`,source:`base16`,colors:{text:`#d5c4a1`,textMuted:`#bdae93`,textSubtle:`#665c54`,textInverse:`#1d2021`,background:`#1d2021`,backgroundAlt:`#3c3836`,backgroundSelection:`#504945`,backgroundHover:`#3c3836`,primary:`#83a598`,primaryMuted:`#5a7068`,secondary:`#d3869b`,accent:`#d65d0e`,info:`#8ec07c`,success:`#b8bb26`,successMuted:`#7a7d24`,error:`#fb4934`,errorMuted:`#a2392c`,warning:`#fabd2f`,warningMuted:`#a27e29`,border:`#665c54`,borderFocused:`#83a598`,borderSubtle:`#504945`,diffAdded:`#3c3f22`,diffAddedText:`#b8bb26`,diffAddedHighlight:`#4b4f2a`,diffRemoved:`#492825`,diffRemovedText:`#fb4934`,diffRemovedHighlight:`#5c322e`,codeBackground:`#3c3836`,promptBorder:`#bdae93`,suggestion:`#83a598`,link:`#83a598`,linkVisited:`#d3869b`,gradientStart:`#83a598`,gradientMid:`#d3869b`,gradientEnd:`#d65d0e`,syntaxKeyword:`#d3869b`,syntaxString:`#b8bb26`,syntaxNumber:`#fe8019`,syntaxComment:`#665c54`,syntaxFunction:`#83a598`,syntaxVariable:`#fb4934`,syntaxType:`#fabd2f`,syntaxOperator:`#d5c4a1`,syntaxPunctuation:`#d5c4a1`}},{name:`onedark`,displayName:`OneDark`,type:`dark`,author:`Lalit Magant (http://github.com/tilal6991)`,source:`base16`,colors:{text:`#abb2bf`,textMuted:`#565c64`,textSubtle:`#545862`,textInverse:`#282c34`,background:`#282c34`,backgroundAlt:`#353b45`,backgroundSelection:`#3e4451`,backgroundHover:`#353b45`,primary:`#61afef`,primaryMuted:`#4a7ba4`,secondary:`#c678dd`,accent:`#be5046`,info:`#56b6c2`,success:`#98c379`,successMuted:`#6b875d`,error:`#e06c75`,errorMuted:`#96525b`,warning:`#e5c07b`,warningMuted:`#99855f`,border:`#545862`,borderFocused:`#61afef`,borderSubtle:`#3e4451`,diffAdded:`#3e4a42`,diffAddedText:`#98c379`,diffAddedHighlight:`#4c5c50`,diffRemoved:`#4d3941`,diffRemovedText:`#e06c75`,diffRemovedHighlight:`#614750`,codeBackground:`#353b45`,promptBorder:`#565c64`,suggestion:`#61afef`,link:`#61afef`,linkVisited:`#c678dd`,gradientStart:`#61afef`,gradientMid:`#c678dd`,gradientEnd:`#be5046`,syntaxKeyword:`#c678dd`,syntaxString:`#98c379`,syntaxNumber:`#d19a66`,syntaxComment:`#545862`,syntaxFunction:`#61afef`,syntaxVariable:`#e06c75`,syntaxType:`#e5c07b`,syntaxOperator:`#abb2bf`,syntaxPunctuation:`#abb2bf`}},{name:`solarized-dark`,displayName:`Solarized Dark`,type:`dark`,author:`Ethan Schoonover (modified by aramisgithub)`,source:`base16`,colors:{text:`#93a1a1`,textMuted:`#839496`,textSubtle:`#657b83`,textInverse:`#002b36`,background:`#002b36`,backgroundAlt:`#073642`,backgroundSelection:`#586e75`,backgroundHover:`#073642`,primary:`#268bd2`,primaryMuted:`#176594`,secondary:`#6c71c4`,accent:`#d33682`,info:`#2aa198`,success:`#859900`,successMuted:`#506d16`,error:`#dc322f`,errorMuted:`#842f32`,warning:`#b58900`,warningMuted:`#6d6316`,border:`#657b83`,borderFocused:`#268bd2`,borderSubtle:`#586e75`,diffAdded:`#1b412b`,diffAddedText:`#859900`,diffAddedHighlight:`#235236`,diffRemoved:`#2c2c35`,diffRemovedText:`#dc322f`,diffRemovedHighlight:`#3a3644`,codeBackground:`#073642`,promptBorder:`#839496`,suggestion:`#268bd2`,link:`#268bd2`,linkVisited:`#6c71c4`,gradientStart:`#268bd2`,gradientMid:`#6c71c4`,gradientEnd:`#d33682`,syntaxKeyword:`#6c71c4`,syntaxString:`#859900`,syntaxNumber:`#cb4b16`,syntaxComment:`#657b83`,syntaxFunction:`#268bd2`,syntaxVariable:`#dc322f`,syntaxType:`#b58900`,syntaxOperator:`#93a1a1`,syntaxPunctuation:`#93a1a1`}},{name:`monokai`,displayName:`Monokai`,type:`dark`,author:`Wimer Hazenberg (http://www.monokai.nl)`,source:`base16`,colors:{text:`#f8f8f2`,textMuted:`#a59f85`,textSubtle:`#75715e`,textInverse:`#272822`,background:`#272822`,backgroundAlt:`#383830`,backgroundSelection:`#49483e`,backgroundHover:`#383830`,primary:`#66d9ef`,primaryMuted:`#4d929d`,secondary:`#ae81ff`,accent:`#cc6633`,info:`#a1efe4`,success:`#a6e22e`,successMuted:`#739829`,error:`#f92672`,errorMuted:`#a52752`,warning:`#f4bf75`,warningMuted:`#a28354`,border:`#75715e`,borderFocused:`#66d9ef`,borderSubtle:`#49483e`,diffAdded:`#404d24`,diffAddedText:`#a6e22e`,diffAddedHighlight:`#50602d`,diffRemoved:`#512832`,diffRemovedText:`#f92672`,diffRemovedHighlight:`#66323f`,codeBackground:`#383830`,promptBorder:`#a59f85`,suggestion:`#66d9ef`,link:`#66d9ef`,linkVisited:`#ae81ff`,gradientStart:`#66d9ef`,gradientMid:`#ae81ff`,gradientEnd:`#cc6633`,syntaxKeyword:`#ae81ff`,syntaxString:`#a6e22e`,syntaxNumber:`#fd971f`,syntaxComment:`#75715e`,syntaxFunction:`#66d9ef`,syntaxVariable:`#f92672`,syntaxType:`#f4bf75`,syntaxOperator:`#f8f8f2`,syntaxPunctuation:`#f8f8f2`}},{name:`tokyo-night-terminal-dark`,displayName:`Tokyo Night Terminal Dark`,type:`dark`,author:`Michaël Ball`,source:`base16`,colors:{text:`#787c99`,textMuted:`#787c99`,textSubtle:`#444b6a`,textInverse:`#16161e`,background:`#16161e`,backgroundAlt:`#1a1b26`,backgroundSelection:`#2f3549`,backgroundHover:`#1a1b26`,primary:`#7aa2f7`,primaryMuted:`#526aa0`,secondary:`#bb9af7`,accent:`#d18616`,info:`#7dcfff`,success:`#41a6b5`,successMuted:`#306c79`,error:`#f7768e`,errorMuted:`#9d5061`,warning:`#e0af68`,warningMuted:`#8f724a`,border:`#444b6a`,borderFocused:`#7aa2f7`,borderSubtle:`#2f3549`,diffAdded:`#1f333c`,diffAddedText:`#41a6b5`,diffAddedHighlight:`#28424c`,diffRemoved:`#432934`,diffRemovedText:`#f7768e`,diffRemovedHighlight:`#563543`,codeBackground:`#1a1b26`,promptBorder:`#787c99`,suggestion:`#7aa2f7`,link:`#7aa2f7`,linkVisited:`#bb9af7`,gradientStart:`#7aa2f7`,gradientMid:`#bb9af7`,gradientEnd:`#d18616`,syntaxKeyword:`#bb9af7`,syntaxString:`#41a6b5`,syntaxNumber:`#ff9e64`,syntaxComment:`#444b6a`,syntaxFunction:`#7aa2f7`,syntaxVariable:`#f7768e`,syntaxType:`#e0af68`,syntaxOperator:`#787c99`,syntaxPunctuation:`#787c99`}},{name:`rose-pine`,displayName:`Rosé Pine`,type:`dark`,author:`Emilia Dunfelt <edun@dunfelt.se>`,source:`base16`,colors:{text:`#e0def4`,textMuted:`#908caa`,textSubtle:`#6e6a86`,textInverse:`#191724`,background:`#191724`,backgroundAlt:`#1f1d2e`,backgroundSelection:`#26233a`,backgroundHover:`#1f1d2e`,primary:`#c4a7e7`,primaryMuted:`#806d99`,secondary:`#f6c177`,accent:`#524f67`,info:`#9ccfd8`,success:`#31748f`,successMuted:`#274f64`,error:`#eb6f92`,errorMuted:`#974c66`,warning:`#ebbcba`,warningMuted:`#977a7e`,border:`#6e6a86`,borderFocused:`#c4a7e7`,borderSubtle:`#26233a`,diffAdded:`#1e2a39`,diffAddedText:`#31748f`,diffAddedHighlight:`#263648`,diffRemoved:`#43293a`,diffRemovedText:`#eb6f92`,diffRemovedHighlight:`#55344a`,codeBackground:`#1f1d2e`,promptBorder:`#908caa`,suggestion:`#c4a7e7`,link:`#c4a7e7`,linkVisited:`#f6c177`,gradientStart:`#c4a7e7`,gradientMid:`#f6c177`,gradientEnd:`#524f67`,syntaxKeyword:`#f6c177`,syntaxString:`#31748f`,syntaxNumber:`#f6c177`,syntaxComment:`#6e6a86`,syntaxFunction:`#c4a7e7`,syntaxVariable:`#eb6f92`,syntaxType:`#ebbcba`,syntaxOperator:`#e0def4`,syntaxPunctuation:`#e0def4`}},{name:`material-darker`,displayName:`Material Darker`,type:`dark`,author:`Nate Peterson`,source:`base16`,colors:{text:`#eeffff`,textMuted:`#b2ccd6`,textSubtle:`#4a4a4a`,textInverse:`#212121`,background:`#212121`,backgroundAlt:`#303030`,backgroundSelection:`#353535`,backgroundHover:`#303030`,primary:`#82aaff`,primaryMuted:`#5b73a6`,secondary:`#c792ea`,accent:`#ff5370`,info:`#89ddff`,success:`#c3e88d`,successMuted:`#829862`,error:`#f07178`,errorMuted:`#9d5155`,warning:`#ffcb6b`,warningMuted:`#a6874d`,border:`#4a4a4a`,borderFocused:`#82aaff`,borderSubtle:`#353535`,diffAdded:`#414937`,diffAddedText:`#c3e88d`,diffAddedHighlight:`#505c44`,diffRemoved:`#4a3132`,diffRemovedText:`#f07178`,diffRemovedHighlight:`#5e3d40`,codeBackground:`#303030`,promptBorder:`#b2ccd6`,suggestion:`#82aaff`,link:`#82aaff`,linkVisited:`#c792ea`,gradientStart:`#82aaff`,gradientMid:`#c792ea`,gradientEnd:`#ff5370`,syntaxKeyword:`#c792ea`,syntaxString:`#c3e88d`,syntaxNumber:`#f78c6c`,syntaxComment:`#4a4a4a`,syntaxFunction:`#82aaff`,syntaxVariable:`#f07178`,syntaxType:`#ffcb6b`,syntaxOperator:`#eeffff`,syntaxPunctuation:`#eeffff`}}]};const IL=FL,LL=(0,Z.createContext)(null);function RL(){let e=(0,Z.use)(LL);if(!e)throw Error(`useTheme must be used within a ThemeProvider`);return e}function zL({children:e,defaultTheme:t}){let[n,r]=(0,Z.useState)(t||IL.default||`catppuccin-mocha`),i=(0,Z.useMemo)(()=>IL.themes.find(e=>e.name===n)||IL.themes.find(e=>e.name===IL.default)||IL.themes[0],[n]),a=(0,Z.useMemo)(()=>({theme:i,colors:i.colors,setTheme:r,availableThemes:IL.themes}),[i]);return(0,X.jsx)(LL.Provider,{value:a,children:e})}function BL(e){return(e.startsWith(`"`)&&e.endsWith(`"`)?e.slice(1,-1):e).replace(/<br\s*\/?>/gi,`
12593
12593
  `).replace(/\\n/g,`
12594
12594
  `).replace(/<\/?(?:sub|sup|small|mark)\s*>/gi,``).replace(/\*\*(.+?)\*\*/g,`<b>$1</b>`).replace(/(?<!\*)\*([^\s*](?:[^*]*[^\s*])?)\*(?!\*)/g,`<i>$1</i>`).replace(/~~(.+?)~~/g,`<s>$1</s>`)}function VL(e){let t=e.split(`
12595
12595
  `).map(e=>e.trim()).filter(e=>e.length>0&&!e.startsWith(`%%`));if(t.length===0)throw Error(`Empty mermaid diagram`);let n=t[0];return/^stateDiagram(-v2)?\s*$/i.test(n)?UL(t):HL(t)}function HL(e){let t=e[0].match(/^(?:graph|flowchart)\s+(TD|TB|LR|BT|RL)\s*$/i);if(!t)throw Error(`Invalid mermaid header: "${e[0]}". Expected "graph TD", "flowchart LR", "stateDiagram-v2", etc.`);let n={direction:t[1].toUpperCase(),nodes:new Map,edges:[],subgraphs:[],classDefs:new Map,classAssignments:new Map,nodeStyles:new Map,linkStyles:new Map},r=[];for(let t=1;t<e.length;t++){let i=e[t],a=i.match(/^classDef\s+(\w+)\s+(.+)$/);if(a){let e=a[1],t=a[2],r=KL(t);n.classDefs.set(e,r);continue}let o=i.match(/^class\s+([\w,-]+)\s+(\w+)$/);if(o){let e=o[1].split(`,`).map(e=>e.trim()),t=o[2];for(let r of e)n.classAssignments.set(r,t);continue}let s=i.match(/^style\s+([\w,-]+)\s+(.+)$/);if(s){let e=s[1].split(`,`).map(e=>e.trim()),t=KL(s[2]);for(let r of e)n.nodeStyles.set(r,{...n.nodeStyles.get(r),...t});continue}let c=i.match(/^linkStyle\s+(default|[\d,\s]+)\s+(.+)$/);if(c){let e=c[1].trim(),t=KL(c[2]);if(e===`default`)n.linkStyles.set(`default`,{...n.linkStyles.get(`default`),...t});else{let r=e.split(`,`).map(e=>parseInt(e.trim(),10));for(let e of r)isNaN(e)||n.linkStyles.set(e,{...n.linkStyles.get(e),...t})}continue}let l=i.match(/^direction\s+(TD|TB|LR|BT|RL)\s*$/i);if(l&&r.length>0){r[r.length-1].direction=l[1].toUpperCase();continue}let u=i.match(/^subgraph\s+(.+)$/);if(u){let e=u[1].trim(),t=e.match(/^([\w-]+)\s*\[(.+)\]$/),n,i;t?(n=t[1],i=BL(t[2])):(i=BL(e),n=e.replace(/\s+/g,`_`).replace(/[^\w]/g,``));let a={id:n,label:i,nodeIds:[],children:[]};r.push(a);continue}if(i===`end`){let e=r.pop();e&&(r.length>0?r[r.length-1].children.push(e):n.subgraphs.push(e));continue}QL(i,n,r)}return n}function UL(e){let t={direction:`TD`,nodes:new Map,edges:[],subgraphs:[],classDefs:new Map,classAssignments:new Map,nodeStyles:new Map,linkStyles:new Map},n=[],r=new Set,i=0,a=0;for(let o=1;o<e.length;o++){let s=e[o],c=s.match(/^direction\s+(TD|TB|LR|BT|RL)\s*$/i);if(c){n.length>0?n[n.length-1].direction=c[1].toUpperCase():t.direction=c[1].toUpperCase();continue}let l=s.match(/^linkStyle\s+(default|[\d,\s]+)\s+(.+)$/);if(l){let e=l[1].trim(),n=KL(l[2]);if(e===`default`)t.linkStyles.set(`default`,{...t.linkStyles.get(`default`),...n});else{let r=e.split(`,`).map(e=>parseInt(e.trim(),10));for(let e of r)isNaN(e)||t.linkStyles.set(e,{...t.linkStyles.get(e),...n})}continue}let u=s.match(/^state\s+(?:"([^"]+)"\s+as\s+)?([\w\p{L}]+)\s*\{$/u);if(u){let e=u[1]??u[2],i=u[2],a={id:i,label:e,nodeIds:[],children:[]};n.push(a),r.add(i),t.nodes.delete(i);continue}if(s===`}`){let e=n.pop();e&&(n.length>0?n[n.length-1].children.push(e):t.subgraphs.push(e));continue}let d=s.match(/^state\s+"([^"]+)"\s+as\s+([\w\p{L}]+)\s*$/u);if(d){let e=BL(d[1]),r=d[2];WL(t,n,{id:r,label:e,shape:`rounded`});continue}let f=s.match(/^(\[\*\]|[\w\p{L}-]+)\s*(-->)\s*(\[\*\]|[\w\p{L}-]+)(?:\s*:\s*(.+))?$/u);if(f){let e=f[1],o=f[3],s=f[4]?.trim(),c=s?BL(s):void 0;e===`[*]`?(i++,e=`_start${i>1?i:``}`,WL(t,n,{id:e,label:``,shape:`state-start`})):r.has(e)||GL(t,n,e),o===`[*]`?(a++,o=`_end${a>1?a:``}`,WL(t,n,{id:o,label:``,shape:`state-end`})):r.has(o)||GL(t,n,o),t.edges.push({source:e,target:o,label:c,style:`solid`,hasArrowStart:!1,hasArrowEnd:!0});continue}let p=s.match(/^([\w\p{L}-]+)\s*:\s*(.+)$/u);if(p){let e=p[1];WL(t,n,{id:e,label:BL(p[2].trim()),shape:`rounded`});continue}}return t}function WL(e,t,n){if(e.nodes.has(n.id)||e.nodes.set(n.id,n),t.length>0){let e=t[t.length-1];e.nodeIds.includes(n.id)||e.nodeIds.push(n.id)}}function GL(e,t,n){if(!e.nodes.has(n))WL(e,t,{id:n,label:n,shape:`rounded`});else if(t.length>0){let e=t[t.length-1];e.nodeIds.includes(n)||e.nodeIds.push(n)}}function KL(e){let t=e.replace(/;\s*$/,``),n={};for(let e of t.split(`,`)){let t=e.indexOf(`:`);if(t>0){let r=e.slice(0,t).trim(),i=e.slice(t+1).trim();r&&i&&(n[r]=i)}}return n}var qL=/^(<)?(-->|-.->|==>|---|-\.-|===)(?:\|([^|]*)\|)?/,JL=/^(<)?(--|-\.|==)\s+(.+?)\s+(-->|---|\.\->|-\.\-|==>|===)/,YL=[{regex:/^([\w-]+)\(\(\((.+?)\)\)\)/,shape:`doublecircle`},{regex:/^([\w-]+)\(\[(.+?)\]\)/,shape:`stadium`},{regex:/^([\w-]+)\(\((.+?)\)\)/,shape:`circle`},{regex:/^([\w-]+)\[\[(.+?)\]\]/,shape:`subroutine`},{regex:/^([\w-]+)\[\((.+?)\)\]/,shape:`cylinder`},{regex:/^([\w-]+)\[\/(.+?)\\\]/,shape:`trapezoid`},{regex:/^([\w-]+)\[\\(.+?)\/\]/,shape:`trapezoid-alt`},{regex:/^([\w-]+)>(.+?)\]/,shape:`asymmetric`},{regex:/^([\w-]+)\{\{(.+?)\}\}/,shape:`hexagon`},{regex:/^([\w-]+)\[(.+?)\]/,shape:`rectangle`},{regex:/^([\w-]+)\((.+?)\)/,shape:`rounded`},{regex:/^([\w-]+)\{(.+?)\}/,shape:`diamond`}],XL=/^([\w-]+)/,ZL=/^:::([\w][\w-]*)/;function QL(e,t,n){let r=e.trim(),i=$L(r,t,n);if(!i||i.ids.length===0)return;r=i.remaining.trim();let a=i.ids;for(;r.length>0;){let e,i,o,s,c=r.match(qL);if(c){e=!!c[1];let t=c[2],n=c[3]?.trim();s=n?BL(n):void 0,r=r.slice(c[0].length).trim(),i=rR(t),o=t.endsWith(`>`)}else{let t=r.match(JL);if(!t)break;e=!!t[1];let n=t[3].trim();s=n?BL(n):void 0;let a=t[2],c=t[4];r=r.slice(t[0].length).trim(),i=iR(a,c),o=c.endsWith(`>`)}let l=$L(r,t,n);if(!l||l.ids.length===0)break;r=l.remaining.trim();for(let n of a)for(let r of l.ids)t.edges.push({source:n,target:r,label:s,style:i,hasArrowStart:e,hasArrowEnd:o});a=l.ids}}function $L(e,t,n){let r=eR(e,t,n);if(!r)return null;let i=[r.id],a=r.remaining.trim();for(;a.startsWith(`&`);){a=a.slice(1).trim();let e=eR(a,t,n);if(!e)break;i.push(e.id),a=e.remaining.trim()}return{ids:i,remaining:a}}function eR(e,t,n){let r=null,i=e;for(let{regex:a,shape:o}of YL){let s=e.match(a);if(s){r=s[1];let a=BL(s[2]);tR(t,n,{id:r,label:a,shape:o}),i=e.slice(s[0].length);break}}if(r===null){let a=e.match(XL);a&&(r=a[1],t.nodes.has(r)||tR(t,n,{id:r,label:r,shape:`rectangle`}),i=e.slice(a[0].length))}if(r===null)return null;let a=i.match(ZL);return a&&(t.classAssignments.set(r,a[1]),i=i.slice(a[0].length)),{id:r,remaining:i}}function tR(e,t,n){e.nodes.has(n.id)||e.nodes.set(n.id,n),nR(t,n.id)}function nR(e,t){if(e.length>0){let n=e[e.length-1];n.nodeIds.includes(t)||n.nodeIds.push(t)}}function rR(e){return e===`-.->`||e===`-.-`?`dotted`:e===`==>`||e===`===`?`thick`:`solid`}function iR(e,t){return e===`-.`||t===`.->`||t===`-.-`?`dotted`:e===`==`||t===`==>`||t===`===`?`thick`:`solid`}var aR={x:1,y:0},oR={x:1,y:2},sR={x:0,y:1},cR={x:2,y:1},lR={x:2,y:0},uR={x:0,y:0},dR={x:2,y:2},fR={x:0,y:2},pR={x:1,y:1};function mR(e,t){return e.x===t.x&&e.y===t.y}function hR(e,t){return e.x===t.x&&e.y===t.y}function gR(e,t){return{x:e.x+t.x,y:e.y+t.y}}function _R(e){return`${e.x},${e.y}`}var vR={name:``,styles:{}},yR={fg:`#27272a`,border:`#a1a1aa`,line:`#71717a`,arrow:`#52525b`,corner:`#71717a`,junction:`#a1a1aa`};function bR(){let e=globalThis.process;if(e){if(!e.stdout?.isTTY)return`none`;let t=e.env?.COLORTERM?.toLowerCase()??``,n=e.env?.TERM?.toLowerCase()??``;return t===`truecolor`||t===`24bit`?`truecolor`:n.includes(`256color`)||n.includes(`256`)?`ansi256`:n&&n!==`dumb`?`ansi16`:`none`}return typeof document<`u`?`html`:`none`}function xR(e){let t=e.replace(`#`,``);return t.length===3?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16)}:{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}var SR=`\x1B[`,CR=`${SR}0m`;function wR(e){let{r:t,g:n,b:r}=xR(e);return`${SR}38;2;${t};${n};${r}m`}function TR(e,t,n){let r=(e+t+n)/3;if(Math.max(Math.abs(e-r),Math.abs(t-r),Math.abs(n-r))<10){let e=Math.round(r/255*23);return 232+Math.min(23,Math.max(0,e))}let i=e=>e<48?0:e<115?1:Math.min(5,Math.floor((e-35)/40)),a=i(e),o=i(t),s=i(n);return 16+36*a+6*o+s}function ER(e){let{r:t,g:n,b:r}=xR(e);return`${SR}38;5;${TR(t,n,r)}m`}function DR(e){let{r:t,g:n,b:r}=xR(e),i=.299*t+.587*n+.114*r,a=i>100?0:60,o;return o=t>180&&n<100&&r<100?31:n>180&&t<100&&r<100?32:t>150&&n>150&&r<100?33:r>180&&t<100&&n<100?34:t>150&&r>150&&n<100?35:n>150&&r>150&&t<100?36:i>200?37:i<50?30:37,`${SR}${o+a}m`}function OR(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`)}function kR(e,t){return`<span style="color:${e}">${OR(t)}</span>`}function AR(e,t){switch(e){case`text`:return t.fg;case`border`:return t.border;case`line`:return t.line;case`arrow`:return t.arrow;case`corner`:return t.corner??t.line;case`junction`:return t.junction??t.border;default:return t.fg}}function jR(e,t,n){if(n===`none`)return``;let r=AR(e,t);switch(n){case`truecolor`:return wR(r);case`ansi256`:return ER(r);case`ansi16`:return DR(r);default:return``}}function MR(e,t,n,r){if(r===`none`)return e.join(``);if(r===`html`)return NR(e,t,n);let i=``,a=null,o=``;for(let s=0;s<e.length;s++){let c=e[s],l=t[s]??null;if(c===` `){o.length>0&&(a===null?i+=o:i+=jR(a,n,r)+o+CR,o=``,a=null),i+=c;continue}if(l===a){o+=c;continue}o.length>0&&(a===null?i+=o:i+=jR(a,n,r)+o+CR),o=c,a=l}return o.length>0&&a!==null?i+=jR(a,n,r)+o+CR:o.length>0&&(i+=o),i}function NR(e,t,n){let r=``,i=null,a=``,o=()=>{a.length!==0&&(i===null?r+=OR(a):r+=kR(AR(i,n),a),a=``,i=null)};for(let n=0;n<e.length;n++){let s=e[n],c=t[n]??null;if(s===` `){o(),r+=` `;continue}if(c===i){a+=s;continue}o(),a=s,i=c}return o(),r}function PR(e,t,n){if(n===`none`||e.length===0)return e;if(n===`html`)return kR(t,e);let r;switch(n){case`truecolor`:r=wR(t);break;case`ansi256`:r=ER(t);break;case`ansi16`:r=DR(t);break;default:return e}return`${r}${e}${CR}`}function FR(e,t){let n=[];for(let r=0;r<=e;r++){let e=[];for(let n=0;n<=t;n++)e.push(` `);n.push(e)}return n}function IR(e){let[t,n]=BR(e);return FR(t,n)}function LR(e,t){let n=[];for(let r=0;r<=e;r++){let e=[];for(let n=0;n<=t;n++)e.push(null);n.push(e)}return n}function RR(e,t,n){let r=e.length-1,i=(e[0]?.length??1)-1,a=LR(Math.max(t,r),Math.max(n,i));for(let t=0;t<a.length;t++)for(let n=0;n<a[0].length;n++)t<e.length&&n<e[0].length&&(a[t][n]=e[t][n]);return e.length=0,e.push(...a),e}function zR(e,t,n,r){(t>=e.length||n>=(e[0]?.length??0))&&RR(e,t,n),e[t][n]=r}function BR(e){return[e.length-1,(e[0]?.length??1)-1]}function VR(e,t,n){let[r,i]=BR(e),a=FR(Math.max(t,r),Math.max(n,i));for(let t=0;t<a.length;t++)for(let n=0;n<a[0].length;n++)t<e.length&&n<e[0].length&&(a[t][n]=e[t][n]);return e.length=0,e.push(...a),e}var HR=new Set([`─`,`│`,`┌`,`┐`,`└`,`┘`,`├`,`┤`,`┬`,`┴`,`┼`,`╴`,`╵`,`╶`,`╷`]);function UR(e){return HR.has(e)}function WR(e){return/^[a-zA-Z0-9]$/.test(e)}var GR={"─":{"│":`┼`,"┌":`┬`,"┐":`┬`,"└":`┴`,"┘":`┴`,"├":`┼`,"┤":`┼`,"┬":`┬`,"┴":`┴`},"│":{"─":`┼`,"┌":`├`,"┐":`┤`,"└":`├`,"┘":`┤`,"├":`├`,"┤":`┤`,"┬":`┼`,"┴":`┼`},"┌":{"─":`┬`,"│":`├`,"┐":`┬`,"└":`├`,"┘":`┼`,"├":`├`,"┤":`┼`,"┬":`┬`,"┴":`┼`},"┐":{"─":`┬`,"│":`┤`,"┌":`┬`,"└":`┼`,"┘":`┤`,"├":`┼`,"┤":`┤`,"┬":`┬`,"┴":`┼`},"└":{"─":`┴`,"│":`├`,"┌":`├`,"┐":`┼`,"┘":`┴`,"├":`├`,"┤":`┼`,"┬":`┼`,"┴":`┴`},"┘":{"─":`┴`,"│":`┤`,"┌":`┼`,"┐":`┤`,"└":`┴`,"├":`┼`,"┤":`┤`,"┬":`┼`,"┴":`┴`},"├":{"─":`┼`,"│":`├`,"┌":`├`,"┐":`┼`,"└":`├`,"┘":`┼`,"┤":`┼`,"┬":`┼`,"┴":`┼`},"┤":{"─":`┼`,"│":`┤`,"┌":`┼`,"┐":`┤`,"└":`┼`,"┘":`┤`,"├":`┼`,"┬":`┼`,"┴":`┼`},"┬":{"─":`┬`,"│":`┼`,"┌":`┬`,"┐":`┬`,"└":`┼`,"┘":`┼`,"├":`┼`,"┤":`┼`,"┴":`┼`},"┴":{"─":`┴`,"│":`┼`,"┌":`┼`,"┐":`┼`,"└":`┴`,"┘":`┴`,"├":`┼`,"┤":`┼`,"┬":`┼`}};function KR(e,t){return GR[e]?.[t]??e}function qR(e,t,n,...r){let[i,a]=BR(e);for(let e of r){let[n,r]=BR(e);i=Math.max(i,n+t.x),a=Math.max(a,r+t.y)}let o=FR(i,a);for(let t=0;t<=i;t++)for(let n=0;n<=a;n++)t<e.length&&n<e[0].length&&(o[t][n]=e[t][n]);for(let e of r)for(let r=0;r<e.length;r++)for(let i=0;i<e[0].length;i++){let a=e[r][i];if(a!==` `){let e=r+t.x,s=i+t.y,c=o[e][s];!n&&UR(a)&&UR(c)?o[e][s]=KR(c,a):WR(c)&&WR(a)||(o[e][s]=a)}}return o}function JR(e,t){let[n,r]=BR(e),i=[],a=t?.roleCanvas,o=t?.colorMode??`none`,s=t?.theme??yR;for(let t=0;t<=r;t++)if(o===`none`||!a){let r=``;for(let i=0;i<=n;i++)r+=e[i][t];i.push(r)}else{let r=[],c=[];for(let i=0;i<=n;i++)r.push(e[i][t]),c.push(a[i]?.[t]??null);i.push(MR(r,c,s,o))}return i.join(`
@@ -12633,19 +12633,19 @@ https://github.com/highlightjs/highlight.js/issues/2277`),a=e,i=t);let o={code:i
12633
12633
  `),displayLineCount:i.length,totalLines:n,hasMore:n>r}},[e,r]),l=(0,Z.useMemo)(()=>{if(!a)return a;let n=t?LK(t):void 0;if(n===`mermaid`){let t=RK(e);if(t!==null)return t}if(n&&(0,OK.supportsLanguage)(n))try{return(0,OK.highlight)(a,{language:n})}catch{}return a},[a,t,e]);if(!a)return null;let u=(n+o-1).toString().length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[l.split(`
12634
12634
  `).map((e,t)=>{let r=n+t;return(0,X.jsxs)($,{dimColor:i,children:[(0,X.jsxs)($,{dimColor:!0,children:[String(r).padStart(u,` `),` │ `]}),e]},t)}),s&&(0,X.jsxs)($,{dimColor:!0,children:[` ... `,o-c,` more lines`]})]})}function BK(e,t){let n=LK(t);if(n&&n!==`mermaid`&&(0,OK.supportsLanguage)(n))try{return(0,OK.highlight)(e,{language:n}).split(`
12635
12635
  `)}catch{}return e.split(`
12636
- `)}function VK(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>VK(e));let t={};for(let[n,r]of Object.entries(e)){let e=n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase());t[e]=VK(r)}return t}function HK(e){if(typeof e!=`string`)return e;let t=e.trim();return t?Number(t):NaN}function UK(e){if(typeof e!=`string`)return e;let t=e.trim().toLowerCase();return[`true`,`1`,`yes`,`y`].includes(t)?!0:[`false`,`0`,`no`,`n`].includes(t)?!1:e}const WK=Vc(HK,Is()),GK=Vc(HK,Is().optional()),KK=Vc(UK,Bs()),qK=Vc(UK,Bs().optional()),JK=tc({questions:$s(tc({question:J(),header:J(),options:$s(tc({label:J(),description:J()})),multiSelect:KK})),answers:fc(J(),J()).optional()}),YK={displayName:`AskUserQuestion`,getHeaderParams(e){return``},renderUI(e,t,n){let r=JK.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.questions||[],o=n?.data.answers??i.answers??{};if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`){let e=Object.keys(o).length>0;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:e?`success`:`rejected`}),(0,X.jsx)(FK,{color:e?`green`:`yellow`,children:e?`User answered ${Object.keys(o).length} question${Object.keys(o).length===1?``:`s`}`:n?.userNote?(0,X.jsxs)(X.Fragment,{children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):`User cancelled the questions`})]})}if(t===`pending`||t===`executing`)return(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`pending`,showSpinner:!0});let s=a.length,c=Object.keys(o).length;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`success`}),(0,X.jsxs)(FK,{children:[`Answered `,s,` question`,s===1?``:`s`]}),c>0&&(0,X.jsx)(IK,{children:Object.entries(o).map(([e,t],n)=>{let r=parseInt(e.replace(`question_`,``),10),i=a[r];return(0,X.jsxs)(Q,{flexDirection:`column`,marginBottom:1,children:[(0,X.jsx)($,{dimColor:!0,children:i?.header||`Question ${r+1}`}),(0,X.jsxs)($,{color:`cyan`,children:[`→ `,String(t)]})]},n)})})]})}},XK={displayName:`EnterPlanMode`,getHeaderParams(e){return``},renderUI(e,t,n){return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):t===`pending`||t===`executing`?(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`pending`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`success`}),(0,X.jsx)(FK,{children:`Entered plan mode`})]})}};let ZK=function(e){return e[e.Prompt=0]=`Prompt`,e[e.Help=1]=`Help`,e[e.Bash=2]=`Bash`,e[e.Command=3]=`Command`,e[e.Files=4]=`Files`,e}({});const QK=(0,Z.createContext)(null),$K=()=>{let e=(0,Z.use)(QK);if(!e)throw Error(`${$K.name} must be used within ${nq.name}`);return e},eq=[xl.Normal,xl.AcceptEdits,xl.PlanMode];function tq(e,t){switch(t.type){case`CYCLE`:{if(e.isWaitingForYoloConfirm)return{agentMode:xl.Yolo,isWaitingForYoloConfirm:!1};if(e.agentMode===xl.Yolo)return{agentMode:xl.Normal,isWaitingForYoloConfirm:!1};let t=eq.indexOf(e.agentMode);return t===-1?{agentMode:xl.Normal,isWaitingForYoloConfirm:!1}:t===eq.length-1?{agentMode:e.agentMode,isWaitingForYoloConfirm:!0}:{agentMode:eq[t+1],isWaitingForYoloConfirm:!1}}case`SET`:return{agentMode:t.mode,isWaitingForYoloConfirm:!1};case`RESET`:return{agentMode:xl.Normal,isWaitingForYoloConfirm:!1};case`YOLO_TIMEOUT`:return{...e,isWaitingForYoloConfirm:!1}}}function nq({children:e,initialMode:t}){let[{agentMode:n,isWaitingForYoloConfirm:r},i]=(0,Z.useReducer)(tq,{agentMode:t??xl.Normal,isWaitingForYoloConfirm:!1});(0,Z.useEffect)(()=>{if(!r)return;let e=setTimeout(()=>i({type:`YOLO_TIMEOUT`}),3e3);return()=>clearTimeout(e)},[r]);let a=(0,Z.useMemo)(()=>({agentMode:n,setAgentMode:e=>i({type:`SET`,mode:e}),cycleAgentMode:()=>i({type:`CYCLE`}),isWaitingForYoloConfirm:r,resetToNormal:()=>i({type:`RESET`})}),[n,r]);return(0,X.jsx)(QK.Provider,{value:a,children:e})}const rq=tc({planFilePath:J()});function iq({rawInput:e,status:t,parsedResult:n}){let{agentMode:r}=$K(),i=rq.safeParse(VK(e)),a=(i.success?i.data.planFilePath:e?.planFilePath)||``;if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]});if(t===`pending`||t===`executing`)return(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`pending`,showSpinner:!0});let o=r===xl.AcceptEdits?`Plan approved (auto-accept mode)`:`Plan approved`;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`success`}),(0,X.jsxs)(FK,{children:[o,`: `,jK(a)]})]})}const aq={displayName:`ExitPlanMode`,getHeaderParams(e){return e?.planFilePath||``},renderUI(e,t,n){return(0,X.jsx)(iq,{rawInput:e,status:t,parsedResult:n})}},oq={displayName:`HandOff`,getHeaderParams(e){return``},renderUI(e,t,n){return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`HandOff`,status:`success`}),(0,X.jsx)(FK,{children:`Handed off to main agent`})]})}},sq=tc({agent:J(),task:J()}),cq={displayName:`Subagent`,getHeaderParams(e){return e?.agent||``},renderUI(e,t,n){let r=sq.safeParse(VK(e)),i=r.success?r.data.agent:e?.agent||``;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Subagent`,params:i,status:`success`}),(0,X.jsxs)(FK,{children:[`Switched to `,i,` agent`]})]})}},lq=tc({todos:Vc(e=>{if(e==null)return[];if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return Array.isArray(e)?e:[]},$s(tc({content:J(),status:mc([`pending`,`in_progress`,`completed`,`cancelled`]),id:J().optional()})))});function uq({rawInput:e,parsedResult:t}){let n=lq.safeParse(VK(e)),r=n.success?n.data.todos:[],i=(0,Z.useCallback)(e=>{switch(e){case`completed`:return`[x]`;case`in_progress`:return`[>]`;default:return`[ ]`}},[]),a=(0,Z.useCallback)(e=>{switch(e){case`completed`:return`green`;case`in_progress`:return`blue`;default:return`gray`}},[]);return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`TodoWrite`,status:`success`}),t?.summary&&(0,X.jsx)(FK,{children:t.summary}),r.length>0&&(0,X.jsx)(IK,{children:r.map((e,t)=>(0,X.jsxs)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:[(0,X.jsx)($,{color:a(e.status),children:i(e.status)}),(0,X.jsx)($,{color:e.status===`completed`?`gray`:void 0,dimColor:e.status===`completed`,children:e.content})]},t))})]})}const dq={displayName:`TodoWrite`,getHeaderParams(e){return``},renderUI(e,t,n){return(0,X.jsx)(uq,{rawInput:e,parsedResult:n})}},fq=tc({id:WK}),pq={displayName:`CloseTab`,getHeaderParams(e){let t=e;return`id: ${String(t.id??``)}`},renderUI(e,t,n){let r=fq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`CloseTab`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.id;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`pending`,showSpinner:!0}):n?t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error closing tab`})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`success`}),(0,X.jsx)(FK,{children:`Closed`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`pending`})})}},mq=tc({action:mc([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:uc([WK,WK]).optional(),startCoordinate:uc([WK,WK]).optional(),duration:GK,text:J().optional(),scrollAmount:GK,scrollDirection:mc([`up`,`down`,`left`,`right`]).optional()}),hq={displayName:`Computer`,getHeaderParams(e){return e?.action||`action`},renderUI(e,t,n){let r=mq.safeParse(VK(e)),i=r.success?r.data.action:e?.action||`action`;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`Computer`,params:i,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Computer`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing computer action`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Computer`,params:i,status:`success`}),(0,X.jsxs)(FK,{children:[`Performed `,i]})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Computer`,params:i,status:`pending`})})}},gq=tc({id:GK}),_q={displayName:`GetElements`,getHeaderParams(e){let t=e;return t.id===void 0?``:`id: ${String(t.id)}`},renderUI(e,t,n){let r=gq.safeParse(VK(e)),i=r.success&&r.data.id!==void 0?`id: ${r.data.id}`:void 0;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error: Failed to get interactive elements`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Found elements`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`pending`})})}},vq=tc({id:GK}),yq={displayName:`GetContent`,getHeaderParams(e){let t=e;return t.id===void 0?``:`id: ${String(t.id)}`},renderUI(e,t,n){let r=vq.safeParse(VK(e)),i=r.success&&r.data.id!==void 0?`id: ${r.data.id}`:void 0;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error: Failed to get tab content`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Got content`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`pending`})})}},bq=tc({url:J()}),xq={displayName:`Navigate`,getHeaderParams(e){let t=e?.url||``;return t.length>50?t.substring(0,47)+`...`:t},renderUI(e,t,n){let r=bq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Navigate`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=i.length>50?i.substring(0,47)+`...`:i;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error navigating to URL`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`success`}),(0,X.jsx)(FK,{children:`Navigated`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`pending`})})}},Sq=tc({url:J().optional()}),Cq={displayName:`NewTab`,getHeaderParams(e){let t=e?.url||``;return t.length>40?t.substring(0,37)+`...`:t},renderUI(e,t,n){let r=Sq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`NewTab`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=(i.length>40?i.substring(0,37)+`...`:i)||void 0;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error opening new tab`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Opened tab`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`pending`})})}},wq=tc({id:J(),action:mc([`click`,`type`,`hover`,`scroll`,`focus`,`select`]),text:J().optional(),scroll_direction:mc([`up`,`down`,`left`,`right`]).optional(),scroll_amount:GK,held_keys:J().optional(),tab_id:GK}),Tq={displayName:`PerformAction`,getHeaderParams(e){return`id: ${(e.id||``).substring(0,20)}`},renderUI(e,t,n){let r=e,i=wq.safeParse(VK(e)),a=i.success?i.data.action:r.action||`action`,o=`id: ${(r.id||``).substring(0,20)}`,s=a.charAt(0).toUpperCase()+a.slice(1);return!n&&t===`executing`?(0,X.jsx)(PK,{name:s,params:o,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:s,params:o,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing action`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:s,params:o,status:`success`}),(0,X.jsxs)(FK,{children:[`Performed `,a]})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:s,params:o,status:`pending`})})}},Eq={displayName:`Refresh`,getHeaderParams(e){return``},renderUI(e,t,n){return!n&&t===`executing`?(0,X.jsx)(PK,{name:`Refresh`,status:`pending`,showSpinner:!0}):n?t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Refresh`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error refreshing tab`})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Refresh`,status:`success`}),(0,X.jsx)(FK,{children:`Refreshed`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Refresh`,status:`pending`})})}},Dq=tc({id:WK}),Oq={displayName:`SwitchTab`,getHeaderParams(e){let t=e;return`id: ${String(t.id??``)}`},renderUI(e,t,n){let r=Dq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`SwitchTab`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.id;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error switching tab`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`success`}),(0,X.jsxs)(FK,{children:[`Switched to tab `,i]})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`pending`})})}},kq=tc({targetFile:J(),explanation:J().optional()}),Aq={displayName:`Delete`,getHeaderParams(e){try{return jK(e?.targetFile||e?.target_file||`[unknown]`)}catch{return`[unknown]`}},renderUI(e,t,n){let r=kq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let{targetFile:i}=r.data,a=jK(i);return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`rejected`}),(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`rejected`}),(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error deleting file`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`Delete`,params:a,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`success`}),(0,X.jsx)(FK,{children:`Deleted`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Delete`,params:a,status:`pending`})})}};function jq(e,t){return SK(e,t)}const Mq=(0,Z.memo)(({line:e,pairedLine:t,lineNumber:n,dimmed:r=!1})=>{let{colors:i}=RL();if(e.type===`separator`)return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsxs)($,{dimColor:!0,children:[n,` `]}),(0,X.jsxs)($,{dimColor:!0,children:[`⋮ `,e.skippedLines,` unchanged lines`]})]});if(e.type===`unchanged`)return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsxs)($,{dimColor:!0,children:[n,` `]}),(0,X.jsx)(Q,{flexShrink:1,children:(0,X.jsx)($,{dimColor:!0,wrap:`wrap`,children:e.highlightedContent??e.content})})]});if(e.type===`removed`){let a=t?.type===`added`?jq(e.content,t.content):null;return(0,X.jsxs)(Q,{flexDirection:`row`,backgroundColor:i.diffRemoved,children:[(0,X.jsxs)($,{backgroundColor:i.diffRemoved,color:i.diffRemovedText,dimColor:r,children:[n,` -`,` `]}),(0,X.jsx)(Q,{flexShrink:1,children:(0,X.jsx)($,{color:i.diffRemovedText,dimColor:r,wrap:`wrap`,children:a?a.map((e,t)=>e.removed?(0,X.jsx)($,{backgroundColor:i.diffRemovedHighlight,dimColor:r,children:e.value},t):e.added?null:(0,X.jsx)($,{backgroundColor:i.diffRemoved,dimColor:r,children:e.value},t)):(0,X.jsx)($,{backgroundColor:i.diffRemoved,dimColor:r,children:e.highlightedContent??e.content})})})]})}if(e.type===`added`){let a=t?.type===`removed`?jq(t.content,e.content):null;return(0,X.jsxs)(Q,{flexDirection:`row`,backgroundColor:i.diffAdded,children:[(0,X.jsxs)($,{backgroundColor:i.diffAdded,color:i.diffAddedText,dimColor:r,children:[n,` +`,` `]}),(0,X.jsx)(Q,{flexShrink:1,children:(0,X.jsx)($,{color:i.diffAddedText,dimColor:r,wrap:`wrap`,children:a?a.map((e,t)=>e.added?(0,X.jsx)($,{backgroundColor:i.diffAddedHighlight,dimColor:r,children:e.value},t):e.removed?null:(0,X.jsx)($,{backgroundColor:i.diffAdded,dimColor:r,children:e.value},t)):(0,X.jsx)($,{backgroundColor:i.diffAdded,dimColor:r,children:e.highlightedContent??e.content})})})]})}return null});Mq.displayName=`DiffLineContent`;const Nq=(0,Z.memo)(({filePath:e,hunks:t})=>{let{colors:n}=RL(),r=t.reduce((e,t)=>e+t.lines.filter(e=>e.startsWith(`+`)).length,0),i=t.reduce((e,t)=>e+t.lines.filter(e=>e.startsWith(`-`)).length,0);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{bold:!0,children:e}),(r>0||i>0)&&(0,X.jsxs)($,{dimColor:!0,children:[r>0&&(0,X.jsxs)($,{color:n.diffAddedText,children:[`+`,r]}),r>0&&i>0&&(0,X.jsx)($,{children:` `}),i>0&&(0,X.jsxs)($,{color:n.diffRemovedText,children:[`-`,i]})]})]})});Nq.displayName=`DiffPreviewTitle`;const Pq=(0,Z.memo)(({filePath:e,originalContent:t,newContent:n,dimmed:r=!1,...i})=>{let[a,o]=(0,Z.useState)(n),s=a!==n;(0,Z.useEffect)(()=>{if(a===n)return;let e=setTimeout(()=>o(n),0);return()=>clearTimeout(e)},[n,a]);let{diffLines:c,totalOriginalLines:l}=(0,Z.useMemo)(()=>{let n=BK(t,e),r=BK(a,e),i=EK(e,e,t,a,void 0,void 0,{context:1}),o=[],s=0;for(let e=0;e<i.hunks.length;e++){let t=i.hunks[e];if(!t)continue;let a=t.oldStart;if(e>0&&a>s+1){let e=a-s-1;e>0&&o.push({type:`separator`,content:``,skippedLines:e})}let c=t.oldStart,l=t.newStart;for(let e of t.lines){let t=e[0],i=e.slice(1);t!==`\\`&&(t===`+`?o.push({type:`added`,content:i,highlightedContent:r[l-1],newLineNumber:l++}):t===`-`?o.push({type:`removed`,content:i,highlightedContent:n[c-1],originalLineNumber:c++}):o.push({type:`unchanged`,content:i,highlightedContent:n[c-1],originalLineNumber:c++,newLineNumber:l++}))}s=c-1}return{diffLines:o,totalOriginalLines:t.split(`
12637
- `).length}},[e,t,a]),u=(0,Z.useMemo)(()=>{let e=new Map;for(let t=0;t<c.length;t++){let n=c[t];if(n&&n.type===`removed`){let r=c[t+1];r&&r.type===`added`&&(e.set(t,r),e.set(t+1,n))}}return e},[c]);if(c.length===0)return(0,X.jsxs)(Q,{flexDirection:`column`,...i,children:[(0,X.jsx)(Q,{borderStyle:`singleDouble`,width:`100%`,borderTop:!1,borderLeft:!1,borderRight:!1,borderBottom:!0}),(0,X.jsx)($,{dimColor:!0,children:`No changes detected`}),(0,X.jsx)(Q,{borderStyle:`singleDouble`,width:`100%`,borderTop:!1,borderLeft:!1,borderRight:!1,borderBottom:!0})]});let d=Math.max(l,...c.filter(e=>e.type!==`separator`).map(e=>e.originalLineNumber||e.newLineNumber||0)).toString().length;return(0,X.jsxs)(Q,{flexDirection:`column`,...i,children:[s&&(0,X.jsx)(Q,{marginBottom:0,children:(0,X.jsx)($,{dimColor:!0,children:`Processing diff...`})}),(0,X.jsx)(Q,{flexDirection:`column`,children:c.map((e,t)=>{let n=u.get(t);if(e.type===`separator`)return(0,X.jsx)(Mq,{line:e,lineNumber:` `.repeat(d),dimmed:r},`sep-${t}`);let i=e.originalLineNumber||e.newLineNumber||``;return(0,X.jsx)(Mq,{line:e,pairedLine:n,lineNumber:String(i).padStart(d,` `),dimmed:r},t)})})]})});Pq.displayName=`DiffPreview`;const Fq=tc({targetFile:J(),codeEdit:J(),overwriteFile:qK,instructions:J().optional(),startLine:ic([Is(),J(),Gs(),Us()]).optional().transform(e=>{if(e==null)return;let t=Number(e);return isNaN(t)?void 0:t}),endLine:ic([Is(),J(),Gs(),Us()]).optional().transform(e=>{if(e==null)return;let t=Number(e);return isNaN(t)?void 0:t}),explanation:J().optional()});function Iq({rawInput:e,status:t,parsedResult:n,toolDisplayData:r}){let[i,a]=(0,Z.useState)(!1),o=n!=null&&(t===`success`||n.phase===`skipped`),{isFocused:s}=cI({id:`edit-tool-${e?.targetFile||e?.target_file||`unknown`}`,isActive:o});sI((e,t)=>{s&&t.ctrl&&e===`o`&&a(e=>!e)},{isActive:s&&o});let c=Fq.safeParse(VK(e));if(!c.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Edit`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let l=c.data,u=n?.data.targetFile??l.targetFile,d=!n&&(t===`executing`||t===`pending`),f=jK(u),p=r?.isPlanFile??!1,m=n?.data.isNewFile??r?.isNewFile??!1,h=m?`Create`:`Update`;if(p&&t===`success`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:`success`}),(0,X.jsx)(FK,{children:`Updated plan`})]});if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`){let e=r?.originalContent??``,t=r?.newContent??``,i=n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`});return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:`rejected`}),!p&&e&&t&&(0,X.jsx)(IK,{children:(0,X.jsx)(Pq,{filePath:u,originalContent:e,newContent:t,dimmed:!0})}),i]})}if(d)return(0,X.jsx)(PK,{name:h,params:f,status:`pending`,showSpinner:!0});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:h,params:f,status:`pending`})});let g=n.phase===`skipped`,_=n.summary??`Updated`,v=r?.originalContent,y=r?.finalContent??r?.newContent;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:g?`rejected`:`success`}),(0,X.jsx)(FK,{color:g?`yellow`:void 0,children:_}),!g&&v!==void 0&&y!==void 0&&(0,X.jsx)(IK,{children:m?(0,X.jsx)(zK,{filePath:u,content:y,maxLines:i?100:15}):(0,X.jsx)(Pq,{filePath:u,originalContent:v,newContent:y})})]})}const Lq={displayName:`Edit`,getHeaderParams(e){try{return jK(e?.targetFile||e?.target_file||`[unknown]`)}catch{return`[unknown]`}},renderUI(e,t,n,r){return(0,X.jsx)(Iq,{rawInput:e,status:t,parsedResult:n,toolDisplayData:r})}},Rq=tc({relativeWorkspacePath:J().optional(),explanation:J().optional()}),zq={displayName:`ListDir`,getHeaderParams(e){try{return jK(e?.relativeWorkspacePath||e?.relative_workspace_path||`.`)}catch{return`[unknown]`}},renderUI(e,t,n){let r=Rq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`LS`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=jK(r.data.relativeWorkspacePath||`.`);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`List`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error listing directory`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`LS`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`LS`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`LS`,params:i,status:`pending`})})}},Bq=tc({targetFile:J(),startLineOneIndexed:GK,endLineOneIndexed:GK,startLine:GK,endLine:GK,shouldReadEntireFile:qK,explanation:J().optional()}),Vq={displayName:`Read`,getHeaderParams(e){try{let t=e,n=jK(t.targetFile||e.target_file||`[unknown]`),r=t.startLineOneIndexed||e.start_line_one_indexed||e.startLine||e.start_line,i=t.endLineOneIndexed||e.end_line_one_indexed||e.endLine||e.end_line;return r!==void 0&&i!==void 0?`${n}:${r}-${i}`:n}catch{return`[unknown]`}},renderUI(e,t,n){let r=Bq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,{targetFile:a,startLineOneIndexed:o,endLineOneIndexed:s}=i;if(!a||typeof a!=`string`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:`[invalid file path]`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error: Invalid file path parameter`})]});let c=!n&&(t===`executing`||t===`pending`),l=jK(a),u=o??i.startLine,d=s??i.endLine,f=l;if(u!==void 0&&d!==void 0&&(f=`${l}:${u}-${d}`),c)return(0,X.jsx)(PK,{name:`Read`,params:f,status:`pending`,showSpinner:!0});if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:f,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error reading file`})]});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Read`,params:f,status:`pending`})});let p=n.data.content??``,m=n.data.startLine??u??1,h=n.data.lineCount??p.split(`
12638
- `).length;return(0,X.jsx)(Hq,{displayParams:f,content:p,filePath:a,startLine:m,lineCount:h})}};function Hq({displayParams:e,content:t,filePath:n,startLine:r,lineCount:i}){let[a,o]=(0,Z.useState)(!1),s=t.split(`
12639
- `).length,c=a?100:4,l=s>4,{isFocused:u}=cI({id:`read-file-${n}`,isActive:l});return sI((e,t)=>{u&&t.ctrl&&e===`o`&&o(e=>!e)},{isActive:u&&l}),(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:e,status:`success`}),(0,X.jsxs)(FK,{children:[`Read `,i,` lines`]}),(0,X.jsx)(IK,{children:(0,X.jsx)(zK,{content:t,filePath:n,startLine:r,maxLines:c})})]})}const Uq=tc({targetFile:J(),explanation:J().optional()}),Wq={displayName:`Upload`,getHeaderParams(e){try{return jK(e?.targetFile||e?.target_file||`[unknown]`)}catch{return`[unknown]`}},renderUI(e,t,n){let r=Uq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Upload`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let{targetFile:i}=r.data,a=jK(i);return!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`Upload`,params:a,status:`pending`,showSpinner:!0}):n?n.phase===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Upload`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:n.errorMessage??`Error executing tool`})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Upload`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Upload`,params:a,status:`pending`})})}},Gq=tc({uri:J().optional()}),Kq={displayName:`GetDiagnostics`,getHeaderParams(e){let t=e?.uri;return t?`for ${t}`:`for all files`},renderUI(e,t,n){let r=Gq.safeParse(VK(e)),i=r.success?r.data.uri:void 0,a=i?`for ${i}`:`for all files`;return!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`pending`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error getting diagnostics`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`pending`})})}};function qq(e){return e[0]??{}}function Jq(e){return Array.isArray(e)?e:e==null?[]:[e]}function Yq(e){return typeof e.bytes==`function`?e.bytes():e.arrayBuffer()}const Xq=`orpc`;var Zq=class extends Error{constructor(...e){super(...e),this.name=`AbortError`}};function Qq(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}function $q(){return globalThis[`__@orpc/shared@1.13.6/otel/config__`]}function eJ(e,t={},n){return($q()?.tracer)?.startSpan(e,t,n)}function tJ(e,t,n={}){if(!e)return;let r=nJ(t);e.recordException(r),(!n.signal?.aborted||n.signal.reason!==t)&&e.setStatus({code:2,message:r.message})}function nJ(e){if(e instanceof Error){let t={message:e.message,name:e.name,stack:e.stack};return`code`in e&&(typeof e.code==`string`||typeof e.code==`number`)&&(t.code=e.code),t}return{message:String(e)}}async function rJ({name:e,context:t,...n},r){let i=$q()?.tracer;if(!i)return r();let a=async e=>{try{return await r(e)}catch(t){throw tJ(e,t,n),t}finally{e.end()}};return t?i.startActiveSpan(e,n,t,a):i.startActiveSpan(e,n,a)}async function iJ(e,t){let n=$q();if(!e||!n)return t();let r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}var aJ=class{openIds=new Set;queues=new Map;waiters=new Map;get length(){return this.openIds.size}get waiterIds(){return Array.from(this.waiters.keys())}hasBufferedItems(e){return!!this.queues.get(e)?.length}open(e){this.openIds.add(e)}isOpen(e){return this.openIds.has(e)}push(e,t){this.assertOpen(e);let n=this.waiters.get(e);if(n?.length)n.shift()[0](t),n.length===0&&this.waiters.delete(e);else{let n=this.queues.get(e);n?n.push(t):this.queues.set(e,[t])}}async pull(e){this.assertOpen(e);let t=this.queues.get(e);if(t?.length){let n=t.shift();return t.length===0&&this.queues.delete(e),n}return new Promise((t,n)=>{let r=this.waiters.get(e),i=[t,n];r?r.push(i):this.waiters.set(e,[i])})}close({id:e,reason:t}={}){if(e===void 0){this.waiters.forEach((e,n)=>{let r=t??new Zq(`[AsyncIdQueue] Queue[${n}] was closed or aborted while waiting for pulling.`);e.forEach(([,e])=>e(r))}),this.waiters.clear(),this.openIds.clear(),this.queues.clear();return}let n=t??new Zq(`[AsyncIdQueue] Queue[${e}] was closed or aborted while waiting for pulling.`);this.waiters.get(e)?.forEach(([,e])=>e(n)),this.waiters.delete(e),this.openIds.delete(e),this.queues.delete(e)}assertOpen(e){if(!this.isOpen(e))throw Error(`[AsyncIdQueue] Cannot access queue[${e}] because it is not open or aborted.`)}};function oJ(e){return!e||typeof e!=`object`?!1:`next`in e&&typeof e.next==`function`&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==`function`}const sJ=Symbol.for(`asyncDispose`),cJ=Symbol.asyncDispose??sJ;var lJ=class{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=Qq(async()=>{if(this.#e)return{done:!0,value:void 0};try{let t=await e();return t.done&&(this.#e=!0),t}catch(e){throw this.#e=!0,e}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n(`next`))}})}next(){return this.#r()}async return(e){return this.#e=!0,this.#t||(this.#t=!0,await this.#n(`return`)),{done:!0,value:e}}async throw(e){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n(`throw`)),e}async[cJ](){this.#e=!0,this.#t||(this.#t=!0,await this.#n(`dispose`))}[Symbol.asyncIterator](){return this}};function uJ({name:e,...t},n){let r;return new lJ(async()=>{r??=eJ(e);try{let e=await iJ(r,()=>n.next());return r?.addEvent(e.done?`completed`:`yielded`),e}catch(e){throw tJ(r,e,t),e}},async e=>{try{e!==`next`&&await iJ(r,()=>n.return?.())}catch(e){throw tJ(r,e,t),e}finally{r?.end()}})}var dJ=class{index=BigInt(1);generate(){let e=this.index.toString(36);return this.index++,e}};function fJ(e,t,n){let r=(t,i)=>{let a=e[i];return a?a({...t,next:(e=t)=>r(e,i+1)}):n(t)};return r(t,0)}function pJ(e){if(e)return JSON.parse(e)}function mJ(e){return JSON.stringify(e)}function hJ(e){return _J(e)?Object.getPrototypeOf(e)?.constructor:null}function gJ(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function _J(e){return!!e&&(typeof e==`object`||typeof e==`function`)}function vJ(e){if(Array.isArray(e))return e.map(vJ);if(gJ(e)){let t={};for(let n in e)t[n]=vJ(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=vJ(e[n]);return t}return e}const yJ=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function bJ(e,...t){return typeof e==`function`?e(...t):e}function xJ(e){return new Proxy(e,{get(e,t,n){let r=Reflect.get(e,t,n);return t!==`then`||typeof r!=`function`?r:new Proxy(r,{apply(t,n,r){if(r.length!==2||r.some(e=>!CJ(e)))return Reflect.apply(t,n,r);let i=!0;r[0].call(n,xJ(new Proxy(e,{get:(e,t,n)=>{if(i&&t===`then`){i=!1;return}return Reflect.get(e,t,n)}})))}})}})}const SJ=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function CJ(e){return typeof e==`function`&&SJ.test(e.toString())}function wJ(e,t){return new Proxy(typeof e==`function`?t:e,{get(n,r){let i=r in t?t:bJ(e),a=Reflect.get(i,r);return typeof a==`function`?a.bind(i):a},has(n,r){return Reflect.has(t,r)||Reflect.has(bJ(e),r)}})}function TJ(e){try{return decodeURIComponent(e)}catch{return e}}const EJ={BAD_REQUEST:{status:400,message:`Bad Request`},UNAUTHORIZED:{status:401,message:`Unauthorized`},FORBIDDEN:{status:403,message:`Forbidden`},NOT_FOUND:{status:404,message:`Not Found`},METHOD_NOT_SUPPORTED:{status:405,message:`Method Not Supported`},NOT_ACCEPTABLE:{status:406,message:`Not Acceptable`},TIMEOUT:{status:408,message:`Request Timeout`},CONFLICT:{status:409,message:`Conflict`},PRECONDITION_FAILED:{status:412,message:`Precondition Failed`},PAYLOAD_TOO_LARGE:{status:413,message:`Payload Too Large`},UNSUPPORTED_MEDIA_TYPE:{status:415,message:`Unsupported Media Type`},UNPROCESSABLE_CONTENT:{status:422,message:`Unprocessable Content`},TOO_MANY_REQUESTS:{status:429,message:`Too Many Requests`},CLIENT_CLOSED_REQUEST:{status:499,message:`Client Closed Request`},INTERNAL_SERVER_ERROR:{status:500,message:`Internal Server Error`},NOT_IMPLEMENTED:{status:501,message:`Not Implemented`},BAD_GATEWAY:{status:502,message:`Bad Gateway`},SERVICE_UNAVAILABLE:{status:503,message:`Service Unavailable`},GATEWAY_TIMEOUT:{status:504,message:`Gateway Timeout`}};function DJ(e,t){return t??EJ[e]?.status??500}function OJ(e,t){return t||EJ[e]?.message||e}const kJ=Symbol.for(`__@orpc/client@1.13.6/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[kJ]??=new WeakSet;const AJ=globalThis[kJ];var jJ=class extends Error{defined;code;status;data;constructor(e,...t){let n=qq(t);if(n.status!==void 0&&!NJ(n.status))throw Error(`[ORPCError] Invalid error status code.`);let r=OJ(e,n.message);super(r,n),this.code=e,this.status=DJ(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(AJ.has(this)){let t=hJ(e);if(t&&AJ.has(t))return!0}return super[Symbol.hasInstance](e)}};AJ.add(jJ);function MJ(e){return e instanceof jJ?e:new jJ(`INTERNAL_SERVER_ERROR`,{message:`Internal server error`,cause:e})}function NJ(e){return e<200||e>=400}function PJ(e){if(!gJ(e))return!1;let t=[`defined`,`code`,`status`,`message`,`data`];return Object.keys(e).some(e=>!t.includes(e))?!1:`defined`in e&&typeof e.defined==`boolean`&&`code`in e&&typeof e.code==`string`&&`status`in e&&typeof e.status==`number`&&NJ(e.status)&&`message`in e&&typeof e.message==`string`}function FJ(e,t={}){return new jJ(e.code,{...t,...e})}var IJ=class extends TypeError{},LJ=class extends Error{data;constructor(e){super(e?.message??`An error event was received`,e),this.data=e?.data}};function RJ(e){if(e.includes(`
12640
- `))throw new IJ(`Event's id must not contain a newline character`)}function zJ(e){if(!Number.isInteger(e)||e<0)throw new IJ(`Event's retry must be a integer and >= 0`)}function BJ(e){if(e.includes(`
12641
- `))throw new IJ(`Event's comment must not contain a newline character`)}const VJ=Symbol(`ORPC_EVENT_SOURCE_META`);function HJ(e,t){if(t.id===void 0&&t.retry===void 0&&!t.comments?.length)return e;if(t.id!==void 0&&RJ(t.id),t.retry!==void 0&&zJ(t.retry),t.comments!==void 0)for(let e of t.comments)BJ(e);return new Proxy(e,{get(e,n,r){return n===VJ?t:Reflect.get(e,n,r)}})}function UJ(e){return _J(e)?Reflect.get(e,VJ):void 0}var WJ=class extends lJ{hibernationCallback;constructor(e){super(async()=>{throw Error(`Cannot iterate over hibernating iterator directly`)},async e=>{if(e!==`next`)throw Error(`Cannot cleanup hibernating iterator directly`)}),this.hibernationCallback=e}};function GJ(e){return`inline; filename="${e.replace(/"/g,`\\"`)}"; filename*=utf-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}`}function KJ(e){let t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&typeof t[2]==`string`)return TJ(t[2]);let n=e.match(/filename="((?:\\"|[^"])*)"/i);if(n&&typeof n[1]==`string`)return n[1].replace(/\\"/g,`"`)}function qJ(e,t){let n={...e};for(let e in t)Array.isArray(t[e])?n[e]=[...Jq(n[e]),...t[e]]:t[e]!==void 0&&(Array.isArray(n[e])?n[e]=[...n[e],t[e]]:n[e]===void 0?n[e]=t[e]:n[e]=[n[e],t[e]]);return n}function JJ(e){if(typeof e==`string`||e===void 0)return e;if(e.length!==0)return e.join(`, `)}function YJ(e){return!!(JJ(e[`content-type`])?.startsWith(`text/event-stream`)&&JJ(e[`content-disposition`])===void 0)}function XJ(e,t){let n=async e=>{let n=await t.error(e);if(n!==e){let t=UJ(e);t&&_J(n)&&(n=HJ(n,t))}return n};return new lJ(async()=>{let{done:r,value:i}=await(async()=>{try{return await e.next()}catch(e){throw await n(e)}})(),a=await t.value(i,r);if(a!==i){let e=UJ(i);e&&_J(a)&&(a=HJ(a,e))}return{done:r,value:a}},async()=>{try{await e.return?.()}catch(e){throw await n(e)}})}function ZJ(e){return{...e,context:e.context??{}}}function QJ(e,t={}){let n=t.path??[];return xJ(new Proxy(async(...[t,r={}])=>await e.call(n,t,ZJ(r)),{get(r,i){return typeof i==`string`?QJ(e,{...t,path:[...n,i]}):Reflect.get(r,i)}}))}var $J=class extends Error{issues;data;constructor(e){super(e.message,e),this.issues=e.issues,this.data=e.data}};function eY(e,t){return{...e,...t}}async function tY(e,t){let{code:n,status:r,message:i,data:a,cause:o,defined:s}=t,c=e?.[t.code];if(!c||DJ(t.code,c.status)!==t.status)return s?new jJ(n,{defined:!1,status:r,message:i,data:a,cause:o}):t;if(!c.data)return s?t:new jJ(n,{defined:!0,status:r,message:i,data:a,cause:o});let l=await c.data[`~standard`].validate(t.data);return l.issues?s?new jJ(n,{defined:!1,status:r,message:i,data:a,cause:o}):t:new jJ(n,{defined:!0,status:r,message:i,data:l.value,cause:o})}var nY=class{"~orpc";constructor(e){if(e.route?.successStatus&&NJ(e.route.successStatus))throw Error(`[ContractProcedure] Invalid successStatus.`);if(Object.values(e.errorMap).some(e=>e&&e.status&&!NJ(e.status)))throw Error(`[ContractProcedure] Invalid error status code.`);this[`~orpc`]=e}};function rY(e){return e instanceof nY?!0:(typeof e==`object`||typeof e==`function`)&&e!==null&&`~orpc`in e&&typeof e[`~orpc`]==`object`&&e[`~orpc`]!==null&&`errorMap`in e[`~orpc`]&&`route`in e[`~orpc`]&&`meta`in e[`~orpc`]}function iY(e,t={}){return e.forEach((e,n)=>{Array.isArray(t[n])?t[n].push(e):t[n]===void 0?t[n]=e:t[n]=[t[n],e]}),t}var aY=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e){for(let t of this.plugins)t.init?.(e)}},oY=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new aY(n.plugins).init(n),this.interceptors=Jq(n.interceptors),this.clientInterceptors=Jq(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return rJ({name:`${Xq}.${e.join(`/`)}`,signal:n.signal},r=>(r?.setAttribute(`rpc.system`,Xq),r?.setAttribute(`rpc.method`,e.join(`.`)),oJ(t)&&(t=uJ({name:`consume_event_iterator_input`,signal:n.signal},t)),fJ(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{let i=$q(),a,o=i?.trace.getActiveSpan()??r;o&&i&&(a=i?.trace.setSpan(i.context.active(),o));let s=await rJ({name:`encode_request`,context:a},()=>this.codec.encode(e,t,n)),c=await fJ(this.clientInterceptors,{...n,input:t,path:e,request:s},({input:e,path:t,request:n,...r})=>rJ({name:`send_request`,signal:r.signal,context:a},()=>this.sender.call(n,r,t,e))),l=await rJ({name:`decode_response`,context:a},()=>this.codec.decode(c,n,e,t));return oJ(l)?uJ({name:`consume_event_iterator_output`,signal:n.signal},l):l})))}};const sY={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7};var cY=class{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map(e=>e.type)).size)throw Error(`Custom serializer type must be unique.`)}serialize(e,t=[],n=[],r=[],i=[]){for(let a of this.customSerializers)if(a.condition(e)){let o=this.serialize(a.serialize(e),t,n,r,i);return n.push([a.type,...t]),o}if(e instanceof Blob)return r.push(t),i.push(e),[e,n,r,i];if(typeof e==`bigint`)return n.push([sY.BIGINT,...t]),[e.toString(),n,r,i];if(e instanceof Date)return n.push([sY.DATE,...t]),Number.isNaN(e.getTime())?[null,n,r,i]:[e.toISOString(),n,r,i];if(Number.isNaN(e))return n.push([sY.NAN,...t]),[null,n,r,i];if(e instanceof URL)return n.push([sY.URL,...t]),[e.toString(),n,r,i];if(e instanceof RegExp)return n.push([sY.REGEXP,...t]),[e.toString(),n,r,i];if(e instanceof Set){let a=this.serialize(Array.from(e),t,n,r,i);return n.push([sY.SET,...t]),a}if(e instanceof Map){let a=this.serialize(Array.from(e.entries()),t,n,r,i);return n.push([sY.MAP,...t]),a}if(Array.isArray(e))return[e.map((e,a)=>e===void 0?(n.push([sY.UNDEFINED,...t,a]),e):this.serialize(e,[...t,a],n,r,i)[0]),n,r,i];if(gJ(e)){let a={};for(let o in e)o===`toJSON`&&typeof e[o]==`function`||(a[o]=this.serialize(e[o],[...t,o],n,r,i)[0]);return[a,n,r,i]}return[e,n,r,i]}deserialize(e,t,n,r){let i={data:e};n&&r&&n.forEach((e,t)=>{let n=i,a=`data`;e.forEach(e=>{if(n=n[a],a=e,!Object.hasOwn(n,a))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${a}`)}),n[a]=r(t)});for(let e of t){let t=e[0],n=i,r=`data`;for(let t=1;t<e.length;t++)if(n=n[r],r=e[t],!Object.hasOwn(n,r))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${r}`);for(let e of this.customSerializers)if(e.type===t){n[r]=e.deserialize(n[r]);break}switch(t){case sY.BIGINT:n[r]=BigInt(n[r]);break;case sY.DATE:n[r]=new Date(n[r]??`Invalid Date`);break;case sY.NAN:n[r]=NaN;break;case sY.UNDEFINED:n[r]=void 0;break;case sY.URL:n[r]=new URL(n[r]);break;case sY.REGEXP:{let[,e,t]=n[r].match(/^\/(.*)\/([a-z]*)$/);n[r]=new RegExp(e,t);break}case sY.SET:n[r]=new Set(n[r]);break;case sY.MAP:n[r]=new Map(n[r]);break}}return i.data}};function lY(e){return`/${e.map(encodeURIComponent).join(`/`)}`}function uY(e){return typeof e.forEach==`function`?iY(e):e}function dY(e){return Object.entries(EJ).find(([,t])=>t.status===e)?.[0]??`MALFORMED_ORPC_ERROR_RESPONSE`}var fY=class{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??`POST`,this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=uY(await bJ(this.headers,n,e,t));n.lastEventId!==void 0&&(r=qJ(r,{"last-event-id":n.lastEventId}));let i=await bJ(this.expectedMethod,n,e,t),a=await bJ(this.baseUrl,n,e,t),o=new URL(a);o.pathname=`${o.pathname.replace(/\/$/,``)}${lY(e)}`;let s=this.serializer.serialize(t);if(i===`GET`&&!(s instanceof FormData)&&!oJ(s)){let a=await bJ(this.maxUrlLength,n,e,t),c=new URL(o);if(c.searchParams.append(`data`,mJ(s)),c.toString().length<=a)return{body:void 0,method:i,headers:r,url:c,signal:n.signal}}return{url:o,method:i===`GET`?this.fallbackMethod:i,headers:r,body:s,signal:n.signal}}async decode(e){let t=!NJ(e.status),n=await(async()=>{let t=!1;try{let n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(e){throw t?Error(`Invalid RPC response format.`,{cause:e}):Error(`Cannot parse response body, please check the response body and content-type.`,{cause:e})}})();if(!t)throw PJ(n)?FJ(n):new jJ(dY(e.status),{status:e.status,data:{...e,body:n}});return n}},pY=class{constructor(e){this.jsonSerializer=e}serialize(e){return oJ(e)?XJ(e,{value:async e=>this.#e(e,!1),error:async e=>new LJ({data:this.#e(MJ(e).toJSON(),!1),cause:e})}):this.#e(e,!0)}#e(e,t){let[n,r,i,a]=this.jsonSerializer.serialize(e),o=r.length===0?void 0:r;if(!t||a.length===0)return{json:n,meta:o};let s=new FormData;return s.set(`data`,mJ({json:n,meta:o,maps:i})),a.forEach((e,t)=>{s.set(t.toString(),e)}),s}deserialize(e){return oJ(e)?XJ(e,{value:async e=>this.#t(e),error:async e=>{if(!(e instanceof LJ))return e;let t=this.#t(e.data);return PJ(t)?FJ(t,{cause:e}):new LJ({data:t,cause:e})}}):this.#t(e)}#t(e){if(e===void 0)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);let t=JSON.parse(e.get(`data`));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,t=>e.get(t.toString()))}},mY=class extends oY{constructor(e,t){let n=new fY(new pY(new cY(t)),t);super(n,e,t)}};function hY(e,t){return{...e,...t}}function gY(e,t){return{...e,...t}}function _Y(e,t){return e.path?{...e,path:`${t}${e.path}`}:e}function vY(e,t){return{...e,tags:[...t,...e.tags??[]]}}function yY(e,t){return e?`${e}${t}`:t}function bY(e,t){return e?[...e,...t]:t}function xY(e,t){let n=e;return t.prefix&&(n=_Y(n,t.prefix)),t.tags?.length&&(n=vY(n,t.tags)),n}function SY(e,t){let n=e;for(let e=0;e<t.length;e++){let r=t[e];if(!n||rY(n))return;n=n[r]}return n}function CY(e,t){if(rY(e))return new nY({...e[`~orpc`],errorMap:eY(t.errorMap,e[`~orpc`].errorMap),route:xY(e[`~orpc`].route,t)});let n={};for(let r in e)n[r]=CY(e[r],t);return n}const wY=new class e extends nY{constructor(e){super(e),this[`~orpc`].prefix=e.prefix,this[`~orpc`].tags=e.tags}$meta(t){return new e({...this[`~orpc`],meta:t})}$route(t){return new e({...this[`~orpc`],route:t})}$input(t){return new e({...this[`~orpc`],inputSchema:t})}errors(t){return new e({...this[`~orpc`],errorMap:eY(this[`~orpc`].errorMap,t)})}meta(t){return new e({...this[`~orpc`],meta:hY(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:gY(this[`~orpc`].route,t)})}input(t){return new e({...this[`~orpc`],inputSchema:t})}output(t){return new e({...this[`~orpc`],outputSchema:t})}prefix(t){return new e({...this[`~orpc`],prefix:yY(this[`~orpc`].prefix,t)})}tag(...t){return new e({...this[`~orpc`],tags:bY(this[`~orpc`].tags,t)})}router(e){return CY(e,this[`~orpc`])}}({errorMap:{},route:{},meta:{}}),TY={editorStateChanged:wY.input(tc({file:J().nullable(),startLine:Is().optional(),endLine:Is().optional()})).output(tc({ok:Bs()})),toolDecision:wY.input(tc({toolId:J(),decision:mc([`accept`,`reject`,`allowAlways`])})).output(tc({ok:Bs()}))};function EY(e){return{...e,context:e.context??{}}}function DY(e,t){return async n=>{let{response:r}=await e.handle({...n,body:()=>Promise.resolve(n.body)},EY(t));return r??{status:404,headers:{},body:`No procedure matched`}}}const OY=/^http:\/\/orpc\//;var kY=(e=>(e[e.REQUEST=1]=`REQUEST`,e[e.RESPONSE=2]=`RESPONSE`,e[e.EVENT_ITERATOR=3]=`EVENT_ITERATOR`,e[e.ABORT_SIGNAL=4]=`ABORT_SIGNAL`,e))(kY||{});function AY(e,t,n){if(t===3){let r=n;return{i:e,t,p:{e:r.event,d:r.data,m:r.meta}}}if(t===4)return{i:e,t,p:n};let r=n;return{i:e,p:{u:r.url.toString().replace(OY,`/`),b:r.body,h:Object.keys(r.headers).length>0?r.headers:void 0,m:r.method===`POST`?void 0:r.method}}}function jY(e){let t=e.i,n=e.t??1;if(n===3){let r=e.p;return[t,n,{event:r.e,data:r.d,meta:r.m}]}if(n===4)return[t,n,e.p];let r=e.p;return[t,1,{url:r.u.startsWith(`/`)?new URL(`http://orpc${r.u}`):new URL(r.u),headers:r.h??{},method:r.m??`POST`,body:r.b}]}function MY(e,t,n){if(t===3){let r=n;return{i:e,t,p:{e:r.event,d:r.data,m:r.meta}}}if(t===4)return{i:e,t,p:void 0};let r=n;return{i:e,p:{s:r.status===200?void 0:r.status,h:Object.keys(r.headers).length>0?r.headers:void 0,b:r.body}}}function NY(e){let t=e.i,n=e.t;if(n===3){let r=e.p;return[t,n,{event:r.e,data:r.d,meta:r.m}]}if(n===4)return[t,n,e.p];let r=e.p;return[t,2,{status:r.s??200,headers:r.h??{},body:r.b}]}async function PY(e,t,n){if(t===3||t===4)return BY(AY(e,t,n));let r=n,{body:i,headers:a}=await RY(r.body,r.headers),o=AY(e,1,{...r,body:i instanceof Blob?void 0:i,headers:a});return i instanceof Blob?BY(o,i):BY(o)}async function FY(e){let{json:t,buffer:n}=await VY(e),[r,i,a]=jY(t);if(i===3||i===4)return[r,i,a];let o=a,s=await zY(o.headers,o.body,n);return[r,i,{...o,body:s}]}async function IY(e,t,n){if(t===3||t===4)return BY(MY(e,t,n));let r=n,{body:i,headers:a}=await RY(r.body,r.headers),o=MY(e,2,{...r,body:i instanceof Blob?void 0:i,headers:a});return i instanceof Blob?BY(o,i):BY(o)}async function LY(e){let{json:t,buffer:n}=await VY(e),[r,i,a]=NY(t);if(i===3||i===4)return[r,i,a];let o=a,s=await zY(o.headers,o.body,n);return[r,i,{...o,body:s}]}async function RY(e,t){let n={...t},r=n[`content-disposition`];if(delete n[`content-type`],delete n[`content-disposition`],e instanceof Blob)return n[`content-type`]=e.type,n[`content-disposition`]=r??GJ(e instanceof File?e.name:`blob`),{body:e,headers:n};if(e instanceof FormData){let t=new Response(e);return n[`content-type`]=t.headers.get(`content-type`),{body:await t.blob(),headers:n}}return e instanceof URLSearchParams?(n[`content-type`]=`application/x-www-form-urlencoded`,{body:e.toString(),headers:n}):oJ(e)?(n[`content-type`]=`text/event-stream`,{body:void 0,headers:n}):{body:e,headers:n}}async function zY(e,t,n){let r=JJ(e[`content-type`]),i=JJ(e[`content-disposition`]);if(typeof i==`string`){let e=KJ(i)??`blob`;return new File(n===void 0?[]:[n],e,{type:r})}return r?.startsWith(`multipart/form-data`)?new Response(n,{headers:{"content-type":r}}).formData():r?.startsWith(`application/x-www-form-urlencoded`)&&typeof t==`string`?new URLSearchParams(t):t}async function BY(e,t){let n=mJ(e);return t===void 0||t.size===0?n:Yq(new Blob([new TextEncoder().encode(n),new Uint8Array([255]),t]))}async function VY(e){if(typeof e==`string`)return{json:JSON.parse(e)};let t=e instanceof Uint8Array?e:new Uint8Array(e),n=t.indexOf(255);if(n===-1){let e=new TextDecoder().decode(t);return{json:JSON.parse(e)}}let r=new TextDecoder().decode(t.subarray(0,n)),i=t.subarray(n+1);return{json:JSON.parse(r),buffer:i}}function HY(e,t,n,r={}){let i;return new lJ(async()=>{i??=eJ(`consume_event_iterator_stream`);try{let n=await iJ(i,()=>e.pull(t));switch(n.event){case`message`:{let e=n.data;return n.meta&&_J(e)&&(e=HJ(e,n.meta)),i?.addEvent(`message`),{value:e,done:!1}}case`error`:{let e=new LJ({data:n.data});throw n.meta&&(e=HJ(e,n.meta)),i?.addEvent(`error`),e}case`done`:{let e=n.data;return n.meta&&_J(e)&&(e=HJ(e,n.meta)),i?.addEvent(`done`),{value:e,done:!0}}}}catch(e){throw e instanceof LJ||tJ(i,e,r),e}},async e=>{try{e!==`next`&&i?.addEvent(`cancelled`),await iJ(i,()=>n(e))}catch(e){throw tJ(i,e,r),e}finally{i?.end()}})}function UY(e,t){return rJ({name:`stream_event_iterator`},async n=>{for(;;){let r=await(async()=>{try{let{value:t,done:r}=await e.next();return r?(n?.addEvent(`done`),{event:`done`,data:t,meta:UJ(t)}):(n?.addEvent(`message`),{event:`message`,data:t,meta:UJ(t)})}catch(e){if(e instanceof LJ)return n?.addEvent(`error`),{event:`error`,data:e.data,meta:UJ(e)};try{await t({event:`error`,data:void 0})}catch(t){throw tJ(n,e),t}throw e}})(),i=!1;try{let n=await t(r);if(r.event===`done`||r.event===`error`)return;if(n===`abort`){i=!0,await e.return?.();return}}catch(t){if(!i)try{await e.return?.()}catch(e){throw tJ(n,t),e}throw t}}})}var WY=class{peer;constructor(e){this.peer=new GY(async([t,n,r])=>{await e(await PY(t,n,r))})}get length(){return this.peer.length}open(e){return this.peer.open(e)}async request(e){return this.peer.request(e)}async message(e){return this.peer.message(await LY(e))}close(e={}){return this.peer.close(e)}},GY=class{idGenerator=new dJ;responseQueue=new aJ;serverEventIteratorQueue=new aJ;serverControllers=new Map;cleanupFns=new Map;send;constructor(e){this.send=async t=>{let n=t[0];this.serverControllers.has(n)&&await e(t)}}get length(){return(+this.responseQueue.length+this.serverEventIteratorQueue.length+this.serverControllers.size+this.cleanupFns.size)/4}open(e){this.serverEventIteratorQueue.open(e),this.responseQueue.open(e);let t=new AbortController;return this.serverControllers.set(e,t),this.cleanupFns.set(e,[]),t}async request(e){let t=e.signal;return rJ({name:`send_peer_request`,signal:t},async()=>{if(t?.aborted)throw t.reason;let n=this.idGenerator.generate(),r=this.open(n);try{let i=$q();if(i){let t=vJ(e.headers);i.propagation.inject(i.context.active(),t),e={...e,headers:t}}if(await this.send([n,kY.REQUEST,e]),t?.aborted)throw await this.send([n,kY.ABORT_SIGNAL,void 0]),t.reason;let a;if(t?.addEventListener(`abort`,a=async()=>{await this.send([n,kY.ABORT_SIGNAL,void 0]),this.close({id:n,reason:t.reason})},{once:!0}),this.cleanupFns.get(n)?.push(()=>{t?.removeEventListener(`abort`,a)}),oJ(e.body)){let t=e.body;UY(t,async e=>r.signal.aborted?`abort`:(await this.send([n,kY.EVENT_ITERATOR,e]),`next`))}let o=await this.responseQueue.pull(n);if(YJ(o.headers)){let e=HY(this.serverEventIteratorQueue,n,async e=>{try{e!==`next`&&await this.send([n,kY.ABORT_SIGNAL,void 0])}finally{this.close({id:n})}},{signal:t});return{...o,body:e}}return this.close({id:n}),o}catch(e){throw this.close({id:n,reason:e}),e}})}async message([e,t,n]){if(t===kY.ABORT_SIGNAL){this.serverControllers.get(e)?.abort();return}if(t===kY.EVENT_ITERATOR){this.serverEventIteratorQueue.isOpen(e)&&this.serverEventIteratorQueue.push(e,n);return}this.responseQueue.isOpen(e)&&this.responseQueue.push(e,n)}close(e={}){e.id===void 0?(this.serverControllers.forEach(t=>t.abort(e.reason)),this.serverControllers.clear(),this.cleanupFns.forEach(e=>e.forEach(e=>e())),this.cleanupFns.clear()):(this.serverControllers.get(e.id)?.abort(e.reason),this.serverControllers.delete(e.id),this.cleanupFns.get(e.id)?.forEach(e=>e()),this.cleanupFns.delete(e.id)),this.responseQueue.close(e),this.serverEventIteratorQueue.close(e)}},KY=class{peer;constructor(e){this.peer=new qY(async([t,n,r])=>{await e(await IY(t,n,r))})}get length(){return this.peer.length}open(e){return this.peer.open(e)}async message(e,t){return this.peer.message(await FY(e),t)}async response(e,t){return this.peer.response(e,t)}close({abort:e=!0,...t}={}){return this.peer.close({...t,abort:e})}},qY=class{clientEventIteratorQueue=new aJ;clientControllers=new Map;send;constructor(e){this.send=async t=>{let n=t[0];this.clientControllers.has(n)&&await e(t)}}get length(){return(this.clientEventIteratorQueue.length+this.clientControllers.size)/2}open(e){this.clientEventIteratorQueue.open(e);let t=new AbortController;return this.clientControllers.set(e,t),t}async message([e,t,n],r){if(t===kY.ABORT_SIGNAL)return this.close({id:e,reason:new Zq(`Client aborted the request`)}),[e,void 0];if(t===kY.EVENT_ITERATOR)return this.clientEventIteratorQueue.isOpen(e)&&this.clientEventIteratorQueue.push(e,n),[e,void 0];let i=this.open(e).signal,a={...n,signal:i,body:YJ(n.headers)?HY(this.clientEventIteratorQueue,e,async t=>{t!==`next`&&await this.send([e,kY.ABORT_SIGNAL,void 0])},{signal:i}):n.body};if(r){let t,n=$q();n&&(t=n.propagation.extract(n.context.active(),a.headers)),await rJ({name:`receive_peer_request`,context:t},async()=>{let t=await rJ({name:`handle_request`},async()=>{try{return await r(a)}catch(t){throw this.close({id:e,reason:t,abort:!1}),t}});await rJ({name:`send_peer_response`},()=>this.response(e,t))})}return[e,a]}async response(e,t){let n=this.clientControllers.get(e)?.signal;if(!(!n||n.aborted))try{if(await this.send([e,kY.RESPONSE,t]),!n.aborted&&oJ(t.body))if(t.body instanceof WJ)t.body.hibernationCallback?.(e);else{let r=t.body;await UY(r,async t=>n.aborted?`abort`:(await this.send([e,kY.EVENT_ITERATOR,t]),`next`))}this.close({id:e,abort:!1})}catch(t){throw this.close({id:e,reason:t,abort:!1}),t}}close({abort:e=!0,...t}={}){t.id===void 0?(e&&this.clientControllers.forEach(e=>e.abort(t.reason)),this.clientControllers.clear()):(e&&this.clientControllers.get(t.id)?.abort(t.reason),this.clientControllers.delete(t.id)),this.clientEventIteratorQueue.close(t)}};function JY(e){let t;if(typeof e==`string`)t=e;else{let n=e instanceof Uint8Array?e:new Uint8Array(e);t=Buffer.from(n).toString(`utf8`)}return Buffer.from(t+`
12642
- `,`utf8`)}function YY(e){let t=[],n=0;for(let r=0;r<e.length;r++)if(e[r]===10){let i=e.subarray(n,r).toString(`utf8`).trim();i&&t.push(i),n=r+1}return[t,e.subarray(n)]}function XY(e,t){let n=DY(t,{});try{f.existsSync(e)&&f.unlinkSync(e)}catch{}let r=N.createServer(e=>{let t=new KY(t=>{e.write(JY(t))}),r=Buffer.alloc(0);e.on(`data`,async e=>{r=Buffer.concat([r,e]);let[i,a]=YY(r);r=a;for(let e of i)await t.message(e,n)}),e.on(`close`,()=>{t.close()}),e.on(`error`,()=>{t.close()})});return new Promise((t,n)=>{r.on(`error`,n),r.listen(e,()=>{try{f.chmodSync(e,438)}catch{}t({getSocketPath:()=>e,dispose:()=>{r.close();try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}})})})}var ZY=class{peer;constructor(e){this.peer=e}async call(e){let t=await this.peer.request(e);return{...t,body:()=>Promise.resolve(t.body)}}},QY=class extends mY{constructor(e){super(new ZY(e),{url:`orpc:/`})}};function $Y(e,t){let n=t?.timeoutMs??2e3;return new Promise((t,r)=>{let i=N.connect(e),a=setTimeout(()=>{i.destroy(),r(Error(`Connection to ${e} timed out after ${n}ms`))},n);i.on(`connect`,()=>{clearTimeout(a);let e=new WY(e=>{i.write(JY(e))}),n=Buffer.alloc(0);i.on(`data`,async t=>{n=Buffer.concat([n,t]);let[r,i]=YY(n);n=i;for(let t of r)await e.message(t)}),i.on(`close`,()=>e.close()),i.on(`error`,()=>e.close()),t({link:new QY(e),dispose:()=>{e.close(),i.destroy()}})}),i.on(`error`,e=>{clearTimeout(a),r(e)})})}const eX=Symbol(`ORPC_LAZY_SYMBOL`);function tX(e,t={}){return{[eX]:{loader:e,meta:t}}}function nX(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&eX in e}function rX(e){return e[eX].meta}function iX(e){return nX(e)?e[eX].loader():Promise.resolve({default:e})}function aX(e,t){if(t.length>e.length)return!1;for(let n=0;n<e.length;n++){if(t[n]===void 0)return!0;if(e[n]!==t[n])return!1}return!0}function oX(e,t,n){return n.dedupeLeading&&aX(t,e)?t:[...e,...t]}function sX(e,t){return[...e,t]}var cX=class{"~orpc";constructor(e){this[`~orpc`]=e}};function lX(e){return e instanceof cX?!0:rY(e)&&`middlewares`in e[`~orpc`]&&`inputValidationIndex`in e[`~orpc`]&&`outputValidationIndex`in e[`~orpc`]&&`handler`in e[`~orpc`]}function uX(e,t){return{...e,...t}}function dX(e){return new Proxy(e,{get(t,n){return typeof n==`string`?(...t)=>{let r=qq(t),i=e[n];return new jJ(n,{defined:!!i,status:i?.status,message:r.message??i?.message,data:r.data,cause:r.cause})}:Reflect.get(t,n)}})}function fX(e){return{output:e,context:{}}}function pX(e,...t){let n=qq(t);return async(...[t,r])=>{let i=Jq(n.path),{default:a}=await iX(e),o=r?.context??{},s=await bJ(n.context??{},o),c=dX(a[`~orpc`].errorMap),l=async e=>e instanceof jJ?await tY(a[`~orpc`].errorMap,e):e;try{let e=await rJ({name:`call_procedure`,signal:r?.signal},e=>(e?.setAttribute(`procedure.path`,[...i]),fJ(Jq(n.interceptors),{context:s,input:t,errors:c,path:i,procedure:a,signal:r?.signal,lastEventId:r?.lastEventId},e=>gX(e.procedure,e))));return oJ(e)?e instanceof WJ?e:wJ(e,XJ(uJ({name:`consume_event_iterator_output`,signal:r?.signal},e),{value:e=>e,error:e=>l(e)})):e}catch(e){throw await l(e)}}}async function mX(e,t){let n=e[`~orpc`].inputSchema;return n?rJ({name:`validate_input`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new jJ(`BAD_REQUEST`,{message:`Input validation failed`,data:{issues:e.issues},cause:new $J({message:`Input validation failed`,issues:e.issues,data:t})});return e.value}):t}async function hX(e,t){let n=e[`~orpc`].outputSchema;return n?rJ({name:`validate_output`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new jJ(`INTERNAL_SERVER_ERROR`,{message:`Output validation failed`,cause:new $J({message:`Output validation failed`,issues:e.issues,data:t})});return e.value}):t}async function gX(e,t){let n=e[`~orpc`].middlewares,r=Math.min(Math.max(0,e[`~orpc`].inputValidationIndex),n.length),i=Math.min(Math.max(0,e[`~orpc`].outputValidationIndex),n.length),a=async(o,s,c)=>{let l=c;o===r&&(l=await mX(e,l));let u=n[o],d=u?await rJ({name:`middleware.${u.name}`,signal:t.signal},async e=>(e?.setAttribute(`middleware.index`,o),e?.setAttribute(`middleware.name`,u.name),(await u({...t,context:s,next:async(...[e])=>{let t=e?.context??{};return{output:await a(o+1,uX(s,t),l),context:t}}},l,fX)).output)):await rJ({name:`handler`,signal:t.signal},()=>e[`~orpc`].handler({...t,context:s,input:l}));return o===i?await hX(e,d):d};return a(0,t.context,t.input)}const _X=Symbol(`ORPC_HIDDEN_ROUTER_CONTRACT`);function vX(e,t){return new Proxy(e,{get(e,n){return n===_X?t:Reflect.get(e,n)}})}function yX(e){return e[_X]}function bX(e,t){let n=e;for(let e=0;e<t.length;e++){let r=t[e];if(!n||lX(n))return;if(!nX(n)){n=n[r];continue}let i=n,a=t.slice(e);return tX(async()=>iX(bX((await iX(i)).default,a)),rX(i))}return n}function xX(e){return new Proxy(e,{get(t,n){return typeof n==`string`?xX(bX(e,[n])):Reflect.get(t,n)}})}function SX(e,t){if(nX(e)){let n=rX(e),r=n?.prefix?yY(t.prefix,n?.prefix):t.prefix;return xX(tX(async()=>{let{default:n}=await iX(e);return iX(SX(n,t))},{...n,prefix:r}))}if(lX(e)){let n=oX(t.middlewares,e[`~orpc`].middlewares,{dedupeLeading:t.dedupeLeadingMiddlewares}),r=n.length-e[`~orpc`].middlewares.length;return new cX({...e[`~orpc`],route:xY(e[`~orpc`].route,t),errorMap:eY(t.errorMap,e[`~orpc`].errorMap),middlewares:n,inputValidationIndex:e[`~orpc`].inputValidationIndex+r,outputValidationIndex:e[`~orpc`].outputValidationIndex+r})}let n={};for(let r in e)n[r]=SX(e[r],t);return n}function CX(e,t,n=[]){let r=e.router,i=yX(e.router);if(i!==void 0&&(r=i),nX(r))n.push({router:r,path:e.path});else if(rY(r))t({contract:r,path:e.path});else for(let i in r)CX({router:r[i],path:[...e.path,i]},t,n);return n}function wX(e,t){return new cX({...e[`~orpc`],errorMap:t[`~orpc`].errorMap,route:t[`~orpc`].route,meta:t[`~orpc`].meta})}const TX={initialInputValidationIndex:0,initialOutputValidationIndex:0,dedupeLeadingMiddlewares:!0};function EX(e,t){return t===void 0?TX[e]:t}function DX(e){let t=((...t)=>e(...t));return t.mapInput=t=>DX((n,r,...i)=>e(n,t(r),...i)),t.concat=(t,n)=>{let r=n?DX(t).mapInput(n):t;return DX((t,n,i,...a)=>e({...t,next:(...[e])=>r({...t,context:{...t.context,...e?.context},next:(...[n])=>t.next({context:{...e?.context,...n?.context}})},n,i,...a)},n,i,...a))},t}function OX(e){return async t=>{try{return[null,await e(t)]}catch(e){if(e instanceof Error&&`digest`in e&&typeof e.digest==`string`&&e.digest.startsWith(`NEXT_`)||e instanceof Response&&`options`in e&&gJ(e.options)||gJ(e)&&e.isNotFound===!0)throw e;return[MJ(e).toJSON(),void 0]}}}var kX=class e extends cX{errors(t){return new e({...this[`~orpc`],errorMap:eY(this[`~orpc`].errorMap,t)})}meta(t){return new e({...this[`~orpc`],meta:hY(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:gY(this[`~orpc`].route,t)})}use(t,n){let r=n?DX(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:sX(this[`~orpc`].middlewares,r)})}callable(...e){let t=pX(this,...e);return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}actionable(...e){let t=OX(pX(this,...e));return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}},AX=class e{"~orpc";constructor(e){this[`~orpc`]=e}$config(t){let n=this[`~orpc`].inputValidationIndex-EX(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),r=this[`~orpc`].outputValidationIndex-EX(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex);return new e({...this[`~orpc`],config:t,dedupeLeadingMiddlewares:EX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares),inputValidationIndex:EX(`initialInputValidationIndex`,t.initialInputValidationIndex)+n,outputValidationIndex:EX(`initialOutputValidationIndex`,t.initialOutputValidationIndex)+r})}$context(){return new e({...this[`~orpc`],middlewares:[],inputValidationIndex:EX(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),outputValidationIndex:EX(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)})}$meta(t){return new e({...this[`~orpc`],meta:t})}$route(t){return new e({...this[`~orpc`],route:t})}$input(t){return new e({...this[`~orpc`],inputSchema:t})}middleware(e){return DX(e)}errors(t){return new e({...this[`~orpc`],errorMap:eY(this[`~orpc`].errorMap,t)})}use(t,n){let r=n?DX(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:sX(this[`~orpc`].middlewares,r)})}meta(t){return new e({...this[`~orpc`],meta:hY(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:gY(this[`~orpc`].route,t)})}input(t){return new e({...this[`~orpc`],inputSchema:t,inputValidationIndex:EX(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex)+this[`~orpc`].middlewares.length})}output(t){return new e({...this[`~orpc`],outputSchema:t,outputValidationIndex:EX(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)+this[`~orpc`].middlewares.length})}handler(e){return new kX({...this[`~orpc`],handler:e})}prefix(t){return new e({...this[`~orpc`],prefix:yY(this[`~orpc`].prefix,t)})}tag(...t){return new e({...this[`~orpc`],tags:bY(this[`~orpc`].tags,t)})}router(e){return SX(e,this[`~orpc`])}lazy(e){return SX(tX(e),this[`~orpc`])}};new AX({config:{},route:{},meta:{},errorMap:{},inputValidationIndex:EX(`initialInputValidationIndex`),outputValidationIndex:EX(`initialOutputValidationIndex`),middlewares:[],dedupeLeadingMiddlewares:!0});function jX(e,t,n){return rY(e)?new AX({...e[`~orpc`],config:t,middlewares:n,inputValidationIndex:EX(`initialInputValidationIndex`,t?.initialInputValidationIndex)+n.length,outputValidationIndex:EX(`initialOutputValidationIndex`,t?.initialOutputValidationIndex)+n.length,dedupeLeadingMiddlewares:EX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}):new Proxy(e,{get:(r,i)=>{if(typeof i!=`string`)return Reflect.get(r,i);let a;i===`middleware`?a=e=>DX(e):i===`use`?a=r=>jX(e,t,sX(n,r)):i===`router`?a=r=>vX(SX(r,{middlewares:n,errorMap:{},prefix:void 0,tags:void 0,dedupeLeadingMiddlewares:EX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}),e):i===`lazy`&&(a=r=>vX(SX(tX(r),{middlewares:n,errorMap:{},prefix:void 0,tags:void 0,dedupeLeadingMiddlewares:EX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}),e));let o=SY(r,[i]);if(!o)return a??o;let s=jX(o,t,n);return a?new Proxy(a,{get(e,t){return Reflect.get(s,t)}}):s}})}function MX(e,t={}){let n=jX(e,t,[]),r=new Proxy(n,{get:(t,n)=>{let i;n===`$context`?i=()=>r:n===`$config`&&(i=t=>MX(e,t));let a=Reflect.get(t,n);return!i||!a||typeof a!=`function`&&typeof a!=`object`?i||a:new Proxy(i,{get(e,t){return Reflect.get(a,t)}})}});return r}var NX=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e,t){for(let n of this.plugins)n.init?.(e,t)}},PX=class{constructor(e,t,n,r){this.matcher=t,this.codec=n,new NX(r.plugins).init(r,e),this.interceptors=Jq(r.interceptors),this.clientInterceptors=Jq(r.clientInterceptors),this.rootInterceptors=Jq(r.rootInterceptors),this.matcher.init(e)}interceptors;clientInterceptors;rootInterceptors;async handle(e,t){let n=t.prefix?.replace(/\/$/,``)||void 0;return n&&!e.url.pathname.startsWith(`${n}/`)&&e.url.pathname!==n?{matched:!1,response:void 0}:fJ(this.rootInterceptors,{...t,request:e,prefix:n},async t=>rJ({name:`${e.method} ${e.url.pathname}`},async e=>{let n;try{return await fJ(this.interceptors,t,async({request:t,context:r,prefix:i})=>{let a=t.method,o=t.url,s=i?o.pathname.replace(i,``):o.pathname,c=await rJ({name:`find_procedure`},()=>this.matcher.match(a,`/${s.replace(/^\/|\/$/g,``)}`));if(!c)return{matched:!1,response:void 0};e?.updateName(`${Xq}.${c.path.join(`/`)}`),e?.setAttribute(`rpc.system`,Xq),e?.setAttribute(`rpc.method`,c.path.join(`.`)),n=`decode_input`;let l=await rJ({name:`decode_input`},()=>this.codec.decode(t,c.params,c.procedure));n=void 0,oJ(l)&&(l=uJ({name:`consume_event_iterator_input`,signal:t.signal},l));let u=pX(c.procedure,{context:r,path:c.path,interceptors:this.clientInterceptors});n=`call_procedure`;let d=await u(l,{signal:t.signal,lastEventId:JJ(t.headers[`last-event-id`])});return n=void 0,{matched:!0,response:this.codec.encode(d,c.procedure)}})}catch(t){n!==`call_procedure`&&tJ(e,t);let r=n===`decode_input`&&!(t instanceof jJ)?new jJ(`BAD_REQUEST`,{message:`Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,cause:t}):MJ(t);return{matched:!0,response:this.codec.encodeError(r)}}}))}},FX=class{constructor(e){this.serializer=e}async decode(e,t,n){let r=e.method===`GET`?pJ(e.url.searchParams.getAll(`data`).at(-1)):await e.body();return this.serializer.deserialize(r)}encode(e,t){return{status:200,headers:{},body:this.serializer.serialize(e)}}encodeError(e){return{status:e.status,headers:{},body:this.serializer.serialize(e.toJSON())}}},IX=class{filter;tree=new yJ;pendingRouters=[];constructor(e={}){this.filter=e.filter??!0}init(e,t=[]){let n=CX({router:e,path:t},t=>{if(!bJ(this.filter,t))return;let{path:n,contract:r}=t,i=lY(n);lX(r)?this.tree[i]={path:n,contract:r,procedure:r,router:e}:this.tree[i]={path:n,contract:r,procedure:void 0,router:e}});this.pendingRouters.push(...n.map(e=>({...e,httpPathPrefix:lY(e.path)})))}async match(e,t){if(this.pendingRouters.length){let e=[];for(let n of this.pendingRouters)if(t.startsWith(n.httpPathPrefix)){let{default:e}=await iX(n.router);this.init(e,n.path)}else e.push(n);this.pendingRouters=e}let n=this.tree[t];if(n){if(!n.procedure){let{default:e}=await iX(bX(n.router,n.path));if(!lX(e))throw Error(`
12643
- [Contract-First] Missing or invalid implementation for procedure at path: ${lY(n.path)}.
12636
+ `)}function VK(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(e=>VK(e));let t={};for(let[n,r]of Object.entries(e)){let e=n.replace(/_([a-z])/g,(e,t)=>t.toUpperCase());t[e]=VK(r)}return t}function HK(e){if(typeof e!=`string`)return e;let t=e.trim();return t?Number(t):NaN}function UK(e){if(typeof e!=`string`)return e;let t=e.trim().toLowerCase();return[`true`,`1`,`yes`,`y`].includes(t)?!0:[`false`,`0`,`no`,`n`].includes(t)?!1:e}const WK=Vc(HK,Is()),GK=Vc(HK,Is().optional()),KK=Vc(UK,Bs()),qK=Vc(UK,Bs().optional()),JK=tc({questions:$s(tc({question:J(),header:J(),options:$s(tc({label:J(),description:J()})),multiSelect:KK})),answers:fc(J(),J()).optional()}),YK={displayName:`AskUserQuestion`,getHeaderParams(e){return``},renderUI(e,t,n){let r=JK.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.questions||[],o=n?.data.answers??i.answers??{};if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`){let e=Object.keys(o).length>0;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:e?`success`:`rejected`}),(0,X.jsx)(FK,{color:e?`green`:`yellow`,children:e?`User answered ${Object.keys(o).length} question${Object.keys(o).length===1?``:`s`}`:n?.userNote?(0,X.jsxs)(X.Fragment,{children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):`User cancelled the questions`})]})}if(t===`pending`||t===`executing`)return(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`pending`,showSpinner:!0});let s=a.length,c=Object.keys(o).length;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`AskUserQuestion`,status:`success`}),(0,X.jsxs)(FK,{children:[`Answered `,s,` question`,s===1?``:`s`]}),c>0&&(0,X.jsx)(IK,{children:Object.entries(o).map(([e,t],n)=>{let r=parseInt(e.replace(`question_`,``),10),i=a[r];return(0,X.jsxs)(Q,{flexDirection:`column`,marginBottom:1,children:[(0,X.jsx)($,{dimColor:!0,children:i?.header||`Question ${r+1}`}),(0,X.jsxs)($,{color:`cyan`,children:[`→ `,String(t)]})]},n)})})]})}},XK={displayName:`EnterPlanMode`,getHeaderParams(e){return``},renderUI(e,t,n){return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):t===`pending`||t===`executing`?(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`pending`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`EnterPlanMode`,status:`success`}),(0,X.jsx)(FK,{children:`Entered plan mode`})]})}};let ZK=function(e){return e[e.Prompt=0]=`Prompt`,e[e.Help=1]=`Help`,e[e.Bash=2]=`Bash`,e[e.Command=3]=`Command`,e[e.Files=4]=`Files`,e}({});const QK=(0,Z.createContext)(null),$K=()=>{let e=(0,Z.use)(QK);if(!e)throw Error(`${$K.name} must be used within ${nq.name}`);return e},eq=[xl.Normal,xl.AcceptEdits,xl.PlanMode];function tq(e,t){switch(t.type){case`CYCLE`:{if(e.isWaitingForYoloConfirm)return{agentMode:xl.Yolo,isWaitingForYoloConfirm:!1};if(e.agentMode===xl.Yolo)return{agentMode:xl.Normal,isWaitingForYoloConfirm:!1};let t=eq.indexOf(e.agentMode);return t===-1?{agentMode:xl.Normal,isWaitingForYoloConfirm:!1}:t===eq.length-1?{agentMode:e.agentMode,isWaitingForYoloConfirm:!0}:{agentMode:eq[t+1],isWaitingForYoloConfirm:!1}}case`SET`:return{agentMode:t.mode,isWaitingForYoloConfirm:!1};case`RESET`:return{agentMode:xl.Normal,isWaitingForYoloConfirm:!1};case`YOLO_TIMEOUT`:return{...e,isWaitingForYoloConfirm:!1}}}function nq({children:e,initialMode:t}){let[{agentMode:n,isWaitingForYoloConfirm:r},i]=(0,Z.useReducer)(tq,{agentMode:t??xl.Normal,isWaitingForYoloConfirm:!1});(0,Z.useEffect)(()=>{if(!r)return;let e=setTimeout(()=>i({type:`YOLO_TIMEOUT`}),3e3);return()=>clearTimeout(e)},[r]);let a=(0,Z.useMemo)(()=>({agentMode:n,setAgentMode:e=>i({type:`SET`,mode:e}),cycleAgentMode:()=>i({type:`CYCLE`}),isWaitingForYoloConfirm:r,resetToNormal:()=>i({type:`RESET`})}),[n,r]);return(0,X.jsx)(QK.Provider,{value:a,children:e})}const rq=tc({planFilePath:J()});function iq({rawInput:e,status:t,parsedResult:n}){let{agentMode:r}=$K(),i=rq.safeParse(VK(e)),a=(i.success?i.data.planFilePath:e?.planFilePath)||``;if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]});if(t===`pending`||t===`executing`)return(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`pending`,showSpinner:!0});let o=r===xl.AcceptEdits?`Plan approved (auto-accept mode)`:`Plan approved`;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`ExitPlanMode`,status:`success`}),(0,X.jsxs)(FK,{children:[o,`: `,jK(a)]})]})}const aq={displayName:`ExitPlanMode`,getHeaderParams(e){return e?.planFilePath||``},renderUI(e,t,n){return(0,X.jsx)(iq,{rawInput:e,status:t,parsedResult:n})}},oq={displayName:`HandOff`,getHeaderParams(e){return``},renderUI(e,t,n){return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`HandOff`,status:`success`}),(0,X.jsx)(FK,{children:`Handed off to main agent`})]})}},sq=tc({agent:J(),task:J()}),cq={displayName:`Subagent`,getHeaderParams(e){return e?.agent||``},renderUI(e,t,n){let r=sq.safeParse(VK(e)),i=r.success?r.data.agent:e?.agent||``;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Subagent`,params:i,status:`success`}),(0,X.jsxs)(FK,{children:[`Switched to `,i,` agent`]})]})}},lq=tc({todos:Vc(e=>{if(e==null)return[];if(typeof e==`string`)try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}return Array.isArray(e)?e:[]},$s(tc({content:J(),status:mc([`pending`,`in_progress`,`completed`,`cancelled`]),id:J().optional()})))});function uq({rawInput:e,parsedResult:t}){let n=lq.safeParse(VK(e)),r=n.success?n.data.todos:[],i=(0,Z.useCallback)(e=>{switch(e){case`completed`:return`[x]`;case`in_progress`:return`[>]`;default:return`[ ]`}},[]),a=(0,Z.useCallback)(e=>{switch(e){case`completed`:return`green`;case`in_progress`:return`blue`;default:return`gray`}},[]);return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`TodoWrite`,status:`success`}),t?.summary&&(0,X.jsx)(FK,{children:t.summary}),r.length>0&&(0,X.jsx)(IK,{children:r.map((e,t)=>(0,X.jsxs)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:[(0,X.jsx)($,{color:a(e.status),children:i(e.status)}),(0,X.jsx)($,{color:e.status===`completed`?`gray`:void 0,dimColor:e.status===`completed`,children:e.content})]},t))})]})}const dq={displayName:`TodoWrite`,getHeaderParams(e){return``},renderUI(e,t,n){return(0,X.jsx)(uq,{rawInput:e,parsedResult:n})}},fq=tc({id:WK}),pq={displayName:`CloseTab`,getHeaderParams(e){let t=e;return`id: ${String(t.id??``)}`},renderUI(e,t,n){let r=fq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`CloseTab`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.id;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`pending`,showSpinner:!0}):n?t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error closing tab`})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`success`}),(0,X.jsx)(FK,{children:`Closed`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`CloseTab`,params:`id: ${i}`,status:`pending`})})}},mq=tc({action:mc([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:uc([WK,WK]).optional(),startCoordinate:uc([WK,WK]).optional(),duration:GK,text:J().optional(),scrollAmount:GK,scrollDirection:mc([`up`,`down`,`left`,`right`]).optional()}),hq={displayName:`Computer`,getHeaderParams(e){return e?.action||`action`},renderUI(e,t,n){let r=mq.safeParse(VK(e)),i=r.success?r.data.action:e?.action||`action`;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`Computer`,params:i,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Computer`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing computer action`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Computer`,params:i,status:`success`}),(0,X.jsxs)(FK,{children:[`Performed `,i]})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Computer`,params:i,status:`pending`})})}},gq=tc({id:GK}),_q={displayName:`GetElements`,getHeaderParams(e){let t=e;return t.id===void 0?``:`id: ${String(t.id)}`},renderUI(e,t,n){let r=gq.safeParse(VK(e)),i=r.success&&r.data.id!==void 0?`id: ${r.data.id}`:void 0;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error: Failed to get interactive elements`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Found elements`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`GetElements`,params:i,status:`pending`})})}},vq=tc({id:GK}),yq={displayName:`GetContent`,getHeaderParams(e){let t=e;return t.id===void 0?``:`id: ${String(t.id)}`},renderUI(e,t,n){let r=vq.safeParse(VK(e)),i=r.success&&r.data.id!==void 0?`id: ${r.data.id}`:void 0;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error: Failed to get tab content`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Got content`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`GetContent`,params:i,status:`pending`})})}},bq=tc({url:J()}),xq={displayName:`Navigate`,getHeaderParams(e){let t=e?.url||``;return t.length>50?t.substring(0,47)+`...`:t},renderUI(e,t,n){let r=bq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Navigate`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=i.length>50?i.substring(0,47)+`...`:i;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error navigating to URL`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`success`}),(0,X.jsx)(FK,{children:`Navigated`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Navigate`,params:a,status:`pending`})})}},Sq=tc({url:J().optional()}),Cq={displayName:`NewTab`,getHeaderParams(e){let t=e?.url||``;return t.length>40?t.substring(0,37)+`...`:t},renderUI(e,t,n){let r=Sq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`NewTab`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=(i.length>40?i.substring(0,37)+`...`:i)||void 0;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error opening new tab`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Opened tab`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`NewTab`,params:a,status:`pending`})})}},wq=tc({id:J(),action:mc([`click`,`type`,`hover`,`scroll`,`focus`,`select`]),text:J().optional(),scroll_direction:mc([`up`,`down`,`left`,`right`]).optional(),scroll_amount:GK,held_keys:J().optional(),tab_id:GK}),Tq={displayName:`PerformAction`,getHeaderParams(e){return`id: ${(e.id||``).substring(0,20)}`},renderUI(e,t,n){let r=e,i=wq.safeParse(VK(e)),a=i.success?i.data.action:r.action||`action`,o=`id: ${(r.id||``).substring(0,20)}`,s=a.charAt(0).toUpperCase()+a.slice(1);return!n&&t===`executing`?(0,X.jsx)(PK,{name:s,params:o,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:s,params:o,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing action`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:s,params:o,status:`success`}),(0,X.jsxs)(FK,{children:[`Performed `,a]})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:s,params:o,status:`pending`})})}},Eq={displayName:`Refresh`,getHeaderParams(e){return``},renderUI(e,t,n){return!n&&t===`executing`?(0,X.jsx)(PK,{name:`Refresh`,status:`pending`,showSpinner:!0}):n?t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Refresh`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error refreshing tab`})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Refresh`,status:`success`}),(0,X.jsx)(FK,{children:`Refreshed`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Refresh`,status:`pending`})})}},Dq=tc({id:WK}),Oq={displayName:`SwitchTab`,getHeaderParams(e){let t=e;return`id: ${String(t.id??``)}`},renderUI(e,t,n){let r=Dq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`SwitchTab`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.id;return!n&&t===`executing`?(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`executing`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error switching tab`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`success`}),(0,X.jsxs)(FK,{children:[`Switched to tab `,i]})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`SwitchTab`,params:`id: ${i}`,status:`pending`})})}},kq=tc({targetFile:J(),explanation:J().optional()}),Aq={displayName:`Delete`,getHeaderParams(e){try{return jK(e?.targetFile||e?.target_file||`[unknown]`)}catch{return`[unknown]`}},renderUI(e,t,n){let r=kq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let{targetFile:i}=r.data,a=jK(i);return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`rejected`}),(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`rejected`}),(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error deleting file`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`Delete`,params:a,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Delete`,params:a,status:`success`}),(0,X.jsx)(FK,{children:`Deleted`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Delete`,params:a,status:`pending`})})}};function jq(e,t){return SK(e,t)}function Mq(e,t,n){return new Promise(r=>{setImmediate(()=>{let i=BK(e,n),a=BK(t,n),o=EK(n,n,e,t,void 0,void 0,{context:1}),s=[],c=0;for(let e=0;e<o.hunks.length;e++){let t=o.hunks[e];if(!t)continue;let n=t.oldStart;if(e>0&&n>c+1){let e=n-c-1;e>0&&s.push({type:`separator`,content:``,skippedLines:e})}let r=t.oldStart,l=t.newStart;for(let e of t.lines){let t=e[0],n=e.slice(1);t!==`\\`&&(t===`+`?s.push({type:`added`,content:n,highlightedContent:a[l-1],newLineNumber:l++}):t===`-`?s.push({type:`removed`,content:n,highlightedContent:i[r-1],originalLineNumber:r++}):s.push({type:`unchanged`,content:n,highlightedContent:i[r-1],originalLineNumber:r++,newLineNumber:l++}))}c=r-1}let l=e.split(`
12637
+ `).length;r({diffLines:s,totalOriginalLines:l})})})}const Nq=(0,Z.memo)(({line:e,pairedLine:t,lineNumber:n,dimmed:r=!1})=>{let{colors:i}=RL();if(e.type===`separator`)return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsxs)($,{dimColor:!0,children:[n,` `]}),(0,X.jsxs)($,{dimColor:!0,children:[`⋮ `,e.skippedLines,` unchanged lines`]})]});if(e.type===`unchanged`)return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsxs)($,{dimColor:!0,children:[n,` `]}),(0,X.jsx)(Q,{flexShrink:1,children:(0,X.jsx)($,{dimColor:!0,wrap:`wrap`,children:e.highlightedContent??e.content})})]});if(e.type===`removed`){let a=t?.type===`added`?jq(e.content,t.content):null;return(0,X.jsxs)(Q,{flexDirection:`row`,backgroundColor:i.diffRemoved,children:[(0,X.jsxs)($,{backgroundColor:i.diffRemoved,color:i.diffRemovedText,dimColor:r,children:[n,` -`,` `]}),(0,X.jsx)(Q,{flexShrink:1,children:(0,X.jsx)($,{color:i.diffRemovedText,dimColor:r,wrap:`wrap`,children:a?a.map((e,t)=>e.removed?(0,X.jsx)($,{backgroundColor:i.diffRemovedHighlight,dimColor:r,children:e.value},t):e.added?null:(0,X.jsx)($,{backgroundColor:i.diffRemoved,dimColor:r,children:e.value},t)):(0,X.jsx)($,{backgroundColor:i.diffRemoved,dimColor:r,children:e.highlightedContent??e.content})})})]})}if(e.type===`added`){let a=t?.type===`removed`?jq(t.content,e.content):null;return(0,X.jsxs)(Q,{flexDirection:`row`,backgroundColor:i.diffAdded,children:[(0,X.jsxs)($,{backgroundColor:i.diffAdded,color:i.diffAddedText,dimColor:r,children:[n,` +`,` `]}),(0,X.jsx)(Q,{flexShrink:1,children:(0,X.jsx)($,{color:i.diffAddedText,dimColor:r,wrap:`wrap`,children:a?a.map((e,t)=>e.added?(0,X.jsx)($,{backgroundColor:i.diffAddedHighlight,dimColor:r,children:e.value},t):e.removed?null:(0,X.jsx)($,{backgroundColor:i.diffAdded,dimColor:r,children:e.value},t)):(0,X.jsx)($,{backgroundColor:i.diffAdded,dimColor:r,children:e.highlightedContent??e.content})})})]})}return null});Nq.displayName=`DiffLineContent`;const Pq=(0,Z.memo)(({filePath:e,hunks:t})=>{let{colors:n}=RL(),r=t.reduce((e,t)=>e+t.lines.filter(e=>e.startsWith(`+`)).length,0),i=t.reduce((e,t)=>e+t.lines.filter(e=>e.startsWith(`-`)).length,0);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{bold:!0,children:e}),(r>0||i>0)&&(0,X.jsxs)($,{dimColor:!0,children:[r>0&&(0,X.jsxs)($,{color:n.diffAddedText,children:[`+`,r]}),r>0&&i>0&&(0,X.jsx)($,{children:` `}),i>0&&(0,X.jsxs)($,{color:n.diffRemovedText,children:[`-`,i]})]})]})});Pq.displayName=`DiffPreviewTitle`;const Fq=(0,Z.memo)(({filePath:e,originalContent:t,newContent:n,dimmed:r=!1,...i})=>{let[a,o]=(0,Z.useState)(null),s=a===null,c=(0,Z.useRef)(0);(0,Z.useEffect)(()=>{let r=++c.current;o(null);let i=!1;return Mq(t,n,e).then(e=>{!i&&c.current===r&&o(e)}),()=>{i=!0}},[t,n,e]);let l=a?.diffLines??[],u=a?.totalOriginalLines??0,d=(0,Z.useMemo)(()=>{let e=new Map;for(let t=0;t<l.length;t++){let n=l[t];if(n&&n.type===`removed`){let r=l[t+1];r&&r.type===`added`&&(e.set(t,r),e.set(t+1,n))}}return e},[l]);if(s)return(0,X.jsx)(Q,{flexDirection:`column`,...i,children:(0,X.jsx)(Q,{marginBottom:0,children:(0,X.jsx)($,{dimColor:!0,children:`Processing diff...`})})});if(l.length===0)return(0,X.jsxs)(Q,{flexDirection:`column`,...i,children:[(0,X.jsx)(Q,{borderStyle:`singleDouble`,width:`100%`,borderTop:!1,borderLeft:!1,borderRight:!1,borderBottom:!0}),(0,X.jsx)($,{dimColor:!0,children:`No changes detected`}),(0,X.jsx)(Q,{borderStyle:`singleDouble`,width:`100%`,borderTop:!1,borderLeft:!1,borderRight:!1,borderBottom:!0})]});let f=Math.max(u,...l.filter(e=>e.type!==`separator`).map(e=>e.originalLineNumber||e.newLineNumber||0)).toString().length;return(0,X.jsx)(Q,{flexDirection:`column`,...i,children:(0,X.jsx)(Q,{flexDirection:`column`,children:l.map((e,t)=>{let n=d.get(t);if(e.type===`separator`)return(0,X.jsx)(Nq,{line:e,lineNumber:` `.repeat(f),dimmed:r},`sep-${t}`);let i=e.originalLineNumber||e.newLineNumber||``;return(0,X.jsx)(Nq,{line:e,pairedLine:n,lineNumber:String(i).padStart(f,` `),dimmed:r},t)})})})});Fq.displayName=`DiffPreview`;const Iq=tc({targetFile:J(),codeEdit:J(),overwriteFile:qK,instructions:J().optional(),startLine:ic([Is(),J(),Gs(),Us()]).optional().transform(e=>{if(e==null)return;let t=Number(e);return isNaN(t)?void 0:t}),endLine:ic([Is(),J(),Gs(),Us()]).optional().transform(e=>{if(e==null)return;let t=Number(e);return isNaN(t)?void 0:t}),explanation:J().optional()});function Lq({rawInput:e,status:t,parsedResult:n,toolDisplayData:r}){let[i,a]=(0,Z.useState)(!1),o=n!=null&&(t===`success`||n.phase===`skipped`),{isFocused:s}=cI({id:`edit-tool-${e?.targetFile||e?.target_file||`unknown`}`,isActive:o});sI((e,t)=>{s&&t.ctrl&&e===`o`&&a(e=>!e)},{isActive:s&&o});let c=Iq.safeParse(VK(e));if(!c.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Edit`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let l=c.data,u=n?.data.targetFile??l.targetFile,d=!n&&(t===`executing`||t===`pending`),f=jK(u),p=r?.isPlanFile??!1,m=n?.data.isNewFile??r?.isNewFile??!1,h=m?`Create`:`Update`;if(p&&t===`success`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:`success`}),(0,X.jsx)(FK,{children:`Updated plan`})]});if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`){let e=r?.originalContent??``,t=r?.newContent??``,i=n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`});return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:`rejected`}),!p&&e&&t&&(0,X.jsx)(IK,{children:(0,X.jsx)(Fq,{filePath:u,originalContent:e,newContent:t,dimmed:!0})}),i]})}if(d)return(0,X.jsx)(PK,{name:h,params:f,status:`pending`,showSpinner:!0});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:h,params:f,status:`pending`})});let g=n.phase===`skipped`,_=n.summary??`Updated`,v=r?.originalContent,y=r?.finalContent??r?.newContent;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:h,params:f,status:g?`rejected`:`success`}),(0,X.jsx)(FK,{color:g?`yellow`:void 0,children:_}),!g&&v!==void 0&&y!==void 0&&(0,X.jsx)(IK,{children:m?(0,X.jsx)(zK,{filePath:u,content:y,maxLines:i?100:15}):(0,X.jsx)(Fq,{filePath:u,originalContent:v,newContent:y})})]})}const Rq={displayName:`Edit`,getHeaderParams(e){try{return jK(e?.targetFile||e?.target_file||`[unknown]`)}catch{return`[unknown]`}},renderUI(e,t,n,r){return(0,X.jsx)(Lq,{rawInput:e,status:t,parsedResult:n,toolDisplayData:r})}},zq=tc({relativeWorkspacePath:J().optional(),explanation:J().optional()}),Bq={displayName:`ListDir`,getHeaderParams(e){try{return jK(e?.relativeWorkspacePath||e?.relative_workspace_path||`.`)}catch{return`[unknown]`}},renderUI(e,t,n){let r=zq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`LS`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=jK(r.data.relativeWorkspacePath||`.`);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`List`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error listing directory`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`LS`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`LS`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`LS`,params:i,status:`pending`})})}},Vq=tc({targetFile:J(),startLineOneIndexed:GK,endLineOneIndexed:GK,startLine:GK,endLine:GK,shouldReadEntireFile:qK,explanation:J().optional()}),Hq={displayName:`Read`,getHeaderParams(e){try{let t=e,n=jK(t.targetFile||e.target_file||`[unknown]`),r=t.startLineOneIndexed||e.start_line_one_indexed||e.startLine||e.start_line,i=t.endLineOneIndexed||e.end_line_one_indexed||e.endLine||e.end_line;return r!==void 0&&i!==void 0?`${n}:${r}-${i}`:n}catch{return`[unknown]`}},renderUI(e,t,n){let r=Vq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,{targetFile:a,startLineOneIndexed:o,endLineOneIndexed:s}=i;if(!a||typeof a!=`string`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:`[invalid file path]`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error: Invalid file path parameter`})]});let c=!n&&(t===`executing`||t===`pending`),l=jK(a),u=o??i.startLine,d=s??i.endLine,f=l;if(u!==void 0&&d!==void 0&&(f=`${l}:${u}-${d}`),c)return(0,X.jsx)(PK,{name:`Read`,params:f,status:`pending`,showSpinner:!0});if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:f,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error reading file`})]});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Read`,params:f,status:`pending`})});let p=n.data.content??``,m=n.data.startLine??u??1,h=n.data.lineCount??p.split(`
12638
+ `).length;return(0,X.jsx)(Uq,{displayParams:f,content:p,filePath:a,startLine:m,lineCount:h})}};function Uq({displayParams:e,content:t,filePath:n,startLine:r,lineCount:i}){let[a,o]=(0,Z.useState)(!1),s=t.split(`
12639
+ `).length,c=a?100:4,l=s>4,{isFocused:u}=cI({id:`read-file-${n}`,isActive:l});return sI((e,t)=>{u&&t.ctrl&&e===`o`&&o(e=>!e)},{isActive:u&&l}),(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Read`,params:e,status:`success`}),(0,X.jsxs)(FK,{children:[`Read `,i,` lines`]}),(0,X.jsx)(IK,{children:(0,X.jsx)(zK,{content:t,filePath:n,startLine:r,maxLines:c})})]})}const Wq=tc({targetFile:J(),explanation:J().optional()}),Gq={displayName:`Upload`,getHeaderParams(e){try{return jK(e?.targetFile||e?.target_file||`[unknown]`)}catch{return`[unknown]`}},renderUI(e,t,n){let r=Wq.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Upload`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let{targetFile:i}=r.data,a=jK(i);return!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`Upload`,params:a,status:`pending`,showSpinner:!0}):n?n.phase===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Upload`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:n.errorMessage??`Error executing tool`})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Upload`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Upload`,params:a,status:`pending`})})}},Kq=tc({uri:J().optional()}),qq={displayName:`GetDiagnostics`,getHeaderParams(e){let t=e?.uri;return t?`for ${t}`:`for all files`},renderUI(e,t,n){let r=Kq.safeParse(VK(e)),i=r.success?r.data.uri:void 0,a=i?`for ${i}`:`for all files`;return!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`pending`,showSpinner:!0}):t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error getting diagnostics`})]}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`GetDiagnostics`,params:a,status:`pending`})})}};function Jq(e){return e[0]??{}}function Yq(e){return Array.isArray(e)?e:e==null?[]:[e]}function Xq(e){return typeof e.bytes==`function`?e.bytes():e.arrayBuffer()}const Zq=`orpc`;var Qq=class extends Error{constructor(...e){super(...e),this.name=`AbortError`}};function $q(e){let t=Promise.resolve();return(...n)=>t=t.catch(()=>{}).then(()=>e(...n))}function eJ(){return globalThis[`__@orpc/shared@1.13.6/otel/config__`]}function tJ(e,t={},n){return(eJ()?.tracer)?.startSpan(e,t,n)}function nJ(e,t,n={}){if(!e)return;let r=rJ(t);e.recordException(r),(!n.signal?.aborted||n.signal.reason!==t)&&e.setStatus({code:2,message:r.message})}function rJ(e){if(e instanceof Error){let t={message:e.message,name:e.name,stack:e.stack};return`code`in e&&(typeof e.code==`string`||typeof e.code==`number`)&&(t.code=e.code),t}return{message:String(e)}}async function iJ({name:e,context:t,...n},r){let i=eJ()?.tracer;if(!i)return r();let a=async e=>{try{return await r(e)}catch(t){throw nJ(e,t,n),t}finally{e.end()}};return t?i.startActiveSpan(e,n,t,a):i.startActiveSpan(e,n,a)}async function aJ(e,t){let n=eJ();if(!e||!n)return t();let r=n.trace.setSpan(n.context.active(),e);return n.context.with(r,t)}var oJ=class{openIds=new Set;queues=new Map;waiters=new Map;get length(){return this.openIds.size}get waiterIds(){return Array.from(this.waiters.keys())}hasBufferedItems(e){return!!this.queues.get(e)?.length}open(e){this.openIds.add(e)}isOpen(e){return this.openIds.has(e)}push(e,t){this.assertOpen(e);let n=this.waiters.get(e);if(n?.length)n.shift()[0](t),n.length===0&&this.waiters.delete(e);else{let n=this.queues.get(e);n?n.push(t):this.queues.set(e,[t])}}async pull(e){this.assertOpen(e);let t=this.queues.get(e);if(t?.length){let n=t.shift();return t.length===0&&this.queues.delete(e),n}return new Promise((t,n)=>{let r=this.waiters.get(e),i=[t,n];r?r.push(i):this.waiters.set(e,[i])})}close({id:e,reason:t}={}){if(e===void 0){this.waiters.forEach((e,n)=>{let r=t??new Qq(`[AsyncIdQueue] Queue[${n}] was closed or aborted while waiting for pulling.`);e.forEach(([,e])=>e(r))}),this.waiters.clear(),this.openIds.clear(),this.queues.clear();return}let n=t??new Qq(`[AsyncIdQueue] Queue[${e}] was closed or aborted while waiting for pulling.`);this.waiters.get(e)?.forEach(([,e])=>e(n)),this.waiters.delete(e),this.openIds.delete(e),this.queues.delete(e)}assertOpen(e){if(!this.isOpen(e))throw Error(`[AsyncIdQueue] Cannot access queue[${e}] because it is not open or aborted.`)}};function sJ(e){return!e||typeof e!=`object`?!1:`next`in e&&typeof e.next==`function`&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]==`function`}const cJ=Symbol.for(`asyncDispose`),lJ=Symbol.asyncDispose??cJ;var uJ=class{#e=!1;#t=!1;#n;#r;constructor(e,t){this.#n=t,this.#r=$q(async()=>{if(this.#e)return{done:!0,value:void 0};try{let t=await e();return t.done&&(this.#e=!0),t}catch(e){throw this.#e=!0,e}finally{this.#e&&!this.#t&&(this.#t=!0,await this.#n(`next`))}})}next(){return this.#r()}async return(e){return this.#e=!0,this.#t||(this.#t=!0,await this.#n(`return`)),{done:!0,value:e}}async throw(e){throw this.#e=!0,this.#t||(this.#t=!0,await this.#n(`throw`)),e}async[lJ](){this.#e=!0,this.#t||(this.#t=!0,await this.#n(`dispose`))}[Symbol.asyncIterator](){return this}};function dJ({name:e,...t},n){let r;return new uJ(async()=>{r??=tJ(e);try{let e=await aJ(r,()=>n.next());return r?.addEvent(e.done?`completed`:`yielded`),e}catch(e){throw nJ(r,e,t),e}},async e=>{try{e!==`next`&&await aJ(r,()=>n.return?.())}catch(e){throw nJ(r,e,t),e}finally{r?.end()}})}var fJ=class{index=BigInt(1);generate(){let e=this.index.toString(36);return this.index++,e}};function pJ(e,t,n){let r=(t,i)=>{let a=e[i];return a?a({...t,next:(e=t)=>r(e,i+1)}):n(t)};return r(t,0)}function mJ(e){if(e)return JSON.parse(e)}function hJ(e){return JSON.stringify(e)}function gJ(e){return vJ(e)?Object.getPrototypeOf(e)?.constructor:null}function _J(e){if(!e||typeof e!=`object`)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||!t||!t.constructor}function vJ(e){return!!e&&(typeof e==`object`||typeof e==`function`)}function yJ(e){if(Array.isArray(e))return e.map(yJ);if(_J(e)){let t={};for(let n in e)t[n]=yJ(e[n]);for(let n of Object.getOwnPropertySymbols(e))t[n]=yJ(e[n]);return t}return e}const bJ=(()=>{let e=function(){};return e.prototype=Object.create(null),Object.freeze(e.prototype),e})();function xJ(e,...t){return typeof e==`function`?e(...t):e}function SJ(e){return new Proxy(e,{get(e,t,n){let r=Reflect.get(e,t,n);return t!==`then`||typeof r!=`function`?r:new Proxy(r,{apply(t,n,r){if(r.length!==2||r.some(e=>!wJ(e)))return Reflect.apply(t,n,r);let i=!0;r[0].call(n,SJ(new Proxy(e,{get:(e,t,n)=>{if(i&&t===`then`){i=!1;return}return Reflect.get(e,t,n)}})))}})}})}const CJ=/^\s*function\s*\(\)\s*\{\s*\[native code\]\s*\}\s*$/;function wJ(e){return typeof e==`function`&&CJ.test(e.toString())}function TJ(e,t){return new Proxy(typeof e==`function`?t:e,{get(n,r){let i=r in t?t:xJ(e),a=Reflect.get(i,r);return typeof a==`function`?a.bind(i):a},has(n,r){return Reflect.has(t,r)||Reflect.has(xJ(e),r)}})}function EJ(e){try{return decodeURIComponent(e)}catch{return e}}const DJ={BAD_REQUEST:{status:400,message:`Bad Request`},UNAUTHORIZED:{status:401,message:`Unauthorized`},FORBIDDEN:{status:403,message:`Forbidden`},NOT_FOUND:{status:404,message:`Not Found`},METHOD_NOT_SUPPORTED:{status:405,message:`Method Not Supported`},NOT_ACCEPTABLE:{status:406,message:`Not Acceptable`},TIMEOUT:{status:408,message:`Request Timeout`},CONFLICT:{status:409,message:`Conflict`},PRECONDITION_FAILED:{status:412,message:`Precondition Failed`},PAYLOAD_TOO_LARGE:{status:413,message:`Payload Too Large`},UNSUPPORTED_MEDIA_TYPE:{status:415,message:`Unsupported Media Type`},UNPROCESSABLE_CONTENT:{status:422,message:`Unprocessable Content`},TOO_MANY_REQUESTS:{status:429,message:`Too Many Requests`},CLIENT_CLOSED_REQUEST:{status:499,message:`Client Closed Request`},INTERNAL_SERVER_ERROR:{status:500,message:`Internal Server Error`},NOT_IMPLEMENTED:{status:501,message:`Not Implemented`},BAD_GATEWAY:{status:502,message:`Bad Gateway`},SERVICE_UNAVAILABLE:{status:503,message:`Service Unavailable`},GATEWAY_TIMEOUT:{status:504,message:`Gateway Timeout`}};function OJ(e,t){return t??DJ[e]?.status??500}function kJ(e,t){return t||DJ[e]?.message||e}const AJ=Symbol.for(`__@orpc/client@1.13.6/error/ORPC_ERROR_CONSTRUCTORS__`);globalThis[AJ]??=new WeakSet;const jJ=globalThis[AJ];var MJ=class extends Error{defined;code;status;data;constructor(e,...t){let n=Jq(t);if(n.status!==void 0&&!PJ(n.status))throw Error(`[ORPCError] Invalid error status code.`);let r=kJ(e,n.message);super(r,n),this.code=e,this.status=OJ(e,n.status),this.defined=n.defined??!1,this.data=n.data}toJSON(){return{defined:this.defined,code:this.code,status:this.status,message:this.message,data:this.data}}static[Symbol.hasInstance](e){if(jJ.has(this)){let t=gJ(e);if(t&&jJ.has(t))return!0}return super[Symbol.hasInstance](e)}};jJ.add(MJ);function NJ(e){return e instanceof MJ?e:new MJ(`INTERNAL_SERVER_ERROR`,{message:`Internal server error`,cause:e})}function PJ(e){return e<200||e>=400}function FJ(e){if(!_J(e))return!1;let t=[`defined`,`code`,`status`,`message`,`data`];return Object.keys(e).some(e=>!t.includes(e))?!1:`defined`in e&&typeof e.defined==`boolean`&&`code`in e&&typeof e.code==`string`&&`status`in e&&typeof e.status==`number`&&PJ(e.status)&&`message`in e&&typeof e.message==`string`}function IJ(e,t={}){return new MJ(e.code,{...t,...e})}var LJ=class extends TypeError{},RJ=class extends Error{data;constructor(e){super(e?.message??`An error event was received`,e),this.data=e?.data}};function zJ(e){if(e.includes(`
12640
+ `))throw new LJ(`Event's id must not contain a newline character`)}function BJ(e){if(!Number.isInteger(e)||e<0)throw new LJ(`Event's retry must be a integer and >= 0`)}function VJ(e){if(e.includes(`
12641
+ `))throw new LJ(`Event's comment must not contain a newline character`)}const HJ=Symbol(`ORPC_EVENT_SOURCE_META`);function UJ(e,t){if(t.id===void 0&&t.retry===void 0&&!t.comments?.length)return e;if(t.id!==void 0&&zJ(t.id),t.retry!==void 0&&BJ(t.retry),t.comments!==void 0)for(let e of t.comments)VJ(e);return new Proxy(e,{get(e,n,r){return n===HJ?t:Reflect.get(e,n,r)}})}function WJ(e){return vJ(e)?Reflect.get(e,HJ):void 0}var GJ=class extends uJ{hibernationCallback;constructor(e){super(async()=>{throw Error(`Cannot iterate over hibernating iterator directly`)},async e=>{if(e!==`next`)throw Error(`Cannot cleanup hibernating iterator directly`)}),this.hibernationCallback=e}};function KJ(e){return`inline; filename="${e.replace(/"/g,`\\"`)}"; filename*=utf-8''${encodeURIComponent(e).replace(/['()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`).replace(/%(7C|60|5E)/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)))}`}function qJ(e){let t=e.match(/filename\*=(UTF-8'')?([^;]*)/i);if(t&&typeof t[2]==`string`)return EJ(t[2]);let n=e.match(/filename="((?:\\"|[^"])*)"/i);if(n&&typeof n[1]==`string`)return n[1].replace(/\\"/g,`"`)}function JJ(e,t){let n={...e};for(let e in t)Array.isArray(t[e])?n[e]=[...Yq(n[e]),...t[e]]:t[e]!==void 0&&(Array.isArray(n[e])?n[e]=[...n[e],t[e]]:n[e]===void 0?n[e]=t[e]:n[e]=[n[e],t[e]]);return n}function YJ(e){if(typeof e==`string`||e===void 0)return e;if(e.length!==0)return e.join(`, `)}function XJ(e){return!!(YJ(e[`content-type`])?.startsWith(`text/event-stream`)&&YJ(e[`content-disposition`])===void 0)}function ZJ(e,t){let n=async e=>{let n=await t.error(e);if(n!==e){let t=WJ(e);t&&vJ(n)&&(n=UJ(n,t))}return n};return new uJ(async()=>{let{done:r,value:i}=await(async()=>{try{return await e.next()}catch(e){throw await n(e)}})(),a=await t.value(i,r);if(a!==i){let e=WJ(i);e&&vJ(a)&&(a=UJ(a,e))}return{done:r,value:a}},async()=>{try{await e.return?.()}catch(e){throw await n(e)}})}function QJ(e){return{...e,context:e.context??{}}}function $J(e,t={}){let n=t.path??[];return SJ(new Proxy(async(...[t,r={}])=>await e.call(n,t,QJ(r)),{get(r,i){return typeof i==`string`?$J(e,{...t,path:[...n,i]}):Reflect.get(r,i)}}))}var eY=class extends Error{issues;data;constructor(e){super(e.message,e),this.issues=e.issues,this.data=e.data}};function tY(e,t){return{...e,...t}}async function nY(e,t){let{code:n,status:r,message:i,data:a,cause:o,defined:s}=t,c=e?.[t.code];if(!c||OJ(t.code,c.status)!==t.status)return s?new MJ(n,{defined:!1,status:r,message:i,data:a,cause:o}):t;if(!c.data)return s?t:new MJ(n,{defined:!0,status:r,message:i,data:a,cause:o});let l=await c.data[`~standard`].validate(t.data);return l.issues?s?new MJ(n,{defined:!1,status:r,message:i,data:a,cause:o}):t:new MJ(n,{defined:!0,status:r,message:i,data:l.value,cause:o})}var rY=class{"~orpc";constructor(e){if(e.route?.successStatus&&PJ(e.route.successStatus))throw Error(`[ContractProcedure] Invalid successStatus.`);if(Object.values(e.errorMap).some(e=>e&&e.status&&!PJ(e.status)))throw Error(`[ContractProcedure] Invalid error status code.`);this[`~orpc`]=e}};function iY(e){return e instanceof rY?!0:(typeof e==`object`||typeof e==`function`)&&e!==null&&`~orpc`in e&&typeof e[`~orpc`]==`object`&&e[`~orpc`]!==null&&`errorMap`in e[`~orpc`]&&`route`in e[`~orpc`]&&`meta`in e[`~orpc`]}function aY(e,t={}){return e.forEach((e,n)=>{Array.isArray(t[n])?t[n].push(e):t[n]===void 0?t[n]=e:t[n]=[t[n],e]}),t}var oY=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e){for(let t of this.plugins)t.init?.(e)}},sY=class{constructor(e,t,n={}){this.codec=e,this.sender=t,new oY(n.plugins).init(n),this.interceptors=Yq(n.interceptors),this.clientInterceptors=Yq(n.clientInterceptors)}interceptors;clientInterceptors;call(e,t,n){return iJ({name:`${Zq}.${e.join(`/`)}`,signal:n.signal},r=>(r?.setAttribute(`rpc.system`,Zq),r?.setAttribute(`rpc.method`,e.join(`.`)),sJ(t)&&(t=dJ({name:`consume_event_iterator_input`,signal:n.signal},t)),pJ(this.interceptors,{...n,path:e,input:t},async({path:e,input:t,...n})=>{let i=eJ(),a,o=i?.trace.getActiveSpan()??r;o&&i&&(a=i?.trace.setSpan(i.context.active(),o));let s=await iJ({name:`encode_request`,context:a},()=>this.codec.encode(e,t,n)),c=await pJ(this.clientInterceptors,{...n,input:t,path:e,request:s},({input:e,path:t,request:n,...r})=>iJ({name:`send_request`,signal:r.signal,context:a},()=>this.sender.call(n,r,t,e))),l=await iJ({name:`decode_response`,context:a},()=>this.codec.decode(c,n,e,t));return sJ(l)?dJ({name:`consume_event_iterator_output`,signal:n.signal},l):l})))}};const cY={BIGINT:0,DATE:1,NAN:2,UNDEFINED:3,URL:4,REGEXP:5,SET:6,MAP:7};var lY=class{customSerializers;constructor(e={}){if(this.customSerializers=e.customJsonSerializers??[],this.customSerializers.length!==new Set(this.customSerializers.map(e=>e.type)).size)throw Error(`Custom serializer type must be unique.`)}serialize(e,t=[],n=[],r=[],i=[]){for(let a of this.customSerializers)if(a.condition(e)){let o=this.serialize(a.serialize(e),t,n,r,i);return n.push([a.type,...t]),o}if(e instanceof Blob)return r.push(t),i.push(e),[e,n,r,i];if(typeof e==`bigint`)return n.push([cY.BIGINT,...t]),[e.toString(),n,r,i];if(e instanceof Date)return n.push([cY.DATE,...t]),Number.isNaN(e.getTime())?[null,n,r,i]:[e.toISOString(),n,r,i];if(Number.isNaN(e))return n.push([cY.NAN,...t]),[null,n,r,i];if(e instanceof URL)return n.push([cY.URL,...t]),[e.toString(),n,r,i];if(e instanceof RegExp)return n.push([cY.REGEXP,...t]),[e.toString(),n,r,i];if(e instanceof Set){let a=this.serialize(Array.from(e),t,n,r,i);return n.push([cY.SET,...t]),a}if(e instanceof Map){let a=this.serialize(Array.from(e.entries()),t,n,r,i);return n.push([cY.MAP,...t]),a}if(Array.isArray(e))return[e.map((e,a)=>e===void 0?(n.push([cY.UNDEFINED,...t,a]),e):this.serialize(e,[...t,a],n,r,i)[0]),n,r,i];if(_J(e)){let a={};for(let o in e)o===`toJSON`&&typeof e[o]==`function`||(a[o]=this.serialize(e[o],[...t,o],n,r,i)[0]);return[a,n,r,i]}return[e,n,r,i]}deserialize(e,t,n,r){let i={data:e};n&&r&&n.forEach((e,t)=>{let n=i,a=`data`;e.forEach(e=>{if(n=n[a],a=e,!Object.hasOwn(n,a))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${a}`)}),n[a]=r(t)});for(let e of t){let t=e[0],n=i,r=`data`;for(let t=1;t<e.length;t++)if(n=n[r],r=e[t],!Object.hasOwn(n,r))throw Error(`Security error: accessing non-existent path during deserialization. Path segment: ${r}`);for(let e of this.customSerializers)if(e.type===t){n[r]=e.deserialize(n[r]);break}switch(t){case cY.BIGINT:n[r]=BigInt(n[r]);break;case cY.DATE:n[r]=new Date(n[r]??`Invalid Date`);break;case cY.NAN:n[r]=NaN;break;case cY.UNDEFINED:n[r]=void 0;break;case cY.URL:n[r]=new URL(n[r]);break;case cY.REGEXP:{let[,e,t]=n[r].match(/^\/(.*)\/([a-z]*)$/);n[r]=new RegExp(e,t);break}case cY.SET:n[r]=new Set(n[r]);break;case cY.MAP:n[r]=new Map(n[r]);break}}return i.data}};function uY(e){return`/${e.map(encodeURIComponent).join(`/`)}`}function dY(e){return typeof e.forEach==`function`?aY(e):e}function fY(e){return Object.entries(DJ).find(([,t])=>t.status===e)?.[0]??`MALFORMED_ORPC_ERROR_RESPONSE`}var pY=class{constructor(e,t){this.serializer=e,this.baseUrl=t.url,this.maxUrlLength=t.maxUrlLength??2083,this.fallbackMethod=t.fallbackMethod??`POST`,this.expectedMethod=t.method??this.fallbackMethod,this.headers=t.headers??{}}baseUrl;maxUrlLength;fallbackMethod;expectedMethod;headers;async encode(e,t,n){let r=dY(await xJ(this.headers,n,e,t));n.lastEventId!==void 0&&(r=JJ(r,{"last-event-id":n.lastEventId}));let i=await xJ(this.expectedMethod,n,e,t),a=await xJ(this.baseUrl,n,e,t),o=new URL(a);o.pathname=`${o.pathname.replace(/\/$/,``)}${uY(e)}`;let s=this.serializer.serialize(t);if(i===`GET`&&!(s instanceof FormData)&&!sJ(s)){let a=await xJ(this.maxUrlLength,n,e,t),c=new URL(o);if(c.searchParams.append(`data`,hJ(s)),c.toString().length<=a)return{body:void 0,method:i,headers:r,url:c,signal:n.signal}}return{url:o,method:i===`GET`?this.fallbackMethod:i,headers:r,body:s,signal:n.signal}}async decode(e){let t=!PJ(e.status),n=await(async()=>{let t=!1;try{let n=await e.body();return t=!0,this.serializer.deserialize(n)}catch(e){throw t?Error(`Invalid RPC response format.`,{cause:e}):Error(`Cannot parse response body, please check the response body and content-type.`,{cause:e})}})();if(!t)throw FJ(n)?IJ(n):new MJ(fY(e.status),{status:e.status,data:{...e,body:n}});return n}},mY=class{constructor(e){this.jsonSerializer=e}serialize(e){return sJ(e)?ZJ(e,{value:async e=>this.#e(e,!1),error:async e=>new RJ({data:this.#e(NJ(e).toJSON(),!1),cause:e})}):this.#e(e,!0)}#e(e,t){let[n,r,i,a]=this.jsonSerializer.serialize(e),o=r.length===0?void 0:r;if(!t||a.length===0)return{json:n,meta:o};let s=new FormData;return s.set(`data`,hJ({json:n,meta:o,maps:i})),a.forEach((e,t)=>{s.set(t.toString(),e)}),s}deserialize(e){return sJ(e)?ZJ(e,{value:async e=>this.#t(e),error:async e=>{if(!(e instanceof RJ))return e;let t=this.#t(e.data);return FJ(t)?IJ(t,{cause:e}):new RJ({data:t,cause:e})}}):this.#t(e)}#t(e){if(e===void 0)return;if(!(e instanceof FormData))return this.jsonSerializer.deserialize(e.json,e.meta??[]);let t=JSON.parse(e.get(`data`));return this.jsonSerializer.deserialize(t.json,t.meta??[],t.maps,t=>e.get(t.toString()))}},hY=class extends sY{constructor(e,t){let n=new pY(new mY(new lY(t)),t);super(n,e,t)}};function gY(e,t){return{...e,...t}}function _Y(e,t){return{...e,...t}}function vY(e,t){return e.path?{...e,path:`${t}${e.path}`}:e}function yY(e,t){return{...e,tags:[...t,...e.tags??[]]}}function bY(e,t){return e?`${e}${t}`:t}function xY(e,t){return e?[...e,...t]:t}function SY(e,t){let n=e;return t.prefix&&(n=vY(n,t.prefix)),t.tags?.length&&(n=yY(n,t.tags)),n}function CY(e,t){let n=e;for(let e=0;e<t.length;e++){let r=t[e];if(!n||iY(n))return;n=n[r]}return n}function wY(e,t){if(iY(e))return new rY({...e[`~orpc`],errorMap:tY(t.errorMap,e[`~orpc`].errorMap),route:SY(e[`~orpc`].route,t)});let n={};for(let r in e)n[r]=wY(e[r],t);return n}const TY=new class e extends rY{constructor(e){super(e),this[`~orpc`].prefix=e.prefix,this[`~orpc`].tags=e.tags}$meta(t){return new e({...this[`~orpc`],meta:t})}$route(t){return new e({...this[`~orpc`],route:t})}$input(t){return new e({...this[`~orpc`],inputSchema:t})}errors(t){return new e({...this[`~orpc`],errorMap:tY(this[`~orpc`].errorMap,t)})}meta(t){return new e({...this[`~orpc`],meta:gY(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:_Y(this[`~orpc`].route,t)})}input(t){return new e({...this[`~orpc`],inputSchema:t})}output(t){return new e({...this[`~orpc`],outputSchema:t})}prefix(t){return new e({...this[`~orpc`],prefix:bY(this[`~orpc`].prefix,t)})}tag(...t){return new e({...this[`~orpc`],tags:xY(this[`~orpc`].tags,t)})}router(e){return wY(e,this[`~orpc`])}}({errorMap:{},route:{},meta:{}}),EY={editorStateChanged:TY.input(tc({file:J().nullable(),startLine:Is().optional(),endLine:Is().optional()})).output(tc({ok:Bs()})),toolDecision:TY.input(tc({toolId:J(),decision:mc([`accept`,`reject`,`allowAlways`])})).output(tc({ok:Bs()}))};function DY(e){return{...e,context:e.context??{}}}function OY(e,t){return async n=>{let{response:r}=await e.handle({...n,body:()=>Promise.resolve(n.body)},DY(t));return r??{status:404,headers:{},body:`No procedure matched`}}}const kY=/^http:\/\/orpc\//;var AY=(e=>(e[e.REQUEST=1]=`REQUEST`,e[e.RESPONSE=2]=`RESPONSE`,e[e.EVENT_ITERATOR=3]=`EVENT_ITERATOR`,e[e.ABORT_SIGNAL=4]=`ABORT_SIGNAL`,e))(AY||{});function jY(e,t,n){if(t===3){let r=n;return{i:e,t,p:{e:r.event,d:r.data,m:r.meta}}}if(t===4)return{i:e,t,p:n};let r=n;return{i:e,p:{u:r.url.toString().replace(kY,`/`),b:r.body,h:Object.keys(r.headers).length>0?r.headers:void 0,m:r.method===`POST`?void 0:r.method}}}function MY(e){let t=e.i,n=e.t??1;if(n===3){let r=e.p;return[t,n,{event:r.e,data:r.d,meta:r.m}]}if(n===4)return[t,n,e.p];let r=e.p;return[t,1,{url:r.u.startsWith(`/`)?new URL(`http://orpc${r.u}`):new URL(r.u),headers:r.h??{},method:r.m??`POST`,body:r.b}]}function NY(e,t,n){if(t===3){let r=n;return{i:e,t,p:{e:r.event,d:r.data,m:r.meta}}}if(t===4)return{i:e,t,p:void 0};let r=n;return{i:e,p:{s:r.status===200?void 0:r.status,h:Object.keys(r.headers).length>0?r.headers:void 0,b:r.body}}}function PY(e){let t=e.i,n=e.t;if(n===3){let r=e.p;return[t,n,{event:r.e,data:r.d,meta:r.m}]}if(n===4)return[t,n,e.p];let r=e.p;return[t,2,{status:r.s??200,headers:r.h??{},body:r.b}]}async function FY(e,t,n){if(t===3||t===4)return VY(jY(e,t,n));let r=n,{body:i,headers:a}=await zY(r.body,r.headers),o=jY(e,1,{...r,body:i instanceof Blob?void 0:i,headers:a});return i instanceof Blob?VY(o,i):VY(o)}async function IY(e){let{json:t,buffer:n}=await HY(e),[r,i,a]=MY(t);if(i===3||i===4)return[r,i,a];let o=a,s=await BY(o.headers,o.body,n);return[r,i,{...o,body:s}]}async function LY(e,t,n){if(t===3||t===4)return VY(NY(e,t,n));let r=n,{body:i,headers:a}=await zY(r.body,r.headers),o=NY(e,2,{...r,body:i instanceof Blob?void 0:i,headers:a});return i instanceof Blob?VY(o,i):VY(o)}async function RY(e){let{json:t,buffer:n}=await HY(e),[r,i,a]=PY(t);if(i===3||i===4)return[r,i,a];let o=a,s=await BY(o.headers,o.body,n);return[r,i,{...o,body:s}]}async function zY(e,t){let n={...t},r=n[`content-disposition`];if(delete n[`content-type`],delete n[`content-disposition`],e instanceof Blob)return n[`content-type`]=e.type,n[`content-disposition`]=r??KJ(e instanceof File?e.name:`blob`),{body:e,headers:n};if(e instanceof FormData){let t=new Response(e);return n[`content-type`]=t.headers.get(`content-type`),{body:await t.blob(),headers:n}}return e instanceof URLSearchParams?(n[`content-type`]=`application/x-www-form-urlencoded`,{body:e.toString(),headers:n}):sJ(e)?(n[`content-type`]=`text/event-stream`,{body:void 0,headers:n}):{body:e,headers:n}}async function BY(e,t,n){let r=YJ(e[`content-type`]),i=YJ(e[`content-disposition`]);if(typeof i==`string`){let e=qJ(i)??`blob`;return new File(n===void 0?[]:[n],e,{type:r})}return r?.startsWith(`multipart/form-data`)?new Response(n,{headers:{"content-type":r}}).formData():r?.startsWith(`application/x-www-form-urlencoded`)&&typeof t==`string`?new URLSearchParams(t):t}async function VY(e,t){let n=hJ(e);return t===void 0||t.size===0?n:Xq(new Blob([new TextEncoder().encode(n),new Uint8Array([255]),t]))}async function HY(e){if(typeof e==`string`)return{json:JSON.parse(e)};let t=e instanceof Uint8Array?e:new Uint8Array(e),n=t.indexOf(255);if(n===-1){let e=new TextDecoder().decode(t);return{json:JSON.parse(e)}}let r=new TextDecoder().decode(t.subarray(0,n)),i=t.subarray(n+1);return{json:JSON.parse(r),buffer:i}}function UY(e,t,n,r={}){let i;return new uJ(async()=>{i??=tJ(`consume_event_iterator_stream`);try{let n=await aJ(i,()=>e.pull(t));switch(n.event){case`message`:{let e=n.data;return n.meta&&vJ(e)&&(e=UJ(e,n.meta)),i?.addEvent(`message`),{value:e,done:!1}}case`error`:{let e=new RJ({data:n.data});throw n.meta&&(e=UJ(e,n.meta)),i?.addEvent(`error`),e}case`done`:{let e=n.data;return n.meta&&vJ(e)&&(e=UJ(e,n.meta)),i?.addEvent(`done`),{value:e,done:!0}}}}catch(e){throw e instanceof RJ||nJ(i,e,r),e}},async e=>{try{e!==`next`&&i?.addEvent(`cancelled`),await aJ(i,()=>n(e))}catch(e){throw nJ(i,e,r),e}finally{i?.end()}})}function WY(e,t){return iJ({name:`stream_event_iterator`},async n=>{for(;;){let r=await(async()=>{try{let{value:t,done:r}=await e.next();return r?(n?.addEvent(`done`),{event:`done`,data:t,meta:WJ(t)}):(n?.addEvent(`message`),{event:`message`,data:t,meta:WJ(t)})}catch(e){if(e instanceof RJ)return n?.addEvent(`error`),{event:`error`,data:e.data,meta:WJ(e)};try{await t({event:`error`,data:void 0})}catch(t){throw nJ(n,e),t}throw e}})(),i=!1;try{let n=await t(r);if(r.event===`done`||r.event===`error`)return;if(n===`abort`){i=!0,await e.return?.();return}}catch(t){if(!i)try{await e.return?.()}catch(e){throw nJ(n,t),e}throw t}}})}var GY=class{peer;constructor(e){this.peer=new KY(async([t,n,r])=>{await e(await FY(t,n,r))})}get length(){return this.peer.length}open(e){return this.peer.open(e)}async request(e){return this.peer.request(e)}async message(e){return this.peer.message(await RY(e))}close(e={}){return this.peer.close(e)}},KY=class{idGenerator=new fJ;responseQueue=new oJ;serverEventIteratorQueue=new oJ;serverControllers=new Map;cleanupFns=new Map;send;constructor(e){this.send=async t=>{let n=t[0];this.serverControllers.has(n)&&await e(t)}}get length(){return(+this.responseQueue.length+this.serverEventIteratorQueue.length+this.serverControllers.size+this.cleanupFns.size)/4}open(e){this.serverEventIteratorQueue.open(e),this.responseQueue.open(e);let t=new AbortController;return this.serverControllers.set(e,t),this.cleanupFns.set(e,[]),t}async request(e){let t=e.signal;return iJ({name:`send_peer_request`,signal:t},async()=>{if(t?.aborted)throw t.reason;let n=this.idGenerator.generate(),r=this.open(n);try{let i=eJ();if(i){let t=yJ(e.headers);i.propagation.inject(i.context.active(),t),e={...e,headers:t}}if(await this.send([n,AY.REQUEST,e]),t?.aborted)throw await this.send([n,AY.ABORT_SIGNAL,void 0]),t.reason;let a;if(t?.addEventListener(`abort`,a=async()=>{await this.send([n,AY.ABORT_SIGNAL,void 0]),this.close({id:n,reason:t.reason})},{once:!0}),this.cleanupFns.get(n)?.push(()=>{t?.removeEventListener(`abort`,a)}),sJ(e.body)){let t=e.body;WY(t,async e=>r.signal.aborted?`abort`:(await this.send([n,AY.EVENT_ITERATOR,e]),`next`))}let o=await this.responseQueue.pull(n);if(XJ(o.headers)){let e=UY(this.serverEventIteratorQueue,n,async e=>{try{e!==`next`&&await this.send([n,AY.ABORT_SIGNAL,void 0])}finally{this.close({id:n})}},{signal:t});return{...o,body:e}}return this.close({id:n}),o}catch(e){throw this.close({id:n,reason:e}),e}})}async message([e,t,n]){if(t===AY.ABORT_SIGNAL){this.serverControllers.get(e)?.abort();return}if(t===AY.EVENT_ITERATOR){this.serverEventIteratorQueue.isOpen(e)&&this.serverEventIteratorQueue.push(e,n);return}this.responseQueue.isOpen(e)&&this.responseQueue.push(e,n)}close(e={}){e.id===void 0?(this.serverControllers.forEach(t=>t.abort(e.reason)),this.serverControllers.clear(),this.cleanupFns.forEach(e=>e.forEach(e=>e())),this.cleanupFns.clear()):(this.serverControllers.get(e.id)?.abort(e.reason),this.serverControllers.delete(e.id),this.cleanupFns.get(e.id)?.forEach(e=>e()),this.cleanupFns.delete(e.id)),this.responseQueue.close(e),this.serverEventIteratorQueue.close(e)}},qY=class{peer;constructor(e){this.peer=new JY(async([t,n,r])=>{await e(await LY(t,n,r))})}get length(){return this.peer.length}open(e){return this.peer.open(e)}async message(e,t){return this.peer.message(await IY(e),t)}async response(e,t){return this.peer.response(e,t)}close({abort:e=!0,...t}={}){return this.peer.close({...t,abort:e})}},JY=class{clientEventIteratorQueue=new oJ;clientControllers=new Map;send;constructor(e){this.send=async t=>{let n=t[0];this.clientControllers.has(n)&&await e(t)}}get length(){return(this.clientEventIteratorQueue.length+this.clientControllers.size)/2}open(e){this.clientEventIteratorQueue.open(e);let t=new AbortController;return this.clientControllers.set(e,t),t}async message([e,t,n],r){if(t===AY.ABORT_SIGNAL)return this.close({id:e,reason:new Qq(`Client aborted the request`)}),[e,void 0];if(t===AY.EVENT_ITERATOR)return this.clientEventIteratorQueue.isOpen(e)&&this.clientEventIteratorQueue.push(e,n),[e,void 0];let i=this.open(e).signal,a={...n,signal:i,body:XJ(n.headers)?UY(this.clientEventIteratorQueue,e,async t=>{t!==`next`&&await this.send([e,AY.ABORT_SIGNAL,void 0])},{signal:i}):n.body};if(r){let t,n=eJ();n&&(t=n.propagation.extract(n.context.active(),a.headers)),await iJ({name:`receive_peer_request`,context:t},async()=>{let t=await iJ({name:`handle_request`},async()=>{try{return await r(a)}catch(t){throw this.close({id:e,reason:t,abort:!1}),t}});await iJ({name:`send_peer_response`},()=>this.response(e,t))})}return[e,a]}async response(e,t){let n=this.clientControllers.get(e)?.signal;if(!(!n||n.aborted))try{if(await this.send([e,AY.RESPONSE,t]),!n.aborted&&sJ(t.body))if(t.body instanceof GJ)t.body.hibernationCallback?.(e);else{let r=t.body;await WY(r,async t=>n.aborted?`abort`:(await this.send([e,AY.EVENT_ITERATOR,t]),`next`))}this.close({id:e,abort:!1})}catch(t){throw this.close({id:e,reason:t,abort:!1}),t}}close({abort:e=!0,...t}={}){t.id===void 0?(e&&this.clientControllers.forEach(e=>e.abort(t.reason)),this.clientControllers.clear()):(e&&this.clientControllers.get(t.id)?.abort(t.reason),this.clientControllers.delete(t.id)),this.clientEventIteratorQueue.close(t)}};function YY(e){let t;if(typeof e==`string`)t=e;else{let n=e instanceof Uint8Array?e:new Uint8Array(e);t=Buffer.from(n).toString(`utf8`)}return Buffer.from(t+`
12642
+ `,`utf8`)}function XY(e){let t=[],n=0;for(let r=0;r<e.length;r++)if(e[r]===10){let i=e.subarray(n,r).toString(`utf8`).trim();i&&t.push(i),n=r+1}return[t,e.subarray(n)]}function ZY(e,t){let n=OY(t,{});try{f.existsSync(e)&&f.unlinkSync(e)}catch{}let r=N.createServer(e=>{let t=new qY(t=>{e.write(YY(t))}),r=Buffer.alloc(0);e.on(`data`,async e=>{r=Buffer.concat([r,e]);let[i,a]=XY(r);r=a;for(let e of i)await t.message(e,n)}),e.on(`close`,()=>{t.close()}),e.on(`error`,()=>{t.close()})});return new Promise((t,n)=>{r.on(`error`,n),r.listen(e,()=>{try{f.chmodSync(e,438)}catch{}t({getSocketPath:()=>e,dispose:()=>{r.close();try{f.existsSync(e)&&f.unlinkSync(e)}catch{}}})})})}var QY=class{peer;constructor(e){this.peer=e}async call(e){let t=await this.peer.request(e);return{...t,body:()=>Promise.resolve(t.body)}}},$Y=class extends hY{constructor(e){super(new QY(e),{url:`orpc:/`})}};function eX(e,t){let n=t?.timeoutMs??2e3;return new Promise((t,r)=>{let i=N.connect(e),a=setTimeout(()=>{i.destroy(),r(Error(`Connection to ${e} timed out after ${n}ms`))},n);i.on(`connect`,()=>{clearTimeout(a);let e=new GY(e=>{i.write(YY(e))}),n=Buffer.alloc(0);i.on(`data`,async t=>{n=Buffer.concat([n,t]);let[r,i]=XY(n);n=i;for(let t of r)await e.message(t)}),i.on(`close`,()=>e.close()),i.on(`error`,()=>e.close()),t({link:new $Y(e),dispose:()=>{e.close(),i.destroy()}})}),i.on(`error`,e=>{clearTimeout(a),r(e)})})}const tX=Symbol(`ORPC_LAZY_SYMBOL`);function nX(e,t={}){return{[tX]:{loader:e,meta:t}}}function rX(e){return(typeof e==`object`||typeof e==`function`)&&e!==null&&tX in e}function iX(e){return e[tX].meta}function aX(e){return rX(e)?e[tX].loader():Promise.resolve({default:e})}function oX(e,t){if(t.length>e.length)return!1;for(let n=0;n<e.length;n++){if(t[n]===void 0)return!0;if(e[n]!==t[n])return!1}return!0}function sX(e,t,n){return n.dedupeLeading&&oX(t,e)?t:[...e,...t]}function cX(e,t){return[...e,t]}var lX=class{"~orpc";constructor(e){this[`~orpc`]=e}};function uX(e){return e instanceof lX?!0:iY(e)&&`middlewares`in e[`~orpc`]&&`inputValidationIndex`in e[`~orpc`]&&`outputValidationIndex`in e[`~orpc`]&&`handler`in e[`~orpc`]}function dX(e,t){return{...e,...t}}function fX(e){return new Proxy(e,{get(t,n){return typeof n==`string`?(...t)=>{let r=Jq(t),i=e[n];return new MJ(n,{defined:!!i,status:i?.status,message:r.message??i?.message,data:r.data,cause:r.cause})}:Reflect.get(t,n)}})}function pX(e){return{output:e,context:{}}}function mX(e,...t){let n=Jq(t);return async(...[t,r])=>{let i=Yq(n.path),{default:a}=await aX(e),o=r?.context??{},s=await xJ(n.context??{},o),c=fX(a[`~orpc`].errorMap),l=async e=>e instanceof MJ?await nY(a[`~orpc`].errorMap,e):e;try{let e=await iJ({name:`call_procedure`,signal:r?.signal},e=>(e?.setAttribute(`procedure.path`,[...i]),pJ(Yq(n.interceptors),{context:s,input:t,errors:c,path:i,procedure:a,signal:r?.signal,lastEventId:r?.lastEventId},e=>_X(e.procedure,e))));return sJ(e)?e instanceof GJ?e:TJ(e,ZJ(dJ({name:`consume_event_iterator_output`,signal:r?.signal},e),{value:e=>e,error:e=>l(e)})):e}catch(e){throw await l(e)}}}async function hX(e,t){let n=e[`~orpc`].inputSchema;return n?iJ({name:`validate_input`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new MJ(`BAD_REQUEST`,{message:`Input validation failed`,data:{issues:e.issues},cause:new eY({message:`Input validation failed`,issues:e.issues,data:t})});return e.value}):t}async function gX(e,t){let n=e[`~orpc`].outputSchema;return n?iJ({name:`validate_output`},async()=>{let e=await n[`~standard`].validate(t);if(e.issues)throw new MJ(`INTERNAL_SERVER_ERROR`,{message:`Output validation failed`,cause:new eY({message:`Output validation failed`,issues:e.issues,data:t})});return e.value}):t}async function _X(e,t){let n=e[`~orpc`].middlewares,r=Math.min(Math.max(0,e[`~orpc`].inputValidationIndex),n.length),i=Math.min(Math.max(0,e[`~orpc`].outputValidationIndex),n.length),a=async(o,s,c)=>{let l=c;o===r&&(l=await hX(e,l));let u=n[o],d=u?await iJ({name:`middleware.${u.name}`,signal:t.signal},async e=>(e?.setAttribute(`middleware.index`,o),e?.setAttribute(`middleware.name`,u.name),(await u({...t,context:s,next:async(...[e])=>{let t=e?.context??{};return{output:await a(o+1,dX(s,t),l),context:t}}},l,pX)).output)):await iJ({name:`handler`,signal:t.signal},()=>e[`~orpc`].handler({...t,context:s,input:l}));return o===i?await gX(e,d):d};return a(0,t.context,t.input)}const vX=Symbol(`ORPC_HIDDEN_ROUTER_CONTRACT`);function yX(e,t){return new Proxy(e,{get(e,n){return n===vX?t:Reflect.get(e,n)}})}function bX(e){return e[vX]}function xX(e,t){let n=e;for(let e=0;e<t.length;e++){let r=t[e];if(!n||uX(n))return;if(!rX(n)){n=n[r];continue}let i=n,a=t.slice(e);return nX(async()=>aX(xX((await aX(i)).default,a)),iX(i))}return n}function SX(e){return new Proxy(e,{get(t,n){return typeof n==`string`?SX(xX(e,[n])):Reflect.get(t,n)}})}function CX(e,t){if(rX(e)){let n=iX(e),r=n?.prefix?bY(t.prefix,n?.prefix):t.prefix;return SX(nX(async()=>{let{default:n}=await aX(e);return aX(CX(n,t))},{...n,prefix:r}))}if(uX(e)){let n=sX(t.middlewares,e[`~orpc`].middlewares,{dedupeLeading:t.dedupeLeadingMiddlewares}),r=n.length-e[`~orpc`].middlewares.length;return new lX({...e[`~orpc`],route:SY(e[`~orpc`].route,t),errorMap:tY(t.errorMap,e[`~orpc`].errorMap),middlewares:n,inputValidationIndex:e[`~orpc`].inputValidationIndex+r,outputValidationIndex:e[`~orpc`].outputValidationIndex+r})}let n={};for(let r in e)n[r]=CX(e[r],t);return n}function wX(e,t,n=[]){let r=e.router,i=bX(e.router);if(i!==void 0&&(r=i),rX(r))n.push({router:r,path:e.path});else if(iY(r))t({contract:r,path:e.path});else for(let i in r)wX({router:r[i],path:[...e.path,i]},t,n);return n}function TX(e,t){return new lX({...e[`~orpc`],errorMap:t[`~orpc`].errorMap,route:t[`~orpc`].route,meta:t[`~orpc`].meta})}const EX={initialInputValidationIndex:0,initialOutputValidationIndex:0,dedupeLeadingMiddlewares:!0};function DX(e,t){return t===void 0?EX[e]:t}function OX(e){let t=((...t)=>e(...t));return t.mapInput=t=>OX((n,r,...i)=>e(n,t(r),...i)),t.concat=(t,n)=>{let r=n?OX(t).mapInput(n):t;return OX((t,n,i,...a)=>e({...t,next:(...[e])=>r({...t,context:{...t.context,...e?.context},next:(...[n])=>t.next({context:{...e?.context,...n?.context}})},n,i,...a)},n,i,...a))},t}function kX(e){return async t=>{try{return[null,await e(t)]}catch(e){if(e instanceof Error&&`digest`in e&&typeof e.digest==`string`&&e.digest.startsWith(`NEXT_`)||e instanceof Response&&`options`in e&&_J(e.options)||_J(e)&&e.isNotFound===!0)throw e;return[NJ(e).toJSON(),void 0]}}}var AX=class e extends lX{errors(t){return new e({...this[`~orpc`],errorMap:tY(this[`~orpc`].errorMap,t)})}meta(t){return new e({...this[`~orpc`],meta:gY(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:_Y(this[`~orpc`].route,t)})}use(t,n){let r=n?OX(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:cX(this[`~orpc`].middlewares,r)})}callable(...e){let t=mX(this,...e);return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}actionable(...e){let t=kX(mX(this,...e));return new Proxy(t,{get:(e,t)=>Reflect.has(this,t)?Reflect.get(this,t):Reflect.get(e,t),has:(e,t)=>Reflect.has(this,t)||Reflect.has(e,t)})}},jX=class e{"~orpc";constructor(e){this[`~orpc`]=e}$config(t){let n=this[`~orpc`].inputValidationIndex-DX(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),r=this[`~orpc`].outputValidationIndex-DX(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex);return new e({...this[`~orpc`],config:t,dedupeLeadingMiddlewares:DX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares),inputValidationIndex:DX(`initialInputValidationIndex`,t.initialInputValidationIndex)+n,outputValidationIndex:DX(`initialOutputValidationIndex`,t.initialOutputValidationIndex)+r})}$context(){return new e({...this[`~orpc`],middlewares:[],inputValidationIndex:DX(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex),outputValidationIndex:DX(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)})}$meta(t){return new e({...this[`~orpc`],meta:t})}$route(t){return new e({...this[`~orpc`],route:t})}$input(t){return new e({...this[`~orpc`],inputSchema:t})}middleware(e){return OX(e)}errors(t){return new e({...this[`~orpc`],errorMap:tY(this[`~orpc`].errorMap,t)})}use(t,n){let r=n?OX(t).mapInput(n):t;return new e({...this[`~orpc`],middlewares:cX(this[`~orpc`].middlewares,r)})}meta(t){return new e({...this[`~orpc`],meta:gY(this[`~orpc`].meta,t)})}route(t){return new e({...this[`~orpc`],route:_Y(this[`~orpc`].route,t)})}input(t){return new e({...this[`~orpc`],inputSchema:t,inputValidationIndex:DX(`initialInputValidationIndex`,this[`~orpc`].config.initialInputValidationIndex)+this[`~orpc`].middlewares.length})}output(t){return new e({...this[`~orpc`],outputSchema:t,outputValidationIndex:DX(`initialOutputValidationIndex`,this[`~orpc`].config.initialOutputValidationIndex)+this[`~orpc`].middlewares.length})}handler(e){return new AX({...this[`~orpc`],handler:e})}prefix(t){return new e({...this[`~orpc`],prefix:bY(this[`~orpc`].prefix,t)})}tag(...t){return new e({...this[`~orpc`],tags:xY(this[`~orpc`].tags,t)})}router(e){return CX(e,this[`~orpc`])}lazy(e){return CX(nX(e),this[`~orpc`])}};new jX({config:{},route:{},meta:{},errorMap:{},inputValidationIndex:DX(`initialInputValidationIndex`),outputValidationIndex:DX(`initialOutputValidationIndex`),middlewares:[],dedupeLeadingMiddlewares:!0});function MX(e,t,n){return iY(e)?new jX({...e[`~orpc`],config:t,middlewares:n,inputValidationIndex:DX(`initialInputValidationIndex`,t?.initialInputValidationIndex)+n.length,outputValidationIndex:DX(`initialOutputValidationIndex`,t?.initialOutputValidationIndex)+n.length,dedupeLeadingMiddlewares:DX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}):new Proxy(e,{get:(r,i)=>{if(typeof i!=`string`)return Reflect.get(r,i);let a;i===`middleware`?a=e=>OX(e):i===`use`?a=r=>MX(e,t,cX(n,r)):i===`router`?a=r=>yX(CX(r,{middlewares:n,errorMap:{},prefix:void 0,tags:void 0,dedupeLeadingMiddlewares:DX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}),e):i===`lazy`&&(a=r=>yX(CX(nX(r),{middlewares:n,errorMap:{},prefix:void 0,tags:void 0,dedupeLeadingMiddlewares:DX(`dedupeLeadingMiddlewares`,t.dedupeLeadingMiddlewares)}),e));let o=CY(r,[i]);if(!o)return a??o;let s=MX(o,t,n);return a?new Proxy(a,{get(e,t){return Reflect.get(s,t)}}):s}})}function NX(e,t={}){let n=MX(e,t,[]),r=new Proxy(n,{get:(t,n)=>{let i;n===`$context`?i=()=>r:n===`$config`&&(i=t=>NX(e,t));let a=Reflect.get(t,n);return!i||!a||typeof a!=`function`&&typeof a!=`object`?i||a:new Proxy(i,{get(e,t){return Reflect.get(a,t)}})}});return r}var PX=class{plugins;constructor(e=[]){this.plugins=[...e].sort((e,t)=>(e.order??0)-(t.order??0))}init(e,t){for(let n of this.plugins)n.init?.(e,t)}},FX=class{constructor(e,t,n,r){this.matcher=t,this.codec=n,new PX(r.plugins).init(r,e),this.interceptors=Yq(r.interceptors),this.clientInterceptors=Yq(r.clientInterceptors),this.rootInterceptors=Yq(r.rootInterceptors),this.matcher.init(e)}interceptors;clientInterceptors;rootInterceptors;async handle(e,t){let n=t.prefix?.replace(/\/$/,``)||void 0;return n&&!e.url.pathname.startsWith(`${n}/`)&&e.url.pathname!==n?{matched:!1,response:void 0}:pJ(this.rootInterceptors,{...t,request:e,prefix:n},async t=>iJ({name:`${e.method} ${e.url.pathname}`},async e=>{let n;try{return await pJ(this.interceptors,t,async({request:t,context:r,prefix:i})=>{let a=t.method,o=t.url,s=i?o.pathname.replace(i,``):o.pathname,c=await iJ({name:`find_procedure`},()=>this.matcher.match(a,`/${s.replace(/^\/|\/$/g,``)}`));if(!c)return{matched:!1,response:void 0};e?.updateName(`${Zq}.${c.path.join(`/`)}`),e?.setAttribute(`rpc.system`,Zq),e?.setAttribute(`rpc.method`,c.path.join(`.`)),n=`decode_input`;let l=await iJ({name:`decode_input`},()=>this.codec.decode(t,c.params,c.procedure));n=void 0,sJ(l)&&(l=dJ({name:`consume_event_iterator_input`,signal:t.signal},l));let u=mX(c.procedure,{context:r,path:c.path,interceptors:this.clientInterceptors});n=`call_procedure`;let d=await u(l,{signal:t.signal,lastEventId:YJ(t.headers[`last-event-id`])});return n=void 0,{matched:!0,response:this.codec.encode(d,c.procedure)}})}catch(t){n!==`call_procedure`&&nJ(e,t);let r=n===`decode_input`&&!(t instanceof MJ)?new MJ(`BAD_REQUEST`,{message:`Malformed request. Ensure the request body is properly formatted and the 'Content-Type' header is set correctly.`,cause:t}):NJ(t);return{matched:!0,response:this.codec.encodeError(r)}}}))}},IX=class{constructor(e){this.serializer=e}async decode(e,t,n){let r=e.method===`GET`?mJ(e.url.searchParams.getAll(`data`).at(-1)):await e.body();return this.serializer.deserialize(r)}encode(e,t){return{status:200,headers:{},body:this.serializer.serialize(e)}}encodeError(e){return{status:e.status,headers:{},body:this.serializer.serialize(e.toJSON())}}},LX=class{filter;tree=new bJ;pendingRouters=[];constructor(e={}){this.filter=e.filter??!0}init(e,t=[]){let n=wX({router:e,path:t},t=>{if(!xJ(this.filter,t))return;let{path:n,contract:r}=t,i=uY(n);uX(r)?this.tree[i]={path:n,contract:r,procedure:r,router:e}:this.tree[i]={path:n,contract:r,procedure:void 0,router:e}});this.pendingRouters.push(...n.map(e=>({...e,httpPathPrefix:uY(e.path)})))}async match(e,t){if(this.pendingRouters.length){let e=[];for(let n of this.pendingRouters)if(t.startsWith(n.httpPathPrefix)){let{default:e}=await aX(n.router);this.init(e,n.path)}else e.push(n);this.pendingRouters=e}let n=this.tree[t];if(n){if(!n.procedure){let{default:e}=await aX(xX(n.router,n.path));if(!uX(e))throw Error(`
12643
+ [Contract-First] Missing or invalid implementation for procedure at path: ${uY(n.path)}.
12644
12644
  Ensure that the procedure is correctly defined and matches the expected contract.
12645
- `);n.procedure=wX(e,n.contract)}return{path:n.path,procedure:n.procedure}}}},LX=class extends PX{constructor(e,t={}){let n=new pY(new cY(t)),r=new IX(t),i=new FX(n);super(e,r,i,t)}},RX=class{socketServer;socketPath;editorState={file:void 0,startLine:void 0,endLine:void 0};onEditorStateCallback=null;pendingDecisions=new Map;constructor(){let e=S.join(t.homedir(),ke.configDirName,`cli`);this.socketPath=S.join(e,`${process.pid}.sock`)}getEditorState(){return{...this.editorState}}onEditorChange(e){this.onEditorStateCallback=e}waitForDecision(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Aborted`));return}let i=()=>{t?.removeEventListener(`abort`,a),this.pendingDecisions.delete(e)},a=()=>{i(),r(Error(`Aborted`))};t?.addEventListener(`abort`,a,{once:!0}),this.pendingDecisions.set(e,{resolve:e=>{i(),n(e)},cleanup:i})})}async start(){let e=S.dirname(this.socketPath);f.existsSync(e)||f.mkdirSync(e,{recursive:!0});let t=MX(TY),n=t.router({editorStateChanged:t.editorStateChanged.handler(async({input:e})=>(this.editorState={file:e.file??void 0,startLine:e.startLine,endLine:e.endLine},this.onEditorStateCallback?.(this.editorState),{ok:!0})),toolDecision:t.toolDecision.handler(async({input:e})=>{let t=this.pendingDecisions.get(e.toolId);return t&&t.resolve(e.decision),{ok:!0}})});this.socketServer=await XY(this.socketPath,new LX(n))}dispose(){for(let[,e]of this.pendingDecisions)e.cleanup();this.pendingDecisions.clear(),this.socketServer?.dispose(),this.socketServer=void 0}},zX=class{client=null;disposeSocket=null;currentFile=void 0;selectionStartLine=void 0;selectionEndLine=void 0;onFileChangeCallback=null;constructor(e){this.pushServer=e}findSocketPath(){let e=process.env[ke.socketEnvVar];if(e&&p.existsSync(e))return e;try{let e=C.join(n.homedir(),ke.configDirName,ke.ideDirName),t=p.readdirSync(e).filter(e=>e.endsWith(`.sock`));if(t.length===0)return null;let r=null;for(let n of t){let t=C.join(e,n);try{let e=p.statSync(t);(!r||e.mtimeMs>r.mtime)&&(r={path:t,mtime:e.mtimeMs})}catch{}}if(r&&p.existsSync(r.path))return r.path}catch{}return null}async connect(){try{let e=this.findSocketPath();if(!e)return!1;let t=await $Y(e,{timeoutMs:2e3});this.client=QJ(t.link),this.disposeSocket=()=>t.dispose(),await this.client.register({cliSocketPath:this.pushServer.socketPath,pid:process.pid});let n=this.pushServer.getEditorState();return this.currentFile=n.file,this.selectionStartLine=n.startLine,this.selectionEndLine=n.endLine,this.pushServer.onEditorChange(e=>{this.currentFile=e.file,this.selectionStartLine=e.startLine,this.selectionEndLine=e.endLine,this.onFileChangeCallback?.(e.file,e.startLine,e.endLine)}),!0}catch{return!1}}getCurrentFile(){return this.currentFile}getSelectionRange(){return{startLine:this.selectionStartLine,endLine:this.selectionEndLine}}isConnected(){return this.client!==null}onFileChange(e){this.onFileChangeCallback=e}async showDiff(e){if(!this.client)return!1;try{return(await this.client.showDiff({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async showToolView(e){if(!this.client)return!1;try{return(await this.client.showToolView({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async notifyDiffDecision(e){if(!this.client)throw Error(`Not connected to extension`);await this.client.notifyDiffDecision(e)}async openPlanFile(e){if(!this.client)throw Error(`Not connected to extension`);return{opened:(await this.client.openFile({file:e})).success}}async getDiagnostics(e){if(!this.client)throw Error(`Not connected to extension`);return this.client.getDiagnostics({...e&&{files:e}})}dispose(){this.disposeSocket?.(),this.disposeSocket=null,this.client=null,this.currentFile=void 0,this.selectionStartLine=void 0,this.selectionEndLine=void 0,this.onFileChangeCallback=null}};const BX=(0,Z.createContext)(null);function VX(){let e=(0,Z.use)(BX);if(!e)throw Error(`useExtensionFile must be used within ExtensionFileProvider`);return e}function HX({children:e,initialFile:t}){let[n,r]=(0,Z.useState)(t),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(void 0),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=!1;return(async()=>{let t=new RX;try{await t.start()}catch{}if(e){t.dispose();return}p.current=t,d(t),t.onEditorChange(e=>{r(e.file),a(e.startLine),s(e.endLine)});for(let n of[0,...[500,1e3,2e3,3e3,4e3]]){if(e||(n>0&&await new Promise(e=>setTimeout(e,n)),e))return;try{let n=new zX(t);if(await n.connect()){if(e){n.dispose();return}let i=t.getEditorState();r(i.file),a(i.startLine),s(i.endLine),n.onFileChange((e,t,n)=>{r(e),a(t),s(n)}),f.current=n,l(n);return}}catch{}}})(),()=>{e=!0,f.current&&(f.current.dispose(),f.current=null,l(null)),p.current&&(p.current.dispose(),p.current=null,d(null))}},[]),(0,X.jsx)(BX.Provider,{value:{currentFile:n,selectionStartLine:i,selectionEndLine:o,connection:c,pushServer:u},children:e})}const UX=(0,Z.createContext)(null);function WX({children:e}){let[t,n]=(0,Z.useState)(`idle`),r=(0,Z.useCallback)(()=>n(`upload`),[]),i=(0,Z.useCallback)(()=>n(`download`),[]),a=(0,Z.useCallback)(()=>n(`idle`),[]),o=(0,Z.useMemo)(()=>({activity:t,setActivity:n,startUpload:r,startDownload:i,stopActivity:a}),[t,r,i,a]);return(0,X.jsx)(UX.Provider,{value:o,children:e})}function GX(){let e=(0,Z.use)(UX);if(!e)throw Error(`useNetworkActivity must be used within NetworkActivityProvider`);return e}let KX=function(e){return e.ESC=`\x1B`,e.BEL=`\x07`,e.ST=`\x1B\\`,e.ENABLE_FOCUS_REPORTING=`${e.ESC}[?1004h`,e.DISABLE_FOCUS_REPORTING=`${e.ESC}[?1004l`,e.FOCUS_IN=`${e.ESC}[I`,e.FOCUS_OUT=`${e.ESC}[O`,e.SHOW_CURSOR=`${e.ESC}[?25h`,e.HIDE_CURSOR=`${e.ESC}[?25l`,e.SET_TITLE=`${e.ESC}]2;`,e.RESET_SGR=`${e.ESC}[0m`,e.SOFT_RESET=`${e.ESC}[!p`,e.HARD_RESET=`${e.ESC}c`,e.ENABLE_BRACKETED_PASTE=`${e.ESC}[?2004h`,e.DISABLE_BRACKETED_PASTE=`${e.ESC}[?2004l`,e.PASTE_MODE_PREFIX=`${e.ESC}[200~`,e.PASTE_MODE_SUFFIX=`${e.ESC}[201~`,e.DIM=`${e.ESC}[2m`,e.BOLD=`${e.ESC}[1m`,e.RESET_BOLD=`${e.ESC}[22m`,e.ITALIC=`${e.ESC}[3m`,e.RESET_ITALIC=`${e.ESC}[23m`,e.STRIKETHROUGH=`${e.ESC}[9m`,e.RESET_STRIKETHROUGH=`${e.ESC}[29m`,e.UNDERLINE=`${e.ESC}[4m`,e.RESET_UNDERLINE=`${e.ESC}[24m`,e}({});function qX(e){return`${KX.ESC}]9;\n\n${e}${KX.BEL}`}function JX(e,t){return`${KX.ESC}]777;notify;${e};${t}${KX.BEL}`}function YX(e,t){let n=Math.floor(Math.random()*1e4),r=`${KX.ESC}]99;i=${n}:d=0:p=title;${e}${KX.ST}`,i=`${KX.ESC}]99;i=${n}:p=body;${t}${KX.ST}`,a=`${KX.ESC}]99;i=${n}:d=1:a=focus;${KX.ST}`;return r+i+a}function XX(e,t){let n=`9;4;${e};${t===void 0?0:Math.max(0,Math.min(100,Math.round(t)))}`;return`${KX.ESC}]${n}${KX.BEL}${KX.ESC}]${n}${KX.ST}`}function ZX(e){return e.replaceAll(`\x1B`,``).replaceAll(`\x07`,``).replaceAll(`
12646
- `,` `).replaceAll(`\r`,` `).replaceAll(`;`,`:`).trim().slice(0,120)}function QX(e){return`${KX.ESC}]${e}${KX.BEL}${KX.ESC}]${e}${KX.ST}`}function $X(){return QX(`1337;Progress=`)}function eZ(e){return QX(`1337;Progress=${e}`)}function tZ(e,t){let n=Math.max(0,Math.min(100,Math.round(e))),r=t?ZX(t):``;return r?QX(`1337;Progress=${n};${r}`)+QX(`1337;Progress=message=${r};percent=${n}`):QX(`1337;Progress=${n}`)}function nZ({onlyFirst:e=!1}={}){return RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:`g`)}const rZ=nZ();function iZ(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(rZ,``)}const aZ=[`pycharm`,`intellij`,`webstorm`,`phpstorm`,`rubymine`,`clion`,`goland`,`rider`,`datagrip`,`appcode`,`dataspell`,`aqua`,`gateway`,`fleet`,`jetbrains`,`androidstudio`];function oZ(e){if(U.env.CURSOR_TRACE_ID)return e?.debug?.(`Detected Cursor terminal via CURSOR_TRACE_ID`),`cursor`;if(U.env.VSCODE_GIT_ASKPASS_MAIN?.includes(`/.cursor-server/`))return e?.debug?.(`Detected Cursor terminal via VSCODE_GIT_ASKPASS_MAIN`),`cursor`;if(U.env.VSCODE_GIT_ASKPASS_MAIN?.includes(`/.windsurf-server/`))return e?.debug?.(`Detected Windsurf terminal`),`windsurf`;let t=U.env.__CFBundleIdentifier?.toLowerCase();if(t?.includes(`vscodium`))return`codium`;if(t?.includes(`windsurf`))return`windsurf`;if(t?.includes(`com.google.android.studio`))return`androidstudio`;if(t){for(let e of aZ)if(t.includes(e))return e}if(U.env.VisualStudioVersion)return`visualstudio`;if(U.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`)return`pycharm`;if(U.env.TERM===`xterm-ghostty`)return`ghostty`;if(U.env.TERM?.includes(`kitty`))return`kitty`;if(U.env.WEZTERM_PANE)return`WezTerm`;if(U.env.ITERM_SESSION_ID)return`iTerm.app`;if(U.env.TERM_PROGRAM===`Apple_Terminal`)return`Apple_Terminal`;if(U.env.TERM_PROGRAM)return U.env.TERM_PROGRAM;if(U.env.STY)return`screen`;if(U.env.KONSOLE_VERSION)return`konsole`;if(U.env.GNOME_TERMINAL_SERVICE)return`gnome-terminal`;if(U.env.XTERM_VERSION)return`xterm`;if(U.env.VTE_VERSION)return`vte-based`;if(U.env.TERMINATOR_UUID)return`terminator`;if(U.env.KITTY_WINDOW_ID)return`kitty`;if(U.env.ALACRITTY_LOG)return`alacritty`;if(U.env.TILIX_ID)return`tilix`;if(U.env.WT_SESSION)return`windows-terminal`;if(U.env.SESSIONNAME&&U.env.TERM===`cygwin`)return`cygwin`;if(U.env.MSYSTEM)return U.env.MSYSTEM.toLowerCase();if(U.env.ConEmuANSI||U.env.ConEmuPID||U.env.ConEmuTask)return`conemu`;if(U.env.WSL_DISTRO_NAME)return`wsl-${U.env.WSL_DISTRO_NAME}`;if(U.env.SSH_CONNECTION||U.env.SSH_CLIENT||U.env.SSH_TTY)return`ssh-session`;if(U.env.TERM){let e=U.env.TERM;return e.includes(`alacritty`)?`alacritty`:e.includes(`rxvt`)?`rxvt`:e.includes(`termite`)?`termite`:U.env.TERM}return U.stdout.isTTY?(e?.debug?.(`Could not detect terminal type`),null):(e?.debug?.(`Non-interactive terminal detected`),`non-interactive`)}function sZ(){switch(oZ()){case`Apple_Terminal`:return`Option+Enter`;case`cursor`:case`windsurf`:case`vscode`:case`codium`:case`iTerm.app`:case`ghostty`:case`WezTerm`:case`kitty`:case`alacritty`:return`Shift+Enter`;default:return`backslash (\\) + Enter`}}function cZ(e){U.stdout.isTTY&&U.stdout.write(e)}function lZ(e,t){cZ(qX(e?`${e}:\n${t}`:t))}function uZ(e,t){cZ(YX(e,t))}function dZ(e,t){cZ(JX(e,t))}function fZ(e,t){cZ(KX.BEL)}async function pZ(e){let{title:t=`Abacus.AI`,message:n}=e;switch(oZ()){case`iTerm.app`:lZ(t,n);break;case`kitty`:uZ(t,n);break;case`ghostty`:dZ(t,n);break;case`WezTerm`:lZ(t,n);break;default:U.platform===`win32`&&fZ(t,n);break}}async function mZ(e,t){await pZ({...t,message:e,title:t?.title??`Action Required`})}async function hZ(e,t){await pZ({...t,message:e,title:t?.title??`Task Complete`})}const gZ=(0,Z.createContext)(null),_Z=()=>{let e=(0,Z.use)(gZ);if(!e)throw Error(`useNotification must be used within NotificationProvider`);return e},vZ=({children:e})=>{let{isFocused:t}=lI(),n=(0,Z.useCallback)(async(e,n)=>{t||await pZ({message:e,title:n})},[t]),r=(0,Z.useCallback)(async e=>{t||await mZ(e)},[t]),i=(0,Z.useCallback)(async e=>{t||await hZ(e)},[t]),a=(0,Z.useMemo)(()=>({notifyIfUnfocused:n,notifyActionRequired:r,notifyTaskComplete:i}),[n,r,i]);return(0,X.jsx)(gZ.Provider,{value:a,children:e})},yZ=(0,Z.createContext)(null),bZ=()=>{let e=(0,Z.use)(yZ);if(!e)throw Error(`useApiClient must be used within ApiClientProvider`);return e},xZ=(0,Z.memo)(({children:e,client:t,authManager:n})=>{let[r,i]=(0,Z.useState)(!1),a=(0,Z.useCallback)(()=>i(!1),[]),o=(0,Z.useMemo)(()=>({apiClient:t,authManager:n,authExpired:r,setAuthExpired:i,clearAuthExpired:a}),[r,t,n,a]);return(0,X.jsx)(yZ.Provider,{value:o,children:e})});xZ.displayName=`ApiClientProvider`;const SZ=[`conemu`,`ghostty`,`windows-terminal`,`WezTerm`,`iTerm.app`];let CZ=null;function wZ(e){if(!e||!U.stdout.isTTY)return!1;if(SZ.includes(e))return!0;let t=e.toLowerCase();return t.includes(`iterm`)||t.includes(`ghostty`)||t.includes(`wezterm`)||t.includes(`conemu`)}function TZ(e){U.stdout.write(e)}function EZ(e){switch(e){case`indeterminate`:return 3;case`error`:return 2;case`warning`:return 4;default:return 1}}function DZ(){CZ&&=(clearTimeout(CZ),null)}function OZ(){DZ(),CZ=setTimeout(()=>{kZ()},500)}function kZ(){let e=oZ();wZ(e)&&(TZ(XX(0)),e?.toLowerCase().includes(`iterm`)&&TZ($X()))}function AZ(e,t){if(e instanceof Promise)return MZ(e,t);let n=e,r=oZ();if(!wZ(r))return;DZ();let i=0;n.percentage===void 0?n.total!==void 0&&n.current!==void 0&&n.total>0&&(i=n.current/n.total*100):i=n.percentage;let a=n.state??`default`;TZ(XX(EZ(a),i)),r?.toLowerCase().includes(`iterm`)&&(a===`indeterminate`?TZ(eZ(2)):(TZ(tZ(i,n.label)),i>=100&&TZ(eZ(1)))),(a===`error`||i>=100)&&OZ()}function jZ(){DZ(),kZ()}async function MZ(e,t){let{label:n,hideOnComplete:r=!0}=t??{};AZ({state:`indeterminate`,label:n});try{let t=await e;return AZ({percentage:100,state:`default`,label:n}),r&&OZ(),t}catch(e){throw AZ({percentage:100,state:`error`,label:n}),r&&OZ(),e}}const NZ=(0,Z.createContext)(null);function PZ(e,t){switch(t.type){case`INIT_SEND`:return[...e.filter(e=>e.temp!==!0),t.userSeg,t.spinnySeg];case`TEXT_DELTA`:{let{segId:n,content:r}=t,i=e.map(e=>e.type===`code_llm_tool_call`&&e.status===`transient`&&!e.toolUseResult?{...e,status:`completed`,parsedResult:{phase:`error`,toolType:Array.isArray(e.toolUseRequest)?e.toolUseRequest[0]?.name??``:e.toolUseRequest?.name??``,data:{},summary:``}}:e).filter(e=>!e.isSpinny);return i.find(e=>e.id===n)?i.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...i,{id:n,status:`transient`,source:`bot`,type:`text`,segment:r}]}case`THINKING_DELTA`:{let{segId:n,content:r,startTime:i}=t;return e.find(e=>e.id===n)?e.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...e,{id:n,status:`transient`,source:`bot`,type:`thinking`,isSpinny:!0,segment:r,thinkingStartTime:i}]}case`THINKING_COMPLETE`:return e.map(e=>e.id===t.segId?{...e,status:`completed`,isSpinny:!1,thinkingEndTime:t.endTime}:e);case`TOOL_DISPLAY_DATA`:return e.map(e=>e.id===t.toolCallId?{...e,toolDisplayData:{...e.toolDisplayData,...t.data}}:e);case`TOOL_REQUESTED`:{let{textSegId:n,toolSeg:r}=t,i;return i=n?e.filter(e=>!e.isSpinny).map(e=>e.id===n?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...i,r]}case`TOOL_EXECUTION_COMPLETE`:{let{toolCallId:n,rawResult:r,parsedResult:i,spinnySeg:a}=t;return[...e.map(e=>e.id===n?{...e,status:`completed`,toolUseResult:r,...i!==void 0&&{parsedResult:i}}:e),a]}case`TOOL_USER_MESSAGE`:return[...e,t.seg];case`TEXT_COMPLETED`:return e.map(e=>e.id===t.segId?{...e,status:`completed`}:e);case`FINALIZE`:{let n=e;return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n.filter(e=>!e.isSpinny)}case`ADD_NOTIFICATION`:{let n=t.seg,r=e[e.length-1];if(r&&r.type===`code_llm_notification`&&r.message===n.message&&r.severity===n.severity){let t=[...e];return t[t.length-1]={...r,flashKey:(r.flashKey??0)+1},t}return[...e,n]}case`ERROR`:return[...e.filter(e=>!e.isSpinny),t.errorSeg];case`REMOVE_USER_SEG`:return e.filter(e=>e.id!==t.userSegId);case`CLEAR`:return[];case`LOAD`:return t.segments;case`REMOVE_TEMP`:return e.some(e=>e.temp===!0)?e.filter(e=>e.temp!==!0):e;default:return e}}function FZ(e){switch(e.type){case`text`:return{id:e.id,status:`completed`,source:e.source,type:`text`,segment:e.content};case`thinking`:return{id:e.id,status:`completed`,source:`bot`,type:`thinking`,segment:e.content,isSpinny:e.isSpinny,...e.title!==void 0&&{title:e.title}};case`tool_call`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:e.toolUseRequest,toolUseResult:e.toolUseResult??{id:e.toolUseRequest.id,content:` `},...e.parsedResult!==void 0&&{parsedResult:e.parsedResult},...e.toolDisplayData!==void 0&&{toolDisplayData:e.toolDisplayData}};case`notification`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:e.severity,...e.actions!==void 0&&{actions:e.actions}};case`tool_group`:return{id:e.id,status:`completed`,source:`bot`,type:`text`,segment:e.summary}}}const IZ=(0,Z.memo)(({children:e,apiClient:t,configService:n,agentArgs:r})=>{let{agentMode:i,setAgentMode:a}=$K(),o=(0,Z.useRef)(i),{notifyActionRequired:s,notifyTaskComplete:c}=_Z(),{startUpload:l,startDownload:u,stopActivity:d}=GX(),{authManager:f,setAuthExpired:p}=bZ(),{connection:m,pushServer:h}=VX(),g=(0,Z.useRef)(m),_=(0,Z.useRef)(h);(0,Z.useEffect)(()=>{g.current=m},[m]),(0,Z.useEffect)(()=>{_.current=h},[h]);let[v,y]=(0,Z.useState)(Sl.Idle),[b,x]=(0,Z.useReducer)(PZ,[]),S=(0,Z.useRef)(new Map),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)([]),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(!0),[I,L]=(0,Z.useState)(!0),R=(0,Z.useRef)(!0),z=(0,Z.useRef)(null),B=(0,Z.useRef)(Sl.Idle),V=(0,Z.useCallback)(e=>{B.current=e,y(e)},[]);(0,Z.useEffect)(()=>()=>{z.current&&clearTimeout(z.current)},[]);let H=(0,Z.useMemo)(()=>({}),[]),[ee,te]=(0,Z.useState)(null),ne=process.cwd(),re=(0,Z.useMemo)(()=>new Pk(async e=>{let t=g.current,n=e,r=null;if(t&&_.current&&e.type===`edit_file`){let i=e.tool.id,a=S.current.get(i),o=e.tool.input??{},s=o.targetFile??e.filePath??``,c=a?.originalContent??e.originalContent??``,l=a?.newContent??e.newContent??o.codeEdit??``;s&&(c||l)&&await t.showDiff({filePath:s,originalContent:c,modifiedContent:l,toolId:i})&&(n={...e,diffShownInEditor:!0},r=s)}if(t&&e.type===`exit_plan_mode`&&e.planFilePath){let n=e.tool.id;if(_.current&&await t.showToolView({filePath:e.planFilePath,toolKey:n})){let e=await _.current.waitForDecision(n);return e===`allowAlways`?`allowAlways`:e}await t.openPlanFile(e.planFilePath).catch(()=>{})}let i=await new Promise(e=>{D({request:n,resolve:t=>{D(null),V(t===`accept`||t===`allowAlways`||typeof t==`object`&&t.type===`accept_with_message`||typeof t==`object`&&t.type===`question_answers`?Sl.ExecutingTool:Sl.Submitted),setTimeout(()=>e(t),0).unref()}}),V(Sl.WaitingForToolPermission),s(`Abacus.AI is waiting for your input`)});if(r&&t){let e=i===`reject`||typeof i==`object`&&i.type===`reject_with_message`;t.notifyDiffDecision({targetFile:r,decision:e?`reject`:`accept`}).catch(()=>{})}return i}),[s,V]),ie=(0,Z.useRef)(null);function ae(){return new Mk({allowedDirectories:[ne,...r?.[`add-dir`]?.map(e=>C.isAbsolute(e)?e:C.resolve(ne,e))??[]],primaryWorkspace:ne,apiClient:t,mode:o.current,permissionProvider:re,config:n,diagnosticsProvider:{getDiagnostics:async e=>{let t=g.current;return t?t.getDiagnostics(e):[]}},cliAllowedTools:r?.[`allowed-tools`],cliDisallowedTools:r?.[`disallowed-tools`]})}ie.current||=ae();let oe=ie.current;(0,Z.useEffect)(()=>{o.current=i,oe.setMode(i)},[i,oe]),(0,Z.useEffect)(()=>{r?.conversationId&&fe(r.conversationId)},[]),(0,Z.useEffect)(()=>{switch(v){case Sl.Submitted:case Sl.Streaming:AZ({state:`indeterminate`,label:`Processing`});break;case Sl.ExecutingTool:AZ({state:`indeterminate`,label:`Executing tools`});break;case Sl.WaitingForToolPermission:jZ();break;case Sl.Idle:jZ();break}},[v]);let se=(0,Z.useCallback)((e,t=`info`,n=!1)=>{x({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:t,message:e,temp:n}})},[]),ce=(0,Z.useCallback)(()=>{x({type:`CLEAR`}),T(null),V(Sl.Idle),te(null),S.current.clear(),ie.current=ae()},[t,ne,re]),le=(0,Z.useCallback)(()=>{x({type:`CLEAR`})},[]),U=(0,Z.useCallback)(()=>{x({type:`REMOVE_TEMP`})},[]),ue=(0,Z.useCallback)(()=>{let e=oe.dequeue();oe.clearQueue(),k([]),e!==null&&j(e),oe.stop(),D(null),V(Sl.Idle)},[oe,V]),de=(0,Z.useCallback)(()=>{E&&E.resolve(`reject`)},[E]),fe=(0,Z.useCallback)(async e=>{V(Sl.LoadingConversation),x({type:`CLEAR`}),T(null),te(e);try{let t=await oe.loadConversation(e);t.title&&T(t.title),t.segments.length>0&&x({type:`LOAD`,segments:t.segments.map(e=>FZ(e))})}catch{se(`Failed to load conversation`,`error`)}finally{V(Sl.Idle)}},[oe,se,V]),pe=(0,Z.useCallback)(async(e,t)=>{await oe.mcp.refresh(),t&&se(`MCP tools refreshed`,`info`,!0)},[oe,se]),me=(0,Z.useCallback)(async({message:e,selectedModel:t,fileAttachments:n})=>{if(!e||v===Sl.LoadingConversation)return;t&&oe.setModel(t);let r=e;if(n&&n.length>0){let e=n.filter(e=>!e.mimeType.startsWith(`image/`));for(let t of e){let e=typeof t.content==`string`?t.content:t.content.toString(`utf-8`);r+=`\n\n<file path="${t.filePath}">\n${e}\n</file>`}}let i=crypto.randomUUID();x({type:`INIT_SEND`,userSeg:{id:i,status:`completed`,source:`user`,type:`text`,segment:e},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),V(Sl.Submitted),l();let o=null,s=null,m,h=g.current,_=h?.getCurrentFile(),y=h?.getSelectionRange();if(h&&_)try{let e=(await h.getDiagnostics([_])).filter(e=>e.severity===`error`||e.severity===`warning`);e.length>0&&(m=e.map(e=>`${e.file}:${e.line}:${e.column} [${e.severity}] ${e.message}`).join(`
12647
- `))}catch{}try{for await(let e of oe.send(r,{diagnosticIssues:m,currentFile:_??void 0,selectionStartLine:y?.startLine,selectionEndLine:y?.endLine}))switch(e.type){case`text_delta`:{V(Sl.Streaming),d(),u();let t=e.content;o||=crypto.randomUUID(),x({type:`TEXT_DELTA`,segId:o,content:t});break}case`thinking_delta`:{let t=e.content;s||=crypto.randomUUID(),x({type:`THINKING_DELTA`,segId:s,content:t,startTime:Date.now()});break}case`thinking_complete`:s&&=(x({type:`THINKING_COMPLETE`,segId:s,endTime:Date.now()}),null);break;case`tool_display_data`:{let{toolCallId:t,data:n}=e,r=S.current.get(t)??{};S.current.set(t,{...r,...n}),x({type:`TOOL_DISPLAY_DATA`,toolCallId:t,data:n});break}case`tool_requested`:{V(Sl.ExecutingTool),d(),l();let t=e.tool.id,n={id:t,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:t,name:e.tool.name,input:e.tool.input},toolDisplayData:S.current.get(t)};x({type:`TOOL_REQUESTED`,toolCallId:t,textSegId:o,toolSeg:n}),o=null;break}case`tool_execution_complete`:{d(),u();let t=e.tool.id,{parsedResult:n,...r}=e.result,i={id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Analyzing result`,temp:!0,isSpinny:!0};x({type:`TOOL_EXECUTION_COMPLETE`,toolCallId:t,rawResult:r,...n!==void 0&&{parsedResult:n},spinnySeg:i}),o=null;break}case`notification`:x({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:e.severity,message:e.message,...e.actions!==void 0&&{actions:e.actions}}});break;case`error`:x({type:`ERROR`,errorSeg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:`error`,message:e.error.message}});break;case`mode_changed`:a(e.mode);break;case`tool_user_message`:x({type:`TOOL_USER_MESSAGE`,seg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.message}});break;case`retry`:N({attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,isNetworkError:e.isNetworkError});break;case`network_status`:e.online?(z.current&&=(clearTimeout(z.current),null),R.current=!0,F(!0),L(!0),N(null),setTimeout(()=>{if(B.current===Sl.Idle&&oe.getQueue().length>0){let e=oe.dequeue();e&&(k(oe.getQueue()),me({message:e}))}},0).unref?.()):(R.current=!1,F(!1),z.current||=setTimeout(()=>{z.current=null,R.current||L(!1)},3e4));break;case`user_message_dequeued`:x({type:`INIT_SEND`,userSeg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:e.content},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),k(oe.getQueue()),o=null,s=null;break;case`turn_complete`:o&&=(x({type:`TEXT_COMPLETED`,segId:o}),null),k(oe.getQueue());break}}catch(e){if(e instanceof Se)f.isEnvAuth()||(p(!0),f.logout()),x({type:`REMOVE_USER_SEG`,userSegId:i}),se(`Session expired — use /login to authenticate again.`,`error`,!0);else{let t=e instanceof Ce?`Unable to connect to API`:e instanceof Error?e.message:`An error occurred`;x({type:`REMOVE_USER_SEG`,userSegId:i}),se(t,`error`,!0)}j(r),oe.clearQueue(),k([])}finally{d(),N(null);let e=oe.getConversationId();e&&te(e),x({type:`FINALIZE`,textSegId:o}),V(Sl.Idle),c(`Abacus.AI completed the task`)}},[oe,v,se,c,l,u,d,a,f,p]),he=(0,Z.useCallback)(e=>{oe.enqueue(e),k(oe.getQueue())},[oe]),ge=(0,Z.useCallback)(()=>{oe.dequeue(),k(oe.getQueue())},[oe]),_e=(0,Z.useCallback)(()=>{oe.clearQueue(),k([])},[oe]),W=(0,Z.useCallback)(()=>{j(null)},[]),ve=(0,Z.useCallback)((e,t)=>oe.addAllowedDirectory(e,t),[oe]),ye=(0,Z.useMemo)(()=>({conversationId:ee,conversationTitle:w,segments:b,segmentsLength:b.length,sendMessage:me,stop:ue,rejectPendingPermission:de,agentStatus:v,clearSegments:ce,clearSegmentsOnly:le,clearTempSegments:U,loadConversation:fe,addNotification:se,mcp:oe.mcp,addAllowedDirectory:ve,pendingToolPermission:E,refreshMcpTools:pe,queuedMessages:O,addToQueue:he,removeFirstFromQueue:ge,clearQueue:_e,dequeuedOnStop:A,clearDequeuedOnStop:W,activeToolOutputs:H,retryState:M,networkOnline:P,debouncedNetworkOnline:I}),[ee,w,b,me,ue,de,v,ce,le,U,fe,se,oe,ve,E,pe,O,he,ge,_e,A,W,H,M,P,I]);return(0,X.jsx)(NZ.Provider,{value:ye,children:e})});IZ.displayName=`AgentProvider`;function LZ(){let e=(0,Z.use)(NZ);if(!e)throw Error(`Agent context not found. Did you forget to wrap your component in <${IZ.name}>?`);return e}const RZ=tc({url:J()}),zZ={displayName:`Fetch`,getHeaderParams(e){try{let t=e?.url||``;return t.length>50?t.substring(0,47)+`...`:t}catch{return`[unknown]`}},renderUI(e,t,n){let r=RZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Fetch`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=i.length>50?i.substring(0,47)+`...`:i;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error fetching URL`})]}):t===`executing`?(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`executing`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Fetched content`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`pending`})})}},BZ=tc({query:J(),includePattern:J().optional(),excludePattern:J().optional(),explanation:J().optional()}),VZ={displayName:`FileSearch`,getHeaderParams(e){try{return`pattern: "${e?.query||`[no pattern]`}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=BZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=[`pattern: "${i.query}"`];i.includePattern&&a.push(`path: "${i.includePattern}"`),i.excludePattern&&a.push(`exclude: "${i.excludePattern}"`);let o=a.join(`, `);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:o,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error searching files`})]}):t===`executing`?(0,X.jsx)(PK,{name:`Search`,params:o,status:`executing`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:o,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Search`,params:o,status:`pending`})})}};function HZ(e){let t=[];return e.pattern&&t.push(`pattern: "${e.pattern}"`),e.path&&t.push(`path: "${e.path}"`),t.length>0?t.join(`, `):`[no pattern]`}const UZ={displayName:`Search`,getHeaderParams(e){try{return HZ(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=HZ(e);if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error matching files`})]});if(t===`executing`)return(0,X.jsx)(PK,{name:`Search`,params:r,status:`executing`,showSpinner:!0});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Search`,params:r,status:`pending`})});let i=n.data.files??[],a=i.slice(0,10),o=i.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`success`}),(0,X.jsx)(FK,{children:n.summary}),i.length>0&&(0,X.jsxs)(IK,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more file`,o===1?``:`s`]})]})]})}};function WZ(e){let t=e,n=[];t.pattern&&n.push(`pattern: "${t.pattern}"`),t.path&&n.push(`path: "${t.path}"`);let r=t.outputMode||e.output_mode;return r&&n.push(`outputMode: "${r}"`),t.glob&&n.push(`glob: "${t.glob}"`),t[`-i`]&&n.push(`case-insensitive`),n.length>0?n.join(`, `):`[no pattern]`}const GZ={displayName:`Search`,getHeaderParams(e){try{return WZ(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=WZ(e);if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error searching content`})]});if(t===`executing`)return(0,X.jsx)(PK,{name:`Search`,params:r,status:`executing`,showSpinner:!0});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Search`,params:r,status:`pending`})});let i=n.data.matches??[],a=i.slice(0,10),o=i.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`success`}),(0,X.jsx)(FK,{children:n.summary}),i.length>0&&(0,X.jsxs)(IK,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more match`,o===1?``:`es`]})]})]})}},KZ=tc({query:J(),command:J().optional(),explanation:J().optional()}),qZ={displayName:`Search`,getHeaderParams(e){try{return`"${e?.query||``}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=KZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=`"${r.data.query}"`;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing semantic search`})]}):t===`executing`?(0,X.jsx)(PK,{name:`Search`,params:i,status:`executing`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:i,status:`success`}),(0,X.jsx)(FK,{children:`Completed`})]})}},JZ=tc({searchTerm:J(),query:J().optional(),explanation:J().optional()}),YZ={displayName:`WebSearch`,getHeaderParams(e){try{return`"${e?.searchTerm||e?.search_term||e?.query||`[no query]`}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=JZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`WebSearch`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.searchTerm||i.query||``,o=`"${a.length>40?a.substring(0,37)+`...`:a}"`;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`WebSearch`,params:o,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing web search`})]}):t===`executing`?(0,X.jsx)(PK,{name:`WebSearch`,params:o,status:`executing`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`WebSearch`,params:o,status:`success`}),(0,X.jsx)(FK,{children:`Found results`})]})}},XZ=tc({shellId:J(),filter:J().optional()}),ZZ={displayName:`TerminalOutput`,getHeaderParams(e){try{let t=e,n=[`id: ${t.shellId||``}`];return t.filter&&n.push(`filter: ${t.filter}`),n.join(`, `)}catch{return`[unknown]`}},renderUI(e,t,n){let r=XZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`pending`})})}},QZ=tc({shellId:J()}),$Z={displayName:`KillShell`,getHeaderParams(e){try{return`id: ${e.shellId||``}`}catch{return`[unknown]`}},renderUI(e,t,n){let r=QZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`pending`})})}};function eQ(e,t,n){let r=n?100:t,i=e.split(`
12648
- `).filter(Boolean);return i.length<=r?{lines:i,isTruncated:!1,hiddenCount:0}:{lines:i.slice(0,r),isTruncated:!0,hiddenCount:i.length-r}}function tQ(e){return`${(e/1e3).toFixed(1)}s`}function nQ({command:e,toolCallId:t,executionResult:n}){let{agentStatus:r,activeToolOutputs:i}=LZ(),[a]=(0,Z.useState)(Date.now()),[o,s]=(0,Z.useState)(0),[c,l]=(0,Z.useState)(!1),u=!n&&(r===Sl.Streaming||r===Sl.ExecutingTool),d=i[t]||``,f=n?.output||``,p=u?d:f,m=(0,Z.useDeferredValue)(p),h=p!==m;(0,Z.useEffect)(()=>{if(u){let e=setInterval(()=>{s(Date.now()-a)},1e3);return()=>clearInterval(e)}else n&&s(n.duration??0);return()=>{}},[u,a,n]);let{lines:g,isTruncated:_,hiddenCount:v}=(0,Z.useMemo)(()=>eQ(m,7,c),[m,c]),y=!u&&n!==void 0&&(_||c),{isFocused:b}=cI({id:`bash-tool-${t}`,isActive:y});sI((e,t)=>{b&&t.ctrl&&e===`o`&&l(e=>!e)},{isActive:b&&y});let x=e,S=n?.exitCode??0,C=n?.status===`error`||S!==0,w=u?`pending`:C?`error`:`success`;if(u&&g.length===0)return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:w,showSpinner:!0}),(0,X.jsx)(FK,{color:`gray`,children:`Running…`})]});if(u&&g.length>0){let e=o>0?` (${tQ(o)})`:``;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:w,showSpinner:!0}),(0,X.jsxs)(IK,{children:[g.map((e,t)=>(0,X.jsx)($,{children:e},t)),_&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,v,` more line`,v===1?``:`s`,e]}),h&&(0,X.jsx)($,{dimColor:!0,children:`Processing output...`})]})]})}if(n){let e=!f&&(n.duration??0)===0,t=AK(n.duration??0),r=e?`exit ${S}`:`exit ${S} (${t})`,i=g.length>0;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:w}),i&&(0,X.jsxs)(IK,{children:[C&&(0,X.jsx)($,{color:`red`,dimColor:!0,children:`Error:`}),g.map((e,t)=>(0,X.jsx)($,{color:C?`red`:void 0,dimColor:!0,children:e},t)),_&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,v,` `,c?`more `:``,`line`,v===1?``:`s`,c?``:` (ctrl+o to expand)`]})]}),(0,X.jsx)(FK,{color:C?`red`:`gray`,children:r})]})}return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:`pending`})})}const rQ=tc({command:J(),explanation:J().optional(),runInBackground:qK,shellId:J().optional(),interactiveMode:qK,timeout:Gc().optional()});function iQ({rawInput:e,status:t,parsedResult:n}){let r=rQ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:``,paramsLanguage:`bash`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.command||``,o=i.timeout?` (timeout: ${(i.timeout/1e3).toFixed(0)}s)`:``;if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:a,paramsLanguage:`bash`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:a,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:a,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]});if(n?.data?.timedOut)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:`${a}${o}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(FK,{children:`Running in the background`})]});if(n?.runInBackground)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:`${a}${o}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]});let s=e?.id||`unknown`,c=n?.data;return(0,X.jsx)(nQ,{command:`${a}${o}`,toolCallId:s,executionResult:c})}const aQ={read_file:Vq,edit:Lq,list_dir:zq,delete_file:Aq,upload_image:Wq,grep:GZ,glob:UZ,file_search:VZ,semantic_search_server:qZ,web_search:YZ,fetch_url:zZ,bash:{displayName:`Bash`,getHeaderParams(e){try{return e?.command||`[no command]`}catch{return`[unknown]`}},renderUI(e,t,n){return(0,X.jsx)(iQ,{rawInput:e,status:t,parsedResult:n})}},bash_output:ZZ,kill_shell:$Z,navigate_to:xq,new_tab:Cq,close_tab:pq,switch_active_tab:Oq,refresh_tab:Eq,get_tab_content:yq,computer:hq,get_interactive_elements:_q,perform_interactive_element_action:Tq,ask_user_question:YK,enter_plan_mode:XK,exit_plan_mode:aq,subagent:cq,hand_off_to_main:oq,todo_write:dq,get_diagnostics:Kq};function oQ(e){let t=e.toolUseRequest;return t?(Array.isArray(t)?t:[t]).map(e=>{let t=e;return{name:t.name??``,input:t.input??{}}}).filter(e=>e.name):[]}function sQ(e,t=4){let n=[];for(let r of e){if(n.length>=t)break;for(let e of oQ(r)){if(n.length>=t)break;let r=aQ[e.name];if(!r)continue;let i=``;try{i=r.getHeaderParams(e.input)}catch{}if(!i)continue;let a=r.displayName??e.name;n.push({label:a,detail:i})}}return n}const cQ=(0,Z.memo)(({counts:e,segments:t})=>{let{colors:n}=RL(),r=(0,Z.useMemo)(()=>{let t=[];return e.toolUses>0&&t.push(`${e.toolUses} tool ${e.toolUses===1?`use`:`uses`}`),e.responses>0&&t.push(`${e.responses} ${e.responses===1?`response`:`responses`}`),t.length===0?`Conversation compacted`:t.join(`, `)+` compacted`},[e]),i=(0,Z.useMemo)(()=>sQ(t),[t]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:n.textMuted,children:`⟐`}),(0,X.jsx)($,{color:n.textMuted,dimColor:!0,children:r})]}),i.map((e,t)=>(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:2,children:(0,X.jsxs)($,{color:n.textMuted,dimColor:!0,children:[`⎿ `,e.label,` `,e.detail]})},t))]})});cQ.displayName=`CompactedPlaceholder`;const lQ=(0,Z.createContext)(null);function uQ(){let e=(0,Z.use)(lQ);if(!e)throw Error(`useUpdate must be used within UpdateProvider`);return e}function dQ({children:e,configService:t}){let[n,r]=(0,Z.useState)(null),i=(0,Z.useMemo)(()=>t.get(`autoUpdate`)!==!1,[t]);(0,Z.useEffect)(()=>{let e=!0,t=()=>{jj(PA).then(t=>{e&&r(e=>e?.latestVersion===t?.latestVersion?e:t)}).catch(()=>{})};t();let n=setInterval(t,6e4);return()=>{e=!1,clearInterval(n)}},[]);let a=(0,Z.useMemo)(()=>({updateInfo:n,autoUpdate:i}),[n,i]);return(0,X.jsx)(lQ.Provider,{value:a,children:e})}const fQ=(0,Z.createContext)(null),pQ=()=>{let e=(0,Z.use)(fQ);if(!e)throw Error(`${pQ.name} must be used within a ${mQ.name}`);return e};function mQ({children:e}){let[t,n]=(0,Z.useState)({columns:process.stdout.columns-8,rows:process.stdout.rows}),r=(0,Z.useCallback)(()=>{n({columns:process.stdout.columns-8,rows:process.stdout.rows})},[]);(0,Z.useLayoutEffect)(()=>(process.stdout.on(`resize`,r),()=>{process.stdout.off(`resize`,r)}),[r]);let i=(0,Z.useMemo)(()=>({width:t.columns,height:t.rows}),[t.columns,t.rows]);return(0,X.jsx)(fQ.Provider,{value:i,children:e})}function hQ(){let{height:e}=pQ();return Math.max(0,e-3)}let gQ=function(e){return e.Models=`models`,e.CreateConversation=`create-conversation`,e.GetConversation=`get-conversation`,e.Grep=`grep`,e.FileSearch=`file-search`,e.ListDir=`list-dir`,e.ReadFile=`read-file`,e.DeleteFile=`delete-file`,e.EditFile=`edit-file`,e.RunTerminal=`run-terminal`,e.GetTerminalOutput=`get-terminal-output`,e.MCPTool=`mcp-tool`,e}({});function _Q(e){return PL({queryKey:[gQ.Models],queryFn:async()=>{try{return(await e.listLLMModels())?.result??[]}catch{return[]}},staleTime:300*1e3,retry:1,refetchOnMount:`always`,refetchOnWindowFocus:!1})}const vQ=/\/var\/folders\/.*\/T\/TemporaryItems\/.*screencaptureui.*\//i,yQ=`.abacusai/screenshots`;function bQ(e){return vQ.test(e)}function xQ(e){try{let t=SQ(e.replace(/\\ /g,` `));if(!g(t))return null;let n=C.resolve(process.cwd(),yQ);g(n)||_(n,{recursive:!0});let r=C.basename(t),i=C.join(n,r);return h(t,i),i}catch{return null}}function SQ(e){if(e.startsWith(`file://`))try{return decodeURIComponent(e.slice(7))}catch{return e.slice(7)}return e}let CQ;function wQ(){if(CQ!==void 0)return CQ;try{return c(`which`,[`wl-paste`],{stdio:`ignore`}),CQ=`wl-paste`,`wl-paste`}catch{}try{return c(`which`,[`xclip`],{stdio:`ignore`}),CQ=`xclip`,`xclip`}catch{}return CQ=null,null}async function TQ(){try{if(process.platform===`darwin`){let e=c(`osascript`,[`-e`,`clipboard info`],{encoding:`utf8`,timeout:2e3});return/PNGf|JPEG|TIFF|GIF/i.test(e)}if(process.platform===`win32`)return c(`powershell`,[`-NoProfile`,`-Command`,`Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::ContainsImage()`],{encoding:`utf8`,timeout:2e3}).trim().toLowerCase()===`true`;let e=wQ();if(e===`wl-paste`)return c(`wl-paste`,[`--list-types`],{encoding:`utf8`,timeout:2e3}).includes(`image/`);if(e===`xclip`)return c(`xclip`,[`-selection`,`clipboard`,`-t`,`TARGETS`,`-o`],{encoding:`utf8`,timeout:2e3}).includes(`image/`)}catch{}return!1}async function EQ(e){try{let t=C.resolve(e,yQ);g(t)||_(t,{recursive:!0});let n=Date.now(),r=C.join(t,`clipboard-${n}.png`);if(process.platform===`darwin`)c(`osascript`,[`-e`,`
12645
+ `);n.procedure=TX(e,n.contract)}return{path:n.path,procedure:n.procedure}}}},RX=class extends FX{constructor(e,t={}){let n=new mY(new lY(t)),r=new LX(t),i=new IX(n);super(e,r,i,t)}},zX=class{socketServer;socketPath;editorState={file:void 0,startLine:void 0,endLine:void 0};onEditorStateCallback=null;pendingDecisions=new Map;constructor(){let e=S.join(t.homedir(),ke.configDirName,`cli`);this.socketPath=S.join(e,`${process.pid}.sock`)}getEditorState(){return{...this.editorState}}onEditorChange(e){this.onEditorStateCallback=e}waitForDecision(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Aborted`));return}let i=()=>{t?.removeEventListener(`abort`,a),this.pendingDecisions.delete(e)},a=()=>{i(),r(Error(`Aborted`))};t?.addEventListener(`abort`,a,{once:!0}),this.pendingDecisions.set(e,{resolve:e=>{i(),n(e)},cleanup:i})})}async start(){let e=S.dirname(this.socketPath);f.existsSync(e)||f.mkdirSync(e,{recursive:!0});let t=NX(EY),n=t.router({editorStateChanged:t.editorStateChanged.handler(async({input:e})=>(this.editorState={file:e.file??void 0,startLine:e.startLine,endLine:e.endLine},this.onEditorStateCallback?.(this.editorState),{ok:!0})),toolDecision:t.toolDecision.handler(async({input:e})=>{let t=this.pendingDecisions.get(e.toolId);return t&&t.resolve(e.decision),{ok:!0}})});this.socketServer=await ZY(this.socketPath,new RX(n))}dispose(){for(let[,e]of this.pendingDecisions)e.cleanup();this.pendingDecisions.clear(),this.socketServer?.dispose(),this.socketServer=void 0}},BX=class{client=null;disposeSocket=null;currentFile=void 0;selectionStartLine=void 0;selectionEndLine=void 0;onFileChangeCallback=null;constructor(e){this.pushServer=e}findSocketPath(){let e=process.env[ke.socketEnvVar];if(e&&p.existsSync(e))return e;try{let e=C.join(n.homedir(),ke.configDirName,ke.ideDirName),t=p.readdirSync(e).filter(e=>e.endsWith(`.sock`));if(t.length===0)return null;let r=null;for(let n of t){let t=C.join(e,n);try{let e=p.statSync(t);(!r||e.mtimeMs>r.mtime)&&(r={path:t,mtime:e.mtimeMs})}catch{}}if(r&&p.existsSync(r.path))return r.path}catch{}return null}async connect(){try{let e=this.findSocketPath();if(!e)return!1;let t=await eX(e,{timeoutMs:2e3});this.client=$J(t.link),this.disposeSocket=()=>t.dispose(),await this.client.register({cliSocketPath:this.pushServer.socketPath,pid:process.pid});let n=this.pushServer.getEditorState();return this.currentFile=n.file,this.selectionStartLine=n.startLine,this.selectionEndLine=n.endLine,this.pushServer.onEditorChange(e=>{this.currentFile=e.file,this.selectionStartLine=e.startLine,this.selectionEndLine=e.endLine,this.onFileChangeCallback?.(e.file,e.startLine,e.endLine)}),!0}catch{return!1}}getCurrentFile(){return this.currentFile}getSelectionRange(){return{startLine:this.selectionStartLine,endLine:this.selectionEndLine}}isConnected(){return this.client!==null}onFileChange(e){this.onFileChangeCallback=e}async showDiff(e){if(!this.client)return!1;try{return(await this.client.showDiff({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async showToolView(e){if(!this.client)return!1;try{return(await this.client.showToolView({...e,cliSocketPath:this.pushServer.socketPath})).success}catch{return!1}}async notifyDiffDecision(e){if(!this.client)throw Error(`Not connected to extension`);await this.client.notifyDiffDecision(e)}async openPlanFile(e){if(!this.client)throw Error(`Not connected to extension`);return{opened:(await this.client.openFile({file:e})).success}}async getDiagnostics(e){if(!this.client)throw Error(`Not connected to extension`);return this.client.getDiagnostics({...e&&{files:e}})}dispose(){this.disposeSocket?.(),this.disposeSocket=null,this.client=null,this.currentFile=void 0,this.selectionStartLine=void 0,this.selectionEndLine=void 0,this.onFileChangeCallback=null}};const VX=(0,Z.createContext)(null);function HX(){let e=(0,Z.use)(VX);if(!e)throw Error(`useExtensionFile must be used within ExtensionFileProvider`);return e}function UX({children:e,initialFile:t}){let[n,r]=(0,Z.useState)(t),[i,a]=(0,Z.useState)(void 0),[o,s]=(0,Z.useState)(void 0),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{let e=!1;return(async()=>{let t=new zX;try{await t.start()}catch{}if(e){t.dispose();return}p.current=t,d(t),t.onEditorChange(e=>{r(e.file),a(e.startLine),s(e.endLine)});for(let n of[0,...[500,1e3,2e3,3e3,4e3]]){if(e||(n>0&&await new Promise(e=>setTimeout(e,n)),e))return;try{let n=new BX(t);if(await n.connect()){if(e){n.dispose();return}let i=t.getEditorState();r(i.file),a(i.startLine),s(i.endLine),n.onFileChange((e,t,n)=>{r(e),a(t),s(n)}),f.current=n,l(n);return}}catch{}}})(),()=>{e=!0,f.current&&(f.current.dispose(),f.current=null,l(null)),p.current&&(p.current.dispose(),p.current=null,d(null))}},[]),(0,X.jsx)(VX.Provider,{value:{currentFile:n,selectionStartLine:i,selectionEndLine:o,connection:c,pushServer:u},children:e})}const WX=(0,Z.createContext)(null);function GX({children:e}){let[t,n]=(0,Z.useState)(`idle`),r=(0,Z.useCallback)(()=>n(`upload`),[]),i=(0,Z.useCallback)(()=>n(`download`),[]),a=(0,Z.useCallback)(()=>n(`idle`),[]),o=(0,Z.useMemo)(()=>({activity:t,setActivity:n,startUpload:r,startDownload:i,stopActivity:a}),[t,r,i,a]);return(0,X.jsx)(WX.Provider,{value:o,children:e})}function KX(){let e=(0,Z.use)(WX);if(!e)throw Error(`useNetworkActivity must be used within NetworkActivityProvider`);return e}let qX=function(e){return e.ESC=`\x1B`,e.BEL=`\x07`,e.ST=`\x1B\\`,e.ENABLE_FOCUS_REPORTING=`${e.ESC}[?1004h`,e.DISABLE_FOCUS_REPORTING=`${e.ESC}[?1004l`,e.FOCUS_IN=`${e.ESC}[I`,e.FOCUS_OUT=`${e.ESC}[O`,e.SHOW_CURSOR=`${e.ESC}[?25h`,e.HIDE_CURSOR=`${e.ESC}[?25l`,e.SET_TITLE=`${e.ESC}]2;`,e.RESET_SGR=`${e.ESC}[0m`,e.SOFT_RESET=`${e.ESC}[!p`,e.HARD_RESET=`${e.ESC}c`,e.ENABLE_BRACKETED_PASTE=`${e.ESC}[?2004h`,e.DISABLE_BRACKETED_PASTE=`${e.ESC}[?2004l`,e.PASTE_MODE_PREFIX=`${e.ESC}[200~`,e.PASTE_MODE_SUFFIX=`${e.ESC}[201~`,e.DIM=`${e.ESC}[2m`,e.BOLD=`${e.ESC}[1m`,e.RESET_BOLD=`${e.ESC}[22m`,e.ITALIC=`${e.ESC}[3m`,e.RESET_ITALIC=`${e.ESC}[23m`,e.STRIKETHROUGH=`${e.ESC}[9m`,e.RESET_STRIKETHROUGH=`${e.ESC}[29m`,e.UNDERLINE=`${e.ESC}[4m`,e.RESET_UNDERLINE=`${e.ESC}[24m`,e}({});function JX(e){return`${qX.ESC}]9;\n\n${e}${qX.BEL}`}function YX(e,t){return`${qX.ESC}]777;notify;${e};${t}${qX.BEL}`}function XX(e,t){let n=Math.floor(Math.random()*1e4),r=`${qX.ESC}]99;i=${n}:d=0:p=title;${e}${qX.ST}`,i=`${qX.ESC}]99;i=${n}:p=body;${t}${qX.ST}`,a=`${qX.ESC}]99;i=${n}:d=1:a=focus;${qX.ST}`;return r+i+a}function ZX(e,t){let n=`9;4;${e};${t===void 0?0:Math.max(0,Math.min(100,Math.round(t)))}`;return`${qX.ESC}]${n}${qX.BEL}${qX.ESC}]${n}${qX.ST}`}function QX(e){return e.replaceAll(`\x1B`,``).replaceAll(`\x07`,``).replaceAll(`
12646
+ `,` `).replaceAll(`\r`,` `).replaceAll(`;`,`:`).trim().slice(0,120)}function $X(e){return`${qX.ESC}]${e}${qX.BEL}${qX.ESC}]${e}${qX.ST}`}function eZ(){return $X(`1337;Progress=`)}function tZ(e){return $X(`1337;Progress=${e}`)}function nZ(e,t){let n=Math.max(0,Math.min(100,Math.round(e))),r=t?QX(t):``;return r?$X(`1337;Progress=${n};${r}`)+$X(`1337;Progress=message=${r};percent=${n}`):$X(`1337;Progress=${n}`)}function rZ({onlyFirst:e=!1}={}){return RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:`g`)}const iZ=rZ();function aZ(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(iZ,``)}const oZ=[`pycharm`,`intellij`,`webstorm`,`phpstorm`,`rubymine`,`clion`,`goland`,`rider`,`datagrip`,`appcode`,`dataspell`,`aqua`,`gateway`,`fleet`,`jetbrains`,`androidstudio`];function sZ(e){if(U.env.CURSOR_TRACE_ID)return e?.debug?.(`Detected Cursor terminal via CURSOR_TRACE_ID`),`cursor`;if(U.env.VSCODE_GIT_ASKPASS_MAIN?.includes(`/.cursor-server/`))return e?.debug?.(`Detected Cursor terminal via VSCODE_GIT_ASKPASS_MAIN`),`cursor`;if(U.env.VSCODE_GIT_ASKPASS_MAIN?.includes(`/.windsurf-server/`))return e?.debug?.(`Detected Windsurf terminal`),`windsurf`;let t=U.env.__CFBundleIdentifier?.toLowerCase();if(t?.includes(`vscodium`))return`codium`;if(t?.includes(`windsurf`))return`windsurf`;if(t?.includes(`com.google.android.studio`))return`androidstudio`;if(t){for(let e of oZ)if(t.includes(e))return e}if(U.env.VisualStudioVersion)return`visualstudio`;if(U.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`)return`pycharm`;if(U.env.TERM===`xterm-ghostty`)return`ghostty`;if(U.env.TERM?.includes(`kitty`))return`kitty`;if(U.env.WEZTERM_PANE)return`WezTerm`;if(U.env.ITERM_SESSION_ID)return`iTerm.app`;if(U.env.TERM_PROGRAM===`Apple_Terminal`)return`Apple_Terminal`;if(U.env.TERM_PROGRAM)return U.env.TERM_PROGRAM;if(U.env.STY)return`screen`;if(U.env.KONSOLE_VERSION)return`konsole`;if(U.env.GNOME_TERMINAL_SERVICE)return`gnome-terminal`;if(U.env.XTERM_VERSION)return`xterm`;if(U.env.VTE_VERSION)return`vte-based`;if(U.env.TERMINATOR_UUID)return`terminator`;if(U.env.KITTY_WINDOW_ID)return`kitty`;if(U.env.ALACRITTY_LOG)return`alacritty`;if(U.env.TILIX_ID)return`tilix`;if(U.env.WT_SESSION)return`windows-terminal`;if(U.env.SESSIONNAME&&U.env.TERM===`cygwin`)return`cygwin`;if(U.env.MSYSTEM)return U.env.MSYSTEM.toLowerCase();if(U.env.ConEmuANSI||U.env.ConEmuPID||U.env.ConEmuTask)return`conemu`;if(U.env.WSL_DISTRO_NAME)return`wsl-${U.env.WSL_DISTRO_NAME}`;if(U.env.SSH_CONNECTION||U.env.SSH_CLIENT||U.env.SSH_TTY)return`ssh-session`;if(U.env.TERM){let e=U.env.TERM;return e.includes(`alacritty`)?`alacritty`:e.includes(`rxvt`)?`rxvt`:e.includes(`termite`)?`termite`:U.env.TERM}return U.stdout.isTTY?(e?.debug?.(`Could not detect terminal type`),null):(e?.debug?.(`Non-interactive terminal detected`),`non-interactive`)}function cZ(){switch(sZ()){case`Apple_Terminal`:return`Option+Enter`;case`cursor`:case`windsurf`:case`vscode`:case`codium`:case`iTerm.app`:case`ghostty`:case`WezTerm`:case`kitty`:case`alacritty`:return`Shift+Enter`;default:return`backslash (\\) + Enter`}}function lZ(e){U.stdout.isTTY&&U.stdout.write(e)}function uZ(e,t){lZ(JX(e?`${e}:\n${t}`:t))}function dZ(e,t){lZ(XX(e,t))}function fZ(e,t){lZ(YX(e,t))}function pZ(e,t){lZ(qX.BEL)}async function mZ(e){let{title:t=`Abacus.AI`,message:n}=e;switch(sZ()){case`iTerm.app`:uZ(t,n);break;case`kitty`:dZ(t,n);break;case`ghostty`:fZ(t,n);break;case`WezTerm`:uZ(t,n);break;default:U.platform===`win32`&&pZ(t,n);break}}async function hZ(e,t){await mZ({...t,message:e,title:t?.title??`Action Required`})}async function gZ(e,t){await mZ({...t,message:e,title:t?.title??`Task Complete`})}const _Z=(0,Z.createContext)(null),vZ=()=>{let e=(0,Z.use)(_Z);if(!e)throw Error(`useNotification must be used within NotificationProvider`);return e},yZ=({children:e})=>{let{isFocused:t}=lI(),n=(0,Z.useCallback)(async(e,n)=>{t||await mZ({message:e,title:n})},[t]),r=(0,Z.useCallback)(async e=>{t||await hZ(e)},[t]),i=(0,Z.useCallback)(async e=>{t||await gZ(e)},[t]),a=(0,Z.useMemo)(()=>({notifyIfUnfocused:n,notifyActionRequired:r,notifyTaskComplete:i}),[n,r,i]);return(0,X.jsx)(_Z.Provider,{value:a,children:e})},bZ=(0,Z.createContext)(null),xZ=()=>{let e=(0,Z.use)(bZ);if(!e)throw Error(`useApiClient must be used within ApiClientProvider`);return e},SZ=(0,Z.memo)(({children:e,client:t,authManager:n})=>{let[r,i]=(0,Z.useState)(!1),a=(0,Z.useCallback)(()=>i(!1),[]),o=(0,Z.useMemo)(()=>({apiClient:t,authManager:n,authExpired:r,setAuthExpired:i,clearAuthExpired:a}),[r,t,n,a]);return(0,X.jsx)(bZ.Provider,{value:o,children:e})});SZ.displayName=`ApiClientProvider`;const CZ=[`conemu`,`ghostty`,`windows-terminal`,`WezTerm`,`iTerm.app`];let wZ=null;function TZ(e){if(!e||!U.stdout.isTTY)return!1;if(CZ.includes(e))return!0;let t=e.toLowerCase();return t.includes(`iterm`)||t.includes(`ghostty`)||t.includes(`wezterm`)||t.includes(`conemu`)}function EZ(e){U.stdout.write(e)}function DZ(e){switch(e){case`indeterminate`:return 3;case`error`:return 2;case`warning`:return 4;default:return 1}}function OZ(){wZ&&=(clearTimeout(wZ),null)}function kZ(){OZ(),wZ=setTimeout(()=>{AZ()},500)}function AZ(){let e=sZ();TZ(e)&&(EZ(ZX(0)),e?.toLowerCase().includes(`iterm`)&&EZ(eZ()))}function jZ(e,t){if(e instanceof Promise)return NZ(e,t);let n=e,r=sZ();if(!TZ(r))return;OZ();let i=0;n.percentage===void 0?n.total!==void 0&&n.current!==void 0&&n.total>0&&(i=n.current/n.total*100):i=n.percentage;let a=n.state??`default`;EZ(ZX(DZ(a),i)),r?.toLowerCase().includes(`iterm`)&&(a===`indeterminate`?EZ(tZ(2)):(EZ(nZ(i,n.label)),i>=100&&EZ(tZ(1)))),(a===`error`||i>=100)&&kZ()}function MZ(){OZ(),AZ()}async function NZ(e,t){let{label:n,hideOnComplete:r=!0}=t??{};jZ({state:`indeterminate`,label:n});try{let t=await e;return jZ({percentage:100,state:`default`,label:n}),r&&kZ(),t}catch(e){throw jZ({percentage:100,state:`error`,label:n}),r&&kZ(),e}}const PZ=(0,Z.createContext)(null);function FZ(e,t){switch(t.type){case`INIT_SEND`:return[...e.filter(e=>e.temp!==!0),t.userSeg,t.spinnySeg];case`TEXT_DELTA`:{let{segId:n,content:r}=t,i=e.map(e=>e.type===`code_llm_tool_call`&&e.status===`transient`&&!e.toolUseResult?{...e,status:`completed`,parsedResult:{phase:`error`,toolType:Array.isArray(e.toolUseRequest)?e.toolUseRequest[0]?.name??``:e.toolUseRequest?.name??``,data:{},summary:``}}:e).filter(e=>!e.isSpinny);return i.find(e=>e.id===n)?i.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...i,{id:n,status:`transient`,source:`bot`,type:`text`,segment:r}]}case`THINKING_DELTA`:{let{segId:n,content:r,startTime:i}=t;return e.find(e=>e.id===n)?e.map(e=>e.id===n?{...e,segment:(e.segment||``)+r}:e):[...e,{id:n,status:`transient`,source:`bot`,type:`thinking`,isSpinny:!0,segment:r,thinkingStartTime:i}]}case`THINKING_COMPLETE`:return e.map(e=>e.id===t.segId?{...e,status:`completed`,isSpinny:!1,thinkingEndTime:t.endTime}:e);case`TOOL_DISPLAY_DATA`:return e.map(e=>e.id===t.toolCallId?{...e,toolDisplayData:{...e.toolDisplayData,...t.data}}:e);case`TOOL_REQUESTED`:{let{textSegId:n,toolSeg:r}=t,i;return i=n?e.filter(e=>!e.isSpinny).map(e=>e.id===n?{...e,status:`completed`}:e):e.filter(e=>!e.isSpinny),[...i,r]}case`TOOL_EXECUTION_COMPLETE`:{let{toolCallId:n,rawResult:r,parsedResult:i,spinnySeg:a}=t;return[...e.map(e=>e.id===n?{...e,status:`completed`,toolUseResult:r,...i!==void 0&&{parsedResult:i}}:e),a]}case`TOOL_USER_MESSAGE`:return[...e,t.seg];case`TEXT_COMPLETED`:return e.map(e=>e.id===t.segId?{...e,status:`completed`}:e);case`FINALIZE`:{let n=e;return t.textSegId&&(n=n.map(e=>e.id===t.textSegId?{...e,status:`completed`}:e)),n.filter(e=>!e.isSpinny)}case`ADD_NOTIFICATION`:{let n=t.seg,r=e[e.length-1];if(r&&r.type===`code_llm_notification`&&r.message===n.message&&r.severity===n.severity){let t=[...e];return t[t.length-1]={...r,flashKey:(r.flashKey??0)+1},t}return[...e,n]}case`ERROR`:return[...e.filter(e=>!e.isSpinny),t.errorSeg];case`REMOVE_USER_SEG`:return e.filter(e=>e.id!==t.userSegId);case`CLEAR`:return[];case`LOAD`:return t.segments;case`REMOVE_TEMP`:return e.some(e=>e.temp===!0)?e.filter(e=>e.temp!==!0):e;default:return e}}function IZ(e){switch(e.type){case`text`:return{id:e.id,status:`completed`,source:e.source,type:`text`,segment:e.content};case`thinking`:return{id:e.id,status:`completed`,source:`bot`,type:`thinking`,segment:e.content,isSpinny:e.isSpinny,...e.title!==void 0&&{title:e.title}};case`tool_call`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:e.toolUseRequest,toolUseResult:e.toolUseResult??{id:e.toolUseRequest.id,content:` `},...e.parsedResult!==void 0&&{parsedResult:e.parsedResult},...e.toolDisplayData!==void 0&&{toolDisplayData:e.toolDisplayData}};case`notification`:return{id:e.id,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:e.severity,...e.actions!==void 0&&{actions:e.actions}};case`tool_group`:return{id:e.id,status:`completed`,source:`bot`,type:`text`,segment:e.summary}}}const LZ=(0,Z.memo)(({children:e,apiClient:t,configService:n,agentArgs:r})=>{let{agentMode:i,setAgentMode:a}=$K(),o=(0,Z.useRef)(i),{notifyActionRequired:s,notifyTaskComplete:c}=vZ(),{startUpload:l,startDownload:u,stopActivity:d}=KX(),{authManager:f,setAuthExpired:p}=xZ(),{connection:m,pushServer:h}=HX(),g=(0,Z.useRef)(m),_=(0,Z.useRef)(h);(0,Z.useEffect)(()=>{g.current=m},[m]),(0,Z.useEffect)(()=>{_.current=h},[h]);let[v,y]=(0,Z.useState)(Sl.Idle),[b,x]=(0,Z.useReducer)(FZ,[]),S=(0,Z.useRef)(new Map),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)([]),[A,j]=(0,Z.useState)(null),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(!0),[I,L]=(0,Z.useState)(!0),R=(0,Z.useRef)(!0),z=(0,Z.useRef)(null),B=(0,Z.useRef)(Sl.Idle),V=(0,Z.useCallback)(e=>{B.current=e,y(e)},[]);(0,Z.useEffect)(()=>()=>{z.current&&clearTimeout(z.current)},[]);let H=(0,Z.useMemo)(()=>({}),[]),[ee,te]=(0,Z.useState)(null),ne=process.cwd(),re=(0,Z.useMemo)(()=>new Pk(async e=>{let t=g.current,n=e,r=null;if(t&&_.current&&e.type===`edit_file`){let i=e.tool.id,a=S.current.get(i),o=e.tool.input??{},s=o.targetFile??e.filePath??``,c=a?.originalContent??e.originalContent??``,l=a?.newContent??e.newContent??o.codeEdit??``;s&&(c||l)&&await t.showDiff({filePath:s,originalContent:c,modifiedContent:l,toolId:i})&&(n={...e,diffShownInEditor:!0},r=s)}if(t&&e.type===`exit_plan_mode`&&e.planFilePath){let n=e.tool.id;if(_.current&&await t.showToolView({filePath:e.planFilePath,toolKey:n})){let e=await _.current.waitForDecision(n);return e===`allowAlways`?`allowAlways`:e}await t.openPlanFile(e.planFilePath).catch(()=>{})}let i=await new Promise(e=>{D({request:n,resolve:t=>{D(null),V(t===`accept`||t===`allowAlways`||typeof t==`object`&&t.type===`accept_with_message`||typeof t==`object`&&t.type===`question_answers`?Sl.ExecutingTool:Sl.Submitted);let n=setImmediate(()=>e(t));typeof n?.unref==`function`&&n.unref()}}),V(Sl.WaitingForToolPermission),s(`Abacus.AI is waiting for your input`)});if(r&&t){let e=i===`reject`||typeof i==`object`&&i.type===`reject_with_message`;t.notifyDiffDecision({targetFile:r,decision:e?`reject`:`accept`}).catch(()=>{})}return i}),[s,V]),ie=(0,Z.useRef)(null);function ae(){return new Mk({allowedDirectories:[ne,...r?.[`add-dir`]?.map(e=>C.isAbsolute(e)?e:C.resolve(ne,e))??[]],primaryWorkspace:ne,apiClient:t,mode:o.current,permissionProvider:re,config:n,diagnosticsProvider:{getDiagnostics:async e=>{let t=g.current;return t?t.getDiagnostics(e):[]}},cliAllowedTools:r?.[`allowed-tools`],cliDisallowedTools:r?.[`disallowed-tools`]})}ie.current||=ae();let oe=ie.current;(0,Z.useEffect)(()=>{o.current=i,oe.setMode(i)},[i,oe]),(0,Z.useEffect)(()=>{r?.conversationId&&fe(r.conversationId)},[]),(0,Z.useEffect)(()=>{switch(v){case Sl.Submitted:case Sl.Streaming:jZ({state:`indeterminate`,label:`Processing`});break;case Sl.ExecutingTool:jZ({state:`indeterminate`,label:`Executing tools`});break;case Sl.WaitingForToolPermission:MZ();break;case Sl.Idle:MZ();break}},[v]);let se=(0,Z.useCallback)((e,t=`info`,n=!1)=>{x({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:t,message:e,temp:n}})},[]),ce=(0,Z.useCallback)(()=>{x({type:`CLEAR`}),T(null),V(Sl.Idle),te(null),S.current.clear(),ie.current=ae()},[t,ne,re]),le=(0,Z.useCallback)(()=>{x({type:`CLEAR`})},[]),U=(0,Z.useCallback)(()=>{x({type:`REMOVE_TEMP`})},[]),ue=(0,Z.useCallback)(()=>{let e=oe.dequeue();oe.clearQueue(),k([]),e!==null&&j(e),oe.stop(),D(null),V(Sl.Idle)},[oe,V]),de=(0,Z.useCallback)(()=>{E&&E.resolve(`reject`)},[E]),fe=(0,Z.useCallback)(async e=>{V(Sl.LoadingConversation),x({type:`CLEAR`}),T(null),te(e);try{let t=await oe.loadConversation(e);t.title&&T(t.title),t.segments.length>0&&x({type:`LOAD`,segments:t.segments.map(e=>IZ(e))})}catch{se(`Failed to load conversation`,`error`)}finally{V(Sl.Idle)}},[oe,se,V]),pe=(0,Z.useCallback)(async(e,t)=>{await oe.mcp.refresh(),t&&se(`MCP tools refreshed`,`info`,!0)},[oe,se]),me=(0,Z.useCallback)(async({message:e,selectedModel:t,fileAttachments:n})=>{if(!e||v===Sl.LoadingConversation)return;t&&oe.setModel(t);let r=e;if(n&&n.length>0){let e=n.filter(e=>!e.mimeType.startsWith(`image/`));for(let t of e){let e=typeof t.content==`string`?t.content:t.content.toString(`utf-8`);r+=`\n\n<file path="${t.filePath}">\n${e}\n</file>`}}let i=crypto.randomUUID();x({type:`INIT_SEND`,userSeg:{id:i,status:`completed`,source:`user`,type:`text`,segment:e},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),V(Sl.Submitted),l();let o=null,s=null,m,h=g.current,_=h?.getCurrentFile(),y=h?.getSelectionRange();if(h&&_)try{let e=(await h.getDiagnostics([_])).filter(e=>e.severity===`error`||e.severity===`warning`);e.length>0&&(m=e.map(e=>`${e.file}:${e.line}:${e.column} [${e.severity}] ${e.message}`).join(`
12647
+ `))}catch{}let b=()=>new Promise(e=>setImmediate(e));try{let e=0;for await(let t of oe.send(r,{diagnosticIssues:m,currentFile:_??void 0,selectionStartLine:y?.startLine,selectionEndLine:y?.endLine})){switch(t.type){case`text_delta`:{V(Sl.Streaming),d(),u();let e=t.content;o||=crypto.randomUUID(),x({type:`TEXT_DELTA`,segId:o,content:e});break}case`thinking_delta`:{let e=t.content;s||=crypto.randomUUID(),x({type:`THINKING_DELTA`,segId:s,content:e,startTime:Date.now()});break}case`thinking_complete`:s&&=(x({type:`THINKING_COMPLETE`,segId:s,endTime:Date.now()}),null);break;case`tool_display_data`:{let{toolCallId:e,data:n}=t,r=S.current.get(e)??{};S.current.set(e,{...r,...n}),x({type:`TOOL_DISPLAY_DATA`,toolCallId:e,data:n});break}case`tool_requested`:{V(Sl.ExecutingTool),d(),l();let e=t.tool.id,n={id:e,status:`transient`,source:`bot`,type:`code_llm_tool_call`,toolUseRequest:{id:e,name:t.tool.name,input:t.tool.input},toolDisplayData:S.current.get(e)};x({type:`TOOL_REQUESTED`,toolCallId:e,textSegId:o,toolSeg:n}),o=null;break}case`tool_execution_complete`:{d(),u();let e=t.tool.id,{parsedResult:n,...r}=t.result,i={id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Analyzing result`,temp:!0,isSpinny:!0};x({type:`TOOL_EXECUTION_COMPLETE`,toolCallId:e,rawResult:r,...n!==void 0&&{parsedResult:n},spinnySeg:i}),o=null;break}case`notification`:x({type:`ADD_NOTIFICATION`,seg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:t.severity,message:t.message,...t.actions!==void 0&&{actions:t.actions}}});break;case`error`:x({type:`ERROR`,errorSeg:{id:crypto.randomUUID(),status:`completed`,source:`bot`,type:`code_llm_notification`,severity:`error`,message:t.error.message}});break;case`mode_changed`:a(t.mode);break;case`tool_user_message`:x({type:`TOOL_USER_MESSAGE`,seg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:t.message}});break;case`retry`:N({attempt:t.attempt,maxAttempts:t.maxAttempts,delayMs:t.delayMs,isNetworkError:t.isNetworkError});break;case`network_status`:t.online?(z.current&&=(clearTimeout(z.current),null),R.current=!0,F(!0),L(!0),N(null),setTimeout(()=>{if(B.current===Sl.Idle&&oe.getQueue().length>0){let e=oe.dequeue();e&&(k(oe.getQueue()),me({message:e}))}},0).unref?.()):(R.current=!1,F(!1),z.current||=setTimeout(()=>{z.current=null,R.current||L(!1)},3e4));break;case`user_message_dequeued`:x({type:`INIT_SEND`,userSeg:{id:crypto.randomUUID(),status:`completed`,source:`user`,type:`text`,segment:t.content},spinnySeg:{id:crypto.randomUUID(),status:`transient`,source:`bot`,type:`collapsible_component`,title:`Processing request`,temp:!0,isSpinny:!0}}),k(oe.getQueue()),o=null,s=null;break;case`turn_complete`:o&&=(x({type:`TEXT_COMPLETED`,segId:o}),null),k(oe.getQueue());break}e++,(t.type===`tool_requested`||t.type===`tool_execution_complete`||e>=20)&&(e=0,await b())}}catch(e){if(e instanceof Se)f.isEnvAuth()||(p(!0),f.logout()),x({type:`REMOVE_USER_SEG`,userSegId:i}),se(`Session expired — use /login to authenticate again.`,`error`,!0);else{let t=e instanceof Ce?`Unable to connect to API`:e instanceof Error?e.message:`An error occurred`;x({type:`REMOVE_USER_SEG`,userSegId:i}),se(t,`error`,!0)}j(r),oe.clearQueue(),k([])}finally{d(),N(null);let e=oe.getConversationId();e&&te(e),x({type:`FINALIZE`,textSegId:o}),V(Sl.Idle),c(`Abacus.AI completed the task`)}},[oe,v,se,c,l,u,d,a,f,p]),he=(0,Z.useCallback)(e=>{oe.enqueue(e),k(oe.getQueue())},[oe]),ge=(0,Z.useCallback)(()=>{oe.dequeue(),k(oe.getQueue())},[oe]),_e=(0,Z.useCallback)(()=>{oe.clearQueue(),k([])},[oe]),W=(0,Z.useCallback)(()=>{j(null)},[]),ve=(0,Z.useCallback)((e,t)=>oe.addAllowedDirectory(e,t),[oe]),ye=(0,Z.useMemo)(()=>({conversationId:ee,conversationTitle:w,segments:b,segmentsLength:b.length,sendMessage:me,stop:ue,rejectPendingPermission:de,agentStatus:v,clearSegments:ce,clearSegmentsOnly:le,clearTempSegments:U,loadConversation:fe,addNotification:se,mcp:oe.mcp,addAllowedDirectory:ve,pendingToolPermission:E,refreshMcpTools:pe,queuedMessages:O,addToQueue:he,removeFirstFromQueue:ge,clearQueue:_e,dequeuedOnStop:A,clearDequeuedOnStop:W,activeToolOutputs:H,retryState:M,networkOnline:P,debouncedNetworkOnline:I}),[ee,w,b,me,ue,de,v,ce,le,U,fe,se,oe,ve,E,pe,O,he,ge,_e,A,W,H,M,P,I]);return(0,X.jsx)(PZ.Provider,{value:ye,children:e})});LZ.displayName=`AgentProvider`;function RZ(){let e=(0,Z.use)(PZ);if(!e)throw Error(`Agent context not found. Did you forget to wrap your component in <${LZ.name}>?`);return e}const zZ=tc({query:J(),includePattern:J().optional(),excludePattern:J().optional(),explanation:J().optional()}),BZ={displayName:`FileSearch`,getHeaderParams(e){try{return`pattern: "${e?.query||`[no pattern]`}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=zZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=[`pattern: "${i.query}"`];i.includePattern&&a.push(`path: "${i.includePattern}"`),i.excludePattern&&a.push(`exclude: "${i.excludePattern}"`);let o=a.join(`, `);return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:o,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error searching files`})]}):t===`executing`?(0,X.jsx)(PK,{name:`Search`,params:o,status:`executing`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:o,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Search`,params:o,status:`pending`})})}};function VZ(e){let t=[];return e.pattern&&t.push(`pattern: "${e.pattern}"`),e.path&&t.push(`path: "${e.path}"`),t.length>0?t.join(`, `):`[no pattern]`}const HZ={displayName:`Search`,getHeaderParams(e){try{return VZ(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=VZ(e);if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error matching files`})]});if(t===`executing`)return(0,X.jsx)(PK,{name:`Search`,params:r,status:`executing`,showSpinner:!0});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Search`,params:r,status:`pending`})});let i=n.data.files??[],a=i.slice(0,10),o=i.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`success`}),(0,X.jsx)(FK,{children:n.summary}),i.length>0&&(0,X.jsxs)(IK,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more file`,o===1?``:`s`]})]})]})}};function UZ(e){let t=e,n=[];t.pattern&&n.push(`pattern: "${t.pattern}"`),t.path&&n.push(`path: "${t.path}"`);let r=t.outputMode||e.output_mode;return r&&n.push(`outputMode: "${r}"`),t.glob&&n.push(`glob: "${t.glob}"`),t[`-i`]&&n.push(`case-insensitive`),n.length>0?n.join(`, `):`[no pattern]`}const WZ={displayName:`Search`,getHeaderParams(e){try{return UZ(e)}catch{return`[unknown]`}},renderUI(e,t,n){let r=UZ(e);if(t===`error`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error searching content`})]});if(t===`executing`)return(0,X.jsx)(PK,{name:`Search`,params:r,status:`executing`,showSpinner:!0});if(!n)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Search`,params:r,status:`pending`})});let i=n.data.matches??[],a=i.slice(0,10),o=i.length-a.length;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:r,status:`success`}),(0,X.jsx)(FK,{children:n.summary}),i.length>0&&(0,X.jsxs)(IK,{children:[a.map((e,t)=>(0,X.jsx)($,{dimColor:!0,children:e},t)),o>0&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,o,` more match`,o===1?``:`es`]})]})]})}},GZ=tc({query:J(),command:J().optional(),explanation:J().optional()}),KZ={displayName:`Search`,getHeaderParams(e){try{return`"${e?.query||``}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=GZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=`"${r.data.query}"`;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing semantic search`})]}):t===`executing`?(0,X.jsx)(PK,{name:`Search`,params:i,status:`executing`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Search`,params:i,status:`success`}),(0,X.jsx)(FK,{children:`Completed`})]})}},qZ=tc({url:J()}),JZ={displayName:`Web Fetch`,getHeaderParams(e){try{let t=e?.url||``;return t.length>50?t.substring(0,47)+`...`:t}catch{return`[unknown]`}},renderUI(e,t,n){let r=qZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Fetch`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data.url||``,a=i.length>50?i.substring(0,47)+`...`:i;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error fetching URL`})]}):t===`executing`?(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`executing`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`success`}),(0,X.jsx)(FK,{children:n.summary??`Fetched content`})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Fetch`,params:a,status:`pending`})})}},YZ=tc({searchTerm:J(),query:J().optional(),explanation:J().optional()}),XZ={displayName:`WebSearch`,getHeaderParams(e){try{return`"${e?.searchTerm||e?.search_term||e?.query||`[no query]`}"`}catch{return`[unknown]`}},renderUI(e,t,n){let r=YZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`WebSearch`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.searchTerm||i.query||``,o=`"${a.length>40?a.substring(0,37)+`...`:a}"`;return t===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`WebSearch`,params:o,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error performing web search`})]}):t===`executing`?(0,X.jsx)(PK,{name:`WebSearch`,params:o,status:`executing`,showSpinner:!0}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`WebSearch`,params:o,status:`success`}),(0,X.jsx)(FK,{children:`Found results`})]})}},ZZ=tc({shellId:J(),filter:J().optional()}),QZ={displayName:`TerminalOutput`,getHeaderParams(e){try{let t=e,n=[`id: ${t.shellId||``}`];return t.filter&&n.push(`filter: ${t.filter}`),n.join(`, `)}catch{return`[unknown]`}},renderUI(e,t,n){let r=ZZ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`TerminalOutput`,params:i,status:`pending`})})}},$Z=tc({shellId:J()}),eQ={displayName:`KillShell`,getHeaderParams(e){try{return`id: ${e.shellId||``}`}catch{return`[unknown]`}},renderUI(e,t,n){let r=$Z.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:``,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=`id: ${r.data.shellId}`;return t===`interrupted`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]}):t===`rejected`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`rejected`}),n?.userNote?(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]}):(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]}):!n&&(t===`executing`||t===`pending`)?(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`pending`,showSpinner:!0}):n?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`KillShell`,params:i,status:`pending`})})}};function tQ(e,t,n){let r=n?100:t,i=e.split(`
12648
+ `).filter(Boolean);return i.length<=r?{lines:i,isTruncated:!1,hiddenCount:0}:{lines:i.slice(0,r),isTruncated:!0,hiddenCount:i.length-r}}function nQ(e){return`${(e/1e3).toFixed(1)}s`}function rQ({command:e,toolCallId:t,executionResult:n}){let{agentStatus:r,activeToolOutputs:i}=RZ(),[a]=(0,Z.useState)(Date.now()),[o,s]=(0,Z.useState)(0),[c,l]=(0,Z.useState)(!1),u=!n&&(r===Sl.Streaming||r===Sl.ExecutingTool),d=i[t]||``,f=n?.output||``,p=u?d:f,m=(0,Z.useDeferredValue)(p),h=p!==m;(0,Z.useEffect)(()=>{if(u){let e=setInterval(()=>{s(Date.now()-a)},1e3);return()=>clearInterval(e)}else n&&s(n.duration??0);return()=>{}},[u,a,n]);let{lines:g,isTruncated:_,hiddenCount:v}=(0,Z.useMemo)(()=>tQ(m,7,c),[m,c]),y=!u&&n!==void 0&&(_||c),{isFocused:b}=cI({id:`bash-tool-${t}`,isActive:y});sI((e,t)=>{b&&t.ctrl&&e===`o`&&l(e=>!e)},{isActive:b&&y});let x=e,S=n?.exitCode??0,C=n?.status===`error`||S!==0,w=u?`pending`:C?`error`:`success`;if(u&&g.length===0)return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:w,showSpinner:!0}),(0,X.jsx)(FK,{color:`gray`,children:`Running…`})]});if(u&&g.length>0){let e=o>0?` (${nQ(o)})`:``;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:w,showSpinner:!0}),(0,X.jsxs)(IK,{children:[g.map((e,t)=>(0,X.jsx)($,{children:e},t)),_&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,v,` more line`,v===1?``:`s`,e]}),h&&(0,X.jsx)($,{dimColor:!0,children:`Processing output...`})]})]})}if(n){let e=!f&&(n.duration??0)===0,t=AK(n.duration??0),r=e?`exit ${S}`:`exit ${S} (${t})`,i=g.length>0;return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:w}),i&&(0,X.jsxs)(IK,{children:[C&&(0,X.jsx)($,{color:`red`,dimColor:!0,children:`Error:`}),g.map((e,t)=>(0,X.jsx)($,{color:C?`red`:void 0,dimColor:!0,children:e},t)),_&&(0,X.jsxs)($,{dimColor:!0,children:[`… +`,v,` `,c?`more `:``,`line`,v===1?``:`s`,c?``:` (ctrl+o to expand)`]})]}),(0,X.jsx)(FK,{color:C?`red`:`gray`,children:r})]})}return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(PK,{name:`Bash`,params:x,paramsLanguage:`bash`,status:`pending`})})}const iQ=tc({command:J(),explanation:J().optional(),runInBackground:qK,shellId:J().optional(),interactiveMode:qK,timeout:Gc().optional()});function aQ({rawInput:e,status:t,parsedResult:n}){let r=iQ.safeParse(VK(e));if(!r.success)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:``,paramsLanguage:`bash`,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Invalid params`})]});let i=r.data,a=i.command||``,o=i.timeout?` (timeout: ${(i.timeout/1e3).toFixed(0)}s)`:``;if(t===`interrupted`)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:a,paramsLanguage:`bash`,status:`interrupted`}),(0,X.jsx)(FK,{color:`yellow`,children:`Interrupted · What should I do instead?`})]});if(t===`rejected`)return n?.userNote?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:a,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsxs)(FK,{color:`yellow`,children:[`Rejected · `,(0,X.jsxs)($,{italic:!0,children:[`"`,n.userNote,`"`]})]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:a,paramsLanguage:`bash`,status:`rejected`}),(0,X.jsx)(FK,{color:`yellow`,children:`Rejected`})]});if(n?.data?.timedOut)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:`${a}${o}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(FK,{children:`Running in the background`})]});if(n?.runInBackground)return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:`Bash`,params:`${a}${o}`,paramsLanguage:`bash`,status:`success`}),(0,X.jsx)(FK,{children:n.summary})]});let s=e?.id||`unknown`,c=n?.data;return(0,X.jsx)(rQ,{command:`${a}${o}`,toolCallId:s,executionResult:c})}const oQ={read_file:Hq,edit:Rq,list_dir:Bq,delete_file:Aq,upload_image:Gq,grep:WZ,glob:HZ,file_search:BZ,semantic_search_server:KZ,web_search:XZ,web_fetch:JZ,bash:{displayName:`Bash`,getHeaderParams(e){try{return e?.command||`[no command]`}catch{return`[unknown]`}},renderUI(e,t,n){return(0,X.jsx)(aQ,{rawInput:e,status:t,parsedResult:n})}},bash_output:QZ,kill_shell:eQ,navigate_to:xq,new_tab:Cq,close_tab:pq,switch_active_tab:Oq,refresh_tab:Eq,get_tab_content:yq,computer:hq,get_interactive_elements:_q,perform_interactive_element_action:Tq,ask_user_question:YK,enter_plan_mode:XK,exit_plan_mode:aq,subagent:cq,hand_off_to_main:oq,todo_write:dq,get_diagnostics:qq};function sQ(e){let t=e.toolUseRequest;return t?(Array.isArray(t)?t:[t]).map(e=>{let t=e;return{name:t.name??``,input:t.input??{}}}).filter(e=>e.name):[]}function cQ(e,t=4){let n=[];for(let r of e){if(n.length>=t)break;for(let e of sQ(r)){if(n.length>=t)break;let r=oQ[e.name];if(!r)continue;let i=``;try{i=r.getHeaderParams(e.input)}catch{}if(!i)continue;let a=r.displayName??e.name;n.push({label:a,detail:i})}}return n}const lQ=(0,Z.memo)(({counts:e,segments:t})=>{let{colors:n}=RL(),r=(0,Z.useMemo)(()=>{let t=[];return e.toolUses>0&&t.push(`${e.toolUses} tool ${e.toolUses===1?`use`:`uses`}`),e.responses>0&&t.push(`${e.responses} ${e.responses===1?`response`:`responses`}`),t.length===0?`Conversation compacted`:t.join(`, `)+` compacted`},[e]),i=(0,Z.useMemo)(()=>cQ(t),[t]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:n.textMuted,children:`⟐`}),(0,X.jsx)($,{color:n.textMuted,dimColor:!0,children:r})]}),i.map((e,t)=>(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:2,children:(0,X.jsxs)($,{color:n.textMuted,dimColor:!0,children:[`⎿ `,e.label,` `,e.detail]})},t))]})});lQ.displayName=`CompactedPlaceholder`;const uQ=(0,Z.createContext)(null);function dQ(){let e=(0,Z.use)(uQ);if(!e)throw Error(`useUpdate must be used within UpdateProvider`);return e}function fQ({children:e,configService:t}){let[n,r]=(0,Z.useState)(null),i=(0,Z.useMemo)(()=>t.get(`autoUpdate`)!==!1,[t]);(0,Z.useEffect)(()=>{let e=!0,t=()=>{jj(PA).then(t=>{e&&r(e=>e?.latestVersion===t?.latestVersion?e:t)}).catch(()=>{})};t();let n=setInterval(t,6e4);return()=>{e=!1,clearInterval(n)}},[]);let a=(0,Z.useMemo)(()=>({updateInfo:n,autoUpdate:i}),[n,i]);return(0,X.jsx)(uQ.Provider,{value:a,children:e})}const pQ=(0,Z.createContext)(null),mQ=()=>{let e=(0,Z.use)(pQ);if(!e)throw Error(`${mQ.name} must be used within a ${hQ.name}`);return e};function hQ({children:e}){let[t,n]=(0,Z.useState)({columns:process.stdout.columns-8,rows:process.stdout.rows}),r=(0,Z.useCallback)(()=>{n({columns:process.stdout.columns-8,rows:process.stdout.rows})},[]);(0,Z.useLayoutEffect)(()=>(process.stdout.on(`resize`,r),()=>{process.stdout.off(`resize`,r)}),[r]);let i=(0,Z.useMemo)(()=>({width:t.columns,height:t.rows}),[t.columns,t.rows]);return(0,X.jsx)(pQ.Provider,{value:i,children:e})}function gQ(){let{height:e}=mQ();return Math.max(0,e-3)}let _Q=function(e){return e.Models=`models`,e.CreateConversation=`create-conversation`,e.GetConversation=`get-conversation`,e.Grep=`grep`,e.FileSearch=`file-search`,e.ListDir=`list-dir`,e.ReadFile=`read-file`,e.DeleteFile=`delete-file`,e.EditFile=`edit-file`,e.RunTerminal=`run-terminal`,e.GetTerminalOutput=`get-terminal-output`,e.MCPTool=`mcp-tool`,e}({});function vQ(e){return PL({queryKey:[_Q.Models],queryFn:async()=>{try{return(await e.listLLMModels())?.result??[]}catch{return[]}},staleTime:300*1e3,retry:1,refetchOnMount:`always`,refetchOnWindowFocus:!1})}const yQ=/\/var\/folders\/.*\/T\/TemporaryItems\/.*screencaptureui.*\//i,bQ=`.abacusai/screenshots`;function xQ(e){return yQ.test(e)}function SQ(e){try{let t=CQ(e.replace(/\\ /g,` `));if(!g(t))return null;let n=C.resolve(process.cwd(),bQ);g(n)||_(n,{recursive:!0});let r=C.basename(t),i=C.join(n,r);return h(t,i),i}catch{return null}}function CQ(e){if(e.startsWith(`file://`))try{return decodeURIComponent(e.slice(7))}catch{return e.slice(7)}return e}let wQ;function TQ(){if(wQ!==void 0)return wQ;try{return c(`which`,[`wl-paste`],{stdio:`ignore`}),wQ=`wl-paste`,`wl-paste`}catch{}try{return c(`which`,[`xclip`],{stdio:`ignore`}),wQ=`xclip`,`xclip`}catch{}return wQ=null,null}async function EQ(){try{if(process.platform===`darwin`){let e=c(`osascript`,[`-e`,`clipboard info`],{encoding:`utf8`,timeout:2e3});return/PNGf|JPEG|TIFF|GIF/i.test(e)}if(process.platform===`win32`)return c(`powershell`,[`-NoProfile`,`-Command`,`Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.Clipboard]::ContainsImage()`],{encoding:`utf8`,timeout:2e3}).trim().toLowerCase()===`true`;let e=TQ();if(e===`wl-paste`)return c(`wl-paste`,[`--list-types`],{encoding:`utf8`,timeout:2e3}).includes(`image/`);if(e===`xclip`)return c(`xclip`,[`-selection`,`clipboard`,`-t`,`TARGETS`,`-o`],{encoding:`utf8`,timeout:2e3}).includes(`image/`)}catch{}return!1}async function DQ(e){try{let t=C.resolve(e,bQ);g(t)||_(t,{recursive:!0});let n=Date.now(),r=C.join(t,`clipboard-${n}.png`);if(process.platform===`darwin`)c(`osascript`,[`-e`,`
12649
12649
  set destFile to "${r}"
12650
12650
  try
12651
12651
  set imgData to (clipboard info for «class PNGf»)
@@ -12662,33 +12662,33 @@ https://github.com/highlightjs/highlight.js/issues/2277`),a=e,i=t);let o={code:i
12662
12662
  close access fileRef
12663
12663
  end try
12664
12664
  end try
12665
- `],{timeout:5e3});else if(process.platform===`win32`)c(`powershell`,[`-NoProfile`,`-Command`,`Add-Type -Assembly System.Windows.Forms; [System.Windows.Forms.Clipboard]::GetImage().Save("${r}", [System.Drawing.Imaging.ImageFormat]::Png)`],{timeout:5e3});else{let e=wQ();if(e===`wl-paste`)x(r,c(`wl-paste`,[`--no-newline`,`--type`,`image/png`],{timeout:5e3}));else if(e===`xclip`)x(r,c(`xclip`,[`-selection`,`clipboard`,`-t`,`image/png`,`-o`],{timeout:5e3}));else return null}try{if(b(r).size===0)return null}catch{return null}return r}catch{return null}}async function DQ(){try{if(process.platform===`darwin`)return c(`pbpaste`,{encoding:`utf8`,timeout:2e3});if(process.platform===`win32`)return c(`powershell`,[`-NoProfile`,`-Command`,`Get-Clipboard`],{encoding:`utf8`,timeout:2e3});let e=wQ();if(e===`wl-paste`)return c(`wl-paste`,[`--no-newline`],{encoding:`utf8`,timeout:2e3});if(e===`xclip`)return c(`xclip`,[`-selection`,`clipboard`,`-o`],{encoding:`utf8`,timeout:2e3})}catch{}return null}async function OQ(e,t){let n=await e.getDeploymentConversation({deploymentConversationId:t});if(!n?.success||!n.result?.history)return 0;let r=0;for(let e of n.result.history)e.computePointsUsed&&typeof e.computePointsUsed==`number`&&(r+=e.computePointsUsed);return r}const kQ=/[ \t()[\]{};|*?$`'"#&<>!~]/;function AQ(e){return e.replace(RegExp(`\\\\([${kQ.source.slice(1,-1)}])`,`g`),`$1`)}const jQ=n.homedir();function MQ(e){return e===`~`?jQ:e.startsWith(`~/`)?C.join(jQ,e.slice(2)):e}function NQ(e,t=process.cwd()){let n=C.resolve(t,e);return n===jQ||n.startsWith(`${jQ}${C.sep}`)?`~${n.slice(jQ.length).split(C.sep).join(`/`)}`:n}function PQ(e){let t=C.resolve(e),n=C.relative(process.cwd(),t);if(!n)return`.`;let r=n.split(C.sep).join(`/`);return r.startsWith(`.`)?r:`./${r}`}function FQ(e){let t=C.resolve(e),n=process.cwd(),r=C.relative(n,t);if(!r)return`.`;if(!r.startsWith(`..`)){let e=r.split(C.sep).join(`/`);return e.startsWith(`.`)?e:`./${e}`}return t===jQ||t.startsWith(`${jQ}${C.sep}`)?`~${t.slice(jQ.length).split(C.sep).join(`/`)}`:t}function IQ(e){return e.includes(` `)?`'${e.replace(/'/g,`'\\''`)}'`:e}function LQ(e){return FQ(e)}function RQ(e){let t=e.startsWith(`'`)||e.startsWith(`"`)?e.slice(1):e;return t.startsWith(`/`)||t.startsWith(`~`)||t.startsWith(`./`)||t.startsWith(`../`)||/^file:\/\//i.test(t)||/^[A-Za-z]:[/\\]/.test(t)||t.startsWith(`\\\\`)||e.startsWith(`& '`)}function*zQ(e){let t=e.trim();if(!RQ(t))return;let n=t.replace(/^& /,``);function r(e){let t=e.trim();return/^file:\/\//i.test(t)&&(t=SQ(t)),t=t.replace(/\\ /g,` `),t=MQ(t),C.resolve(t)}let i=`NORMAL`,a=``,o=0;for(;o<n.length;){let e=n[o];if(i===`SINGLE`){if(e===`'`&&n.slice(o,o+4)===`'\\''`){a+=`'`,o+=4;continue}if(e===`'`){let e=r(a);e&&(yield e),a=``,i=`NORMAL`,o++;continue}a+=e,o++;continue}if(i===`DOUBLE`){if(e===`"`){let e=r(a);e&&(yield e),a=``,i=`NORMAL`,o++;continue}a+=e,o++;continue}if(e===`'`){i=`SINGLE`,o++;continue}if(e===`"`){i=`DOUBLE`,o++;continue}if(e===`\\`&&o+1<n.length&&n[o+1]===` `){a+=`\\ `,o+=2;continue}if(e===` `||e===`
12666
- `||e===` `){if(a.trim()){let e=r(a);e&&(yield e),a=``}o++;continue}a+=e,o++}if(a.trim()){let e=r(a);e&&(yield e)}}function BQ(e){let t=[];for(let n of zQ(e)){if(!g(n))return null;let e=IQ(LQ(n));t.push(`@${e}`)}return t.length===0?null:t.join(` `)+` `}function VQ(e){return typeof e==`string`?e:typeof e==`object`&&e&&`segment`in e?e.segment:null}function HQ(){return process.platform===`win32`}async function UQ(e){return new Promise(t=>setTimeout(t,e))}function WQ({onlyFirst:e=!1}={}){return RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:`g`)}const GQ=WQ();function KQ(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return!e.includes(`\x1B`)&&!e.includes(`›`)?e:e.replace(GQ,``)}const qQ=new Intl.Segmenter,JQ=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$`,`v`),YQ=RegExp(`^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+`,`v`),XQ=RegExp(`^\\p{RGI_Emoji}$`,`v`),ZQ=/^[\d#*]\u20E3$/,QQ=/\p{Extended_Pictographic}/gu;function $Q(e){if(e.length>50)return!1;if(ZQ.test(e))return!0;if(e.includes(`‍`)){let t=e.match(QQ);return t!==null&&t.length>=2}return!1}function e$(e){return e.replace(YQ,``)}function t$(e){return JQ.test(e)}function n$(e,t){let n=0;if(e.length>1)for(let r of e.slice(1))r>=`＀`&&r<=`￯`&&(n+=AM(r.codePointAt(0),t));return n}function r$(e,t={}){if(typeof e!=`string`||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t,i=e;if(!r&&(i.includes(`\x1B`)||i.includes(`›`))&&(i=KQ(i)),i.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(i))return i.length;let a=0,o={ambiguousAsWide:!n};for(let{segment:e}of qQ.segment(i)){if(t$(e))continue;if(XQ.test(e)||$Q(e)){a+=2;continue}let t=e$(e).codePointAt(0);a+=AM(t,o),a+=n$(e,o)}return a}const i$=[RegExp(`\x1B\\[2J`,`g`),RegExp(`\x1B\\[H`,`g`),RegExp(`\x1B\\[\\d+(;\\d+)?H`,`g`),RegExp(`\x1Bc`,`g`),RegExp(`\x1B\\[!p`,`g`),RegExp(`\x1B\\[\\?1049[hl]`,`g`),RegExp(`\x1B\\[\\d*[ABCD]`,`g`),RegExp(`\x1B\\[s`,`g`),RegExp(`\x1B\\[u`,`g`),RegExp(`\x1B\\[\\d*J`,`g`),RegExp(`\x1B\\[\\d*K`,`g`),RegExp(`\x1B\\[\\?25[hl]`,`g`),RegExp(`\x07`,`g`)];function a$(e){let t=e;for(let e of i$)t=t.replace(e,``);return t}const o$=new Map,s$=1e3;function c$(e){let t=!0;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>127){t=!1;break}if(t)return e.split(``);if(e.length<=s$){let t=o$.get(e);if(t)return t}let n=Array.from(e);return e.length<=s$&&o$.set(e,n),n}function l$(e){return c$(e).length}function u$(e,t,n){return c$(e).slice(t,n).join(``)}function d$(e){return c$(k(iZ(e))).filter(e=>{let t=e.codePointAt(0);return t===void 0?!1:t===10||t===13||t===9?!0:!(t>=0&&t<=31||t>=128&&t<=159)}).join(``)}const f$=new Map,p$=e=>{if(/^[\u0020-\u007E]*$/.test(e))return e.length;if(f$.has(e))return f$.get(e);let t=r$(e);return f$.set(e,t),t};nZ();function m$(e,t){if(!x$(e[t]))return!1;let n=t+1;for(;n<e.length&&C$(e[n]);)n++;return n>=e.length||!x$(e[n])}function h$(e,t){let{lines:n,cursorRow:r,cursorCol:i}=e;switch(t.type){case`vim_delete_word_forward`:case`vim_change_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=A$(n,o,s,!0);if(e)o=e.row,s=e.col;else{let e=n[o]||``,t=k$(e,s);s=t===null?l$(e):t+1;break}}return o!==r||s!==i?P$(B$(e),r,i,o,s,``):e}case`vim_delete_word_backward`:case`vim_change_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=j$(n,o,s);if(e)o=e.row,s=e.col;else break}return o!==r||s!==i?P$(B$(e),o,s,r,i,``):e}case`vim_delete_word_end`:case`vim_change_word_end`:{let{count:a}=t.payload,o=r,s=i,c=r,l=i;for(let e=0;e<a;e++){let t=A$(n,o,s,!1);if(t){if(c=t.row,l=t.col+1,e<a-1){let e=A$(n,t.row,t.col+1,!0);if(e)o=e.row,s=e.col;else break}}else break}if(c<n.length){let e=l$(n[c]||``);l=Math.min(l,e)}return c!==r||l!==i?P$(B$(e),r,i,c,l,``):e}case`vim_delete_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=n.length;if(o===1||a>=o)return{...B$(e),lines:[``],cursorRow:0,cursorCol:0,preferredCol:null};let s=B$(e),c=[...s.lines];c.splice(r,a);let l=Math.min(r,c.length-1);return{...s,lines:c,cursorRow:l,cursorCol:0,preferredCol:null}}case`vim_change_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=B$(e),{startOffset:s,endOffset:c}=N$(r,a,o.lines),{startRow:l,startCol:u,endRow:d,endCol:f}=M$(s,c,o.lines);return P$(o,l,u,d,f,``)}case`vim_delete_to_end_of_line`:case`vim_change_to_end_of_line`:{let t=n[r]||``;return i<l$(t)?P$(B$(e),r,i,r,l$(t),``):e}case`vim_change_movement`:{let{movement:a,count:o}=t.payload,s=n.length;switch(a){case`h`:{let t=Math.max(0,i-o);return P$(B$(e),r,t,r,i,``)}case`j`:{let t=Math.min(o,s-r);if(t>0)if(s===1){let t=e.lines[0]||``;return P$(B$(e),0,0,0,l$(t),``)}else{let n=B$(e),{startOffset:i,endOffset:a}=N$(r,t,n.lines),{startRow:o,startCol:s,endRow:c,endCol:l}=M$(i,a,n.lines);return P$(n,o,s,c,l,``)}return e}case`k`:if(Math.min(o,r+1)>0)if(e.lines.length===1){let t=e.lines[0]||``;return P$(B$(e),0,0,0,l$(t),``)}else{let t=Math.max(0,r-o+1),n=r-t+1,i=B$(e),{startOffset:a,endOffset:s}=N$(t,n,i.lines),{startRow:c,startCol:l,endRow:u,endCol:d}=M$(a,s,i.lines);return{...P$(i,c,l,u,d,``),cursorRow:t,cursorCol:0}}return e;case`l`:return P$(B$(e),r,i,r,Math.min(l$(n[r]||``),i+o),``);default:return e}}case`vim_move_left`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++)if(s>0)s--;else if(o>0){o--;let e=l$(a[o]||``);s=e===0?0:e-1}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_right`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++){let e=a[o]||``,t=l$(e);if(t===0)o<a.length-1&&(o++,s=0);else if(s<t-1){s++;let n=c$(e);for(;s<n.length&&C$(n[s])&&s<t-1;)s++}else o<a.length-1&&(o++,s=0)}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_up`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.max(0,r-n),s=l$(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_down`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.min(a.length-1,r+n),s=l$(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=A$(n,o,s,!0);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=j$(n,o,s);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_end`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){if(e===0){let e=c$(n[o]||``);if(s<e.length&&x$(e[s])&&(s+1>=e.length||!w$(e[s+1])||x$(e[s])&&m$(e,s))){let e=A$(n,o,s+1,!1);if(e){o=e.row,s=e.col;continue}}}let t=A$(n,o,s,!1);if(t)o=t.row,s=t.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_delete_char`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=l$(a[r]||``);if(i<o){let t=Math.min(n,o-i);return P$(B$(e),r,i,r,i+t,``)}return e}case`vim_insert_at_cursor`:return e;case`vim_append_at_cursor`:{let{cursorRow:t,cursorCol:n,lines:r}=e,i=n<l$(r[t]||``)?n+1:n;return{...e,cursorCol:i,preferredCol:null}}case`vim_open_line_below`:{let{cursorRow:t,lines:n}=e,r=B$(e),i=l$(n[t]||``);return P$(r,t,i,t,i,`
12667
- `)}case`vim_open_line_above`:{let{cursorRow:t}=e;return{...P$(B$(e),t,0,t,0,`
12668
- `),cursorRow:t,cursorCol:0}}case`vim_append_at_line_end`:{let{cursorRow:t,lines:n}=e,r=l$(n[t]||``);return{...e,cursorCol:r,preferredCol:null}}case`vim_insert_at_line_start`:{let{cursorRow:t,lines:n}=e,r=n[t]||``,i=0,a=c$(r);for(;i<a.length&&/\s/.test(a[i]);)i++;return{...e,cursorCol:i,preferredCol:null}}case`vim_move_to_line_start`:return{...e,cursorCol:0,preferredCol:null};case`vim_move_to_line_end`:{let{cursorRow:t,lines:n}=e,r=l$(n[t]||``);return{...e,cursorCol:r>0?r-1:0,preferredCol:null}}case`vim_move_to_first_nonwhitespace`:{let{cursorRow:t,lines:n}=e,r=n[t]||``,i=0,a=c$(r);for(;i<a.length&&/\s/.test(a[i]);)i++;return{...e,cursorCol:i,preferredCol:null}}case`vim_move_to_first_line`:return{...e,cursorRow:0,cursorCol:0,preferredCol:null};case`vim_move_to_last_line`:{let{lines:t}=e,n=t.length-1;return{...e,cursorRow:n,cursorCol:0,preferredCol:null}}case`vim_move_to_line`:{let{lineNumber:n}=t.payload,{lines:r}=e,i=Math.min(Math.max(0,n-1),r.length-1);return{...e,cursorRow:i,cursorCol:0,preferredCol:null}}case`vim_escape_insert_mode`:{let{cursorCol:t}=e,n=t>0?t-1:0;return{...e,cursorCol:n,preferredCol:null}}default:return e}}let g$=0;const _$=/\[Pasted text (#\d+) \+\d+ lines\]/g;function v$(e){return e.length>500?!0:e.split(/\r\n|\r|\n/).length>5}function y$(e){g$++;let t=`#${g$}`;return{placeholder:`[Pasted text ${t} +${e.split(/\r\n|\r|\n/).length} lines]`,id:t}}function b$(e){return e===void 0?!1:!/[\s,.;!?]/.test(e)}const x$=e=>/[\w\p{L}\p{N}]/u.test(e),S$=e=>/\s/.test(e),C$=e=>/\p{M}/u.test(e),w$=e=>x$(e)||C$(e),T$=e=>/[\p{Script=Latin}]/u.test(e)?`latin`:/[\p{Script=Han}]/u.test(e)?`han`:/[\p{Script=Arabic}]/u.test(e)?`arabic`:/[\p{Script=Hiragana}]/u.test(e)?`hiragana`:/[\p{Script=Katakana}]/u.test(e)?`katakana`:/[\p{Script=Cyrillic}]/u.test(e)?`cyrillic`:`other`,E$=(e,t)=>!x$(e)||!x$(t)?!1:T$(e)!==T$(t),D$=(e,t)=>{let n=c$(e),r=t;if(r>=n.length)return null;let i=n[r];if(x$(i))for(;r<n.length&&w$(n[r]);){if(r+1<n.length&&x$(n[r+1])&&E$(n[r],n[r+1])){r++;break}r++}else if(!S$(i))for(;r<n.length&&!x$(n[r])&&!S$(n[r]);)r++;for(;r<n.length&&S$(n[r]);)r++;return r<n.length?r:null},O$=(e,t)=>{let n=c$(e),r=t;if(r<=0)return null;for(r--;r>=0&&S$(n[r]);)r--;if(r<0)return null;if(x$(n[r])){for(;r>=0&&x$(n[r]);){if(r-1>=0&&x$(n[r-1])&&E$(n[r],n[r-1]))return r;r--}return r+1}else{for(;r>=0&&!x$(n[r])&&!S$(n[r]);)r--;return r+1}},k$=(e,t)=>{let n=c$(e),r=t,i=r<n.length&&w$(n[r])&&(r+1>=n.length||!w$(n[r+1])||x$(n[r])&&r+1<n.length&&x$(n[r+1])&&E$(n[r],n[r+1])),a=r<n.length&&!w$(n[r])&&!S$(n[r])&&(r+1>=n.length||S$(n[r+1])||w$(n[r+1]));if(i||a)for(r++;r<n.length&&S$(n[r]);)r++;if(r<n.length&&!w$(n[r]))for(;r<n.length&&S$(n[r]);)r++;let o=!1,s=-1;if(r<n.length&&w$(n[r]))for(;r<n.length&&w$(n[r]);){if(o=!0,x$(n[r])&&(s=r),r+1<n.length&&x$(n[r+1])&&E$(n[r],n[r+1])){r++,x$(n[r-1])&&(s=r-1);break}r++}else if(r<n.length&&!S$(n[r]))for(;r<n.length&&!x$(n[r])&&!S$(n[r]);)o=!0,s=r,r++;return o&&s>=t?s:null},A$=(e,t,n,r)=>{let i=e[t]||``,a=r?D$(i,n):k$(i,n);if(a!==null)return{row:t,col:a};for(let n=t+1;n<e.length;n++){let t=e[n]||``,i=c$(t);if(i.length===0){let t=!1;for(let r=n+1;r<e.length;r++){let n=c$(e[r]||``),i=0;for(;i<n.length&&S$(n[i]);)i++;if(i<n.length){t=!0;break}}if(!t)return{row:n,col:0};continue}let a=0;for(;a<i.length&&S$(i[a]);)a++;if(a<i.length){if(r)return{row:n,col:a};{let e=k$(t,a);if(e!==null)return{row:n,col:e}}}}return null},j$=(e,t,n)=>{let r=O$(e[t]||``,n);if(r!==null)return{row:t,col:r};for(let n=t-1;n>=0;n--){let t=e[n]||``,r=c$(t);if(r.length===0)continue;let i=r.length;for(;i>0&&S$(r[i-1]);)i--;if(i>0){let e=O$(t,i);if(e!==null)return{row:n,col:e}}}return null},M$=(e,t,n)=>{let r=0,i=0,a=0,o=0,s=0;for(let t=0;t<n.length;t++){let o=n[t].length+1;if(r+o>e){i=t,a=e-r;break}r+=o}r=0;for(let e=0;e<n.length;e++){let i=n[e].length+(e<n.length-1?1:0);if(r+i>=t){o=e,s=t-r;break}r+=i}return{startRow:i,startCol:a,endRow:o,endCol:s}},N$=(e,t,n)=>{let r=0;for(let t=0;t<e;t++)r+=n[t].length+1;let i=r;for(let r=0;r<t;r++){let t=e+r;t<n.length&&(i+=n[t].length,t<n.length-1&&(i+=1))}return{startOffset:r,endOffset:i}},P$=(e,t,n,r,i,a)=>{let o=t=>e.lines[t]||``,s=e=>l$(o(e)),c=(e,t,n)=>Math.min(Math.max(e,t),n);if(t>r||t===r&&n>i||t<0||n<0||r>=e.lines.length||r<e.lines.length&&i>s(r))return e;let l=[...e.lines],u=c(n,0,s(t)),d=c(i,0,s(r)),f=u$(o(t),0,u),p=u$(o(r),d),m=a.replace(/\r\n/g,`
12665
+ `],{timeout:5e3});else if(process.platform===`win32`)c(`powershell`,[`-NoProfile`,`-Command`,`Add-Type -Assembly System.Windows.Forms; [System.Windows.Forms.Clipboard]::GetImage().Save("${r}", [System.Drawing.Imaging.ImageFormat]::Png)`],{timeout:5e3});else{let e=TQ();if(e===`wl-paste`)x(r,c(`wl-paste`,[`--no-newline`,`--type`,`image/png`],{timeout:5e3}));else if(e===`xclip`)x(r,c(`xclip`,[`-selection`,`clipboard`,`-t`,`image/png`,`-o`],{timeout:5e3}));else return null}try{if(b(r).size===0)return null}catch{return null}return r}catch{return null}}async function OQ(){try{if(process.platform===`darwin`)return c(`pbpaste`,{encoding:`utf8`,timeout:2e3});if(process.platform===`win32`)return c(`powershell`,[`-NoProfile`,`-Command`,`Get-Clipboard`],{encoding:`utf8`,timeout:2e3});let e=TQ();if(e===`wl-paste`)return c(`wl-paste`,[`--no-newline`],{encoding:`utf8`,timeout:2e3});if(e===`xclip`)return c(`xclip`,[`-selection`,`clipboard`,`-o`],{encoding:`utf8`,timeout:2e3})}catch{}return null}async function kQ(e,t){let n=await e.getDeploymentConversation({deploymentConversationId:t});if(!n?.success||!n.result?.history)return 0;let r=0;for(let e of n.result.history)e.computePointsUsed&&typeof e.computePointsUsed==`number`&&(r+=e.computePointsUsed);return r}const AQ=/[ \t()[\]{};|*?$`'"#&<>!~]/;function jQ(e){return e.replace(RegExp(`\\\\([${AQ.source.slice(1,-1)}])`,`g`),`$1`)}const MQ=n.homedir();function NQ(e){return e===`~`?MQ:e.startsWith(`~/`)?C.join(MQ,e.slice(2)):e}function PQ(e,t=process.cwd()){let n=C.resolve(t,e);return n===MQ||n.startsWith(`${MQ}${C.sep}`)?`~${n.slice(MQ.length).split(C.sep).join(`/`)}`:n}function FQ(e){let t=C.resolve(e),n=C.relative(process.cwd(),t);if(!n)return`.`;let r=n.split(C.sep).join(`/`);return r.startsWith(`.`)?r:`./${r}`}function IQ(e){let t=C.resolve(e),n=process.cwd(),r=C.relative(n,t);if(!r)return`.`;if(!r.startsWith(`..`)){let e=r.split(C.sep).join(`/`);return e.startsWith(`.`)?e:`./${e}`}return t===MQ||t.startsWith(`${MQ}${C.sep}`)?`~${t.slice(MQ.length).split(C.sep).join(`/`)}`:t}function LQ(e){return e.includes(` `)?`'${e.replace(/'/g,`'\\''`)}'`:e}function RQ(e){return IQ(e)}function zQ(e){let t=e.startsWith(`'`)||e.startsWith(`"`)?e.slice(1):e;return t.startsWith(`/`)||t.startsWith(`~`)||t.startsWith(`./`)||t.startsWith(`../`)||/^file:\/\//i.test(t)||/^[A-Za-z]:[/\\]/.test(t)||t.startsWith(`\\\\`)||e.startsWith(`& '`)}function*BQ(e){let t=e.trim();if(!zQ(t))return;let n=t.replace(/^& /,``);function r(e){let t=e.trim();return/^file:\/\//i.test(t)&&(t=CQ(t)),t=t.replace(/\\ /g,` `),t=NQ(t),C.resolve(t)}let i=`NORMAL`,a=``,o=0;for(;o<n.length;){let e=n[o];if(i===`SINGLE`){if(e===`'`&&n.slice(o,o+4)===`'\\''`){a+=`'`,o+=4;continue}if(e===`'`){let e=r(a);e&&(yield e),a=``,i=`NORMAL`,o++;continue}a+=e,o++;continue}if(i===`DOUBLE`){if(e===`"`){let e=r(a);e&&(yield e),a=``,i=`NORMAL`,o++;continue}a+=e,o++;continue}if(e===`'`){i=`SINGLE`,o++;continue}if(e===`"`){i=`DOUBLE`,o++;continue}if(e===`\\`&&o+1<n.length&&n[o+1]===` `){a+=`\\ `,o+=2;continue}if(e===` `||e===`
12666
+ `||e===` `){if(a.trim()){let e=r(a);e&&(yield e),a=``}o++;continue}a+=e,o++}if(a.trim()){let e=r(a);e&&(yield e)}}function VQ(e){let t=[];for(let n of BQ(e)){if(!g(n))return null;let e=LQ(RQ(n));t.push(`@${e}`)}return t.length===0?null:t.join(` `)+` `}function HQ(e){return typeof e==`string`?e:typeof e==`object`&&e&&`segment`in e?e.segment:null}function UQ(){return process.platform===`win32`}async function WQ(e){return new Promise(t=>setTimeout(t,e))}function GQ({onlyFirst:e=!1}={}){return RegExp(`(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]`,e?void 0:`g`)}const KQ=GQ();function qQ(e){if(typeof e!=`string`)throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return!e.includes(`\x1B`)&&!e.includes(`›`)?e:e.replace(KQ,``)}const JQ=new Intl.Segmenter,YQ=RegExp(`^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})+$`,`v`),XQ=RegExp(`^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+`,`v`),ZQ=RegExp(`^\\p{RGI_Emoji}$`,`v`),QQ=/^[\d#*]\u20E3$/,$Q=/\p{Extended_Pictographic}/gu;function e$(e){if(e.length>50)return!1;if(QQ.test(e))return!0;if(e.includes(`‍`)){let t=e.match($Q);return t!==null&&t.length>=2}return!1}function t$(e){return e.replace(XQ,``)}function n$(e){return YQ.test(e)}function r$(e,t){let n=0;if(e.length>1)for(let r of e.slice(1))r>=`＀`&&r<=`￯`&&(n+=AM(r.codePointAt(0),t));return n}function i$(e,t={}){if(typeof e!=`string`||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t,i=e;if(!r&&(i.includes(`\x1B`)||i.includes(`›`))&&(i=qQ(i)),i.length===0)return 0;if(/^[\u0020-\u007E]*$/.test(i))return i.length;let a=0,o={ambiguousAsWide:!n};for(let{segment:e}of JQ.segment(i)){if(n$(e))continue;if(ZQ.test(e)||e$(e)){a+=2;continue}let t=t$(e).codePointAt(0);a+=AM(t,o),a+=r$(e,o)}return a}const a$=[RegExp(`\x1B\\[2J`,`g`),RegExp(`\x1B\\[H`,`g`),RegExp(`\x1B\\[\\d+(;\\d+)?H`,`g`),RegExp(`\x1Bc`,`g`),RegExp(`\x1B\\[!p`,`g`),RegExp(`\x1B\\[\\?1049[hl]`,`g`),RegExp(`\x1B\\[\\d*[ABCD]`,`g`),RegExp(`\x1B\\[s`,`g`),RegExp(`\x1B\\[u`,`g`),RegExp(`\x1B\\[\\d*J`,`g`),RegExp(`\x1B\\[\\d*K`,`g`),RegExp(`\x1B\\[\\?25[hl]`,`g`),RegExp(`\x07`,`g`)];function o$(e){let t=e;for(let e of a$)t=t.replace(e,``);return t}const s$=new Map,c$=1e3;function l$(e){let t=!0;for(let n=0;n<e.length;n++)if(e.charCodeAt(n)>127){t=!1;break}if(t)return e.split(``);if(e.length<=c$){let t=s$.get(e);if(t)return t}let n=Array.from(e);return e.length<=c$&&s$.set(e,n),n}function u$(e){return l$(e).length}function d$(e,t,n){return l$(e).slice(t,n).join(``)}function f$(e){return l$(k(aZ(e))).filter(e=>{let t=e.codePointAt(0);return t===void 0?!1:t===10||t===13||t===9?!0:!(t>=0&&t<=31||t>=128&&t<=159)}).join(``)}const p$=new Map,m$=e=>{if(/^[\u0020-\u007E]*$/.test(e))return e.length;if(p$.has(e))return p$.get(e);let t=i$(e);return p$.set(e,t),t};rZ();function h$(e,t){if(!S$(e[t]))return!1;let n=t+1;for(;n<e.length&&w$(e[n]);)n++;return n>=e.length||!S$(e[n])}function g$(e,t){let{lines:n,cursorRow:r,cursorCol:i}=e;switch(t.type){case`vim_delete_word_forward`:case`vim_change_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=j$(n,o,s,!0);if(e)o=e.row,s=e.col;else{let e=n[o]||``,t=A$(e,s);s=t===null?u$(e):t+1;break}}return o!==r||s!==i?F$(V$(e),r,i,o,s,``):e}case`vim_delete_word_backward`:case`vim_change_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=M$(n,o,s);if(e)o=e.row,s=e.col;else break}return o!==r||s!==i?F$(V$(e),o,s,r,i,``):e}case`vim_delete_word_end`:case`vim_change_word_end`:{let{count:a}=t.payload,o=r,s=i,c=r,l=i;for(let e=0;e<a;e++){let t=j$(n,o,s,!1);if(t){if(c=t.row,l=t.col+1,e<a-1){let e=j$(n,t.row,t.col+1,!0);if(e)o=e.row,s=e.col;else break}}else break}if(c<n.length){let e=u$(n[c]||``);l=Math.min(l,e)}return c!==r||l!==i?F$(V$(e),r,i,c,l,``):e}case`vim_delete_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=n.length;if(o===1||a>=o)return{...V$(e),lines:[``],cursorRow:0,cursorCol:0,preferredCol:null};let s=V$(e),c=[...s.lines];c.splice(r,a);let l=Math.min(r,c.length-1);return{...s,lines:c,cursorRow:l,cursorCol:0,preferredCol:null}}case`vim_change_line`:{let{count:i}=t.payload;if(n.length===0)return e;let a=Math.min(i,n.length-r),o=V$(e),{startOffset:s,endOffset:c}=P$(r,a,o.lines),{startRow:l,startCol:u,endRow:d,endCol:f}=N$(s,c,o.lines);return F$(o,l,u,d,f,``)}case`vim_delete_to_end_of_line`:case`vim_change_to_end_of_line`:{let t=n[r]||``;return i<u$(t)?F$(V$(e),r,i,r,u$(t),``):e}case`vim_change_movement`:{let{movement:a,count:o}=t.payload,s=n.length;switch(a){case`h`:{let t=Math.max(0,i-o);return F$(V$(e),r,t,r,i,``)}case`j`:{let t=Math.min(o,s-r);if(t>0)if(s===1){let t=e.lines[0]||``;return F$(V$(e),0,0,0,u$(t),``)}else{let n=V$(e),{startOffset:i,endOffset:a}=P$(r,t,n.lines),{startRow:o,startCol:s,endRow:c,endCol:l}=N$(i,a,n.lines);return F$(n,o,s,c,l,``)}return e}case`k`:if(Math.min(o,r+1)>0)if(e.lines.length===1){let t=e.lines[0]||``;return F$(V$(e),0,0,0,u$(t),``)}else{let t=Math.max(0,r-o+1),n=r-t+1,i=V$(e),{startOffset:a,endOffset:s}=P$(t,n,i.lines),{startRow:c,startCol:l,endRow:u,endCol:d}=N$(a,s,i.lines);return{...F$(i,c,l,u,d,``),cursorRow:t,cursorCol:0}}return e;case`l`:return F$(V$(e),r,i,r,Math.min(u$(n[r]||``),i+o),``);default:return e}}case`vim_move_left`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++)if(s>0)s--;else if(o>0){o--;let e=u$(a[o]||``);s=e===0?0:e-1}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_right`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=r,s=i;for(let e=0;e<n;e++){let e=a[o]||``,t=u$(e);if(t===0)o<a.length-1&&(o++,s=0);else if(s<t-1){s++;let n=l$(e);for(;s<n.length&&w$(n[s])&&s<t-1;)s++}else o<a.length-1&&(o++,s=0)}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_up`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.max(0,r-n),s=u$(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_down`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=Math.min(a.length-1,r+n),s=u$(a[o]||``),c=Math.min(i,s>0?s-1:0);return{...e,cursorRow:o,cursorCol:c,preferredCol:null}}case`vim_move_word_forward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=j$(n,o,s,!0);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_backward`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){let e=M$(n,o,s);if(e)o=e.row,s=e.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_move_word_end`:{let{count:a}=t.payload,o=r,s=i;for(let e=0;e<a;e++){if(e===0){let e=l$(n[o]||``);if(s<e.length&&S$(e[s])&&(s+1>=e.length||!T$(e[s+1])||S$(e[s])&&h$(e,s))){let e=j$(n,o,s+1,!1);if(e){o=e.row,s=e.col;continue}}}let t=j$(n,o,s,!1);if(t)o=t.row,s=t.col;else break}return{...e,cursorRow:o,cursorCol:s,preferredCol:null}}case`vim_delete_char`:{let{count:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a}=e,o=u$(a[r]||``);if(i<o){let t=Math.min(n,o-i);return F$(V$(e),r,i,r,i+t,``)}return e}case`vim_insert_at_cursor`:return e;case`vim_append_at_cursor`:{let{cursorRow:t,cursorCol:n,lines:r}=e,i=n<u$(r[t]||``)?n+1:n;return{...e,cursorCol:i,preferredCol:null}}case`vim_open_line_below`:{let{cursorRow:t,lines:n}=e,r=V$(e),i=u$(n[t]||``);return F$(r,t,i,t,i,`
12667
+ `)}case`vim_open_line_above`:{let{cursorRow:t}=e;return{...F$(V$(e),t,0,t,0,`
12668
+ `),cursorRow:t,cursorCol:0}}case`vim_append_at_line_end`:{let{cursorRow:t,lines:n}=e,r=u$(n[t]||``);return{...e,cursorCol:r,preferredCol:null}}case`vim_insert_at_line_start`:{let{cursorRow:t,lines:n}=e,r=n[t]||``,i=0,a=l$(r);for(;i<a.length&&/\s/.test(a[i]);)i++;return{...e,cursorCol:i,preferredCol:null}}case`vim_move_to_line_start`:return{...e,cursorCol:0,preferredCol:null};case`vim_move_to_line_end`:{let{cursorRow:t,lines:n}=e,r=u$(n[t]||``);return{...e,cursorCol:r>0?r-1:0,preferredCol:null}}case`vim_move_to_first_nonwhitespace`:{let{cursorRow:t,lines:n}=e,r=n[t]||``,i=0,a=l$(r);for(;i<a.length&&/\s/.test(a[i]);)i++;return{...e,cursorCol:i,preferredCol:null}}case`vim_move_to_first_line`:return{...e,cursorRow:0,cursorCol:0,preferredCol:null};case`vim_move_to_last_line`:{let{lines:t}=e,n=t.length-1;return{...e,cursorRow:n,cursorCol:0,preferredCol:null}}case`vim_move_to_line`:{let{lineNumber:n}=t.payload,{lines:r}=e,i=Math.min(Math.max(0,n-1),r.length-1);return{...e,cursorRow:i,cursorCol:0,preferredCol:null}}case`vim_escape_insert_mode`:{let{cursorCol:t}=e,n=t>0?t-1:0;return{...e,cursorCol:n,preferredCol:null}}default:return e}}let _$=0;const v$=/\[Pasted text (#\d+) \+\d+ lines\]/g;function y$(e){return e.length>500?!0:e.split(/\r\n|\r|\n/).length>5}function b$(e){_$++;let t=`#${_$}`;return{placeholder:`[Pasted text ${t} +${e.split(/\r\n|\r|\n/).length} lines]`,id:t}}function x$(e){return e===void 0?!1:!/[\s,.;!?]/.test(e)}const S$=e=>/[\w\p{L}\p{N}]/u.test(e),C$=e=>/\s/.test(e),w$=e=>/\p{M}/u.test(e),T$=e=>S$(e)||w$(e),E$=e=>/[\p{Script=Latin}]/u.test(e)?`latin`:/[\p{Script=Han}]/u.test(e)?`han`:/[\p{Script=Arabic}]/u.test(e)?`arabic`:/[\p{Script=Hiragana}]/u.test(e)?`hiragana`:/[\p{Script=Katakana}]/u.test(e)?`katakana`:/[\p{Script=Cyrillic}]/u.test(e)?`cyrillic`:`other`,D$=(e,t)=>!S$(e)||!S$(t)?!1:E$(e)!==E$(t),O$=(e,t)=>{let n=l$(e),r=t;if(r>=n.length)return null;let i=n[r];if(S$(i))for(;r<n.length&&T$(n[r]);){if(r+1<n.length&&S$(n[r+1])&&D$(n[r],n[r+1])){r++;break}r++}else if(!C$(i))for(;r<n.length&&!S$(n[r])&&!C$(n[r]);)r++;for(;r<n.length&&C$(n[r]);)r++;return r<n.length?r:null},k$=(e,t)=>{let n=l$(e),r=t;if(r<=0)return null;for(r--;r>=0&&C$(n[r]);)r--;if(r<0)return null;if(S$(n[r])){for(;r>=0&&S$(n[r]);){if(r-1>=0&&S$(n[r-1])&&D$(n[r],n[r-1]))return r;r--}return r+1}else{for(;r>=0&&!S$(n[r])&&!C$(n[r]);)r--;return r+1}},A$=(e,t)=>{let n=l$(e),r=t,i=r<n.length&&T$(n[r])&&(r+1>=n.length||!T$(n[r+1])||S$(n[r])&&r+1<n.length&&S$(n[r+1])&&D$(n[r],n[r+1])),a=r<n.length&&!T$(n[r])&&!C$(n[r])&&(r+1>=n.length||C$(n[r+1])||T$(n[r+1]));if(i||a)for(r++;r<n.length&&C$(n[r]);)r++;if(r<n.length&&!T$(n[r]))for(;r<n.length&&C$(n[r]);)r++;let o=!1,s=-1;if(r<n.length&&T$(n[r]))for(;r<n.length&&T$(n[r]);){if(o=!0,S$(n[r])&&(s=r),r+1<n.length&&S$(n[r+1])&&D$(n[r],n[r+1])){r++,S$(n[r-1])&&(s=r-1);break}r++}else if(r<n.length&&!C$(n[r]))for(;r<n.length&&!S$(n[r])&&!C$(n[r]);)o=!0,s=r,r++;return o&&s>=t?s:null},j$=(e,t,n,r)=>{let i=e[t]||``,a=r?O$(i,n):A$(i,n);if(a!==null)return{row:t,col:a};for(let n=t+1;n<e.length;n++){let t=e[n]||``,i=l$(t);if(i.length===0){let t=!1;for(let r=n+1;r<e.length;r++){let n=l$(e[r]||``),i=0;for(;i<n.length&&C$(n[i]);)i++;if(i<n.length){t=!0;break}}if(!t)return{row:n,col:0};continue}let a=0;for(;a<i.length&&C$(i[a]);)a++;if(a<i.length){if(r)return{row:n,col:a};{let e=A$(t,a);if(e!==null)return{row:n,col:e}}}}return null},M$=(e,t,n)=>{let r=k$(e[t]||``,n);if(r!==null)return{row:t,col:r};for(let n=t-1;n>=0;n--){let t=e[n]||``,r=l$(t);if(r.length===0)continue;let i=r.length;for(;i>0&&C$(r[i-1]);)i--;if(i>0){let e=k$(t,i);if(e!==null)return{row:n,col:e}}}return null},N$=(e,t,n)=>{let r=0,i=0,a=0,o=0,s=0;for(let t=0;t<n.length;t++){let o=n[t].length+1;if(r+o>e){i=t,a=e-r;break}r+=o}r=0;for(let e=0;e<n.length;e++){let i=n[e].length+(e<n.length-1?1:0);if(r+i>=t){o=e,s=t-r;break}r+=i}return{startRow:i,startCol:a,endRow:o,endCol:s}},P$=(e,t,n)=>{let r=0;for(let t=0;t<e;t++)r+=n[t].length+1;let i=r;for(let r=0;r<t;r++){let t=e+r;t<n.length&&(i+=n[t].length,t<n.length-1&&(i+=1))}return{startOffset:r,endOffset:i}},F$=(e,t,n,r,i,a)=>{let o=t=>e.lines[t]||``,s=e=>u$(o(e)),c=(e,t,n)=>Math.min(Math.max(e,t),n);if(t>r||t===r&&n>i||t<0||n<0||r>=e.lines.length||r<e.lines.length&&i>s(r))return e;let l=[...e.lines],u=c(n,0,s(t)),d=c(i,0,s(r)),f=d$(o(t),0,u),p=d$(o(r),d),m=a.replace(/\r\n/g,`
12669
12669
  `).replace(/\r/g,`
12670
12670
  `).split(`
12671
- `),h=f+m[0];if(m.length===1)l.splice(t,r-t+1,h+p);else{let e=m[m.length-1]+p,n=m.slice(1,-1);l.splice(t,r-t+1,h,...n,e)}let g=t+m.length-1,_=(m.length>1?0:u)+l$(m[m.length-1]);return{...e,lines:l,cursorRow:Math.min(Math.max(g,0),l.length-1),cursorCol:Math.max(0,Math.min(_,l$(l[g]||``))),preferredCol:null}};function F$(e,t,n){return e<t?t:e>n?n:e}function I$(e,t){let n=t,r=0;for(;r<e.length;){let t=l$(e[r]),i=t+(r<e.length-1?1:0);if(n<=t)return[r,n];n-=i,r++}if(e.length>0){let t=e.length-1;return[t,l$(e[t])]}return[0,0]}function L$(e,t){let n=0,r=0,i=0;if(t===0)return[0,0];let a=e.split(`
12672
- `);for(let e=0;e<a.length;e++){let o=a[e],s=l$(o),c=s+(e<a.length-1?1:0);if(t<=i+s)return n=e,r=t-i,[n,r];if(t<=i+c)return n=e,r=s,t===i+c&&e<a.length-1?[e+1,0]:[n,r];i+=c}return a.length>0?(n=a.length-1,r=l$(a[n])):(n=0,r=0),[n,r]}function R$(e,t){let n=[],r=[],i=[];return e.forEach((e,a)=>{if(r[a]=[],e.length===0)r[a].push([n.length,0]),i.push([a,0]),n.push(``);else{let o=0,s=c$(e);for(;o<s.length;){let e=``,c=0,l=0,u=-1,d=0;for(let n=o;n<s.length;n++){let r=s[n],i=p$(r);if(c+i>t){u!==-1&&d>0&&o+d<n?(e=s.slice(o,o+d).join(``),l=d):l===0&&i>t&&(e=r,l=1);break}e+=r,c+=i,l++,r===` `&&(u=n,d=l-1)}l===0&&o<s.length&&(e=s[o],l=1),l===0&&o<s.length&&(e=s[o],l=1),r[a].push([n.length,o]),i.push([a,o]),n.push(e);let f=o;o+=l,f+l<s.length&&o<s.length&&s[o]===` `&&o++}}}),(e.length===0||e.length===1&&e[0]===``)&&n.length===0&&(n.push(``),r[0]||=[],r[0].push([0,0]),i.push([0,0])),{visualLines:n,logicalToVisualMap:r,visualToLogicalMap:i}}function z$(e,t){let{logicalToVisualMap:n,visualLines:r}=e,[i,a]=t,o=n[i];if(!o||o.length===0)return[0,0];let s=o.findIndex(([,e],t)=>{let n=t+1<o.length?o[t+1][1]:1/0;return a>=e&&a<n});s===-1&&(s=a===0?0:o.length-1);let[c,l]=o[s],u=a-l;return[c,Math.min(u,l$(r[c]??``))]}const B$=e=>{let t={lines:[...e.lines],cursorRow:e.cursorRow,cursorCol:e.cursorCol},n=[...e.undoStack,t];return n.length>100&&n.shift(),{...e,undoStack:n,redoStack:[]}};function V$(e,t){let n=B$,r=t=>e.lines[t]??``,i=e=>l$(r(e));switch(t.type){case`set_text`:{let r=e;t.pushToUndo!==!1&&(r=n(e));let i=t.payload.replace(/\r\n?/g,`
12671
+ `),h=f+m[0];if(m.length===1)l.splice(t,r-t+1,h+p);else{let e=m[m.length-1]+p,n=m.slice(1,-1);l.splice(t,r-t+1,h,...n,e)}let g=t+m.length-1,_=(m.length>1?0:u)+u$(m[m.length-1]);return{...e,lines:l,cursorRow:Math.min(Math.max(g,0),l.length-1),cursorCol:Math.max(0,Math.min(_,u$(l[g]||``))),preferredCol:null}};function I$(e,t,n){return e<t?t:e>n?n:e}function L$(e,t){let n=t,r=0;for(;r<e.length;){let t=u$(e[r]),i=t+(r<e.length-1?1:0);if(n<=t)return[r,n];n-=i,r++}if(e.length>0){let t=e.length-1;return[t,u$(e[t])]}return[0,0]}function R$(e,t){let n=0,r=0,i=0;if(t===0)return[0,0];let a=e.split(`
12672
+ `);for(let e=0;e<a.length;e++){let o=a[e],s=u$(o),c=s+(e<a.length-1?1:0);if(t<=i+s)return n=e,r=t-i,[n,r];if(t<=i+c)return n=e,r=s,t===i+c&&e<a.length-1?[e+1,0]:[n,r];i+=c}return a.length>0?(n=a.length-1,r=u$(a[n])):(n=0,r=0),[n,r]}function z$(e,t){let n=[],r=[],i=[];return e.forEach((e,a)=>{if(r[a]=[],e.length===0)r[a].push([n.length,0]),i.push([a,0]),n.push(``);else{let o=0,s=l$(e);for(;o<s.length;){let e=``,c=0,l=0,u=-1,d=0;for(let n=o;n<s.length;n++){let r=s[n],i=m$(r);if(c+i>t){u!==-1&&d>0&&o+d<n?(e=s.slice(o,o+d).join(``),l=d):l===0&&i>t&&(e=r,l=1);break}e+=r,c+=i,l++,r===` `&&(u=n,d=l-1)}l===0&&o<s.length&&(e=s[o],l=1),l===0&&o<s.length&&(e=s[o],l=1),r[a].push([n.length,o]),i.push([a,o]),n.push(e);let f=o;o+=l,f+l<s.length&&o<s.length&&s[o]===` `&&o++}}}),(e.length===0||e.length===1&&e[0]===``)&&n.length===0&&(n.push(``),r[0]||=[],r[0].push([0,0]),i.push([0,0])),{visualLines:n,logicalToVisualMap:r,visualToLogicalMap:i}}function B$(e,t){let{logicalToVisualMap:n,visualLines:r}=e,[i,a]=t,o=n[i];if(!o||o.length===0)return[0,0];let s=o.findIndex(([,e],t)=>{let n=t+1<o.length?o[t+1][1]:1/0;return a>=e&&a<n});s===-1&&(s=a===0?0:o.length-1);let[c,l]=o[s],u=a-l;return[c,Math.min(u,u$(r[c]??``))]}const V$=e=>{let t={lines:[...e.lines],cursorRow:e.cursorRow,cursorCol:e.cursorCol},n=[...e.undoStack,t];return n.length>100&&n.shift(),{...e,undoStack:n,redoStack:[]}};function H$(e,t){let n=V$,r=t=>e.lines[t]??``,i=e=>u$(r(e));switch(t.type){case`set_text`:{let r=e;t.pushToUndo!==!1&&(r=n(e));let i=t.payload.replace(/\r\n?/g,`
12673
12673
  `).split(`
12674
- `),a=i.length===0?[``]:i,o=a.length-1;return{...r,lines:a,cursorRow:o,cursorCol:l$(a[o]??``),preferredCol:null}}case`insert`:{let r=n(e),i=[...r.lines],a=r.cursorRow,o=r.cursorCol,s=e=>i[e]??``,c=d$(t.payload.replace(/\r\n/g,`
12674
+ `),a=i.length===0?[``]:i,o=a.length-1;return{...r,lines:a,cursorRow:o,cursorCol:u$(a[o]??``),preferredCol:null}}case`insert`:{let r=n(e),i=[...r.lines],a=r.cursorRow,o=r.cursorCol,s=e=>i[e]??``,c=f$(t.payload.replace(/\r\n/g,`
12675
12675
  `).replace(/\r/g,`
12676
12676
  `)).split(`
12677
- `),l=s(a),u=u$(l,0,o),d=u$(l,o);if(c.length>1){i[a]=u+c[0];let e=c.slice(1),t=e.pop()??``;i.splice(a+1,0,...e),i.splice(a+c.length-1,0,t+d),a=a+c.length-1,o=l$(t)}else i[a]=u+c[0]+d,o=l$(u)+l$(c[0]);return{...r,lines:i,cursorRow:a,cursorCol:o,preferredCol:null}}case`backspace`:{let t=n(e),r=[...t.lines],i=t.cursorRow,a=t.cursorCol,o=e=>r[e]??``;if(a===0&&i===0)return e;if(a>0){let e=o(i);r[i]=u$(e,0,a-1)+u$(e,a),a--}else if(i>0){let e=o(i-1),t=o(i),n=l$(e);r[i-1]=e+t,r.splice(i,1),i--,a=n}return{...t,lines:r,cursorRow:i,cursorCol:a,preferredCol:null}}case`set_viewport`:{let{width:n,height:r}=t.payload;return n===e.viewportWidth&&r===e.viewportHeight?e:{...e,viewportWidth:n,viewportHeight:r}}case`move`:{let{dir:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a,visualLayout:o,preferredCol:s}=e;if(n===`left`||n===`right`||n===`up`||n===`down`||n===`home`||n===`end`){let t=z$(o,[r,i]),{visualLines:c,visualToLogicalMap:l}=o,u=t[0],d=t[1],f=s,p=l$(c[u]??``);switch(n){case`left`:f=null,d>0?d--:u>0&&(u--,d=l$(c[u]??``));break;case`right`:f=null,d<p?d++:u<c.length-1&&(u++,d=0);break;case`up`:u>0&&(f===null&&(f=d),u--,d=F$(f,0,l$(c[u]??``)));break;case`down`:u<c.length-1&&(f===null&&(f=d),u++,d=F$(f,0,l$(c[u]??``)));break;case`home`:f=null,d=0;break;case`end`:f=null,d=p;break;default:{let t=n;return console.error(`Unknown visual movement direction: ${String(t)}`),e}}if(l[u]){let[t,n]=l[u];return{...e,cursorRow:t,cursorCol:F$(n+d,0,l$(a[t]??``)),preferredCol:f}}return e}switch(n){case`wordLeft`:{if(i===0&&r===0)return e;let t=r,n=i;if(i===0)t--,n=l$(a[t]??``);else{let e=a[r],t=c$(e),o=i,s=!0;for(let e=0;e<o;e++)if(b$(t[e])){s=!1;break}if(s&&o>0)o--;else{for(;o>0&&!b$(t[o-1]);)o--;for(;o>0&&b$(t[o-1]);)o--}n=o}return{...e,cursorRow:t,cursorCol:n,preferredCol:null}}case`wordRight`:{if(r===a.length-1&&i===l$(a[r]??``))return e;let t=r,n=i,o=c$(a[r]??``);if(i>=o.length)t++,n=0;else{let e=i;for(;e<o.length&&!b$(o[e]);)e++;for(;e<o.length&&b$(o[e]);)e++;n=e}return{...e,cursorRow:t,cursorCol:n,preferredCol:null}}default:return e}}case`set_cursor`:return{...e,...t.payload};case`delete`:{let{cursorRow:t,cursorCol:a,lines:o}=e,s=r(t);if(a<i(t)){let r=n(e),i=[...r.lines];return i[t]=u$(s,0,a)+u$(s,a+1),{...r,lines:i,preferredCol:null}}else if(t<o.length-1){let i=n(e),a=r(t+1),o=[...i.lines];return o[t]=s+a,o.splice(t+1,1),{...i,lines:o,preferredCol:null}}return e}case`delete_word_left`:{let{cursorRow:t,cursorCol:i}=e;if(i===0&&t===0)return e;let a=n(e),o=[...a.lines],s=t,c=i,l=``;if(c>0){let e=r(s),t=O$(e,c),n=t===null?0:t;l=u$(e,n,c),o[s]=u$(e,0,n)+u$(e,c),c=n}else{let e=r(t-1),n=r(t),i=l$(e);l=`
12678
- `,o[t-1]=e+n,o.splice(t,1),s--,c=i}return{...a,lines:o,cursorRow:s,cursorCol:c,preferredCol:null,clipboard:l}}case`delete_word_right`:{let{cursorRow:t,cursorCol:i,lines:a}=e,o=r(t),s=l$(o);if(i>=s&&t===a.length-1)return e;let c=n(e),l=[...c.lines],u=``;if(i>=s){let e=r(t+1);u=`
12679
- `,l[t]=o+e,l.splice(t+1,1)}else{let e=D$(o,i),n=e===null?s:e;n<=i&&(n=s),u=u$(o,i,n),l[t]=u$(o,0,i)+u$(o,n)}return{...c,lines:l,preferredCol:null,clipboard:u}}case`kill_line_right`:{let{cursorRow:t,cursorCol:a,lines:o}=e,s=r(t),c=``;if(a<i(t)){let r=n(e),i=[...r.lines];return c=u$(s,a),i[t]=u$(s,0,a),{...r,lines:i,clipboard:c}}else if(t<o.length-1){let i=n(e),a=r(t+1),o=[...i.lines];return c=`
12680
- `+a,o[t]=s+a,o.splice(t+1,1),{...i,lines:o,preferredCol:null,clipboard:c}}return e}case`kill_line_left`:{let{cursorRow:t,cursorCol:i}=e;if(i>0){let a=n(e),o=r(t),s=[...a.lines],c=u$(o,0,i);return s[t]=u$(o,i),{...a,lines:s,cursorCol:0,preferredCol:null,clipboard:c}}return e}case`yank`:{if(!e.clipboard)return e;let t=n(e),i=[...t.lines],a=t.cursorRow,o=t.cursorCol,s=r(a),c=u$(s,0,o),l=u$(s,o),u=e.clipboard.replace(/\r\n/g,`
12677
+ `),l=s(a),u=d$(l,0,o),d=d$(l,o);if(c.length>1){i[a]=u+c[0];let e=c.slice(1),t=e.pop()??``;i.splice(a+1,0,...e),i.splice(a+c.length-1,0,t+d),a=a+c.length-1,o=u$(t)}else i[a]=u+c[0]+d,o=u$(u)+u$(c[0]);return{...r,lines:i,cursorRow:a,cursorCol:o,preferredCol:null}}case`backspace`:{let t=n(e),r=[...t.lines],i=t.cursorRow,a=t.cursorCol,o=e=>r[e]??``;if(a===0&&i===0)return e;if(a>0){let e=o(i);r[i]=d$(e,0,a-1)+d$(e,a),a--}else if(i>0){let e=o(i-1),t=o(i),n=u$(e);r[i-1]=e+t,r.splice(i,1),i--,a=n}return{...t,lines:r,cursorRow:i,cursorCol:a,preferredCol:null}}case`set_viewport`:{let{width:n,height:r}=t.payload;return n===e.viewportWidth&&r===e.viewportHeight?e:{...e,viewportWidth:n,viewportHeight:r}}case`move`:{let{dir:n}=t.payload,{cursorRow:r,cursorCol:i,lines:a,visualLayout:o,preferredCol:s}=e;if(n===`left`||n===`right`||n===`up`||n===`down`||n===`home`||n===`end`){let t=B$(o,[r,i]),{visualLines:c,visualToLogicalMap:l}=o,u=t[0],d=t[1],f=s,p=u$(c[u]??``);switch(n){case`left`:f=null,d>0?d--:u>0&&(u--,d=u$(c[u]??``));break;case`right`:f=null,d<p?d++:u<c.length-1&&(u++,d=0);break;case`up`:u>0&&(f===null&&(f=d),u--,d=I$(f,0,u$(c[u]??``)));break;case`down`:u<c.length-1&&(f===null&&(f=d),u++,d=I$(f,0,u$(c[u]??``)));break;case`home`:f=null,d=0;break;case`end`:f=null,d=p;break;default:{let t=n;return console.error(`Unknown visual movement direction: ${String(t)}`),e}}if(l[u]){let[t,n]=l[u];return{...e,cursorRow:t,cursorCol:I$(n+d,0,u$(a[t]??``)),preferredCol:f}}return e}switch(n){case`wordLeft`:{if(i===0&&r===0)return e;let t=r,n=i;if(i===0)t--,n=u$(a[t]??``);else{let e=a[r],t=l$(e),o=i,s=!0;for(let e=0;e<o;e++)if(x$(t[e])){s=!1;break}if(s&&o>0)o--;else{for(;o>0&&!x$(t[o-1]);)o--;for(;o>0&&x$(t[o-1]);)o--}n=o}return{...e,cursorRow:t,cursorCol:n,preferredCol:null}}case`wordRight`:{if(r===a.length-1&&i===u$(a[r]??``))return e;let t=r,n=i,o=l$(a[r]??``);if(i>=o.length)t++,n=0;else{let e=i;for(;e<o.length&&!x$(o[e]);)e++;for(;e<o.length&&x$(o[e]);)e++;n=e}return{...e,cursorRow:t,cursorCol:n,preferredCol:null}}default:return e}}case`set_cursor`:return{...e,...t.payload};case`delete`:{let{cursorRow:t,cursorCol:a,lines:o}=e,s=r(t);if(a<i(t)){let r=n(e),i=[...r.lines];return i[t]=d$(s,0,a)+d$(s,a+1),{...r,lines:i,preferredCol:null}}else if(t<o.length-1){let i=n(e),a=r(t+1),o=[...i.lines];return o[t]=s+a,o.splice(t+1,1),{...i,lines:o,preferredCol:null}}return e}case`delete_word_left`:{let{cursorRow:t,cursorCol:i}=e;if(i===0&&t===0)return e;let a=n(e),o=[...a.lines],s=t,c=i,l=``;if(c>0){let e=r(s),t=k$(e,c),n=t===null?0:t;l=d$(e,n,c),o[s]=d$(e,0,n)+d$(e,c),c=n}else{let e=r(t-1),n=r(t),i=u$(e);l=`
12678
+ `,o[t-1]=e+n,o.splice(t,1),s--,c=i}return{...a,lines:o,cursorRow:s,cursorCol:c,preferredCol:null,clipboard:l}}case`delete_word_right`:{let{cursorRow:t,cursorCol:i,lines:a}=e,o=r(t),s=u$(o);if(i>=s&&t===a.length-1)return e;let c=n(e),l=[...c.lines],u=``;if(i>=s){let e=r(t+1);u=`
12679
+ `,l[t]=o+e,l.splice(t+1,1)}else{let e=O$(o,i),n=e===null?s:e;n<=i&&(n=s),u=d$(o,i,n),l[t]=d$(o,0,i)+d$(o,n)}return{...c,lines:l,preferredCol:null,clipboard:u}}case`kill_line_right`:{let{cursorRow:t,cursorCol:a,lines:o}=e,s=r(t),c=``;if(a<i(t)){let r=n(e),i=[...r.lines];return c=d$(s,a),i[t]=d$(s,0,a),{...r,lines:i,clipboard:c}}else if(t<o.length-1){let i=n(e),a=r(t+1),o=[...i.lines];return c=`
12680
+ `+a,o[t]=s+a,o.splice(t+1,1),{...i,lines:o,preferredCol:null,clipboard:c}}return e}case`kill_line_left`:{let{cursorRow:t,cursorCol:i}=e;if(i>0){let a=n(e),o=r(t),s=[...a.lines],c=d$(o,0,i);return s[t]=d$(o,i),{...a,lines:s,cursorCol:0,preferredCol:null,clipboard:c}}return e}case`yank`:{if(!e.clipboard)return e;let t=n(e),i=[...t.lines],a=t.cursorRow,o=t.cursorCol,s=r(a),c=d$(s,0,o),l=d$(s,o),u=e.clipboard.replace(/\r\n/g,`
12681
12681
  `).replace(/\r/g,`
12682
12682
  `).split(`
12683
- `);if(u.length>1){i[a]=c+u[0];let e=u.slice(1,-1),t=u[u.length-1]??``;i.splice(a+1,0,...e,t+l),a=a+u.length-1,o=l$(t)}else i[a]=c+u[0]+l,o=l$(c)+l$(u[0]);return{...t,lines:i,cursorRow:a,cursorCol:o,preferredCol:null}}case`transpose_chars`:{let{cursorRow:t,cursorCol:i}=e,a=r(t),o=l$(a);if(o<2||i===0&&t===0)return e;let s=n(e),c=[...s.lines],l=t,u=i;if(i>0&&i<o){let e=u$(a,0,i-1),n=u$(a,i-1,i),r=u$(a,i,i+1),o=u$(a,i+1);c[t]=e+r+n+o,u=i+1}else if(i===0&&t>0){let e=r(t-1),n=l$(e);if(n>0&&o>0){let r=u$(e,n-1),i=u$(a,0,1);c[t-1]=u$(e,0,n-1)+i,c[t]=r+u$(a,1)}}else if(i===o&&i>0){let e=u$(a,0,i-2),n=u$(a,i-2,i-1);c[t]=e+u$(a,i-1,i)+n,u=i-1}return{...s,lines:c,cursorRow:l,cursorCol:u,preferredCol:null}}case`undo`:{let t=e.undoStack[e.undoStack.length-1];if(!t)return e;let n={lines:[...e.lines],cursorRow:e.cursorRow,cursorCol:e.cursorCol};return{...e,...t,undoStack:e.undoStack.slice(0,-1),redoStack:[...e.redoStack,n]}}case`redo`:{let t=e.redoStack[e.redoStack.length-1];if(!t)return e;let n={lines:[...e.lines],cursorRow:e.cursorRow,cursorCol:e.cursorCol};return{...e,...t,redoStack:e.redoStack.slice(0,-1),undoStack:[...e.undoStack,n]}}case`replace_range`:{let{startRow:r,startCol:i,endRow:a,endCol:o,text:s}=t.payload;return P$(n(e),r,i,a,o,s)}case`move_to_offset`:{let{offset:n}=t.payload,[r,i]=L$(e.lines.join(`
12684
- `),n);return{...e,cursorRow:r,cursorCol:i,preferredCol:null}}case`create_undo_snapshot`:return n(e);case`vim_delete_word_forward`:case`vim_delete_word_backward`:case`vim_delete_word_end`:case`vim_change_word_forward`:case`vim_change_word_backward`:case`vim_change_word_end`:case`vim_delete_line`:case`vim_change_line`:case`vim_delete_to_end_of_line`:case`vim_change_to_end_of_line`:case`vim_change_movement`:case`vim_move_left`:case`vim_move_right`:case`vim_move_up`:case`vim_move_down`:case`vim_move_word_forward`:case`vim_move_word_backward`:case`vim_move_word_end`:case`vim_delete_char`:case`vim_insert_at_cursor`:case`vim_append_at_cursor`:case`vim_open_line_below`:case`vim_open_line_above`:case`vim_append_at_line_end`:case`vim_insert_at_line_start`:case`vim_move_to_line_start`:case`vim_move_to_line_end`:case`vim_move_to_first_nonwhitespace`:case`vim_move_to_first_line`:case`vim_move_to_last_line`:case`vim_move_to_line`:case`vim_escape_insert_mode`:return h$(e,t);default:{let n=t;return console.error(`Unknown action encountered: ${String(n)}`),e}}}function H$(e,t){let n=V$(e,t);return n.lines!==e.lines||n.viewportWidth!==e.viewportWidth?{...n,visualLayout:R$(n.lines,n.viewportWidth)}:n}function U$({initialText:e=``,initialCursorOffset:t=0,viewport:r,stdin:i,setRawMode:a,onChange:o}){let s=(0,Z.useRef)(new Map),[c,l]=(0,Z.useReducer)(H$,(0,Z.useMemo)(()=>{let n=e.split(`
12685
- `),[i,a]=I$(n.length===0?[``]:n,t),o=R$(n.length===0?[``]:n,r.width);return{lines:n.length===0?[``]:n,cursorRow:i,cursorCol:a,preferredCol:null,undoStack:[],redoStack:[],clipboard:null,selectionAnchor:null,viewportWidth:r.width,viewportHeight:r.height,visualLayout:o}},[e,t,r.width,r.height])),{lines:u,cursorRow:f,cursorCol:m,preferredCol:h,selectionAnchor:g,visualLayout:_}=c,v=(0,Z.useMemo)(()=>u.join(`
12686
- `),[u]),y=(0,Z.useMemo)(()=>z$(_,[f,m]),[_,f,m]),{visualLines:b,visualToLogicalMap:x}=_,[S,w]=(0,Z.useState)(0),T=(0,Z.useEffectEvent)(e=>{o?.(e)});(0,Z.useEffect)(()=>{T(v)},[v]),(0,Z.useEffect)(()=>{l({type:`set_viewport`,payload:{width:r.width,height:r.height}})},[r.width,r.height]),(0,Z.useEffect)(()=>{let{height:e}=r,t=b.length,n=Math.max(0,t-e),i=S;y[0]<S?i=y[0]:y[0]>=S+e&&(i=y[0]-e+1),i=F$(i,0,n),i!==S&&w(i)},[y,S,r,b.length]);let E=(0,Z.useCallback)((e,{paste:t=!1,isPaste:n=!1}={})=>{if((t||n)&&v$(e)){let{placeholder:t,id:n}=y$(e);s.current.set(n,e),l({type:`insert`,payload:t});return}if(/[\n\r]/.test(e)){l({type:`insert`,payload:e});return}let r=``;for(let t of c$(e))t.codePointAt(0)===127?(r.length>0&&(l({type:`insert`,payload:r}),r=``),l({type:`backspace`})):r+=t;r.length>0&&l({type:`insert`,payload:r})},[]),D=(0,Z.useCallback)(()=>{l({type:`insert`,payload:`
12687
- `})},[]),O=(0,Z.useCallback)(()=>{l({type:`backspace`})},[]),k=(0,Z.useCallback)(()=>{l({type:`delete`})},[]),A=(0,Z.useCallback)(e=>{l({type:`move`,payload:{dir:e}})},[l]),j=(0,Z.useCallback)(()=>{l({type:`undo`})},[]),M=(0,Z.useCallback)(()=>{l({type:`redo`})},[]),N=(0,Z.useCallback)(e=>{e||s.current.clear(),l({type:`set_text`,payload:e})},[]),P=(0,Z.useCallback)(e=>e.replace(_$,(e,t)=>s.current.get(t)??`[Pasted text ${t}]`),[]),F=(0,Z.useCallback)(()=>{l({type:`delete_word_left`})},[]),I=(0,Z.useCallback)(()=>{l({type:`delete_word_right`})},[]),L=(0,Z.useCallback)(()=>{l({type:`kill_line_right`})},[]),R=(0,Z.useCallback)(()=>{l({type:`kill_line_left`})},[]),z=(0,Z.useCallback)(()=>{l({type:`yank`})},[]),B=(0,Z.useCallback)(()=>{l({type:`transpose_chars`})},[]),V=(0,Z.useCallback)(e=>{l({type:`vim_delete_word_forward`,payload:{count:e}})},[]),H=(0,Z.useCallback)(e=>{l({type:`vim_delete_word_backward`,payload:{count:e}})},[]),ee=(0,Z.useCallback)(e=>{l({type:`vim_delete_word_end`,payload:{count:e}})},[]),te=(0,Z.useCallback)(e=>{l({type:`vim_change_word_forward`,payload:{count:e}})},[]),ne=(0,Z.useCallback)(e=>{l({type:`vim_change_word_backward`,payload:{count:e}})},[]),re=(0,Z.useCallback)(e=>{l({type:`vim_change_word_end`,payload:{count:e}})},[]),ie=(0,Z.useCallback)(e=>{l({type:`vim_delete_line`,payload:{count:e}})},[]),ae=(0,Z.useCallback)(e=>{l({type:`vim_change_line`,payload:{count:e}})},[]),oe=(0,Z.useCallback)(()=>{l({type:`vim_delete_to_end_of_line`})},[]),se=(0,Z.useCallback)(()=>{l({type:`vim_change_to_end_of_line`})},[]),ce=(0,Z.useCallback)((e,t)=>{l({type:`vim_change_movement`,payload:{movement:e,count:t}})},[]),le=(0,Z.useCallback)(e=>{l({type:`vim_move_left`,payload:{count:e}})},[]),U=(0,Z.useCallback)(e=>{l({type:`vim_move_right`,payload:{count:e}})},[]),ue=(0,Z.useCallback)(e=>{l({type:`vim_move_up`,payload:{count:e}})},[]),de=(0,Z.useCallback)(e=>{l({type:`vim_move_down`,payload:{count:e}})},[]),fe=(0,Z.useCallback)(e=>{l({type:`vim_move_word_forward`,payload:{count:e}})},[]),pe=(0,Z.useCallback)(e=>{l({type:`vim_move_word_backward`,payload:{count:e}})},[]),me=(0,Z.useCallback)(e=>{l({type:`vim_move_word_end`,payload:{count:e}})},[]),he=(0,Z.useCallback)(e=>{l({type:`vim_delete_char`,payload:{count:e}})},[]),ge=(0,Z.useCallback)(()=>{l({type:`vim_insert_at_cursor`})},[]),_e=(0,Z.useCallback)(()=>{l({type:`vim_append_at_cursor`})},[]),W=(0,Z.useCallback)(()=>{l({type:`vim_open_line_below`})},[]),ve=(0,Z.useCallback)(()=>{l({type:`vim_open_line_above`})},[]),ye=(0,Z.useCallback)(()=>{l({type:`vim_append_at_line_end`})},[]),be=(0,Z.useCallback)(()=>{l({type:`vim_insert_at_line_start`})},[]),G=(0,Z.useCallback)(()=>{l({type:`vim_move_to_line_start`})},[]),xe=(0,Z.useCallback)(()=>{l({type:`vim_move_to_line_end`})},[]),Se=(0,Z.useCallback)(()=>{l({type:`vim_move_to_first_nonwhitespace`})},[]),Ce=(0,Z.useCallback)(()=>{l({type:`vim_move_to_first_line`})},[]),we=(0,Z.useCallback)(()=>{l({type:`vim_move_to_last_line`})},[]),Te=(0,Z.useCallback)(e=>{l({type:`vim_move_to_line`,payload:{lineNumber:e}})},[]),Ee=(0,Z.useCallback)(()=>{l({type:`vim_escape_insert_mode`})},[]),De=(0,Z.useCallback)(async(e={})=>{let t=e.editor??process.env.VISUAL??process.env.EDITOR??(process.platform===`win32`?`notepad`:`vi`),r=p.mkdtempSync(C.join(n.tmpdir(),`gemini-edit-`)),o=C.join(r,`buffer.txt`);p.writeFileSync(o,v,`utf8`),l({type:`create_undo_snapshot`});let s=i?.isRaw??!1;try{a?.(!1);let{status:e,error:n}=d(t,[o],{stdio:`inherit`});if(n)throw n;if(typeof e==`number`&&e!==0)throw Error(`External editor exited with status ${e}`);let r=p.readFileSync(o,`utf8`);r=r.replace(/\r\n?/g,`
12683
+ `);if(u.length>1){i[a]=c+u[0];let e=u.slice(1,-1),t=u[u.length-1]??``;i.splice(a+1,0,...e,t+l),a=a+u.length-1,o=u$(t)}else i[a]=c+u[0]+l,o=u$(c)+u$(u[0]);return{...t,lines:i,cursorRow:a,cursorCol:o,preferredCol:null}}case`transpose_chars`:{let{cursorRow:t,cursorCol:i}=e,a=r(t),o=u$(a);if(o<2||i===0&&t===0)return e;let s=n(e),c=[...s.lines],l=t,u=i;if(i>0&&i<o){let e=d$(a,0,i-1),n=d$(a,i-1,i),r=d$(a,i,i+1),o=d$(a,i+1);c[t]=e+r+n+o,u=i+1}else if(i===0&&t>0){let e=r(t-1),n=u$(e);if(n>0&&o>0){let r=d$(e,n-1),i=d$(a,0,1);c[t-1]=d$(e,0,n-1)+i,c[t]=r+d$(a,1)}}else if(i===o&&i>0){let e=d$(a,0,i-2),n=d$(a,i-2,i-1);c[t]=e+d$(a,i-1,i)+n,u=i-1}return{...s,lines:c,cursorRow:l,cursorCol:u,preferredCol:null}}case`undo`:{let t=e.undoStack[e.undoStack.length-1];if(!t)return e;let n={lines:[...e.lines],cursorRow:e.cursorRow,cursorCol:e.cursorCol};return{...e,...t,undoStack:e.undoStack.slice(0,-1),redoStack:[...e.redoStack,n]}}case`redo`:{let t=e.redoStack[e.redoStack.length-1];if(!t)return e;let n={lines:[...e.lines],cursorRow:e.cursorRow,cursorCol:e.cursorCol};return{...e,...t,redoStack:e.redoStack.slice(0,-1),undoStack:[...e.undoStack,n]}}case`replace_range`:{let{startRow:r,startCol:i,endRow:a,endCol:o,text:s}=t.payload;return F$(n(e),r,i,a,o,s)}case`move_to_offset`:{let{offset:n}=t.payload,[r,i]=R$(e.lines.join(`
12684
+ `),n);return{...e,cursorRow:r,cursorCol:i,preferredCol:null}}case`create_undo_snapshot`:return n(e);case`vim_delete_word_forward`:case`vim_delete_word_backward`:case`vim_delete_word_end`:case`vim_change_word_forward`:case`vim_change_word_backward`:case`vim_change_word_end`:case`vim_delete_line`:case`vim_change_line`:case`vim_delete_to_end_of_line`:case`vim_change_to_end_of_line`:case`vim_change_movement`:case`vim_move_left`:case`vim_move_right`:case`vim_move_up`:case`vim_move_down`:case`vim_move_word_forward`:case`vim_move_word_backward`:case`vim_move_word_end`:case`vim_delete_char`:case`vim_insert_at_cursor`:case`vim_append_at_cursor`:case`vim_open_line_below`:case`vim_open_line_above`:case`vim_append_at_line_end`:case`vim_insert_at_line_start`:case`vim_move_to_line_start`:case`vim_move_to_line_end`:case`vim_move_to_first_nonwhitespace`:case`vim_move_to_first_line`:case`vim_move_to_last_line`:case`vim_move_to_line`:case`vim_escape_insert_mode`:return g$(e,t);default:{let n=t;return console.error(`Unknown action encountered: ${String(n)}`),e}}}function U$(e,t){let n=H$(e,t);return n.lines!==e.lines||n.viewportWidth!==e.viewportWidth?{...n,visualLayout:z$(n.lines,n.viewportWidth)}:n}function W$({initialText:e=``,initialCursorOffset:t=0,viewport:r,stdin:i,setRawMode:a,onChange:o}){let s=(0,Z.useRef)(new Map),[c,l]=(0,Z.useReducer)(U$,(0,Z.useMemo)(()=>{let n=e.split(`
12685
+ `),[i,a]=L$(n.length===0?[``]:n,t),o=z$(n.length===0?[``]:n,r.width);return{lines:n.length===0?[``]:n,cursorRow:i,cursorCol:a,preferredCol:null,undoStack:[],redoStack:[],clipboard:null,selectionAnchor:null,viewportWidth:r.width,viewportHeight:r.height,visualLayout:o}},[e,t,r.width,r.height])),{lines:u,cursorRow:f,cursorCol:m,preferredCol:h,selectionAnchor:g,visualLayout:_}=c,v=(0,Z.useMemo)(()=>u.join(`
12686
+ `),[u]),y=(0,Z.useMemo)(()=>B$(_,[f,m]),[_,f,m]),{visualLines:b,visualToLogicalMap:x}=_,[S,w]=(0,Z.useState)(0),T=(0,Z.useEffectEvent)(e=>{o?.(e)});(0,Z.useEffect)(()=>{T(v)},[v]),(0,Z.useEffect)(()=>{l({type:`set_viewport`,payload:{width:r.width,height:r.height}})},[r.width,r.height]),(0,Z.useEffect)(()=>{let{height:e}=r,t=b.length,n=Math.max(0,t-e),i=S;y[0]<S?i=y[0]:y[0]>=S+e&&(i=y[0]-e+1),i=I$(i,0,n),i!==S&&w(i)},[y,S,r,b.length]);let E=(0,Z.useCallback)((e,{paste:t=!1,isPaste:n=!1}={})=>{if((t||n)&&y$(e)){let{placeholder:t,id:n}=b$(e);s.current.set(n,e),l({type:`insert`,payload:t});return}if(/[\n\r]/.test(e)){l({type:`insert`,payload:e});return}let r=``;for(let t of l$(e))t.codePointAt(0)===127?(r.length>0&&(l({type:`insert`,payload:r}),r=``),l({type:`backspace`})):r+=t;r.length>0&&l({type:`insert`,payload:r})},[]),D=(0,Z.useCallback)(()=>{l({type:`insert`,payload:`
12687
+ `})},[]),O=(0,Z.useCallback)(()=>{l({type:`backspace`})},[]),k=(0,Z.useCallback)(()=>{l({type:`delete`})},[]),A=(0,Z.useCallback)(e=>{l({type:`move`,payload:{dir:e}})},[l]),j=(0,Z.useCallback)(()=>{l({type:`undo`})},[]),M=(0,Z.useCallback)(()=>{l({type:`redo`})},[]),N=(0,Z.useCallback)(e=>{e||s.current.clear(),l({type:`set_text`,payload:e})},[]),P=(0,Z.useCallback)(e=>e.replace(v$,(e,t)=>s.current.get(t)??`[Pasted text ${t}]`),[]),F=(0,Z.useCallback)(()=>{l({type:`delete_word_left`})},[]),I=(0,Z.useCallback)(()=>{l({type:`delete_word_right`})},[]),L=(0,Z.useCallback)(()=>{l({type:`kill_line_right`})},[]),R=(0,Z.useCallback)(()=>{l({type:`kill_line_left`})},[]),z=(0,Z.useCallback)(()=>{l({type:`yank`})},[]),B=(0,Z.useCallback)(()=>{l({type:`transpose_chars`})},[]),V=(0,Z.useCallback)(e=>{l({type:`vim_delete_word_forward`,payload:{count:e}})},[]),H=(0,Z.useCallback)(e=>{l({type:`vim_delete_word_backward`,payload:{count:e}})},[]),ee=(0,Z.useCallback)(e=>{l({type:`vim_delete_word_end`,payload:{count:e}})},[]),te=(0,Z.useCallback)(e=>{l({type:`vim_change_word_forward`,payload:{count:e}})},[]),ne=(0,Z.useCallback)(e=>{l({type:`vim_change_word_backward`,payload:{count:e}})},[]),re=(0,Z.useCallback)(e=>{l({type:`vim_change_word_end`,payload:{count:e}})},[]),ie=(0,Z.useCallback)(e=>{l({type:`vim_delete_line`,payload:{count:e}})},[]),ae=(0,Z.useCallback)(e=>{l({type:`vim_change_line`,payload:{count:e}})},[]),oe=(0,Z.useCallback)(()=>{l({type:`vim_delete_to_end_of_line`})},[]),se=(0,Z.useCallback)(()=>{l({type:`vim_change_to_end_of_line`})},[]),ce=(0,Z.useCallback)((e,t)=>{l({type:`vim_change_movement`,payload:{movement:e,count:t}})},[]),le=(0,Z.useCallback)(e=>{l({type:`vim_move_left`,payload:{count:e}})},[]),U=(0,Z.useCallback)(e=>{l({type:`vim_move_right`,payload:{count:e}})},[]),ue=(0,Z.useCallback)(e=>{l({type:`vim_move_up`,payload:{count:e}})},[]),de=(0,Z.useCallback)(e=>{l({type:`vim_move_down`,payload:{count:e}})},[]),fe=(0,Z.useCallback)(e=>{l({type:`vim_move_word_forward`,payload:{count:e}})},[]),pe=(0,Z.useCallback)(e=>{l({type:`vim_move_word_backward`,payload:{count:e}})},[]),me=(0,Z.useCallback)(e=>{l({type:`vim_move_word_end`,payload:{count:e}})},[]),he=(0,Z.useCallback)(e=>{l({type:`vim_delete_char`,payload:{count:e}})},[]),ge=(0,Z.useCallback)(()=>{l({type:`vim_insert_at_cursor`})},[]),_e=(0,Z.useCallback)(()=>{l({type:`vim_append_at_cursor`})},[]),W=(0,Z.useCallback)(()=>{l({type:`vim_open_line_below`})},[]),ve=(0,Z.useCallback)(()=>{l({type:`vim_open_line_above`})},[]),ye=(0,Z.useCallback)(()=>{l({type:`vim_append_at_line_end`})},[]),be=(0,Z.useCallback)(()=>{l({type:`vim_insert_at_line_start`})},[]),G=(0,Z.useCallback)(()=>{l({type:`vim_move_to_line_start`})},[]),xe=(0,Z.useCallback)(()=>{l({type:`vim_move_to_line_end`})},[]),Se=(0,Z.useCallback)(()=>{l({type:`vim_move_to_first_nonwhitespace`})},[]),Ce=(0,Z.useCallback)(()=>{l({type:`vim_move_to_first_line`})},[]),we=(0,Z.useCallback)(()=>{l({type:`vim_move_to_last_line`})},[]),Te=(0,Z.useCallback)(e=>{l({type:`vim_move_to_line`,payload:{lineNumber:e}})},[]),Ee=(0,Z.useCallback)(()=>{l({type:`vim_escape_insert_mode`})},[]),De=(0,Z.useCallback)(async(e={})=>{let t=e.editor??process.env.VISUAL??process.env.EDITOR??(process.platform===`win32`?`notepad`:`vi`),r=p.mkdtempSync(C.join(n.tmpdir(),`gemini-edit-`)),o=C.join(r,`buffer.txt`);p.writeFileSync(o,v,`utf8`),l({type:`create_undo_snapshot`});let s=i?.isRaw??!1;try{a?.(!1);let{status:e,error:n}=d(t,[o],{stdio:`inherit`});if(n)throw n;if(typeof e==`number`&&e!==0)throw Error(`External editor exited with status ${e}`);let r=p.readFileSync(o,`utf8`);r=r.replace(/\r\n?/g,`
12688
12688
  `),l({type:`set_text`,payload:r,pushToUndo:!1})}catch(e){console.error(`[useTextBuffer] external editor error`,e)}finally{s&&a?.(!0);try{p.unlinkSync(o)}catch{}try{p.rmdirSync(r)}catch{}}},[v,i,a]),Oe=(0,Z.useCallback)((e,t)=>{if(t.paste){E(e,{paste:!0});return}t.return||e===`\r`||e===`
12689
- `||e===`\\\r`?D():t.leftArrow&&!t.meta&&!t.ctrl||t.ctrl&&e===`b`?A(`left`):t.rightArrow&&!t.meta&&!t.ctrl||t.ctrl&&e===`f`?A(`right`):t.upArrow||t.ctrl&&e===`p`?A(`up`):t.downArrow||t.ctrl&&e===`n`?A(`down`):(t.ctrl||t.meta)&&t.leftArrow||t.meta&&e===`b`?A(`wordLeft`):(t.ctrl||t.meta)&&t.rightArrow||t.meta&&e===`f`?A(`wordRight`):t.home||t.ctrl&&e===`a`?A(`home`):t.end||t.ctrl&&e===`e`?A(`end`):t.ctrl&&e===`k`?L():t.ctrl&&e===`u`?R():t.ctrl&&e===`y`?z():t.ctrl&&e===`t`?B():t.ctrl&&e===`w`||(t.meta||t.ctrl)&&(t.backspace||e===``)?F():(t.meta||t.ctrl)&&t.delete||t.meta&&e===`d`&&!t.ctrl&&!t.shift?I():t.super&&t.backspace?R():t.super&&t.delete?L():t.backspace||e===``||t.ctrl&&e===`h`?O():t.delete||t.ctrl&&e===`d`&&!t.meta&&!t.shift?k():t.ctrl&&!t.shift&&e===`z`?j():t.ctrl&&t.shift&&e===`z`?M():e&&!t.ctrl&&!t.meta&&E(e,{paste:!1})},[D,A,F,I,O,k,E,j,M,L,R,z,B]),ke=(0,Z.useMemo)(()=>b.slice(S,S+r.height),[b,S,r.height]),Ae=(0,Z.useCallback)((e,t,n,r,i)=>{l({type:`replace_range`,payload:{startRow:e,startCol:t,endRow:n,endCol:r,text:i}})},[]),je=(0,Z.useCallback)((e,t,n)=>{let[r,i]=L$(v,e),[a,o]=L$(v,t);Ae(r,i,a,o,n)},[v,Ae]),K=(0,Z.useCallback)(e=>{l({type:`move_to_offset`,payload:{offset:e}})},[]);return(0,Z.useMemo)(()=>({lines:u,text:v,cursor:[f,m],preferredCol:h,selectionAnchor:g,allVisualLines:b,viewportVisualLines:ke,visualCursor:y,visualScrollRow:S,visualToLogicalMap:x,setText:N,getExpandedText:P,insert:E,newline:D,backspace:O,del:k,move:A,undo:j,redo:M,replaceRange:Ae,replaceRangeByOffset:je,moveToOffset:K,deleteWordLeft:F,deleteWordRight:I,killLineRight:L,killLineLeft:R,yank:z,transposeChars:B,handleInput:Oe,openInExternalEditor:De,vimDeleteWordForward:V,vimDeleteWordBackward:H,vimDeleteWordEnd:ee,vimChangeWordForward:te,vimChangeWordBackward:ne,vimChangeWordEnd:re,vimDeleteLine:ie,vimChangeLine:ae,vimDeleteToEndOfLine:oe,vimChangeToEndOfLine:se,vimChangeMovement:ce,vimMoveLeft:le,vimMoveRight:U,vimMoveUp:ue,vimMoveDown:de,vimMoveWordForward:fe,vimMoveWordBackward:pe,vimMoveWordEnd:me,vimDeleteChar:he,vimInsertAtCursor:ge,vimAppendAtCursor:_e,vimOpenLineBelow:W,vimOpenLineAbove:ve,vimAppendAtLineEnd:ye,vimInsertAtLineStart:be,vimMoveToLineStart:G,vimMoveToLineEnd:xe,vimMoveToFirstNonWhitespace:Se,vimMoveToFirstLine:Ce,vimMoveToLastLine:we,vimMoveToLine:Te,vimEscapeInsertMode:Ee}),[u,v,f,m,h,g,b,ke,y,S,N,E,D,O,k,A,j,M,Ae,je,K,F,I,L,R,z,B,Oe,De,V,H,ee,te,ne,re,ie,ae,oe,se,ce,le,U,ue,de,fe,pe,me,he,ge,_e,W,ve,ye,be,G,xe,Se,Ce,we,Te,Ee,x,P])}const W$=/^#(?:[0-9a-fA-F]{3}){1,2}$/;function G$(e,t){if(!e)return e;if(W$.test(t))return NA.hex(t)(e);let n=NA[t];return typeof n==`function`?n(e):e}function K$(e){let t=e.flags.includes(`g`)?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function q$(e,t){if(!t?.length||!e)return e;let n=[{text:e,styled:!1}];for(let e of t){let t=K$(e.regex),r=[];for(let i of n){if(i.styled||!i.text){r.push(i);continue}let n=0,a;for(;(a=t.exec(i.text))!==null;){let o=a.index,s=o+a[0].length;o>n&&r.push({text:i.text.slice(n,o),styled:!1});let c=G$(i.text.slice(o,s),e.color);r.push({text:c,styled:!0}),s===n&&(t.lastIndex+=1),n=s}n<i.text.length&&r.push({text:i.text.slice(n),styled:!1})}n=r}return n.map(e=>e.text).join(``)}const J$=(0,Z.memo)(({initialValue:e,onChange:t,onSubmit:n,placeholder:r=`Type text...`,ref:i,placeholderProps:a,onKeyDown:o,grammar:s,disabled:c,width:l=2**53-1,height:u=2**53-1,ghostText:d,...f})=>{let{isFocused:p}=lI(),m=U$({initialText:e,initialCursorOffset:0,viewport:{width:l,height:u},onChange:e=>t?.(e,m)});(0,Z.useEffect)(()=>{i&&(i.current=m)},[m,i]);let h=(0,Z.useCallback)(async()=>{let e=m.text;if(e.trim()){try{if(await Promise.resolve(n?.(e))===!1)return}catch{return}m.text===e&&m.setText(``)}},[m,n]);sI((0,Z.useCallback)((e,t)=>{let n=!1;if(o?.({input:e,key:t,target:m,preventDefault:()=>{n=!0}}),!n&&!c){if(!c&&t.return&&!t.ctrl&&!t.meta&&!t.shift){if(m.text.endsWith(`\\`)){m.backspace(),m.newline();return}h();return}m.handleInput(e,t)}},[m,h,o,c]),{isActive:!c});let g=m.viewportVisualLines,[_,v]=m.visualCursor,y=m.visualScrollRow,b=p,x=(0,Z.useMemo)(()=>e=>q$(e,s),[s]);return!m.text&&r?(0,X.jsx)(Q,{...f,children:b?(0,X.jsxs)($,{dimColor:!0,...a,children:[NA.inverse(r.slice(0,1)),r.slice(1)]}):(0,X.jsx)($,{color:`gray`,...a,children:r})}):(0,X.jsx)(Q,{flexDirection:`column`,flexGrow:1,...f,children:g.map((e,t)=>{let n=y+t,r=_-y;if(!(b&&t===r))return(0,X.jsx)($,{children:(s?.length?x(e):e)||` `},`line-${n}`);let i=e.slice(0,v),a=e[v]??` `,o=e.slice(v+1),c=s?.length?x(i):i,l=s?.length?x(o):o,u=d&&!o&&v>=e.length;return(0,X.jsxs)($,{children:[c,NA.inverse(a),l,u&&NA.dim(d)]},`line-${n}`)})})});J$.displayName=`Input`;var Y$=class{constructor(){}async listServers(){let e=await this.findConfigSources(),t=[];for(let n of e)if(n.exists)try{let e=await this.loadServersFromSource(n);t.push(...e)}catch{}return t}async addServer(e,t){this.validateServerConfig(t);let n=await this.findConfigSources(),r=n.find(e=>e.type===`abacusai-user`&&e.exists),i=n.find(e=>e.type===`vscode-user`&&e.exists),a=n.filter(e=>e.exists),o=n.find(e=>e.type===`cursor-global`),s=n.find(e=>e.type===`vscode-user`),c=r||i||a[0]||s||o;if(!c)throw Error(`No suitable configuration location found.`);await this.addServerToSource(c,e,t)}async removeServer(e){let t=await this.findConfigSources(),n=!1;for(let r of t)if(r.exists)try{await this.removeServerFromSource(r.path,e)&&(n=!0)}catch{}if(!n)throw Error(`Server '${e}' not found in any configuration file`)}async getServer(e){return(await this.listServers()).find(t=>t.name===e||t.id===e)}async addServerFromJson(e,t){let n;try{n=this.parseJsonWithFallback(t)}catch(e){throw Error(`Invalid JSON syntax: ${e instanceof Error?e.message:String(e)}`)}try{this.validateServerConfig(n)}catch(e){throw Error(`Invalid server configuration: ${e instanceof Error?e.message:String(e)}`)}await this.addServer(e,n)}async addServerFromUrl(e,t,n){let r;r=t.startsWith(`http://`)||t.startsWith(`https://`)?{url:t}:{command:t,args:n||[]},await this.addServer(e,r)}formatServerInfo(e){let t=[`Name: ${e.name}`,`ID: ${e.id}`,`Source: ${e.description||`Unknown`}`,`Status: ${e.status||`unknown`}`];return`url`in e.config?(t.push(`Type: HTTP`),t.push(`URL: ${e.config.url}`),e.config.headers&&Object.keys(e.config.headers).length>0&&t.push(`Headers: ${JSON.stringify(e.config.headers,null,2)}`)):`command`in e.config&&(t.push(`Type: Command`),t.push(`Command: ${e.config.command}`),e.config.args&&e.config.args.length>0&&t.push(`Arguments: ${e.config.args.join(` `)}`),e.config.env&&Object.keys(e.config.env).length>0&&t.push(`Environment: ${JSON.stringify(e.config.env,null,2)}`),e.config.cwd&&t.push(`Working Directory: ${e.config.cwd}`)),t.join(`
12690
- `)}formatServerList(e){let t=[];if(e.length===0)t.push(`No MCP servers found.`),t.push(``),t.push(`Use the following commands to manage MCP servers:`),t.push(``),t.push($$);else{t.push(`📡 MCP Servers:`),t.push(``);let n={};for(let t of e){let e=this.getServerSourceLabel(t);n[e]||(n[e]=[]),n[e].push(t)}for(let[e,r]of Object.entries(n)){t.push(` ${e}:`);for(let e of r){let n=`url`in e.config?`🌐`:`💻`;t.push(` ${n} ${e.name}`)}t.push(``)}t.push(`📝 Example - Add GitHub MCP Server:`),t.push(` /mcp add-json github '{"command":"npx","args":["-y","@modelcontextprotocol/server-github"],"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"your_token"}}'`),t.push(``)}return t.join(`
12691
- `)}async findConfigSources(){let e=[],t=process.platform===`win32`?C.join(n.homedir(),`AppData`,`Roaming`,`Claude`,`claude_desktop_config.json`):process.platform===`darwin`?C.join(n.homedir(),`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`):C.join(n.homedir(),`.config`,`Claude`,`claude_desktop_config.json`);e.push({path:t,type:`claude-desktop`,label:`Claude Desktop`,exists:p.existsSync(t)});let r=C.join(n.homedir(),`.codeium`,`windsurf`,`mcp_config.json`);e.push({path:r,type:`windsurf`,label:`Windsurf`,exists:p.existsSync(r)});let i=C.join(n.homedir(),`.cursor`,`mcp.json`);e.push({path:i,type:`cursor-global`,label:`Cursor (Global)`,exists:p.existsSync(i)});let a=C.join(process.cwd(),`.cursor`,`mcp.json`);e.push({path:a,type:`cursor-workspace`,label:`Cursor (Workspace)`,exists:p.existsSync(a)});let o=[ke.fullName,`AbacusAI`,`CodeLLM`];for(let t of o){let n=this.getUserDataDir(t);if(n){let r=C.join(n,`User`,`mcp.json`);p.existsSync(r)&&e.push({path:r,type:`abacusai-user`,label:`${t} (User)`,exists:!0})}}let s=process.platform===`win32`?C.join(n.homedir(),`AppData`,`Roaming`,`Code`,`User`):process.platform===`darwin`?C.join(n.homedir(),`Library`,`Application Support`,`Code`,`User`):C.join(n.homedir(),`.config`,`Code`,`User`),c=C.join(s,`mcp.json`);return e.push({path:c,type:`vscode-user`,label:`VSCode (User)`,exists:p.existsSync(c)}),e}getUserDataDir(e){try{switch(process.platform){case`win32`:{let t=process.env.APPDATA;return t?C.join(t,e):null}case`darwin`:return C.join(n.homedir(),`Library`,`Application Support`,e);case`linux`:{let t=process.env.XDG_CONFIG_HOME||C.join(n.homedir(),`.config`);return C.join(t,e)}default:return null}}catch{return null}}async loadServersFromSource(e){let t=await v.readFile(e.path,`utf8`),n=[],r;try{r=this.parseJsonWithFallback(t)}catch(e){throw Error(`JSON parsing failed: ${e instanceof Error?e.message:String(e)}`)}if(e.type.startsWith(`vscode`)||e.type===`abacusai-user`){let t;if(r.servers&&!r.mcp?t=r.servers:r.mcp?.servers&&(t=r.mcp.servers),t)for(let[r,i]of Object.entries(t))n.push({id:`${e.type}.${r}`,name:r,config:i,status:`stopped`,description:`${e.label} - ${this.getServerTypeDescription(i)}`})}else if([`cursor-global`,`cursor-workspace`,`claude-desktop`,`windsurf`].includes(e.type)){let t=r;if(t.mcpServers)for(let[r,i]of Object.entries(t.mcpServers)){let t=i.url?{type:`http`,url:i.url,headers:{}}:{type:`stdio`,command:i.command||``,args:i.args||[],env:i.env||{}};n.push({id:`${e.type}.${r}`,name:r,config:t,status:`stopped`,description:`${e.label} - ${this.getServerTypeDescription(t)}`})}}return n}parseJsonWithFallback(e){try{return JSON.parse(e)}catch(t){try{let t=e.replace(/,(\s*[}\]])/g,`$1`).replace(/([}\]]),(\s*[}\]])/g,`$1$2`);return JSON.parse(t)}catch(e){let n=t instanceof Error?t.message:String(t),r=e instanceof Error?e.message:String(e);throw Error(`JSON parsing failed. Original error: ${n}. After fixing trailing commas: ${r}`)}}}async addServerToSource(e,t,n){let r=e.path,i=C.dirname(r);if(await v.mkdir(i,{recursive:!0}),[`vscode-user`,`vscode-workspace`,`abacusai-user`].includes(e.type))if(r.endsWith(`mcp.json`)){let e={servers:{}};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.servers=e.servers||{},e.servers[t]=n;let i=JSON.stringify(e,null,2);await v.writeFile(r,i,`utf8`)}else{let e={};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.mcp=e.mcp||{servers:{}},e.mcp.servers=e.mcp.servers||{},e.mcp.servers[t]=n;let i=JSON.stringify(e,null,2);await v.writeFile(r,i,`utf8`)}else if(e.type===`cursor-global`){let e={mcpServers:{}};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.mcpServers=e.mcpServers||{};let i=`url`in n?{url:n.url}:{command:n.command,args:n.args?[...n.args]:void 0,env:n.env?Object.fromEntries(Object.entries(n.env).map(([e,t])=>[e,String(t)])):void 0};e.mcpServers[t]=i;let a=JSON.stringify(e,null,2);await v.writeFile(r,a,`utf8`)}else if(e.type===`cursor-workspace`){let e={mcpServers:{}};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.mcpServers=e.mcpServers||{};let i=`url`in n?{url:n.url}:{command:n.command,args:n.args?[...n.args]:void 0,env:n.env?Object.fromEntries(Object.entries(n.env).map(([e,t])=>[e,String(t)])):void 0};e.mcpServers[t]=i;let a=JSON.stringify(e,null,2);await v.writeFile(r,a,`utf8`)}else throw Error(`Unsupported config source type: ${e.type}`)}async removeServerFromSource(e,t){if(!p.existsSync(e))return!1;let n=await v.readFile(e,`utf8`),r=e.includes(`.cursor`)||e.includes(`claude_desktop_config.json`)||e.includes(`mcp_config.json`);if(e.endsWith(`mcp.json`)){let r=this.parseJsonWithFallback(n);if(!r.servers||!r.servers[t])return!1;delete r.servers[t];let i=JSON.stringify(r,null,2);return await v.writeFile(e,i,`utf8`),!0}else if(e.endsWith(`settings.json`)){let r=this.parseJsonWithFallback(n),i=r?.mcp||{servers:{}};if(!i.servers||!i.servers[t])return!1;delete i.servers[t],r.mcp=i;let a=JSON.stringify(r,null,2);return await v.writeFile(e,a,`utf8`),!0}else if(r){let r=this.parseJsonWithFallback(n);if(!r.mcpServers||!r.mcpServers[t])return!1;delete r.mcpServers[t];let i=JSON.stringify(r,null,2);return await v.writeFile(e,i,`utf8`),!0}else throw Error(`Unsupported config file format: ${e}`)}validateServerConfig(e){if(!e||typeof e!=`object`)throw Error(`Server configuration must be a valid object`);if(`mcpServers`in e||`servers`in e)throw Error(`Invalid configuration format. Server configuration should not contain "mcpServers" or "servers" properties. Each server should be configured individually.`);if(`url`in e){if(!e.url)throw Error(`URL is required for HTTP servers`);if(typeof e.url!=`string`)throw Error(`URL must be a string`);if(!e.url.startsWith(`http://`)&&!e.url.startsWith(`https://`))throw Error(`URL must start with http:// or https://`)}else if(`command`in e){if(!e.command)throw Error(`Command is required for stdio servers`);if(typeof e.command!=`string`)throw Error(`Command must be a string`);if(e.args&&!Array.isArray(e.args))throw Error(`Arguments must be an array`);if(e.args&&e.args.some(e=>typeof e!=`string`))throw Error(`All arguments must be strings`)}else throw Error(`Server configuration must have either "url" or "command" property`)}getServerTypeDescription(e){if(`url`in e)return`HTTP server at ${e.url}`;if(`command`in e){let t=e.args&&e.args.length>0?` ${e.args.join(` `)}`:``;return`Command: ${e.command}${t}`}return`Unknown server type`}getServerSourceLabel(e){return e.id.startsWith(`claude-desktop`)?`Claude Desktop`:e.id.startsWith(`windsurf`)?`Windsurf`:e.id.startsWith(`cursor-global`)?`Cursor (Global)`:e.id.startsWith(`cursor-workspace`)?`Cursor (Workspace)`:e.id.startsWith(`abacusai-user`)?e.description?.includes(`${ke.fullName}-dev`)||e.description?.includes(`CodeLLM-dev`)?`${ke.fullName}-dev (User)`:`${ke.fullName} (User)`:e.id.startsWith(`vscode-user`)?`VSCode (User)`:e.id.startsWith(`vscode-workspace`)?`VSCode (Workspace)`:`Other`}},X$=class{standaloneService;constructor(){this.standaloneService=new Y$}async listServers(){return this.standaloneService.listServers()}async addServer(e,t){return this.standaloneService.addServer(e,t)}async removeServer(e){return this.standaloneService.removeServer(e)}async getServer(e){return this.standaloneService.getServer(e)}async addServerFromJson(e,t){return this.standaloneService.addServerFromJson(e,t)}async addServerFromUrl(e,t,n){return this.standaloneService.addServerFromUrl(e,t,n)}formatServerInfo(e){return this.standaloneService.formatServerInfo(e)}formatServerList(e){return this.standaloneService.formatServerList(e)}};function Z$(e,t){try{let r=C.join(n.tmpdir(),`abacus-tui-logs`);p.existsSync(r)||p.mkdirSync(r,{recursive:!0});let i=C.join(r,`mcp-errors.log`),a=new Date().toISOString(),o=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:``,c=`[${a}] ${e}: ${o}\n${s?`Stack: ${s}\n`:``}\n`;p.appendFileSync(i,c,`utf8`)}catch{console.error(`[MCP] ${e}:`,t)}}var Q$=class{mcpService;mcp;constructor(e){this.mcpService=new X$,this.mcp=e}async listServers(){let e=await this.mcpService.listServers();if(this.mcp){let t=this.mcp.listServers();for(let n of e)n.status=t.find(e=>e.config.id===n.id||e.config.id===n.name)?`running`:`stopped`}return this.mcpService.formatServerList(e)}async addServer(e,t,n){await this.mcpService.addServerFromUrl(e,t,n),this.mcp&&this.mcp.refresh().catch(t=>{Z$(`Failed to refresh MCP connections after adding server '${e}'`,t)})}async removeServer(e){await this.mcpService.removeServer(e),this.mcp&&this.mcp.removeServer(e).catch(t=>{Z$(`Failed to disconnect MCP server '${e}'`,t)})}async getServer(e){let t=await this.mcpService.getServer(e);return t?(this.mcp&&(t.status=this.mcp.listServers().find(e=>e.config.id===t.id||e.config.id===t.name)?`running`:`stopped`),this.mcpService.formatServerInfo(t)):null}async addServerFromJson(e,t){await this.mcpService.addServerFromJson(e,t),this.mcp&&this.mcp.refresh().catch(t=>{Z$(`Failed to refresh MCP connections after adding server '${e}' from JSON`,t)})}async getServerNames(){let e=await this.mcpService.listServers();if(this.mcp){let t=this.mcp.listServers();for(let n of e)n.status=t.find(e=>e.config.id===n.id||e.config.id===n.name)?`running`:`stopped`}return e.map(e=>({name:e.name,status:e.status}))}formatHelp(){return $$}};const $$=`
12689
+ `||e===`\\\r`?D():t.leftArrow&&!t.meta&&!t.ctrl||t.ctrl&&e===`b`?A(`left`):t.rightArrow&&!t.meta&&!t.ctrl||t.ctrl&&e===`f`?A(`right`):t.upArrow||t.ctrl&&e===`p`?A(`up`):t.downArrow||t.ctrl&&e===`n`?A(`down`):(t.ctrl||t.meta)&&t.leftArrow||t.meta&&e===`b`?A(`wordLeft`):(t.ctrl||t.meta)&&t.rightArrow||t.meta&&e===`f`?A(`wordRight`):t.home||t.ctrl&&e===`a`?A(`home`):t.end||t.ctrl&&e===`e`?A(`end`):t.ctrl&&e===`k`?L():t.ctrl&&e===`u`?R():t.ctrl&&e===`y`?z():t.ctrl&&e===`t`?B():t.ctrl&&e===`w`||(t.meta||t.ctrl)&&(t.backspace||e===``)?F():(t.meta||t.ctrl)&&t.delete||t.meta&&e===`d`&&!t.ctrl&&!t.shift?I():t.super&&t.backspace?R():t.super&&t.delete?L():t.backspace||e===``||t.ctrl&&e===`h`?O():t.delete||t.ctrl&&e===`d`&&!t.meta&&!t.shift?k():t.ctrl&&!t.shift&&e===`z`?j():t.ctrl&&t.shift&&e===`z`?M():e&&!t.ctrl&&!t.meta&&E(e,{paste:!1})},[D,A,F,I,O,k,E,j,M,L,R,z,B]),ke=(0,Z.useMemo)(()=>b.slice(S,S+r.height),[b,S,r.height]),Ae=(0,Z.useCallback)((e,t,n,r,i)=>{l({type:`replace_range`,payload:{startRow:e,startCol:t,endRow:n,endCol:r,text:i}})},[]),je=(0,Z.useCallback)((e,t,n)=>{let[r,i]=R$(v,e),[a,o]=R$(v,t);Ae(r,i,a,o,n)},[v,Ae]),K=(0,Z.useCallback)(e=>{l({type:`move_to_offset`,payload:{offset:e}})},[]);return(0,Z.useMemo)(()=>({lines:u,text:v,cursor:[f,m],preferredCol:h,selectionAnchor:g,allVisualLines:b,viewportVisualLines:ke,visualCursor:y,visualScrollRow:S,visualToLogicalMap:x,setText:N,getExpandedText:P,insert:E,newline:D,backspace:O,del:k,move:A,undo:j,redo:M,replaceRange:Ae,replaceRangeByOffset:je,moveToOffset:K,deleteWordLeft:F,deleteWordRight:I,killLineRight:L,killLineLeft:R,yank:z,transposeChars:B,handleInput:Oe,openInExternalEditor:De,vimDeleteWordForward:V,vimDeleteWordBackward:H,vimDeleteWordEnd:ee,vimChangeWordForward:te,vimChangeWordBackward:ne,vimChangeWordEnd:re,vimDeleteLine:ie,vimChangeLine:ae,vimDeleteToEndOfLine:oe,vimChangeToEndOfLine:se,vimChangeMovement:ce,vimMoveLeft:le,vimMoveRight:U,vimMoveUp:ue,vimMoveDown:de,vimMoveWordForward:fe,vimMoveWordBackward:pe,vimMoveWordEnd:me,vimDeleteChar:he,vimInsertAtCursor:ge,vimAppendAtCursor:_e,vimOpenLineBelow:W,vimOpenLineAbove:ve,vimAppendAtLineEnd:ye,vimInsertAtLineStart:be,vimMoveToLineStart:G,vimMoveToLineEnd:xe,vimMoveToFirstNonWhitespace:Se,vimMoveToFirstLine:Ce,vimMoveToLastLine:we,vimMoveToLine:Te,vimEscapeInsertMode:Ee}),[u,v,f,m,h,g,b,ke,y,S,N,E,D,O,k,A,j,M,Ae,je,K,F,I,L,R,z,B,Oe,De,V,H,ee,te,ne,re,ie,ae,oe,se,ce,le,U,ue,de,fe,pe,me,he,ge,_e,W,ve,ye,be,G,xe,Se,Ce,we,Te,Ee,x,P])}const G$=/^#(?:[0-9a-fA-F]{3}){1,2}$/;function K$(e,t){if(!e)return e;if(G$.test(t))return NA.hex(t)(e);let n=NA[t];return typeof n==`function`?n(e):e}function q$(e){let t=e.flags.includes(`g`)?e.flags:`${e.flags}g`;return new RegExp(e.source,t)}function J$(e,t){if(!t?.length||!e)return e;let n=[{text:e,styled:!1}];for(let e of t){let t=q$(e.regex),r=[];for(let i of n){if(i.styled||!i.text){r.push(i);continue}let n=0,a;for(;(a=t.exec(i.text))!==null;){let o=a.index,s=o+a[0].length;o>n&&r.push({text:i.text.slice(n,o),styled:!1});let c=K$(i.text.slice(o,s),e.color);r.push({text:c,styled:!0}),s===n&&(t.lastIndex+=1),n=s}n<i.text.length&&r.push({text:i.text.slice(n),styled:!1})}n=r}return n.map(e=>e.text).join(``)}const Y$=(0,Z.memo)(({initialValue:e,onChange:t,onSubmit:n,placeholder:r=`Type text...`,ref:i,placeholderProps:a,onKeyDown:o,grammar:s,disabled:c,width:l=2**53-1,height:u=2**53-1,ghostText:d,...f})=>{let{isFocused:p}=lI(),m=W$({initialText:e,initialCursorOffset:0,viewport:{width:l,height:u},onChange:e=>t?.(e,m)});(0,Z.useEffect)(()=>{i&&(i.current=m)},[m,i]);let h=(0,Z.useCallback)(async()=>{let e=m.text;if(e.trim()){try{if(await Promise.resolve(n?.(e))===!1)return}catch{return}m.text===e&&m.setText(``)}},[m,n]);sI((0,Z.useCallback)((e,t)=>{let n=!1;if(o?.({input:e,key:t,target:m,preventDefault:()=>{n=!0}}),!n&&!c){if(!c&&t.return&&!t.ctrl&&!t.meta&&!t.shift){if(m.text.endsWith(`\\`)){m.backspace(),m.newline();return}h();return}m.handleInput(e,t)}},[m,h,o,c]),{isActive:!c});let g=m.viewportVisualLines,[_,v]=m.visualCursor,y=m.visualScrollRow,b=p,x=(0,Z.useMemo)(()=>e=>J$(e,s),[s]);return!m.text&&r?(0,X.jsx)(Q,{...f,children:b?(0,X.jsxs)($,{dimColor:!0,...a,children:[NA.inverse(r.slice(0,1)),r.slice(1)]}):(0,X.jsx)($,{color:`gray`,...a,children:r})}):(0,X.jsx)(Q,{flexDirection:`column`,flexGrow:1,...f,children:g.map((e,t)=>{let n=y+t,r=_-y;if(!(b&&t===r))return(0,X.jsx)($,{children:(s?.length?x(e):e)||` `},`line-${n}`);let i=e.slice(0,v),a=e[v]??` `,o=e.slice(v+1),c=s?.length?x(i):i,l=s?.length?x(o):o,u=d&&!o&&v>=e.length;return(0,X.jsxs)($,{children:[c,NA.inverse(a),l,u&&NA.dim(d)]},`line-${n}`)})})});Y$.displayName=`Input`;var X$=class{constructor(){}async listServers(){let e=await this.findConfigSources(),t=[];for(let n of e)if(n.exists)try{let e=await this.loadServersFromSource(n);t.push(...e)}catch{}return t}async addServer(e,t){this.validateServerConfig(t);let n=await this.findConfigSources(),r=n.find(e=>e.type===`abacusai-user`&&e.exists),i=n.find(e=>e.type===`vscode-user`&&e.exists),a=n.filter(e=>e.exists),o=n.find(e=>e.type===`cursor-global`),s=n.find(e=>e.type===`vscode-user`),c=r||i||a[0]||s||o;if(!c)throw Error(`No suitable configuration location found.`);await this.addServerToSource(c,e,t)}async removeServer(e){let t=await this.findConfigSources(),n=!1;for(let r of t)if(r.exists)try{await this.removeServerFromSource(r.path,e)&&(n=!0)}catch{}if(!n)throw Error(`Server '${e}' not found in any configuration file`)}async getServer(e){return(await this.listServers()).find(t=>t.name===e||t.id===e)}async addServerFromJson(e,t){let n;try{n=this.parseJsonWithFallback(t)}catch(e){throw Error(`Invalid JSON syntax: ${e instanceof Error?e.message:String(e)}`)}try{this.validateServerConfig(n)}catch(e){throw Error(`Invalid server configuration: ${e instanceof Error?e.message:String(e)}`)}await this.addServer(e,n)}async addServerFromUrl(e,t,n){let r;r=t.startsWith(`http://`)||t.startsWith(`https://`)?{url:t}:{command:t,args:n||[]},await this.addServer(e,r)}formatServerInfo(e){let t=[`Name: ${e.name}`,`ID: ${e.id}`,`Source: ${e.description||`Unknown`}`,`Status: ${e.status||`unknown`}`];return`url`in e.config?(t.push(`Type: HTTP`),t.push(`URL: ${e.config.url}`),e.config.headers&&Object.keys(e.config.headers).length>0&&t.push(`Headers: ${JSON.stringify(e.config.headers,null,2)}`)):`command`in e.config&&(t.push(`Type: Command`),t.push(`Command: ${e.config.command}`),e.config.args&&e.config.args.length>0&&t.push(`Arguments: ${e.config.args.join(` `)}`),e.config.env&&Object.keys(e.config.env).length>0&&t.push(`Environment: ${JSON.stringify(e.config.env,null,2)}`),e.config.cwd&&t.push(`Working Directory: ${e.config.cwd}`)),t.join(`
12690
+ `)}formatServerList(e){let t=[];if(e.length===0)t.push(`No MCP servers found.`),t.push(``),t.push(`Use the following commands to manage MCP servers:`),t.push(``),t.push(e1);else{t.push(`📡 MCP Servers:`),t.push(``);let n={};for(let t of e){let e=this.getServerSourceLabel(t);n[e]||(n[e]=[]),n[e].push(t)}for(let[e,r]of Object.entries(n)){t.push(` ${e}:`);for(let e of r){let n=`url`in e.config?`🌐`:`💻`;t.push(` ${n} ${e.name}`)}t.push(``)}t.push(`📝 Example - Add GitHub MCP Server:`),t.push(` /mcp add-json github '{"command":"npx","args":["-y","@modelcontextprotocol/server-github"],"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"your_token"}}'`),t.push(``)}return t.join(`
12691
+ `)}async findConfigSources(){let e=[],t=process.platform===`win32`?C.join(n.homedir(),`AppData`,`Roaming`,`Claude`,`claude_desktop_config.json`):process.platform===`darwin`?C.join(n.homedir(),`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`):C.join(n.homedir(),`.config`,`Claude`,`claude_desktop_config.json`);e.push({path:t,type:`claude-desktop`,label:`Claude Desktop`,exists:p.existsSync(t)});let r=C.join(n.homedir(),`.codeium`,`windsurf`,`mcp_config.json`);e.push({path:r,type:`windsurf`,label:`Windsurf`,exists:p.existsSync(r)});let i=C.join(n.homedir(),`.cursor`,`mcp.json`);e.push({path:i,type:`cursor-global`,label:`Cursor (Global)`,exists:p.existsSync(i)});let a=C.join(process.cwd(),`.cursor`,`mcp.json`);e.push({path:a,type:`cursor-workspace`,label:`Cursor (Workspace)`,exists:p.existsSync(a)});let o=[ke.fullName,`AbacusAI`,`CodeLLM`];for(let t of o){let n=this.getUserDataDir(t);if(n){let r=C.join(n,`User`,`mcp.json`);p.existsSync(r)&&e.push({path:r,type:`abacusai-user`,label:`${t} (User)`,exists:!0})}}let s=process.platform===`win32`?C.join(n.homedir(),`AppData`,`Roaming`,`Code`,`User`):process.platform===`darwin`?C.join(n.homedir(),`Library`,`Application Support`,`Code`,`User`):C.join(n.homedir(),`.config`,`Code`,`User`),c=C.join(s,`mcp.json`);return e.push({path:c,type:`vscode-user`,label:`VSCode (User)`,exists:p.existsSync(c)}),e}getUserDataDir(e){try{switch(process.platform){case`win32`:{let t=process.env.APPDATA;return t?C.join(t,e):null}case`darwin`:return C.join(n.homedir(),`Library`,`Application Support`,e);case`linux`:{let t=process.env.XDG_CONFIG_HOME||C.join(n.homedir(),`.config`);return C.join(t,e)}default:return null}}catch{return null}}async loadServersFromSource(e){let t=await v.readFile(e.path,`utf8`),n=[],r;try{r=this.parseJsonWithFallback(t)}catch(e){throw Error(`JSON parsing failed: ${e instanceof Error?e.message:String(e)}`)}if(e.type.startsWith(`vscode`)||e.type===`abacusai-user`){let t;if(r.servers&&!r.mcp?t=r.servers:r.mcp?.servers&&(t=r.mcp.servers),t)for(let[r,i]of Object.entries(t))n.push({id:`${e.type}.${r}`,name:r,config:i,status:`stopped`,description:`${e.label} - ${this.getServerTypeDescription(i)}`})}else if([`cursor-global`,`cursor-workspace`,`claude-desktop`,`windsurf`].includes(e.type)){let t=r;if(t.mcpServers)for(let[r,i]of Object.entries(t.mcpServers)){let t=i.url?{type:`http`,url:i.url,headers:{}}:{type:`stdio`,command:i.command||``,args:i.args||[],env:i.env||{}};n.push({id:`${e.type}.${r}`,name:r,config:t,status:`stopped`,description:`${e.label} - ${this.getServerTypeDescription(t)}`})}}return n}parseJsonWithFallback(e){try{return JSON.parse(e)}catch(t){try{let t=e.replace(/,(\s*[}\]])/g,`$1`).replace(/([}\]]),(\s*[}\]])/g,`$1$2`);return JSON.parse(t)}catch(e){let n=t instanceof Error?t.message:String(t),r=e instanceof Error?e.message:String(e);throw Error(`JSON parsing failed. Original error: ${n}. After fixing trailing commas: ${r}`)}}}async addServerToSource(e,t,n){let r=e.path,i=C.dirname(r);if(await v.mkdir(i,{recursive:!0}),[`vscode-user`,`vscode-workspace`,`abacusai-user`].includes(e.type))if(r.endsWith(`mcp.json`)){let e={servers:{}};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.servers=e.servers||{},e.servers[t]=n;let i=JSON.stringify(e,null,2);await v.writeFile(r,i,`utf8`)}else{let e={};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.mcp=e.mcp||{servers:{}},e.mcp.servers=e.mcp.servers||{},e.mcp.servers[t]=n;let i=JSON.stringify(e,null,2);await v.writeFile(r,i,`utf8`)}else if(e.type===`cursor-global`){let e={mcpServers:{}};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.mcpServers=e.mcpServers||{};let i=`url`in n?{url:n.url}:{command:n.command,args:n.args?[...n.args]:void 0,env:n.env?Object.fromEntries(Object.entries(n.env).map(([e,t])=>[e,String(t)])):void 0};e.mcpServers[t]=i;let a=JSON.stringify(e,null,2);await v.writeFile(r,a,`utf8`)}else if(e.type===`cursor-workspace`){let e={mcpServers:{}};if(p.existsSync(r))try{let t=await v.readFile(r,`utf8`);e=this.parseJsonWithFallback(t)}catch{}e.mcpServers=e.mcpServers||{};let i=`url`in n?{url:n.url}:{command:n.command,args:n.args?[...n.args]:void 0,env:n.env?Object.fromEntries(Object.entries(n.env).map(([e,t])=>[e,String(t)])):void 0};e.mcpServers[t]=i;let a=JSON.stringify(e,null,2);await v.writeFile(r,a,`utf8`)}else throw Error(`Unsupported config source type: ${e.type}`)}async removeServerFromSource(e,t){if(!p.existsSync(e))return!1;let n=await v.readFile(e,`utf8`),r=e.includes(`.cursor`)||e.includes(`claude_desktop_config.json`)||e.includes(`mcp_config.json`);if(e.endsWith(`mcp.json`)){let r=this.parseJsonWithFallback(n);if(!r.servers||!r.servers[t])return!1;delete r.servers[t];let i=JSON.stringify(r,null,2);return await v.writeFile(e,i,`utf8`),!0}else if(e.endsWith(`settings.json`)){let r=this.parseJsonWithFallback(n),i=r?.mcp||{servers:{}};if(!i.servers||!i.servers[t])return!1;delete i.servers[t],r.mcp=i;let a=JSON.stringify(r,null,2);return await v.writeFile(e,a,`utf8`),!0}else if(r){let r=this.parseJsonWithFallback(n);if(!r.mcpServers||!r.mcpServers[t])return!1;delete r.mcpServers[t];let i=JSON.stringify(r,null,2);return await v.writeFile(e,i,`utf8`),!0}else throw Error(`Unsupported config file format: ${e}`)}validateServerConfig(e){if(!e||typeof e!=`object`)throw Error(`Server configuration must be a valid object`);if(`mcpServers`in e||`servers`in e)throw Error(`Invalid configuration format. Server configuration should not contain "mcpServers" or "servers" properties. Each server should be configured individually.`);if(`url`in e){if(!e.url)throw Error(`URL is required for HTTP servers`);if(typeof e.url!=`string`)throw Error(`URL must be a string`);if(!e.url.startsWith(`http://`)&&!e.url.startsWith(`https://`))throw Error(`URL must start with http:// or https://`)}else if(`command`in e){if(!e.command)throw Error(`Command is required for stdio servers`);if(typeof e.command!=`string`)throw Error(`Command must be a string`);if(e.args&&!Array.isArray(e.args))throw Error(`Arguments must be an array`);if(e.args&&e.args.some(e=>typeof e!=`string`))throw Error(`All arguments must be strings`)}else throw Error(`Server configuration must have either "url" or "command" property`)}getServerTypeDescription(e){if(`url`in e)return`HTTP server at ${e.url}`;if(`command`in e){let t=e.args&&e.args.length>0?` ${e.args.join(` `)}`:``;return`Command: ${e.command}${t}`}return`Unknown server type`}getServerSourceLabel(e){return e.id.startsWith(`claude-desktop`)?`Claude Desktop`:e.id.startsWith(`windsurf`)?`Windsurf`:e.id.startsWith(`cursor-global`)?`Cursor (Global)`:e.id.startsWith(`cursor-workspace`)?`Cursor (Workspace)`:e.id.startsWith(`abacusai-user`)?e.description?.includes(`${ke.fullName}-dev`)||e.description?.includes(`CodeLLM-dev`)?`${ke.fullName}-dev (User)`:`${ke.fullName} (User)`:e.id.startsWith(`vscode-user`)?`VSCode (User)`:e.id.startsWith(`vscode-workspace`)?`VSCode (Workspace)`:`Other`}},Z$=class{standaloneService;constructor(){this.standaloneService=new X$}async listServers(){return this.standaloneService.listServers()}async addServer(e,t){return this.standaloneService.addServer(e,t)}async removeServer(e){return this.standaloneService.removeServer(e)}async getServer(e){return this.standaloneService.getServer(e)}async addServerFromJson(e,t){return this.standaloneService.addServerFromJson(e,t)}async addServerFromUrl(e,t,n){return this.standaloneService.addServerFromUrl(e,t,n)}formatServerInfo(e){return this.standaloneService.formatServerInfo(e)}formatServerList(e){return this.standaloneService.formatServerList(e)}};function Q$(e,t){try{let r=C.join(n.tmpdir(),`abacus-tui-logs`);p.existsSync(r)||p.mkdirSync(r,{recursive:!0});let i=C.join(r,`mcp-errors.log`),a=new Date().toISOString(),o=t instanceof Error?t.message:String(t),s=t instanceof Error?t.stack:``,c=`[${a}] ${e}: ${o}\n${s?`Stack: ${s}\n`:``}\n`;p.appendFileSync(i,c,`utf8`)}catch{console.error(`[MCP] ${e}:`,t)}}var $$=class{mcpService;mcp;constructor(e){this.mcpService=new Z$,this.mcp=e}async listServers(){let e=await this.mcpService.listServers();if(this.mcp){let t=this.mcp.listServers();for(let n of e)n.status=t.find(e=>e.config.id===n.id||e.config.id===n.name)?`running`:`stopped`}return this.mcpService.formatServerList(e)}async addServer(e,t,n){await this.mcpService.addServerFromUrl(e,t,n),this.mcp&&this.mcp.refresh().catch(t=>{Q$(`Failed to refresh MCP connections after adding server '${e}'`,t)})}async removeServer(e){await this.mcpService.removeServer(e),this.mcp&&this.mcp.removeServer(e).catch(t=>{Q$(`Failed to disconnect MCP server '${e}'`,t)})}async getServer(e){let t=await this.mcpService.getServer(e);return t?(this.mcp&&(t.status=this.mcp.listServers().find(e=>e.config.id===t.id||e.config.id===t.name)?`running`:`stopped`),this.mcpService.formatServerInfo(t)):null}async addServerFromJson(e,t){await this.mcpService.addServerFromJson(e,t),this.mcp&&this.mcp.refresh().catch(t=>{Q$(`Failed to refresh MCP connections after adding server '${e}' from JSON`,t)})}async getServerNames(){let e=await this.mcpService.listServers();if(this.mcp){let t=this.mcp.listServers();for(let n of e)n.status=t.find(e=>e.config.id===n.id||e.config.id===n.name)?`running`:`stopped`}return e.map(e=>({name:e.name,status:e.status}))}formatHelp(){return e1}};const e1=`
12692
12692
  MCP (Model Context Protocol) Commands:
12693
12693
 
12694
12694
  /mcp list List configured MCP servers
@@ -12704,12 +12704,12 @@ TUI Features:
12704
12704
  - Full MCP server management from command line
12705
12705
  - All commands work independently in TUI
12706
12706
  - Direct file-based configuration access
12707
- `,e1=`\\x1b\\r`,t1=O(s);function n1(e){if(!p.existsSync(e))return null;let t=`${e}.${oe(4).toString(`hex`)}.bak`;try{return p.copyFileSync(e,t),t}catch{return null}}async function r1(e){let t=n.homedir(),r;r=U.platform===`win32`?C.join(t,`AppData`,`Roaming`,e,`User`):U.platform===`darwin`?C.join(t,`Library`,`Application Support`,e,`User`):C.join(t,`.config`,e,`User`);let i=C.join(r,`keybindings.json`);try{p.existsSync(r)||p.mkdirSync(r,{recursive:!0});let t=[];if(p.existsSync(i)){let n=p.readFileSync(i,`utf-8`);if(!n1(i))return{success:!1,message:`Failed to backup existing ${e} keybindings`};let r=n.replace(/\/\/.*$/gm,``).replace(/\/\*[\s\S]*?\*\//g,``);try{t=JSON.parse(r||`[]`)}catch{t=[]}if(t.find(e=>e.key===`shift+enter`&&e.command===`workbench.action.terminal.sendSequence`&&e.when===`terminalFocus`))return{success:!1,message:`Found existing ${e} Shift+Enter key binding. Remove it to continue.\nSee: ${i}`}}return t.push({key:`shift+enter`,command:`workbench.action.terminal.sendSequence`,args:{text:`\x1B\r`},when:`terminalFocus`}),p.writeFileSync(i,JSON.stringify(t,null,2),`utf-8`),{success:!0,message:`Installed ${e} terminal Shift+Enter key binding\nSee: ${i}`}}catch(t){return{success:!1,message:`Failed to install ${e} terminal Shift+Enter key binding: ${t instanceof Error?t.message:String(t)}`}}}async function i1(e,t){try{let{stdout:n,stderr:r}=await t1(e,t,{encoding:`utf8`});return{stdout:n,stderr:r,code:0}}catch(e){if(e&&typeof e==`object`&&`code`in e){let t=e;return{stdout:t.stdout||``,stderr:t.stderr||``,code:typeof t.code==`number`?t.code:1}}return{stdout:``,stderr:e instanceof Error?e.message:String(e),code:1}}}async function a1(){if(U.platform!==`darwin`)return{success:!1,message:`iTerm2 setup is only available on macOS`};try{let{code:e}=await i1(`defaults`,[`write`,`com.googlecode.iterm2`,`GlobalKeyMap`,`-dict-add`,`0xd-0x20000`,`<dict><key>Text</key><string>\x1B\r</string><key>Action</key><integer>12</integer></dict>`]);return e===0?{success:!0,message:`Installed iTerm2 Shift+Enter key binding
12708
- Restart iTerm2 for changes to take effect.`,requiresRestart:!0}:{success:!1,message:`Failed to install iTerm2 Shift+Enter key binding`}}catch(e){return{success:!1,message:`Failed to configure iTerm2: ${e instanceof Error?e.message:String(e)}`}}}async function o1(){if(U.platform!==`darwin`)return{success:!1,message:`Apple Terminal setup is only available on macOS`};let e=C.join(n.homedir(),`Library`,`Preferences`,`com.apple.Terminal.plist`),t=n1(e);try{let{stdout:n,code:r}=await i1(`defaults`,[`read`,`com.apple.Terminal`,`Default Window Settings`]);if(r!==0||!n.trim())return{success:!1,message:`Failed to read default Terminal.app profile`};let i=n.trim(),{code:a}=await i1(`/usr/libexec/PlistBuddy`,[`-c`,`Add :'Window Settings':'${i}':useOptionAsMetaKey bool true`,e]);return a!==0&&({code:a}=await i1(`/usr/libexec/PlistBuddy`,[`-c`,`Set :'Window Settings':'${i}':useOptionAsMetaKey true`,e])),await i1(`killall`,[`cfprefsd`]),{success:!0,message:`Configured Terminal.app to use Option as Meta key
12707
+ `,t1=`\\x1b\\r`,n1=O(s);function r1(e){if(!p.existsSync(e))return null;let t=`${e}.${oe(4).toString(`hex`)}.bak`;try{return p.copyFileSync(e,t),t}catch{return null}}async function i1(e){let t=n.homedir(),r;r=U.platform===`win32`?C.join(t,`AppData`,`Roaming`,e,`User`):U.platform===`darwin`?C.join(t,`Library`,`Application Support`,e,`User`):C.join(t,`.config`,e,`User`);let i=C.join(r,`keybindings.json`);try{p.existsSync(r)||p.mkdirSync(r,{recursive:!0});let t=[];if(p.existsSync(i)){let n=p.readFileSync(i,`utf-8`);if(!r1(i))return{success:!1,message:`Failed to backup existing ${e} keybindings`};let r=n.replace(/\/\/.*$/gm,``).replace(/\/\*[\s\S]*?\*\//g,``);try{t=JSON.parse(r||`[]`)}catch{t=[]}if(t.find(e=>e.key===`shift+enter`&&e.command===`workbench.action.terminal.sendSequence`&&e.when===`terminalFocus`))return{success:!1,message:`Found existing ${e} Shift+Enter key binding. Remove it to continue.\nSee: ${i}`}}return t.push({key:`shift+enter`,command:`workbench.action.terminal.sendSequence`,args:{text:`\x1B\r`},when:`terminalFocus`}),p.writeFileSync(i,JSON.stringify(t,null,2),`utf-8`),{success:!0,message:`Installed ${e} terminal Shift+Enter key binding\nSee: ${i}`}}catch(t){return{success:!1,message:`Failed to install ${e} terminal Shift+Enter key binding: ${t instanceof Error?t.message:String(t)}`}}}async function a1(e,t){try{let{stdout:n,stderr:r}=await n1(e,t,{encoding:`utf8`});return{stdout:n,stderr:r,code:0}}catch(e){if(e&&typeof e==`object`&&`code`in e){let t=e;return{stdout:t.stdout||``,stderr:t.stderr||``,code:typeof t.code==`number`?t.code:1}}return{stdout:``,stderr:e instanceof Error?e.message:String(e),code:1}}}async function o1(){if(U.platform!==`darwin`)return{success:!1,message:`iTerm2 setup is only available on macOS`};try{let{code:e}=await a1(`defaults`,[`write`,`com.googlecode.iterm2`,`GlobalKeyMap`,`-dict-add`,`0xd-0x20000`,`<dict><key>Text</key><string>\x1B\r</string><key>Action</key><integer>12</integer></dict>`]);return e===0?{success:!0,message:`Installed iTerm2 Shift+Enter key binding
12708
+ Restart iTerm2 for changes to take effect.`,requiresRestart:!0}:{success:!1,message:`Failed to install iTerm2 Shift+Enter key binding`}}catch(e){return{success:!1,message:`Failed to configure iTerm2: ${e instanceof Error?e.message:String(e)}`}}}async function s1(){if(U.platform!==`darwin`)return{success:!1,message:`Apple Terminal setup is only available on macOS`};let e=C.join(n.homedir(),`Library`,`Preferences`,`com.apple.Terminal.plist`),t=r1(e);try{let{stdout:n,code:r}=await a1(`defaults`,[`read`,`com.apple.Terminal`,`Default Window Settings`]);if(r!==0||!n.trim())return{success:!1,message:`Failed to read default Terminal.app profile`};let i=n.trim(),{code:a}=await a1(`/usr/libexec/PlistBuddy`,[`-c`,`Add :'Window Settings':'${i}':useOptionAsMetaKey bool true`,e]);return a!==0&&({code:a}=await a1(`/usr/libexec/PlistBuddy`,[`-c`,`Set :'Window Settings':'${i}':useOptionAsMetaKey true`,e])),await a1(`killall`,[`cfprefsd`]),{success:!0,message:`Configured Terminal.app to use Option as Meta key
12709
12709
  Option+Enter will now insert a newline
12710
- Restart Terminal.app for changes to take effect.`,requiresRestart:!0,backupPath:t||void 0}}catch(e){return{success:!1,message:`Failed to configure Terminal.app: ${e instanceof Error?e.message:String(e)}`}}}async function s1(){let e=[],t=U.env.XDG_CONFIG_HOME;t?e.push(C.join(t,`ghostty`,`config`)):e.push(C.join(n.homedir(),`.config`,`ghostty`,`config`)),U.platform===`darwin`&&e.push(C.join(n.homedir(),`Library`,`Application Support`,`com.mitchellh.ghostty`,`config`));let r=null,i=!1;for(let t of e)if(p.existsSync(t)){r=t,i=!0;break}r||=e[0];try{let e=``;if(i){if(e=p.readFileSync(r,`utf-8`),e.includes(`shift+enter`))return{success:!1,message:`Found existing Ghostty Shift+Enter key binding. Remove it to continue.\nSee: ${r}`};if(!n1(r))return{success:!1,message:`Failed to backup existing Ghostty config`}}else{let e=C.dirname(r);p.existsSync(e)||p.mkdirSync(e,{recursive:!0})}let t=e;return e&&!e.endsWith(`
12710
+ Restart Terminal.app for changes to take effect.`,requiresRestart:!0,backupPath:t||void 0}}catch(e){return{success:!1,message:`Failed to configure Terminal.app: ${e instanceof Error?e.message:String(e)}`}}}async function c1(){let e=[],t=U.env.XDG_CONFIG_HOME;t?e.push(C.join(t,`ghostty`,`config`)):e.push(C.join(n.homedir(),`.config`,`ghostty`,`config`)),U.platform===`darwin`&&e.push(C.join(n.homedir(),`Library`,`Application Support`,`com.mitchellh.ghostty`,`config`));let r=null,i=!1;for(let t of e)if(p.existsSync(t)){r=t,i=!0;break}r||=e[0];try{let e=``;if(i){if(e=p.readFileSync(r,`utf-8`),e.includes(`shift+enter`))return{success:!1,message:`Found existing Ghostty Shift+Enter key binding. Remove it to continue.\nSee: ${r}`};if(!r1(r))return{success:!1,message:`Failed to backup existing Ghostty config`}}else{let e=C.dirname(r);p.existsSync(e)||p.mkdirSync(e,{recursive:!0})}let t=e;return e&&!e.endsWith(`
12711
12711
  `)&&(t+=`
12712
- `),t+=`keybind = shift+enter=text:${e1}\n`,p.writeFileSync(r,t,`utf-8`),{success:!0,message:`Installed Ghostty Shift+Enter key binding\nSee: ${r}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install Ghostty Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function c1(){let e=C.join(n.homedir(),`.wezterm.lua`);try{let t=``,n=!1;if(p.existsSync(e)){if(n=!0,t=p.readFileSync(e,`utf-8`),t.includes(`mods="SHIFT"`)&&t.includes(`key="Enter"`))return{success:!1,message:`Found existing WezTerm Shift+Enter key binding. Remove it to continue.\nSee: ${e}`};if(!n1(e))return{success:!1,message:`Failed to backup existing WezTerm config`}}let r=`{key="Enter", mods="SHIFT", action=wezterm.action{SendString="${e1}"}}`;if(!n)t=`local wezterm = require 'wezterm'
12712
+ `),t+=`keybind = shift+enter=text:${t1}\n`,p.writeFileSync(r,t,`utf-8`),{success:!0,message:`Installed Ghostty Shift+Enter key binding\nSee: ${r}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install Ghostty Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function l1(){let e=C.join(n.homedir(),`.wezterm.lua`);try{let t=``,n=!1;if(p.existsSync(e)){if(n=!0,t=p.readFileSync(e,`utf-8`),t.includes(`mods="SHIFT"`)&&t.includes(`key="Enter"`))return{success:!1,message:`Found existing WezTerm Shift+Enter key binding. Remove it to continue.\nSee: ${e}`};if(!r1(e))return{success:!1,message:`Failed to backup existing WezTerm config`}}let r=`{key="Enter", mods="SHIFT", action=wezterm.action{SendString="${t1}"}}`;if(!n)t=`local wezterm = require 'wezterm'
12713
12713
  local config = wezterm.config_builder()
12714
12714
 
12715
12715
  config.keys = {
@@ -12717,36 +12717,36 @@ config.keys = {
12717
12717
  }
12718
12718
 
12719
12719
  return config
12720
- `;else{let e=t.match(/config\.keys\s*=\s*\{([^}]*)\}/s);if(e){let n=e[1]??``,i=n.trim()?`${n.trim()},\n ${r},`:`\n ${r},\n`;t=t.replace(/config\.keys\s*=\s*\{[^}]*\}/s,`config.keys = {${i}}`)}else t.match(/return\s+config/s)?t=t.replace(/return\s+config/s,`config.keys = {\n ${r},\n}\n\nreturn config`):t+=`\nconfig.keys = {\n ${r},\n}\n`}return p.writeFileSync(e,t,`utf-8`),{success:!0,message:`Installed WezTerm Shift+Enter key binding\nSee: ${e}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install WezTerm Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function l1(){let e=[],t=U.env.XDG_CONFIG_HOME;t?e.push(C.join(t,`kitty`,`kitty.conf`)):e.push(C.join(n.homedir(),`.config`,`kitty`,`kitty.conf`)),U.platform===`darwin`&&e.push(C.join(n.homedir(),`Library`,`Preferences`,`kitty`,`kitty.conf`));let r=null,i=!1;for(let t of e)if(p.existsSync(t)){r=t,i=!0;break}r||=e[0];try{let e=``;if(i){if(e=p.readFileSync(r,`utf-8`),e.includes(`shift+enter`)&&e.includes(`send_text`))return{success:!1,message:`Found existing Kitty Shift+Enter key binding. Remove it to continue.\nSee: ${r}`};if(!n1(r))return{success:!1,message:`Failed to backup existing Kitty config`}}else{let e=C.dirname(r);p.existsSync(e)||p.mkdirSync(e,{recursive:!0})}let t=e;return e&&!e.endsWith(`
12720
+ `;else{let e=t.match(/config\.keys\s*=\s*\{([^}]*)\}/s);if(e){let n=e[1]??``,i=n.trim()?`${n.trim()},\n ${r},`:`\n ${r},\n`;t=t.replace(/config\.keys\s*=\s*\{[^}]*\}/s,`config.keys = {${i}}`)}else t.match(/return\s+config/s)?t=t.replace(/return\s+config/s,`config.keys = {\n ${r},\n}\n\nreturn config`):t+=`\nconfig.keys = {\n ${r},\n}\n`}return p.writeFileSync(e,t,`utf-8`),{success:!0,message:`Installed WezTerm Shift+Enter key binding\nSee: ${e}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install WezTerm Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function u1(){let e=[],t=U.env.XDG_CONFIG_HOME;t?e.push(C.join(t,`kitty`,`kitty.conf`)):e.push(C.join(n.homedir(),`.config`,`kitty`,`kitty.conf`)),U.platform===`darwin`&&e.push(C.join(n.homedir(),`Library`,`Preferences`,`kitty`,`kitty.conf`));let r=null,i=!1;for(let t of e)if(p.existsSync(t)){r=t,i=!0;break}r||=e[0];try{let e=``;if(i){if(e=p.readFileSync(r,`utf-8`),e.includes(`shift+enter`)&&e.includes(`send_text`))return{success:!1,message:`Found existing Kitty Shift+Enter key binding. Remove it to continue.\nSee: ${r}`};if(!r1(r))return{success:!1,message:`Failed to backup existing Kitty config`}}else{let e=C.dirname(r);p.existsSync(e)||p.mkdirSync(e,{recursive:!0})}let t=e;return e&&!e.endsWith(`
12721
12721
  `)&&(t+=`
12722
- `),t+=`map shift+enter send_text all ${e1}\n`,p.writeFileSync(r,t,`utf-8`),{success:!0,message:`Installed Kitty Shift+Enter key binding\nSee: ${r}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install Kitty Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function u1(){let e=[],t=U.env.XDG_CONFIG_HOME;t?(e.push(C.join(t,`alacritty`,`alacritty.toml`)),e.push(C.join(t,`alacritty`,`alacritty.yml`))):(e.push(C.join(n.homedir(),`.config`,`alacritty`,`alacritty.toml`)),e.push(C.join(n.homedir(),`.config`,`alacritty`,`alacritty.yml`))),U.platform===`darwin`&&(e.push(C.join(n.homedir(),`.alacritty.toml`)),e.push(C.join(n.homedir(),`.alacritty.yml`)));let r=null,i=!1,a=!0;for(let t of e)if(p.existsSync(t)){r=t,i=!0,a=t.endsWith(`.toml`);break}r||=e[0];try{let e=``;if(i){if(e=p.readFileSync(r,`utf-8`),e.includes(`Shift`)&&e.includes(`Return`))return{success:!1,message:`Found existing Alacritty Shift+Enter key binding. Remove it to continue.\nSee: ${r}`};if(!n1(r))return{success:!1,message:`Failed to backup existing Alacritty config`}}else{let e=C.dirname(r);p.existsSync(e)||p.mkdirSync(e,{recursive:!0})}let t=e;return e&&!e.endsWith(`
12722
+ `),t+=`map shift+enter send_text all ${t1}\n`,p.writeFileSync(r,t,`utf-8`),{success:!0,message:`Installed Kitty Shift+Enter key binding\nSee: ${r}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install Kitty Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function d1(){let e=[],t=U.env.XDG_CONFIG_HOME;t?(e.push(C.join(t,`alacritty`,`alacritty.toml`)),e.push(C.join(t,`alacritty`,`alacritty.yml`))):(e.push(C.join(n.homedir(),`.config`,`alacritty`,`alacritty.toml`)),e.push(C.join(n.homedir(),`.config`,`alacritty`,`alacritty.yml`))),U.platform===`darwin`&&(e.push(C.join(n.homedir(),`.alacritty.toml`)),e.push(C.join(n.homedir(),`.alacritty.yml`)));let r=null,i=!1,a=!0;for(let t of e)if(p.existsSync(t)){r=t,i=!0,a=t.endsWith(`.toml`);break}r||=e[0];try{let e=``;if(i){if(e=p.readFileSync(r,`utf-8`),e.includes(`Shift`)&&e.includes(`Return`))return{success:!1,message:`Found existing Alacritty Shift+Enter key binding. Remove it to continue.\nSee: ${r}`};if(!r1(r))return{success:!1,message:`Failed to backup existing Alacritty config`}}else{let e=C.dirname(r);p.existsSync(e)||p.mkdirSync(e,{recursive:!0})}let t=e;return e&&!e.endsWith(`
12723
12723
  `)&&(t+=`
12724
12724
  `),a?t+=`
12725
12725
  [[keyboard.bindings]]
12726
12726
  key = "Return"
12727
12727
  mods = "Shift"
12728
- chars = "${e1}"
12728
+ chars = "${t1}"
12729
12729
  `:t+=`
12730
12730
  key_bindings:
12731
- - { key: Return, mods: Shift, chars: "${e1}" }
12732
- `,p.writeFileSync(r,t,`utf-8`),{success:!0,message:`Installed Alacritty Shift+Enter key binding\nSee: ${r}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install Alacritty Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function d1(){let e=oZ();if(!e)return{success:!1,message:`Could not detect terminal. You can use backslash (\\) + Enter for newlines.`};switch(e){case`cursor`:return r1(`Cursor`);case`windsurf`:return r1(`Windsurf`);case`vscode`:return r1(`Code`);case`codium`:return r1(`VSCodium`);case`ghostty`:return s1();case`iTerm.app`:return a1();case`Apple_Terminal`:return o1();case`WezTerm`:return c1();case`kitty`:return l1();case`alacritty`:return u1();default:return{success:!1,message:`Terminal "${e}" is not supported for automatic setup.\n\nYou can use backslash (\\) + Enter for newlines.\n\nSupported terminals:\n- VS Code, Cursor, Windsurf, VSCodium\n- Ghostty\n- iTerm2\n- Apple Terminal\n- WezTerm\n- Kitty\n- Alacritty`}}}const f1={topLeft:``,top:`─`,topRight:``,left:``,right:``,bottomLeft:``,bottom:`─`,bottomRight:``},p1={topLeft:``,top:`╌`,topRight:``,left:``,right:``,bottomLeft:``,bottom:`╌`,bottomRight:``},m1=(0,Z.memo)(({title:e,subtitle:t})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{borderStyle:f1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsxs)($,{children:[` `,e]}),t&&(0,X.jsxs)($,{dimColor:!0,children:[` `,t]}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1})]}));m1.displayName=`PermissionPreviewHeader`;const h1=(0,Z.memo)(({title:e,subtitle:t,options:n,onDismiss:r})=>{let[i,a]=(0,Z.useState)(0),o=(0,Z.useRef)(n);o.current=n;let s=(0,Z.useRef)(i);s.current=i;let c=(0,Z.useRef)(r);c.current=r;let l=(0,Z.useCallback)(async()=>{let e=o.current[s.current];e&&await e.action(),c.current()},[]),u=(0,Z.useRef)(l);return u.current=l,sI((0,Z.useCallback)((e,t)=>{if(t.upArrow){a(e=>Math.max(0,e-1));return}if(t.downArrow){a(e=>Math.min(o.current.length-1,e+1));return}if(t.escape){c.current();return}if(t.return){u.current();return}},[]),{isActive:!0}),(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{borderStyle:f1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsxs)($,{children:[` `,e]}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),t&&(0,X.jsxs)($,{dimColor:!0,children:[` `,t]}),t&&(0,X.jsx)($,{}),n.map((e,t)=>{let n=t===i;return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?` ❯ `:` `}),(0,X.jsx)($,{color:n?void 0:`gray`,children:`${t+1}. ${e.label}`})]},t)}),(0,X.jsx)($,{}),(0,X.jsx)($,{dimColor:!0,children:` Enter to confirm · Esc to cancel`})]})});h1.displayName=`CommandOverlay`;const g1=.25,_1=(0,Z.memo)(({text:e,color:t=`#94a3b8`})=>{let[n,r]=(0,Z.useState)(0),i=e.length;(0,Z.useEffect)(()=>{let e=setInterval(()=>{(0,Z.startTransition)(()=>{r(e=>e+1)})},100);return()=>clearInterval(e)},[]);let a=(0,Z.useMemo)(()=>v1(t),[t]);return(0,X.jsx)($,{children:(0,Z.useMemo)(()=>{let t=n%i,r=Math.max(i*.6,3),o=``;for(let n=0;n<i;n++){let s=Math.abs(n-t),c=i-s,l=Math.min(s,c),u=y1(a,Math.max(0,1-l/r));o+=NA.rgb(u.r,u.g,u.b)(e[n])}return o},[n,i,a,e])})});_1.displayName=`Shimmer`;function v1(e){let t=e.replace(`#`,``);return{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function y1(e,t){let n=Math.floor(e.r*g1),r=Math.floor(e.g*g1),i=Math.floor(e.b*g1);return{r:Math.floor(n+(e.r-n)*t),g:Math.floor(r+(e.g-r)*t),b:Math.floor(i+(e.b-i)*t)}}function b1(e){return new Promise(t=>{process.platform===`darwin`?s(`open`,[e],e=>t(!e)):process.platform===`win32`?s(`cmd`,[`/c`,`start`,``,e],e=>t(!e)):s(`xdg-open`,[e],e=>t(!e))})}function x1(e){return new Promise(t=>{let n=process.platform===`darwin`?u(`pbcopy`):process.platform===`win32`?u(`clip`):u(`xclip`,[`-selection`,`clipboard`]);n.on(`error`,()=>t(!1)),n.on(`exit`,e=>t(e===0)),n.stdin?.write(e),n.stdin?.end()})}const S1=(0,Z.memo)(({initialEmail:e,auth:t,onDismiss:n})=>{let[r,i]=(0,Z.useState)(()=>e?{type:`connecting`,email:e}:{type:`input`,mode:`email`}),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(null),u=(0,Z.useRef)(!1),d=(0,Z.useRef)(n);d.current=n;let f=(0,Z.useCallback)(async e=>{i({type:`connecting`,email:e});try{let n=await t.initiateDeviceCode(e);if(u.current)return;if(!n.success||!n.verificationUri||!n.userCode){i({type:`error`,message:n.error??`Failed to initiate login`,canRetry:!0});return}i({type:`polling`,verificationUri:n.verificationUri,userCode:n.userCode,pollingInterval:n.pollingInterval??5})}catch(e){if(u.current)return;i({type:`error`,message:e instanceof Error?e.message:`Failed to connect`,canRetry:!0})}},[t]);(0,Z.useEffect)(()=>{e&&f(e)},[]),(0,Z.useEffect)(()=>{r.type===`polling`&&(o(!1),c(!1),b1(r.verificationUri).then(e=>{u.current||o(e)}))},[r.type===`polling`?r.verificationUri:null]),(0,Z.useEffect)(()=>{if(r.type!==`polling`)return;let e=!0,n=r.pollingInterval*1e3,a=Date.now()+600*1e3,{userCode:o}=r;return(async()=>{for(;e&&!u.current&&Date.now()<a;){if(await new Promise(e=>setTimeout(e,n)),!e||u.current)return;try{let n=await t.pollDeviceCode(o);if(!e||u.current)return;if(n.success&&n.deviceCode){try{if(await t.completeDeviceCodeLogin(n.deviceCode,n.chatWebUrl),!e||u.current)return;i({type:`success`})}catch(t){if(!e||u.current)return;i({type:`error`,message:t instanceof Error?t.message:`Failed to complete login`,canRetry:!1})}return}}catch{}}e&&!u.current&&i({type:`error`,message:`Authentication timed out. Please try again.`,canRetry:!0})})(),()=>{e=!1}},[r.type===`polling`?r.userCode:null,t]),(0,Z.useEffect)(()=>{if(r.type===`success`){let e=setTimeout(()=>d.current(),1500);return()=>clearTimeout(e)}},[r.type]);let p=(0,Z.useCallback)(e=>{let n=e.trim();if(n){if(r.type===`input`&&r.mode===`apikey`){t.loginWithApiKey(n).then(()=>{u.current||i({type:`success`})}).catch(e=>{u.current||i({type:`error`,message:e instanceof Error?e.message:`API key login failed`,canRetry:!0})});return}f(n)}},[r,f,t]),m=(0,Z.useCallback)(()=>{u.current=!0,d.current()},[]),h=(0,Z.useCallback)(()=>{r.type===`polling`&&x1(r.verificationUri).then(e=>{e&&c(!0)})},[r]);if(sI((0,Z.useCallback)((e,t)=>{if(t.escape){m();return}if(r.type===`input`&&t.ctrl&&(e===`a`||e===``)){i(e=>e.type===`input`?{type:`input`,mode:e.mode===`email`?`apikey`:`email`}:e);return}if(r.type===`polling`&&e===`c`){h();return}if(r.type===`error`&&r.canRetry&&t.return){i({type:`input`,mode:`email`});return}},[r,m,h]),{isActive:r.type!==`input`}),r.type===`input`){let e=r.mode===`email`;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{dimColor:!0,children:e?` Email:`:` API Key:`}),(0,X.jsx)(J$,{ref:l,placeholder:e?`you@example.com`:`Paste your API key`,onSubmit:p,onKeyDown:e=>{e.key.paste&&(e.preventDefault(),e.target.insert(e.input)),e.key.escape&&(e.preventDefault(),m()),e.key.ctrl&&(e.input===`a`||e.input===``)&&(e.preventDefault(),i(e=>e.type===`input`?{type:`input`,mode:e.mode===`email`?`apikey`:`email`}:e))}})]}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Enter to submit · Esc to cancel · Ctrl+A to switch to`,` `,e?`API key`:`email`]})]})}return r.type===`connecting`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)(_1,{text:`Logging in as ${r.email}...`})]}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Esc to cancel`]})]}):r.type===`polling`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)($,{children:[` `,a?(0,X.jsx)($,{color:`yellow`,children:`Opening browser to sign in...`}):(0,X.jsx)(_1,{text:`Opening browser to sign in...`})]}),(0,X.jsx)($,{}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Browser didn't open? Use the URL below to sign in`,` `,(0,X.jsxs)($,{dimColor:!1,color:s?`green`:`gray`,children:[`(`,s?`copied!`:`c to copy`,`)`]})]}),(0,X.jsxs)($,{color:`cyan`,children:[` `,r.verificationUri]}),(0,X.jsx)($,{}),(0,X.jsxs)($,{children:[` `,`Your one-time code:`,` `,(0,X.jsx)($,{color:`yellowBright`,bold:!0,children:r.userCode})]}),(0,X.jsx)($,{}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)(_1,{text:`Waiting for authentication...`})]}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Esc to cancel`]})]}):r.type===`success`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)($,{color:`green`,children:[` `,`✓ Logged in successfully!`]}),(0,X.jsx)($,{})]}):r.type===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)($,{color:`red`,children:[` `,`✗ `,r.message]}),(0,X.jsx)($,{}),(0,X.jsxs)($,{dimColor:!0,children:[` `,r.canRetry?`Enter to retry · `:``,`Esc to close`]})]}):null});S1.displayName=`LoginOverlay`;const C1=new class{commands=new Map;register(e){this.commands.has(e.id)||this.commands.set(e.id,e)}clear(){this.commands.clear()}get(e){return this.commands.get(e)}getAll(){return Array.from(this.commands.values())}getAliasesForMode(e,t){return e.alias?Array.isArray(e.alias)?e.alias:e.alias[t]??[]:[]}buildCommandMatch(e,t){if(e.subcommands&&e.subcommands.length>0){if(t.length===0)return{command:e,args:``,query:``,needsSubcommand:!0};let n=t[0],r=e.subcommands.find(e=>e.id===n);if(!r){let n=t.join(` `);return{command:e,args:n,query:n,needsSubcommand:!0}}let i=t.slice(1).join(` `);return{command:e,subcommand:r,args:i,query:i}}let n=t.join(` `);return{command:e,args:n,query:n}}findCommandByAlias(e,t){let n=e.toLowerCase();for(let e of this.commands.values())if(this.getAliasesForMode(e,t).some(e=>e.toLowerCase()===n))return e}matchByAlias(e,t){let n=e.trim().split(/\s+/).filter(Boolean);if(n.length===0)return null;let[r,...i]=n,a=this.findCommandByAlias(r,t);return!a||!(a.requiresArgument||a.subcommands&&a.subcommands.length>0)&&i.length>0?null:this.buildCommandMatch(a,i)}parseArgs(e){let t=[],n=``,r=null,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(i){n+=o,i=!1;continue}if(o===`\\`){i=!0;continue}if(o===`'`||o===`"`){r===o?r=null:r===null?r=o:n+=o;continue}if(o===` `&&r===null){n.length>0&&(t.push(n),n=``);continue}n+=o}return n.length>0&&t.push(n),t}async execute(e){if(e.needsSubcommand)return!1;let t=e.args?this.parseArgs(e.args):[];return(e.subcommand||e.command).requiresArgument&&t.length===0?!1:e.subcommand?.execute?(await e.subcommand.execute(t),!0):e.command.execute?(await e.command.execute(t),!0):!1}match(e,t){let n=e.trim();if(t!==void 0&&!n.startsWith(`/`))return this.matchByAlias(n,t);if(!n.startsWith(`/`))return null;let r=n.slice(1).split(/\s+/).filter(Boolean);if(r.length===0)return null;let[i,...a]=r,o=this.commands.get(i);if(!o)return null;let s=e.trimStart().slice(1+i.length),c=s.length>0&&/\s/.test(s[0]);return a.length===0&&!c?{command:o,args:``,query:``,exactMatch:!0}:this.buildCommandMatch(o,a)}search(e,t){let n=this.getAll().filter(e=>!e.isAvailable||!t||e.isAvailable(t));return e?new Qx(n,{selector:e=>`${e.id} ${e.description}`}).find(e).map(e=>e.item):n}searchSubcommands(e,t){return e.subcommands?t?new Qx(e.subcommands,{selector:e=>`${e.id} ${e.description}`}).find(t).map(e=>e.item):e.subcommands:[]}},w1=FL;function T1(){let e=C1.getAll(),t=[],n=Math.max(0,...e.map(e=>e.subcommands&&e.subcommands.length>0?Math.max(0,...e.subcommands.map(e=>e.usage?.length||0)):e.usage?.length||0));t.push(`Abacus.AI CLI`,``,`Abacus.AI CLI has read access to files in the current directory and can run commands and edit files with your permission.`,``,`Use npx -y @abacus-ai/cli@latest to run latest version of abacusai interactive mode directly from your terminal`,``,`Usage Modes:`,`- REPL: abacusai (interactive session)`,`- Non-interactive: abacusai -p "question"`,``,`Run abacusai --help for all command line options`,``,`For first time users, use /login to authenticate to Abacus.AI CLI`,``,`Common Tasks:`,`- Ask questions about your codebase > How does agent.py work?`,`- Edit files > Update code.ts to...`,`- Fix errors > cargo build`,`- Run commands > /help`,`- Run bash commands > wc`,``,`Interactive Mode Commands:`,``);for(let r of e)if(r.subcommands&&r.subcommands.length>0)for(let e of r.subcommands)t.push(` ${(e.usage||``).padEnd(n+2)} ${e.description||``}`);else t.push(` ${(r.usage||``).padEnd(n+2)} ${r.description||``}`);return t.push(``,`Type any command and press Enter to execute.`),t.join(`
12733
- `)}function E1(e){let t=e.mcp?new Q$(e.mcp):void 0,n=(t,n=`info`,r)=>{e.addNotification?.(t,n,r)},i=[{id:`version`,description:`Show CLI version`,usage:`/version`,execute:()=>{let t=e.getUpdateInfo?.();n(t?`Abacus.AI CLI version ${PA} (${t.latestVersion} available)`:`Abacus.AI CLI version ${PA}`,`info`)}},{id:`exit`,description:`Exit the application`,usage:`/exit`,alias:{[ZK.Prompt]:[`exit`,`quit`]},execute:()=>{e.onExit?.()}},{id:`new`,description:`Start a new conversation`,usage:`/new`,isAvailable:e=>e.segmentsLength>0,execute:()=>{e.onNewChat?.()}},{id:`clear`,description:`Clear the output display while keeping the current conversation`,usage:`/clear`,alias:{[ZK.Prompt]:[`cls`,`clear`]},isAvailable:e=>e.segmentsLength>0,execute:()=>{e.onClearChat?.()}},{id:`stop`,description:`Stop the current streaming response and any running bash tools`,usage:`/stop`,isAvailable:e=>e.agentStatus===Sl.Submitted||e.agentStatus===Sl.Streaming||e.agentStatus===Sl.ExecutingTool||e.agentStatus===Sl.WaitingForToolPermission,execute:async()=>{let t=e.getAgentStatus?.(),r=t===Sl.Submitted||t===Sl.Streaming||t===Sl.ExecutingTool||t===Sl.WaitingForToolPermission;e.onStop?.(),r?n(`Agent stopped successfully`,`info`):n(`No active agent process to stop`,`warning`)}},{id:`help`,description:`Show commands and functionalities`,usage:`/help`,alias:{[ZK.Prompt]:[`help`]},execute:()=>{e.onHelp?e.onHelp():n(T1(),`info`)}},{id:`model`,description:`Switch to a different model`,usage:`/model <model_name>`,requiresArgument:!0,ghostProvider:e=>e?null:`claude-sonnet`,completionProvider:async t=>{if(!e.getModels)return[];let n=await e.getModels();if(!n?.length)return[];let r=n.map(e=>({label:e.label,id:e.value,description:e.model?.provider??``,badge:e.model?.isDefault?`default`:void 0}));return t.trim()?new Qx(r,{selector:e=>`${e.label} ${e.description}`}).find(t).map(e=>e.item):r},execute:async t=>{let r=t.join(` `).trim();if(!r){n(`Please specify a model name`,`error`);return}if(e.getModels){let t=await e.getModels();if(!t||t.length===0){n(`No models are available`,`error`);return}let i=t.find(e=>e.label===r||e.value===r);if(!i){n(`Model "${r}" not found`,`error`);return}e.onModelChange?.(i.value)}else e.onModelChange?.(r)}},{id:`resume`,description:`Resume a previous chat conversation`,usage:`/resume <chat_title>`,requiresArgument:!0,completionProvider:async t=>{if(!e.getChatTitles)return[];let n=await e.getChatTitles();if(!n?.length)return[];let r=n.map(e=>({label:e.title,id:e.id,description:e.messageCount?`${e.messageCount} msgs`:void 0}));return t.trim()?new Qx(r,{selector:e=>`${e.label} ${e.description??``}`}).find(t).map(e=>e.item):r},execute:t=>{let n=t.join(` `).trim();n&&e.onResumeChat?.(n)}},{id:`login`,description:`Log in to Abacus.AI CLI with email or API key`,usage:`/login [email|api_key]`,ghostProvider:e=>e?null:`example@gmail.com`,uiProvider:(t,r)=>{if(e.checkEnvAuth){let{isEnvAuth:t}=e.checkEnvAuth();if(t)return n(`You are logged in via environment variables. Remove ${ke.envPrefix}API_KEY to logout.`,`warning`),r.onDismiss(),null}if(!e.loginAuth)return n(`Login not available`,`error`),r.onDismiss(),null;let i=t.filter(Boolean).join(` `).trim(),a=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i);return i&&!a?(e.onLogin?.(i),r.onDismiss(),null):(0,X.jsx)(S1,{initialEmail:a?i:void 0,auth:e.loginAuth,onDismiss:r.onDismiss})},execute:async t=>{if(e.checkEnvAuth){let{isEnvAuth:t}=e.checkEnvAuth();if(t){n(`You are logged in via environment variables. Remove ${ke.envPrefix}API_KEY to logout.`,`warning`);return}}let r=t.filter(Boolean).join(` `).trim();r&&e.onLogin?.(r)}},{id:`logout`,description:`Log out of Abacus.AI CLI`,usage:`/logout`,execute:async()=>{if(e.checkEnvAuth){let{isEnvAuth:t}=e.checkEnvAuth();if(t){n(`You are logged in via environment variables. Remove ${ke.envPrefix}API_KEY to logout.`,`warning`);return}}try{e.onLogout?.(),n(`Logged out successfully`,`info`)}catch(e){n(`Logout failed: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`status`,description:`Show current user status`,usage:`/status`,execute:async()=>{try{await e.getUserInfo?.()}catch(e){n(`Failed to get status: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`usage`,description:`Show total credits consumed in current conversation`,usage:`/usage`,isAvailable:()=>e.getTotalCredits!==void 0,execute:async()=>{if(!e.getTotalCredits){n(`Usage information not available`,`error`);return}try{let t=await e.getTotalCredits();n(t>0?`Total credits consumed: ${Math.floor(t*100)/100}`:`No credits consumed yet in this conversation`,`info`)}catch(e){n(`Failed to get usage: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`terminal-setup`,description:`Automatically configure terminal for Shift+Enter newlines`,usage:`/terminal-setup`,execute:async()=>{try{n(`Setting up terminal keybindings...`,`info`);let e=await d1();if(e.success){let t=e.message;e.backupPath&&(t+=`\n\nBackup created: ${e.backupPath}`),e.requiresRestart&&(t+=`
12731
+ - { key: Return, mods: Shift, chars: "${t1}" }
12732
+ `,p.writeFileSync(r,t,`utf-8`),{success:!0,message:`Installed Alacritty Shift+Enter key binding\nSee: ${r}`,requiresRestart:!0}}catch(e){return{success:!1,message:`Failed to install Alacritty Shift+Enter key binding: ${e instanceof Error?e.message:String(e)}`}}}async function f1(){let e=sZ();if(!e)return{success:!1,message:`Could not detect terminal. You can use backslash (\\) + Enter for newlines.`};switch(e){case`cursor`:return i1(`Cursor`);case`windsurf`:return i1(`Windsurf`);case`vscode`:return i1(`Code`);case`codium`:return i1(`VSCodium`);case`ghostty`:return c1();case`iTerm.app`:return o1();case`Apple_Terminal`:return s1();case`WezTerm`:return l1();case`kitty`:return u1();case`alacritty`:return d1();default:return{success:!1,message:`Terminal "${e}" is not supported for automatic setup.\n\nYou can use backslash (\\) + Enter for newlines.\n\nSupported terminals:\n- VS Code, Cursor, Windsurf, VSCodium\n- Ghostty\n- iTerm2\n- Apple Terminal\n- WezTerm\n- Kitty\n- Alacritty`}}}const p1={topLeft:``,top:`─`,topRight:``,left:``,right:``,bottomLeft:``,bottom:`─`,bottomRight:``},m1={topLeft:``,top:`╌`,topRight:``,left:``,right:``,bottomLeft:``,bottom:`╌`,bottomRight:``},h1=(0,Z.memo)(({title:e,subtitle:t})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsxs)($,{children:[` `,e]}),t&&(0,X.jsxs)($,{dimColor:!0,children:[` `,t]}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1})]}));h1.displayName=`PermissionPreviewHeader`;const g1=(0,Z.memo)(({title:e,subtitle:t,options:n,onDismiss:r})=>{let[i,a]=(0,Z.useState)(0),o=(0,Z.useRef)(n);o.current=n;let s=(0,Z.useRef)(i);s.current=i;let c=(0,Z.useRef)(r);c.current=r;let l=(0,Z.useCallback)(async()=>{let e=o.current[s.current];e&&await e.action(),c.current()},[]),u=(0,Z.useRef)(l);return u.current=l,sI((0,Z.useCallback)((e,t)=>{if(t.upArrow){a(e=>Math.max(0,e-1));return}if(t.downArrow){a(e=>Math.min(o.current.length-1,e+1));return}if(t.escape){c.current();return}if(t.return){u.current();return}},[]),{isActive:!0}),(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsxs)($,{children:[` `,e]}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),t&&(0,X.jsxs)($,{dimColor:!0,children:[` `,t]}),t&&(0,X.jsx)($,{}),n.map((e,t)=>{let n=t===i;return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?` ❯ `:` `}),(0,X.jsx)($,{color:n?void 0:`gray`,children:`${t+1}. ${e.label}`})]},t)}),(0,X.jsx)($,{}),(0,X.jsx)($,{dimColor:!0,children:` Enter to confirm · Esc to cancel`})]})});g1.displayName=`CommandOverlay`;const _1=.25,v1=(0,Z.memo)(({text:e,color:t=`#94a3b8`})=>{let[n,r]=(0,Z.useState)(0),i=e.length;(0,Z.useEffect)(()=>{let e=setInterval(()=>{(0,Z.startTransition)(()=>{r(e=>e+1)})},100);return()=>clearInterval(e)},[]);let a=(0,Z.useMemo)(()=>y1(t),[t]);return(0,X.jsx)($,{children:(0,Z.useMemo)(()=>{let t=n%i,r=Math.max(i*.6,3),o=``;for(let n=0;n<i;n++){let s=Math.abs(n-t),c=i-s,l=Math.min(s,c),u=b1(a,Math.max(0,1-l/r));o+=NA.rgb(u.r,u.g,u.b)(e[n])}return o},[n,i,a,e])})});v1.displayName=`Shimmer`;function y1(e){let t=e.replace(`#`,``);return{r:parseInt(t.substring(0,2),16),g:parseInt(t.substring(2,4),16),b:parseInt(t.substring(4,6),16)}}function b1(e,t){let n=Math.floor(e.r*_1),r=Math.floor(e.g*_1),i=Math.floor(e.b*_1);return{r:Math.floor(n+(e.r-n)*t),g:Math.floor(r+(e.g-r)*t),b:Math.floor(i+(e.b-i)*t)}}function x1(e){return new Promise(t=>{process.platform===`darwin`?s(`open`,[e],e=>t(!e)):process.platform===`win32`?s(`cmd`,[`/c`,`start`,``,e],e=>t(!e)):s(`xdg-open`,[e],e=>t(!e))})}function S1(e){return new Promise(t=>{let n=process.platform===`darwin`?u(`pbcopy`):process.platform===`win32`?u(`clip`):u(`xclip`,[`-selection`,`clipboard`]);n.on(`error`,()=>t(!1)),n.on(`exit`,e=>t(e===0)),n.stdin?.write(e),n.stdin?.end()})}const C1=(0,Z.memo)(({initialEmail:e,auth:t,onDismiss:n})=>{let[r,i]=(0,Z.useState)(()=>e?{type:`connecting`,email:e}:{type:`input`,mode:`email`}),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(null),u=(0,Z.useRef)(!1),d=(0,Z.useRef)(n);d.current=n;let f=(0,Z.useCallback)(async e=>{i({type:`connecting`,email:e});try{let n=await t.initiateDeviceCode(e);if(u.current)return;if(!n.success||!n.verificationUri||!n.userCode){i({type:`error`,message:n.error??`Failed to initiate login`,canRetry:!0});return}i({type:`polling`,verificationUri:n.verificationUri,userCode:n.userCode,pollingInterval:n.pollingInterval??5})}catch(e){if(u.current)return;i({type:`error`,message:e instanceof Error?e.message:`Failed to connect`,canRetry:!0})}},[t]);(0,Z.useEffect)(()=>{e&&f(e)},[]),(0,Z.useEffect)(()=>{r.type===`polling`&&(o(!1),c(!1),x1(r.verificationUri).then(e=>{u.current||o(e)}))},[r.type===`polling`?r.verificationUri:null]),(0,Z.useEffect)(()=>{if(r.type!==`polling`)return;let e=!0,n=r.pollingInterval*1e3,a=Date.now()+600*1e3,{userCode:o}=r;return(async()=>{for(;e&&!u.current&&Date.now()<a;){if(await new Promise(e=>setTimeout(e,n)),!e||u.current)return;try{let n=await t.pollDeviceCode(o);if(!e||u.current)return;if(n.success&&n.deviceCode){try{if(await t.completeDeviceCodeLogin(n.deviceCode,n.chatWebUrl),!e||u.current)return;i({type:`success`})}catch(t){if(!e||u.current)return;i({type:`error`,message:t instanceof Error?t.message:`Failed to complete login`,canRetry:!1})}return}}catch{}}e&&!u.current&&i({type:`error`,message:`Authentication timed out. Please try again.`,canRetry:!0})})(),()=>{e=!1}},[r.type===`polling`?r.userCode:null,t]),(0,Z.useEffect)(()=>{if(r.type===`success`){let e=setTimeout(()=>d.current(),1500);return()=>clearTimeout(e)}},[r.type]);let p=(0,Z.useCallback)(e=>{let n=e.trim();if(n){if(r.type===`input`&&r.mode===`apikey`){t.loginWithApiKey(n).then(()=>{u.current||i({type:`success`})}).catch(e=>{u.current||i({type:`error`,message:e instanceof Error?e.message:`API key login failed`,canRetry:!0})});return}f(n)}},[r,f,t]),m=(0,Z.useCallback)(()=>{u.current=!0,d.current()},[]),h=(0,Z.useCallback)(()=>{r.type===`polling`&&S1(r.verificationUri).then(e=>{e&&c(!0)})},[r]);if(sI((0,Z.useCallback)((e,t)=>{if(t.escape){m();return}if(r.type===`input`&&t.ctrl&&(e===`a`||e===``)){i(e=>e.type===`input`?{type:`input`,mode:e.mode===`email`?`apikey`:`email`}:e);return}if(r.type===`polling`&&e===`c`){h();return}if(r.type===`error`&&r.canRetry&&t.return){i({type:`input`,mode:`email`});return}},[r,m,h]),{isActive:r.type!==`input`}),r.type===`input`){let e=r.mode===`email`;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{dimColor:!0,children:e?` Email:`:` API Key:`}),(0,X.jsx)(Y$,{ref:l,placeholder:e?`you@example.com`:`Paste your API key`,onSubmit:p,onKeyDown:e=>{e.key.paste&&(e.preventDefault(),e.target.insert(e.input)),e.key.escape&&(e.preventDefault(),m()),e.key.ctrl&&(e.input===`a`||e.input===``)&&(e.preventDefault(),i(e=>e.type===`input`?{type:`input`,mode:e.mode===`email`?`apikey`:`email`}:e))}})]}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Enter to submit · Esc to cancel · Ctrl+A to switch to`,` `,e?`API key`:`email`]})]})}return r.type===`connecting`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)(v1,{text:`Logging in as ${r.email}...`})]}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Esc to cancel`]})]}):r.type===`polling`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)($,{children:[` `,a?(0,X.jsx)($,{color:`yellow`,children:`Opening browser to sign in...`}):(0,X.jsx)(v1,{text:`Opening browser to sign in...`})]}),(0,X.jsx)($,{}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Browser didn't open? Use the URL below to sign in`,` `,(0,X.jsxs)($,{dimColor:!1,color:s?`green`:`gray`,children:[`(`,s?`copied!`:`c to copy`,`)`]})]}),(0,X.jsxs)($,{color:`cyan`,children:[` `,r.verificationUri]}),(0,X.jsx)($,{}),(0,X.jsxs)($,{children:[` `,`Your one-time code:`,` `,(0,X.jsx)($,{color:`yellowBright`,bold:!0,children:r.userCode})]}),(0,X.jsx)($,{}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)(v1,{text:`Waiting for authentication...`})]}),(0,X.jsxs)($,{dimColor:!0,children:[` `,`Esc to cancel`]})]}):r.type===`success`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)($,{color:`green`,children:[` `,`✓ Logged in successfully!`]}),(0,X.jsx)($,{})]}):r.type===`error`?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)($,{}),(0,X.jsxs)($,{color:`red`,children:[` `,`✗ `,r.message]}),(0,X.jsx)($,{}),(0,X.jsxs)($,{dimColor:!0,children:[` `,r.canRetry?`Enter to retry · `:``,`Esc to close`]})]}):null});C1.displayName=`LoginOverlay`;const w1=new class{commands=new Map;register(e){this.commands.has(e.id)||this.commands.set(e.id,e)}clear(){this.commands.clear()}get(e){return this.commands.get(e)}getAll(){return Array.from(this.commands.values())}getAliasesForMode(e,t){return e.alias?Array.isArray(e.alias)?e.alias:e.alias[t]??[]:[]}buildCommandMatch(e,t){if(e.subcommands&&e.subcommands.length>0){if(t.length===0)return{command:e,args:``,query:``,needsSubcommand:!0};let n=t[0],r=e.subcommands.find(e=>e.id===n);if(!r){let n=t.join(` `);return{command:e,args:n,query:n,needsSubcommand:!0}}let i=t.slice(1).join(` `);return{command:e,subcommand:r,args:i,query:i}}let n=t.join(` `);return{command:e,args:n,query:n}}findCommandByAlias(e,t){let n=e.toLowerCase();for(let e of this.commands.values())if(this.getAliasesForMode(e,t).some(e=>e.toLowerCase()===n))return e}matchByAlias(e,t){let n=e.trim().split(/\s+/).filter(Boolean);if(n.length===0)return null;let[r,...i]=n,a=this.findCommandByAlias(r,t);return!a||!(a.requiresArgument||a.subcommands&&a.subcommands.length>0)&&i.length>0?null:this.buildCommandMatch(a,i)}parseArgs(e){let t=[],n=``,r=null,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(i){n+=o,i=!1;continue}if(o===`\\`){i=!0;continue}if(o===`'`||o===`"`){r===o?r=null:r===null?r=o:n+=o;continue}if(o===` `&&r===null){n.length>0&&(t.push(n),n=``);continue}n+=o}return n.length>0&&t.push(n),t}async execute(e){if(e.needsSubcommand)return!1;let t=e.args?this.parseArgs(e.args):[];return(e.subcommand||e.command).requiresArgument&&t.length===0?!1:e.subcommand?.execute?(await e.subcommand.execute(t),!0):e.command.execute?(await e.command.execute(t),!0):!1}match(e,t){let n=e.trim();if(t!==void 0&&!n.startsWith(`/`))return this.matchByAlias(n,t);if(!n.startsWith(`/`))return null;let r=n.slice(1).split(/\s+/).filter(Boolean);if(r.length===0)return null;let[i,...a]=r,o=this.commands.get(i);if(!o)return null;let s=e.trimStart().slice(1+i.length),c=s.length>0&&/\s/.test(s[0]);return a.length===0&&!c?{command:o,args:``,query:``,exactMatch:!0}:this.buildCommandMatch(o,a)}search(e,t){let n=this.getAll().filter(e=>!e.isAvailable||!t||e.isAvailable(t));return e?new Qx(n,{selector:e=>`${e.id} ${e.description}`}).find(e).map(e=>e.item):n}searchSubcommands(e,t){return e.subcommands?t?new Qx(e.subcommands,{selector:e=>`${e.id} ${e.description}`}).find(t).map(e=>e.item):e.subcommands:[]}},T1=FL;function E1(){let e=w1.getAll(),t=[],n=Math.max(0,...e.map(e=>e.subcommands&&e.subcommands.length>0?Math.max(0,...e.subcommands.map(e=>e.usage?.length||0)):e.usage?.length||0));t.push(`Abacus.AI CLI`,``,`Abacus.AI CLI has read access to files in the current directory and can run commands and edit files with your permission.`,``,`Use npx -y @abacus-ai/cli@latest to run latest version of abacusai interactive mode directly from your terminal`,``,`Usage Modes:`,`- REPL: abacusai (interactive session)`,`- Non-interactive: abacusai -p "question"`,``,`Run abacusai --help for all command line options`,``,`For first time users, use /login to authenticate to Abacus.AI CLI`,``,`Common Tasks:`,`- Ask questions about your codebase > How does agent.py work?`,`- Edit files > Update code.ts to...`,`- Fix errors > cargo build`,`- Run commands > /help`,`- Run bash commands > wc`,``,`Interactive Mode Commands:`,``);for(let r of e)if(r.subcommands&&r.subcommands.length>0)for(let e of r.subcommands)t.push(` ${(e.usage||``).padEnd(n+2)} ${e.description||``}`);else t.push(` ${(r.usage||``).padEnd(n+2)} ${r.description||``}`);return t.push(``,`Type any command and press Enter to execute.`),t.join(`
12733
+ `)}function D1(e){let t=e.mcp?new $$(e.mcp):void 0,n=(t,n=`info`,r)=>{e.addNotification?.(t,n,r)},i=[{id:`version`,description:`Show CLI version`,usage:`/version`,execute:()=>{let t=e.getUpdateInfo?.();n(t?`Abacus.AI CLI version ${PA} (${t.latestVersion} available)`:`Abacus.AI CLI version ${PA}`,`info`)}},{id:`exit`,description:`Exit the application`,usage:`/exit`,alias:{[ZK.Prompt]:[`exit`,`quit`]},execute:()=>{e.onExit?.()}},{id:`new`,description:`Start a new conversation`,usage:`/new`,isAvailable:e=>e.segmentsLength>0,execute:()=>{e.onNewChat?.()}},{id:`clear`,description:`Clear the output display while keeping the current conversation`,usage:`/clear`,alias:{[ZK.Prompt]:[`cls`,`clear`]},isAvailable:e=>e.segmentsLength>0,execute:()=>{e.onClearChat?.()}},{id:`stop`,description:`Stop the current streaming response and any running bash tools`,usage:`/stop`,isAvailable:e=>e.agentStatus===Sl.Submitted||e.agentStatus===Sl.Streaming||e.agentStatus===Sl.ExecutingTool||e.agentStatus===Sl.WaitingForToolPermission,execute:async()=>{let t=e.getAgentStatus?.(),r=t===Sl.Submitted||t===Sl.Streaming||t===Sl.ExecutingTool||t===Sl.WaitingForToolPermission;e.onStop?.(),r?n(`Agent stopped successfully`,`info`):n(`No active agent process to stop`,`warning`)}},{id:`help`,description:`Show commands and functionalities`,usage:`/help`,alias:{[ZK.Prompt]:[`help`]},execute:()=>{e.onHelp?e.onHelp():n(E1(),`info`)}},{id:`model`,description:`Switch to a different model`,usage:`/model <model_name>`,requiresArgument:!0,ghostProvider:e=>e?null:`claude-sonnet`,completionProvider:async t=>{if(!e.getModels)return[];let n=await e.getModels();if(!n?.length)return[];let r=n.map(e=>({label:e.label,id:e.value,description:e.model?.provider??``,badge:e.model?.isDefault?`default`:void 0}));return t.trim()?new Qx(r,{selector:e=>`${e.label} ${e.description}`}).find(t).map(e=>e.item):r},execute:async t=>{let r=t.join(` `).trim();if(!r){n(`Please specify a model name`,`error`);return}if(e.getModels){let t=await e.getModels();if(!t||t.length===0){n(`No models are available`,`error`);return}let i=t.find(e=>e.label===r||e.value===r);if(!i){n(`Model "${r}" not found`,`error`);return}e.onModelChange?.(i.value)}else e.onModelChange?.(r)}},{id:`resume`,description:`Resume a previous chat conversation`,usage:`/resume <chat_title>`,requiresArgument:!0,completionProvider:async t=>{if(!e.getChatTitles)return[];let n=await e.getChatTitles();if(!n?.length)return[];let r=n.map(e=>({label:e.title,id:e.id,description:e.messageCount?`${e.messageCount} msgs`:void 0}));return t.trim()?new Qx(r,{selector:e=>`${e.label} ${e.description??``}`}).find(t).map(e=>e.item):r},execute:t=>{let n=t.join(` `).trim();n&&e.onResumeChat?.(n)}},{id:`login`,description:`Log in to Abacus.AI CLI with email or API key`,usage:`/login [email|api_key]`,ghostProvider:e=>e?null:`example@gmail.com`,uiProvider:(t,r)=>{if(e.checkEnvAuth){let{isEnvAuth:t}=e.checkEnvAuth();if(t)return n(`You are logged in via environment variables. Remove ${ke.envPrefix}API_KEY to logout.`,`warning`),r.onDismiss(),null}if(!e.loginAuth)return n(`Login not available`,`error`),r.onDismiss(),null;let i=t.filter(Boolean).join(` `).trim(),a=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i);return i&&!a?(e.onLogin?.(i),r.onDismiss(),null):(0,X.jsx)(C1,{initialEmail:a?i:void 0,auth:e.loginAuth,onDismiss:r.onDismiss})},execute:async t=>{if(e.checkEnvAuth){let{isEnvAuth:t}=e.checkEnvAuth();if(t){n(`You are logged in via environment variables. Remove ${ke.envPrefix}API_KEY to logout.`,`warning`);return}}let r=t.filter(Boolean).join(` `).trim();r&&e.onLogin?.(r)}},{id:`logout`,description:`Log out of Abacus.AI CLI`,usage:`/logout`,execute:async()=>{if(e.checkEnvAuth){let{isEnvAuth:t}=e.checkEnvAuth();if(t){n(`You are logged in via environment variables. Remove ${ke.envPrefix}API_KEY to logout.`,`warning`);return}}try{e.onLogout?.(),n(`Logged out successfully`,`info`)}catch(e){n(`Logout failed: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`status`,description:`Show current user status`,usage:`/status`,execute:async()=>{try{await e.getUserInfo?.()}catch(e){n(`Failed to get status: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`usage`,description:`Show total credits consumed in current conversation`,usage:`/usage`,isAvailable:()=>e.getTotalCredits!==void 0,execute:async()=>{if(!e.getTotalCredits){n(`Usage information not available`,`error`);return}try{let t=await e.getTotalCredits();n(t>0?`Total credits consumed: ${Math.floor(t*100)/100}`:`No credits consumed yet in this conversation`,`info`)}catch(e){n(`Failed to get usage: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`terminal-setup`,description:`Automatically configure terminal for Shift+Enter newlines`,usage:`/terminal-setup`,execute:async()=>{try{n(`Setting up terminal keybindings...`,`info`);let e=await f1();if(e.success){let t=e.message;e.backupPath&&(t+=`\n\nBackup created: ${e.backupPath}`),e.requiresRestart&&(t+=`
12734
12734
 
12735
- Please restart your terminal for changes to take effect.`),n(t,`info`)}else n(e.message,`warning`)}catch(e){n(`Terminal setup failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}},{id:`theme`,description:`Switch between color themes`,usage:`/theme [theme_name]`,completionProvider:e=>{let t=w1.themes.map(e=>({label:e.displayName,id:e.name,badge:e.name===w1.default?`default`:void 0}));return e.trim()?new Qx(t,{selector:e=>e.label}).find(e).map(e=>e.item):t},execute:async t=>{let r=t.join(` `).trim();if(r)try{let t=w1.themes.find(e=>e.displayName.toLowerCase()===r.toLowerCase()||e.name.toLowerCase()===r.toLowerCase());t?e.setTheme?(e.setTheme(t.name),n(`${t.displayName} applied`,`info`)):n(`Theme switching not available`,`error`):n(`Theme "${r}" not found`,`error`)}catch(e){n(`Failed to switch theme: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}},{id:`mcp`,description:`MCP server management`,usage:`/mcp <subcommand>`,subcommands:[{id:`list`,description:`List configured MCP servers`,usage:`/mcp list`,execute:async()=>{if(!t){n(`MCP service not available`,`error`);return}try{n(await t.listServers(),`info`)}catch(e){n(`Failed to list MCP servers: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`add`,description:`Add an MCP server`,usage:`/mcp add <name> <commandOrUrl> [args...]`,requiresArgument:!0,ghostProvider:e=>e?null:`my-server npx -y @mcp/server`,execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length<2){n(`Usage: /mcp add <name> <commandOrUrl> [args...]`,`error`),n(`[TIP] Use /mcp add-json for JSON configuration`,`info`);return}let[r,i,...a]=e;if(i.trim().startsWith(`{`)){n(`Invalid: JSON detected. Use /mcp add-json for JSON configuration`,`error`);return}try{await t.addServer(r,i,a),n(`Added MCP server '${r}'`,`info`)}catch(e){n(`Failed to add MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`add-json`,description:`Add an MCP server with JSON configuration`,usage:`/mcp add-json <name> <json>`,requiresArgument:!0,execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length!==2){n(`Usage: /mcp add-json <name> <json>`,`error`),n(`Example: /mcp add-json github '{"command":"npx","args":["-y","@modelcontextprotocol/server-github"],"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"your_token"}}'`,`info`);return}try{let[r,i]=e;await t.addServerFromJson(r,i),n(`Added MCP server '${r}' from JSON`,`info`)}catch(e){n(`Failed to add MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`remove`,description:`Remove an MCP server`,usage:`/mcp remove <name>`,requiresArgument:!0,completionProvider:async e=>{if(!t)return[];let n=(await t.getServerNames()).map(e=>({label:e.name,badge:e.status??`unknown`}));return e.trim()?new Qx(n,{selector:e=>e.label}).find(e).map(e=>e.item):n},execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length!==1){n(`Usage: /mcp remove <name>`,`error`);return}try{await t.removeServer(e[0]),n(`Removed MCP server '${e[0]}'`,`info`)}catch(e){n(`Failed to remove MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`get`,description:`Get details about an MCP server`,usage:`/mcp get <name>`,requiresArgument:!0,completionProvider:async e=>{if(!t)return[];let n=(await t.getServerNames()).map(e=>({label:e.name,badge:e.status??`unknown`}));return e.trim()?new Qx(n,{selector:e=>e.label}).find(e).map(e=>e.item):n},execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length!==1){n(`Usage: /mcp get <name>`,`error`);return}try{let r=await t.getServer(e[0]);r?n(r,`info`):n(`Server '${e[0]}' not found`,`error`)}catch(e){n(`Failed to get MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}}]},{id:`add-dir`,description:`Add a directory to the agent's allowed access paths for this session`,usage:`/add-dir <path>`,requiresArgument:!0,ghostProvider:e=>e?null:`../my-project`,completionProvider:async e=>{try{let t=E((e.trim()||`.`).replace(/^~/,r())),n,i;try{(await F.stat(t)).isDirectory()?(n=t,i=``):(n=C.dirname(t),i=C.basename(t))}catch{n=C.dirname(t),i=C.basename(t)}let a=(await F.readdir(n,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.name.startsWith(`.`)).map(e=>{let t=C.join(n,e.name);return{label:C.relative(process.cwd(),t)||e.name,description:t}});return i?new Qx(a,{selector:e=>e.label}).find(i).map(e=>e.item):a}catch{return[]}},uiProvider:(t,i)=>{let a=t.join(` `).trim();if(!a)return null;let o=E(a.replace(/^~/,r()));return(0,X.jsx)(h1,{title:`Add ${o} to workspace`,subtitle:`${ke.longName} will be able to read files in this directory and make edits when auto-accept edits is on.`,options:[{label:`Yes, for this session`,action:()=>{if(!e.addAllowedDirectory){n(`Cannot add directory: session not available`,`error`);return}e.addAllowedDirectory(o),n(`Added '${o}' to allowed directories (session only)`,`info`)}},{label:`Yes, and remember this directory`,action:()=>{if(!e.addAllowedDirectory){n(`Cannot add directory: session not available`,`error`);return}e.addAllowedDirectory(o,{persist:!0}),n(`Added '${o}' to allowed directories (persistent)`,`info`)}},{label:`No`,action:()=>{}}],onDismiss:i.onDismiss})},execute:async t=>{let i=t.join(` `).trim();if(!i){n(`Usage: /add-dir <path>`,`error`);return}if(!e.addAllowedDirectory){n(`Cannot add directory: session not available`,`error`);return}try{let t=E(i.replace(/^~/,r()));e.addAllowedDirectory(t),n(`Added '${t}' to allowed directories`,`info`)}catch(e){n(`Failed to add directory: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}}];C1.clear(),(async()=>{let t=i;if(e.checkEnvAuth){let{shouldHide:n}=e.checkEnvAuth();n&&(t=i.filter(e=>e.id!==`login`&&e.id!==`logout`))}t.forEach(e=>C1.register(e))})()}const D1=(0,Z.createContext)(null);function O1(){let e=(0,Z.use)(D1);if(!e)throw Error(`${O1.name} must be used within ${k1.name}`);return e}function k1({children:e}){let[t,n]=(0,Z.useState)(``),[r,i]=(0,Z.useState)(ZK.Prompt),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(`idle`),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),{queuedMessages:f,addToQueue:p,removeFirstFromQueue:m,clearQueue:h}=LZ(),[g,_]=(0,Z.useState)([]),v=(0,Z.useCallback)(e=>{_(t=>[...t,e])},[]),y=(0,Z.useCallback)(()=>{_([])},[]),b=(0,Z.useMemo)(()=>({prompt:t,setPrompt:n,mode:r,setMode:i,bufferRef:a,activity:o,setActivity:s,queuedMessages:f,addToQueue:p,removeFirstFromQueue:m,clearQueue:h,attachments:g,setAttachments:_,addAttachment:v,clearAttachments:y,ghostText:c,setGhostText:l,commandOverlay:u,setCommandOverlay:d}),[t,r,o,f,p,m,h,g,v,y,c,u]);return(0,X.jsx)(D1.Provider,{value:b,children:e})}const A1=/[A-Za-z0-9_.~/\\-]/;function j1(e,t){let[n,r]=t,i=e.split(`
12736
- `)[n]||``,a=-1;for(let e=Math.min(r,i.length)-1;e>=0;e--){let t=i[e];if(t===`@`){a=e;break}if(!A1.test(t))break}if(a===-1)return null;if(a>0){let e=i[a-1];if(e&&!/\s/.test(e))return null}let o=a+1;for(;o<i.length&&A1.test(i[o]);)o++;let s=Math.min(r,o);return{query:i.slice(a+1,s),startRow:n,startCol:a,endRow:n,endCol:o}}function M1(){return[{regex:RegExp(`(?:^|\\s)@(?:'[^']*'|(?:[A-Za-z0-9_.~/-]|\\\\ )+)`,`gm`),color:`cyanBright`},{regex:RegExp(`^/[A-Za-z0-9_./\\-]+`,`gm`),color:`magentaBright`},{regex:RegExp(`\\[Pasted text #\\d+ \\+\\d+ lines\\]`,`g`),color:`yellowBright`}]}const N1=(0,Z.memo)(()=>{let{queuedMessages:e}=O1();return e.length===0?null:(0,X.jsx)(Q,{flexDirection:`column`,children:e.map((e,t)=>(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`❯`}),(0,X.jsx)($,{dimColor:!0,italic:!0,children:e.trim()})]},t))})});N1.displayName=`MessageQueue`;const P1=(0,Z.memo)(({mode:e,prompt:t,handler:n,onExitFilesMode:r,hints:i,availableHeight:a,onLoadingChange:o,commandContext:s})=>n?(0,X.jsx)(X.Fragment,{children:n.render({prompt:t,onExit:r,hints:i,availableHeight:a,onLoadingChange:o,commandContext:s})}):null);P1.displayName=`ModePanel`;function F1(e){return typeof e==`string`?{label:e}:e}const I1=(0,Z.memo)(({items:e,limit:t=10,maxHeight:n,initialIndex:r=0,isActive:i=!0,showIndex:a=!0,showIndicators:o=!1,onHighlight:s,onSubmit:c,onTab:l,onCancel:u,onEscape:d,renderItem:f})=>{let p=e.length,[m,h]=(0,Z.useState)(Math.max(0,Math.min(r,Math.max(0,p-1)))),[g,_]=(0,Z.useState)(0),v=(0,Z.useMemo)(()=>e.map(F1),[e]),y=(0,Z.useMemo)(()=>{if(n!==void 0&&n>0){let e=(o?2:0)+(a?1:0);return Math.max(1,Math.min(t,n-e))}return t},[n,t,o,a]),b=Math.max(1,Math.min(y,p||y)),x=Math.floor(b/2);(0,Z.useEffect)(()=>{m>=p&&(h(p===0?0:p-1),_(0))},[p,m]);let S=(0,Z.useEffectEvent)(e=>{typeof s==`function`&&p>0&&s(v[e].label,e)});(0,Z.useEffect)(()=>{S(m)},[m]);let C=(0,Z.useCallback)(e=>{let t=Math.max(0,p-b);return Math.max(0,Math.min(e,t))},[p,b]),w=(0,Z.useCallback)(()=>{if(p===0||m<=0)return;let e=m-1;h(e),e<g+x&&_(C(e-x)),e>g+b-1&&_(C(e-b+1))},[p,m,g,x,b,C]),T=(0,Z.useCallback)(()=>{if(p===0||m>=p-1)return;let e=m+1;h(e),e>g+x&&_(C(e-x)),e<g&&_(C(e))},[p,m,g,x,C]);sI((e,t)=>{if(i){if(t.upArrow){w();return}if(t.downArrow){T();return}if(t.escape){d?.(),u?.();return}if(t.tab&&!t.ctrl&&!t.meta&&!t.shift){p>0&&l?.(v[m].label,m);return}t.return&&!t.ctrl&&!t.meta&&!t.shift&&(p>0?c?.(v[m].label,m):(d?.(),u?.()))}},{isActive:i});let E=(0,Z.useMemo)(()=>{if(p===0)return[];let e=Math.min(p,g+b);return v.slice(g,e)},[v,p,g,b]),D=n===void 0||n>=3,O=o&&D,k=a&&D;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[O&&p>0&&g>0&&(0,X.jsxs)($,{dimColor:!0,children:[`▲ `,k&&p>1&&`(${m+1}/${p})`]}),p===0?(0,X.jsx)($,{dimColor:!0,children:`No matches`}):E.map((e,t)=>{let n=g+t,r=n===m;return f?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:r?`cyanBright`:void 0,children:r?`> `:` `}),f(e,r)]},`${e.label}-${n}`):(0,X.jsxs)($,{color:r?`cyanBright`:void 0,children:[r?`> `:` `,e.label,e.description?(0,X.jsxs)($,{dimColor:!0,children:[` `,e.description]}):null,e.badge?(0,X.jsxs)($,{color:`yellow`,children:[` [`,e.badge,`]`]}):null]},`${e.label}-${n}`)}),O&&p>0&&g+b<p&&(0,X.jsxs)($,{dimColor:!0,children:[`▼ `,k&&p>1&&`(${m+1}/${p})`]}),!O&&k&&p>1&&(0,X.jsx)($,{dimColor:!0,children:`(${m+1}/${p})`})]})});I1.displayName=`Select`;const L1=(0,Z.memo)(({prompt:e,onAccept:t,onCancel:n,availableHeight:r,onLoadingChange:i,commandContext:a})=>{let{bufferRef:o,setGhostText:s,setCommandOverlay:c}=O1(),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)([]),[p,m]=(0,Z.useState)(!1),h=(0,Z.useCallback)(()=>{o.current?.setText(``)},[o]),g=(0,Z.useDeferredValue)((0,Z.useMemo)(()=>{let t=e.trim();return t.startsWith(`/`)?t.slice(1):``},[e])),_=(0,Z.useMemo)(()=>l?l.exactMatch?{type:`commands`,query:l.command.id}:l.needsSubcommand?{type:`subcommands`,query:l.query}:l.subcommand?.completionProvider||l.command.completionProvider?{type:`completions`,query:l.query}:null:{type:`commands`,query:g},[l,g]);(0,Z.useEffect)(()=>{let t=e.trimStart();if(!t.startsWith(`/`)){u(null);return}u(C1.match(t))},[e]),(0,Z.useEffect)(()=>{if(!l||l.needsSubcommand||l.exactMatch){s(null);return}let e=l.subcommand?.ghostProvider||l.command.ghostProvider;if(!e){s(null);return}return s(e(l.query||``)),()=>s(null)},[l,l?.query,s]),(0,Z.useEffect)(()=>(i?.(p),()=>{i?.(!1)}),[p,i]),(0,Z.useEffect)(()=>{let e=l?.subcommand?.completionProvider||l?.command.completionProvider;if(!e||l?.needsSubcommand){f([]),m(!1);return}m(!0);let t=e(l.query||``);if(t instanceof Promise)t.then(e=>{f(e.map(e=>typeof e==`string`?e:e.label)),m(!1)}).catch(()=>{f([]),m(!1)});else if(Symbol.asyncIterator in Object(t)){let e=t;(async()=>{for await(let t of e)f(t.map(e=>typeof e==`string`?e:e.label));m(!1)})().catch(()=>{f([]),m(!1)})}else Array.isArray(t)&&(f(t.map(e=>typeof e==`string`?e:e.label)),m(!1))},[l,l?.query]);let v=(0,Z.useMemo)(()=>_?_.type===`subcommands`&&l?.command.subcommands?C1.searchSubcommands(l.command,_.query).map(e=>`${e.id} - ${e.description}`):_.type===`completions`?p||d.length===0?[]:d:C1.search(g,a).map(e=>`${e.id} - ${e.description}`):[],[_,l,d,p,g,a]),y=(0,Z.useCallback)((e,t)=>{if(!_)return null;if(_.type===`subcommands`&&l?.command.subcommands){let e=C1.searchSubcommands(l.command,_.query)[t];return e?`/${l.command.id} ${e.id} `:null}if(_.type===`completions`&&l)return p||e.startsWith(`Loading`)||e.startsWith(`No `)?null:`${l.subcommand?`/${l.command.id} ${l.subcommand.id}`:`/${l.command.id}`} ${e}`;let n=C1.search(g,a)[t];return n?`/${n.id} `:null},[_,l,g,p,a]),b=(0,Z.useCallback)((e,t)=>{let n=o.current;if(!n)return;let r=y(e,t);r&&n.setText(r)},[o,y]),x=(0,Z.useCallback)(async(e,n)=>{let r=o.current;if(!r){t();return}if(!_)return;if(_.type===`subcommands`&&l?.command.subcommands){let e=C1.searchSubcommands(l.command,_.query)[n];e&&(e.requiresArgument||e.completionProvider?r.setText(`/${l.command.id} ${e.id} `):(await e.execute([]),r.setText(``),t()));return}if(_.type===`completions`&&l){if(p||e.startsWith(`Loading`)||e.startsWith(`No `))return;let n=l.command;if(n.uiProvider){let t={onDismiss:()=>{c(null),h()},clearBuffer:h},r=n.uiProvider([e],t);if(r){c(r);return}}let i=l.subcommand||l.command;i.execute&&(await i.execute([e]),r.setText(``),t());return}let i=C1.search(g,a)[n];if(i){if(i.subcommands&&i.subcommands.length>0){r.setText(`/${i.id} `);return}if(i.requiresArgument||i.completionProvider){r.setText(`/${i.id} `);return}if(i.uiProvider){let e={onDismiss:()=>{c(null),h()},clearBuffer:h},t=i.uiProvider([],e);if(t){c(t);return}}i.execute&&(await i.execute([]),r.setText(``),t())}},[o,l,g,t,_,p,a,h,c]),S=!!_&&v.length>0;return sI((e,n)=>{if(!n.return||n.ctrl||n.meta||n.shift)return;let r=o.current;if(!r)return;let i=r.text.trimStart();if(!i.startsWith(`/`))return;let a=C1.match(i);if(!a||a.needsSubcommand)return;let s=a.subcommand||a.command;if(!(s.completionProvider&&s.requiresArgument)){if(a.command.uiProvider){let e=a.args?a.args.split(/\s+/).filter(Boolean):[],t={onDismiss:()=>{c(null),h()},clearBuffer:h},n=a.command.uiProvider(e,t);if(n){c(n);return}}(async()=>{await C1.execute(a)&&(r.setText(``),t())})()}},{isActive:!S}),S?(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(I1,{items:v,limit:Math.max(1,Math.min(10,r-2)),maxHeight:r,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:x,onTab:b,onCancel:n})}):null});L1.displayName=`CommandPicker`;function R1(e){let{setCommandOverlay:t}=O1(),n=(0,Z.useCallback)((n,r)=>{if(!n.uiProvider)return!1;let i={onDismiss:()=>{t(null),e()},clearBuffer:e},a=n.uiProvider(r,i);return a?(t(a),!0):!1},[t,e]);return{executeCommand:(0,Z.useCallback)(async t=>{let r=t.trimStart();if(!r.startsWith(`/`))return;let i=C1.match(r);if(!i||i.needsSubcommand)return;let a=i.subcommand||i.command;if(a.completionProvider&&a.requiresArgument){e();return}if(i.command.uiProvider&&i.args!==void 0){let e=i.args.split(/\s+/).filter(Boolean);if(n(i.command,e))return}try{await C1.execute(i)&&e()}catch{}},[e,n]),showCommandUI:n,renderer:(0,Z.useCallback)(({prompt:e,onExit:t,availableHeight:n,onLoadingChange:r,commandContext:i})=>(0,X.jsx)(L1,{prompt:e,onAccept:t,onCancel:t,availableHeight:n,onLoadingChange:r,commandContext:i}),[]),shouldPreventDefault:(0,Z.useCallback)((e,t)=>!!(t.return||t.upArrow||t.downArrow||t.escape||t.tab),[])}}function z1({output:e,command:t,truncate:n=!1,maxLines:r=10}){let i=e.split(`
12737
- `),a=[],o=!1;if(n&&i.length>r){let e=Math.max(1,Math.floor(r/2)),t=i.slice(0,e).map((e,t)=>({line:e,originalIndex:t})),n=i.slice(-e).map((t,n)=>({line:t,originalIndex:i.length-e+n}));a=[...t,...n],o=!0}else a=i.map((e,t)=>({line:e,originalIndex:t}));return(0,X.jsxs)(Q,{flexDirection:`column`,paddingX:1,children:[(0,X.jsx)($,{dimColor:!0,children:`${NQ(process.cwd())}$ ${t}`}),e&&a.map((e,t)=>o&&t===Math.floor(a.length/2)?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)($,{dimColor:!0,children:[`... (`,i.length-r,` lines hidden) ...`]}),(0,X.jsx)($,{children:e.line})]},`trunc-${e.originalIndex}`):(0,X.jsx)($,{children:e.line},`line-${e.originalIndex}`))]})}const B1=[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`];function V1(){let e=t.platform(),n={};for(let[e,t]of Object.entries(process.env))t!==void 0&&(n[e]=t);return e===`win32`?{command:process.env.COMSPEC||`cmd.exe`,args:[],env:n}:{command:process.env.SHELL||`/bin/bash`,args:[],env:{...n,BASH_SILENCE_DEPRECATION_WARNING:`1`,PS1:``}}}var H1=class{shell=null;queue=[];notify=null;isProcessing=!1;destroyed=!1;isWindows;signalHandlers=new Map;constructor(){this.isWindows=t.platform()===`win32`,this.startShell(),this.setupSignalForwarding()}setupSignalForwarding(){for(let e of B1){let t=()=>{if(this.shell&&!this.shell.killed&&this.shell.exitCode===null)try{this.shell.kill(e)}catch{}};this.signalHandlers.set(e,t),process.on(e,t)}}removeSignalHandlers(){for(let[e,t]of this.signalHandlers)process.removeListener(e,t);this.signalHandlers.clear()}startShell(){if(this.shell||this.destroyed)return;let{command:e,args:t,env:n}=V1();this.shell=u(e,t,{stdio:[`pipe`,`pipe`,`pipe`],env:n,cwd:process.cwd(),shell:!1}),this.shell.stdin&&this.shell.stdin.on(`error`,e=>{if(e.code!==`EPIPE`)throw e}),this.shell.stdout&&this.shell.stdout.on(`data`,e=>{let t=e.toString(`utf8`);if(this.queue.push({type:`stdout`,data:t}),this.notify){let e=this.notify;this.notify=null,e()}}),this.shell.stderr&&this.shell.stderr.on(`data`,e=>{let t=e.toString(`utf8`);if(!(t.includes(`no job control in this shell`)||t.includes(`The default interactive shell is now zsh`)||t.includes(`To update your account to use zsh`)||t.includes("please run `chsh -s /bin/zsh`")||t.includes(`For more details, please visit`))&&(this.queue.push({type:`stderr`,data:t}),this.notify)){let e=this.notify;this.notify=null,e()}}),this.shell.on(`exit`,()=>{this.shell=null,this.startShell()})}async executeCommand(e){if(!this.shell||!this.shell.stdin)throw Error(`Shell not initialized`);this.queue.length=0;let t=`__CMD_END_${Date.now()}_${Math.random().toString(36).substring(7)}__`,n;return n=this.isWindows?`${e}\necho ${t}\n`:`${e}\necho "${t}"\n`,this.shell.stdin.write(n),this.isProcessing=!0,{stream:this.createStream(t),exit:this.createExitPromise(t)}}async*createStream(e){for(;;){for(;this.queue.length>0;){let t=this.queue.shift();if(t){if(t.data.includes(e)){let n=t.data.replace(e,``).replace(/\n$/,``);n&&(yield{type:t.type,data:n}),this.isProcessing=!1;return}yield t}}if(!this.isProcessing)return;await new Promise(e=>{this.notify=e})}}async createExitPromise(e){for(;this.isProcessing;)await new Promise(e=>setTimeout(e,100));return 0}killProcessGracefully(e){try{e.kill(`SIGTERM`);let t=setTimeout(()=>{e&&!e.killed&&e.kill(`SIGKILL`)},5e3);t.unref&&t.unref()}catch{}}destroy(){this.destroyed=!0,this.removeSignalHandlers(),this.shell&&=(this.shell.stdin?.on(`error`,e=>{if(e.code!==`EPIPE`)throw e}),this.killProcessGracefully(this.shell),null)}};let U1=null;function W1(){return U1||=new H1,U1}function G1({state:e,setState:t,onCommandComplete:n,commandHistory:r,currentPrompt:i,availableHeight:a}){let{submittedCommand:o,runId:s}=e,c=(0,Z.useMemo)(()=>o?.trim()||``,[o]),l=(0,Z.useRef)(-1),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!c||s===l.current)return;l.current=s,u.current&&u.current.abort();let e=new AbortController;return u.current=e,t(e=>({...e,isRunning:!0,output:``})),K1({command:c,setOutput:e=>{t(t=>({...t,output:e}))},signal:e.signal}).then(r=>{e.signal.aborted||(t(e=>({...e,isRunning:!1})),r!==void 0&&n(r))}).catch(r=>{e.signal.aborted||(t(e=>({...e,isRunning:!1})),n(``))}),()=>{e.abort(),u.current=null}},[c,s,t,n]);let d=i.trim().length>0,f=o?2:3,p=r.slice(-f),m=Math.max(0,r.length-f),h=p.length+(o?1:0),g=Math.max(1,a-h),_=h>0?Math.max(3,Math.floor(g/h)):10,v=d||a<15||h>1;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[p.map((e,t)=>{let n=m+t;return(0,X.jsx)(z1,{output:e.output,command:e.command,truncate:v,maxLines:_},`history-${n}`)}),o&&(0,X.jsx)(z1,{output:e.output,command:c||o,truncate:v,maxLines:_},`submitted-${s}`)]})}async function K1({command:e,setOutput:t,signal:n}){let{stream:r,exit:i}=await W1().executeCommand(e),a=``;try{for await(let e of r){if(n.aborted)return;a+=a$(e.data),n.aborted||t(a)}return n.aborted?void 0:(await i,a)}catch(e){if(n.aborted)return;throw e}}var q1=ve({parseShellHistory:()=>X1,shellHistory:()=>Q1,shellHistoryPath:()=>Z1});function J1(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];r===131&&n+1<e.length?(t.push(e[n+1]^32),n++):t.push(r)}return Buffer.from(t)}function Y1(e){return X1(J1(p.readFileSync(e)).toString(`utf8`))}function X1(e){let t=/^: \d+:0;/;return e.trim().split(`
12738
- `).map(e=>t.test(e)?e.split(`;`).slice(1).join(`;`):e)}function Z1({extraPaths:e=[]}={}){if(process.env.HISTFILE)return process.env.HISTFILE;let t=n.homedir(),r=new Set([C.join(t,`.bash_history`),C.join(t,`.zsh_history`),C.join(t,`.history`)]);for(let t of e)r.add(t);return(()=>{let e,t=0;for(let n of r)p.existsSync(n)&&p.statSync(n).size>t&&(t=p.statSync(n).size,e=n);return e})()}function Q1(e={}){if(process.platform===`win32`){let t=Z1(e);if(t)return Y1(t);let{stdout:n}=o.spawnSync(`doskey`,[`/history`],{encoding:`utf8`});return n.trim().split(`\r
12739
- `)}return Y1(Z1(e))}var $1=_e((()=>{}));const e0=1e3;function t0(){let[e,t]=(0,Z.useState)({submittedCommand:null,runId:0,output:``,isRunning:!1}),[n,r]=(0,Z.useState)([]),[i,a]=(0,Z.useState)([]),[o,s]=(0,Z.useState)(-1),c=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{c.current||(c.current=!0,Promise.resolve().then(()=>($1(),q1)).then(e=>{let t=e.shellHistory??e.default;a((typeof t==`function`?t():[]).slice(-e0))}).catch(()=>{}))},[]);let l=(0,Z.useCallback)(e=>{let n=e.trim();n&&(a(e=>e.length>0&&e[e.length-1]===n?e:[...e,n].slice(-e0)),s(-1),t(e=>({submittedCommand:n,runId:e.runId+1,output:``,isRunning:!0})))},[]),u=(0,Z.useCallback)(e=>{t(t=>(t.submittedCommand&&r(n=>[...n,{command:t.submittedCommand,output:e}].slice(-1e3)),{submittedCommand:null,runId:t.runId,output:``,isRunning:!1}))},[]);return{submitCommand:l,renderer:(0,Z.useCallback)(r=>(0,X.jsx)(G1,{state:e,setState:t,onCommandComplete:u,commandHistory:n,currentPrompt:r.prompt,availableHeight:r.availableHeight}),[e,u,n]),navigateHistory:(0,Z.useCallback)(e=>{if(i.length===0)return null;let t=o;return e===`up`?t=o===-1?i.length-1:Math.max(0,o-1):(t=o===-1?-1:o+1,t>=i.length&&(t=-1)),s(t),t===-1?``:i[t]},[i,o]),getActivity:()=>e.isRunning?`pending`:`idle`}}const n0=(0,Z.memo)(({hints:e,availableHeight:t})=>{let{agentMode:n,isWaitingForYoloConfirm:r}=$K();if(t!==void 0&&t<1)return null;if(e?.exitKey)return(0,X.jsxs)($,{dimColor:!0,children:[`Press `,e.exitKey===`c`?`Ctrl+C`:`Ctrl+D`,` again to exit`]});if(r)return(0,X.jsxs)($,{dimColor:!0,children:[`Press `,(0,X.jsx)($,{color:`redBright`,children:`shift+tab`}),` again to enable YOLO mode (dangerous)`]});switch(n){case xl.Normal:return(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts • shift+tab to cycle modes`});case xl.AcceptEdits:return(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`cyanBright`,children:`⏵⏵`}),` accept edits on (shift+tab to cycle)`]});case xl.PlanMode:return(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`cyanBright`,children:`⏸`}),` plan mode on (shift+tab to cycle)`]});case xl.Yolo:return(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`redBright`,children:`⚠`}),` YOLO mode - all tools auto-accepted (shift+tab to cycle)`]});default:return(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts`})}});n0.displayName=`AgentModeIndicator`;const r0=15e3,i0=/^(node_modules|\.git|dist|build|out|coverage|\.vscode|\.idea|\.DS_Store)$/;let a0=null;function o0(e,t){let n=e.replace(/\\/g,`/`);return{path:n,name:C.posix.basename(n),isDirectory:t}}function s0(e){return e.name.startsWith(`.`)||e.path.split(`/`).some(e=>e.startsWith(`.`)&&e!==`.`)}async function c0(e){try{let t=await l0(`git`,[`rev-parse`,`--show-toplevel`],e);if(!t)return null;let[n,r]=await Promise.all([u0(`git`,[`ls-files`],t),u0(`git`,[`ls-files`,`--others`,`--exclude-standard`],t)]),i=[],a=new Set;for(let e of[...n,...r]){if(!e)continue;let n=C.resolve(t,e);i.push(o0(n,!1));let r=C.posix.dirname(e);for(;r&&r!==`.`;){let e=C.resolve(t,r);if(a.has(e))break;a.add(e),i.push(o0(e,!0)),r=C.posix.dirname(r)}}return i}catch{return null}}function l0(e,t,n){return new Promise((r,i)=>{let a=u(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]}),o=``;a.stdout.on(`data`,e=>o+=e.toString()),a.on(`close`,e=>e===0?r(o.trim()):i()),a.on(`error`,i)})}function u0(e,t,n){return new Promise(r=>{let i=[],a=u(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]});A({input:a.stdout}).on(`line`,e=>i.push(e.trim())),a.on(`close`,()=>r(i)),a.on(`error`,()=>r(i))})}async function d0(e,t){let n=[`--files`,`--no-messages`,`--max-depth`,`100`];t.includeHidden&&n.push(`--hidden`),t.useGitignore||n.push(`--no-ignore`);for(let e of t.globs)n.push(`-g`,e);for(let e of t.ignoreGlobs)n.push(`-g`,e);return new Promise(t=>{let r=[],i=u(ue,n,{cwd:e,stdio:[`ignore`,`pipe`,`pipe`]});A({input:i.stdout}).on(`line`,t=>{let n=AQ(t.trim());n&&r.push(o0(C.resolve(e,n),!1))}),i.on(`close`,()=>t(r)),i.on(`error`,()=>t(r))})}async function f0(e,t){let n=[],r=async(e,i)=>{if(!(i>12||n.length>=r0))try{let a=await v.readdir(e,{withFileTypes:!0}),o=[];for(let r of a){if(!t&&r.name.startsWith(`.`))continue;let i=C.join(e,r.name);r.isDirectory()?i0.test(r.name)||(n.push(o0(i,!0)),o.push(i)):r.isFile()&&n.push(o0(i,!1))}await Promise.all(o.map(e=>r(e,i+1)))}catch{}};return await r(e,0),n}function p0(e){let t=e.includeHidden??!1,n=e.globs??[],r=e.ignoreGlobs??[],i=e.useRipgrep??!0,a=e.useGitignore??!0,o=e.root,s=new Set,c=[],l=e=>{c.length>=r0||s.has(e.path)||(s.add(e.path),!(!t&&s0(e))&&c.push(e))},u=i&&a&&n.length===0&&r.length===0;return{docs:c,ready:(async()=>{if(u){let e=await c0(o);if(e){for(let t of e)l(t);return}}if(i){let e=await d0(o,{includeHidden:t,globs:n,ignoreGlobs:r,useGitignore:a});for(let t of e)l(t);let i=await f0(o,t);for(let e of i)e.isDirectory&&l(e)}else{let e=await f0(o,t);for(let t of e)l(t)}})()}}function m0(e){let t=C.resolve(e.root);if(a0&&a0.key===t&&Date.now()-a0.at<6e4)return a0.index;let n=p0(e);return a0={key:t,index:n,at:Date.now()},n}async function h0(e,t,n){let r=new Map;for(let n=0;n<e.length;n+=64){let i=e.slice(n,n+64);await Promise.all(i.map(async e=>{try{let n=C.isAbsolute(e.path)?e.path:C.resolve(t,e.path),i=await v.stat(n);r.set(e.path,i.mtimeMs)}catch{r.set(e.path,0)}}))}let i=[...e].sort((e,t)=>{let n=(r.get(t.path)??0)-(r.get(e.path)??0);return n===0?e.path.split(`/`).length-t.path.split(`/`).length||e.name.localeCompare(t.name):n}).slice(0,n);return{paths:i.map(e=>e.path),isDirectory:i.map(e=>e.isDirectory)}}async function g0(e,t){let n=t.root,r=t.maxResults??100;if(!(await v.stat(n).catch(()=>null))?.isDirectory())return{paths:[],isDirectory:[]};let i=m0(t);await i.ready;let a=e.trim();if(!a)return h0(i.docs,n,r);let o=new Qx(i.docs,{selector:e=>e.path,limit:r}).find(a);return{paths:o.map(e=>e.item.path),isDirectory:o.map(e=>e.item.isDirectory)}}function _0(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)([]),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>(o.current&&clearTimeout(o.current),a.current&&a.current.abort(),o.current=setTimeout(()=>{if(e===s.current)return;s.current=e;let t=new AbortController;a.current=t,(async()=>{try{let r=await g0(e,{root:process.cwd()});if(t.signal.aborted)return;n(r.paths.map(PQ)),i(r.isDirectory)}catch{}})()},100),()=>{o.current&&clearTimeout(o.current),a.current&&a.current.abort()}),[e]),{results:t,isDirectory:r}}const v0=(0,Z.memo)(({onAccept:e,onCancel:t,availableHeight:n})=>{let{prompt:r,bufferRef:i}=O1(),[a,o]=(0,Z.useState)(``);(0,Z.useEffect)(()=>{let e=i.current;if(!e){o(``);return}let t=j1(e.text,e.cursor)?.query??``;o(e=>e===t?e:t)},[i,r]);let s=(0,Z.useDeferredValue)(a),{results:c,isDirectory:l}=_0(s),u=a!==s,d=c.map((e,t)=>l[t]?`${e}/`:e),f=(0,Z.useCallback)((t,n)=>{let r=i.current;if(!r)return e();let a=j1(r.text,r.cursor);if(a){let e=c[n];r.replaceRange(a.startRow,a.startCol,a.endRow,a.endCol,`@${e}${l[n]?`/`:``} `)}e()},[i,e,c,l]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(I1,{items:d,limit:Math.max(1,Math.min(10,n-2)),maxHeight:n,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:f,onTab:f,onCancel:t}),u&&(0,X.jsx)(Q,{marginTop:0,children:(0,X.jsx)($,{dimColor:!0,children:`Searching...`})})]})});v0.displayName=`FileMentionPicker`;const y0=[[`! for terminal/bash mode`,`/ for commands`,`@ for file paths`],[`esc esc to clear input`,`shift + tab to cycle agent modes`,`${sZ().toLowerCase()} for newline`],[`ctrl + z to undo`,`ctrl + v to paste images`]],b0=(0,Z.memo)(({availableHeight:e})=>e!==void 0&&e<3?null:(0,X.jsx)(Q,{flexDirection:`row`,columnGap:5,rowGap:1,flexWrap:`wrap`,children:(e!==void 0&&e<6?y0.slice(0,1):e!==void 0&&e<9?y0.slice(0,2):y0).map((e,t)=>(0,X.jsx)(Q,{flexDirection:`column`,children:e.map(e=>(0,X.jsx)($,{dimColor:!0,children:e},e))},t))}));b0.displayName=`Help`;function x0(){return{mode:ZK.Prompt,render:({prompt:e,hints:t,availableHeight:n})=>(0,X.jsx)(n0,{hints:t,availableHeight:n})}}function S0(){return{mode:ZK.Help,render:({availableHeight:e})=>(0,X.jsx)(b0,{availableHeight:e})}}function C0(e){return{mode:ZK.Files,render:({prompt:t,availableHeight:n})=>(0,X.jsx)(v0,{onAccept:e,onCancel:e,availableHeight:n}),shouldPreventDefault:(e,t)=>t.upArrow||t.downArrow||t.escape||t.return||t.tab}}function w0(e,t){let n=t0(),r=R1(t);return{handlers:(0,Z.useMemo)(()=>{let t={mode:ZK.Bash,render:n.renderer,onSubmit:n.submitCommand},i={mode:ZK.Command,render:r.renderer,onSubmit:r.executeCommand,shouldPreventDefault:r.shouldPreventDefault};return new Map([[ZK.Prompt,x0()],[ZK.Help,S0()],[ZK.Bash,t],[ZK.Command,i],[ZK.Files,C0(e)]])},[n,r,e]),getActivity:n.getActivity,bashNavigateHistory:n.navigateHistory}}const T0={[ZK.Prompt]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[ZK.Help]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[ZK.Bash]:{color:`greenBright`,placeholder:HQ()?`Try "dir"`:`Try "ls -la"`,prefix:`!`},[ZK.Command]:{color:`magentaBright`,placeholder:`Try "/resume <chat title>"`,prefix:`❯`},[ZK.Files]:{color:`cyanBright`,placeholder:`Try "@help.md"`,prefix:`@`}},E0={"!":{mode:ZK.Bash,preventDefault:!0,atStartOnly:!0},"?":{mode:ZK.Help,preventDefault:!0,atStartOnly:!0},"@":{mode:ZK.Files,preventDefault:!1,atStartOnly:!1}},D0=(0,Z.memo)(({hints:e,composerRef:t})=>{let{prompt:n,setPrompt:r,mode:i,setMode:a,bufferRef:o,activity:s,setActivity:c,queuedMessages:l,addToQueue:u,clearQueue:d,addAttachment:f,clearAttachments:p,ghostText:m,commandOverlay:h}=O1(),{updateInfo:g,autoUpdate:_}=uQ(),v=(0,Z.useCallback)(e=>o.current?.getExpandedText(e)??e,[o]),y=(0,Z.useCallback)(()=>{},[]),b=(0,Z.useRef)({text:``,timer:null}),x=(0,Z.useRef)(null);x.current||(x.current=new Vk(`cli-repl`),x.current.load());let S=x.current,w=(0,Z.useRef)(``),T=(0,Z.useRef)(0),E=(0,Z.useRef)(null);(0,Z.useImperativeHandle)(t,()=>({hasText:()=>n.length>0,hasQueue:()=>l.length>0,saveAndClear:()=>{let e=n.trimStart();e&&(S.append(e),S.resetNavigation()),o.current?.setText(``),y(),p()},clear:()=>{o.current?.setText(``),y(),p()},clearQueue:()=>d()}));let{currentFile:D,selectionStartLine:O,selectionEndLine:k}=VX(),{sendMessage:A,clearSegments:j,clearSegmentsOnly:M,clearTempSegments:N,stop:P,addNotification:I,mcp:L,addAllowedDirectory:R,refreshMcpTools:z,loadConversation:B,agentStatus:V,segmentsLength:H,conversationId:ee,dequeuedOnStop:te,clearDequeuedOnStop:ne}=LZ(),{apiClient:re,authManager:ie}=bZ(),{data:ae=[],refetch:oe}=_Q(re),{cycleAgentMode:se,resetToNormal:ce,isWaitingForYoloConfirm:le}=$K(),{setTheme:U}=RL(),ue=hQ(),{handlers:de,getActivity:fe,bashNavigateHistory:pe}=w0(()=>a(ZK.Prompt),(0,Z.useCallback)(()=>{o.current?.setText(``)},[o])),me=de.get(i)||null,[he,ge]=(0,Z.useState)([]),[_e,W]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)(null),[be,G]=(0,Z.useState)(!0),xe=(0,Z.useRef)(null),[Se,Ce]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(!1),Ee=(0,Z.useMemo)(()=>({agentStatus:V,segmentsLength:H,isLoggedIn:ve??!1}),[V,H,ve]),De=(0,Z.useCallback)(async()=>{try{let e=await re.getConversationsList(ke.agentType,process.cwd());e?.result&&ge(e.result.slice(0,25))}catch{}},[re]);(0,Z.useEffect)(()=>{De()},[De]),(0,Z.useEffect)(()=>{re.getUserInfo().then(e=>ye(!!e?.result?.email)).catch(()=>{ye(ie.isAuthenticated())})},[re,ie]),(0,Z.useEffect)(()=>{te&&(o.current?.setText(te),ne())},[te,ne,o]);let Oe=_e||ae[0]?.llmName||``,Ae=(0,Z.useRef)(Oe);(0,Z.useEffect)(()=>(Ae.current!==Oe&&(Ae.current=Oe,G(!0)),xe.current&&clearTimeout(xe.current),Oe&&(xe.current=setTimeout(()=>G(!1),5e3)),()=>{xe.current&&clearTimeout(xe.current)}),[Oe]),(0,Z.useEffect)(()=>{if(!Se){Te(!1);return}let e=setInterval(()=>Te(e=>!e),500);return()=>clearInterval(e)},[Se]),(0,Z.useEffect)(()=>{E1({onExit:()=>{$j(0)},onNewChat:()=>{j(),d(),o.current?.setText(``)},onClearChat:()=>{M(),o.current?.setText(``)},onStop:()=>{P()},onModelChange:e=>{let t=ae.find(t=>t.llmName===e);t?(W(t.llmName),o.current?.setText(``)):I(`Model not found`,`error`)},onResumeChat:async e=>{let t=he.find(t=>(t.name||t.deploymentConversationId||`Untitled`).toLowerCase().includes(e.toLowerCase()));if(t?.deploymentConversationId)try{d(),o.current?.setText(``),await B(t.deploymentConversationId),I(`Resumed conversation: ${t.name||t.deploymentConversationId}`,`info`)}catch(e){I(`Failed to load conversation: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}else I(`Conversation "${e}" not found`,`error`)},onLogin:async e=>{try{if(ie.isEnvAuth()){I(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}if(!e){I(`Usage: /login <email> or /login <api_key>`,`error`);return}if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){let t=e,n=await $k(),r=await re.authenticateDeviceForCodeLlm(t,n);if(!r?.success||!r?.result){I(r?.error??`Failed to start device code login`,`error`);return}let{verificationUri:i,userCode:a,pollingInterval:o}=r.result;I(`Open the URL and enter the code to authenticate.\n\nURL: ${i}\nCode: ${a}\n\nPolling for completion...`,`info`),(async()=>{let e=(o||5)*1e3,t=Date.now()+600*1e3;for(;Date.now()<t;){await UQ(e);try{let e=await re.pollDeviceCode(a);if(e?.success&&e.result?.deviceCode){let t=e.result.deviceCode,n=e.result.chatWebUrl;if(await ie.loginWithDeviceCode(t),n){let e=n.replace(/^https?:\/\//,``);re.setChatWebDomain(e)}I(`Authentication successful!`,`info`),ye(!0),await De(),await oe();return}}catch{}}I(`Authentication timed out. Please try again.`,`error`)})()}else{await ie.loginWithApiKey(e);try{(await re.getUserInfo())?.result?.email?(I(`API key login successful!`,`info`),ye(!0),await De(),await oe()):(await ie.logout(),I(`Invalid API key — authentication failed`,`error`))}catch(e){await ie.logout(),I(`API key authentication failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}o.current?.setText(``)}catch(e){I(`Login failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}},onLogout:async()=>{if(ie.isEnvAuth()){I(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}await ie.logout(),ye(!1)},getUserInfo:async()=>{try{let e=await re.getUserInfo();if(e?.success&&e.result){let{name:t,email:n,organization:r}=e.result,i=r?.name||`No team`,a=ie.getAuthKind(),o=a.type===`env_api_key`?`API key (env)`:a.type===`env_device_code`?`Device code (env)`:a.type===`api_key`?`API key`:a.type===`device_code`?`Device code`:a.type===`oauth_token`?`OAuth token`:`Unknown`;I(`User Status:\n\nName: ${t||`N/A`}\nEmail: ${n||`N/A`}\nTeam: ${i}\nAuth Method: ${o}`,`info`)}else I(`Failed to get user info`,`error`)}catch{I(`Failed to get user info`,`error`)}},getModels:async()=>ae.filter(e=>e.codeAgentSupported).map(e=>({label:e.name||e.llmName,value:e.llmName,model:e})),getChatTitles:async()=>he.map(e=>{let t=e.name||e.deploymentConversationId||`Untitled`;return{id:e.deploymentConversationId||``,title:t.length>50?t.substring(0,47)+`...`:t,messageCount:e.hasHistory,date:e.createdAt}}),addNotification:I,mcp:L,addAllowedDirectory:R,refreshMcpTools:z,getAgentStatus:()=>V,getTotalCredits:ee?()=>OQ(re,ee):void 0,setTheme:U,loginAuth:{initiateDeviceCode:async e=>{let t=await $k(),n=await re.authenticateDeviceForCodeLlm(e,t);return!n?.success||!n?.result?{success:!1,error:n?.error??`Failed to start device code login`}:{success:!0,verificationUri:n.result.verificationUri,userCode:n.result.userCode,pollingInterval:n.result.pollingInterval}},pollDeviceCode:async e=>{let t=await re.pollDeviceCode(e);return t?.success&&t.result?.deviceCode?{success:!0,deviceCode:t.result.deviceCode,chatWebUrl:t.result.chatWebUrl}:{success:!1}},completeDeviceCodeLogin:async(e,t)=>{if(await ie.loginWithDeviceCode(e),t){let e=t.replace(/^https?:\/\//,``);re.setChatWebDomain(e)}ye(!0),await De(),await oe()},loginWithApiKey:async e=>{if(await ie.loginWithApiKey(e),!(await re.getUserInfo())?.result?.email)throw await ie.logout(),Error(`Invalid API key — authentication failed`);ye(!0),await De(),await oe()},isEnvAuth:()=>ie.isEnvAuth()},checkEnvAuth:()=>({isEnvAuth:ie.isEnvAuth(),shouldHide:ie.isEnvAuth()}),getUpdateInfo:()=>g})},[ae,j,M,d,o,re,oe,P,I,L,R,z,B,he,De,V,ee,U,ie,g]);let je=(0,Z.useCallback)(async e=>{try{let t=await F.stat(e),n=await F.readFile(e),r=C.extname(e).toLowerCase(),i=r===`.jpg`||r===`.jpeg`?`image/jpeg`:`image/png`;f({doc_id:`tui-`+Math.random().toString(36).slice(2,11)+`-`+Date.now().toString(36),filename:e,filePath:C.resolve(e),fileName:C.basename(e),content:n.toString(`base64`),mimeType:i,mime_type:i,size:t.size,metadata:{uploadedAt:new Date().toISOString(),source:`tui-clipboard`,isImage:!0,encoding:`base64`}})}catch{}},[f]),K=(0,Z.useCallback)(async()=>{if(await TQ()){let e=await EQ(process.cwd());if(e){let t=IQ(LQ(e));o.current?.insert(`@${t} `),await je(e);return}}let e=await DQ();if(!e)return;let t=BQ(e.trim());if(t){o.current?.insert(t);return}o.current?.insert(e,{isPaste:!0})},[o,je]),Me=(0,Z.useCallback)(e=>{let t=e.target.cursor[0]===0&&e.target.cursor[1]===0;if(!e.key.paste){let t=process.platform===`darwin`&&e.key.super&&e.input===`v`,n=process.platform!==`darwin`&&e.key.ctrl&&e.input===`v`||process.platform===`linux`&&e.key.ctrl&&e.key.shift&&e.input===`V`;if(t||n){K(),e.preventDefault();return}}if(e.key.paste){let t=e.input.replace(/[\r\n]+$/,``),n=t.trim();if(bQ(n)){let t=xQ(n);if(t){let n=IQ(LQ(t));o.current?.insert(`@${n} `),je(t),e.preventDefault();return}}let r=BQ(t.trim());if(r){o.current?.insert(r),e.preventDefault();return}(async()=>{if(await TQ()){let e=await EQ(process.cwd());if(e){let t=IQ(LQ(e));o.current?.insert(`@${t} `),await je(e);return}}o.current?.insert(t,{isPaste:!0})})(),e.preventDefault();return}if(e.input.length>3&&!e.key.ctrl&&!e.key.meta&&!e.key.paste){b.current.text+=e.input,b.current.timer&&clearTimeout(b.current.timer),b.current.timer=setTimeout(()=>{let e=b.current.text;b.current={text:``,timer:null};let t=BQ(e.trim());if(t){o.current?.insert(t);return}o.current?.insert(e,{isPaste:!0})},50),e.preventDefault();return}if(i===ZK.Prompt&&e.key.upArrow&&e.target.visualCursor[0]===0&&l.length>0&&n.trim()===``){let t=l[0];o.current?.setText(t),d(),e.preventDefault();return}if(me?.shouldPreventDefault&&me.shouldPreventDefault(e.input||``,e.key)){e.preventDefault();return}if((i===ZK.Prompt||i===ZK.Help||i===ZK.Files)&&(e.key.upArrow||e.key.downArrow)){let t=e.target,r=t.visualCursor[0]===0,i=t.visualCursor[0]>=t.allVisualLines.length-1;if(e.key.upArrow&&r){if(S.getEntries().length>0){S.isNavigating()||(w.current=n);let t=S.navigateUp();if(t){o.current?.setText(t.message),e.preventDefault();return}}}else if(e.key.downArrow&&i){if(!S.isNavigating()){e.preventDefault();return}let t=S.navigateDown();t?o.current?.setText(t.message):o.current?.setText(w.current),e.preventDefault();return}}if(i===ZK.Bash&&pe){let t=e.target,n=e.key.upArrow&&t.visualCursor[0]===0,r=e.key.downArrow&&t.visualCursor[0]>=t.allVisualLines.length-1;if(n||r){let t=pe(e.key.upArrow?`up`:`down`);if(t!==null){o.current?.setText(t),e.preventDefault();return}}}if(t&&e.key.backspace){if(le){ce(),e.preventDefault();return}i!==ZK.Prompt&&(a(ZK.Prompt),S.resetNavigation(),w.current=``,e.preventDefault());return}if(i===ZK.Prompt&&e.key.shift&&e.key.tab){se(),e.preventDefault();return}let r=E0[e.input];if(r&&(!r.atStartOnly||t)){i!==r.mode&&a(r.mode),r.preventDefault&&r.mode!==ZK.Command&&e.preventDefault();return}},[i,a,me,pe,o,K,je,l,n,d,le,ce,se,S]),Ne=(0,Z.useCallback)((e,t)=>{let n=T.current;T.current=e.length,r(e);let o=e.trim(),s=o.startsWith(`/`),c=o.slice(1).split(/\s/)[0]||``,l=s&&(c===``||!/[/\\.]/.test(c)&&/^[a-zA-Z]/.test(c)),u=V===Sl.Submitted||V===Sl.Streaming||V===Sl.ExecutingTool||V===Sl.WaitingForToolPermission;e.length>0&&!l&&!u&&N();let d=j1(e,t.cursor);if(o.length===0&&n>0&&(i===ZK.Command||i===ZK.Bash||i===ZK.Help)){a(ZK.Prompt);return}if(d){i!==ZK.Files&&a(ZK.Files);return}if(i===ZK.Files){d||a(ZK.Prompt);return}i===ZK.Help&&o.length>0&&a(ZK.Prompt),E.current&&=(clearTimeout(E.current),null),!l&&i===ZK.Command&&o.length>0?a(ZK.Prompt):l&&i!==ZK.Command&&(E.current=setTimeout(()=>{E.current=null,a(ZK.Command)},80))},[i,r,a,N,V]),Pe=(0,Z.useCallback)(async e=>{let t=e.trim();if(!t.startsWith(`/`)){let e=C1.match(t,i);if(e&&await C1.execute(e)){o.current?.setText(``),p();return}}if(me?.onSubmit){me.onSubmit(e),i===ZK.Bash?(o.current?.setText(``),c(fe())):i===ZK.Command&&a(ZK.Prompt),p();return}switch(i){case ZK.Prompt:if(ve===!1){I(`Not logged in. Use /login email@example.com to login.`,`warning`);return}if(V===Sl.Submitted||V===Sl.Streaming||V===Sl.ExecutingTool||V===Sl.WaitingForToolPermission){let t=v(e.trimStart());u(t),S.append(t),S.resetNavigation(),w.current=``,y(),o.current?.setText(``);return}let t=_e||ae[0]?.llmName||void 0,n=v(e);S.append(n),S.resetNavigation(),w.current=``,A({message:n,selectedModel:t}),y(),p();return;default:}},[i,me,A,fe,c,_e,a,o,V,u,I,p,ve,v,y,S,ae]),{color:Fe,placeholder:Ie,prefix:Le}=T0[i],Re=H>0?``:Ie,ze=(0,Z.useMemo)(()=>M1(),[]),Be=(i===ZK.Bash?fe():s)===`pending`||V===Sl.WaitingForToolPermission,Ve=NQ(process.cwd()),He=(0,Z.useMemo)(()=>(0,X.jsx)(Q,{flexGrow:1,borderStyle:{bottom:`─`},borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderDimColor:!0}),[]);return(0,X.jsxs)(X.Fragment,{children:[h,(0,X.jsx)(Z.Activity,{mode:h?`hidden`:`visible`,children:(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(N1,{}),(0,X.jsxs)(Q,{flexDirection:`row`,alignItems:`flex-end`,children:[He,ve===!1&&(0,X.jsx)($,{dimColor:!0,children:` Not logged in`}),ve===!1&&be&&Oe&&(0,X.jsx)($,{dimColor:!0,children:` •`}),be&&Oe&&(0,X.jsxs)($,{children:[` `,ae.find(e=>e.llmName===Oe)?.name||Oe]}),(ve===!1||be&&Oe)&&(0,X.jsx)($,{dimColor:!0,children:` •`}),(0,X.jsxs)($,{color:`yellowBright`,children:[` `,Ve]})]}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:Fe,dimColor:we,children:Le}),(0,X.jsx)(J$,{ref:o,onChange:Ne,onKeyDown:Me,onSubmit:Pe,placeholder:Re,grammar:ze,disabled:Be,ghostText:m??void 0})]}),(0,X.jsx)(Q,{flexDirection:`row`,children:He}),(0,X.jsxs)(Q,{justifyContent:`space-between`,children:[(0,X.jsx)(P1,{mode:i,prompt:n,handler:me,onExitFilesMode:()=>a(ZK.Prompt),hints:e,availableHeight:ue,onLoadingChange:Ce,commandContext:Ee}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[D&&O!==void 0&&k!==void 0?(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsxs)($,{color:`cyan`,children:[k-O+1,` lines selected`]}),` `,`in `,(0,X.jsx)($,{color:`cyan`,children:C.basename(D)})]}):D&&(0,X.jsxs)($,{dimColor:!0,children:[`in `,(0,X.jsx)($,{color:`cyan`,children:C.basename(D)})]}),e?.escClear&&(0,X.jsx)($,{wrap:`truncate-middle`,dimColor:!0,children:`Press ESC again to clear input`}),e?.escClear&&g&&(0,X.jsx)($,{dimColor:!0,children:`·`}),g&&(0,X.jsx)($,{wrap:`truncate-middle`,dimColor:!0,children:g.isEphemeral?`Update available (${g.latestVersion})`:_?`Update available (${g.latestVersion}) · Restart to auto-update`:`Update available (${g.latestVersion}) · Run: ${Mj()}`})]})]})]})})]})});D0.displayName=`ComposerInner`;const O0=(0,Z.memo)(({hints:e,composerRef:t})=>(0,X.jsx)(k1,{children:(0,X.jsx)(Z.Suspense,{fallback:(0,X.jsx)($,{dimColor:!0,children:`Loading models...`}),children:(0,X.jsx)(D0,{hints:e,composerRef:t})})}));O0.displayName=`Composer`;var k0=class extends Z.Component{state={hasError:!1,error:null,errorInfo:null};static getDerivedStateFromError(e){return{hasError:!0,error:e,errorInfo:null}}componentDidCatch(e,t){this.setState({error:e,errorInfo:t}),this.props.onError&&this.props.onError(e,t)}render(){let{hasError:e,error:t,errorInfo:n}=this.state,{fallback:r,children:i}=this.props;return e?r?typeof r==`function`?r(t,n):r:(0,X.jsxs)(Q,{flexDirection:`column`,padding:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong.`}),t&&(0,X.jsxs)(Q,{marginTop:1,flexDirection:`column`,children:[(0,X.jsx)($,{color:`yellow`,children:t.toString()}),n?.componentStack&&(0,X.jsx)($,{color:`gray`,children:n.componentStack})]})]}):i}};const A0=(0,Z.memo)(({duration:e,credits:t,conversationId:n})=>{let{colors:r}=RL();return(0,X.jsxs)(Q,{flexDirection:`column`,paddingY:1,children:[(0,X.jsx)($,{color:r.primary,children:`
12735
+ Please restart your terminal for changes to take effect.`),n(t,`info`)}else n(e.message,`warning`)}catch(e){n(`Terminal setup failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}},{id:`theme`,description:`Switch between color themes`,usage:`/theme [theme_name]`,completionProvider:e=>{let t=T1.themes.map(e=>({label:e.displayName,id:e.name,badge:e.name===T1.default?`default`:void 0}));return e.trim()?new Qx(t,{selector:e=>e.label}).find(e).map(e=>e.item):t},execute:async t=>{let r=t.join(` `).trim();if(r)try{let t=T1.themes.find(e=>e.displayName.toLowerCase()===r.toLowerCase()||e.name.toLowerCase()===r.toLowerCase());t?e.setTheme?(e.setTheme(t.name),n(`${t.displayName} applied`,`info`)):n(`Theme switching not available`,`error`):n(`Theme "${r}" not found`,`error`)}catch(e){n(`Failed to switch theme: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}},{id:`mcp`,description:`MCP server management`,usage:`/mcp <subcommand>`,subcommands:[{id:`list`,description:`List configured MCP servers`,usage:`/mcp list`,execute:async()=>{if(!t){n(`MCP service not available`,`error`);return}try{n(await t.listServers(),`info`)}catch(e){n(`Failed to list MCP servers: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`add`,description:`Add an MCP server`,usage:`/mcp add <name> <commandOrUrl> [args...]`,requiresArgument:!0,ghostProvider:e=>e?null:`my-server npx -y @mcp/server`,execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length<2){n(`Usage: /mcp add <name> <commandOrUrl> [args...]`,`error`),n(`[TIP] Use /mcp add-json for JSON configuration`,`info`);return}let[r,i,...a]=e;if(i.trim().startsWith(`{`)){n(`Invalid: JSON detected. Use /mcp add-json for JSON configuration`,`error`);return}try{await t.addServer(r,i,a),n(`Added MCP server '${r}'`,`info`)}catch(e){n(`Failed to add MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`add-json`,description:`Add an MCP server with JSON configuration`,usage:`/mcp add-json <name> <json>`,requiresArgument:!0,execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length!==2){n(`Usage: /mcp add-json <name> <json>`,`error`),n(`Example: /mcp add-json github '{"command":"npx","args":["-y","@modelcontextprotocol/server-github"],"env":{"GITHUB_PERSONAL_ACCESS_TOKEN":"your_token"}}'`,`info`);return}try{let[r,i]=e;await t.addServerFromJson(r,i),n(`Added MCP server '${r}' from JSON`,`info`)}catch(e){n(`Failed to add MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`remove`,description:`Remove an MCP server`,usage:`/mcp remove <name>`,requiresArgument:!0,completionProvider:async e=>{if(!t)return[];let n=(await t.getServerNames()).map(e=>({label:e.name,badge:e.status??`unknown`}));return e.trim()?new Qx(n,{selector:e=>e.label}).find(e).map(e=>e.item):n},execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length!==1){n(`Usage: /mcp remove <name>`,`error`);return}try{await t.removeServer(e[0]),n(`Removed MCP server '${e[0]}'`,`info`)}catch(e){n(`Failed to remove MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}},{id:`get`,description:`Get details about an MCP server`,usage:`/mcp get <name>`,requiresArgument:!0,completionProvider:async e=>{if(!t)return[];let n=(await t.getServerNames()).map(e=>({label:e.name,badge:e.status??`unknown`}));return e.trim()?new Qx(n,{selector:e=>e.label}).find(e).map(e=>e.item):n},execute:async e=>{if(!t){n(`MCP service not available`,`error`);return}if(e.length!==1){n(`Usage: /mcp get <name>`,`error`);return}try{let r=await t.getServer(e[0]);r?n(r,`info`):n(`Server '${e[0]}' not found`,`error`)}catch(e){n(`Failed to get MCP server: ${e instanceof Error?e.message:`Unknown error occurred`}`,`error`)}}}]},{id:`add-dir`,description:`Add a directory to the agent's allowed access paths for this session`,usage:`/add-dir <path>`,requiresArgument:!0,ghostProvider:e=>e?null:`../my-project`,completionProvider:async e=>{try{let t=E((e.trim()||`.`).replace(/^~/,r())),n,i;try{(await F.stat(t)).isDirectory()?(n=t,i=``):(n=C.dirname(t),i=C.basename(t))}catch{n=C.dirname(t),i=C.basename(t)}let a=(await F.readdir(n,{withFileTypes:!0})).filter(e=>e.isDirectory()&&!e.name.startsWith(`.`)).map(e=>{let t=C.join(n,e.name);return{label:C.relative(process.cwd(),t)||e.name,description:t}});return i?new Qx(a,{selector:e=>e.label}).find(i).map(e=>e.item):a}catch{return[]}},uiProvider:(t,i)=>{let a=t.join(` `).trim();if(!a)return null;let o=E(a.replace(/^~/,r()));return(0,X.jsx)(g1,{title:`Add ${o} to workspace`,subtitle:`${ke.longName} will be able to read files in this directory and make edits when auto-accept edits is on.`,options:[{label:`Yes, for this session`,action:()=>{if(!e.addAllowedDirectory){n(`Cannot add directory: session not available`,`error`);return}e.addAllowedDirectory(o),n(`Added '${o}' to allowed directories (session only)`,`info`)}},{label:`Yes, and remember this directory`,action:()=>{if(!e.addAllowedDirectory){n(`Cannot add directory: session not available`,`error`);return}e.addAllowedDirectory(o,{persist:!0}),n(`Added '${o}' to allowed directories (persistent)`,`info`)}},{label:`No`,action:()=>{}}],onDismiss:i.onDismiss})},execute:async t=>{let i=t.join(` `).trim();if(!i){n(`Usage: /add-dir <path>`,`error`);return}if(!e.addAllowedDirectory){n(`Cannot add directory: session not available`,`error`);return}try{let t=E(i.replace(/^~/,r()));e.addAllowedDirectory(t),n(`Added '${t}' to allowed directories`,`info`)}catch(e){n(`Failed to add directory: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}}];w1.clear(),(async()=>{let t=i;if(e.checkEnvAuth){let{shouldHide:n}=e.checkEnvAuth();n&&(t=i.filter(e=>e.id!==`login`&&e.id!==`logout`))}t.forEach(e=>w1.register(e))})()}const O1=(0,Z.createContext)(null);function k1(){let e=(0,Z.use)(O1);if(!e)throw Error(`${k1.name} must be used within ${A1.name}`);return e}function A1({children:e}){let[t,n]=(0,Z.useState)(``),[r,i]=(0,Z.useState)(ZK.Prompt),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(`idle`),[c,l]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),{queuedMessages:f,addToQueue:p,removeFirstFromQueue:m,clearQueue:h}=RZ(),[g,_]=(0,Z.useState)([]),v=(0,Z.useCallback)(e=>{_(t=>[...t,e])},[]),y=(0,Z.useCallback)(()=>{_([])},[]),b=(0,Z.useMemo)(()=>({prompt:t,setPrompt:n,mode:r,setMode:i,bufferRef:a,activity:o,setActivity:s,queuedMessages:f,addToQueue:p,removeFirstFromQueue:m,clearQueue:h,attachments:g,setAttachments:_,addAttachment:v,clearAttachments:y,ghostText:c,setGhostText:l,commandOverlay:u,setCommandOverlay:d}),[t,r,o,f,p,m,h,g,v,y,c,u]);return(0,X.jsx)(O1.Provider,{value:b,children:e})}const j1=/[A-Za-z0-9_.~/\\-]/;function M1(e,t){let[n,r]=t,i=e.split(`
12736
+ `)[n]||``,a=-1;for(let e=Math.min(r,i.length)-1;e>=0;e--){let t=i[e];if(t===`@`){a=e;break}if(!j1.test(t))break}if(a===-1)return null;if(a>0){let e=i[a-1];if(e&&!/\s/.test(e))return null}let o=a+1;for(;o<i.length&&j1.test(i[o]);)o++;let s=Math.min(r,o);return{query:i.slice(a+1,s),startRow:n,startCol:a,endRow:n,endCol:o}}function N1(){return[{regex:RegExp(`(?:^|\\s)@(?:'[^']*'|(?:[A-Za-z0-9_.~/-]|\\\\ )+)`,`gm`),color:`cyanBright`},{regex:RegExp(`^/[A-Za-z0-9_./\\-]+`,`gm`),color:`magentaBright`},{regex:RegExp(`\\[Pasted text #\\d+ \\+\\d+ lines\\]`,`g`),color:`yellowBright`}]}const P1=(0,Z.memo)(()=>{let{queuedMessages:e}=k1();return e.length===0?null:(0,X.jsx)(Q,{flexDirection:`column`,children:e.map((e,t)=>(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`❯`}),(0,X.jsx)($,{dimColor:!0,italic:!0,children:e.trim()})]},t))})});P1.displayName=`MessageQueue`;const F1=(0,Z.memo)(({mode:e,prompt:t,handler:n,onExitFilesMode:r,hints:i,availableHeight:a,onLoadingChange:o,commandContext:s})=>n?(0,X.jsx)(X.Fragment,{children:n.render({prompt:t,onExit:r,hints:i,availableHeight:a,onLoadingChange:o,commandContext:s})}):null);F1.displayName=`ModePanel`;function I1(e){return typeof e==`string`?{label:e}:e}const L1=(0,Z.memo)(({items:e,limit:t=10,maxHeight:n,initialIndex:r=0,isActive:i=!0,showIndex:a=!0,showIndicators:o=!1,onHighlight:s,onSubmit:c,onTab:l,onCancel:u,onEscape:d,renderItem:f})=>{let p=e.length,[m,h]=(0,Z.useState)(Math.max(0,Math.min(r,Math.max(0,p-1)))),[g,_]=(0,Z.useState)(0),v=(0,Z.useMemo)(()=>e.map(I1),[e]),y=(0,Z.useMemo)(()=>{if(n!==void 0&&n>0){let e=(o?2:0)+(a?1:0);return Math.max(1,Math.min(t,n-e))}return t},[n,t,o,a]),b=Math.max(1,Math.min(y,p||y)),x=Math.floor(b/2);(0,Z.useEffect)(()=>{m>=p&&(h(p===0?0:p-1),_(0))},[p,m]);let S=(0,Z.useEffectEvent)(e=>{typeof s==`function`&&p>0&&s(v[e].label,e)});(0,Z.useEffect)(()=>{S(m)},[m]);let C=(0,Z.useCallback)(e=>{let t=Math.max(0,p-b);return Math.max(0,Math.min(e,t))},[p,b]),w=(0,Z.useCallback)(()=>{if(p===0||m<=0)return;let e=m-1;h(e),e<g+x&&_(C(e-x)),e>g+b-1&&_(C(e-b+1))},[p,m,g,x,b,C]),T=(0,Z.useCallback)(()=>{if(p===0||m>=p-1)return;let e=m+1;h(e),e>g+x&&_(C(e-x)),e<g&&_(C(e))},[p,m,g,x,C]);sI((e,t)=>{if(i){if(t.upArrow){w();return}if(t.downArrow){T();return}if(t.escape){d?.(),u?.();return}if(t.tab&&!t.ctrl&&!t.meta&&!t.shift){p>0&&l?.(v[m].label,m);return}t.return&&!t.ctrl&&!t.meta&&!t.shift&&(p>0?c?.(v[m].label,m):(d?.(),u?.()))}},{isActive:i});let E=(0,Z.useMemo)(()=>{if(p===0)return[];let e=Math.min(p,g+b);return v.slice(g,e)},[v,p,g,b]),D=n===void 0||n>=3,O=o&&D,k=a&&D;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[O&&p>0&&g>0&&(0,X.jsxs)($,{dimColor:!0,children:[`▲ `,k&&p>1&&`(${m+1}/${p})`]}),p===0?(0,X.jsx)($,{dimColor:!0,children:`No matches`}):E.map((e,t)=>{let n=g+t,r=n===m;return f?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:r?`cyanBright`:void 0,children:r?`> `:` `}),f(e,r)]},`${e.label}-${n}`):(0,X.jsxs)($,{color:r?`cyanBright`:void 0,children:[r?`> `:` `,e.label,e.description?(0,X.jsxs)($,{dimColor:!0,children:[` `,e.description]}):null,e.badge?(0,X.jsxs)($,{color:`yellow`,children:[` [`,e.badge,`]`]}):null]},`${e.label}-${n}`)}),O&&p>0&&g+b<p&&(0,X.jsxs)($,{dimColor:!0,children:[`▼ `,k&&p>1&&`(${m+1}/${p})`]}),!O&&k&&p>1&&(0,X.jsx)($,{dimColor:!0,children:`(${m+1}/${p})`})]})});L1.displayName=`Select`;const R1=(0,Z.memo)(({prompt:e,onAccept:t,onCancel:n,availableHeight:r,onLoadingChange:i,commandContext:a})=>{let{bufferRef:o,setGhostText:s,setCommandOverlay:c}=k1(),[l,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)([]),[p,m]=(0,Z.useState)(!1),h=(0,Z.useCallback)(()=>{o.current?.setText(``)},[o]),g=(0,Z.useDeferredValue)((0,Z.useMemo)(()=>{let t=e.trim();return t.startsWith(`/`)?t.slice(1):``},[e])),_=(0,Z.useMemo)(()=>l?l.exactMatch?{type:`commands`,query:l.command.id}:l.needsSubcommand?{type:`subcommands`,query:l.query}:l.subcommand?.completionProvider||l.command.completionProvider?{type:`completions`,query:l.query}:null:{type:`commands`,query:g},[l,g]);(0,Z.useEffect)(()=>{let t=e.trimStart();if(!t.startsWith(`/`)){u(null);return}u(w1.match(t))},[e]),(0,Z.useEffect)(()=>{if(!l||l.needsSubcommand||l.exactMatch){s(null);return}let e=l.subcommand?.ghostProvider||l.command.ghostProvider;if(!e){s(null);return}return s(e(l.query||``)),()=>s(null)},[l,l?.query,s]),(0,Z.useEffect)(()=>(i?.(p),()=>{i?.(!1)}),[p,i]),(0,Z.useEffect)(()=>{let e=l?.subcommand?.completionProvider||l?.command.completionProvider;if(!e||l?.needsSubcommand){f([]),m(!1);return}m(!0);let t=e(l.query||``);if(t instanceof Promise)t.then(e=>{f(e.map(e=>typeof e==`string`?e:e.label)),m(!1)}).catch(()=>{f([]),m(!1)});else if(Symbol.asyncIterator in Object(t)){let e=t;(async()=>{for await(let t of e)f(t.map(e=>typeof e==`string`?e:e.label));m(!1)})().catch(()=>{f([]),m(!1)})}else Array.isArray(t)&&(f(t.map(e=>typeof e==`string`?e:e.label)),m(!1))},[l,l?.query]);let v=(0,Z.useMemo)(()=>_?_.type===`subcommands`&&l?.command.subcommands?w1.searchSubcommands(l.command,_.query).map(e=>`${e.id} - ${e.description}`):_.type===`completions`?p||d.length===0?[]:d:w1.search(g,a).map(e=>`${e.id} - ${e.description}`):[],[_,l,d,p,g,a]),y=(0,Z.useCallback)((e,t)=>{if(!_)return null;if(_.type===`subcommands`&&l?.command.subcommands){let e=w1.searchSubcommands(l.command,_.query)[t];return e?`/${l.command.id} ${e.id} `:null}if(_.type===`completions`&&l)return p||e.startsWith(`Loading`)||e.startsWith(`No `)?null:`${l.subcommand?`/${l.command.id} ${l.subcommand.id}`:`/${l.command.id}`} ${e}`;let n=w1.search(g,a)[t];return n?`/${n.id} `:null},[_,l,g,p,a]),b=(0,Z.useCallback)((e,t)=>{let n=o.current;if(!n)return;let r=y(e,t);r&&n.setText(r)},[o,y]),x=(0,Z.useCallback)(async(e,n)=>{let r=o.current;if(!r){t();return}if(!_)return;if(_.type===`subcommands`&&l?.command.subcommands){let e=w1.searchSubcommands(l.command,_.query)[n];e&&(e.requiresArgument||e.completionProvider?r.setText(`/${l.command.id} ${e.id} `):(await e.execute([]),r.setText(``),t()));return}if(_.type===`completions`&&l){if(p||e.startsWith(`Loading`)||e.startsWith(`No `))return;let n=l.command;if(n.uiProvider){let t={onDismiss:()=>{c(null),h()},clearBuffer:h},r=n.uiProvider([e],t);if(r){c(r);return}}let i=l.subcommand||l.command;i.execute&&(await i.execute([e]),r.setText(``),t());return}let i=w1.search(g,a)[n];if(i){if(i.subcommands&&i.subcommands.length>0){r.setText(`/${i.id} `);return}if(i.requiresArgument||i.completionProvider){r.setText(`/${i.id} `);return}if(i.uiProvider){let e={onDismiss:()=>{c(null),h()},clearBuffer:h},t=i.uiProvider([],e);if(t){c(t);return}}i.execute&&(await i.execute([]),r.setText(``),t())}},[o,l,g,t,_,p,a,h,c]),S=!!_&&v.length>0;return sI((e,n)=>{if(!n.return||n.ctrl||n.meta||n.shift)return;let r=o.current;if(!r)return;let i=r.text.trimStart();if(!i.startsWith(`/`))return;let a=w1.match(i);if(!a||a.needsSubcommand)return;let s=a.subcommand||a.command;if(!(s.completionProvider&&s.requiresArgument)){if(a.command.uiProvider){let e=a.args?a.args.split(/\s+/).filter(Boolean):[],t={onDismiss:()=>{c(null),h()},clearBuffer:h},n=a.command.uiProvider(e,t);if(n){c(n);return}}(async()=>{await w1.execute(a)&&(r.setText(``),t())})()}},{isActive:!S}),S?(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)(L1,{items:v,limit:Math.max(1,Math.min(10,r-2)),maxHeight:r,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:x,onTab:b,onCancel:n})}):null});R1.displayName=`CommandPicker`;function z1(e){let{setCommandOverlay:t}=k1(),n=(0,Z.useCallback)((n,r)=>{if(!n.uiProvider)return!1;let i={onDismiss:()=>{t(null),e()},clearBuffer:e},a=n.uiProvider(r,i);return a?(t(a),!0):!1},[t,e]);return{executeCommand:(0,Z.useCallback)(async t=>{let r=t.trimStart();if(!r.startsWith(`/`))return;let i=w1.match(r);if(!i||i.needsSubcommand)return;let a=i.subcommand||i.command;if(a.completionProvider&&a.requiresArgument){e();return}if(i.command.uiProvider&&i.args!==void 0){let e=i.args.split(/\s+/).filter(Boolean);if(n(i.command,e))return}try{await w1.execute(i)&&e()}catch{}},[e,n]),showCommandUI:n,renderer:(0,Z.useCallback)(({prompt:e,onExit:t,availableHeight:n,onLoadingChange:r,commandContext:i})=>(0,X.jsx)(R1,{prompt:e,onAccept:t,onCancel:t,availableHeight:n,onLoadingChange:r,commandContext:i}),[]),shouldPreventDefault:(0,Z.useCallback)((e,t)=>!!(t.return||t.upArrow||t.downArrow||t.escape||t.tab),[])}}function B1({output:e,command:t,truncate:n=!1,maxLines:r=10}){let i=e.split(`
12737
+ `),a=[],o=!1;if(n&&i.length>r){let e=Math.max(1,Math.floor(r/2)),t=i.slice(0,e).map((e,t)=>({line:e,originalIndex:t})),n=i.slice(-e).map((t,n)=>({line:t,originalIndex:i.length-e+n}));a=[...t,...n],o=!0}else a=i.map((e,t)=>({line:e,originalIndex:t}));return(0,X.jsxs)(Q,{flexDirection:`column`,paddingX:1,children:[(0,X.jsx)($,{dimColor:!0,children:`${PQ(process.cwd())}$ ${t}`}),e&&a.map((e,t)=>o&&t===Math.floor(a.length/2)?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)($,{dimColor:!0,children:[`... (`,i.length-r,` lines hidden) ...`]}),(0,X.jsx)($,{children:e.line})]},`trunc-${e.originalIndex}`):(0,X.jsx)($,{children:e.line},`line-${e.originalIndex}`))]})}const V1=[`SIGUSR1`,`SIGUSR2`,`SIGTERM`,`SIGINT`,`SIGHUP`];function H1(){let e=t.platform(),n={};for(let[e,t]of Object.entries(process.env))t!==void 0&&(n[e]=t);return e===`win32`?{command:process.env.COMSPEC||`cmd.exe`,args:[],env:n}:{command:process.env.SHELL||`/bin/bash`,args:[],env:{...n,BASH_SILENCE_DEPRECATION_WARNING:`1`,PS1:``}}}var U1=class{shell=null;queue=[];notify=null;isProcessing=!1;destroyed=!1;isWindows;signalHandlers=new Map;constructor(){this.isWindows=t.platform()===`win32`,this.startShell(),this.setupSignalForwarding()}setupSignalForwarding(){for(let e of V1){let t=()=>{if(this.shell&&!this.shell.killed&&this.shell.exitCode===null)try{this.shell.kill(e)}catch{}};this.signalHandlers.set(e,t),process.on(e,t)}}removeSignalHandlers(){for(let[e,t]of this.signalHandlers)process.removeListener(e,t);this.signalHandlers.clear()}startShell(){if(this.shell||this.destroyed)return;let{command:e,args:t,env:n}=H1();this.shell=u(e,t,{stdio:[`pipe`,`pipe`,`pipe`],env:n,cwd:process.cwd(),shell:!1}),this.shell.stdin&&this.shell.stdin.on(`error`,e=>{if(e.code!==`EPIPE`)throw e}),this.shell.stdout&&this.shell.stdout.on(`data`,e=>{let t=e.toString(`utf8`);if(this.queue.push({type:`stdout`,data:t}),this.notify){let e=this.notify;this.notify=null,e()}}),this.shell.stderr&&this.shell.stderr.on(`data`,e=>{let t=e.toString(`utf8`);if(!(t.includes(`no job control in this shell`)||t.includes(`The default interactive shell is now zsh`)||t.includes(`To update your account to use zsh`)||t.includes("please run `chsh -s /bin/zsh`")||t.includes(`For more details, please visit`))&&(this.queue.push({type:`stderr`,data:t}),this.notify)){let e=this.notify;this.notify=null,e()}}),this.shell.on(`exit`,()=>{this.shell=null,this.startShell()})}async executeCommand(e){if(!this.shell||!this.shell.stdin)throw Error(`Shell not initialized`);this.queue.length=0;let t=`__CMD_END_${Date.now()}_${Math.random().toString(36).substring(7)}__`,n;return n=this.isWindows?`${e}\necho ${t}\n`:`${e}\necho "${t}"\n`,this.shell.stdin.write(n),this.isProcessing=!0,{stream:this.createStream(t),exit:this.createExitPromise(t)}}async*createStream(e){for(;;){for(;this.queue.length>0;){let t=this.queue.shift();if(t){if(t.data.includes(e)){let n=t.data.replace(e,``).replace(/\n$/,``);n&&(yield{type:t.type,data:n}),this.isProcessing=!1;return}yield t}}if(!this.isProcessing)return;await new Promise(e=>{this.notify=e})}}async createExitPromise(e){for(;this.isProcessing;)await new Promise(e=>setTimeout(e,100));return 0}killProcessGracefully(e){try{e.kill(`SIGTERM`);let t=setTimeout(()=>{e&&!e.killed&&e.kill(`SIGKILL`)},5e3);t.unref&&t.unref()}catch{}}destroy(){this.destroyed=!0,this.removeSignalHandlers(),this.shell&&=(this.shell.stdin?.on(`error`,e=>{if(e.code!==`EPIPE`)throw e}),this.killProcessGracefully(this.shell),null)}};let W1=null;function G1(){return W1||=new U1,W1}function K1({state:e,setState:t,onCommandComplete:n,commandHistory:r,currentPrompt:i,availableHeight:a}){let{submittedCommand:o,runId:s}=e,c=(0,Z.useMemo)(()=>o?.trim()||``,[o]),l=(0,Z.useRef)(-1),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{if(!c||s===l.current)return;l.current=s,u.current&&u.current.abort();let e=new AbortController;return u.current=e,t(e=>({...e,isRunning:!0,output:``})),q1({command:c,setOutput:e=>{t(t=>({...t,output:e}))},signal:e.signal}).then(r=>{e.signal.aborted||(t(e=>({...e,isRunning:!1})),r!==void 0&&n(r))}).catch(r=>{e.signal.aborted||(t(e=>({...e,isRunning:!1})),n(``))}),()=>{e.abort(),u.current=null}},[c,s,t,n]);let d=i.trim().length>0,f=o?2:3,p=r.slice(-f),m=Math.max(0,r.length-f),h=p.length+(o?1:0),g=Math.max(1,a-h),_=h>0?Math.max(3,Math.floor(g/h)):10,v=d||a<15||h>1;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[p.map((e,t)=>{let n=m+t;return(0,X.jsx)(B1,{output:e.output,command:e.command,truncate:v,maxLines:_},`history-${n}`)}),o&&(0,X.jsx)(B1,{output:e.output,command:c||o,truncate:v,maxLines:_},`submitted-${s}`)]})}async function q1({command:e,setOutput:t,signal:n}){let{stream:r,exit:i}=await G1().executeCommand(e),a=``;try{for await(let e of r){if(n.aborted)return;a+=o$(e.data),n.aborted||t(a)}return n.aborted?void 0:(await i,a)}catch(e){if(n.aborted)return;throw e}}var J1=ve({parseShellHistory:()=>Z1,shellHistory:()=>$1,shellHistoryPath:()=>Q1});function Y1(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];r===131&&n+1<e.length?(t.push(e[n+1]^32),n++):t.push(r)}return Buffer.from(t)}function X1(e){return Z1(Y1(p.readFileSync(e)).toString(`utf8`))}function Z1(e){let t=/^: \d+:0;/;return e.trim().split(`
12738
+ `).map(e=>t.test(e)?e.split(`;`).slice(1).join(`;`):e)}function Q1({extraPaths:e=[]}={}){if(process.env.HISTFILE)return process.env.HISTFILE;let t=n.homedir(),r=new Set([C.join(t,`.bash_history`),C.join(t,`.zsh_history`),C.join(t,`.history`)]);for(let t of e)r.add(t);return(()=>{let e,t=0;for(let n of r)p.existsSync(n)&&p.statSync(n).size>t&&(t=p.statSync(n).size,e=n);return e})()}function $1(e={}){if(process.platform===`win32`){let t=Q1(e);if(t)return X1(t);let{stdout:n}=o.spawnSync(`doskey`,[`/history`],{encoding:`utf8`});return n.trim().split(`\r
12739
+ `)}return X1(Q1(e))}var e0=_e((()=>{}));const t0=1e3;function n0(){let[e,t]=(0,Z.useState)({submittedCommand:null,runId:0,output:``,isRunning:!1}),[n,r]=(0,Z.useState)([]),[i,a]=(0,Z.useState)([]),[o,s]=(0,Z.useState)(-1),c=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{c.current||(c.current=!0,Promise.resolve().then(()=>(e0(),J1)).then(e=>{let t=e.shellHistory??e.default;a((typeof t==`function`?t():[]).slice(-t0))}).catch(()=>{}))},[]);let l=(0,Z.useCallback)(e=>{let n=e.trim();n&&(a(e=>e.length>0&&e[e.length-1]===n?e:[...e,n].slice(-t0)),s(-1),t(e=>({submittedCommand:n,runId:e.runId+1,output:``,isRunning:!0})))},[]),u=(0,Z.useCallback)(e=>{t(t=>(t.submittedCommand&&r(n=>[...n,{command:t.submittedCommand,output:e}].slice(-1e3)),{submittedCommand:null,runId:t.runId,output:``,isRunning:!1}))},[]);return{submitCommand:l,renderer:(0,Z.useCallback)(r=>(0,X.jsx)(K1,{state:e,setState:t,onCommandComplete:u,commandHistory:n,currentPrompt:r.prompt,availableHeight:r.availableHeight}),[e,u,n]),navigateHistory:(0,Z.useCallback)(e=>{if(i.length===0)return null;let t=o;return e===`up`?t=o===-1?i.length-1:Math.max(0,o-1):(t=o===-1?-1:o+1,t>=i.length&&(t=-1)),s(t),t===-1?``:i[t]},[i,o]),getActivity:()=>e.isRunning?`pending`:`idle`}}const r0=(0,Z.memo)(({hints:e,availableHeight:t})=>{let{agentMode:n,isWaitingForYoloConfirm:r}=$K();if(t!==void 0&&t<1)return null;if(e?.exitKey)return(0,X.jsxs)($,{dimColor:!0,children:[`Press `,e.exitKey===`c`?`Ctrl+C`:`Ctrl+D`,` again to exit`]});if(r)return(0,X.jsxs)($,{dimColor:!0,children:[`Press `,(0,X.jsx)($,{color:`redBright`,children:`shift+tab`}),` again to enable YOLO mode (dangerous)`]});switch(n){case xl.Normal:return(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts • shift+tab to cycle modes`});case xl.AcceptEdits:return(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`cyanBright`,children:`⏵⏵`}),` accept edits on (shift+tab to cycle)`]});case xl.PlanMode:return(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`cyanBright`,children:`⏸`}),` plan mode on (shift+tab to cycle)`]});case xl.Yolo:return(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsx)($,{color:`redBright`,children:`⚠`}),` YOLO mode - all tools auto-accepted (shift+tab to cycle)`]});default:return(0,X.jsx)($,{dimColor:!0,children:`? for shortcuts`})}});r0.displayName=`AgentModeIndicator`;const i0=15e3,a0=/^(node_modules|\.git|dist|build|out|coverage|\.vscode|\.idea|\.DS_Store)$/;let o0=null;function s0(e,t){let n=e.replace(/\\/g,`/`);return{path:n,name:C.posix.basename(n),isDirectory:t}}function c0(e){return e.name.startsWith(`.`)||e.path.split(`/`).some(e=>e.startsWith(`.`)&&e!==`.`)}async function l0(e){try{let t=await u0(`git`,[`rev-parse`,`--show-toplevel`],e);if(!t)return null;let[n,r]=await Promise.all([d0(`git`,[`ls-files`],t),d0(`git`,[`ls-files`,`--others`,`--exclude-standard`],t)]),i=[],a=new Set;for(let e of[...n,...r]){if(!e)continue;let n=C.resolve(t,e);i.push(s0(n,!1));let r=C.posix.dirname(e);for(;r&&r!==`.`;){let e=C.resolve(t,r);if(a.has(e))break;a.add(e),i.push(s0(e,!0)),r=C.posix.dirname(r)}}return i}catch{return null}}function u0(e,t,n){return new Promise((r,i)=>{let a=u(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]}),o=``;a.stdout.on(`data`,e=>o+=e.toString()),a.on(`close`,e=>e===0?r(o.trim()):i()),a.on(`error`,i)})}function d0(e,t,n){return new Promise(r=>{let i=[],a=u(e,t,{cwd:n,stdio:[`ignore`,`pipe`,`pipe`]});A({input:a.stdout}).on(`line`,e=>i.push(e.trim())),a.on(`close`,()=>r(i)),a.on(`error`,()=>r(i))})}async function f0(e,t){let n=[`--files`,`--no-messages`,`--max-depth`,`100`];t.includeHidden&&n.push(`--hidden`),t.useGitignore||n.push(`--no-ignore`);for(let e of t.globs)n.push(`-g`,e);for(let e of t.ignoreGlobs)n.push(`-g`,e);return new Promise(t=>{let r=[],i=u(ue,n,{cwd:e,stdio:[`ignore`,`pipe`,`pipe`]});A({input:i.stdout}).on(`line`,t=>{let n=jQ(t.trim());n&&r.push(s0(C.resolve(e,n),!1))}),i.on(`close`,()=>t(r)),i.on(`error`,()=>t(r))})}async function p0(e,t){let n=[],r=async(e,i)=>{if(!(i>12||n.length>=i0))try{let a=await v.readdir(e,{withFileTypes:!0}),o=[];for(let r of a){if(!t&&r.name.startsWith(`.`))continue;let i=C.join(e,r.name);r.isDirectory()?a0.test(r.name)||(n.push(s0(i,!0)),o.push(i)):r.isFile()&&n.push(s0(i,!1))}await Promise.all(o.map(e=>r(e,i+1)))}catch{}};return await r(e,0),n}function m0(e){let t=e.includeHidden??!1,n=e.globs??[],r=e.ignoreGlobs??[],i=e.useRipgrep??!0,a=e.useGitignore??!0,o=e.root,s=new Set,c=[],l=e=>{c.length>=i0||s.has(e.path)||(s.add(e.path),!(!t&&c0(e))&&c.push(e))},u=i&&a&&n.length===0&&r.length===0;return{docs:c,ready:(async()=>{if(u){let e=await l0(o);if(e){for(let t of e)l(t);return}}if(i){let e=await f0(o,{includeHidden:t,globs:n,ignoreGlobs:r,useGitignore:a});for(let t of e)l(t);let i=await p0(o,t);for(let e of i)e.isDirectory&&l(e)}else{let e=await p0(o,t);for(let t of e)l(t)}})()}}function h0(e){let t=C.resolve(e.root);if(o0&&o0.key===t&&Date.now()-o0.at<6e4)return o0.index;let n=m0(e);return o0={key:t,index:n,at:Date.now()},n}async function g0(e,t,n){let r=new Map;for(let n=0;n<e.length;n+=64){let i=e.slice(n,n+64);await Promise.all(i.map(async e=>{try{let n=C.isAbsolute(e.path)?e.path:C.resolve(t,e.path),i=await v.stat(n);r.set(e.path,i.mtimeMs)}catch{r.set(e.path,0)}}))}let i=[...e].sort((e,t)=>{let n=(r.get(t.path)??0)-(r.get(e.path)??0);return n===0?e.path.split(`/`).length-t.path.split(`/`).length||e.name.localeCompare(t.name):n}).slice(0,n);return{paths:i.map(e=>e.path),isDirectory:i.map(e=>e.isDirectory)}}async function _0(e,t){let n=t.root,r=t.maxResults??100;if(!(await v.stat(n).catch(()=>null))?.isDirectory())return{paths:[],isDirectory:[]};let i=h0(t);await i.ready;let a=e.trim();if(!a)return g0(i.docs,n,r);let o=new Qx(i.docs,{selector:e=>e.path,limit:r}).find(a);return{paths:o.map(e=>e.item.path),isDirectory:o.map(e=>e.item.isDirectory)}}function v0(e){let[t,n]=(0,Z.useState)([]),[r,i]=(0,Z.useState)([]),a=(0,Z.useRef)(null),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>(o.current&&clearTimeout(o.current),a.current&&a.current.abort(),o.current=setTimeout(()=>{if(e===s.current)return;s.current=e;let t=new AbortController;a.current=t,(async()=>{try{let r=await _0(e,{root:process.cwd()});if(t.signal.aborted)return;n(r.paths.map(FQ)),i(r.isDirectory)}catch{}})()},100),()=>{o.current&&clearTimeout(o.current),a.current&&a.current.abort()}),[e]),{results:t,isDirectory:r}}const y0=(0,Z.memo)(({onAccept:e,onCancel:t,availableHeight:n})=>{let{prompt:r,bufferRef:i}=k1(),[a,o]=(0,Z.useState)(``);(0,Z.useEffect)(()=>{let e=i.current;if(!e){o(``);return}let t=M1(e.text,e.cursor)?.query??``;o(e=>e===t?e:t)},[i,r]);let s=(0,Z.useDeferredValue)(a),{results:c,isDirectory:l}=v0(s),u=a!==s,d=c.map((e,t)=>l[t]?`${e}/`:e),f=(0,Z.useCallback)((t,n)=>{let r=i.current;if(!r)return e();let a=M1(r.text,r.cursor);if(a){let e=c[n];r.replaceRange(a.startRow,a.startCol,a.endRow,a.endCol,`@${e}${l[n]?`/`:``} `)}e()},[i,e,c,l]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(L1,{items:d,limit:Math.max(1,Math.min(10,n-2)),maxHeight:n,isActive:!0,showIndex:!0,showIndicators:!0,onSubmit:f,onTab:f,onCancel:t}),u&&(0,X.jsx)(Q,{marginTop:0,children:(0,X.jsx)($,{dimColor:!0,children:`Searching...`})})]})});y0.displayName=`FileMentionPicker`;const b0=[[`! for terminal/bash mode`,`/ for commands`,`@ for file paths`],[`esc esc to clear input`,`shift + tab to cycle agent modes`,`${cZ().toLowerCase()} for newline`],[`ctrl + z to undo`,`ctrl + v to paste images`]],x0=(0,Z.memo)(({availableHeight:e})=>e!==void 0&&e<3?null:(0,X.jsx)(Q,{flexDirection:`row`,columnGap:5,rowGap:1,flexWrap:`wrap`,children:(e!==void 0&&e<6?b0.slice(0,1):e!==void 0&&e<9?b0.slice(0,2):b0).map((e,t)=>(0,X.jsx)(Q,{flexDirection:`column`,children:e.map(e=>(0,X.jsx)($,{dimColor:!0,children:e},e))},t))}));x0.displayName=`Help`;function S0(){return{mode:ZK.Prompt,render:({prompt:e,hints:t,availableHeight:n})=>(0,X.jsx)(r0,{hints:t,availableHeight:n})}}function C0(){return{mode:ZK.Help,render:({availableHeight:e})=>(0,X.jsx)(x0,{availableHeight:e})}}function w0(e){return{mode:ZK.Files,render:({prompt:t,availableHeight:n})=>(0,X.jsx)(y0,{onAccept:e,onCancel:e,availableHeight:n}),shouldPreventDefault:(e,t)=>t.upArrow||t.downArrow||t.escape||t.return||t.tab}}function T0(e,t){let n=n0(),r=z1(t);return{handlers:(0,Z.useMemo)(()=>{let t={mode:ZK.Bash,render:n.renderer,onSubmit:n.submitCommand},i={mode:ZK.Command,render:r.renderer,onSubmit:r.executeCommand,shouldPreventDefault:r.shouldPreventDefault};return new Map([[ZK.Prompt,S0()],[ZK.Help,C0()],[ZK.Bash,t],[ZK.Command,i],[ZK.Files,w0(e)]])},[n,r,e]),getActivity:n.getActivity,bashNavigateHistory:n.navigateHistory}}const E0={[ZK.Prompt]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[ZK.Help]:{color:void 0,placeholder:`Try "Build a ecommerce website..."`,prefix:`❯`},[ZK.Bash]:{color:`greenBright`,placeholder:UQ()?`Try "dir"`:`Try "ls -la"`,prefix:`!`},[ZK.Command]:{color:`magentaBright`,placeholder:`Try "/resume <chat title>"`,prefix:`❯`},[ZK.Files]:{color:`cyanBright`,placeholder:`Try "@help.md"`,prefix:`@`}},D0={"!":{mode:ZK.Bash,preventDefault:!0,atStartOnly:!0},"?":{mode:ZK.Help,preventDefault:!0,atStartOnly:!0},"@":{mode:ZK.Files,preventDefault:!1,atStartOnly:!1}},O0=(0,Z.memo)(({hints:e,composerRef:t})=>{let{prompt:n,setPrompt:r,mode:i,setMode:a,bufferRef:o,activity:s,setActivity:c,queuedMessages:l,addToQueue:u,clearQueue:d,addAttachment:f,clearAttachments:p,ghostText:m,commandOverlay:h}=k1(),{updateInfo:g,autoUpdate:_}=dQ(),v=(0,Z.useCallback)(e=>o.current?.getExpandedText(e)??e,[o]),y=(0,Z.useCallback)(()=>{},[]),b=(0,Z.useRef)({text:``,timer:null}),x=(0,Z.useRef)(null);x.current||(x.current=new Vk(`cli-repl`),x.current.load());let S=x.current,w=(0,Z.useRef)(``),T=(0,Z.useRef)(0),E=(0,Z.useRef)(null);(0,Z.useImperativeHandle)(t,()=>({hasText:()=>n.length>0,hasQueue:()=>l.length>0,saveAndClear:()=>{let e=n.trimStart();e&&(S.append(e),S.resetNavigation()),o.current?.setText(``),y(),p()},clear:()=>{o.current?.setText(``),y(),p()},clearQueue:()=>d()}));let{currentFile:D,selectionStartLine:O,selectionEndLine:k}=HX(),{sendMessage:A,clearSegments:j,clearSegmentsOnly:M,clearTempSegments:N,stop:P,addNotification:I,mcp:L,addAllowedDirectory:R,refreshMcpTools:z,loadConversation:B,agentStatus:V,segmentsLength:H,conversationId:ee,dequeuedOnStop:te,clearDequeuedOnStop:ne}=RZ(),{apiClient:re,authManager:ie}=xZ(),{data:ae=[],refetch:oe}=vQ(re),{cycleAgentMode:se,resetToNormal:ce,isWaitingForYoloConfirm:le}=$K(),{setTheme:U}=RL(),ue=gQ(),{handlers:de,getActivity:fe,bashNavigateHistory:pe}=T0(()=>a(ZK.Prompt),(0,Z.useCallback)(()=>{o.current?.setText(``)},[o])),me=de.get(i)||null,[he,ge]=(0,Z.useState)([]),[_e,W]=(0,Z.useState)(``),[ve,ye]=(0,Z.useState)(null),[be,G]=(0,Z.useState)(!0),xe=(0,Z.useRef)(null),[Se,Ce]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(!1),Ee=(0,Z.useMemo)(()=>({agentStatus:V,segmentsLength:H,isLoggedIn:ve??!1}),[V,H,ve]),De=(0,Z.useCallback)(async()=>{try{let e=await re.getConversationsList(ke.agentType,process.cwd());e?.result&&ge(e.result.slice(0,25))}catch{}},[re]);(0,Z.useEffect)(()=>{De()},[De]),(0,Z.useEffect)(()=>{re.getUserInfo().then(e=>ye(!!e?.result?.email)).catch(()=>{ye(ie.isAuthenticated())})},[re,ie]),(0,Z.useEffect)(()=>{te&&(o.current?.setText(te),ne())},[te,ne,o]);let Oe=_e||ae[0]?.llmName||``,Ae=(0,Z.useRef)(Oe);(0,Z.useEffect)(()=>(Ae.current!==Oe&&(Ae.current=Oe,G(!0)),xe.current&&clearTimeout(xe.current),Oe&&(xe.current=setTimeout(()=>G(!1),5e3)),()=>{xe.current&&clearTimeout(xe.current)}),[Oe]),(0,Z.useEffect)(()=>{if(!Se){Te(!1);return}let e=setInterval(()=>Te(e=>!e),500);return()=>clearInterval(e)},[Se]),(0,Z.useEffect)(()=>{D1({onExit:()=>{$j(0)},onNewChat:()=>{j(),d(),o.current?.setText(``)},onClearChat:()=>{M(),o.current?.setText(``)},onStop:()=>{P()},onModelChange:e=>{let t=ae.find(t=>t.llmName===e);t?(W(t.llmName),o.current?.setText(``)):I(`Model not found`,`error`)},onResumeChat:async e=>{let t=he.find(t=>(t.name||t.deploymentConversationId||`Untitled`).toLowerCase().includes(e.toLowerCase()));if(t?.deploymentConversationId)try{d(),o.current?.setText(``),await B(t.deploymentConversationId),I(`Resumed conversation: ${t.name||t.deploymentConversationId}`,`info`)}catch(e){I(`Failed to load conversation: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}else I(`Conversation "${e}" not found`,`error`)},onLogin:async e=>{try{if(ie.isEnvAuth()){I(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}if(!e){I(`Usage: /login <email> or /login <api_key>`,`error`);return}if(/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e)){let t=e,n=await $k(),r=await re.authenticateDeviceForCodeLlm(t,n);if(!r?.success||!r?.result){I(r?.error??`Failed to start device code login`,`error`);return}let{verificationUri:i,userCode:a,pollingInterval:o}=r.result;I(`Open the URL and enter the code to authenticate.\n\nURL: ${i}\nCode: ${a}\n\nPolling for completion...`,`info`),(async()=>{let e=(o||5)*1e3,t=Date.now()+600*1e3;for(;Date.now()<t;){await WQ(e);try{let e=await re.pollDeviceCode(a);if(e?.success&&e.result?.deviceCode){let t=e.result.deviceCode,n=e.result.chatWebUrl;if(await ie.loginWithDeviceCode(t),n){let e=n.replace(/^https?:\/\//,``);re.setChatWebDomain(e)}I(`Authentication successful!`,`info`),ye(!0),await De(),await oe();return}}catch{}}I(`Authentication timed out. Please try again.`,`error`)})()}else{await ie.loginWithApiKey(e);try{(await re.getUserInfo())?.result?.email?(I(`API key login successful!`,`info`),ye(!0),await De(),await oe()):(await ie.logout(),I(`Invalid API key — authentication failed`,`error`))}catch(e){await ie.logout(),I(`API key authentication failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}}o.current?.setText(``)}catch(e){I(`Login failed: ${e instanceof Error?e.message:`Unknown error`}`,`error`)}},onLogout:async()=>{if(ie.isEnvAuth()){I(`You are authenticated via an environment variable. Unset it to use /login or /logout.`,`error`);return}await ie.logout(),ye(!1)},getUserInfo:async()=>{try{let e=await re.getUserInfo();if(e?.success&&e.result){let{name:t,email:n,organization:r}=e.result,i=r?.name||`No team`,a=ie.getAuthKind(),o=a.type===`env_api_key`?`API key (env)`:a.type===`env_device_code`?`Device code (env)`:a.type===`api_key`?`API key`:a.type===`device_code`?`Device code`:a.type===`oauth_token`?`OAuth token`:`Unknown`;I(`User Status:\n\nName: ${t||`N/A`}\nEmail: ${n||`N/A`}\nTeam: ${i}\nAuth Method: ${o}`,`info`)}else I(`Failed to get user info`,`error`)}catch{I(`Failed to get user info`,`error`)}},getModels:async()=>ae.filter(e=>e.codeAgentSupported).map(e=>({label:e.name||e.llmName,value:e.llmName,model:e})),getChatTitles:async()=>he.map(e=>{let t=e.name||e.deploymentConversationId||`Untitled`;return{id:e.deploymentConversationId||``,title:t.length>50?t.substring(0,47)+`...`:t,messageCount:e.hasHistory,date:e.createdAt}}),addNotification:I,mcp:L,addAllowedDirectory:R,refreshMcpTools:z,getAgentStatus:()=>V,getTotalCredits:ee?()=>kQ(re,ee):void 0,setTheme:U,loginAuth:{initiateDeviceCode:async e=>{let t=await $k(),n=await re.authenticateDeviceForCodeLlm(e,t);return!n?.success||!n?.result?{success:!1,error:n?.error??`Failed to start device code login`}:{success:!0,verificationUri:n.result.verificationUri,userCode:n.result.userCode,pollingInterval:n.result.pollingInterval}},pollDeviceCode:async e=>{let t=await re.pollDeviceCode(e);return t?.success&&t.result?.deviceCode?{success:!0,deviceCode:t.result.deviceCode,chatWebUrl:t.result.chatWebUrl}:{success:!1}},completeDeviceCodeLogin:async(e,t)=>{if(await ie.loginWithDeviceCode(e),t){let e=t.replace(/^https?:\/\//,``);re.setChatWebDomain(e)}ye(!0),await De(),await oe()},loginWithApiKey:async e=>{if(await ie.loginWithApiKey(e),!(await re.getUserInfo())?.result?.email)throw await ie.logout(),Error(`Invalid API key — authentication failed`);ye(!0),await De(),await oe()},isEnvAuth:()=>ie.isEnvAuth()},checkEnvAuth:()=>({isEnvAuth:ie.isEnvAuth(),shouldHide:ie.isEnvAuth()}),getUpdateInfo:()=>g})},[ae,j,M,d,o,re,oe,P,I,L,R,z,B,he,De,V,ee,U,ie,g]);let je=(0,Z.useCallback)(async e=>{try{let t=await F.stat(e),n=await F.readFile(e),r=C.extname(e).toLowerCase(),i=r===`.jpg`||r===`.jpeg`?`image/jpeg`:`image/png`;f({doc_id:`tui-`+Math.random().toString(36).slice(2,11)+`-`+Date.now().toString(36),filename:e,filePath:C.resolve(e),fileName:C.basename(e),content:n.toString(`base64`),mimeType:i,mime_type:i,size:t.size,metadata:{uploadedAt:new Date().toISOString(),source:`tui-clipboard`,isImage:!0,encoding:`base64`}})}catch{}},[f]),K=(0,Z.useCallback)(async()=>{if(await EQ()){let e=await DQ(process.cwd());if(e){let t=LQ(RQ(e));o.current?.insert(`@${t} `),await je(e);return}}let e=await OQ();if(!e)return;let t=VQ(e.trim());if(t){o.current?.insert(t);return}o.current?.insert(e,{isPaste:!0})},[o,je]),Me=(0,Z.useCallback)(e=>{let t=e.target.cursor[0]===0&&e.target.cursor[1]===0;if(!e.key.paste){let t=process.platform===`darwin`&&e.key.super&&e.input===`v`,n=process.platform!==`darwin`&&e.key.ctrl&&e.input===`v`||process.platform===`linux`&&e.key.ctrl&&e.key.shift&&e.input===`V`;if(t||n){K(),e.preventDefault();return}}if(e.key.paste){let t=e.input.replace(/[\r\n]+$/,``),n=t.trim();if(xQ(n)){let t=SQ(n);if(t){let n=LQ(RQ(t));o.current?.insert(`@${n} `),je(t),e.preventDefault();return}}let r=VQ(t.trim());if(r){o.current?.insert(r),e.preventDefault();return}(async()=>{if(await EQ()){let e=await DQ(process.cwd());if(e){let t=LQ(RQ(e));o.current?.insert(`@${t} `),await je(e);return}}o.current?.insert(t,{isPaste:!0})})(),e.preventDefault();return}if(e.input.length>3&&!e.key.ctrl&&!e.key.meta&&!e.key.paste){b.current.text+=e.input,b.current.timer&&clearTimeout(b.current.timer),b.current.timer=setTimeout(()=>{let e=b.current.text;b.current={text:``,timer:null};let t=VQ(e.trim());if(t){o.current?.insert(t);return}o.current?.insert(e,{isPaste:!0})},50),e.preventDefault();return}if(i===ZK.Prompt&&e.key.upArrow&&e.target.visualCursor[0]===0&&l.length>0&&n.trim()===``){let t=l[0];o.current?.setText(t),d(),e.preventDefault();return}if(me?.shouldPreventDefault&&me.shouldPreventDefault(e.input||``,e.key)){e.preventDefault();return}if((i===ZK.Prompt||i===ZK.Help||i===ZK.Files)&&(e.key.upArrow||e.key.downArrow)){let t=e.target,r=t.visualCursor[0]===0,i=t.visualCursor[0]>=t.allVisualLines.length-1;if(e.key.upArrow&&r){if(S.getEntries().length>0){S.isNavigating()||(w.current=n);let t=S.navigateUp();if(t){o.current?.setText(t.message),e.preventDefault();return}}}else if(e.key.downArrow&&i){if(!S.isNavigating()){e.preventDefault();return}let t=S.navigateDown();t?o.current?.setText(t.message):o.current?.setText(w.current),e.preventDefault();return}}if(i===ZK.Bash&&pe){let t=e.target,n=e.key.upArrow&&t.visualCursor[0]===0,r=e.key.downArrow&&t.visualCursor[0]>=t.allVisualLines.length-1;if(n||r){let t=pe(e.key.upArrow?`up`:`down`);if(t!==null){o.current?.setText(t),e.preventDefault();return}}}if(t&&e.key.backspace){if(le){ce(),e.preventDefault();return}i!==ZK.Prompt&&(a(ZK.Prompt),S.resetNavigation(),w.current=``,e.preventDefault());return}if(i===ZK.Prompt&&e.key.shift&&e.key.tab){se(),e.preventDefault();return}let r=D0[e.input];if(r&&(!r.atStartOnly||t)){i!==r.mode&&a(r.mode),r.preventDefault&&r.mode!==ZK.Command&&e.preventDefault();return}},[i,a,me,pe,o,K,je,l,n,d,le,ce,se,S]),Ne=(0,Z.useCallback)((e,t)=>{let n=T.current;T.current=e.length,r(e);let o=e.trim(),s=o.startsWith(`/`),c=o.slice(1).split(/\s/)[0]||``,l=s&&(c===``||!/[/\\.]/.test(c)&&/^[a-zA-Z]/.test(c)),u=V===Sl.Submitted||V===Sl.Streaming||V===Sl.ExecutingTool||V===Sl.WaitingForToolPermission;e.length>0&&!l&&!u&&N();let d=M1(e,t.cursor);if(o.length===0&&n>0&&(i===ZK.Command||i===ZK.Bash||i===ZK.Help)){a(ZK.Prompt);return}if(d){i!==ZK.Files&&a(ZK.Files);return}if(i===ZK.Files){d||a(ZK.Prompt);return}i===ZK.Help&&o.length>0&&a(ZK.Prompt),E.current&&=(clearTimeout(E.current),null),!l&&i===ZK.Command&&o.length>0?a(ZK.Prompt):l&&i!==ZK.Command&&(E.current=setTimeout(()=>{E.current=null,a(ZK.Command)},80))},[i,r,a,N,V]),Pe=(0,Z.useCallback)(async e=>{let t=e.trim();if(!t.startsWith(`/`)){let e=w1.match(t,i);if(e&&await w1.execute(e)){o.current?.setText(``),p();return}}if(me?.onSubmit){me.onSubmit(e),i===ZK.Bash?(o.current?.setText(``),c(fe())):i===ZK.Command&&a(ZK.Prompt),p();return}switch(i){case ZK.Prompt:if(ve===!1){I(`Not logged in. Use /login email@example.com to login.`,`warning`);return}if(V===Sl.Submitted||V===Sl.Streaming||V===Sl.ExecutingTool||V===Sl.WaitingForToolPermission){let t=v(e.trimStart());u(t),S.append(t),S.resetNavigation(),w.current=``,y(),o.current?.setText(``);return}let t=_e||ae[0]?.llmName||void 0,n=v(e);S.append(n),S.resetNavigation(),w.current=``,A({message:n,selectedModel:t}),y(),p();return;default:}},[i,me,A,fe,c,_e,a,o,V,u,I,p,ve,v,y,S,ae]),{color:Fe,placeholder:Ie,prefix:Le}=E0[i],Re=H>0?``:Ie,ze=(0,Z.useMemo)(()=>N1(),[]),Be=(i===ZK.Bash?fe():s)===`pending`||V===Sl.WaitingForToolPermission,Ve=PQ(process.cwd()),He=(0,Z.useMemo)(()=>(0,X.jsx)(Q,{flexGrow:1,borderStyle:{bottom:`─`},borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1,borderDimColor:!0}),[]);return(0,X.jsxs)(X.Fragment,{children:[h,(0,X.jsx)(Z.Activity,{mode:h?`hidden`:`visible`,children:(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(P1,{}),(0,X.jsxs)(Q,{flexDirection:`row`,alignItems:`flex-end`,children:[He,ve===!1&&(0,X.jsx)($,{dimColor:!0,children:` Not logged in`}),ve===!1&&be&&Oe&&(0,X.jsx)($,{dimColor:!0,children:` •`}),be&&Oe&&(0,X.jsxs)($,{children:[` `,ae.find(e=>e.llmName===Oe)?.name||Oe]}),(ve===!1||be&&Oe)&&(0,X.jsx)($,{dimColor:!0,children:` •`}),(0,X.jsxs)($,{color:`yellowBright`,children:[` `,Ve]})]}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:Fe,dimColor:we,children:Le}),(0,X.jsx)(Y$,{ref:o,onChange:Ne,onKeyDown:Me,onSubmit:Pe,placeholder:Re,grammar:ze,disabled:Be,ghostText:m??void 0})]}),(0,X.jsx)(Q,{flexDirection:`row`,children:He}),(0,X.jsxs)(Q,{justifyContent:`space-between`,children:[(0,X.jsx)(F1,{mode:i,prompt:n,handler:me,onExitFilesMode:()=>a(ZK.Prompt),hints:e,availableHeight:ue,onLoadingChange:Ce,commandContext:Ee}),(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[D&&O!==void 0&&k!==void 0?(0,X.jsxs)($,{dimColor:!0,children:[(0,X.jsxs)($,{color:`cyan`,children:[k-O+1,` lines selected`]}),` `,`in `,(0,X.jsx)($,{color:`cyan`,children:C.basename(D)})]}):D&&(0,X.jsxs)($,{dimColor:!0,children:[`in `,(0,X.jsx)($,{color:`cyan`,children:C.basename(D)})]}),e?.escClear&&(0,X.jsx)($,{wrap:`truncate-middle`,dimColor:!0,children:`Press ESC again to clear input`}),e?.escClear&&g&&(0,X.jsx)($,{dimColor:!0,children:`·`}),g&&(0,X.jsx)($,{wrap:`truncate-middle`,dimColor:!0,children:g.isEphemeral?`Update available (${g.latestVersion})`:_?`Update available (${g.latestVersion}) · Restart to auto-update`:`Update available (${g.latestVersion}) · Run: ${Mj()}`})]})]})]})})]})});O0.displayName=`ComposerInner`;const k0=(0,Z.memo)(({hints:e,composerRef:t})=>(0,X.jsx)(A1,{children:(0,X.jsx)(Z.Suspense,{fallback:(0,X.jsx)($,{dimColor:!0,children:`Loading models...`}),children:(0,X.jsx)(O0,{hints:e,composerRef:t})})}));k0.displayName=`Composer`;var A0=class extends Z.Component{state={hasError:!1,error:null,errorInfo:null};static getDerivedStateFromError(e){return{hasError:!0,error:e,errorInfo:null}}componentDidCatch(e,t){this.setState({error:e,errorInfo:t}),this.props.onError&&this.props.onError(e,t)}render(){let{hasError:e,error:t,errorInfo:n}=this.state,{fallback:r,children:i}=this.props;return e?r?typeof r==`function`?r(t,n):r:(0,X.jsxs)(Q,{flexDirection:`column`,padding:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong.`}),t&&(0,X.jsxs)(Q,{marginTop:1,flexDirection:`column`,children:[(0,X.jsx)($,{color:`yellow`,children:t.toString()}),n?.componentStack&&(0,X.jsx)($,{color:`gray`,children:n.componentStack})]})]}):i}};const j0=(0,Z.memo)(({duration:e,credits:t,conversationId:n})=>{let{colors:r}=RL();return(0,X.jsxs)(Q,{flexDirection:`column`,paddingY:1,children:[(0,X.jsx)($,{color:r.primary,children:`
12740
12740
  ▞▀▖▌ ▞▀▖▜▘ ▞▀▖▌ ▜▘
12741
12741
  ▙▄▌▛▀▖▝▀▖▞▀▖▌ ▌▞▀▘ ▙▄▌▐ ▌ ▌ ▐
12742
12742
  ▌ ▌▌ ▌▞▀▌▌ ▖▌ ▌▝▀▖▗▖▌ ▌▐ ▌ ▖▌ ▐
12743
12743
  ▘ ▘▀▀ ▝▀▘▝▀ ▝▀▘▀▀ ▝▘▘ ▘▀▘ ▝▀ ▀▀▘▀▘
12744
- `}),(0,X.jsx)(Q,{height:1}),(0,X.jsx)($,{color:r.info,children:`https://desktop.abacus.ai`}),(0,X.jsx)(Q,{height:1}),(0,X.jsxs)($,{dimColor:!0,children:[`Spent `,e,` in the CLI`]}),t>0&&(0,X.jsxs)($,{dimColor:!0,children:[`Total credits used: `,Math.floor(t*100)/100]}),n&&(0,X.jsxs)($,{dimColor:!0,children:[`abacusai --resume `,n]})]})});A0.displayName=`ExitMessage`;function j0(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var M0=j0();function N0(e){M0=e}var P0={exec:()=>null};function F0(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(L0.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var I0=(()=>{try{return!0}catch{return!1}})(),L0={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`),blockquoteBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}>`)},R0=/^(?:[ \t]*(?:\n|$))+/,z0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,B0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,V0=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,H0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,U0=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,W0=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,G0=F0(W0).replace(/bull/g,U0).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),K0=F0(W0).replace(/bull/g,U0).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),q0=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,J0=/^[^\n]+/,Y0=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,X0=F0(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Y0).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Z0=F0(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,U0).getRegex(),Q0=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,$0=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,e2=F0(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,$0).replace(`tag`,Q0).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),t2=F0(q0).replace(`hr`,V0).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Q0).getRegex(),n2={blockquote:F0(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,t2).getRegex(),code:z0,def:X0,fences:B0,heading:H0,hr:V0,html:e2,lheading:G0,list:Z0,newline:R0,paragraph:t2,table:P0,text:J0},r2=F0(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,V0).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Q0).getRegex(),i2={...n2,lheading:K0,table:r2,paragraph:F0(q0).replace(`hr`,V0).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,r2).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,Q0).getRegex()},a2={...n2,html:F0(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,$0).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:P0,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:F0(q0).replace(`hr`,V0).replace(`heading`,` *#{1,6} *[^
12745
- ]`).replace(`lheading`,G0).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},o2=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,s2=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,c2=/^( {2,}|\\)\n(?!\s*$)/,l2=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,u2=/[\p{P}\p{S}]/u,d2=/[\s\p{P}\p{S}]/u,f2=/[^\s\p{P}\p{S}]/u,p2=F0(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,d2).getRegex(),m2=/(?!~)[\p{P}\p{S}]/u,h2=/(?!~)[\s\p{P}\p{S}]/u,g2=/(?:[^\s\p{P}\p{S}]|~)/u,_2=/(?![*_])[\p{P}\p{S}]/u,v2=/(?![*_])[\s\p{P}\p{S}]/u,y2=/(?:[^\s\p{P}\p{S}]|[*_])/u,b2=F0(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,I0?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),x2=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,S2=F0(x2,`u`).replace(/punct/g,u2).getRegex(),C2=F0(x2,`u`).replace(/punct/g,m2).getRegex(),w2=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,T2=F0(w2,`gu`).replace(/notPunctSpace/g,f2).replace(/punctSpace/g,d2).replace(/punct/g,u2).getRegex(),E2=F0(w2,`gu`).replace(/notPunctSpace/g,g2).replace(/punctSpace/g,h2).replace(/punct/g,m2).getRegex(),D2=F0(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,f2).replace(/punctSpace/g,d2).replace(/punct/g,u2).getRegex(),O2=F0(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,_2).getRegex(),k2=F0(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,y2).replace(/punctSpace/g,v2).replace(/punct/g,_2).getRegex(),A2=F0(/\\(punct)/,`gu`).replace(/punct/g,u2).getRegex(),j2=F0(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),M2=F0($0).replace(`(?:-->|$)`,`-->`).getRegex(),N2=F0(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,M2).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),P2=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,F2=F0(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,P2).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),I2=F0(/^!?\[(label)\]\[(ref)\]/).replace(`label`,P2).replace(`ref`,Y0).getRegex(),L2=F0(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Y0).getRegex(),R2=F0(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,I2).replace(`nolink`,L2).getRegex(),z2=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,B2={_backpedal:P0,anyPunctuation:A2,autolink:j2,blockSkip:b2,br:c2,code:s2,del:P0,delLDelim:P0,delRDelim:P0,emStrongLDelim:S2,emStrongRDelimAst:T2,emStrongRDelimUnd:D2,escape:o2,link:F2,nolink:L2,punctuation:p2,reflink:I2,reflinkSearch:R2,tag:N2,text:l2,url:P0},V2={...B2,link:F0(/^!?\[(label)\]\((.*?)\)/).replace(`label`,P2).getRegex(),reflink:F0(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,P2).getRegex()},H2={...B2,emStrongRDelimAst:E2,emStrongLDelim:C2,delLDelim:O2,delRDelim:k2,url:F0(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,z2).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:F0(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,z2).getRegex()},U2={...H2,br:F0(c2).replace(`{2,}`,`*`).getRegex(),text:F0(H2.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},W2={normal:n2,gfm:i2,pedantic:a2},G2={normal:B2,gfm:H2,breaks:U2,pedantic:V2},K2={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},q2=e=>K2[e];function J2(e,t){if(t){if(L0.escapeTest.test(e))return e.replace(L0.escapeReplace,q2)}else if(L0.escapeTestNoEncode.test(e))return e.replace(L0.escapeReplaceNoEncode,q2);return e}function Y2(e){try{e=encodeURI(e).replace(L0.percentDecode,`%`)}catch{return null}return e}function X2(e,t){let n=e.replace(L0.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(L0.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(L0.slashPipe,`|`);return n}function Z2(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Q2(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function $2(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function e4(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function t4(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
12744
+ `}),(0,X.jsx)(Q,{height:1}),(0,X.jsx)($,{color:r.info,children:`https://desktop.abacus.ai`}),(0,X.jsx)(Q,{height:1}),(0,X.jsxs)($,{dimColor:!0,children:[`Spent `,e,` in the CLI`]}),t>0&&(0,X.jsxs)($,{dimColor:!0,children:[`Total credits used: `,Math.floor(t*100)/100]}),n&&(0,X.jsxs)($,{dimColor:!0,children:[`abacusai --resume `,n]})]})});j0.displayName=`ExitMessage`;function M0(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var N0=M0();function P0(e){N0=e}var F0={exec:()=>null};function I0(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(R0.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var L0=(()=>{try{return!0}catch{return!1}})(),R0={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,`i`),blockquoteBeginRegex:e=>RegExp(`^ {0,${Math.min(3,e-1)}}>`)},z0=/^(?:[ \t]*(?:\n|$))+/,B0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,V0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,H0=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,U0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,W0=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,G0=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,K0=I0(G0).replace(/bull/g,W0).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),q0=I0(G0).replace(/bull/g,W0).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),J0=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Y0=/^[^\n]+/,X0=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Z0=I0(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,X0).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Q0=I0(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,W0).getRegex(),$0=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,e2=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,t2=I0(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,e2).replace(`tag`,$0).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),n2=I0(J0).replace(`hr`,H0).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,$0).getRegex(),r2={blockquote:I0(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,n2).getRegex(),code:B0,def:Z0,fences:V0,heading:U0,hr:H0,html:t2,lheading:K0,list:Q0,newline:z0,paragraph:n2,table:F0,text:Y0},i2=I0(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,H0).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,$0).getRegex(),a2={...r2,lheading:q0,table:i2,paragraph:I0(J0).replace(`hr`,H0).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,i2).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,$0).getRegex()},o2={...r2,html:I0(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,e2).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:F0,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I0(J0).replace(`hr`,H0).replace(`heading`,` *#{1,6} *[^
12745
+ ]`).replace(`lheading`,K0).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},s2=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,c2=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,l2=/^( {2,}|\\)\n(?!\s*$)/,u2=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,d2=/[\p{P}\p{S}]/u,f2=/[\s\p{P}\p{S}]/u,p2=/[^\s\p{P}\p{S}]/u,m2=I0(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,f2).getRegex(),h2=/(?!~)[\p{P}\p{S}]/u,g2=/(?!~)[\s\p{P}\p{S}]/u,_2=/(?:[^\s\p{P}\p{S}]|~)/u,v2=/(?![*_])[\p{P}\p{S}]/u,y2=/(?![*_])[\s\p{P}\p{S}]/u,b2=/(?:[^\s\p{P}\p{S}]|[*_])/u,x2=I0(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,L0?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),S2=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,C2=I0(S2,`u`).replace(/punct/g,d2).getRegex(),w2=I0(S2,`u`).replace(/punct/g,h2).getRegex(),T2=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,E2=I0(T2,`gu`).replace(/notPunctSpace/g,p2).replace(/punctSpace/g,f2).replace(/punct/g,d2).getRegex(),D2=I0(T2,`gu`).replace(/notPunctSpace/g,_2).replace(/punctSpace/g,g2).replace(/punct/g,h2).getRegex(),O2=I0(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,p2).replace(/punctSpace/g,f2).replace(/punct/g,d2).getRegex(),k2=I0(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,v2).getRegex(),A2=I0(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,b2).replace(/punctSpace/g,y2).replace(/punct/g,v2).getRegex(),j2=I0(/\\(punct)/,`gu`).replace(/punct/g,d2).getRegex(),M2=I0(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),N2=I0(e2).replace(`(?:-->|$)`,`-->`).getRegex(),P2=I0(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,N2).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),F2=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,I2=I0(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,F2).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),L2=I0(/^!?\[(label)\]\[(ref)\]/).replace(`label`,F2).replace(`ref`,X0).getRegex(),R2=I0(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,X0).getRegex(),z2=I0(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,L2).replace(`nolink`,R2).getRegex(),B2=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,V2={_backpedal:F0,anyPunctuation:j2,autolink:M2,blockSkip:x2,br:l2,code:c2,del:F0,delLDelim:F0,delRDelim:F0,emStrongLDelim:C2,emStrongRDelimAst:E2,emStrongRDelimUnd:O2,escape:s2,link:I2,nolink:R2,punctuation:m2,reflink:L2,reflinkSearch:z2,tag:P2,text:u2,url:F0},H2={...V2,link:I0(/^!?\[(label)\]\((.*?)\)/).replace(`label`,F2).getRegex(),reflink:I0(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,F2).getRegex()},U2={...V2,emStrongRDelimAst:D2,emStrongLDelim:w2,delLDelim:k2,delRDelim:A2,url:I0(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,B2).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:I0(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,B2).getRegex()},W2={...U2,br:I0(l2).replace(`{2,}`,`*`).getRegex(),text:I0(U2.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},G2={normal:r2,gfm:a2,pedantic:o2},K2={normal:V2,gfm:U2,breaks:W2,pedantic:H2},q2={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,'"':`&quot;`,"'":`&#39;`},J2=e=>q2[e];function Y2(e,t){if(t){if(R0.escapeTest.test(e))return e.replace(R0.escapeReplace,J2)}else if(R0.escapeTestNoEncode.test(e))return e.replace(R0.escapeReplaceNoEncode,J2);return e}function X2(e){try{e=encodeURI(e).replace(R0.percentDecode,`%`)}catch{return null}return e}function Z2(e,t){let n=e.replace(R0.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(R0.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(R0.slashPipe,`|`);return n}function Q2(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function $2(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function e4(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function t4(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function n4(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
12746
12746
  `).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
12747
- `)}var n4=class{options;rules;lexer;constructor(e){this.options=e||M0}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=t[0].replace(this.rules.other.codeRemoveIndent,``);return{type:`code`,raw:t[0],codeBlockStyle:`indented`,text:this.options.pedantic?e:Z2(e,`
12748
- `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=t4(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Z2(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Z2(t[0],`
12749
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Z2(t[0],`
12747
+ `)}var r4=class{options;rules;lexer;constructor(e){this.options=e||N0}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=t[0].replace(this.rules.other.codeRemoveIndent,``);return{type:`code`,raw:t[0],codeBlockStyle:`indented`,text:this.options.pedantic?e:Q2(e,`
12748
+ `)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=n4(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=Q2(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:Q2(t[0],`
12749
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=Q2(t[0],`
12750
12750
  `).split(`
12751
12751
  `),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
12752
12752
  `),c=s.replace(this.rules.other.blockquoteSetextReplace,`
@@ -12757,17 +12757,17 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
12757
12757
  `),o=this.blockquote(a);i[i.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,r=r.substring(0,r.length-t.text.length)+o.text;break}else if(u?.type===`list`){let t=u,a=t.raw+`
12758
12758
  `+e.join(`
12759
12759
  `),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
12760
- `);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=$2(t[2].split(`
12760
+ `);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=e4(t[2].split(`
12761
12761
  `,1)[0],t[1].length),l=e.split(`
12762
12762
  `,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
12763
12763
  `,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
12764
12764
  `,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
12765
12765
  `+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
12766
12766
  `+l}u=!l.trim(),r+=p+`
12767
- `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),e.task){if(e.text=e.text.replace(this.rules.other.listReplaceTask,``),e.tokens[0]?.type===`text`||e.tokens[0]?.type===`paragraph`){e.tokens[0].raw=e.tokens[0].raw.replace(this.rules.other.listReplaceTask,``),e.tokens[0].text=e.tokens[0].text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}}let t=this.rules.other.listTaskCheckbox.exec(e.raw);if(t){let n={type:`checkbox`,raw:t[0]+` `,checked:t[0]!==`[ ]`};e.checked=n.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=n.raw+e.tokens[0].raw,e.tokens[0].text=n.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(n)):e.tokens.unshift({type:`paragraph`,raw:n.raw,text:n.raw,tokens:[n]}):e.tokens.unshift(n)}}if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:`html`,block:!0,raw:t[0],pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:t[0],href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=X2(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
12768
- `):[],a={type:`table`,raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(X2(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:`heading`,raw:t[0],depth:t[2].charAt(0)===`=`?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
12769
- `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Z2(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Q2(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),e4(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return e4(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},r4=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||M0,this.options.tokenizer=this.options.tokenizer||new n4,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:L0,block:W2.normal,inline:G2.normal};this.options.pedantic?(t.block=W2.pedantic,t.inline=G2.pedantic):this.options.gfm&&(t.block=W2.gfm,this.options.breaks?t.inline=G2.breaks:t.inline=G2.gfm),this.tokenizer.rules=t}static get rules(){return{block:W2,inline:G2}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(L0.carriageReturn,`
12770
- `),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(L0.tabCharGlobal,` `).replace(L0.spaceLine,``));e;){let r;if(this.options.extensions?.block?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let n=t.at(-1);r.raw.length===1&&n!==void 0?n.raw+=`
12767
+ `,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),e.task){if(e.text=e.text.replace(this.rules.other.listReplaceTask,``),e.tokens[0]?.type===`text`||e.tokens[0]?.type===`paragraph`){e.tokens[0].raw=e.tokens[0].raw.replace(this.rules.other.listReplaceTask,``),e.tokens[0].text=e.tokens[0].text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}}let t=this.rules.other.listTaskCheckbox.exec(e.raw);if(t){let n={type:`checkbox`,raw:t[0]+` `,checked:t[0]!==`[ ]`};e.checked=n.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=n.raw+e.tokens[0].raw,e.tokens[0].text=n.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(n)):e.tokens.unshift({type:`paragraph`,raw:n.raw,text:n.raw,tokens:[n]}):e.tokens.unshift(n)}}if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t)return{type:`html`,block:!0,raw:t[0],pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:t[0]}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:t[0],href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Z2(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
12768
+ `):[],a={type:`table`,raw:t[0],header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(Z2(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:`heading`,raw:t[0],depth:t[2].charAt(0)===`=`?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
12769
+ `?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=Q2(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=$2(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),t4(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return t4(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||r[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[2])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!=null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},i4=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||N0,this.options.tokenizer=this.options.tokenizer||new r4,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:R0,block:G2.normal,inline:K2.normal};this.options.pedantic?(t.block=G2.pedantic,t.inline=K2.pedantic):this.options.gfm&&(t.block=G2.gfm,this.options.breaks?t.inline=K2.breaks:t.inline=K2.gfm),this.tokenizer.rules=t}static get rules(){return{block:G2,inline:K2}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(R0.carriageReturn,`
12770
+ `),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){for(this.options.pedantic&&(e=e.replace(R0.tabCharGlobal,` `).replace(R0.spaceLine,``));e;){let r;if(this.options.extensions?.block?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let n=t.at(-1);r.raw.length===1&&n!==void 0?n.raw+=`
12771
12771
  `:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
12772
12772
  `)?``:`
12773
12773
  `)+r.raw,n.text+=`
@@ -12780,9 +12780,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
12780
12780
  `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
12781
12781
  `)?``:`
12782
12782
  `)+r.raw,n.text+=`
12783
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(r);continue}if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}else throw Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``;for(;e;){a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}else throw Error(t)}}return t}},i4=class{options;parser;constructor(e){this.options=e||M0}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(L0.notSpaceStart)?.[0],i=e.replace(L0.endingNewline,``)+`
12784
- `;return r?`<pre><code class="language-`+J2(r)+`">`+(n?i:J2(i,!0))+`</code></pre>
12785
- `:`<pre><code>`+(n?i:J2(i,!0))+`</code></pre>
12783
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(r);continue}if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}else throw Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!=null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!=null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!=null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``;for(;e;){a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){let t=`Infinite loop on byte: `+e.charCodeAt(0);if(this.options.silent){console.error(t);break}else throw Error(t)}}return t}},a4=class{options;parser;constructor(e){this.options=e||N0}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(R0.notSpaceStart)?.[0],i=e.replace(R0.endingNewline,``)+`
12784
+ `;return r?`<pre><code class="language-`+Y2(r)+`">`+(n?i:Y2(i,!0))+`</code></pre>
12785
+ `:`<pre><code>`+(n?i:Y2(i,!0))+`</code></pre>
12786
12786
  `}blockquote({tokens:e}){return`<blockquote>
12787
12787
  ${this.parser.parse(e)}</blockquote>
12788
12788
  `}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
@@ -12798,38 +12798,38 @@ ${this.parser.parse(e)}</blockquote>
12798
12798
  `}tablerow({text:e}){return`<tr>
12799
12799
  ${e}</tr>
12800
12800
  `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
12801
- `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${J2(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=Y2(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+J2(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=Y2(e);if(i===null)return J2(n);e=i;let a=`<img src="${e}" alt="${J2(n)}"`;return t&&(a+=` title="${J2(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:J2(e.text)}},a4=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},o4=class e{options;renderer;textRenderer;constructor(e){this.options=e||M0,this.options.renderer=this.options.renderer||new i4,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new a4}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},s4=class{options;block;constructor(e){this.options=e||M0}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?r4.lex:r4.lexInline}provideParser(){return this.block?o4.parse:o4.parseInline}},c4=new class{defaults=j0();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=o4;Renderer=i4;TextRenderer=a4;Lexer=r4;Tokenizer=n4;Hooks=s4;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new i4(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new n4(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new s4;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];s4.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&s4.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return r4.lex(e,t??this.defaults)}parser(e,t){return o4.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer():e?r4.lex:r4.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser():e?o4.parse:o4.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer():e?r4.lex:r4.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser():e?o4.parse:o4.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
12802
- Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+J2(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function l4(e,t){return c4.parse(e,t)}l4.options=l4.setOptions=function(e){return c4.setOptions(e),l4.defaults=c4.defaults,N0(l4.defaults),l4},l4.getDefaults=j0,l4.defaults=M0,l4.use=function(...e){return c4.use(...e),l4.defaults=c4.defaults,N0(l4.defaults),l4},l4.walkTokens=function(e,t){return c4.walkTokens(e,t)},l4.parseInline=c4.parseInline,l4.Parser=o4,l4.parser=o4.parse,l4.Renderer=i4,l4.TextRenderer=a4,l4.Lexer=r4,l4.lexer=r4.lex,l4.Tokenizer=n4,l4.Hooks=s4,l4.parse=l4,l4.options,l4.setOptions,l4.use,l4.walkTokens,l4.parseInline,o4.parse,r4.lex;var u4=Object.defineProperty,d4=Object.defineProperties,f4=Object.getOwnPropertyDescriptors,p4=Object.getOwnPropertySymbols,m4=Object.prototype.hasOwnProperty,h4=Object.prototype.propertyIsEnumerable,g4=(e,t,n)=>t in e?u4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_4=(e,t)=>{for(var n in t||={})m4.call(t,n)&&g4(e,n,t[n]);if(p4)for(var n of p4(t))h4.call(t,n)&&g4(e,n,t[n]);return e},v4=(e,t)=>d4(e,f4(t)),y4=(e,t)=>{let n=!1,r=!1;for(let i=0;i<t;i+=1){if(e[i]===`\\`&&i+1<e.length&&e[i+1]==="`"){i+=1;continue}if(e.substring(i,i+3)==="```"){r=!r,i+=2;continue}!r&&e[i]==="`"&&(n=!n)}return n||r},b4=(e,t)=>{let n=e.substring(t,t+3)==="```",r=t>0&&e.substring(t-1,t+2)==="```",i=t>1&&e.substring(t-2,t+1)==="```";return n||r||i},x4=e=>{let t=0;for(let n=0;n<e.length;n+=1){if(e[n]===`\\`&&n+1<e.length&&e[n+1]==="`"){n+=1;continue}e[n]==="`"&&!b4(e,n)&&(t+=1)}return t},S4=(e,t)=>{let n=!1,r=!1,i=-1;for(let a=0;a<e.length;a+=1){if(e[a]===`\\`&&a+1<e.length&&e[a+1]==="`"){a+=1;continue}if(e.substring(a,a+3)==="```"){r=!r,a+=2;continue}if(!r&&e[a]==="`")if(n){if(i<t&&t<a)return!0;n=!1,i=-1}else n=!0,i=a}return!1},C4=/^(\s*(?:[-*+]|\d+[.)]) +)>(=?\s*[$]?\d)/gm,w4=e=>!e||typeof e!=`string`||!e.includes(`>`)?e:e.replace(C4,(t,n,r,i)=>y4(e,i)?t:`${n}\\>${r}`),T4=/(\*\*)([^*]*\*?)$/,E4=/(__)([^_]*?)$/,D4=/(\*\*\*)([^*]*?)$/,O4=/(\*)([^*]*?)$/,k4=/(_)([^_]*?)$/,A4=/(`)([^`]*?)$/,j4=/(~~)([^~]*?)$/,M4=/^[\s_~*`]*$/,N4=/^[\s]*[-*+][\s]+$/,P4=/[\p{L}\p{N}_]/u,F4=/^```[^`\n]*```?$/,I4=/^\*{4,}$/,L4=/(__)([^_]+)_$/,R4=/(~~)([^~]+)~$/,z4=/~~/g,B4=e=>{if(!e)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95?!0:P4.test(e)},V4=(e,t)=>{let n=1;for(let r=t-1;r>=0;--r)if(e[r]===`]`)n+=1;else if(e[r]===`[`&&(--n,n===0))return r;return-1},H4=(e,t)=>{let n=1;for(let r=t+1;r<e.length;r+=1)if(e[r]===`[`)n+=1;else if(e[r]===`]`&&(--n,n===0))return r;return-1},U4=(e,t)=>{let n=!1,r=!1;for(let i=0;i<e.length&&i<t;i+=1){if(e[i]===`\\`&&e[i+1]===`$`){i+=1;continue}e[i]===`$`&&(e[i+1]===`$`?(r=!r,i+=1,n=!1):r||(n=!n))}return n||r},W4=(e,t)=>{for(let n=t;n<e.length;n+=1){if(e[n]===`)`)return!0;if(e[n]===`
12803
- `)return!1}return!1},G4=(e,t)=>{for(let n=t-1;n>=0;--n){if(e[n]===`)`)return!1;if(e[n]===`(`)return n>0&&e[n-1]===`]`?W4(e,t):!1;if(e[n]===`
12804
- `)return!1}return!1},K4=(e,t)=>{for(let n=t-1;n>=0;--n){if(e[n]===`>`)return!1;if(e[n]===`<`){let t=n+1<e.length?e[n+1]:``;return t>=`a`&&t<=`z`||t>=`A`&&t<=`Z`||t===`/`}if(e[n]===`
12805
- `)return!1}return!1},q4=(e,t,n)=>{let r=0;for(let n=t-1;n>=0;--n)if(e[n]===`
12801
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${Y2(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=X2(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+Y2(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=X2(e);if(i===null)return Y2(n);e=i;let a=`<img src="${e}" alt="${Y2(n)}"`;return t&&(a+=` title="${Y2(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:Y2(e.text)}},o4=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},s4=class e{options;renderer;textRenderer;constructor(e){this.options=e||N0,this.options.renderer=this.options.renderer||new a4,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new o4}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},c4=class{options;block;constructor(e){this.options=e||N0}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(){return this.block?i4.lex:i4.lexInline}provideParser(){return this.block?s4.parse:s4.parseInline}},l4=new class{defaults=M0();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=s4;Renderer=a4;TextRenderer=o4;Lexer=i4;Tokenizer=r4;Hooks=c4;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new a4(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new r4(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new c4;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];c4.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&c4.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return i4.lex(e,t??this.defaults)}parser(e,t){return s4.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer():e?i4.lex:i4.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser():e?s4.parse:s4.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer():e?i4.lex:i4.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser():e?s4.parse:s4.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
12802
+ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+Y2(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function u4(e,t){return l4.parse(e,t)}u4.options=u4.setOptions=function(e){return l4.setOptions(e),u4.defaults=l4.defaults,P0(u4.defaults),u4},u4.getDefaults=M0,u4.defaults=N0,u4.use=function(...e){return l4.use(...e),u4.defaults=l4.defaults,P0(u4.defaults),u4},u4.walkTokens=function(e,t){return l4.walkTokens(e,t)},u4.parseInline=l4.parseInline,u4.Parser=s4,u4.parser=s4.parse,u4.Renderer=a4,u4.TextRenderer=o4,u4.Lexer=i4,u4.lexer=i4.lex,u4.Tokenizer=r4,u4.Hooks=c4,u4.parse=u4,u4.options,u4.setOptions,u4.use,u4.walkTokens,u4.parseInline,s4.parse,i4.lex;var d4=Object.defineProperty,f4=Object.defineProperties,p4=Object.getOwnPropertyDescriptors,m4=Object.getOwnPropertySymbols,h4=Object.prototype.hasOwnProperty,g4=Object.prototype.propertyIsEnumerable,_4=(e,t,n)=>t in e?d4(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,v4=(e,t)=>{for(var n in t||={})h4.call(t,n)&&_4(e,n,t[n]);if(m4)for(var n of m4(t))g4.call(t,n)&&_4(e,n,t[n]);return e},y4=(e,t)=>f4(e,p4(t)),b4=(e,t)=>{let n=!1,r=!1;for(let i=0;i<t;i+=1){if(e[i]===`\\`&&i+1<e.length&&e[i+1]==="`"){i+=1;continue}if(e.substring(i,i+3)==="```"){r=!r,i+=2;continue}!r&&e[i]==="`"&&(n=!n)}return n||r},x4=(e,t)=>{let n=e.substring(t,t+3)==="```",r=t>0&&e.substring(t-1,t+2)==="```",i=t>1&&e.substring(t-2,t+1)==="```";return n||r||i},S4=e=>{let t=0;for(let n=0;n<e.length;n+=1){if(e[n]===`\\`&&n+1<e.length&&e[n+1]==="`"){n+=1;continue}e[n]==="`"&&!x4(e,n)&&(t+=1)}return t},C4=(e,t)=>{let n=!1,r=!1,i=-1;for(let a=0;a<e.length;a+=1){if(e[a]===`\\`&&a+1<e.length&&e[a+1]==="`"){a+=1;continue}if(e.substring(a,a+3)==="```"){r=!r,a+=2;continue}if(!r&&e[a]==="`")if(n){if(i<t&&t<a)return!0;n=!1,i=-1}else n=!0,i=a}return!1},w4=/^(\s*(?:[-*+]|\d+[.)]) +)>(=?\s*[$]?\d)/gm,T4=e=>!e||typeof e!=`string`||!e.includes(`>`)?e:e.replace(w4,(t,n,r,i)=>b4(e,i)?t:`${n}\\>${r}`),E4=/(\*\*)([^*]*\*?)$/,D4=/(__)([^_]*?)$/,O4=/(\*\*\*)([^*]*?)$/,k4=/(\*)([^*]*?)$/,A4=/(_)([^_]*?)$/,j4=/(`)([^`]*?)$/,M4=/(~~)([^~]*?)$/,N4=/^[\s_~*`]*$/,P4=/^[\s]*[-*+][\s]+$/,F4=/[\p{L}\p{N}_]/u,I4=/^```[^`\n]*```?$/,L4=/^\*{4,}$/,R4=/(__)([^_]+)_$/,z4=/(~~)([^~]+)~$/,B4=/~~/g,V4=e=>{if(!e)return!1;let t=e.charCodeAt(0);return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95?!0:F4.test(e)},H4=(e,t)=>{let n=1;for(let r=t-1;r>=0;--r)if(e[r]===`]`)n+=1;else if(e[r]===`[`&&(--n,n===0))return r;return-1},U4=(e,t)=>{let n=1;for(let r=t+1;r<e.length;r+=1)if(e[r]===`[`)n+=1;else if(e[r]===`]`&&(--n,n===0))return r;return-1},W4=(e,t)=>{let n=!1,r=!1;for(let i=0;i<e.length&&i<t;i+=1){if(e[i]===`\\`&&e[i+1]===`$`){i+=1;continue}e[i]===`$`&&(e[i+1]===`$`?(r=!r,i+=1,n=!1):r||(n=!n))}return n||r},G4=(e,t)=>{for(let n=t;n<e.length;n+=1){if(e[n]===`)`)return!0;if(e[n]===`
12803
+ `)return!1}return!1},K4=(e,t)=>{for(let n=t-1;n>=0;--n){if(e[n]===`)`)return!1;if(e[n]===`(`)return n>0&&e[n-1]===`]`?G4(e,t):!1;if(e[n]===`
12804
+ `)return!1}return!1},q4=(e,t)=>{for(let n=t-1;n>=0;--n){if(e[n]===`>`)return!1;if(e[n]===`<`){let t=n+1<e.length?e[n+1]:``;return t>=`a`&&t<=`z`||t>=`A`&&t<=`Z`||t===`/`}if(e[n]===`
12805
+ `)return!1}return!1},J4=(e,t,n)=>{let r=0;for(let n=t-1;n>=0;--n)if(e[n]===`
12806
12806
  `){r=n+1;break}let i=e.length;for(let n=t;n<e.length;n+=1)if(e[n]===`
12807
- `){i=n;break}let a=e.substring(r,i),o=0,s=!1;for(let e of a)if(e===n)o+=1;else if(e!==` `&&e!==` `){s=!0;break}return o>=3&&!s},J4=(e,t,n,r)=>n===`\\`||e.includes(`$`)&&U4(e,t)?!0:n!==`*`&&r===`*`?(t<e.length-2?e[t+2]:``)!==`*`:!!(n===`*`||n&&r&&B4(n)&&B4(r)||(!n||n===` `||n===` `||n===`
12807
+ `){i=n;break}let a=e.substring(r,i),o=0,s=!1;for(let e of a)if(e===n)o+=1;else if(e!==` `&&e!==` `){s=!0;break}return o>=3&&!s},Y4=(e,t,n,r)=>n===`\\`||e.includes(`$`)&&W4(e,t)?!0:n!==`*`&&r===`*`?(t<e.length-2?e[t+2]:``)!==`*`:!!(n===`*`||n&&r&&V4(n)&&V4(r)||(!n||n===` `||n===` `||n===`
12808
12808
  `)&&(!r||r===` `||r===` `||r===`
12809
- `)),Y4=e=>{let t=0,n=!1,r=e.length;for(let i=0;i<r;i+=1){if(e[i]==="`"&&i+2<r&&e[i+1]==="`"&&e[i+2]==="`"){n=!n,i+=2;continue}if(n||e[i]!==`*`)continue;let a=i>0?e[i-1]:``,o=i<r-1?e[i+1]:``;J4(e,i,a,o)||(t+=1)}return t},X4=(e,t,n,r)=>!!(n===`\\`||e.includes(`$`)&&U4(e,t)||G4(e,t)||K4(e,t)||n===`_`||r===`_`||n&&r&&B4(n)&&B4(r)),Z4=e=>{let t=0,n=!1,r=e.length;for(let i=0;i<r;i+=1){if(e[i]==="`"&&i+2<r&&e[i+1]==="`"&&e[i+2]==="`"){n=!n,i+=2;continue}if(n||e[i]!==`_`)continue;let a=i>0?e[i-1]:``,o=i<r-1?e[i+1]:``;X4(e,i,a,o)||(t+=1)}return t},Q4=e=>{let t=0,n=0,r=!1;for(let i=0;i<e.length;i+=1){if(e[i]==="`"&&i+2<e.length&&e[i+1]==="`"&&e[i+2]==="`"){n>=3&&(t+=Math.floor(n/3)),n=0,r=!r,i+=2;continue}r||(e[i]===`*`?n+=1:(n>=3&&(t+=Math.floor(n/3)),n=0))}return n>=3&&(t+=Math.floor(n/3)),t},$4=e=>{let t=0,n=!1;for(let r=0;r<e.length;r+=1){if(e[r]==="`"&&r+2<e.length&&e[r+1]==="`"&&e[r+2]==="`"){n=!n,r+=2;continue}n||e[r]===`*`&&r+1<e.length&&e[r+1]===`*`&&(t+=1,r+=1)}return t},e3=e=>{let t=0,n=!1;for(let r=0;r<e.length;r+=1){if(e[r]==="`"&&r+2<e.length&&e[r+1]==="`"&&e[r+2]==="`"){n=!n,r+=2;continue}n||e[r]===`_`&&r+1<e.length&&e[r+1]===`_`&&(t+=1,r+=1)}return t},t3=(e,t,n)=>{if(!t||M4.test(t))return!0;let r=e.substring(0,n).lastIndexOf(`
12810
- `),i=r===-1?0:r+1,a=e.substring(i,n);return N4.test(a)&&t.includes(`
12811
- `)?!0:q4(e,n,`*`)},n3=e=>{let t=e.match(T4);if(!t)return e;let n=t[2],r=e.lastIndexOf(t[1]);return y4(e,r)||S4(e,r)||t3(e,n,r)?e:$4(e)%2==1?n.endsWith(`*`)?`${e}*`:`${e}**`:e},r3=(e,t,n)=>{if(!t||M4.test(t))return!0;let r=e.substring(0,n).lastIndexOf(`
12812
- `),i=r===-1?0:r+1,a=e.substring(i,n);return N4.test(a)&&t.includes(`
12813
- `)?!0:q4(e,n,`_`)},i3=e=>{let t=e.match(E4);if(!t){let t=e.match(L4);if(t){let n=e.lastIndexOf(t[1]);if(!(y4(e,n)||S4(e,n))&&e3(e)%2==1)return`${e}_`}return e}let n=t[2],r=e.lastIndexOf(t[1]);return y4(e,r)||S4(e,r)||r3(e,n,r)?e:e3(e)%2==1?`${e}__`:e},a3=e=>{let t=!1;for(let n=0;n<e.length;n+=1){if(e[n]==="`"&&n+2<e.length&&e[n+1]==="`"&&e[n+2]==="`"){t=!t,n+=2;continue}if(!t&&e[n]===`*`&&e[n-1]!==`*`&&e[n+1]!==`*`&&e[n-1]!==`\\`&&!U4(e,n)){let t=n>0?e[n-1]:``,r=n<e.length-1?e[n+1]:``;if((!t||t===` `||t===` `||t===`
12809
+ `)),X4=e=>{let t=0,n=!1,r=e.length;for(let i=0;i<r;i+=1){if(e[i]==="`"&&i+2<r&&e[i+1]==="`"&&e[i+2]==="`"){n=!n,i+=2;continue}if(n||e[i]!==`*`)continue;let a=i>0?e[i-1]:``,o=i<r-1?e[i+1]:``;Y4(e,i,a,o)||(t+=1)}return t},Z4=(e,t,n,r)=>!!(n===`\\`||e.includes(`$`)&&W4(e,t)||K4(e,t)||q4(e,t)||n===`_`||r===`_`||n&&r&&V4(n)&&V4(r)),Q4=e=>{let t=0,n=!1,r=e.length;for(let i=0;i<r;i+=1){if(e[i]==="`"&&i+2<r&&e[i+1]==="`"&&e[i+2]==="`"){n=!n,i+=2;continue}if(n||e[i]!==`_`)continue;let a=i>0?e[i-1]:``,o=i<r-1?e[i+1]:``;Z4(e,i,a,o)||(t+=1)}return t},$4=e=>{let t=0,n=0,r=!1;for(let i=0;i<e.length;i+=1){if(e[i]==="`"&&i+2<e.length&&e[i+1]==="`"&&e[i+2]==="`"){n>=3&&(t+=Math.floor(n/3)),n=0,r=!r,i+=2;continue}r||(e[i]===`*`?n+=1:(n>=3&&(t+=Math.floor(n/3)),n=0))}return n>=3&&(t+=Math.floor(n/3)),t},e3=e=>{let t=0,n=!1;for(let r=0;r<e.length;r+=1){if(e[r]==="`"&&r+2<e.length&&e[r+1]==="`"&&e[r+2]==="`"){n=!n,r+=2;continue}n||e[r]===`*`&&r+1<e.length&&e[r+1]===`*`&&(t+=1,r+=1)}return t},t3=e=>{let t=0,n=!1;for(let r=0;r<e.length;r+=1){if(e[r]==="`"&&r+2<e.length&&e[r+1]==="`"&&e[r+2]==="`"){n=!n,r+=2;continue}n||e[r]===`_`&&r+1<e.length&&e[r+1]===`_`&&(t+=1,r+=1)}return t},n3=(e,t,n)=>{if(!t||N4.test(t))return!0;let r=e.substring(0,n).lastIndexOf(`
12810
+ `),i=r===-1?0:r+1,a=e.substring(i,n);return P4.test(a)&&t.includes(`
12811
+ `)?!0:J4(e,n,`*`)},r3=e=>{let t=e.match(E4);if(!t)return e;let n=t[2],r=e.lastIndexOf(t[1]);return b4(e,r)||C4(e,r)||n3(e,n,r)?e:e3(e)%2==1?n.endsWith(`*`)?`${e}*`:`${e}**`:e},i3=(e,t,n)=>{if(!t||N4.test(t))return!0;let r=e.substring(0,n).lastIndexOf(`
12812
+ `),i=r===-1?0:r+1,a=e.substring(i,n);return P4.test(a)&&t.includes(`
12813
+ `)?!0:J4(e,n,`_`)},a3=e=>{let t=e.match(D4);if(!t){let t=e.match(R4);if(t){let n=e.lastIndexOf(t[1]);if(!(b4(e,n)||C4(e,n))&&t3(e)%2==1)return`${e}_`}return e}let n=t[2],r=e.lastIndexOf(t[1]);return b4(e,r)||C4(e,r)||i3(e,n,r)?e:t3(e)%2==1?`${e}__`:e},o3=e=>{let t=!1;for(let n=0;n<e.length;n+=1){if(e[n]==="`"&&n+2<e.length&&e[n+1]==="`"&&e[n+2]==="`"){t=!t,n+=2;continue}if(!t&&e[n]===`*`&&e[n-1]!==`*`&&e[n+1]!==`*`&&e[n-1]!==`\\`&&!W4(e,n)){let t=n>0?e[n-1]:``,r=n<e.length-1?e[n+1]:``;if((!t||t===` `||t===` `||t===`
12814
12814
  `)&&(!r||r===` `||r===` `||r===`
12815
- `)||t&&r&&B4(t)&&B4(r))continue;return n}}return-1},o3=e=>{if(!e.match(O4))return e;let t=a3(e);if(t===-1||y4(e,t)||S4(e,t))return e;let n=e.substring(t+1);return!n||M4.test(n)?e:Y4(e)%2==1?`${e}*`:e},s3=e=>{let t=!1;for(let n=0;n<e.length;n+=1){if(e[n]==="`"&&n+2<e.length&&e[n+1]==="`"&&e[n+2]==="`"){t=!t,n+=2;continue}if(!t&&e[n]===`_`&&e[n-1]!==`_`&&e[n+1]!==`_`&&e[n-1]!==`\\`&&!U4(e,n)&&!G4(e,n)){let t=n>0?e[n-1]:``,r=n<e.length-1?e[n+1]:``;if(t&&r&&B4(t)&&B4(r))continue;return n}}return-1},c3=e=>{let t=e.length;for(;t>0&&e[t-1]===`
12816
- `;)--t;return t<e.length?`${e.slice(0,t)}_${e.slice(t)}`:`${e}_`},l3=e=>{if(!e.endsWith(`**`))return null;let t=e.slice(0,-2);if($4(t)%2!=1)return null;let n=t.indexOf(`**`),r=s3(t);return n!==-1&&r!==-1&&n<r?`${t}_**`:null},u3=e=>{if(!e.match(k4))return e;let t=s3(e);if(t===-1)return e;let n=e.substring(t+1);if(!n||M4.test(n)||y4(e,t)||S4(e,t))return e;if(Z4(e)%2==1){let t=l3(e);return t===null?c3(e):t}return e},d3=e=>{let t=$4(e),n=Y4(e);return t%2==0&&n%2==0},f3=(e,t,n)=>!t||M4.test(t)||y4(e,n)||S4(e,n)?!0:q4(e,n,`*`),p3=e=>{if(I4.test(e))return e;let t=e.match(D4);if(!t)return e;let n=t[2];return f3(e,n,e.lastIndexOf(t[1]))?e:Q4(e)%2==1?d3(e)?e:`${e}***`:e},m3=/<[a-zA-Z/][^>]*$/,h3=e=>{let t=e.match(m3);return!t||t.index===void 0||y4(e,t.index)?e:e.substring(0,t.index).trimEnd()},g3=e=>!e.match(F4)||e.includes(`
12817
- `)?null:e.endsWith("``")&&!e.endsWith("```")?`${e}\``:e,_3=e=>(e.match(/```/g)||[]).length%2==1,v3=e=>{let t=g3(e);if(t!==null)return t;let n=e.match(A4);if(n&&!_3(e)){let t=n[2];if(!t||M4.test(t))return e;if(x4(e)%2==1)return`${e}\``}return e},y3=(e,t)=>t>=2&&e.substring(t-2,t+1)==="```"||t>=1&&e.substring(t-1,t+2)==="```"||t<=e.length-3&&e.substring(t,t+3)==="```",b3=e=>{let t=0,n=!1;for(let r=0;r<e.length-1;r+=1)e[r]==="`"&&!y3(e,r)&&(n=!n),!n&&e[r]===`$`&&e[r+1]===`$`&&(t+=1,r+=1);return t},x3=e=>{let t=e.indexOf(`$$`);return t!==-1&&e.indexOf(`
12815
+ `)||t&&r&&V4(t)&&V4(r))continue;return n}}return-1},s3=e=>{if(!e.match(k4))return e;let t=o3(e);if(t===-1||b4(e,t)||C4(e,t))return e;let n=e.substring(t+1);return!n||N4.test(n)?e:X4(e)%2==1?`${e}*`:e},c3=e=>{let t=!1;for(let n=0;n<e.length;n+=1){if(e[n]==="`"&&n+2<e.length&&e[n+1]==="`"&&e[n+2]==="`"){t=!t,n+=2;continue}if(!t&&e[n]===`_`&&e[n-1]!==`_`&&e[n+1]!==`_`&&e[n-1]!==`\\`&&!W4(e,n)&&!K4(e,n)){let t=n>0?e[n-1]:``,r=n<e.length-1?e[n+1]:``;if(t&&r&&V4(t)&&V4(r))continue;return n}}return-1},l3=e=>{let t=e.length;for(;t>0&&e[t-1]===`
12816
+ `;)--t;return t<e.length?`${e.slice(0,t)}_${e.slice(t)}`:`${e}_`},u3=e=>{if(!e.endsWith(`**`))return null;let t=e.slice(0,-2);if(e3(t)%2!=1)return null;let n=t.indexOf(`**`),r=c3(t);return n!==-1&&r!==-1&&n<r?`${t}_**`:null},d3=e=>{if(!e.match(A4))return e;let t=c3(e);if(t===-1)return e;let n=e.substring(t+1);if(!n||N4.test(n)||b4(e,t)||C4(e,t))return e;if(Q4(e)%2==1){let t=u3(e);return t===null?l3(e):t}return e},f3=e=>{let t=e3(e),n=X4(e);return t%2==0&&n%2==0},p3=(e,t,n)=>!t||N4.test(t)||b4(e,n)||C4(e,n)?!0:J4(e,n,`*`),m3=e=>{if(L4.test(e))return e;let t=e.match(O4);if(!t)return e;let n=t[2];return p3(e,n,e.lastIndexOf(t[1]))?e:$4(e)%2==1?f3(e)?e:`${e}***`:e},h3=/<[a-zA-Z/][^>]*$/,g3=e=>{let t=e.match(h3);return!t||t.index===void 0||b4(e,t.index)?e:e.substring(0,t.index).trimEnd()},_3=e=>!e.match(I4)||e.includes(`
12817
+ `)?null:e.endsWith("``")&&!e.endsWith("```")?`${e}\``:e,v3=e=>(e.match(/```/g)||[]).length%2==1,y3=e=>{let t=_3(e);if(t!==null)return t;let n=e.match(j4);if(n&&!v3(e)){let t=n[2];if(!t||N4.test(t))return e;if(S4(e)%2==1)return`${e}\``}return e},b3=(e,t)=>t>=2&&e.substring(t-2,t+1)==="```"||t>=1&&e.substring(t-1,t+2)==="```"||t<=e.length-3&&e.substring(t,t+3)==="```",x3=e=>{let t=0,n=!1;for(let r=0;r<e.length-1;r+=1)e[r]==="`"&&!b3(e,r)&&(n=!n),!n&&e[r]===`$`&&e[r+1]===`$`&&(t+=1,r+=1);return t},S3=e=>{let t=e.indexOf(`$$`);return t!==-1&&e.indexOf(`
12818
12818
  `,t)!==-1&&!e.endsWith(`
12819
12819
  `)?`${e}
12820
- $$`:`${e}$$`},S3=e=>b3(e)%2==0?e:x3(e),C3=(e,t,n)=>{if(e.substring(t+2).includes(`)`))return null;let r=V4(e,t);if(r===-1||y4(e,r))return null;let i=r>0&&e[r-1]===`!`,a=i?r-1:r,o=e.substring(0,a);if(i)return o;let s=e.substring(r+1,t);return n===`text-only`?`${o}${s}`:`${o}[${s}](streamdown:incomplete-link)`},w3=(e,t)=>{for(let n=0;n<t;n++)if(e[n]===`[`&&!y4(e,n)){if(n>0&&e[n-1]===`!`)continue;let t=H4(e,n);if(t===-1)return n;if(t+1<e.length&&e[t+1]===`(`){let r=e.indexOf(`)`,t+2);r!==-1&&(n=r)}}return t},T3=(e,t,n)=>{let r=t>0&&e[t-1]===`!`,i=r?t-1:t;if(!e.substring(t+1).includes(`]`)){let a=e.substring(0,i);if(r)return a;if(n===`text-only`){let n=w3(e,t);return e.substring(0,n)+e.substring(n+1)}return`${e}](streamdown:incomplete-link)`}if(H4(e,t)===-1){let a=e.substring(0,i);if(r)return a;if(n===`text-only`){let n=w3(e,t);return e.substring(0,n)+e.substring(n+1)}return`${e}](streamdown:incomplete-link)`}return null},E3=(e,t=`protocol`)=>{let n=e.lastIndexOf(`](`);if(n!==-1&&!y4(e,n)){let r=C3(e,n,t);if(r!==null)return r}for(let n=e.length-1;n>=0;--n)if(e[n]===`[`&&!y4(e,n)){let r=T3(e,n,t);if(r!==null)return r}return e},D3=/^-{1,2}$/,O3=/^[\s]*-{1,2}[\s]+$/,k3=/^={1,2}$/,A3=/^[\s]*={1,2}[\s]+$/,j3=e=>{if(!e||typeof e!=`string`)return e;let t=e.lastIndexOf(`
12821
- `);if(t===-1)return e;let n=e.substring(t+1),r=e.substring(0,t),i=n.trim();if(D3.test(i)&&!n.match(O3)){let t=r.split(`
12822
- `).at(-1);if(t&&t.trim().length>0)return`${e}\u200B`}if(k3.test(i)&&!n.match(A3)){let t=r.split(`
12823
- `).at(-1);if(t&&t.trim().length>0)return`${e}\u200B`}return e},M3=e=>{let t=e.match(j4);if(t){let n=t[2];if(!n||M4.test(n))return e;let r=e.lastIndexOf(t[1]);if(y4(e,r)||S4(e,r))return e;if(e.match(z4)?.length%2==1)return`${e}~~`}else{let t=e.match(R4);if(t){let n=e.lastIndexOf(t[0].slice(0,2));if(y4(e,n)||S4(e,n))return e;if(e.match(z4)?.length%2==1)return`${e}~`}}return e},N3=e=>e!==!1,P3={COMPARISON_OPERATORS:-10,HTML_TAGS:-5,SETEXT_HEADINGS:0,LINKS:10,BOLD_ITALIC:20,BOLD:30,ITALIC_DOUBLE_UNDERSCORE:40,ITALIC_SINGLE_ASTERISK:41,ITALIC_SINGLE_UNDERSCORE:42,INLINE_CODE:50,STRIKETHROUGH:60,KATEX:70,DEFAULT:100},F3=[{handler:{name:`comparisonOperators`,handle:w4,priority:P3.COMPARISON_OPERATORS},optionKey:`comparisonOperators`},{handler:{name:`htmlTags`,handle:h3,priority:P3.HTML_TAGS},optionKey:`htmlTags`},{handler:{name:`setextHeadings`,handle:j3,priority:P3.SETEXT_HEADINGS},optionKey:`setextHeadings`},{handler:{name:`links`,handle:E3,priority:P3.LINKS},optionKey:`links`,earlyReturn:e=>e.endsWith(`](streamdown:incomplete-link)`)},{handler:{name:`boldItalic`,handle:p3,priority:P3.BOLD_ITALIC},optionKey:`boldItalic`},{handler:{name:`bold`,handle:n3,priority:P3.BOLD},optionKey:`bold`},{handler:{name:`italicDoubleUnderscore`,handle:i3,priority:P3.ITALIC_DOUBLE_UNDERSCORE},optionKey:`italic`},{handler:{name:`italicSingleAsterisk`,handle:o3,priority:P3.ITALIC_SINGLE_ASTERISK},optionKey:`italic`},{handler:{name:`italicSingleUnderscore`,handle:u3,priority:P3.ITALIC_SINGLE_UNDERSCORE},optionKey:`italic`},{handler:{name:`inlineCode`,handle:v3,priority:P3.INLINE_CODE},optionKey:`inlineCode`},{handler:{name:`strikethrough`,handle:M3,priority:P3.STRIKETHROUGH},optionKey:`strikethrough`},{handler:{name:`katex`,handle:S3,priority:P3.KATEX},optionKey:`katex`}],I3=e=>{let t=e?.linkMode??`protocol`;return F3.filter(({handler:t,optionKey:n})=>t.name===`links`?N3(e?.links)||N3(e?.images):N3(e?.[n])).map(({handler:e,earlyReturn:n})=>e.name===`links`?{handler:v4(_4({},e),{handle:e=>E3(e,t)}),earlyReturn:t===`protocol`?n:void 0}:{handler:e,earlyReturn:n})},L3=(e,t)=>{if(!e||typeof e!=`string`)return e;let n=e.endsWith(` `)&&!e.endsWith(` `)?e.slice(0,-1):e,r=I3(t),i=(t?.handlers??[]).map(e=>({handler:v4(_4({},e),{priority:e.priority??P3.DEFAULT}),earlyReturn:void 0})),a=[...r,...i].sort((e,t)=>(e.handler.priority??0)-(t.handler.priority??0));for(let{handler:e,earlyReturn:t}of a)if(n=e.handle(n),t!=null&&t(n))return n;return n};function R3(e){if(!e)return!1;let t=e.toLowerCase().trim();return t===`mermaid`||t===`mmd`}function z3(e){try{return KV(e)}catch{return null}}function B3({children:e,language:t}){if(R3(t)){let t=z3(e||``);if(t!==null)return(0,X.jsx)(Q,{paddingX:1,flexDirection:`row`,alignSelf:`flex-start`,children:(0,X.jsx)($,{children:t})})}let n=e;if(t&&(0,OK.supportsLanguage)(t))try{n=(0,OK.highlight)(e||``,{language:t})}catch{}return(0,X.jsx)(Q,{paddingX:1,flexDirection:`row`,alignSelf:`flex-start`,children:(0,X.jsx)($,{children:n})})}B3.displayName=`CodeBlock`;function V3({href:e,children:t}){let{colors:n}=RL(),r=`\x1b]8;;${e}\x07`;return(0,X.jsx)($,{color:n.link,underline:!0,transform:e=>`${r}${e}]8;;`,children:t})}V3.displayName=`Link`;function H3(e){return`text`in e&&typeof e.text==`string`?e.text:`tokens`in e&&Array.isArray(e.tokens)?e.tokens.map(e=>H3(e)).join(``):``}function U3(e){return`checked`in e&&typeof e.checked==`boolean`}function W3(e,t,n=!1){return e?e.map((e,r)=>(0,X.jsx)(Z.Fragment,{children:G3(e,t,n)},r)):null}function G3(e,t,n=!1){let r=e=>n?(0,X.jsx)($,{dimColor:!0,italic:!0,children:e}):e;switch(e.type){case`strong`:return(0,X.jsx)($,{bold:!0,children:W3(e.tokens,t,n)});case`em`:return(0,X.jsx)($,{italic:!0,children:W3(e.tokens,t,n)});case`del`:return(0,X.jsx)($,{strikethrough:!0,children:W3(e.tokens,t,n)});case`codespan`:return r((0,X.jsx)($,{color:t.primary,dimColor:!0,children:e.text}));case`link`:return r((0,X.jsx)(V3,{href:e.href,children:H3(e)}));case`image`:{let t=e,n=t.text||t.href;return r((0,X.jsxs)($,{dimColor:!0,children:[n,` `,t.href!==n&&`(${t.href})`]}))}case`checkbox`:{let n=U3(e)&&e.checked===!0;return r((0,X.jsx)($,{color:t.secondary,children:n?`[✓]`:`[ ]`}))}case`text`:return e.tokens?W3(e.tokens,t,n):r(e.text);case`br`:return`
12824
- `;default:return r(H3(e))}}function K3(e,t,n=0,r=!1){switch(e.type){case`heading`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{bold:!0,color:e.depth<=2?t.primary:t.secondary,dimColor:e.depth>2,children:W3(e.tokens,t,r)})},`heading-${e.depth}`);case`paragraph`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:W3(e.tokens,t,r)})},`paragraph`);case`code`:return(0,X.jsx)(B3,{language:e.lang,children:e.text},`code`);case`blockquote`:return(0,X.jsx)(Q,{borderRight:!1,borderTop:!1,borderBottom:!1,borderStyle:`double`,borderColor:t.border,paddingLeft:1,flexDirection:`column`,children:e.tokens?.map((e,r)=>(0,X.jsx)(Q,{children:K3(e,t,n,!0)},r))},`blockquote`);case`list`:return(0,X.jsx)(Q,{flexDirection:`column`,children:e.items.map((i,a)=>{let o=e.ordered?(Number(e.start)||1)+a:null,s=i.task===!0,c=i.checked===!0,l=i.tokens?.filter(e=>e.type!==`checkbox`)||[];return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:t.secondary,dimColor:!0,children:s?c?`[✓] `:`[ ] `:o===null?`• `:`${o}. `}),(0,X.jsx)(Q,{flexGrow:1,flexDirection:`column`,children:l.map((e,i)=>(0,X.jsx)(Q,{children:K3(e,t,n+1,r)},i))})]},a)})},`list`);case`table`:{let n=e,i=n.header.map((e,t)=>{let r=H3(e).length;for(let e of n.rows)r=Math.max(r,H3(e[t]).length);return Math.max(r,3)});return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{flexDirection:`row`,borderTop:!1,borderLeft:!1,borderRight:!1,borderStyle:`single`,borderColor:t.border,alignSelf:`flex-start`,children:n.header.map((e,a)=>{let o=n.align?.[a]||null;return(0,X.jsx)(Q,{width:i[a]+2,paddingX:1,justifyContent:o===`center`?`center`:o===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{bold:!0,color:t.primary,children:W3(e.tokens,t,r)})},a)})}),n.rows.map((e,a)=>(0,X.jsx)(Q,{flexDirection:`row`,children:e.map((e,a)=>{let o=n.align?.[a]||null;return(0,X.jsx)(Q,{width:i[a]+2,paddingX:1,justifyContent:o===`center`?`center`:o===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{children:W3(e.tokens,t,r)})},a)})},a))]},`table`)}case`hr`:return(0,X.jsx)(Q,{children:(0,X.jsx)($,{dimColor:!0,children:`─`.repeat(50)})},`hr`);case`space`:return null;default:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:G3(e,t,r)})})}}function q3({children:e}){let{colors:t}=RL(),n=(0,Z.useDeferredValue)(e),r=e!==n,i=(0,Z.useMemo)(()=>{try{let e=L3(n);return l4.lexer(e,{gfm:!0,breaks:!0})}catch{return[]}},[n]),a=(0,Z.useMemo)(()=>{let e=[],n=i.length;return i.forEach((r,i)=>{let a=i===n-1;if(r.type===`space`){e.push((0,X.jsx)(Q,{height:1},`space-${i}`));return}e.push((0,X.jsx)(Q,{flexDirection:`column`,children:K3(r,t)},i)),r.type===`heading`&&!a&&e.push((0,X.jsx)(Q,{height:1},`heading-space-${i}`))}),e},[i,t]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[r&&(0,X.jsx)(Q,{children:(0,X.jsx)($,{dimColor:!0,children:`Rendering markdown...`})}),a]})}q3.displayName=`Markdown`;const J3=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming.adventuring.assembling.ballooning.befriending.blinking.blossoming.browsing.burrowing.capering.cartwheeling.celebrating.charging.cheering.chuckling.clambering.clapping.climbing.confettifying.connecting.contemplating.cuddling.curating.dabbling.daydreaming.delighting.detecting.doodling.doodling.drizzling.echoing.edging.elucidating.fiddling.flapping.flickering.flipping.formulating.gallivanting.gamboling.gesticulating.harmonizing.hiding.hitchhiking.hopping.illuminating.investigating.jamming.kaleidoscoping.leapfrogging.levitating.listening.lounging.marveling.mimicking.murmuring.mystifying.narrating.nestling.nuzzling.orchestrating.peeking.perambulating.perusing.pirouetting.plopping.poking.prepping.processing.purring.questing.quipping.quizzing.rambling.relishing.reveling.romping.scampering.scanning.scheming.scribbling.shuffling.skedaddling.snoozing.snuggling.spinning.squeaking.squirming.stalking.star-jumping.strolling.swirling.tapping.tasting.tiptoeing.toddling.traversing.tripping.tuning.unfolding.unraveling.updating.vibing.wandering.whirling.whizzing.wiggling.winking.wobbling.wondering.yodeling.yondering.zipping.zizzling.zoning`.split(`.`);function Y3(e){return e.charAt(0).toUpperCase()+e.slice(1)}function X3(){return J3[Math.floor(Math.random()*J3.length)]}var Z3=class{startTime;constructor(){this.startTime=performance.now()}getElapsedSeconds(){return(performance.now()-this.startTime)/1e3}getElapsedMs(){return performance.now()-this.startTime}getFormattedDuration(){return Q3(this.getElapsedMs())}reset(){this.startTime=performance.now()}};function Q3(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=[];return n>0&&a.push(`${n}h`),r>0&&a.push(`${r}m`),(i>0||a.length===0)&&a.push(`${i}s`),a.join(` `)}function $3(e){let t=aQ[e.name];if(!t)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)($,{color:`red`,children:[`Unknown tool: `,e.name]})});let n;n=e.result?.rejected?(()=>{try{return JSON.parse(e.result.content)}catch{return{}}})().reason===`interrupted`?`interrupted`:`rejected`:e.result?`success`:e.parsedResult?.phase===`error`?`error`:`executing`;let r=e.input??{},i=``;try{i=t.getHeaderParams(r)}catch{}try{return t.renderUI(r,n,e.parsedResult,e.displayData)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`Error rendering tool ${e.name}:`,r),(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:t.displayName,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error rendering tool`})]})}}const e6=(0,Z.memo)(({char:e,color:t})=>{let[n,r]=(0,Z.useState)(!0);return(0,Z.useEffect)(()=>{let e=setInterval(()=>{(0,Z.startTransition)(()=>{r(e=>!e)})},500);return()=>clearInterval(e)},[]),(0,X.jsx)($,{color:t,children:n?e:` `})});e6.displayName=`BlinkingIndicator`;const t6=(0,Z.memo)(e=>{let{type:t,segment:n,isSpinny:r=!1,source:i}=e;if(t!==`text`)throw Error(`Can only render text segments, got ${t}`);let a=(0,Z.useMemo)(()=>VQ(n),[n]);return a?.trim()?i===`user`?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`❯`}),(0,X.jsx)($,{dimColor:!0,italic:!0,children:a})]}):r?(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:(0,X.jsx)(_1,{text:a})}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`⏺`}),(0,X.jsx)(q3,{children:a.trimStart()})]})}):null});t6.displayName=`TextSegment`;const n6=(0,Z.memo)(e=>{let{segment:t,thinkingStartTime:n,thinkingEndTime:r}=e,{colors:i}=RL(),a=(0,Z.useMemo)(()=>VQ(t),[t]),o=(0,Z.useMemo)(()=>n&&r?`thought for ${Q3(r-n)}`:null,[n,r]);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`flex-start`,children:[(0,X.jsx)($,{color:i.textSubtle,children:`✳`}),(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[o&&(0,X.jsxs)($,{dimColor:!0,children:[`(`,o,`)`]}),a&&(0,X.jsx)($,{color:i.textSubtle,wrap:`wrap`,children:a})]})]})});n6.displayName=`ExpandedThinkingSegment`;const r6=5e3,i6=(0,Z.memo)(e=>{let{isSpinny:t=!1,thinkingStartTime:n,thinkingEndTime:r}=e,[i,a]=(0,Z.useState)(performance.now()),[o,s]=(0,Z.useState)(!1);if((0,Z.useEffect)(()=>{if(!t||!n)return;let e=setInterval(()=>{(0,Z.startTransition)(()=>a(performance.now()))},1e3);return()=>clearInterval(e)},[t,n]),(0,Z.useEffect)(()=>{if(t||!r)return;let e=setTimeout(()=>s(!0),2e3);return()=>clearTimeout(e)},[t,r]),o)return null;let c=(0,Z.useMemo)(()=>{if(t){if(!n)return`thinking...`;let e=i-n;return e<r6?`thinking...`:`thinking for ${Q3(e)}`}if(n&&r){let e=r-n;return e<r6?`thought`:`thought for ${Q3(e)}`}return`thinking...`},[n,r,t,i]);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`flex-start`,children:[t?(0,X.jsx)(e6,{char:`●`,color:`cyan`}):(0,X.jsx)($,{color:`green`,children:`●`}),(0,X.jsx)($,{dimColor:!0,children:c})]})});i6.displayName=`ThinkingSegment`;const a6=(0,Z.memo)(e=>{let{toolUseRequest:t,toolUseResult:n,toolDisplayData:r,parsedResult:i}=e;return t?Array.isArray(t)?(0,X.jsx)(X.Fragment,{children:t.map((e,t)=>(0,X.jsx)($3,{...e,result:n,displayData:r,parsedResult:i},e.id??t))}):(0,X.jsx)($3,{...t,result:n,displayData:r,parsedResult:i}):null});a6.displayName=`ToolCallSegment`;const o6=(0,Z.memo)(e=>{let{type:t,segment:n,title:r,isSpinny:i=!1}=e,{colors:a}=RL(),o=(0,Z.useRef)(X3());if(t!==`collapsible_component`)throw Error(`Can only render collapsible component segments, got ${t}`);let s=(0,Z.useMemo)(()=>VQ(n),[n]);if(!s&&!r)throw Error(`Collapsible component segment must have content or title`);let c=r||Y3(o.current);return(0,X.jsxs)(Q,{borderStyle:s?`single`:void 0,borderColor:a.border,flexDirection:`column`,alignItems:`flex-start`,gap:1,children:[c&&(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:i?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(_1,{text:`${c}...`}),(0,X.jsx)($,{dimColor:!0,children:`(esc to interrupt)`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)($,{color:a.textMuted,children:c})]})}),s&&(0,X.jsx)(q3,{children:s})]})});o6.displayName=`CollapsibleComponentSegment`;const s6=(0,Z.memo)(e=>{let{type:t,message:n,severity:r=`info`,actions:i,flashKey:a}=e,{colors:o}=RL();if(t!==`code_llm_notification`)throw Error(`Can only render notification segments, got ${t}`);let[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(a);if((0,Z.useEffect)(()=>{if(a!==l.current&&a!=null){l.current=a,c(!0);let e=setTimeout(()=>c(!1),600);return()=>clearTimeout(e)}},[a]),!n)throw Error(`Notification segment must have message`);let u=(0,Z.useMemo)(()=>r===`info`||r===`success`||r===`error`||r===`warning`?r:`info`,[r]),d=(0,Z.useMemo)(()=>{switch(u){case`info`:return o.info;case`success`:return o.success;case`warning`:return o.warning;case`error`:return o.error;default:return o.info}},[u,o]),f=e=>e.replace(/_/g,` `).replace(/([A-Z])/g,` $1`).trim().split(` `).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(` `),p=(0,Z.useMemo)(()=>(i||[]).filter(e=>e.link),[i]);return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:d,children:s?`◉`:`●`}),(0,X.jsx)($,{color:d,bold:s,inverse:s,children:s?` ${n} `:n})]}),p.length>0&&(0,X.jsx)(Q,{marginLeft:2,flexDirection:`row`,gap:1,children:p.map((e,t)=>(0,X.jsxs)(Z.Fragment,{children:[t>0&&(0,X.jsx)($,{children:` | `}),(0,X.jsx)($,{color:`cyan`,underline:!0,children:f(e.type)})]},t))})]})});s6.displayName=`NotificationSegment`;const c6=(0,Z.memo)(({segment:e})=>{switch(e.type){case`text`:return(0,X.jsx)(t6,{...e});case`thinking`:return(0,X.jsx)(i6,{...e});case`code_llm_tool_call`:return(0,X.jsx)(a6,{...e});case`collapsible_component`:return(0,X.jsx)(o6,{...e});case`code_llm_agent_tool_request`:return(0,X.jsx)(a6,{...e});case`code_llm_notification`:return(0,X.jsx)(s6,{...e});default:return null}});c6.displayName=`SegmentBase`;function l6(e,t){return(0,X.jsx)(s6,{id:`error-fallback`,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:`error`})}function u6({segment:e}){return(0,X.jsx)(k0,{fallback:l6,children:(0,X.jsx)(c6,{segment:e})})}const d6=(0,Z.memo)(({snapshot:e,onClose:t})=>{let{colors:n}=RL();return sI((e,n)=>{(n.ctrl||n.super)&&e===`o`&&t(),n.escape&&t()}),(0,X.jsxs)(Q,{flexDirection:`column`,gap:1,children:[(0,X.jsx)(Q,{flexDirection:`column`,gap:1,paddingBottom:1,width:`95%`,children:(0,Z.useMemo)(()=>e.filter(e=>!e.temp&&!e.isSpinny),[e]).map(e=>(0,X.jsx)(f6,{segment:e},e.id))}),(0,X.jsxs)(Q,{borderStyle:`single`,borderColor:n.border,paddingLeft:1,paddingRight:1,flexDirection:`row`,gap:2,children:[(0,X.jsx)($,{color:n.textMuted,children:`expanded view`}),(0,X.jsx)($,{dimColor:!0,children:`ctrl+o or esc to collapse`})]})]})});d6.displayName=`ExpandedView`;const f6=(0,Z.memo)(({segment:e})=>e.type===`thinking`?(0,X.jsx)(n6,{...e}):(0,X.jsx)(u6,{segment:e}));f6.displayName=`ExpandedSegment`;var p6=W(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self,n.tinycolor=r())})(e,(function(){function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}var t=/^\s+/,n=/\s+$/;function r(e,t){if(e||=``,t||={},e instanceof r)return e;if(!(this instanceof r))return new r(e,t);var n=i(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}r.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(e.r*299+e.g*587+e.b*114)/1e3},getLuminance:function(){var e=this.toRgb(),t=e.r/255,n=e.g/255,r=e.b/255,i=t<=.03928?t/12.92:((t+.055)/1.055)**2.4,a=n<=.03928?n/12.92:((n+.055)/1.055)**2.4,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4;return .2126*i+.7152*a+.0722*o},setAlpha:function(e){return this._a=O(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=c(this._r,this._g,this._b);return{h:e.h*360,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=c(this._r,this._g,this._b),t=Math.round(e.h*360),n=Math.round(e.s*100),r=Math.round(e.v*100);return this._a==1?`hsv(`+t+`, `+n+`%, `+r+`%)`:`hsva(`+t+`, `+n+`%, `+r+`%, `+this._roundA+`)`},toHsl:function(){var e=o(this._r,this._g,this._b);return{h:e.h*360,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=o(this._r,this._g,this._b),t=Math.round(e.h*360),n=Math.round(e.s*100),r=Math.round(e.l*100);return this._a==1?`hsl(`+t+`, `+n+`%, `+r+`%)`:`hsla(`+t+`, `+n+`%, `+r+`%, `+this._roundA+`)`},toHex:function(e){return u(this._r,this._g,this._b,e)},toHexString:function(e){return`#`+this.toHex(e)},toHex8:function(e){return d(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return`#`+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return this._a==1?`rgb(`+Math.round(this._r)+`, `+Math.round(this._g)+`, `+Math.round(this._b)+`)`:`rgba(`+Math.round(this._r)+`, `+Math.round(this._g)+`, `+Math.round(this._b)+`, `+this._roundA+`)`},toPercentageRgb:function(){return{r:Math.round(k(this._r,255)*100)+`%`,g:Math.round(k(this._g,255)*100)+`%`,b:Math.round(k(this._b,255)*100)+`%`,a:this._a}},toPercentageRgbString:function(){return this._a==1?`rgb(`+Math.round(k(this._r,255)*100)+`%, `+Math.round(k(this._g,255)*100)+`%, `+Math.round(k(this._b,255)*100)+`%)`:`rgba(`+Math.round(k(this._r,255)*100)+`%, `+Math.round(k(this._g,255)*100)+`%, `+Math.round(k(this._b,255)*100)+`%, `+this._roundA+`)`},toName:function(){return this._a===0?`transparent`:this._a<1?!1:E[u(this._r,this._g,this._b,!0)]||!1},toFilter:function(e){var t=`#`+f(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?`GradientType = 1, `:``;if(e){var a=r(e);n=`#`+f(a._r,a._g,a._b,a._a)}return`progid:DXImageTransform.Microsoft.gradient(`+i+`startColorstr=`+t+`,endColorstr=`+n+`)`},toString:function(e){var t=!!e;e||=this._format;var n=!1,r=this._a<1&&this._a>=0;return!t&&r&&(e===`hex`||e===`hex6`||e===`hex3`||e===`hex4`||e===`hex8`||e===`name`)?e===`name`&&this._a===0?this.toName():this.toRgbString():(e===`rgb`&&(n=this.toRgbString()),e===`prgb`&&(n=this.toPercentageRgbString()),(e===`hex`||e===`hex6`)&&(n=this.toHexString()),e===`hex3`&&(n=this.toHexString(!0)),e===`hex4`&&(n=this.toHex8String(!0)),e===`hex8`&&(n=this.toHex8String()),e===`name`&&(n=this.toName()),e===`hsl`&&(n=this.toHslString()),e===`hsv`&&(n=this.toHsvString()),n||this.toHexString())},clone:function(){return r(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(g,arguments)},brighten:function(){return this._applyModification(_,arguments)},darken:function(){return this._applyModification(v,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(m,arguments)},greyscale:function(){return this._applyModification(h,arguments)},spin:function(){return this._applyModification(y,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(C,arguments)},complement:function(){return this._applyCombination(b,arguments)},monochromatic:function(){return this._applyCombination(w,arguments)},splitcomplement:function(){return this._applyCombination(S,arguments)},triad:function(){return this._applyCombination(x,[3])},tetrad:function(){return this._applyCombination(x,[4])}},r.fromRatio=function(t,n){if(e(t)==`object`){var i={};for(var a in t)t.hasOwnProperty(a)&&(a===`a`?i[a]=t[a]:i[a]=F(t[a]));t=i}return r(t,n)};function i(t){var n={r:0,g:0,b:0},r=1,i=null,o=null,c=null,u=!1,d=!1;return typeof t==`string`&&(t=B(t)),e(t)==`object`&&(z(t.r)&&z(t.g)&&z(t.b)?(n=a(t.r,t.g,t.b),u=!0,d=String(t.r).substr(-1)===`%`?`prgb`:`rgb`):z(t.h)&&z(t.s)&&z(t.v)?(i=F(t.s),o=F(t.v),n=l(t.h,i,o),u=!0,d=`hsv`):z(t.h)&&z(t.s)&&z(t.l)&&(i=F(t.s),c=F(t.l),n=s(t.h,i,c),u=!0,d=`hsl`),t.hasOwnProperty(`a`)&&(r=t.a)),r=O(r),{ok:u,format:t.format||d,r:Math.min(255,Math.max(n.r,0)),g:Math.min(255,Math.max(n.g,0)),b:Math.min(255,Math.max(n.b,0)),a:r}}function a(e,t,n){return{r:k(e,255)*255,g:k(t,255)*255,b:k(n,255)*255}}function o(e,t,n){e=k(e,255),t=k(t,255),n=k(n,255);var r=Math.max(e,t,n),i=Math.min(e,t,n),a,o,s=(r+i)/2;if(r==i)a=o=0;else{var c=r-i;switch(o=s>.5?c/(2-r-i):c/(r+i),r){case e:a=(t-n)/c+(t<n?6:0);break;case t:a=(n-e)/c+2;break;case n:a=(e-t)/c+4;break}a/=6}return{h:a,s:o,l:s}}function s(e,t,n){var r,i,a;e=k(e,360),t=k(t,100),n=k(n,100);function o(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(t===0)r=i=a=n;else{var s=n<.5?n*(1+t):n+t-n*t,c=2*n-s;r=o(c,s,e+1/3),i=o(c,s,e),a=o(c,s,e-1/3)}return{r:r*255,g:i*255,b:a*255}}function c(e,t,n){e=k(e,255),t=k(t,255),n=k(n,255);var r=Math.max(e,t,n),i=Math.min(e,t,n),a,o,s=r,c=r-i;if(o=r===0?0:c/r,r==i)a=0;else{switch(r){case e:a=(t-n)/c+(t<n?6:0);break;case t:a=(n-e)/c+2;break;case n:a=(e-t)/c+4;break}a/=6}return{h:a,s:o,v:s}}function l(e,t,n){e=k(e,360)*6,t=k(t,100),n=k(n,100);var r=Math.floor(e),i=e-r,a=n*(1-t),o=n*(1-i*t),s=n*(1-(1-i)*t),c=r%6,l=[n,o,a,a,s,n][c],u=[s,n,n,o,a,a][c],d=[a,a,s,n,n,o][c];return{r:l*255,g:u*255,b:d*255}}function u(e,t,n,r){var i=[P(Math.round(e).toString(16)),P(Math.round(t).toString(16)),P(Math.round(n).toString(16))];return r&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join(``)}function d(e,t,n,r,i){var a=[P(Math.round(e).toString(16)),P(Math.round(t).toString(16)),P(Math.round(n).toString(16)),P(I(r))];return i&&a[0].charAt(0)==a[0].charAt(1)&&a[1].charAt(0)==a[1].charAt(1)&&a[2].charAt(0)==a[2].charAt(1)&&a[3].charAt(0)==a[3].charAt(1)?a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0)+a[3].charAt(0):a.join(``)}function f(e,t,n,r){return[P(I(r)),P(Math.round(e).toString(16)),P(Math.round(t).toString(16)),P(Math.round(n).toString(16))].join(``)}r.equals=function(e,t){return!e||!t?!1:r(e).toRgbString()==r(t).toRgbString()},r.random=function(){return r.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})};function p(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.s-=t/100,n.s=A(n.s),r(n)}function m(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.s+=t/100,n.s=A(n.s),r(n)}function h(e){return r(e).desaturate(100)}function g(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.l+=t/100,n.l=A(n.l),r(n)}function _(e,t){t=t===0?0:t||10;var n=r(e).toRgb();return n.r=Math.max(0,Math.min(255,n.r-Math.round(255*-(t/100)))),n.g=Math.max(0,Math.min(255,n.g-Math.round(255*-(t/100)))),n.b=Math.max(0,Math.min(255,n.b-Math.round(255*-(t/100)))),r(n)}function v(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.l-=t/100,n.l=A(n.l),r(n)}function y(e,t){var n=r(e).toHsl(),i=(n.h+t)%360;return n.h=i<0?360+i:i,r(n)}function b(e){var t=r(e).toHsl();return t.h=(t.h+180)%360,r(t)}function x(e,t){if(isNaN(t)||t<=0)throw Error(`Argument to polyad must be a positive number`);for(var n=r(e).toHsl(),i=[r(e)],a=360/t,o=1;o<t;o++)i.push(r({h:(n.h+o*a)%360,s:n.s,l:n.l}));return i}function S(e){var t=r(e).toHsl(),n=t.h;return[r(e),r({h:(n+72)%360,s:t.s,l:t.l}),r({h:(n+216)%360,s:t.s,l:t.l})]}function C(e,t,n){t||=6,n||=30;var i=r(e).toHsl(),a=360/n,o=[r(e)];for(i.h=(i.h-(a*t>>1)+720)%360;--t;)i.h=(i.h+a)%360,o.push(r(i));return o}function w(e,t){t||=6;for(var n=r(e).toHsv(),i=n.h,a=n.s,o=n.v,s=[],c=1/t;t--;)s.push(r({h:i,s:a,v:o})),o=(o+c)%1;return s}r.mix=function(e,t,n){n=n===0?0:n||50;var i=r(e).toRgb(),a=r(t).toRgb(),o=n/100;return r({r:(a.r-i.r)*o+i.r,g:(a.g-i.g)*o+i.g,b:(a.b-i.b)*o+i.b,a:(a.a-i.a)*o+i.a})},r.readability=function(e,t){var n=r(e),i=r(t);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},r.isReadable=function(e,t,n){var i=r.readability(e,t),a,o=!1;switch(a=V(n),a.level+a.size){case`AAsmall`:case`AAAlarge`:o=i>=4.5;break;case`AAlarge`:o=i>=3;break;case`AAAsmall`:o=i>=7;break}return o},r.mostReadable=function(e,t,n){var i=null,a=0,o,s,c,l;n||={},s=n.includeFallbackColors,c=n.level,l=n.size;for(var u=0;u<t.length;u++)o=r.readability(e,t[u]),o>a&&(a=o,i=r(t[u]));return r.isReadable(e,i,{level:c,size:l})||!s?i:(n.includeFallbackColors=!1,r.mostReadable(e,[`#fff`,`#000`],n))};var T=r.names={aliceblue:`f0f8ff`,antiquewhite:`faebd7`,aqua:`0ff`,aquamarine:`7fffd4`,azure:`f0ffff`,beige:`f5f5dc`,bisque:`ffe4c4`,black:`000`,blanchedalmond:`ffebcd`,blue:`00f`,blueviolet:`8a2be2`,brown:`a52a2a`,burlywood:`deb887`,burntsienna:`ea7e5d`,cadetblue:`5f9ea0`,chartreuse:`7fff00`,chocolate:`d2691e`,coral:`ff7f50`,cornflowerblue:`6495ed`,cornsilk:`fff8dc`,crimson:`dc143c`,cyan:`0ff`,darkblue:`00008b`,darkcyan:`008b8b`,darkgoldenrod:`b8860b`,darkgray:`a9a9a9`,darkgreen:`006400`,darkgrey:`a9a9a9`,darkkhaki:`bdb76b`,darkmagenta:`8b008b`,darkolivegreen:`556b2f`,darkorange:`ff8c00`,darkorchid:`9932cc`,darkred:`8b0000`,darksalmon:`e9967a`,darkseagreen:`8fbc8f`,darkslateblue:`483d8b`,darkslategray:`2f4f4f`,darkslategrey:`2f4f4f`,darkturquoise:`00ced1`,darkviolet:`9400d3`,deeppink:`ff1493`,deepskyblue:`00bfff`,dimgray:`696969`,dimgrey:`696969`,dodgerblue:`1e90ff`,firebrick:`b22222`,floralwhite:`fffaf0`,forestgreen:`228b22`,fuchsia:`f0f`,gainsboro:`dcdcdc`,ghostwhite:`f8f8ff`,gold:`ffd700`,goldenrod:`daa520`,gray:`808080`,green:`008000`,greenyellow:`adff2f`,grey:`808080`,honeydew:`f0fff0`,hotpink:`ff69b4`,indianred:`cd5c5c`,indigo:`4b0082`,ivory:`fffff0`,khaki:`f0e68c`,lavender:`e6e6fa`,lavenderblush:`fff0f5`,lawngreen:`7cfc00`,lemonchiffon:`fffacd`,lightblue:`add8e6`,lightcoral:`f08080`,lightcyan:`e0ffff`,lightgoldenrodyellow:`fafad2`,lightgray:`d3d3d3`,lightgreen:`90ee90`,lightgrey:`d3d3d3`,lightpink:`ffb6c1`,lightsalmon:`ffa07a`,lightseagreen:`20b2aa`,lightskyblue:`87cefa`,lightslategray:`789`,lightslategrey:`789`,lightsteelblue:`b0c4de`,lightyellow:`ffffe0`,lime:`0f0`,limegreen:`32cd32`,linen:`faf0e6`,magenta:`f0f`,maroon:`800000`,mediumaquamarine:`66cdaa`,mediumblue:`0000cd`,mediumorchid:`ba55d3`,mediumpurple:`9370db`,mediumseagreen:`3cb371`,mediumslateblue:`7b68ee`,mediumspringgreen:`00fa9a`,mediumturquoise:`48d1cc`,mediumvioletred:`c71585`,midnightblue:`191970`,mintcream:`f5fffa`,mistyrose:`ffe4e1`,moccasin:`ffe4b5`,navajowhite:`ffdead`,navy:`000080`,oldlace:`fdf5e6`,olive:`808000`,olivedrab:`6b8e23`,orange:`ffa500`,orangered:`ff4500`,orchid:`da70d6`,palegoldenrod:`eee8aa`,palegreen:`98fb98`,paleturquoise:`afeeee`,palevioletred:`db7093`,papayawhip:`ffefd5`,peachpuff:`ffdab9`,peru:`cd853f`,pink:`ffc0cb`,plum:`dda0dd`,powderblue:`b0e0e6`,purple:`800080`,rebeccapurple:`663399`,red:`f00`,rosybrown:`bc8f8f`,royalblue:`4169e1`,saddlebrown:`8b4513`,salmon:`fa8072`,sandybrown:`f4a460`,seagreen:`2e8b57`,seashell:`fff5ee`,sienna:`a0522d`,silver:`c0c0c0`,skyblue:`87ceeb`,slateblue:`6a5acd`,slategray:`708090`,slategrey:`708090`,snow:`fffafa`,springgreen:`00ff7f`,steelblue:`4682b4`,tan:`d2b48c`,teal:`008080`,thistle:`d8bfd8`,tomato:`ff6347`,turquoise:`40e0d0`,violet:`ee82ee`,wheat:`f5deb3`,white:`fff`,whitesmoke:`f5f5f5`,yellow:`ff0`,yellowgreen:`9acd32`},E=r.hexNames=D(T);function D(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}function O(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function k(e,t){M(e)&&(e=`100%`);var n=N(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function A(e){return Math.min(1,Math.max(0,e))}function j(e){return parseInt(e,16)}function M(e){return typeof e==`string`&&e.indexOf(`.`)!=-1&&parseFloat(e)===1}function N(e){return typeof e==`string`&&e.indexOf(`%`)!=-1}function P(e){return e.length==1?`0`+e:``+e}function F(e){return e<=1&&(e=e*100+`%`),e}function I(e){return Math.round(parseFloat(e)*255).toString(16)}function L(e){return j(e)/255}var R=function(){var e=`(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)`,t=`[\\s|\\(]+(`+e+`)[,|\\s]+(`+e+`)[,|\\s]+(`+e+`)\\s*\\)?`,n=`[\\s|\\(]+(`+e+`)[,|\\s]+(`+e+`)[,|\\s]+(`+e+`)[,|\\s]+(`+e+`)\\s*\\)?`;return{CSS_UNIT:new RegExp(e),rgb:RegExp(`rgb`+t),rgba:RegExp(`rgba`+n),hsl:RegExp(`hsl`+t),hsla:RegExp(`hsla`+n),hsv:RegExp(`hsv`+t),hsva:RegExp(`hsva`+n),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();function z(e){return!!R.CSS_UNIT.exec(e)}function B(e){e=e.replace(t,``).replace(n,``).toLowerCase();var r=!1;if(T[e])e=T[e],r=!0;else if(e==`transparent`)return{r:0,g:0,b:0,a:0,format:`name`};var i;return(i=R.rgb.exec(e))?{r:i[1],g:i[2],b:i[3]}:(i=R.rgba.exec(e))?{r:i[1],g:i[2],b:i[3],a:i[4]}:(i=R.hsl.exec(e))?{h:i[1],s:i[2],l:i[3]}:(i=R.hsla.exec(e))?{h:i[1],s:i[2],l:i[3],a:i[4]}:(i=R.hsv.exec(e))?{h:i[1],s:i[2],v:i[3]}:(i=R.hsva.exec(e))?{h:i[1],s:i[2],v:i[3],a:i[4]}:(i=R.hex8.exec(e))?{r:j(i[1]),g:j(i[2]),b:j(i[3]),a:L(i[4]),format:r?`name`:`hex8`}:(i=R.hex6.exec(e))?{r:j(i[1]),g:j(i[2]),b:j(i[3]),format:r?`name`:`hex`}:(i=R.hex4.exec(e))?{r:j(i[1]+``+i[1]),g:j(i[2]+``+i[2]),b:j(i[3]+``+i[3]),a:L(i[4]+``+i[4]),format:r?`name`:`hex8`}:(i=R.hex3.exec(e))?{r:j(i[1]+``+i[1]),g:j(i[2]+``+i[2]),b:j(i[3]+``+i[3]),format:r?`name`:`hex`}:!1}function V(e){var t,n;return e||={level:`AA`,size:`small`},t=(e.level||`AA`).toUpperCase(),n=(e.size||`small`).toLowerCase(),t!==`AA`&&t!==`AAA`&&(t=`AA`),n!==`small`&&n!==`large`&&(n=`small`),{level:t,size:n}}return r}))})),m6=W(((e,t)=>{let n=p6(),r={r:256,g:256,b:256,a:1},i={h:360,s:1,v:1,a:1};function a(e,t,n){let r={};for(let i in e)e.hasOwnProperty(i)&&(r[i]=n===0?0:(t[i]-e[i])/n);return r}function o(e,t,n,r){let i={};for(let a in t)t.hasOwnProperty(a)&&(i[a]=e[a]*n+t[a],i[a]=i[a]<0?i[a]+r[a]:r[a]===1?i[a]:i[a]%r[a]);return i}function s(e,t,i){let s=e.color.toRgb(),c=a(s,t.color.toRgb(),i),l=[e.color];for(let e=1;e<i;e++){let t=o(c,s,e,r);l.push(n(t))}return l}function c(e,t,r,c){let l=e.color.toHsv(),u=t.color.toHsv();if(l.s===0||u.s===0)return s(e,t,r);let d;if(typeof c==`boolean`)d=c;else{let e=l.h<u.h&&u.h-l.h<180||l.h>u.h&&l.h-u.h>180;d=c===`long`&&e||c===`short`&&!e}let f=a(l,u,r),p=[e.color],m;m=l.h<=u.h&&!d||l.h>=u.h&&d?u.h-l.h:d?360-u.h+l.h:360-l.h+u.h,f.h=(-1)**(d?1:0)*Math.abs(m)/r;for(let e=1;e<r;e++){let t=o(f,l,e,i);p.push(n(t))}return p}function l(e,t){let n=e.length;if(t=parseInt(t,10),isNaN(t)||t<2)throw Error(`Invalid number of steps (< 2)`);if(t<n)throw Error(`Number of steps cannot be inferior to number of stops`);let r=[];for(let i=1;i<n;i++){let n=(t-1)*(e[i].pos-e[i-1].pos);r.push(Math.max(1,Math.round(n)))}let i=1;for(let e=n-1;e--;)i+=r[e];for(;i!==t;)if(i<t){let e=Math.min.apply(null,r);r[r.indexOf(e)]++,i++}else{let e=Math.max.apply(null,r);r[r.indexOf(e)]--,i--}return r}function u(e,t,r,i){if(t<0||t>1)throw Error(`Position must be between 0 and 1`);let s,c;for(let n=0,r=e.length;n<r-1;n++)if(t>=e[n].pos&&t<e[n+1].pos){s=e[n],c=e[n+1];break}return s||=c=e[e.length-1],n(o(a(s.color[r](),c.color[r](),(c.pos-s.pos)*100),s.color[r](),(t-s.pos)*100,i))}var d=class e{constructor(e){if(e.length<2)throw Error(`Invalid number of stops (< 2)`);let t=e[0].pos!==void 0,r=e.length,i=-1,a=!1;this.stops=e.map((e,o)=>{let s=e.pos!==void 0;if(t^s)throw Error(`Cannot mix positionned and not posionned color stops`);if(s){let t=e.color!==void 0;if(!t&&(a||o===0||o===r-1))throw Error(`Cannot define two consecutive position-only stops`);if(a=!t,e={color:t?n(e.color):null,colorLess:!t,pos:e.pos},e.pos<0||e.pos>1)throw Error(`Color stops positions must be between 0 and 1`);if(e.pos<i)throw Error(`Color stops positions are not ordered`);i=e.pos}else e={color:n(e.color===void 0?e:e.color),pos:o/(r-1)};return e}),this.stops[0].pos!==0&&(this.stops.unshift({color:this.stops[0].color,pos:0}),r++),this.stops[r-1].pos!==1&&this.stops.push({color:this.stops[r-1].color,pos:1})}reverse(){let t=[];return this.stops.forEach(function(e){t.push({color:e.color,pos:1-e.pos})}),new e(t.reverse())}loop(){let t=[],n=[];return this.stops.forEach(e=>{t.push({color:e.color,pos:e.pos/2})}),this.stops.slice(0,-1).forEach(e=>{n.push({color:e.color,pos:1-e.pos/2})}),new e(t.concat(n.reverse()))}rgb(e){let t=l(this.stops,e),n=[];this.stops.forEach((e,t)=>{e.colorLess&&(e.color=s(this.stops[t-1],this.stops[t+1],2)[1])});for(let e=0,r=this.stops.length;e<r-1;e++){let r=s(this.stops[e],this.stops[e+1],t[e]);n.splice(n.length,0,...r)}return n.push(this.stops[this.stops.length-1].color),n}hsv(e,t){let n=l(this.stops,e),r=[];this.stops.forEach((e,n)=>{e.colorLess&&(e.color=c(this.stops[n-1],this.stops[n+1],2,t)[1])});for(let e=0,i=this.stops.length;e<i-1;e++){let i=c(this.stops[e],this.stops[e+1],n[e],t);r.splice(r.length,0,...i)}return r.push(this.stops[this.stops.length-1].color),r}css(e,t){e||=`linear`,t||=e===`linear`?`to right`:`ellipse at center`;let n=e+`-gradient(`+t;return this.stops.forEach(function(e){n+=`, `+(e.colorLess?``:e.color.toRgbString()+` `)+e.pos*100+`%`}),n+=`)`,n}rgbAt(e){return u(this.stops,e,`toRgb`,r)}hsvAt(e){return u(this.stops,e,`toHsv`,i)}};t.exports=function(e){if(arguments.length===1){if(!Array.isArray(arguments[0]))throw Error(`"stops" is not an array`);e=arguments[0]}else e=Array.prototype.slice.call(arguments);return new d(e)}})),h6=ve({atlas:()=>w6,cristal:()=>T6,default:()=>_6,fruit:()=>j6,instagram:()=>M6,mind:()=>D6,morning:()=>O6,multiline:()=>b6,passion:()=>A6,pastel:()=>I6,rainbow:()=>F6,retro:()=>N6,summer:()=>P6,teen:()=>E6,vice:()=>k6}),g6=be(m6(),1);const _6=(...e)=>{let t,n;if(e.length===0)throw Error(`Missing gradient colors`);if(Array.isArray(e[0]))t=(0,g6.default)(e[0]),n=x6(e[1]);else{if(e.length===1)throw Error(`Expected an array of colors, received ${JSON.stringify(e[0])}`);t=(0,g6.default)(...e)}let r=(e,r)=>y6(e?e.toString():``,t,r??n);return r.multiline=(e,r)=>b6(e?e.toString():``,t,r??n),r},v6=(e,t,n)=>t.interpolation?.toLowerCase()===`hsv`?e.hsv(n,t.hsvSpin?.toLowerCase()||!1):e.rgb(n);function y6(e,t,n){let r=v6(t,x6(n),Math.max(e.replace(/\s/g,``).length,t.stops.length)),i=``;for(let t of e)i+=t.match(/\s/g)?t:NA.hex(r.shift()?.toHex()||`#000`)(t);return i}function b6(e,t,n){let r=x6(n),i=e.split(`
12825
- `),a=v6(t,r,Math.max(...i.map(e=>e.length),t.stops.length)),o=[];for(let e of i){let t=a.slice(0),n=``;for(let r of e)n+=NA.hex(t.shift()?.toHex()||`#000`)(r);o.push(n)}return o.join(`
12826
- `)}function x6(e){let t={interpolation:`rgb`,hsvSpin:`short`,...e};if(e!==void 0&&typeof e!=`object`)throw TypeError(`Expected \`options\` to be an \`object\`, got \`${typeof e}\``);if(typeof t.interpolation!=`string`)throw TypeError(`Expected \`options.interpolation\` to be \`rgb\` or \`hsv\`, got \`${typeof t.interpolation}\``);if(t.interpolation.toLowerCase()===`hsv`&&typeof t.hsvSpin!=`string`)throw TypeError(`Expected \`options.hsvSpin\` to be a \`short\` or \`long\`, got \`${typeof t.hsvSpin}\``);return t}const S6={atlas:{colors:[`#feac5e`,`#c779d0`,`#4bc0c8`],options:{}},cristal:{colors:[`#bdfff3`,`#4ac29a`],options:{}},teen:{colors:[`#77a1d3`,`#79cbca`,`#e684ae`],options:{}},mind:{colors:[`#473b7b`,`#3584a7`,`#30d2be`],options:{}},morning:{colors:[`#ff5f6d`,`#ffc371`],options:{interpolation:`hsv`}},vice:{colors:[`#5ee7df`,`#b490ca`],options:{interpolation:`hsv`}},passion:{colors:[`#f43b47`,`#453a94`],options:{}},fruit:{colors:[`#ff4e50`,`#f9d423`],options:{}},instagram:{colors:[`#833ab4`,`#fd1d1d`,`#fcb045`],options:{}},retro:{colors:[`#3f51b1`,`#5a55ae`,`#7b5fac`,`#8f6aae`,`#a86aa4`,`#cc6b8e`,`#f18271`,`#f3a469`,`#f7c978`],options:{}},summer:{colors:[`#fdbb2d`,`#22c1c3`],options:{}},rainbow:{colors:[`#ff0000`,`#ff0100`],options:{interpolation:`hsv`,hsvSpin:`long`}},pastel:{colors:[`#74ebd5`,`#74ecd5`],options:{interpolation:`hsv`,hsvSpin:`long`}}};function C6(e){let t=t=>_6(...e.colors)(t,e.options);return t.multiline=(t=``)=>_6(...e.colors).multiline(t,e.options),t}const w6=C6(S6.atlas),T6=C6(S6.cristal),E6=C6(S6.teen),D6=C6(S6.mind),O6=C6(S6.morning),k6=C6(S6.vice),A6=C6(S6.passion),j6=C6(S6.fruit),M6=C6(S6.instagram),N6=C6(S6.retro),P6=C6(S6.summer),F6=C6(S6.rainbow),I6=C6(S6.pastel);_6.atlas=w6,_6.cristal=T6,_6.teen=E6,_6.mind=D6,_6.morning=O6,_6.vice=k6,_6.passion=A6,_6.fruit=j6,_6.instagram=M6,_6.retro=N6,_6.summer=P6,_6.rainbow=F6,_6.pastel=I6;const L6=(0,Z.memo)(e=>{let t=(0,Z.useMemo)(()=>e.name?h6[e.name]:_6(...e.colors),[e.name,e.colors]);return(0,X.jsx)($,{transform:e=>t.multiline(KQ(e)),children:e.children})});L6.displayName=`Gradient`;const R6=(0,Z.memo)(()=>{let{width:e}=pQ(),{colors:t}=RL(),n=(0,Z.useMemo)(()=>[t.gradientStart,t.gradientMid,t.gradientEnd],[t]);return e<=50?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,flexWrap:`wrap`,children:[(0,X.jsx)(L6,{colors:n,children:(0,X.jsx)($,{children:`Abacus AI`})}),(0,X.jsxs)($,{color:t.textMuted,children:[`v`,PA]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(L6,{colors:n,children:(0,X.jsx)($,{children:` ▗▄▖ ▗▄▄▖ ▗▄▖ ▗▄▄▖▗▖ ▗▖ ▗▄▄▖ ▗▄▖ ▗▄▄▄▖ ▗▄▄▖▗▖ ▗▄▄▄▖
12820
+ $$`:`${e}$$`},C3=e=>x3(e)%2==0?e:S3(e),w3=(e,t,n)=>{if(e.substring(t+2).includes(`)`))return null;let r=H4(e,t);if(r===-1||b4(e,r))return null;let i=r>0&&e[r-1]===`!`,a=i?r-1:r,o=e.substring(0,a);if(i)return o;let s=e.substring(r+1,t);return n===`text-only`?`${o}${s}`:`${o}[${s}](streamdown:incomplete-link)`},T3=(e,t)=>{for(let n=0;n<t;n++)if(e[n]===`[`&&!b4(e,n)){if(n>0&&e[n-1]===`!`)continue;let t=U4(e,n);if(t===-1)return n;if(t+1<e.length&&e[t+1]===`(`){let r=e.indexOf(`)`,t+2);r!==-1&&(n=r)}}return t},E3=(e,t,n)=>{let r=t>0&&e[t-1]===`!`,i=r?t-1:t;if(!e.substring(t+1).includes(`]`)){let a=e.substring(0,i);if(r)return a;if(n===`text-only`){let n=T3(e,t);return e.substring(0,n)+e.substring(n+1)}return`${e}](streamdown:incomplete-link)`}if(U4(e,t)===-1){let a=e.substring(0,i);if(r)return a;if(n===`text-only`){let n=T3(e,t);return e.substring(0,n)+e.substring(n+1)}return`${e}](streamdown:incomplete-link)`}return null},D3=(e,t=`protocol`)=>{let n=e.lastIndexOf(`](`);if(n!==-1&&!b4(e,n)){let r=w3(e,n,t);if(r!==null)return r}for(let n=e.length-1;n>=0;--n)if(e[n]===`[`&&!b4(e,n)){let r=E3(e,n,t);if(r!==null)return r}return e},O3=/^-{1,2}$/,k3=/^[\s]*-{1,2}[\s]+$/,A3=/^={1,2}$/,j3=/^[\s]*={1,2}[\s]+$/,M3=e=>{if(!e||typeof e!=`string`)return e;let t=e.lastIndexOf(`
12821
+ `);if(t===-1)return e;let n=e.substring(t+1),r=e.substring(0,t),i=n.trim();if(O3.test(i)&&!n.match(k3)){let t=r.split(`
12822
+ `).at(-1);if(t&&t.trim().length>0)return`${e}\u200B`}if(A3.test(i)&&!n.match(j3)){let t=r.split(`
12823
+ `).at(-1);if(t&&t.trim().length>0)return`${e}\u200B`}return e},N3=e=>{let t=e.match(M4);if(t){let n=t[2];if(!n||N4.test(n))return e;let r=e.lastIndexOf(t[1]);if(b4(e,r)||C4(e,r))return e;if(e.match(B4)?.length%2==1)return`${e}~~`}else{let t=e.match(z4);if(t){let n=e.lastIndexOf(t[0].slice(0,2));if(b4(e,n)||C4(e,n))return e;if(e.match(B4)?.length%2==1)return`${e}~`}}return e},P3=e=>e!==!1,F3={COMPARISON_OPERATORS:-10,HTML_TAGS:-5,SETEXT_HEADINGS:0,LINKS:10,BOLD_ITALIC:20,BOLD:30,ITALIC_DOUBLE_UNDERSCORE:40,ITALIC_SINGLE_ASTERISK:41,ITALIC_SINGLE_UNDERSCORE:42,INLINE_CODE:50,STRIKETHROUGH:60,KATEX:70,DEFAULT:100},I3=[{handler:{name:`comparisonOperators`,handle:T4,priority:F3.COMPARISON_OPERATORS},optionKey:`comparisonOperators`},{handler:{name:`htmlTags`,handle:g3,priority:F3.HTML_TAGS},optionKey:`htmlTags`},{handler:{name:`setextHeadings`,handle:M3,priority:F3.SETEXT_HEADINGS},optionKey:`setextHeadings`},{handler:{name:`links`,handle:D3,priority:F3.LINKS},optionKey:`links`,earlyReturn:e=>e.endsWith(`](streamdown:incomplete-link)`)},{handler:{name:`boldItalic`,handle:m3,priority:F3.BOLD_ITALIC},optionKey:`boldItalic`},{handler:{name:`bold`,handle:r3,priority:F3.BOLD},optionKey:`bold`},{handler:{name:`italicDoubleUnderscore`,handle:a3,priority:F3.ITALIC_DOUBLE_UNDERSCORE},optionKey:`italic`},{handler:{name:`italicSingleAsterisk`,handle:s3,priority:F3.ITALIC_SINGLE_ASTERISK},optionKey:`italic`},{handler:{name:`italicSingleUnderscore`,handle:d3,priority:F3.ITALIC_SINGLE_UNDERSCORE},optionKey:`italic`},{handler:{name:`inlineCode`,handle:y3,priority:F3.INLINE_CODE},optionKey:`inlineCode`},{handler:{name:`strikethrough`,handle:N3,priority:F3.STRIKETHROUGH},optionKey:`strikethrough`},{handler:{name:`katex`,handle:C3,priority:F3.KATEX},optionKey:`katex`}],L3=e=>{let t=e?.linkMode??`protocol`;return I3.filter(({handler:t,optionKey:n})=>t.name===`links`?P3(e?.links)||P3(e?.images):P3(e?.[n])).map(({handler:e,earlyReturn:n})=>e.name===`links`?{handler:y4(v4({},e),{handle:e=>D3(e,t)}),earlyReturn:t===`protocol`?n:void 0}:{handler:e,earlyReturn:n})},R3=(e,t)=>{if(!e||typeof e!=`string`)return e;let n=e.endsWith(` `)&&!e.endsWith(` `)?e.slice(0,-1):e,r=L3(t),i=(t?.handlers??[]).map(e=>({handler:y4(v4({},e),{priority:e.priority??F3.DEFAULT}),earlyReturn:void 0})),a=[...r,...i].sort((e,t)=>(e.handler.priority??0)-(t.handler.priority??0));for(let{handler:e,earlyReturn:t}of a)if(n=e.handle(n),t!=null&&t(n))return n;return n};function z3(e){if(!e)return!1;let t=e.toLowerCase().trim();return t===`mermaid`||t===`mmd`}function B3(e){try{return KV(e)}catch{return null}}function V3({children:e,language:t}){if(z3(t)){let t=B3(e||``);if(t!==null)return(0,X.jsx)(Q,{paddingX:1,flexDirection:`row`,alignSelf:`flex-start`,children:(0,X.jsx)($,{children:t})})}let n=e;if(t&&(0,OK.supportsLanguage)(t))try{n=(0,OK.highlight)(e||``,{language:t})}catch{}return(0,X.jsx)(Q,{paddingX:1,flexDirection:`row`,alignSelf:`flex-start`,children:(0,X.jsx)($,{children:n})})}V3.displayName=`CodeBlock`;function H3({href:e,children:t}){let{colors:n}=RL(),r=`\x1b]8;;${e}\x07`;return(0,X.jsx)($,{color:n.link,underline:!0,transform:e=>`${r}${e}]8;;`,children:t})}H3.displayName=`Link`;function U3(e){return`text`in e&&typeof e.text==`string`?e.text:`tokens`in e&&Array.isArray(e.tokens)?e.tokens.map(e=>U3(e)).join(``):``}function W3(e){return`checked`in e&&typeof e.checked==`boolean`}function G3(e,t,n=!1){return e?e.map((e,r)=>(0,X.jsx)(Z.Fragment,{children:K3(e,t,n)},r)):null}function K3(e,t,n=!1){let r=e=>n?(0,X.jsx)($,{dimColor:!0,italic:!0,children:e}):e;switch(e.type){case`strong`:return(0,X.jsx)($,{bold:!0,children:G3(e.tokens,t,n)});case`em`:return(0,X.jsx)($,{italic:!0,children:G3(e.tokens,t,n)});case`del`:return(0,X.jsx)($,{strikethrough:!0,children:G3(e.tokens,t,n)});case`codespan`:return r((0,X.jsx)($,{color:t.primary,dimColor:!0,children:e.text}));case`link`:return r((0,X.jsx)(H3,{href:e.href,children:U3(e)}));case`image`:{let t=e,n=t.text||t.href;return r((0,X.jsxs)($,{dimColor:!0,children:[n,` `,t.href!==n&&`(${t.href})`]}))}case`checkbox`:{let n=W3(e)&&e.checked===!0;return r((0,X.jsx)($,{color:t.secondary,children:n?`[✓]`:`[ ]`}))}case`text`:return e.tokens?G3(e.tokens,t,n):r(e.text);case`br`:return`
12824
+ `;default:return r(U3(e))}}function q3(e,t,n=0,r=!1){switch(e.type){case`heading`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{bold:!0,color:e.depth<=2?t.primary:t.secondary,dimColor:e.depth>2,children:G3(e.tokens,t,r)})},`heading-${e.depth}`);case`paragraph`:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:G3(e.tokens,t,r)})},`paragraph`);case`code`:return(0,X.jsx)(V3,{language:e.lang,children:e.text},`code`);case`blockquote`:return(0,X.jsx)(Q,{borderRight:!1,borderTop:!1,borderBottom:!1,borderStyle:`double`,borderColor:t.border,paddingLeft:1,flexDirection:`column`,children:e.tokens?.map((e,r)=>(0,X.jsx)(Q,{children:q3(e,t,n,!0)},r))},`blockquote`);case`list`:return(0,X.jsx)(Q,{flexDirection:`column`,children:e.items.map((i,a)=>{let o=e.ordered?(Number(e.start)||1)+a:null,s=i.task===!0,c=i.checked===!0,l=i.tokens?.filter(e=>e.type!==`checkbox`)||[];return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:t.secondary,dimColor:!0,children:s?c?`[✓] `:`[ ] `:o===null?`• `:`${o}. `}),(0,X.jsx)(Q,{flexGrow:1,flexDirection:`column`,children:l.map((e,i)=>(0,X.jsx)(Q,{children:q3(e,t,n+1,r)},i))})]},a)})},`list`);case`table`:{let n=e,i=n.header.map((e,t)=>{let r=U3(e).length;for(let e of n.rows)r=Math.max(r,U3(e[t]).length);return Math.max(r,3)});return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(Q,{flexDirection:`row`,borderTop:!1,borderLeft:!1,borderRight:!1,borderStyle:`single`,borderColor:t.border,alignSelf:`flex-start`,children:n.header.map((e,a)=>{let o=n.align?.[a]||null;return(0,X.jsx)(Q,{width:i[a]+2,paddingX:1,justifyContent:o===`center`?`center`:o===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{bold:!0,color:t.primary,children:G3(e.tokens,t,r)})},a)})}),n.rows.map((e,a)=>(0,X.jsx)(Q,{flexDirection:`row`,children:e.map((e,a)=>{let o=n.align?.[a]||null;return(0,X.jsx)(Q,{width:i[a]+2,paddingX:1,justifyContent:o===`center`?`center`:o===`right`?`flex-end`:`flex-start`,children:(0,X.jsx)($,{children:G3(e.tokens,t,r)})},a)})},a))]},`table`)}case`hr`:return(0,X.jsx)(Q,{children:(0,X.jsx)($,{dimColor:!0,children:`─`.repeat(50)})},`hr`);case`space`:return null;default:return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsx)($,{children:K3(e,t,r)})})}}function J3({children:e}){let{colors:t}=RL(),n=(0,Z.useDeferredValue)(e),r=e!==n,i=(0,Z.useMemo)(()=>{try{let e=R3(n);return u4.lexer(e,{gfm:!0,breaks:!0})}catch{return[]}},[n]),a=(0,Z.useMemo)(()=>{let e=[],n=i.length;return i.forEach((r,i)=>{let a=i===n-1;if(r.type===`space`){e.push((0,X.jsx)(Q,{height:1},`space-${i}`));return}e.push((0,X.jsx)(Q,{flexDirection:`column`,children:q3(r,t)},i)),r.type===`heading`&&!a&&e.push((0,X.jsx)(Q,{height:1},`heading-space-${i}`))}),e},[i,t]);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[r&&(0,X.jsx)(Q,{children:(0,X.jsx)($,{dimColor:!0,children:`Rendering markdown...`})}),a]})}J3.displayName=`Markdown`;const Y3=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming.adventuring.assembling.ballooning.befriending.blinking.blossoming.browsing.burrowing.capering.cartwheeling.celebrating.charging.cheering.chuckling.clambering.clapping.climbing.confettifying.connecting.contemplating.cuddling.curating.dabbling.daydreaming.delighting.detecting.doodling.doodling.drizzling.echoing.edging.elucidating.fiddling.flapping.flickering.flipping.formulating.gallivanting.gamboling.gesticulating.harmonizing.hiding.hitchhiking.hopping.illuminating.investigating.jamming.kaleidoscoping.leapfrogging.levitating.listening.lounging.marveling.mimicking.murmuring.mystifying.narrating.nestling.nuzzling.orchestrating.peeking.perambulating.perusing.pirouetting.plopping.poking.prepping.processing.purring.questing.quipping.quizzing.rambling.relishing.reveling.romping.scampering.scanning.scheming.scribbling.shuffling.skedaddling.snoozing.snuggling.spinning.squeaking.squirming.stalking.star-jumping.strolling.swirling.tapping.tasting.tiptoeing.toddling.traversing.tripping.tuning.unfolding.unraveling.updating.vibing.wandering.whirling.whizzing.wiggling.winking.wobbling.wondering.yodeling.yondering.zipping.zizzling.zoning`.split(`.`);function X3(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Z3(){return Y3[Math.floor(Math.random()*Y3.length)]}var Q3=class{startTime;constructor(){this.startTime=performance.now()}getElapsedSeconds(){return(performance.now()-this.startTime)/1e3}getElapsedMs(){return performance.now()-this.startTime}getFormattedDuration(){return $3(this.getElapsedMs())}reset(){this.startTime=performance.now()}};function $3(e){let t=Math.floor(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60,a=[];return n>0&&a.push(`${n}h`),r>0&&a.push(`${r}m`),(i>0||a.length===0)&&a.push(`${i}s`),a.join(` `)}function e6(e){let t=oQ[e.name];if(!t)return(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)($,{color:`red`,children:[`Unknown tool: `,e.name]})});let n;n=e.result?.rejected?(()=>{try{return JSON.parse(e.result.content)}catch{return{}}})().reason===`interrupted`?`interrupted`:`rejected`:e.result?`success`:e.parsedResult?.phase===`error`?`error`:`executing`;let r=e.input??{},i=``;try{i=t.getHeaderParams(r)}catch{}try{return t.renderUI(r,n,e.parsedResult,e.displayData)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`Error rendering tool ${e.name}:`,r),(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(PK,{name:t.displayName,params:i,status:`error`}),(0,X.jsx)(FK,{color:`red`,children:`Error rendering tool`})]})}}const t6=(0,Z.memo)(({char:e,color:t})=>{let[n,r]=(0,Z.useState)(!0);return(0,Z.useEffect)(()=>{let e=setInterval(()=>{(0,Z.startTransition)(()=>{r(e=>!e)})},500);return()=>clearInterval(e)},[]),(0,X.jsx)($,{color:t,children:n?e:` `})});t6.displayName=`BlinkingIndicator`;const n6=(0,Z.memo)(e=>{let{type:t,segment:n,isSpinny:r=!1,source:i}=e;if(t!==`text`)throw Error(`Can only render text segments, got ${t}`);let a=(0,Z.useMemo)(()=>HQ(n),[n]);return a?.trim()?i===`user`?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`❯`}),(0,X.jsx)($,{dimColor:!0,italic:!0,children:a})]}):r?(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:(0,X.jsx)(v1,{text:a})}):(0,X.jsx)(Q,{flexDirection:`column`,children:(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`white`,children:`⏺`}),(0,X.jsx)(J3,{children:a.trimStart()})]})}):null});n6.displayName=`TextSegment`;const r6=(0,Z.memo)(e=>{let{segment:t,thinkingStartTime:n,thinkingEndTime:r}=e,{colors:i}=RL(),a=(0,Z.useMemo)(()=>HQ(t),[t]),o=(0,Z.useMemo)(()=>n&&r?`thought for ${$3(r-n)}`:null,[n,r]);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`flex-start`,children:[(0,X.jsx)($,{color:i.textSubtle,children:`✳`}),(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[o&&(0,X.jsxs)($,{dimColor:!0,children:[`(`,o,`)`]}),a&&(0,X.jsx)($,{color:i.textSubtle,wrap:`wrap`,children:a})]})]})});r6.displayName=`ExpandedThinkingSegment`;const i6=5e3,a6=(0,Z.memo)(e=>{let{isSpinny:t=!1,thinkingStartTime:n,thinkingEndTime:r}=e,[i,a]=(0,Z.useState)(performance.now()),[o,s]=(0,Z.useState)(!1);if((0,Z.useEffect)(()=>{if(!t||!n)return;let e=setInterval(()=>{(0,Z.startTransition)(()=>a(performance.now()))},1e3);return()=>clearInterval(e)},[t,n]),(0,Z.useEffect)(()=>{if(t||!r)return;let e=setTimeout(()=>s(!0),2e3);return()=>clearTimeout(e)},[t,r]),o)return null;let c=(0,Z.useMemo)(()=>{if(t){if(!n)return`thinking...`;let e=i-n;return e<i6?`thinking...`:`thinking for ${$3(e)}`}if(n&&r){let e=r-n;return e<i6?`thought`:`thought for ${$3(e)}`}return`thinking...`},[n,r,t,i]);return(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`flex-start`,children:[t?(0,X.jsx)(t6,{char:`●`,color:`cyan`}):(0,X.jsx)($,{color:`green`,children:`●`}),(0,X.jsx)($,{dimColor:!0,children:c})]})});a6.displayName=`ThinkingSegment`;const o6=(0,Z.memo)(e=>{let{toolUseRequest:t,toolUseResult:n,toolDisplayData:r,parsedResult:i}=e;return t?Array.isArray(t)?(0,X.jsx)(X.Fragment,{children:t.map((e,t)=>(0,X.jsx)(e6,{...e,result:n,displayData:r,parsedResult:i},e.id??t))}):(0,X.jsx)(e6,{...t,result:n,displayData:r,parsedResult:i}):null});o6.displayName=`ToolCallSegment`;const s6=(0,Z.memo)(e=>{let{type:t,segment:n,title:r,isSpinny:i=!1}=e,{colors:a}=RL(),o=(0,Z.useRef)(Z3());if(t!==`collapsible_component`)throw Error(`Can only render collapsible component segments, got ${t}`);let s=(0,Z.useMemo)(()=>HQ(n),[n]);if(!s&&!r)throw Error(`Collapsible component segment must have content or title`);let c=r||X3(o.current);return(0,X.jsxs)(Q,{borderStyle:s?`single`:void 0,borderColor:a.border,flexDirection:`column`,alignItems:`flex-start`,gap:1,children:[c&&(0,X.jsx)(Q,{flexDirection:`row`,alignItems:`center`,gap:1,children:i?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)(v1,{text:`${c}...`}),(0,X.jsx)($,{dimColor:!0,children:`(esc to interrupt)`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{children:` `}),(0,X.jsx)($,{color:a.textMuted,children:c})]})}),s&&(0,X.jsx)(J3,{children:s})]})});s6.displayName=`CollapsibleComponentSegment`;const c6=(0,Z.memo)(e=>{let{type:t,message:n,severity:r=`info`,actions:i,flashKey:a}=e,{colors:o}=RL();if(t!==`code_llm_notification`)throw Error(`Can only render notification segments, got ${t}`);let[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(a);if((0,Z.useEffect)(()=>{if(a!==l.current&&a!=null){l.current=a,c(!0);let e=setTimeout(()=>c(!1),600);return()=>clearTimeout(e)}},[a]),!n)throw Error(`Notification segment must have message`);let u=(0,Z.useMemo)(()=>r===`info`||r===`success`||r===`error`||r===`warning`?r:`info`,[r]),d=(0,Z.useMemo)(()=>{switch(u){case`info`:return o.info;case`success`:return o.success;case`warning`:return o.warning;case`error`:return o.error;default:return o.info}},[u,o]),f=e=>e.replace(/_/g,` `).replace(/([A-Z])/g,` $1`).trim().split(` `).filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(` `),p=(0,Z.useMemo)(()=>(i||[]).filter(e=>e.link),[i]);return(0,X.jsxs)(Q,{flexDirection:`column`,gap:0,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:d,children:s?`◉`:`●`}),(0,X.jsx)($,{color:d,bold:s,inverse:s,children:s?` ${n} `:n})]}),p.length>0&&(0,X.jsx)(Q,{marginLeft:2,flexDirection:`row`,gap:1,children:p.map((e,t)=>(0,X.jsxs)(Z.Fragment,{children:[t>0&&(0,X.jsx)($,{children:` | `}),(0,X.jsx)($,{color:`cyan`,underline:!0,children:f(e.type)})]},t))})]})});c6.displayName=`NotificationSegment`;const l6=(0,Z.memo)(({segment:e})=>{switch(e.type){case`text`:return(0,X.jsx)(n6,{...e});case`thinking`:return(0,X.jsx)(a6,{...e});case`code_llm_tool_call`:return(0,X.jsx)(o6,{...e});case`collapsible_component`:return(0,X.jsx)(s6,{...e});case`code_llm_agent_tool_request`:return(0,X.jsx)(o6,{...e});case`code_llm_notification`:return(0,X.jsx)(c6,{...e});default:return null}});l6.displayName=`SegmentBase`;function u6(e,t){return(0,X.jsx)(c6,{id:`error-fallback`,status:`completed`,source:`bot`,type:`code_llm_notification`,message:e.message,severity:`error`})}function d6({segment:e}){return(0,X.jsx)(A0,{fallback:u6,children:(0,X.jsx)(l6,{segment:e})})}const f6=(0,Z.memo)(({snapshot:e,onClose:t})=>{let{colors:n}=RL();return sI((e,n)=>{(n.ctrl||n.super)&&e===`o`&&t(),n.escape&&t()}),(0,X.jsxs)(Q,{flexDirection:`column`,gap:1,children:[(0,X.jsx)(Q,{flexDirection:`column`,gap:1,paddingBottom:1,width:`95%`,children:(0,Z.useMemo)(()=>e.filter(e=>!e.temp&&!e.isSpinny),[e]).map(e=>(0,X.jsx)(p6,{segment:e},e.id))}),(0,X.jsxs)(Q,{borderStyle:`single`,borderColor:n.border,paddingLeft:1,paddingRight:1,flexDirection:`row`,gap:2,children:[(0,X.jsx)($,{color:n.textMuted,children:`expanded view`}),(0,X.jsx)($,{dimColor:!0,children:`ctrl+o or esc to collapse`})]})]})});f6.displayName=`ExpandedView`;const p6=(0,Z.memo)(({segment:e})=>e.type===`thinking`?(0,X.jsx)(r6,{...e}):(0,X.jsx)(d6,{segment:e}));p6.displayName=`ExpandedSegment`;var m6=W(((e,t)=>{(function(n,r){typeof e==`object`&&t!==void 0?t.exports=r():typeof define==`function`&&define.amd?define(r):(n=typeof globalThis<`u`?globalThis:n||self,n.tinycolor=r())})(e,(function(){function e(t){"@babel/helpers - typeof";return e=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},e(t)}var t=/^\s+/,n=/\s+$/;function r(e,t){if(e||=``,t||={},e instanceof r)return e;if(!(this instanceof r))return new r(e,t);var n=i(e);this._originalInput=e,this._r=n.r,this._g=n.g,this._b=n.b,this._a=n.a,this._roundA=Math.round(100*this._a)/100,this._format=t.format||n.format,this._gradientType=t.gradientType,this._r<1&&(this._r=Math.round(this._r)),this._g<1&&(this._g=Math.round(this._g)),this._b<1&&(this._b=Math.round(this._b)),this._ok=n.ok}r.prototype={isDark:function(){return this.getBrightness()<128},isLight:function(){return!this.isDark()},isValid:function(){return this._ok},getOriginalInput:function(){return this._originalInput},getFormat:function(){return this._format},getAlpha:function(){return this._a},getBrightness:function(){var e=this.toRgb();return(e.r*299+e.g*587+e.b*114)/1e3},getLuminance:function(){var e=this.toRgb(),t=e.r/255,n=e.g/255,r=e.b/255,i=t<=.03928?t/12.92:((t+.055)/1.055)**2.4,a=n<=.03928?n/12.92:((n+.055)/1.055)**2.4,o=r<=.03928?r/12.92:((r+.055)/1.055)**2.4;return .2126*i+.7152*a+.0722*o},setAlpha:function(e){return this._a=O(e),this._roundA=Math.round(100*this._a)/100,this},toHsv:function(){var e=c(this._r,this._g,this._b);return{h:e.h*360,s:e.s,v:e.v,a:this._a}},toHsvString:function(){var e=c(this._r,this._g,this._b),t=Math.round(e.h*360),n=Math.round(e.s*100),r=Math.round(e.v*100);return this._a==1?`hsv(`+t+`, `+n+`%, `+r+`%)`:`hsva(`+t+`, `+n+`%, `+r+`%, `+this._roundA+`)`},toHsl:function(){var e=o(this._r,this._g,this._b);return{h:e.h*360,s:e.s,l:e.l,a:this._a}},toHslString:function(){var e=o(this._r,this._g,this._b),t=Math.round(e.h*360),n=Math.round(e.s*100),r=Math.round(e.l*100);return this._a==1?`hsl(`+t+`, `+n+`%, `+r+`%)`:`hsla(`+t+`, `+n+`%, `+r+`%, `+this._roundA+`)`},toHex:function(e){return u(this._r,this._g,this._b,e)},toHexString:function(e){return`#`+this.toHex(e)},toHex8:function(e){return d(this._r,this._g,this._b,this._a,e)},toHex8String:function(e){return`#`+this.toHex8(e)},toRgb:function(){return{r:Math.round(this._r),g:Math.round(this._g),b:Math.round(this._b),a:this._a}},toRgbString:function(){return this._a==1?`rgb(`+Math.round(this._r)+`, `+Math.round(this._g)+`, `+Math.round(this._b)+`)`:`rgba(`+Math.round(this._r)+`, `+Math.round(this._g)+`, `+Math.round(this._b)+`, `+this._roundA+`)`},toPercentageRgb:function(){return{r:Math.round(k(this._r,255)*100)+`%`,g:Math.round(k(this._g,255)*100)+`%`,b:Math.round(k(this._b,255)*100)+`%`,a:this._a}},toPercentageRgbString:function(){return this._a==1?`rgb(`+Math.round(k(this._r,255)*100)+`%, `+Math.round(k(this._g,255)*100)+`%, `+Math.round(k(this._b,255)*100)+`%)`:`rgba(`+Math.round(k(this._r,255)*100)+`%, `+Math.round(k(this._g,255)*100)+`%, `+Math.round(k(this._b,255)*100)+`%, `+this._roundA+`)`},toName:function(){return this._a===0?`transparent`:this._a<1?!1:E[u(this._r,this._g,this._b,!0)]||!1},toFilter:function(e){var t=`#`+f(this._r,this._g,this._b,this._a),n=t,i=this._gradientType?`GradientType = 1, `:``;if(e){var a=r(e);n=`#`+f(a._r,a._g,a._b,a._a)}return`progid:DXImageTransform.Microsoft.gradient(`+i+`startColorstr=`+t+`,endColorstr=`+n+`)`},toString:function(e){var t=!!e;e||=this._format;var n=!1,r=this._a<1&&this._a>=0;return!t&&r&&(e===`hex`||e===`hex6`||e===`hex3`||e===`hex4`||e===`hex8`||e===`name`)?e===`name`&&this._a===0?this.toName():this.toRgbString():(e===`rgb`&&(n=this.toRgbString()),e===`prgb`&&(n=this.toPercentageRgbString()),(e===`hex`||e===`hex6`)&&(n=this.toHexString()),e===`hex3`&&(n=this.toHexString(!0)),e===`hex4`&&(n=this.toHex8String(!0)),e===`hex8`&&(n=this.toHex8String()),e===`name`&&(n=this.toName()),e===`hsl`&&(n=this.toHslString()),e===`hsv`&&(n=this.toHsvString()),n||this.toHexString())},clone:function(){return r(this.toString())},_applyModification:function(e,t){var n=e.apply(null,[this].concat([].slice.call(t)));return this._r=n._r,this._g=n._g,this._b=n._b,this.setAlpha(n._a),this},lighten:function(){return this._applyModification(g,arguments)},brighten:function(){return this._applyModification(_,arguments)},darken:function(){return this._applyModification(v,arguments)},desaturate:function(){return this._applyModification(p,arguments)},saturate:function(){return this._applyModification(m,arguments)},greyscale:function(){return this._applyModification(h,arguments)},spin:function(){return this._applyModification(y,arguments)},_applyCombination:function(e,t){return e.apply(null,[this].concat([].slice.call(t)))},analogous:function(){return this._applyCombination(C,arguments)},complement:function(){return this._applyCombination(b,arguments)},monochromatic:function(){return this._applyCombination(w,arguments)},splitcomplement:function(){return this._applyCombination(S,arguments)},triad:function(){return this._applyCombination(x,[3])},tetrad:function(){return this._applyCombination(x,[4])}},r.fromRatio=function(t,n){if(e(t)==`object`){var i={};for(var a in t)t.hasOwnProperty(a)&&(a===`a`?i[a]=t[a]:i[a]=F(t[a]));t=i}return r(t,n)};function i(t){var n={r:0,g:0,b:0},r=1,i=null,o=null,c=null,u=!1,d=!1;return typeof t==`string`&&(t=B(t)),e(t)==`object`&&(z(t.r)&&z(t.g)&&z(t.b)?(n=a(t.r,t.g,t.b),u=!0,d=String(t.r).substr(-1)===`%`?`prgb`:`rgb`):z(t.h)&&z(t.s)&&z(t.v)?(i=F(t.s),o=F(t.v),n=l(t.h,i,o),u=!0,d=`hsv`):z(t.h)&&z(t.s)&&z(t.l)&&(i=F(t.s),c=F(t.l),n=s(t.h,i,c),u=!0,d=`hsl`),t.hasOwnProperty(`a`)&&(r=t.a)),r=O(r),{ok:u,format:t.format||d,r:Math.min(255,Math.max(n.r,0)),g:Math.min(255,Math.max(n.g,0)),b:Math.min(255,Math.max(n.b,0)),a:r}}function a(e,t,n){return{r:k(e,255)*255,g:k(t,255)*255,b:k(n,255)*255}}function o(e,t,n){e=k(e,255),t=k(t,255),n=k(n,255);var r=Math.max(e,t,n),i=Math.min(e,t,n),a,o,s=(r+i)/2;if(r==i)a=o=0;else{var c=r-i;switch(o=s>.5?c/(2-r-i):c/(r+i),r){case e:a=(t-n)/c+(t<n?6:0);break;case t:a=(n-e)/c+2;break;case n:a=(e-t)/c+4;break}a/=6}return{h:a,s:o,l:s}}function s(e,t,n){var r,i,a;e=k(e,360),t=k(t,100),n=k(n,100);function o(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}if(t===0)r=i=a=n;else{var s=n<.5?n*(1+t):n+t-n*t,c=2*n-s;r=o(c,s,e+1/3),i=o(c,s,e),a=o(c,s,e-1/3)}return{r:r*255,g:i*255,b:a*255}}function c(e,t,n){e=k(e,255),t=k(t,255),n=k(n,255);var r=Math.max(e,t,n),i=Math.min(e,t,n),a,o,s=r,c=r-i;if(o=r===0?0:c/r,r==i)a=0;else{switch(r){case e:a=(t-n)/c+(t<n?6:0);break;case t:a=(n-e)/c+2;break;case n:a=(e-t)/c+4;break}a/=6}return{h:a,s:o,v:s}}function l(e,t,n){e=k(e,360)*6,t=k(t,100),n=k(n,100);var r=Math.floor(e),i=e-r,a=n*(1-t),o=n*(1-i*t),s=n*(1-(1-i)*t),c=r%6,l=[n,o,a,a,s,n][c],u=[s,n,n,o,a,a][c],d=[a,a,s,n,n,o][c];return{r:l*255,g:u*255,b:d*255}}function u(e,t,n,r){var i=[P(Math.round(e).toString(16)),P(Math.round(t).toString(16)),P(Math.round(n).toString(16))];return r&&i[0].charAt(0)==i[0].charAt(1)&&i[1].charAt(0)==i[1].charAt(1)&&i[2].charAt(0)==i[2].charAt(1)?i[0].charAt(0)+i[1].charAt(0)+i[2].charAt(0):i.join(``)}function d(e,t,n,r,i){var a=[P(Math.round(e).toString(16)),P(Math.round(t).toString(16)),P(Math.round(n).toString(16)),P(I(r))];return i&&a[0].charAt(0)==a[0].charAt(1)&&a[1].charAt(0)==a[1].charAt(1)&&a[2].charAt(0)==a[2].charAt(1)&&a[3].charAt(0)==a[3].charAt(1)?a[0].charAt(0)+a[1].charAt(0)+a[2].charAt(0)+a[3].charAt(0):a.join(``)}function f(e,t,n,r){return[P(I(r)),P(Math.round(e).toString(16)),P(Math.round(t).toString(16)),P(Math.round(n).toString(16))].join(``)}r.equals=function(e,t){return!e||!t?!1:r(e).toRgbString()==r(t).toRgbString()},r.random=function(){return r.fromRatio({r:Math.random(),g:Math.random(),b:Math.random()})};function p(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.s-=t/100,n.s=A(n.s),r(n)}function m(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.s+=t/100,n.s=A(n.s),r(n)}function h(e){return r(e).desaturate(100)}function g(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.l+=t/100,n.l=A(n.l),r(n)}function _(e,t){t=t===0?0:t||10;var n=r(e).toRgb();return n.r=Math.max(0,Math.min(255,n.r-Math.round(255*-(t/100)))),n.g=Math.max(0,Math.min(255,n.g-Math.round(255*-(t/100)))),n.b=Math.max(0,Math.min(255,n.b-Math.round(255*-(t/100)))),r(n)}function v(e,t){t=t===0?0:t||10;var n=r(e).toHsl();return n.l-=t/100,n.l=A(n.l),r(n)}function y(e,t){var n=r(e).toHsl(),i=(n.h+t)%360;return n.h=i<0?360+i:i,r(n)}function b(e){var t=r(e).toHsl();return t.h=(t.h+180)%360,r(t)}function x(e,t){if(isNaN(t)||t<=0)throw Error(`Argument to polyad must be a positive number`);for(var n=r(e).toHsl(),i=[r(e)],a=360/t,o=1;o<t;o++)i.push(r({h:(n.h+o*a)%360,s:n.s,l:n.l}));return i}function S(e){var t=r(e).toHsl(),n=t.h;return[r(e),r({h:(n+72)%360,s:t.s,l:t.l}),r({h:(n+216)%360,s:t.s,l:t.l})]}function C(e,t,n){t||=6,n||=30;var i=r(e).toHsl(),a=360/n,o=[r(e)];for(i.h=(i.h-(a*t>>1)+720)%360;--t;)i.h=(i.h+a)%360,o.push(r(i));return o}function w(e,t){t||=6;for(var n=r(e).toHsv(),i=n.h,a=n.s,o=n.v,s=[],c=1/t;t--;)s.push(r({h:i,s:a,v:o})),o=(o+c)%1;return s}r.mix=function(e,t,n){n=n===0?0:n||50;var i=r(e).toRgb(),a=r(t).toRgb(),o=n/100;return r({r:(a.r-i.r)*o+i.r,g:(a.g-i.g)*o+i.g,b:(a.b-i.b)*o+i.b,a:(a.a-i.a)*o+i.a})},r.readability=function(e,t){var n=r(e),i=r(t);return(Math.max(n.getLuminance(),i.getLuminance())+.05)/(Math.min(n.getLuminance(),i.getLuminance())+.05)},r.isReadable=function(e,t,n){var i=r.readability(e,t),a,o=!1;switch(a=V(n),a.level+a.size){case`AAsmall`:case`AAAlarge`:o=i>=4.5;break;case`AAlarge`:o=i>=3;break;case`AAAsmall`:o=i>=7;break}return o},r.mostReadable=function(e,t,n){var i=null,a=0,o,s,c,l;n||={},s=n.includeFallbackColors,c=n.level,l=n.size;for(var u=0;u<t.length;u++)o=r.readability(e,t[u]),o>a&&(a=o,i=r(t[u]));return r.isReadable(e,i,{level:c,size:l})||!s?i:(n.includeFallbackColors=!1,r.mostReadable(e,[`#fff`,`#000`],n))};var T=r.names={aliceblue:`f0f8ff`,antiquewhite:`faebd7`,aqua:`0ff`,aquamarine:`7fffd4`,azure:`f0ffff`,beige:`f5f5dc`,bisque:`ffe4c4`,black:`000`,blanchedalmond:`ffebcd`,blue:`00f`,blueviolet:`8a2be2`,brown:`a52a2a`,burlywood:`deb887`,burntsienna:`ea7e5d`,cadetblue:`5f9ea0`,chartreuse:`7fff00`,chocolate:`d2691e`,coral:`ff7f50`,cornflowerblue:`6495ed`,cornsilk:`fff8dc`,crimson:`dc143c`,cyan:`0ff`,darkblue:`00008b`,darkcyan:`008b8b`,darkgoldenrod:`b8860b`,darkgray:`a9a9a9`,darkgreen:`006400`,darkgrey:`a9a9a9`,darkkhaki:`bdb76b`,darkmagenta:`8b008b`,darkolivegreen:`556b2f`,darkorange:`ff8c00`,darkorchid:`9932cc`,darkred:`8b0000`,darksalmon:`e9967a`,darkseagreen:`8fbc8f`,darkslateblue:`483d8b`,darkslategray:`2f4f4f`,darkslategrey:`2f4f4f`,darkturquoise:`00ced1`,darkviolet:`9400d3`,deeppink:`ff1493`,deepskyblue:`00bfff`,dimgray:`696969`,dimgrey:`696969`,dodgerblue:`1e90ff`,firebrick:`b22222`,floralwhite:`fffaf0`,forestgreen:`228b22`,fuchsia:`f0f`,gainsboro:`dcdcdc`,ghostwhite:`f8f8ff`,gold:`ffd700`,goldenrod:`daa520`,gray:`808080`,green:`008000`,greenyellow:`adff2f`,grey:`808080`,honeydew:`f0fff0`,hotpink:`ff69b4`,indianred:`cd5c5c`,indigo:`4b0082`,ivory:`fffff0`,khaki:`f0e68c`,lavender:`e6e6fa`,lavenderblush:`fff0f5`,lawngreen:`7cfc00`,lemonchiffon:`fffacd`,lightblue:`add8e6`,lightcoral:`f08080`,lightcyan:`e0ffff`,lightgoldenrodyellow:`fafad2`,lightgray:`d3d3d3`,lightgreen:`90ee90`,lightgrey:`d3d3d3`,lightpink:`ffb6c1`,lightsalmon:`ffa07a`,lightseagreen:`20b2aa`,lightskyblue:`87cefa`,lightslategray:`789`,lightslategrey:`789`,lightsteelblue:`b0c4de`,lightyellow:`ffffe0`,lime:`0f0`,limegreen:`32cd32`,linen:`faf0e6`,magenta:`f0f`,maroon:`800000`,mediumaquamarine:`66cdaa`,mediumblue:`0000cd`,mediumorchid:`ba55d3`,mediumpurple:`9370db`,mediumseagreen:`3cb371`,mediumslateblue:`7b68ee`,mediumspringgreen:`00fa9a`,mediumturquoise:`48d1cc`,mediumvioletred:`c71585`,midnightblue:`191970`,mintcream:`f5fffa`,mistyrose:`ffe4e1`,moccasin:`ffe4b5`,navajowhite:`ffdead`,navy:`000080`,oldlace:`fdf5e6`,olive:`808000`,olivedrab:`6b8e23`,orange:`ffa500`,orangered:`ff4500`,orchid:`da70d6`,palegoldenrod:`eee8aa`,palegreen:`98fb98`,paleturquoise:`afeeee`,palevioletred:`db7093`,papayawhip:`ffefd5`,peachpuff:`ffdab9`,peru:`cd853f`,pink:`ffc0cb`,plum:`dda0dd`,powderblue:`b0e0e6`,purple:`800080`,rebeccapurple:`663399`,red:`f00`,rosybrown:`bc8f8f`,royalblue:`4169e1`,saddlebrown:`8b4513`,salmon:`fa8072`,sandybrown:`f4a460`,seagreen:`2e8b57`,seashell:`fff5ee`,sienna:`a0522d`,silver:`c0c0c0`,skyblue:`87ceeb`,slateblue:`6a5acd`,slategray:`708090`,slategrey:`708090`,snow:`fffafa`,springgreen:`00ff7f`,steelblue:`4682b4`,tan:`d2b48c`,teal:`008080`,thistle:`d8bfd8`,tomato:`ff6347`,turquoise:`40e0d0`,violet:`ee82ee`,wheat:`f5deb3`,white:`fff`,whitesmoke:`f5f5f5`,yellow:`ff0`,yellowgreen:`9acd32`},E=r.hexNames=D(T);function D(e){var t={};for(var n in e)e.hasOwnProperty(n)&&(t[e[n]]=n);return t}function O(e){return e=parseFloat(e),(isNaN(e)||e<0||e>1)&&(e=1),e}function k(e,t){M(e)&&(e=`100%`);var n=N(e);return e=Math.min(t,Math.max(0,parseFloat(e))),n&&(e=parseInt(e*t,10)/100),Math.abs(e-t)<1e-6?1:e%t/parseFloat(t)}function A(e){return Math.min(1,Math.max(0,e))}function j(e){return parseInt(e,16)}function M(e){return typeof e==`string`&&e.indexOf(`.`)!=-1&&parseFloat(e)===1}function N(e){return typeof e==`string`&&e.indexOf(`%`)!=-1}function P(e){return e.length==1?`0`+e:``+e}function F(e){return e<=1&&(e=e*100+`%`),e}function I(e){return Math.round(parseFloat(e)*255).toString(16)}function L(e){return j(e)/255}var R=function(){var e=`(?:[-\\+]?\\d*\\.\\d+%?)|(?:[-\\+]?\\d+%?)`,t=`[\\s|\\(]+(`+e+`)[,|\\s]+(`+e+`)[,|\\s]+(`+e+`)\\s*\\)?`,n=`[\\s|\\(]+(`+e+`)[,|\\s]+(`+e+`)[,|\\s]+(`+e+`)[,|\\s]+(`+e+`)\\s*\\)?`;return{CSS_UNIT:new RegExp(e),rgb:RegExp(`rgb`+t),rgba:RegExp(`rgba`+n),hsl:RegExp(`hsl`+t),hsla:RegExp(`hsla`+n),hsv:RegExp(`hsv`+t),hsva:RegExp(`hsva`+n),hex3:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex6:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,hex4:/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,hex8:/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/}}();function z(e){return!!R.CSS_UNIT.exec(e)}function B(e){e=e.replace(t,``).replace(n,``).toLowerCase();var r=!1;if(T[e])e=T[e],r=!0;else if(e==`transparent`)return{r:0,g:0,b:0,a:0,format:`name`};var i;return(i=R.rgb.exec(e))?{r:i[1],g:i[2],b:i[3]}:(i=R.rgba.exec(e))?{r:i[1],g:i[2],b:i[3],a:i[4]}:(i=R.hsl.exec(e))?{h:i[1],s:i[2],l:i[3]}:(i=R.hsla.exec(e))?{h:i[1],s:i[2],l:i[3],a:i[4]}:(i=R.hsv.exec(e))?{h:i[1],s:i[2],v:i[3]}:(i=R.hsva.exec(e))?{h:i[1],s:i[2],v:i[3],a:i[4]}:(i=R.hex8.exec(e))?{r:j(i[1]),g:j(i[2]),b:j(i[3]),a:L(i[4]),format:r?`name`:`hex8`}:(i=R.hex6.exec(e))?{r:j(i[1]),g:j(i[2]),b:j(i[3]),format:r?`name`:`hex`}:(i=R.hex4.exec(e))?{r:j(i[1]+``+i[1]),g:j(i[2]+``+i[2]),b:j(i[3]+``+i[3]),a:L(i[4]+``+i[4]),format:r?`name`:`hex8`}:(i=R.hex3.exec(e))?{r:j(i[1]+``+i[1]),g:j(i[2]+``+i[2]),b:j(i[3]+``+i[3]),format:r?`name`:`hex`}:!1}function V(e){var t,n;return e||={level:`AA`,size:`small`},t=(e.level||`AA`).toUpperCase(),n=(e.size||`small`).toLowerCase(),t!==`AA`&&t!==`AAA`&&(t=`AA`),n!==`small`&&n!==`large`&&(n=`small`),{level:t,size:n}}return r}))})),h6=W(((e,t)=>{let n=m6(),r={r:256,g:256,b:256,a:1},i={h:360,s:1,v:1,a:1};function a(e,t,n){let r={};for(let i in e)e.hasOwnProperty(i)&&(r[i]=n===0?0:(t[i]-e[i])/n);return r}function o(e,t,n,r){let i={};for(let a in t)t.hasOwnProperty(a)&&(i[a]=e[a]*n+t[a],i[a]=i[a]<0?i[a]+r[a]:r[a]===1?i[a]:i[a]%r[a]);return i}function s(e,t,i){let s=e.color.toRgb(),c=a(s,t.color.toRgb(),i),l=[e.color];for(let e=1;e<i;e++){let t=o(c,s,e,r);l.push(n(t))}return l}function c(e,t,r,c){let l=e.color.toHsv(),u=t.color.toHsv();if(l.s===0||u.s===0)return s(e,t,r);let d;if(typeof c==`boolean`)d=c;else{let e=l.h<u.h&&u.h-l.h<180||l.h>u.h&&l.h-u.h>180;d=c===`long`&&e||c===`short`&&!e}let f=a(l,u,r),p=[e.color],m;m=l.h<=u.h&&!d||l.h>=u.h&&d?u.h-l.h:d?360-u.h+l.h:360-l.h+u.h,f.h=(-1)**(d?1:0)*Math.abs(m)/r;for(let e=1;e<r;e++){let t=o(f,l,e,i);p.push(n(t))}return p}function l(e,t){let n=e.length;if(t=parseInt(t,10),isNaN(t)||t<2)throw Error(`Invalid number of steps (< 2)`);if(t<n)throw Error(`Number of steps cannot be inferior to number of stops`);let r=[];for(let i=1;i<n;i++){let n=(t-1)*(e[i].pos-e[i-1].pos);r.push(Math.max(1,Math.round(n)))}let i=1;for(let e=n-1;e--;)i+=r[e];for(;i!==t;)if(i<t){let e=Math.min.apply(null,r);r[r.indexOf(e)]++,i++}else{let e=Math.max.apply(null,r);r[r.indexOf(e)]--,i--}return r}function u(e,t,r,i){if(t<0||t>1)throw Error(`Position must be between 0 and 1`);let s,c;for(let n=0,r=e.length;n<r-1;n++)if(t>=e[n].pos&&t<e[n+1].pos){s=e[n],c=e[n+1];break}return s||=c=e[e.length-1],n(o(a(s.color[r](),c.color[r](),(c.pos-s.pos)*100),s.color[r](),(t-s.pos)*100,i))}var d=class e{constructor(e){if(e.length<2)throw Error(`Invalid number of stops (< 2)`);let t=e[0].pos!==void 0,r=e.length,i=-1,a=!1;this.stops=e.map((e,o)=>{let s=e.pos!==void 0;if(t^s)throw Error(`Cannot mix positionned and not posionned color stops`);if(s){let t=e.color!==void 0;if(!t&&(a||o===0||o===r-1))throw Error(`Cannot define two consecutive position-only stops`);if(a=!t,e={color:t?n(e.color):null,colorLess:!t,pos:e.pos},e.pos<0||e.pos>1)throw Error(`Color stops positions must be between 0 and 1`);if(e.pos<i)throw Error(`Color stops positions are not ordered`);i=e.pos}else e={color:n(e.color===void 0?e:e.color),pos:o/(r-1)};return e}),this.stops[0].pos!==0&&(this.stops.unshift({color:this.stops[0].color,pos:0}),r++),this.stops[r-1].pos!==1&&this.stops.push({color:this.stops[r-1].color,pos:1})}reverse(){let t=[];return this.stops.forEach(function(e){t.push({color:e.color,pos:1-e.pos})}),new e(t.reverse())}loop(){let t=[],n=[];return this.stops.forEach(e=>{t.push({color:e.color,pos:e.pos/2})}),this.stops.slice(0,-1).forEach(e=>{n.push({color:e.color,pos:1-e.pos/2})}),new e(t.concat(n.reverse()))}rgb(e){let t=l(this.stops,e),n=[];this.stops.forEach((e,t)=>{e.colorLess&&(e.color=s(this.stops[t-1],this.stops[t+1],2)[1])});for(let e=0,r=this.stops.length;e<r-1;e++){let r=s(this.stops[e],this.stops[e+1],t[e]);n.splice(n.length,0,...r)}return n.push(this.stops[this.stops.length-1].color),n}hsv(e,t){let n=l(this.stops,e),r=[];this.stops.forEach((e,n)=>{e.colorLess&&(e.color=c(this.stops[n-1],this.stops[n+1],2,t)[1])});for(let e=0,i=this.stops.length;e<i-1;e++){let i=c(this.stops[e],this.stops[e+1],n[e],t);r.splice(r.length,0,...i)}return r.push(this.stops[this.stops.length-1].color),r}css(e,t){e||=`linear`,t||=e===`linear`?`to right`:`ellipse at center`;let n=e+`-gradient(`+t;return this.stops.forEach(function(e){n+=`, `+(e.colorLess?``:e.color.toRgbString()+` `)+e.pos*100+`%`}),n+=`)`,n}rgbAt(e){return u(this.stops,e,`toRgb`,r)}hsvAt(e){return u(this.stops,e,`toHsv`,i)}};t.exports=function(e){if(arguments.length===1){if(!Array.isArray(arguments[0]))throw Error(`"stops" is not an array`);e=arguments[0]}else e=Array.prototype.slice.call(arguments);return new d(e)}})),g6=ve({atlas:()=>T6,cristal:()=>E6,default:()=>v6,fruit:()=>M6,instagram:()=>N6,mind:()=>O6,morning:()=>k6,multiline:()=>x6,passion:()=>j6,pastel:()=>L6,rainbow:()=>I6,retro:()=>P6,summer:()=>F6,teen:()=>D6,vice:()=>A6}),_6=be(h6(),1);const v6=(...e)=>{let t,n;if(e.length===0)throw Error(`Missing gradient colors`);if(Array.isArray(e[0]))t=(0,_6.default)(e[0]),n=S6(e[1]);else{if(e.length===1)throw Error(`Expected an array of colors, received ${JSON.stringify(e[0])}`);t=(0,_6.default)(...e)}let r=(e,r)=>b6(e?e.toString():``,t,r??n);return r.multiline=(e,r)=>x6(e?e.toString():``,t,r??n),r},y6=(e,t,n)=>t.interpolation?.toLowerCase()===`hsv`?e.hsv(n,t.hsvSpin?.toLowerCase()||!1):e.rgb(n);function b6(e,t,n){let r=y6(t,S6(n),Math.max(e.replace(/\s/g,``).length,t.stops.length)),i=``;for(let t of e)i+=t.match(/\s/g)?t:NA.hex(r.shift()?.toHex()||`#000`)(t);return i}function x6(e,t,n){let r=S6(n),i=e.split(`
12825
+ `),a=y6(t,r,Math.max(...i.map(e=>e.length),t.stops.length)),o=[];for(let e of i){let t=a.slice(0),n=``;for(let r of e)n+=NA.hex(t.shift()?.toHex()||`#000`)(r);o.push(n)}return o.join(`
12826
+ `)}function S6(e){let t={interpolation:`rgb`,hsvSpin:`short`,...e};if(e!==void 0&&typeof e!=`object`)throw TypeError(`Expected \`options\` to be an \`object\`, got \`${typeof e}\``);if(typeof t.interpolation!=`string`)throw TypeError(`Expected \`options.interpolation\` to be \`rgb\` or \`hsv\`, got \`${typeof t.interpolation}\``);if(t.interpolation.toLowerCase()===`hsv`&&typeof t.hsvSpin!=`string`)throw TypeError(`Expected \`options.hsvSpin\` to be a \`short\` or \`long\`, got \`${typeof t.hsvSpin}\``);return t}const C6={atlas:{colors:[`#feac5e`,`#c779d0`,`#4bc0c8`],options:{}},cristal:{colors:[`#bdfff3`,`#4ac29a`],options:{}},teen:{colors:[`#77a1d3`,`#79cbca`,`#e684ae`],options:{}},mind:{colors:[`#473b7b`,`#3584a7`,`#30d2be`],options:{}},morning:{colors:[`#ff5f6d`,`#ffc371`],options:{interpolation:`hsv`}},vice:{colors:[`#5ee7df`,`#b490ca`],options:{interpolation:`hsv`}},passion:{colors:[`#f43b47`,`#453a94`],options:{}},fruit:{colors:[`#ff4e50`,`#f9d423`],options:{}},instagram:{colors:[`#833ab4`,`#fd1d1d`,`#fcb045`],options:{}},retro:{colors:[`#3f51b1`,`#5a55ae`,`#7b5fac`,`#8f6aae`,`#a86aa4`,`#cc6b8e`,`#f18271`,`#f3a469`,`#f7c978`],options:{}},summer:{colors:[`#fdbb2d`,`#22c1c3`],options:{}},rainbow:{colors:[`#ff0000`,`#ff0100`],options:{interpolation:`hsv`,hsvSpin:`long`}},pastel:{colors:[`#74ebd5`,`#74ecd5`],options:{interpolation:`hsv`,hsvSpin:`long`}}};function w6(e){let t=t=>v6(...e.colors)(t,e.options);return t.multiline=(t=``)=>v6(...e.colors).multiline(t,e.options),t}const T6=w6(C6.atlas),E6=w6(C6.cristal),D6=w6(C6.teen),O6=w6(C6.mind),k6=w6(C6.morning),A6=w6(C6.vice),j6=w6(C6.passion),M6=w6(C6.fruit),N6=w6(C6.instagram),P6=w6(C6.retro),F6=w6(C6.summer),I6=w6(C6.rainbow),L6=w6(C6.pastel);v6.atlas=T6,v6.cristal=E6,v6.teen=D6,v6.mind=O6,v6.morning=k6,v6.vice=A6,v6.passion=j6,v6.fruit=M6,v6.instagram=N6,v6.retro=P6,v6.summer=F6,v6.rainbow=I6,v6.pastel=L6;const R6=(0,Z.memo)(e=>{let t=(0,Z.useMemo)(()=>e.name?g6[e.name]:v6(...e.colors),[e.name,e.colors]);return(0,X.jsx)($,{transform:e=>t.multiline(qQ(e)),children:e.children})});R6.displayName=`Gradient`;const z6=(0,Z.memo)(()=>{let{width:e}=mQ(),{colors:t}=RL(),n=(0,Z.useMemo)(()=>[t.gradientStart,t.gradientMid,t.gradientEnd],[t]);return e<=50?(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,flexWrap:`wrap`,children:[(0,X.jsx)(R6,{colors:n,children:(0,X.jsx)($,{children:`Abacus AI`})}),(0,X.jsxs)($,{color:t.textMuted,children:[`v`,PA]})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(R6,{colors:n,children:(0,X.jsx)($,{children:` ▗▄▖ ▗▄▄▖ ▗▄▖ ▗▄▄▖▗▖ ▗▖ ▗▄▄▖ ▗▄▖ ▗▄▄▄▖ ▗▄▄▖▗▖ ▗▄▄▄▖
12827
12827
  ▐▌ ▐▌▐▌ ▐▌▐▌ ▐▌▐▌ ▐▌ ▐▌▐▌ ▐▌ ▐▌ █ ▐▌ ▐▌ █
12828
12828
  ▐▛▀▜▌▐▛▀▚▖▐▛▀▜▌▐▌ ▐▌ ▐▌ ▝▀▚▖▐▛▀▜▌ █ ▐▌ ▐▌ █
12829
- ▐▌ ▐▌▐▙▄▞▘▐▌ ▐▌▝▚▄▄▖▝▚▄▞▘▗▄▄▞▘▐▌ ▐▌▗▄█▄▖ ▝▚▄▄▖▐▙▄▄▖▗▄█▄▖ `})}),(0,X.jsxs)($,{color:t.textMuted,children:[`v`,PA]})]})});R6.displayName=`Header`;const z6=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming`.split(`.`);function B6(e){return e.charAt(0).toUpperCase()+e.slice(1)}function V6(){return z6[Math.floor(Math.random()*z6.length)]}function H6(e,t){let[n,r]=(0,Z.useState)(0),i=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>{if(!e)return;let t=setInterval(()=>{r(e=>e+1)},500);return()=>clearInterval(t)},[e]),!e)return null;let a=Date.now();if(t){if(i.current===null&&(i.current=t+5e3),a>i.current)return null;let n=t-e;return n<5e3?`thought`:`thought for ${Q3(n)}`}i.current=null;let o=a-e;return o<5e3?`thinking`:`thinking for ${Q3(o)}`}function U6(e){let[,t]=(0,Z.useState)(0);if((0,Z.useEffect)(()=>{if(!e)return;let n=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(n)},[e]),!e)return null;let n=Date.now()-e;return n<5e3?null:Q3(n)}const W6=({status:e,thinkingStartTime:t,thinkingEndTime:n,runStartTime:r})=>{let{activity:i}=GX(),[a,o]=(0,Z.useState)(()=>V6()),s=(0,Z.useRef)(Sl.Idle);(0,Z.useEffect)(()=>{s.current===Sl.Idle&&e!==Sl.Idle&&o(V6()),s.current=e},[e]);let c=H6(t,n),l=U6(r);if(!(e!==Sl.Idle&&e!==Sl.WaitingForToolPermission))return null;let u=e===Sl.LoadingConversation?`Resuming`:B6(a);return(0,X.jsxs)(Q,{paddingLeft:1,flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`cyan`,children:i===`upload`?`↑`:i===`download`?`↓`:`•`}),(0,X.jsx)(_1,{text:`${u}...`}),c&&(0,X.jsxs)($,{color:`cyan`,children:[`(`,c,`)`]}),l&&!c&&(0,X.jsx)($,{dimColor:!0,children:l}),e!==Sl.LoadingConversation&&(0,X.jsx)($,{dimColor:!0,children:`(esc/ctrl+c to interrupt)`})]})},G6=new Set([`read_file`,`list_dir`,`grep`,`file_search`,`semantic_search_server`,`web_search`,`fetch_url`,`get_tab_content`,`bash_output`,`kill_shell`,`get_interactive_elements`,`navigate_to`,`new_tab`,`switch_active_tab`,`close_tab`,`refresh_tab`,`get_diagnostics`,`upload_image`]);function K6(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function q6(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.input??{}:t.input??{}:{}}function J6(e){let t=K6(e),n=q6(e),r=aQ[t];if(!r)return``;try{return r.getHeaderParams(n)}catch{return``}}function Y6(e){switch(e){case`read_file`:return`read`;case`list_dir`:return`list`;case`grep`:case`file_search`:case`semantic_search_server`:return`search`;case`web_search`:return`web`;case`fetch_url`:return`fetch`;case`navigate_to`:case`new_tab`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:return`browser`;case`bash_output`:return`terminal`;case`kill_shell`:return`terminal`;case`get_diagnostics`:return`diag`;default:return`other`}}function X6(e){let t=[];function n(e,n,r){let i=n+r;if(i===0)return;let a;if(r>0)switch(e){case`search`:a=i===1?`searching for 1 pattern`:`searching for ${i} patterns`;break;case`read`:a=i===1?`reading 1 file`:`reading ${i} files`;break;case`list`:a=i===1?`listing 1 directory`:`listing ${i} directories`;break;case`web`:a=i===1?`searching the web`:`searching the web ${i} times`;break;case`fetch`:a=i===1?`fetching 1 URL`:`fetching ${i} URLs`;break;case`browser`:a=i===1?`navigating browser`:`navigating browser ${i} times`;break;case`terminal`:a=`getting terminal output`;break;case`diag`:a=`checking diagnostics`;break;default:a=i===1?`1 operation`:`${i} operations`;break}else switch(e){case`search`:a=n===1?`searched for 1 pattern`:`searched for ${n} patterns`;break;case`read`:a=n===1?`read 1 file`:`read ${n} files`;break;case`list`:a=n===1?`listed 1 directory`:`listed ${n} directories`;break;case`web`:a=n===1?`searched the web`:`searched the web ${n} times`;break;case`fetch`:a=n===1?`fetched 1 URL`:`fetched ${n} URLs`;break;case`browser`:a=n===1?`navigated browser`:`navigated browser ${n} times`;break;case`terminal`:a=`got terminal output`;break;case`diag`:a=`checked diagnostics`;break;default:a=n===1?`1 operation`:`${n} operations`;break}t.push(a)}for(let t of[`search`,`read`,`list`,`web`,`fetch`,`browser`,`terminal`,`diag`,`other`]){let r=e[t];r&&n(t,r.completed,r.executing)}return t.join(`, `)}const Z6=(0,Z.memo)(({segments:e})=>{let{colors:t}=RL(),n={},r=null,i=!1,a=!1;for(let t of e){let e=Y6(K6(t)),o=!t.toolUseResult;if(n[e]||(n[e]={completed:0,executing:0}),o)n[e].executing++,r=t,i=!0;else{n[e].completed++;let r=t.toolUseResult;(r?.rejected||r?.content?.startsWith(`Error:`))&&(a=!0)}}let o=X6(n),s=o.charAt(0).toUpperCase()+o.slice(1),c=r?J6(r):null;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`center`,children:[i?(0,X.jsx)(NK,{}):(0,X.jsx)($,{color:a?`red`:i?`white`:`green`,children:`⏺`}),(0,X.jsxs)($,{children:[s,i?`…`:``]}),(0,X.jsx)($,{color:t.textMuted,dimColor:!0,children:`(ctrl+o to expand)`})]}),c&&(0,X.jsxs)(Q,{flexDirection:`row`,paddingLeft:2,children:[(0,X.jsxs)($,{color:t.textSubtle,dimColor:!0,children:[`⎿`,` `]}),(0,X.jsx)($,{color:t.textSubtle,children:c})]})]})});Z6.displayName=`ToolGroupSummary`;const Q6=(0,Z.memo)(({questions:e,onResolve:t})=>{let[n,r]=(0,Z.useState)(0),[i,a]=(0,Z.useState)(0),[o,s]=(0,Z.useState)(()=>new Map),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(()=>new Map),f=(0,Z.useRef)(null),p=(0,Z.useCallback)(e=>f.current?.getExpandedText(e)??e,[]),m=e[n],h=o.get(n)??new Set,g=(0,Z.useRef)(i);g.current=i;let _=(0,Z.useRef)(n);_.current=n;let v=(0,Z.useRef)(c);v.current=c;let y=(0,Z.useRef)(e);y.current=e;let b=(0,Z.useRef)(o);b.current=o;let x=(0,Z.useRef)(u);x.current=u;let S=(0,Z.useCallback)((e,t)=>{let n={};for(let r=0;r<y.current.length;r++){let i=y.current[r];if(!i)continue;let a=e.get(r);if(!a||a.size===0)continue;let o=[...a].sort((e,t)=>e-t).map(e=>i.options[e]?.label??``).filter(Boolean),s=t.get(r);n[`question_${r}`]=s?`${o.join(`, `)} — ${s}`:o.join(`, `)}return n},[]),C=(0,Z.useCallback)((e,n)=>{t({type:`question_answers`,answers:S(e,n)})},[t,S]),w=(0,Z.useCallback)((e,t,n)=>{e>=y.current.length?C(t,n):(r(e),a(0),l(!1))},[C]),T=(0,Z.useCallback)(()=>{let e=_.current;if(!y.current[e])return;let t=b.current,n=x.current;w(e+1,t,n)},[w]),E=(0,Z.useRef)(T);E.current=T;let D=(0,Z.useCallback)(e=>{if(e.key.return){let t=p(f.current?.text?.trim()??``),n=_.current,r=new Map(x.current);t?r.set(n,t):r.delete(n),d(r),l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.escape){l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.tab){l(!1),f.current?.setText(``),e.preventDefault();return}},[p]),O=(0,Z.useCallback)(e=>{let t=_.current,n=new Map(x.current),r=p(e.trim());r?n.set(t,r):n.delete(t),d(n),l(!1),f.current?.setText(``)},[p]);if(sI((0,Z.useCallback)((e,t)=>{if(v.current)return;let n=_.current,i=y.current[n];if(!i)return;let o=i.options.length;if(t.upArrow){a(e=>Math.max(0,e-1));return}if(t.downArrow){a(e=>Math.min(o-1,e+1));return}if(t.leftArrow){n>0&&(r(n-1),a(0),l(!1));return}if(t.rightArrow){n<y.current.length-1&&(r(n+1),a(0),l(!1));return}if(e===` `){let e=g.current,t=new Map(b.current),r=new Set(t.get(n)??[]);i.multiSelect?r.has(e)?r.delete(e):r.add(e):(r.clear(),r.add(e)),t.set(n,r),s(t);return}if(t.return){if((b.current.get(n)??new Set).size===0&&!i.multiSelect){let e=g.current,t=new Map(b.current),r=new Set([e]);t.set(n,r),s(t),w(n+1,t,x.current)}else E.current();return}if(t.tab){l(!0),setTimeout(()=>{let e=x.current.get(n)??``;f.current&&e&&f.current.setText(e)},0);return}if(t.escape){C(b.current,x.current);return}},[w,C]),{isActive:!c}),!m)return null;let k=u.get(n);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`Questions (${n+1}/${e.length}): ${m.header}`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:m.question})}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:m.options.map((e,t)=>{let n=t===i,r=h.has(t),a=m.multiSelect?r?`[x] `:`[ ] `:r?`◉ `:`○ `;return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:r?`green`:n?void 0:`gray`,children:[a,e.label]}),e.description?(0,X.jsxs)($,{dimColor:!0,children:[` — `,e.description]}):null]},t)})}),c?(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{dimColor:!0,children:`Note: `}),(0,X.jsx)(J$,{ref:f,flexGrow:1,maxWidth:`90%`,placeholder:`Add context or instructions…`,onSubmit:O,onKeyDown:D})]})}):(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:k&&(0,X.jsxs)($,{dimColor:!0,children:[`Note: `,(0,X.jsx)($,{italic:!0,children:k})]})}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:1,paddingBottom:1,gap:2,children:c?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter save note`}),(0,X.jsx)($,{dimColor:!0,children:`esc discard note`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ option`}),(0,X.jsx)($,{dimColor:!0,children:`space select`}),(0,X.jsx)($,{dimColor:!0,children:`enter confirm`}),e.length>1&&(0,X.jsx)($,{dimColor:!0,children:`←→ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),(0,X.jsx)($,{dimColor:!0,children:`esc skip`})]})})]})});Q6.displayName=`AskUserQuestionPermissionUI`;const $6=(0,Z.memo)(({option:e,index:t,isSelected:n,showAsInput:r,inputPlaceholder:i,inputPrefix:a,inputBufferRef:o,onInputSubmit:s,onInputKeyDown:c})=>r?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{children:`${t+1}. ${a||``}`}),(0,X.jsx)(J$,{ref:o,flexGrow:1,maxWidth:`90%`,placeholder:i,onSubmit:s,onKeyDown:c})]}):(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:n?void 0:`gray`,children:[`${t+1}. ${e.label}`,e.hint&&(0,X.jsxs)($,{dimColor:!0,children:[` (`,e.hint,`)`]})]})]}));$6.displayName=`PermissionOptionItem`;const e8=(0,Z.memo)(({options:e,onSelect:t,inputPlaceholder:n=`and tell AbacusAI`,onModeSwitch:r,modeSwitchHint:i})=>{let[a,o]=(0,Z.useState)(0),[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(null),u=(0,Z.useCallback)(e=>l.current?.getExpandedText(e)??e,[]),d=(0,Z.useCallback)(()=>{},[]),f=(0,Z.useRef)(``),p=(0,Z.useRef)(``),m=(0,Z.useMemo)(()=>e.filter(e=>e.value!==`input`),[e]),h=s,g=(0,Z.useRef)(a);g.current=a;let _=(0,Z.useRef)(m.length);_.current=m.length;let v=(0,Z.useRef)(h);v.current=h;let y=(0,Z.useRef)(t);y.current=t;let b=(0,Z.useRef)(r);b.current=r;let x=(0,Z.useRef)(m);x.current=m;let S=(0,Z.useCallback)(()=>{let e=x.current[g.current];if(e)if(v.current){let t=l.current?.text?.trim();if(t){let n=u(t),r=e.value===`accept`?`accept`:`reject`;y.current({decision:r,userMessage:n}),d()}}else e.value!==`input`&&y.current({decision:e.value})},[u,d]),C=(0,Z.useRef)(S);C.current=S;let w=(0,Z.useCallback)(e=>{if(e.trim()){let t=x.current[g.current],n=u(e.trim()),r=t?.value===`accept`?`accept`:`reject`;y.current({decision:r,userMessage:n}),d()}},[u,d]),T=(0,Z.useCallback)(e=>{if(e.key.upArrow||e.key.downArrow){let t=x.current[g.current],n=l.current?.text||``;t?.value===`accept`?f.current=n:t?.value===`reject`&&(p.current=n),c(!1),e.key.upArrow?o(e=>Math.max(0,e-1)):o(e=>Math.min(_.current-1,e+1)),e.preventDefault();return}if(e.key.tab){let t=x.current[g.current];t?.value===`accept`?f.current=``:t?.value===`reject`&&(p.current=``),d(),c(!1),e.preventDefault();return}if(e.key.escape){d(),c(!1),y.current({decision:`reject`}),e.preventDefault();return}},[d]);sI((0,Z.useCallback)((e,t)=>{if(!v.current){if(t.upArrow){o(e=>Math.max(0,e-1));return}if(t.downArrow){o(e=>Math.min(_.current-1,e+1));return}if(t.escape){y.current({decision:`reject`});return}if(t.tab&&t.shift){if(b.current){b.current();return}let e=x.current.findIndex(e=>e.value===`allowAlways`);e!==-1&&(o(e),setTimeout(()=>{y.current({decision:`allowAlways`})},0));return}if(t.tab){let e=x.current[g.current];if(e&&(e.value===`accept`||e.value===`reject`)){c(!0);let t=e.value===`accept`?f.current:p.current;setTimeout(()=>{l.current&&t&&l.current.setText(t)},0)}return}if(t.return){C.current();return}}},[]),{isActive:!0}),(0,Z.useEffect)(()=>{let e=m[a];e&&(e.value!==`accept`&&e.value!==`reject`||(e.value===`accept`?f.current:p.current)&&!s&&c(!0))},[a,m,s]);let E=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{s&&(E.current=!0)},[s]),(0,Z.useEffect)(()=>{if(!s||!E.current)return;let e=m[a];if(!e)return;let t=e.value===`accept`?f.current:e.value===`reject`?p.current:``;t?setTimeout(()=>{l.current&&l.current.text===``&&l.current.setText(t),E.current=!1},0):E.current=!1},[s,a,m]);let D=m[a],O=s&&D,k=e=>e.value===`accept`?`Yes, `:e.value===`reject`?`No, `:``,A=!s&&D&&(D.value===`accept`||D.value===`reject`),j=m.some(e=>e.value===`allowAlways`||e.value===`allowAlwaysWithRule`);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[m.map((e,t)=>{let r=t===a,i=O&&r,o=e.value===`accept`?f.current:e.value===`reject`?p.current:``;return(0,X.jsx)($6,{option:!i&&o?{...e,label:`${e.label}, ${o}`}:e,index:t,isSelected:r,showAsInput:i,inputPrefix:k(e),inputPlaceholder:n,inputBufferRef:l,onInputSubmit:w,onInputKeyDown:T},t)}),(0,X.jsx)(Q,{flexDirection:`row`,marginTop:1,gap:2,children:s?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter submit`}),(0,X.jsx)($,{dimColor:!0,children:`tab discard note`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`enter select`}),A&&(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),i&&(0,X.jsxs)($,{dimColor:!0,children:[`shift+tab `,i]}),!i&&j&&(0,X.jsx)($,{dimColor:!0,children:`shift+tab don't ask again`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]})})]})});e8.displayName=`PermissionOptions`;function t8(e){return e.decision===`accept`&&e.userMessage?{type:`accept_with_message`,message:e.userMessage}:e.decision===`reject`&&e.userMessage?{type:`reject_with_message`,message:e.userMessage}:e.decision===`allowAlwaysWithRule`?e.rule?{type:`allow_always_with_rule`,rule:e.rule}:`accept`:e.decision}const n8=(0,Z.memo)(({filePath:e,originalContent:t,newContent:n,diffShownInEditor:r,onResolve:i})=>{let a=!t,{agentMode:o}=$K(),s=o===xl.PlanMode,c=Gk(e,process.cwd()),l=[{label:`Yes, apply changes`,value:`accept`},...s?[]:[{label:`Yes, and always allow Edit(${c})`,value:`allowAlwaysWithRule`}],{label:`No, reject changes`,value:`reject`}],u=e=>{if(e.decision===`allowAlwaysWithRule`){i({type:`allow_always_with_rule`,rule:`Edit(${c})`});return}i(t8(e))};return r?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`${a?`Create`:`Update`} file ${e}`,subtitle:`Opened changes in the editor`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:l,onSelect:u,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`${a?`Create`:`Update`} file ${e}`}),a?(0,X.jsx)(zK,{filePath:e,content:n,maxLines:100}):(0,X.jsx)(Pq,{filePath:e,originalContent:t,newContent:n,paddingLeft:1}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:l,onSelect:u,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});n8.displayName=`EditFilePermissionUI`;const r8=(0,Z.memo)(({filePath:e,onResolve:t})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`Delete file ${e}`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{color:`red`,children:e})}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:[{label:`Yes, delete file`,value:`accept`},{label:`No, keep file`,value:`reject`}],onSelect:e=>{t(t8(e))}})})]}));r8.displayName=`DeleteFilePermissionUI`;const i8=(0,Z.memo)(({description:e,url:t,displayName:n,onResolve:r})=>{let i=[{label:`Yes, allow action`,value:`accept`},{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`},{label:`No, deny action`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`Browser action: ${e}`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),t&&(0,X.jsxs)($,{dimColor:!0,children:[`URL: `,t]})]}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:i,onSelect:e=>{if(e.decision===`allowAlwaysWithRule`){r({type:`allow_always_with_rule`,rule:n});return}r(t8(e))}})})]})});i8.displayName=`BrowserActionPermissionUI`;const a8=(0,Z.memo)(({command:e,background:t,onResolve:n})=>{let r=Uk(e),i=[{label:`Yes, run command`,value:`accept`},{label:`Yes, and always allow Bash(${r})`,value:`allowAlwaysWithRule`},{label:`No, skip command`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`Bash command`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:(0,OK.supportsLanguage)(`bash`)?(()=>{try{return(0,OK.highlight)(e,{language:`bash`})}catch{return e}})():e}),t&&(0,X.jsx)(Q,{paddingTop:1,children:(0,X.jsx)($,{dimColor:!0,children:`(Running in background)`})})]}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:i,onSelect:e=>{if(e.decision===`allowAlwaysWithRule`){n({type:`allow_always_with_rule`,rule:`Bash(${r})`});return}n(t8(e))},inputPlaceholder:`Type here to tell AbacusAI what to do differently`,onModeSwitch:()=>n(`allowAlways`),modeSwitchHint:`allow all tools`})})]})});a8.displayName=`RunTerminalPermissionUI`;const o8=(0,Z.memo)(({title:e,description:t,toolName:n,onResolve:r})=>{let i=[{label:`Yes, allow`,value:`accept`},...n?[{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`}]:[],{label:`No, deny`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:e}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:(0,OK.supportsLanguage)(`json`)?(()=>{try{return(0,OK.highlight)(t,{language:`json`})}catch{return t}})():t})}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:i,onSelect:e=>{if(e.decision===`allowAlwaysWithRule`&&n){r({type:`allow_always_with_rule`,rule:n});return}r(t8(e))}})})]})});o8.displayName=`GenericPermissionUI`;const s8=(0,Z.memo)(({planFilePath:e,planContent:t,onResolve:n})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`Ready to code? Implement plan: ${e.length>60?`…${e.slice(-60)}`:e}`}),t&&(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{dimColor:!0,children:`Here is Abacus's plan:`}),(0,X.jsx)(q3,{children:t})]}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:[{label:`Yes, implement the plan (approve each edit)`,value:`accept`},{label:`Yes, implement the plan (auto-accept all edits)`,value:`allowAlways`,hint:`shift+tab`},{label:`No, keep planning`,value:`reject`}],onSelect:e=>{n(t8(e))},inputPlaceholder:`Add instructions for the implementation`})})]}));s8.displayName=`ExitPlanModePermissionUI`;const c8=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow read`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny read`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(m1,{title:`Read file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:p1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(e8,{options:r,onSelect:e=>{n(t8(e))}})})]})});c8.displayName=`ReadOutsideDirectoryPermissionUI`;const l8=(0,Z.memo)(({pendingTool:e})=>{let{request:t,resolve:n}=e;switch(t.type){case`edit_file`:return(0,X.jsx)(n8,{filePath:t.filePath,originalContent:t.originalContent,newContent:t.newContent,diffShownInEditor:t.diffShownInEditor,onResolve:n});case`delete_file`:return(0,X.jsx)(r8,{filePath:t.filePath,onResolve:n});case`run_terminal`:return(0,X.jsx)(a8,{command:t.command,background:t.background,onResolve:n});case`browser_action`:return(0,X.jsx)(i8,{description:t.description,url:t.url,displayName:t.displayName,onResolve:n});case`generic`:return(0,X.jsx)(o8,{title:`Tool: ${t.toolName}`,description:t.inputSummary,toolName:t.toolName,onResolve:n});case`read_outside_directory`:return(0,X.jsx)(c8,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`exit_plan_mode`:return(0,X.jsx)(s8,{planFilePath:t.planFilePath,planContent:t.planContent,onResolve:n});case`ask_user_question`:return(0,X.jsx)(Q6,{questions:t.questions,onResolve:n});default:return null}});l8.displayName=`ToolPermissionUI`;function u8(e){let t=(0,Z.useRef)(!1),n=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{n.current=e},[e]),(0,Z.useEffect)(()=>{let e=()=>{t.current||(t.current=!0,n.current())};return process.on(`exit`,e),process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{e(),process.off(`exit`,e),process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}},[])}const d8=(0,Z.createContext)(null),f8=()=>{let e=(0,Z.use)(d8);if(!e)throw Error(`${f8.name} must be used within a ${p8.name}`);return e};function p8({children:e}){let t=(0,Z.useCallback)(e=>{let t=e.split(``).filter(e=>{let t=e.codePointAt(0);return!(t<=31||t===127)}).join(``);process.stdout.write(`${KX.SET_TITLE}${t}${KX.BEL}`)},[]);u8(()=>{process.stdout.write(`${KX.SET_TITLE}${KX.BEL}`)});let n=(0,Z.useMemo)(()=>({setTitle:t}),[t]);return(0,X.jsx)(d8.Provider,{value:n,children:e})}const m8=2e3;function h8(e,t,n){return e===Sl.ExecutingTool?`tool-executing`:e===Sl.Submitted||e===Sl.Streaming?`streaming`:e===Sl.WaitingForToolPermission&&t?`permission-ui`:n()?`idle-with-text`:`idle-empty`}function g8(e){let{agentStatus:t,hasPendingPermission:n,composerHasText:r,hasQueuedMessages:i,stopAgent:a,rejectPermission:o,saveAndClearComposer:s,clearComposer:c,dequeueOne:l,clearQueue:u,exitApp:d}=e,[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),g=(0,Z.useRef)(null),_=(0,Z.useRef)(null),v=(0,Z.useCallback)(()=>{p(!1),g.current&&=(clearTimeout(g.current),null)},[]),y=(0,Z.useCallback)(()=>{h(null),_.current&&=(clearTimeout(_.current),null)},[]),b=(0,Z.useCallback)(()=>{v(),y()},[v,y]),x=h8(t,n,r),S=(0,Z.useRef)(x);return(0,Z.useEffect)(()=>{let e=S.current;S.current=x,e!==x&&b()},[x,b]),sI((0,Z.useEffectEvent)((e,x)=>{if(x.ctrl&&e===`z`){process.platform!==`win32`&&process.kill(process.pid,`SIGTSTP`);return}let S=x.escape,C=x.ctrl&&e===`c`,w=x.ctrl&&e===`d`;if(!S&&!C&&!w)return;let T=h8(t,n,r);if(T===`tool-executing`||T===`streaming`){b(),a();return}if(T===`permission-ui`){b(),o();return}if(T===`idle-with-text`){if(S){f?(c(),b()):(y(),p(!0),g.current=setTimeout(()=>{p(!1),g.current=null},m8));return}let e=C?`c`:`d`;if(m===e){b(),d();return}if(m!==null){y(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},m8);return}v(),s(),i()&&u(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},m8);return}if(T===`idle-empty`){if(S){i()&&l();return}let e=C?`c`:`d`;if(m===e){b(),d();return}if(m!==null){y(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},m8);return}i()&&u(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},m8)}}),{isActive:!0}),(0,Z.useEffect)(()=>()=>{g.current&&clearTimeout(g.current),_.current&&clearTimeout(_.current)},[]),{escClear:f,exitKey:m}}function _8(e){return e.type===`code_llm_tool_call`||e.type===`code_llm_agent_tool_request`}function v8(e){let t=e.toolUseResult;return!!(t?.rejected||t?.content?.startsWith(`Error:`))}function y8(e){if(e.type!==`code_llm_notification`)return!1;let t=(e.message??``).toLowerCase();return t.includes(`compacting conversation`)||t.includes(`compacted conversation`)}function b8(e){let t={toolUses:0,responses:0};for(let n of e)switch(n.type){case`code_llm_tool_call`:case`code_llm_agent_tool_request`:t.toolUses+=Array.isArray(n.toolUseRequest)?n.toolUseRequest.length:1;break;case`text`:n.source===`bot`&&t.responses++;break}return t}function x8(e,t){return{toolUses:e.toolUses+t.toolUses,responses:e.responses+t.responses}}function S8(e){let t={toolUses:0,responses:0},n=[],r=[],i=0,a=[];for(let a=0;a<e.length;a++){let o=e[a];if(y8(o)){let e=b8(n);t=x8(t,e),r.push(...n),n=[],i++;continue}n.push(o)}i>0&&a.push({kind:`compacted`,id:`compacted-${i}`,counts:t,segments:r});let o=C8(n);return a.push(...o),a}function C8(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.type===`thinking`){t.push({kind:`segment`,segment:r}),n++;continue}if(_8(r)&&G6.has(w8(r))){let i=[r],a=n+1;for(;a<e.length;){let t=e[a];if(t.type===`thinking`){a++;continue}if(v8(i[i.length-1]))break;if(_8(t)&&G6.has(w8(t)))i.push(t),a++;else break}i.length===1?t.push({kind:`segment`,segment:i[0]}):t.push({kind:`tool-group`,id:i[0].id,segments:i}),n=a;continue}t.push({kind:`segment`,segment:r}),n++}return t}function w8(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function T8(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`thinking`)return{thinkingStartTime:n.thinkingStartTime??null,thinkingEndTime:n.thinkingEndTime??null}}return{thinkingStartTime:null,thinkingEndTime:null}}function E8({timing:e}){let{setTitle:t}=f8(),{segments:n,agentStatus:r,pendingToolPermission:i,conversationTitle:a,conversationId:o,addNotification:s,stop:c,rejectPendingPermission:l,removeFirstFromQueue:u,clearQueue:d}=LZ(),f=(0,Z.useRef)(null),{authExpired:p,clearAuthExpired:m,apiClient:h}=bZ();(0,Z.useEffect)(()=>{p&&(s(`Session expired — use /login to authenticate again.`,`error`),m())},[p,s,m]);let[g,_]=(0,Z.useState)(null),v=(0,Z.useCallback)(()=>{_(e=>e===null?n.filter(e=>!e.temp&&!e.isSpinny):null)},[n]);sI((0,Z.useCallback)((e,t)=>{(t.ctrl||t.super)&&e===`o`&&v()},[v]),{isActive:g===null});let{lastItem:y,prevItems:b}=(0,Z.useMemo)(()=>{let e=S8(n.filter(e=>!e.temp&&!e.isSpinny));return{lastItem:e.at(-1)??null,prevItems:e.slice(0,-1)}},[n]),{thinkingStartTime:x,thinkingEndTime:S}=(0,Z.useMemo)(()=>T8(n),[n]),C=(0,Z.useRef)(Sl.Idle),[w,T]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=C.current===Sl.Idle,t=r!==Sl.Idle&&r!==Sl.WaitingForToolPermission;e&&t?T(Date.now()):r===Sl.Idle&&T(null),C.current=r},[r]);let E=r===Sl.WaitingForToolPermission&&i!==null,[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(`0`),[j,M]=(0,Z.useState)(0);(0,Z.useEffect)(()=>{t(a?`${a} • Abacus.AI CLI`:`Abacus.AI CLI`)},[a,t]),(0,Z.useEffect)(()=>Qj(async()=>{let t=e.getFormattedDuration(),n=0;if(o)try{n=await OQ(h,o)}catch{}M(n),A(t),O(!0),await new Promise(e=>setTimeout(e,100))},{wait:2e3,streams:[process.stdout,process.stderr]}),[e,o,h]);let N=g8({agentStatus:r,hasPendingPermission:i!==null,composerHasText:()=>f.current?.hasText()??!1,hasQueuedMessages:()=>f.current?.hasQueue()??!1,stopAgent:c,rejectPermission:l,saveAndClearComposer:()=>f.current?.saveAndClear(),clearComposer:()=>f.current?.clear(),dequeueOne:u,clearQueue:d,exitApp:()=>$j(0)}),P=r!==Sl.Idle&&r!==Sl.WaitingForToolPermission,F=i?.request.tool.id??null;return g===null?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(Q,{flexDirection:`column`,gap:1,paddingBottom:1,width:`95%`,children:[(0,X.jsx)(R6,{}),(0,X.jsxs)(kK.Provider,{value:F,children:[b.map(e=>e.kind===`compacted`?(0,X.jsx)(cQ,{counts:e.counts,segments:e.segments},e.id):e.kind===`segment`?(0,X.jsx)(u6,{segment:e.segment},e.segment.id):(0,X.jsx)(Z6,{segments:e.segments},e.id)),y&&(y.kind===`compacted`?(0,X.jsx)(cQ,{counts:y.counts,segments:y.segments},y.id):y.kind===`segment`?(0,X.jsx)(u6,{segment:y.segment},y.segment.id):(0,X.jsx)(Z6,{segments:y.segments},y.id))]}),P&&(0,X.jsx)(k0,{onError:e=>{process.stderr.write(`[status-indicator error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(W6,{status:r,thinkingStartTime:x,thinkingEndTime:S,runStartTime:w})})]}),D?(0,X.jsx)(A0,{duration:k,credits:j,conversationId:o}):(0,X.jsxs)(X.Fragment,{children:[E&&(0,X.jsx)(k0,{onError:e=>{process.stderr.write(`[tool-permission error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(l8,{pendingTool:i})}),(0,X.jsx)(Z.Activity,{mode:E?`hidden`:`visible`,children:(0,X.jsx)(k0,{fallback:e=>(0,X.jsxs)(Q,{flexDirection:`column`,paddingX:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong in the input area.`}),(0,X.jsx)($,{color:`yellow`,children:e.message}),(0,X.jsxs)($,{dimColor:!0,children:[`Press Escape to restart the CLI, or resume with: `,ke.binName,` -c`,` `,o]})]}),onError:e=>{process.stderr.write(`[composer error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(O0,{hints:N,composerRef:f})})})]})]}):(0,X.jsx)(d6,{snapshot:g,onClose:()=>_(null)})}async function D8({apiClient:e,authManager:t,configService:n,agentArgs:r}){let i=new gL,a=new Z3,o,s=r?.[`permission-mode`];if(s)switch(s){case`yolo`:o=xl.Yolo;break;case`accept-edits`:o=xl.AcceptEdits;break;case`plan`:o=xl.PlanMode;break;default:o=xl.Normal;break}else r?.[`dangerously-skip-permissions`]?o=xl.Yolo:r?.[`auto-accept-edits`]?o=xl.AcceptEdits:r?.[`plan-mode`]&&(o=xl.PlanMode);let c=process.stdout,l=e=>{c&&c.writable&&c.write(e)},u=()=>l(KX.HIDE_CURSOR),d=()=>l(KX.SHOW_CURSOR);u();let f=rI((0,X.jsx)(zL,{children:(0,X.jsx)(xZ,{client:e,authManager:t,children:(0,X.jsx)(yL,{client:i,children:(0,X.jsx)(mQ,{children:(0,X.jsx)(p8,{children:(0,X.jsx)(vZ,{children:(0,X.jsx)(dQ,{configService:n,children:(0,X.jsx)(HX,{children:(0,X.jsx)(nq,{initialMode:o,children:(0,X.jsx)(WX,{children:(0,X.jsx)(IZ,{apiClient:e,configService:n,agentArgs:r,children:(0,X.jsx)(E8,{timing:a})})})})})})})})})})})}),{exitOnCtrlC:!1,suspendable:!0,onSuspended:()=>{process.stderr.write(`
12829
+ ▐▌ ▐▌▐▙▄▞▘▐▌ ▐▌▝▚▄▄▖▝▚▄▞▘▗▄▄▞▘▐▌ ▐▌▗▄█▄▖ ▝▚▄▄▖▐▙▄▄▖▗▄█▄▖ `})}),(0,X.jsxs)($,{color:t.textMuted,children:[`v`,PA]})]})});z6.displayName=`Header`;const B6=`baking.beaming.booping.bouncing.brewing.bubbling.chasing.churning.coalescing.conjuring.cooking.crafting.crunching.cuddling.dancing.dazzling.discovering.doodling.dreaming.drifting.enchanting.exploring.finding.floating.fluttering.foraging.forging.frolicking.gathering.giggling.gliding.greeting.growing.hatching.herding.honking.hopping.hugging.humming.imagining.inventing.jingling.juggling.jumping.kindling.knitting.launching.leaping.mapping.marinating.meandering.mixing.moseying.munching.napping.nibbling.noodling.orbiting.painting.percolating.petting.plotting.pondering.popping.prancing.purring.puzzling.questing.riding.roaming.rolling.sauteeing.scribbling.seeking.shimmying.singing.skipping.sleeping.snacking.sniffing.snuggling.soaring.sparking.spinning.splashing.sprouting.squishing.stargazing.stirring.strolling.swimming.swinging.tickling.tinkering.toasting.tumbling.twirling.waddling.wandering.watching.weaving.whistling.wibbling.wiggling.wishing.wobbling.wondering.yawning.zooming`.split(`.`);function V6(e){return e.charAt(0).toUpperCase()+e.slice(1)}function H6(){return B6[Math.floor(Math.random()*B6.length)]}function U6(e,t){let[n,r]=(0,Z.useState)(0),i=(0,Z.useRef)(null);if((0,Z.useEffect)(()=>{if(!e)return;let t=setInterval(()=>{r(e=>e+1)},500);return()=>clearInterval(t)},[e]),!e)return null;let a=Date.now();if(t){if(i.current===null&&(i.current=t+5e3),a>i.current)return null;let n=t-e;return n<5e3?`thought`:`thought for ${$3(n)}`}i.current=null;let o=a-e;return o<5e3?`thinking`:`thinking for ${$3(o)}`}function W6(e){let[,t]=(0,Z.useState)(0);if((0,Z.useEffect)(()=>{if(!e)return;let n=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(n)},[e]),!e)return null;let n=Date.now()-e;return n<5e3?null:$3(n)}const G6=({status:e,thinkingStartTime:t,thinkingEndTime:n,runStartTime:r})=>{let{activity:i}=KX(),[a,o]=(0,Z.useState)(()=>H6()),s=(0,Z.useRef)(Sl.Idle);(0,Z.useEffect)(()=>{s.current===Sl.Idle&&e!==Sl.Idle&&o(H6()),s.current=e},[e]);let c=U6(t,n),l=W6(r);if(!(e!==Sl.Idle&&e!==Sl.WaitingForToolPermission))return null;let u=e===Sl.LoadingConversation?`Resuming`:V6(a);return(0,X.jsxs)(Q,{paddingLeft:1,flexDirection:`row`,gap:1,children:[(0,X.jsx)($,{color:`cyan`,children:i===`upload`?`↑`:i===`download`?`↓`:`•`}),(0,X.jsx)(v1,{text:`${u}...`}),c&&(0,X.jsxs)($,{color:`cyan`,children:[`(`,c,`)`]}),l&&!c&&(0,X.jsx)($,{dimColor:!0,children:l}),e!==Sl.LoadingConversation&&(0,X.jsx)($,{dimColor:!0,children:`(esc/ctrl+c to interrupt)`})]})},K6=new Set([`read_file`,`list_dir`,`grep`,`file_search`,`semantic_search_server`,`web_search`,`web_fetch`,`get_tab_content`,`bash_output`,`kill_shell`,`get_interactive_elements`,`navigate_to`,`new_tab`,`switch_active_tab`,`close_tab`,`refresh_tab`,`get_diagnostics`,`upload_image`]);function q6(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function J6(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.input??{}:t.input??{}:{}}function Y6(e){let t=q6(e),n=J6(e),r=oQ[t];if(!r)return``;try{return r.getHeaderParams(n)}catch{return``}}function X6(e){switch(e){case`read_file`:return`read`;case`list_dir`:return`list`;case`grep`:case`file_search`:case`semantic_search_server`:return`search`;case`web_search`:return`web`;case`web_fetch`:return`fetch`;case`navigate_to`:case`new_tab`:case`switch_active_tab`:case`close_tab`:case`refresh_tab`:case`get_tab_content`:case`get_interactive_elements`:return`browser`;case`bash_output`:return`terminal`;case`kill_shell`:return`terminal`;case`get_diagnostics`:return`diag`;default:return`other`}}function Z6(e){let t=[];function n(e,n,r){let i=n+r;if(i===0)return;let a;if(r>0)switch(e){case`search`:a=i===1?`searching for 1 pattern`:`searching for ${i} patterns`;break;case`read`:a=i===1?`reading 1 file`:`reading ${i} files`;break;case`list`:a=i===1?`listing 1 directory`:`listing ${i} directories`;break;case`web`:a=i===1?`searching the web`:`searching the web ${i} times`;break;case`fetch`:a=i===1?`fetching 1 URL`:`fetching ${i} URLs`;break;case`browser`:a=i===1?`navigating browser`:`navigating browser ${i} times`;break;case`terminal`:a=`getting terminal output`;break;case`diag`:a=`checking diagnostics`;break;default:a=i===1?`1 operation`:`${i} operations`;break}else switch(e){case`search`:a=n===1?`searched for 1 pattern`:`searched for ${n} patterns`;break;case`read`:a=n===1?`read 1 file`:`read ${n} files`;break;case`list`:a=n===1?`listed 1 directory`:`listed ${n} directories`;break;case`web`:a=n===1?`searched the web`:`searched the web ${n} times`;break;case`fetch`:a=n===1?`fetched 1 URL`:`fetched ${n} URLs`;break;case`browser`:a=n===1?`navigated browser`:`navigated browser ${n} times`;break;case`terminal`:a=`got terminal output`;break;case`diag`:a=`checked diagnostics`;break;default:a=n===1?`1 operation`:`${n} operations`;break}t.push(a)}for(let t of[`search`,`read`,`list`,`web`,`fetch`,`browser`,`terminal`,`diag`,`other`]){let r=e[t];r&&n(t,r.completed,r.executing)}return t.join(`, `)}const Q6=(0,Z.memo)(({segments:e})=>{let{colors:t}=RL(),n={},r=null,i=!1,a=!1;for(let t of e){let e=X6(q6(t)),o=!t.toolUseResult;if(n[e]||(n[e]={completed:0,executing:0}),o)n[e].executing++,r=t,i=!0;else{n[e].completed++;let r=t.toolUseResult;(r?.rejected||r?.content?.startsWith(`Error:`))&&(a=!0)}}let o=Z6(n),s=o.charAt(0).toUpperCase()+o.slice(1),c=r?Y6(r):null;return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsxs)(Q,{flexDirection:`row`,gap:1,alignItems:`center`,children:[i?(0,X.jsx)(NK,{}):(0,X.jsx)($,{color:a?`red`:i?`white`:`green`,children:`⏺`}),(0,X.jsxs)($,{children:[s,i?`…`:``]}),(0,X.jsx)($,{color:t.textMuted,dimColor:!0,children:`(ctrl+o to expand)`})]}),c&&(0,X.jsxs)(Q,{flexDirection:`row`,paddingLeft:2,children:[(0,X.jsxs)($,{color:t.textSubtle,dimColor:!0,children:[`⎿`,` `]}),(0,X.jsx)($,{color:t.textSubtle,children:c})]})]})});Q6.displayName=`ToolGroupSummary`;const $6=(0,Z.memo)(({questions:e,onResolve:t})=>{let[n,r]=(0,Z.useState)(0),[i,a]=(0,Z.useState)(0),[o,s]=(0,Z.useState)(()=>new Map),[c,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(()=>new Map),f=(0,Z.useRef)(null),p=(0,Z.useCallback)(e=>f.current?.getExpandedText(e)??e,[]),m=e[n],h=o.get(n)??new Set,g=(0,Z.useRef)(i);g.current=i;let _=(0,Z.useRef)(n);_.current=n;let v=(0,Z.useRef)(c);v.current=c;let y=(0,Z.useRef)(e);y.current=e;let b=(0,Z.useRef)(o);b.current=o;let x=(0,Z.useRef)(u);x.current=u;let S=(0,Z.useCallback)((e,t)=>{let n={};for(let r=0;r<y.current.length;r++){let i=y.current[r];if(!i)continue;let a=e.get(r);if(!a||a.size===0)continue;let o=[...a].sort((e,t)=>e-t).map(e=>i.options[e]?.label??``).filter(Boolean),s=t.get(r);n[`question_${r}`]=s?`${o.join(`, `)} — ${s}`:o.join(`, `)}return n},[]),C=(0,Z.useCallback)((e,n)=>{t({type:`question_answers`,answers:S(e,n)})},[t,S]),w=(0,Z.useCallback)((e,t,n)=>{e>=y.current.length?C(t,n):(r(e),a(0),l(!1))},[C]),T=(0,Z.useCallback)(()=>{let e=_.current;if(!y.current[e])return;let t=b.current,n=x.current;w(e+1,t,n)},[w]),E=(0,Z.useRef)(T);E.current=T;let D=(0,Z.useCallback)(e=>{if(e.key.return){let t=p(f.current?.text?.trim()??``),n=_.current,r=new Map(x.current);t?r.set(n,t):r.delete(n),d(r),l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.escape){l(!1),f.current?.setText(``),e.preventDefault();return}if(e.key.tab){l(!1),f.current?.setText(``),e.preventDefault();return}},[p]),O=(0,Z.useCallback)(e=>{let t=_.current,n=new Map(x.current),r=p(e.trim());r?n.set(t,r):n.delete(t),d(n),l(!1),f.current?.setText(``)},[p]);if(sI((0,Z.useCallback)((e,t)=>{if(v.current)return;let n=_.current,i=y.current[n];if(!i)return;let o=i.options.length;if(t.upArrow){a(e=>Math.max(0,e-1));return}if(t.downArrow){a(e=>Math.min(o-1,e+1));return}if(t.leftArrow){n>0&&(r(n-1),a(0),l(!1));return}if(t.rightArrow){n<y.current.length-1&&(r(n+1),a(0),l(!1));return}if(e===` `){let e=g.current,t=new Map(b.current),r=new Set(t.get(n)??[]);i.multiSelect?r.has(e)?r.delete(e):r.add(e):(r.clear(),r.add(e)),t.set(n,r),s(t);return}if(t.return){if((b.current.get(n)??new Set).size===0&&!i.multiSelect){let e=g.current,t=new Map(b.current),r=new Set([e]);t.set(n,r),s(t),w(n+1,t,x.current)}else E.current();return}if(t.tab){l(!0),setTimeout(()=>{let e=x.current.get(n)??``;f.current&&e&&f.current.setText(e)},0);return}if(t.escape){C(b.current,x.current);return}},[w,C]),{isActive:!c}),!m)return null;let k=u.get(n);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`Questions (${n+1}/${e.length}): ${m.header}`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:m.question})}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:m.options.map((e,t)=>{let n=t===i,r=h.has(t),a=m.multiSelect?r?`[x] `:`[ ] `:r?`◉ `:`○ `;return(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:r?`green`:n?void 0:`gray`,children:[a,e.label]}),e.description?(0,X.jsxs)($,{dimColor:!0,children:[` — `,e.description]}):null]},t)})}),c?(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{dimColor:!0,children:`Note: `}),(0,X.jsx)(Y$,{ref:f,flexGrow:1,maxWidth:`90%`,placeholder:`Add context or instructions…`,onSubmit:O,onKeyDown:D})]})}):(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingTop:1,children:k&&(0,X.jsxs)($,{dimColor:!0,children:[`Note: `,(0,X.jsx)($,{italic:!0,children:k})]})}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`row`,paddingLeft:1,paddingBottom:1,gap:2,children:c?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter save note`}),(0,X.jsx)($,{dimColor:!0,children:`esc discard note`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ option`}),(0,X.jsx)($,{dimColor:!0,children:`space select`}),(0,X.jsx)($,{dimColor:!0,children:`enter confirm`}),e.length>1&&(0,X.jsx)($,{dimColor:!0,children:`←→ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),(0,X.jsx)($,{dimColor:!0,children:`esc skip`})]})})]})});$6.displayName=`AskUserQuestionPermissionUI`;const e8=(0,Z.memo)(({option:e,index:t,isSelected:n,showAsInput:r,inputPlaceholder:i,inputPrefix:a,inputBufferRef:o,onInputSubmit:s,onInputKeyDown:c})=>r?(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:`cyan`,children:`❯ `}),(0,X.jsx)($,{children:`${t+1}. ${a||``}`}),(0,X.jsx)(Y$,{ref:o,flexGrow:1,maxWidth:`90%`,placeholder:i,onSubmit:s,onKeyDown:c})]}):(0,X.jsxs)(Q,{flexDirection:`row`,children:[(0,X.jsx)($,{color:n?`cyan`:void 0,children:n?`❯ `:` `}),(0,X.jsxs)($,{color:n?void 0:`gray`,children:[`${t+1}. ${e.label}`,e.hint&&(0,X.jsxs)($,{dimColor:!0,children:[` (`,e.hint,`)`]})]})]}));e8.displayName=`PermissionOptionItem`;const t8=(0,Z.memo)(({options:e,onSelect:t,inputPlaceholder:n=`and tell AbacusAI`,onModeSwitch:r,modeSwitchHint:i})=>{let[a,o]=(0,Z.useState)(0),[s,c]=(0,Z.useState)(!1),l=(0,Z.useRef)(null),u=(0,Z.useCallback)(e=>l.current?.getExpandedText(e)??e,[]),d=(0,Z.useCallback)(()=>{},[]),f=(0,Z.useRef)(``),p=(0,Z.useRef)(``),m=(0,Z.useMemo)(()=>e.filter(e=>e.value!==`input`),[e]),h=s,g=(0,Z.useRef)(a);g.current=a;let _=(0,Z.useRef)(m.length);_.current=m.length;let v=(0,Z.useRef)(h);v.current=h;let y=(0,Z.useRef)(t);y.current=t;let b=(0,Z.useRef)(r);b.current=r;let x=(0,Z.useRef)(m);x.current=m;let S=(0,Z.useCallback)(()=>{let e=x.current[g.current];if(e)if(v.current){let t=l.current?.text?.trim();if(t){let n=u(t),r=e.value===`accept`?`accept`:`reject`;y.current({decision:r,userMessage:n}),d()}}else e.value!==`input`&&y.current({decision:e.value})},[u,d]),C=(0,Z.useRef)(S);C.current=S;let w=(0,Z.useCallback)(e=>{if(e.trim()){let t=x.current[g.current],n=u(e.trim()),r=t?.value===`accept`?`accept`:`reject`;y.current({decision:r,userMessage:n}),d()}},[u,d]),T=(0,Z.useCallback)(e=>{if(e.key.upArrow||e.key.downArrow){let t=x.current[g.current],n=l.current?.text||``;t?.value===`accept`?f.current=n:t?.value===`reject`&&(p.current=n),c(!1),e.key.upArrow?o(e=>Math.max(0,e-1)):o(e=>Math.min(_.current-1,e+1)),e.preventDefault();return}if(e.key.tab){let t=x.current[g.current];t?.value===`accept`?f.current=``:t?.value===`reject`&&(p.current=``),d(),c(!1),e.preventDefault();return}if(e.key.escape){d(),c(!1),y.current({decision:`reject`}),e.preventDefault();return}},[d]);sI((0,Z.useCallback)((e,t)=>{if(!v.current){if(t.upArrow){o(e=>Math.max(0,e-1));return}if(t.downArrow){o(e=>Math.min(_.current-1,e+1));return}if(t.escape){y.current({decision:`reject`});return}if(t.tab&&t.shift){if(b.current){b.current();return}let e=x.current.findIndex(e=>e.value===`allowAlways`);e!==-1&&(o(e),setTimeout(()=>{y.current({decision:`allowAlways`})},0));return}if(t.tab){let e=x.current[g.current];if(e&&(e.value===`accept`||e.value===`reject`)){c(!0);let t=e.value===`accept`?f.current:p.current;setTimeout(()=>{l.current&&t&&l.current.setText(t)},0)}return}if(t.return){C.current();return}}},[]),{isActive:!0}),(0,Z.useEffect)(()=>{let e=m[a];e&&(e.value!==`accept`&&e.value!==`reject`||(e.value===`accept`?f.current:p.current)&&!s&&c(!0))},[a,m,s]);let E=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{s&&(E.current=!0)},[s]),(0,Z.useEffect)(()=>{if(!s||!E.current)return;let e=m[a];if(!e)return;let t=e.value===`accept`?f.current:e.value===`reject`?p.current:``;t?setTimeout(()=>{l.current&&l.current.text===``&&l.current.setText(t),E.current=!1},0):E.current=!1},[s,a,m]);let D=m[a],O=s&&D,k=e=>e.value===`accept`?`Yes, `:e.value===`reject`?`No, `:``,A=!s&&D&&(D.value===`accept`||D.value===`reject`),j=m.some(e=>e.value===`allowAlways`||e.value===`allowAlwaysWithRule`);return(0,X.jsxs)(Q,{flexDirection:`column`,children:[m.map((e,t)=>{let r=t===a,i=O&&r,o=e.value===`accept`?f.current:e.value===`reject`?p.current:``;return(0,X.jsx)(e8,{option:!i&&o?{...e,label:`${e.label}, ${o}`}:e,index:t,isSelected:r,showAsInput:i,inputPrefix:k(e),inputPlaceholder:n,inputBufferRef:l,onInputSubmit:w,onInputKeyDown:T},t)}),(0,X.jsx)(Q,{flexDirection:`row`,marginTop:1,gap:2,children:s?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`enter submit`}),(0,X.jsx)($,{dimColor:!0,children:`tab discard note`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]}):(0,X.jsxs)(X.Fragment,{children:[(0,X.jsx)($,{dimColor:!0,children:`↑↓ navigate`}),(0,X.jsx)($,{dimColor:!0,children:`enter select`}),A&&(0,X.jsx)($,{dimColor:!0,children:`tab add note`}),i&&(0,X.jsxs)($,{dimColor:!0,children:[`shift+tab `,i]}),!i&&j&&(0,X.jsx)($,{dimColor:!0,children:`shift+tab don't ask again`}),(0,X.jsx)($,{dimColor:!0,children:`esc reject`})]})})]})});t8.displayName=`PermissionOptions`;function n8(e){return e.decision===`accept`&&e.userMessage?{type:`accept_with_message`,message:e.userMessage}:e.decision===`reject`&&e.userMessage?{type:`reject_with_message`,message:e.userMessage}:e.decision===`allowAlwaysWithRule`?e.rule?{type:`allow_always_with_rule`,rule:e.rule}:`accept`:e.decision}const r8=(0,Z.memo)(({filePath:e,originalContent:t,newContent:n,diffShownInEditor:r,onResolve:i})=>{let a=!t,{agentMode:o}=$K(),s=o===xl.PlanMode,c=Gk(e,process.cwd()),l=[{label:`Yes, apply changes`,value:`accept`},...s?[]:[{label:`Yes, and always allow Edit(${c})`,value:`allowAlwaysWithRule`}],{label:`No, reject changes`,value:`reject`}],u=e=>{if(e.decision===`allowAlwaysWithRule`){i({type:`allow_always_with_rule`,rule:`Edit(${c})`});return}i(n8(e))};return r?(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`${a?`Create`:`Update`} file ${e}`,subtitle:`Opened changes in the editor`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:l,onSelect:u,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]}):(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`${a?`Create`:`Update`} file ${e}`}),a?(0,X.jsx)(zK,{filePath:e,content:n,maxLines:100}):(0,X.jsx)(Fq,{filePath:e,originalContent:t,newContent:n,paddingLeft:1}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:l,onSelect:u,onModeSwitch:()=>i(`allowAlways`),modeSwitchHint:`auto-accept all edits`})})]})});r8.displayName=`EditFilePermissionUI`;const i8=(0,Z.memo)(({filePath:e,onResolve:t})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`Delete file ${e}`}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{color:`red`,children:e})}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:[{label:`Yes, delete file`,value:`accept`},{label:`No, keep file`,value:`reject`}],onSelect:e=>{t(n8(e))}})})]}));i8.displayName=`DeleteFilePermissionUI`;const a8=(0,Z.memo)(({description:e,url:t,displayName:n,onResolve:r})=>{let i=[{label:`Yes, allow action`,value:`accept`},{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`},{label:`No, deny action`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`Browser action: ${e}`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),t&&(0,X.jsxs)($,{dimColor:!0,children:[`URL: `,t]})]}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:i,onSelect:e=>{if(e.decision===`allowAlwaysWithRule`){r({type:`allow_always_with_rule`,rule:n});return}r(n8(e))}})})]})});a8.displayName=`BrowserActionPermissionUI`;const o8=(0,Z.memo)(({command:e,background:t,onResolve:n})=>{let r=Uk(e),i=[{label:`Yes, run command`,value:`accept`},{label:`Yes, and always allow Bash(${r})`,value:`allowAlwaysWithRule`},{label:`No, skip command`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`Bash command`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:(0,OK.supportsLanguage)(`bash`)?(()=>{try{return(0,OK.highlight)(e,{language:`bash`})}catch{return e}})():e}),t&&(0,X.jsx)(Q,{paddingTop:1,children:(0,X.jsx)($,{dimColor:!0,children:`(Running in background)`})})]}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:i,onSelect:e=>{if(e.decision===`allowAlwaysWithRule`){n({type:`allow_always_with_rule`,rule:`Bash(${r})`});return}n(n8(e))},inputPlaceholder:`Type here to tell AbacusAI what to do differently`,onModeSwitch:()=>n(`allowAlways`),modeSwitchHint:`allow all tools`})})]})});o8.displayName=`RunTerminalPermissionUI`;const s8=(0,Z.memo)(({title:e,description:t,toolName:n,onResolve:r})=>{let i=[{label:`Yes, allow`,value:`accept`},...n?[{label:`Yes, and always allow ${n}`,value:`allowAlwaysWithRule`}]:[],{label:`No, deny`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:e}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:(0,X.jsx)($,{children:(0,OK.supportsLanguage)(`json`)?(()=>{try{return(0,OK.highlight)(t,{language:`json`})}catch{return t}})():t})}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:i,onSelect:e=>{if(e.decision===`allowAlwaysWithRule`&&n){r({type:`allow_always_with_rule`,rule:n});return}r(n8(e))}})})]})});s8.displayName=`GenericPermissionUI`;const c8=(0,Z.memo)(({planFilePath:e,planContent:t,onResolve:n})=>(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`Ready to code? Implement plan: ${e.length>60?`…${e.slice(-60)}`:e}`}),t&&(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{dimColor:!0,children:`Here is Abacus's plan:`}),(0,X.jsx)(J3,{children:t})]}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:[{label:`Yes, implement the plan (approve each edit)`,value:`accept`},{label:`Yes, implement the plan (auto-accept all edits)`,value:`allowAlways`,hint:`shift+tab`},{label:`No, keep planning`,value:`reject`}],onSelect:e=>{n(n8(e))},inputPlaceholder:`Add instructions for the implementation`})})]}));c8.displayName=`ExitPlanModePermissionUI`;const l8=(0,Z.memo)(({filePath:e,deducedDirectory:t,onResolve:n})=>{let r=[{label:`Yes, allow read`,value:`accept`},{label:`Yes, and always allow ${t}`,value:`allowAlways`},{label:`No, deny read`,value:`reject`}];return(0,X.jsxs)(Q,{flexDirection:`column`,children:[(0,X.jsx)(h1,{title:`Read file outside workspace`}),(0,X.jsxs)(Q,{flexDirection:`column`,paddingLeft:1,paddingY:1,children:[(0,X.jsx)($,{children:e}),(0,X.jsxs)($,{dimColor:!0,children:[`Directory: `,t]})]}),(0,X.jsx)(Q,{borderStyle:m1,borderBottom:!0,borderTop:!1,borderLeft:!1,borderRight:!1}),(0,X.jsx)(Q,{flexDirection:`column`,paddingLeft:1,children:(0,X.jsx)(t8,{options:r,onSelect:e=>{n(n8(e))}})})]})});l8.displayName=`ReadOutsideDirectoryPermissionUI`;const u8=(0,Z.memo)(({pendingTool:e})=>{let{request:t,resolve:n}=e;switch(t.type){case`edit_file`:return(0,X.jsx)(r8,{filePath:t.filePath,originalContent:t.originalContent,newContent:t.newContent,diffShownInEditor:t.diffShownInEditor,onResolve:n});case`delete_file`:return(0,X.jsx)(i8,{filePath:t.filePath,onResolve:n});case`run_terminal`:return(0,X.jsx)(o8,{command:t.command,background:t.background,onResolve:n});case`browser_action`:return(0,X.jsx)(a8,{description:t.description,url:t.url,displayName:t.displayName,onResolve:n});case`generic`:return(0,X.jsx)(s8,{title:`Tool: ${t.toolName}`,description:t.inputSummary,toolName:t.toolName,onResolve:n});case`read_outside_directory`:return(0,X.jsx)(l8,{filePath:t.filePath,deducedDirectory:t.deducedDirectory,onResolve:n});case`exit_plan_mode`:return(0,X.jsx)(c8,{planFilePath:t.planFilePath,planContent:t.planContent,onResolve:n});case`ask_user_question`:return(0,X.jsx)($6,{questions:t.questions,onResolve:n});default:return null}});u8.displayName=`ToolPermissionUI`;function d8(e){let t=(0,Z.useRef)(!1),n=(0,Z.useRef)(e);(0,Z.useEffect)(()=>{n.current=e},[e]),(0,Z.useEffect)(()=>{let e=()=>{t.current||(t.current=!0,n.current())};return process.on(`exit`,e),process.on(`SIGINT`,e),process.on(`SIGTERM`,e),()=>{e(),process.off(`exit`,e),process.off(`SIGINT`,e),process.off(`SIGTERM`,e)}},[])}const f8=(0,Z.createContext)(null),p8=()=>{let e=(0,Z.use)(f8);if(!e)throw Error(`${p8.name} must be used within a ${m8.name}`);return e};function m8({children:e}){let t=(0,Z.useCallback)(e=>{let t=e.split(``).filter(e=>{let t=e.codePointAt(0);return!(t<=31||t===127)}).join(``);process.stdout.write(`${qX.SET_TITLE}${t}${qX.BEL}`)},[]);d8(()=>{process.stdout.write(`${qX.SET_TITLE}${qX.BEL}`)});let n=(0,Z.useMemo)(()=>({setTitle:t}),[t]);return(0,X.jsx)(f8.Provider,{value:n,children:e})}const h8=2e3;function g8(e,t,n){return e===Sl.ExecutingTool?`tool-executing`:e===Sl.Submitted||e===Sl.Streaming?`streaming`:e===Sl.WaitingForToolPermission&&t?`permission-ui`:n()?`idle-with-text`:`idle-empty`}function _8(e){let{agentStatus:t,hasPendingPermission:n,composerHasText:r,hasQueuedMessages:i,stopAgent:a,rejectPermission:o,saveAndClearComposer:s,clearComposer:c,dequeueOne:l,clearQueue:u,exitApp:d}=e,[f,p]=(0,Z.useState)(!1),[m,h]=(0,Z.useState)(null),g=(0,Z.useRef)(null),_=(0,Z.useRef)(null),v=(0,Z.useCallback)(()=>{p(!1),g.current&&=(clearTimeout(g.current),null)},[]),y=(0,Z.useCallback)(()=>{h(null),_.current&&=(clearTimeout(_.current),null)},[]),b=(0,Z.useCallback)(()=>{v(),y()},[v,y]),x=g8(t,n,r),S=(0,Z.useRef)(x);return(0,Z.useEffect)(()=>{let e=S.current;S.current=x,e!==x&&b()},[x,b]),sI((0,Z.useEffectEvent)((e,x)=>{if(x.ctrl&&e===`z`){process.platform!==`win32`&&process.kill(process.pid,`SIGTSTP`);return}let S=x.escape,C=x.ctrl&&e===`c`,w=x.ctrl&&e===`d`;if(!S&&!C&&!w)return;let T=g8(t,n,r);if(T===`tool-executing`||T===`streaming`){b(),a();return}if(T===`permission-ui`){b(),o();return}if(T===`idle-with-text`){if(S){f?(c(),b()):(y(),p(!0),g.current=setTimeout(()=>{p(!1),g.current=null},h8));return}let e=C?`c`:`d`;if(m===e){b(),d();return}if(m!==null){y(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},h8);return}v(),s(),i()&&u(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},h8);return}if(T===`idle-empty`){if(S){i()&&l();return}let e=C?`c`:`d`;if(m===e){b(),d();return}if(m!==null){y(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},h8);return}i()&&u(),h(e),_.current=setTimeout(()=>{h(null),_.current=null},h8)}}),{isActive:!0}),(0,Z.useEffect)(()=>()=>{g.current&&clearTimeout(g.current),_.current&&clearTimeout(_.current)},[]),{escClear:f,exitKey:m}}function v8(e){return e.type===`code_llm_tool_call`||e.type===`code_llm_agent_tool_request`}function y8(e){let t=e.toolUseResult;return!!(t?.rejected||t?.content?.startsWith(`Error:`))}function b8(e){if(e.type!==`code_llm_notification`)return!1;let t=(e.message??``).toLowerCase();return t.includes(`compacting conversation`)||t.includes(`compacted conversation`)}function x8(e){let t={toolUses:0,responses:0};for(let n of e)switch(n.type){case`code_llm_tool_call`:case`code_llm_agent_tool_request`:t.toolUses+=Array.isArray(n.toolUseRequest)?n.toolUseRequest.length:1;break;case`text`:n.source===`bot`&&t.responses++;break}return t}function S8(e,t){return{toolUses:e.toolUses+t.toolUses,responses:e.responses+t.responses}}function C8(e){let t={toolUses:0,responses:0},n=[],r=[],i=0,a=[];for(let a=0;a<e.length;a++){let o=e[a];if(b8(o)){let e=x8(n);t=S8(t,e),r.push(...n),n=[],i++;continue}n.push(o)}i>0&&a.push({kind:`compacted`,id:`compacted-${i}`,counts:t,segments:r});let o=w8(n);return a.push(...o),a}function w8(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r.type===`thinking`){t.push({kind:`segment`,segment:r}),n++;continue}if(v8(r)&&K6.has(T8(r))){let i=[r],a=n+1;for(;a<e.length;){let t=e[a];if(t.type===`thinking`){a++;continue}if(y8(i[i.length-1]))break;if(v8(t)&&K6.has(T8(t)))i.push(t),a++;else break}i.length===1?t.push({kind:`segment`,segment:i[0]}):t.push({kind:`tool-group`,id:i[0].id,segments:i}),n=a;continue}t.push({kind:`segment`,segment:r}),n++}return t}function T8(e){let t=e.toolUseRequest;return t?Array.isArray(t)?t[0]?.name??``:t.name??``:``}function E8(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.type===`thinking`)return{thinkingStartTime:n.thinkingStartTime??null,thinkingEndTime:n.thinkingEndTime??null}}return{thinkingStartTime:null,thinkingEndTime:null}}function D8({timing:e}){let{setTitle:t}=p8(),{segments:n,agentStatus:r,pendingToolPermission:i,conversationTitle:a,conversationId:o,addNotification:s,stop:c,rejectPendingPermission:l,removeFirstFromQueue:u,clearQueue:d}=RZ(),f=(0,Z.useRef)(null),{authExpired:p,clearAuthExpired:m,apiClient:h}=xZ();(0,Z.useEffect)(()=>{p&&(s(`Session expired — use /login to authenticate again.`,`error`),m())},[p,s,m]);let[g,_]=(0,Z.useState)(null),v=(0,Z.useCallback)(()=>{_(e=>e===null?n.filter(e=>!e.temp&&!e.isSpinny):null)},[n]);sI((0,Z.useCallback)((e,t)=>{(t.ctrl||t.super)&&e===`o`&&v()},[v]),{isActive:g===null});let{lastItem:y,prevItems:b}=(0,Z.useMemo)(()=>{let e=C8(n.filter(e=>!e.temp&&!e.isSpinny));return{lastItem:e.at(-1)??null,prevItems:e.slice(0,-1)}},[n]),{thinkingStartTime:x,thinkingEndTime:S}=(0,Z.useMemo)(()=>E8(n),[n]),C=(0,Z.useRef)(Sl.Idle),[w,T]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{let e=C.current===Sl.Idle,t=r!==Sl.Idle&&r!==Sl.WaitingForToolPermission;e&&t?T(Date.now()):r===Sl.Idle&&T(null),C.current=r},[r]);let E=r===Sl.WaitingForToolPermission&&i!==null,[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(`0`),[j,M]=(0,Z.useState)(0);(0,Z.useEffect)(()=>{t(a?`${a} • Abacus.AI CLI`:`Abacus.AI CLI`)},[a,t]),(0,Z.useEffect)(()=>Qj(async()=>{let t=e.getFormattedDuration(),n=0;if(o)try{n=await kQ(h,o)}catch{}M(n),A(t),O(!0),await new Promise(e=>setTimeout(e,100))},{wait:2e3,streams:[process.stdout,process.stderr]}),[e,o,h]);let N=_8({agentStatus:r,hasPendingPermission:i!==null,composerHasText:()=>f.current?.hasText()??!1,hasQueuedMessages:()=>f.current?.hasQueue()??!1,stopAgent:c,rejectPermission:l,saveAndClearComposer:()=>f.current?.saveAndClear(),clearComposer:()=>f.current?.clear(),dequeueOne:u,clearQueue:d,exitApp:()=>$j(0)}),P=r!==Sl.Idle&&r!==Sl.WaitingForToolPermission,F=i?.request.tool.id??null;return g===null?(0,X.jsxs)(X.Fragment,{children:[(0,X.jsxs)(Q,{flexDirection:`column`,gap:1,paddingBottom:1,width:`95%`,children:[(0,X.jsx)(z6,{}),(0,X.jsxs)(kK.Provider,{value:F,children:[b.map(e=>e.kind===`compacted`?(0,X.jsx)(lQ,{counts:e.counts,segments:e.segments},e.id):e.kind===`segment`?(0,X.jsx)(d6,{segment:e.segment},e.segment.id):(0,X.jsx)(Q6,{segments:e.segments},e.id)),y&&(y.kind===`compacted`?(0,X.jsx)(lQ,{counts:y.counts,segments:y.segments},y.id):y.kind===`segment`?(0,X.jsx)(d6,{segment:y.segment},y.segment.id):(0,X.jsx)(Q6,{segments:y.segments},y.id))]}),P&&(0,X.jsx)(A0,{onError:e=>{process.stderr.write(`[status-indicator error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(G6,{status:r,thinkingStartTime:x,thinkingEndTime:S,runStartTime:w})})]}),D?(0,X.jsx)(j0,{duration:k,credits:j,conversationId:o}):(0,X.jsxs)(X.Fragment,{children:[E&&(0,X.jsx)(A0,{onError:e=>{process.stderr.write(`[tool-permission error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(u8,{pendingTool:i})}),(0,X.jsx)(Z.Activity,{mode:E?`hidden`:`visible`,children:(0,X.jsx)(A0,{fallback:e=>(0,X.jsxs)(Q,{flexDirection:`column`,paddingX:1,children:[(0,X.jsx)($,{color:`red`,bold:!0,children:`Something went wrong in the input area.`}),(0,X.jsx)($,{color:`yellow`,children:e.message}),(0,X.jsxs)($,{dimColor:!0,children:[`Press Escape to restart the CLI, or resume with: `,ke.binName,` -c`,` `,o]})]}),onError:e=>{process.stderr.write(`[composer error] ${e.stack??e.message}\n`)},children:(0,X.jsx)(k0,{hints:N,composerRef:f})})})]})]}):(0,X.jsx)(f6,{snapshot:g,onClose:()=>_(null)})}async function O8({apiClient:e,authManager:t,configService:n,agentArgs:r}){let i=new gL,a=new Q3,o,s=r?.[`permission-mode`];if(s)switch(s){case`yolo`:o=xl.Yolo;break;case`accept-edits`:o=xl.AcceptEdits;break;case`plan`:o=xl.PlanMode;break;default:o=xl.Normal;break}else r?.[`dangerously-skip-permissions`]?o=xl.Yolo:r?.[`auto-accept-edits`]?o=xl.AcceptEdits:r?.[`plan-mode`]&&(o=xl.PlanMode);let c=process.stdout,l=e=>{c&&c.writable&&c.write(e)},u=()=>l(qX.HIDE_CURSOR),d=()=>l(qX.SHOW_CURSOR);u();let f=rI((0,X.jsx)(zL,{children:(0,X.jsx)(SZ,{client:e,authManager:t,children:(0,X.jsx)(yL,{client:i,children:(0,X.jsx)(hQ,{children:(0,X.jsx)(m8,{children:(0,X.jsx)(yZ,{children:(0,X.jsx)(fQ,{configService:n,children:(0,X.jsx)(UX,{children:(0,X.jsx)(nq,{initialMode:o,children:(0,X.jsx)(GX,{children:(0,X.jsx)(LZ,{apiClient:e,configService:n,agentArgs:r,children:(0,X.jsx)(D8,{timing:a})})})})})})})})})})})}),{exitOnCtrlC:!1,suspendable:!0,onSuspended:()=>{process.stderr.write(`
12830
12830
  Abacus.AI has been suspended. Run \`fg\` to bring Abacus back.
12831
- `)}}),p=!1,m=()=>{p||(p=!0,d())},h=()=>{p||(p=!0,f.cleanupTerminal())};process.once(`exit`,h),await f.waitUntilExit(),process.off(`exit`,h),m()}function O8(e,t=1){throw console.error(NA.red(e)),$j(t),Error(e)}function k8(e){try{return new URL(e)}catch{O8(`Invalid ${ke.envPrefix}BASE_URL: ${e}`)}}function A8(e){(e?.[`output-format`]||e?.[`input-format`])&&!e?.print&&O8(`--output-format and --input-format flags can only be used with --print mode`)}async function j8(){let e=process.stdin;e.isTTY&&O8(`No prompt provided and no piped input detected. Either provide a prompt or pipe input.`);let t=``;for await(let n of e)t+=n;let n=t.trim();return n||O8(`No input provided`),n}async function M8(e){return e?.prompt?e.prompt:j8()}async function N8(e,t){let n=t.get(`baseUrl`);n&&(k8(n),e.setUrl(n),e.resetEndpoints(),await e.getApiEndpoint())}async function P8(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(ke.agentType))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}}async function F8(e,t){if(t?.version){console.log(`Abacus.AI CLI version ${PA}`),$j(0);return}if(A8(t),t?.print){let e=await M8(t);await oM({agentArgs:{...t,prompt:e}})}else{let n=await Qk.create(),r=new Oe(n,{error:(e,...t)=>Vj.error(e,...t),debug:(...e)=>Vj.debug(...e),warn:(e,...t)=>Vj.warn(e,...t)});await N8(r,e);let i=await P8(t,r);await D8({apiClient:r,authManager:n,configService:e,agentArgs:{...t,...i&&{conversationId:i}}})}}async function I8(){try{let e=await jj(PA);e||(console.log(`${ke.fullName} CLI is up to date (${PA})`),process.exit(0)),console.log(`Updating ${e.currentVersion} → ${e.latestVersion}...`),Pj(e)?(console.log(`✓ Updated to ${e.latestVersion}`),process.exit(0)):(console.error(`Update failed.`),process.exit(1))}catch(e){console.error(`Update check failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}async function L8(e){try{if(e.get(`autoUpdate`)===!1||Oj())return;let t=await jj(PA);if(!t)return;process.stderr.write(`Updating to ${t.latestVersion}...\n`),Pj(t)&&process.stderr.write(`✓ Updated
12832
- `)}catch{}}if(process.argv[2]===`upgrade`)await I8();else{let{values:e,positionals:t}=D({options:{help:{type:`boolean`,short:`h`},version:{type:`boolean`,short:`v`},model:{type:`string`,short:`m`},print:{type:`boolean`,short:`p`},resume:{type:`string`},continue:{type:`boolean`,short:`c`},"output-format":{type:`string`},"input-format":{type:`string`},"allow-editing":{type:`string`},"auto-accept-edits":{type:`boolean`},"dangerously-skip-permissions":{type:`boolean`},"plan-mode":{type:`boolean`},"permission-mode":{type:`string`},"allowed-tools":{type:`string`,multiple:!0},"disallowed-tools":{type:`string`,multiple:!0},"add-dir":{type:`string`,multiple:!0}},allowPositionals:!0,strict:!0});e.help&&(console.log(`Usage: abacus [options] [prompt]
12831
+ `)}}),p=!1,m=()=>{p||(p=!0,d())},h=()=>{p||(p=!0,f.cleanupTerminal())};process.once(`exit`,h),await f.waitUntilExit(),process.off(`exit`,h),m()}function k8(e,t=1){throw console.error(NA.red(e)),$j(t),Error(e)}function A8(e){try{return new URL(e)}catch{k8(`Invalid ${ke.envPrefix}BASE_URL: ${e}`)}}function j8(e){(e?.[`output-format`]||e?.[`input-format`])&&!e?.print&&k8(`--output-format and --input-format flags can only be used with --print mode`)}async function M8(){let e=process.stdin;e.isTTY&&k8(`No prompt provided and no piped input detected. Either provide a prompt or pipe input.`);let t=``;for await(let n of e)t+=n;let n=t.trim();return n||k8(`No input provided`),n}async function N8(e){return e?.prompt?e.prompt:M8()}async function P8(e,t){let n=t.get(`baseUrl`);n&&(A8(n),e.setUrl(n),e.resetEndpoints(),await e.getApiEndpoint())}async function F8(e,t){if(e?.resume)return e.resume;if(e?.continue)try{return((await t.getConversationsList(ke.agentType))?.result??[]).sort((e,t)=>{let n=e.lastEventCreatedAt?new Date(e.lastEventCreatedAt).getTime():0;return(t.lastEventCreatedAt?new Date(t.lastEventCreatedAt).getTime():0)-n})[0]?.deploymentConversationId}catch{}}async function I8(e,t){if(t?.version){console.log(`Abacus.AI CLI version ${PA}`),$j(0);return}if(j8(t),t?.print){let e=await N8(t);await oM({agentArgs:{...t,prompt:e}})}else{let n=await Qk.create(),r=new Oe(n,{error:(e,...t)=>Vj.error(e,...t),debug:(...e)=>Vj.debug(...e),warn:(e,...t)=>Vj.warn(e,...t)});await P8(r,e);let i=await F8(t,r);await O8({apiClient:r,authManager:n,configService:e,agentArgs:{...t,...i&&{conversationId:i}}})}}async function L8(){try{let e=await jj(PA);e||(console.log(`${ke.fullName} CLI is up to date (${PA})`),process.exit(0)),console.log(`Updating ${e.currentVersion} → ${e.latestVersion}...`),Pj(e)?(console.log(`✓ Updated to ${e.latestVersion}`),process.exit(0)):(console.error(`Update failed.`),process.exit(1))}catch(e){console.error(`Update check failed: ${e instanceof Error?e.message:String(e)}`),process.exit(1)}}async function R8(e){try{if(e.get(`autoUpdate`)===!1||Oj())return;let t=await jj(PA);if(!t)return;process.stderr.write(`Updating to ${t.latestVersion}...\n`),Pj(t)&&process.stderr.write(`✓ Updated
12832
+ `)}catch{}}if(process.argv[2]===`upgrade`)await L8();else{let{values:e,positionals:t}=D({options:{help:{type:`boolean`,short:`h`},version:{type:`boolean`,short:`v`},model:{type:`string`,short:`m`},print:{type:`boolean`,short:`p`},resume:{type:`string`},continue:{type:`boolean`,short:`c`},"output-format":{type:`string`},"input-format":{type:`string`},"allow-editing":{type:`string`},"auto-accept-edits":{type:`boolean`},"dangerously-skip-permissions":{type:`boolean`},"plan-mode":{type:`boolean`},"permission-mode":{type:`string`},"allowed-tools":{type:`string`,multiple:!0},"disallowed-tools":{type:`string`,multiple:!0},"add-dir":{type:`string`,multiple:!0}},allowPositionals:!0,strict:!0});e.help&&(console.log(`Usage: abacus [options] [prompt]
12833
12833
 
12834
12834
  Commands:
12835
12835
  upgrade Check for updates and install the latest version
@@ -12848,4 +12848,4 @@ Options:
12848
12848
  --permission-mode <mode> Permission mode: normal, accept-edits, yolo, plan
12849
12849
  --allowed-tools <pattern> Auto-allow tool patterns (can repeat)
12850
12850
  --disallowed-tools <pattern> Auto-deny tool patterns (can repeat)
12851
- --add-dir <path> Additional allowed directory (can repeat)`),process.exit(0));let n=new Bk({cwd:process.cwd()});await n.load(),await L8(n),await F8(n,{...e,prompt:t.length>0?t.join(` `):null}).catch(e=>{console.error(e),process.exit(1)})}export{};
12851
+ --add-dir <path> Additional allowed directory (can repeat)`),process.exit(0));let n=new Bk({cwd:process.cwd()});await n.load(),await R8(n),await I8(n,{...e,prompt:t.length>0?t.join(` `):null}).catch(e=>{console.error(e),process.exit(1)})}export{};