@gencode/agents 0.9.1 → 0.9.2

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 CHANGED
@@ -1,5 +1,11 @@
1
1
  # @gencode/agents
2
2
 
3
+ ## 0.9.2
4
+
5
+ ### Patch Changes
6
+
7
+ - 修复使用 `apiFormat: "anthropic-messages"` 连接 Anthropic Messages API 或兼容网关时,部分网关只在完整 assistant 消息中返回最终文本、或返回格式正常但没有文本和工具调用的空响应,导致 agent 可能丢失最终回复或静默结束的问题。修复后系统会从完整 assistant 消息中补齐最终文本,并将真正的空响应识别为可重试错误交给既有重试逻辑处理,无需调整 API 配置。
8
+
3
9
  ## 0.9.1
4
10
 
5
11
  ### Patch Changes
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ import{A as e,C as t,D as n,E as r,F as i,I as a,M as o,N as s,O as c,P as l,S a
17
17
  `);t.content?t.content.unshift({type:`text`,text:e}):t.content=[{type:`text`,text:e}]}else{let e=s[0].thinkingSignature;e&&e.length>0&&(t[e]=s.map(e=>e.thinking).join(`
18
18
  `))}let c=i.content.filter(e=>e.type===`toolCall`);if(c.length>0){t.tool_calls=c.map(e=>({id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}));let e=c.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}let l=t.content;if(!(l!=null&&l.length>0)&&!t.tool_calls)continue;r.push(t),o=i.role;continue}if(i.role===`toolResult`){let i=[],s=t;for(;s<a.length&&a[s].role===`toolResult`;s+=1){let t=a[s],o=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
19
19
  `),c=t.content.some(e=>e.type===`image`),l={role:`tool`,content:ct(o.length>0?o:`(see attached image)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(l.name=t.toolName),r.push(l),c&&e.input.includes(`image`))for(let e of t.content)e.type===`image`&&i.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}t=s-1,i.length>0?(n.requiresAssistantAfterToolResult&&r.push({role:`assistant`,content:`I have processed the tool results.`}),r.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...i]}),o=`user`):o=`toolResult`}}return r}function ra(e,t){return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:!1}}}))}function ia(e){if(e===null)return`stop`;switch(e){case`stop`:return`stop`;case`length`:return`length`;case`function_call`:case`tool_calls`:return`toolUse`;case`error`:case`content_filter`:return`error`;default:throw Error(`Unhandled stop reason: ${e}`)}}function aa(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||n.includes(`api.z.ai`),i=t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||t===`opencode`||n.includes(`opencode.ai`),a=t===`mistral`||n.includes(`mistral.ai`)||n.includes(`chutes.ai`),o=t===`xai`||n.includes(`api.x.ai`),s=t===`mistral`||n.includes(`mistral.ai`);return{supportsStore:!i,supportsDeveloperRole:!i,supportsReasoningEffort:!o&&!r,supportsUsageInStreaming:!0,maxTokensField:a?`max_tokens`:`max_completion_tokens`,requiresToolResultName:s,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:s,requiresMistralToolIds:s,thinkingFormat:r?`zai`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},supportsStrictMode:!0}}function oa(e){let t=aa(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresMistralToolIds:e.compat.requiresMistralToolIds??t.requiresMistralToolIds,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode}:t}const sa=new Set([`internalservererror`,`ratelimiterror`,`serveroverloadederror`,`serviceunavailableerror`,`gatewaytimeouterror`,`badgatewayerror`]),ca=new Set([`badrequesterror`,`authenticationerror`,`permissiondeniederror`,`notfounderror`]);function la(e){let t=pa(e?.maxAttempts,3),n=ma(e?.initialDelayMs,250),r=ma(e?.maxDelayMs,2e3);return{enabled:e?.enabled??!0,maxAttempts:Math.max(1,t),initialDelayMs:n,maxDelayMs:Math.max(n,r)}}function ua(e,t){return t.initialDelayMs<=0?0:Math.min(t.maxDelayMs,t.initialDelayMs*2**Math.max(0,e-1))}async function da(e,t){if(!(e<=0)){if(t?.aborted)throw Error(`aborted`);await new Promise((n,r)=>{let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`aborted`))},{once:!0})})}}function fa(e){if(_a(e))return!1;let t=ha(e),n=ga(e);if(t?.statusCode!==void 0)return ya(t.statusCode);if(t?.providerCode!==void 0)return va(t.providerCode);if(t?.providerType!==void 0){let e=t.providerType.toLowerCase();if(sa.has(e))return!0;if(ca.has(e))return!1}if(t?.code===`timeout`||t?.code===`network_error`)return!0;if(t?.code===`aborted`||t?.code===`invalid_response`)return!1;let r=ba(t?.message??n);return r===void 0?t?.retryable===!0:ya(r)}function pa(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>0?Math.floor(e):t}function ma(e,t){return typeof e==`number`&&Number.isFinite(e)&&e>=0?Math.floor(e):t}function ha(e){if(!e||typeof e!=`object`)return null;let t=e;return t.retryable===void 0&&t.statusCode===void 0&&t.code===void 0&&t.providerCode===void 0&&t.providerType===void 0?null:{message:typeof t.message==`string`?t.message:void 0,code:t.code,statusCode:t.statusCode,providerCode:t.providerCode,providerType:t.providerType,retryable:t.retryable}}function ga(e){if(typeof e==`string`)return e;if(e instanceof Error&&typeof e.message==`string`||e&&typeof e==`object`&&typeof e.message==`string`)return e.message}function _a(e){return ha(e)?.code===`aborted`?!0:e instanceof Error&&e.name===`AbortError`}function va(e){return/^\d+$/.test(e)?ya(Number(e)):!1}function ya(e){return e===408||e===409||e===425||e===429||e>=500}function ba(e){if(!e||!e.includes(`LLM upstream returned an error payload in a 200 stream:`))return;let t=e.match(/\(([A-Za-z]+Error)\s+(\d{3})\)\s*$/);if(t)return Number(t[2])}const xa=[`请求上下文过大`,`context_length_exceeded`,`context length exceeded`,`maximum context length`,`context window`,`reduce the length of the messages`,`prompt is too long`,`too many tokens`,`context limit`,`token limit`,`input too long`,`request too large`,`上下文`,`token`,`超限`],Sa=[/exceed.*context/i,/超出.*长度/],Ca=[`authentication`,`invalid_api_key`,`permission`,`model_not_found`,`content_policy`,`safety`,`moderation`],wa=[`Emergency compaction after a context-limit error.`,`Preserve: active thread goal requirements, acceptance criteria, file paths, test commands, and unfinished work.`,`Preserve skill names/paths that were loaded.`,`Drop redundant tool output and stale exploration.`].join(` `);var Ta=class{runRecoveriesUsedCount=0;turnRecoveryUsed=!1;turnRecoverySucceeded=!1;resetTurnSlot(){this.turnRecoveryUsed=!1}canAttemptRecovery(){return this.runRecoveriesUsedCount<2&&!this.turnRecoveryUsed}beginTurnRecovery(){return this.canAttemptRecovery()?(this.turnRecoveryUsed=!0,this.runRecoveriesUsedCount+=1,!0):!1}markTurnRecoverySucceeded(){this.turnRecoverySucceeded=!0}wasTurnRecoverySucceeded(){return this.turnRecoverySucceeded}get runRecoveriesUsed(){return this.runRecoveriesUsedCount}};function Ea(e){let t=[],n=e=>{if(typeof e!=`string`)return;let n=e.trim();n&&(t.push(n),Da(n,t))};if(e instanceof Y)n(e.providerMessage),n(e.message);else if(e instanceof Error)n(e.message);else if(typeof e==`string`)n(e);else if(e&&typeof e==`object`){let t=e;n(t.providerMessage),n(t.message)}return t.join(`
20
- `)}function Da(e,t){let n=e.trim();if(!(!n.startsWith(`{`)||!n.endsWith(`}`)))try{let e=JSON.parse(n);typeof e.message==`string`&&e.message.trim()&&t.push(e.message.trim())}catch{}}function Oa(e){let t=e.toLowerCase();return Ca.some(e=>t.includes(e.toLowerCase()))&&!xa.some(e=>t.includes(e.toLowerCase()))?!1:xa.some(e=>t.includes(e.toLowerCase()))?!0:Sa.some(t=>t.test(e))}function ka(e){if(e instanceof Y&&e.statusCode!==void 0)return e.statusCode;if(e&&typeof e==`object`){let t=e.statusCode;if(typeof t==`number`&&Number.isFinite(t))return t;let n=e.code;if(typeof n==`number`&&n===400||typeof n==`string`&&n===`400`)return 400}return ba(Ea(e))}function Aa(e){if(e&&typeof e==`object`){let t=e,n=Ea(e);if(t.retryable===!1&&!Oa(n))return!1}let t=Ea(e),n=ka(e);return t.includes(`请求上下文过大`)?n===void 0||n===400:n===400?Oa(t):!1}function ja(e,t){return t?[`LLM context limit exceeded (HTTP 400). Emergency compaction was attempted but the request still failed.`,`Try /compact, reduce tool output size, or start a new session.`,`Original: ${e}`].join(` `):e}function Ma(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function Na(e=new Date){let t=Ma(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Pa=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Fa=null;function Ia(){return Na()}function La(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Ra(e){return G.join(e,`.aimax`)}function za(e){return{appLogPath:G.join(e,`app.log`),errorLogPath:G.join(e,`errors.log`)}}function Ba(e){let{appLogPath:t,errorLogPath:n}=za(e);mt.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Va(e,t,n){return`[${Ia()}] [${e}] ${t}${La(n)}`}function Ha(e,t,n){process.stderr.write(`${Va(e,t,n)}\n`)}function Ua(e,t,n){if(!Fa){Ha(e,t,n);return}let r=Va(e,t,n),i=mt.getLogger();if(e===Pa.ERROR){i.error(r);return}if(e===Pa.WARN){i.warn(r);return}i.info(r)}function Wa(e){let t=Ra(e);Fa?.dataDir!==e&&(q.mkdirSync(t,{recursive:!0}),Ba(t),Fa={dataDir:e,logDir:t})}const X={info:(e,t)=>Ua(Pa.INFO,e,t),warn:(e,t)=>Ua(Pa.WARN,e,t),error:(e,t)=>Ua(Pa.ERROR,e,t)};function Ga(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}async function Ka(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,contextLimitRecovery:f,onTurnRecordProduced:p}=e;f?.budget.resetTurnSlot();let m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=Pi(),O=Ri(),k=new Set,ee=Promise.resolve(),A,j=!1,M=!1,te=e=>{k.add(e),e.catch(e=>{A??=e}).finally(()=>{k.delete(e)})},ne=async()=>{for(;k.size>0;)await Promise.allSettled([...k]);if(A)throw A},N=t.subscribe(e=>{let t=ee.then(()=>P(e));ee=t.catch(()=>{}),te(t)});async function P(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=mo(`partial`in t?t.partial:void 0)??mo(`message`in t?t.message:void 0)??mo(`message`in e?e.message:void 0),a=ho(t.delta,r,h);r?(h=r,g=r):a&&(g+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){m=``,h=``,g=``,e.usage&&(_=e.usage.input,v=e.usage.output);return}m=fo(e);let r=ho(``,m,g||h);h=m,g=m,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(_=e.usage.input,v=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(_=t.usage.input,v=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=fo(e);await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:t.usage?{input:_,output:v,total:_+v}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(b=eo(t));let r=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:lo(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),a=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),o=new Set(r.map(e=>e.toolCallId));for(let e of T.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)T.delete(e.toolCallId);if(C.push({message:t,toolResults:r}),p&&!n){let e=!!D.signal,n=!!O.signal;if(e&&D.signal.transparentPause||await p(so(oo(t),e||n),n?[]:r.map(co)),e||n)return}return}if(e.type===`tool_execution_start`){g=``,w.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=po(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:lo(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let F=la(d),I=F.enabled?F.maxAttempts:1;f&&(I=Math.max(I,2));try{qa({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=I;e++){let d=C.length;b=void 0,y=void 0;try{if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);X.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await Fi(D,async()=>{await zi(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await ne();let f=D.signal;if(f)throw f;let p=O.signal;if(p)throw p;let h=typeof t.state.error==`string`?t.state.error:void 0,g=b??h;if(g){if(y=go(g),X.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await R(g,y,e,d)||await z(g,d))continue;await B(ja(y,j),g),await s.dispatchProgress(i,{type:`error`,message:ja(y,j)})}y||X.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await ne(),Ai(t)||Mi(t))throw t;if(y=go(t),X.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await R(t,y,e,d)||await z(t,d))continue;await B(ja(y,j),t),await s.dispatchProgress(i,{type:`error`,message:ja(y,j)});break}}}finally{N()}function L(){m=``,h=``,g=``}async function R(e,n,r,a){if(!Xa({error:e,attempt:r,maxAttempts:I,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g}))return!1;let o=ua(r,F);return X.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:I,delayMs:o,error:n}),await ro({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:I,message:n,delayMs:o}),C.length=a,L(),io(t),await da(o,u),!0}async function z(e,n){if(!f||u?.aborted||!Aa(e)||!f.budget.beginTurnRecovery())return!1;j=!0,await f.onPhase(`context_limit_recovery_started`,{turnKind:f.turnKind,runRecoveriesUsed:f.budget.runRecoveriesUsed});let r=await f.reloadHistory();if(r.status!==`compacted`)return await f.onPhase(`context_limit_recovery_skipped`,{turnKind:f.turnKind,reason:r.status===`skipped`?r.reason:`reload_failed`}),!1;await f.onPhase(`context_limit_recovery_ready`,{turnKind:f.turnKind}),C.length=n,L(),io(t);let i=t.state;return typeof i.error==`string`&&(i.error=void 0),y=void 0,b=void 0,!0}async function B(e,t){p&&await p(Qa(e,t),[])}let V=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:V,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let H=(O.signal?``:C.length>0?fo(C[C.length-1].message):``)||m||$a(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;return p&&!Za(C)&&!y&&m.trim().length>0&&await p({role:`assistant`,content:m,timestamp:new Date().toISOString()},[]),!y&&j?(await f?.onPhase(`context_limit_recovery_succeeded`,{turnKind:f.turnKind}),f.budget.markTurnRecoverySucceeded(),M=!0):y&&j&&await f?.onPhase(`context_limit_recovery_failed`,{turnKind:f.turnKind,error:y}),{text:H,inputTokens:_,outputTokens:v,error:y?ja(y,j):void 0,turnRecords:C,contextLimitRecoverySucceeded:M}}function qa(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model;if(!n||typeof n.id!=`string`)return;let r=typeof t?.systemPrompt==`string`?t.systemPrompt:``,i=Array.isArray(t?.messages)?[...t.messages]:[],a=e.continueFromHistory?i:Ja(i,e.message),o=Ya(t?.tools);try{let t=Xi(n,{systemPrompt:r,messages:a,tools:o.length>0?o.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},{});e.eventDispatcher.dispatchProgress(e.sessionId,{type:`model_request`,model:n.id,provider:typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`,systemPrompt:r,tools:o,requestJson:t})}catch{}}function Ja(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function Ya(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function Xa(e){return e.attempt>=e.maxAttempts||!fa(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&fo(e.message).trim().length===0)}function Za(e){return e.some(e=>oo(e.message)!==null||e.toolResults.length>0)}function Qa(e,t){return{role:`assistant`,content:e,stopReason:(t&&typeof t==`object`?t.code:void 0)===`aborted`||e===`aborted`?`aborted`:`error`,errorMessage:e,timestamp:new Date().toISOString()}}function $a(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];for(let e=r.toolResults.length-1;e>=0;e--){let n=r.toolResults[e];if(n.toolName===t&&n.content.trim().length>0)return n.content}}return``}function eo(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:to(t.errorCode),statusCode:no(t.statusCode),providerCode:to(t.providerCode),providerType:to(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function to(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function no(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function ro(e){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`runner`,phase:`llm_turn_retry_scheduled`,message:`retrying transient LLM turn failure`,details:{attempt:e.attempt,nextAttempt:e.attempt+1,maxAttempts:e.maxAttempts,delayMs:e.delayMs,error:e.message}})}function io(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&ao(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function ao(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function oo(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function so(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function co(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function lo(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:uo(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function uo(e){let t=e.indexOf(`
20
+ `)}function Da(e,t){let n=e.trim();if(!(!n.startsWith(`{`)||!n.endsWith(`}`)))try{let e=JSON.parse(n);typeof e.message==`string`&&e.message.trim()&&t.push(e.message.trim())}catch{}}function Oa(e){let t=e.toLowerCase();return Ca.some(e=>t.includes(e.toLowerCase()))&&!xa.some(e=>t.includes(e.toLowerCase()))?!1:xa.some(e=>t.includes(e.toLowerCase()))?!0:Sa.some(t=>t.test(e))}function ka(e){if(e instanceof Y&&e.statusCode!==void 0)return e.statusCode;if(e&&typeof e==`object`){let t=e.statusCode;if(typeof t==`number`&&Number.isFinite(t))return t;let n=e.code;if(typeof n==`number`&&n===400||typeof n==`string`&&n===`400`)return 400}return ba(Ea(e))}function Aa(e){if(e&&typeof e==`object`){let t=e,n=Ea(e);if(t.retryable===!1&&!Oa(n))return!1}let t=Ea(e),n=ka(e);return t.includes(`请求上下文过大`)?n===void 0||n===400:n===400?Oa(t):!1}function ja(e,t){return t?[`LLM context limit exceeded (HTTP 400). Emergency compaction was attempted but the request still failed.`,`Try /compact, reduce tool output size, or start a new session.`,`Original: ${e}`].join(` `):e}function Ma(e){let t=new Intl.DateTimeFormat(`en-CA`,{timeZone:`Asia/Shanghai`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}).formatToParts(e);return Object.fromEntries(t.map(e=>[e.type,e.value]))}function Na(e=new Date){let t=Ma(e),n=String(e.getMilliseconds()).padStart(3,`0`);return`${t.year}-${t.month}-${t.day} ${t.hour}:${t.minute}:${t.second}.${n}`}let Pa=function(e){return e.INFO=`INFO`,e.WARN=`WARN`,e.ERROR=`ERROR`,e}({}),Fa=null;function Ia(){return Na()}function La(e){if(!e)return``;let t=Object.entries(e).filter(([,e])=>e!==void 0).map(([e,t])=>`${e}=${JSON.stringify(t)}`);return t.length>0?` ${t.join(` `)}`:``}function Ra(e){return G.join(e,`.aimax`)}function za(e){return{appLogPath:G.join(e,`app.log`),errorLogPath:G.join(e,`errors.log`)}}function Ba(e){let{appLogPath:t,errorLogPath:n}=za(e);mt.configure({appenders:{appFile:{type:`file`,filename:t,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorFile:{type:`file`,filename:n,maxLogSize:5*1024*1024,backups:3,compress:!0,keepFileExt:!0,layout:{type:`messagePassThrough`}},errorsOnly:{type:`logLevelFilter`,appender:`errorFile`,level:`error`,maxLevel:`fatal`}},categories:{default:{appenders:[`appFile`,`errorsOnly`],level:`info`}}})}function Va(e,t,n){return`[${Ia()}] [${e}] ${t}${La(n)}`}function Ha(e,t,n){process.stderr.write(`${Va(e,t,n)}\n`)}function Ua(e,t,n){if(!Fa){Ha(e,t,n);return}let r=Va(e,t,n),i=mt.getLogger();if(e===Pa.ERROR){i.error(r);return}if(e===Pa.WARN){i.warn(r);return}i.info(r)}function Wa(e){let t=Ra(e);Fa?.dataDir!==e&&(q.mkdirSync(t,{recursive:!0}),Ba(t),Fa={dataDir:e,logDir:t})}const X={info:(e,t)=>Ua(Pa.INFO,e,t),warn:(e,t)=>Ua(Pa.WARN,e,t),error:(e,t)=>Ua(Pa.ERROR,e,t)};function Ga(e,t){if(e===void 0)return;let n=e.replace(/\s+/g,` `).trim();return t===void 0||n.length<=t?n:`${n.slice(0,Math.max(0,t-3))}...`}async function Ka(e){let{agent:t,message:n,continueFromHistory:r=!1,sessionId:i,modelId:a,historyMessages:o,eventDispatcher:s,hooks:c,hookCtx:l,abortSignal:u,retry:d,contextLimitRecovery:f,onTurnRecordProduced:p}=e;f?.budget.resetTurnSlot();let m=``,h=``,g=``,_=0,v=0,y,b,x=0,S=0,C=[],w=new Map,T=new Map,E=new Set,D=Pi(),O=Ri(),k=new Set,ee=Promise.resolve(),A,j=!1,M=!1,te=e=>{k.add(e),e.catch(e=>{A??=e}).finally(()=>{k.delete(e)})},ne=async()=>{for(;k.size>0;)await Promise.allSettled([...k]);if(A)throw A},N=t.subscribe(e=>{let t=ee.then(()=>P(e));ee=t.catch(()=>{}),te(t)});async function P(e){let n=()=>!!O.signal||D.signal?.transparentPause===!0;if(e.type===`message_update`){let t=e.assistantMessageEvent;if(S===0&&(t.type===`text_delta`||t.type===`done`)&&(S=Date.now()),t.type===`text_delta`&&typeof t.delta==`string`){if(n())return;let r=mo(`partial`in t?t.partial:void 0)??mo(`message`in t?t.message:void 0)??mo(`message`in e?e.message:void 0),a=ho(t.delta,r,h);r?(h=r,g=r):a&&(g+=a),a&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:a})}if(t.type===`done`){let e=t.message;if(n()){m=``,h=``,g=``,e.usage&&(_=e.usage.input,v=e.usage.output);return}m=fo(e);let r=ho(``,m,g||h);h=m,g=m,r&&await s.dispatchProgress(i,{type:`stream_text_delta`,text:r}),e.usage&&(_=e.usage.input,v=e.usage.output)}return}if(e.type===`message_end`){let t=e.message;if(t.usage&&(_=t.usage.input,v=t.usage.output),t.role===`assistant`&&Array.isArray(t.content)){let e=t,n=fo(e);!m&&n&&(m=n),await c.dispatch(`assistant_message_end`,{sessionId:i,model:a,assistantText:n,assistantMessage:e,hasToolCalls:e.content.some(e=>e.type===`toolCall`),durationMs:x>0?Math.max(0,Date.now()-x):void 0,usage:t.usage?{input:_,output:v,total:_+v}:void 0},l)}return}if(e.type===`turn_end`){let t=e.message,n=t.stopReason===`error`||t.stopReason===`aborted`;n&&(b=eo(t));let r=(e.toolResults??[]).map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,content:e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),isError:e.isError,toolResultRef:lo(e.content.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i,e.toolCallId,e.toolName)})),a=new Set(t.content.filter(e=>e.type===`toolCall`).map(e=>e.id)),o=new Set(r.map(e=>e.toolCallId));for(let e of T.values())!o.has(e.toolCallId)&&a.has(e.toolCallId)&&r.push(e);for(let e of r)T.delete(e.toolCallId);if(C.push({message:t,toolResults:r}),p&&!n){let e=!!D.signal,n=!!O.signal;if(e&&D.signal.transparentPause||await p(so(oo(t),e||n),n?[]:r.map(co)),e||n)return}return}if(e.type===`tool_execution_start`){g=``,w.set(e.toolCallId,e.args);return}if(e.type===`tool_execution_end`){let n=typeof e.result==`string`?e.result:JSON.stringify(e.result),r=po(e.result),a=e.result&&typeof e.result==`object`?e.result.details:void 0,o=a&&typeof a==`object`?a.toolResultRef:lo(r,i,e.toolCallId,e.toolName),c=w.get(e.toolCallId);if(w.delete(e.toolCallId),D.signal?.transparentPause===!0){t.abort();return}if(O.signal){E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c}));return}T.set(e.toolCallId,{toolCallId:e.toolCallId,toolName:e.toolName,content:r,isError:!!e.isError,...o?{toolResultRef:o}:{}}),E.has(e.toolCallId)||(E.add(e.toolCallId),await s.dispatchProgress(i,{type:`tool_start`,toolCallId:e.toolCallId,name:e.toolName,input:c})),await s.dispatchProgress(i,{type:`tool_end`,toolCallId:e.toolCallId,name:e.toolName,input:c,output:n,isError:e.isError})}}let F=la(d),I=F.enabled?F.maxAttempts:1;f&&(I=Math.max(I,2));try{qa({agent:t,message:n,continueFromHistory:r,sessionId:i,channel:e.channel,eventDispatcher:s});for(let e=1;e<=I;e++){let d=C.length;b=void 0,y=void 0;try{if(await c.dispatch(`llm_input`,{sessionId:i,model:a,prompt:typeof n==`string`?n:JSON.stringify(n),historyMessages:o},l),u?.aborted)throw Error(`aborted`);X.info(`llm turn attempt started`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,continueFromHistory:r,historyMessageCount:o.length,messageMode:typeof n==`string`?`text`:`messages`,messageLength:typeof n==`string`?n.length:void 0,messagesCount:typeof n==`string`?void 0:n.length}),x=Date.now(),await Fi(D,async()=>{await zi(O,async()=>{e>1||r?await t.continue():await t.prompt(n)})}),await ne();let f=D.signal;if(f)throw f;let p=O.signal;if(p)throw p;let h=C.some(e=>e.message.content.some(e=>e.type===`toolCall`||e.type===`text`&&typeof e.text==`string`&&e.text.trim().length>0));!b&&C.length>0&&!h&&m.trim().length===0&&(X.warn(`llm turn produced empty response`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,turnRecordCount:C.length}),b={message:`LLM returned an empty response (no text, no tool calls)`,retryable:!0});let g=typeof t.state.error==`string`?t.state.error:void 0,S=b??g;if(S){if(y=go(S),X.warn(`llm turn attempt completed with provider error`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await R(S,y,e,d)||await z(S,d))continue;await B(ja(y,j),S),await s.dispatchProgress(i,{type:`error`,message:ja(y,j)})}y||X.info(`llm turn attempt completed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,inputTokens:_,outputTokens:v,turnRecordCount:C.length-d,textLength:m.length});break}catch(t){if(await ne(),Ai(t)||Mi(t))throw t;if(y=go(t),X.warn(`llm turn attempt failed`,{sessionId:i,modelId:a,attempt:e,maxAttempts:I,error:y}),await R(t,y,e,d)||await z(t,d))continue;await B(ja(y,j),t),await s.dispatchProgress(i,{type:`error`,message:ja(y,j)});break}}}finally{N()}function L(){m=``,h=``,g=``}async function R(e,n,r,a){if(!Xa({error:e,attempt:r,maxAttempts:I,turnRecords:C,attemptTurnRecordStart:a,finalAssistantText:m,streamedAssistantSnapshot:h,streamedTextSinceBoundary:g}))return!1;let o=ua(r,F);return X.warn(`llm turn retry scheduled`,{sessionId:i,attempt:r,maxAttempts:I,delayMs:o,error:n}),await ro({eventDispatcher:s,sessionId:i,attempt:r,maxAttempts:I,message:n,delayMs:o}),C.length=a,L(),io(t),await da(o,u),!0}async function z(e,n){if(!f||u?.aborted||!Aa(e)||!f.budget.beginTurnRecovery())return!1;j=!0,await f.onPhase(`context_limit_recovery_started`,{turnKind:f.turnKind,runRecoveriesUsed:f.budget.runRecoveriesUsed});let r=await f.reloadHistory();if(r.status!==`compacted`)return await f.onPhase(`context_limit_recovery_skipped`,{turnKind:f.turnKind,reason:r.status===`skipped`?r.reason:`reload_failed`}),!1;await f.onPhase(`context_limit_recovery_ready`,{turnKind:f.turnKind}),C.length=n,L(),io(t);let i=t.state;return typeof i.error==`string`&&(i.error=void 0),y=void 0,b=void 0,!0}async function B(e,t){p&&await p(Qa(e,t),[])}let V=C.length>0?C[C.length-1]?.message:void 0;await c.dispatch(`llm_output`,{sessionId:i,model:a,assistantTexts:m?[m]:[],lastAssistant:V,durationMs:S>0?Math.max(0,Date.now()-S):void 0,usage:{input:_,output:v,total:_+v}},l);let H=(O.signal?``:C.length>0?fo(C[C.length-1].message):``)||m||$a(C,`subagent_spawn`);if(D.signal)throw D.signal;if(O.signal)throw O.signal;return p&&!Za(C)&&!y&&m.trim().length>0&&await p({role:`assistant`,content:m,timestamp:new Date().toISOString()},[]),!y&&j?(await f?.onPhase(`context_limit_recovery_succeeded`,{turnKind:f.turnKind}),f.budget.markTurnRecoverySucceeded(),M=!0):y&&j&&await f?.onPhase(`context_limit_recovery_failed`,{turnKind:f.turnKind,error:y}),{text:H,inputTokens:_,outputTokens:v,error:y?ja(y,j):void 0,turnRecords:C,contextLimitRecoverySucceeded:M}}function qa(e){if(e.channel!==`WEB`)return;let t=e.agent.state,n=t?.model;if(!n||typeof n.id!=`string`)return;let r=typeof t?.systemPrompt==`string`?t.systemPrompt:``,i=Array.isArray(t?.messages)?[...t.messages]:[],a=e.continueFromHistory?i:Ja(i,e.message),o=Ya(t?.tools);try{let t=Xi(n,{systemPrompt:r,messages:a,tools:o.length>0?o.map(e=>({name:e.name,description:e.description,parameters:e.parameters,execute:async()=>({content:[]})})):void 0},{});e.eventDispatcher.dispatchProgress(e.sessionId,{type:`model_request`,model:n.id,provider:typeof n.provider==`string`?n.provider:typeof n.api==`string`?n.api:`unknown`,systemPrompt:r,tools:o,requestJson:t})}catch{}}function Ja(e,t){return typeof t==`string`?[...e,{role:`user`,content:t}]:[...e,...t]}function Ya(e){return Array.isArray(e)?e.filter(e=>typeof e==`object`&&!!e).flatMap(e=>{let t=typeof e.name==`string`?e.name:``;return t?[{name:t,description:typeof e.description==`string`?e.description:void 0,parameters:e.parameters}]:[]}):[]}function Xa(e){return e.attempt>=e.maxAttempts||!fa(e.error)||e.finalAssistantText.trim().length>0||e.streamedAssistantSnapshot.trim().length>0||e.streamedTextSinceBoundary.trim().length>0?!1:e.turnRecords.slice(e.attemptTurnRecordStart).every(e=>e.toolResults.length===0&&fo(e.message).trim().length===0)}function Za(e){return e.some(e=>oo(e.message)!==null||e.toolResults.length>0)}function Qa(e,t){return{role:`assistant`,content:e,stopReason:(t&&typeof t==`object`?t.code:void 0)===`aborted`||e===`aborted`?`aborted`:`error`,errorMessage:e,timestamp:new Date().toISOString()}}function $a(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];for(let e=r.toolResults.length-1;e>=0;e--){let n=r.toolResults[e];if(n.toolName===t&&n.content.trim().length>0)return n.content}}return``}function eo(e){let t=e;return{message:e.errorMessage??(e.stopReason===`aborted`?`aborted`:`Unknown LLM error`),code:to(t.errorCode),statusCode:no(t.statusCode),providerCode:to(t.providerCode),providerType:to(t.providerType),retryable:typeof t.retryable==`boolean`?t.retryable:void 0}}function to(e){if(e==null)return;let t=String(e).trim();return t.length>0?t:void 0}function no(e){if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e==`string`&&/^\d+$/.test(e))return Number(e)}async function ro(e){await e.eventDispatcher.dispatchDiagnostic(e.sessionId,{level:`warn`,scope:`runner`,phase:`llm_turn_retry_scheduled`,message:`retrying transient LLM turn failure`,details:{attempt:e.attempt,nextAttempt:e.attempt+1,maxAttempts:e.maxAttempts,delayMs:e.delayMs,error:e.message}})}function io(e){let t=e.state;if(!Array.isArray(t.messages)||t.messages.length===0)return;let n=[...t.messages];for(;n.length>0&&ao(n[n.length-1]);)n.pop();n.length!==t.messages.length&&e.replaceMessages(n)}function ao(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`aborted`)}function oo(e){let t=e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``),n=e.content.filter(e=>e.type===`toolCall`).map(e=>({id:e.id,name:e.name,arguments:e.arguments}));if(t.trim().length===0&&n.length===0)return null;let r={role:`assistant`,content:t,timestamp:new Date().toISOString()};return n.length>0&&(r.toolCalls=n),r}function so(e,t){return!e||!t?e:!e.toolCalls||e.toolCalls.length===0?null:{...e,content:``}}function co(e){return{role:`tool_result`,toolCallId:e.toolCallId,toolName:e.toolName,content:e.content,isError:e.isError,toolResultRef:e.toolResultRef,timestamp:new Date().toISOString()}}function lo(e,t,n,r){let i=e.match(/\[tool result persisted\][^\n]*\((\d+) chars\)\.\nFull output: ([^\n]+)/);if(i)return{sessionId:t,toolCallId:n,toolName:r,storagePath:i[2]??``,preview:uo(e),originalChars:Number(i[1]??`0`),truncated:!0,createdAt:new Date().toISOString()}}function uo(e){let t=e.indexOf(`
21
21
  Preview:
22
22
  `);return t===-1?``:e.slice(t+10).replace(/\n\.\.\.$/,``)}function fo(e){return e.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function po(e){if(typeof e==`string`)return e;if(!e||typeof e!=`object`)return JSON.stringify(e);let t=e.content;return Array.isArray(t)?t.filter(e=>e&&typeof e==`object`&&e.type===`text`).map(e=>e.text??``).join(``):JSON.stringify(e)}function mo(e){if(!e||typeof e!=`object`)return null;let t=e;return Array.isArray(t.content)?t.content.filter(e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`&&`text`in e).map(e=>e.text).join(``):null}function ho(e,t,n){return t?n?t===n?``:t.startsWith(n)?t.slice(n.length):t:t:e}function go(e){let t=_o(e);return t?t.code===`http_error`&&t.statusCode?t.providerMessage?`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}: ${t.providerMessage}`:`LLM upstream returned HTTP ${t.statusCode}${t.statusText?` ${t.statusText}`:``}`:t.code===`timeout`?`LLM request timed out`:t.code===`network_error`?t.message:t.code===`aborted`?`LLM request was aborted`:t.message:e instanceof Error?e.message:String(e)}function _o(e){if(e instanceof Y)return e;if(e&&typeof e==`object`&&!(e instanceof Error)){let t=e,n=typeof t.message==`string`&&t.message.trim()?t.message:void 0;return!n&&t.code===void 0&&t.statusCode===void 0?null:{message:n??`Unknown LLM error`,code:to(t.code),statusCode:no(t.statusCode),statusText:to(t.statusText),providerMessage:to(t.providerMessage)}}if(!(e instanceof Error))return null;let t=e;return e.name!==`LlmRequestError`&&!t.code?null:{message:e.message,code:t.code,statusCode:t.statusCode,statusText:t.statusText,providerMessage:t.providerMessage}}async function vo(e){let t=wo(e.toolResultPreviewChars),n=To(e.systemPrompt,e.agentDefinition),r=Do(e.model,e.agentDefinition),i=oi(e.tools??[],e.agentDefinition),a=Eo(e.message,e.agentDefinition),o=await Ka({agent:new Ze({initialState:{systemPrompt:n,model:r,tools:i,messages:[]},getApiKey:e.getApiKey}),message:a,sessionId:e.sessionId,modelId:r.id,historyMessages:[],eventDispatcher:yo({diagnosticDispatcher:e.diagnosticDispatcher,phasePrefix:e.diagnosticPhasePrefix}),hooks:new _i,hookCtx:{sessionId:e.sessionId},abortSignal:e.abortSignal});return{text:o.text,usage:{input:o.inputTokens,output:o.outputTokens,total:o.inputTokens+o.outputTokens},error:o.error,toolCalls:xo(o.turnRecords),toolResults:So(o.turnRecords,t)}}function yo(e){let t=e.phasePrefix??`silent_agent`;return new vi({channel:`internal`,onProgress:async n=>{e.diagnosticDispatcher&&await bo(e.diagnosticDispatcher,t,n)}})}async function bo(e,t,n){let r=n.sessionId;if(r){if(n.type===`stream_text_delta`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_stream`,message:`silent agent streamed text`,details:{textLength:n.text.length}});return}if(n.type===`tool_start`){await e.dispatchDiagnostic(r,{level:`info`,scope:`skill`,phase:`${t}_tool_started`,message:`silent agent tool started`,details:{toolCallId:n.toolCallId,toolName:n.name,input:n.input}});return}if(n.type===`tool_end`){await e.dispatchDiagnostic(r,{level:n.isError?`warn`:`info`,scope:`skill`,phase:`${t}_tool_completed`,message:n.isError?`silent agent tool failed`:`silent agent tool completed`,details:{toolCallId:n.toolCallId,toolName:n.name,isError:n.isError}});return}if(n.type===`error`){await e.dispatchDiagnostic(r,{level:`warn`,scope:`skill`,phase:`${t}_error`,message:`silent agent reported error`,details:{error:n.message}});return}n.type===`diagnostic`&&await e.dispatchDiagnostic(r,{level:n.level,scope:n.scope,phase:`${t}_${n.phase}`,message:n.message,...n.details?{details:n.details}:{}})}}function xo(e){let t=[];for(let n of e)for(let e of n.message.content)e.type===`toolCall`&&t.push({id:e.id,name:e.name,arguments:e.arguments??{}});return t}function So(e,t){return e.flatMap(e=>e.toolResults.map(e=>({toolCallId:e.toolCallId,toolName:e.toolName,isError:e.isError,content:e.content,preview:Co(e.content,t)})))}function Co(e,t){return t===0?``:e.length<=t?e:t<=3?`.`.repeat(t):`${e.slice(0,t-3)}...`}function wo(e){let t=e??800;if(!Number.isFinite(t))throw Error(`toolResultPreviewChars must be a finite non-negative integer.`);return Math.max(0,Math.floor(t))}function To(e,t){return[t?.systemPrompt.trim(),e.trim()].filter(Boolean).join(`
23
23
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gencode/agents",
3
- "version": "0.9.1",
3
+ "version": "0.9.2",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",