@sourcegraph/amp 0.0.1759147319-g41306c → 0.0.1759150769-gc5f674
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.js +8 -8
- package/package.json +1 -1
package/dist/main.js
CHANGED
@@ -1855,7 +1855,7 @@ Solutions:
|
|
1855
1855
|
|
1856
1856
|
`),Q.id,z,0.7,X);return X?.throwIfAborted(),yield*hZ8(U)}}function hZ8(J){return async function*(){let Q=J.message,Z=Q.choices[0];if(Z?.message){let G=[];if(Z.message.content)G.push({type:"text",text:Z.message.content});if(Z.message.tool_calls)for(let z of Z.message.tool_calls)try{let U=z,F=U.function?.arguments?JSON.parse(U.function.arguments):{};G.push({type:"tool_use",id:z.id,name:U.function?.name??"",input:F})}catch(U){let F=z;a.error("Failed to parse tool call arguments",U,{toolCallId:z.id,functionName:F.function?.name}),G.push({type:"tool_use",id:z.id,name:F.function?.name??"",inputPartialJSON:{json:F.function?.arguments??""}})}if(G.length>0){let z=e31(Z.finish_reason);yield{type:"assistant:message",message:{role:"assistant",content:G,state:{type:"complete",stopReason:z}}}}}let Y=((G)=>{let U=`${Q.model.includes("/")?Q.model.split("/")[0]:"anthropic"}/${G.replace(/^[^/]+\//,"")}`;return kc1(U)})(Q.model),K=Q.usage,q=K?{model:Q.model,maxInputTokens:Y,inputTokens:K.prompt_tokens,outputTokens:K.completion_tokens,cacheCreationInputTokens:null,cacheReadInputTokens:null,totalInputTokens:K.prompt_tokens}:{model:Q.model,maxInputTokens:Y,inputTokens:0,outputTokens:0,cacheCreationInputTokens:null,cacheReadInputTokens:null,totalInputTokens:0};return{model:Q.model,"~debugUsage":q,"~debugParamsUsed":{model:Q.model,finishReason:Z?.finish_reason}}}()}var fZ8=void 0;var LD0=p(()=>{OQ();B0();qD();C2();XJ();GD0();cw();jo();tI();YL1();wo();GL1();p4()});function OD0(J){if(J.before===void 0&&J.after===void 0)throw Error("unreachable");if(J.before===null&&J.after===null)throw Error("unreachable")}function $o(J,Q,Z){let X=new Map,Y=(q)=>{let G=void 0;for(let[z,U]of X.entries())for(let[F,W]of U.entries()){if(!u0.equalURIs(F,q))continue;if(!G||W.timestamp<G.timestamp)G=W}return G},K=async({filesFilter:q,toolUsesToRevert:G,pruneRevertedToolUses:z})=>{let U=new _5,F=new Map;for(let[D,M]of X.entries()){let V=G?G.has(D):!0;for(let[N,L]of M.entries()){if(q&&!q(N))continue;if(L.reverted)continue;let O=U.get(N)||{changesAfterKeep:[]};if(!V){if(!O.latestKeepChange||L.timestamp>O.latestKeepChange.timestamp)O.latestKeepChange=L}else O.changesAfterKeep.push(L),F.set(L,D);U.set(N,O)}}let W=Array.from(U.entries()).filter(([,{changesAfterKeep:D}])=>D.length>0);if(await Sa(W,gZ8,async([D,{latestKeepChange:M,changesAfterKeep:V}])=>{try{let N=V.reduce((O,A)=>A.timestamp<O.timestamp?A:O),L=M?M.after:N.isNewFile?null:N.before;await Z(D,L),sS(D,Q,Date.now());for(let O of V){O.reverted=!0;let A=F.get(O);if(A)try{let j={toolUseID:A,fileChangeID:O.id};await J.store(Q,j,O)}catch(j){a.error(`Error updating backup for file ${D}:`,j)}}}catch(N){a.error(`Error reverting file ${D}:`,N)}}),z&&G)for(let D of G)X.delete(D)};return{async getAllRecords(){return X},async record(q){if(!q.toolUse)return;let G=X.get(q.toolUse);if(!G)G=new _5,X.set(q.toolUse,G);if(G.has(q.uri))throw Error(`change to file ${q.uri} is already tracked for tool use ${q.toolUse}, multiple changes are not yet implemented`);let z=Y(q.uri),U=q.before===null,F=z?gF(z.before??"",q.after??"",q.uri):gF(q.before??"",q.after??"",q.uri),W=crypto.randomUUID(),H={id:W,uri:x8(q.uri),before:q.before??"",after:q.after??"",diff:F,isNewFile:U,reverted:!1,timestamp:Date.now()};sS(q.uri,Q,H.timestamp),G.set(q.uri,H),await J.store(Q,{toolUseID:q.toolUse,fileChangeID:W},H),a.debug("Recorded file change",{isNewFile:U,filePath:q.uri.toString(),toolUseID:q.toolUse})},async restoreFromBackups(){let q=await J.list(Q);X.clear();for(let G of q){let{toolUseID:z}=G,U=await J.load(Q,G);if(!U)continue;if(U.filePath&&!U.uri)U.uri=x8(S0.file(U.filePath));if(!X.has(z))X.set(z,new _5);X.get(z).set(U.uri,U)}return{totalBackups:q.length}},async revertAll(q){let G=new Set;for(let[z]of X.entries())G.add(z);await K({filesFilter:q?(z)=>u0.equalURIs(z,q):void 0,toolUsesToRevert:G,pruneRevertedToolUses:!1})},async revertChanges(q){await K({toolUsesToRevert:q,pruneRevertedToolUses:!0})},async cleanupBackups(){await J.cleanup(Q)},async getLastEdit(q){let G,z=0;for(let[U,F]of X.entries()){let W=F.get(q);if(W&&!W.reverted&&W.timestamp>=z)G=W,z=W.timestamp}if(!G)return;return{oldContent:G.before,newContent:G.after,revert:()=>{G.reverted=!0}}},dispose(){X.clear()}}}var gZ8=4;var Po=p(()=>{K8();B0();nG();H3();dc();va()});function zL1(J,Q){let Z={readFile:async(X,Y)=>{let K=await Q.getLastEdit(X);if(K)return K.newContent;return J.readFile(X,Y)},readBinaryFile:async(X,Y)=>{let K=await Z.readFile(X,Y);return new TextEncoder().encode(K)},getMtime:async(X,Y)=>{if(await Q.getLastEdit(X))return Date.now();return J.getMtime(X,Y)},stat:async(X,Y)=>{let K=await Q.getLastEdit(X);if(K)return{size:N2.bufferByteLengthCompat(K.newContent),isDirectory:!1};return J.stat(X,Y)},realpath:async(X,Y)=>{return J.realpath(X,Y)},findFiles:async(X,Y)=>{return J.findFiles(X,Y)},readdir:async(X,Y)=>{return J.readdir(X,Y)},access:async(X,Y)=>{if(await Q.getLastEdit(X))return;return J.access(X,Y)},watch:()=>DY};return Z}function AD0(J,Q,Z){let X={...zL1(J,Q),writeFile:async(Y,K,q)=>{await Q.record({toolUse:Z,uri:Y,before:await lv(X,Y,q),after:K})},mkdirp:async()=>{},rename:async(Y,K)=>{throw Error("Rename operations are not supported in this implementation")},delete:async(Y,K)=>{throw Error("Delete operations are not supported in this implementation")},isExclusiveWriterFor:async()=>!0,watch(){return DY},__isImmutableBaseFileSystem:!1,__trackedFileSystem:!0};return X}var jD0=p(()=>{i0();nS();hJ()});function To(J,Q,Z){async function X(Y,K,q){let G={};G.before=await lv(J,K),await q(),G.after=await lv(J,K),OD0(G),await Q.record({toolUse:Y,uri:K,...G})}return{...J,async writeFile(Y,K,q){await X(Z,Y,()=>J.writeFile(Y,K,q))},__isImmutableBaseFileSystem:!1,__trackedFileSystem:!0}}var UL1=p(()=>{Po();hJ()});function RD0(J,Q,Z,X){async function Y(q,G,z){let U=Q.fileSystemForURI(X(),q);if(U.mountedTree.fs==="os"&&!Jq(U))if(G!==null)await U.writeFile(q,G,{signal:z});else await U.delete(q,{signal:z})}let K=$o(J.fileChangeTrackerStorage,Z,Y);return{fileSystemReader:()=>{let q=Q.fileSystemWithMountedTrees(X());return $U1(q)?q.mapReader((G)=>{if(Jq(G))return zL1(G,K);return G}):q},trackedFileSystem:(q)=>{function G(z,U){if($U1(z))return{...z.map((F)=>G(F,U)),__trackedFileSystem:!0};if(Jq(z))return AD0(z,K,U);return To(z,K,U)}return G(Q.fileSystemWithMountedTrees(X()),q)},tracker:K}}var wD0=p(()=>{Po();hJ();jD0();UL1();wF()});async function ID0(J,Q=()=>!0){let Z=await J.getAllRecords(),X=Ca(Z,(K,q)=>Q(q)),Y=[];for(let[K,q]of X.entries()){let{added:G,removed:z,modified:U,created:F,reverted:W}=mZ8(q);if(!G&&!z&&!U)continue;Y.push({created:F,uri:x8(K),reverted:W,diff:void 0,after:void 0,diffStat:{added:G,removed:z,modified:U}})}return Y}function mZ8(J){let Q=J.diff.split(`
|
1857
1857
|
`),Z=0,X=0,Y=0;for(let G of Q){if(G.startsWith("+")&&!G.startsWith("+++"))Z++;if(G.startsWith("-")&&!G.startsWith("---"))X++;if(G.startsWith("@"))Y++}let K=J.reverted,q=J.isNewFile===!0;if(q)Z=J.after.split(`
|
1858
|
-
`).length,X=0,Y=0;return{added:Z,removed:X,modified:Y,created:q,reverted:K}}var ED0=p(()=>{K8();va()});function uZ8(J){if(J.action.type==="redact-tool-input"&&J.on.event!=="tool:post-execute")return"redact-tool-input action can only be used with tool:post-execute event";if(J.action.type==="send-user-message"&&J.on.event!=="tool:pre-execute")return"send-user-message action can only be used with tool:pre-execute event";return null}function FL1(J){if(!J||!Array.isArray(J))return[];return J.filter((Q)=>{if(Q.compatibilityDate!=="2025-05-13")return!1;let Z=uZ8(Q);if(Z)return a.warn(`Hook "${Q.id}" is invalid: ${Z}`),!1;return!0})}var $D0=p(()=>{B0()});function PD0(J,Q){if(!J)return{action:null};J=FL1(J);for(let Z of J){if(Z.if===!1)continue;if(Z.on.event==="tool:pre-execute"){if(!(Array.isArray(Z.on.tool)?Z.on.tool:[Z.on.tool]).includes(Q.toolUse.name))continue;let Y=JSON.stringify(Q.toolUse.input),K=Array.isArray(Z.on["input.contains"])?Z.on["input.contains"]:[Z.on["input.contains"]];for(let q of K)if(Y.includes(q)){if(a.debug(`Hook triggered: ${Z.id}`,{hookID:Z.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,matchString:q,action:Z.action}),Z.action.type==="send-user-message")return{hookID:Z.id,action:Z.action}}}}return{action:null}}function TD0(J,Q){if(!J)return{action:null};J=FL1(J);for(let Z of J){if(Z.if===!1)continue;if(Z.on.event==="tool:post-execute"){if(!(Array.isArray(Z.on.tool)?Z.on.tool:[Z.on.tool]).includes(Q.toolUse.name))continue;if(a.debug(`Post-execution hook triggered: ${Z.id}`,{hookID:Z.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,action:Z.action}),Z.action.type==="redact-tool-input")return{hookID:Z.id,action:Z.action}}}return{action:null}}function CD0(J,Q){if(!J)return{action:null};try{return J(Q.thread)}catch(Z){return a.error("Error processing assistant end-turn hook",Z),{action:null}}}async function Co(J,Q,Z){if(!Q.action)return{abortOp:!1};switch(Q.action.type){case"send-user-message":return await J.handle({type:"user:message",message:{content:[{type:"text",text:Q.action.message}],source:{type:"hook",hook:Q.hookID}}}),{abortOp:!0};case"redact-tool-input":if(!Z?.toolUseID)return a.warn("redact-tool-input action requires toolUseID in context"),{abortOp:!1};return await J.handle({type:"tool:processed",toolUse:Z.toolUseID,newArgs:Q.action.redactedInput}),a.debug("Tool input redacted",{hookID:Q.hookID,toolUseID:Z.toolUseID}),{abortOp:!1}}}var SD0=p(()=>{B0();$D0()});function dZ8(J){return J?J.length>=pZ8:!1}function cZ8(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z&&Z.role!=="info")return Z}return}function lZ8(J,Q){J["~debug"]={...J["~debug"]??{},...Q.usage?{lastInferenceUsage:Q.usage}:{},...Q.params?{lastInferenceInput:Q.params}:{}}}function vD0(J){return(Q)=>{switch(Q.v++,J.type){case"cancelled":{Mx(Q);let Z=Q.messages.at(-1);if(Z?.role==="user"){let X=Z.content.findLast((Y)=>Y.type==="tool_result");if(X)X.run.status="cancelled"}break}case"summary:created":{if(J.summary.type==="external"){if(!Q.summaryThreads)Q.summaryThreads=[];Q.summaryThreads.push(J.summary.summaryThreadID),Q.messages.push({role:"info",content:[{type:"summary",summary:{type:"thread",thread:J.summary.summaryThreadID}}]})}else if(J.summary.type==="internal")Q.messages.push({role:"info",content:[{type:"summary",summary:{type:"message",summary:J.summary.summary}}]});break}case"fork:created":{if(!Q.forkThreads)Q.forkThreads={};let Z=Q.forkThreads[J.fromMessageIndex]||[];Q.forkThreads={...Q.forkThreads,[J.fromMessageIndex]:[...Z,J.forkThreadID]},Q.v++;break}case"thread:truncate":{if(Q.messages.splice(J.fromIndex),Q.forkThreads){let Z=[];for(let X in Q.forkThreads){let Y=Number(X);if(Y>=J.fromIndex)Z.push(Y)}for(let X of Z)delete Q.forkThreads[X];if(Object.keys(Q.forkThreads).length===0)Q.forkThreads=void 0}break}case"user:message":{Mx(Q);let Z={role:"user",...J.message},X=mR(Z);if(J.index!==void 0){if(!Q.messages[J.index])throw Error(`user message at index ${J.index} not found`);Q.messages.splice(J.index,Q.messages.length-J.index,X)}else Q.messages.push(X);break}case"user:message-queue:dequeue":{if(Mx(Q),!Q.queuedMessages)return;let[Z,...X]=Q.queuedMessages;if(!Z)return;Q.messages.push(Z.queuedMessage),Q.queuedMessages=X;break}case"user:tool-input":{if(!UZ(Q,J.toolUse)){a.debug(`Ignoring user:tool-input delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(hC(Q,J.toolUse));if(!X){a.debug(`Ignoring user:tool-input delta for missing tool result block ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}X.userInput=J.value;break}case"tool:data":{if(!Sp(Q,J.toolUse)){a.debug(`Ignoring tool:data delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(mR(J.data));So(Q,J.toolUse,X);break}case"tool:processed":{let Z=Sp(Q,J.toolUse);if(!Z){a.debug(`Ignoring tool:processed delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=Z.block.input;Z.block.input=J.newArgs,Z.message.originalToolUseInput={...Z.message.originalToolUseInput,[J.toolUse]:X};break}case"assistant:message":{let Z=G7(Q,"assistant"),X=Z?.content.filter((Y)=>Y.type==="tool_use").map((Y)=>Y.id)||[];if(Mx(Q),Z?.state.type==="cancelled"){for(let Y of Q.messages)if(Y.role==="user")Y.content=Y.content.filter((K)=>{if(K.type==="tool_result"&&X.includes(K.toolUseID))return!1;return!0})}Q.messages.push(c8(J.message));break}case"assistant:message-delta":{let Z=J.event,X=Q.messages.at(-1);if(Z.type==="message_start"){let K=cZ8(Q);if(!K||K.role!=="user")throw Error("(unreachable) assistant message start without user message");return Mx(Q),Q.messages=[...Q.messages,{role:"assistant",content:[],state:{type:"streaming"}}],Q}let Y=c8(G7(Q,"assistant"));if(!Y)throw Error("(unreachable) no last assistant message to update");switch(Z.type){case"content_block_start":{if(Z.index!==Y.content.length)throw Error("(bug) content block delta out of order");let K;switch(Z.content_block.type){case"text":K={type:"text",text:""};break;case"thinking":K={type:"thinking",thinking:"",signature:""};break;case"redacted_thinking":K={type:"redacted_thinking",data:Z.content_block.data};break;case"tool_use":K={type:"tool_use",id:Z.content_block.id,name:Z.content_block.name,input:Z.content_block.input,inputPartialJSON:{json:""}};break;default:throw Error(`unsupported content block type: ${Z.content_block.type}`)}Y.content.push(K);break}case"content_block_delta":{let K=Y.content[Z.index];if(!K)throw Error("(bug) content block delta index out of bounds");switch(Z.delta.type){case"text_delta":{if(K.type!=="text")throw Error(`(bug) content block delta type mismatch: text_delta !== ${K.type}`);K.text+=Z.delta.text;break}case"input_json_delta":{if(K.type!=="tool_use")throw Error(`(bug) content block delta type mismatch: input_json_delta !== ${K.type}`);if(!K.inputPartialJSON)throw Error("(bug) input_json_delta without incomplete");K.inputPartialJSON.json+=Z.delta.partial_json;try{K.input=DF(K.inputPartialJSON.json),K.inputIncomplete=kD0(K.inputPartialJSON.json)}catch{K.input={}}break}case"thinking_delta":{if(K.type!=="thinking")throw Error(`(bug) content block delta type mismatch: thinking_delta !== ${K.type}`);K.thinking+=Z.delta.thinking;break}case"signature_delta":{if(K.type!=="thinking")throw Error(`(bug) content block delta type mismatch: signature_delta !== ${K.type}`);K.signature=Z.delta.signature;break}}break}case"content_block_stop":{let K=Y.content[Z.index];if(!K)throw Error("(bug) content block delta index out of bounds");if(K.type==="tool_use"){if(!K.inputPartialJSON)throw Error("(bug) content block stop without incomplete");if(K.inputPartialJSON.json==="")K.input={};else K.input=JSON.parse(K.inputPartialJSON.json);delete K.inputPartialJSON,delete K.inputIncomplete}break}case"message_delta":{if(Z.delta.stop_reason){if(Z.delta.stop_reason==="max_tokens"){for(let K of Y.content)if(K.type==="tool_use"&&K.inputPartialJSON)delete K.inputPartialJSON,So(Q,K.id,{status:"error",error:{message:"Ran into max tokens limit of 200 tokens. Received only partial input for tool."}})}else for(let K of Y.content)if(K.type==="tool_use"&&K.inputPartialJSON){a.debug("Found a block with inputPartialJSON still set on message_delta");try{if(K.inputPartialJSON.json!=="")K.input=JSON.parse(K.inputPartialJSON.json);else K.input={}}catch(q){a.error(`Failed to parse malformed JSON for tool_use ${K.id}`,q,{threadId:Q.id,blockId:K.id,input:K.inputPartialJSON.json});let G=`Malformed JSON: '${K.inputPartialJSON.json}'.`;So(Q,K.id,{status:"error",error:{message:G}})}delete K.inputPartialJSON}if(Y.state={type:"complete",stopReason:Z.delta.stop_reason},Y.state.stopReason==="tool_use"&&!Y.content.some((K)=>K.type==="tool_use"))Y.state.stopReason="end_turn"}break}case"message_stop":break}break}case"inference:completed":{if(lZ8(Q,{usage:J.usage,params:J.params}),!Q.env)Q.env={initial:{}};if(!Q.env.initial.tags)Q.env.initial.tags=[];let Z=`model:${J.model}`;if(!Q.env.initial.tags.includes(Z))Q.env.initial.tags=[...Q.env.initial.tags,Z];if(J.usage)for(let X=Q.messages.length-1;X>=0;X--){let Y=Q.messages[X];if(Y?.role==="assistant"){Y.usage=J.usage;break}}break}case"title":{Q.title=J.value||void 0;break}case"max-tokens":{Q.maxTokens=J.value||void 0;break}case"main-thread":{Q.mainThreadID=J.value||void 0;break}case"environment":{Q.env=c8(J.env);break}case"user:message-queue:enqueue":{if(!Q.queuedMessages)Q.queuedMessages=[];if(dZ8(Q.queuedMessages))break;let Z={role:"user",...J.message},X=mR(Z);Q.queuedMessages.push({id:xY("queued-"),queuedMessage:c8(X)});break}case"user:message-queue:discard":{if(J.id===void 0){Q.queuedMessages=[];break}let Z=Q.queuedMessages?.findIndex((X)=>X.id===J.id);if(Z===void 0)throw Error(`queued message with id ${J.id} not found`);Q?.queuedMessages?.splice(Z,1);break}case"info:manual-bash-invocation":{Q.messages.push({role:"info",content:[{type:"manual_bash_invocation",args:c8(J.args),toolRun:c8(J.toolRun),hidden:J.hidden}]});break}case"info:model-switch-start":{Q.messages.push({role:"info",content:[{type:"model_switch",switchType:"start",from:J.from,to:J.to,timestamp:J.timestamp??Date.now(),reason:J.reason,keyword:J.keyword,userMessageIndex:J.userMessageIndex}]});break}case"info:model-switch-end":{Q.messages.push({role:"info",content:[{type:"model_switch",switchType:"end",from:J.from,to:J.to,timestamp:J.timestamp??Date.now(),reason:J.reason,keyword:J.keyword,userMessageIndex:J.userMessageIndex}]});break}}}}function Mx(J){let Q=c8(G7(J,"assistant"));if(!Q)return;let Z=!1,X=[];if(Q.state.type==="streaming")Q.state={type:"cancelled"},Z=!0;else if(Q.state.type==="complete"){if(Q.content.some((K)=>K.type==="tool_use"&&("inputPartialJSON"in K)))Q.state={type:"cancelled"},Z=!0}if(Z){for(let K of Q.content)if(K.type==="tool_use"&&K.inputPartialJSON){X.push(K.id),a.debug(`Cleaning up partial tool_use ${K.id}`,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:J.id,blockID:K.id});try{if(K.inputPartialJSON.json!=="")K.input=DF(K.inputPartialJSON.json),K.inputIncomplete=kD0(K.inputPartialJSON.json);else K.input={}}catch(q){a.warn(`Failed to parse partial JSON for cancelled tool_use ${K.id}:`,q,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:J.id,blockID:K.id,input:K.inputPartialJSON.json}),K.input={}}delete K.inputPartialJSON}let Y=jQ(J);for(let K of X)if(!Y.has(K))So(J,K,{status:"cancelled"})}}function So(J,Q,Z){let X,Y=Sp(J,Q);if(Y){let q=Y.messageIndex;for(let G=q+1;G<J.messages.length;G++){let z=J.messages[G];if(z?.role==="user"){X=z;break}}}if(!X)X={role:"user",content:[]},J.messages.push(X);let K=hC(J,Q);if(K)K.run=c8(Z);else K={type:"tool_result",toolUseID:Q,run:c8(Z)},X.content.push(K)}function kD0(J){try{return DF(J.replace(/\\+$/,"")+'"')}catch{return DF(J)}}var pZ8=5;var _D0=p(()=>{Ul();OQ();B0();xU1();Z4()});function bD0(J){let Q=[],Z=/@((?:[^\s@\\,;]|\\.)+)/g,X;while((X=Z.exec(J))!==null){let Y=X[1],K=iZ8(Y).replace(/[.,;:!?)}\]]+$/,"");Q.push(K)}return Q}function iZ8(J){if(J.match(/^[A-Za-z]:[\\]/))return J.replace(/\\(.)/g,(Q,Z)=>{if(Z===" "||Z==="("||Z===")"||Z==="["||Z==="]"||Z==="?"||Z==="*")return Z;return Q});return J.replace(/\\(.)/g,"$1")}function vo(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}var xD0={};N6(xD0,{getUserState:()=>nZ8});async function nZ8(){if(!await RQ.isConnected())return;let Q=await q6(RQ.status),Z=Q.selections?.[0],X=vo(Z),Y=X&&Z?{line:Z.range.startLine,column:Z.range.startCharacter}:void 0;return{currentlyVisibleFiles:Q.visibleFiles??[],activeEditor:Q.openFile,cursorLocation:Y,cursorLocationLine:X?Z?.content:void 0,selectionRange:!X&&Z?{content:Z?.content,start:{line:Z?.range.startLine,column:Z?.range.startCharacter},end:{line:Z?.range.endLine,column:Z?.range.endCharacter}}:void 0}}var yD0=p(()=>{i0();ej()});async function fD0({configService:J,filesystem:Q},Z){let X=await q6(J.workspaceRoots)??[];if(X.length===0)return{role:"user",content:Z.content,source:Z.source,fileMentions:void 0,userState:void 0};let Y=await $l({fileSystem:Q},bD0(ZJ(Z.content)),{searchPaths:X}),K=await(await Promise.resolve().then(() => (yD0(),xD0))).getUserState();return{role:"user",content:Z.content,source:Z.source,fileMentions:Y,userState:{...K??Pt1}}}var hD0=p(()=>{i0();LF();Z4();IB()});class WL1{deps;threadID;async resumeInProgressTools(){for(let J of this.thread.messages){if(J.role!=="user")continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;if(!(!C5(Q.run)&&Q.run.status!=="blocked-on-user"&&!this.ops.tools[Q.toolUseID]))continue;let X=this.findToolUseById(Q.toolUseID);if(!X)continue;if(X.name===Q4||X.name===Pd1){this.findAndCancelToolRun(Q.toolUseID);continue}a.debug(`re-invoking tool ${X.name} with ID ${Q.toolUseID}`,{name:"resumeInProgressTools",threadID:this.threadID}),this.invokeTool(X,Q.userInput)}}await this.updateFileChanges()}findToolUseById(J){for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Z of Q.content)if(Z.type==="tool_use"&&Z.id===J)return Z}return}trackFilesFromHistory(){a.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let J of this.thread.messages){if(J.role==="user"&&J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Q)=>Q.uri).filter((Q)=>Q!==void 0));if(J.role==="user"){for(let Q of J.content)if(Q.type==="tool_result"&&Q.run.status==="done")this.trackFiles(Q.run.trackFiles??[])}}}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupPermissionsChangeHandler(){LU1.pipe(d8(),jg1(1),eA(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){for(let J=this.thread.messages.length-1;J>=0;J--){let Q=this.thread.messages[J];if(!Q||Q.role!=="user")continue;let Z=!1;for(let X of Q.content)if(X.type==="tool_result"&&X.run?.status==="blocked-on-user"&&X.toolUseID)Z=!0,this.checkAndApproveBlockedTool(X.toolUseID);if(!Z)break}}async checkAndApproveBlockedTool(J){try{let Q=this.findToolUseById(J);if(!Q){a.warn("Tool use block not found for blocked tool",{toolUseID:J});return}let Z=await ml(Q.name,Q.input??{},"thread",this.threadID,J);if(Z.permitted)a.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:J,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:J,value:{accepted:!0}});else a.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:J,reason:Z.reason})}catch(Q){a.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:J})}}async cleanupTaskToolSubThreads(J=this.thread.messages.length){let Q=this.thread.messages.slice(0,J),Z=vQ1(Q),X=new Set(Z.map((K)=>K.toolUseID)),Y=new Set;for(let[K]of this.registeredSubthreads.entries())if(!X.has(K))Y.add(K);for(let K of Y){let q=this.registeredSubthreads.get(K);if(q.fileChanges?.unsubscribe(),await q.worker?.revertFileChanges(),q.latestFiles=[],this.mergeAndEmit(),await this.cleanupThreadBackups(q.threadID),await q.worker?.asyncDispose(),this.deps.deleteThread)try{await this.deps.deleteThread(q.threadID)}catch(G){a.error(`Failed to delete Task tool sub-thread: ${q.threadID}`,G,{threadID:this.threadID,subThreadID:q.threadID})}else a.warn(`Cannot delete Task tool sub-thread: ${q.threadID} - threadHistoryService not available`,{threadID:this.threadID,subThreadID:q.threadID});this.registeredSubthreads.delete(K)}if(Y.size>0)this.emitSubthreads()}ops={tools:{},toolMessages:{},inference:null};_state=new P4("initial");state=this._state.pipe(d8(),r9({shouldCountRefs:!0}));handlePromise=Promise.resolve();ephemeralError=new P4(void 0);inferenceState=new P4("idle");summaryState=new P4("idle");fileChanges=new P4({files:[]});toolCallUpdates=new b8;trackedFiles=new VZ;fs;cachedFileChanges=[];registeredSubthreads=new Map;subthreadSequenceNumber=0;_subthreadsSubject=new P4([]);subthreads=this._subthreadsSubject.pipe(d8(),r9({shouldCountRefs:!0}));disposed$=new b8;isDisposed=!1;cancelledToolUses=new Set;constructor(J,Q){this.deps=J;this.threadID=Q;this.fs=RD0({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.vfs,Q,()=>nv(this.thread))}status=this.state.pipe(S9((J)=>J==="active"?J4(this.inferenceState.pipe(d8()),this.summaryState,this.fileChanges.pipe(d8()),this.ephemeralError,this.toolCallUpdates.pipe(d7(void 0))).pipe(g0(([Q,Z,X,Y])=>({state:J,inferenceState:Q,summaryState:Z,fileChanges:X,ephemeralError:Y?{message:Y.message,stack:"stack"in Y?Y.stack:void 0,error:"error"in Y&&Y.error&&typeof Y.error==="object"&&"error"in Y.error?Y.error.error:void 0}:void 0})),eA(this.disposed$)):K0.of({state:J})),r9({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(J),this.__testing__setThread(J)}updateThread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(vD0(J)),this.__testing__setThread(this.threadReadWriter.read())}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(J){}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),await this.initializeCompletedSubthreads(),this.thread.mainThreadID)return;if(Lc1(J)||Oc1(J)||kQ1(J)){this.inferenceState.next("cancelled");return}await this.resumeInProgressTools(),this.setupSettingsChangeHandlers();let Q=this.thread.messages.findLastIndex((X)=>X.role==="user"?Ac1(X):X.role==="assistant"&&X.state.type==="complete");if(Q===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Z=this.thread.messages[Q];switch(Z.role){case"user":this.onThreadDelta({type:"user:message",message:Z});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Z});break}}resumed=!1;async initializeCompletedSubthreads(){let J=vQ1(this.thread.messages);for(let{toolUseID:Q,threadID:Z,toolUse:X,toolResult:Y}of J){let K=C5(Y.run),q=Y.run.status==="blocked-on-user";if(K&&!q)await this.registerSubthread(Q,Z,X)}}async summarizeThread(){await this.acquireThread(),this.summaryState.next("summarizing"),await this.cancel();try{let J=await this.deps.threadSummaryService.summarizeThread(this.threadID);await this.handle({type:"summary:created",summary:{type:"internal",summary:J.summary}})}finally{this.summaryState.next("idle"),this.inferenceState.next("idle"),await this.handle({type:"user:message-queue:dequeue"}).catch((J)=>{a.error("Failed to dequeue messages after summarization",J,{threadID:this.threadID})})}}async createSummaryThread(){await this.acquireThread(),this.summaryState.next("creating-summary-thread"),await this.cancel();try{let J=await this.deps.threadSummaryService.createSummaryThread(this.threadID);return await this.handle({type:"summary:created",summary:{type:"external",summaryThreadID:J.threadID}}),J.threadID}finally{this.summaryState.next("idle"),await this.handle({type:"user:message-queue:dequeue"}).catch((J)=>{a.error("Failed to dequeue messages after summary thread creation",J,{threadID:this.threadID})})}}async forkThread(J){await this.acquireThread();let{threadService:Q}=this.deps,Z=await Q.forkThread(this.threadID,J);await this.handle({type:"fork:created",forkThreadID:Z.threadID,fromMessageIndex:J});let X=await Q.getPrimitiveProperty(this.threadID,"v");if(X!==null)await Q.flushVersion(this.threadID,X);return Z.threadID}async handle(J,Q){this.handlePromise=this.handlePromise.then(async()=>{await this.innerHandle(J,Q)}).catch((Z)=>{a.error("Unhandled error in handle promise queue",{err:Z},{threadID:this.threadID})}),await this.handlePromise}async innerHandle(J,Q){if(this.isDisposed){a.debug(`Skipping ${J.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Q?.aborted){a.debug(`Skipping ${J.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),J.type==="thread:truncate")await this.cleanupFileChanges(J.fromIndex),await this.cleanupTaskToolSubThreads(J.fromIndex);let Z=J;if(J.type==="user:message"){let X=await fD0({configService:this.deps.configService,filesystem:this.fs.fileSystemReader()},J.message);Z=SC(J,(Y)=>{if(Y.message=c8(X),Y.message.fileMentions?.imageBlocks?.length)a.debug(`Adding ${Y.message.fileMentions.imageBlocks.length} image attachments to message`,{name:"adding image attachments",threadID:this.threadID}),Y.message.content=[...Y.message.content,...Y.message.fileMentions.imageBlocks];if(!Y.message.meta)Y.message.meta={};Y.message.meta.sentAt=Date.now(),Q?.throwIfAborted()})}try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let X=J.type==="user:message"&&J.index!==void 0;if(this.updateThread(Z),this.onThreadDelta(Z),X)await this.cleanupFileChanges(),await this.cleanupTaskToolSubThreads(),await this.cleanupForkThreads()}catch(X){if(!DR(X))a.error("Ephemeral error during handle processing",X,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(X instanceof Error?X:Error(String(X)));else a.debug(`AbortError caught during handle processing for ${Z.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;onThreadDelta(J){switch(J.type){case"user:message":{if(J.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((Q)=>{if(Q.role==="user"){for(let Z of Q.content)if(Z.type==="tool_result"&&Z.run.status==="done"&&Z.run.trackFiles)this.trackFiles(Z.run.trackFiles);if(Q.fileMentions?.files)this.trackFiles(Q.fileMentions.files.map((Z)=>Z.uri).filter((Z)=>Z!==void 0))}});else this.trackFiles(J.message.fileMentions?.files?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0)??[]);this.runInferenceAndUpdateThread();break}case"user:message-queue:dequeue":{let Q=this.thread.messages.at(-1);if(!Q)break;if(Q.role!=="user")break;this.trackFiles(Q.fileMentions?.files?.map((Z)=>Z.uri).filter((Z)=>Z!==void 0)??[]),this.runInferenceAndUpdateThread();break}case"user:tool-input":{let Q=UZ(this.thread,J.toolUse);if(Q)this.invokeTool(Q,J.value);break}case"tool:data":{if(this.cancelledToolUses.has(J.toolUse)){this.updateThread({type:"tool:data",toolUse:J.toolUse,data:{status:"cancelled",reason:"cancelled by user message"}});return}let Q=UZ(this.thread,J.toolUse);if(J.data.status==="in-progress"&&Q?.name===c7){let Z=Q,X=SQ1(J.data.progress);if(X)this.registerSubthread(J.toolUse,X,Z)}if(C5(J.data))this.cancelledToolUses.delete(J.toolUse);if(Q){let Z=gD0(this.thread,J.toolUse);if(a.debug(`updated tool_result${Z?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${J.type}, ${J.toolUse}, ${J.data.status})`,threadID:this.threadID}),Z&&this.inferenceState.getValue()!=="cancelled")this.runInferenceAndUpdateThread()}this.toolCallUpdates.next();break}case"assistant:message":{let Q=this.findToolUsesNeedingInvocation(J.message);a.debug(`saw ${Q.length} tool uses (${Q.map((Z)=>Z.name).join(", ")})`,{name:`handleThreadDelta(${J.type})`,threadID:this.threadID});for(let Z of Q)this.invokeTool(Z,void 0);break}case"assistant:message-delta":{if(J.event.type==="message_start")a.debug("token usage",J.event.message.usage);else if(J.event.type==="message_delta"&&J.inferenceStart&&J.event.usage?.output_tokens){let Y=performance.now()-J.inferenceStart;a.debug("completed message",{outputTokens:J.event.usage.output_tokens,tokensPerSecond:J.event.usage.output_tokens/Y*1000,inferenceDuration:yU0(Y)})}let Q=G7(this.thread,"assistant");if(!Q)throw Error("no assistant message found");let Z=this.findToolUsesNeedingInvocation(Q);for(let X of Z)this.invokeTool(X,void 0);if(gD0(this.thread))this.runInferenceAndUpdateThread();break}case"user:message-queue:enqueue":{let Q=this.inferenceState.getValue(),Z=this.summaryState.getValue();if(JV1(this.thread,Q)!=="tool-running"&&Z==="idle"){if(Q==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(Q==="idle"){let Y=this.thread.messages.at(-1);if(Y?.role==="assistant"){if(Y.state.type==="cancelled"||Y.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(Y.state.type==="complete"&&Y.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(Y?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"cancelled":{let Q=vj(this.thread);if(Q)this.updateThread({type:"info:model-switch-end",from:Q.to,to:Q.from,reason:Q.reason,keyword:Q.keyword,userMessageIndex:Q.userMessageIndex});break}case"inference:completed":{let Q=G7(this.thread,"assistant");if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="end_turn"){let X=vj(this.thread);if(X)this.updateThread({type:"info:model-switch-end",from:X.to,to:X.from,reason:X.reason,keyword:X.keyword,userMessageIndex:X.userMessageIndex});if(this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else Co(this,CD0(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}))}break}}}findToolUsesNeedingInvocation(J){if(J.content.some((Y)=>Y.type==="tool_use"&&Y.inputPartialJSON))return[];if(!(J.state?.type==="complete"||J.state?.type==="cancelled"))return[];let X=jQ(this.thread);return J.content.filter((Y)=>Y.type==="tool_use").filter((Y)=>!X.has(Y.id)&&!this.cancelledToolUses.has(Y.id))}async getWorkspaceRoots(J){return await q6(this.deps.configService.workspaceRoots,J)??this.thread.env?.initial?.trees?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0).map(MX)??[]}isToolUseEffectivelyComplete(J){if(!J.inputPartialJSON)return!0;try{return JSON.parse(J.inputPartialJSON.json),!0}catch{return!1}}async invokeTool(J,Q){if(this.ops.tools[J.id])throw Error(`(bug) tool invocation already in progress: ${J.id}`);if(!this.isToolUseEffectivelyComplete(J))throw Error(`(bug) tool use is incomplete: ${J.id}`);let Z=await A9();if(Z.settings?.hooks){let Y=PD0(Z.settings.hooks,{threadID:this.threadID,toolUse:J}),{abortOp:K}=await Co(this,Y);if(K)return}let X=new AbortController;this.ops.tools[J.id]=X,this.updateThread({type:"tool:data",toolUse:J.id,data:{status:"in-progress"}});try{let Y=await this.getWorkspaceRoots(X.signal),K=vp(this.thread),q=new K0((W)=>{this.ops.toolMessages[J.id]=W}),G={...this.deps,dir:Y.at(0)??null,dirs:Y,tool:J.name,thread:this.thread,config:await A9(),trackedFiles:new VZ(this.trackedFiles),filesystem:this.fs.trackedFileSystem(J.id),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:J.id,todos:K,toolMessages:q,threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this)},z=this.deps.toolService.preprocessArgs?.(J.name,J.input,G);if(z)this.handle({type:"tool:processed",toolUse:J.id,newArgs:z});let U=z??J.input,F=this.deps.toolService.invokeTool(J.name,{args:U,userInput:Q},G).pipe(eA(this.disposed$),_G(()=>{delete this.ops.tools[J.id],this.ops.toolMessages[J.id]?.complete(),delete this.ops.toolMessages[J.id]})).subscribe({next:async(W)=>{if(a.debug(`${J.id}, ${W.status}`,{name:"invokeTool",threadID:this.threadID}),C5(W)){if(delete this.ops.tools[J.id],F.unsubscribe(),W.status==="done"&&W.trackFiles?.length)this.trackFiles(W.trackFiles);if(Z.settings?.hooks){let H=TD0(Z.settings.hooks,{threadID:this.threadID,toolUse:J});await Co(this,H,{toolUseID:J.id})}}await this.updateFileChanges(),await this.handle({type:"tool:data",toolUse:J.id,data:W},X.signal)},error:async(W)=>{await this.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:"message"in W?W.message:String(W),displayMessage:"displayMessage"in W?W.displayMessage:void 0}}},X.signal)},complete:()=>{}});PN(X.signal,()=>F.unsubscribe())}catch(Y){throw delete this.ops.tools[J.id],Y}}async cancelInProgressTools(){for(let J of Object.keys(this.ops.tools))await this.cancelTool(J)}cancelAllActiveTools(){let J=jQ(this.thread);for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Z of Q.content)if(Z.type==="tool_use"&&!Z.inputPartialJSON){let X=J.get(Z.id);if(!(X&&C5(X.run)))this.cancelledToolUses.add(Z.id)}}for(let Q of this.thread.messages)if(Q.role==="user"){for(let Z of Q.content)if(Z.type==="tool_result"){if(!C5(Z.run))this.cancelledToolUses.add(Z.toolUseID)}}}cancelUnstartedTools(){let J=jQ(this.thread),Q=this.thread.messages.findLastIndex((X)=>kQ1(X)),Z=Q===-1?this.thread.messages:this.thread.messages.slice(Q+1);for(let X of Z){if(X.role!=="assistant")continue;for(let Y of X.content)if(Y.type==="tool_use"&&!Y.inputPartialJSON){let K=J.get(Y.id);if(!K||K.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:Y.id,data:{status:"cancelled"}})}}}async runInferenceAndUpdateThread(){this.ops.inference?.abort(),this.ops.inference=null,this.inferenceState.next("running");let J=new AbortController;this.ops.inference=J,this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools();for(let F of this.thread.messages)if(F.role==="user"){for(let W of F.content)if(W.type==="tool_result"&&W.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:W.toolUseID,data:{status:"cancelled"}})}if(this.thread.messages.length===1&&this.thread.mainThreadID===void 0){let F=this.thread.messages[0];if(F.role!=="user")throw Error("(bug) first message is not a user message");if(this.deps.generateThreadTitle(F,this.thread.id,J.signal).then((W)=>{if(J.signal.aborted||this.isDisposed)return;if(this.thread.title!==W)this.updateThread({type:"title",value:W})}).catch((W)=>{if(!DR(W))a.error("generateThreadTitle error",W,{name:"ThreadWorker",threadID:this.threadID})}),this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(W)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...W}}})}).catch((W)=>{a.error("Failed to initialize thread environment",W,{threadID:this.threadID})})}let Z=await A9(),X=jc1(this.thread),Y=vj(this.thread),{model:K,activeSwitch:q,detection:G,baseModel:z}=$Y0(Z.settings,X,this.thread);if(!q&&G?.shouldSwitch&&G.targetModel){let F=X?this.thread.messages.indexOf(X):-1;if(F===-1){a.warn("Could not find triggering user message for model switch",{threadID:this.threadID,hasLastUser:!!X});return}this.updateThread({type:"info:model-switch-start",from:z,to:G.targetModel,reason:"keyword",keyword:G.detectedKeyword,userMessageIndex:F})}let U=q?.to||G?.targetModel||K;try{let[F,W,H]=U.match(/(.*?)\/(.*)/)??[],M=VD0(W??"",H??"").run(H??"",this.thread,{toolService:this.deps.toolService,configService:this.deps.configService,getThreadEnvironment:this.deps.getThreadEnvironment,latestConfig:A9,filesystem:this.fs.fileSystemReader(),threadService:this.deps.threadService},J.signal);while(!0){let V=await M.next();if(V.done){await this.handle({type:"inference:completed",model:V.value.model,usage:V.value["~debugUsage"],params:V.value["~debugParamsUsed"]});return}await this.handle(V.value,J.signal),J.signal?.throwIfAborted()}}catch(F){if(!(DR(F)||Ro1(F))){let W=F instanceof Error?F:Error(String(F));this.ephemeralError.next(W)}return}finally{if(this.ops.inference===J)this.ops.inference=null,this.inferenceState.next("idle")}}async findAndCancelToolRun(J,Q){if(this.cancelInference(),!UZ(this.thread,J))return;await this.cancelTool(J,Q)}async cancelToolOnly(J,Q){if(!UZ(this.thread,J))return;let X=this.cancelDataForToolRun(J);this.cancelSubthread(J);let Y=this.ops.toolMessages[J];if(Y){try{Y.next({type:"stop-command"})}catch(K){a.warn("Failed to send stop-command",{id:J,error:K})}Y.complete(),delete this.ops.toolMessages[J]}a.debug(`cancelToolOnly(${J})`),await this.handle({type:"tool:data",toolUse:J,data:X},Q)}invokeBashTool(J,Q,Z){return new K0((X)=>{let Y,K,q,z=((F)=>{return PN(F,()=>{if(a.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),q?.unsubscribe(),K?.unsubscribe(),X?.complete(),Y)this.handleManualBashInvocation(J,{status:"cancelled",progress:PQ1(Y)},Z)})})(Q);return(async()=>{try{if(Q.aborted){X.error(Error("Operation was aborted"));return}let F=await this.getWorkspaceRoots(Q),W=await A9(),H={...this.deps,dir:F.at(0)??null,dirs:F,tool:Q4,thread:this.thread,config:W,trackedFiles:new VZ(this.trackedFiles),filesystem:G10(this.fs.fileSystemReader()),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:Sj(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this)};K=this.deps.toolService.invokeTool(Q4,{args:J,userInput:{accepted:!0}},H).subscribe({next:(D)=>{Y=D,X.next(D)},error:(D)=>{X.error(D)},complete:()=>{if(Y)this.handleManualBashInvocation(J,Y,Z);X.complete()}}),q=this.disposed$.subscribe(()=>{z(),K?.unsubscribe(),X?.complete()})}catch(F){X.error(F)}})(),()=>{z(),K?.unsubscribe(),q?.unsubscribe()}})}async handleManualBashInvocation(J,Q,Z){await this.handle({type:"info:manual-bash-invocation",args:J,toolRun:Q,hidden:Z})}async cleanupThreadBackups(J){try{await this.fs.tracker.cleanupBackups(),a.debug(`Cleaned up backup files for thread ${J}`,{threadID:J})}catch(Q){a.error("Error cleaning up thread backups",Q,{threadID:J})}}cancelDataForToolRun(J){let Z=jQ(this.thread).get(J)?.run;return{status:"cancelled",progress:Z?PQ1(Z):void 0}}async cancelTool(J,Q){let Z=this.cancelDataForToolRun(J);this.cancelSubthread(J);let X=this.ops.toolMessages[J];if(X){try{X.next({type:"stop-command"})}catch(Y){a.warn("Failed to send stop-command",{id:J,error:Y})}X.complete(),delete this.ops.toolMessages[J]}a.debug(`cancelToolRun(${J})`),await this.handle({type:"tool:data",toolUse:J,data:Z},Q)}async cancel(){a.debug("cancel: aborting inference operation and tools"),this.cancelInference(),this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools(),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(Error(Gz1.USER_CANCELLED)),this.ops.inference=null;this.inferenceState.next("cancelled")}async retry(){if(a.debug("retry: retrying inference operation"),this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;this.inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}cancelSubthread(J){let Q=this.registeredSubthreads.get(J);if(Q&&Q.worker)Q.worker.cancel()}abortToolOp(J){this.ops.tools[J]?.abort(),delete this.ops.tools[J]}abortAllTools(){for(let J of Object.keys(this.ops.tools)){let Q=J,Z=this.ops.toolMessages[Q];if(Z)try{Z.next({type:"stop-command"}),Z.complete(),delete this.ops.toolMessages[Q]}catch(X){a.warn("Failed to send stop-command during disposal",{id:Q,error:X})}this.abortToolOp(Q)}}trackFiles(J){for(let Q of J)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let J=await this.fs.tracker.restoreFromBackups();a.debug(`Restored ${J.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(J){a.error("Error restoring file changes",J,{threadID:this.threadID})}}async revertFileChanges(J){for(let Q of this.registeredSubthreads.values()){let Z=Q?.worker;if(Z)await Z.revertFileChanges(J)}await this.fs.tracker.revertAll(J),await this.updateFileChanges()}async getAllTrackedChanges(){let J=new Map;for(let Z of this.registeredSubthreads.values()){let X=Z?.worker;if(X){let Y=await X.getAllTrackedChanges();for(let[K,q]of Y.entries())J.set(K,q)}}let Q=await this.fs.tracker.getAllRecords();for(let[Z,X]of Q.entries())J.set(Z,X);return J}async cleanupForkThreads(J=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:J})}async cleanupFileChanges(J=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,J).forEach((Y)=>{if(Y.role==="user"){for(let K of Y.content)if(K.type==="tool_result")Q.add(K.toolUseID)}else for(let K of Y.content)if(K.type==="tool_use")Q.add(K.id)});let Z=new Set,X=await this.fs.tracker.getAllRecords();for(let[Y]of X.entries())if(!Q.has(Y))Z.add(Y);if(Z.size===0)return;await this.fs.tracker.revertChanges(Z),await this.updateFileChanges()}async updateFileChanges(){this.cachedFileChanges=await ID0(this.fs.tracker),this.mergeAndEmit()}mergeAndEmit(){let J=new _5;for(let Z of this.cachedFileChanges)J.set(Z.uri,Z);for(let Z of this.registeredSubthreads.values())for(let X of Z.latestFiles??[])J.set(X.uri,X);let Q=J.size;if(Q>50)a.warn("Excessive file changes detected - potential memory issue",{name:"mergeAndEmit",threadID:this.threadID,fileChangeCount:Q,ownFileChanges:this.cachedFileChanges.length,subthreadCount:this.registeredSubthreads.size});this.fileChanges.next({files:[...J.values()]})}emitSubthreads(){let J=Array.from(this.registeredSubthreads.values()).sort((Q,Z)=>Q.sequenceNumber-Z.sequenceNumber).map((Q)=>({threadID:Q.threadID,toolUse:Q.toolUse,sequenceNumber:Q.sequenceNumber}));this._subthreadsSubject.next(J)}async registerSubthread(J,Q,Z){if(this.registeredSubthreads.has(J))return;let X=await dJ.getOrCreateForSubThread(this.deps,Q);await X.resume();let Y=X.status.pipe(vJ((K)=>K.state==="active"),g0((K)=>K.fileChanges.files),eA(this.disposed$)).subscribe((K)=>{let q=this.registeredSubthreads.get(J);if(!q)return;q.latestFiles=K,this.mergeAndEmit()});this.registeredSubthreads.set(J,{threadID:Q,worker:X,fileChanges:Y,toolUse:Z,sequenceNumber:++this.subthreadSequenceNumber}),this.emitSubthreads()}async asyncDispose(){if(this.isDisposed)return;if(a.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,subthreadCount:this.registeredSubthreads.size,activeToolCount:Object.keys(this.ops.tools).length}),this.isDisposed=!0,this.disposed$.next(),this.disposed$.complete(),await Promise.all(this.registeredSubthreads.values().map(async(J)=>{J.fileChanges?.unsubscribe(),await J.worker?.asyncDispose()})),this.registeredSubthreads.clear(),this.cancelledToolUses.clear(),this._state.complete(),this.ephemeralError.complete(),this.inferenceState.complete(),this.summaryState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this._subthreadsSubject.complete(),this.abortAllTools(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.fs.tracker.dispose(),this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}selectModel(J){return AD1(J,G7(this.thread,"user"))}}function gD0(J,Q){let Z=G7(J,"assistant");if(!Z||Z.state.type!=="complete"||Z.state.stopReason!=="tool_use")return!1;let X=Z.content.filter((q)=>q.type==="tool_use").map((q)=>q.id);if(Q&&!X.includes(Q))return a.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:J.id}),!1;if(X.length===0)return!1;let Y=jQ(J);return X.every((q)=>{let G=Y.get(q);if(!G||!C5(G.run))return!1;let z=G.run.status;return z!=="cancelled"&&z!=="rejected-by-user"})}var mD0=p(()=>{K8();i0();OQ();MR();B0();V4();LD0();nG();OU1();hJ();wD0();wF();Z9();C2();ED0();SD0();RD1();Z4();_D0();$3();hD0()});class pD0{threadWorkers=new ZC;async getOrCreateForThread(J,Q){if(await J.threadService.getPrimitiveProperty(Q,"mainThreadID"))return this.getOrCreateForSubThread(J,Q);return this.getOrCreateForThreadInternal(J,Q)}async getOrCreateForSubThread(J,Q){let Z=S5(J.toolService,wr);return this.getOrCreateForThreadInternal({...J,toolService:Z},Q)}async getOrCreateForThreadInternal(J,Q){let Z=this.threadWorkers.get(Q);if(!Z){if(Z=new WL1(J,Q),this.threadWorkers.set(Q,Z),this.threadWorkers.size>25)a.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return HL1.record(this.threadWorkers.size),Z}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(S9((J)=>J.size===0?K0.of({}):J4(...Array.from(J.values()).map((Q)=>Q.status.pipe(g0((Z)=>[Q.threadID,Q.threadReadWriter?d_(Q.thread,Z):void 0])))).pipe(g0((Q)=>Object.fromEntries(Q)))),hK(25),r9())}get(J){return this.threadWorkers.get(J)}prettyPrintToolRun(J,Q,Z){let X=this.threadWorkers.get(J);if(!X)throw Error(`No worker found for thread ${J}`);for(let Y of X.thread.messages)for(let K of Y.content)if(K.type==="tool_result"&&K.toolUseID===Q)return bU0(K.run,Z);throw Error(`Tool run not found for thread ${J} and tool use ${Q}`)}async cancelToolOnly(J,Q){await this.threadWorkers.get(J)?.cancelToolOnly(Q)}async cancel(J){await this.threadWorkers.get(J)?.cancel()}async dispose(J){let Q=this.threadWorkers.get(J);if(Q)await Q.asyncDispose(),this.threadWorkers.delete(J),HL1.record(this.threadWorkers.size);this.threadWorkers.dispose()}async retry(J){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);await Q.retry()}async revertFileChanges(J,Q){let Z=this.threadWorkers.get(J);if(!Z)throw Error(`No active worker for thread ${J}`);await Z.revertFileChanges(Q)}async cleanupThreadBackups(J,Q){let Z=this.threadWorkers.get(Q);if(Z)await Z.fs.tracker.cleanupBackups();else{let X=await J.threadService.get(Q);if(!X)return;let Y=J.vfs.fileSystemWithMountedTrees(nv(X));try{await new sv(Y).cleanup(Q),a.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(K){a.error("Error cleaning up thread backups",K,{threadID:Q})}}}async disposeAll(){await Promise.all(this.threadWorkers.values().map(async(J)=>await J.asyncDispose())),this.threadWorkers.clear(),HL1.record(0)}}var uD0,aZ8,HL1,dJ;var $3=p(()=>{uD0=u6(HC(),1);i0();B0();wF();Er();xU0();C2();tl();mD0();aZ8=uD0.metrics.getMeter("thread-worker-service"),HL1=aZ8.createGauge("thread_worker_count",{description:"Number of active thread workers"});dJ=new pD0});var Nx=e((lD0)=>{Object.defineProperty(lD0,"__esModule",{value:!0});lD0.regexpCode=lD0.getEsmExportName=lD0.getProperty=lD0.safeStringify=lD0.stringify=lD0.strConcat=lD0.addCodeArg=lD0.str=lD0._=lD0.nil=lD0._Code=lD0.Name=lD0.IDENTIFIER=lD0._CodeOrName=void 0;class ko{}lD0._CodeOrName=ko;lD0.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class JE extends ko{constructor(J){super();if(!lD0.IDENTIFIER.test(J))throw Error("CodeGen: name must be a valid identifier");this.str=J}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}lD0.Name=JE;class Cq extends ko{constructor(J){super();this._items=typeof J==="string"?[J]:J}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let J=this._items[0];return J===""||J==='""'}get str(){var J;return(J=this._str)!==null&&J!==void 0?J:this._str=this._items.reduce((Q,Z)=>`${Q}${Z}`,"")}get names(){var J;return(J=this._names)!==null&&J!==void 0?J:this._names=this._items.reduce((Q,Z)=>{if(Z instanceof JE)Q[Z.str]=(Q[Z.str]||0)+1;return Q},{})}}lD0._Code=Cq;lD0.nil=new Cq("");function dD0(J,...Q){let Z=[J[0]],X=0;while(X<Q.length)DL1(Z,Q[X]),Z.push(J[++X]);return new Cq(Z)}lD0._=dD0;var BL1=new Cq("+");function cD0(J,...Q){let Z=[Vx(J[0])],X=0;while(X<Q.length)Z.push(BL1),DL1(Z,Q[X]),Z.push(BL1,Vx(J[++X]));return rZ8(Z),new Cq(Z)}lD0.str=cD0;function DL1(J,Q){if(Q instanceof Cq)J.push(...Q._items);else if(Q instanceof JE)J.push(Q);else J.push(tZ8(Q))}lD0.addCodeArg=DL1;function rZ8(J){let Q=1;while(Q<J.length-1){if(J[Q]===BL1){let Z=sZ8(J[Q-1],J[Q+1]);if(Z!==void 0){J.splice(Q-1,3,Z);continue}J[Q++]="+"}Q++}}function sZ8(J,Q){if(Q==='""')return J;if(J==='""')return Q;if(typeof J=="string"){if(Q instanceof JE||J[J.length-1]!=='"')return;if(typeof Q!="string")return`${J.slice(0,-1)}${Q}"`;if(Q[0]==='"')return J.slice(0,-1)+Q.slice(1);return}if(typeof Q=="string"&&Q[0]==='"'&&!(J instanceof JE))return`"${J}${Q.slice(1)}`;return}function oZ8(J,Q){return Q.emptyStr()?J:J.emptyStr()?Q:cD0`${J}${Q}`}lD0.strConcat=oZ8;function tZ8(J){return typeof J=="number"||typeof J=="boolean"||J===null?J:Vx(Array.isArray(J)?J.join(","):J)}function eZ8(J){return new Cq(Vx(J))}lD0.stringify=eZ8;function Vx(J){return JSON.stringify(J).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}lD0.safeStringify=Vx;function JX8(J){return typeof J=="string"&&lD0.IDENTIFIER.test(J)?new Cq(`.${J}`):dD0`[${J}]`}lD0.getProperty=JX8;function QX8(J){if(typeof J=="string"&&lD0.IDENTIFIER.test(J))return new Cq(`${J}`);throw Error(`CodeGen: invalid export name: ${J}, use explicit $id name mapping`)}lD0.getEsmExportName=QX8;function ZX8(J){return new Cq(J.toString())}lD0.regexpCode=ZX8});var LL1=e((rD0)=>{Object.defineProperty(rD0,"__esModule",{value:!0});rD0.ValueScope=rD0.ValueScopeName=rD0.Scope=rD0.varKinds=rD0.UsedValueState=void 0;var $Z=Nx();class nD0 extends Error{constructor(J){super(`CodeGen: "code" for ${J} not defined`);this.value=J.value}}var bo;(function(J){J[J.Started=0]="Started",J[J.Completed=1]="Completed"})(bo||(rD0.UsedValueState=bo={}));rD0.varKinds={const:new $Z.Name("const"),let:new $Z.Name("let"),var:new $Z.Name("var")};class VL1{constructor({prefixes:J,parent:Q}={}){this._names={},this._prefixes=J,this._parent=Q}toName(J){return J instanceof $Z.Name?J:this.name(J)}name(J){return new $Z.Name(this._newName(J))}_newName(J){let Q=this._names[J]||this._nameGroup(J);return`${J}${Q.index++}`}_nameGroup(J){var Q,Z;if(((Z=(Q=this._parent)===null||Q===void 0?void 0:Q._prefixes)===null||Z===void 0?void 0:Z.has(J))||this._prefixes&&!this._prefixes.has(J))throw Error(`CodeGen: prefix "${J}" is not allowed in this scope`);return this._names[J]={prefix:J,index:0}}}rD0.Scope=VL1;class NL1 extends $Z.Name{constructor(J,Q){super(Q);this.prefix=J}setValue(J,{property:Q,itemIndex:Z}){this.value=J,this.scopePath=$Z._`.${new $Z.Name(Q)}[${Z}]`}}rD0.ValueScopeName=NL1;var MX8=$Z._`\n`;class aD0 extends VL1{constructor(J){super(J);this._values={},this._scope=J.scope,this.opts={...J,_n:J.lines?MX8:$Z.nil}}get(){return this._scope}name(J){return new NL1(J,this._newName(J))}value(J,Q){var Z;if(Q.ref===void 0)throw Error("CodeGen: ref must be passed in value");let X=this.toName(J),{prefix:Y}=X,K=(Z=Q.key)!==null&&Z!==void 0?Z:Q.ref,q=this._values[Y];if(q){let U=q.get(K);if(U)return U}else q=this._values[Y]=new Map;q.set(K,X);let G=this._scope[Y]||(this._scope[Y]=[]),z=G.length;return G[z]=Q.ref,X.setValue(Q,{property:Y,itemIndex:z}),X}getValue(J,Q){let Z=this._values[J];if(!Z)return;return Z.get(Q)}scopeRefs(J,Q=this._values){return this._reduceValues(Q,(Z)=>{if(Z.scopePath===void 0)throw Error(`CodeGen: name "${Z}" has no value`);return $Z._`${J}${Z.scopePath}`})}scopeCode(J=this._values,Q,Z){return this._reduceValues(J,(X)=>{if(X.value===void 0)throw Error(`CodeGen: name "${X}" has no value`);return X.value.code},Q,Z)}_reduceValues(J,Q,Z={},X){let Y=$Z.nil;for(let K in J){let q=J[K];if(!q)continue;let G=Z[K]=Z[K]||new Map;q.forEach((z)=>{if(G.has(z))return;G.set(z,bo.Started);let U=Q(z);if(U){let F=this.opts.es5?rD0.varKinds.var:rD0.varKinds.const;Y=$Z._`${Y}${F} ${z} = ${U};${this.opts._n}`}else if(U=X===null||X===void 0?void 0:X(z))Y=$Z._`${Y}${U}${this.opts._n}`;else throw new nD0(z);G.set(z,bo.Completed)})}return Y}}rD0.ValueScope=aD0});var _8=e((PZ)=>{Object.defineProperty(PZ,"__esModule",{value:!0});PZ.or=PZ.and=PZ.not=PZ.CodeGen=PZ.operators=PZ.varKinds=PZ.ValueScopeName=PZ.ValueScope=PZ.Scope=PZ.Name=PZ.regexpCode=PZ.stringify=PZ.getProperty=PZ.nil=PZ.strConcat=PZ.str=PZ._=void 0;var R9=Nx(),Sq=LL1(),fD=Nx();Object.defineProperty(PZ,"_",{enumerable:!0,get:function(){return fD._}});Object.defineProperty(PZ,"str",{enumerable:!0,get:function(){return fD.str}});Object.defineProperty(PZ,"strConcat",{enumerable:!0,get:function(){return fD.strConcat}});Object.defineProperty(PZ,"nil",{enumerable:!0,get:function(){return fD.nil}});Object.defineProperty(PZ,"getProperty",{enumerable:!0,get:function(){return fD.getProperty}});Object.defineProperty(PZ,"stringify",{enumerable:!0,get:function(){return fD.stringify}});Object.defineProperty(PZ,"regexpCode",{enumerable:!0,get:function(){return fD.regexpCode}});Object.defineProperty(PZ,"Name",{enumerable:!0,get:function(){return fD.Name}});var mo=LL1();Object.defineProperty(PZ,"Scope",{enumerable:!0,get:function(){return mo.Scope}});Object.defineProperty(PZ,"ValueScope",{enumerable:!0,get:function(){return mo.ValueScope}});Object.defineProperty(PZ,"ValueScopeName",{enumerable:!0,get:function(){return mo.ValueScopeName}});Object.defineProperty(PZ,"varKinds",{enumerable:!0,get:function(){return mo.varKinds}});PZ.operators={GT:new R9._Code(">"),GTE:new R9._Code(">="),LT:new R9._Code("<"),LTE:new R9._Code("<="),EQ:new R9._Code("==="),NEQ:new R9._Code("!=="),NOT:new R9._Code("!"),OR:new R9._Code("||"),AND:new R9._Code("&&"),ADD:new R9._Code("+")};class hD{optimizeNodes(){return this}optimizeNames(J,Q){return this}}class oD0 extends hD{constructor(J,Q,Z){super();this.varKind=J,this.name=Q,this.rhs=Z}render({es5:J,_n:Q}){let Z=J?Sq.varKinds.var:this.varKind,X=this.rhs===void 0?"":` = ${this.rhs}`;return`${Z} ${this.name}${X};`+Q}optimizeNames(J,Q){if(!J[this.name.str])return;if(this.rhs)this.rhs=ZE(this.rhs,J,Q);return this}get names(){return this.rhs instanceof R9._CodeOrName?this.rhs.names:{}}}class jL1 extends hD{constructor(J,Q,Z){super();this.lhs=J,this.rhs=Q,this.sideEffects=Z}render({_n:J}){return`${this.lhs} = ${this.rhs};`+J}optimizeNames(J,Q){if(this.lhs instanceof R9.Name&&!J[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ZE(this.rhs,J,Q),this}get names(){let J=this.lhs instanceof R9.Name?{}:{...this.lhs.names};return go(J,this.rhs)}}class tD0 extends jL1{constructor(J,Q,Z,X){super(J,Z,X);this.op=Q}render({_n:J}){return`${this.lhs} ${this.op}= ${this.rhs};`+J}}class eD0 extends hD{constructor(J){super();this.label=J,this.names={}}render({_n:J}){return`${this.label}:`+J}}class JM0 extends hD{constructor(J){super();this.label=J,this.names={}}render({_n:J}){return`break${this.label?` ${this.label}`:""};`+J}}class QM0 extends hD{constructor(J){super();this.error=J}render({_n:J}){return`throw ${this.error};`+J}get names(){return this.error.names}}class ZM0 extends hD{constructor(J){super();this.code=J}render({_n:J}){return`${this.code};`+J}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(J,Q){return this.code=ZE(this.code,J,Q),this}get names(){return this.code instanceof R9._CodeOrName?this.code.names:{}}}class uo extends hD{constructor(J=[]){super();this.nodes=J}render(J){return this.nodes.reduce((Q,Z)=>Q+Z.render(J),"")}optimizeNodes(){let{nodes:J}=this,Q=J.length;while(Q--){let Z=J[Q].optimizeNodes();if(Array.isArray(Z))J.splice(Q,1,...Z);else if(Z)J[Q]=Z;else J.splice(Q,1)}return J.length>0?this:void 0}optimizeNames(J,Q){let{nodes:Z}=this,X=Z.length;while(X--){let Y=Z[X];if(Y.optimizeNames(J,Q))continue;OX8(J,Y.names),Z.splice(X,1)}return Z.length>0?this:void 0}get names(){return this.nodes.reduce((J,Q)=>UL(J,Q.names),{})}}class gD extends uo{render(J){return"{"+J._n+super.render(J)+"}"+J._n}}class XM0 extends uo{}class Lx extends gD{}Lx.kind="else";class zW extends gD{constructor(J,Q){super(Q);this.condition=J}render(J){let Q=`if(${this.condition})`+super.render(J);if(this.else)Q+="else "+this.else.render(J);return Q}optimizeNodes(){super.optimizeNodes();let J=this.condition;if(J===!0)return this.nodes;let Q=this.else;if(Q){let Z=Q.optimizeNodes();Q=this.else=Array.isArray(Z)?new Lx(Z):Z}if(Q){if(J===!1)return Q instanceof zW?Q:Q.nodes;if(this.nodes.length)return this;return new zW(zM0(J),Q instanceof zW?[Q]:Q.nodes)}if(J===!1||!this.nodes.length)return;return this}optimizeNames(J,Q){var Z;if(this.else=(Z=this.else)===null||Z===void 0?void 0:Z.optimizeNames(J,Q),!(super.optimizeNames(J,Q)||this.else))return;return this.condition=ZE(this.condition,J,Q),this}get names(){let J=super.names;if(go(J,this.condition),this.else)UL(J,this.else.names);return J}}zW.kind="if";class QE extends gD{}QE.kind="for";class YM0 extends QE{constructor(J){super();this.iteration=J}render(J){return`for(${this.iteration})`+super.render(J)}optimizeNames(J,Q){if(!super.optimizeNames(J,Q))return;return this.iteration=ZE(this.iteration,J,Q),this}get names(){return UL(super.names,this.iteration.names)}}class KM0 extends QE{constructor(J,Q,Z,X){super();this.varKind=J,this.name=Q,this.from=Z,this.to=X}render(J){let Q=J.es5?Sq.varKinds.var:this.varKind,{name:Z,from:X,to:Y}=this;return`for(${Q} ${Z}=${X}; ${Z}<${Y}; ${Z}++)`+super.render(J)}get names(){let J=go(super.names,this.from);return go(J,this.to)}}class OL1 extends QE{constructor(J,Q,Z,X){super();this.loop=J,this.varKind=Q,this.name=Z,this.iterable=X}render(J){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(J)}optimizeNames(J,Q){if(!super.optimizeNames(J,Q))return;return this.iterable=ZE(this.iterable,J,Q),this}get names(){return UL(super.names,this.iterable.names)}}class xo extends gD{constructor(J,Q,Z){super();this.name=J,this.args=Q,this.async=Z}render(J){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(J)}}xo.kind="func";class yo extends uo{render(J){return"return "+super.render(J)}}yo.kind="return";class qM0 extends gD{render(J){let Q="try"+super.render(J);if(this.catch)Q+=this.catch.render(J);if(this.finally)Q+=this.finally.render(J);return Q}optimizeNodes(){var J,Q;return super.optimizeNodes(),(J=this.catch)===null||J===void 0||J.optimizeNodes(),(Q=this.finally)===null||Q===void 0||Q.optimizeNodes(),this}optimizeNames(J,Q){var Z,X;return super.optimizeNames(J,Q),(Z=this.catch)===null||Z===void 0||Z.optimizeNames(J,Q),(X=this.finally)===null||X===void 0||X.optimizeNames(J,Q),this}get names(){let J=super.names;if(this.catch)UL(J,this.catch.names);if(this.finally)UL(J,this.finally.names);return J}}class fo extends gD{constructor(J){super();this.error=J}render(J){return`catch(${this.error})`+super.render(J)}}fo.kind="catch";class ho extends gD{render(J){return"finally"+super.render(J)}}ho.kind="finally";class GM0{constructor(J,Q={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Q,_n:Q.lines?`
|
1858
|
+
`).length,X=0,Y=0;return{added:Z,removed:X,modified:Y,created:q,reverted:K}}var ED0=p(()=>{K8();va()});function uZ8(J){if(J.action.type==="redact-tool-input"&&J.on.event!=="tool:post-execute")return"redact-tool-input action can only be used with tool:post-execute event";if(J.action.type==="send-user-message"&&J.on.event!=="tool:pre-execute")return"send-user-message action can only be used with tool:pre-execute event";return null}function FL1(J){if(!J||!Array.isArray(J))return[];return J.filter((Q)=>{if(Q.compatibilityDate!=="2025-05-13")return!1;let Z=uZ8(Q);if(Z)return a.warn(`Hook "${Q.id}" is invalid: ${Z}`),!1;return!0})}var $D0=p(()=>{B0()});function PD0(J,Q){if(!J)return{action:null};J=FL1(J);for(let Z of J){if(Z.if===!1)continue;if(Z.on.event==="tool:pre-execute"){if(!(Array.isArray(Z.on.tool)?Z.on.tool:[Z.on.tool]).includes(Q.toolUse.name))continue;let Y=JSON.stringify(Q.toolUse.input),K=Array.isArray(Z.on["input.contains"])?Z.on["input.contains"]:[Z.on["input.contains"]];for(let q of K)if(Y.includes(q)){if(a.debug(`Hook triggered: ${Z.id}`,{hookID:Z.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,matchString:q,action:Z.action}),Z.action.type==="send-user-message")return{hookID:Z.id,action:Z.action}}}}return{action:null}}function TD0(J,Q){if(!J)return{action:null};J=FL1(J);for(let Z of J){if(Z.if===!1)continue;if(Z.on.event==="tool:post-execute"){if(!(Array.isArray(Z.on.tool)?Z.on.tool:[Z.on.tool]).includes(Q.toolUse.name))continue;if(a.debug(`Post-execution hook triggered: ${Z.id}`,{hookID:Z.id,threadID:Q.threadID,toolName:Q.toolUse.name,toolUseID:Q.toolUse.id,action:Z.action}),Z.action.type==="redact-tool-input")return{hookID:Z.id,action:Z.action}}}return{action:null}}function CD0(J,Q){if(!J)return{action:null};try{return J(Q.thread)}catch(Z){return a.error("Error processing assistant end-turn hook",Z),{action:null}}}async function Co(J,Q,Z){if(!Q.action)return{abortOp:!1};switch(Q.action.type){case"send-user-message":return await J.handle({type:"user:message",message:{content:[{type:"text",text:Q.action.message}],source:{type:"hook",hook:Q.hookID}}}),{abortOp:!0};case"redact-tool-input":if(!Z?.toolUseID)return a.warn("redact-tool-input action requires toolUseID in context"),{abortOp:!1};return await J.handle({type:"tool:processed",toolUse:Z.toolUseID,newArgs:Q.action.redactedInput}),a.debug("Tool input redacted",{hookID:Q.hookID,toolUseID:Z.toolUseID}),{abortOp:!1}}}var SD0=p(()=>{B0();$D0()});function dZ8(J){return J?J.length>=pZ8:!1}function cZ8(J){for(let Q=J.messages.length-1;Q>=0;Q--){let Z=J.messages[Q];if(Z&&Z.role!=="info")return Z}return}function lZ8(J,Q){J["~debug"]={...J["~debug"]??{},...Q.usage?{lastInferenceUsage:Q.usage}:{},...Q.params?{lastInferenceInput:Q.params}:{}}}function vD0(J){return(Q)=>{switch(Q.v++,J.type){case"cancelled":{Mx(Q);let Z=Q.messages.at(-1);if(Z?.role==="user"){let X=Z.content.findLast((Y)=>Y.type==="tool_result");if(X)X.run.status="cancelled"}break}case"summary:created":{if(J.summary.type==="external"){if(!Q.summaryThreads)Q.summaryThreads=[];Q.summaryThreads.push(J.summary.summaryThreadID),Q.messages.push({role:"info",content:[{type:"summary",summary:{type:"thread",thread:J.summary.summaryThreadID}}]})}else if(J.summary.type==="internal")Q.messages.push({role:"info",content:[{type:"summary",summary:{type:"message",summary:J.summary.summary}}]});break}case"fork:created":{if(!Q.forkThreads)Q.forkThreads={};let Z=Q.forkThreads[J.fromMessageIndex]||[];Q.forkThreads={...Q.forkThreads,[J.fromMessageIndex]:[...Z,J.forkThreadID]},Q.v++;break}case"thread:truncate":{if(Q.messages.splice(J.fromIndex),Q.forkThreads){let Z=[];for(let X in Q.forkThreads){let Y=Number(X);if(Y>=J.fromIndex)Z.push(Y)}for(let X of Z)delete Q.forkThreads[X];if(Object.keys(Q.forkThreads).length===0)Q.forkThreads=void 0}break}case"user:message":{Mx(Q);let Z={role:"user",...J.message},X=mR(Z);if(J.index!==void 0){if(!Q.messages[J.index])throw Error(`user message at index ${J.index} not found`);Q.messages.splice(J.index,Q.messages.length-J.index,X)}else Q.messages.push(X);break}case"user:message-queue:dequeue":{if(Mx(Q),!Q.queuedMessages)return;let[Z,...X]=Q.queuedMessages;if(!Z)return;Q.messages.push(Z.queuedMessage),Q.queuedMessages=X;break}case"user:tool-input":{if(!UZ(Q,J.toolUse)){a.debug(`Ignoring user:tool-input delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(hC(Q,J.toolUse));if(!X){a.debug(`Ignoring user:tool-input delta for missing tool result block ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}X.userInput=J.value;break}case"tool:data":{if(!Sp(Q,J.toolUse)){a.debug(`Ignoring tool:data delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=c8(mR(J.data));So(Q,J.toolUse,X);break}case"tool:processed":{let Z=Sp(Q,J.toolUse);if(!Z){a.debug(`Ignoring tool:processed delta for missing tool use ${J.toolUse} (likely deleted due to thread edit/truncation)`);break}let X=Z.block.input;Z.block.input=J.newArgs,Z.message.originalToolUseInput={...Z.message.originalToolUseInput,[J.toolUse]:X};break}case"assistant:message":{let Z=G7(Q,"assistant"),X=Z?.content.filter((Y)=>Y.type==="tool_use").map((Y)=>Y.id)||[];if(Mx(Q),Z?.state.type==="cancelled"){for(let Y of Q.messages)if(Y.role==="user")Y.content=Y.content.filter((K)=>{if(K.type==="tool_result"&&X.includes(K.toolUseID))return!1;return!0})}Q.messages.push(c8(J.message));break}case"assistant:message-delta":{let Z=J.event,X=Q.messages.at(-1);if(Z.type==="message_start"){let K=cZ8(Q);if(!K||K.role!=="user")throw Error("(unreachable) assistant message start without user message");return Mx(Q),Q.messages=[...Q.messages,{role:"assistant",content:[],state:{type:"streaming"}}],Q}let Y=c8(G7(Q,"assistant"));if(!Y)throw Error("(unreachable) no last assistant message to update");switch(Z.type){case"content_block_start":{if(Z.index!==Y.content.length)throw Error("(bug) content block delta out of order");let K;switch(Z.content_block.type){case"text":K={type:"text",text:""};break;case"thinking":K={type:"thinking",thinking:"",signature:""};break;case"redacted_thinking":K={type:"redacted_thinking",data:Z.content_block.data};break;case"tool_use":K={type:"tool_use",id:Z.content_block.id,name:Z.content_block.name,input:Z.content_block.input,inputPartialJSON:{json:""}};break;default:throw Error(`unsupported content block type: ${Z.content_block.type}`)}Y.content.push(K);break}case"content_block_delta":{let K=Y.content[Z.index];if(!K)throw Error("(bug) content block delta index out of bounds");switch(Z.delta.type){case"text_delta":{if(K.type!=="text")throw Error(`(bug) content block delta type mismatch: text_delta !== ${K.type}`);K.text+=Z.delta.text;break}case"input_json_delta":{if(K.type!=="tool_use")throw Error(`(bug) content block delta type mismatch: input_json_delta !== ${K.type}`);if(!K.inputPartialJSON)throw Error("(bug) input_json_delta without incomplete");K.inputPartialJSON.json+=Z.delta.partial_json;try{K.input=DF(K.inputPartialJSON.json),K.inputIncomplete=kD0(K.inputPartialJSON.json)}catch{K.input={}}break}case"thinking_delta":{if(K.type!=="thinking")throw Error(`(bug) content block delta type mismatch: thinking_delta !== ${K.type}`);K.thinking+=Z.delta.thinking;break}case"signature_delta":{if(K.type!=="thinking")throw Error(`(bug) content block delta type mismatch: signature_delta !== ${K.type}`);K.signature=Z.delta.signature;break}}break}case"content_block_stop":{let K=Y.content[Z.index];if(!K)throw Error("(bug) content block delta index out of bounds");if(K.type==="tool_use"){if(!K.inputPartialJSON)throw Error("(bug) content block stop without incomplete");if(K.inputPartialJSON.json==="")K.input={};else K.input=JSON.parse(K.inputPartialJSON.json);delete K.inputPartialJSON,delete K.inputIncomplete}break}case"message_delta":{if(Z.delta.stop_reason){if(Z.delta.stop_reason==="max_tokens"){for(let K of Y.content)if(K.type==="tool_use"&&K.inputPartialJSON)delete K.inputPartialJSON,So(Q,K.id,{status:"error",error:{message:"Ran into max tokens limit of 200 tokens. Received only partial input for tool."}})}else for(let K of Y.content)if(K.type==="tool_use"&&K.inputPartialJSON){a.debug("Found a block with inputPartialJSON still set on message_delta");try{if(K.inputPartialJSON.json!=="")K.input=JSON.parse(K.inputPartialJSON.json);else K.input={}}catch(q){a.error(`Failed to parse malformed JSON for tool_use ${K.id}`,q,{threadId:Q.id,blockId:K.id,input:K.inputPartialJSON.json});let G=`Malformed JSON: '${K.inputPartialJSON.json}'.`;So(Q,K.id,{status:"error",error:{message:G}})}delete K.inputPartialJSON}if(Y.state={type:"complete",stopReason:Z.delta.stop_reason},Y.state.stopReason==="tool_use"&&!Y.content.some((K)=>K.type==="tool_use"))Y.state.stopReason="end_turn"}break}case"message_stop":break}break}case"inference:completed":{if(lZ8(Q,{usage:J.usage,params:J.params}),!Q.env)Q.env={initial:{}};if(!Q.env.initial.tags)Q.env.initial.tags=[];let Z=`model:${J.model}`;if(!Q.env.initial.tags.includes(Z))Q.env.initial.tags=[...Q.env.initial.tags,Z];if(J.usage)for(let X=Q.messages.length-1;X>=0;X--){let Y=Q.messages[X];if(Y?.role==="assistant"){Y.usage=J.usage;break}}break}case"title":{Q.title=J.value||void 0;break}case"max-tokens":{Q.maxTokens=J.value||void 0;break}case"main-thread":{Q.mainThreadID=J.value||void 0;break}case"environment":{Q.env=c8(J.env);break}case"user:message-queue:enqueue":{if(!Q.queuedMessages)Q.queuedMessages=[];if(dZ8(Q.queuedMessages))break;let Z={role:"user",...J.message},X=mR(Z);Q.queuedMessages.push({id:xY("queued-"),queuedMessage:c8(X)});break}case"user:message-queue:discard":{if(J.id===void 0){Q.queuedMessages=[];break}let Z=Q.queuedMessages?.findIndex((X)=>X.id===J.id);if(Z===void 0)throw Error(`queued message with id ${J.id} not found`);Q?.queuedMessages?.splice(Z,1);break}case"info:manual-bash-invocation":{Q.messages.push({role:"info",content:[{type:"manual_bash_invocation",args:c8(J.args),toolRun:c8(J.toolRun),hidden:J.hidden}]});break}case"info:model-switch-start":{Q.messages.push({role:"info",content:[{type:"model_switch",switchType:"start",from:J.from,to:J.to,timestamp:J.timestamp??Date.now(),reason:J.reason,keyword:J.keyword,userMessageIndex:J.userMessageIndex}]});break}case"info:model-switch-end":{Q.messages.push({role:"info",content:[{type:"model_switch",switchType:"end",from:J.from,to:J.to,timestamp:J.timestamp??Date.now(),reason:J.reason,keyword:J.keyword,userMessageIndex:J.userMessageIndex}]});break}}}}function Mx(J){let Q=c8(G7(J,"assistant"));if(!Q)return;let Z=!1,X=[];if(Q.state.type==="streaming")Q.state={type:"cancelled"},Z=!0;else if(Q.state.type==="complete"){if(Q.content.some((K)=>K.type==="tool_use"&&("inputPartialJSON"in K)))Q.state={type:"cancelled"},Z=!0}if(Z){for(let K of Q.content)if(K.type==="tool_use"&&K.inputPartialJSON){X.push(K.id),a.debug(`Cleaning up partial tool_use ${K.id}`,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:J.id,blockID:K.id});try{if(K.inputPartialJSON.json!=="")K.input=DF(K.inputPartialJSON.json),K.inputIncomplete=kD0(K.inputPartialJSON.json);else K.input={}}catch(q){a.warn(`Failed to parse partial JSON for cancelled tool_use ${K.id}:`,q,{name:"markPriorStreamingAssistantMessageAsCancelled",threadID:J.id,blockID:K.id,input:K.inputPartialJSON.json}),K.input={}}delete K.inputPartialJSON}let Y=jQ(J);for(let K of X)if(!Y.has(K))So(J,K,{status:"cancelled"})}}function So(J,Q,Z){let X,Y=Sp(J,Q);if(Y){let q=Y.messageIndex;for(let G=q+1;G<J.messages.length;G++){let z=J.messages[G];if(z?.role==="user"){X=z;break}}}if(!X)X={role:"user",content:[]},J.messages.push(X);let K=hC(J,Q);if(K)K.run=c8(Z);else K={type:"tool_result",toolUseID:Q,run:c8(Z)},X.content.push(K)}function kD0(J){try{return DF(J.replace(/\\+$/,"")+'"')}catch{return DF(J)}}var pZ8=5;var _D0=p(()=>{Ul();OQ();B0();xU1();Z4()});function bD0(J){let Q=[],Z=/@((?:[^\s@\\,;]|\\.)+)/g,X;while((X=Z.exec(J))!==null){let Y=X[1],K=iZ8(Y).replace(/[.,;:!?)}\]]+$/,"");Q.push(K)}return Q}function iZ8(J){if(J.match(/^[A-Za-z]:[\\]/))return J.replace(/\\(.)/g,(Q,Z)=>{if(Z===" "||Z==="("||Z===")"||Z==="["||Z==="]"||Z==="?"||Z==="*")return Z;return Q});return J.replace(/\\(.)/g,"$1")}function vo(J){if(!J)return!1;return J.range.startLine===J.range.endLine&&J.range.startCharacter===J.range.endCharacter}var xD0={};N6(xD0,{getUserState:()=>nZ8});async function nZ8(){if(!await RQ.isConnected())return;let Q=await q6(RQ.status),Z=Q.selections?.[0],X=vo(Z),Y=X&&Z?{line:Z.range.startLine,column:Z.range.startCharacter}:void 0;return{currentlyVisibleFiles:Q.visibleFiles??[],activeEditor:Q.openFile,cursorLocation:Y,cursorLocationLine:X?Z?.content:void 0,selectionRange:!X&&Z?{content:Z?.content,start:{line:Z?.range.startLine,column:Z?.range.startCharacter},end:{line:Z?.range.endLine,column:Z?.range.endCharacter}}:void 0}}var yD0=p(()=>{i0();ej()});async function fD0({configService:J,filesystem:Q},Z){let X=await q6(J.workspaceRoots)??[];if(X.length===0)return{role:"user",content:Z.content,source:Z.source,fileMentions:void 0,userState:void 0};let Y=await $l({fileSystem:Q},bD0(ZJ(Z.content)),{searchPaths:X}),K=await(await Promise.resolve().then(() => (yD0(),xD0))).getUserState();return{role:"user",content:Z.content,source:Z.source,fileMentions:Y,userState:{...K??Pt1}}}var hD0=p(()=>{i0();LF();Z4();IB()});class WL1{deps;threadID;async resumeInProgressTools(){for(let J of this.thread.messages){if(J.role!=="user")continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;if(!(!C5(Q.run)&&Q.run.status!=="blocked-on-user"&&!this.ops.tools[Q.toolUseID]))continue;let X=this.findToolUseById(Q.toolUseID);if(!X)continue;if(X.name===Q4||X.name===Pd1){this.findAndCancelToolRun(Q.toolUseID);continue}a.debug(`re-invoking tool ${X.name} with ID ${Q.toolUseID}`,{name:"resumeInProgressTools",threadID:this.threadID}),this.invokeTool(X,Q.userInput)}}await this.updateFileChanges()}findToolUseById(J){for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Z of Q.content)if(Z.type==="tool_use"&&Z.id===J)return Z}return}trackFilesFromHistory(){a.debug("Tracking files from thread history",{name:"trackFilesFromHistory",threadID:this.threadID});for(let J of this.thread.messages){if(J.role==="user"&&J.fileMentions?.files)this.trackFiles(J.fileMentions.files.map((Q)=>Q.uri).filter((Q)=>Q!==void 0));if(J.role==="user"){for(let Q of J.content)if(Q.type==="tool_result"&&Q.run.status==="done")this.trackFiles(Q.run.trackFiles??[])}}}setupSettingsChangeHandlers(){this.setupPermissionsChangeHandler()}setupPermissionsChangeHandler(){LU1.pipe(d8(),jg1(1),eA(this.disposed$)).subscribe(()=>{this.reevaluateBlockedTools()})}reevaluateBlockedTools(){for(let J=this.thread.messages.length-1;J>=0;J--){let Q=this.thread.messages[J];if(!Q||Q.role!=="user")continue;let Z=!1;for(let X of Q.content)if(X.type==="tool_result"&&X.run?.status==="blocked-on-user"&&X.toolUseID)Z=!0,this.checkAndApproveBlockedTool(X.toolUseID);if(!Z)break}}async checkAndApproveBlockedTool(J){try{let Q=this.findToolUseById(J);if(!Q){a.warn("Tool use block not found for blocked tool",{toolUseID:J});return}let Z=await ml(Q.name,Q.input??{},"thread",this.threadID,J);if(Z.permitted)a.info("Auto-approving previously blocked tool due to permission change",{toolName:Q.name,toolUseID:J,threadID:this.threadID}),this.handle({type:"user:tool-input",toolUse:J,value:{accepted:!0}});else a.debug("Tool remains blocked after permission change",{toolName:Q.name,toolUseID:J,reason:Z.reason})}catch(Q){a.warn("Failed to re-evaluate blocked tool",{error:Q,toolUseID:J})}}async cleanupTaskToolSubThreads(J=this.thread.messages.length){let Q=this.thread.messages.slice(0,J),Z=vQ1(Q),X=new Set(Z.map((K)=>K.toolUseID)),Y=new Set;for(let[K]of this.registeredSubthreads.entries())if(!X.has(K))Y.add(K);for(let K of Y){let q=this.registeredSubthreads.get(K);if(q.fileChanges?.unsubscribe(),await q.worker?.revertFileChanges(),q.latestFiles=[],this.mergeAndEmit(),await this.cleanupThreadBackups(q.threadID),await q.worker?.asyncDispose(),this.deps.deleteThread)try{await this.deps.deleteThread(q.threadID)}catch(G){a.error(`Failed to delete Task tool sub-thread: ${q.threadID}`,G,{threadID:this.threadID,subThreadID:q.threadID})}else a.warn(`Cannot delete Task tool sub-thread: ${q.threadID} - threadHistoryService not available`,{threadID:this.threadID,subThreadID:q.threadID});this.registeredSubthreads.delete(K)}if(Y.size>0)this.emitSubthreads()}ops={tools:{},toolMessages:{},inference:null};_state=new P4("initial");state=this._state.pipe(d8(),r9({shouldCountRefs:!0}));handlePromise=Promise.resolve();ephemeralError=new P4(void 0);inferenceState=new P4("idle");summaryState=new P4("idle");fileChanges=new P4({files:[]});toolCallUpdates=new b8;trackedFiles=new VZ;fs;cachedFileChanges=[];registeredSubthreads=new Map;subthreadSequenceNumber=0;_subthreadsSubject=new P4([]);subthreads=this._subthreadsSubject.pipe(d8(),r9({shouldCountRefs:!0}));disposed$=new b8;isDisposed=!1;cancelledToolUses=new Set;constructor(J,Q){this.deps=J;this.threadID=Q;this.fs=RD0({fileChangeTrackerStorage:this.deps.fileChangeTrackerStorage},this.deps.vfs,Q,()=>nv(this.thread))}status=this.state.pipe(S9((J)=>J==="active"?J4(this.inferenceState.pipe(d8()),this.summaryState,this.fileChanges.pipe(d8()),this.ephemeralError,this.toolCallUpdates.pipe(d7(void 0))).pipe(g0(([Q,Z,X,Y])=>({state:J,inferenceState:Q,summaryState:Z,fileChanges:X,ephemeralError:Y?{message:Y.message,stack:"stack"in Y?Y.stack:void 0,error:"error"in Y&&Y.error&&typeof Y.error==="object"&&"error"in Y.error?Y.error.error:void 0}:void 0})),eA(this.disposed$)):K0.of({state:J})),r9({shouldCountRefs:!0}));threadReadWriter=null;get thread(){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);return this.threadReadWriter.read()}set thread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.write(J),this.__testing__setThread(J)}updateThread(J){if(!this.threadReadWriter)throw Error(`thread read-writer not initialized for ThreadWorker: ${this.threadID}`);this.threadReadWriter.update(vD0(J)),this.__testing__setThread(this.threadReadWriter.read())}async acquireThread(){if(!this.threadReadWriter)this.threadReadWriter=await this.deps.threadService.exclusiveSyncReadWriter(this.threadID),this._state.next("active")}__testing__setThread(J){}async resume(){if(this.resumed)return;if(this.resumed=!0,this.handleCalled)throw Error("cannot call ThreadWorker.resume after ThreadWorker.handle");await this.acquireThread(),await this.restoreFileChangesFromBackups();let J=this.thread.messages.at(-1);if(J?.role==="assistant"&&J.state.type==="streaming")this.updateThread({type:"thread:truncate",fromIndex:this.thread.messages.length-1});if(this.trackFilesFromHistory(),await this.initializeCompletedSubthreads(),this.thread.mainThreadID)return;if(Lc1(J)||Oc1(J)||kQ1(J)){this.inferenceState.next("cancelled");return}await this.resumeInProgressTools(),this.setupSettingsChangeHandlers();let Q=this.thread.messages.findLastIndex((X)=>X.role==="user"?Ac1(X):X.role==="assistant"&&X.state.type==="complete");if(Q===-1){if(this.thread.messages.length!==0)throw Error(`(bug) invalid thread: ${this.threadID}`);return}let Z=this.thread.messages[Q];switch(Z.role){case"user":this.onThreadDelta({type:"user:message",message:Z});break;case"assistant":this.onThreadDelta({type:"assistant:message",message:Z});break}}resumed=!1;async initializeCompletedSubthreads(){let J=vQ1(this.thread.messages);for(let{toolUseID:Q,threadID:Z,toolUse:X,toolResult:Y}of J){let K=C5(Y.run),q=Y.run.status==="blocked-on-user";if(K&&!q)await this.registerSubthread(Q,Z,X)}}async summarizeThread(){await this.acquireThread(),this.summaryState.next("summarizing"),await this.cancel();try{let J=await this.deps.threadSummaryService.summarizeThread(this.threadID);await this.handle({type:"summary:created",summary:{type:"internal",summary:J.summary}})}finally{this.summaryState.next("idle"),this.inferenceState.next("idle"),await this.handle({type:"user:message-queue:dequeue"}).catch((J)=>{a.error("Failed to dequeue messages after summarization",J,{threadID:this.threadID})})}}async createSummaryThread(){await this.acquireThread(),this.summaryState.next("creating-summary-thread"),await this.cancel();try{let J=await this.deps.threadSummaryService.createSummaryThread(this.threadID);return await this.handle({type:"summary:created",summary:{type:"external",summaryThreadID:J.threadID}}),J.threadID}finally{this.summaryState.next("idle"),await this.handle({type:"user:message-queue:dequeue"}).catch((J)=>{a.error("Failed to dequeue messages after summary thread creation",J,{threadID:this.threadID})})}}async forkThread(J){await this.acquireThread();let{threadService:Q}=this.deps,Z=await Q.forkThread(this.threadID,J);await this.handle({type:"fork:created",forkThreadID:Z.threadID,fromMessageIndex:J});let X=await Q.getPrimitiveProperty(this.threadID,"v");if(X!==null)await Q.flushVersion(this.threadID,X);return Z.threadID}async handle(J,Q){this.handlePromise=this.handlePromise.then(async()=>{await this.innerHandle(J,Q)}).catch((Z)=>{a.error("Unhandled error in handle promise queue",{err:Z},{threadID:this.threadID})}),await this.handlePromise}async innerHandle(J,Q){if(this.isDisposed){a.debug(`Skipping ${J.type} - worker disposed.`,{name:"handle queue",threadID:this.threadID});return}if(Q?.aborted){a.debug(`Skipping ${J.type} - signal aborted.`,{name:"handle queue",threadID:this.threadID});return}if(await this.resume(),this.handleCalled=!0,await this.acquireThread(),J.type==="thread:truncate")await this.cleanupFileChanges(J.fromIndex),await this.cleanupTaskToolSubThreads(J.fromIndex);let Z=J;if(J.type==="user:message"){let X=await fD0({configService:this.deps.configService,filesystem:this.fs.fileSystemReader()},J.message);Z=SC(J,(Y)=>{if(Y.message=c8(X),Y.message.fileMentions?.imageBlocks?.length)a.debug(`Adding ${Y.message.fileMentions.imageBlocks.length} image attachments to message`,{name:"adding image attachments",threadID:this.threadID}),Y.message.content=[...Y.message.content,...Y.message.fileMentions.imageBlocks];if(!Y.message.meta)Y.message.meta={};Y.message.meta.sentAt=Date.now(),Q?.throwIfAborted()})}try{if(this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);let X=J.type==="user:message"&&J.index!==void 0;if(this.updateThread(Z),this.onThreadDelta(Z),X)await this.cleanupFileChanges(),await this.cleanupTaskToolSubThreads(),await this.cleanupForkThreads()}catch(X){if(!DR(X))a.error("Ephemeral error during handle processing",X,{name:"ThreadWorker",threadID:this.threadID}),this.ephemeralError.next(X instanceof Error?X:Error(String(X)));else a.debug(`AbortError caught during handle processing for ${Z.type}.`,{name:"handle queue",threadID:this.threadID})}}handleCalled=!1;onThreadDelta(J){switch(J.type){case"user:message":{if(J.index!==void 0)this.trackedFiles.clear(),this.thread.messages.forEach((Q)=>{if(Q.role==="user"){for(let Z of Q.content)if(Z.type==="tool_result"&&Z.run.status==="done"&&Z.run.trackFiles)this.trackFiles(Z.run.trackFiles);if(Q.fileMentions?.files)this.trackFiles(Q.fileMentions.files.map((Z)=>Z.uri).filter((Z)=>Z!==void 0))}});else this.trackFiles(J.message.fileMentions?.files?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0)??[]);this.runInferenceAndUpdateThread();break}case"user:message-queue:dequeue":{let Q=this.thread.messages.at(-1);if(!Q)break;if(Q.role!=="user")break;this.trackFiles(Q.fileMentions?.files?.map((Z)=>Z.uri).filter((Z)=>Z!==void 0)??[]),this.runInferenceAndUpdateThread();break}case"user:tool-input":{let Q=UZ(this.thread,J.toolUse);if(Q)this.invokeTool(Q,J.value);break}case"tool:data":{if(this.cancelledToolUses.has(J.toolUse)){this.updateThread({type:"tool:data",toolUse:J.toolUse,data:{status:"cancelled",reason:"cancelled by user message"}});return}let Q=UZ(this.thread,J.toolUse);if(J.data.status==="in-progress"&&Q?.name===c7){let Z=Q,X=SQ1(J.data.progress);if(X)this.registerSubthread(J.toolUse,X,Z)}if(C5(J.data))this.cancelledToolUses.delete(J.toolUse);if(Q){let Z=gD0(this.thread,J.toolUse);if(a.debug(`updated tool_result${Z?" and running inference because all tools completed":""}`,{name:`handleThreadDelta(${J.type}, ${J.toolUse}, ${J.data.status})`,threadID:this.threadID}),Z&&this.inferenceState.getValue()!=="cancelled")this.runInferenceAndUpdateThread()}this.toolCallUpdates.next();break}case"assistant:message":{let Q=this.findToolUsesNeedingInvocation(J.message);a.debug(`saw ${Q.length} tool uses (${Q.map((Z)=>Z.name).join(", ")})`,{name:`handleThreadDelta(${J.type})`,threadID:this.threadID});for(let Z of Q)this.invokeTool(Z,void 0);break}case"assistant:message-delta":{if(J.event.type==="message_start")a.debug("token usage",J.event.message.usage);else if(J.event.type==="message_delta"&&J.inferenceStart&&J.event.usage?.output_tokens){let Y=performance.now()-J.inferenceStart;a.debug("completed message",{outputTokens:J.event.usage.output_tokens,tokensPerSecond:J.event.usage.output_tokens/Y*1000,inferenceDuration:yU0(Y)})}let Q=G7(this.thread,"assistant");if(!Q)throw Error("no assistant message found");let Z=this.findToolUsesNeedingInvocation(Q);for(let X of Z)this.invokeTool(X,void 0);if(gD0(this.thread))this.runInferenceAndUpdateThread();break}case"user:message-queue:enqueue":{let Q=this.inferenceState.getValue(),Z=this.summaryState.getValue();if(JV1(this.thread,Q)!=="tool-running"&&Z==="idle"){if(Q==="cancelled"){this.handle({type:"user:message-queue:dequeue"});break}else if(Q==="idle"){let Y=this.thread.messages.at(-1);if(Y?.role==="assistant"){if(Y.state.type==="cancelled"||Y.state.type==="error"){this.handle({type:"user:message-queue:dequeue"});break}if(Y.state.type==="complete"&&Y.state.stopReason!=="tool_use"){this.handle({type:"user:message-queue:dequeue"});break}}else if(Y?.role==="info"){this.handle({type:"user:message-queue:dequeue"});break}}}break}case"info:manual-bash-invocation":{this.handle({type:"user:message-queue:dequeue"});break}case"cancelled":{let Q=vj(this.thread);if(Q)this.updateThread({type:"info:model-switch-end",from:Q.to,to:Q.from,reason:Q.reason,keyword:Q.keyword,userMessageIndex:Q.userMessageIndex});break}case"inference:completed":{let Q=G7(this.thread,"assistant");if(Q&&Q.state.type==="complete"&&Q.state.stopReason==="end_turn"){let X=vj(this.thread);if(X)this.updateThread({type:"info:model-switch-end",from:X.to,to:X.from,reason:X.reason,keyword:X.keyword,userMessageIndex:X.userMessageIndex});if(this.thread.queuedMessages&&this.thread.queuedMessages.length>0)this.handle({type:"user:message-queue:dequeue"});else Co(this,CD0(this.deps.internalHooks?.onAssistantTurnEnd,{thread:this.thread}))}break}}}findToolUsesNeedingInvocation(J){if(J.content.some((Y)=>Y.type==="tool_use"&&Y.inputPartialJSON))return[];if(!(J.state?.type==="complete"||J.state?.type==="cancelled"))return[];let X=jQ(this.thread);return J.content.filter((Y)=>Y.type==="tool_use").filter((Y)=>!X.has(Y.id)&&!this.cancelledToolUses.has(Y.id))}async getWorkspaceRoots(J){return await q6(this.deps.configService.workspaceRoots,J)??this.thread.env?.initial?.trees?.map((Q)=>Q.uri).filter((Q)=>Q!==void 0).map(MX)??[]}isToolUseEffectivelyComplete(J){if(!J.inputPartialJSON)return!0;try{return JSON.parse(J.inputPartialJSON.json),!0}catch{return!1}}async invokeTool(J,Q){if(this.ops.tools[J.id])throw Error(`(bug) tool invocation already in progress: ${J.id}`);if(!this.isToolUseEffectivelyComplete(J))throw Error(`(bug) tool use is incomplete: ${J.id}`);let Z=await A9();if(Z.settings?.hooks){let Y=PD0(Z.settings.hooks,{threadID:this.threadID,toolUse:J}),{abortOp:K}=await Co(this,Y);if(K)return}let X=new AbortController;this.ops.tools[J.id]=X,this.updateThread({type:"tool:data",toolUse:J.id,data:{status:"in-progress"}});try{let Y=await this.getWorkspaceRoots(X.signal),K=vp(this.thread),q=new K0((W)=>{this.ops.toolMessages[J.id]=W}),G={...this.deps,dir:Y.at(0)??null,dirs:Y,tool:J.name,thread:this.thread,config:await A9(),trackedFiles:new VZ(this.trackedFiles),filesystem:this.fs.trackedFileSystem(J.id),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:J.id,todos:K,toolMessages:q,threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this)},z=this.deps.toolService.preprocessArgs?.(J.name,J.input,G);if(z)this.handle({type:"tool:processed",toolUse:J.id,newArgs:z});let U=z??J.input,F=this.deps.toolService.invokeTool(J.name,{args:U,userInput:Q},G).pipe(eA(this.disposed$),_G(()=>{delete this.ops.tools[J.id],this.ops.toolMessages[J.id]?.complete(),delete this.ops.toolMessages[J.id]})).subscribe({next:async(W)=>{if(a.debug(`${J.id}, ${W.status}`,{name:"invokeTool",threadID:this.threadID}),C5(W)){if(delete this.ops.tools[J.id],F.unsubscribe(),W.status==="done"&&W.trackFiles?.length)this.trackFiles(W.trackFiles);if(Z.settings?.hooks){let H=TD0(Z.settings.hooks,{threadID:this.threadID,toolUse:J});await Co(this,H,{toolUseID:J.id})}}await this.updateFileChanges(),await this.handle({type:"tool:data",toolUse:J.id,data:W},X.signal)},error:async(W)=>{await this.handle({type:"tool:data",toolUse:J.id,data:{status:"error",error:{message:"message"in W?W.message:String(W),displayMessage:"displayMessage"in W?W.displayMessage:void 0}}},X.signal)},complete:()=>{}});PN(X.signal,()=>F.unsubscribe())}catch(Y){throw delete this.ops.tools[J.id],Y}}async cancelInProgressTools(){for(let J of Object.keys(this.ops.tools))await this.cancelTool(J)}cancelAllActiveTools(){let J=jQ(this.thread);for(let Q of this.thread.messages){if(Q.role!=="assistant")continue;for(let Z of Q.content)if(Z.type==="tool_use"&&!Z.inputPartialJSON){let X=J.get(Z.id);if(!(X&&C5(X.run)))this.cancelledToolUses.add(Z.id)}}for(let Q of this.thread.messages)if(Q.role==="user"){for(let Z of Q.content)if(Z.type==="tool_result"){if(!C5(Z.run))this.cancelledToolUses.add(Z.toolUseID)}}}cancelUnstartedTools(){let J=jQ(this.thread),Q=this.thread.messages.findLastIndex((X)=>kQ1(X)),Z=Q===-1?this.thread.messages:this.thread.messages.slice(Q+1);for(let X of Z){if(X.role!=="assistant")continue;for(let Y of X.content)if(Y.type==="tool_use"&&!Y.inputPartialJSON){let K=J.get(Y.id);if(!K||K.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:Y.id,data:{status:"cancelled"}})}}}async runInferenceAndUpdateThread(){this.ops.inference?.abort(),this.ops.inference=null,this.inferenceState.next("running");let J=new AbortController;this.ops.inference=J,this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools();for(let F of this.thread.messages)if(F.role==="user"){for(let W of F.content)if(W.type==="tool_result"&&W.run.status==="blocked-on-user")this.updateThread({type:"tool:data",toolUse:W.toolUseID,data:{status:"cancelled"}})}if(this.thread.messages.length===1&&this.thread.mainThreadID===void 0){let F=this.thread.messages[0];if(F.role!=="user")throw Error("(bug) first message is not a user message");if(this.deps.generateThreadTitle(F,this.thread.id,J.signal).then((W)=>{if(J.signal.aborted||this.isDisposed)return;if(this.thread.title!==W)this.updateThread({type:"title",value:W})}).catch((W)=>{if(!DR(W))a.error("generateThreadTitle error",W,{name:"ThreadWorker",threadID:this.threadID})}),this.deps.getThreadEnvironment)this.deps.getThreadEnvironment().then(async(W)=>{this.updateThread({type:"environment",env:{initial:{...this.thread.env?.initial,...W}}})}).catch((W)=>{a.error("Failed to initialize thread environment",W,{threadID:this.threadID})})}let Z=await A9(),X=jc1(this.thread),Y=vj(this.thread),{model:K,activeSwitch:q,detection:G,baseModel:z}=$Y0(Z.settings,X,this.thread);if(!q&&G?.shouldSwitch&&G.targetModel){let F=X?this.thread.messages.indexOf(X):-1;if(F===-1){a.warn("Could not find triggering user message for model switch",{threadID:this.threadID,hasLastUser:!!X});return}this.updateThread({type:"info:model-switch-start",from:z,to:G.targetModel,reason:"keyword",keyword:G.detectedKeyword,userMessageIndex:F})}let U=q?.to||G?.targetModel||K;try{let[F,W,H]=U.match(/(.*?)\/(.*)/)??[],M=VD0(W??"",H??"").run(H??"",this.thread,{toolService:this.deps.toolService,configService:this.deps.configService,getThreadEnvironment:this.deps.getThreadEnvironment,latestConfig:A9,filesystem:this.fs.fileSystemReader(),threadService:this.deps.threadService},J.signal);while(!0){let V=await M.next();if(V.done){await this.handle({type:"inference:completed",model:V.value.model,usage:V.value["~debugUsage"],params:V.value["~debugParamsUsed"]});return}await this.handle(V.value,J.signal),J.signal?.throwIfAborted()}}catch(F){if(!(DR(F)||Ro1(F))){let W=F instanceof Error?F:Error(String(F));this.ephemeralError.next(W)}return}finally{if(this.ops.inference===J)this.ops.inference=null,this.inferenceState.next("idle")}}async findAndCancelToolRun(J,Q){if(this.cancelInference(),!UZ(this.thread,J))return;await this.cancelTool(J,Q)}async cancelToolOnly(J,Q){if(!UZ(this.thread,J))return;let X=this.cancelDataForToolRun(J);this.cancelSubthread(J);let Y=this.ops.toolMessages[J];if(Y){try{Y.next({type:"stop-command"})}catch(K){a.warn("Failed to send stop-command",{id:J,error:K})}Y.complete(),delete this.ops.toolMessages[J]}a.debug(`cancelToolOnly(${J})`),await this.handle({type:"tool:data",toolUse:J,data:X},Q)}invokeBashTool(J,Q,Z){return new K0((X)=>{let Y,K,q,z=((F)=>{return PN(F,()=>{if(a.warn("Manual bash abort -> unsubscribe",{threadID:this.threadID}),q?.unsubscribe(),K?.unsubscribe(),X?.complete(),Y)this.handleManualBashInvocation(J,{status:"cancelled",progress:PQ1(Y)},Z)})})(Q);return(async()=>{try{if(Q.aborted){X.error(Error("Operation was aborted"));return}let F=await this.getWorkspaceRoots(Q),W=await A9(),H={...this.deps,dir:F.at(0)??null,dirs:F,tool:Q4,thread:this.thread,config:W,trackedFiles:new VZ(this.trackedFiles),filesystem:G10(this.fs.fileSystemReader()),fileChangeTracker:this.fs.tracker,getAllTrackedChanges:this.getAllTrackedChanges.bind(this),toolUseID:Sj(),todos:[],threadEnvironment:this.thread.env?.initial??await this.deps.getThreadEnvironment(),handleThreadDelta:this.handle.bind(this)};K=this.deps.toolService.invokeTool(Q4,{args:J,userInput:{accepted:!0}},H).subscribe({next:(D)=>{Y=D,X.next(D)},error:(D)=>{X.error(D)},complete:()=>{if(Y)this.handleManualBashInvocation(J,Y,Z);X.complete()}}),q=this.disposed$.subscribe(()=>{z(),K?.unsubscribe(),X?.complete()})}catch(F){X.error(F)}})(),()=>{z(),K?.unsubscribe(),q?.unsubscribe()}})}async handleManualBashInvocation(J,Q,Z){await this.handle({type:"info:manual-bash-invocation",args:J,toolRun:Q,hidden:Z})}async cleanupThreadBackups(J){try{await this.fs.tracker.cleanupBackups(),a.debug(`Cleaned up backup files for thread ${J}`,{threadID:J})}catch(Q){a.error("Error cleaning up thread backups",Q,{threadID:J})}}cancelDataForToolRun(J){let Z=jQ(this.thread).get(J)?.run;return{status:"cancelled",progress:Z?PQ1(Z):void 0}}async cancelTool(J,Q){let Z=this.cancelDataForToolRun(J);this.cancelSubthread(J);let X=this.ops.toolMessages[J];if(X){try{X.next({type:"stop-command"})}catch(Y){a.warn("Failed to send stop-command",{id:J,error:Y})}X.complete(),delete this.ops.toolMessages[J]}a.debug(`cancelToolRun(${J})`),await this.handle({type:"tool:data",toolUse:J,data:Z},Q)}async cancel(){a.debug("cancel: aborting inference operation and tools"),this.cancelInference(),this.cancelAllActiveTools(),this.cancelUnstartedTools(),await this.cancelInProgressTools(),await this.handle({type:"cancelled"},void 0)}cancelInference(){if(this.ops.inference)this.ops.inference.abort(Error(Gz1.USER_CANCELLED)),this.ops.inference=null;this.inferenceState.next("cancelled")}async retry(){if(a.debug("retry: retrying inference operation"),this.ephemeralError.getValue()!==void 0)this.ephemeralError.next(void 0);if(this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;this.inferenceState.next("idle"),await this.runInferenceAndUpdateThread()}cancelSubthread(J){let Q=this.registeredSubthreads.get(J);if(Q&&Q.worker)Q.worker.cancel()}abortToolOp(J){this.ops.tools[J]?.abort(),delete this.ops.tools[J]}abortAllTools(){for(let J of Object.keys(this.ops.tools)){let Q=J,Z=this.ops.toolMessages[Q];if(Z)try{Z.next({type:"stop-command"}),Z.complete(),delete this.ops.toolMessages[Q]}catch(X){a.warn("Failed to send stop-command during disposal",{id:Q,error:X})}this.abortToolOp(Q)}}trackFiles(J){for(let Q of J)this.trackedFiles.add(Q)}async restoreFileChangesFromBackups(){try{let J=await this.fs.tracker.restoreFromBackups();a.debug(`Restored ${J.totalBackups} backup files from disk`),await this.updateFileChanges()}catch(J){a.error("Error restoring file changes",J,{threadID:this.threadID})}}async revertFileChanges(J){for(let Q of this.registeredSubthreads.values()){let Z=Q?.worker;if(Z)await Z.revertFileChanges(J)}await this.fs.tracker.revertAll(J),await this.updateFileChanges()}async getAllTrackedChanges(){let J=new Map;for(let Z of this.registeredSubthreads.values()){let X=Z?.worker;if(X){let Y=await X.getAllTrackedChanges();for(let[K,q]of Y.entries())J.set(K,q)}}let Q=await this.fs.tracker.getAllRecords();for(let[Z,X]of Q.entries())J.set(Z,X);return J}async cleanupForkThreads(J=this.thread.messages.length){await this.acquireThread(),this.updateThread({type:"thread:truncate",fromIndex:J})}async cleanupFileChanges(J=this.thread.messages.length){let Q=new Set;this.thread.messages.slice(0,J).forEach((Y)=>{if(Y.role==="user"){for(let K of Y.content)if(K.type==="tool_result")Q.add(K.toolUseID)}else for(let K of Y.content)if(K.type==="tool_use")Q.add(K.id)});let Z=new Set,X=await this.fs.tracker.getAllRecords();for(let[Y]of X.entries())if(!Q.has(Y))Z.add(Y);if(Z.size===0)return;await this.fs.tracker.revertChanges(Z),await this.updateFileChanges()}async updateFileChanges(){this.cachedFileChanges=await ID0(this.fs.tracker),this.mergeAndEmit()}mergeAndEmit(){let J=new _5;for(let Z of this.cachedFileChanges)J.set(Z.uri,Z);for(let Z of this.registeredSubthreads.values())for(let X of Z.latestFiles??[])J.set(X.uri,X);let Q=J.size;if(Q>50)a.warn("Excessive file changes detected - potential memory issue",{name:"mergeAndEmit",threadID:this.threadID,fileChangeCount:Q,ownFileChanges:this.cachedFileChanges.length,subthreadCount:this.registeredSubthreads.size});this.fileChanges.next({files:[...J.values()]})}emitSubthreads(){let J=Array.from(this.registeredSubthreads.values()).sort((Q,Z)=>Q.sequenceNumber-Z.sequenceNumber).map((Q)=>({threadID:Q.threadID,toolUse:Q.toolUse,sequenceNumber:Q.sequenceNumber}));this._subthreadsSubject.next(J)}async registerSubthread(J,Q,Z){if(this.registeredSubthreads.has(J))return;let X=await dJ.getOrCreateForSubThread(this.deps,Q);await X.resume();let Y=X.status.pipe(vJ((K)=>K.state==="active"),g0((K)=>K.fileChanges.files),eA(this.disposed$)).subscribe((K)=>{let q=this.registeredSubthreads.get(J);if(!q)return;q.latestFiles=K,this.mergeAndEmit()});this.registeredSubthreads.set(J,{threadID:Q,worker:X,fileChanges:Y,toolUse:Z,sequenceNumber:++this.subthreadSequenceNumber}),this.emitSubthreads()}async asyncDispose(){if(this.isDisposed)return;if(a.debug("ThreadWorker disposal starting",{name:"ThreadWorker.dispose",threadID:this.threadID,subthreadCount:this.registeredSubthreads.size,activeToolCount:Object.keys(this.ops.tools).length}),this.isDisposed=!0,this.disposed$.next(),this.disposed$.complete(),await Promise.all(Array.from(this.registeredSubthreads.values()).map(async(J)=>{J.fileChanges?.unsubscribe(),await J.worker?.asyncDispose()})),this.registeredSubthreads.clear(),this.cancelledToolUses.clear(),this._state.complete(),this.ephemeralError.complete(),this.inferenceState.complete(),this.summaryState.complete(),this.fileChanges.complete(),this.toolCallUpdates.complete(),this._subthreadsSubject.complete(),this.abortAllTools(),this.ops.inference)this.ops.inference.abort(),this.ops.inference=null;if(this.fs.tracker.dispose(),this.threadReadWriter)await this.threadReadWriter.asyncDispose(),this.threadReadWriter=null}selectModel(J){return AD1(J,G7(this.thread,"user"))}}function gD0(J,Q){let Z=G7(J,"assistant");if(!Z||Z.state.type!=="complete"||Z.state.stopReason!=="tool_use")return!1;let X=Z.content.filter((q)=>q.type==="tool_use").map((q)=>q.id);if(Q&&!X.includes(Q))return a.debug(`tool:data for orphaned tool_use ${Q} - ignoring for inference`,{name:"shouldRunInferenceWithToolData",threadID:J.id}),!1;if(X.length===0)return!1;let Y=jQ(J);return X.every((q)=>{let G=Y.get(q);if(!G||!C5(G.run))return!1;let z=G.run.status;return z!=="cancelled"&&z!=="rejected-by-user"})}var mD0=p(()=>{K8();i0();OQ();MR();B0();V4();LD0();nG();OU1();hJ();wD0();wF();Z9();C2();ED0();SD0();RD1();Z4();_D0();$3();hD0()});class pD0{threadWorkers=new ZC;async getOrCreateForThread(J,Q){if(await J.threadService.getPrimitiveProperty(Q,"mainThreadID"))return this.getOrCreateForSubThread(J,Q);return this.getOrCreateForThreadInternal(J,Q)}async getOrCreateForSubThread(J,Q){let Z=S5(J.toolService,wr);return this.getOrCreateForThreadInternal({...J,toolService:Z},Q)}async getOrCreateForThreadInternal(J,Q){let Z=this.threadWorkers.get(Q);if(!Z){if(Z=new WL1(J,Q),this.threadWorkers.set(Q,Z),this.threadWorkers.size>25)a.info("Many active thread workers detected",{name:"ThreadWorkerService.memoryCheck",threadID:Q,totalWorkerCount:this.threadWorkers.size})}return HL1.record(this.threadWorkers.size),Z}get workers(){return this.threadWorkers.observable}get statuses(){return this.threadWorkers.observable.pipe(S9((J)=>J.size===0?K0.of({}):J4(...Array.from(J.values()).map((Q)=>Q.status.pipe(g0((Z)=>[Q.threadID,Q.threadReadWriter?d_(Q.thread,Z):void 0])))).pipe(g0((Q)=>Object.fromEntries(Q)))),hK(25),r9())}get(J){return this.threadWorkers.get(J)}prettyPrintToolRun(J,Q,Z){let X=this.threadWorkers.get(J);if(!X)throw Error(`No worker found for thread ${J}`);for(let Y of X.thread.messages)for(let K of Y.content)if(K.type==="tool_result"&&K.toolUseID===Q)return bU0(K.run,Z);throw Error(`Tool run not found for thread ${J} and tool use ${Q}`)}async cancelToolOnly(J,Q){await this.threadWorkers.get(J)?.cancelToolOnly(Q)}async cancel(J){await this.threadWorkers.get(J)?.cancel()}async dispose(J){let Q=this.threadWorkers.get(J);if(Q)await Q.asyncDispose(),this.threadWorkers.delete(J),HL1.record(this.threadWorkers.size);this.threadWorkers.dispose()}async retry(J){let Q=this.threadWorkers.get(J);if(!Q)throw Error(`No active worker for thread ${J}`);await Q.retry()}async revertFileChanges(J,Q){let Z=this.threadWorkers.get(J);if(!Z)throw Error(`No active worker for thread ${J}`);await Z.revertFileChanges(Q)}async cleanupThreadBackups(J,Q){let Z=this.threadWorkers.get(Q);if(Z)await Z.fs.tracker.cleanupBackups();else{let X=await J.threadService.get(Q);if(!X)return;let Y=J.vfs.fileSystemWithMountedTrees(nv(X));try{await new sv(Y).cleanup(Q),a.debug(`Cleaned up backup files for thread ${Q}`,{threadID:Q})}catch(K){a.error("Error cleaning up thread backups",K,{threadID:Q})}}}async disposeAll(){await Promise.all(Array.from(this.threadWorkers.values()).map(async(J)=>await J.asyncDispose())),this.threadWorkers.clear(),HL1.record(0)}}var uD0,aZ8,HL1,dJ;var $3=p(()=>{uD0=u6(HC(),1);i0();B0();wF();Er();xU0();C2();tl();mD0();aZ8=uD0.metrics.getMeter("thread-worker-service"),HL1=aZ8.createGauge("thread_worker_count",{description:"Number of active thread workers"});dJ=new pD0});var Nx=e((lD0)=>{Object.defineProperty(lD0,"__esModule",{value:!0});lD0.regexpCode=lD0.getEsmExportName=lD0.getProperty=lD0.safeStringify=lD0.stringify=lD0.strConcat=lD0.addCodeArg=lD0.str=lD0._=lD0.nil=lD0._Code=lD0.Name=lD0.IDENTIFIER=lD0._CodeOrName=void 0;class ko{}lD0._CodeOrName=ko;lD0.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class JE extends ko{constructor(J){super();if(!lD0.IDENTIFIER.test(J))throw Error("CodeGen: name must be a valid identifier");this.str=J}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}lD0.Name=JE;class Cq extends ko{constructor(J){super();this._items=typeof J==="string"?[J]:J}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let J=this._items[0];return J===""||J==='""'}get str(){var J;return(J=this._str)!==null&&J!==void 0?J:this._str=this._items.reduce((Q,Z)=>`${Q}${Z}`,"")}get names(){var J;return(J=this._names)!==null&&J!==void 0?J:this._names=this._items.reduce((Q,Z)=>{if(Z instanceof JE)Q[Z.str]=(Q[Z.str]||0)+1;return Q},{})}}lD0._Code=Cq;lD0.nil=new Cq("");function dD0(J,...Q){let Z=[J[0]],X=0;while(X<Q.length)DL1(Z,Q[X]),Z.push(J[++X]);return new Cq(Z)}lD0._=dD0;var BL1=new Cq("+");function cD0(J,...Q){let Z=[Vx(J[0])],X=0;while(X<Q.length)Z.push(BL1),DL1(Z,Q[X]),Z.push(BL1,Vx(J[++X]));return rZ8(Z),new Cq(Z)}lD0.str=cD0;function DL1(J,Q){if(Q instanceof Cq)J.push(...Q._items);else if(Q instanceof JE)J.push(Q);else J.push(tZ8(Q))}lD0.addCodeArg=DL1;function rZ8(J){let Q=1;while(Q<J.length-1){if(J[Q]===BL1){let Z=sZ8(J[Q-1],J[Q+1]);if(Z!==void 0){J.splice(Q-1,3,Z);continue}J[Q++]="+"}Q++}}function sZ8(J,Q){if(Q==='""')return J;if(J==='""')return Q;if(typeof J=="string"){if(Q instanceof JE||J[J.length-1]!=='"')return;if(typeof Q!="string")return`${J.slice(0,-1)}${Q}"`;if(Q[0]==='"')return J.slice(0,-1)+Q.slice(1);return}if(typeof Q=="string"&&Q[0]==='"'&&!(J instanceof JE))return`"${J}${Q.slice(1)}`;return}function oZ8(J,Q){return Q.emptyStr()?J:J.emptyStr()?Q:cD0`${J}${Q}`}lD0.strConcat=oZ8;function tZ8(J){return typeof J=="number"||typeof J=="boolean"||J===null?J:Vx(Array.isArray(J)?J.join(","):J)}function eZ8(J){return new Cq(Vx(J))}lD0.stringify=eZ8;function Vx(J){return JSON.stringify(J).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}lD0.safeStringify=Vx;function JX8(J){return typeof J=="string"&&lD0.IDENTIFIER.test(J)?new Cq(`.${J}`):dD0`[${J}]`}lD0.getProperty=JX8;function QX8(J){if(typeof J=="string"&&lD0.IDENTIFIER.test(J))return new Cq(`${J}`);throw Error(`CodeGen: invalid export name: ${J}, use explicit $id name mapping`)}lD0.getEsmExportName=QX8;function ZX8(J){return new Cq(J.toString())}lD0.regexpCode=ZX8});var LL1=e((rD0)=>{Object.defineProperty(rD0,"__esModule",{value:!0});rD0.ValueScope=rD0.ValueScopeName=rD0.Scope=rD0.varKinds=rD0.UsedValueState=void 0;var $Z=Nx();class nD0 extends Error{constructor(J){super(`CodeGen: "code" for ${J} not defined`);this.value=J.value}}var bo;(function(J){J[J.Started=0]="Started",J[J.Completed=1]="Completed"})(bo||(rD0.UsedValueState=bo={}));rD0.varKinds={const:new $Z.Name("const"),let:new $Z.Name("let"),var:new $Z.Name("var")};class VL1{constructor({prefixes:J,parent:Q}={}){this._names={},this._prefixes=J,this._parent=Q}toName(J){return J instanceof $Z.Name?J:this.name(J)}name(J){return new $Z.Name(this._newName(J))}_newName(J){let Q=this._names[J]||this._nameGroup(J);return`${J}${Q.index++}`}_nameGroup(J){var Q,Z;if(((Z=(Q=this._parent)===null||Q===void 0?void 0:Q._prefixes)===null||Z===void 0?void 0:Z.has(J))||this._prefixes&&!this._prefixes.has(J))throw Error(`CodeGen: prefix "${J}" is not allowed in this scope`);return this._names[J]={prefix:J,index:0}}}rD0.Scope=VL1;class NL1 extends $Z.Name{constructor(J,Q){super(Q);this.prefix=J}setValue(J,{property:Q,itemIndex:Z}){this.value=J,this.scopePath=$Z._`.${new $Z.Name(Q)}[${Z}]`}}rD0.ValueScopeName=NL1;var MX8=$Z._`\n`;class aD0 extends VL1{constructor(J){super(J);this._values={},this._scope=J.scope,this.opts={...J,_n:J.lines?MX8:$Z.nil}}get(){return this._scope}name(J){return new NL1(J,this._newName(J))}value(J,Q){var Z;if(Q.ref===void 0)throw Error("CodeGen: ref must be passed in value");let X=this.toName(J),{prefix:Y}=X,K=(Z=Q.key)!==null&&Z!==void 0?Z:Q.ref,q=this._values[Y];if(q){let U=q.get(K);if(U)return U}else q=this._values[Y]=new Map;q.set(K,X);let G=this._scope[Y]||(this._scope[Y]=[]),z=G.length;return G[z]=Q.ref,X.setValue(Q,{property:Y,itemIndex:z}),X}getValue(J,Q){let Z=this._values[J];if(!Z)return;return Z.get(Q)}scopeRefs(J,Q=this._values){return this._reduceValues(Q,(Z)=>{if(Z.scopePath===void 0)throw Error(`CodeGen: name "${Z}" has no value`);return $Z._`${J}${Z.scopePath}`})}scopeCode(J=this._values,Q,Z){return this._reduceValues(J,(X)=>{if(X.value===void 0)throw Error(`CodeGen: name "${X}" has no value`);return X.value.code},Q,Z)}_reduceValues(J,Q,Z={},X){let Y=$Z.nil;for(let K in J){let q=J[K];if(!q)continue;let G=Z[K]=Z[K]||new Map;q.forEach((z)=>{if(G.has(z))return;G.set(z,bo.Started);let U=Q(z);if(U){let F=this.opts.es5?rD0.varKinds.var:rD0.varKinds.const;Y=$Z._`${Y}${F} ${z} = ${U};${this.opts._n}`}else if(U=X===null||X===void 0?void 0:X(z))Y=$Z._`${Y}${U}${this.opts._n}`;else throw new nD0(z);G.set(z,bo.Completed)})}return Y}}rD0.ValueScope=aD0});var _8=e((PZ)=>{Object.defineProperty(PZ,"__esModule",{value:!0});PZ.or=PZ.and=PZ.not=PZ.CodeGen=PZ.operators=PZ.varKinds=PZ.ValueScopeName=PZ.ValueScope=PZ.Scope=PZ.Name=PZ.regexpCode=PZ.stringify=PZ.getProperty=PZ.nil=PZ.strConcat=PZ.str=PZ._=void 0;var R9=Nx(),Sq=LL1(),fD=Nx();Object.defineProperty(PZ,"_",{enumerable:!0,get:function(){return fD._}});Object.defineProperty(PZ,"str",{enumerable:!0,get:function(){return fD.str}});Object.defineProperty(PZ,"strConcat",{enumerable:!0,get:function(){return fD.strConcat}});Object.defineProperty(PZ,"nil",{enumerable:!0,get:function(){return fD.nil}});Object.defineProperty(PZ,"getProperty",{enumerable:!0,get:function(){return fD.getProperty}});Object.defineProperty(PZ,"stringify",{enumerable:!0,get:function(){return fD.stringify}});Object.defineProperty(PZ,"regexpCode",{enumerable:!0,get:function(){return fD.regexpCode}});Object.defineProperty(PZ,"Name",{enumerable:!0,get:function(){return fD.Name}});var mo=LL1();Object.defineProperty(PZ,"Scope",{enumerable:!0,get:function(){return mo.Scope}});Object.defineProperty(PZ,"ValueScope",{enumerable:!0,get:function(){return mo.ValueScope}});Object.defineProperty(PZ,"ValueScopeName",{enumerable:!0,get:function(){return mo.ValueScopeName}});Object.defineProperty(PZ,"varKinds",{enumerable:!0,get:function(){return mo.varKinds}});PZ.operators={GT:new R9._Code(">"),GTE:new R9._Code(">="),LT:new R9._Code("<"),LTE:new R9._Code("<="),EQ:new R9._Code("==="),NEQ:new R9._Code("!=="),NOT:new R9._Code("!"),OR:new R9._Code("||"),AND:new R9._Code("&&"),ADD:new R9._Code("+")};class hD{optimizeNodes(){return this}optimizeNames(J,Q){return this}}class oD0 extends hD{constructor(J,Q,Z){super();this.varKind=J,this.name=Q,this.rhs=Z}render({es5:J,_n:Q}){let Z=J?Sq.varKinds.var:this.varKind,X=this.rhs===void 0?"":` = ${this.rhs}`;return`${Z} ${this.name}${X};`+Q}optimizeNames(J,Q){if(!J[this.name.str])return;if(this.rhs)this.rhs=ZE(this.rhs,J,Q);return this}get names(){return this.rhs instanceof R9._CodeOrName?this.rhs.names:{}}}class jL1 extends hD{constructor(J,Q,Z){super();this.lhs=J,this.rhs=Q,this.sideEffects=Z}render({_n:J}){return`${this.lhs} = ${this.rhs};`+J}optimizeNames(J,Q){if(this.lhs instanceof R9.Name&&!J[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ZE(this.rhs,J,Q),this}get names(){let J=this.lhs instanceof R9.Name?{}:{...this.lhs.names};return go(J,this.rhs)}}class tD0 extends jL1{constructor(J,Q,Z,X){super(J,Z,X);this.op=Q}render({_n:J}){return`${this.lhs} ${this.op}= ${this.rhs};`+J}}class eD0 extends hD{constructor(J){super();this.label=J,this.names={}}render({_n:J}){return`${this.label}:`+J}}class JM0 extends hD{constructor(J){super();this.label=J,this.names={}}render({_n:J}){return`break${this.label?` ${this.label}`:""};`+J}}class QM0 extends hD{constructor(J){super();this.error=J}render({_n:J}){return`throw ${this.error};`+J}get names(){return this.error.names}}class ZM0 extends hD{constructor(J){super();this.code=J}render({_n:J}){return`${this.code};`+J}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(J,Q){return this.code=ZE(this.code,J,Q),this}get names(){return this.code instanceof R9._CodeOrName?this.code.names:{}}}class uo extends hD{constructor(J=[]){super();this.nodes=J}render(J){return this.nodes.reduce((Q,Z)=>Q+Z.render(J),"")}optimizeNodes(){let{nodes:J}=this,Q=J.length;while(Q--){let Z=J[Q].optimizeNodes();if(Array.isArray(Z))J.splice(Q,1,...Z);else if(Z)J[Q]=Z;else J.splice(Q,1)}return J.length>0?this:void 0}optimizeNames(J,Q){let{nodes:Z}=this,X=Z.length;while(X--){let Y=Z[X];if(Y.optimizeNames(J,Q))continue;OX8(J,Y.names),Z.splice(X,1)}return Z.length>0?this:void 0}get names(){return this.nodes.reduce((J,Q)=>UL(J,Q.names),{})}}class gD extends uo{render(J){return"{"+J._n+super.render(J)+"}"+J._n}}class XM0 extends uo{}class Lx extends gD{}Lx.kind="else";class zW extends gD{constructor(J,Q){super(Q);this.condition=J}render(J){let Q=`if(${this.condition})`+super.render(J);if(this.else)Q+="else "+this.else.render(J);return Q}optimizeNodes(){super.optimizeNodes();let J=this.condition;if(J===!0)return this.nodes;let Q=this.else;if(Q){let Z=Q.optimizeNodes();Q=this.else=Array.isArray(Z)?new Lx(Z):Z}if(Q){if(J===!1)return Q instanceof zW?Q:Q.nodes;if(this.nodes.length)return this;return new zW(zM0(J),Q instanceof zW?[Q]:Q.nodes)}if(J===!1||!this.nodes.length)return;return this}optimizeNames(J,Q){var Z;if(this.else=(Z=this.else)===null||Z===void 0?void 0:Z.optimizeNames(J,Q),!(super.optimizeNames(J,Q)||this.else))return;return this.condition=ZE(this.condition,J,Q),this}get names(){let J=super.names;if(go(J,this.condition),this.else)UL(J,this.else.names);return J}}zW.kind="if";class QE extends gD{}QE.kind="for";class YM0 extends QE{constructor(J){super();this.iteration=J}render(J){return`for(${this.iteration})`+super.render(J)}optimizeNames(J,Q){if(!super.optimizeNames(J,Q))return;return this.iteration=ZE(this.iteration,J,Q),this}get names(){return UL(super.names,this.iteration.names)}}class KM0 extends QE{constructor(J,Q,Z,X){super();this.varKind=J,this.name=Q,this.from=Z,this.to=X}render(J){let Q=J.es5?Sq.varKinds.var:this.varKind,{name:Z,from:X,to:Y}=this;return`for(${Q} ${Z}=${X}; ${Z}<${Y}; ${Z}++)`+super.render(J)}get names(){let J=go(super.names,this.from);return go(J,this.to)}}class OL1 extends QE{constructor(J,Q,Z,X){super();this.loop=J,this.varKind=Q,this.name=Z,this.iterable=X}render(J){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(J)}optimizeNames(J,Q){if(!super.optimizeNames(J,Q))return;return this.iterable=ZE(this.iterable,J,Q),this}get names(){return UL(super.names,this.iterable.names)}}class xo extends gD{constructor(J,Q,Z){super();this.name=J,this.args=Q,this.async=Z}render(J){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(J)}}xo.kind="func";class yo extends uo{render(J){return"return "+super.render(J)}}yo.kind="return";class qM0 extends gD{render(J){let Q="try"+super.render(J);if(this.catch)Q+=this.catch.render(J);if(this.finally)Q+=this.finally.render(J);return Q}optimizeNodes(){var J,Q;return super.optimizeNodes(),(J=this.catch)===null||J===void 0||J.optimizeNodes(),(Q=this.finally)===null||Q===void 0||Q.optimizeNodes(),this}optimizeNames(J,Q){var Z,X;return super.optimizeNames(J,Q),(Z=this.catch)===null||Z===void 0||Z.optimizeNames(J,Q),(X=this.finally)===null||X===void 0||X.optimizeNames(J,Q),this}get names(){let J=super.names;if(this.catch)UL(J,this.catch.names);if(this.finally)UL(J,this.finally.names);return J}}class fo extends gD{constructor(J){super();this.error=J}render(J){return`catch(${this.error})`+super.render(J)}}fo.kind="catch";class ho extends gD{render(J){return"finally"+super.render(J)}}ho.kind="finally";class GM0{constructor(J,Q={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Q,_n:Q.lines?`
|
1859
1859
|
`:""},this._extScope=J,this._scope=new Sq.Scope({parent:J}),this._nodes=[new XM0]}toString(){return this._root.render(this.opts)}name(J){return this._scope.name(J)}scopeName(J){return this._extScope.name(J)}scopeValue(J,Q){let Z=this._extScope.value(J,Q);return(this._values[Z.prefix]||(this._values[Z.prefix]=new Set)).add(Z),Z}getScopeValue(J,Q){return this._extScope.getValue(J,Q)}scopeRefs(J){return this._extScope.scopeRefs(J,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(J,Q,Z,X){let Y=this._scope.toName(Q);if(Z!==void 0&&X)this._constants[Y.str]=Z;return this._leafNode(new oD0(J,Y,Z)),Y}const(J,Q,Z){return this._def(Sq.varKinds.const,J,Q,Z)}let(J,Q,Z){return this._def(Sq.varKinds.let,J,Q,Z)}var(J,Q,Z){return this._def(Sq.varKinds.var,J,Q,Z)}assign(J,Q,Z){return this._leafNode(new jL1(J,Q,Z))}add(J,Q){return this._leafNode(new tD0(J,PZ.operators.ADD,Q))}code(J){if(typeof J=="function")J();else if(J!==R9.nil)this._leafNode(new ZM0(J));return this}object(...J){let Q=["{"];for(let[Z,X]of J){if(Q.length>1)Q.push(",");if(Q.push(Z),Z!==X||this.opts.es5)Q.push(":"),(0,R9.addCodeArg)(Q,X)}return Q.push("}"),new R9._Code(Q)}if(J,Q,Z){if(this._blockNode(new zW(J)),Q&&Z)this.code(Q).else().code(Z).endIf();else if(Q)this.code(Q).endIf();else if(Z)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(J){return this._elseNode(new zW(J))}else(){return this._elseNode(new Lx)}endIf(){return this._endBlockNode(zW,Lx)}_for(J,Q){if(this._blockNode(J),Q)this.code(Q).endFor();return this}for(J,Q){return this._for(new YM0(J),Q)}forRange(J,Q,Z,X,Y=this.opts.es5?Sq.varKinds.var:Sq.varKinds.let){let K=this._scope.toName(J);return this._for(new KM0(Y,K,Q,Z),()=>X(K))}forOf(J,Q,Z,X=Sq.varKinds.const){let Y=this._scope.toName(J);if(this.opts.es5){let K=Q instanceof R9.Name?Q:this.var("_arr",Q);return this.forRange("_i",0,R9._`${K}.length`,(q)=>{this.var(Y,R9._`${K}[${q}]`),Z(Y)})}return this._for(new OL1("of",X,Y,Q),()=>Z(Y))}forIn(J,Q,Z,X=this.opts.es5?Sq.varKinds.var:Sq.varKinds.const){if(this.opts.ownProperties)return this.forOf(J,R9._`Object.keys(${Q})`,Z);let Y=this._scope.toName(J);return this._for(new OL1("in",X,Y,Q),()=>Z(Y))}endFor(){return this._endBlockNode(QE)}label(J){return this._leafNode(new eD0(J))}break(J){return this._leafNode(new JM0(J))}return(J){let Q=new yo;if(this._blockNode(Q),this.code(J),Q.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(yo)}try(J,Q,Z){if(!Q&&!Z)throw Error('CodeGen: "try" without "catch" and "finally"');let X=new qM0;if(this._blockNode(X),this.code(J),Q){let Y=this.name("e");this._currNode=X.catch=new fo(Y),Q(Y)}if(Z)this._currNode=X.finally=new ho,this.code(Z);return this._endBlockNode(fo,ho)}throw(J){return this._leafNode(new QM0(J))}block(J,Q){if(this._blockStarts.push(this._nodes.length),J)this.code(J).endBlock(Q);return this}endBlock(J){let Q=this._blockStarts.pop();if(Q===void 0)throw Error("CodeGen: not in self-balancing block");let Z=this._nodes.length-Q;if(Z<0||J!==void 0&&Z!==J)throw Error(`CodeGen: wrong number of nodes: ${Z} vs ${J} expected`);return this._nodes.length=Q,this}func(J,Q=R9.nil,Z,X){if(this._blockNode(new xo(J,Q,Z)),X)this.code(X).endFunc();return this}endFunc(){return this._endBlockNode(xo)}optimize(J=1){while(J-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(J){return this._currNode.nodes.push(J),this}_blockNode(J){this._currNode.nodes.push(J),this._nodes.push(J)}_endBlockNode(J,Q){let Z=this._currNode;if(Z instanceof J||Q&&Z instanceof Q)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${Q?`${J.kind}/${Q.kind}`:J.kind}"`)}_elseNode(J){let Q=this._currNode;if(!(Q instanceof zW))throw Error('CodeGen: "else" without "if"');return this._currNode=Q.else=J,this}get _root(){return this._nodes[0]}get _currNode(){let J=this._nodes;return J[J.length-1]}set _currNode(J){let Q=this._nodes;Q[Q.length-1]=J}}PZ.CodeGen=GM0;function UL(J,Q){for(let Z in Q)J[Z]=(J[Z]||0)+(Q[Z]||0);return J}function go(J,Q){return Q instanceof R9._CodeOrName?UL(J,Q.names):J}function ZE(J,Q,Z){if(J instanceof R9.Name)return X(J);if(!Y(J))return J;return new R9._Code(J._items.reduce((K,q)=>{if(q instanceof R9.Name)q=X(q);if(q instanceof R9._Code)K.push(...q._items);else K.push(q);return K},[]));function X(K){let q=Z[K.str];if(q===void 0||Q[K.str]!==1)return K;return delete Q[K.str],q}function Y(K){return K instanceof R9._Code&&K._items.some((q)=>q instanceof R9.Name&&Q[q.str]===1&&Z[q.str]!==void 0)}}function OX8(J,Q){for(let Z in Q)J[Z]=(J[Z]||0)-(Q[Z]||0)}function zM0(J){return typeof J=="boolean"||typeof J=="number"||J===null?!J:R9._`!${AL1(J)}`}PZ.not=zM0;var AX8=UM0(PZ.operators.AND);function jX8(...J){return J.reduce(AX8)}PZ.and=jX8;var RX8=UM0(PZ.operators.OR);function wX8(...J){return J.reduce(RX8)}PZ.or=wX8;function UM0(J){return(Q,Z)=>Q===R9.nil?Z:Z===R9.nil?Q:R9._`${AL1(Q)} ${J} ${AL1(Z)}`}function AL1(J){return J instanceof R9.Name?J:R9._`(${J})`}});var H9=e((LM0)=>{Object.defineProperty(LM0,"__esModule",{value:!0});LM0.checkStrictMode=LM0.getErrorPath=LM0.Type=LM0.useFunc=LM0.setEvaluated=LM0.evaluatedPropsToName=LM0.mergeEvaluated=LM0.eachItem=LM0.unescapeJsonPointer=LM0.escapeJsonPointer=LM0.escapeFragment=LM0.unescapeFragment=LM0.schemaRefOrVal=LM0.schemaHasRulesButRef=LM0.schemaHasRules=LM0.checkUnknownRules=LM0.alwaysValidSchema=LM0.toHash=void 0;var b2=_8(),PX8=Nx();function TX8(J){let Q={};for(let Z of J)Q[Z]=!0;return Q}LM0.toHash=TX8;function CX8(J,Q){if(typeof Q=="boolean")return Q;if(Object.keys(Q).length===0)return!0;return BM0(J,Q),!DM0(Q,J.self.RULES.all)}LM0.alwaysValidSchema=CX8;function BM0(J,Q=J.schema){let{opts:Z,self:X}=J;if(!Z.strictSchema)return;if(typeof Q==="boolean")return;let Y=X.RULES.keywords;for(let K in Q)if(!Y[K])NM0(J,`unknown keyword: "${K}"`)}LM0.checkUnknownRules=BM0;function DM0(J,Q){if(typeof J=="boolean")return!J;for(let Z in J)if(Q[Z])return!0;return!1}LM0.schemaHasRules=DM0;function SX8(J,Q){if(typeof J=="boolean")return!J;for(let Z in J)if(Z!=="$ref"&&Q.all[Z])return!0;return!1}LM0.schemaHasRulesButRef=SX8;function vX8({topSchemaRef:J,schemaPath:Q},Z,X,Y){if(!Y){if(typeof Z=="number"||typeof Z=="boolean")return Z;if(typeof Z=="string")return b2._`${Z}`}return b2._`${J}${Q}${(0,b2.getProperty)(X)}`}LM0.schemaRefOrVal=vX8;function kX8(J){return MM0(decodeURIComponent(J))}LM0.unescapeFragment=kX8;function _X8(J){return encodeURIComponent(wL1(J))}LM0.escapeFragment=_X8;function wL1(J){if(typeof J=="number")return`${J}`;return J.replace(/~/g,"~0").replace(/\//g,"~1")}LM0.escapeJsonPointer=wL1;function MM0(J){return J.replace(/~1/g,"/").replace(/~0/g,"~")}LM0.unescapeJsonPointer=MM0;function bX8(J,Q){if(Array.isArray(J))for(let Z of J)Q(Z);else Q(J)}LM0.eachItem=bX8;function WM0({mergeNames:J,mergeToName:Q,mergeValues:Z,resultToName:X}){return(Y,K,q,G)=>{let z=q===void 0?K:q instanceof b2.Name?(K instanceof b2.Name?J(Y,K,q):Q(Y,K,q),q):K instanceof b2.Name?(Q(Y,q,K),K):Z(K,q);return G===b2.Name&&!(z instanceof b2.Name)?X(Y,z):z}}LM0.mergeEvaluated={props:WM0({mergeNames:(J,Q,Z)=>J.if(b2._`${Z} !== true && ${Q} !== undefined`,()=>{J.if(b2._`${Q} === true`,()=>J.assign(Z,!0),()=>J.assign(Z,b2._`${Z} || {}`).code(b2._`Object.assign(${Z}, ${Q})`))}),mergeToName:(J,Q,Z)=>J.if(b2._`${Z} !== true`,()=>{if(Q===!0)J.assign(Z,!0);else J.assign(Z,b2._`${Z} || {}`),IL1(J,Z,Q)}),mergeValues:(J,Q)=>J===!0?!0:{...J,...Q},resultToName:VM0}),items:WM0({mergeNames:(J,Q,Z)=>J.if(b2._`${Z} !== true && ${Q} !== undefined`,()=>J.assign(Z,b2._`${Q} === true ? true : ${Z} > ${Q} ? ${Z} : ${Q}`)),mergeToName:(J,Q,Z)=>J.if(b2._`${Z} !== true`,()=>J.assign(Z,Q===!0?!0:b2._`${Z} > ${Q} ? ${Z} : ${Q}`)),mergeValues:(J,Q)=>J===!0?!0:Math.max(J,Q),resultToName:(J,Q)=>J.var("items",Q)})};function VM0(J,Q){if(Q===!0)return J.var("props",!0);let Z=J.var("props",b2._`{}`);if(Q!==void 0)IL1(J,Z,Q);return Z}LM0.evaluatedPropsToName=VM0;function IL1(J,Q,Z){Object.keys(Z).forEach((X)=>J.assign(b2._`${Q}${(0,b2.getProperty)(X)}`,!0))}LM0.setEvaluated=IL1;var HM0={};function xX8(J,Q){return J.scopeValue("func",{ref:Q,code:HM0[Q.code]||(HM0[Q.code]=new PX8._Code(Q.code))})}LM0.useFunc=xX8;var RL1;(function(J){J[J.Num=0]="Num",J[J.Str=1]="Str"})(RL1||(LM0.Type=RL1={}));function yX8(J,Q,Z){if(J instanceof b2.Name){let X=Q===RL1.Num;return Z?X?b2._`"[" + ${J} + "]"`:b2._`"['" + ${J} + "']"`:X?b2._`"/" + ${J}`:b2._`"/" + ${J}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Z?(0,b2.getProperty)(J).toString():"/"+wL1(J)}LM0.getErrorPath=yX8;function NM0(J,Q,Z=J.opts.strictSchema){if(!Z)return;if(Q=`strict mode: ${Q}`,Z===!0)throw Error(Q);J.self.logger.warn(Q)}LM0.checkStrictMode=NM0});var dY=e((AM0)=>{Object.defineProperty(AM0,"__esModule",{value:!0});var nJ=_8(),JY8={data:new nJ.Name("data"),valCxt:new nJ.Name("valCxt"),instancePath:new nJ.Name("instancePath"),parentData:new nJ.Name("parentData"),parentDataProperty:new nJ.Name("parentDataProperty"),rootData:new nJ.Name("rootData"),dynamicAnchors:new nJ.Name("dynamicAnchors"),vErrors:new nJ.Name("vErrors"),errors:new nJ.Name("errors"),this:new nJ.Name("this"),self:new nJ.Name("self"),scope:new nJ.Name("scope"),json:new nJ.Name("json"),jsonPos:new nJ.Name("jsonPos"),jsonLen:new nJ.Name("jsonLen"),jsonPart:new nJ.Name("jsonPart")};AM0.default=JY8});var Ox=e((IM0)=>{Object.defineProperty(IM0,"__esModule",{value:!0});IM0.extendErrors=IM0.resetErrorsCount=IM0.reportExtraError=IM0.reportError=IM0.keyword$DataError=IM0.keywordError=void 0;var x9=_8(),co=H9(),bQ=dY();IM0.keywordError={message:({keyword:J})=>x9.str`must pass "${J}" keyword validation`};IM0.keyword$DataError={message:({keyword:J,schemaType:Q})=>Q?x9.str`"${J}" keyword must be ${Q} ($data)`:x9.str`"${J}" keyword is invalid ($data)`};function ZY8(J,Q=IM0.keywordError,Z,X){let{it:Y}=J,{gen:K,compositeRule:q,allErrors:G}=Y,z=wM0(J,Q,Z);if(X!==null&&X!==void 0?X:q||G)jM0(K,z);else RM0(Y,x9._`[${z}]`)}IM0.reportError=ZY8;function XY8(J,Q=IM0.keywordError,Z){let{it:X}=J,{gen:Y,compositeRule:K,allErrors:q}=X,G=wM0(J,Q,Z);if(jM0(Y,G),!(K||q))RM0(X,bQ.default.vErrors)}IM0.reportExtraError=XY8;function YY8(J,Q){J.assign(bQ.default.errors,Q),J.if(x9._`${bQ.default.vErrors} !== null`,()=>J.if(Q,()=>J.assign(x9._`${bQ.default.vErrors}.length`,Q),()=>J.assign(bQ.default.vErrors,null)))}IM0.resetErrorsCount=YY8;function KY8({gen:J,keyword:Q,schemaValue:Z,data:X,errsCount:Y,it:K}){if(Y===void 0)throw Error("ajv implementation error");let q=J.name("err");J.forRange("i",Y,bQ.default.errors,(G)=>{if(J.const(q,x9._`${bQ.default.vErrors}[${G}]`),J.if(x9._`${q}.instancePath === undefined`,()=>J.assign(x9._`${q}.instancePath`,(0,x9.strConcat)(bQ.default.instancePath,K.errorPath))),J.assign(x9._`${q}.schemaPath`,x9.str`${K.errSchemaPath}/${Q}`),K.opts.verbose)J.assign(x9._`${q}.schema`,Z),J.assign(x9._`${q}.data`,X)})}IM0.extendErrors=KY8;function jM0(J,Q){let Z=J.const("err",Q);J.if(x9._`${bQ.default.vErrors} === null`,()=>J.assign(bQ.default.vErrors,x9._`[${Z}]`),x9._`${bQ.default.vErrors}.push(${Z})`),J.code(x9._`${bQ.default.errors}++`)}function RM0(J,Q){let{gen:Z,validateName:X,schemaEnv:Y}=J;if(Y.$async)Z.throw(x9._`new ${J.ValidationError}(${Q})`);else Z.assign(x9._`${X}.errors`,Q),Z.return(!1)}var FL={keyword:new x9.Name("keyword"),schemaPath:new x9.Name("schemaPath"),params:new x9.Name("params"),propertyName:new x9.Name("propertyName"),message:new x9.Name("message"),schema:new x9.Name("schema"),parentSchema:new x9.Name("parentSchema")};function wM0(J,Q,Z){let{createErrors:X}=J.it;if(X===!1)return x9._`{}`;return qY8(J,Q,Z)}function qY8(J,Q,Z={}){let{gen:X,it:Y}=J,K=[GY8(Y,Z),zY8(J,Z)];return UY8(J,Q,K),X.object(...K)}function GY8({errorPath:J},{instancePath:Q}){let Z=Q?x9.str`${J}${(0,co.getErrorPath)(Q,co.Type.Str)}`:J;return[bQ.default.instancePath,(0,x9.strConcat)(bQ.default.instancePath,Z)]}function zY8({keyword:J,it:{errSchemaPath:Q}},{schemaPath:Z,parentSchema:X}){let Y=X?Q:x9.str`${Q}/${J}`;if(Z)Y=x9.str`${Y}${(0,co.getErrorPath)(Z,co.Type.Str)}`;return[FL.schemaPath,Y]}function UY8(J,{params:Q,message:Z},X){let{keyword:Y,data:K,schemaValue:q,it:G}=J,{opts:z,propertyName:U,topSchemaRef:F,schemaPath:W}=G;if(X.push([FL.keyword,Y],[FL.params,typeof Q=="function"?Q(J):Q||x9._`{}`]),z.messages)X.push([FL.message,typeof Z=="function"?Z(J):Z]);if(z.verbose)X.push([FL.schema,q],[FL.parentSchema,x9._`${F}${W}`],[bQ.default.data,K]);if(U)X.push([FL.propertyName,U])}});var CM0=e((PM0)=>{Object.defineProperty(PM0,"__esModule",{value:!0});PM0.boolOrEmptySchema=PM0.topBoolOrEmptySchema=void 0;var DY8=Ox(),MY8=_8(),VY8=dY(),NY8={message:"boolean schema is false"};function LY8(J){let{gen:Q,schema:Z,validateName:X}=J;if(Z===!1)$M0(J,!1);else if(typeof Z=="object"&&Z.$async===!0)Q.return(VY8.default.data);else Q.assign(MY8._`${X}.errors`,null),Q.return(!0)}PM0.topBoolOrEmptySchema=LY8;function OY8(J,Q){let{gen:Z,schema:X}=J;if(X===!1)Z.var(Q,!1),$M0(J);else Z.var(Q,!0)}PM0.boolOrEmptySchema=OY8;function $M0(J,Q){let{gen:Z,data:X}=J,Y={gen:Z,keyword:"false schema",data:X,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:J};(0,DY8.reportError)(Y,NY8,void 0,Q)}});var $L1=e((SM0)=>{Object.defineProperty(SM0,"__esModule",{value:!0});SM0.getRules=SM0.isJSONType=void 0;var jY8=["string","number","integer","boolean","null","object","array"],RY8=new Set(jY8);function wY8(J){return typeof J=="string"&&RY8.has(J)}SM0.isJSONType=wY8;function IY8(){let J={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...J,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},J.number,J.string,J.array,J.object],post:{rules:[]},all:{},keywords:{}}}SM0.getRules=IY8});var PL1=e((bM0)=>{Object.defineProperty(bM0,"__esModule",{value:!0});bM0.shouldUseRule=bM0.shouldUseGroup=bM0.schemaHasRulesForType=void 0;function $Y8({schema:J,self:Q},Z){let X=Q.RULES.types[Z];return X&&X!==!0&&kM0(J,X)}bM0.schemaHasRulesForType=$Y8;function kM0(J,Q){return Q.rules.some((Z)=>_M0(J,Z))}bM0.shouldUseGroup=kM0;function _M0(J,Q){var Z;return J[Q.keyword]!==void 0||((Z=Q.definition.implements)===null||Z===void 0?void 0:Z.some((X)=>J[X]!==void 0))}bM0.shouldUseRule=_M0});var Ax=e((gM0)=>{Object.defineProperty(gM0,"__esModule",{value:!0});gM0.reportTypeError=gM0.checkDataTypes=gM0.checkDataType=gM0.coerceAndCheckDataType=gM0.getJSONTypes=gM0.getSchemaTypes=gM0.DataType=void 0;var CY8=$L1(),SY8=PL1(),vY8=Ox(),l8=_8(),yM0=H9(),XE;(function(J){J[J.Correct=0]="Correct",J[J.Wrong=1]="Wrong"})(XE||(gM0.DataType=XE={}));function kY8(J){let Q=fM0(J.type);if(Q.includes("null")){if(J.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!Q.length&&J.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(J.nullable===!0)Q.push("null")}return Q}gM0.getSchemaTypes=kY8;function fM0(J){let Q=Array.isArray(J)?J:J?[J]:[];if(Q.every(CY8.isJSONType))return Q;throw Error("type must be JSONType or JSONType[]: "+Q.join(","))}gM0.getJSONTypes=fM0;function _Y8(J,Q){let{gen:Z,data:X,opts:Y}=J,K=bY8(Q,Y.coerceTypes),q=Q.length>0&&!(K.length===0&&Q.length===1&&(0,SY8.schemaHasRulesForType)(J,Q[0]));if(q){let G=CL1(Q,X,Y.strictNumbers,XE.Wrong);Z.if(G,()=>{if(K.length)xY8(J,Q,K);else SL1(J)})}return q}gM0.coerceAndCheckDataType=_Y8;var hM0=new Set(["string","number","integer","boolean","null"]);function bY8(J,Q){return Q?J.filter((Z)=>hM0.has(Z)||Q==="array"&&Z==="array"):[]}function xY8(J,Q,Z){let{gen:X,data:Y,opts:K}=J,q=X.let("dataType",l8._`typeof ${Y}`),G=X.let("coerced",l8._`undefined`);if(K.coerceTypes==="array")X.if(l8._`${q} == 'object' && Array.isArray(${Y}) && ${Y}.length == 1`,()=>X.assign(Y,l8._`${Y}[0]`).assign(q,l8._`typeof ${Y}`).if(CL1(Q,Y,K.strictNumbers),()=>X.assign(G,Y)));X.if(l8._`${G} !== undefined`);for(let U of Z)if(hM0.has(U)||U==="array"&&K.coerceTypes==="array")z(U);X.else(),SL1(J),X.endIf(),X.if(l8._`${G} !== undefined`,()=>{X.assign(Y,G),yY8(J,G)});function z(U){switch(U){case"string":X.elseIf(l8._`${q} == "number" || ${q} == "boolean"`).assign(G,l8._`"" + ${Y}`).elseIf(l8._`${Y} === null`).assign(G,l8._`""`);return;case"number":X.elseIf(l8._`${q} == "boolean" || ${Y} === null
|
1860
1860
|
|| (${q} == "string" && ${Y} && ${Y} == +${Y})`).assign(G,l8._`+${Y}`);return;case"integer":X.elseIf(l8._`${q} === "boolean" || ${Y} === null
|
1861
1861
|
|| (${q} === "string" && ${Y} && ${Y} == +${Y} && !(${Y} % 1))`).assign(G,l8._`+${Y}`);return;case"boolean":X.elseIf(l8._`${Y} === "false" || ${Y} === 0 || ${Y} === null`).assign(G,!1).elseIf(l8._`${Y} === "true" || ${Y} === 1`).assign(G,!0);return;case"null":X.elseIf(l8._`${Y} === "" || ${Y} === 0 || ${Y} === false`),X.assign(G,null);return;case"array":X.elseIf(l8._`${q} === "string" || ${q} === "number"
|
@@ -5440,7 +5440,7 @@ See https://ampcode.com/manual#toolboxes`);return Q[0]||QR}function iJ6(J,Q){let
|
|
5440
5440
|
`);J.command("use").argument("<tool-name>","The tool to invoke").summary("Invoke a tool with arguments or JSON input from stdin").description(Z).option("--only <field>","Extract only the specified field from the result").allowUnknownOption(!0).allowExcessArguments(!0).action(async function(X,Y,K){let q=K.optsWithGlobals(),G=await Q(K,q),z=0;await G.mcpService.initialized;let U=K.args.slice(1),F;if(dJ6()){let W=[];for await(let H of process.stdin)W.push(H);F=Buffer.concat(W).toString("utf-8").trim()}await uJ6({toolName:X,rawArgs:U,stdinInput:F,only:Y.only,threadDeps:G,stdout:process.stdout,stderr:process.stderr,exit:(W)=>{z=W}}),await G.asyncDispose(),G.cleanupTerminal(),process.exit(z)})}var nJ6=p(()=>{yS();WV();$J6();SJ6();kJ6();cJ6()});function aJ6(J){let Q=J.trim();if(Q==="quit"||Q==="exit")return"/quit";return J}import R29 from"node:fs";import rJ6 from"node:path";function sJ6(J){let Q=J.trim().replace(/^["']|["']$/g,"");if(Q=Q.replace(/\\(.)/g,"$1"),!/\.(png|jpe?g|gif|webp)$/i.test(Q))return null;if(!rJ6.isAbsolute(Q))return null;return a.debug("Extracted image path",{original:J,extracted:Q}),Q}function oJ6(J){try{let Q=rJ6.extname(J).toLowerCase(),Z=Eo1(Q);if(!Z)return a.warn("Unsupported image file extension",{ext:Q}),null;try{let X=R29.readFileSync(J);return w29(X,Z)}catch(X){a.error(`Failed to read image file ${J}:`,X)}}catch(Q){a.error("Error handling image file path",{imagePath:J,error:Q})}return null}function w29(J,Q){if(J.length>NR)return a.warn(`Image file too large: ${J.length} bytes (max: ${NR})`),null;return{type:"image",source:{type:"base64",data:J.toString("base64"),mediaType:Q}}}var tJ6=p(()=>{B0();TN()});function eJ6(J){return J.kind==="executable"}function JQ6(J){return J.kind==="markdown"}import{spawn as I29}from"node:child_process";import{promises as E29}from"node:fs";async function tb1(J,Q,Z,X={}){let{timeoutMs:Y=QQ6,signal:K}=X;try{let q=await Z.getCommand(J);if(!q)return{success:!1,output:"",error:`Command '${J}' not found`};if(!await Z.isCommandAvailable(J))return{success:!1,output:"",error:`Command '${J}' is not available for execution`};if(a.debug("Executing command",{commandName:J,filePath:q.filePath,args:Q}),JQ6(q))return await $29(q,Q);else if(eJ6(q))return await P29(q,Q,Y,K);else return{success:!1,output:"",error:"Unsupported command type"}}catch(q){return a.error("Failed to execute command",{commandName:J,error:q}),{success:!1,output:"",error:q instanceof Error?q.message:"Unknown error occurred"}}}async function $29(J,Q){try{if(Q.length>0)return{success:!1,output:"",error:"Markdown commands do not accept arguments"};let Z=await E29.readFile(J.filePath,"utf8");return{success:!0,output:(Z.length>jH?Z.slice(0,jH)+`
|
5441
5441
|
... (output truncated at ${jH} characters)`:Z).trim(),exitCode:0}}catch(Z){return{success:!1,output:"",error:Z instanceof Error?Z.message:"Failed to read markdown file"}}}async function P29(J,Q,Z=QQ6,X){return new Promise((Y)=>{let[K,q]=T29(J,Q);a.debug("Spawning command",{spawnCommand:K,spawnArgs:q.slice(0,10),filePath:J.filePath,timeoutMs:Z});let G=jo1(X),z=!1,U=setTimeout(()=>{z=!0,G.abort(),a.warn("Command execution timed out",{commandName:J.name,timeoutMs:Z})},Z),F=I29(K,q,{stdio:["pipe","pipe","pipe"],signal:G.signal,detached:!0}),W=[],H=[],D=0;F.stdout?.on("data",(M)=>{let V=M.toString();if(D+=V.length,D<=jH)W.push(V);else{let N=jH-(D-V.length);if(N>0)W.push(V.slice(0,N))}}),F.stderr?.on("data",(M)=>{let V=M.toString();if(D+=V.length,D<=jH)H.push(V);else{let N=jH-(D-V.length);if(N>0)H.push(V.slice(0,N))}}),F.on("close",(M)=>{if(clearTimeout(U),z){Y({success:!1,output:W.join(""),error:`Command timed out after ${Z}ms`,exitCode:void 0});return}if(G.signal.aborted){Y({success:!1,output:W.join(""),error:"The command was aborted",exitCode:M??void 0});return}let V=M===0||M===1,N=W.join(""),L=H.join(""),O=N;if(!V&&!N.trim()&&L.trim())O=L;else if(L.trim())O+=N?`
|
5442
5442
|
${L}`:L;if(D>jH)O+=`
|
5443
|
-
... (output truncated at ${jH} characters)`;Y({success:V,output:O.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),F.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:W.join(""),error:V})})})}function T29(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return S29(Z,X?[...X]:null,Y,Q);else return C29(Z,X?[...X]:null,Y,Q)}function C29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function S29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}var jH=50000,QQ6=300000;var ZQ6=p(()=>{MR();B0()});var XQ6=p(()=>{ZQ6();lJ1()});var k41,mz2,uz2,pz2,dz2,cz2,lz2,iz2,nz2,az2,dm,rz2,sz2,oz2,tz2,ez2;var YQ6=p(()=>{k41=globalThis.window?.document!==void 0,mz2=globalThis.process?.versions?.node!==void 0,uz2=globalThis.process?.versions?.bun!==void 0,pz2=globalThis.Deno?.version?.deno!==void 0,dz2=globalThis.process?.versions?.electron!==void 0,cz2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,lz2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,iz2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,nz2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,az2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,dm=globalThis.navigator?.userAgentData?.platform,rz2=dm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",sz2=dm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",oz2=dm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",tz2=dm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),ez2=dm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var _41={};N6(_41,{scrollUp:()=>s29,scrollDown:()=>o29,link:()=>X49,image:()=>Y49,iTerm:()=>K49,exitAlternativeScreen:()=>Q49,eraseUp:()=>r29,eraseStartLine:()=>n29,eraseScreen:()=>eb1,eraseLines:()=>l29,eraseLine:()=>zQ6,eraseEndLine:()=>i29,eraseDown:()=>a29,enterAlternativeScreen:()=>J49,cursorUp:()=>qQ6,cursorTo:()=>_29,cursorShow:()=>c29,cursorSavePosition:()=>h29,cursorRestorePosition:()=>g29,cursorPrevLine:()=>p29,cursorNextLine:()=>u29,cursorMove:()=>b29,cursorLeft:()=>GQ6,cursorHide:()=>d29,cursorGetPosition:()=>m29,cursorForward:()=>y29,cursorDown:()=>x29,cursorBackward:()=>f29,clearTerminal:()=>e29,clearScreen:()=>t29,beep:()=>Z49});import Jx1 from"node:process";var z2="\x1B[",lm="\x1B]",ST="\x07",cm=";",KQ6,v29,k29,_29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return z2+(J+1)+"G";return z2+(Q+1)+cm+(J+1)+"H"},b29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=z2+-J+"D";else if(J>0)Z+=z2+J+"C";if(Q<0)Z+=z2+-Q+"A";else if(Q>0)Z+=z2+Q+"B";return Z},qQ6=(J=1)=>z2+J+"A",x29=(J=1)=>z2+J+"B",y29=(J=1)=>z2+J+"C",f29=(J=1)=>z2+J+"D",GQ6,h29,g29,m29,u29,p29,d29,c29,l29=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=zQ6+(Z<J-1?qQ6():"");if(J)Q+=GQ6;return Q},i29,n29,zQ6,a29,r29,eb1,s29,o29,t29="\x1Bc",e29,J49,Q49,Z49,X49=(J,Q)=>[lm,"8",cm,cm,Q,ST,J,lm,"8",cm,cm,ST].join(""),Y49=(J,Q={})=>{let Z=`${lm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+ST},K49;var Qx1=p(()=>{YQ6();KQ6=!k41&&Jx1.env.TERM_PROGRAM==="Apple_Terminal",v29=!k41&&Jx1.platform==="win32",k29=k41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Jx1.cwd,GQ6=z2+"G",h29=KQ6?"\x1B7":z2+"s",g29=KQ6?"\x1B8":z2+"u",m29=z2+"6n",u29=z2+"E",p29=z2+"F",d29=z2+"?25l",c29=z2+"?25h",i29=z2+"K",n29=z2+"1K",zQ6=z2+"2K",a29=z2+"J",r29=z2+"1J",eb1=z2+"2J",s29=z2+"S",o29=z2+"T",e29=v29?`${eb1}${z2}0f`:`${eb1}${z2}3J${z2}H`,J49=z2+"?1049h",Q49=z2+"?1049l",Z49=ST,K49={setCwd:(J=k29())=>`${lm}50;CurrentDir=${J}${ST}`,annotation(J,Q={}){let Z=`${lm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+ST}}});var UQ6=p(()=>{Qx1();Qx1()});var Zx1=e((KU2,FQ6)=>{FQ6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var BQ6=e((qU2,HQ6)=>{var q49=o1("os"),WQ6=o1("tty"),_K=Zx1(),{env:o5}=process,jV;if(_K("no-color")||_K("no-colors")||_K("color=false")||_K("color=never"))jV=0;else if(_K("color")||_K("colors")||_K("color=true")||_K("color=always"))jV=1;if("FORCE_COLOR"in o5)if(o5.FORCE_COLOR==="true")jV=1;else if(o5.FORCE_COLOR==="false")jV=0;else jV=o5.FORCE_COLOR.length===0?1:Math.min(parseInt(o5.FORCE_COLOR,10),3);function Xx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function Yx1(J,Q){if(jV===0)return 0;if(_K("color=16m")||_K("color=full")||_K("color=truecolor"))return 3;if(_K("color=256"))return 2;if(J&&!Q&&jV===void 0)return 0;let Z=jV||0;if(o5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=q49.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in o5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in o5))||o5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in o5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o5.TEAMCITY_VERSION)?1:0;if(o5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o5){let X=parseInt((o5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(o5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o5.TERM))return 1;if("COLORTERM"in o5)return 1;return Z}function G49(J){let Q=Yx1(J,J&&J.isTTY);return Xx1(Q)}HQ6.exports={supportsColor:G49,stdout:Xx1(Yx1(!0,WQ6.isatty(1))),stderr:Xx1(Yx1(!0,WQ6.isatty(2)))}});var VQ6=e((GU2,MQ6)=>{var z49=BQ6(),vT=Zx1();function DQ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function Kx1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(vT("no-hyperlink")||vT("no-hyperlinks")||vT("hyperlink=false")||vT("hyperlink=never"))return!1;if(vT("hyperlink=true")||vT("hyperlink=always"))return!0;if(X)return!0;if(!z49.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=DQ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=DQ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}MQ6.exports={supportsHyperlink:Kx1,stdout:Kx1(process.stdout),stderr:Kx1(process.stderr)}});function RV(J,Q,{target:Z="stdout",...X}={}){if(!b41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return _41.link(J,Q)}var b41;var NQ6=p(()=>{UQ6();b41=u6(VQ6(),1);RV.isSupported=b41.default.stdout;RV.stderr=(J,Q,Z={})=>RV(J,Q,{target:"stderr",...Z});RV.stderr.isSupported=b41.default.stderr});class qx1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759147319-g41306c"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await M10(Q)}catch(Q){a.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}var LQ6=p(()=>{B0();PB()});class zY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function OQ6(J){if(J instanceof x41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zY)return{title:"Info",description:J.message,type:"info"};return a.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var x41;var Gx1=p(()=>{B0();x41=class x41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as AQ6}from"node:child_process";import{rmdir as U49}from"node:fs/promises";import{tmpdir as F49}from"node:os";import jQ6 from"node:path";import{mkdtemp as W49,readFile as H49,unlink as B49,writeFile as _U2}from"fs/promises";class zx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=BC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new qx1(async()=>{try{return(await A9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),Q2.pipe(g0((Q)=>Q.settings["internal.modes"]),d8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...D49},J)Object.assign(this.commands,M49)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{a.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await tb1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var D49,M49;var RQ6=p(()=>{XQ6();B0();V4();DC();dw();p4();lU();nb1();PB();qD();K8();i0();NQ6();$41();ab1();LQ6();Gx1();D49={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${h5} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:xY0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new x41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await W49(jQ6.join(F49(),"amp-edit-")),Y=jQ6.join(X,"message.amp.md");AQ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await H49(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return a.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await B49(Y),await U49(X)}catch(K){a.warn("Failed to clean up temporary file",K)}return}catch(Z){return a.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return uU("dangerouslyAllowAll",!1),new zY("Amp is now following permissions rules for this session")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return uU("dangerouslyAllowAll",!0),new zY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await TT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw a.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:TT};await S41(Y);return}catch(Y){a.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return a.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new zY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return a.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
|
5443
|
+
... (output truncated at ${jH} characters)`;Y({success:V,output:O.trim(),error:!V?L.trim()||"Command failed":void 0,exitCode:M??void 0})}),F.on("error",(M)=>{clearTimeout(U);let V=M.message;if(z)V=`Command timed out after ${Z}ms`;else if(M.message.includes("operation was aborted")||M.name==="AbortError")V="The command was aborted";Y({success:!1,output:W.join(""),error:V})})})}function T29(J,Q){let{filePath:Z,interpreter:X,extension:Y}=J;if(process.platform==="win32")return S29(Z,X?[...X]:null,Y,Q);else return C29(Z,X?[...X]:null,Y,Q)}function C29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];else return[J,X]}function S29(J,Q,Z,X){if(Q&&Q.length>0&&Q[0])return[Q[0],[...Q.slice(1),J,...X]];switch(Z.toLowerCase()){case".bat":case".cmd":return["cmd.exe",["/c",J,...X]];case".ps1":return["powershell.exe",["-ExecutionPolicy","Bypass","-File",J,...X]];case".exe":return[J,X];default:return[J,X]}}var jH=50000,QQ6=300000;var ZQ6=p(()=>{MR();B0()});var XQ6=p(()=>{ZQ6();lJ1()});var k41,mz2,uz2,pz2,dz2,cz2,lz2,iz2,nz2,az2,dm,rz2,sz2,oz2,tz2,ez2;var YQ6=p(()=>{k41=globalThis.window?.document!==void 0,mz2=globalThis.process?.versions?.node!==void 0,uz2=globalThis.process?.versions?.bun!==void 0,pz2=globalThis.Deno?.version?.deno!==void 0,dz2=globalThis.process?.versions?.electron!==void 0,cz2=globalThis.navigator?.userAgent?.includes("jsdom")===!0,lz2=typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope,iz2=typeof DedicatedWorkerGlobalScope<"u"&&globalThis instanceof DedicatedWorkerGlobalScope,nz2=typeof SharedWorkerGlobalScope<"u"&&globalThis instanceof SharedWorkerGlobalScope,az2=typeof ServiceWorkerGlobalScope<"u"&&globalThis instanceof ServiceWorkerGlobalScope,dm=globalThis.navigator?.userAgentData?.platform,rz2=dm==="macOS"||globalThis.navigator?.platform==="MacIntel"||globalThis.navigator?.userAgent?.includes(" Mac ")===!0||globalThis.process?.platform==="darwin",sz2=dm==="Windows"||globalThis.navigator?.platform==="Win32"||globalThis.process?.platform==="win32",oz2=dm==="Linux"||globalThis.navigator?.platform?.startsWith("Linux")===!0||globalThis.navigator?.userAgent?.includes(" Linux ")===!0||globalThis.process?.platform==="linux",tz2=dm==="iOS"||globalThis.navigator?.platform==="MacIntel"&&globalThis.navigator?.maxTouchPoints>1||/iPad|iPhone|iPod/.test(globalThis.navigator?.platform),ez2=dm==="Android"||globalThis.navigator?.platform==="Android"||globalThis.navigator?.userAgent?.includes(" Android ")===!0||globalThis.process?.platform==="android"});var _41={};N6(_41,{scrollUp:()=>s29,scrollDown:()=>o29,link:()=>X49,image:()=>Y49,iTerm:()=>K49,exitAlternativeScreen:()=>Q49,eraseUp:()=>r29,eraseStartLine:()=>n29,eraseScreen:()=>eb1,eraseLines:()=>l29,eraseLine:()=>zQ6,eraseEndLine:()=>i29,eraseDown:()=>a29,enterAlternativeScreen:()=>J49,cursorUp:()=>qQ6,cursorTo:()=>_29,cursorShow:()=>c29,cursorSavePosition:()=>h29,cursorRestorePosition:()=>g29,cursorPrevLine:()=>p29,cursorNextLine:()=>u29,cursorMove:()=>b29,cursorLeft:()=>GQ6,cursorHide:()=>d29,cursorGetPosition:()=>m29,cursorForward:()=>y29,cursorDown:()=>x29,cursorBackward:()=>f29,clearTerminal:()=>e29,clearScreen:()=>t29,beep:()=>Z49});import Jx1 from"node:process";var z2="\x1B[",lm="\x1B]",ST="\x07",cm=";",KQ6,v29,k29,_29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");if(typeof Q!=="number")return z2+(J+1)+"G";return z2+(Q+1)+cm+(J+1)+"H"},b29=(J,Q)=>{if(typeof J!=="number")throw TypeError("The `x` argument is required");let Z="";if(J<0)Z+=z2+-J+"D";else if(J>0)Z+=z2+J+"C";if(Q<0)Z+=z2+-Q+"A";else if(Q>0)Z+=z2+Q+"B";return Z},qQ6=(J=1)=>z2+J+"A",x29=(J=1)=>z2+J+"B",y29=(J=1)=>z2+J+"C",f29=(J=1)=>z2+J+"D",GQ6,h29,g29,m29,u29,p29,d29,c29,l29=(J)=>{let Q="";for(let Z=0;Z<J;Z++)Q+=zQ6+(Z<J-1?qQ6():"");if(J)Q+=GQ6;return Q},i29,n29,zQ6,a29,r29,eb1,s29,o29,t29="\x1Bc",e29,J49,Q49,Z49,X49=(J,Q)=>[lm,"8",cm,cm,Q,ST,J,lm,"8",cm,cm,ST].join(""),Y49=(J,Q={})=>{let Z=`${lm}1337;File=inline=1`;if(Q.width)Z+=`;width=${Q.width}`;if(Q.height)Z+=`;height=${Q.height}`;if(Q.preserveAspectRatio===!1)Z+=";preserveAspectRatio=0";return Z+":"+Buffer.from(J).toString("base64")+ST},K49;var Qx1=p(()=>{YQ6();KQ6=!k41&&Jx1.env.TERM_PROGRAM==="Apple_Terminal",v29=!k41&&Jx1.platform==="win32",k29=k41?()=>{throw Error("`process.cwd()` only works in Node.js, not the browser.")}:Jx1.cwd,GQ6=z2+"G",h29=KQ6?"\x1B7":z2+"s",g29=KQ6?"\x1B8":z2+"u",m29=z2+"6n",u29=z2+"E",p29=z2+"F",d29=z2+"?25l",c29=z2+"?25h",i29=z2+"K",n29=z2+"1K",zQ6=z2+"2K",a29=z2+"J",r29=z2+"1J",eb1=z2+"2J",s29=z2+"S",o29=z2+"T",e29=v29?`${eb1}${z2}0f`:`${eb1}${z2}3J${z2}H`,J49=z2+"?1049h",Q49=z2+"?1049l",Z49=ST,K49={setCwd:(J=k29())=>`${lm}50;CurrentDir=${J}${ST}`,annotation(J,Q={}){let Z=`${lm}1337;`,X=Q.x!==void 0,Y=Q.y!==void 0;if((X||Y)&&!(X&&Y&&Q.length!==void 0))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(J=J.replaceAll("|",""),Z+=Q.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",Q.length>0)Z+=(X?[J,Q.length,Q.x,Q.y]:[Q.length,J]).join("|");else Z+=J;return Z+ST}}});var UQ6=p(()=>{Qx1();Qx1()});var Zx1=e((KU2,FQ6)=>{FQ6.exports=(J,Q=process.argv)=>{let Z=J.startsWith("-")?"":J.length===1?"-":"--",X=Q.indexOf(Z+J),Y=Q.indexOf("--");return X!==-1&&(Y===-1||X<Y)}});var BQ6=e((qU2,HQ6)=>{var q49=o1("os"),WQ6=o1("tty"),_K=Zx1(),{env:o5}=process,jV;if(_K("no-color")||_K("no-colors")||_K("color=false")||_K("color=never"))jV=0;else if(_K("color")||_K("colors")||_K("color=true")||_K("color=always"))jV=1;if("FORCE_COLOR"in o5)if(o5.FORCE_COLOR==="true")jV=1;else if(o5.FORCE_COLOR==="false")jV=0;else jV=o5.FORCE_COLOR.length===0?1:Math.min(parseInt(o5.FORCE_COLOR,10),3);function Xx1(J){if(J===0)return!1;return{level:J,hasBasic:!0,has256:J>=2,has16m:J>=3}}function Yx1(J,Q){if(jV===0)return 0;if(_K("color=16m")||_K("color=full")||_K("color=truecolor"))return 3;if(_K("color=256"))return 2;if(J&&!Q&&jV===void 0)return 0;let Z=jV||0;if(o5.TERM==="dumb")return Z;if(process.platform==="win32"){let X=q49.release().split(".");if(Number(X[0])>=10&&Number(X[2])>=10586)return Number(X[2])>=14931?3:2;return 1}if("CI"in o5){if(["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((X)=>(X in o5))||o5.CI_NAME==="codeship")return 1;return Z}if("TEAMCITY_VERSION"in o5)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(o5.TEAMCITY_VERSION)?1:0;if(o5.COLORTERM==="truecolor")return 3;if("TERM_PROGRAM"in o5){let X=parseInt((o5.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(o5.TERM_PROGRAM){case"iTerm.app":return X>=3?3:2;case"Apple_Terminal":return 2}}if(/-256(color)?$/i.test(o5.TERM))return 2;if(/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(o5.TERM))return 1;if("COLORTERM"in o5)return 1;return Z}function G49(J){let Q=Yx1(J,J&&J.isTTY);return Xx1(Q)}HQ6.exports={supportsColor:G49,stdout:Xx1(Yx1(!0,WQ6.isatty(1))),stderr:Xx1(Yx1(!0,WQ6.isatty(2)))}});var VQ6=e((GU2,MQ6)=>{var z49=BQ6(),vT=Zx1();function DQ6(J){if(/^\d{3,4}$/.test(J)){let Z=/(\d{1,2})(\d{2})/.exec(J)||[];return{major:0,minor:parseInt(Z[1],10),patch:parseInt(Z[2],10)}}let Q=(J||"").split(".").map((Z)=>parseInt(Z,10));return{major:Q[0],minor:Q[1],patch:Q[2]}}function Kx1(J){let{CI:Q,FORCE_HYPERLINK:Z,NETLIFY:X,TEAMCITY_VERSION:Y,TERM_PROGRAM:K,TERM_PROGRAM_VERSION:q,VTE_VERSION:G,TERM:z}=process.env;if(Z)return!(Z.length>0&&parseInt(Z,10)===0);if(vT("no-hyperlink")||vT("no-hyperlinks")||vT("hyperlink=false")||vT("hyperlink=never"))return!1;if(vT("hyperlink=true")||vT("hyperlink=always"))return!0;if(X)return!0;if(!z49.supportsColor(J))return!1;if(J&&!J.isTTY)return!1;if("WT_SESSION"in process.env)return!0;if(process.platform==="win32")return!1;if(Q)return!1;if(Y)return!1;if(K){let U=DQ6(q||"");switch(K){case"iTerm.app":if(U.major===3)return U.minor>=1;return U.major>3;case"WezTerm":return U.major>=20200620;case"vscode":return U.major>1||U.major===1&&U.minor>=72;case"ghostty":return!0}}if(G){if(G==="0.50.0")return!1;let U=DQ6(G);return U.major>0||U.minor>=50}switch(z){case"alacritty":return!0}return!1}MQ6.exports={supportsHyperlink:Kx1,stdout:Kx1(process.stdout),stderr:Kx1(process.stderr)}});function RV(J,Q,{target:Z="stdout",...X}={}){if(!b41.default[Z]){if(X.fallback===!1)return J;return typeof X.fallback==="function"?X.fallback(J,Q):`${J} (${Q})`}return _41.link(J,Q)}var b41;var NQ6=p(()=>{UQ6();b41=u6(VQ6(),1);RV.isSupported=b41.default.stdout;RV.stderr=(J,Q,Z={})=>RV(J,Q,{target:"stderr",...Z});RV.stderr.isSupported=b41.default.stderr});class qx1{enabled;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J){this.enabled=J;this.startTimer()}startTimer(){this.timer=setInterval(()=>{this.flushEvents()},this.bufferTimeMs)}async flushEvents(){if(this.commandCounts.size===0||!await this.enabled())return;let J=Array.from(this.commandCounts.entries()).map(([Q,Z])=>({feature:"cli.command",action:Q,source:{client:"cli",clientVersion:"0.0.1759150769-gc5f674"},parameters:{metadata:{count:Z}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Q=JSON.stringify(J);await M10(Q)}catch(Q){a.error("Failed to export command telemetry events",Q)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Q=this.commandCounts.get(J)||0;this.commandCounts.set(J,Q+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}var LQ6=p(()=>{B0();PB()});class zY{message;name;constructor(J){this.message=J;this.name="InformationMessage"}}function OQ6(J){if(J instanceof x41)return{title:"Cannot compact thread",description:"Thread has no messages to compact.",type:"error"};if(J instanceof zY)return{title:"Info",description:J.message,type:"info"};return a.warn("Unknown error type encountered",{name:J.name,message:J.message,stack:J.stack}),{title:"Error",description:J.message||"An unexpected error occurred.",type:"error"}}var x41;var Gx1=p(()=>{B0();x41=class x41 extends Error{constructor(J="Thread has no messages to compact"){super(J);this.name="NoMessagesToCompactError"}}});import{execSync as AQ6}from"node:child_process";import{rmdir as U49}from"node:fs/promises";import{tmpdir as F49}from"node:os";import jQ6 from"node:path";import{mkdtemp as W49,readFile as H49,unlink as B49,writeFile as _U2}from"fs/promises";class zx1{commands;customRegistry;latestCustom=[];telemetrySubmitter;constructor(J=BC()){this.customRegistry=J,this._initBaseCommands(!1),this.customRegistry.commands.subscribe((Q)=>this.latestCustom=Q),this.telemetrySubmitter=new qx1(async()=>{try{return(await A9()).settings["experimental.cli.commandTelemetry.enabled"]===!0}catch{return!1}}),Q2.pipe(g0((Q)=>Q.settings["internal.modes"]),d8()).subscribe((Q)=>{this._initBaseCommands(Q??!1)})}_initBaseCommands(J){if(this.commands={...D49},J)Object.assign(this.commands,M49)}async execute(J,Q,Z=[],X){this.telemetrySubmitter.submit(J).catch((G)=>{a.debug("Failed to submit command telemetry",G)});let Y=this.commands[J];if(Y)return Y.execute(Q,Z);let K=this.latestCustom.find((G)=>G.name===J),q=await tb1(J,Z,this.customRegistry,{signal:X});if(q.success)if(K?.kind==="markdown"){Q.editorDispatch({type:"set-input",input:q.output});return}else{Q.worker.handle({type:"user:message",message:{content:[{type:"text",text:q.output}]}});return}return Error(q.error??`Command '${J}' failed`)}query(J,Q,Z){let X=J.toLowerCase(),Y=Object.values(this.commands).filter((q)=>q.name.toLowerCase().includes(X)).filter((q)=>{if(!Q||!q.isVisible)return!0;return q.isVisible(Q,Z)}),K=this.latestCustom.filter((q)=>q.available&&q.name.toLowerCase().includes(X)).map((q)=>({name:q.name,description:"Custom command",requiresArgs:q.kind==="executable",execute:(G,z)=>this.execute(q.name,G,z??[])}));return[...Y,...K]}async cleanup(){await this.telemetrySubmitter.dispose()}get(J){let Q=this.commands[J];if(Q)return Q;let Z=this.latestCustom.find((X)=>X.name===J);return{name:J,description:"Custom command",requiresArgs:Z?.kind==="executable",execute:(X,Y)=>this.execute(J,X,Y??[])}}}var D49,M49;var RQ6=p(()=>{XQ6();B0();V4();DC();dw();p4();lU();nb1();PB();qD();K8();i0();NQ6();$41();ab1();LQ6();Gx1();D49={"generate-agent-file":{name:"generate-agent-file",description:`Generate an ${h5} file in the current workspace`,execute:async(J,Q)=>{J.worker.handle({type:"user:message",message:{content:[{type:"text",text:xY0}]}});return}},compact:{name:"compact",description:"Compact the thread. Optional: /compact [message] to queue a message after compaction",execute:async(J,Q)=>{if(J.thread.messages.length===0)return new x41;if(Q&&Q.length>0){let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}try{await J.worker.summarizeThread()}catch(Z){return Z instanceof Error?Z:Error("Failed to compact thread")}}},editor:{name:"editor",description:"Open $EDITOR to write a prompt",launchesWindow:!0,execute:async(J,Q)=>{try{let Z=process.env.EDITOR||process.env.VISUAL||"nano",X=await W49(jQ6.join(F49(),"amp-edit-")),Y=jQ6.join(X,"message.amp.md");AQ6(`${Z} "${Y}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");try{let q=(await H49(Y,"utf-8")).trim();if(q)J.editorDispatch({type:"set-input",input:q})}catch(K){if(K?.code==="ENOENT")return;return a.error("Failed to read temporary file",K),Error("Failed to read editor content")}try{await B49(Y),await U49(X)}catch(K){a.warn("Failed to clean up temporary file",K)}return}catch(Z){return a.error("Failed to open editor",Z),Error("Failed to open editor")}}},help:{name:"help",description:"Show help and hotkeys",execute:async(J,Q)=>{J.openHelp();return}},permissions:{name:"permissions",description:"Edit permission rules in $EDITOR, or `/permissions off|on` to toggle for this session",launchesWindow:!0,execute:async(J,Q)=>{if(Q&&Q.length>0){let Y=Q[0]?.trim().toLowerCase();switch(Y){case"on":try{return uU("dangerouslyAllowAll",!1),new zY("Amp is now following permissions rules for this session")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to enable permissions for this session")}case"off":try{return uU("dangerouslyAllowAll",!0),new zY("Permissions disabled for this session - you will NOT be asked for confirmation before Amp runs a command.")}catch(K){return a.error("Failed to set dangerously allow all setting",K),Error("Failed to disable permissions for this session")}case"edit":break;default:return Error(`Invalid option: ${Y}. Use: on, off, or edit (or no argument for edit)`)}}let Z=await TT();if(Z===null)return Error("No editor found, please set $EDITOR to edit permissions");let X="";try{let Y={stdin:process.stdin,stdout:process.stdout,stderr:{write:(K)=>{return X=K.toString(),!0}},exit:(K)=>{if(K!==0)throw a.error("editPermissions exited with status",K),Error(X)},settingsFile:J.settingsFilePath,resolveEditor:TT};await S41(Y);return}catch(Y){a.error("failed to open permissions editor:",Y);let K=Y instanceof Error?`: ${Y.message}`:"";return Error(`Failed to open ${Z}${K}`)}finally{process.stdout.write("\x1B[?25l")}}},new:{name:"new",description:"Start a new thread",execute:async(J,Q)=>{try{await J.startNewThread();return}catch(Z){return a.error("Failed to start new thread",Z),Error("Failed to start new thread")}},isVisible:(J)=>J.messages.length!==0},continue:{name:"continue",description:"Continue an existing thread",requiresArgs:!1,requiresPicker:!0,execute:async(J,Q)=>{try{if(Q&&Q.length>0){let Z=Q[0]?.trim();if(!Z)return Error("Invalid thread ID provided");return await J.switchToThread(Z),new zY(`Switched to existing thread: ${Z}`)}await J.pickAndContinueThread();return}catch(Z){return a.error("Failed to continue thread",Z),Error("Failed to continue thread")}}},queue:{name:"queue",description:"Queue a message to send when inference completes. If no inference running, sends immediately.",requiresArgs:!0,execute:async(J,Q)=>{if(!Q||Q.length===0)return Error("Queue command requires a message argument. Usage: /queue <message>");let X=[{type:"text",text:Q.join(" ").trim()}],Y=J.takeImageAttachments?.()??[];if(Y.length>0)X.push(...Y);J.worker.handle({type:"user:message-queue:enqueue",message:{content:X}})}},dequeue:{name:"dequeue",description:"Dequeue all messages and restore them to the prompt editor",execute:async(J,Q)=>{let Z=J.thread.queuedMessages??[];if(Z.length===0)return;let Y=Z.map((K)=>{return K.queuedMessage.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").trim()}).filter(Boolean).join(`
|
5444
5444
|
`).trim();await J.worker.handle({type:"user:message-queue:discard"}),J.editorDispatch({type:"set-input",input:Y})},isVisible:(J)=>(J.queuedMessages?.length??0)>0},share:{name:"share",description:"Set thread visibility - `/share private|workspace|group|public`",execute:async(J,Q)=>{let{thread:Z,threadSyncService:X,ampURL:Y}=J;if(!Q||Q.length===0)return Error("Please specify a visibility option: private, workspace, group, or public");let K=av(new URL(Y),Z.id).toString(),G=`Thread URL: ${RV(K,K,{fallback:()=>K})}`,z=Q[0]?.trim().toLowerCase(),U;switch(z){case"private":U={visibility:"private",sharedGroupIDs:[]};break;case"workspace":U={visibility:"thread_workspace_shared"};break;case"group":U={visibility:"private",sharedGroupIDs:[],shareWithAllCreatorGroups:!0};break;case"public":U={visibility:"public"};break;default:return Error(`Invalid visibility option: ${z}. Use: private, workspace, group, or public`)}try{return await X.updateThreadMeta(Z.id,U),new zY(`${G}
|
5445
5445
|
|
5446
5446
|
This thread's visibility has been updated to: ${z}`)}catch(F){let W=F instanceof Error?F.message:String(F);if(W.includes("no-workspace"))return Error("You are not a member of any workspace.");if(W.includes("groups-disabled"))return Error("The groups feature is not enabled for this workspace.");if(W.includes("no-groups"))return Error("You are not a member of any groups.");return a.error("Unexpected failure to update thread visibility",F),Error(`Failed to update thread visibility for ${Z.id}`)}}},browser:{name:"browser",description:"Open the current thread in your browser",requiresArgs:!1,execute:async(J,Q)=>{let{thread:Z,ampURL:X}=J,Y=av(new URL(X),Z.id).toString();try{return await PT(Y),new zY("Thread opened in browser")}catch(K){a.error("Failed to open browser",{error:K});let q=RV(Y,Y,{fallback:()=>Y});return new zY(`Could not open browser automatically. Thread URL: ${q}`)}},isVisible:(J)=>J.messages.length!==0},settings:{name:"settings",description:"Open CLI settings file in $EDITOR",launchesWindow:!0,execute:async(J)=>{let Q=await TT();if(Q===null)return Error("No editor found, please set $EDITOR to edit settings");try{AQ6(`${Q} "${J.settingsFilePath}"`,{stdio:"inherit"}),process.stdout.write("\x1B[?25l");return}catch(Z){return a.error("Failed to open settings in editor",Z),Error(`Failed to open ${Q}`)}}},"agent-files":{name:"agent-files",description:"List AGENTS.md guidance files in use for the current thread",execute:async(J)=>{try{let Q=await J.getGuidanceFiles();if(Q.length===0)return new zY("No guidance files are currently in use for this thread.");let Z=Q.length,X=`Agent ${NX(Z,"File")} (${Z}):`,Y=Q.map((K)=>` • ${QJ(MX(K.uri))} (${K.type})`).join(`
|
@@ -5619,7 +5619,7 @@ https://www.jetbrains.com/help/idea/managing-plugins.html#install_plugin_from_di
|
|
5619
5619
|
`),J.stdout.write(`Continue this thread with: amp threads continue ${q}
|
5620
5620
|
`)}}function JY9(J){let Q=0;for(let Y=0;Y<J.length;Y++){let K=J.charCodeAt(Y);Q=(Q<<5)-Q+K,Q=Q&Q}let Z=[9,10,11,12,13,14,15,208,209,210,211,212,213,214,215],X=Math.abs(Q)%Z.length;return l1.index(Z[X])}var UF6,FF6;var HF6=p(()=>{B0();V4();DC();dw();p4();TN();Z4();$3();K8();i0();tJ6();RQ6();p7();J71();RA();cZ6();em();vU();hx1();t5();mT();TA();nZ6();m9();Q71();D2();UX6();UX();C9();Wy1();j7();om();V9();cz6();iz6();MQ();hX6();tz6();ez6();KU6();UU6();WU6();cT();HU6();ky1();BU6();NU6();cU6();lU6();fz6();nU6();Ah1();sU6();tU6();$71();dz6();YF6();zF6();UF6=class UF6 extends R6{dependencies;constructor(J){super();this.dependencies=J}createState(){return new FF6}};FF6=class FF6 extends j6{themeColors=null;themeApp=null;selectionListener=null;ideStatus=null;isConfirmingExit=!1;isConfirmingClearInput=!1;copyMessageTimer=null;isShowingHelp=!1;isShowingDebugOverlay=!1;isShowingConsoleOverlay=!1;isShowingConfirmationOverlay=!1;isShowingFileChangesOverlay=!1;confirmationOverlayContent="";exitConfirmTimeout=null;clearInputConfirmTimeout=null;historyIndex=-1;historyDraft=null;bashInvocations=[];dismissedEphemeralErrorKey=null;currentTitle=void 0;currentShellModeStatus=void 0;imageAttachments=[];displayMessage=null;executingCommand=null;isShowingJetBrainsInstaller=!1;isShowingIdePicker=!1;currentProgressBarState="off";progressReportTimer=null;showingSelectionCopiedHint=!1;isShowingThreadPicker=!1;submitDisabledHint=null;submitDisabledHintTimer=null;isShowingTrainingModeDialog=!1;pendingTrainingMode=null;currentAgentMode=void 0;agentModeSubscription=null;updateState=null;updateServiceSubscription=null;isFreeTierEnabled=!1;isProcessing(){let{threadState:J}=this.widget.dependencies;if(!J.mainThread)return!1;return Boolean(J.viewState.state==="active"&&(J.viewState.interactionState==="tool-running"||J.viewState.inferenceState==="running"))}isSummarizing(J){return J.state==="active"&&J.summaryState!=="idle"}parseShellModeInput(J){if(J.startsWith("$$")){let Q=J.slice(2).trim();return Q?{cmd:Q,hidden:!0}:null}if(J.startsWith("$")){let Q=J.slice(1).trim();return Q?{cmd:Q,hidden:!1}:null}return null}isSlashCommand(J){if(!J.startsWith("/"))return!1;if((J.split(" ")[0]?.slice(1)||"").includes("/"))return!1;return!0}showSubmitDisabledHint(J){if(this.submitDisabledHintTimer)clearTimeout(this.submitDisabledHintTimer);this.setState(()=>{this.submitDisabledHint=J}),this.submitDisabledHintTimer=setTimeout(()=>{this.setState(()=>{this.submitDisabledHint=null}),this.submitDisabledHintTimer=null},3000)}getUIHint(){let J=this.themeColors?.colorScheme;if(!J)return null;let Q=this.themeApp;if(!Q)return null;if(this.submitDisabledHint)return new w1(this.submitDisabledHint,new v1({color:J.foreground,dim:!0}));if(this.isConfirmingExit)return new w1("",void 0,[new w1("Ctrl+C",new v1({color:Q.keybind})),new w1(" again to exit",new v1({color:J.foreground,dim:!0}))]);if(this.isConfirmingClearInput)return new w1("",void 0,[new w1("Esc",new v1({color:Q.keybind})),new w1(" again to clear input",new v1({color:J.foreground,dim:!0}))]);if(this.isShowingHelp)return new w1("",void 0,[new w1("Escape",new v1({color:Q.keybind})),new w1(" to close help",new v1({color:J.foreground,dim:!0}))]);if(this.isProcessing()||this.bashInvocations.length>0)return new w1("",void 0,[new w1("Esc",new v1({color:Q.keybind})),new w1(" to cancel",new v1({color:J.foreground,dim:!0}))]);if(this.showingSelectionCopiedHint)return new w1("Selection copied to clipboard",new v1({color:J.foreground,dim:!0}));return null}isTranscriptEmpty(){let{threadState:J}=this.widget.dependencies;return J.items.length===0}textController=new H71;messageScrollControllers=new Map;getMessageScrollController(J){if(!this.messageScrollControllers.has(J))this.messageScrollControllers.set(J,new CV);return this.messageScrollControllers.get(J)}scrollMessageViewToBottom(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.id;if(!Q)return;this.getMessageScrollController(Q).scrollToBottom()}findElementByKey(J){return this.searchElementTreeByKey(this.context.element,J)}searchElementTreeByKey(J,Q){if(!J)return null;if(J?.widget?.key?.value===Q)return J;if(J?.child){let X=this.searchElementTreeByKey(J.child,Q);if(X)return X}if(J?.children)for(let X of J.children){let Y=this.searchElementTreeByKey(X,Q);if(Y)return Y}return null}clearActiveSelection(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller?.hasSelection)return Q.controller.clearSelection(),this.setState(()=>{}),!0}return!1}setupSelectionListener(){let J=this.findElementByKey("message-view-selection-area");if(J?.state){let Q=J.state;if(Q?.controller&&!this.selectionListener)this.selectionListener=()=>{this.setState(()=>{})},Q.controller.addListener(this.selectionListener),Q.controller.onSelectionCopied=()=>{if(this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}}updateTerminalTitle(){let{threadState:J}=this.widget.dependencies,Q=J.mainThread?.title;if(Q!==this.currentTitle){this.currentTitle=Q;let Z=process.cwd().replace(process.env.HOME||"","~"),X=Q?`amp - ${Q} - ${Z}`:"";process.stdout.write(Nx1(X))}}_handleTextCopy(J){if(J&&J.length>0){if(this.setState(()=>{this.showingSelectionCopiedHint=!0}),this.copyMessageTimer)clearTimeout(this.copyMessageTimer);this.copyMessageTimer=setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1}),this.copyMessageTimer=null},2000)}}textFieldKey=new $J("text-field");ideStatusSubscription=null;ideMessageSubscription=null;ideAppendToPromptSubscription=null;commands=null;completionBuilder=null;textChangeListener=()=>{let J=this.textController.text,Q=J.startsWith("$$")?"hidden":J.startsWith("$")?"normal":void 0;if(Q!==this.currentShellModeStatus)this.currentShellModeStatus=Q,this.setState(()=>{})};getCommands(){if(!this.commands)this.commands=new zx1(this.widget.dependencies.commandRegistry);return this.commands}getCompletionBuilder(){if(!this.completionBuilder)this.completionBuilder=new Ch1(this.getCommands(),this.widget.dependencies.fuzzyServer,new v51);return this.completionBuilder}navigateHistoryPrevious=()=>{let J=this.widget.dependencies.history.previous();if(J!==null){if(this.historyIndex===-1)this.historyDraft=this.textController.text;this.historyIndex++,this.textController.text=J,this.textController.moveCursorToStart()}};navigateHistoryNext=()=>{let J=this.widget.dependencies.history.next();if(J!==null)this.historyIndex--,this.textController.text=J,this.textController.moveCursorToEnd();else if(this.historyIndex>-1)this.historyIndex=-1,this.textController.text=this.historyDraft||"",this.textController.moveCursorToEnd(),this.historyDraft=null};resetHistory=()=>{this.widget.dependencies.history.reset(),this.historyIndex=-1,this.historyDraft=null};openJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!0})};dismissJetBrainsInstaller=()=>{this.setState(()=>{this.isShowingJetBrainsInstaller=!1})};openIdePicker=()=>{this.setState(()=>{this.isShowingIdePicker=!0})};dismissIdePicker=()=>{this.widget.dependencies.ideClient.sendStatus({enabled:!1}),this.setState(()=>{this.isShowingIdePicker=!1})};handleIdeSelection=async(J)=>{try{await this.connectToSelectedIde(J)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})}this.widget.dependencies.lockfileManager.selectConfig(J),this.setState(()=>{this.isShowingIdePicker=!1})};async connectToSelectedIde(J){await this.widget.dependencies.ideClient.start(J)}removeBashInvocation=(J)=>{this.setState(()=>{this.bashInvocations=this.bashInvocations.filter((Q)=>Q.id!==J)})};invokeBashCommand=(J,{hidden:Q})=>{let Z=Date.now(),X=`bash-${Z}-${Math.random().toString(36).substring(7)}`,Y={cmd:J},K=new AbortController;this.widget.dependencies.worker.invokeBashTool(Y,K.signal,Q).subscribe({next:(q)=>{this.setState(()=>{if(this.bashInvocations.find((z)=>z.id===X))this.bashInvocations=this.bashInvocations.map((z)=>z.id===X?{...z,toolRun:q}:z);else{let z={id:X,args:Y,toolRun:q,startTime:Z,abortController:K,hidden:Q};this.bashInvocations=[...this.bashInvocations,z]}})},error:()=>this.removeBashInvocation(X),complete:()=>this.removeBashInvocation(X)})};cancelBashInvocations=()=>{let J=this.bashInvocations.find((Q)=>Q.toolRun.status==="in-progress");if(J)J.abortController.abort()};handleHistoryNavigation=(J)=>{if(J.key==="p"&&J.ctrlKey)return this.navigateHistoryPrevious(),"handled";if(J.key==="n"&&J.ctrlKey)return this.navigateHistoryNext(),"handled";return"ignored"};onTextSubmitted=async(J)=>{let{threadState:Q}=this.widget.dependencies;if(this.isSummarizing(Q.viewState)){this.showSubmitDisabledHint("Unable to submit while compacting.");return}if(!J.trim())return;let Z=this.parseShellModeInput(J);if(Z){if(Z.cmd&&!this.isProcessing())this.invokeBashCommand(Z.cmd,{hidden:Z.hidden}),this.widget.dependencies.history.add(J),this.textController.clear(),this.resetHistory();else this.showSubmitDisabledHint("Unable to use shell mode while agent is active");return}let X=aJ6(J);if(this.isSlashCommand(X)&&Q.mainThread){let Y=X.slice(1).split(" "),K=Y[0],q=Y.slice(1).filter((G)=>G.trim()!=="");if(K){let G=Q.viewState,z=this.getCommands().query(K,Q.mainThread,G).filter((U)=>U.name===K).pop();if(z){if((z.requiresArgs||z.requiresPicker)&&q.length===0){this.textController.clear(),this.textController.insertText(`/${K} `);return}this.textController.clear(),this.resetHistory(),await this.executeCommand(z,q)}return}}this.textController.clear(),this.resetHistory(),await this.sendUserMessage(X)};onOptionSelected=(J)=>{switch(J.type){case"command":{let Q=`/${J.name} `;this.onTextSubmitted(Q);break}case"file":{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Q.slice(0,Z).lastIndexOf("@");if(Y!==-1){let K=Q.slice(0,Y),q=Q.slice(Z),G=K+`@${J.path} `+q;this.textController.clear(),this.textController.insertText(G),this.textController.cursorPosition=Y+1+J.path.length+1}break}case"thread":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]==="/continue"){let X=`/continue ${J.threadId} `;this.onTextSubmitted(X)}break}case"argument":{let Z=this.textController.text.split(" ");if(Z.length>=1&&Z[0]?.startsWith("/")){let Y=`${Z[0]} ${J.value} `;this.onTextSubmitted(Y)}break}}};executeCommand=async(J,Q)=>{let{threadState:Z}=this.widget.dependencies;if(!Z.mainThread||!J)return;let X=new AbortController,Y=Date.now(),q={id:`command-${Y}-${Math.random().toString(36).substring(7)}`,name:J.name,startTime:Y,abortController:X};this.setState(()=>{this.executingCommand=q});try{if(J.name==="new"){let z=await this.widget.dependencies.startNewThread();E71(z);return}if(J.launchesWindow)TU.instance.tuiInstance.suspend();let G=await this.getCommands().execute(J.name,{worker:this.widget.dependencies.worker,thread:Z.mainThread,ampURL:this.widget.dependencies.ampURL,threadSyncService:this.widget.dependencies.threadSyncService,takeImageAttachments:()=>{let z=this.imageAttachments;return this.setState(()=>{this.imageAttachments=[]}),z},editorDispatch:(z)=>{if(z.type==="set-input")this.textController.clear(),this.textController.insertText(z.input);else if(z.type==="clear")this.textController.clear()},exitApp:()=>{process.exit(0)},openHelp:()=>{this.setState(()=>{this.isShowingHelp=!0})},showCommandOverlay:(z)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=z})},settingsFilePath:this.widget.dependencies.settingsStorage.getSettingsFilePath(),settingsStorage:this.widget.dependencies.settingsStorage,startNewThread:async()=>{await this.widget.dependencies.startNewThread()},pickAndContinueThread:this.widget.dependencies.pickAndContinueThread,switchToThread:async(z)=>{await this.switchToExistingThread(z)},getGuidanceFiles:async()=>{if(!Z.mainThread)return[];return(await Ua({filesystem:this.widget.dependencies.worker.fs.fileSystemReader(),configService:this.widget.dependencies.configService,threadService:this.widget.dependencies.threadService},Z.mainThread,X.signal)).map((U)=>({uri:U.uri,type:U.type}))}},Q,X.signal);if(J.launchesWindow)TU.instance.tuiInstance.resume();if(G)this.setState(()=>{this.displayMessage=G})}catch(G){a.error("Error executing command:",G)}finally{this.setState(()=>{this.executingCommand=null})}};buildOptions=async(J)=>{let Q=this.textController.text,Z=this.textController.cursorPosition,Y=Yg1().detect(Q,Z);if(Y){let{threadState:K}=this.widget.dependencies;return await this.getCompletionBuilder().buildOptions(Y,K.mainThread,K.viewState)}return[]};initState(){if(PG.getInstance().interceptConsole(),this.widget.dependencies.startWithPicker)this.isShowingThreadPicker=!0;this.checkFreeTierStatus(),E71(this.widget.dependencies.worker),this.ideStatusSubscription=this.widget.dependencies.ideClient.status.subscribe((Q)=>{this.setState(()=>{this.ideStatus=Q})}),this.ideMessageSubscription=this.widget.dependencies.ideClient.messages.subscribe(async(Q)=>{let Z=lT();if(!Z){a.warn("No active thread worker found to handle IDE message");return}await new Promise((X)=>setTimeout(X,50)),await Z.handle({type:"user:message",message:{content:[{type:"text",text:Q}]}}),a.debug("Message sent from IDE to agent",{message:Q.slice(0,100)})}),this.ideAppendToPromptSubscription=this.widget.dependencies.ideClient.appendToPrompt.subscribe((Q)=>{this.textController.insertText(Q),a.debug("Appended text to CLI prompt from IDE",{text:Q.slice(0,100)})}),this.updateServiceSubscription=this.widget.dependencies.updateService.state.subscribe((Q)=>{this.setState(()=>{this.updateState=Q})}),this.agentModeSubscription=Q2.pipe(g0((Q)=>Q.settings["experimental.agentMode"]),d8()).subscribe((Q)=>{this.setState(()=>{this.currentAgentMode=Q})}),this.textController.addListener(this.textChangeListener),this.getCommands(),this.textController.onInsertText=(Q,Z)=>{if(Q.length<=3)return!0;let X=sJ6(Q);if(!X)return!0;if(this.imageAttachments.length>=$o1)return!1;let Y=oJ6(X);if(Y)return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Y]}),!1;return!0},this.updateTerminalTitle();let J=this.widget.dependencies.lockfileManager.getSelectedConfig();if(J)this.connectToSelectedIde(J).catch((Q)=>{let Z=Q instanceof Error?Q.message:String(Q);this.setState(()=>{this.displayMessage=Error(`Failed to connect to IDE: ${Z}`)})});else if(this.widget.dependencies.showIdePicker)this.openIdePicker();else if(this.widget.dependencies.showJetBrainsInstaller)this.openJetBrainsInstaller()}didUpdateWidget(J){super.didUpdateWidget(J),this.setupSelectionListener()}dispose(){if(this.ideStatusSubscription)this.ideStatusSubscription.unsubscribe();if(this.ideMessageSubscription)this.ideMessageSubscription.unsubscribe();if(this.ideAppendToPromptSubscription)this.ideAppendToPromptSubscription.unsubscribe();if(this.updateServiceSubscription)this.updateServiceSubscription.unsubscribe();if(this.agentModeSubscription)this.agentModeSubscription.unsubscribe();if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;if(this.textController.removeListener(this.textChangeListener),this.commands)this.commands.cleanup().catch((J)=>{a.debug("Failed to cleanup commands during disposal",J)});for(let J of this.messageScrollControllers.values())J.dispose();if(this.messageScrollControllers.clear(),process.stdout.write(Nx1("")),this.shouldUseProgressBar())process.stdout.write(Lx1());if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null}getCurrentConfirmation(){let{threadState:J}=this.widget.dependencies,Z=[...J.activeTools,...J.subagentActiveTools].filter((q)=>q.toolRun.status==="blocked-on-user");if(Z.length===0)return null;let X=Z[0],Y=X.toolRun.status==="blocked-on-user"?X.toolRun.toAllow??[]:[],K=X.toolRun.status==="blocked-on-user"?X.toolRun.reason:void 0;return{type:"tool-use",tools:[{useBlock:X.toolUse,toAllow:Y}],subthreadID:X.subthreadID,reason:K}}shouldUseProgressBar(){return m8.of(this.context).capabilities.xtversion?.toLowerCase().startsWith("ghostty")??!1}updateProgressBar(){if(!this.shouldUseProgressBar())return;let{threadState:J}=this.widget.dependencies,Q=this.getCurrentConfirmation(),Z="off";if(Q)Z="paused";else if(this.isProcessing())Z="indeterminate";if(Z!==this.currentProgressBarState)this.currentProgressBarState=Z,this.sendProgressReport(Z);this.scheduleProgressReportTimer()}sendProgressReport(J){switch(J){case"indeterminate":process.stdout.write(iQ6());break;case"paused":process.stdout.write(nQ6());break;case"off":process.stdout.write(Lx1());break}}scheduleProgressReportTimer(){if(this.progressReportTimer)clearTimeout(this.progressReportTimer),this.progressReportTimer=null;if(this.currentProgressBarState!=="off")this.progressReportTimer=setTimeout(()=>{if(this.currentProgressBarState!=="off")this.sendProgressReport(this.currentProgressBarState),this.scheduleProgressReportTimer()},1e4)}onConfirmationResponse=async(J)=>{let Q=this.getCurrentConfirmation();if(!Q||Q.type!=="tool-use"){a.error("No current tool confirmation found");return}let Z=Q.tools[0]?.useBlock;if(!Z){a.error("No tool use block found in confirmation");return}if(J==="allow-all-session")uU("dangerouslyAllowAll",!0);if(J==="allow-all-persistent")try{await this.widget.dependencies.settingsStorage.set("dangerouslyAllowAll",!0)}catch(Y){if(Y&&Y instanceof Error)this.setState(()=>{this.displayMessage=Y});else a.error("Failed to write dangerouslyAllowAll setting:",Y);return}if(J==="always-guarded"){let Y=Q.tools[0]?.toAllow??[],K=await this.widget.dependencies.settingsStorage.get("guardedFiles.allowlist")||[],q=[...Y,...K];await this.widget.dependencies.settingsStorage.set("guardedFiles.allowlist",q)}let X=J!==null&&["yes","allow-all-session","allow-all-persistent","always-guarded"].includes(J);try{let Y={type:"user:tool-input",toolUse:Z.id,value:{accepted:X}};if(Q.subthreadID)await(await dJ.getOrCreateForThread(this.widget.dependencies.workerDeps,Q.subthreadID)).handle(Y);else await this.widget.dependencies.worker.handle(Y)}catch(Y){a.error("Failed to send tool confirmation:",Y)}};showConfirmationOverlay=(J)=>{this.setState(()=>{this.isShowingConfirmationOverlay=!0,this.confirmationOverlayContent=J})};getErrorKey(J){return`${J.constructor.name}:${J.message}`}getCurrentEphemeralError(){let{threadState:J}=this.widget.dependencies,Q=J.viewState;if(Q.state!=="active"||!Q.ephemeralError)return null;let Z=this.getErrorKey(Q.ephemeralError);if(this.dismissedEphemeralErrorKey===Z)return null;return Q.ephemeralError}handleEphemeralErrorResponse=async(J)=>{let Q=this.getCurrentEphemeralError(),Z=this.widget.dependencies.worker;switch(J){case"retry":this.dismissedEphemeralErrorKey=null,await Z.retry();break;case"compact":this.dismissedEphemeralErrorKey=null,await Z.summarizeThread();break;case"dismiss":if(Q)this.dismissedEphemeralErrorKey=this.getErrorKey(Q);break}this.setState(()=>{})};handleDisplayMessageDismiss=()=>{this.setState(()=>{this.displayMessage=null})};cancelStreamingMessage=async()=>{await dJ.cancel(this.widget.dependencies.threadID)};switchToExistingThread=async(J)=>{try{let Q=await this.widget.dependencies.switchToThread(J);this.widget.dependencies.worker=Q,this.widget.dependencies.threadID=Q.thread.id,E71(Q),I71()?.switchWorker(this.widget.dependencies.worker),this.setState(()=>{})}catch(Q){throw a.error("Failed to switch to thread:",J,Q),Error(`Failed to switch to thread: ${J}`)}};sendUserMessage=async(J)=>{await this.proceedWithUserMessage(J)};proceedWithUserMessage=async(J)=>{this.cancelBashInvocations(),this.widget.dependencies.history.add(J);let Q=lT()||this.widget.dependencies.worker,Z=[{type:"text",text:J}];if(this.imageAttachments.length>0)Z.push(...this.imageAttachments);await Q.handle({type:"user:message",message:{content:Z}}),this.scrollMessageViewToBottom(),this.setState(()=>{this.imageAttachments=[]})};onTrainingModeDialogResponse=async(J)=>{if(this.setState(()=>{this.isShowingTrainingModeDialog=!1}),J&&this.pendingTrainingMode)try{let Q=await this.widget.dependencies.internalAPIClient.updateUserTrainingMode({enabled:!0});if(!Q.ok){let Z=Q.error.message||"Failed to enable training mode";await this.showErrorMessage(Z),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else await this.proceedWithUserMessage(this.pendingTrainingMode)}catch(Q){await this.showErrorMessage(`Failed to enable training mode:
|
5621
5621
|
|
5622
|
-
${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){a.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;TU.instance.stop()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=tX9();if(J===Q)return"~";if(J.startsWith(Q+fu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(fu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(fu.sep),"…",Q.slice(-2).join(fu.sep)].join(fu.sep)}build(J){let Q=m8.of(J),Z=I8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new _H({child:new Jg1({onSelect:async(b)=>{if(b)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(b);else process.exit(0)},pageSize:50,threadFetcher:new v51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,W=this.isTranscriptEmpty()?new D51({useGpt5:this.widget.dependencies.useGpt5,updateState:this.updateState??void 0}):new Eh1({key:U?new $J(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,controller:U?this.getMessageScrollController(U):new CV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),D=this.getCurrentEphemeralError(),M=this.buildBottomWidget(D,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Nc1(q.mainThread):void 0,L=new P71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),O=new Ph1({activeTools:[...q.activeTools,...q.subagentActiveTools],subagents:q.subagents}),A=new w71({bashInvocations:this.bashInvocations}),j=[];if(this.isFreeTierEnabled)j.push(new c6({decoration:new j2(Y.secondary),child:new P8({padding:W6.horizontal(1),child:new q0({text:new w1("Thank you for trying the ad-supported Amp Free experiment — AD",new v1({color:l1.black})),textAlign:"center"})})}));j.push(new $2({child:W}),O,A,new c6({constraints:new y6(0,Q.size.width,0,H),child:M}),new r0({height:1,child:new P8({padding:W6.horizontal(1),child:L})}));let R=new O6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),I=new E5(()=>{if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingDebugOverlay)return this.setState(()=>{this.isShowingDebugOverlay=!1}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return a.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((m)=>{a.error("Failed to cancel streaming message:",m)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),w=new E5(()=>{return this.onExitPressed(),"handled"}),E=new E5(()=>{return this.setState(()=>{this.isShowingDebugOverlay=!this.isShowingDebugOverlay}),"handled"}),$=new E5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),P=new E5(()=>{return yV.instance.toggleAll(),"handled"}),C=new E5(()=>{return TU.instance.tuiInstance.getScreen().markForRefresh(),EJ.instance.requestFrame(),"handled"}),_=new E5(()=>{let b=this.findElementByKey("message-view-selection-area");if(b?.state){let m=b.state,n=m.controller?.copySelection();if(n&&n.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{m.controller.endCopyHighlight(),m.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),g=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageUp(Q1,100)}return"handled"}),T=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageDown(Q1,100)}return"handled"}),v=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(0,100);return"handled"}),f=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),h=new Map([[m2.key("Escape"),new Ku],[m2.ctrl("c"),new uT],[m2.ctrl("l"),new Uu],[m2.alt("d"),new qu],[m2.alt("c"),new Gu],[m2.ctrl("r"),new zu],[m2.key("PageUp"),new Y71],[m2.key("PageDown"),new K71],[m2.key("Home"),new q71],[m2.key("End"),new G71]]);if(process.platform==="darwin")h.set(m2.meta("c"),new uT);let S=new Map([[Ku,I],[t41,w],[Uu,C],[qu,E],[Gu,$],[zu,P],[uT,_],[Y71,g],[K71,T],[q71,v],[G71,f]]),y=R;if(this.isShowingDebugOverlay)y=new WY({children:[y,new TH({top:2,right:2,child:new bh1})]});if(this.isShowingConsoleOverlay)y=new WY({children:[y,new _h1]});if(this.isShowingHelp)y=new WY({children:[y,new yh1]});if(this.isShowingFileChangesOverlay)y=new WY({children:[y,new vy1]});if(this.isShowingConfirmationOverlay)y=new WY({children:[y,new Sh1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"ide-picker-shortcuts",child:new hh1({lockfileManager:this.widget.dependencies.lockfileManager,onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"jetbrains-installer-shortcuts",child:new oh1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"main-app-shortcuts",child:y})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new xh1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new Qg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new kh1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new th1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=eX9(X),U=new D71({key:this.textFieldKey,controller:this.textController,triggers:[Yg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Th1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:TU.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,_)=>{let g=_?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=Th1(C);break}let y=oz6(C),b=new w1(h,new v1({color:T})),m=new w1(S,new v1({color:v})),n=[b,m];if(y){let u=new w1(" - ",new v1({color:f,dim:!0})),Q1=new w1(y,new v1({color:f,dim:!0}));n.push(u,Q1)}return new c6({decoration:new j2(g),child:new q0({text:new w1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),F=Y.mainThread?.queuedMessages??[],W=new J2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,D=this.imageAttachments.length>0?new c6({padding:W6.only({bottom:1,left:1}),child:new q0({text:new w1("",void 0,[new w1("Images: ",new v1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new w1(`[image ${C+1}]`,new v1({color:Z.success})),...C<this.imageAttachments.length-1?[new w1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(F)&&F.length>0,N=D?new O6({crossAxisAlignment:"start",children:[D,W]}):W,L=V?new eh1({queuedMessages:F}):void 0,O=M?new fx1(new $h1({todos:K}),{clipBehavior:"antiAlias"}):void 0,A=[],j=Y.viewState;if(!this.isSummarizing(j))A.push({text:new w1("",void 0,[new w1("Enter",new v1({color:G.keybind})),new w1(" to send",new v1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)A.push({text:new w1(H==="hidden"?"shell mode (incognito)":"shell mode",new v1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:D?1:0});let R=this.currentAgentMode;if(R&&!["default",sU[0]].includes(R)&&!H){let P=JY9(R);A.push({text:new w1("",void 0,[new w1("agent-mode: ",new v1({color:Z.foreground,dim:!0})),new w1(R,new v1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=S0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return A.push({text:new w1($,new v1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new wy1({leftChild:N,rightChild1:L,rightChild2:O,maxHeight:q,overlayTexts:A,borderColor:Z.border})}}});import{randomBytes as QY9}from"node:crypto";import{mkdir as ZY9,readFile as VF6,writeFile as XY9}from"node:fs/promises";import YY9 from"node:os";import Kg1 from"node:path";import{stderr as o2,stdout as u2}from"node:process";function KY9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function iA(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")uU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")uU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")uU("experimental.agentMode",Q.agentMode)}async function zg1(J){try{await ZY9(Kg1.dirname(qg1),{recursive:!0}),await XY9(qg1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function zY9(){try{return(await VF6(qg1,"utf-8")).trim()}catch(J){return null}}async function UY9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return GY9.parse(Q)}catch(Z){if(Z instanceof T0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function FY9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}function DY9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new E2(vK.unknownCommand(Z),1,q)}}function ey2(){return NF6}function _51(J){return{...J,getThreadEnvironment:Y41,vfs:H10({os:J.fileSystem}),fileChangeTrackerStorage:new sv(J.fileSystem),generateThreadTitle:Ha,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function nA(J,Q){Cc1("0.0.1759147319-g41306c");let Z=xQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:qb1,homeDir:Ug1,userConfigDir:LF6}),X=await A9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=ul(Tp()),K=le1({configService:Z,toolService:Y}),q=iL0(Y,R8,Dt).catch((L)=>{a.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{a.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)Sc1(!0);if(Q.ide&&fb1())vc1(!0);if(Y66(Y,X.settings),Q.jetbrains)Y.registerTool(fa);else if(Q.ide)Y.registerTool(hK0);let z;if(!J.executeMode)z=new D41(process.cwd(),{},!0);else z=new class extends D41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
|
5622
|
+
${Q}`),this.textController.clear(),this.textController.insertText(this.pendingTrainingMode)}else if(!J&&this.pendingTrainingMode)this.textController.clear(),this.textController.insertText(this.pendingTrainingMode);this.setState(()=>{this.pendingTrainingMode=null})};async showErrorMessage(J){this.setState(()=>{this.displayMessage=Error(J)})}async checkFreeTierStatus(){try{let J=await this.widget.dependencies.internalAPIClient.getUserFreeTierStatus({});if(J.ok)this.setState(()=>{this.isFreeTierEnabled=J.result.enabled})}catch(J){a.debug("Failed to check free tier status:",J)}}onExitPressed=()=>{if(this.isConfirmingExit){if(this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout),this.exitConfirmTimeout=null;TU.instance.stop()}else{if(this.setState(()=>{this.isConfirmingExit=!0}),this.exitConfirmTimeout)clearTimeout(this.exitConfirmTimeout);this.exitConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingExit=!1}),this.exitConfirmTimeout=null},1000)}};toHomeRelative(J){let Q=tX9();if(J===Q)return"~";if(J.startsWith(Q+fu.sep))return"~"+J.slice(Q.length);return J}shorten(J){let Q=J.split(fu.sep).filter(Boolean);if(Q.length<=5)return J;return[Q.slice(0,2).join(fu.sep),"…",Q.slice(-2).join(fu.sep)].join(fu.sep)}build(J){let Q=m8.of(J),Z=I8.of(J),X=Z.base;this.themeColors=X;let{colors:Y,app:K}=Z;this.themeApp=K;let{threadState:q}=this.widget.dependencies;if(this.isShowingThreadPicker)return new _H({child:new Jg1({onSelect:async(b)=>{if(b)this.isShowingThreadPicker=!1,this.setState(),await this.switchToExistingThread(b);else process.exit(0)},pageSize:50,threadFetcher:new v51})});this.updateTerminalTitle(),this.updateProgressBar();let G=this.getCurrentConfirmation(),z=q.todosList,U=q.mainThread?.id,W=this.isTranscriptEmpty()?new D51({useGpt5:this.widget.dependencies.useGpt5,updateState:this.updateState??void 0}):new Eh1({key:U?new $J(`message-view-${U}`):void 0,items:q.items,activeTools:q.activeTools,controller:U?this.getMessageScrollController(U):new CV,autofocus:!1,onCopy:this._handleTextCopy.bind(this)}),H=Math.max(Math.floor(Q.size.height*0.4),10),D=this.getCurrentEphemeralError(),M=this.buildBottomWidget(D,G,Y,Z,q,z,H),V=Q.size.width<40,N=q.mainThread?Nc1(q.mainThread):void 0,L=new P71({threadViewState:q.viewState,threadTokenUsage:N,threadID:U??null,onFileChangesClick:()=>{this.setState(()=>{this.isShowingFileChangesOverlay=!this.isShowingFileChangesOverlay})},ideStatus:this.ideStatus,isNarrow:V,uiHint:this.getUIHint()??void 0,waitingForConfirmation:!!G,showingEphemeralError:Boolean(q.viewState.state==="active"&&q.viewState.ephemeralError),runningBashInvocations:this.bashInvocations.length>0,executingCommand:this.executingCommand?.name??null}),O=new Ph1({activeTools:[...q.activeTools,...q.subagentActiveTools],subagents:q.subagents}),A=new w71({bashInvocations:this.bashInvocations}),j=[];if(this.isFreeTierEnabled)j.push(new c6({decoration:new j2(Y.secondary),child:new P8({padding:W6.horizontal(1),child:new q0({text:new w1("Thank you for trying the ad-supported Amp Free experiment — AD",new v1({color:l1.black})),textAlign:"center"})})}));j.push(new $2({child:W}),O,A,new c6({constraints:new y6(0,Q.size.width,0,H),child:M}),new r0({height:1,child:new P8({padding:W6.horizontal(1),child:L})}));let R=new O6({crossAxisAlignment:"stretch",mainAxisSize:"max",children:j}),I=new E5(()=>{if(this.getCurrentEphemeralError())return this.handleEphemeralErrorResponse("dismiss"),"handled";if(this.displayMessage)return this.handleDisplayMessageDismiss(),"handled";if(this.isShowingHelp)return this.setState(()=>{this.isShowingHelp=!1}),"handled";if(this.isShowingFileChangesOverlay)return this.setState(()=>{this.isShowingFileChangesOverlay=!1}),"handled";if(this.isShowingIdePicker)return this.dismissIdePicker(),"handled";if(this.isShowingJetBrainsInstaller)return this.dismissJetBrainsInstaller(),"handled";if(this.isShowingConfirmationOverlay)return this.setState(()=>{this.isShowingConfirmationOverlay=!1,this.confirmationOverlayContent=""}),"handled";if(this.isShowingDebugOverlay)return this.setState(()=>{this.isShowingDebugOverlay=!1}),"handled";if(this.isShowingConsoleOverlay)return this.setState(()=>{this.isShowingConsoleOverlay=!1}),"handled";if(this.clearActiveSelection())return"handled";if(this.isConfirmingClearInput){if(this.textController.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.bashInvocations.length>0)return this.cancelBashInvocations(),"handled";if(this.executingCommand)return a.info("Canceling executing command:",this.executingCommand.name),this.executingCommand.abortController.abort(),"handled";if(this.isProcessing())return this.cancelStreamingMessage().catch((m)=>{a.error("Failed to cancel streaming message:",m)}),"handled";if(this.textController.text.trim()!==""||this.imageAttachments.length>0){if(this.setState(()=>{this.isConfirmingClearInput=!0}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout);return this.clearInputConfirmTimeout=setTimeout(()=>{this.setState(()=>{this.isConfirmingClearInput=!1}),this.clearInputConfirmTimeout=null},1000),"handled"}return"ignored"}),w=new E5(()=>{return this.onExitPressed(),"handled"}),E=new E5(()=>{return this.setState(()=>{this.isShowingDebugOverlay=!this.isShowingDebugOverlay}),"handled"}),$=new E5(()=>{return this.setState(()=>{this.isShowingConsoleOverlay=!this.isShowingConsoleOverlay}),"handled"}),P=new E5(()=>{return yV.instance.toggleAll(),"handled"}),C=new E5(()=>{return TU.instance.tuiInstance.getScreen().markForRefresh(),EJ.instance.requestFrame(),"handled"}),_=new E5(()=>{let b=this.findElementByKey("message-view-selection-area");if(b?.state){let m=b.state,n=m.controller?.copySelection();if(n&&n.length>0)return this.setState(()=>{this.showingSelectionCopiedHint=!0}),setTimeout(()=>{this.setState(()=>{this.showingSelectionCopiedHint=!1})},2000),setTimeout(()=>{m.controller.endCopyHighlight(),m.controller.clear()},350),"handled"}return this.onExitPressed(),"handled"}),g=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageUp(Q1,100)}return"handled"}),T=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m){let n=this.getMessageScrollController(m),u=Math.max(Math.floor(Q.size.height*0.4),10),Q1=Q.size.height-u;n.animatePageDown(Q1,100)}return"handled"}),v=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(0,100);return"handled"}),f=new E5(()=>{let{threadState:b}=this.widget.dependencies,m=b.mainThread?.id;if(m)this.getMessageScrollController(m).animateTo(Number.MAX_SAFE_INTEGER,100);return"handled"}),h=new Map([[m2.key("Escape"),new Ku],[m2.ctrl("c"),new uT],[m2.ctrl("l"),new Uu],[m2.alt("d"),new qu],[m2.alt("c"),new Gu],[m2.ctrl("r"),new zu],[m2.key("PageUp"),new Y71],[m2.key("PageDown"),new K71],[m2.key("Home"),new q71],[m2.key("End"),new G71]]);if(process.platform==="darwin")h.set(m2.meta("c"),new uT);let S=new Map([[Ku,I],[t41,w],[Uu,C],[qu,E],[Gu,$],[zu,P],[uT,_],[Y71,g],[K71,T],[q71,v],[G71,f]]),y=R;if(this.isShowingDebugOverlay)y=new WY({children:[y,new TH({top:2,right:2,child:new bh1})]});if(this.isShowingConsoleOverlay)y=new WY({children:[y,new _h1]});if(this.isShowingHelp)y=new WY({children:[y,new yh1]});if(this.isShowingFileChangesOverlay)y=new WY({children:[y,new vy1]});if(this.isShowingConfirmationOverlay)y=new WY({children:[y,new Sh1({details:this.confirmationOverlayContent})]});if(this.isShowingIdePicker)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"ide-picker-shortcuts",child:new hh1({lockfileManager:this.widget.dependencies.lockfileManager,onCancel:this.dismissIdePicker,onSelect:this.handleIdeSelection})})})});if(this.isShowingJetBrainsInstaller)return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"jetbrains-installer-shortcuts",child:new oh1({configService:this.widget.dependencies.configService,ideClient:this.widget.dependencies.ideClient,onExit:()=>process.exit(0),onContinue:this.dismissJetBrainsInstaller})})})});return new _H({child:new bK({actions:S,child:new TV({shortcuts:h,debugLabel:"main-app-shortcuts",child:y})})})}buildBottomWidget(J,Q,Z,X,Y,K,q){if(J)return new xh1({error:J,ampURL:this.widget.dependencies.ampURL,onResponse:this.handleEphemeralErrorResponse});if(this.isShowingTrainingModeDialog)return new Qg1({onResponse:this.onTrainingModeDialogResponse});if(Q){if(this.displayMessage)this.handleDisplayMessageDismiss();return new kh1({confirmationRequest:Q,onResponse:this.onConfirmationResponse,onShowOverlay:this.showConfirmationOverlay})}if(this.displayMessage)return new th1({message:this.displayMessage,onDismiss:this.handleDisplayMessageDismiss});let G=X.app,z=eX9(X),U=new D71({key:this.textFieldKey,controller:this.textController,triggers:[Yg1()],optionsBuilder:this.buildOptions,onSelected:this.onOptionSelected,displayStringForOption:(P)=>Th1(P),overlayBorderColor:Z.border,textFieldProps:{placeholder:"Type your message... (use / for commands, @ for files)",wrap:!0,minLines:3,maxLines:null,expands:!0,autofocus:!0,onSubmitted:this.onTextSubmitted,submitKey:{character:"Enter"},prompts:z,style:{border:null},clipboard:TU.instance.tuiInstance.clipboard},optionViewBuilder:(P,C,_)=>{let g=_?Z.selection:void 0,T=C.type==="command"?Z.warning:Z.secondary,v=Z.foreground,f=Z.foreground,h,S;switch(C.type){case"command":h="/",S=C.name;break;case"file":h="@",S=C.path;break;case"thread":h="",S=C.title;break;default:h="",S=Th1(C);break}let y=oz6(C),b=new w1(h,new v1({color:T})),m=new w1(S,new v1({color:v})),n=[b,m];if(y){let u=new w1(" - ",new v1({color:f,dim:!0})),Q1=new w1(y,new v1({color:f,dim:!0}));n.push(u,Q1)}return new c6({decoration:new j2(g),child:new q0({text:new w1("",void 0,n),maxLines:1,overflow:"ellipsis"})})}}),F=Y.mainThread?.queuedMessages??[],W=new J2({onKey:this.handleHistoryNavigation,child:U}),H=this.currentShellModeStatus,D=this.imageAttachments.length>0?new c6({padding:W6.only({bottom:1,left:1}),child:new q0({text:new w1("",void 0,[new w1("Images: ",new v1({color:Z.foreground,dim:!0})),...this.imageAttachments.flatMap((P,C)=>[new w1(`[image ${C+1}]`,new v1({color:Z.success})),...C<this.imageAttachments.length-1?[new w1(" ")]:[]])])})}):null,M=Array.isArray(K)&&K.length>0,V=Array.isArray(F)&&F.length>0,N=D?new O6({crossAxisAlignment:"start",children:[D,W]}):W,L=V?new eh1({queuedMessages:F}):void 0,O=M?new fx1(new $h1({todos:K}),{clipBehavior:"antiAlias"}):void 0,A=[],j=Y.viewState;if(!this.isSummarizing(j))A.push({text:new w1("",void 0,[new w1("Enter",new v1({color:G.keybind})),new w1(" to send",new v1({color:Z.foreground,dim:!0}))]),position:"bottom-left"});if(H)A.push({text:new w1(H==="hidden"?"shell mode (incognito)":"shell mode",new v1({color:H==="hidden"?X.app.shellModeHidden:X.app.shellMode})),position:"top-left",offsetY:D?1:0});let R=this.currentAgentMode;if(R&&!["default",sU[0]].includes(R)&&!H){let P=JY9(R);A.push({text:new w1("",void 0,[new w1("agent-mode: ",new v1({color:Z.foreground,dim:!0})),new w1(R,new v1({color:P}))]),position:"top-left",offsetY:0})}let I=Y.mainThread?.metadata?.treeInfo?.uri,w;if(I)w=S0.isUri(I)?I.fsPath:I;else w=process.cwd();let E=this.toHomeRelative(w),$=this.shorten(E);return A.push({text:new w1($,new v1({color:Z.foreground,dim:!0})),position:"bottom-right"}),new wy1({leftChild:N,rightChild1:L,rightChild2:O,maxHeight:q,overlayTexts:A,borderColor:Z.border})}}});import{randomBytes as QY9}from"node:crypto";import{mkdir as ZY9,readFile as VF6,writeFile as XY9}from"node:fs/promises";import YY9 from"node:os";import Kg1 from"node:path";import{stderr as o2,stdout as u2}from"node:process";function KY9(J){process.emitWarning=function(Q,Z,X,Y){let K=typeof Q==="string"?Q:Q.message||String(Q),q=Z||"Warning",G=!1;J.warn(K,{name:q,code:X})}}function iA(J,Q){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")uU("dangerouslyAllowAll",Q.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("tryGpt5")==="cli")uU("gpt5",Q.tryGpt5);if(J.getOptionValueSourceWithGlobals("agentMode")==="cli")uU("experimental.agentMode",Q.agentMode)}async function zg1(J){try{await ZY9(Kg1.dirname(qg1),{recursive:!0}),await XY9(qg1,J,"utf-8")}catch(Q){a.debug("Failed to save last thread ID",Q)}}async function zY9(){try{return(await VF6(qg1,"utf-8")).trim()}catch(J){return null}}async function UY9(J){let Q;try{Q=JSON.parse(J)}catch(Z){throw Error(`Failed to parse --mcp-config as JSON: ${Z instanceof Error?Z.message:String(Z)}`)}try{return GY9.parse(Q)}catch(Z){if(Z instanceof T0.ZodError){let X=Z.issues.map((Y)=>`${Y.path.join(".")}: ${Y.message}`).join(", ");throw Error(`Invalid MCP server configuration: ${X}`)}throw Error(`Failed to validate MCP server configuration: ${String(Z)}`)}}function FY9(J,Q){return{...J,async get(Z){if(Z==="mcpServers"){let X=await J.get(Z)||{},Y={};if(typeof X==="object")for(let[K,q]of Object.entries(X))Y[K]={...q,_target:"global"};for(let[K,q]of Object.entries(Q))Y[K]={...q,_target:"workspace"};return Y}return J.get(Z)},async keys(){let Z=await J.keys();if(!Z.includes("mcpServers"))Z.push("mcpServers");return Z},[Symbol.dispose](){J[Symbol.dispose]()}}}function DY9(J,Q){let Z=Q.args[0],X=Q.commands.map((K)=>K.name());if(Z&&!Z.includes(" ")&&Z.length<30&&!/[./\\]/.test(Z)){let K=X.filter((G)=>Z.includes(G)||G.includes(Z)),q="Run amp --help for a list of available commands.";if(K.length>0)q=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new E2(vK.unknownCommand(Z),1,q)}}function ey2(){return NF6}function _51(J){return{...J,getThreadEnvironment:Y41,vfs:H10({os:J.fileSystem}),fileChangeTrackerStorage:new sv(J.fileSystem),generateThreadTitle:Ha,deleteThread:(Q)=>J.threadHistoryService.delete(Q)}}async function nA(J,Q){Cc1("0.0.1759150769-gc5f674");let Z=xQ1({storage:J.settings,secretStorage:J.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:J.ampURL,defaultCacheDirectory:qb1,homeDir:Ug1,userConfigDir:LF6}),X=await A9();a.debug("Global configuration initialized",{hasCacheDirectory:!!X.settings.cacheDirectory,settingsKeys:Object.keys(X.settings)});let Y=ul(Tp()),K=le1({configService:Z,toolService:Y}),q=iL0(Y,R8,Dt).catch((L)=>{a.warn("Toolbox registration failed, continuing anyway:",L)}),G=K.initialized.catch((L)=>{a.warn("MCP service initialization failed, continuing anyway:",L)});if(J.executeMode)await Promise.all([G,q]);if(Q.jetbrains)Sc1(!0);if(Q.ide&&fb1())vc1(!0);if(Y66(Y,X.settings),Q.jetbrains)Y.registerTool(fa);else if(Q.ide)Y.registerTool(hK0);let z;if(!J.executeMode)z=new D41(process.cwd(),{},!0);else z=new class extends D41{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};if(!await J.secrets.get("apiKey",J.ampURL)){if(u2.write(`No API key found. Starting login flow...
|
5623
5623
|
`),!await MY9(J))await MA(),process.exit(1)}let U=await $10({isDevelopment:!1}),F=new uU1(U),W=new gU1(U,{lazy:!0}),H=new SD1(F),D=Q.notifications!==void 0?Q.notifications:!J.executeMode,M=z66({playNotificationSound:async(L)=>{if(D){q66(L);let O=kx1(),A=_x1();if((!O||A)&&X.settings["notifications.system.enabled"]!==!1){if(L==="idle")process.stdout.write("\x1B]777;notify;Amp;Agent is ready\x1B\\");else if(L==="requires-user-input")process.stdout.write("\x1B]777;notify;Amp;Waiting for approval\x1B\\")}}},windowFocused:()=>Promise.resolve(!1),threadService:F});a.info("Starting Amp background services");let V=dY0({threadService:F,threadHistoryService:W,isExtensionDevelopment:!1}),N={configService:Z,toolService:Y,mcpService:K,threadService:F,threadHistoryService:W,threadSummaryService:H,threadSyncService:V,threadStorage:U,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:z,notificationService:M,fileSystem:Q.jetbrains||Q.ide?z10:R8};return{...N,async asyncDispose(){await N.mcpService.dispose(),await N.threadService.asyncDispose(),N.configService.unsubscribe(),N.toolService.dispose(),N.fuzzyServer.dispose(),N.threadSyncService.dispose(),N.settingsStorage[Symbol.dispose]()}}}async function MY9(J){if(!J.executeMode){if(!await ib1("Would you like to log in to Amp? [(y)es, (n)o]: "))return u2.write(`Login cancelled. Run the command again to retry.
|
5624
5624
|
`),!1}return await OF6(J)}async function OF6(J){let Q=QY9(32).toString("hex"),Z=await lb1(J.ampURL,Q);try{await PT(Z)}catch(Y){a.error("Failed to open browser",{error:Y})}let X=await lb1(J.ampURL,Q,!1);u2.write(`If your browser did not open automatically, visit:
|
5625
5625
|
|
@@ -5629,12 +5629,12 @@ ${Q8.blue.bold(X)}
|
|
5629
5629
|
Login successful! You can now use the Amp CLI.
|
5630
5630
|
`),!0}catch(Y){return a.error("Login failed",{error:Y}),o2.write(`
|
5631
5631
|
Login failed: ${Y instanceof Error?Y.message:String(Y)}
|
5632
|
-
`),!1}}function VY9(){let J=new tg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)HT(),process.exit(0);let H=W.originalError??W;q76(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.
|
5633
|
-
`),process.exit(0)}),J.addHelpText("after",C56()),J.configureHelp({formatHelp:S56}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await AY9(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await OY9(M,await vb1(D,M.settings))});let Q=async(W,H,D)=>{xQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Ug1,userConfigDir:LF6});let M={...H,executeMode:!1};await Gg1(M,{...W,startWithPicker:!0},D)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await PY9(D,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);if(H.pick)await Q(M,V,D);else await $Y9(M,V,W,D)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await EY9(M,V,W,D)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await IY9(M,V,W,D,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await wY9(M,V,W,D)}),iJ6(J,async(W,H)=>{let D=await yK(H);iA(W,H);let M=await nA(D,H);return{context:D,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:HT,asyncDispose:M.asyncDispose.bind(M)}}),WJ6(J),e56(J,async(W)=>{return(await yK(W)).settings});let X=new tg().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(W)=>{await gb1(W.force||!1,W.verbose||!1,"0.0.
|
5632
|
+
`),!1}}function VY9(){let J=new tg().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});J.exitOverride((W)=>{if(W.code==="commander.help"||W.code==="commander.version"||W.exitCode===0)HT(),process.exit(0);let H=W.originalError??W;q76(H)}),J.option("-V, --version","output the version number",()=>{u2.write(`0.0.1759150769-gc5f674 (released 2025-09-29T13:04:54.948Z)
|
5633
|
+
`),process.exit(0)}),J.addHelpText("after",C56()),J.configureHelp({formatHelp:S56}),J.command("logout").description("Log out by removing stored API key").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await AY9(M)}),J.command("login").description("Log in to Amp").addHelpText("after","If AMP_URL is set during login, it will be persisted to global settings for future CLI invocations, though AMP_URL will continue to take precedence.").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await OY9(M,await vb1(D,M.settings))});let Q=async(W,H,D)=>{xQ1({storage:H.settings,secretStorage:H.secrets,workspaceRoots:K0.of([S0.file(process.cwd())]),defaultAmpURL:H.ampURL,homeDir:Ug1,userConfigDir:LF6});let M={...H,executeMode:!1};await Gg1(M,{...W,startWithPicker:!0},D)},Z=J.command("threads").alias("t").alias("thread").summary("Manage threads").description("Thread management commands. When no subcommand is provided, defaults to listing threads.").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,M,H)});Z.command("new").alias("n").summary("Create a new thread").description("Create a new thread and print its ID. The thread will be empty. You can set the visibility using the --visibility option.").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await PY9(D,M,H)}),Z.command("continue [threadId]").alias("c").summary("Continue an existing thread").description("Continue an existing thread by resuming the conversation. If no thread ID is provided, the most recently used thread will be continued.").option("--pick","Pick a thread interactively from a list").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);if(H.pick)await Q(M,V,D);else await $Y9(M,V,W,D)}),Z.command("fork [threadId]").alias("f").summary("Fork an existing thread").description("Create a new thread by forking an existing one. This copies the conversation history up to the current point and creates a new thread where you can explore different directions. If no thread ID is provided, the most recently used thread will be forked.").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await EY9(M,V,W,D)}),Z.command("list").alias("l").alias("ls").summary("List all threads").description("List all your threads with their IDs, names, and last modified times.").action(async(W,H)=>{let D=H.optsWithGlobals(),M=await yK(D);await MF6(D,M,H)}),Z.command("share <threadId>").summary("Share a thread").description("Change thread visibility (private, public, workspace, group) or share with Amp support for debugging. Use --visibility to change who can access the thread, or --support to share with the Amp team for troubleshooting.").alias("s").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").option("--support","Share thread with Amp support for debugging").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await IY9(M,V,W,D,H.support)}),Z.command("compact <threadId>").alias("co").summary("Compact a thread").description("Compact a thread by creating a summary of the conversation history. This reduces the thread size while preserving the key information and context, making it more token efficient for future use.").action(async(W,H,D)=>{let M=D.optsWithGlobals(),V=await yK(M);await wY9(M,V,W,D)}),iJ6(J,async(W,H)=>{let D=await yK(H);iA(W,H);let M=await nA(D,H);return{context:D,mcpService:M.mcpService,toolService:M.toolService,cleanupTerminal:HT,asyncDispose:M.asyncDispose.bind(M)}}),WJ6(J),e56(J,async(W)=>{return(await yK(W)).settings});let X=new tg().name("install").description("Install required tools like ripgrep to $AMP_HOME/bin").option("--force","Force reinstallation even if already installed").option("--verbose","Show installation progress and results").action(async(W)=>{await gb1(W.force||!1,W.verbose||!1,"0.0.1759150769-gc5f674"),process.exit()});J.addCommand(X,{hidden:!0});function Y(W,H,D){let V=typeof W.description==="string"?W.description:D===void 0?W.description(!0):W.description(D),N=new YA(H,V),L=BY9(W);if(L)N.default(L);if(N.hidden=WY9(W)||DF6(W),"choices"in W)N.choices([...W.choices]);return N}for(let W of BF6)switch(W.type){case"flag":{J.addOption(Y(W,`--${W.long}`)),J.addOption(Y(W,`--no-${W.long}`,!1));break}case"switch":{J.addOption(Y(W,`--${W.long}`,!0));break}default:{J.addOption(Y(W,`--${W.long} <value>`));break}}let K=new YA("-x, --execute [message]","Use execute mode, optionally with user message. In execute mode, agent will execute provided prompt (either as argument, or via stdin). Only last assistant message is printed. Enabled automatically when redirecting stdout.").default(!1);if(J.addOption(K),process.env.AMP_CLI_REMOTE){let W=new YA("-r, --remote","When used with -x/--execute, execute in an async agent on the Amp server.").default(!1);J.addOption(W)}let q=new YA("--stream-json","When used with --execute, output in Claude Code compatible stream JSON format instead of plain text.").default(!1).hideHelp(!0);J.addOption(q);let G=new YA("--stream-json-input","Read JSON Lines user messages from stdin. Requires both --execute and --stream-json.").default(!1).hideHelp(!0);J.addOption(G);let z=new YA("--stats","When used with --execute, output JSON with both result and token usage data (for /evals).").default(!1).hideHelp(!0);J.addOption(z),J.action(async(W,H)=>{let D=W,M=await yK(D);if(Object.keys(D).forEach((V)=>{let N=BF6.find((L)=>L.name===V);if(N&&DF6(N)&&!HY9(N))o2.write(Q8.yellow(`Warning: '--${V}' flag is deprecated
|
5634
5634
|
`))}),H.args.length>0)DY9(M,H);await Gg1(M,D,H)});let U=new tg("doctor").summary("Generate support bundle").description("Generate a support bundle for troubleshooting issues. This collects logs, configuration, and system information into a file that can be shared with Amp support for debugging.").option("--output-dir <path>","Directory to save the support bundle",process.cwd()).option("--include-full-logs","Include full log history",!1).allowUnknownOption(!1).action(async(W)=>{await RY9(W.outputDir,W.includeFullLogs)});J.addCommand(U);let F=new tg("update").summary("Update Amp CLI").description("Update Amp CLI to the latest version. You can specify a particular version to install, or leave blank to get the latest stable release.").option("--version <version>","Update to a specific version").allowUnknownOption(!1).action(async(W)=>{await jY9(W.version)});return J.addCommand(F),J}async function k51(J,Q){let{thread:Z,visibility:X}=Q,Y=Z?.id??aK(),K=_51(J);if(Z)await J.threadStorage.set(Y,Z);let q=await dJ.getOrCreateForThread(K,Y);if(X)await J.threadSyncService.updateThreadMeta(Y,T41(X));let G=J.threadService.observe(Y).subscribe(async(z)=>{if(G7(z,"assistant"))await zg1(Y),G.unsubscribe()});return await q.resume(),q}async function Gg1(J,Q,Z){let X=process.stdin,Y=P41(Q);if(Y instanceof Error)FX(Y.message);let K,q=null;if(Q.streamJsonInput)K="";else if(typeof Q.execute==="string"){K=Q.execute;let R=(await rb1()).trimEnd();if(R)q=R}else K=(await rb1()).trimEnd();if(Q.remote&&!J.executeMode)throw new E2("The -r/--remote flag currently only works with --execute mode",1,'Use: amp --remote --execute "your message"');if(Q.streamJson&&!J.executeMode)throw new E2("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(Q.streamJsonInput&&!J.executeMode)throw new E2("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.streamJsonInput&&!Q.streamJson)throw new E2("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(Q.stats&&!J.executeMode)throw new E2("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(Q.streamJsonInput&&typeof Q.execute==="string"&&Q.execute.trim()!=="")throw new E2("Do not provide a message argument when using --stream-json-input",1,`Supply messages via stdin JSONL instead: echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"your message"}]}}' | amp --execute --stream-json --stream-json-input`);if(J.executeMode&&K===""&&!Q.streamJsonInput)throw new E2("User message must be provided through stdin or as argument when using execute mode",1,`Either pass a message as an argument: amp --execute "your message"
|
5635
5635
|
Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMode&&!J.streamJsonMode&&typeof Q.execute!=="string")X=await jJ6();iA(Z,Q);let G=await nA(J,Q);NF6=G;let z=_51(G),U=async(R)=>{let I=await VF6(R,"utf-8"),w=JSON.parse(I);if(!aU(w.id))throw new E2(vK.invalidThreadId);return k51(G,{visibility:Y,thread:w})},F=async(R)=>{if(!aU(R))throw new E2(vK.invalidThreadId);let I=await G.threadService.get(R)??void 0;return k51(G,{visibility:Y,thread:I})},W=async()=>{try{if(Q.threadId)return F(Q.threadId);else return k51(G,{visibility:Y})}catch(R){if(R instanceof E2)throw R;throw await K41(R,Q.threadId),Error("handleError should have called process.exit()")}},H=async()=>{return k51(G,{visibility:Y})};if(Q.format==="jsonl")o2.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
5636
|
-
`),await MA(),process.exit(1);if(J.executeMode&&Q.remote)await BJ6(K,q),await G.asyncDispose(),process.exit(0);let D=await W();if(J.executeMode)await O76(D,D.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1,N=new aq1;if(Q.jetbrains||Q.ide){await N.cleanUpLockfiles();let R=await N.getConfigs();if(R.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let I=R[0];if(I)N.selectConfig(I)}else M=!0}let L=db1("0.0.
|
5637
|
-
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=EU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await NJ6(Y),await LJ6(Y),J.mcpConfig){let q=await UY9(J.mcpConfig);Y=FY9(Y,q)}let K=await Y.get("url","global");if(!K)K=GZ;if(!nH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=sp1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:MJ6(await vb1(J,Y))}}function NY9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function LY9(){let J=NY9(process.argv);if(r46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),KY9(a),a.info("Starting Amp CLI.",{version:"0.0.
|
5636
|
+
`),await MA(),process.exit(1);if(J.executeMode&&Q.remote)await BJ6(K,q),await G.asyncDispose(),process.exit(0);let D=await W();if(J.executeMode)await O76(D,D.threadID,K,q,G,!!Q.streamJson,!!Q.streamJsonInput,!!Q.stats,J.ampURL),await G.asyncDispose(),process.exit(0);let M=!1,V=!1,N=new aq1;if(Q.jetbrains||Q.ide){await N.cleanUpLockfiles();let R=await N.getConfigs();if(R.length===0){if(Q.jetbrains)V=!await G.configService.get("jetbrains.skipInstall")}else if(R.length===1){let I=R[0];if(I)N.selectConfig(I)}else M=!0}let L=db1("0.0.1759150769-gc5f674",G.settingsStorage),O=K0.of([S0.file(process.cwd())]),A=BC(void 0,O);if(K)D.handle({type:"user:message",message:{content:[{type:"text",text:K}]}});let j=await A9();await WF6({stdin:X,stdout:process.stdout,history:new Bb1,fuzzyServer:G.fuzzyServer,settingsStorage:G.settingsStorage,threadService:G.threadService,threadSyncService:G.threadSyncService,threadID:D.threadID,worker:D,workerDeps:z,configService:G.configService,internalAPIClient:NZ,ampURL:J.ampURL,useGpt5:j.settings.gpt5??!1,startNewThread:H,pickAndContinueThread:async()=>{a.info("Thread picker requested - not yet implemented in TUI")},switchToThread:F,ideClient:RQ,commandRegistry:A,showJetBrainsInstaller:V,showIdePicker:M,lockfileManager:N,startWithPicker:Q.startWithPicker,updateService:L}),await G.asyncDispose(),process.exit(0)}async function yK(J){if(J.interactive)o2.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
5637
|
+
`);let Q=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Z=!1,X=process.stdout.isTTY&&process.stderr.isTTY,Y=EU({...J,getHook:process.env.AMP_URL?(q,G)=>{if(q==="url")return Promise.resolve(process.env.AMP_URL);return G()}:void 0});if(await NJ6(Y),await LJ6(Y),J.mcpConfig){let q=await UY9(J.mcpConfig);Y=FY9(Y,q)}let K=await Y.get("url","global");if(!K)K=GZ;if(!nH(K))a.info("Targeting custom Amp server",{ampURL:K});return Y=sp1(Y),{executeMode:Q,streamJsonMode:Z,isTTY:X,ampURL:K,settings:Y,secrets:MJ6(await vb1(J,Y))}}function NY9(J){let Q={};for(let Z=0;Z<J.length;Z++){let X=J[Z];if(X?.startsWith("--")){let K=X.slice(2).replace(/-([a-z])/g,(G,z)=>z.toUpperCase()),q=J[Z+1];if(q&&!q.startsWith("--"))Q[K]=q,Z++}}return Q}async function LY9(){let J=NY9(process.argv);if(r46({logLevel:J.logLevel||process.env.AMP_LOG_LEVEL,logFile:J.logFile||process.env.AMP_LOG_FILE}),KY9(a),a.info("Starting Amp CLI.",{version:"0.0.1759150769-gc5f674",buildTimestamp:"2025-09-29T13:04:54.948Z",buildType:"'release'"}),parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new E2(vK.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");await VY9().parseAsync(process.argv)}async function OY9(J,Q){if(process.env.AMP_URL)await J.settings.set("url",process.env.AMP_URL,"global"),u2.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
5638
5638
|
`);else if(!nH(J.ampURL))u2.write(`Logging in to ${new URL(J.ampURL).hostname}
|
5639
5639
|
`);let Z=process.env.AMP_API_KEY;if(Z)u2.write(`API key found in environment variable, storing...
|
5640
5640
|
`),await Q.set("apiKey",Z,J.ampURL),u2.write(`API key successfully stored.
|
@@ -5650,7 +5650,7 @@ Or pipe via stdin: echo "your message" | amp --execute`);if(K!==""&&!J.executeMo
|
|
5650
5650
|
`));try{let Q;if(J)Q=J,o2.write(Q8.blue(`Updating to version ${J}...
|
5651
5651
|
`)),await ET(J),o2.write(Q8.green(`✓ Successfully updated to version ${J}
|
5652
5652
|
`));else{o2.write(Q8.blue(`Checking for updates...
|
5653
|
-
`));let{hasUpdate:X,latestVersion:Y}=await hR("0.0.
|
5653
|
+
`));let{hasUpdate:X,latestVersion:Y}=await hR("0.0.1759150769-gc5f674");if(!X)o2.write(Q8.green(`✓ Amp CLI is already up to date.
|
5654
5654
|
`)),process.exit(0);if(!Y)o2.write(Q8.yellow("[WARN] could not find latest version")),process.exit(0);Q=Y,o2.write(Q8.blue(`Updating to version ${Y}...
|
5655
5655
|
`)),await ET(Y),o2.write(Q8.green(`✓ Successfully updated to version ${Y}
|
5656
5656
|
`))}let Z=await jA(Q);if(Z.warning)o2.write(`
|
package/package.json
CHANGED