@sourcegraph/amp 0.0.1775796884-g79426c → 0.0.1775809573-g243cc5
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 +14 -14
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -867,7 +867,7 @@ ${DY5(Z.progress)}
|
|
|
867
867
|
Instead, ask the user to provide the information you need to complete the task, or ask the user to manually edit the secret file.
|
|
868
868
|
</secret-file-instruction>`)}return Z.join(`
|
|
869
869
|
`)}function wY5(J,Z){if(Z?.stripGuidanceFiles&&typeof J==="object"&&J!==null){if("discoveredGuidanceFiles"in J){let{discoveredGuidanceFiles:Y,...X}=J;J=X}}if(Bv0(J)){let Y=J.content??J.contentURL?.startsWith("data:"),X=J.content??J.contentURL?.replace(/^data:[^;,]*;base64,/,"")??"";if(Y){let K=ZN({type:"image",sourcePath:J.absolutePath,source:{type:"base64",mediaType:J.imageInfo.mimeType,data:X}});if(K)return[{type:"text",text:K}]}return[{type:"image",source:Y?{type:"base64",media_type:J.imageInfo.mimeType,data:X}:{type:"url",url:J.contentURL??""}}]}function Q(Y){if(typeof Y==="object"&&Y!==null&&"type"in Y){if(Y.type==="text"&&"text"in Y&&typeof Y.text==="string")return!0;if(Y.type==="image"&&"source"in Y)return!0}return!1}if(Array.isArray(J)&&J.every(k04))return J.map((Y)=>{if(Y.type==="text")return{type:"text",text:Y.text};else if(Y.type==="image")return{type:"image",source:{type:"base64",data:Y.data,media_type:Y.mimeType}};else if(Y.type==="resource"&&"resource"in Y)return{type:"text",text:IH(Y.resource,"resource")};else if(Y.type==="resource_link")return{type:"text",text:IH(Y,"resource_link")};else if(Y.type==="audio")return{type:"text",text:"[audio content]"};else return{type:"text",text:JSON.stringify(Y)}});if(Array.isArray(J)&&J.every(Q))return J;if(typeof J==="string")return[{type:"text",text:J}];if(Array.isArray(J)&&J.every((Y)=>typeof Y==="string"))return[{type:"text",text:J.join(`
|
|
870
|
-
`)}];if(J===void 0)return[{type:"text",text:"undefined"}];if(J===null)return[{type:"text",text:"null"}];return[{type:"text",text:IH(J)}]}function LY5(J){return Array.isArray(J)}function OY5(J){let Z=[];for(let Q of J){if(!LY5(Q.content)||Q.role!=="assistant"){Z.push(Q);continue}let Y=Q.content.filter((X)=>{if(X.type!=="thinking"&&X.type!=="redacted_thinking")return!0;let K="provider"in X?X.provider:void 0;return!K||K==="anthropic"});if(Y.length===0)continue;Z.push({...Q,content:Y})}return Z}function EY5(J,Z){let Q=K2(Z);if(J.type==="web_search_tool_result")return Q.warn("Ignored web search tool result block"),!1;if(J.type==="tool_search_tool_result")return!1;return!0}function MY5(J){return typeof J==="object"&&J!==null&&"type"in J&&"message"in J&&typeof J.type==="string"&&typeof J.message==="string"}function AY5(J){if(MY5(J)){if(J.type==="invalid_request_error"&&J.message.toLowerCase().includes("prompt is too long"))return new ZZ}return J}class Ov0{async*stream({model:J,thread:Z,systemPrompt:Q,tools:Y,configService:X,signal:K,serviceAuthToken:V,requestHeaders:G,reasoningEffort:F,logger:z}){let q=K2(z),W=dm(Z,{agentMode:"default",logger:q}),H=GT(V),U=await WQ({configService:X},K,H?{defaultHeaders:H}:void 0),D=await X.getLatest(K),N=F==="none"?{...D.settings,"anthropic.thinking.enabled":!1}:D.settings,w=N["anthropic.thinking.enabled"]??!0,L=J,O=_H(L),{agentMode:E}=zJ(D.settings,Z),M={id:Z.id,agentMode:E},A=cm(E,L),j=zT(L,{enableLargeContext:A}),I=Z.maxTokens??g04,T={model:O,max_tokens:I,messages:Z5(z90(W)),system:Q,tools:CM(Y),stream:!0},P=w?m04(W):0;if(w)T.thinking={type:"enabled",budget_tokens:P};if(D.settings["anthropic.speed"]==="fast"&&Lv0(L,{enableLargeContext:A}))T.speed="fast";let h=D.settings["anthropic.temperature"];if(h!==void 0&&!w)T.temperature=h;let p=U.messages.stream(T,{signal:K,maxRetries:0,headers:{...FT(N,M,L,nZ(Z)?.messageId,{enableLargeContext:A}),...G??{},...H??{}}}),x=new Map;for await(let k of p){if(k.type==="content_block_start"){let f=Date.now();x.set(k.index,{...x.get(k.index),startTime:x.get(k.index)?.startTime??f})}if(k.type==="content_block_stop"){let f=Date.now();x.set(k.index,{startTime:x.get(k.index)?.startTime??f,finalTime:f})}if(p.currentMessage)yield y04(p.currentMessage,j,q,x)}yield y04(await p.finalMessage(),j,q,x)}}function y04(J,Z,Q,Y=new Map){function X(){let V=J.stop_reason;switch(V){case"end_turn":case"stop_sequence":return{type:"complete",stopReason:"end_turn"};case"tool_use":return{type:"complete",stopReason:"tool_use"};case"max_tokens":case"model_context_window_exceeded":return{type:"error",error:{message:V}};case"refusal":return{type:"error",error:{message:"The model refused to respond to this request. Please retry with a different prompt."}};case"pause_turn":return{type:"error",error:{message:"We received a pause_turn request from the model, but this is not implemented"}};case"compaction":return{type:"error",error:{message:"We received a compaction request from the model, but this is not implemented"}};case null:return{type:"streaming"}}}function K(){if(!J.usage)return;let V=J.model;return{model:V,maxInputTokens:Z??t7(`anthropic/${V}`),inputTokens:J.usage.input_tokens,outputTokens:J.usage.output_tokens,cacheCreationInputTokens:J.usage.cache_creation_input_tokens,cacheReadInputTokens:J.usage.cache_read_input_tokens,totalInputTokens:J.usage.input_tokens+(J.usage.cache_creation_input_tokens??0)+(J.usage.cache_read_input_tokens??0),timestamp:new Date().toISOString()}}return{role:"assistant",messageId:0,content:J.content.flatMap((V,G)=>EY5(V,Q)?[GY5(V,Y.get(G))]:[]),state:X(),usage:K()}}var ID8,FY5,PD8,CD8,F90,Mz,x04="claude-opus-4-6-1m",f04=1e6,g04=32000,_D8,WY5=8000,wv0=4000,ZZ;var f7=Q0(()=>{N04();E1();JZ();GJ();w3();RH();$J();aZ();JN();d4();KT();CH();G90();EB();VT();y3();XK();PM();ID8=Q5.CLAUDE_SONNET_4.name,FY5=Q5.CLAUDE_SONNET_4_5.name,PD8=Q5.CLAUDE_OPUS_4.name,CD8=Q5.CLAUDE_OPUS_4_5.name,F90=Q5.CLAUDE_OPUS_4_6.name,Mz=Q5.CLAUDE_HAIKU_4_5.name;_D8=1e6-g04;ZZ=class ZZ extends Error{constructor(J="Token limit exceeded."){super(J);this.name="TokenLimitError",Object.setPrototypeOf(this,ZZ.prototype)}}});function d04(J){if(J.status==="done"){if(J.result!==null&&typeof J.result==="object"&&"output"in J.result&&typeof J.result.output==="string"){if("truncation"in J.result&&typeof J.result.truncation==="object"&&J.result.truncation!==null&&"prefixLinesOmitted"in J.result.truncation&&typeof J.result.truncation.prefixLinesOmitted==="number"){let Z=J.result.truncation.prefixLinesOmitted;return`--- Truncated ${Z} ${y4(Z,"line")} above this ---
|
|
870
|
+
`)}];if(J===void 0)return[{type:"text",text:"undefined"}];if(J===null)return[{type:"text",text:"null"}];return[{type:"text",text:IH(J)}]}function LY5(J){return Array.isArray(J)}function OY5(J){let Z=[];for(let Q of J){if(!LY5(Q.content)||Q.role!=="assistant"){Z.push(Q);continue}let Y=Q.content.filter((X)=>{if(X.type!=="thinking"&&X.type!=="redacted_thinking")return!0;let K="provider"in X?X.provider:void 0;return!K||K==="anthropic"});if(Y.length===0)continue;Z.push({...Q,content:Y})}return Z}function EY5(J,Z){let Q=K2(Z);if(J.type==="web_search_tool_result")return Q.warn("Ignored web search tool result block"),!1;if(J.type==="tool_search_tool_result")return!1;return!0}function MY5(J){return typeof J==="object"&&J!==null&&"type"in J&&"message"in J&&typeof J.type==="string"&&typeof J.message==="string"}function AY5(J){if(MY5(J)){if(J.type==="invalid_request_error"&&J.message.toLowerCase().includes("prompt is too long"))return new ZZ}return J}class Ov0{async*stream({model:J,thread:Z,systemPrompt:Q,tools:Y,configService:X,signal:K,serviceAuthToken:V,requestHeaders:G,reasoningEffort:F,logger:z}){let q=K2(z),W=dm(Z,{agentMode:"default",logger:q}),H=GT(V),U=await WQ({configService:X},K,H?{defaultHeaders:H}:void 0),D=await X.getLatest(K),N=F==="none"?{...D.settings,"anthropic.thinking.enabled":!1}:D.settings,w=N["anthropic.thinking.enabled"]??!0,L=J,O=_H(L),{agentMode:E}=zJ(D.settings,Z),M={id:Z.id,agentMode:E},A=cm(E,L),j=zT(L,{enableLargeContext:A}),I=Z.maxTokens??g04,T={model:O,max_tokens:I,messages:Z5(z90(W)),system:Q,tools:CM(Y),stream:!0},P=w?m04(W):0;if(w)T.thinking={type:"enabled",budget_tokens:P};if(L.includes("eap"))T.thinking={type:"adaptive"},T.output_config={effort:["low","medium","high","max"].includes(F)?F:"high"};if(D.settings["anthropic.speed"]==="fast"&&Lv0(L,{enableLargeContext:A}))T.speed="fast";let h=D.settings["anthropic.temperature"];if(h!==void 0&&!w)T.temperature=h;let p=U.messages.stream(T,{signal:K,maxRetries:0,headers:{...FT(N,M,L,nZ(Z)?.messageId,{enableLargeContext:A}),...G??{},...H??{}}}),x=new Map;for await(let k of p){if(k.type==="content_block_start"){let f=Date.now();x.set(k.index,{...x.get(k.index),startTime:x.get(k.index)?.startTime??f})}if(k.type==="content_block_stop"){let f=Date.now();x.set(k.index,{startTime:x.get(k.index)?.startTime??f,finalTime:f})}if(p.currentMessage)yield y04(p.currentMessage,j,q,x)}yield y04(await p.finalMessage(),j,q,x)}}function y04(J,Z,Q,Y=new Map){function X(){let V=J.stop_reason;switch(V){case"end_turn":case"stop_sequence":return{type:"complete",stopReason:"end_turn"};case"tool_use":return{type:"complete",stopReason:"tool_use"};case"max_tokens":case"model_context_window_exceeded":return{type:"error",error:{message:V}};case"refusal":return{type:"error",error:{message:"The model refused to respond to this request. Please retry with a different prompt."}};case"pause_turn":return{type:"error",error:{message:"We received a pause_turn request from the model, but this is not implemented"}};case"compaction":return{type:"error",error:{message:"We received a compaction request from the model, but this is not implemented"}};case null:return{type:"streaming"}}}function K(){if(!J.usage)return;let V=J.model;return{model:V,maxInputTokens:Z??t7(`anthropic/${V}`),inputTokens:J.usage.input_tokens,outputTokens:J.usage.output_tokens,cacheCreationInputTokens:J.usage.cache_creation_input_tokens,cacheReadInputTokens:J.usage.cache_read_input_tokens,totalInputTokens:J.usage.input_tokens+(J.usage.cache_creation_input_tokens??0)+(J.usage.cache_read_input_tokens??0),timestamp:new Date().toISOString()}}return{role:"assistant",messageId:0,content:J.content.flatMap((V,G)=>EY5(V,Q)?[GY5(V,Y.get(G))]:[]),state:X(),usage:K()}}var ID8,FY5,PD8,CD8,F90,Mz,x04="claude-opus-4-6-1m",f04=1e6,g04=32000,_D8,WY5=8000,wv0=4000,ZZ;var f7=Q0(()=>{N04();E1();JZ();GJ();w3();RH();$J();aZ();JN();d4();KT();CH();G90();EB();VT();y3();XK();PM();ID8=Q5.CLAUDE_SONNET_4.name,FY5=Q5.CLAUDE_SONNET_4_5.name,PD8=Q5.CLAUDE_OPUS_4.name,CD8=Q5.CLAUDE_OPUS_4_5.name,F90=Q5.CLAUDE_OPUS_4_6.name,Mz=Q5.CLAUDE_HAIKU_4_5.name;_D8=1e6-g04;ZZ=class ZZ extends Error{constructor(J="Token limit exceeded."){super(J);this.name="TokenLimitError",Object.setPrototypeOf(this,ZZ.prototype)}}});function d04(J){if(J.status==="done"){if(J.result!==null&&typeof J.result==="object"&&"output"in J.result&&typeof J.result.output==="string"){if("truncation"in J.result&&typeof J.result.truncation==="object"&&J.result.truncation!==null&&"prefixLinesOmitted"in J.result.truncation&&typeof J.result.truncation.prefixLinesOmitted==="number"){let Z=J.result.truncation.prefixLinesOmitted;return`--- Truncated ${Z} ${y4(Z,"line")} above this ---
|
|
871
871
|
`+J.result.output}return J.result.output}}return p04.default.stringify(J)}var p04;var c04=Q0(()=>{S9();p04=U4(BH(),1)});function Ev0(J){if(J.messages.length===0)return J;return v9(J,(Z)=>{let Q=!0;while(Q&&Z.messages.length>0){Q=!1;let Y=Z.messages.length-1,X=Z.messages[Y];if(X?.role==="assistant"){let K=X.state;if(K.type==="complete"&&K.stopReason==="tool_use"){let G=new Set;for(let F of X.content)if(F.type==="tool_use")G.add(F.id);if(G.size>0)_.debug("Removing trailing assistant message with tool_use stop",{toolUseCount:G.size}),Z.messages.pop(),Q=!0}continue}if(X?.role==="user"&&Y>=1){let K=Z.messages[Y-1];if(K?.role==="assistant"){let V=K.state;if(V.type==="complete"&&V.stopReason==="tool_use"){let F=new Set;for(let W of K.content)if(W.type==="tool_use")F.add(W.id);let z=new Set;for(let W of X.content)if(W.type==="tool_result"&&m8(W.run.status))z.add(W.toolUseID);if(!(F.size>0&&[...F].every((W)=>z.has(W))))_.debug("Removing incomplete tool use sequence from thread for handoff",{expectedCount:F.size,actualCount:z.size}),Z.messages.pop(),Z.messages.pop(),Q=!0}}}}})}var l04=Q0(()=>{GJ();n0();d4()});function IY5(J){let Z=Math.min(J,jY5);return Math.ceil(Z/RY5)}function n04(J){let Z=/@([^\s@]+)/g,Q=[],Y;while((Y=Z.exec(J))!==null){let X=Y[1]?.trim();if(X)Q.push(X)}return Q}function Av0(J,Z){return J.map((Q)=>{let Y=Q.startsWith("file:")?t8(Q,Z):Q;return"@"+fh1(Y)})}function jv0(J,Z){let Q=[];for(let Y of J){let X=Y.trim();if(!X)continue;if(X.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(X)){_.debug("Skipping absolute path from model",{path:X});continue}for(let K of Z)try{let V=a1(K.with({path:`${K.path}/${X}`}));Q.push(V);break}catch{}}return Q}async function a04(J,Z,Q){let Y=[];await Promise.all(J.map(async(z)=>{try{let q=r8(z),W=await Z.stat(q);if(!W.isDirectory){let H=t8(z,Q);Y.push({uri:z,relativePath:H,estimatedTokens:IY5(W.size)})}}catch{}}));let X=J.map((z)=>Y.find((q)=>q.uri===z)).filter((z)=>z!==void 0),K=[],V=[],G=Mv0,F=0;for(let z of X)if(G>=z.estimatedTokens)K.push(z.uri),G-=z.estimatedTokens,F+=z.estimatedTokens;else V.push(z.relativePath);return{filesToMention:K,filesAsPlainPaths:V,totalEstimatedTokens:F}}var i04=10,Mv0=25000,jY5=32768,RY5=3.5;var o04=Q0(()=>{D4();n0();aR0();fX()});var U90=u((rD8,Q14)=>{var H90=Object.prototype.hasOwnProperty,Z14=Object.prototype.toString,r04=Object.defineProperty,s04=Object.getOwnPropertyDescriptor,t04=function(Z){if(typeof Array.isArray==="function")return Array.isArray(Z);return Z14.call(Z)==="[object Array]"},e04=function(Z){if(!Z||Z14.call(Z)!=="[object Object]")return!1;var Q=H90.call(Z,"constructor"),Y=Z.constructor&&Z.constructor.prototype&&H90.call(Z.constructor.prototype,"isPrototypeOf");if(Z.constructor&&!Q&&!Y)return!1;var X;for(X in Z);return typeof X>"u"||H90.call(Z,X)},$14=function(Z,Q){if(r04&&Q.name==="__proto__")r04(Z,Q.name,{enumerable:!0,configurable:!0,value:Q.newValue,writable:!0});else Z[Q.name]=Q.newValue},J14=function(Z,Q){if(Q==="__proto__"){if(!H90.call(Z,Q))return;else if(s04)return s04(Z,Q).value}return Z[Q]};Q14.exports=function J(){var Z,Q,Y,X,K,V,G=arguments[0],F=1,z=arguments.length,q=!1;if(typeof G==="boolean")q=G,G=arguments[1]||{},F=2;if(G==null||typeof G!=="object"&&typeof G!=="function")G={};for(;F<z;++F)if(Z=arguments[F],Z!=null){for(Q in Z)if(Y=J14(G,Q),X=J14(Z,Q),G!==X){if(q&&X&&(e04(X)||(K=t04(X)))){if(K)K=!1,V=Y&&t04(Y)?Y:[];else V=Y&&e04(Y)?Y:{};$14(G,{name:Q,newValue:J(q,V,X)})}else if(typeof X<"u")$14(G,{name:Q,newValue:X})}}return G}});var Y14=u((sD8,PY5)=>{PY5.exports={name:"gaxios",version:"7.1.2",description:"A simple common HTTP client specifically for Google APIs and services.",main:"build/cjs/src/index.js",types:"build/cjs/src/index.d.ts",files:["build/"],exports:{".":{import:{types:"./build/esm/src/index.d.ts",default:"./build/esm/src/index.js"},require:{types:"./build/cjs/src/index.d.ts",default:"./build/cjs/src/index.js"}}},scripts:{lint:"gts check --no-inline-config",test:"c8 mocha build/esm/test","presystem-test":"npm run compile","system-test":"mocha build/esm/system-test --timeout 80000",compile:"tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs",fix:"gts fix",prepare:"npm run compile",pretest:"npm run compile",webpack:"webpack","prebrowser-test":"npm run compile","browser-test":"node build/browser-test/browser-test-runner.js",docs:"jsdoc -c .jsdoc.js","docs-test":"linkinator docs","predocs-test":"npm run docs","samples-test":"cd samples/ && npm link ../ && npm test && cd ../",prelint:"cd samples; npm link ../; npm install",clean:"gts clean"},repository:"googleapis/gaxios",keywords:["google"],engines:{node:">=18"},author:"Google, LLC",license:"Apache-2.0",devDependencies:{"@babel/plugin-proposal-private-methods":"^7.18.6","@types/cors":"^2.8.6","@types/express":"^5.0.0","@types/extend":"^3.0.1","@types/mocha":"^10.0.10","@types/multiparty":"4.2.1","@types/mv":"^2.1.0","@types/ncp":"^2.0.1","@types/node":"^22.0.0","@types/sinon":"^17.0.0","@types/tmp":"0.2.6",assert:"^2.0.0",browserify:"^17.0.0",c8:"^10.0.0",cors:"^2.8.5",express:"^5.0.0",gts:"^6.0.0","is-docker":"^3.0.0",jsdoc:"^4.0.0","jsdoc-fresh":"^4.0.0","jsdoc-region-tag":"^3.0.0",karma:"^6.0.0","karma-chrome-launcher":"^3.0.0","karma-coverage":"^2.0.0","karma-firefox-launcher":"^2.0.0","karma-mocha":"^2.0.0","karma-remap-coverage":"^0.1.5","karma-sourcemap-loader":"^0.4.0","karma-webpack":"^5.0.1",linkinator:"^6.1.2",mocha:"^11.1.0",multiparty:"^4.2.1",mv:"^2.1.1",ncp:"^2.0.0",nock:"^14.0.0-beta.13","null-loader":"^4.0.0","pack-n-play":"^3.0.0",puppeteer:"^24.0.0",sinon:"^21.0.0","stream-browserify":"^3.0.0",tmp:"0.2.5","ts-loader":"^9.5.2",typescript:"^5.8.3",webpack:"^5.35.0","webpack-cli":"^6.0.1"},dependencies:{extend:"^3.0.2","https-proxy-agent":"^7.0.1","node-fetch":"^3.3.2"}}});var K14=u((tD8,X14)=>{var CY5=Y14();X14.exports={pkg:CY5}});var Pv0=u((VK)=>{var G14=VK&&VK.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(VK,"__esModule",{value:!0});VK.GaxiosError=VK.GAXIOS_ERROR_SYMBOL=void 0;VK.defaultErrorRedactor=F14;var V14=G14(U90()),_Y5=G14(K14()),Rv0=_Y5.default.pkg;VK.GAXIOS_ERROR_SYMBOL=Symbol.for(`${Rv0.name}-gaxios-error`);class Iv0 extends Error{config;response;code;status;error;[VK.GAXIOS_ERROR_SYMBOL]=Rv0.version;static[Symbol.hasInstance](J){if(J&&typeof J==="object"&&VK.GAXIOS_ERROR_SYMBOL in J&&J[VK.GAXIOS_ERROR_SYMBOL]===Rv0.version)return!0;return Function.prototype[Symbol.hasInstance].call(Iv0,J)}constructor(J,Z,Q,Y){super(J,{cause:Y});if(this.config=Z,this.response=Q,this.error=Y instanceof Error?Y:void 0,this.config=(0,V14.default)(!0,{},Z),this.response)this.response.config=(0,V14.default)(!0,{},this.response.config);if(this.response){try{this.response.data=TY5(this.config.responseType,this.response?.bodyUsed?this.response?.data:void 0)}catch{}this.status=this.response.status}if(Y instanceof DOMException)this.code=Y.name;else if(Y&&typeof Y==="object"&&"code"in Y&&(typeof Y.code==="string"||typeof Y.code==="number"))this.code=Y.code}static extractAPIErrorFromResponse(J,Z="The request failed"){let Q=Z;if(typeof J.data==="string")Q=J.data;if(J.data&&typeof J.data==="object"&&"error"in J.data&&J.data.error&&!J.ok){if(typeof J.data.error==="string")return{message:J.data.error,code:J.status,status:J.statusText};if(typeof J.data.error==="object"){Q="message"in J.data.error&&typeof J.data.error.message==="string"?J.data.error.message:Q;let Y="status"in J.data.error&&typeof J.data.error.status==="string"?J.data.error.status:J.statusText,X="code"in J.data.error&&typeof J.data.error.code==="number"?J.data.error.code:J.status;if("errors"in J.data.error&&Array.isArray(J.data.error.errors)){let K=[];for(let V of J.data.error.errors)if(typeof V==="object"&&"message"in V&&typeof V.message==="string")K.push(V.message);return Object.assign({message:K.join(`
|
|
872
872
|
`)||Q,code:X,status:Y},J.data.error)}return Object.assign({message:Q,code:X,status:Y},J.data.error)}}return{message:Q,code:J.status,status:J.statusText}}}VK.GaxiosError=Iv0;function TY5(J,Z){switch(J){case"stream":return Z;case"json":return JSON.parse(JSON.stringify(Z));case"arraybuffer":return JSON.parse(Buffer.from(Z).toString("utf8"));case"blob":return JSON.parse(Z.text());default:return Z}}function F14(J){function Q(K){if(!K)return;K.forEach((V,G)=>{if(/^authentication$/i.test(G)||/^authorization$/i.test(G)||/secret/i.test(G))K.set(G,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")})}function Y(K,V){if(typeof K==="object"&&K!==null&&typeof K[V]==="string"){let G=K[V];if(/grant_type=/i.test(G)||/assertion=/i.test(G)||/secret/i.test(G))K[V]="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}function X(K){if(!K||typeof K!=="object")return;else if(K instanceof FormData||K instanceof URLSearchParams||"forEach"in K&&"set"in K)K.forEach((V,G)=>{if(["grant_type","assertion"].includes(G)||/secret/.test(G))K.set(G,"<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")});else{if("grant_type"in K)K.grant_type="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("assertion"in K)K.assertion="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.";if("client_secret"in K)K.client_secret="<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>."}}if(J.config){if(Q(J.config.headers),Y(J.config,"data"),X(J.config.data),Y(J.config,"body"),X(J.config.body),J.config.url.searchParams.has("token"))J.config.url.searchParams.set("token","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.");if(J.config.url.searchParams.has("client_secret"))J.config.url.searchParams.set("client_secret","<<REDACTED> - See `errorRedactor` option in `gaxios` for configuration>.")}if(J.response){if(F14({config:J.response.config}),Q(J.response.headers),J.response.bodyUsed)Y(J.response,"data"),X(J.response.data)}return J}});var W14=u((q14)=>{Object.defineProperty(q14,"__esModule",{value:!0});q14.getRetryConfig=SY5;async function SY5(J){let Z=z14(J);if(!J||!J.config||!Z&&!J.config.retry)return{shouldRetry:!1};Z=Z||{},Z.currentRetryAttempt=Z.currentRetryAttempt||0,Z.retry=Z.retry===void 0||Z.retry===null?3:Z.retry,Z.httpMethodsToRetry=Z.httpMethodsToRetry||["GET","HEAD","PUT","OPTIONS","DELETE"],Z.noResponseRetries=Z.noResponseRetries===void 0||Z.noResponseRetries===null?2:Z.noResponseRetries,Z.retryDelayMultiplier=Z.retryDelayMultiplier?Z.retryDelayMultiplier:2,Z.timeOfFirstRequest=Z.timeOfFirstRequest?Z.timeOfFirstRequest:Date.now(),Z.totalTimeout=Z.totalTimeout?Z.totalTimeout:Number.MAX_SAFE_INTEGER,Z.maxRetryDelay=Z.maxRetryDelay?Z.maxRetryDelay:Number.MAX_SAFE_INTEGER;let Q=[[100,199],[408,408],[429,429],[500,599]];if(Z.statusCodesToRetry=Z.statusCodesToRetry||Q,J.config.retryConfig=Z,!await(Z.shouldRetry||kY5)(J))return{shouldRetry:!1,config:J.config};let X=vY5(Z);J.config.retryConfig.currentRetryAttempt+=1;let K=Z.retryBackoff?Z.retryBackoff(J,X):new Promise((V)=>{setTimeout(V,X)});if(Z.onRetryAttempt)await Z.onRetryAttempt(J);return await K,{shouldRetry:!0,config:J.config}}function kY5(J){let Z=z14(J);if(J.config.signal?.aborted&&J.code!=="TimeoutError"||J.code==="AbortError")return!1;if(!Z||Z.retry===0)return!1;if(!J.response&&(Z.currentRetryAttempt||0)>=Z.noResponseRetries)return!1;if(!Z.httpMethodsToRetry||!Z.httpMethodsToRetry.includes(J.config.method?.toUpperCase()||"GET"))return!1;if(J.response&&J.response.status){let Q=!1;for(let[Y,X]of Z.statusCodesToRetry){let K=J.response.status;if(K>=Y&&K<=X){Q=!0;break}}if(!Q)return!1}if(Z.currentRetryAttempt=Z.currentRetryAttempt||0,Z.currentRetryAttempt>=Z.retry)return!1;return!0}function z14(J){if(J&&J.config&&J.config.retryConfig)return J.config.retryConfig;return}function vY5(J){let Q=(J.currentRetryAttempt?0:J.retryDelay??100)+(Math.pow(J.retryDelayMultiplier,J.currentRetryAttempt)-1)/2*1000,Y=J.totalTimeout-(Date.now()-J.timeOfFirstRequest);return Math.min(Q,Y,J.maxRetryDelay)}});var Cv0=u((U14)=>{Object.defineProperty(U14,"__esModule",{value:!0});U14.GaxiosInterceptorManager=void 0;class H14 extends Set{}U14.GaxiosInterceptorManager=H14});var w14=u((HQ)=>{var xY5=HQ&&HQ.__createBinding||(Object.create?function(J,Z,Q,Y){if(Y===void 0)Y=Q;var X=Object.getOwnPropertyDescriptor(Z,Q);if(!X||("get"in X?!Z.__esModule:X.writable||X.configurable))X={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty(J,Y,X)}:function(J,Z,Q,Y){if(Y===void 0)Y=Q;J[Y]=Z[Q]}),fY5=HQ&&HQ.__setModuleDefault||(Object.create?function(J,Z){Object.defineProperty(J,"default",{enumerable:!0,value:Z})}:function(J,Z){J.default=Z}),B14=HQ&&HQ.__importStar||function(J){if(J&&J.__esModule)return J;var Z={};if(J!=null){for(var Q in J)if(Q!=="default"&&Object.prototype.hasOwnProperty.call(J,Q))xY5(Z,J,Q)}return fY5(Z,J),Z};Object.defineProperty(HQ,"__esModule",{value:!0});HQ.req=HQ.json=HQ.toBuffer=void 0;var uY5=B14(P0("http")),bY5=B14(P0("https"));async function N14(J){let Z=0,Q=[];for await(let Y of J)Z+=Y.length,Q.push(Y);return Buffer.concat(Q,Z)}HQ.toBuffer=N14;async function hY5(J){let Q=(await N14(J)).toString("utf8");try{return JSON.parse(Q)}catch(Y){let X=Y;throw X.message+=` (input: ${Q})`,X}}HQ.json=hY5;function gY5(J,Z={}){let Y=((typeof J==="string"?J:J.href).startsWith("https:")?bY5:uY5).request(J,Z),X=new Promise((K,V)=>{Y.once("response",K).once("error",V).end()});return Y.then=X.then.bind(X),Y}HQ.req=gY5});var A14=u((AY)=>{var O14=AY&&AY.__createBinding||(Object.create?function(J,Z,Q,Y){if(Y===void 0)Y=Q;var X=Object.getOwnPropertyDescriptor(Z,Q);if(!X||("get"in X?!Z.__esModule:X.writable||X.configurable))X={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty(J,Y,X)}:function(J,Z,Q,Y){if(Y===void 0)Y=Q;J[Y]=Z[Q]}),mY5=AY&&AY.__setModuleDefault||(Object.create?function(J,Z){Object.defineProperty(J,"default",{enumerable:!0,value:Z})}:function(J,Z){J.default=Z}),E14=AY&&AY.__importStar||function(J){if(J&&J.__esModule)return J;var Z={};if(J!=null){for(var Q in J)if(Q!=="default"&&Object.prototype.hasOwnProperty.call(J,Q))O14(Z,J,Q)}return mY5(Z,J),Z},pY5=AY&&AY.__exportStar||function(J,Z){for(var Q in J)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Z,Q))O14(Z,J,Q)};Object.defineProperty(AY,"__esModule",{value:!0});AY.Agent=void 0;var dY5=E14(P0("net")),L14=E14(P0("http")),cY5=P0("https");pY5(w14(),AY);var Az=Symbol("AgentBaseInternalState");class M14 extends L14.Agent{constructor(J){super(J);this[Az]={}}isSecureEndpoint(J){if(J){if(typeof J.secureEndpoint==="boolean")return J.secureEndpoint;if(typeof J.protocol==="string")return J.protocol==="https:"}let{stack:Z}=Error();if(typeof Z!=="string")return!1;return Z.split(`
|
|
873
873
|
`).some((Q)=>Q.indexOf("(https.js:")!==-1||Q.indexOf("node:https:")!==-1)}incrementSockets(J){if(this.maxSockets===1/0&&this.maxTotalSockets===1/0)return null;if(!this.sockets[J])this.sockets[J]=[];let Z=new dY5.Socket({writable:!1});return this.sockets[J].push(Z),this.totalSocketCount++,Z}decrementSockets(J,Z){if(!this.sockets[J]||Z===null)return;let Q=this.sockets[J],Y=Q.indexOf(Z);if(Y!==-1){if(Q.splice(Y,1),this.totalSocketCount--,Q.length===0)delete this.sockets[J]}}getName(J){if(typeof J.secureEndpoint==="boolean"?J.secureEndpoint:this.isSecureEndpoint(J))return cY5.Agent.prototype.getName.call(this,J);return super.getName(J)}createSocket(J,Z,Q){let Y={...Z,secureEndpoint:this.isSecureEndpoint(Z)},X=this.getName(Y),K=this.incrementSockets(X);Promise.resolve().then(()=>this.connect(J,Y)).then((V)=>{if(this.decrementSockets(X,K),V instanceof L14.Agent)try{return V.addRequest(J,Y)}catch(G){return Q(G)}this[Az].currentSocket=V,super.createSocket(J,Z,Q)},(V)=>{this.decrementSockets(X,K),Q(V)})}createConnection(){let J=this[Az].currentSocket;if(this[Az].currentSocket=void 0,!J)throw Error("No socket was returned in the `connect()` function");return J}get defaultPort(){return this[Az].defaultPort??(this.protocol==="https:"?443:80)}set defaultPort(J){if(this[Az])this[Az].defaultPort=J}get protocol(){return this[Az].protocol??(this.isSecureEndpoint()?"https:":"http:")}set protocol(J){if(this[Az])this[Az].protocol=J}}AY.Agent=M14});var j14=u((HT)=>{var lY5=HT&&HT.__importDefault||function(J){return J&&J.__esModule?J:{default:J}};Object.defineProperty(HT,"__esModule",{value:!0});HT.parseProxyResponse=void 0;var iY5=lY5(px()),D90=(0,iY5.default)("https-proxy-agent:parse-proxy-response");function nY5(J){return new Promise((Z,Q)=>{let Y=0,X=[];function K(){let q=J.read();if(q)z(q);else J.once("readable",K)}function V(){J.removeListener("end",G),J.removeListener("error",F),J.removeListener("readable",K)}function G(){V(),D90("onend"),Q(Error("Proxy connection ended before receiving CONNECT response"))}function F(q){V(),D90("onerror %o",q),Q(q)}function z(q){X.push(q),Y+=q.length;let W=Buffer.concat(X,Y),H=W.indexOf(`\r
|
|
@@ -1163,8 +1163,12 @@ You are a pragmatic, effective software engineer. You take engineering quality s
|
|
|
1163
1163
|
- When two approaches are both correct, prefer the one with fewer new names, helpers, layers, and tests.
|
|
1164
1164
|
- Keep obvious single-use logic inline. Do not extract a helper unless it is reused, hides meaningful complexity, or names a real domain concept.
|
|
1165
1165
|
- A small amount of duplication is better than speculative abstraction.
|
|
1166
|
+
- Avoid over-engineering. Only make changes that are directly requested or clearly necessary. Keep solutions simple and focused.
|
|
1167
|
+
- Don't add features, refactor code, or make "improvements" beyond what was asked. A bug fix doesn't need surrounding code cleaned up. A simple feature doesn't need extra configurability.
|
|
1168
|
+
- Don't add error handling, fallbacks, or validation for scenarios that can't happen. Trust internal code and framework guarantees. Only validate at system boundaries (user input, external APIs).
|
|
1169
|
+
- Don't create helpers, utilities, or abstractions for one-time operations. Don't design for hypothetical future requirements. The right amount of complexity is the minimum needed for the current task.
|
|
1170
|
+
- Default to not adding tests. Add a test only when the user asks, or when the change fixes a subtle bug or protects an important behavioral boundary that existing tests do not already cover. When adding tests, prefer a single high-leverage regression test at the highest relevant layer. Do not add tests for helpers, simple predicates, glue code, or behavior already enforced by types or covered indirectly.
|
|
1166
1171
|
- Do not assume work-in-progress changes in the current thread need backward compatibility; earlier unreleased shapes in the same thread are drafts, not legacy contracts. Preserve old formats only when they already exist outside the current edit, such as persisted data, shipped behavior, external consumers, or an explicit user requirement; if unclear, ask one short question instead of adding speculative compatibility code.
|
|
1167
|
-
- Default to not adding tests. Add a test only when the user asks, or when the change fixes a subtle bug or protects an important behavioral boundary that existing tests do not already cover. When adding tests, prefer a single high-leverage regression test at the highest relevant layer. Do not add tests for helpers, simple predicates, glue code, or behavior already enforced by types or covered indirectly.
|
|
1168
1172
|
|
|
1169
1173
|
## Autonomy and persistence
|
|
1170
1174
|
|
|
@@ -1313,10 +1317,6 @@ ${K?`- When visualizing data for analytics, business intelligence, or data explo
|
|
|
1313
1317
|
- When changing an existing file, use ${F8}. Only use ${A8} for files that do not exist yet.
|
|
1314
1318
|
- Make the smallest reasonable diff. Do not rewrite whole files to change a few lines.
|
|
1315
1319
|
|
|
1316
|
-
# Extended thinking
|
|
1317
|
-
|
|
1318
|
-
Extended thinking adds latency and should only be used when it will meaningfully improve answer quality — typically for problems that require multi-step reasoning. When in doubt, respond directly.
|
|
1319
|
-
|
|
1320
1320
|
# Doing tasks
|
|
1321
1321
|
|
|
1322
1322
|
- NEVER propose changes to code you haven't read. If a user asks about or wants you to modify a file, read it first. Understand existing code before suggesting modifications.
|
|
@@ -4707,11 +4707,11 @@ ${U}`))}},error:(H)=>{if(!W)W=!0,G(Error(`Failed to spawn brew: ${H.message}`))}
|
|
|
4707
4707
|
${U}`;if(X==="pnpm"&&U.includes("Unable to find the global bin directory"))D+=`
|
|
4708
4708
|
|
|
4709
4709
|
Hint: Try running "pnpm setup" to configure pnpm global directory, or use npm instead:
|
|
4710
|
-
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(H)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${H.message}`))},complete:()=>{if(!q)q=!0,V()}})})}n0();n0();TN();async function GX0(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=FC4(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 EY3="https://static.ampcode.com/cli/cli-version.txt";async function FX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${EY3}?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=FC4(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 MY3=604800000;function GC4(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>MY3)return{ageMs:Q};return null}function FC4(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 Mo0(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?gz(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function Ao0(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 hz(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 hz(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 VX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await FX0(J):await GX0(J,hj());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!==Bo0()){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 hz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}TN();import{stderr as kq}from"node:process";function zC4(J){let Z=new eN().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 zo0(Y.force||!1,Y.verbose||!1,"0.0.
|
|
4710
|
+
npm install -g @sourcegraph/amp`;G(Error(D))}},error:(H)=>{if(!q)q=!0,G(Error(`Failed to spawn ${X}: ${H.message}`))},complete:()=>{if(!q)q=!0,V()}})})}n0();n0();TN();async function GX0(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=FC4(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 EY3="https://static.ampcode.com/cli/cli-version.txt";async function FX0(J){let Z=new AbortController,Q=setTimeout(()=>Z.abort(),5000);try{let Y=await fetch(`${EY3}?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=FC4(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 MY3=604800000;function GC4(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>MY3)return{ageMs:Q};return null}function FC4(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 Mo0(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?gz(Q):void 0;return{sha:Y,age:X}}catch{return null}}E1();function Ao0(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 hz(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 hz(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 VX0(),W=q==="binary"||q==="brew";K.debug("checking",{currentVersion:J,mode:z,packageManager:q,isBinaryDistribution:W});let H=W?await FX0(J):await GX0(J,hj());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!==Bo0()){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 hz(5000),Y.next("hidden"),G.unsubscribe(),Y.complete()}}),{state:X}}TN();import{stderr as kq}from"node:process";function zC4(J){let Z=new eN().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 zo0(Y.force||!1,Y.verbose||!1,"0.0.1775809573-g243cc5"),process.exit()});J.addCommand(Z,{hidden:!0});let Q=new eN("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 AY3(Y.targetVersion)});J.addCommand(Q)}async function AY3(J){let Q=process.platform==="win32"&&bj()?{currentExecutablePath:process.execPath}:void 0;if(process.env.AMP_SKIP_UPDATE_CHECK==="1")kq.write(l0.yellow(`Note: AMP_SKIP_UPDATE_CHECK=1 is set, which disables automatic update checking. Manual updates will still work.
|
|
4711
4711
|
|
|
4712
4712
|
`));try{if(!J){kq.write(l0.blue(`Checking for updates...
|
|
4713
|
-
`));let{hasUpdate:K,latestVersion:V}=bj()?await FX0("0.0.
|
|
4714
|
-
`));let z=await yw("0.0.
|
|
4713
|
+
`));let{hasUpdate:K,latestVersion:V}=bj()?await FX0("0.0.1775809573-g243cc5"):await GX0("0.0.1775809573-g243cc5",hj());if(!K){let G=Mo0("0.0.1775809573-g243cc5"),F=G?.age?`released ${G.age} ago`:`built ${gz(new Date("2026-04-10T08:29:56.283Z"))} ago`;kq.write(l0.green(`✓ Amp is already up to date on version ${"0.0.1775809573-g243cc5"} (${F})
|
|
4714
|
+
`));let z=await yw("0.0.1775809573-g243cc5",Q);if(z.warning)kq.write(`
|
|
4715
4715
|
`+l0.yellow(z.warning)+`
|
|
4716
4716
|
`);process.exit(0)}if(!V)kq.write(l0.yellow("[WARN] could not find latest version")),process.exit(0);J=V}kq.write(l0.blue(`Updating to version ${J}...
|
|
4717
4717
|
`)),await ti(J,void 0,(K)=>{kq.write(l0.dim(`Running: ${K}
|
|
@@ -5918,7 +5918,7 @@ ${X}`,Z);this.line=Q,this.column=Y,this.codeblock=X}}/*!
|
|
|
5918
5918
|
`),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 C(q.slice(1,-1),new g({color:Y.app.keybind,bold:!0})));else K.push(new C(q,new g({color:Q.colorScheme.foreground})));if(V<X.length-1)K.push(new C(`
|
|
5919
5919
|
`))}return new p0({decoration:{color:Q.colorScheme.background,border:Y4.all(new Z4(Y.app.keybind,1,"rounded"))},child:new d0({padding:C0.symmetric(0,1),child:new J0({text:new C(void 0,void 0,K)})})})}}class O11 extends w2{chartData;highlightIndex;showAxes;colors;constructor({key:J,chartData:Z,highlightIndex:Q=null,showAxes:Y=!0,colors:X=HF0}){super(J?{key:J}:{});this.chartData=Z,this.highlightIndex=Q,this.showAxes=Y,this.colors=X}createRenderObject(){return new w11({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 Em4(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 yC3(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 xC3(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 fC3(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 uC3(J,Z,Q,Y,X,K,V){let G;try{let D=f1.of(J),B=x0.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 C(B,H,void 0,DX0(D),()=>{l3(J,D)});if(Y.length<=1){if(W.push(new C(`${Z.label}: `,F)),Z.link)W.push(U(Z.link,K(Z.value)));else W.push(new C(K(Z.value),z));if(Z.meta)W.push(new C(` (${Z.meta})`,q))}else{let D=V==="stacked-bar"||V==="stacked-area";W.push(new C(`${Z.label}
|
|
5920
5920
|
`,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 C("● ",new g({color:O}))),W.push(new C(`${w.name}: `,q)),L.link)W.push(U(L.link,K(L.value)));else W.push(new C(K(L.value),z));if(N<Y.length-1||D)W.push(new C(`
|
|
5921
|
-
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),z))}return new p0({decoration:{color:G.background,border:Y4.all(new Z4(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}rD();n0();S9();ME();T7();y3();x2();kd();fX();tZ();GY();ZQ();yA();d4();rg();dP();E1();n0();tZ();class E11{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.1775796884-g79426c"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await p40(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 IL extends g0{props;constructor(J){super();this.props=J}createState(){return new Mm4}}class Mm4 extends h0{_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 Am4 extends h0{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=x0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Y4.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 D1({children:[new p0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new c1({child:F})]}),q=new p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let H=new p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new p0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new b0({children:[q,new I0({height:1}),z,new k5,H]})})}}class ea extends g0{props;constructor(J){super();this.props=J}createState(){return new Am4}}ZQ();class jm4 extends h0{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>=bV)return!1;let Z=await VL(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=x0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new mU({controller:this.controller,triggers:[new oK],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 p0({constraints:new M1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new p0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new c1({child:z}),new I0({height:1}),W];return new p0({decoration:{border:Y4.all(new Z4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new b0({children:H})})}}class M11 extends g0{props;constructor(J){super();this.props=J}createState(){return new jm4}}function Rm4(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 A11 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)=>Rm4(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=x0.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:D1.end([new J0({text:new C(B,new g({color:U}))})])});return new p0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new c1({child:new J0({text:new C(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(Rm4(X.pubDate),Q)]})})}})}}QB();class j11 extends g0{createState(){return new Im4}}class Im4 extends h0{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=x0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function bC3(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 R11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function hC3(J,Z,Q,Y){return[R11("+",J,Y.success),k5.horizontal(1),R11("~",Z,Y.warning),k5.horizontal(1),R11("-",Q,Y.destructive)]}function gC3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class DF0 extends g0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Pm4}}class Pm4 extends h0{spinner=new M5;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=bC3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=x0.of(J),U=new d0({padding:C0.symmetric(0,1),child:new X4({child:new J0({text:new C("",new g({color:H.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:H.colors.primary,dim:!0})),new C(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=k9(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(!gC3(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=x0.of(M),{app:j,colors:I}=A,T=O?j.selectionBackground:void 0,P=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,H0)=>new I0({width:H0,child:D1.end([new J0({text:new C(s,new g({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new ha({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],H0=L.ancestorsAreLast.slice(1);for(let N0 of H0)s.push(new C(d.getAncestorPrefix(N0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,F0=d.getConnectorText(r);s.push(new C(F0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new C("",void 0,s)}))}let m=[],b=F===L.id?new C("(current) ",new g({color:I.success})):G.has(L.id)?new C("(visited) ",new g({color:I.foreground,dim:!0})):null;if(b)m.push(new J0({text:b}));if(ZA(x))m.push(new j11),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 J0({text:new C("[fork] ",new g({color:I.primary}))}))}else if(f)m.push(new J0({text:new C("[handoff] ",new g({color:I.accent}))}));if(m.push(new c1({child:new J0({text:new C(n,new g({color:P})),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(...hC3(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 p0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...m]})})}})}}n0();class tK{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 BF0(J){if(J instanceof tK)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"}}n0();xX();TN();fX();tZ();d4();D4();dP();var P11=U4(BH(),1);import{execSync as kR}from"node:child_process";import{writeFile as uy}from"node:fs/promises";import mC3 from"node:os";import eq from"node:path";var Cm4="c446b2e9b16cdc06df2ec285894d6421",pC3="5ea19563777f4ade8707fc56f7e7a388",dC3="amp-thread-worker",_m4=[{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 cC3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function CL(J){if(!J||!cC3(J.meta))return!1;return J.meta.usesDtw===!0}function C11(J){let Z=new URL(`https://dash.cloudflare.com/${Cm4}/workers/durable-objects/view/${pC3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function _11(J){let Z=new URL(`https://dash.cloudflare.com/${Cm4}/workers/services/view/${dC3}/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 lC3(J,Z){if(gW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function T11(J,Z){let Q=lC3(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 $o(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Jo(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Jo(J){return J.path??M8(J.uri)}function Tm4(J,Z,Q){let Y=$o("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Sm4(J,Z){return T11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
5921
|
+
`))}if(D)W.push(new C(" ",q)),W.push(new C("Total: ",q)),W.push(new C(K(B),z))}return new p0({decoration:{color:G.background,border:Y4.all(new Z4(G.border,1,"rounded"))},child:new J0({text:new C(void 0,void 0,W)})})}rD();n0();S9();ME();T7();y3();x2();kd();fX();tZ();GY();ZQ();yA();d4();rg();dP();E1();n0();tZ();class E11{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.1775809573-g243cc5"},parameters:{metadata:{count:Q}},timestamp:Date.now()*1000}));this.commandCounts.clear();try{let Z=JSON.stringify(J);await p40(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 IL extends g0{props;constructor(J){super();this.props=J}createState(){return new Mm4}}class Mm4 extends h0{_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 Am4 extends h0{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=x0.of(J),{colors:Q,app:Y}=Z,X=this.widget.props.isRequiredArg??!0,K=this.controller.text.trim().length>0,V=!X||K,G=Y4.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 D1({children:[new p0({decoration:{color:Q.background},child:new J0({text:new C(">",new g({color:Q.foreground}))})}),new c1({child:F})]}),q=new p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=[];if(V)W.push(new C("Enter",new g({color:Y.keybind}))),W.push(new C(" to submit, ",new g({color:Q.foreground,dim:!0})));W.push(new C("Esc",new g({color:Y.keybind}))),W.push(new C(" to cancel",new g({color:Q.foreground,dim:!0})));let H=new p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,W)})});return new p0({decoration:{border:G,color:Q.background},padding:C0.all(1),child:new b0({children:[q,new I0({height:1}),z,new k5,H]})})}}class ea extends g0{props;constructor(J){super();this.props=J}createState(){return new Am4}}ZQ();class jm4 extends h0{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>=bV)return!1;let Z=await VL(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=x0.of(J),{colors:Q,app:Y}=Z,K=O4.of(J).size.height,V=Math.max(Math.floor(K*0.5),10),G=new mU({controller:this.controller,triggers:[new oK],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 p0({constraints:new M1({maxHeight:V}),padding:C0.symmetric(1,0),child:F}),q=new p0({padding:C0.symmetric(1,0),child:new J0({text:new C("",void 0,[new C("Command: ",new g({color:Q.foreground})),new C(this.widget.props.commandName,new g({color:Y.command,bold:!0}))])})}),W=new p0({padding:C0.symmetric(1,0),child:new J0({text:this.isConfirmingClearInput?new C("",void 0,[new C("Esc",new g({color:Y.keybind})),new C(" again to clear input",new g({color:Q.foreground,dim:!0}))]):new C("",void 0,[new C("Press ",new g({color:Q.foreground,dim:!0})),new C("Enter",new g({color:Y.keybind})),new C(" to submit, ",new g({color:Q.foreground,dim:!0})),new C("Esc",new g({color:Y.keybind})),new C(" to clear",new g({color:Q.foreground,dim:!0}))])})}),H=[q,new I0({height:1}),new c1({child:z}),new I0({height:1}),W];return new p0({decoration:{border:Y4.all(new Z4(Q.foreground,1,"solid")),color:Q.background},padding:C0.all(1),child:new b0({children:H})})}}class M11 extends g0{props;constructor(J){super();this.props=J}createState(){return new jm4}}function Rm4(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 A11 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)=>Rm4(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=x0.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:D1.end([new J0({text:new C(B,new g({color:U}))})])});return new p0({decoration:W?{color:W}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[new c1({child:new J0({text:new C(X.title,new g({color:H})),overflow:"ellipsis",maxLines:1})}),new I0({width:2}),D(Rm4(X.pubDate),Q)]})})}})}}QB();class j11 extends g0{createState(){return new Im4}}class Im4 extends h0{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=x0.of(J).colors;return new J0({text:new C("●",new g({color:this.isGreen?Q.success:Q.mutedForeground,bold:!0})),maxLines:1})}}function bC3(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 R11(J,Z,Q){return new J0({text:new C(`${J}${Z}`,new g({color:Q})),maxLines:1})}function hC3(J,Z,Q,Y){return[R11("+",J,Y.success),k5.horizontal(1),R11("~",Z,Y.warning),k5.horizontal(1),R11("-",Q,Y.destructive)]}function gC3(J){return typeof J==="object"&&J!==null&&"then"in J&&typeof J.then==="function"}class DF0 extends g0{props;debugLabel="ThreadContinuationPicker";constructor(J){super();this.props=J}createState(){return new Pm4}}class Pm4 extends h0{spinner=new M5;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=bC3(z),W=Math.max(0,...q.map((L)=>L.description.timeAgo.length)),H=x0.of(J),U=new d0({padding:C0.symmetric(0,1),child:new X4({child:new J0({text:new C("",new g({color:H.colors.foreground,dim:!0}),[new C("Alt+W/Ctrl+T",new g({color:H.colors.primary,dim:!0})),new C(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=k9(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(!gC3(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=x0.of(M),{app:j,colors:I}=A,T=O?j.selectionBackground:void 0,P=O?j.selectionForeground:I.foreground,h=I.mutedForeground,p=(s,H0)=>new I0({width:H0,child:D1.end([new J0({text:new C(s,new g({color:h}))})])}),x=Z.threadViewStates[L.id],k=[],f=L.relationshipType==="handoff",d=new ha({connectorColor:I.mutedForeground});if(L.depth>0){let s=[],H0=L.ancestorsAreLast.slice(1);for(let N0 of H0)s.push(new C(d.getAncestorPrefix(N0),new g({color:d.connectorColor,dim:d.connectorDim})));let r=L.isLast?d.elbow:d.tee,F0=d.getConnectorText(r);s.push(new C(F0,new g({color:d.connectorColor,dim:d.connectorDim}))),k.push(new J0({text:new C("",void 0,s)}))}let m=[],b=F===L.id?new C("(current) ",new g({color:I.success})):G.has(L.id)?new C("(visited) ",new g({color:I.foreground,dim:!0})):null;if(b)m.push(new J0({text:b}));if(ZA(x))m.push(new j11),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 J0({text:new C("[fork] ",new g({color:I.primary}))}))}else if(f)m.push(new J0({text:new C("[handoff] ",new g({color:I.accent}))}));if(m.push(new c1({child:new J0({text:new C(n,new g({color:P})),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(...hC3(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 p0({decoration:T?{color:T}:void 0,padding:C0.symmetric(2,0),child:new D1({children:[...k,...m]})})}})}}n0();class tK{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 BF0(J){if(J instanceof tK)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"}}n0();xX();TN();fX();tZ();d4();D4();dP();var P11=U4(BH(),1);import{execSync as kR}from"node:child_process";import{writeFile as uy}from"node:fs/promises";import mC3 from"node:os";import eq from"node:path";var Cm4="c446b2e9b16cdc06df2ec285894d6421",pC3="5ea19563777f4ade8707fc56f7e7a388",dC3="amp-thread-worker",_m4=[{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 cC3(J){return!!J&&typeof J==="object"&&"usesDtw"in J}function CL(J){if(!J||!cC3(J.meta))return!1;return J.meta.usesDtw===!0}function C11(J){let Z=new URL(`https://dash.cloudflare.com/${Cm4}/workers/durable-objects/view/${pC3}/studio`);return Z.searchParams.set("name",J),Z.searchParams.set("jurisdiction","none"),Z.toString()}function _11(J){let Z=new URL(`https://dash.cloudflare.com/${Cm4}/workers/services/view/${dC3}/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 lC3(J,Z){if(gW(J))return`amp dtw-curl ${Z}`;return`AMP_URL=${JSON.stringify(J)} pnpm -C cli cli -- dtw-curl ${Z}`}function T11(J,Z){let Q=lC3(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 $o(J,Z,Q){let Y=`select(.pid == ${Z})`,X=Jo(Q);return`${J==="snapshot"?`tail -n 10000 ${X}`:`tail -f ${X}`} | jq -C '${Y}'`}function Jo(J){return J.path??M8(J.uri)}function Tm4(J,Z,Q){let Y=$o("snapshot",J,Z);return Q?`${Y} | ${Q}`:Y}function Sm4(J,Z){return T11(J,Z).map(({label:Q,command:Y})=>`# ${Q}
|
|
5922
5922
|
${Y}`).join(`
|
|
5923
5923
|
|
|
5924
5924
|
`)}function I11(J){if(J===void 0||!Number.isFinite(J)||J<=0)return"n/a";return`${gz(J)} ago (\`${new Date(J).toISOString()}\`)`}function iC3(J){if(!J)return"n/a";let Z=Date.parse(J);if(!Number.isFinite(Z))return`\`${J}\``;return I11(Z)}function PL(J){if(J===void 0||J===null)return"n/a";return`\`${String(J)}\``}function NF0(J,Z="#"){let{thread:Q,threadViewState:Y}=J,X=(V)=>`${Z} ${V}`,K=[X("Thread"),`- ID: \`${Q.id}\``,`- Title: ${b10(Q)}`,`- URL: \`${ZH(new URL(J.ampURL),Q.id).toString()}\``,`- Created: ${I11(Q.created)}`,`- Agent mode: ${PL(Q.agentMode)}`,`- Effective mode: \`${J.effectiveAgentMode}\``,`- DTW backed: ${CL(Q)?"yes":"no"}`,`- Executor type: ${PL(Q.meta?.executorType)}`,`- Messages: \`${Q.messages.length}\` total / \`${z8(Q)}\` human / \`${Q.queuedMessages?.length??0}\` queued`];if(Q.meta?.status!==void 0)K.push(`- Merge status: ${PL(Q.meta.status??"null")}`);if(Q.meta?.lastKnownAgentState)K.push(`- Last known agent state: \`${Q.meta.lastKnownAgentState.state}\` at ${iC3(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: \`${gW(J.ampURL)?Q7:J.ampURL}\``,`- Thread pool mode: \`${J.threadPoolIsDTW?"dtw":"worker"}\``,`- Connection state: ${PL(J.transportState)}`,`- Connection role: ${PL(J.transportRole)}`,`- Processing: ${J.isProcessing?"yes":"no"}`,`- PID: ${PL(J.pid)}`,`- Client ID: ${PL(J.clientId)}`),J.logFile)K.push(`- Log file: \`${Jo(J.logFile)}\``);if(!Y)return K.push("",X("View State"),"- No live thread view state available."),K.join(`
|
|
@@ -6143,7 +6143,7 @@ ${t.content||""}`:t.content||"",R0=[],o0=t.baseDir.startsWith("file://")?tF0(t.b
|
|
|
6143
6143
|
`),process.exit(1)}process.stdout.write(await Cv3(F.result.displayText)+`
|
|
6144
6144
|
`),process.exit(0)})}TN();import{stdout as _v3}from"node:process";function Tv3({version:J,buildTimestamp:Z,buildType:Q}){let Y=Q==="dev"?"dev":"released",X=Z?new Date(Z):null,K=X&&!Number.isNaN(X.getTime())?`, ${gz(X)} ago`:"";return`${J} (${Y}${Z?` ${Z}`:""}${K})`}function Kl4(J){_v3.write(`${Tv3(J)}
|
|
6145
6145
|
`)}function Vl4(J,Z){J.option("-V, --version","Print the version number and exit",()=>{Kl4(Z),process.exit(0)}),J.command("version").description("Print the version number and exit").action(()=>{Kl4(Z),process.exit(0)})}var ru3=nL.join(vX,"logs","headless.log"),r51=nL.join(Ov,"device-id.json"),_a4=`cli-tui-${ba4(16).toString("hex")}`;async function su3(){for(let J of jE)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(() => U4(qx(),1))}catch{}if(process.env.AMP_PWD)try{process.chdir(process.env.AMP_PWD),delete process.env.AMP_PWD}catch(J){n$.write(`Failed to change directory to ${process.env.AMP_PWD}: ${J}
|
|
6146
|
-
`)}function tu3(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")iJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")iJ("experimental.agentMode",Z.mode)}function pa4(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 eu3(J){try{return await ga4(J,"utf-8")}catch{return J}}async function s51(J,Z,Q){let Y=pa4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!lo(X,S7.HARNESS_SYSTEM_PROMPT)&&!da4(K))throw new _1("You are not allowed to do this.",1);iJ("systemPrompt",await eu3(Y))}function da4(J){return!!(J&&Q10(J))}function lo(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t51(J){return(J.userEmail?N$(J.userEmail):!1)||lo(J.features,S7.DTW_TUI)}function Ta4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new _1("This TUI mode is not enabled for your user;",1)}function e51(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return t51({userEmail:Z.user.email,features:Z.features})}function $b3(J){return J!=="pending"}function Wx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Jb3(J){let Z=Wx(J);if(Z)return Z.id;if(Gz(J))throw Error(J.error.message);throw Error("unreachable")}function Zb3(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 mz0(J){let Y=Zb3(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 _1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Sa4(J){if(!a6.write(J))await iu3(a6,"drain")}var ka4=[{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??mK,description:`Custom settings file path (overrides the default location ${mK})`},{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 ${Ya0})`},{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:n7(),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:$z.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}],va4=(J)=>("deprecated"in J)&&J.deprecated===!0,Qb3=(J)=>("hidden"in J)&&J.hidden===!0,Yb3=(J)=>("default"in J),Xb3=(J)=>("default"in J)?J.default:void 0,ca4=[{name:"toggle-skills-count",entryPoint:Y01}];function Kb3(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 _1(E3.unknownCommand(Q),1,V)}}async function J31(J){return{...J,getThreadEnvironment:WZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new rV(J.fileSystem),generateThreadTitle:W90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>ZJ(J.configService),pluginService:J.pluginService}}function la4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:WZ,filesystem:J.fileSystem,threadService:J.threadService}}var pz0=F1.file(ma4.homedir()),$31=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(pz0,".config");function Vb3(J){return lq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())cq4();else Xp0(Z);let Q=sX0(),Y=Ur0();if((!Q||Y||xC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(TU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(TU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(sX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Zu1("0.0.
|
|
6146
|
+
`)}function tu3(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")iJ("dangerouslyAllowAll",Z.dangerouslyAllowAll);if(J.getOptionValueSourceWithGlobals("mode")==="cli")iJ("experimental.agentMode",Z.mode)}function pa4(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 eu3(J){try{return await ga4(J,"utf-8")}catch{return J}}async function s51(J,Z,Q){let Y=pa4(J,Z);if(!Y)return;let X=_6(Q)?Q.features:[],K=_6(Q)?Q.user.email:void 0;if(!lo(X,S7.HARNESS_SYSTEM_PROMPT)&&!da4(K))throw new _1("You are not allowed to do this.",1);iJ("systemPrompt",await eu3(Y))}function da4(J){return!!(J&&Q10(J))}function lo(J,Z){return J?.some((Q)=>Q.name===Z&&Q.enabled)??!1}function t51(J){return(J.userEmail?N$(J.userEmail):!1)||lo(J.features,S7.DTW_TUI)}function Ta4(J){if(J.dtwEnabled&&!J.hasV2TUIAccess)throw new _1("This TUI mode is not enabled for your user;",1)}function e51(J,Z){if(typeof J==="boolean")return J;if(!_6(Z))return!1;return t51({userEmail:Z.user.email,features:Z.features})}function $b3(J){return J!=="pending"}function Wx(J){if(!_6(J))return null;return{...J.user,features:J.features??[],team:J.workspace??void 0}}function Jb3(J){let Z=Wx(J);if(Z)return Z.id;if(Gz(J))throw Error(J.error.message);throw Error("unreachable")}function Zb3(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 mz0(J){let Y=Zb3(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 _1(`Couldn't connect to the Amp server at ${J}.`,1,Y)}async function Sa4(J){if(!a6.write(J))await iu3(a6,"drain")}var ka4=[{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??mK,description:`Custom settings file path (overrides the default location ${mK})`},{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 ${Ya0})`},{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:n7(),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:$z.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}],va4=(J)=>("deprecated"in J)&&J.deprecated===!0,Qb3=(J)=>("hidden"in J)&&J.hidden===!0,Yb3=(J)=>("default"in J),Xb3=(J)=>("default"in J)?J.default:void 0,ca4=[{name:"toggle-skills-count",entryPoint:Y01}];function Kb3(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 _1(E3.unknownCommand(Q),1,V)}}async function J31(J){return{...J,getThreadEnvironment:WZ,osFileSystem:J.fileSystem,skillService:J.skillService,fileChangeTrackerStorage:new rV(J.fileSystem),generateThreadTitle:W90,deleteThread:(Z)=>J.threadService.delete(Z),getServerStatus:()=>ZJ(J.configService),pluginService:J.pluginService}}function la4(J){return{toolService:J.toolService,configService:J.configService,skillService:J.skillService,getThreadEnvironment:WZ,filesystem:J.fileSystem,threadService:J.threadService}}var pz0=F1.file(ma4.homedir()),$31=process.env.XDG_CONFIG_HOME?F1.file(process.env.XDG_CONFIG_HOME):G1.joinPath(pz0,".config");function Vb3(J){return lq4({playNotificationSound:async(Z)=>{if(J.useNotificationsForService){if(process.platform==="darwin"&&Z==="idle"&&J.isTUIVoiceNotifEnabled())cq4();else Xp0(Z);let Q=sX0(),Y=Ur0();if((!Q||Y||xC4())&&J.config.settings["notifications.system.enabled"]!==!1){if(Z==="idle")process.stdout.write(TU("\x1B]777;notify;Amp;Agent is ready\x1B\\"));else if(Z==="requires-user-input")process.stdout.write(TU("\x1B]777;notify;Amp;Waiting for approval\x1B\\"))}}},windowFocused:()=>Promise.resolve(sX0()),threadService:J.threadService,configService:J.configService,threadViewStates$:J.threadViewStates$})}async function T9(J,Z,Q){let Y=Q?.deferAuth??!1;Zu1("0.0.1775809573-g243cc5");let X=a10({storage:J.settings,secretStorage:J.secrets,workspaceRoot:k0.of(F1.file(process.cwd())),defaultAmpURL:J.ampURL,homeDir:pz0,userConfigDir:$31});Fb4(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...
|
|
6147
6147
|
`);let b=await Gb3(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(ZJ(X).pipe(h5($b3))),F=Y?"pending":await G;if(!Y)_.info("Server status resolved",{status:"ready",isAuthenticated:_6(F),isError:Gz(F),errorMessage:Gz(F)?F.error.message:void 0});let z=G.then((m)=>Jb3(m)),{toolService:q,dispose:W}=xJ0({configService:X}),H=new Map,U=()=>H.clear(),D=new HT0(X,J.settings.getWorkspaceRootPath()),B=Ye1({configService:X,filesystem:P8}),N=ta1({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 H0=(async()=>{let r=new kE(J.secrets),F0=await r.getClientInfo(m,b),N0=n?.scopes??F0?.scopes,L0=tI4();_.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?sI4():rI4(m);let V0=new iR0({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:N0,headlessAuthHandler:e});return _.debug("OAuth provider created",{serverName:m,serverUrl:b,hasManualClientId:!!(n?.clientId??F0?.clientId),willUseDCR:!(n?.clientId??F0?.clientId),scopes:N0,headlessMode:L0,executeMode:J.executeMode}),V0})();return H.set(c,H0),H0}}),w=Wm0({configService:X,filesystem:P8,spawn:t$0}),L;if(J.executeMode){let m=await iG4({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=Hm0({toolService:q,providers:[N,w]});if(Z.jetbrains)LE("JetBrains");else if(Z.ide&&xP4())LE("VS Code");else if(Z.ide&&fP4())LE("Neovim");else if(Z.ide){let m=await su3();if(m){let b=Y40(m.ideName);if(b)LE(b)}}if(J.executeMode)Qu1(!0);let O,E=JJ.status.pipe(w1((m)=>Boolean(m.connected&&m.authenticated&&m.ideName&&du1(m.ideName))),g4()).subscribe((m)=>{if(m){if(!O)O=q.registerTool(lG4)}else O?.dispose(),O=void 0}),M;if(!J.executeMode){let m=await J.settings.get("fuzzy.alwaysIncludePaths")??[];M=new qv(process.cwd(),{alwaysIncludePaths:m},!0)}else M=new class extends qv{async start(){}async query(){return[]}getStats(){return{state:"unstarted",stats:[]}}dispose(){}};let A=new Dk0(I80(X),{maxThreads:200});_.info("Starting Amp background services");let j=Z.takeMeBack?!1:void 0,I=e51(j,F),T=new z01,P=process.env.PLUGINS??"off",h=Z.headless?nu4():void 0,p=h??new dV0({configService:X}),x=p instanceof dV0?p:void 0;if(x)x.pluginExecutorKind=I?"local":"unknown";let k=_T0({configService:X,fileSystem:P8,platform:p,internalPlugins:ca4,pluginFilter:P}),f=no1({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:P8,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 Gb3(J){if(!J.executeMode){if(!await bX0("Would you like to log in to Amp? [(y)es, (n)o]: "))return a6.write(`Login cancelled. Run the command again to retry.
|
|
6148
6148
|
`),!1}return await ia4(J)}async function ia4(J){let Z=ba4(32).toString("hex"),Q=await _v(J.ampURL,Z),Y=new AbortController;try{await _V(Q,Y.signal)}catch(K){_.error("Error opening browser",{error:K})}let X=await _v(J.ampURL,Z,!1);a6.write(`If your browser does not open automatically, visit:
|
|
6149
6149
|
|
|
@@ -6151,7 +6151,7 @@ ${l0.blue.bold(X)}
|
|
|
6151
6151
|
|
|
6152
6152
|
`);try{return await i_4(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}),n$.write(`
|
|
6153
6153
|
Login failed: ${K instanceof Error?K.message:String(K)}
|
|
6154
|
-
`),!1}}function ya4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Fb3(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 _1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!Y7(Y.threadId))throw new _1("Create response did not include a valid thread ID",1);return Y.threadId}function zb3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function qb3(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 _1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!zb3(Q))throw new _1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Wb3(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 Hb3(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 _1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Ub3(J){let Z=new eN().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)Sj(),process.exit(0);let N=B.originalError??B;yR4(N)}),Vl4(Z,{version:"0.0.
|
|
6154
|
+
`),!1}}function ya4(J){if(!J||J.length===0)return;let Z=J.join(" ").trim();return Z.length>0?Z:void 0}async function Fb3(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 _1(`Create request failed (${Q.status}): ${X}`,1)}let Y=await Q.json();if(!Y.threadId||!Y7(Y.threadId))throw new _1("Create response did not include a valid thread ID",1);return Y.threadId}function zb3(J){return typeof J==="object"&&J!==null&&"durableObjectId"in J&&typeof J.durableObjectId==="string"&&J.durableObjectId.length>0}async function qb3(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 _1(`Durable object ID request failed (${Z.status}): ${Y}`,1)}let Q=await Z.json();if(!zb3(Q))throw new _1("Durable object ID response did not include a durableObjectId",1);return Q.durableObjectId}function Wb3(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 Hb3(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 _1(`Spawn request failed (${Z.status}): ${Q}`,1)}}function Ub3(J){let Z=new eN().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)Sj(),process.exit(0);let N=B.originalError??B;yR4(N)}),Vl4(Z,{version:"0.0.1775809573-g243cc5",buildTimestamp:"2026-04-10T08:29:56.283Z",buildType:"'release'"}),Z.addHelpText("after",kP4()),Z.configureHelp({formatHelp:vP4}),Z.command("logout").description("Log out by removing stored API key").action(async(B,N)=>{let w=N.optsWithGlobals(),L=await C3(w);await Mb3(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 C3(w);await Eb3(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 C3(L);await qI4(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 C3(w);await WI4(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",`
|
|
6155
6155
|
Actions:
|
|
6156
6156
|
create Create a new DTW thread and print its ID
|
|
6157
6157
|
add-message <message> Send a user message and wait for message_added
|
|
@@ -6215,8 +6215,8 @@ ${M}
|
|
|
6215
6215
|
|
|
6216
6216
|
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 Db3(J){_.info("[createDTWThreadPool] Creating DTW thread pool",{threadId:J.threadId,ampURL:J.ampURL,workerUrl:process.env.AMP_WORKER_URL});try{let Z=new ga({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:WZ,osFileSystem:J.fileSystem,fileChangeTrackerStorage:new rV(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 Bb3(J){if(J.streamJsonInput)return{userInput:"",stdinInput:null};if(typeof J.execute==="string"){let Z=(await Uy()).trimEnd();return{userInput:J.execute,stdinInput:Z||null}}return{userInput:(await Uy()).trimEnd(),stdinInput:null}}function Nb3(J,Z,Q){if(J.remote&&!Z)throw new _1("The -r/--remote flag requires --execute mode",1,'Use: amp --remote --execute "your message"');if(J.streamJson&&!Z)throw new _1("The --stream-json flag requires --execute mode",1,'Use: amp --execute "your message" --stream-json');if(J.streamJsonInput&&!Z)throw new _1("The --stream-json-input flag requires --execute mode",1,"Use: amp --execute --stream-json --stream-json-input");if(J.streamJsonInput&&!J.streamJson)throw new _1("The --stream-json-input flag requires --stream-json",1,"Use: amp --execute --stream-json --stream-json-input");if(J.stats&&!Z)throw new _1("The --stats flag requires --execute mode",1,'Use: amp --execute "your message" --stats');if(J.archive&&!Z)throw new _1("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 _1("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 _1("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"
|
|
6217
6217
|
Or pipe via stdin: echo "your message" | amp --execute`)}async function dz0(J,Z,Q,Y){let X=process.hrtime.bigint(),K=(e,V0)=>{let i=Number(process.hrtime.bigint()-V0)/1e6,a=bO4();_.info("Startup phase",{phase:e,phaseMs:Math.round(i),sinceMainMs:a===null?void 0:Math.round(a)})},{userInput:V,stdinInput:G}=await Bb3(Z),F=!!Z.streamJson||!!Z.streamJsonThinking;Nb3({...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 J31(H);K("runMainThread:createWorkerDeps",z);let{serverStatus:D}=H;if(!W&&Gz(D)){let e=Gv(Error(D.error.message));if(e.message===E3.networkOffline||e.message===E3.networkTimeout)throw mz0(J.ampURL);throw new _1(E3.invalidAPIKey,1)}let B=_6(D)?D:null,N=B?.user.email,w=da4(N),L=t51({userEmail:N,features:B?.features}),O=Z.takeMeBack?!1:void 0,E=B!==null&&e51(O,B);if(!W)await s51(Q,Z,D);let M=Wx(D),A=M?.features??[],j=M?.team??null,I=pV0(Z,M);if(I instanceof Error)_3(I.message);if((J.executeMode||F)&&p8(Z.mode)&&!w)throw new _1(`Execute mode is not permitted with --mode '${Z.mode}'`,1);if(B&&!EE(Z.mode,N))throw new _1(`Agent mode '${Z.mode}' is only available for Amp employees`,1);if(J.executeMode&&Z.remote)await ru4(V,G,H.configService),await H.asyncDispose(),process.exit(0);if(Z.headless){if(process.env.AMP_EXECUTOR!=="1"&&(!N||!N$(N)))throw new _1("Headless DTW mode is only available for Amp employees",1);let V0=await H.secretStorage.get("apiKey",J.ampURL);if(!V0)throw new _1("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 _1(`Invalid thread ID: ${i}`,1);let a=i?void 0:await Sb3({dependencies:H,visibility:I??void 0,usesThreadActors:Z.threadActors?!0:void 0}),t=i??a?.threadId;if(!t)throw new _1("Failed to resolve headless thread ID",1);let $0=await ZP4(t);if($0.status==="already-running")await H.asyncDispose(),await RU(),process.exit(0);try{await aI4({ampURL:J.ampURL,apiKey:V0,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 $0.release(),await H.asyncDispose()}await RU(),process.exit(0)}let T=J.executeMode?void 0:async(e)=>io(e,"interactive"),P={threadService:H.threadService,workerDeps:U,createThread:async()=>{let e=W?await H.serverStatusPromise:D,V0=await RY0(J.settings,process.cwd(),Wx(e),I);if(V0 instanceof Error)_3(V0.message);return j01(U,{threadMeta:V0?$F(V0):void 0,agentMode:Z.mode,onFirstAssistantMessage:T})},validateThreadOwnership:async(e,V0)=>{if(V0?.nonBlockingOwnershipCheck){xa4(e,H.configService,H.viewerUserIDPromise).catch((i)=>{if(i instanceof _1){if(V0.onOwnershipError){V0.onOwnershipError(i,e);return}IU(i,e);return}_.warn("Failed to validate thread ownership in CLI, allowing to open",{error:i})});return}try{await xa4(e,H.configService,H.viewerUserIDPromise)}catch(i){if(i instanceof _1)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 Db3({ampURL:J.ampURL,configService:H.configService,threadService:H.threadService,mcpService:H.mcpService,clientID:_a4,toolboxService:H.toolboxService,toolService:H.toolService,skillService:H.skillService,fileSystem:H.fileSystem,threadId:Z.threadId,useThreadActors:Z.threadActors?!0:void 0});return rb4(P,Z.threadId,{nonBlockingOwnershipCheck:Z.nonBlockingThreadOwnershipCheck})}catch(V0){if(V0 instanceof _1)throw V0;throw await IU(V0,Z.threadId),Error("handleError should have called process.exit()")}};if(Z.format==="jsonl")n$.write(`jsonl format is deprecated. Version "0.0.1752148945-gd8844f" or earlier is required to use jsonl format.
|
|
6218
|
-
`),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(),V0=Vb(e),i=await i5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(V0)});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 O01:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await s51(Q,Z,e);let V0=process.hrtime.bigint(),i=e51(O,e),a=_6(e)?t51({userEmail:e.user.email,features:e.features}):!1;Ta4({dtwEnabled:i,hasV2TUIAccess:a});let t=await h(i?"dtw":"worker");if(K("runMainThread:createThreadPool",V0),k.attach(t),V){let $0=await P1(t.threadHandles$);if(!$0)throw new _1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let V0=e instanceof Error?e:Error(String(e));k.setInitError(V0),await IU(e,Z.threadId)});else z=process.hrtime.bigint(),Ta4({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&&lo(B.features,S7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{b=_6(e)&&lo(e.features,S7.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(),Vb3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>b,threadViewStates$:()=>f.threadHandles$.pipe(C4((e)=>{if(!e)return k0.of({});return F5(e.thread$,e.threadViewState$).pipe(w1(([V0,i])=>({[V0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){mu4(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},V0=await aR4({threadPool:f,...e});if(await io(V0,"execute"),Z.archive)await H.threadService.archive(V0,!0),await no(H.threadService,V0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await ou1();let e=await RE({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let V0=e[0];if(V0)JJ.selectConfig(V0)}else s=!0}z=process.hrtime.bigint();let H0=Ao0("0.0.
|
|
6219
|
-
`);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 Qo1({get:async(G)=>{if(G!==Fg)return;try{let F=await ga4(r51,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==Fg)return;await ha4(nL.dirname(r51),{recursive:!0}),await nu3(r51,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:tF()});Yu1(Y);let X=await QX0({...J,workspaceTrust:{current:!0,changes:Lj0},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 hu4(J.mcpConfig);X=gu4(X,G)}let K=nL.dirname(X.getSettingsFilePath());dq4(Ov,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()}),!gW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=rx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:mX0(await pi(J,X))}}function wb3(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 Lb3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=nL.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?ru3:Ya0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Ob3(){uO4();let J=wb3(process.argv),Z=Lb3(process.argv,J),Q=nj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)l0.level=0;if(tu3(_),_.info("Starting Amp CLI.",{version:"0.0.
|
|
6218
|
+
`),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(),V0=Vb(e),i=await i5.getUserFreeTierStatus({},{config:H.configService,signal:AbortSignal.timeout(V0)});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 O01:null,f,d=null;if(k)f=k,d=(async()=>{let e=W?await H.serverStatusPromise:H.serverStatus;await s51(Q,Z,e);let V0=process.hrtime.bigint(),i=e51(O,e),a=_6(e)?t51({userEmail:e.user.email,features:e.features}):!1;Ta4({dtwEnabled:i,hasV2TUIAccess:a});let t=await h(i?"dtw":"worker");if(K("runMainThread:createThreadPool",V0),k.attach(t),V){let $0=await P1(t.threadHandles$);if(!$0)throw new _1("No active thread is available yet.",1);await $0.sendMessage({content:[{type:"text",text:V}]})}})(),d.catch(async(e)=>{let V0=e instanceof Error?e:Error(String(e));k.setInitError(V0),await IU(e,Z.threadId)});else z=process.hrtime.bigint(),Ta4({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&&lo(B.features,S7.TUI_VOICE_NOTIF);if(W)H.serverStatusPromise.then((e)=>{b=_6(e)&&lo(e.features,S7.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(),Vb3({configService:H.configService,threadService:H.threadService,config:n,useNotificationsForService:m,isTUIVoiceNotifEnabled:()=>b,threadViewStates$:()=>f.threadHandles$.pipe(C4((e)=>{if(!e)return k0.of({});return F5(e.thread$,e.threadViewState$).pipe(w1(([V0,i])=>({[V0.id]:i})))}))}),K("runMainThread:createCliNotificationService",z),J.executeMode){mu4(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},V0=await aR4({threadPool:f,...e});if(await io(V0,"execute"),Z.archive)await H.threadService.archive(V0,!0),await no(H.threadService,V0);await H.asyncDispose(),process.exit(0)}let c=!1,s=!1;if(Z.jetbrains||Z.ide){await ou1();let e=await RE({jetbrainsOnly:Z.jetbrains});if(e.length===0){if(Z.jetbrains)c=!await H.configService.get("jetbrains.skipInstall")}else if(e.length===1){let V0=e[0];if(V0)JJ.selectConfig(V0)}else s=!0}z=process.hrtime.bigint();let H0=Ao0("0.0.1775809573-g243cc5",H.settingsStorage,{startDelayMs:3000});K("runMainThread:createUpdateService",z),z=process.hrtime.bigint();let r=new Q01(H.mcpService,J.settings.getWorkspaceRootPath());if(K("runMainThread:createMcpTrustHandler",z),V&&J.executeMode){let e=await P1(f.threadHandles$);if(!e)throw new _1("No active thread is available yet.",1);await e.sendMessage({content:[{type:"text",text:V}]})}z=process.hrtime.bigint();let F0=await cV0();K("runMainThread:loadSessionState",z),_.info("Loaded session state:",F0);let N0={...F0,launchCount:F0.launchCount+1};Wy((e)=>({...e,launchCount:e.launchCount+1}));let L0=Z.threadId&&Y7(Z.threadId)?Z.threadId:void 0;try{if(z=process.hrtime.bigint(),await kh4({history:new fa0,fuzzyServer:H.fuzzyServer,settingsStorage:H.settingsStorage,threadService:H.threadService,skillService:H.skillService,configService:H.configService,secretStorage:H.secretStorage,internalAPIClient:i5,threadPool:f,createSystemPromptDeps:async()=>la4(H),ideClient:JJ,mcpService:H.mcpService,toolboxService:H.toolboxService,mcpTrustHandler:r,updateService:H0,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:_a4,logFile:{path:Y},sessionState:N0,freeTierStatusPromise:p,workspace:j??null,features:A,isDogfooding:w,initialAgentMode:Q.getOptionValueSourceWithGlobals("mode")==="cli"?Z.mode:void 0,buildTimestamp:"2026-04-10T08:29:56.283Z"},(e)=>new y01({...e,threadPool:e.threadPool},(V0)=>new E61({...V0,threadState:V0.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 C3(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)n$.write(`Warning: --interactive flag is deprecated. Interactive mode is now the default unless --execute is used or output is redirected.
|
|
6219
|
+
`);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 Qo1({get:async(G)=>{if(G!==Fg)return;try{let F=await ga4(r51,"utf-8");return JSON.parse(F).installationID}catch{return}},set:async(G,F)=>{if(G!==Fg)return;await ha4(nL.dirname(r51),{recursive:!0}),await nu3(r51,JSON.stringify({installationID:F},null,2),{mode:384})}},{clientType:"cli",platform:tF()});Yu1(Y);let X=await QX0({...J,workspaceTrust:{current:!0,changes:Lj0},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 hu4(J.mcpConfig);X=gu4(X,G)}let K=nL.dirname(X.getSettingsFilePath());dq4(Ov,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()}),!gW(V))_.info("Targeting custom Amp server",{ampURL:V});return X=rx1(X),{executeMode:Z,isTTY:Q,ampURL:V,settings:X,secrets:mX0(await pi(J,X))}}function wb3(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 Lb3(J,Z){let Q=J.includes("--headless")||J.some((X)=>X.startsWith("--headless=")),Y=nL.resolve(Z.logFile??process.env.AMP_LOG_FILE??(Q?ru3:Ya0));return{logLevel:Z.logLevel??process.env.AMP_LOG_LEVEL??"info",logFile:Y}}async function Ob3(){uO4();let J=wb3(process.argv),Z=Lb3(process.argv,J),Q=nj4(Z),Y=process.argv.includes("--no-color"),X=process.argv.includes("--color"),K=process.stdout.isTTY&&process.stderr.isTTY;if(Y||!X&&!K)l0.level=0;if(tu3(_),_.info("Starting Amp CLI.",{version:"0.0.1775809573-g243cc5",buildTimestamp:"2026-04-10T08:29:56.283Z"}),process.platform==="win32"&&bj())eP4();if(parseInt(process.version.slice(1).split(".")[0]??"")<20)throw new _1(E3.nodeVersion(process.version),1,"Please upgrade your Node.js installation from https://nodejs.org");if(process.argv.includes("--neo")){await ku4();return}await Ub3(Q).parseAsync(process.argv)}mq4().startActiveSpan("main",async(J)=>{process.on("exit",()=>J.end()),await Ob3().catch(IU)});async function Eb3(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}
|
|
6220
6220
|
`);else if(!gW(J.ampURL))a6.write(`Logging in to ${new URL(J.ampURL).hostname}
|
|
6221
6221
|
`);let Y=process.env.AMP_API_KEY;if(Y)a6.write(`API key found in environment variable, storing...
|
|
6222
6222
|
`),await Z.set("apiKey",Y,J.ampURL),a6.write(`API key successfully stored.
|