@sourcegraph/amp 0.0.1776038869-g0bc56e → 0.0.1776056343-g168e20
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 +9 -9
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -4234,7 +4234,7 @@ ${v8(Lk5)}
|
|
|
4234
4234
|
`,inputSchema:{type:"object",properties:{url:{type:"string",description:"The URL of the web page to read"},objective:{type:"string",description:"A natural-language description of the research goal. If set, only relevant excerpts will be returned. If not set, the full content of the web page will be returned. "},forceRefetch:{type:"boolean",description:"Force a live fetch of the URL (default: use a cached version that may be a few days old)"}},required:["url"]},source:"builtin"},fn:Nk5};T4();var Oq4=({args:J,userInput:Z},Q)=>{let Y=F30(J);return GJ0({args:Y,userInput:Z},Q)};var Eq4={spec:{name:JY,description:`Runs a shell command and returns its output.
|
|
4235
4235
|
- Always set the \`workdir\` param when using the shell_command function. Do not use \`cd\` unless absolutely necessary. For doing file changes, use the ${vV}
|
|
4236
4236
|
- Avoid end-buffering pipes like \`| tail -20\` for long-running commands; they can hide progress and trigger inactivity timeouts
|
|
4237
|
-
- Use \`timeout_ms\` to increase the inactivity timeout for commands that may stay quiet for long stretches`,inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},workdir:{type:"string",description:"Optional working directory to run the command in; defaults to the turn cwd."},login:{type:"boolean",description:"Whether to run the shell with login shell semantics. Defaults to true."},timeout_ms:{type:"number",description:"The timeout for the command in milliseconds"}},required:["command"],additionalProperties:!1},source:"builtin",meta:{disableTimeout:!0},executionProfile:{serial:!
|
|
4237
|
+
- Use \`timeout_ms\` to increase the inactivity timeout for commands that may stay quiet for long stretches`,inputSchema:{type:"object",properties:{command:{type:"string",description:"Shell command to execute."},workdir:{type:"string",description:"Optional working directory to run the command in; defaults to the turn cwd."},login:{type:"boolean",description:"Whether to run the shell with login shell semantics. Defaults to true."},timeout_ms:{type:"number",description:"The timeout for the command in milliseconds"}},required:["command"],additionalProperties:!1},source:"builtin",meta:{disableTimeout:!0},executionProfile:{serial:!1,resourceKeys:()=>[]}},fn:Oq4,preprocessArgs:lo1};$m0();cX();T4();L1();a0();y2();cX();ZN();uA();O20();f3();function Mq4(J){return{runInference:async(Z,Q,Y,X,K,V,G)=>{let F=await bJ4(Y,X,Q,K,$8(Z),V,G,void 0,void 0,J),z=F.message,q=[],W=z.choices[0];if(W?.message?.tool_calls){for(let U of W.message.tool_calls)if(U.id){let D=U;q.push({id:U.id,name:D.function?.name??"",input:D.function?.arguments?JSON.parse(D.function.arguments):void 0})}}let H;if(z.usage){let U=z.usage,D=U.prompt_tokens_details?.cached_tokens??U.cached_tokens??0;H={model:$8(Z),maxInputTokens:0,inputTokens:0,outputTokens:U.completion_tokens,cacheReadInputTokens:D,cacheCreationInputTokens:U.prompt_tokens-D,totalInputTokens:U.prompt_tokens,timestamp:new Date().toISOString()}}return{result:F,toolUses:q,debugUsage:H}},extractMessage:(Z)=>{return Z.message.choices[0]?.message?.content||void 0},updateConversation:(Z,Q,Y)=>{let K=Q.message.choices[0];if(K?.message){let V=K.message,G={role:"assistant",content:V.content||"",reasoning_content:V.reasoning_content?.length?V.reasoning_content:void 0,tool_calls:V.tool_calls};Z.push(G)}for(let{id:V,result:G}of Y){let F={role:"tool",content:Ok5(G),tool_call_id:V};Z.push(F)}}}}function Ok5(J){if(J.status==="error"){let Z=J.error;return JSON.stringify(Z)}if(J.status==="done"){if(typeof J.result==="string")return J.result;let Z=JSON.stringify(J.result);return Z===void 0?"":Z}return`Tool execution status: ${J.status}`}function Ek5(J,Z,Q,Y){let X=[{role:"user",content:J}];return new b9().run(jK,{systemPrompt:Q,model:Z,spec:P8["task-subagent"]},{toolService:Y.toolService,env:Y,conversation:X})}function Mk5(J,Z,Q,Y){let X=[{role:"user",content:J}];return new b9().run(Mq4(),{systemPrompt:Q,model:Z,spec:P8["task-subagent"]},{toolService:Y.toolService,env:Y,conversation:X})}function Ak5(J){let{model:Z,agentMode:Q}=WJ(J.config.settings,J.thread);if(Q==="deep")return{model:Q5.CLAUDE_OPUS_4_6.name,provider:A6.ANTHROPIC};let{provider:Y}=aF(Z);return{model:Z,provider:Y}}function Iq4(J,Z,Q){let{model:Y,provider:X}=Ak5(Q);return _.debug("Task subagent starting:",{model:Y,provider:X,description:Z.substring(0,100)+(Z.length>100?"...":"")}),d4(()=>Ck5(Q)).pipe(_4((K)=>{if(X===A6.FIREWORKS)return Mk5(J,Y,K,Q);return Ek5(J,Y,K,Q)}),w1(jk5))}function jk5(J){switch(J.status){case"in-progress":return{status:"in-progress",progress:J.turns.map((Z)=>({message:Z.message,tool_uses:[...Z.activeTools.values()]}))};case"done":return{status:"done",result:J.message,progress:J.turns.map((Z)=>({message:Z.message,tool_uses:[...Z.activeTools.values()]})),"~debug":J["~debug"]};case"error":return{status:"error",error:{message:J.message},progress:J.turns?.map((Z)=>({message:Z.message,tool_uses:[...Z.activeTools.values()]})),"~debug":J["~debug"]};case"cancelled":return{status:"cancelled",progress:J.turns.map((Z)=>({message:Z.message,tool_uses:[...Z.activeTools.values()]})),reason:Pk5(J.turns),"~debug":J["~debug"]}}}var Rk5=20,Ik5=10,Aq4=80;function jq4(J,Z){let Q=J.split(`
|
|
4238
4238
|
`);if(Q.length<=Z)return J;return Q.slice(0,Z).join(`
|
|
4239
4239
|
`)+`
|
|
4240
4240
|
... (${Q.length-Z} more lines)`}function Rq4(J,Z){let{input:Q,result:Y}=J,X=[];if(!Q||typeof Q!=="object")X.push(J.tool_name);else switch(J.tool_name){case"edit_file":case"create_file":if(Q.path)X.push(`${J.tool_name}(${Q.path})`);else X.push(J.tool_name);break;case"Read":if(Q.path)X.push(`Read(${Q.path})`);else X.push("Read");break;case"Grep":if(Q.pattern){let K=Q.path?` in ${Q.path}`:"";X.push(`Grep("${Q.pattern}"${K})`)}else X.push("Grep");break;case"Bash":if(Q.cmd){let K=String(Q.cmd).length>Aq4?String(Q.cmd).substring(0,Aq4-3)+"...":Q.cmd;X.push(`Bash("${K}")`)}else X.push("Bash");break;case"glob":if(Q.filePattern)X.push(`glob("${Q.filePattern}")`);else X.push("glob");break;default:X.push(J.tool_name)}if(Z&&Y&&J.status==="done")switch(J.tool_name){case"edit_file":case"create_file":{let K=typeof Y==="string"?Y:typeof Y.diff==="string"?Y.diff:null;if(K)X.push(`
|
|
@@ -4711,12 +4711,12 @@ ${D}`))}},error:(U)=>{if(!H)H=!0,F(Error(`Failed to spawn brew: ${U.message}`))}
|
|
|
4711
4711
|
${D}`;if(K==="pnpm"&&D.includes("Unable to find the global bin directory"))B+=`
|
|
4712
4712
|
|
|
4713
4713
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4714
|
-
npm install -g @sourcegraph/amp`;F(Error(B))}},error:(U)=>{if(!W)W=!0,F(Error(`Failed to spawn ${K}: ${U.message}`))},complete:()=>{if(!W)W=!0,G()}})})}a0();a0();iH();async function NX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=OC4(J,z),W=q<0,H,U;if(F.time){let D=F.time[J],B=F.time[z],N=Date.now();if(D)H=Math.floor((N-new Date(D).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:H,latestVersionAge:U,source:"npm"}}catch(G){return _.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var KX3="https://static.ampcode.com/cli/cli-version.txt";async function wX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${KX3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=OC4(J,X),V=K<0;return _.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return _.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var VX3=604800000;function LC4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>VX3)return{ageMs:Q};return null}function OC4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ko0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?hz(Q):void 0;return{sha:Y,age:X}}catch{return null}}L1();function vo0(J,Z,Q={}){let Y=new z4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new dF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await bz(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await bz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await BX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await wX0(J):await NX0(J,dj());if(!(H.latestVersion&&H.hasUpdate)){K.debug("no update available");return}let U=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let D=H.currentVersionAge-H.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!U())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Io0()){if(K.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!U())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await ti(H.latestVersion,q);let D=await yw(H.latestVersion),B={from:H.currentVersion,to:H.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await bz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}iH();import{stderr as cG}from"node:process";function EC4(J){let Z=new tN().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(Y)=>{await Lo0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
4714
|
+
npm install -g @sourcegraph/amp`;F(Error(B))}},error:(U)=>{if(!W)W=!0,F(Error(`Failed to spawn ${K}: ${U.message}`))},complete:()=>{if(!W)W=!0,G()}})})}a0();a0();iH();async function NX0(J,Z){let X=`${Z||"https://registry.npmjs.org"}/@sourcegraph/amp/latest`,K=new AbortController,V=setTimeout(()=>K.abort(),5000);try{let G=await fetch(X,{signal:K.signal});if(!G.ok)return{hasUpdate:!1,currentVersion:J,source:"npm"};let F=await G.json(),z=F.version??F["dist-tags"]?.latest;if(!z)return{hasUpdate:!1,currentVersion:J,source:"npm"};let q=OC4(J,z),W=q<0,H,U;if(F.time){let D=F.time[J],B=F.time[z],N=Date.now();if(D)H=Math.floor((N-new Date(D).getTime())/3600000);if(B)U=Math.floor((N-new Date(B).getTime())/3600000)}return _.info("NPM version comparison",{currentVersion:J,latestVersion:z,compareResult:q,hasUpdate:W,currentVersionAge:H,latestVersionAge:U}),{hasUpdate:W,latestVersion:z,currentVersion:J,currentVersionAge:H,latestVersionAge:U,source:"npm"}}catch(G){return _.debug("Error checking npm version",{error:G}),{hasUpdate:!1,currentVersion:J,source:"npm"}}finally{clearTimeout(V)}}var KX3="https://static.ampcode.com/cli/cli-version.txt";async function wX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${KX3}?t=${Date.now()}`,{signal:Z.signal,cache:"no-store"});if(!Y.ok)return{hasUpdate:!1,currentVersion:J,source:"bin"};let X=(await Y.text()).trim();if(!X||!/^\d+\.\d+\.\d+/.test(X))return{hasUpdate:!1,currentVersion:J,source:"bin"};let K=OC4(J,X),V=K<0;return _.info("Bin version comparison",{currentVersion:J,latestVersion:X,compareResult:K,hasUpdate:V}),{hasUpdate:V,latestVersion:X,currentVersion:J,source:"bin"}}catch(Y){return _.debug("Error checking bin version",{error:Y}),{hasUpdate:!1,currentVersion:J,source:"bin"}}finally{clearTimeout(Q)}}var VX3=604800000;function LC4(J){if(!J)return null;let Z=typeof J==="number"?J:new Date(J).getTime();if(isNaN(Z))return null;let Q=Date.now()-Z;if(Q>VX3)return{ageMs:Q};return null}function OC4(J,Z){let Q=(V)=>{let[G,F]=V.split("-");return{parts:G?.split(".").map(Number)||[],label:F}},Y=Q(J),X=Q(Z),K=Math.max(Y.parts.length,X.parts.length);for(let V=0;V<K;V++){let G=Y.parts[V]||0,F=X.parts[V]||0;if(G<F)return-1;if(G>F)return 1}if(Y.label===X.label)return 0;if(!Y.label&&X.label)return 1;if(Y.label&&!X.label)return-1;if(Y.label&&X.label)return Y.label<X.label?-1:1;return 0}function ko0(J){try{let Z=J.match(/^0\.0\.(\d+)(?:-g?([a-f0-9]+))?/);if(!Z)return null;let Q=parseInt(Z[1],10)*1000,Y=Z[2],X=Q!==0?hz(Q):void 0;return{sha:Y,age:X}}catch{return null}}L1();function vo0(J,Z,Q={}){let Y=new z4,X=Y.pipe(m6({shouldCountRefs:!1}));return setImmediate(async()=>{let K=new dF().scoped("update"),V=Q.startDelayMs??0;if(V>0)await bz(V);let G=X.subscribe({next:(F)=>{K.debug("emit new state",F)}});try{let F=process.env.AMP_TEST_UPDATE_STATUS;if(F){K.debug("using fake update status for testing",{status:F}),await bz(500),Y.next(F);return}if(process.env.AMP_SKIP_UPDATE_CHECK==="1"){K.debug("checking disabled via AMP_SKIP_UPDATE_CHECK environment variable");return}let z=await Z.get("updates.mode");if(z==="disabled"){K.debug("checking disabled");return}let q=await BX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await wX0(J):await NX0(J,dj());if(!(H.latestVersion&&H.hasUpdate)){K.debug("no update available");return}let U=()=>{if(H.currentVersionAge!==void 0&&H.latestVersionAge!==void 0){let D=H.currentVersionAge-H.latestVersionAge,B=0.5;if(Math.abs(D)<0.5)return K.debug("versions too close together, suppressing update warning",{currentVersionAge:H.currentVersionAge,latestVersionAge:H.latestVersionAge,ageDifferenceHours:D}),!0}return!1};if(!z)z=q==="pnpm"?"warn":"auto",K.debug("no configured update mode; selected default based on package manager",{packageManager:q,mode:z});if(q==="brew"){if(!U())Y.next("update-available-brew");return}if(q==="binary"&&process.execPath!==Io0()){if(K.debug("non-standard binary path, showing warning"),!U())Y.next("update-available-unrecognized-path");return}if(z==="warn"){if(!U())Y.next("update-available");return}if(!q){if(K.debug("auto-update not supported, falling back to warn mode"),!U())Y.next("update-available");return}if(q==="binary"&&process.platform==="win32"){if(K.debug("binary auto-update not supported on Windows, falling back to warn mode"),!U())Y.next("update-available");return}try{await ti(H.latestVersion,q);let D=await yw(H.latestVersion),B={from:H.currentVersion,to:H.latestVersion,...D};if(D.status==="same")K.info("success",B),Y.next("updated");else K.warn("success with warning",B),Y.next("updated-with-warning")}catch(D){Y.next("update-error")}}catch(F){K.debug("check failed",{error:F})}finally{await bz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}iH();import{stderr as cG}from"node:process";function EC4(J){let Z=new tN().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(Y)=>{await Lo0(Y.force||!1,Y.verbose||!1,"0.0.1776056343-g168e20"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new tN("update").alias("up").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("--target-version <version>","Update to a specific version").allowUnknownOption(!1).action(async(Y)=>{await FX3(Y.targetVersion)});J.addCommand(Q)}function GX3(J){let Z=Boolean(J.isTTY),Q=0,Y=!1;function X(){if(!Z||!Y)return;J.write(`
|
|
4715
4715
|
`),Y=!1,Q=0}function K(V){if(!Z)return;let G=V.padEnd(Q," ");J.write(`\r${G}`),Y=!0,Q=G.length}return{flushProgressLine:X,renderProgress:K}}async function FX3(J){let Q=process.platform==="win32"&&pj()?{currentExecutablePath:process.execPath}:void 0,{flushProgressLine:Y,renderProgress:X}=GX3(cG);if(process.env.AMP_SKIP_UPDATE_CHECK==="1")cG.write(i0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4716
4716
|
|
|
4717
4717
|
`));try{if(!J){cG.write(i0.blue(`Checking for updates...
|
|
4718
|
-
`));let{hasUpdate:G,latestVersion:F}=pj()?await wX0("0.0.
|
|
4719
|
-
`));let W=await yw("0.0.
|
|
4718
|
+
`));let{hasUpdate:G,latestVersion:F}=pj()?await wX0("0.0.1776056343-g168e20"):await NX0("0.0.1776056343-g168e20",dj());if(!G){let z=ko0("0.0.1776056343-g168e20"),q=z?.age?`released ${z.age} ago`:`built ${hz(new Date("2026-04-13T05:02:54.540Z"))} ago`;cG.write(i0.green(`✓ Amp is already up to date on version ${"0.0.1776056343-g168e20"} (${q})
|
|
4719
|
+
`));let W=await yw("0.0.1776056343-g168e20",Q);if(W.warning)cG.write(`
|
|
4720
4720
|
`+i0.yellow(W.warning)+`
|
|
4721
4721
|
`);process.exit(0)}if(!F)cG.write(i0.yellow("[WARN] could not find latest version")),process.exit(0);J=F}cG.write(i0.blue(`Updating to version ${J}...
|
|
4722
4722
|
`)),await ti(J,void 0,(G)=>{Y(),cG.write(i0.dim(`Running: ${G}
|
|
@@ -5924,7 +5924,7 @@ ${X}`,Z);this.line=Q,this.column=Y,this.codeblock=X}}/*!
|
|
|
5924
5924
|
`),K=[];for(let V=0;V<X.length;V++){let z=X[V].replace(/\b(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|LIMIT|JOIN|LEFT JOIN|RIGHT JOIN|INNER JOIN|ON|AND|OR|AS|IN|NOT|NULL|IS|BETWEEN|LIKE|EXISTS|UNION|DISTINCT|COUNT|SUM|AVG|MIN|MAX|DATE|TIMESTAMP_TRUNC|TIMESTAMP_SUB|CURRENT_TIMESTAMP|INTERVAL|CASE|WHEN|THEN|ELSE|END|WITH|INSERT|UPDATE|DELETE|SET|VALUES|INTO|CREATE|ALTER|DROP|TRUE|FALSE|ASC|DESC)\b/gi,"\x00$1\x01").split(/(\x00[^\x01]+\x01)/);for(let q of z)if(q.startsWith("\x00")&&q.endsWith("\x01"))K.push(new P(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new P(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new P(`
|
|
5925
5925
|
`))}return new l0({decoration:{color:Q.colorScheme.background,border:X4.all(new Z4(Y.app.keybind,1,"rounded"))},child:new c0({padding:C0.symmetric(0,1),child:new $0({text:new P(void 0,void 0,K)})})})}}class y11 extends w2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=EF0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new k11({chartData:this.chartData,highlightIndex:this.highlightIndex,showAxes:this.showAxes,colors:this.colors})}updateRenderObject(J){let Z=J;Z.chartData=this.chartData,Z.highlightIndex=this.highlightIndex,Z.showAxes=this.showAxes,Z.colors=this.colors,Z.markNeedsLayout()}}function ym4(J,Z,Q,Y,X,K,V){if(K<=0)return null;switch(J){case"horizontal-bar":{let G=Q;return G>=0&&G<K?G:null}case"bar":case"stacked-bar":{let G=V?P9:0,F=Y-G;if(F<=0)return null;let z=Z-G;if(z<0||z>=F)return null;let q=Math.max(1,Math.floor(F/K)),W=Math.floor(z/q);return W>=0&&W<K?W:null}case"line":case"sparkline":case"stacked-area":{let G=V?P9:0,F=Y-G;if(F<=0)return null;let z=Math.max(0,Math.min(F-1,Z-G));if(K===1)return 0;let q=F/(K-1),W=Math.round(z/q);return Math.max(0,Math.min(K-1,W))}default:return null}}function P_3(J,Z,Q,Y,X,K,V,G){if(X<=0||Z<0||Z>=X)return null;let F=2;switch(J){case"horizontal-bar":return{x:Math.floor(Q/2),y:Z};case"bar":case"stacked-bar":{let z=K?P9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let H=Math.max(1,Math.floor(q/X)),U=z+Z*H+Math.floor(H/2),D=G>0?V/G:0,B=Math.round((1-D)*(W-1));return{x:U,y:B}}case"line":case"sparkline":case"stacked-area":{let z=K?P9:0,q=Q-z,W=Y-(K?F:0);if(q<=0||W<=0)return null;let H=X>1?z+Math.round(Z/(X-1)*(q-1)):z+Math.floor(q/2),U=G>0?V/G:0,D=Math.round((1-U)*(W-1));return{x:H,y:D}}default:return null}}function C_3(J){let Z=0;for(let Q of J)for(let Y of Q.points)if(Y.value>Z)Z=Y.value;return Z||1}function __3(J,Z,Q,Y,X){if(Q.length<=1){let G=Y(J.value),F=J.meta?` (${J.meta})`:"";return J.label.length+2+G.length+F.length}let K=J.label.length,V=0;for(let G of Q){let F=G.points[Z];if(!F)continue;V+=F.value;let z=2+G.name.length+2+Y(F.value).length;K=Math.max(K,z)}if(X){let G=9+Y(V).length;K=Math.max(K,G)}return K}function T_3(J,Z,Q,Y,X,K,V){let G;try{let D=b1.of(J),B=f0.of(J);G={foreground:D.colorScheme.foreground,background:D.colorScheme.background,border:B.app.keybind}}catch{G={foreground:{type:"index",value:15},background:{type:"index",value:0},border:{type:"index",value:7}}}let F=new g({color:G.foreground,bold:!0}),z=new g({color:G.foreground}),q=new g({color:G.foreground,dim:!0}),W=[],H=new g({color:G.foreground,underline:!0}),U=(D,B)=>new P(B,H,void 0,jX0(D),()=>{i3(J,D)});if(Y.length<=1){if(W.push(new P(`${Z.label}: `,F)),Z.link)W.push(U(Z.link,K(Z.value)));else W.push(new P(K(Z.value),z));if(Z.meta)W.push(new P(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new P(`${Z.label}
|
|
5926
5926
|
`,F));let B=0;for(let N=0;N<Y.length;N++){let w=Y[N],L=w.points[Q];if(!L)continue;B+=L.value;let O=w.color??X[N%X.length]??G.foreground;if(W.push(new P("● ",new g({color:O}))),W.push(new P(`${w.name}: `,q)),L.link)W.push(U(L.link,K(L.value)));else W.push(new P(K(L.value),z));if(N<Y.length-1||D)W.push(new P(`
|
|
5927
|
-
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),z))}return new l0({decoration:{color:G.background,border:X4.all(new Z4(G.border,1,"rounded"))},child:new $0({text:new P(void 0,void 0,W)})})}sD();a0();B9();OE();e7();f3();y2();yd();fX();tZ();GY();ZQ();uA();m4();tg();nP();L1();a0();tZ();class x11{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;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(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1776038869-g0bc56e"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await d40(Z,this.configService)}catch(Z){_.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class PL extends p0{props;constructor(J){super();this.props=J}createState(){return new xm4}}class xm4 extends m0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class fm4 extends m0{controller=new a7;focusNode=new O6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=X4.all(new Z4(Q.foreground,1,"solid")),F=new ZX({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new H1({children:[new l0({decoration:{color:Q.background},child:new $0({text:new P(">",new g({color:Q.foreground}))})}),new i1({child:F})]}),q=new l0({padding:C0.symmetric(1,0),child:new $0({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new g({color:Y.keybind}))),W.push(new P(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new P("Esc",new g({color:Y.keybind}))),W.push(new P(" to cancel",new g({color:Q.foreground,dim:!0})));let H=new l0({padding:C0.symmetric(1,0),child:new $0({text:new P("",void 0,W)})});return new l0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new g0({children:[q,new I0({height:1}),z,new v5,H]})})}}class $o extends p0{props;constructor(J){super();this.props=J}createState(){return new fm4}}ZQ();class um4 extends m0{controller=new a7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new O6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.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 this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=hV)return!1;let Z=await GL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new dU({controller:this.controller,triggers:[new rK],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(U)=>{this.widget.props.onSubmit(U.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:X6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new Y6({focusNode:this.focusNode,child:G}),z=new l0({constraints:new M1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new l0({padding:C0.symmetric(1,0),child:new $0({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new l0({padding:C0.symmetric(1,0),child:new $0({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new g({color:Y.keybind})),new P(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new g({color:Q.foreground,dim:!0})),new P("Enter",new g({color:Y.keybind})),new P(" to submit, ",new g({color:Q.foreground,dim:!0})),new P("Esc",new g({color:Y.keybind})),new P(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new i1({child:z}),new I0({height:1}),W];return new l0({decoration:{border:X4.all(new Z4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new g0({children:H})})}}class f11 extends p0{props;constructor(J){super();this.props=J}createState(){return new um4}}function bm4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class u11 extends h1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>bm4(X.pubDate).length));return new W9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:z.foreground,U=z.mutedForeground,D=(B,N)=>new I0({width:N,child:H1.end([new $0({text:new P(B,new g({color:U}))})])});return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new H1({children:[new i1({child:new $0({text:new P(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(bm4(X.pubDate),Q)]})})}})}}YB();class b11 extends p0{createState(){return new hm4}}class hm4 extends m0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new P("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function S_3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return zG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function h11(J,Z,Q){return new $0({text:new P(`${J}${Z}`,new g({color:Q})),maxLines:1})}function k_3(J,Z,Q,Y){return[h11("+",J,Y.success),v5.horizontal(1),h11("~",Z,Y.warning),v5.horizontal(1),h11("-",Q,Y.destructive)]}function v_3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class AF0 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new gm4}}class gm4 extends m0{spinner=new j5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>!L.workspaceURI||L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=S_3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=f0.of(J),U=new c0({padding:C0.symmetric(0,1),child:new K4({child:new $0({text:new P("",new g({color:H.colors.foreground,dim:!0}),[new P("Alt+W/Ctrl+T",new g({color:H.colors.primary,dim:!0})),new P(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:H.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=S9(L);return B};return new W9({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!v_3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:U,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:I}=A,T=O?j.selectionBackground:void 0,C=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,W0)=>new I0({width:W0,child:H1.end([new $0({text:new P(s,new g({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new ga({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],W0=L.ancestorsAreLast.slice(1);for(let w0 of W0)s.push(new P(d.getAncestorPrefix(w0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,F0=d.getConnectorText(r);s.push(new P(F0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new $0({text:new P("",void 0,s)}))}let m=[],b=F===L.id?new P("(current) ",new g({color:I.success})):G.has(L.id)?new P("(visited) ",new g({color:I.foreground,dim:!0})):null;if(b)m.push(new $0({text:b}));if(YA(x))m.push(new b11),m.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);m.push(new $0({text:new P("[fork] ",new g({color:I.primary}))}))}else if(f)m.push(new $0({text:new P("[handoff] ",new g({color:I.accent}))}));if(m.push(new i1({child:new $0({text:new P(n,new g({color:C})),overflow:"ellipsis",maxLines:1})})),m.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:h,warning:h,destructive:h}:I;m.push(...k_3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),m.push(new I0({width:2}))}return m.push(p(L.description.timeAgo,W)),new l0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new H1({children:[...k,...m]})})}})}}a0();class eK{message;constructor(J){this.message=J}}class E7{widget;title;type;footerStyle;dimensions;constructor(J,Z="Info",Q="info",Y="default",X){this.widget=J;this.title=Z;this.type=Q;this.footerStyle=Y;this.dimensions=X}}function jF0(J){if(J instanceof eK)return{title:"Info",description:J.message,type:"info"};return _.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"}}a0();xX();iH();fX();tZ();m4();H4();nP();var m11=D4(UH(),1);import{execSync as fR}from"node:child_process";import{writeFile as my}from"node:fs/promises";import y_3 from"node:os";import sq from"node:path";var mm4="c446b2e9b16cdc06df2ec285894d6421",x_3="5ea19563777f4ade8707fc56f7e7a388",f_3="amp-thread-worker",pm4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function u_3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function _L(J){if(!J||!u_3(J.meta))return!1;return J.meta.usesDtw===!0}function p11(J){let Z=new URL(`https://dash.cloudflare.com/${mm4}/workers/durable-objects/view/${x_3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function d11(J){let Z=new URL(`https://dash.cloudflare.com/${mm4}/workers/services/view/${f_3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function b_3(J,Z){if(bW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function c11(J,Z){let Q=b_3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Jo(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Zo(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Zo(J){return J.path??A8(J.uri)}function dm4(J,Z,Q){let Y=Jo("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function cm4(J,Z){return c11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
5927
|
+
`))}if(D)W.push(new P(" ",q)),W.push(new P("Total: ",q)),W.push(new P(K(B),z))}return new l0({decoration:{color:G.background,border:X4.all(new Z4(G.border,1,"rounded"))},child:new $0({text:new P(void 0,void 0,W)})})}sD();a0();B9();OE();e7();f3();y2();yd();fX();tZ();GY();ZQ();uA();m4();tg();nP();L1();a0();tZ();class x11{enabled;configService;commandCounts=new Map;timer=null;bufferTimeMs=1e4;constructor(J,Z){this.enabled=J;this.configService=Z;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(([Z,Q])=>({feature:"cli.command",action:Z,source:{client:"cli",clientVersion:"0.0.1776056343-g168e20"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await d40(Z,this.configService)}catch(Z){_.error("Failed to export command telemetry events",Z)}}async submit(J){if(!await this.enabled()||this.timer===null)return;let Z=this.commandCounts.get(J)||0;this.commandCounts.set(J,Z+1)}async dispose(){if(await this.flushEvents(),this.timer!==null)clearInterval(this.timer),this.timer=null}}class PL extends p0{props;constructor(J){super();this.props=J}createState(){return new xm4}}class xm4 extends m0{_state;initState(){super.initState(),this._state=this.widget.props.initialState}build(J){let Z=(Q)=>{this.setState(()=>{this._state=Q(this._state)})};return this.widget.props.builder(J,Z,this._state)}}class fm4 extends m0{controller=new a7;focusNode=new O6({debugLabel:"CommandArgumentPrompt",onKey:(J)=>{if(J.key==="Escape")return this.widget.props.onDismiss(),"handled";return"ignored"}});_textListener=()=>{this.setState(()=>{})};initState(){this.focusNode.requestFocus(),this.controller.addListener(this._textListener)}dispose(){this.controller.removeListener(this._textListener),this.focusNode.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=X4.all(new Z4(Q.foreground,1,"solid")),F=new ZX({controller:this.controller,focusNode:this.focusNode,placeholder:this.widget.props.placeholder??"Enter command argument...",onSubmitted:(U)=>{let D=U.trim();if(X&&D.length===0)return;this.widget.props.onSubmit(D)},autofocus:!0,style:{textColor:Q.foreground,border:null},maxLines:1}),z=new H1({children:[new l0({decoration:{color:Q.background},child:new $0({text:new P(">",new g({color:Q.foreground}))})}),new i1({child:F})]}),q=new l0({padding:C0.symmetric(1,0),child:new $0({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new P("Enter",new g({color:Y.keybind}))),W.push(new P(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new P("Esc",new g({color:Y.keybind}))),W.push(new P(" to cancel",new g({color:Q.foreground,dim:!0})));let H=new l0({padding:C0.symmetric(1,0),child:new $0({text:new P("",void 0,W)})});return new l0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new g0({children:[q,new I0({height:1}),z,new v5,H]})})}}class $o extends p0{props;constructor(J){super();this.props=J}createState(){return new fm4}}ZQ();class um4 extends m0{controller=new a7;imageAttachments=[];imagePaths=[];isConfirmingClearInput=!1;clearInputConfirmTimeout=null;focusNode=new O6({debugLabel:"CommandMultilinePrompt",onKey:(J)=>{if(J.key==="Escape"){if(this.isConfirmingClearInput){if(this.controller.clear(),this.setState(()=>{this.isConfirmingClearInput=!1,this.imageAttachments=[],this.imagePaths=[]}),this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;return"handled"}if(this.controller.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 this.widget.props.onDismiss(),"handled"}return"ignored"}});initState(){if(this.widget.props.initialText)this.controller.text=this.widget.props.initialText;if(this.widget.props.initialImages)this.imageAttachments=[...this.widget.props.initialImages];this.focusNode.requestFocus()}_handleInsertImage=async(J)=>{if(this.imageAttachments.length>=hV)return!1;let Z=await GL(J);if(typeof Z==="object")return this.setState(()=>{this.imageAttachments=[...this.imageAttachments,Z],this.imagePaths=[...this.imagePaths,J]}),!1;return!1};_handlePopImage=()=>{if(this.imageAttachments.length>0)this.setState(()=>{this.imageAttachments=this.imageAttachments.slice(0,-1),this.imagePaths=this.imagePaths.slice(0,-1)})};dispose(){if(this.clearInputConfirmTimeout)clearTimeout(this.clearInputConfirmTimeout),this.clearInputConfirmTimeout=null;this.focusNode.dispose(),this.controller.dispose()}build(J){let Z=f0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new dU({controller:this.controller,triggers:[new rK],completionBuilder:this.widget.props.completionBuilder,onSubmitted:(U)=>{this.widget.props.onSubmit(U.trim(),this.imageAttachments)},theme:Q,placeholder:this.widget.props.placeholder||"Enter your message...",enabled:this.widget.props.enabled??!0,autofocus:!0,clipboard:X6.instance.tuiInstance.clipboard,autoOverlayPosition:!0,onInsertImage:this.widget.props.onInsertImage??this._handleInsertImage,imageAttachments:this.imageAttachments,popImage:this._handlePopImage}),F=new Y6({focusNode:this.focusNode,child:G}),z=new l0({constraints:new M1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new l0({padding:C0.symmetric(1,0),child:new $0({text:new P("",void 0,[new P("Command: ",new g({color:Q.foreground})),new P(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new l0({padding:C0.symmetric(1,0),child:new $0({text:this.isConfirmingClearInput?new P("",void 0,[new P("Esc",new g({color:Y.keybind})),new P(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new P("",void 0,[new P("Press ",new g({color:Q.foreground,dim:!0})),new P("Enter",new g({color:Y.keybind})),new P(" to submit, ",new g({color:Q.foreground,dim:!0})),new P("Esc",new g({color:Y.keybind})),new P(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new i1({child:z}),new I0({height:1}),W];return new l0({decoration:{border:X4.all(new Z4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new g0({children:H})})}}class f11 extends p0{props;constructor(J){super();this.props=J}createState(){return new um4}}function bm4(J){let Q=new Date().getTime()-J.getTime(),Y=Math.floor(Q/60000),X=Math.floor(Q/3600000),K=Math.floor(Q/86400000);if(Y<1)return"just now";if(Y<60)return`${Y}m ago`;if(X<24)return`${X}h ago`;if(K<7)return`${K}d ago`;return J.toLocaleDateString()}class u11 extends h1{props;debugLabel="NewsFeedPicker";constructor(J){super();this.props=J}build(J){let Z=[...this.props.entries].sort((X,K)=>K.pubDate.getTime()-X.pubDate.getTime()),Q=Math.max(0,...Z.map((X)=>bm4(X.pubDate).length));return new W9({items:Z,getLabel:(X)=>X.title,onAccept:(X)=>this.props.onSelect?.(X),onDismiss:this.props.onDismiss,title:this.props.title,emptyStateText:"No news entries available",maxRenderItems:100,renderItem:(X,K,V,G)=>{let F=f0.of(G),{colors:z}=F,q=F.app,W=K?q.selectionBackground:void 0,H=K?q.selectionForeground:z.foreground,U=z.mutedForeground,D=(B,N)=>new I0({width:N,child:H1.end([new $0({text:new P(B,new g({color:U}))})])});return new l0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new H1({children:[new i1({child:new $0({text:new P(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(bm4(X.pubDate),Q)]})})}})}}YB();class b11 extends p0{createState(){return new hm4}}class hm4 extends m0{isGreen=!0;timer;initState(){this.timer=setInterval(()=>{this.isGreen=!this.isGreen,this.setState()},700)}dispose(){if(this.timer)clearInterval(this.timer);super.dispose()}build(J){let Q=f0.of(J).colors;return new $0({text:new P("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function S_3(J){let Z=new Map,Q=new Map,Y=new Map,X=[];for(let V of J)Z.set(V.id,V);for(let V of J){let G=V.relationships.find((F)=>F.role==="child"&&Z.has(F.threadID)&&(F.type==="fork"||F.type==="handoff"));if(G){Y.set(V.id,G.type);let F=G.threadID,z=Q.get(F)||[];z.push(V),Q.set(F,z)}else X.push(V)}return zG0.flatten(X,(V)=>Q.get(V.id)).map((V)=>({...V.item,depth:V.depth,isLast:V.isLast,ancestorsAreLast:V.ancestorsAreLast,relationshipType:Y.get(V.item.id)}))}function h11(J,Z,Q){return new $0({text:new P(`${J}${Z}`,new g({color:Q})),maxLines:1})}function k_3(J,Z,Q,Y){return[h11("+",J,Y.success),v5.horizontal(1),h11("~",Z,Y.warning),v5.horizontal(1),h11("-",Q,Y.destructive)]}function v_3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class AF0 extends p0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new gm4}}class gm4 extends m0{spinner=new j5;spinnerInterval=null;isSwitchingThread=!1;get isBusy(){return this.isSwitchingThread||this.widget.props.isLoading===!0}updateSpinnerAnimation(){if(this.isBusy){if(!this.spinnerInterval)this.spinnerInterval=setInterval(()=>{this.spinner.step(),this.setState(()=>{})},100);return}if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null}setSwitchingThread(J){if(this.isSwitchingThread===J)return;this.setState(()=>{this.isSwitchingThread=J}),this.updateSpinnerAnimation()}initState(){super.initState(),this.updateSpinnerAnimation()}didUpdateWidget(J){this.updateSpinnerAnimation()}dispose(){if(this.spinnerInterval)clearInterval(this.spinnerInterval),this.spinnerInterval=null;super.dispose()}build(J){let{props:Z}=this.widget,Q=this.isBusy,Y=this.isSwitchingThread?"Switching thread...":"Loading threads...",X=`${this.spinner.toBraille()} ${Y}`,K=Z.filterByWorkspace&&Z.currentWorkspaceURI?Z.threads.filter((L)=>!L.workspaceURI||L.workspaceURI===Z.currentWorkspaceURI):Z.threads;if(Z.excludeCurrentThread&&Z.currentThreadID)K=K.filter((L)=>L.id!==Z.currentThreadID);let V=Z.recentThreadIDs||[],G=new Set(V),F=Z.currentThreadID,z=[...K].sort((L,O)=>{if(F){if(L.id===F)return-1;if(O.id===F)return 1}let E=V.indexOf(L.id),M=V.indexOf(O.id);if(E!==-1&&M!==-1)return E-M;if(E!==-1)return-1;if(M!==-1)return 1;return 0}),q=S_3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=f0.of(J),U=new c0({padding:C0.symmetric(0,1),child:new K4({child:new $0({text:new P("",new g({color:H.colors.foreground,dim:!0}),[new P("Alt+W/Ctrl+T",new g({color:H.colors.primary,dim:!0})),new P(Z.filterByWorkspace?" for all workspaces":" to filter by workspace",new g({color:H.colors.foreground,dim:!0}))])})})}),D="",B=null,N=(L)=>{if(L!==D)D=L,B=S9(L);return B};return new W9({items:q,getLabel:(L)=>`${L.title} ${L.id}`,filterItem:(L,O)=>{let E=N(O);if(E)return L.id.toLowerCase()===E.toLowerCase();return!0},normalizeQuery:(L)=>N(L)?"":L,onAccept:async(L,O)=>{if(!Z.onSelect||this.isSwitchingThread)return;let E=Z.onSelect(L.id,O);if(!v_3(E))return;this.setSwitchingThread(!0);try{await E}finally{if(this.mounted)this.setSwitchingThread(!1)}},onDismiss:Z.onDismiss,onSelectionChange:(L)=>{if(Z.previewController){if(L)Z.previewController.select(L.id)}},title:Z.title,enabled:!Q,isLoading:Q,hidePromptWhenLoading:!0,loadingText:X,emptyStateText:Z.hasError?"Failed to load threads":"No threads match your filter",maxRenderItems:200,footer:Q||Z.hasError?void 0:U,renderItem:(L,O,E,M)=>{let A=f0.of(M),{app:j,colors:I}=A,T=O?j.selectionBackground:void 0,C=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,W0)=>new I0({width:W0,child:H1.end([new $0({text:new P(s,new g({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new ga({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],W0=L.ancestorsAreLast.slice(1);for(let w0 of W0)s.push(new P(d.getAncestorPrefix(w0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,F0=d.getConnectorText(r);s.push(new P(F0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new $0({text:new P("",void 0,s)}))}let m=[],b=F===L.id?new P("(current) ",new g({color:I.success})):G.has(L.id)?new P("(visited) ",new g({color:I.foreground,dim:!0})):null;if(b)m.push(new $0({text:b}));if(YA(x))m.push(new b11),m.push(new I0({width:1}));let n=L.title;if(L.relationshipType==="fork"){let s=n.match(/^Forked\((\d+)\): /);if(s)n=n.slice(s[0].length);else while(n.startsWith("Forked: "))n=n.slice(8);m.push(new $0({text:new P("[fork] ",new g({color:I.primary}))}))}else if(f)m.push(new $0({text:new P("[handoff] ",new g({color:I.accent}))}));if(m.push(new i1({child:new $0({text:new P(n,new g({color:C})),overflow:"ellipsis",maxLines:1})})),m.push(new I0({width:2})),L.diffStats&&(L.diffStats.added>0||L.diffStats.changed>0||L.diffStats.deleted>0)){let s=O?{success:h,warning:h,destructive:h}:I;m.push(...k_3(L.diffStats.added,L.diffStats.changed,L.diffStats.deleted,s)),m.push(new I0({width:2}))}return m.push(p(L.description.timeAgo,W)),new l0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new H1({children:[...k,...m]})})}})}}a0();class eK{message;constructor(J){this.message=J}}class E7{widget;title;type;footerStyle;dimensions;constructor(J,Z="Info",Q="info",Y="default",X){this.widget=J;this.title=Z;this.type=Q;this.footerStyle=Y;this.dimensions=X}}function jF0(J){if(J instanceof eK)return{title:"Info",description:J.message,type:"info"};return _.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"}}a0();xX();iH();fX();tZ();m4();H4();nP();var m11=D4(UH(),1);import{execSync as fR}from"node:child_process";import{writeFile as my}from"node:fs/promises";import y_3 from"node:os";import sq from"node:path";var mm4="c446b2e9b16cdc06df2ec285894d6421",x_3="5ea19563777f4ade8707fc56f7e7a388",f_3="amp-thread-worker",pm4=[{id:"cli-open",label:"cli: open in pager"},{id:"cloudflare-logs",label:"cloudflare: open logs"},{id:"cloudflare-data-studio",label:"cloudflare: open data studio"}];function u_3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function _L(J){if(!J||!u_3(J.meta))return!1;return J.meta.usesDtw===!0}function p11(J){let Z=new URL(`https://dash.cloudflare.com/${mm4}/workers/durable-objects/view/${x_3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function d11(J){let Z=new URL(`https://dash.cloudflare.com/${mm4}/workers/services/view/${f_3}/production/observability/events`);return Z.searchParams.set("filterCombination",'"and"'),Z.searchParams.set("calculations",'[{"operator":"count"}]'),Z.searchParams.set("orderBy",'{"value":"count","limit":10,"order":"desc"}'),Z.searchParams.set("timeframe","24h"),Z.searchParams.set("conditions","{}"),Z.searchParams.set("conditionCombination",'"and"'),Z.searchParams.set("alertTiming",'{"interval":300,"window":900,"timeBeforeFiring":600,"timeBeforeResolved":600}'),Z.searchParams.set("filters",JSON.stringify([{key:"threadId",operation:"eq",value:J,type:"string"}])),Z.toString()}function b_3(J,Z){if(bW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function c11(J,Z){let Q=b_3(Z,J);return[{label:"dtw: get full transcript",command:`${Q} get-transcript`},{label:"dtw: send message via curl",command:`${Q} add-message "<your message here>"`},{label:"dtw: dump full sqlite DB to disk",command:`${Q} dump`},{label:"dtw: fetch Cloudflare logs",command:`./scripts/fetch-cloudflare-logs.ts ${J}`}]}function Jo(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Zo(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Zo(J){return J.path??A8(J.uri)}function dm4(J,Z,Q){let Y=Jo("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function cm4(J,Z){return c11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
5928
5928
|
${Y}`).join(`
|
|
5929
5929
|
|
|
5930
5930
|
`)}function g11(J){if(J===void 0||!Number.isFinite(J)||J<=0)return"n/a";return`${hz(J)} ago (\`${new Date(J).toISOString()}\`)`}function h_3(J){if(!J)return"n/a";let Z=Date.parse(J);if(!Number.isFinite(Z))return`\`${J}\``;return g11(Z)}function CL(J){if(J===void 0||J===null)return"n/a";return`\`${String(J)}\``}function RF0(J,Z="#"){let{thread:Q,threadViewState:Y}=J,X=(V)=>`${Z} ${V}`,K=[X("Thread"),`- ID: \`${Q.id}\``,`- Title: ${c10(Q)}`,`- URL: \`${$H(new URL(J.ampURL),Q.id).toString()}\``,`- Created: ${g11(Q.created)}`,`- Agent mode: ${CL(Q.agentMode)}`,`- Effective mode: \`${J.effectiveAgentMode}\``,`- DTW backed: ${_L(Q)?"yes":"no"}`,`- Executor type: ${CL(Q.meta?.executorType)}`,`- Messages: \`${Q.messages.length}\` total / \`${q8(Q)}\` human / \`${Q.queuedMessages?.length??0}\` queued`];if(Q.meta?.status!==void 0)K.push(`- Merge status: ${CL(Q.meta.status??"null")}`);if(Q.meta?.lastKnownAgentState)K.push(`- Last known agent state: \`${Q.meta.lastKnownAgentState.state}\` at ${h_3(Q.meta.lastKnownAgentState.updatedAt)}`);if(J.initialTreePath)K.push(`- Initial tree: \`${J.initialTreePath}\``);if(J.currentWorkspacePath)K.push(`- Current workspace: \`${J.currentWorkspacePath}\``);if(K.push("",X("Runtime"),`- Amp URL: \`${bW(J.ampURL)?Q7:J.ampURL}\``,`- Thread pool mode: \`${J.threadPoolIsDTW?"dtw":"worker"}\``,`- Connection state: ${CL(J.transportState)}`,`- Connection role: ${CL(J.transportRole)}`,`- Processing: ${J.isProcessing?"yes":"no"}`,`- PID: ${CL(J.pid)}`,`- Client ID: ${CL(J.clientId)}`),J.logFile)K.push(`- Log file: \`${Zo(J.logFile)}\``);if(!Y)return K.push("",X("View State"),"- No live thread view state available."),K.join(`
|
|
@@ -6150,7 +6150,7 @@ ${t.content||""}`:t.content||"",R0=[],y0=t.baseDir.startsWith("file://")?Kz0(t.b
|
|
|
6150
6150
|
`),process.exit(1)}process.stdout.write(await Ey3(F.result.displayText)+`
|
|
6151
6151
|
`),process.exit(0)})}iH();import{stdout as My3}from"node:process";function Ay3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${hz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function wl4(J){My3.write(`${Ay3(J)}
|
|
6152
6152
|
`)}function Ll4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{wl4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{wl4(Z),process.exit(0)})}var db3=aL.join(vX,"logs","headless.log"),z31=aL.join(Rv,"device-id.json"),ma4=`cli-tui-${ra4(16).toString("hex")}`;async function cb3(){for(let J of IE)try{if((await J.listConfigs()).length>0)return J}catch(Z){_.debug("Failed to detect query-based IDE integration",{ideName:J.ideName,error:Z})}return}try{if(process.platform==="win32")await Promise.resolve().then(() => D4(Ux(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){o$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6153
|
-
`)}function lb3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function A7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")N$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")N$("experimental.agentMode",Z.mode)}function $o4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function ib3(J){try{return await ta4(J,"utf-8")}catch{return J}}async function q31(J,Z,Q){let Y=$o4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!io(X,P7.HARNESS_SYSTEM_PROMPT)&&!Jo4(K))throw new T1("You are not allowed to do this.",1);N$("systemPrompt",await ib3(Y))}function Jo4(J){return!!(J&&Y10(J))}function io(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function W31(J){return(J.userEmail?B$(J.userEmail):!1)||io(J.features,P7.DTW_TUI)}function pa4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function H31(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return W31({userEmail:Z.user.email,features:Z.features})}function nb3(J){return J!=="pending"}function Dx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function ab3(J){let Z=Dx(J);if(Z)return Z.id;if(Vz(J))throw Error(J.error.message);throw Error("unreachable")}function ob3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function oz0(J){let Y=ob3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function da4(J){if(!a6.write(J))await hb3(a6,"drain")}var ca4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??pK,description:`Custom settings file path (overrides the default location ${pK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${qa0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:i7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:oF.SMART.key,description:`Set the agent mode (${uX({},!1).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],la4=(J)=>("deprecated"in J)&&J.deprecated===!0,rb3=(J)=>("hidden"in J)&&J.hidden===!0,sb3=(J)=>("default"in J),tb3=(J)=>("default"in J)?J.default:void 0,Zo4=[{name:"toggle-skills-count",entryPoint:O01}];function eb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(M3.unknownCommand(Q),1,V)}}async function D31(J){return{...J,getThreadEnvironment:DZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new sV(J.fileSystem),generateThreadTitle:U90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>YJ(J.configService),pluginService:J.pluginService}}function Qo4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:DZ,filesystem:J.fileSystem,threadService:J.threadService}}var rz0=G1.file(ea4.homedir()),U31=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(rz0,".config");function $h3(J){return QW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())ZW4();else Wp0(Z);let Q=YK0(),Y=Rr0();if((!Q||Y||iC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(SU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(SU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(YK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Iu1("0.0.
|
|
6153
|
+
`)}function lb3(J){process.emitWarning=(Z,Q,Y,X)=>{let K=typeof Z==="string"?Z:Z.message||String(Z),V=Q||"Warning",G=!1;J.warn(K,{name:V,code:Y})}}function A7(J,Z){if(J.getOptionValueSourceWithGlobals("dangerouslyAllowAll")==="cli")N$("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")N$("experimental.agentMode",Z.mode)}function $o4(J,Z){if(J.getOptionValueSourceWithGlobals("sp")==="cli"&&Z.sp)return Z.sp;if(J.getOptionValueSourceWithGlobals("systemPrompt")==="cli"&&Z.systemPrompt)return Z.systemPrompt;return}async function ib3(J){try{return await ta4(J,"utf-8")}catch{return J}}async function q31(J,Z,Q){let Y=$o4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!io(X,P7.HARNESS_SYSTEM_PROMPT)&&!Jo4(K))throw new T1("You are not allowed to do this.",1);N$("systemPrompt",await ib3(Y))}function Jo4(J){return!!(J&&Y10(J))}function io(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function W31(J){return(J.userEmail?B$(J.userEmail):!1)||io(J.features,P7.DTW_TUI)}function pa4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new T1("This TUI mode is not enabled for your user;",1)}function H31(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return W31({userEmail:Z.user.email,features:Z.features})}function nb3(J){return J!=="pending"}function Dx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function ab3(J){let Z=Dx(J);if(Z)return Z.id;if(Vz(J))throw Error(J.error.message);throw Error("unreachable")}function ob3(J){try{let Z=new URL(J);return Z.hostname==="localhost"||Z.hostname==="127.0.0.1"}catch{return J.includes("localhost")||J.includes("127.0.0.1")}}function oz0(J){let Y=ob3(J)?"Run `pnpm dev` to start the local server, then try again.":"Check your network connection or the server URL and try again.";return new T1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function da4(J){if(!a6.write(J))await hb3(a6,"drain")}var ca4=[{name:"notifications",long:"notifications",type:"flag",description:(J)=>`${J?"Enable":"Disable"} sound notifications (enabled by default when not in execute mode)`},{name:"color",long:"color",type:"flag",description:(J)=>`${J?"Enable":"Disable"} color output (enabled by default if stdout and stderr are sent to a TTY)`},{name:"settingsFile",long:"settings-file",type:"option",default:process.env.AMP_SETTINGS_FILE??pK,description:`Custom settings file path (overrides the default location ${pK})`},{name:"logLevel",long:"log-level",type:"option",description:`Set log level (${Object.keys(_).join(", ")})`},{name:"logFile",long:"log-file",type:"option",description:`Set log file location (overrides the default location ${qa0})`},{name:"format",long:"format",type:"option",description:"output using the standard or new-ui. Options: `ui`, `new-ui`",choices:["ui","jsonl","new-ui"],hidden:!0,deprecated:!0},{name:"dangerouslyAllowAll",long:"dangerously-allow-all",type:"switch",default:!1,description:"Disable all command confirmation prompts (agent will execute all commands without asking)"},{name:"jetbrains",long:"jetbrains",type:"flag",default:i7(),description:(J)=>J?"Enable JetBrains integration. When enabled, Amp automatically includes your open JetBrains file and text selection with every message.":"Disable JetBrains integration"},{name:"ide",long:"ide",type:"flag",default:!0,description:(J)=>J?"Enable IDE connection (default). When enabled, Amp automatically includes your open IDE's file and text selection with every message.":"Disable IDE connection"},{name:"interactive",long:"interactive",type:"flag",description:(J)=>J?"Enable interactive mode. This will enable the interactive UI.":"Disable interactive mode. This will disable the interactive UI.",hidden:!0,deprecated:!0},{name:"mcpConfig",long:"mcp-config",type:"option",description:"JSON configuration or file path for MCP servers to merge with existing settings"},{name:"mode",long:"mode",short:"m",type:"option",default:oF.SMART.key,description:`Set the agent mode (${uX({},!1).map((J)=>J.mode).join(", ")}) — controls the model, system prompt, and tool selection`,choices:uX().map((J)=>J.mode).concat("large","deep","internal")},{name:"takeMeBack",long:"take-me-back",type:"switch",description:"Disable v2 thread mode and use the legacy worker runtime",hidden:!0},{name:"headless",long:"headless",type:"optional-option",description:"Run headless DTW harness (no TUI). Optionally provide a thread ID to connect as executor.",hidden:!0},{name:"threadActors",long:"thread-actors",type:"switch",description:"Connect to the thread-actors counter service. Optionally provide a thread ID.",hidden:!0},{name:"apiKey",long:"api-key",type:"option",description:"API key for internal DTW commands (overrides AMP_API_KEY)",hidden:!0},{name:"sp",long:"sp",type:"option",description:"Custom system prompt text or file path",hidden:!0},{name:"systemPrompt",long:"system-prompt",type:"option",description:"Custom system prompt text",hidden:!0}],la4=(J)=>("deprecated"in J)&&J.deprecated===!0,rb3=(J)=>("hidden"in J)&&J.hidden===!0,sb3=(J)=>("default"in J),tb3=(J)=>("default"in J)?J.default:void 0,Zo4=[{name:"toggle-skills-count",entryPoint:O01}];function eb3(J,Z){let Q=Z.args[0],Y=Z.commands.map((K)=>K.name());if(Q&&!Q.includes(" ")&&Q.length<30&&!/[./\\]/.test(Q)){let K=Y.filter((G)=>Q.includes(G)||G.includes(Q)),V="Run amp --help for a list of available commands.";if(K.length>0)V=`Did you mean: ${K.join(", ")}? Or run amp --help for all commands.`;throw new T1(M3.unknownCommand(Q),1,V)}}async function D31(J){return{...J,getThreadEnvironment:DZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new sV(J.fileSystem),generateThreadTitle:U90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>YJ(J.configService),pluginService:J.pluginService}}function Qo4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:DZ,filesystem:J.fileSystem,threadService:J.threadService}}var rz0=G1.file(ea4.homedir()),U31=process.env.XDG_CONFIG_HOME?G1.file(process.env.XDG_CONFIG_HOME):V1.joinPath(rz0,".config");function $h3(J){return QW4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())ZW4();else Wp0(Z);let Q=YK0(),Y=Rr0();if((!Q||Y||iC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(SU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(SU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(YK0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Iu1("0.0.1776056343-g168e20");let X=DC({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(G1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:rz0,userConfigDir:U31});Ab4(X);let K=await X.getLatest();_.debug("Global configuration initialized",{settingsKeys:Object.keys(K.settings)});let V=!1;{let m=await J.secrets.get("apiKey",J.ampURL);if(V=Boolean(m),_.info("API key lookup before login",{found:Boolean(m),ampURL:J.ampURL,deferAuth:Y}),!m)if(Y)_.info("No API key found, continuing startup with deferred auth");else{a6.write(`No API key found. Starting login flow...
|
|
6154
6154
|
`);let b=await Jh3(J),n=await J.secrets.get("apiKey",J.ampURL);if(_.info("Login flow completed",{success:b,storedKeyPresent:Boolean(n),ampURL:J.ampURL}),!b)await RU(),process.exit(1);V=!0}}{let m=await X.getLatest(),b=m.settings.url,n=m.secrets.isSet?.[b];_.info("Config secrets state after login",{configURL:b,apiKeySet:n?.apiKey??!1})}let G=P1(YJ(X).pipe(E5(nb3))),F=Y?"pending":await G;if(!Y)_.info("Server status resolved",{status:"ready",isAuthenticated:_6(F),isError:Vz(F),errorMessage:Vz(F)?F.error.message:void 0});let z=G.then((m)=>ab3(m)),{toolService:q,dispose:W}=bJ0({configService:X}),H=new Map,U=()=>H.clear(),D=new LT0(X,J.settings.getWorkspaceRootPath()),B=Ne1({configService:X,filesystem:C8}),N=qo1({configService:X,trustStore:D,skillMCPServers:B.skillMCPServers,createOAuthProvider:async(m,b,n)=>{let c=`${m}:${b}`,s=H.get(c);if(s)return _.debug("Reusing existing OAuth provider for server",{serverName:m,serverUrl:b}),s;_.debug("Creating OAuth provider for server",{serverName:m,serverUrl:b});let W0=(async()=>{let r=new yE(J.secrets),F0=await r.getClientInfo(m,b),w0=n?.scopes??F0?.scopes,L0=GP4();_.info("OAuth headless mode check",{useHeadless:L0,executeMode:J.executeMode,envVar:process.env.AMP_HEADLESS_OAUTH,isTTY:a6.isTTY});let e;if(L0)e=J.executeMode?VP4():KP4(m);let K0=new tR0({storage:r,serverName:m,serverUrl:b,clientId:n?.clientId??F0?.clientId,clientSecret:n?.clientSecret??F0?.clientSecret,authUrl:n?.authUrl??F0?.authUrl,tokenUrl:n?.tokenUrl??F0?.tokenUrl,scopes:w0,headlessAuthHandler:e});return _.debug("OAuth provider created",{serverName:m,serverUrl:b,hasManualClientId:!!(n?.clientId??F0?.clientId),willUseDCR:!(n?.clientId??F0?.clientId),scopes:w0,headlessMode:L0,executeMode:J.executeMode}),K0})();return H.set(c,W0),W0}}),w=Lm0({configService:X,filesystem:C8,spawn:JJ0}),L;if(J.executeMode){let m=await YF4({toolService:q,providers:[N,w],initialTimeout:15000});L=m.registrations;for(let[b,n]of m.initErrors)_.warn(`${b} provider initialization slow or failed:`,n)}else L=Om0({toolService:q,providers:[N,w]});if(Z.jetbrains)AE("JetBrains");else if(Z.ide&&lP4())AE("VS Code");else if(Z.ide&&iP4())AE("Neovim");else if(Z.ide){let m=await cb3();if(m){let b=X40(m.ideName);if(b)AE(b)}}if(J.executeMode)Pu1(!0);let O,E=QJ.status.pipe(w1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&Zb1(m.ideName))),g4()).subscribe((m)=>{if(m){if(!O)O=q.registerTool(QF4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new Bv(process.cwd(),{alwaysIncludePaths:m},!0)}else M=new class extends Bv{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new Mk0(C80(X),{maxThreads:200});_.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=H31(j,F),T=new I01,C=process.env.PLUGINS??"off",h=Z.headless?Vb4():void 0,p=h??new sV0({configService:X}),x=p instanceof sV0?p:void 0;if(x)x.pluginExecutorKind=I?"local":"unknown";let k=fT0({configService:X,fileSystem:C8,platform:p,internalPlugins:Zo4,pluginFilter:C}),f=Kr1({pluginService:k,toolService:q}),d={configService:X,toolService:q,mcpService:N,skillService:B,toolboxService:w,trustStore:D,threadService:A,secretStorage:J.secrets,settingsStorage:J.settings,fuzzyServer:M,fileSystem:C8,terminal:T,pluginService:k,pluginPlatform:x,headlessPluginPlatform:h,serverStatus:F,serverStatusPromise:G,viewerUserIDPromise:z,hasAPIKeyAtStartup:V};return{...d,async asyncDispose(){if(d.mcpService.hasAuthenticatingClients())_.info("Waiting for OAuth authentication to complete before exit..."),await d.mcpService.waitForAuthentication();for(let m of L.values())m.dispose();await d.mcpService.dispose(),U(),await d.threadService.asyncDispose(),d.configService.unsubscribe(),W(),d.fuzzyServer.dispose(),d.settingsStorage[Symbol.dispose](),E.unsubscribe(),O?.dispose(),f.dispose(),await d.pluginService.dispose()}}}async function Jh3(J){if(!J.executeMode){if(!await nX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return a6.write(`Login cancelled. Run the command again to retry.
|
|
6155
6155
|
`),!1}return await Yo4(J)}async function Yo4(J){let Z=ra4(32).toString("hex"),Q=await yv(J.ampURL,Z),Y=new AbortController;try{await TV(Q,Y.signal)}catch(K){_.error("Error opening browser",{error:K})}let X=await yv(J.ampURL,Z,!1);a6.write(`If your browser does not open automatically, visit:
|
|
6156
6156
|
|
|
@@ -6158,7 +6158,7 @@ ${i0.blue.bold(X)}
|
|
|
6158
6158
|
|
|
6159
6159
|
`);try{return await QT4(J.ampURL,Z,J.secrets,Y),a6.write("\nLogin successful! Run `amp` to get started.\n"),!0}catch(K){return _.error("Login failed",{error:K}),o$.write(`
|
|
6160
6160
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
6161
|
-
`),!1}}function ia4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Zh3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!Y7(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function Qh3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Yh3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Qh3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Xh3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Kh3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Vh3(J){let Z=new tN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)xj(),process.exit(0);let N=B.originalError??B;cR4(N)}),Ll4(Z,{version:"0.0.
|
|
6161
|
+
`),!1}}function ia4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Zh3(J){let Z={...J.agentMode?{agentMode:J.agentMode}:{},...J.repositoryURL?{repositoryURL:J.repositoryURL}:{}},Q=await fetch(`${J.ampURL}/api/durable-thread-workers`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify(Z)});if(!Q.ok){let X=await Q.text();throw new T1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!Y7(Y.threadId))throw new T1("Create response did not include a valid thread ID",1);return Y.threadId}function Qh3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function Yh3(J){let Z=await fetch(new URL(`/threads/${J.threadID}/durable-object-id`,J.workerURL),{method:"GET",headers:{Authorization:`Bearer ${J.apiKey}`}});if(!Z.ok){let Y=await Z.text();throw new T1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!Qh3(Q))throw new T1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Xh3(J){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(J)}async function Kh3(J){let Z=await fetch(`${J.workerURL}/threads/${J.threadID}/spawn`,{method:"POST",headers:{Authorization:`Bearer ${J.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({repositoryURL:J.repositoryURL,...J.projectID?{projectID:J.projectID}:{}})});if(!Z.ok){let Q=await Z.text();throw new T1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Vh3(J){let Z=new tN().name("amp").description("AI-powered coding assistant").option("--visibility <visibility>","Set thread visibility (private, public, workspace, group)").configureOutput({writeErr:()=>{}});Z.exitOverride((B)=>{if(B.code==="commander.help"||B.code==="commander.version"||B.exitCode===0)xj(),process.exit(0);let N=B.originalError??B;cR4(N)}),Ll4(Z,{version:"0.0.1776056343-g168e20",buildTimestamp:"2026-04-13T05:02:54.540Z",buildType:"'release'"}),Z.addHelpText("after",pP4()),Z.configureHelp({formatHelp:dP4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await T3(w);await Dh3(L)}),Z.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(B,N)=>{let w=N.optsWithGlobals(),L=await T3(w);await Uh3(L,await pi(w,L.settings))}),Z.command("git-credential-helper [action]",{hidden:!0}).summary("Git credential helper for GitHub").description("Internal: implements the git credential helper protocol. Used inside sandboxes to authenticate git operations with GitHub.").action(async(B,N,w)=>{let L=w.optsWithGlobals(),O=await T3(L);await EI4(B??"get",O.ampURL,O.secrets),process.exit(process.exitCode??0)}),Z.command("sign-commit",{hidden:!0}).summary("Git commit signing helper").description("Internal: implements the gpg signing interface for git commit signing. Used inside sandboxes as gpg.program.").allowUnknownOption().action(async(B,N)=>{let w=N.optsWithGlobals(),L=await T3(w);await MI4(L.ampURL,L.secrets),process.exit(process.exitCode??0)}),Z.command("dtw-curl [threadId] [action] [message...]",{hidden:!0}).summary("DTW helper").description("Internal: helper for DTW one-shot commands.").addHelpText("after",`
|
|
6162
6162
|
Actions:
|
|
6163
6163
|
create Create a new DTW thread and print its ID
|
|
6164
6164
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -6223,8 +6223,8 @@ ${M}
|
|
|
6223
6223
|
|
|
6224
6224
|
This thread belongs to a different user and cannot be continued for security reasons. Set AMP_RESUME_OTHER_USER_THREADS_INSECURE=1 to bypass this check.`)}}async function Gh3(J){_.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new ma({threadService:J.threadService,configService:J.configService,mcpService:J.mcpService,clientID:J.clientID,initialToolDiscovery:Promise.all([J.mcpService.initialized,J.toolboxService.initialized]).then(()=>{return}),toolService:J.toolService,skillService:J.skillService,getThreadEnvironment:DZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new sV(J.fileSystem),ampURL:J.ampURL,useThreadActors:J.useThreadActors});if(J.threadId)await Z.switchThread(J.threadId);else await Z.createThread();return Z}catch(Z){throw _.error("[createDTWThreadPool] Failed to create DTW thread pool",{threadId:J.threadId,error:Z}),Z}}async function Fh3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await wy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await wy()).trimEnd(),stdinInput:null}}function zh3(J,Z,Q){if(J.remote&&!Z)throw new T1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new T1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new T1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new T1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new T1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new T1("The --archive flag requires --execute mode",1,'Use: amp --execute "your message" --archive');if(J.streamJsonInput&&typeof J.execute==="string"&&J.execute.trim()!=="")throw new T1("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"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"..."}}]}}' | amp --execute --stream-json --stream-json-input`);if(Z&&Q===""&&!J.streamJsonInput&&!J.headless)throw new T1("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"
|
|
6225
6225
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function sz0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(e,K0)=>{let i=Number(process.hrtime.bigint()-K0)/1e6,a=rO4();_.info("Startup phase",{phase:e,phaseMs:Math.round(i),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:V,stdinInput:G}=await Fh3(Z),F=!!Z.streamJson||!!Z.streamJsonThinking;zh3({...Z,streamJson:F},J.executeMode,V),A7(Q,Z);let z=process.hrtime.bigint(),q=Boolean(await J.secrets.get("apiKey",J.ampURL)),W=!J.executeMode&&!Z.headless&&!Z.threadActors&&q;_.info("Interactive auth startup mode",{deferInteractiveAuth:W,hasAPIKeyAtStartup:q,executeMode:J.executeMode,headless:Boolean(Z.headless)});let H=await T9(J,Z,{deferAuth:W});K("runMainThread:createThreadDependencies",z),z=process.hrtime.bigint();let U=await D31(H);K("runMainThread:createWorkerDeps",z);let{serverStatus:D}=H;if(!W&&Vz(D)){let e=Hv(Error(D.error.message));if(e.message===M3.networkOffline||e.message===M3.networkTimeout)throw oz0(J.ampURL);throw new T1(M3.invalidAPIKey,1)}let B=_6(D)?D:null,N=B?.user.email,w=Jo4(N),L=W31({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&H31(O,B);if(!W)await q31(Q,Z,D);let M=Dx(D),A=M?.features??[],j=M?.team??null,I=rV0(Z,M);if(I instanceof Error)S3(I.message);if((J.executeMode||F)&&g8(Z.mode)&&!w)throw new T1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!LE(Z.mode,N))throw new T1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await zb4(V,G,H.configService),await H.asyncDispose(),process.exit(0);if(Z.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!N||!B$(N)))throw new T1("Headless DTW mode is only available for Amp employees",1);let K0=await H.secretStorage.get("apiKey",J.ampURL);if(!K0)throw new T1("API key required for headless mode. Please run `amp login` first.",1);let i=typeof Z.headless==="string"&&Z.headless!=="true"?Z.headless:void 0;if(i&&!Y7(i))throw new T1(`Invalid thread ID: ${i}`,1);let a=i?void 0:await jh3({dependencies:H,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),t=i??a?.threadId;if(!t)throw new T1("Failed to resolve headless thread ID",1);let J0=await WP4(t);if(J0.status==="already-running")await H.asyncDispose(),await RU(),process.exit(0);try{await YP4({ampURL:J.ampURL,apiKey:K0,workerUrl:process.env.AMP_WORKER_URL,workspaceRoot:process.cwd(),threadId:t,ownerUserId:a?.ownerUserId,threadVersion:a?.threadVersion,agentMode:a?.agentMode,initialToolDiscovery:Promise.all([H.mcpService.initialized,H.toolboxService.initialized]).then(()=>{return}),configService:H.configService,mcpService:H.mcpService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,pluginService:H.pluginService,pluginPlatform:H.headlessPluginPlatform,useThreadActors:Z.threadActors?!0:void 0})}finally{await J0.release(),await H.asyncDispose()}await RU(),process.exit(0)}let T=J.executeMode?void 0:async(e)=>no(e,"interactive"),C={threadService:H.threadService,workerDeps:U,createThread:async()=>{let e=W?await H.serverStatusPromise:D,K0=await CY0(J.settings,process.cwd(),Dx(e),I);if(K0 instanceof Error)S3(K0.message);return g01(U,{threadMeta:K0?$F(K0):void 0,agentMode:Z.mode,onFirstAssistantMessage:T})},validateThreadOwnership:async(e,K0)=>{if(K0?.nonBlockingOwnershipCheck){na4(e,H.configService,H.viewerUserIDPromise).catch((i)=>{if(i instanceof T1){if(K0.onOwnershipError){K0.onOwnershipError(i,e);return}IU(i,e);return}_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})});return}try{await na4(e,H.configService,H.viewerUserIDPromise)}catch(i){if(i instanceof T1)throw i;_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})}},switchThreadVisibility:I,switchThreadAgentMode:Z.mode,onFirstAssistantMessage:T,handleError:IU},h=async(e)=>{try{if(e==="dtw")return Gh3({ampURL:J.ampURL,configService:H.configService,threadService:H.threadService,mcpService:H.mcpService,clientID:ma4,toolboxService:H.toolboxService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return zh4(C,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(K0){if(K0 instanceof T1)throw K0;throw await IU(K0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")o$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6226
|
-
`),await RU(),process.exit(1);let p=(async()=>{if(W){_.info("Skipping initial free tier status fetch until auth is complete");return}try{let e=await H.configService.getLatest(),K0=zb(e),i=await i5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(K0)});if(i.ok)return _.info("User free tier status:",i),i.result;return}catch(e){_.error("Failed to fetch free tier status:",e);return}})(),k=!J.executeMode?new f01:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await q31(Q,Z,e);let K0=process.hrtime.bigint(),i=H31(O,e),a=_6(e)?W31({userEmail:e.user.email,features:e.features}):!1;pa4({dtwEnabled:i,hasV2TUIAccess:a});let t=await h(i?"dtw":"worker");if(K("runMainThread:createThreadPool",K0),k.attach(t),V){let J0=await P1(t.threadHandles$);if(!J0)throw new T1("No active thread is available yet.",1);await J0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let K0=e instanceof Error?e:Error(String(e));k.setInitError(K0),await IU(e,Z.threadId)});else z=process.hrtime.bigint(),pa4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let m=Z.notifications!==void 0?Z.notifications:!J.executeMode,b=B!==null&&io(B.features,P7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{b=_6(e)&&io(e.features,P7.TUI_VOICE_NOTIF)}).catch((e)=>{_.debug("Failed to resolve TUI voice notification feature flag",{error:e})});z=process.hrtime.bigint();let n=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),$h3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>b,threadViewStates$:()=>f.threadHandles$.pipe(_4((e)=>{if(!e)return k0.of({});return F5(e.thread$,e.threadViewState$).pipe(w1(([K0,i])=>({[K0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){DT4(H.mcpService,J.settings);let e={userInput:V,stdinInput:G,dependencies:H,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},K0=await YI4({threadPool:f,...e});if(await no(K0,"execute"),Z.archive)await H.threadService.archive(K0,!0),await ao(H.threadService,K0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await Gb1();let e=await PE({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let K0=e[0];if(K0)QJ.selectConfig(K0)}else s=!0}z=process.hrtime.bigint();let W0=vo0("0.0.
|
|
6227
|
-
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Bo1({get:async(G)=>{if(G!==qg)return;try{let F=await ta4(z31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==qg)return;await sa4(aL.dirname(z31),{recursive:!0}),await gb3(z31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:i50()});Cu1(Y);let X=await WX0({...J,workspaceTrust:{current:!0,changes:Pj0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await HT4(J.mcpConfig);X=UT4(X,G)}let K=aL.dirname(X.getSettingsFilePath());JW4(Rv,K);let V=await X.get("url","global");if(!V)V=Q7;if(_.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!bW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=zf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:aX0(await pi(J,X))}}function qh3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Wh3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=aL.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?db3:qa0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Hh3(){oO4();let J=qh3(process.argv),Z=Wh3(process.argv,J),Q=XR4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)i0.level=0;if(lb3(_),_.info("Starting Amp CLI.",{version:"0.0.
|
|
6226
|
+
`),await RU(),process.exit(1);let p=(async()=>{if(W){_.info("Skipping initial free tier status fetch until auth is complete");return}try{let e=await H.configService.getLatest(),K0=zb(e),i=await i5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(K0)});if(i.ok)return _.info("User free tier status:",i),i.result;return}catch(e){_.error("Failed to fetch free tier status:",e);return}})(),k=!J.executeMode?new f01:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await q31(Q,Z,e);let K0=process.hrtime.bigint(),i=H31(O,e),a=_6(e)?W31({userEmail:e.user.email,features:e.features}):!1;pa4({dtwEnabled:i,hasV2TUIAccess:a});let t=await h(i?"dtw":"worker");if(K("runMainThread:createThreadPool",K0),k.attach(t),V){let J0=await P1(t.threadHandles$);if(!J0)throw new T1("No active thread is available yet.",1);await J0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let K0=e instanceof Error?e:Error(String(e));k.setInitError(K0),await IU(e,Z.threadId)});else z=process.hrtime.bigint(),pa4({dtwEnabled:E,hasV2TUIAccess:L}),f=await h(E?"dtw":"worker"),K("runMainThread:createThreadPool",z);let m=Z.notifications!==void 0?Z.notifications:!J.executeMode,b=B!==null&&io(B.features,P7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{b=_6(e)&&io(e.features,P7.TUI_VOICE_NOTIF)}).catch((e)=>{_.debug("Failed to resolve TUI voice notification feature flag",{error:e})});z=process.hrtime.bigint();let n=await H.configService.getLatest();if(K("runMainThread:configService.getLatest",z),z=process.hrtime.bigint(),$h3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>b,threadViewStates$:()=>f.threadHandles$.pipe(_4((e)=>{if(!e)return k0.of({});return F5(e.thread$,e.threadViewState$).pipe(w1(([K0,i])=>({[K0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){DT4(H.mcpService,J.settings);let e={userInput:V,stdinInput:G,dependencies:H,streamJson:F,streamJsonInput:!!Z.streamJsonInput,streamJsonThinking:!!Z.streamJsonThinking,stats:!!Z.stats,ampURL:J.ampURL,isDogfooding:w,agentMode:Z.mode,labels:Z.label},K0=await YI4({threadPool:f,...e});if(await no(K0,"execute"),Z.archive)await H.threadService.archive(K0,!0),await ao(H.threadService,K0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await Gb1();let e=await PE({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let K0=e[0];if(K0)QJ.selectConfig(K0)}else s=!0}z=process.hrtime.bigint();let W0=vo0("0.0.1776056343-g168e20",H.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let r=new Ur0(H.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",z),V&&J.executeMode){let e=await P1(f.threadHandles$);if(!e)throw new T1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}z=process.hrtime.bigint();let F0=await tV0();K("runMainThread:loadSessionState",z),_.info("Loaded session state:",F0);let w0={...F0,launchCount:F0.launchCount+1};By((e)=>({...e,launchCount:e.launchCount+1}));let L0=Z.threadId&&Y7(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await lh4({history:new ca0,fuzzyServer:H.fuzzyServer,settingsStorage:H.settingsStorage,threadService:H.threadService,skillService:H.skillService,configService:H.configService,secretStorage:H.secretStorage,internalAPIClient:i5,threadPool:f,createSystemPromptDeps:async()=>Qo4(H),ideClient:QJ,mcpService:H.mcpService,toolboxService:H.toolboxService,mcpTrustHandler:r,updateService:W0,pluginPlatform:H.pluginPlatform,pluginService:H.pluginService},{initialServerStatus:H.serverStatus,stdout:process.stdout,hasAPIKeyAtStartup:H.hasAPIKeyAtStartup,ampURL:J.ampURL,startupThreadID:L0,showJetBrainsInstaller:c,showIdePickerHint:s,openThreadSwitcher:Z.openThreadSwitcher,inspector:Z.inspector,inspectorPort:Z.inspectorPort,jetbrainsMode:Z.jetbrains,clientId:ma4,logFile:{path:Y},sessionState:w0,freeTierStatusPromise:p,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-04-13T05:02:54.540Z"},(e)=>new a01({...e,threadPool:e.threadPool},(K0)=>new x61({...K0,threadState:K0.threadState}))),K("runMainThread:mountApp-returned",z),d)await d}finally{await f.dispose().catch((e)=>{_.error("Failed to dispose thread pool during shutdown",e)})}await H.asyncDispose(),K("runMainThread:dependencies.asyncDispose",X),process.exit(0)}async function T3(J){if(_.info("Initializing CLI context",{argv:process.argv,nodeEnv:"production",hasAmpURL:Boolean(process.env.AMP_URL),hasAmpAPIKey:Boolean(process.env.AMP_API_KEY),hasSettingsFile:Boolean(process.env.AMP_SETTINGS_FILE)}),J.interactive)o$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6227
|
+
`);let Z=!!J.execute||!process.stdout.isTTY&&!J.streamJson,Q=process.stdout.isTTY&&process.stderr.isTTY;_.info("Execution mode resolved",{executeMode:Z,stdoutTTY:process.stdout.isTTY,stderrTTY:process.stderr.isTTY,streamJson:J.streamJson,executeFlag:J.execute});let Y=await Bo1({get:async(G)=>{if(G!==qg)return;try{let F=await ta4(z31,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==qg)return;await sa4(aL.dirname(z31),{recursive:!0}),await gb3(z31,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:i50()});Cu1(Y);let X=await WX0({...J,workspaceTrust:{current:!0,changes:Pj0},getHook:process.env.AMP_URL?(G,F)=>{if(G==="url")return Promise.resolve(process.env.AMP_URL);return F()}:void 0});if(J.mcpConfig){let G=await HT4(J.mcpConfig);X=UT4(X,G)}let K=aL.dirname(X.getSettingsFilePath());JW4(Rv,K);let V=await X.get("url","global");if(!V)V=Q7;if(_.info("Resolved Amp URL",{ampURL:V,settingsFile:X.getSettingsFilePath(),workspaceRoot:X.getWorkspaceRootPath()}),!bW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=zf1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:aX0(await pi(J,X))}}function qh3(J){let Z={};for(let Q=0;Q<J.length;Q++){let Y=J[Q];if(Y?.startsWith("--")){let K=Y.slice(2).replace(/-([a-z])/g,(G,F)=>F.toUpperCase()),V=J[Q+1];if(V&&!V.startsWith("--"))Z[K]=V,Q++}}return Z}function Wh3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=aL.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?db3:qa0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Hh3(){oO4();let J=qh3(process.argv),Z=Wh3(process.argv,J),Q=XR4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)i0.level=0;if(lb3(_),_.info("Starting Amp CLI.",{version:"0.0.1776056343-g168e20",buildTimestamp:"2026-04-13T05:02:54.540Z"}),process.platform==="win32"&&pj())zC4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new T1(M3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");if(process.argv.includes("--neo")){await Jb4();return}await Vh3(Q).parseAsync(process.argv)}eq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Hh3().catch(IU)});async function Uh3(J,Z){let Q=J.ampURL.includes("localhost")||J.ampURL.includes("127.0.0.1");if(process.env.AMP_URL&&!Q)await J.settings.set("url",process.env.AMP_URL,"global"),a6.write(`Saving custom server URL to settings: ${process.env.AMP_URL}
|
|
6228
6228
|
`);else if(!bW(J.ampURL))a6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6229
6229
|
`);let Y=process.env.AMP_API_KEY;if(Y)a6.write(`API key found in environment variable, storing...
|
|
6230
6230
|
`),await Z.set("apiKey",Y,J.ampURL),a6.write(`API key successfully stored.
|