@agiflowai/agent-cli 0.0.4 → 0.0.5
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/CHANGELOG.md +3 -0
- package/dist/{cli-C9n9uE4j.js → cli-CUdEH93F.js} +2 -2
- package/dist/{cli-C9n9uE4j.js.map → cli-CUdEH93F.js.map} +1 -1
- package/dist/cli.js +1 -1
- package/dist/index.js +1 -1
- package/dist/networkLog.js +1 -1
- package/dist/networkLog.js.map +1 -1
- package/dist/package.json +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./cli-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./cli-CUdEH93F.js"),n=require("./AgentHttpService-CYYuD3Wj.js"),c=require("@inquirer/prompts");class m{static async confirm(a,e=!0){return await c.confirm({message:a,default:e})}static async input(a,e){return await c.input({message:a,default:e?.default,validate:e?.validate})}static async password(a,e){return await c.password({message:a,validate:e?.validate})}static async select(a,e,i){return await c.select({message:a,choices:e.map(r=>({name:r,value:r})),default:i})}static async multiSelect(a,e,i){return await c.checkbox({message:a,choices:e.map(r=>({name:r,value:r,checked:i?.includes(r)||!1}))})}static async number(a,e){const i=await c.number({message:a,default:e?.default,validate:r=>r==null?"Value is required":e?.min!==void 0&&r<e.min?`Value must be at least ${e.min}`:e?.max!==void 0&&r>e.max?`Value must be at most ${e.max}`:!0});if(i===void 0)throw new Error("Number input was cancelled or invalid");return i}}exports.BaseCommand=t.BaseCommand;exports.ClaudeCommand=t.ClaudeCommand;exports.ConfigSchema=t.ConfigSchema;exports.ConnectCommand=t.ConnectCommand;exports.DaemonHttpService=t.DaemonHttpService;exports.DaemonWsService=t.DaemonWsService;exports.DeviceCodeAuthService=t.DeviceCodeAuthService;exports.LogoutCommand=t.LogoutCommand;exports.config=t.config;exports.createHeartbeat=t.createHeartbeat;exports.generateDeviceId=t.generateDeviceId;exports.getServerUrl=t.getServerUrl;exports.getSystemInfo=t.getSystemInfo;exports.getWebSocketUrl=t.getWebSocketUrl;exports.httpToWebSocket=t.httpToWebSocket;exports.webSocketToHttp=t.webSocketToHttp;exports.FileSystemUtils=n.FileSystemUtils;exports.Logger=n.Logger;exports.PromptUtils=m;
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/networkLog.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
`),s=[];let o=null,n=null;const i=new Map;for(const y of t)if(y.startsWith("data: ")){const g=y.substring(6).trim();if(g)try{const w=JSON.parse(g);if(w.type==="message_start"&&w.message&&(o=w.message),w.type==="content_block_start"){const L={index:w.index,type:w.content_block.type,id:w.content_block.id,name:w.content_block.name,input:w.content_block.input||{},text:"",partialJson:""};i.set(w.index,L)}if(w.type==="content_block_delta"){const L=i.get(w.index);L&&(w.delta.type==="text_delta"?L.text+=w.delta.text:w.delta.type==="input_json_delta"&&(L.partialJson+=w.delta.partial_json))}if(w.type==="content_block_stop"){const L=i.get(w.index);if(L){if(L.partialJson)try{L.input=JSON.parse(L.partialJson)}catch{}s.push(L)}}w.type==="message_delta"&&w.usage&&(n=w.usage)}catch{}}const a=s.map(y=>y.type==="text"?{type:"text",text:y.text}:y.type==="tool_use"?{type:"tool-invocation",toolInvocation:{toolCallId:y.id,toolName:y.name,args:y.input,state:"call"}}:{type:"text",text:`Unknown content block type: ${y.type}`}),p={id:o?.id||$t.generateId(),role:"assistant",createdAt:new Date().toISOString(),parts:a.length>0?a:[{type:"text",text:""}]},_={...o?.usage||{},...n||{}},l={inputTokens:_.input_tokens||_.inputTokens,outputTokens:_.output_tokens||_.outputTokens,cachedInputTokens:_.cache_read_input_tokens||_.cachedInputTokens,cacheCreationInputTokens:_.cache_creation_input_tokens||_.cacheCreationInputTokens,totalTokens:(_.input_tokens||0)+(_.output_tokens||0),cacheCreation:_.cache_creation,serviceTier:_.service_tier},v=o?.model,k=v?Do.calculateCost(v,l):null;return{message:p,metadata:{model:v,usage:l,cost:k,originalMessageId:o?.id,stopReason:o?.stop_reason,contentLength:a.reduce((y,g)=>g.type==="text"?y+g.text.length:g.type==="tool-invocation"?y+JSON.stringify(g.toolInvocation.args||"").length:y+JSON.stringify(g).length,0),streamingEvents:t.filter(y=>y.startsWith("event:")).length}}}catch(t){return{error:`Failed to parse streaming response: ${t}`,rawText:e}}}static generateId(){return Date.now().toString(36)+Math.random().toString(36).slice(2,10)}}$t.parseStreamingResponse;new Proxy({},{get(r,e){throw new Error(`Module "node:zlib" has been externalized for browser compatibility. Cannot access "node:zlib.${e}" in client code. See https://vite.dev/guide/troubleshooting.html#module-externalized-for-browser-compatibility for more details.`)}});class zs{static parseStreamingResponse(e){try{return e.includes(`
|
|
4
4
|
data:`)||e.startsWith("data:")?this.parseSse(e):this.parseRegular(e)}catch(t){return{error:`Failed to parse Gemini response: ${t}`,rawText:e}}}static parseRegular(e){const t=this.isProbablyGzip(e)||this.hasHighControlCharRatio(e);let s=e;if(t){const o=this.tryGunzip(e);o.ok&&(s=o.text)}try{const o=JSON.parse(s),n=o.response||o,{fullText:i,finishReason:a,texts:p,nextSpeakers:_,reasoningSegments:l}=this.extractCandidateText(n.candidates),v=this.normalizeUsage(n.usageMetadata||o.usageMetadata||o),k=p.length>0?p.map(h=>({type:"text",text:h})):i?[{type:"text",text:i}]:[];return{message:{id:n.responseId||this.generateId(),role:"assistant",createdAt:new Date().toISOString(),parts:k},metadata:{model:n.modelVersion||o.modelVersion,usage:v,responseId:n.responseId,finishReason:a,contentLength:i.length,streamingEvents:0,compressed:t||void 0,nextSpeakers:_.length?_:void 0,reasoningSegments:l.length?l:void 0}}}catch{return{message:{id:this.generateId(),role:"assistant",createdAt:new Date().toISOString(),parts:[{type:"text",text:s}]},metadata:{raw:!0}}}}static parseSse(e){const t=e.split(/\r?\n/);let s,o,n,i;const a=[],p=[],_=[];for(const k of t){if(!k.startsWith("data:"))continue;const h=k.slice(5).trim();if(h)try{const g=JSON.parse(h).response||{};g.modelVersion&&(s=g.modelVersion),g.responseId&&(o=g.responseId),g.usageMetadata&&(i=g.usageMetadata);const w=this.extractCandidateText(g.candidates);!n&&w.finishReason&&(n=w.finishReason),w.texts.length&&a.push(...w.texts),w.nextSpeakers.length&&p.push(...w.nextSpeakers),w.reasoningSegments.length&&_.push(...w.reasoningSegments)}catch{}}const l=a.join(""),v=this.normalizeUsage(i);return{message:{id:o||this.generateId(),role:"assistant",createdAt:new Date().toISOString(),parts:a.length?a.map(k=>({type:"text",text:k})):[]},metadata:{model:s,usage:v,responseId:o,finishReason:n,contentLength:l.length,streamingEvents:t.filter(k=>k.startsWith("data:")).length,nextSpeakers:p.length?p:void 0,reasoningSegments:_.length?_:void 0}}}static extractCandidateText(e){const t=[],s=[],o=[];let n;if(Array.isArray(e))for(const i of e){!n&&i?.finishReason&&(n=i.finishReason);const a=i?.content?.parts||[];if(Array.isArray(a)){for(const p of a)if(p&&typeof p=="object"){if(p.thought===!0)continue;const _=p.text;if(typeof _=="string"&&_.length){const l=_.trim();if(l.startsWith("{")&&l.endsWith("}"))try{const v=JSON.parse(l);if(v&&typeof v=="object"){typeof v.reasoning=="string"&&(o.push(v.reasoning),t.push(v.reasoning)),v.next_speaker&&typeof v.next_speaker=="string"&&s.push(v.next_speaker);continue}}catch{}t.push(_)}}}}return{fullText:t.join(""),finishReason:n,texts:t,finishReasonFound:n,nextSpeakers:s,reasoningSegments:o}}static tryGunzip(e){try{return{ok:!0,text:(void 0)(Buffer.from(e,"latin1")).toString("utf8")}}catch{return{ok:!1,text:e}}}static hasHighControlCharRatio(e){if(!e)return!1;let t=0;const s=Math.min(e.length,256);for(let o=0;o<s;o++){const n=e.charCodeAt(o);n<32&&n!==9&&n!==10&&n!==13&&t++}return t/s>.1}static isProbablyGzip(e){return e.length>=2&&e.charCodeAt(0)===31&&e.charCodeAt(1)===139}static normalizeUsage(e){if(!e||typeof e!="object")return{inputTokens:void 0,outputTokens:void 0,totalTokens:void 0};const t=e.promptTokenCount??e.prompt_tokens,s=e.candidatesTokenCount??e.candidates_tokens,o=e.totalTokenCount??(typeof t=="number"&&typeof s=="number"?t+s:void 0);return{inputTokens:t,outputTokens:s,totalTokens:o}}static generateId(){return Date.now().toString(36)+Math.random().toString(36).slice(2,10)}}zs.parseStreamingResponse;class ue{static parsers=[{name:"Claude (Anthropic)",patterns:[/\/publishers\/anthropic\/models/i,/anthropic\.com/i,/claude\.ai/i,/\/v1\/messages/i],parser:$t},{name:"Google Gemini",patterns:[/generativelanguage\.googleapis\.com/i,/cloudcode-pa\.googleapis\.com/i,/streamGenerateContent/i,/generateContent/i],parser:zs}];static parseStreamingResponse(e,t){const s=ue.getParserForUrl(e);if(!s)return{error:`No parser found for URL: ${e}`,rawText:t,supportedProviders:ue.parsers.map(o=>o.name)};try{const o=s.parseStreamingResponse(t);return o&&typeof o=="object"&&!o.error&&(o.metadata={...o.metadata,parser:ue.getParserNameForUrl(e)}),o}catch(o){return{error:`Parser failed: ${o}`,rawText:t,parser:ue.getParserNameForUrl(e)}}}static getParserForUrl(e){if(!e)return null;for(const t of ue.parsers)if(t.patterns.some(s=>s.test(e)))return t.parser;return null}static getParserNameForUrl(e){if(!e)return"unknown";for(const t of ue.parsers)if(t.patterns.some(s=>s.test(e)))return t.name;return"unknown"}static isSupported(e){return ue.getParserForUrl(e)!==null}static getSupportedProviders(){return ue.parsers.map(e=>e.name)}static registerParser(e,t,s){ue.parsers.push({name:e,patterns:t,parser:s})}}class Cs{LLM_PATTERNS=[/anthropic\.com/i,/claude\.ai/i,/openai\.com/i,/api\.openai\.com/i,/gemini\.google/i,/generativelanguage\.googleapis/i,/cloudcode-pa\.googleapis\.com/i,/bedrock.*\.amazonaws/i,/cognitive\.microsoft/i,/azure\.openai/i,/cohere\.ai/i,/huggingface\.co/i,/replicate\.com/i,/together\.xyz/i,/mistral\.ai/i,/groq\.com/i,/perplexity\.ai/i,/ollama/i,/localhost:\d+\/v1/i,/127\.0\.0\.1:\d+\/v1/i,/\/v1\/chat\/completions/i,/\/v1\/completions/i,/\/v1\/embeddings/i,/\/v1\/messages/i,/\/publishers\/anthropic\/models/i];PROVIDER_MAP=[{pattern:/\/publishers\/anthropic\/models/i,provider:"anthropic"},{pattern:/anthropic\.com|claude\.ai/i,provider:"anthropic"},{pattern:/openai\.com/i,provider:"openai"},{pattern:/gemini\.google|generativelanguage\.googleapis|cloudcode-pa\.googleapis/i,provider:"google"},{pattern:/bedrock.*\.amazonaws/i,provider:"aws-bedrock"},{pattern:/cognitive\.microsoft|azure\.openai/i,provider:"azure"},{pattern:/cohere\.ai/i,provider:"cohere"},{pattern:/huggingface\.co/i,provider:"huggingface"},{pattern:/replicate\.com/i,provider:"replicate"},{pattern:/together\.xyz/i,provider:"together"},{pattern:/mistral\.ai/i,provider:"mistral"},{pattern:/groq\.com/i,provider:"groq"},{pattern:/perplexity\.ai/i,provider:"perplexity"},{pattern:/ollama|localhost:\d+\/v1|127\.0\.0\.1:\d+\/v1/i,provider:"local"}];isLLMCall(e){return e?this.LLM_PATTERNS.some(t=>t.test(e)):!1}detectProvider(e){if(!e)return"unknown";for(const{pattern:t,provider:s}of this.PROVIDER_MAP)if(t.test(e))return s;return"unknown"}getSupportedProviders(){return Array.from(new Set(this.PROVIDER_MAP.map(({provider:e})=>e)))}isProviderSupported(e){return this.getSupportedProviders().includes(e.toLowerCase())}getProviderPattern(e){const t=this.PROVIDER_MAP.find(({provider:s})=>s===e.toLowerCase());return t?t.pattern:null}}class Bo{static enhanceRequest(e){const t=ee.contextData;if(!t)return e;try{const s=JSON.parse(e);s.system?typeof s.system=="string"?s.system=[{type:"text",text:s.system}]:Array.isArray(s.system)||(s.system=[s.system]):s.system=[];const o={type:"text",text:`# Task Context
|
|
5
5
|
|
|
6
|
-
${t}`};return s.system.
|
|
6
|
+
${t}`};return s.system.length>0?s.system.splice(1,0,o):s.system.push(o),JSON.stringify(s)}catch(s){return console.error("Failed to enhance Claude request:",s),e}}}class qo{static enhanceRequest(e){const t=ee.contextData;if(!t)return e;try{const s=JSON.parse(e),o=`# Task Context
|
|
7
7
|
|
|
8
8
|
${t}`;return s.systemInstruction?typeof s.systemInstruction=="string"?s.systemInstruction={parts:[{text:o},{text:s.systemInstruction}]}:s.systemInstruction.parts&&s.systemInstruction.parts.unshift({text:o}):s.systemInstruction={parts:[{text:o}]},JSON.stringify(s)}catch(s){return console.error("Failed to enhance Gemini request:",s),e}}}class Ie{static enhancers=[{name:"Claude (Anthropic)",patterns:[/\/publishers\/anthropic\/models/i,/anthropic\.com/i,/claude\.ai/i,/\/v1\/messages/i],enhancer:Bo},{name:"Google Gemini",patterns:[/generativelanguage\.googleapis\.com/i,/cloudcode-pa\.googleapis\.com/i,/streamGenerateContent/i,/generateContent/i],enhancer:qo}];static enhanceRequest(e,t){const s=Ie.getEnhancerForUrl(e);if(!s)return t;try{return s.enhanceRequest(t)}catch(o){return console.error(`Enhancer failed for ${e}:`,o),t}}static getEnhancerForUrl(e){if(!e)return null;for(const t of Ie.enhancers)if(t.patterns.some(s=>s.test(e)))return t.enhancer;return null}static getEnhancerNameForUrl(e){if(!e)return"unknown";for(const t of Ie.enhancers)if(t.patterns.some(s=>s.test(e)))return t.name;return"unknown"}static isSupported(e){return Ie.getEnhancerForUrl(e)!==null}static getSupportedProviders(){return Ie.enhancers.map(e=>e.name)}static registerEnhancer(e,t,s){Ie.enhancers.push({name:e,patterns:t,enhancer:s})}}class Qt{originalFetch=null;static MAX_LOG_BYTES=256*1024;ctx;extra;constructor(e,t){this.ctx=e,this.extra=t}patch(){if(typeof globalThis.fetch!="function"||this.originalFetch)return;this.originalFetch=globalThis.fetch.bind(globalThis);const e=this.ctx,t=this.extra;globalThis.fetch=async(s,o)=>{const n=Ae.performance.now();let i="";try{i=typeof s=="string"?s:s?.url||""}catch{}const a=(o?.method||s?.method||"GET").toUpperCase();let p="";try{const h=o?.body??s?.body;if(h)if(typeof h=="string")p=h;else if(h instanceof URLSearchParams)p=h.toString();else if(typeof FormData<"u"&&h instanceof FormData){const y={};for(const[g,w]of h.entries())y[g]=typeof w=="string"?w:"[File|Blob]";p=JSON.stringify(y)}else h instanceof Uint8Array||Buffer.isBuffer(h)?p=Buffer.from(h).toString("utf8"):typeof h=="object"&&(p=JSON.stringify(h))}catch{p="<request body error>"}let _=p;if(e.llmProvider.isLLMCall(i)&&p&&p!=="<request body error>")try{_=Ie.enhanceRequest(i,p),_!==p&&o?o.body=_:_!==p&&typeof s=="object"&&s.body&&(s.body=_)}catch(h){console.error("[FetchInstrument] Failed to enhance LLM request:",h)}const l=e.idGenerator(),v=new Date().toISOString();if(t.agentHttpService&&t.sessionId&&t.isValidMessageRequest(i,a,p)){const h={id:l,time:v,transport:"fetch",method:a,url:i,requestBody:p,durationMs:0};t.sendHttpStart(h).catch(y=>{console.error("[FetchInstrument] Failed to send HTTP start:",y)})}let k;try{k=await this.originalFetch(s,o)}catch(h){const y=Ae.performance.now()-n,g={id:l,time:v,transport:"fetch",method:a,url:i,requestBody:p,durationMs:Math.round(y),error:h.message};throw e.handleLogEntry(g),t.agentHttpService&&t.sessionId&&t.isValidMessageRequest(i,a,p)&&t.sendHttpUpdate(g).catch(()=>{}),h}try{const h=Ae.performance.now()-n;let y="",g=0,w=null,L=!1;try{const ie=k.headers.get("content-type")||"";L=/text\/event-stream/i.test(ie);const ae=/^(text\/|application\/(json|xml|javascript))/i.test(ie)||/(json|xml|html)/i.test(ie);if(L){const Te=k.body;if(Te){const[pe,C]=Te.tee(),Y=(async()=>{try{const J=pe.getReader(),j=[];let W=0;for(;;){const{done:u,value:d}=await J.read();if(u)break;j.push(d),W+=d.byteLength}if(y=Buffer.concat(j.map(u=>Buffer.from(u))).toString("utf8"),g=W,e.llmProvider.isLLMCall(i)&&y)try{w=e.responseProcessor(i,y)}catch(u){w={error:`parser_failed: ${u instanceof Error?u.message:String(u)}`}}const Z={id:l,time:v,transport:"fetch",method:a,url:i,requestBody:p,status:k.status,ok:k.ok,durationMs:Math.round(Ae.performance.now()-n),responseBody:y,processedBody:w,bodyBytes:g};return e.handleLogEntry(Z),t.agentHttpService&&t.sessionId&&t.isValidMessageRequest(i,a,p)&&t.sendHttpUpdate(Z).catch(()=>{}),{responseBody:y,processedBody:w,bodyBytes:g}}catch(J){return console.error("Error capturing stream:",J),{responseBody:"<stream capture error>",processedBody:null,bodyBytes:0}}})();k.__capturePromise=Y,k=new Response(C,{status:k.status,statusText:k.statusText,headers:k.headers}),y="<streaming in progress>",w=null}else y="<streaming response not buffered>"}else{const pe=await k.clone().arrayBuffer();g=pe.byteLength;const C=Qt.MAX_LOG_BYTES;ae?pe.byteLength<=C?y=Buffer.from(pe).toString("utf8"):y=`${Buffer.from(pe.slice(0,C)).toString("utf8")}
|
|
9
9
|
...[truncated ${(pe.byteLength-C).toLocaleString()} bytes]`:y=`<${g} bytes binary>`}}catch{y="<response body error>"}if(!L&&e.llmProvider.isLLMCall(i)&&y&&y!=="<response body error>")try{w=e.responseProcessor(i,y)}catch(ie){w={error:`parser_failed: ${ie instanceof Error?ie.message:String(ie)}`}}const U={id:l,time:v,transport:"fetch",method:a,url:i,requestBody:p,status:k.status,ok:k.ok,durationMs:Math.round(h),responseBody:y,processedBody:w,bodyBytes:g};return e.handleLogEntry(U),!L&&t.agentHttpService&&t.sessionId&&t.isValidMessageRequest(i,a,p)&&t.sendHttpUpdate(U).catch(()=>{}),k}catch(h){const y=Ae.performance.now()-n,g={id:l,time:v,transport:"fetch",method:a,url:i,requestBody:p,durationMs:Math.round(y),error:h.message};return e.handleLogEntry(g),t.agentHttpService&&t.sessionId&&t.isValidMessageRequest(i,a,p)&&t.sendHttpUpdate(g).catch(()=>{}),k}}}restore(){this.originalFetch&&(globalThis.fetch=this.originalFetch,this.originalFetch=null)}}class Vo{constructor(e,t,s={isValidMessageRequest:()=>!1,sendHttpStart:async()=>{},sendHttpUpdate:async()=>{}}){this.ctx=e,this.enableHttps=t,this._extra=s}originals=null;patch(){try{let e=function(a,p){try{if(typeof a=="string")return a;if(a instanceof URL)return a.toString();const _=a.protocol||p,l=a.hostname||a.host||"localhost",v=a.port?`:${a.port}`:"",k=a.path||a.pathname||"/";return`${_}//${l}${v}${k}`}catch{return""}},t=function(a,p){return function(l,v){const k=e(l,p),h=(typeof l=="object"&&l.method?l.method:"GET").toUpperCase(),y=Ae.performance.now(),g=n.ctx.idGenerator(),w=new Date().toISOString(),L=[];let U=0,ie=!1;const ae=a(l,C=>{const Y=[];let J=0,j=0;const W=()=>String(C.headers["content-type"]||"");C.on("data",K=>{J+=K.length;const te=W();if(/text\/event-stream/i.test(te))Y.push(K),j+=K.length;else{if(j>=i)return;const u=i-j;K.length<=u?(Y.push(K),j+=K.length):(Y.push(K.subarray(0,u)),j+=u)}}),C.on("end",()=>{const K=Ae.performance.now()-y;let te="";try{const x=W(),O=/text\/event-stream/i.test(x),R=Buffer.concat(Y),q=J>R.length||R.length===i;let V=R;if(!O){const H=String(C.headers["content-encoding"]||"").toLowerCase();if(!q&&V.length&&/(gzip|br|deflate)/.test(H))try{const B=require("node:zlib");H.includes("gzip")?V=B.gunzipSync(R):H.includes("br")?V=B.brotliDecompressSync(R):H.includes("deflate")&&(V=B.inflateSync(R))}catch{}}/text\//i.test(x)||/application\/(json|xml|javascript)/i.test(x)||O?(te=V.toString("utf8"),q&&!O&&(te+=`
|