@cerebriline/agents 4.100.257 → 4.100.259
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/agent-runtime.d.ts.map +1 -1
- package/dist/index.js +3 -3
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../src/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,uBAAuB,EAE5B,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAKX,YAAY,EAEZ,UAAU,EAKV,cAAc,EACd,iBAAiB,EAEjB,yBAAyB,EAOzB,kBAAkB,IAAI,sBAAsB,EAQ5C,iBAAiB,EAEjB,MAAM,eAAe,CAAC;AAmGvB,kEAAkE;AAClE,eAAO,MAAM,wBAAwB,QAAS,CAAC;AAE/C;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACpC,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAClB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,OAAO,GAClB,MAAM,CAmBR;AAYD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAoPjD;;;;;;;;;;;GAWG;AACH,wBAAgB,0BAA0B,CACzC,SAAS,CAAC,EAAE,iBAAiB,GAC3B,MAAM,CAcR;AAYD;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAEjD;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,sCAAsC,IAAI,CAAC;AAExD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,mCAAmC,OAAO,CAAC;AA0BxD;;;;GAIG;AACH,eAAO,MAAM,kDAAkD,sPACgL,CAAC;AAEhP;;;GAGG;AACH,eAAO,MAAM,+CAA+C,0JAC4F,CAAC;AAEzJ;;;GA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,CAAC;AAClC,MAAM,MAAM,KAAK,GAAG,YAAY,CAAC;AAEjC,wBAAgB,WAAW,CAAC,MAAM,EAAE,kBAAkB,GAAG,YAAY,CAEpE"}
|
package/dist/index.js
CHANGED
|
@@ -100,8 +100,8 @@ ${i}
|
|
|
100
100
|
|
|
101
101
|
`);this.pendingHookContexts=[];let t=de("user",[{type:"text",text:e}],{userRunSpan:0,displayRole:"system"}),n=this.state.messages.at(-1);if(n?.role==="assistant"&&n.content.some((r)=>r.type==="tool-call"))this.state.messages.splice(-1,0,t);else this.state.messages.push(t);await this.emit({type:"message-added",snapshot:this.snapshot(),message:t})}async callBeforeRunHooks(){for(let e of this.hooks.beforeRun){let t=await e({snapshot:this.snapshot()});if(this.applyStopControl(t),t?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"RunStart"},t.appendContext))}}async callAfterRunHooks(e){for(let t of this.hooks.afterRun)await t({snapshot:this.snapshot(),result:e})}async generateAssistantMessageRecoveringFaults(){for(let e=1;;e+=1){let t,n,i=!1;try{t=await this.withProviderErrorRetry(()=>this.generateAssistantMessageWithOverflowRecovery())}catch(p){if(this.abortController?.signal.aborted||p instanceof Tt||p instanceof Me||p instanceof ve)throw p;n=p,i=!0}let r=this.config.recoverTurnFault,o=()=>{if(i)throw n;return t};if(!r)return o();let s,a,u;if(i)s=Ot(n),a=n instanceof Error?n.message:String(n),u=ze(n);else if(t?.finishReason==="error")a=this.state.lastError??"",s=Ie(a,this.state.lastErrorClass),u=Yn(a,this.state.lastErrorClass);else return o();if(!s||!this.recoversTurnFault(s))return o();let c=V(this.config.sessionId),d=this.lastRequestTokens;if(u)this.config.logger?.log?.(`Engine bug: the server evicted session ${c??"(unnamed)"} (agent ${this.state.agentId}) at ${new Date().toISOString()}, holding ${d!==void 0?`${d.toLocaleString("en-US")} tokens (its last completed request)`:"an unknown number of tokens (no request had completed)"}, turn ${this.state.iteration}, attempt ${e}: ${a}; waiting to send it again`,{severity:"warn",kind:"engine_eviction",...c?{sessionId:c}:{},agentId:this.state.agentId,...d!==void 0?{tokensHeld:d}:{},iteration:this.state.iteration,attempt:e});else this.config.logger?.log?.(s==="refusal"?`Turn ${this.state.iteration} queued by the server (retry ${e}): ${Xn(a)}; waiting to send it again`:`Turn ${this.state.iteration} failed on a ${s} fault (attempt ${e}): ${a}; waiting to send it again`,{severity:s==="refusal"?"info":"warn"});await this.emit({type:"status-notice",snapshot:this.snapshot(),message:u?"the server evicted the turn to keep others alive (an engine bug) — waiting, then retrying":s==="transport"?"the server dropped the turn — waiting for it to come back, then retrying":"the server queued the turn — waiting for room, then retrying",metadata:{kind:"turn_fault_recovery",reason:s,...u?{evicted:!0}:{},phase:"started",iteration:this.state.iteration,attempt:e,providerError:a}});let y=!1;try{y=await r({kind:s,message:a,attempt:e,iteration:this.state.iteration,...u?{evicted:!0}:{},...u&&d!==void 0?{tokensHeld:d}:{},...c?{sessionId:c}:{},...this.abortController?.signal?{signal:this.abortController.signal}:{}})}catch{y=!1}if(this.throwIfAborted(),!y)return o()}}async generateAssistantMessageWithProviderRetry(){let e=()=>this.generateAssistantMessageRecoveringFaults(),t=await e();if(t.finishReason!=="unknown"||t.interrupted)return t;if(t.message.content.some((n)=>n.type==="tool-call")||this.hasModelToolActivity(t.message))return t;return await this.recordAssistantMessage(t.message,t.finishReason),await this.addUserReminderMessage("Previous turn ended unexpectedly. Continue from where you left off.",{displayRole:"system"}),this.resetLastError(),await e()}async withProviderErrorRetry(e){let t=0;for(;;){let n=await e();if(t>=en||!this.isRetryableProviderErrorTurn(n))return n;t+=1;let i=this.state.lastError;this.resetLastError();let r=Math.min(Tp*2**(t-1),wp);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`provider error — retrying (attempt ${t}/${en})`,metadata:{kind:"provider_error_retry",reason:"provider_error_retry",phase:"started",iteration:this.state.iteration,attempt:t,maxRetries:en,delayMs:r,providerError:i}}),await this.abortableDelay(r)}}isRetryableProviderErrorTurn(e){if(e.finishReason!=="error")return!1;if(e.message.content.length>0)return!1;let t=e.message.metadata?.modelToolActivities;if(Array.isArray(t)&&t.length>0)return!1;let n=this.state.lastErrorClass;if(n==="auth"||n==="context_window_exceeded")return!1;let i=Ie(this.state.lastError??"",n);if(i&&this.recoversTurnFault(i))return!1;return this.state.lastErrorRetryable===!0}resetLastError(){this.state.lastError=void 0,this.state.lastErrorClass=void 0,this.state.lastErrorRetryable=void 0,this.state.lastErrorReported=!1}async abortableDelay(e){this.throwIfAborted();let t=this.abortController?.signal;await new Promise((n,i)=>{let r=()=>{clearTimeout(o),i(this.normalizeAbortError())},o=setTimeout(()=>{t?.removeEventListener("abort",r),n()},e);if(t)t.addEventListener("abort",r,{once:!0})})}async generateAssistantMessageWithOverflowRecovery(){if(this.config.alwaysDescribeImages===!0)await this.describeImagesInTranscript();let e=this.compactBeforeNextTurn;this.compactBeforeNextTurn=!1;let t=await this.generateAssistantMessage(e?{overflowRecovery:!0}:void 0);if(this.isRecoverableImageTurn(t))return await this.retryWithoutImages();if(!this.isRecoverableOverflowTurn(t))return t;this.overflowRecoveryAttempted=!0;let n=this.state.lastError;if(!this.config.prepareTurn)throw new Me(Ip,n);await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"context window exceeded — compacting and retrying",metadata:{kind:"context_overflow_recovery",reason:"context_overflow_recovery",phase:"started",iteration:this.state.iteration,providerError:n}});let i=await this.generateAssistantMessage({overflowRecovery:!0,requireSmallerRequest:!0});if(i.finishReason==="error"&&this.state.lastErrorClass==="context_window_exceeded")throw new Me(Ep,this.state.lastError);return i}async recoverUnparsableToolCall(){if(this.state.lastErrorClass!=="tool_call_unparsable"||this.toolCallParseRetries>=vp)return!1;return this.toolCallParseRetries+=1,await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"the model's tool call did not parse — asking for it again",metadata:{kind:"tool_call_parse_recovery",reason:"tool_call_parse_recovery",phase:"started",iteration:this.state.iteration,attempt:this.toolCallParseRetries,providerError:this.state.lastError,...this.lastToolCallRejection?{rejection:this.lastToolCallRejection}:{}}}),await this.addUserReminderMessage(yp(this.lastToolCallRejection)),!0}isRecoverableImageTurn(e){return e.finishReason==="error"&&this.state.lastErrorClass==="image_input_unsupported"&&!this.imageRecoveryAttempted&&this.hasImageContent()}hasImageContent(){return this.state.messages.some((e)=>e.content.some((t)=>t.type==="image"))}async retryWithoutImages(){this.imageRecoveryAttempted=!0;let e=this.state.lastError,t=await this.describeImagesInTranscript(),n=0;for(let i of this.state.messages)for(let r=0;r<i.content.length;r++){if(i.content[r]?.type!=="image")continue;n+=1,i.content[r]={type:"text",text:np}}return this.config.onImageInputUnsupported?.(),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:"model does not accept images — resending without them",metadata:{kind:"image_input_recovery",reason:"image_input_recovery",phase:"started",iteration:this.state.iteration,droppedImages:n,describedImages:t,providerError:e}}),await this.generateAssistantMessage()}async describeImagesInTranscript(){let e=this.config.describeImages;if(!e)return 0;let t=[],n=[];for(let s of this.state.messages){let a=s.content.filter((u)=>u.type==="text").map((u)=>u.text).join(`
|
|
102
102
|
`).slice(0,ep);for(let u=0;u<s.content.length;u++){let c=s.content[u];if(c?.type!=="image")continue;let d=ip(c);if(d===void 0)continue;t.push({message:s,index:u}),n.push({image:d,mediaType:c.mediaType,context:a.length>0?a:void 0})}}if(n.length===0)return this.config.logger?.log?.(`Vision describer found no images in ${this.state.messages.length} transcript message(s)`),0;let i=[];try{i=await e(n)}catch(s){this.config.logger?.log?.(`Vision model could not describe ${n.length} image(s): ${s instanceof Error?s.message:String(s)}`,{severity:"warn"})}let r=this.config.modelSupportsImages!==!1,o=0;for(let s=0;s<t.length;s++){let a=i[s]?.trim();if(!a&&r)continue;let u=t[s];u.message.content[u.index]={type:"text",text:a?`[image description, from the vision model]
|
|
103
|
-
${a}`:tp},o+=1}return o}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async recordAssistantMessage(e,t){let n=this.replaceSpoiledContent(e);if(this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),n)this.announcedRepetitionRemoval.add(e),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:n,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:"removed",iteration:this.state.iteration}});await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=Tr({distinctId:V(this.config.distinctId),clientName:V(this.config.clientName),clientVersion:V(this.config.clientVersion),clineCoreVersion:V(this.config.clineCoreVersion),sessionId:V(this.config.sessionId),agentId:this.state.agentId,conversationId:V(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n=this.getRetryOutputCap();if(n!==void 0)this.config.logger?.log?.(`Retrying a truncated turn on a reduced output cap of ${n} tokens (attempt ${this.consecutiveMaxTokensRetries}, was ${this.truncatedOutputCapTokens})`,{severity:"info"});let i={systemPrompt:this.config.systemPrompt,messages:Y(this.state.messages),tools:[...this.tools.values()].map((s)=>({name:s.name,description:s.description,inputSchema:s.inputSchema,...s.readOnly?{readOnly:!0}:{}})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:jt(this.config.modelOptions,{metadata:t,...n!==void 0?{maxTokens:n}:{}})},r=Date.now(),o=await this.consumePendingUserMessage();if(o)i={...i,messages:[...i.messages,...Y([o])]};i=await this.prepareTurnForModelRequest(i,e),this.throwIfAborted();for(let s of this.hooks.beforeModel){let a=await s({snapshot:this.snapshot(),request:i});if(this.throwIfAborted(),this.applyStopControl(a),a?.messages)i={...i,messages:Y(a.messages)};if(a?.tools)i={...i,tools:[...a.tools]};if(a?.options)i={...i,options:jt(i.options,a.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...Sp(i)}),{request:i,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=oe(this.state.usage);this.state.lastRequestTimings=void 0;let i=()=>Date.now()-e.startedAt,r=e.request;this.throwIfAborted(),this.captureTaskLifecycle(_r,{durationMs:i(),phase:"provider_request_started"}),r={...r,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])},this.lastIssuedRequest=r;let o=this.openTaskLifecycleStream(r,i),s=[],a=new je,u=new Map,c=new Map,d=new Map,y=[],p=[],v="unknown",b,w="",F="",B=Wt(),H=0,A=this.config.reasoningLoopDetection,P=A===!1?void 0:new me(A,{given:()=>Zt(r.messages)}),G,se=()=>Zt(r.messages),be=A===!1?void 0:new me(A,{given:se}),ae=A===!1?void 0:new Kt(A,{given:se}),K,x,sn=this.config.toolIntentLimit,an=this.toolIntentCutStreak>=pp;if(an)this.toolIntentCutStreak=0;let ln=sn===!1||an||!Xt()?void 0:new Qt({...sn,argumentNames:this.toolArgumentNames(),toolNames:[...this.tools.values()].map((m)=>m.name)}),W;for await(let m of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),m.type){case"text-delta":{w+=m.text,B.textDeltas+=1,B.textChars+=m.text.length;let _=p.at(-1);if(_?.type==="part"&&_.part.type==="text")_.part.text+=m.text;else p.push({type:"part",part:{type:"text",text:m.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:m.text,accumulatedText:w}),K=be?.push(m.text)??void 0;break}case"media":{p.push({type:"part",part:{type:"media",media:m.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:m.media});break}case"reasoning-delta":{F+=m.text,B.reasoningDeltas+=1,B.reasoningChars+=m.text.length;let _=p.at(-1);if(_?.type==="part"&&_.part.type==="reasoning")_.part.text+=m.text,_.part.redacted=m.redacted??_.part.redacted,_.part.metadata=m.metadata??_.part.metadata;else p.push({type:"part",part:{type:"reasoning",text:m.text,redacted:m.redacted,metadata:m.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:m.text,accumulatedText:F,redacted:m.redacted,metadata:m.metadata}),G=P?.push(m.text)??void 0;break}case"tool-input-progress":{if(await this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:{type:"tool-call",toolCallId:m.toolCallId,toolName:m.toolName??"tool",input:void 0},update:{kind:Jn,inputChars:m.inputChars,deltas:m.deltas,...m.inputText?{inputText:m.inputText}:{}}}),m.toolName)c.set(m.toolCallId,m.toolName);if(m.inputText)u.set(m.toolCallId,(u.get(m.toolCallId)??"")+m.inputText),W=ln?.push(m.toolCallId,m.inputText,m.toolName),x=ae?.push(m.toolCallId,m.inputText,m.toolName);break}case"tool-call-delta":{if(m.execution){let D={type:"tool-call",toolCallId:m.toolCallId??ye("model_tool"),toolName:m.toolName??"tool",input:m.input,metadata:m.metadata,execution:m.execution};d.set(D.toolCallId,{toolCallId:D.toolCallId,toolName:D.toolName,execution:m.execution,input:D.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:D});break}let{key:_,created:j}=a.add(m);if(j)p.push({type:"tool",key:_});break}case"tool-result":{let _=d.get(m.toolCallId),j={..._,toolCallId:m.toolCallId,toolName:m.toolName,execution:m.execution,input:m.input===void 0?_?.input:m.input,output:m.output,isError:m.isError};d.set(m.toolCallId,j);let D={type:"tool-call",toolCallId:m.toolCallId,toolName:m.toolName,input:j.input,execution:m.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:D,message:de("tool",[{type:"tool-result",toolCallId:m.toolCallId,toolName:m.toolName,output:m.output,isError:m.isError,execution:m.execution}])});break}case"usage":{if(typeof m.usage.inputTokens==="number"&&m.usage.inputTokens>0)this.state.lastRequestInputTokens=m.usage.inputTokens;let _=a.inputChars();B.toolInputChars=Math.max(0,_-H);let j=Pr({outputTokens:m.usage.outputTokens,providerReasoningTokens:m.usage.reasoningTokenCount,tally:B});H=_,B=Wt(),await this.updateUsage(m.usage,m.timings,{outputSplit:j});break}case"finish":{if(v=m.reason,b=m.requestId,m.error)this.state.lastError=m.error,this.state.lastErrorClass=m.errorClass??Jr(m.error),this.lastToolCallRejection=m.toolCallRejection,this.state.lastErrorRetryable=m.errorRetryable??Zd(m.error),this.state.lastErrorReported=m.errorReported===!0;break}}if(G||K||x||W)break}if(ae&&!x&&!W)for(let m of p){if(m.type!=="tool")continue;let _=a.get(m.key);if(!_?.inputText||u.has(_.toolCallId))continue;if(x=ae.push(_.toolCallId,_.inputText,_.toolName),x)break}let wt=(m,_)=>_?`${m}
|
|
103
|
+
${a}`:tp},o+=1}return o}isRecoverableOverflowTurn(e){if(e.finishReason!=="error"||this.state.lastErrorClass!=="context_window_exceeded"||this.overflowRecoveryAttempted)return!1;return!e.message.content.some((t)=>t.type==="tool-call")}hasModelToolActivity(e){let t=e.metadata?.modelToolActivities;return Array.isArray(t)&&t.length>0}async recordAssistantMessage(e,t){let n=this.replaceSpoiledContent(e);if(this.state.messages.push(e),await this.emit({type:"message-added",snapshot:this.snapshot(),message:e}),n)this.announcedRepetitionRemoval.add(e),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:n,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:"removed",iteration:this.state.iteration,nudged:Boolean(this.repetitionNudges.get(e)?.nudge)}});await this.emit({type:"assistant-message",snapshot:this.snapshot(),iteration:this.state.iteration,message:e,finishReason:t})}async generateAssistantMessage(e){let t=new AbortController;this.modelSteerController=t;try{return await this.generateAssistantMessageForRequest(t,e)}finally{this.modelSteerController=void 0}}async prepareModelRequest(e){let t=Tr({distinctId:V(this.config.distinctId),clientName:V(this.config.clientName),clientVersion:V(this.config.clientVersion),clineCoreVersion:V(this.config.clineCoreVersion),sessionId:V(this.config.sessionId),agentId:this.state.agentId,conversationId:V(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration}),n=this.getRetryOutputCap();if(n!==void 0)this.config.logger?.log?.(`Retrying a truncated turn on a reduced output cap of ${n} tokens (attempt ${this.consecutiveMaxTokensRetries}, was ${this.truncatedOutputCapTokens})`,{severity:"info"});let i={systemPrompt:this.config.systemPrompt,messages:Y(this.state.messages),tools:[...this.tools.values()].map((s)=>({name:s.name,description:s.description,inputSchema:s.inputSchema,...s.readOnly?{readOnly:!0}:{}})),modelTools:this.config.modelTools,signal:this.abortController?.signal,options:jt(this.config.modelOptions,{metadata:t,...n!==void 0?{maxTokens:n}:{}})},r=Date.now(),o=await this.consumePendingUserMessage();if(o)i={...i,messages:[...i.messages,...Y([o])]};i=await this.prepareTurnForModelRequest(i,e),this.throwIfAborted();for(let s of this.hooks.beforeModel){let a=await s({snapshot:this.snapshot(),request:i});if(this.throwIfAborted(),this.applyStopControl(a),a?.messages)i={...i,messages:Y(a.messages)};if(a?.tools)i={...i,tools:[...a.tools]};if(a?.options)i={...i,options:jt(i.options,a.options)}}return this.config.logger?.debug("Agent model request diagnostics",{iteration:this.state.iteration,providerId:"providerId"in this.config&&typeof this.config.providerId==="string"?this.config.providerId:void 0,modelId:"modelId"in this.config&&typeof this.config.modelId==="string"?this.config.modelId:void 0,...Sp(i)}),{request:i,startedAt:r}}async generateAssistantMessageForRequest(e,t){let n=await this.prepareModelRequest(t);return await this.streamPreparedRequest(n,e)}async streamPreparedRequest(e,t){let n=oe(this.state.usage);this.state.lastRequestTimings=void 0;let i=()=>Date.now()-e.startedAt,r=e.request;this.throwIfAborted(),this.captureTaskLifecycle(_r,{durationMs:i(),phase:"provider_request_started"}),r={...r,signal:AbortSignal.any([t.signal,...this.abortController?[this.abortController.signal]:[]])},this.lastIssuedRequest=r;let o=this.openTaskLifecycleStream(r,i),s=[],a=new je,u=new Map,c=new Map,d=new Map,y=[],p=[],v="unknown",b,w="",F="",B=Wt(),H=0,A=this.config.reasoningLoopDetection,P=A===!1?void 0:new me(A,{given:()=>Zt(r.messages)}),G,se=()=>Zt(r.messages),be=A===!1?void 0:new me(A,{given:se}),ae=A===!1?void 0:new Kt(A,{given:se}),K,x,sn=this.config.toolIntentLimit,an=this.toolIntentCutStreak>=pp;if(an)this.toolIntentCutStreak=0;let ln=sn===!1||an||!Xt()?void 0:new Qt({...sn,argumentNames:this.toolArgumentNames(),toolNames:[...this.tools.values()].map((m)=>m.name)}),W;for await(let m of o){if(t.signal.aborted)break;switch(this.throwIfAborted(),m.type){case"text-delta":{w+=m.text,B.textDeltas+=1,B.textChars+=m.text.length;let _=p.at(-1);if(_?.type==="part"&&_.part.type==="text")_.part.text+=m.text;else p.push({type:"part",part:{type:"text",text:m.text}});await this.emit({type:"assistant-text-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:m.text,accumulatedText:w}),K=be?.push(m.text)??void 0;break}case"media":{p.push({type:"part",part:{type:"media",media:m.media}}),await this.emit({type:"assistant-media",snapshot:this.snapshot(),iteration:this.state.iteration,media:m.media});break}case"reasoning-delta":{F+=m.text,B.reasoningDeltas+=1,B.reasoningChars+=m.text.length;let _=p.at(-1);if(_?.type==="part"&&_.part.type==="reasoning")_.part.text+=m.text,_.part.redacted=m.redacted??_.part.redacted,_.part.metadata=m.metadata??_.part.metadata;else p.push({type:"part",part:{type:"reasoning",text:m.text,redacted:m.redacted,metadata:m.metadata}});await this.emit({type:"assistant-reasoning-delta",snapshot:this.snapshot(),iteration:this.state.iteration,text:m.text,accumulatedText:F,redacted:m.redacted,metadata:m.metadata}),G=P?.push(m.text)??void 0;break}case"tool-input-progress":{if(await this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:{type:"tool-call",toolCallId:m.toolCallId,toolName:m.toolName??"tool",input:void 0},update:{kind:Jn,inputChars:m.inputChars,deltas:m.deltas,...m.inputText?{inputText:m.inputText}:{}}}),m.toolName)c.set(m.toolCallId,m.toolName);if(m.inputText)u.set(m.toolCallId,(u.get(m.toolCallId)??"")+m.inputText),W=ln?.push(m.toolCallId,m.inputText,m.toolName),x=ae?.push(m.toolCallId,m.inputText,m.toolName);break}case"tool-call-delta":{if(m.execution){let D={type:"tool-call",toolCallId:m.toolCallId??ye("model_tool"),toolName:m.toolName??"tool",input:m.input,metadata:m.metadata,execution:m.execution};d.set(D.toolCallId,{toolCallId:D.toolCallId,toolName:D.toolName,execution:m.execution,input:D.input}),await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:D});break}let{key:_,created:j}=a.add(m);if(j)p.push({type:"tool",key:_});break}case"tool-result":{let _=d.get(m.toolCallId),j={..._,toolCallId:m.toolCallId,toolName:m.toolName,execution:m.execution,input:m.input===void 0?_?.input:m.input,output:m.output,isError:m.isError};d.set(m.toolCallId,j);let D={type:"tool-call",toolCallId:m.toolCallId,toolName:m.toolName,input:j.input,execution:m.execution};await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:D,message:de("tool",[{type:"tool-result",toolCallId:m.toolCallId,toolName:m.toolName,output:m.output,isError:m.isError,execution:m.execution}])});break}case"usage":{if(typeof m.usage.inputTokens==="number"&&m.usage.inputTokens>0)this.state.lastRequestInputTokens=m.usage.inputTokens;let _=a.inputChars();B.toolInputChars=Math.max(0,_-H);let j=Pr({outputTokens:m.usage.outputTokens,providerReasoningTokens:m.usage.reasoningTokenCount,tally:B});H=_,B=Wt(),await this.updateUsage(m.usage,m.timings,{outputSplit:j});break}case"finish":{if(v=m.reason,b=m.requestId,m.error)this.state.lastError=m.error,this.state.lastErrorClass=m.errorClass??Jr(m.error),this.lastToolCallRejection=m.toolCallRejection,this.state.lastErrorRetryable=m.errorRetryable??Zd(m.error),this.state.lastErrorReported=m.errorReported===!0;break}}if(G||K||x||W)break}if(ae&&!x&&!W)for(let m of p){if(m.type!=="tool")continue;let _=a.get(m.key);if(!_?.inputText||u.has(_.toolCallId))continue;if(x=ae.push(_.toolCallId,_.inputText,_.toolName),x)break}let wt=(m,_)=>_?`${m}
|
|
104
104
|
|
|
105
|
-
${_}`:m;if(G)this.pendingToolIntentNudge=wt(qr(G),await this.onReasoningLoopCut(G));else if(K)this.pendingToolIntentNudge=wt(jr(K),await this.onReasoningLoopCut(K,"reply"));else if(x)this.pendingToolIntentNudge=wt(Br(x),await this.onReasoningLoopCut(x.verdict,`call to \`${x.toolName??"a tool"}
|
|
105
|
+
${_}`:m;if(G)this.pendingToolIntentNudge=wt(qr(G),await this.onReasoningLoopCut(G));else if(K)this.pendingToolIntentNudge=wt(jr(K),await this.onReasoningLoopCut(K,"reply","answer_loop"));else if(x)this.pendingToolIntentNudge=wt(Br(x),await this.onReasoningLoopCut(x.verdict,`call to \`${x.toolName??"a tool"}\``,"argument_loop"));else if(P)this.reasoningLoopStreak=0;if(W)await this.onToolIntentCut(W);else if(ln)this.toolIntentCutStreak=0;this.throwIfAborted();let _t=t.signal.aborted;if(_t)v="stop";if((G||K||x||W)&&v==="unknown")v="stop";let un="",cn;for(let m of p)if(m.type==="tool")cn=m.key;for(let m of p){if(_t&&(m.type==="tool"||m.part.type==="reasoning"))continue;if(m.type==="part"){if(K&&m.part.type==="text"){un+=m.part.text;continue}s.push(m.part);continue}let _=a.get(m.key);if(W&&_?.toolCallId===W.toolCallId||x&&_?.toolCallId===x.toolCallId)continue;let j=a.finish(m.key,v,m.key===cn);if(j.invalid)y.push(j.invalid);if(!j.call||!_)continue;this.config.logger?.debug?.(Yd(this.state.iteration,j.call.toolName,j.call.toolCallId,_.inputText,j.call.input)),s.push(j.call)}let ie={};if(G)ie.reasoningLoop=G;if(K)this.recordCut({channel:"reply",cause:"answer_loop",verdict:K,text:un}),s.push({type:"text",text:"(The reply here was cut: it had come to repeat itself. Its text is not kept.)"}),ie.answerLoop=K;let dn=(m)=>u.get(m)||a.get(m)?.inputText||"";if(x)this.recordCut({channel:"tool_arguments",cause:"argument_loop",verdict:x.verdict,...x.toolName?{toolName:x.toolName}:{},toolCallId:x.toolCallId,text:dn(x.toolCallId)}),s.push({type:"text",text:Fr(x)}),ie.argumentLoop=x;if(W)this.recordCut({channel:"tool_arguments",cause:"tool_intent_overrun",...W.toolName?{toolName:W.toolName}:{},toolCallId:W.toolCallId,text:dn(W.toolCallId)}),s.push({type:"text",text:Gr(W)}),ie.toolIntentOverrun=W;if(v==="max-tokens"){let m=new Set(s.flatMap((D)=>D.type==="tool-call"?[D.toolCallId]:[])),_=new Set(y.map((D)=>D.toolCallId)),j=[];for(let[D,pn]of u){if(m.has(D)&&!_.has(D)||D===x?.toolCallId||D===W?.toolCallId)continue;let Ve=c.get(D);if(this.recordCut({channel:"tool_arguments",cause:"output_limit",...Ve?{toolName:Ve}:{},toolCallId:D,text:pn}),!_.has(D))j.push({...Ve?{toolName:Ve}:{},chars:pn.length})}if(j.length>0)ie.unfinishedToolCalls=j}if(y.length>0)ie.invalidToolCalls=y;if(d.size>0)ie.modelToolActivities=[...d.values()];let He=de("assistant",s,Object.keys(ie).length>0?ie:void 0),We=Op(n,this.state.usage);if(We){if(this.state.lastRequestTimings)We.timings=this.state.lastRequestTimings;He.metrics=We,this.captureUnexpectedReasoningTokens(r,We)}if(this.config.messageModelInfo)He.modelInfo={...this.config.messageModelInfo};for(let m of this.hooks.afterModel){let _=await m({snapshot:this.snapshot(),assistantMessage:He,finishReason:v,...b?{requestId:b}:{}});this.applyStopControl(_)}return{message:He,finishReason:v,interrupted:_t}}async*openTaskLifecycleStream(e,t){let n,i="provider_request_started",r=Date.now();this.trace(`request-start iter=${this.state.iteration}`);try{n=await this.config.model.stream(e),this.trace(`stream-open iter=${this.state.iteration} after=${Date.now()-r}ms`),this.throwIfAborted(),i="provider_stream_started",this.captureTaskLifecycle(kr,{durationMs:t(),phase:i})}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}let o=!1;try{for await(let s of n){if(!o)o=!0,this.trace(`first-chunk iter=${this.state.iteration} after=${Date.now()-r}ms type=${s.type}`),i="first_chunk_received",this.captureTaskLifecycle(Er,{durationMs:t(),phase:i,eventType:s.type});yield s}}catch(s){if(e.signal?.aborted&&!this.abortController?.signal.aborted)return;if(!e.signal?.aborted&&!this.isAbortError(s))this.captureTaskLifecycleFailure(s,i,t());throw s}}captureTaskLifecycleFailure(e,t,n){this.captureTaskLifecycle(Ir,{durationMs:n,error:e,errorClass:Jr(e),phase:t})}captureTaskLifecycle(e,t={}){let n=V(this.config.sessionId);Cr(this.config.telemetry,{event:e,sessionId:n,ulid:n,agentId:this.state.agentId,conversationId:V(this.config.conversationId),runId:this.state.runId,iteration:this.state.iteration>0?this.state.iteration:void 0,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...t})}getTelemetryProviderId(){return V(this.config.messageModelInfo?.provider)??this.telemetryProviderId}getTelemetryModelId(){return V(this.config.messageModelInfo?.id)??this.telemetryModelId}isAbortError(e){return e instanceof ve||this.abortController?.signal.aborted===!0}captureUnexpectedReasoningTokens(e,t){if(!Mp(e)||(t.reasoningTokenCount??0)<=0)return;let n=t.reasoningTokenCount;if(n===void 0)return;xr(this.config.telemetry,{sessionId:this.config.sessionId,agentId:this.state.agentId,runId:this.state.runId,iteration:this.state.iteration,providerId:this.config.messageModelInfo?.provider,modelId:this.config.messageModelInfo?.id,requestedThinking:!1,reasoningTokenCount:n})}async prepareTurnForModelRequest(e,t){if(!this.config.prepareTurn)return e;let n=t?.overflowRecovery===!0,i=t?.requireSmallerRequest===!0,r=await this.config.prepareTurn({agentId:this.state.agentId,conversationId:this.config.conversationId,parentAgentId:this.state.parentAgentId??null,iteration:this.state.iteration,messages:e.messages,systemPrompt:e.systemPrompt,tools:e.tools,model:{id:this.config.messageModelInfo?.id,provider:this.config.messageModelInfo?.provider},signal:e.signal,overflowRecovery:n||void 0,previousRequestInputTokens:this.state.lastRequestInputTokens>0?this.state.lastRequestInputTokens:void 0,emitStatusNotice:(s,a)=>{this.emit({type:"status-notice",snapshot:this.snapshot(),message:s,metadata:a})},reportUsage:(s)=>{this.updateUsage(s,void 0,{auxiliary:!0})}});if(i){if(!(r?.messages!==void 0&&JSON.stringify(r.messages).length<JSON.stringify(e.messages).length))throw new Me(kp,this.state.lastError)}if(!r)return e;let o=e;if(r.messages){let s=Y(r.messages);o={...o,messages:Y(s)}}if(r.systemPrompt!==void 0)o={...o,systemPrompt:r.systemPrompt};return o}async consumePendingUserMessage(){let e=this.config.consumePendingUserMessage;if(!e)return;let t=(await e())?.trim();if(!t)return;let n=de("user",[{type:"text",text:t}],{userRunSpan:0});return this.steerAwaitingResume=!0,this.state.messages.push(n),await this.emit({type:"message-added",snapshot:this.snapshot(),message:n}),n}async updateUsage(e,t,n){let i=n?.auxiliary===!0;if(this.state.usage={inputTokens:this.state.usage.inputTokens+(e.inputTokens??0),outputTokens:this.state.usage.outputTokens+(e.outputTokens??0),cacheReadTokens:this.state.usage.cacheReadTokens+(e.cacheReadTokens??0),cacheWriteTokens:this.state.usage.cacheWriteTokens+(e.cacheWriteTokens??0),reasoningTokenCount:(this.state.usage.reasoningTokenCount??0)+(e.reasoningTokenCount??0),totalCost:(this.state.usage.totalCost??0)+(e.totalCost??0)},t)this.state.lastRequestTimings=t;if(e.inputTokens!==void 0&&!i)this.lastRequestTokens=(e.inputTokens??0)+(e.outputTokens??0);await this.emit({type:"usage-updated",snapshot:this.snapshot(),usage:oe(this.state.usage),...t?{timings:t}:{},...n?.outputSplit?{outputSplit:n.outputSplit}:{},...i?{auxiliary:!0}:{}})}async executeToolCalls(e){this.pendingHookContexts=[];let t=[];for(let d of e){let y=Date.now(),p=await this.prepareToolExecution(d);p.prepareMs=Date.now()-y,t.push(p)}let n=Array(t.length),i=[],r=[],o=this.config.maxParallelToolCalls>1;t.forEach((d,y)=>{let p=this.tools.get(d.toolCall.toolName);(o&&p?.lifecycle?.boundsOwnConcurrency===!0?r:i).push(y)});let s=r.map(async(d)=>{n[d]=await this.executePreparedTool(t[d])}),a=Math.min(Math.max(1,this.config.maxParallelToolCalls),i.length);if(a<=1){for(let d of i)n[d]=await this.executePreparedTool(t[d]);return await Promise.all(s),n}let u=0,c=async()=>{while(!0){let d=u;if(u+=1,d>=i.length)return;let y=i[d];n[y]=await this.executePreparedTool(t[y])}};return await Promise.all([...Array.from({length:a},()=>c()),...s]),n}attachTurnNotes(e,t){let n=[],i=this.repetitionNudgeFor(t);if(i)n.push(i);let r=this.config.completionPolicy?.afterToolsReminder?.();if(r)n.push(r);if(this.pendingToolIntentNudge)n.push(this.pendingToolIntentNudge),this.pendingToolIntentNudge=void 0;if(n.length===0)return[];let o=e.at(-1)?.content??[],s;for(let a=o.length-1;a>=0&&!s;a-=1){let u=o[a];if(u?.type==="tool-result")s=u}if(!s)return n;return s.note=[s.note,...n].filter(Boolean).join(`
|
|
106
106
|
|
|
107
|
-
`),[]}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let i=e[n];if(this.tools.get(i.toolName)?.lifecycle?.completesRun!==!0)continue;let r=t[n],o=r?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===i.toolCallId);if(o&&!o.isError)return r}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,i,r=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof r?.inputParseError==="string")i=r.inputParseError;let o=t?void 0:this.config.unavailableToolReasons?.[e.toolName];if(o)i=`Tool "${e.toolName}" is not offered in this session: ${o}`;let s=r?.toolSource&&typeof r.toolSource==="object"&&!Array.isArray(r.toolSource)?r.toolSource:void 0;if(s?.executionMode==="provider")i=`Tool execution is disabled for provider ${typeof s.providerId==="string"?s.providerId:"provider"}`;if(t&&!i)n=Ce(n,t.inputSchema);let a;if(t&&!i)for(let u of this.hooks.beforeTool){let c=await u({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(c?.input!==void 0)n=c.input;if(c?.policy)a={...a,...c.policy};if(c?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"PreToolUse",toolCall:e},c.appendContext));if(this.applyStopControl(c),c?.skip){i=c.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!i){let u={...Cp(e.toolName,this.config.toolPolicies),...a};if(u.enabled===!1)i=`Tool "${e.toolName}" is disabled by policy`;else if(u.autoApprove===!1){let c=await this.requestToolApproval(e,n,u);if(!c.approved)i=`${c.reason??"Tool was not executed"} -- ${ar}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:i}}async requestToolApproval(e,t,n){let i=this.config.requestToolApproval;if(!i)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await i({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(r){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${r instanceof Error?r.message:String(r)}`}}}async executePreparedTool(e){let t=new Date,n=Date.now();await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let i=Date.now(),r;if(e.skipReason)r={output:{error:e.skipReason},isError:!0};else if(!e.tool)r={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{if(r={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??ye("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),reportStoppedForUser:()=>{this.stoppedForUserBy=e.toolCall.toolName},emitUpdate:(d)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:d})}})},this.stoppedForUserBy!==void 0&&this.stoppedForUserBy!==e.toolCall.toolName&&e.tool.readOnly!==!0)this.stoppedForUserBy=void 0}catch(c){r={output:{error:c instanceof Error?c.message:String(c)},isError:!0}}let o=new Date,s=Date.now(),a=Math.max(0,o.getTime()-t.getTime());if(e.tool)for(let c of this.hooks.afterTool){let d=await c({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:r,startedAt:t,endedAt:o,durationMs:a});if(d?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"PostToolUse",toolCall:e.toolCall},d.appendContext));if(this.applyStopControl(d),d?.result)r=d.result}this.trace(`tool ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`),this.config.logger?.debug?.(`[tool-timing] ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`);let u=de("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:r.output,isError:r.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:u}),u}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ye("run"),status:e,iterations:this.state.iteration,outputText:n??Oe(t??this.findLastAssistantMessage()),messages:Y(this.state.messages),usage:oe(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}recordCut(e){let t=this.config.onLoopCut;if(!t||!e.text)return;let n={agentId:this.state.agentId,iteration:this.state.iteration,...e};Promise.resolve().then(()=>t(n)).catch((i)=>{this.config.logger?.debug?.(`[loop-cut] could not keep the ${e.channel} cut at iteration ${n.iteration}: ${String(i)}`)})}async onReasoningLoopCut(e,t="reasoning"){this.reasoningLoopStreak+=1;let n=(this.config.reasoningLoopDetection===!1?void 0:this.config.reasoningLoopDetection?.maxConsecutiveTrips)??gt.maxConsecutiveTrips,i=Vt(e,t),r=this.reasoningLoopStreak>=n,o=r?await this.config.onReasoningLoopLimitReached?.({iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:n,diagnosis:i}):void 0,s=o?.action==="continue"?o.guidance?.trim():void 0,a=r&&o?.action!=="continue";if(await this.emit({type:"status-notice",snapshot:this.snapshot(),message:a?`${i} Ending the run after ${this.reasoningLoopStreak} turns cut for this.`:r?`${i} That is ${this.reasoningLoopStreak} turns cut for this, and the run was to end here.`:`${i} Cutting the request and continuing.`,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:a?"aborted":"cut",iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,verdict:e,channel:t}}),a){this.abort(new ve(i)),this.throwIfAborted();return}return s}toolArgumentNames(){let e=new Set;for(let t of this.tools.values()){let n=t.inputSchema?.properties;for(let i of Object.keys(n??{}))e.add(i)}return[...e]}async onToolIntentCut(e){this.toolIntentCutStreak+=1,this.pendingToolIntentNudge=Kr(e);let t=e.toolName?`\`${e.toolName}\``:"a tool";this.config.logger?.log?.(`[tool-intent] cut a call to ${t} at iteration ${this.state.iteration}: intent passed ${e.maxChars} characters`),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`The model was writing its reasoning into the \`intent\` of a call to ${t} (past ${e.maxChars.toLocaleString("en-US")} characters). Cutting the request and asking it to make the call again.`,metadata:{kind:"tool_intent_overrun",reason:"tool_intent_overrun",phase:"cut",iteration:this.state.iteration,overrun:e}})}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}eventHookMs=new Map;noteEventHookMs(e,t,n){let i=`${e}#${t}`,r=this.eventHookMs.get(i);if(r)r.ms+=n,r.n+=1;else this.eventHookMs.set(i,{ms:n,n:1})}topEventHooks(e=4){return[...this.eventHookMs.entries()].sort((t,n)=>n[1].ms-t[1].ms).slice(0,e).map(([t,n])=>`${t}=${Math.round(n.ms)}ms/${n.n}`).join(" ")}trace(e){Jd(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=Bp(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",t);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",t);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...t,error:e.error}),!this.state.lastErrorReported)Rr(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:if(!Fp.has(e.type))this.config.logger?.debug?.(`Agent event: ${e.type}`,t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}let n=0;for(let i of this.listeners){let r=Date.now();i(e),this.noteEventHookMs(e.type,`listener${n}`,Date.now()-r),n+=1}for(let i=0;i<this.hooks.onEvent.length;i+=1){let r=Date.now();await this.hooks.onEvent[i](e),this.noteEventHookMs(e.type,i,Date.now()-r)}}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new Tt(e.reason)}}var Dp={no_tool_call:"the turn ended without calling anything — asking the model to carry on",unparsed_tool_call:"a tool call was written as text and never ran — asking for it again",announced_intent:"the model described the next step instead of taking it — asking it to make the call",non_convergence:"several turns of thinking with no work done — asking for a different approach",silent_repetition:"the turn repeated what the last one said — asking for a different approach"};function Up(e){return Dp[e]??`nudged: ${e}`}var Fp=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function Bp(e){return{agentId:e.snapshot.agentId,agentRole:e.snapshot.agentRole,runId:e.snapshot.runId,status:e.snapshot.status,iteration:e.snapshot.iteration,eventType:e.type}}function jp(e){return new qe(e)}var qp=qe;function Hp(e){return new qe(e)}function no(e){let t=e.search(/<\|?tool_call\|?>/),n=(t<0?e:e.slice(t)).replace(/\s+/g," ").trim(),i=5381;for(let r=0;r<n.length;r++)i=(i<<5)+i+n.charCodeAt(r)|0;return`${n.length}:${i}`}export{qp as Agent,qe as AgentRuntime,ve as AgentRuntimeAbortError,bp as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,io as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,gt as DEFAULT_REASONING_LOOP_GUARD,ge as DEFAULT_REASONING_REPETITION,qd as DEFAULT_TOOL_INTENT_MAX_CHARS,ro as NON_CONVERGENCE_MIN_REASONING_CHARS,me as ReasoningLoopGuard,je as ToolCallAssembler,Hp as createAgent,jp as createAgentRuntime,Gt as createRepetitionNudger,Cd as createTool,Vt as describeReasoningLoop,Lr as describeRepetition,Dd as finishToolCalls,vt as isRepetitionLoop,Xt as isToolIntentGuardEnabled,yt as measureReasoningRepetition,Hd as setToolIntentGuardEnabled};
|
|
107
|
+
`),[]}findCompletingToolMessage(e,t){for(let n=0;n<e.length;n+=1){let i=e[n];if(this.tools.get(i.toolName)?.lifecycle?.completesRun!==!0)continue;let r=t[n],o=r?.content.find((s)=>s.type==="tool-result"&&s.toolCallId===i.toolCallId);if(o&&!o.isError)return r}return}async prepareToolExecution(e){let t=this.tools.get(e.toolName),n=e.input,i,r=e.metadata&&typeof e.metadata==="object"&&!Array.isArray(e.metadata)?e.metadata:void 0;if(typeof r?.inputParseError==="string")i=r.inputParseError;let o=t?void 0:this.config.unavailableToolReasons?.[e.toolName];if(o)i=`Tool "${e.toolName}" is not offered in this session: ${o}`;let s=r?.toolSource&&typeof r.toolSource==="object"&&!Array.isArray(r.toolSource)?r.toolSource:void 0;if(s?.executionMode==="provider")i=`Tool execution is disabled for provider ${typeof s.providerId==="string"?s.providerId:"provider"}`;if(t&&!i)n=Ce(n,t.inputSchema);let a;if(t&&!i)for(let u of this.hooks.beforeTool){let c=await u({snapshot:this.snapshot(),tool:t,toolCall:{...e,input:n},input:n});if(c?.input!==void 0)n=c.input;if(c?.policy)a={...a,...c.policy};if(c?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"PreToolUse",toolCall:e},c.appendContext));if(this.applyStopControl(c),c?.skip){i=c.reason??`Tool ${t.name} was blocked by a runtime hook`;break}}if(t&&!i){let u={...Cp(e.toolName,this.config.toolPolicies),...a};if(u.enabled===!1)i=`Tool "${e.toolName}" is disabled by policy`;else if(u.autoApprove===!1){let c=await this.requestToolApproval(e,n,u);if(!c.approved)i=`${c.reason??"Tool was not executed"} -- ${ar}`}}return{toolCall:{...e,input:n},tool:t,input:n,skipReason:i}}async requestToolApproval(e,t,n){let i=this.config.requestToolApproval;if(!i)return{approved:!1,reason:`Tool "${e.toolName}" requires approval but no approval callback is configured`};try{return await i({sessionId:this.config.sessionId?.trim()||this.config.conversationId?.trim()||this.state.runId||this.state.agentId,agentId:this.state.agentId,conversationId:this.config.conversationId?.trim()||this.state.runId||this.state.agentId,iteration:this.state.iteration,toolCallId:e.toolCallId,toolName:e.toolName,input:t,policy:n})}catch(r){return{approved:!1,reason:`Tool "${e.toolName}" approval request failed: ${r instanceof Error?r.message:String(r)}`}}}async executePreparedTool(e){let t=new Date,n=Date.now();await this.emit({type:"tool-started",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall});let i=Date.now(),r;if(e.skipReason)r={output:{error:e.skipReason},isError:!0};else if(!e.tool)r={output:{error:`Unknown tool: ${e.toolCall.toolName}`},isError:!0};else try{if(r={output:await e.tool.execute(e.input,{sessionId:this.config.sessionId,agentId:this.state.agentId,conversationId:this.config.conversationId,runId:this.state.runId??ye("run"),iteration:this.state.iteration,toolCallId:e.toolCall.toolCallId,signal:this.abortController?.signal,metadata:this.config.toolContextMetadata,snapshot:this.snapshot(),reportStoppedForUser:()=>{this.stoppedForUserBy=e.toolCall.toolName},emitUpdate:(d)=>{this.emit({type:"tool-updated",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,update:d})}})},this.stoppedForUserBy!==void 0&&this.stoppedForUserBy!==e.toolCall.toolName&&e.tool.readOnly!==!0)this.stoppedForUserBy=void 0}catch(c){r={output:{error:c instanceof Error?c.message:String(c)},isError:!0}}let o=new Date,s=Date.now(),a=Math.max(0,o.getTime()-t.getTime());if(e.tool)for(let c of this.hooks.afterTool){let d=await c({snapshot:this.snapshot(),tool:e.tool,toolCall:e.toolCall,input:e.input,result:r,startedAt:t,endedAt:o,durationMs:a});if(d?.appendContext?.trim())this.pendingHookContexts.push(nn({source:"PostToolUse",toolCall:e.toolCall},d.appendContext));if(this.applyStopControl(d),d?.result)r=d.result}this.trace(`tool ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`),this.config.logger?.debug?.(`[tool-timing] ${e.toolCall.toolName} prepare=${e.prepareMs??-1}ms preEmit=${i-n}ms exec=${s-i}ms afterHooks=${Date.now()-s}ms total=${Date.now()-n}ms | hooks ${this.topEventHooks()}`);let u=de("tool",[{type:"tool-result",toolCallId:e.toolCall.toolCallId,toolName:e.toolCall.toolName,output:r.output,isError:r.isError}]);return await this.emit({type:"tool-finished",snapshot:this.snapshot(),iteration:this.state.iteration,toolCall:e.toolCall,message:u}),u}finishRun(e,t,n){return this.state.status=e,{agentId:this.state.agentId,agentRole:this.state.agentRole,runId:this.state.runId??ye("run"),status:e,iterations:this.state.iteration,outputText:n??Oe(t??this.findLastAssistantMessage()),messages:Y(this.state.messages),usage:oe(this.state.usage)}}findLastAssistantMessage(){return[...this.state.messages].reverse().find((e)=>e.role==="assistant")}recordCut(e){let t=this.config.onLoopCut;if(!t||!e.text)return;let n={agentId:this.state.agentId,iteration:this.state.iteration,...e};Promise.resolve().then(()=>t(n)).catch((i)=>{this.config.logger?.debug?.(`[loop-cut] could not keep the ${e.channel} cut at iteration ${n.iteration}: ${String(i)}`)})}async onReasoningLoopCut(e,t="reasoning",n="reasoning_loop"){this.reasoningLoopStreak+=1;let i=(this.config.reasoningLoopDetection===!1?void 0:this.config.reasoningLoopDetection?.maxConsecutiveTrips)??gt.maxConsecutiveTrips,r=Vt(e,t),o=this.reasoningLoopStreak>=i,s=o?await this.config.onReasoningLoopLimitReached?.({iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,maxConsecutiveTrips:i,diagnosis:r}):void 0,a=s?.action==="continue"?s.guidance?.trim():void 0,u=o&&s?.action!=="continue";if(await this.emit({type:"status-notice",snapshot:this.snapshot(),message:u?`${r} Ending the run after ${this.reasoningLoopStreak} turns cut for this.`:o?`${r} That is ${this.reasoningLoopStreak} turns cut for this, and the run was to end here.`:`${r} Cutting the request and continuing.`,metadata:{kind:"reasoning_loop",reason:"reasoning_loop",phase:u?"aborted":"cut",cause:n,iteration:this.state.iteration,consecutiveTrips:this.reasoningLoopStreak,verdict:e,channel:t}}),u){this.abort(new ve(r)),this.throwIfAborted();return}return a}toolArgumentNames(){let e=new Set;for(let t of this.tools.values()){let n=t.inputSchema?.properties;for(let i of Object.keys(n??{}))e.add(i)}return[...e]}async onToolIntentCut(e){this.toolIntentCutStreak+=1,this.pendingToolIntentNudge=Kr(e);let t=e.toolName?`\`${e.toolName}\``:"a tool";this.config.logger?.log?.(`[tool-intent] cut a call to ${t} at iteration ${this.state.iteration}: intent passed ${e.maxChars} characters`),await this.emit({type:"status-notice",snapshot:this.snapshot(),message:`The model was writing its reasoning into the \`intent\` of a call to ${t} (past ${e.maxChars.toLocaleString("en-US")} characters). Cutting the request and asking it to make the call again.`,metadata:{kind:"tool_intent_overrun",reason:"tool_intent_overrun",phase:"cut",iteration:this.state.iteration,overrun:e}})}throwIfAborted(){if(this.abortController?.signal.aborted)throw this.normalizeAbortError()}normalizeAbortError(){let e=this.abortController?.signal.reason;if(e instanceof Error)return e;if(typeof e==="string")return Error(e);return Error(this.state.lastError??"Run aborted")}eventHookMs=new Map;noteEventHookMs(e,t,n){let i=`${e}#${t}`,r=this.eventHookMs.get(i);if(r)r.ms+=n,r.n+=1;else this.eventHookMs.set(i,{ms:n,n:1})}topEventHooks(e=4){return[...this.eventHookMs.entries()].sort((t,n)=>n[1].ms-t[1].ms).slice(0,e).map(([t,n])=>`${t}=${Math.round(n.ms)}ms/${n.n}`).join(" ")}trace(e){Jd(e),this.config.logger?.debug?.(`[timing] ${e}`)}async emit(e){let t=Bp(e);switch(e.type){case"run-started":this.config.logger?.info?.("Agent run started",t);break;case"tool-finished":this.config.logger?.info?.("Agent tool finished",t);break;case"run-failed":if(this.config.logger?.error?.("Agent run failed",{...t,error:e.error}),!this.state.lastErrorReported)Rr(this.config.telemetry,{component:"agents",operation:"agent.run",error:e.error,severity:"error",handled:!1,context:{...t,providerId:this.getTelemetryProviderId(),modelId:this.getTelemetryModelId(),...this.state.lastFinishReason?{finishReason:this.state.lastFinishReason}:{}}});break;default:if(!Fp.has(e.type))this.config.logger?.debug?.(`Agent event: ${e.type}`,t);break}switch(e.type){case"assistant-text-delta":case"assistant-reasoning-delta":case"assistant-media":case"tool-updated":break;default:this.config.telemetry?.capture({event:`agent.${e.type}`,properties:t});break}let n=0;for(let i of this.listeners){let r=Date.now();i(e),this.noteEventHookMs(e.type,`listener${n}`,Date.now()-r),n+=1}for(let i=0;i<this.hooks.onEvent.length;i+=1){let r=Date.now();await this.hooks.onEvent[i](e),this.noteEventHookMs(e.type,i,Date.now()-r)}}applyStopControl(e){if(!e?.stop)return;if(e.reason)this.state.lastError=e.reason;throw new Tt(e.reason)}}var Dp={no_tool_call:"the turn ended without calling anything — asking the model to carry on",unparsed_tool_call:"a tool call was written as text and never ran — asking for it again",announced_intent:"the model described the next step instead of taking it — asking it to make the call",non_convergence:"several turns of thinking with no work done — asking for a different approach",silent_repetition:"the turn repeated what the last one said — asking for a different approach"};function Up(e){return Dp[e]??`nudged: ${e}`}var Fp=new Set(["assistant-text-delta","assistant-reasoning-delta","assistant-media","tool-updated"]);function Bp(e){return{agentId:e.snapshot.agentId,agentRole:e.snapshot.agentRole,runId:e.snapshot.runId,status:e.snapshot.status,iteration:e.snapshot.iteration,eventType:e.type}}function jp(e){return new qe(e)}var qp=qe;function Hp(e){return new qe(e)}function no(e){let t=e.search(/<\|?tool_call\|?>/),n=(t<0?e:e.slice(t)).replace(/\s+/g," ").trim(),i=5381;for(let r=0;r<n.length;r++)i=(i<<5)+i+n.charCodeAt(r)|0;return`${n.length}:${i}`}export{qp as Agent,qe as AgentRuntime,ve as AgentRuntimeAbortError,bp as DEFAULT_MAX_NO_TOOL_CALL_NUDGES,io as DEFAULT_NO_TOOL_CALL_TURN_STREAK_LIMIT,gt as DEFAULT_REASONING_LOOP_GUARD,ge as DEFAULT_REASONING_REPETITION,qd as DEFAULT_TOOL_INTENT_MAX_CHARS,ro as NON_CONVERGENCE_MIN_REASONING_CHARS,me as ReasoningLoopGuard,je as ToolCallAssembler,Hp as createAgent,jp as createAgentRuntime,Gt as createRepetitionNudger,Cd as createTool,Vt as describeReasoningLoop,Lr as describeRepetition,Dd as finishToolCalls,vt as isRepetitionLoop,Xt as isToolIntentGuardEnabled,yt as measureReasoningRepetition,Hd as setToolIntentGuardEnabled};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cerebriline/agents",
|
|
3
|
-
"version": "4.100.
|
|
3
|
+
"version": "4.100.259",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "git+https://github.com/mann1x/cline.git",
|
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
"main": "dist/index.js",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"nanoid": "^5.1.7",
|
|
12
|
-
"@cerebriline/llms": "4.100.
|
|
13
|
-
"@cerebriline/shared": "4.100.
|
|
12
|
+
"@cerebriline/llms": "4.100.259",
|
|
13
|
+
"@cerebriline/shared": "4.100.259"
|
|
14
14
|
},
|
|
15
15
|
"exports": {
|
|
16
16
|
".": {
|