@stigmer/runner-slim 3.0.8 → 3.0.9-dev.20260615150714

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.
Files changed (2) hide show
  1. package/main.js +3 -3
  2. package/package.json +6 -6
package/main.js CHANGED
@@ -142,7 +142,7 @@ ${salient}`,"utf-8").toString("base64")}function buildApprovalGrants(pendingAppr
142
142
  [output truncated \u2014 offload failed: ${err instanceof Error?err.message:String(err)}]`,console.warn(`[status-offload] execution=${ctx.executionId} tool=${tc.name} offload failed (non-fatal); truncated inline`)}}function encodedSize(status){return toBinary(AgentExecutionStatusSchema,status).length}function enforceStatusSizeLimit(status,softLimitBytes=STATUS_PAYLOAD_SOFT_LIMIT_BYTES){if(encodedSize(status)<=softLimitBytes)return!1;let toolCalls=[];for(let msg of status.messages)for(let tc of msg.toolCalls)toolCalls.push(tc);toolCalls.sort((a,b)=>byteLen(b.result)+byteLen(b.argsPreview)-(byteLen(a.result)+byteLen(a.argsPreview)));let elidedAny=!1;for(let tc of toolCalls){if(encodedSize(status)<=softLimitBytes)return elidedAny;byteLen(tc.result)>ELISION_MIN_BYTES&&(tc.result=ELISION_MARKER,elidedAny=!0),byteLen(tc.argsPreview)>ELISION_MIN_BYTES&&(tc.argsPreview=ELISION_MARKER,elidedAny=!0),tc.args!==void 0&&(tc.args=void 0,elidedAny=!0)}if(encodedSize(status)>softLimitBytes){let byContent=[...status.messages].sort((a,b)=>byteLen(b.content)-byteLen(a.content));for(let msg of byContent){if(encodedSize(status)<=softLimitBytes)break;byteLen(msg.content)>ELISION_MIN_BYTES&&(msg.content=headChars(msg.content,TEXT_PREVIEW_HEAD_CHARS)+`
143
143
 
144
144
  ${ELISION_MARKER}`,elidedAny=!0)}}return elidedAny}var import_node_crypto,INLINE_TOOL_OUTPUT_MAX_BYTES,TEXT_PREVIEW_HEAD_CHARS,STATUS_PAYLOAD_SOFT_LIMIT_BYTES,STATUS_PAYLOAD_HARD_LIMIT_BYTES,ELISION_MARKER,ELISION_MIN_BYTES,init_status_offload=__esm({"dist/shared/status-offload.js"(){"use strict";import_node_crypto=require("node:crypto");init_esm4();init_api_pb3();init_message_pb();INLINE_TOOL_OUTPUT_MAX_BYTES=256*1024,TEXT_PREVIEW_HEAD_CHARS=4e3,STATUS_PAYLOAD_SOFT_LIMIT_BYTES=3*1024*1024,STATUS_PAYLOAD_HARD_LIMIT_BYTES=2*1024*1024,ELISION_MARKER="[output elided to keep status under the size limit]",ELISION_MIN_BYTES=1024}});function isRetryableError(err){return err instanceof ConnectError?RETRYABLE_CODES.has(err.code):!1}function isTerminalError(err){return err instanceof ConnectError?TERMINAL_CODES.has(err.code):!1}var RETRYABLE_CODES,TERMINAL_CODES,init_grpc_retry=__esm({"dist/shared/grpc-retry.js"(){"use strict";init_esm5();RETRYABLE_CODES=new Set([Code.Unavailable,Code.DeadlineExceeded]),TERMINAL_CODES=new Set([Code.InvalidArgument,Code.NotFound,Code.PermissionDenied])}});function utcTimestamp(){return new Date().toISOString().replace("+00:00","Z")}function isPayloadTooLarge(err){if(typeof err=="object"&&err!==null&&"code"in err&&err.code===8)return!0;let msg=err instanceof Error?err.message:String(err);return/resource_exhausted|exceeds maximum size/i.test(msg)}function defaultDelay(ms){return new Promise(resolve5=>setTimeout(resolve5,ms))}async function persistStatus(client2,executionId,status,options={}){let{offload,retry}=options;if(offload)try{await offloadOversizedToolOutputs(status,offload)}catch(err){console.warn(`[persistStatus] ${executionId}: tool-output offload failed (non-fatal): ${err}`)}enforceStatusSizeLimit(status)&&console.warn(`[persistStatus] ${executionId}: status exceeded the soft size limit; elided oversized inline fields to fit under the gRPC cap`);let baseDelayMs=retry?.baseDelayMs??DEFAULT_PERSIST_RETRY.baseDelayMs,backoffFactor=retry?.backoffFactor??DEFAULT_PERSIST_RETRY.backoffFactor,maxRetries=retry?.maxRetries??DEFAULT_PERSIST_RETRY.maxRetries,delay=retry?.delayFn??defaultDelay;for(let attempt=0;attempt<=maxRetries;attempt++)try{return(await client2.updateStatus(executionId,status)).signal}catch(err){if(isPayloadTooLarge(err)){console.error(`[persistStatus] ${executionId}: payload rejected as too large despite the size guard; hard-eliding and retrying once`),enforceStatusSizeLimit(status,STATUS_PAYLOAD_HARD_LIMIT_BYTES);try{return(await client2.updateStatus(executionId,status)).signal}catch(retryErr){return console.error(`[persistStatus] ${executionId}: still failing after hard elide:`,retryErr),ExecutionControlSignal.UNSPECIFIED}}if(isTerminalError(err))return console.error(`[persistStatus] ${executionId}: terminal error persisting status (attempt ${attempt+1}/${maxRetries+1}): ${err}`),ExecutionControlSignal.UNSPECIFIED;if(isRetryableError(err)&&attempt<maxRetries){let delayMs=baseDelayMs*Math.pow(backoffFactor,attempt);console.warn(`[persistStatus] ${executionId}: retryable error (attempt ${attempt+1}/${maxRetries+1}, retry in ${delayMs}ms): ${err}`),await delay(delayMs);continue}return console.error(`Failed to persist status for ${executionId}:`,err),ExecutionControlSignal.UNSPECIFIED}return ExecutionControlSignal.UNSPECIFIED}async function reportSetupProgress(client2,executionId,phase){let status=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_IN_PROGRESS,setupProgress:create(SetupProgressSchema,{currentPhase:phase})});await persistStatus(client2,executionId,status)}function slimStatus(full){let slim=create(AgentExecutionStatusSchema,{phase:full.phase,error:full.error,startedAt:full.startedAt,completedAt:full.completedAt,pendingApprovals:full.pendingApprovals,structuredOutput:full.structuredOutput}),json5=toJson(AgentExecutionStatusSchema,slim);if(full.structuredOutput){let jsonObj=json5,hasField="structuredOutput"in jsonObj;console.log(`[slimStatus] structuredOutput serialization: inputPresent=true, outputFieldPresent=${hasField}, outputKeys=${Object.keys(jsonObj).join(",")}`)}return json5}var DEFAULT_PERSIST_RETRY,init_status2=__esm({"dist/shared/status.js"(){"use strict";init_esm4();init_api_pb3();init_enum_pb();init_status_offload();init_grpc_retry();DEFAULT_PERSIST_RETRY={baseDelayMs:100,backoffFactor:2,maxRetries:3}}});function extractMcpToolDetails(event){if(event.name!=="mcp")return;let args=event.args;if(args==null||typeof args!="object")return;let obj=args,providerIdentifier=typeof obj.providerIdentifier=="string"?obj.providerIdentifier:"",toolName=typeof obj.toolName=="string"?obj.toolName:"";if(!toolName)return;let innerArgs=typeof obj.args=="object"&&obj.args!==null?obj.args:{};return{providerIdentifier,toolName,innerArgs}}function buildToolCallProto(event,mergedPolicies){let status=mapToolCallStatus(event.status),mcpDetails=extractMcpToolDetails(event),actualName=mcpDetails?.toolName??event.name,mcpServerSlug=mcpDetails?.providerIdentifier??"",toolCall=create(ToolCallSchema,{id:event.call_id,name:actualName,status,startedAt:status===ToolCallStatus.TOOL_CALL_RUNNING?utcTimestamp():"",completedAt:isTerminalToolStatus(status)?utcTimestamp():"",result:toResultString(event.result),error:status===ToolCallStatus.TOOL_CALL_FAILED?typeof event.result=="string"?event.result:"Tool call failed":"",mcpServerSlug,toolKind:classifyTool(actualName,mcpServerSlug)});event.args!=null&&(toolCall.argsPreview=typeof event.args=="string"?event.args:JSON.stringify(event.args));let argsObj=mcpDetails?.innerArgs??(typeof event.args=="object"&&event.args!==null?event.args:void 0);if(argsObj&&typeof argsObj=="object"&&(toolCall.args=argsObj),mergedPolicies&&mcpDetails){let policy=lookupMcpToolPolicy(actualName,mcpServerSlug,mergedPolicies);policy&&(toolCall.requiresApproval=!0,toolCall.approvalMessage=resolveApprovalMessage(policy.approvalMessage,actualName,mcpDetails.innerArgs),status===ToolCallStatus.TOOL_CALL_FAILED&&(toolCall.approvalRequestedAt=utcTimestamp()))}else if(mergedPolicies&&!mcpDetails){let requires=builtInRequiresApproval(actualName);if(toolCall.requiresApproval=requires,requires){let template=getBuiltInApprovalMessage(actualName);template&&(toolCall.approvalMessage=resolveApprovalMessage(template,actualName,argsObj??{}),status===ToolCallStatus.TOOL_CALL_FAILED&&(toolCall.approvalRequestedAt=utcTimestamp()))}}return toolCall}function translateTask(event){return create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:event.text??"",timestamp:utcTimestamp()})}function mapToolCallStatus(cursorStatus){switch(cursorStatus){case"running":return ToolCallStatus.TOOL_CALL_RUNNING;case"completed":return ToolCallStatus.TOOL_CALL_COMPLETED;case"error":return ToolCallStatus.TOOL_CALL_FAILED;default:return ToolCallStatus.TOOL_CALL_STATUS_UNSPECIFIED}}function mapSubAgentStatus(cursorStatus){switch(cursorStatus){case"running":return SubAgentStatus.SUB_AGENT_IN_PROGRESS;case"completed":return SubAgentStatus.SUB_AGENT_COMPLETED;case"error":return SubAgentStatus.SUB_AGENT_FAILED;default:return SubAgentStatus.SUB_AGENT_PENDING}}function isTerminalToolStatus(status){return status===ToolCallStatus.TOOL_CALL_COMPLETED||status===ToolCallStatus.TOOL_CALL_FAILED||status===ToolCallStatus.TOOL_CALL_SKIPPED}function extractSubagentName(args){if(args==null||typeof args!="object")return"task";let obj=args,subagentType=obj.subagentType??obj.subagent_type;if(typeof subagentType=="string"&&subagentType)return subagentType;if(subagentType!=null&&typeof subagentType=="object"){let typed=subagentType;if(typeof typed.name=="string"&&typed.name)return typed.name;if(typeof typed.kind=="string"&&typed.kind&&typed.kind!=="unspecified")return typed.kind}return typeof obj.description=="string"&&obj.description?obj.description:"task"}function safeString(obj,key){if(obj!=null&&typeof obj=="object"&&key in obj){let val=obj[key];return typeof val=="string"?val:""}return""}function toResultString(result){if(result==null)return"";if(typeof result=="string")return result;let canonical=canonicalizeImageResult(result);return canonical!==void 0?canonical:JSON.stringify(result)}function canonicalizeImageResult(result){if(result==null||typeof result!="object")return;let blocks2=resultContentBlocks(result);if(!blocks2)return;let canonical=[],sawImage=!1;for(let block of blocks2){if(!block||typeof block!="object")continue;let b=block;if(b.image&&typeof b.image=="object"){let img=b.image,base646=imageDataToBase64(img.data);if(base646){let mimeType=typeof img.mimeType=="string"?img.mimeType:"image/png";canonical.push({type:"image",data:base646,mimeType}),sawImage=!0;continue}}let text=blockText(b);text!==void 0&&canonical.push({type:"text",text})}return sawImage?JSON.stringify(canonical):void 0}function resultContentBlocks(obj){let value=obj.value;if(value&&typeof value=="object"&&Array.isArray(value.content))return value.content;if(Array.isArray(obj.content))return obj.content}function imageDataToBase64(data){if(data&&typeof data=="object"){let d=data;if(d.type==="Buffer"&&Array.isArray(d.data))try{return Buffer.from(d.data).toString("base64")}catch{return}return}if(typeof data=="string"&&data){let dataUrl=data.match(/^data:image\/[a-zA-Z0-9.+-]+;base64,([\s\S]+)$/);return(dataUrl?dataUrl[1]:data).replace(/\s+/g,"")}}function blockText(b){let t=b.text;if(typeof t=="string")return t;if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}function extractConversationSteps(result,out){if(result==null||typeof result!="object")return;let r=result,value=r.value??r;if(value==null||typeof value!="object")return;let steps=value.conversationSteps;if(Array.isArray(steps))for(let step of steps){if(step==null||typeof step!="object")continue;let s=step,type3=s.type;if(type3==="thinkingMessage"||s.thinkingMessage!=null){let msg=type3==="thinkingMessage"?s.message:s.thinkingMessage,text=typeof msg?.text=="string"?msg.text:"";text&&out.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:text,timestamp:utcTimestamp()}))}else if(type3==="assistantMessage"||s.assistantMessage!=null){let msg=type3==="assistantMessage"?s.message:s.assistantMessage,text=typeof msg?.text=="string"?msg.text:"";text&&out.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:text,timestamp:utcTimestamp()}))}else if(type3==="toolCall"){let msg=s.message;if(msg){let toolName=typeof msg.type=="string"?msg.type:"unknown",toolArgs=msg.args!=null?JSON.stringify(msg.args):"",toolResult="";if(msg.result!=null){let resultObj=msg.result;resultObj.status==="success"&&resultObj.value!=null?toolResult=canonicalizeImageResult(resultObj.value)??(typeof resultObj.value=="string"?resultObj.value:JSON.stringify(resultObj.value)):resultObj.status==="error"?toolResult=typeof resultObj.error=="string"?resultObj.error:JSON.stringify(resultObj):toolResult=JSON.stringify(msg.result)}let aiMsg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),toolCalls:[create(ToolCallSchema,{id:`sub-${toolName}-${out.length}`,name:toolName,status:ToolCallStatus.TOOL_CALL_COMPLETED,argsPreview:toolArgs,result:toolResult,startedAt:utcTimestamp(),completedAt:utcTimestamp(),toolKind:classifyTool(toolName)})]});out.push(aiMsg)}}}}function cancelInProgressSubAgentProtos(subAgents){let changed=!1;for(let sub of subAgents)(sub.status===SubAgentStatus.SUB_AGENT_IN_PROGRESS||sub.status===SubAgentStatus.SUB_AGENT_PENDING)&&(sub.status=SubAgentStatus.SUB_AGENT_CANCELLED,sub.completedAt=utcTimestamp(),changed=!0);return changed}function reconcileDeniedToolCalls(messages,ledger,mergedPolicies){if(ledger.length===0)return[];let deniedTokens=new Set(ledger.map(e=>e.token)),matched=new Set,result=[];for(let msg of messages)for(let tc of msg.toolCalls){let token=toolCallIdentityToken(tc);!deniedTokens.has(token)||matched.has(token)||(markWaitingApproval(tc,mergedPolicies),matched.add(token),result.push(tc))}for(let entry of ledger){if(matched.has(entry.token))continue;let decoded=decodeIdentityToken(entry.token),displayName=entry.toolName||decoded?.key||"tool",salient=decoded?.salient??"",tc=synthesizeWaitingApprovalToolCall(displayName,salient,entry.token,mergedPolicies);appendToolCallToLastAiMessage(messages,tc),matched.add(entry.token),result.push(tc)}return result}function toolCallIdentityToken(tc){let id=toolIdentity(tc.name,tc.mcpServerSlug,toolCallArgs(tc));return grantToken(id.key,id.salient)}function decodeIdentityToken(token){try{let decoded=Buffer.from(token,"base64").toString("utf-8"),nl=decoded.indexOf(`
145
- `);return nl<0?void 0:{key:decoded.slice(0,nl),salient:decoded.slice(nl+1)}}catch{return}}function toolCallArgs(tc){if(tc.args&&typeof tc.args=="object")return tc.args;if(tc.argsPreview)try{let parsed=JSON.parse(tc.argsPreview);if(parsed&&typeof parsed=="object")return parsed}catch{}return{}}function markWaitingApproval(tc,mergedPolicies){tc.status=ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,tc.requiresApproval=!0,tc.approvalMessage||(tc.approvalMessage=resolveDeniedApprovalMessage(tc.name,tc.mcpServerSlug,toolCallArgs(tc),mergedPolicies)),tc.approvalRequestedAt||(tc.approvalRequestedAt=utcTimestamp()),tc.completedAt="",tc.error="",tc.result=""}function synthesizeWaitingApprovalToolCall(displayName,salient,token,mergedPolicies){let tc=create(ToolCallSchema,{id:`approval:${token}`,name:displayName,status:ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,requiresApproval:!0,startedAt:utcTimestamp(),approvalRequestedAt:utcTimestamp(),toolKind:classifyTool(displayName)});return salient&&(tc.argsPreview=JSON.stringify({path:salient})),tc.approvalMessage=salient?`Tool requires approval: ${displayName} (${salient})`:resolveDeniedApprovalMessage(displayName,"",{},mergedPolicies),tc}function resolveDeniedApprovalMessage(name2,mcpServerSlug,args,mergedPolicies){if(mergedPolicies&&mcpServerSlug){let policy=lookupMcpToolPolicy(name2,mcpServerSlug,mergedPolicies);if(policy)return resolveApprovalMessage(policy.approvalMessage,name2,args)}if(!mcpServerSlug){let template=getBuiltInApprovalMessage(name2);if(template)return resolveApprovalMessage(template,name2,args)}return`Tool requires approval: ${name2}`}function appendToolCallToLastAiMessage(messages,tc){for(let i2=messages.length-1;i2>=0;i2--)if(messages[i2].type===MessageType.MESSAGE_AI){messages[i2].toolCalls.push(tc);return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),toolCalls:[tc]});messages.push(msg)}var SUPPRESSED_TOOL_NAMES,MessageAccumulator,init_message_translator=__esm({"dist/activities/execute-cursor/message-translator.js"(){"use strict";init_esm4();init_message_pb();init_subagent_pb();init_enum_pb();init_approval_policy();init_approval_state();init_status2();init_tool_kind();SUPPRESSED_TOOL_NAMES=new Set(["TodoWrite","updateTodos"]);MessageAccumulator=class{messages;activeAiByRunId=new Map;activeThinkingByRunId=new Map;_subAgentExecutions=[];subAgentMap=new Map;mergedPolicies;toolCallIndex=new Map;_subAgentDirty=!1;constructor(messages,options){this.messages=messages,this.mergedPolicies=options?.mergedPolicies}get subAgentExecutions(){return this._subAgentExecutions}get subAgentDirty(){return this._subAgentDirty}markSubAgentPersisted(){this._subAgentDirty=!1}cancelInProgressSubAgents(){cancelInProgressSubAgentProtos(this._subAgentExecutions)&&(this._subAgentDirty=!0)}processEvent(event){switch(event.type){case"assistant":this.accumulateAssistant(event);break;case"thinking":this.accumulateThinking(event);break;case"tool_call":this.finalizeStreaming(event.run_id),this.attachToolCallToLastAi(event);break;case"task":event.text&&this.messages.push(translateTask(event));break}}finalize(){for(let msg of this.activeAiByRunId.values())msg.isStreaming=!1;for(let msg of this.activeThinkingByRunId.values())msg.isStreaming=!1;this.activeAiByRunId.clear(),this.activeThinkingByRunId.clear()}attachToolCallToLastAi(event){if(SUPPRESSED_TOOL_NAMES.has(event.name))return;let existing=this.toolCallIndex.get(event.call_id);if(!existing){let tc=buildToolCallProto(event,this.mergedPolicies);this.findOrCreateLastAiMessage().toolCalls.push(tc),this.toolCallIndex.set(event.call_id,tc);return}this.mergeToolCallEvent(existing,event)}mergeToolCallEvent(existing,event){let status=mapToolCallStatus(event.status);isTerminalToolStatus(existing.status)||(existing.status=status),isTerminalToolStatus(status)&&!existing.completedAt&&(existing.completedAt=utcTimestamp()),!existing.startedAt&&status===ToolCallStatus.TOOL_CALL_RUNNING&&(existing.startedAt=utcTimestamp());let incomingResult=toResultString(event.result);incomingResult&&(existing.result=incomingResult),status===ToolCallStatus.TOOL_CALL_FAILED&&(existing.error||(existing.error=typeof event.result=="string"?event.result:"Tool call failed"),existing.requiresApproval&&!existing.approvalRequestedAt&&(existing.approvalRequestedAt=utcTimestamp())),event.args!=null&&!existing.argsPreview&&(existing.argsPreview=typeof event.args=="string"?event.args:JSON.stringify(event.args))}findOrCreateLastAiMessage(){for(let i2=this.messages.length-1;i2>=0;i2--)if(this.messages[i2].type===MessageType.MESSAGE_AI)return this.messages[i2];let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp()});return this.messages.push(msg),msg}trackSubAgentExecution(event){let existing=this.subAgentMap.get(event.call_id);if(existing)return existing.status=mapSubAgentStatus(event.status),(event.status==="completed"||event.status==="error")&&(existing.completedAt=utcTimestamp()),event.status==="completed"&&event.result!=null&&(existing.output=typeof event.result=="string"?event.result:JSON.stringify(event.result),extractConversationSteps(event.result,existing.messages)),event.status==="error"&&(existing.error=typeof event.result=="string"?event.result:"Sub-agent failed"),this._subAgentDirty=!0,existing;let sub=create(SubAgentExecutionSchema,{id:event.call_id,name:extractSubagentName(event.args),subject:safeString(event.args,"description"),input:safeString(event.args,"prompt"),status:mapSubAgentStatus(event.status),startedAt:utcTimestamp()});return this._subAgentExecutions.push(sub),this.subAgentMap.set(event.call_id,sub),this._subAgentDirty=!0,sub}accumulateAssistant(event){let text=event.message.content.filter(b=>b.type==="text").map(b=>b.text).join("");if(!text)return;let existing=this.activeAiByRunId.get(event.run_id);if(existing){existing.content+=text;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:text,timestamp:utcTimestamp(),isStreaming:!0});this.messages.push(msg),this.activeAiByRunId.set(event.run_id,msg)}accumulateThinking(event){if(!event.text)return;let existing=this.activeThinkingByRunId.get(event.run_id);if(existing){existing.content+=event.text;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:event.text,timestamp:utcTimestamp(),isStreaming:!0});this.messages.push(msg),this.activeThinkingByRunId.set(event.run_id,msg)}finalizeStreaming(runId){let ai=this.activeAiByRunId.get(runId);ai&&(ai.isStreaming=!1,this.activeAiByRunId.delete(runId));let thinking=this.activeThinkingByRunId.get(runId);thinking&&(thinking.isStreaming=!1,this.activeThinkingByRunId.delete(runId))}}}});function formatStallFailure(error91){return`${STALL_ERROR_PREFIX} ${error91.message}. Retry or resume.`}function startStallWatchdog(stallMs,onStall){let lastActivityAt2=Date.now(),fired=!1,timer,tickMs=Math.min(Math.max(Math.floor(stallMs/4),1),15e3),disarm=()=>{timer!==void 0&&(clearInterval(timer),timer=void 0)};return timer=setInterval(()=>{if(fired)return;let idleMs=Date.now()-lastActivityAt2;idleMs>=stallMs&&(fired=!0,disarm(),onStall(idleMs))},tickMs),timer.unref?.(),{recordActivity(){lastActivityAt2=Date.now()},stop(){fired=!0,disarm()}}}var StallTimeoutError,STALL_ERROR_PREFIX,init_stall_watchdog=__esm({"dist/shared/stall-watchdog.js"(){"use strict";StallTimeoutError=class extends Error{stalledMs;constructor(stalledMs,detail){super(`Agent stream stalled: no activity for ${Math.round(stalledMs/1e3)}s`+(detail?` (${detail})`:"")),this.stalledMs=stalledMs,this.name="StallTimeoutError"}},STALL_ERROR_PREFIX="[StallTimeoutError]"}});var artifact_storage_exports={};__export(artifact_storage_exports,{LocalArtifactStorage:()=>LocalArtifactStorage,ProxyArtifactStorage:()=>ProxyArtifactStorage,createArtifactStorage:()=>createArtifactStorage,loadArtifactStorageConfig:()=>loadArtifactStorageConfig});function loadArtifactStorageConfig(config4){let envType=process.env.ARTIFACT_STORAGE_TYPE,type3=envType==="proxy"?"proxy":envType==="local"?"local":config4.proxyEndpoint?"proxy":"local";return{type:type3,localPath:process.env.LOCAL_ARTIFACT_PATH??"/var/stigmer/artifacts",localServeUrl:process.env.LOCAL_ARTIFACT_SERVE_URL??"http://localhost:7235",proxyEndpoint:type3==="proxy"?config4.proxyEndpoint??null:null,proxyAuthToken:type3==="proxy"?config4.stigmerToken??null:null}}function createArtifactStorage(cfg){if(cfg.type==="proxy"){if(!cfg.proxyEndpoint)throw new Error("Proxy artifact storage requires STIGMER_PROXY_ENDPOINT");if(!cfg.proxyAuthToken)throw new Error("Proxy artifact storage requires STIGMER_TOKEN");return new ProxyArtifactStorage(cfg.proxyEndpoint,cfg.proxyAuthToken)}return new LocalArtifactStorage(cfg.localPath,cfg.localServeUrl)}var import_promises2,import_node_path4,LocalArtifactStorage,ProxyArtifactStorage,init_artifact_storage=__esm({"dist/shared/artifact-storage.js"(){"use strict";import_promises2=require("node:fs/promises"),import_node_path4=require("node:path"),LocalArtifactStorage=class{basePath;serveUrlBase;constructor(basePath,serveUrlBase){this.basePath=basePath,this.serveUrlBase=serveUrlBase.replace(/\/+$/,"")}async upload(key,content,_contentType){let filePath=(0,import_node_path4.join)(this.basePath,key);return await(0,import_promises2.mkdir)((0,import_node_path4.dirname)(filePath),{recursive:!0}),await(0,import_promises2.writeFile)(filePath,content),key}async getDownloadUrl(key){return`${this.serveUrlBase}/${key}`}async exists(key){try{return await(0,import_promises2.access)((0,import_node_path4.join)(this.basePath,key)),!0}catch{return!1}}},ProxyArtifactStorage=class{baseUrl;authToken;constructor(proxyEndpoint,authToken){this.baseUrl=`${proxyEndpoint.replace(/\/+$/,"")}/v1/proxy/artifacts`,this.authToken=authToken}async upload(key,content,contentType){let ct=contentType??"application/octet-stream",presignResp=await fetch(`${this.baseUrl}/presigned-upload-url`,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({key,content_type:ct})});if(!presignResp.ok)throw new Error(`Failed to get presigned upload URL (HTTP ${presignResp.status}): `+await presignResp.text());let data=await presignResp.json(),signedHeaders=data.headers??{},uploadHeaders={},contentTypeSigned=!1;for(let[name2,value]of Object.entries(signedHeaders))name2.toLowerCase()!=="host"&&(name2.toLowerCase()==="content-type"&&(contentTypeSigned=!0),uploadHeaders[name2]=value);contentTypeSigned||(uploadHeaders["Content-Type"]=ct);let putResp=await fetch(data.url,{method:"PUT",headers:uploadHeaders,body:content});if(!putResp.ok)throw new Error(`Presigned upload failed (HTTP ${putResp.status}): `+await putResp.text());return key}async getDownloadUrl(key){let resp=await fetch(`${this.baseUrl}/presigned-download-url`,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({key})});if(!resp.ok)throw new Error(`Failed to get presigned download URL (HTTP ${resp.status}): `+await resp.text());return(await resp.json()).url}async exists(key){try{return(await fetch(`${this.baseUrl}/presigned-download-url`,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({key})})).ok}catch{return!1}}}}});async function publishPlanArtifact(opts){let{status,executionId,planText,artifactStorage}=opts;if(planText.trim().length!==0)try{let content=Buffer.from(planText,"utf-8"),contentHash=(0,import_node_crypto2.createHash)("sha256").update(content).digest("hex"),storageKey=`artifacts/${executionId}/${PLAN_ARTIFACT_NAME}`;await artifactStorage.upload(storageKey,content,"text/markdown");let downloadUrl=await artifactStorage.getDownloadUrl(storageKey),artifact=create(ExecutionArtifactSchema,{name:PLAN_ARTIFACT_NAME,sandboxPath:PLAN_ARTIFACT_SANDBOX_PATH,kind:ExecutionArtifactKind.FILE,sizeBytes:BigInt(content.length),storageKey,downloadUrl,createdAt:utcTimestamp(),contentHash}),existingIdx=status.artifacts.findIndex(a=>a.name===PLAN_ARTIFACT_NAME);existingIdx>=0?status.artifacts[existingIdx]=artifact:status.artifacts.push(artifact),console.log(`[plan-artifact] execution=${executionId} \u2014 published ${PLAN_ARTIFACT_NAME} (${content.length} bytes, hash=${contentHash.slice(0,12)})`)}catch(err){console.warn(`[plan-artifact] execution=${executionId} \u2014 failed to publish plan (non-fatal): ${err}`)}}var import_node_crypto2,PLAN_ARTIFACT_NAME,PLAN_ARTIFACT_SANDBOX_PATH,init_plan_artifact=__esm({"dist/shared/plan-artifact.js"(){"use strict";import_node_crypto2=require("node:crypto");init_esm4();init_artifact_pb();init_enum_pb();init_status2();PLAN_ARTIFACT_NAME="plan.md",PLAN_ARTIFACT_SANDBOX_PATH=".stigmer/plans/plan.md"}});function findToolCallById(messages,callId){for(let i2=messages.length-1;i2>=0;i2--)for(let tc of messages[i2].toolCalls)if(tc.id===callId)return tc}function extractShellOutputText(event){return typeof event.data=="string"?event.data:typeof event.output=="string"?event.output:typeof event.text=="string"?event.text:""}function extractCallIdFromShellEvent(event){if(typeof event.callId=="string")return event.callId;if(typeof event.call_id=="string")return event.call_id;if(typeof event.id=="string")return event.id}var DeltaEnricher,init_delta_enricher=__esm({"dist/activities/execute-cursor/delta-enricher.js"(){"use strict";init_enum_pb();init_message_translator();DeltaEnricher=class _DeltaEnricher{shellOutputByCallId=new Map;timingByCallId=new Map;thinkingDurationMs;_isDirty=!1;lastPersistTime=0;lastShellCallId;static PERSIST_DEBOUNCE_MS=500;processDelta(update){switch(update.type){case"shell-output-delta":this.handleShellOutputDelta(update);break;case"tool-call-started":this.handleToolCallStarted(update);break;case"tool-call-completed":this.handleToolCallCompleted(update);break;case"thinking-completed":this.thinkingDurationMs=update.thinkingDurationMs;break}}applyEnrichments(messages){let applied=!1;return this.shellOutputByCallId.size>0&&(applied=this.applyShellOutput(messages)||applied),this.timingByCallId.size>0&&(applied=this.applyTiming(messages)||applied),this.thinkingDurationMs!==void 0&&(applied=this.applyThinkingDuration(messages)||applied),applied}get isDirty(){return this._isDirty?Date.now()-this.lastPersistTime>=_DeltaEnricher.PERSIST_DEBOUNCE_MS:!1}markPersisted(){this._isDirty=!1,this.lastPersistTime=Date.now()}finalize(messages){for(let msg of messages)for(let tc of msg.toolCalls)tc.isStreaming&&(tc.isStreaming=!1,tc.streamingSource=ToolCallStreamingSource.UNSPECIFIED),tc.status===ToolCallStatus.TOOL_CALL_RUNNING&&(tc.completedAt||tc.result)&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.completedAt||(tc.completedAt=utcTimestamp()),console.log(`DeltaEnricher finalize reconciliation: promoted tool call ${tc.id} (${tc.name}) from RUNNING to COMPLETED`))}handleShellOutputDelta(update){let event=update.event,text=extractShellOutputText(event);if(!text)return;let callId=extractCallIdFromShellEvent(event)??this.lastShellCallId;if(!callId)return;let buffer=this.shellOutputByCallId.get(callId);buffer||(buffer={chunks:[],totalLength:0},this.shellOutputByCallId.set(callId,buffer)),buffer.chunks.push(text),buffer.totalLength+=text.length,this._isDirty=!0}handleToolCallStarted(update){let timing=this.getOrCreateTiming(update.callId);timing.startedAt=utcTimestamp(),update.toolCall.type==="shell"&&(this.lastShellCallId=update.callId)}handleToolCallCompleted(update){let timing=this.getOrCreateTiming(update.callId);timing.completedAt=utcTimestamp()}getOrCreateTiming(callId){let timing=this.timingByCallId.get(callId);return timing||(timing={},this.timingByCallId.set(callId,timing)),timing}applyShellOutput(messages){let applied=!1;for(let[callId,buffer]of this.shellOutputByCallId){let tc=findToolCallById(messages,callId);if(!tc)continue;let content=buffer.chunks.join("");tc.result=content,tc.isStreaming=!0,tc.streamingSource=ToolCallStreamingSource.OUTPUT,buffer.chunks=[content],applied=!0}return applied}applyTiming(messages){let applied=!1;for(let[callId,timing]of this.timingByCallId){let tc=findToolCallById(messages,callId);tc&&(timing.startedAt&&!tc.startedAt&&(tc.startedAt=timing.startedAt,applied=!0),timing.completedAt&&!tc.completedAt&&(tc.completedAt=timing.completedAt,applied=!0),timing.completedAt&&tc.status===ToolCallStatus.TOOL_CALL_RUNNING&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,applied=!0),this.timingByCallId.delete(callId))}return applied}applyThinkingDuration(_messages){return this.thinkingDurationMs!==void 0?(console.log(`DeltaEnricher: thinking completed in ${this.thinkingDurationMs}ms`),this.thinkingDurationMs=void 0,!0):!1}}}});var TODO_TOOL_NAMES,STATUS_MAP,TodoTracker,init_todo_tracker=__esm({"dist/activities/execute-cursor/todo-tracker.js"(){"use strict";init_esm4();init_todo_pb();init_enum_pb();init_message_translator();TODO_TOOL_NAMES=new Set(["TodoWrite","updateTodos"]),STATUS_MAP={pending:TodoStatus.TODO_PENDING,in_progress:TodoStatus.TODO_IN_PROGRESS,inprogress:TodoStatus.TODO_IN_PROGRESS,completed:TodoStatus.TODO_COMPLETED,cancelled:TodoStatus.TODO_CANCELLED},TodoTracker=class{todos;_isDirty=!1;constructor(todos){this.todos=todos}processEvent(event){if(event.type!=="tool_call"||!TODO_TOOL_NAMES.has(event.name)||event.status!=="completed")return;let args=this.parseArgs(event.args);if(!args)return;let rawTodos=args.todos;if(!Array.isArray(rawTodos)||rawTodos.length===0){args.merge!==!0&&(this.clearMap(),this._isDirty=!0);return}let merge4=args.merge===!0,now=utcTimestamp();merge4||this.clearMap();for(let i2=0;i2<rawTodos.length;i2++){let raw=rawTodos[i2],id=raw.id||`todo-${i2}`,statusStr=(raw.status??"pending").toLowerCase(),status=STATUS_MAP[statusStr]??TodoStatus.TODO_PENDING,existing=merge4?this.todos[id]:void 0;this.todos[id]=create(TodoItemSchema,{id,content:raw.content??"",status,createdAt:existing?.createdAt||raw.created_at||now,updatedAt:now})}this._isDirty=!0,console.log(`TodoTracker: processed ${rawTodos.length} todo(s) from ${event.name} (merge=${merge4})`)}get isDirty(){return this._isDirty}markPersisted(){this._isDirty=!1}parseArgs(args){if(args==null)return null;if(typeof args=="string")try{return JSON.parse(args)}catch{return null}return typeof args=="object"?args:null}clearMap(){for(let key of Object.keys(this.todos))delete this.todos[key]}}}});function createCursorEventRecorder(executionId){let recordDir=process.env.CURSOR_EVENT_RECORD_DIR;if(recordDir)return new FileCursorEventRecorder(executionId,recordDir)}function safeClone(obj){try{return JSON.parse(JSON.stringify(obj))}catch{return obj&&typeof obj=="object"?{_serializationError:!0,keys:Object.keys(obj)}:{_serializationError:!0}}}var import_promises3,import_node_path5,FileCursorEventRecorder,init_cursor_event_recorder=__esm({"dist/activities/execute-cursor/cursor-event-recorder.js"(){"use strict";import_promises3=require("node:fs/promises"),import_node_path5=require("node:path");FileCursorEventRecorder=class{executionId;outputDir;lines=[];constructor(executionId,outputDir){this.executionId=executionId,this.outputDir=outputDir}record(event,seq2){let entry={seq:seq2,capturedAt:new Date().toISOString(),type:event.type,agent_id:event.agent_id,run_id:event.run_id,event:safeClone(event)};this.lines.push(JSON.stringify(entry))}async flush(){if(this.lines.length===0)return;await(0,import_promises3.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path5.join)(this.outputDir,`${this.executionId}.cursor-events.jsonl`);await(0,import_promises3.writeFile)(filePath,this.lines.join(`
145
+ `);return nl<0?void 0:{key:decoded.slice(0,nl),salient:decoded.slice(nl+1)}}catch{return}}function toolCallArgs(tc){if(tc.args&&typeof tc.args=="object")return tc.args;if(tc.argsPreview)try{let parsed=JSON.parse(tc.argsPreview);if(parsed&&typeof parsed=="object")return parsed}catch{}return{}}function markWaitingApproval(tc,mergedPolicies){tc.status=ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,tc.requiresApproval=!0,tc.approvalMessage||(tc.approvalMessage=resolveDeniedApprovalMessage(tc.name,tc.mcpServerSlug,toolCallArgs(tc),mergedPolicies)),tc.approvalRequestedAt||(tc.approvalRequestedAt=utcTimestamp()),tc.completedAt="",tc.error="",tc.result=""}function synthesizeWaitingApprovalToolCall(displayName,salient,token,mergedPolicies){let tc=create(ToolCallSchema,{id:`approval:${token}`,name:displayName,status:ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,requiresApproval:!0,startedAt:utcTimestamp(),approvalRequestedAt:utcTimestamp(),toolKind:classifyTool(displayName)});return salient&&(tc.argsPreview=JSON.stringify({path:salient})),tc.approvalMessage=salient?`Tool requires approval: ${displayName} (${salient})`:resolveDeniedApprovalMessage(displayName,"",{},mergedPolicies),tc}function resolveDeniedApprovalMessage(name2,mcpServerSlug,args,mergedPolicies){if(mergedPolicies&&mcpServerSlug){let policy=lookupMcpToolPolicy(name2,mcpServerSlug,mergedPolicies);if(policy)return resolveApprovalMessage(policy.approvalMessage,name2,args)}if(!mcpServerSlug){let template=getBuiltInApprovalMessage(name2);if(template)return resolveApprovalMessage(template,name2,args)}return`Tool requires approval: ${name2}`}function appendToolCallToLastAiMessage(messages,tc){for(let i2=messages.length-1;i2>=0;i2--)if(messages[i2].type===MessageType.MESSAGE_AI){messages[i2].toolCalls.push(tc);return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),toolCalls:[tc]});messages.push(msg)}var SUPPRESSED_TOOL_NAMES,MessageAccumulator,init_message_translator=__esm({"dist/activities/execute-cursor/message-translator.js"(){"use strict";init_esm4();init_message_pb();init_subagent_pb();init_enum_pb();init_approval_policy();init_approval_state();init_status2();init_tool_kind();SUPPRESSED_TOOL_NAMES=new Set(["TodoWrite","updateTodos"]);MessageAccumulator=class{messages;activeAiByRunId=new Map;activeThinkingByRunId=new Map;_subAgentExecutions=[];subAgentMap=new Map;mergedPolicies;toolCallIndex=new Map;_dirty=!1;constructor(messages,options){this.messages=messages,this.mergedPolicies=options?.mergedPolicies}get subAgentExecutions(){return this._subAgentExecutions}get isDirty(){return this._dirty}markPersisted(){this._dirty=!1}cancelInProgressSubAgents(){cancelInProgressSubAgentProtos(this._subAgentExecutions)&&(this._dirty=!0)}processEvent(event){switch(event.type){case"assistant":this.accumulateAssistant(event);break;case"thinking":this.accumulateThinking(event);break;case"tool_call":this.finalizeStreaming(event.run_id),this.attachToolCallToLastAi(event);break;case"task":event.text&&this.messages.push(translateTask(event));break}}finalize(){for(let msg of this.activeAiByRunId.values())msg.isStreaming=!1;for(let msg of this.activeThinkingByRunId.values())msg.isStreaming=!1;this.activeAiByRunId.clear(),this.activeThinkingByRunId.clear()}attachToolCallToLastAi(event){if(SUPPRESSED_TOOL_NAMES.has(event.name))return;let existing=this.toolCallIndex.get(event.call_id);if(!existing){let tc=buildToolCallProto(event,this.mergedPolicies);this.findOrCreateLastAiMessage().toolCalls.push(tc),this.toolCallIndex.set(event.call_id,tc),this._dirty=!0;return}this.mergeToolCallEvent(existing,event)}mergeToolCallEvent(existing,event){let status=mapToolCallStatus(event.status),wasTerminal=isTerminalToolStatus(existing.status);isTerminalToolStatus(existing.status)||(existing.status=status),isTerminalToolStatus(status)&&!existing.completedAt&&(existing.completedAt=utcTimestamp()),!wasTerminal&&isTerminalToolStatus(status)&&(this._dirty=!0),!existing.startedAt&&status===ToolCallStatus.TOOL_CALL_RUNNING&&(existing.startedAt=utcTimestamp());let incomingResult=toResultString(event.result);incomingResult&&(existing.result=incomingResult),status===ToolCallStatus.TOOL_CALL_FAILED&&(existing.error||(existing.error=typeof event.result=="string"?event.result:"Tool call failed"),existing.requiresApproval&&!existing.approvalRequestedAt&&(existing.approvalRequestedAt=utcTimestamp())),event.args!=null&&!existing.argsPreview&&(existing.argsPreview=typeof event.args=="string"?event.args:JSON.stringify(event.args))}findOrCreateLastAiMessage(){for(let i2=this.messages.length-1;i2>=0;i2--)if(this.messages[i2].type===MessageType.MESSAGE_AI)return this.messages[i2];let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp()});return this.messages.push(msg),msg}trackSubAgentExecution(event){let existing=this.subAgentMap.get(event.call_id);if(existing)return existing.status=mapSubAgentStatus(event.status),(event.status==="completed"||event.status==="error")&&(existing.completedAt=utcTimestamp()),event.status==="completed"&&event.result!=null&&(existing.output=typeof event.result=="string"?event.result:JSON.stringify(event.result),extractConversationSteps(event.result,existing.messages)),event.status==="error"&&(existing.error=typeof event.result=="string"?event.result:"Sub-agent failed"),this._dirty=!0,existing;let sub=create(SubAgentExecutionSchema,{id:event.call_id,name:extractSubagentName(event.args),subject:safeString(event.args,"description"),input:safeString(event.args,"prompt"),status:mapSubAgentStatus(event.status),startedAt:utcTimestamp()});return this._subAgentExecutions.push(sub),this.subAgentMap.set(event.call_id,sub),this._dirty=!0,sub}accumulateAssistant(event){let text=event.message.content.filter(b=>b.type==="text").map(b=>b.text).join("");if(!text)return;let existing=this.activeAiByRunId.get(event.run_id);if(existing){existing.content+=text;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:text,timestamp:utcTimestamp(),isStreaming:!0});this.messages.push(msg),this.activeAiByRunId.set(event.run_id,msg)}accumulateThinking(event){if(!event.text)return;let existing=this.activeThinkingByRunId.get(event.run_id);if(existing){existing.content+=event.text;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:event.text,timestamp:utcTimestamp(),isStreaming:!0});this.messages.push(msg),this.activeThinkingByRunId.set(event.run_id,msg)}finalizeStreaming(runId){let ai=this.activeAiByRunId.get(runId);ai&&(ai.isStreaming=!1,this.activeAiByRunId.delete(runId));let thinking=this.activeThinkingByRunId.get(runId);thinking&&(thinking.isStreaming=!1,this.activeThinkingByRunId.delete(runId))}}}});function formatStallFailure(error91){return`${STALL_ERROR_PREFIX} ${error91.message}. Retry or resume.`}function startStallWatchdog(stallMs,onStall){let lastActivityAt2=Date.now(),fired=!1,timer,tickMs=Math.min(Math.max(Math.floor(stallMs/4),1),15e3),disarm=()=>{timer!==void 0&&(clearInterval(timer),timer=void 0)};return timer=setInterval(()=>{if(fired)return;let idleMs=Date.now()-lastActivityAt2;idleMs>=stallMs&&(fired=!0,disarm(),onStall(idleMs))},tickMs),timer.unref?.(),{recordActivity(){lastActivityAt2=Date.now()},stop(){fired=!0,disarm()}}}var StallTimeoutError,STALL_ERROR_PREFIX,init_stall_watchdog=__esm({"dist/shared/stall-watchdog.js"(){"use strict";StallTimeoutError=class extends Error{stalledMs;constructor(stalledMs,detail){super(`Agent stream stalled: no activity for ${Math.round(stalledMs/1e3)}s`+(detail?` (${detail})`:"")),this.stalledMs=stalledMs,this.name="StallTimeoutError"}},STALL_ERROR_PREFIX="[StallTimeoutError]"}});var artifact_storage_exports={};__export(artifact_storage_exports,{LocalArtifactStorage:()=>LocalArtifactStorage,ProxyArtifactStorage:()=>ProxyArtifactStorage,createArtifactStorage:()=>createArtifactStorage,loadArtifactStorageConfig:()=>loadArtifactStorageConfig});function loadArtifactStorageConfig(config4){let envType=process.env.ARTIFACT_STORAGE_TYPE,type3=envType==="proxy"?"proxy":envType==="local"?"local":config4.proxyEndpoint?"proxy":"local";return{type:type3,localPath:process.env.LOCAL_ARTIFACT_PATH??"/var/stigmer/artifacts",localServeUrl:process.env.LOCAL_ARTIFACT_SERVE_URL??"http://localhost:7235",proxyEndpoint:type3==="proxy"?config4.proxyEndpoint??null:null,proxyAuthToken:type3==="proxy"?config4.stigmerToken??null:null}}function createArtifactStorage(cfg){if(cfg.type==="proxy"){if(!cfg.proxyEndpoint)throw new Error("Proxy artifact storage requires STIGMER_PROXY_ENDPOINT");if(!cfg.proxyAuthToken)throw new Error("Proxy artifact storage requires STIGMER_TOKEN");return new ProxyArtifactStorage(cfg.proxyEndpoint,cfg.proxyAuthToken)}return new LocalArtifactStorage(cfg.localPath,cfg.localServeUrl)}var import_promises2,import_node_path4,LocalArtifactStorage,ProxyArtifactStorage,init_artifact_storage=__esm({"dist/shared/artifact-storage.js"(){"use strict";import_promises2=require("node:fs/promises"),import_node_path4=require("node:path"),LocalArtifactStorage=class{basePath;serveUrlBase;constructor(basePath,serveUrlBase){this.basePath=basePath,this.serveUrlBase=serveUrlBase.replace(/\/+$/,"")}async upload(key,content,_contentType){let filePath=(0,import_node_path4.join)(this.basePath,key);return await(0,import_promises2.mkdir)((0,import_node_path4.dirname)(filePath),{recursive:!0}),await(0,import_promises2.writeFile)(filePath,content),key}async getDownloadUrl(key){return`${this.serveUrlBase}/${key}`}async exists(key){try{return await(0,import_promises2.access)((0,import_node_path4.join)(this.basePath,key)),!0}catch{return!1}}},ProxyArtifactStorage=class{baseUrl;authToken;constructor(proxyEndpoint,authToken){this.baseUrl=`${proxyEndpoint.replace(/\/+$/,"")}/v1/proxy/artifacts`,this.authToken=authToken}async upload(key,content,contentType){let ct=contentType??"application/octet-stream",presignResp=await fetch(`${this.baseUrl}/presigned-upload-url`,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({key,content_type:ct})});if(!presignResp.ok)throw new Error(`Failed to get presigned upload URL (HTTP ${presignResp.status}): `+await presignResp.text());let data=await presignResp.json(),signedHeaders=data.headers??{},uploadHeaders={},contentTypeSigned=!1;for(let[name2,value]of Object.entries(signedHeaders))name2.toLowerCase()!=="host"&&(name2.toLowerCase()==="content-type"&&(contentTypeSigned=!0),uploadHeaders[name2]=value);contentTypeSigned||(uploadHeaders["Content-Type"]=ct);let putResp=await fetch(data.url,{method:"PUT",headers:uploadHeaders,body:content});if(!putResp.ok)throw new Error(`Presigned upload failed (HTTP ${putResp.status}): `+await putResp.text());return key}async getDownloadUrl(key){let resp=await fetch(`${this.baseUrl}/presigned-download-url`,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({key})});if(!resp.ok)throw new Error(`Failed to get presigned download URL (HTTP ${resp.status}): `+await resp.text());return(await resp.json()).url}async exists(key){try{return(await fetch(`${this.baseUrl}/presigned-download-url`,{method:"POST",headers:{Authorization:`Bearer ${this.authToken}`,"Content-Type":"application/json"},body:JSON.stringify({key})})).ok}catch{return!1}}}}});async function publishPlanArtifact(opts){let{status,executionId,planText,artifactStorage}=opts;if(planText.trim().length!==0)try{let content=Buffer.from(planText,"utf-8"),contentHash=(0,import_node_crypto2.createHash)("sha256").update(content).digest("hex"),storageKey=`artifacts/${executionId}/${PLAN_ARTIFACT_NAME}`;await artifactStorage.upload(storageKey,content,"text/markdown");let downloadUrl=await artifactStorage.getDownloadUrl(storageKey),artifact=create(ExecutionArtifactSchema,{name:PLAN_ARTIFACT_NAME,sandboxPath:PLAN_ARTIFACT_SANDBOX_PATH,kind:ExecutionArtifactKind.FILE,sizeBytes:BigInt(content.length),storageKey,downloadUrl,createdAt:utcTimestamp(),contentHash}),existingIdx=status.artifacts.findIndex(a=>a.name===PLAN_ARTIFACT_NAME);existingIdx>=0?status.artifacts[existingIdx]=artifact:status.artifacts.push(artifact),console.log(`[plan-artifact] execution=${executionId} \u2014 published ${PLAN_ARTIFACT_NAME} (${content.length} bytes, hash=${contentHash.slice(0,12)})`)}catch(err){console.warn(`[plan-artifact] execution=${executionId} \u2014 failed to publish plan (non-fatal): ${err}`)}}var import_node_crypto2,PLAN_ARTIFACT_NAME,PLAN_ARTIFACT_SANDBOX_PATH,init_plan_artifact=__esm({"dist/shared/plan-artifact.js"(){"use strict";import_node_crypto2=require("node:crypto");init_esm4();init_artifact_pb();init_enum_pb();init_status2();PLAN_ARTIFACT_NAME="plan.md",PLAN_ARTIFACT_SANDBOX_PATH=".stigmer/plans/plan.md"}});function findToolCallById(messages,callId){for(let i2=messages.length-1;i2>=0;i2--)for(let tc of messages[i2].toolCalls)if(tc.id===callId)return tc}function extractShellOutputText(event){return typeof event.data=="string"?event.data:typeof event.output=="string"?event.output:typeof event.text=="string"?event.text:""}function extractCallIdFromShellEvent(event){if(typeof event.callId=="string")return event.callId;if(typeof event.call_id=="string")return event.call_id;if(typeof event.id=="string")return event.id}var DeltaEnricher,init_delta_enricher=__esm({"dist/activities/execute-cursor/delta-enricher.js"(){"use strict";init_enum_pb();init_message_translator();DeltaEnricher=class _DeltaEnricher{shellOutputByCallId=new Map;timingByCallId=new Map;thinkingDurationMs;_isDirty=!1;lastPersistTime=0;lastShellCallId;static PERSIST_DEBOUNCE_MS=500;processDelta(update){switch(update.type){case"shell-output-delta":this.handleShellOutputDelta(update);break;case"tool-call-started":this.handleToolCallStarted(update);break;case"tool-call-completed":this.handleToolCallCompleted(update);break;case"thinking-completed":this.thinkingDurationMs=update.thinkingDurationMs;break}}applyEnrichments(messages){let applied=!1;return this.shellOutputByCallId.size>0&&(applied=this.applyShellOutput(messages)||applied),this.timingByCallId.size>0&&(applied=this.applyTiming(messages)||applied),this.thinkingDurationMs!==void 0&&(applied=this.applyThinkingDuration(messages)||applied),applied}get isDirty(){return this._isDirty?Date.now()-this.lastPersistTime>=_DeltaEnricher.PERSIST_DEBOUNCE_MS:!1}markPersisted(){this._isDirty=!1,this.lastPersistTime=Date.now()}finalize(messages){for(let msg of messages)for(let tc of msg.toolCalls)tc.isStreaming&&(tc.isStreaming=!1,tc.streamingSource=ToolCallStreamingSource.UNSPECIFIED),tc.status===ToolCallStatus.TOOL_CALL_RUNNING&&(tc.completedAt||tc.result)&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.completedAt||(tc.completedAt=utcTimestamp()),console.log(`DeltaEnricher finalize reconciliation: promoted tool call ${tc.id} (${tc.name}) from RUNNING to COMPLETED`))}handleShellOutputDelta(update){let event=update.event,text=extractShellOutputText(event);if(!text)return;let callId=extractCallIdFromShellEvent(event)??this.lastShellCallId;if(!callId)return;let buffer=this.shellOutputByCallId.get(callId);buffer||(buffer={chunks:[],totalLength:0},this.shellOutputByCallId.set(callId,buffer)),buffer.chunks.push(text),buffer.totalLength+=text.length,this._isDirty=!0}handleToolCallStarted(update){let timing=this.getOrCreateTiming(update.callId);timing.startedAt=utcTimestamp(),update.toolCall.type==="shell"&&(this.lastShellCallId=update.callId)}handleToolCallCompleted(update){let timing=this.getOrCreateTiming(update.callId);timing.completedAt=utcTimestamp()}getOrCreateTiming(callId){let timing=this.timingByCallId.get(callId);return timing||(timing={},this.timingByCallId.set(callId,timing)),timing}applyShellOutput(messages){let applied=!1;for(let[callId,buffer]of this.shellOutputByCallId){let tc=findToolCallById(messages,callId);if(!tc)continue;let content=buffer.chunks.join("");tc.result=content,tc.isStreaming=!0,tc.streamingSource=ToolCallStreamingSource.OUTPUT,buffer.chunks=[content],applied=!0}return applied}applyTiming(messages){let applied=!1;for(let[callId,timing]of this.timingByCallId){let tc=findToolCallById(messages,callId);tc&&(timing.startedAt&&!tc.startedAt&&(tc.startedAt=timing.startedAt,applied=!0),timing.completedAt&&!tc.completedAt&&(tc.completedAt=timing.completedAt,applied=!0),timing.completedAt&&tc.status===ToolCallStatus.TOOL_CALL_RUNNING&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,applied=!0),this.timingByCallId.delete(callId))}return applied}applyThinkingDuration(_messages){return this.thinkingDurationMs!==void 0?(console.log(`DeltaEnricher: thinking completed in ${this.thinkingDurationMs}ms`),this.thinkingDurationMs=void 0,!0):!1}}}});var TODO_TOOL_NAMES,STATUS_MAP,TodoTracker,init_todo_tracker=__esm({"dist/activities/execute-cursor/todo-tracker.js"(){"use strict";init_esm4();init_todo_pb();init_enum_pb();init_message_translator();TODO_TOOL_NAMES=new Set(["TodoWrite","updateTodos"]),STATUS_MAP={pending:TodoStatus.TODO_PENDING,in_progress:TodoStatus.TODO_IN_PROGRESS,inprogress:TodoStatus.TODO_IN_PROGRESS,completed:TodoStatus.TODO_COMPLETED,cancelled:TodoStatus.TODO_CANCELLED},TodoTracker=class{todos;_isDirty=!1;constructor(todos){this.todos=todos}processEvent(event){if(event.type!=="tool_call"||!TODO_TOOL_NAMES.has(event.name)||event.status!=="completed")return;let args=this.parseArgs(event.args);if(!args)return;let rawTodos=args.todos;if(!Array.isArray(rawTodos)||rawTodos.length===0){args.merge!==!0&&(this.clearMap(),this._isDirty=!0);return}let merge4=args.merge===!0,now=utcTimestamp();merge4||this.clearMap();for(let i2=0;i2<rawTodos.length;i2++){let raw=rawTodos[i2],id=raw.id||`todo-${i2}`,statusStr=(raw.status??"pending").toLowerCase(),status=STATUS_MAP[statusStr]??TodoStatus.TODO_PENDING,existing=merge4?this.todos[id]:void 0;this.todos[id]=create(TodoItemSchema,{id,content:raw.content??"",status,createdAt:existing?.createdAt||raw.created_at||now,updatedAt:now})}this._isDirty=!0,console.log(`TodoTracker: processed ${rawTodos.length} todo(s) from ${event.name} (merge=${merge4})`)}get isDirty(){return this._isDirty}markPersisted(){this._isDirty=!1}parseArgs(args){if(args==null)return null;if(typeof args=="string")try{return JSON.parse(args)}catch{return null}return typeof args=="object"?args:null}clearMap(){for(let key of Object.keys(this.todos))delete this.todos[key]}}}});function shouldPersistStreamingStatus(signals,scheduler,eventCount,nowMs){return signals.deltaEnricherDirty||signals.todosDirty||signals.contentDirty||scheduler.shouldSendUpdate(eventCount,nowMs)}var init_persist_decision=__esm({"dist/activities/execute-cursor/persist-decision.js"(){"use strict"}});function loadStreamingConfig(){let minIntervalMs=parsePositiveInt(process.env.STREAMING_MIN_INTERVAL_MS,DEFAULT_CONFIG.minIntervalMs,"STREAMING_MIN_INTERVAL_MS"),maxIntervalMs=parsePositiveInt(process.env.STREAMING_MAX_INTERVAL_MS,DEFAULT_CONFIG.maxIntervalMs,"STREAMING_MAX_INTERVAL_MS"),burstThreshold=parsePositiveInt(process.env.STREAMING_BURST_THRESHOLD,DEFAULT_CONFIG.burstThreshold,"STREAMING_BURST_THRESHOLD");return maxIntervalMs<minIntervalMs&&(console.warn(`STREAMING_MAX_INTERVAL_MS (${maxIntervalMs}) < STREAMING_MIN_INTERVAL_MS (${minIntervalMs}). Setting max to min value.`),maxIntervalMs=minIntervalMs),{minIntervalMs,maxIntervalMs,burstThreshold}}function parsePositiveInt(raw,fallback,envName){if(!raw)return fallback;let parsed=Number(raw);return!Number.isFinite(parsed)||parsed<=0||!Number.isInteger(parsed)?(console.warn(`Invalid ${envName}='${raw}'. Using default: ${fallback}`),fallback):parsed}var UpdateReason,DEFAULT_CONFIG,StreamingUpdateScheduler,init_streaming_scheduler=__esm({"dist/shared/streaming-scheduler.js"(){"use strict";(function(UpdateReason2){UpdateReason2.TIME_THRESHOLD="time_threshold",UpdateReason2.BURST_PROTECTION="burst_protection",UpdateReason2.KEEPALIVE="keepalive",UpdateReason2.FIRST_UPDATE="first_update",UpdateReason2.NONE="none"})(UpdateReason||(UpdateReason={}));DEFAULT_CONFIG={minIntervalMs:500,maxIntervalMs:5e3,burstThreshold:50};StreamingUpdateScheduler=class{config;lastUpdateTime;lastUpdateEvents=0;lastReason=UpdateReason.NONE;firstCheck=!0;constructor(config4,nowMs){this.config=config4??DEFAULT_CONFIG,this.lastUpdateTime=nowMs??performance.now()}shouldSendUpdate(eventsProcessed,nowMs){let timeSinceLastMs=(nowMs??performance.now())-this.lastUpdateTime,eventsSinceLast=eventsProcessed-this.lastUpdateEvents;return this.firstCheck&&eventsSinceLast>=1?(this.lastReason=UpdateReason.FIRST_UPDATE,!0):timeSinceLastMs>=this.config.minIntervalMs&&eventsSinceLast>=1?(this.lastReason=UpdateReason.TIME_THRESHOLD,!0):eventsSinceLast>=this.config.burstThreshold?(this.lastReason=UpdateReason.BURST_PROTECTION,!0):timeSinceLastMs>=this.config.maxIntervalMs?(this.lastReason=UpdateReason.KEEPALIVE,!0):(this.lastReason=UpdateReason.NONE,!1)}markUpdateSent(eventsProcessed,nowMs){this.lastUpdateTime=nowMs??performance.now(),this.lastUpdateEvents=eventsProcessed,this.firstCheck=!1}get updateReason(){return this.lastReason}timeSinceLastUpdateMs(nowMs){return(nowMs??performance.now())-this.lastUpdateTime}eventsSinceLastUpdate(eventsProcessed){return eventsProcessed-this.lastUpdateEvents}}}});function createCursorEventRecorder(executionId){let recordDir=process.env.CURSOR_EVENT_RECORD_DIR;if(recordDir)return new FileCursorEventRecorder(executionId,recordDir)}function safeClone(obj){try{return JSON.parse(JSON.stringify(obj))}catch{return obj&&typeof obj=="object"?{_serializationError:!0,keys:Object.keys(obj)}:{_serializationError:!0}}}var import_promises3,import_node_path5,FileCursorEventRecorder,init_cursor_event_recorder=__esm({"dist/activities/execute-cursor/cursor-event-recorder.js"(){"use strict";import_promises3=require("node:fs/promises"),import_node_path5=require("node:path");FileCursorEventRecorder=class{executionId;outputDir;lines=[];constructor(executionId,outputDir){this.executionId=executionId,this.outputDir=outputDir}record(event,seq2){let entry={seq:seq2,capturedAt:new Date().toISOString(),type:event.type,agent_id:event.agent_id,run_id:event.run_id,event:safeClone(event)};this.lines.push(JSON.stringify(entry))}async flush(){if(this.lines.length===0)return;await(0,import_promises3.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path5.join)(this.outputDir,`${this.executionId}.cursor-events.jsonl`);await(0,import_promises3.writeFile)(filePath,this.lines.join(`
146
146
  `)+`
147
147
  `),console.log(`CursorEventRecorder: flushed ${this.lines.length} events to ${filePath}`)}}}});function resolvePlaceholders(template,envVars,context3){return template.replace(PLACEHOLDER_RE,(match,varName)=>{if(varName in envVars)return envVars[varName];throw new PlaceholderResolutionError(varName,context3)})}function resolveHeaders(headers,envVars){let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=resolvePlaceholders(value,envVars,`header "${key}"`);return resolved}function filterEnvToDeclaredKeys(declaredEnv,envVars,serverSlug){if(!declaredEnv||Object.keys(declaredEnv).length===0)return Object.keys(envVars).length>0&&console.log(`MCP server '${serverSlug}' has no env declarations \u2014 dropping ${Object.keys(envVars).length} env var(s)`),{};let declaredKeys=new Set(Object.keys(declaredEnv)),filtered={};for(let[key,value]of Object.entries(envVars))declaredKeys.has(key)&&(filtered[key]=value);let dropped=Object.keys(envVars).length-Object.keys(filtered).length;dropped>0&&console.log(`MCP server '${serverSlug}': passing ${Object.keys(filtered).length} declared env var(s), filtered out ${dropped} undeclared key(s)`);let missing=[...declaredKeys].filter(k=>!(k in filtered));return missing.length>0&&console.warn(`MCP server '${serverSlug}': env declares [${missing.sort().join(", ")}] but they are not present in the resolved environment`),filtered}var PLACEHOLDER_RE,PlaceholderResolutionError,init_placeholder_resolver=__esm({"dist/activities/execute-cursor/placeholder-resolver.js"(){"use strict";PLACEHOLDER_RE=/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,PlaceholderResolutionError=class extends Error{variableName;context;constructor(variableName,context3){let where=context3?` in ${context3}`:"";super(`Unresolved placeholder \${${variableName}}${where}: variable is not present in the execution environment`),this.variableName=variableName,this.context=context3,this.name="PlaceholderResolutionError"}}}});async function resolveMcpServers(client2,usages,envVars={}){let resolved=[];for(let usage of usages){let ref=usage.mcpServerRef;if(ref?.slug)try{let mcpServer=await client2.getMcpServerByReference(ref),serverEnv=filterEnvToDeclaredKeys(mcpServer.spec?.env,envVars,ref.slug),server=mcpServerToResolved(mcpServer,ref.slug,serverEnv);server&&resolved.push(server)}catch(err){err instanceof PlaceholderResolutionError?console.error(`MCP server ${ref.org}/${ref.slug}: ${err.message}`):console.warn(`Failed to resolve MCP server ${ref.org}/${ref.slug}: ${err instanceof Error?err.message:err}`)}}return{cursorConfig:toCursorMcpConfig(resolved),resolvedServers:resolved}}function mcpServerToResolved(server,slug,envVars){let spec=server.spec;if(!spec)return null;let status=server.status,toolApprovals=status?.toolApprovals??[],pinnedToolApprovals=spec.pinnedToolApprovals??[],discoveredCapabilitiesEmpty=!status?.discoveredCapabilities||status.discoveredCapabilities.tools.length===0&&status.discoveredCapabilities.resourceTemplates.length===0,base={toolApprovals,pinnedToolApprovals,discoveredCapabilitiesEmpty};switch(spec.serverType.case){case"stdio":{let stdio=spec.serverType.value;if(!stdio.command)return null;let resolvedArgs=stdio.args.length>0?stdio.args.map((arg,i2)=>resolvePlaceholders(arg,envVars,`stdio arg[${i2}]`)):void 0;return{slug,connectionType:"stdio",command:stdio.command,args:resolvedArgs,env:Object.keys(envVars).length>0?{...envVars}:void 0,cwd:stdio.workingDir||void 0,...base}}case"http":{let http3=spec.serverType.value;if(!http3.url)return null;let rawHeaders=Object.keys(http3.headers).length>0?http3.headers:void 0,resolved=rawHeaders?resolveHeaders(Object.fromEntries(Object.entries(rawHeaders)),envVars):void 0;return{slug,connectionType:"http",url:http3.url,headers:resolved,...base}}default:return null}}function toCursorMcpConfig(servers){let result={};for(let server of servers)if(server.connectionType==="stdio"){if(!server.command)continue;result[server.slug]={type:"stdio",command:server.command,args:server.args,env:server.env,cwd:server.cwd}}else{if(!server.url)continue;result[server.slug]={type:server.connectionType,url:server.url,headers:server.headers}}return result}function validateMcpServerEnv(servers,usages,envVars){let warnings=[];for(let usage of usages){let slug=usage.mcpServerRef?.slug;if(!slug)continue;let resolved=servers.find(s=>s.slug===slug);if(!resolved){warnings.push(`MCP server '${slug}': failed to resolve (server may not exist or is inaccessible)`);continue}if(resolved.connectionType==="stdio"&&resolved.env){let emptyKeys=Object.entries(resolved.env).filter(([,v])=>!v).map(([k])=>k);emptyKeys.length>0&&warnings.push(`MCP server '${slug}': env vars [${emptyKeys.join(", ")}] are empty \u2014 server subprocess will likely fail to connect`)}}return warnings}var init_mcp_resolver=__esm({"dist/activities/execute-cursor/mcp-resolver.js"(){"use strict";init_placeholder_resolver();init_placeholder_resolver()}});function hasApproveAllDecision(execution){let status=execution.status;if(!status)return!1;for(let message of status.messages)for(let tc of message.toolCalls)if(tc.approvalAction===ApprovalAction.APPROVE_ALL)return!0;for(let sa of status.subAgentExecutions)for(let message of sa.messages)for(let tc of message.toolCalls)if(tc.approvalAction===ApprovalAction.APPROVE_ALL)return!0;return!1}function mergeApprovalPolicies2(resolvedServers,agentOverrides,autoApproveAll){let merged=new Map;if(autoApproveAll)return merged;for(let server of resolvedServers){let serverPolicies=new Map;for(let policy of server.toolApprovals)policy.toolName&&serverPolicies.set(policy.toolName,{requiresApproval:!0,message:policy.message||`Execute tool: ${policy.toolName}`});for(let pinned of server.pinnedToolApprovals)pinned.toolName&&serverPolicies.set(pinned.toolName,{requiresApproval:!0,message:pinned.message||serverPolicies.get(pinned.toolName)?.message||`Execute tool: ${pinned.toolName}`});for(let override of agentOverrides){if(!override.toolName)continue;let existing=serverPolicies.get(override.toolName);existing?(existing.requiresApproval=override.requiresApproval,override.message&&(existing.message=override.message)):override.requiresApproval&&serverPolicies.set(override.toolName,{requiresApproval:!0,message:override.message||`Execute tool: ${override.toolName}`})}for(let[toolName,policy]of serverPolicies){if(!policy.requiresApproval)continue;let key=`${server.slug}/${toolName}`;merged.set(key,{toolName,mcpServerSlug:server.slug,requiresApproval:!0,approvalMessage:policy.message})}}return merged}function resolveApprovalMessage2(template,toolName,args){return template.replace(/\{\{tool_name\}\}/g,toolName).replace(/\{\{args\.(\w+)\}\}/g,(_match,field)=>{let value=args[field];return value==null?"<unknown>":typeof value=="string"?value:JSON.stringify(value)})}var init_approval_policy2=__esm({"dist/shared/approval-policy.js"(){"use strict";init_enum_pb()}});function resolvePlaceholders2(template,envVars,context3){return template.replace(PLACEHOLDER_RE2,(match,varName)=>{if(varName in envVars)return envVars[varName];throw new PlaceholderResolutionError2(varName,context3)})}function resolveHeaders2(headers,envVars){let resolved={};for(let[key,value]of Object.entries(headers))resolved[key]=resolvePlaceholders2(value,envVars,`header "${key}"`);return resolved}function filterEnvToDeclaredKeys2(declaredEnv,envVars,serverSlug){if(!declaredEnv||Object.keys(declaredEnv).length===0)return Object.keys(envVars).length>0&&console.log(`MCP server '${serverSlug}' has no env declarations \u2014 dropping ${Object.keys(envVars).length} env var(s)`),{};let declaredKeys=new Set(Object.keys(declaredEnv)),filtered={};for(let[key,value]of Object.entries(envVars))declaredKeys.has(key)&&(filtered[key]=value);let dropped=Object.keys(envVars).length-Object.keys(filtered).length;dropped>0&&console.log(`MCP server '${serverSlug}': passing ${Object.keys(filtered).length} declared env var(s), filtered out ${dropped} undeclared key(s)`);let missing=[...declaredKeys].filter(k=>!(k in filtered));return missing.length>0&&console.warn(`MCP server '${serverSlug}': env declares [${missing.sort().join(", ")}] but they are not present in the resolved environment`),filtered}var PLACEHOLDER_RE2,PlaceholderResolutionError2,init_placeholder_resolver2=__esm({"dist/shared/placeholder-resolver.js"(){"use strict";PLACEHOLDER_RE2=/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g,PlaceholderResolutionError2=class extends Error{variableName;context;constructor(variableName,context3){let where=context3?` in ${context3}`:"";super(`Unresolved placeholder \${${variableName}}${where}: variable is not present in the execution environment`),this.variableName=variableName,this.context=context3,this.name="PlaceholderResolutionError"}}}});async function resolveMcpServers2(client2,usages,envVars={}){let resolved=[];for(let usage of usages){let ref=usage.mcpServerRef;if(ref?.slug)try{let mcpServer=await client2.getMcpServerByReference(ref),serverEnv=filterEnvToDeclaredKeys2(mcpServer.spec?.env,envVars,ref.slug),server=mcpServerToResolved2(mcpServer,ref.slug,serverEnv);server&&resolved.push(server)}catch(err){err instanceof PlaceholderResolutionError2?console.error(`MCP server ${ref.org}/${ref.slug}: ${err.message}`):console.warn(`Failed to resolve MCP server ${ref.org}/${ref.slug}: ${err instanceof Error?err.message:err}`)}}return{resolvedServers:resolved}}function mcpServerToResolved2(server,slug,envVars){let spec=server.spec;if(!spec)return null;let status=server.status,toolApprovals=status?.toolApprovals??[],pinnedToolApprovals=spec.pinnedToolApprovals??[],discoveredCapabilitiesEmpty=!status?.discoveredCapabilities||status.discoveredCapabilities.tools.length===0&&status.discoveredCapabilities.resourceTemplates.length===0,base={toolApprovals,pinnedToolApprovals,discoveredCapabilitiesEmpty};switch(spec.serverType.case){case"stdio":{let stdio=spec.serverType.value;if(!stdio.command)return null;let resolvedArgs=stdio.args.length>0?stdio.args.map((arg,i2)=>resolvePlaceholders2(arg,envVars,`stdio arg[${i2}]`)):void 0;return{slug,connectionType:"stdio",command:stdio.command,args:resolvedArgs,env:Object.keys(envVars).length>0?{...envVars}:void 0,cwd:stdio.workingDir||void 0,...base}}case"http":{let http3=spec.serverType.value;if(!http3.url)return null;let rawHeaders=Object.keys(http3.headers).length>0?http3.headers:void 0,resolved=rawHeaders?resolveHeaders2(Object.fromEntries(Object.entries(rawHeaders)),envVars):void 0;return{slug,connectionType:"http",url:http3.url,headers:resolved,...base}}default:return null}}var init_mcp_resolver2=__esm({"dist/shared/mcp-resolver.js"(){"use strict";init_placeholder_resolver2();init_placeholder_resolver2()}});function needsBackfill(server){return SKIP_BACKFILL?!1:server.discoveredCapabilitiesEmpty}async function backfillMcpServersIfNeeded(client2,currentServers,usages,envVars,org,onHeartbeat,secretKeys){let serversNeedingBackfill=currentServers.filter(needsBackfill);if(serversNeedingBackfill.length===0)return currentServers;console.log(`[connect-backfill] Backfill needed for ${serversNeedingBackfill.length} MCP server(s): `+serversNeedingBackfill.map(s=>s.slug).join(", "));let anyBackfilled=!1;for(let server of serversNeedingBackfill)try{let serverRef=usages.find(u=>u.mcpServerRef?.slug===server.slug);if(!serverRef?.mcpServerRef)continue;let fullServer=await client2.getMcpServerByReference(serverRef.mcpServerRef),serverId=fullServer.metadata?.id;if(!serverId)continue;let runtimeEnv=extractRuntimeEnvForServer(fullServer,envVars,secretKeys);console.log(`[connect-backfill] Triggering connect for "${server.slug}" (${serverId})`),onHeartbeat?.();let updated=await Promise.race([client2.connectMcpServer(serverId,org,runtimeEnv),new Promise((_,reject)=>setTimeout(()=>reject(new Error(`Connect timed out after ${CONNECT_TIMEOUT_MS/1e3}s`)),CONNECT_TIMEOUT_MS))]),toolCount=updated.status?.discoveredCapabilities?.tools.length??0,approvalCount=updated.status?.toolApprovals?.length??0;console.log(`[connect-backfill] "${server.slug}" \u2014 discovered ${toolCount} tool(s), classified ${approvalCount} approval policy(ies)`),anyBackfilled=!0,onHeartbeat?.()}catch(err){console.warn(`[connect-backfill] Failed for "${server.slug}": ${err instanceof Error?err.message:err}. Continuing with empty approval policies for this server.`)}return anyBackfilled?(await resolveMcpServers2(client2,usages,envVars)).resolvedServers:currentServers}function extractRuntimeEnvForServer(server,mergedEnv,secretKeys){let envDecls=server.spec?.env;if(!envDecls||Object.keys(envDecls).length===0)return;let runtime={};for(let key of Object.keys(envDecls))if(key in mergedEnv){let isSecret=envDecls[key]?.isSecret??secretKeys?.has(key)??!1;runtime[key]={value:mergedEnv[key],isSecret}}return Object.keys(runtime).length>0?runtime:void 0}var CONNECT_TIMEOUT_MS,SKIP_BACKFILL,init_connect_backfill=__esm({"dist/shared/connect-backfill.js"(){"use strict";init_mcp_resolver2();CONNECT_TIMEOUT_MS=6e4,SKIP_BACKFILL=process.env.SKIP_MCP_CONNECT_BACKFILL==="true"}});async function backfillMcpServersIfNeeded2(client2,currentResult,usages,envVars,org,onHeartbeat,secretKeys){let updatedServers=await backfillMcpServersIfNeeded(client2,currentResult.resolvedServers,usages,envVars,org,onHeartbeat,secretKeys);return updatedServers===currentResult.resolvedServers?currentResult:{cursorConfig:toCursorMcpConfig(updatedServers),resolvedServers:updatedServers}}var init_connect_backfill2=__esm({"dist/activities/execute-cursor/connect-backfill.js"(){"use strict";init_mcp_resolver();init_connect_backfill()}});async function resolveExecutionEnv(client2,executionId){let execCtx;try{execCtx=await client2.getExecutionContextByExecutionId(executionId)}catch(err){if(err?.code===5)return console.log(`No ExecutionContext found for execution ${executionId} \u2014 proceeding with empty environment.`),{envVars:{},secretKeys:new Set};throw err}let envVars={},secretKeys=new Set,data=execCtx.spec?.data;if(data)for(let[key,execValue]of Object.entries(data))envVars[key]=execValue.value,execValue.isSecret&&secretKeys.add(key);return console.log(`Resolved environment from ExecutionContext: context_id=${execCtx.metadata?.id}, env_count=${Object.keys(envVars).length}, secret_count=${secretKeys.size}, keys=[${Object.keys(envVars).sort().join(", ")}]`),{envVars,secretKeys}}var init_env_resolver=__esm({"dist/activities/execute-cursor/env-resolver.js"(){"use strict"}});async function resolveBlueprint(client2,session,fallbackWorkspaceDir){let sessionSpec=session.spec,agentId=(await client2.getAgentInstance(sessionSpec.agentInstanceId)).spec.agentId,agent=await client2.getAgent(agentId),agentSpec=agent.spec,mergedMcpServerUsages=mergeMcpServerUsages(agentSpec.mcpServerUsages,sessionSpec.mcpServerUsages),mergedSkillRefs=mergeSkillRefs(agentSpec.skillRefs,sessionSpec.skillRefs),workspaceDirs=resolveWorkspaceDirs(sessionSpec,fallbackWorkspaceDir),cloudRepos=resolveCloudRepos(sessionSpec.workspaceEntries);return{agent,agentSpec,session,sessionSpec,instructions:agentSpec.instructions,subAgents:agentSpec.subAgents,mergedMcpServerUsages,mergedSkillRefs,workspaceDirs,cloudRepos}}function resolveCloudRepos(workspaceEntries){let repos=[];for(let entry of workspaceEntries)if(entry.source?.source.case==="gitRepo"){let git=entry.source.source.value;repos.push({url:git.url,startingRef:git.branch||void 0})}return repos}function mergeMcpServerUsages(agentUsages,sessionUsages){let bySlug=new Map;for(let usage of agentUsages){let slug=usage.mcpServerRef?.slug;slug&&bySlug.set(slug,usage)}for(let usage of sessionUsages){let slug=usage.mcpServerRef?.slug;slug&&bySlug.set(slug,usage)}return[...bySlug.values()]}function mergeSkillRefs(agentRefs,sessionRefs){let bySlug=new Map;for(let ref of agentRefs)ref.slug&&bySlug.set(ref.slug,ref);for(let ref of sessionRefs)ref.slug&&bySlug.set(ref.slug,ref);return[...bySlug.values()]}function resolveWorkspaceDirs(sessionSpec,fallbackDir){let safeFallback=validateWorkspaceDir(fallbackDir)?fallbackDir:logAndSkipRunnerDir(fallbackDir,"fallback config");if(!sessionSpec.workspaceEntries.length)return safeFallback?[safeFallback]:[];let dirs=[];for(let entry of sessionSpec.workspaceEntries)if(entry.source?.source.case==="localPath"){let path6=entry.source.source.value.path;validateWorkspaceDir(path6)?dirs.push(path6):logAndSkipRunnerDir(path6,"session workspace entry")}return dirs.length>0?dirs:safeFallback?[safeFallback]:[]}function validateWorkspaceDir(dir){let absolute=(0,import_node_path6.resolve)(dir);return!RUNNER_INTERNAL_MARKERS.some(marker=>absolute.includes(marker))}function logAndSkipRunnerDir(dir,source){console.warn(`Workspace dir from ${source} ("${dir}") is a runner-internal path \u2014 rejecting to prevent implementation detail leakage.`)}var import_node_path6,RUNNER_INTERNAL_MARKERS,init_blueprint_resolver=__esm({"dist/activities/execute-cursor/blueprint-resolver.js"(){"use strict";import_node_path6=require("node:path"),RUNNER_INTERNAL_MARKERS=["/runtimes/cursor-runner/","/runtimes/agent-runner/"]}});function buildCursorSubAgentDefinitions(subAgents){if(subAgents.length===0)return;let agents={};for(let sa of subAgents){let name2=sa.name?.trim();if(!name2)continue;let prompt=sa.instructions?.trim()||sa.description?.trim()||name2;agents[name2]={description:sa.description??"",prompt,model:sa.modelOverride?{id:sa.modelOverride}:"inherit"}}return Object.keys(agents).length>0?agents:void 0}var init_subagent_config=__esm({"dist/activities/execute-cursor/subagent-config.js"(){"use strict"}});function getSessionDir(sessionId){let home=process.env.HOME||process.env.USERPROFILE||(0,import_node_os2.homedir)();return(0,import_node_path7.join)(home,".stigmer","sessions",sessionId)}function getPlatformDir(sessionId){return(0,import_node_path7.join)(getSessionDir(sessionId),"platform")}async function ensurePlatformDir(sessionId){let dir=getPlatformDir(sessionId);return await(0,import_promises4.mkdir)(dir,{recursive:!0}),dir}function getHitlDir(sessionId){return(0,import_node_path7.join)(getSessionDir(sessionId),"hitl")}async function ensureHitlDir(sessionId){let dir=getHitlDir(sessionId);return await(0,import_promises4.mkdir)(dir,{recursive:!0}),dir}var import_node_path7,import_promises4,import_node_os2,init_platform_dir=__esm({"dist/shared/workspace/platform-dir.js"(){"use strict";import_node_path7=require("node:path"),import_promises4=require("node:fs/promises"),import_node_os2=require("node:os")}});async function extractZipFileEntries(zipBytes,options){if(zipBytes.length<4)return[];let entries;try{entries=parseZipEntries(zipBytes)}catch{return[]}let excludeSet=new Set(options?.exclude??[]),results=[];for(let entry of entries){if(entry.isDirectory||isExcluded(entry.name,excludeSet))continue;let content=await decompressEntry(entry);results.push({path:entry.name,content})}return results}function isExcluded(name2,excludeSet){if(excludeSet.size===0)return!1;if(excludeSet.has(name2))return!0;let basename5=name2.includes("/")?name2.slice(name2.lastIndexOf("/")+1):name2;return excludeSet.has(basename5)}function parseZipEntries(data){let entries=[],view2=new DataView(data.buffer,data.byteOffset,data.byteLength),offset=0;for(;offset<data.length-4&&view2.getUint32(offset,!0)===67324752;){let hasDataDescriptor=(view2.getUint16(offset+6,!0)&8)!==0,compressionMethod=view2.getUint16(offset+8,!0),compressedSize=view2.getUint32(offset+18,!0),uncompressedSize=view2.getUint32(offset+22,!0),fileNameLength=view2.getUint16(offset+26,!0),extraFieldLength=view2.getUint16(offset+28,!0),fileNameStart=offset+30,fileName=new TextDecoder().decode(data.subarray(fileNameStart,fileNameStart+fileNameLength)),dataStart=fileNameStart+fileNameLength+extraFieldLength;if(hasDataDescriptor&&compressedSize===0){let sizes=findDataDescriptor(data,view2,dataStart,compressionMethod);compressedSize=sizes.compressedSize,uncompressedSize=sizes.uncompressedSize}let compressedData=data.subarray(dataStart,dataStart+compressedSize);entries.push({name:fileName,isDirectory:fileName.endsWith("/"),compressedData,compressionMethod,uncompressedSize});let nextOffset=dataStart+compressedSize;hasDataDescriptor&&(nextOffset+4<=data.length&&view2.getUint32(nextOffset,!0)===134695760?nextOffset+=16:nextOffset+=12),offset=nextOffset}return entries}function findDataDescriptor(data,view2,dataStart,_compressionMethod){for(let pos=dataStart;pos<data.length-16;pos++){let sig=view2.getUint32(pos,!0);if(sig===134695760)return{compressedSize:view2.getUint32(pos+8,!0),uncompressedSize:view2.getUint32(pos+12,!0)};if(sig===67324752||sig===33639248){let descStart=pos-12;if(descStart>=dataStart)return{compressedSize:view2.getUint32(descStart+4,!0),uncompressedSize:view2.getUint32(descStart+8,!0)};break}}for(let pos=dataStart;pos<data.length-4;pos++){let sig=view2.getUint32(pos,!0);if(sig===67324752||sig===33639248||sig===134695760)return{compressedSize:sig===134695760?view2.getUint32(pos+8,!0):pos-dataStart,uncompressedSize:0}}return{compressedSize:data.length-dataStart,uncompressedSize:0}}async function decompressEntry(entry){if(entry.compressionMethod===0)return new TextDecoder().decode(entry.compressedData);if(entry.compressionMethod===8)return new Promise((resolve5,reject)=>{let inflate=(0,import_node_zlib.createInflateRaw)(),chunks=[];inflate.on("data",chunk=>chunks.push(chunk)),inflate.on("end",()=>resolve5(Buffer.concat(chunks).toString("utf-8"))),inflate.on("error",reject),inflate.end(Buffer.from(entry.compressedData))});throw new Error(`Unsupported ZIP compression method: ${entry.compressionMethod}`)}var import_node_zlib,init_zip_extract=__esm({"dist/shared/zip-extract.js"(){"use strict";import_node_zlib=require("node:zlib")}});async function resolveSkills(client2,skillRefs,options){if(console.log(`[resolveSkills] sessionId=${options.sessionId}, primaryWorkspaceDir=${options.primaryWorkspaceDir??"(undefined)"}, skillRefCount=${skillRefs.length}, refs=[${skillRefs.map(r=>`${r.org||"(default)"}/${r.slug}`).join(", ")}]`),skillRefs.length===0)return[];let platformDir=getPlatformDir(options.sessionId),skillsDir=(0,import_node_path8.join)(platformDir,SKILLS_SUBDIR);await(0,import_promises5.mkdir)(skillsDir,{recursive:!0}),await ensureStigmerSymlink(options.primaryWorkspaceDir,platformDir),console.log(`[resolveSkills] symlink created: ${(0,import_node_path8.join)(options.primaryWorkspaceDir,STIGMER_LOCAL_STATE_DIR)} -> ${platformDir}`);let results=[];for(let ref of skillRefs)try{let skill=await client2.getSkillByReference(ref),artifactBytes;if(skill.status?.artifactStorageKey)try{let resp=await client2.getSkillArtifact(skill.status.artifactStorageKey);resp.artifact&&resp.artifact.length>0&&(artifactBytes=resp.artifact)}catch(err){console.warn(`[resolveSkills] artifact download failed for ${ref.slug}, falling back to SKILL.md only: ${err instanceof Error?err.message:err}`)}let meta3=await writeSkill(skill,skillsDir,options.primaryWorkspaceDir,artifactBytes);meta3?(results.push(meta3),console.log(`[resolveSkills] wrote skill: ${meta3.name} -> ${meta3.path}`)):console.warn(`[resolveSkills] skill ${ref.org}/${ref.slug} fetched but had no skillMd content`)}catch(err){console.warn(`[resolveSkills] failed to resolve skill ${ref.org}/${ref.slug}: ${err instanceof Error?err.message:err}`)}return console.log(`[resolveSkills] completed: ${results.length}/${skillRefs.length} skills resolved`),results}async function writeSkill(skill,skillsDir,workspaceDir,artifactBytes){let spec=skill.spec;if(!spec?.skillMd)return null;let name2=spec.name||skill.metadata?.slug||"unknown",skillDir=(0,import_node_path8.join)(skillsDir,name2);await(0,import_promises5.mkdir)(skillDir,{recursive:!0});let skillMdPath=(0,import_node_path8.join)(skillDir,"SKILL.md");if(await(0,import_promises5.writeFile)(skillMdPath,spec.skillMd,"utf-8"),artifactBytes&&artifactBytes.length>0){let entries=await extractZipFileEntries(artifactBytes,{exclude:["SKILL.md"]});for(let entry of entries){let filePath=(0,import_node_path8.join)(skillDir,entry.path);await(0,import_promises5.mkdir)((0,import_node_path8.dirname)(filePath),{recursive:!0}),await(0,import_promises5.writeFile)(filePath,entry.content,"utf-8")}}let relativePath=(0,import_node_path8.join)(STIGMER_LOCAL_STATE_DIR,SKILLS_SUBDIR,name2,"SKILL.md");return{name:name2,description:spec.description||`Skill: ${name2}`,path:relativePath}}async function ensureStigmerSymlink(workspaceDir,platformDir){let linkPath=(0,import_node_path8.join)(workspaceDir,STIGMER_LOCAL_STATE_DIR);try{if(await(0,import_promises5.readlink)(linkPath)===platformDir)return;await(0,import_promises5.unlink)(linkPath)}catch(err){if(err.code!=="ENOENT")if(err.code==="EINVAL")await(0,import_promises5.rm)(linkPath,{recursive:!0,force:!0});else throw err}await(0,import_promises5.symlink)(platformDir,linkPath,"dir")}async function removeStigmerSymlink(workspaceDir){let linkPath=(0,import_node_path8.join)(workspaceDir,STIGMER_LOCAL_STATE_DIR);try{(await(0,import_promises5.lstat)(linkPath)).isSymbolicLink()&&await(0,import_promises5.unlink)(linkPath)}catch(err){err?.code!=="ENOENT"&&console.warn(`removeStigmerSymlink: failed to remove ${linkPath} (non-fatal): ${err instanceof Error?err.message:err}`)}}var import_promises5,import_node_path8,STIGMER_LOCAL_STATE_DIR,SKILLS_SUBDIR,init_skill_resolver=__esm({"dist/activities/execute-cursor/skill-resolver.js"(){"use strict";import_promises5=require("node:fs/promises"),import_node_path8=require("node:path");init_platform_dir();init_zip_extract();STIGMER_LOCAL_STATE_DIR=".stigmer",SKILLS_SUBDIR="skills"}});async function resolveAttachments(attachments,sessionId,primaryWorkspaceDir,mode){if(attachments.length===0)return[];let platformDir=getPlatformDir(sessionId),inputsDir=(0,import_node_path9.join)(platformDir,INPUTS_SUBDIR);await(0,import_promises6.mkdir)(inputsDir,{recursive:!0});let results=[];for(let attachment of attachments)try{let resolved=await resolveAttachment(attachment,inputsDir,mode);resolved&&results.push(resolved)}catch(err){console.warn(`Failed to resolve attachment ${attachment.filename}: ${err instanceof Error?err.message:err}`)}return results}async function resolveAttachment(attachment,inputsDir,mode){if(mode==="local"&&attachment.localPath){let filename=attachment.filename||(0,import_node_path9.basename)(attachment.localPath),destPath=(0,import_node_path9.join)(inputsDir,filename);return await(0,import_promises6.copyFile)(attachment.localPath,destPath),{filename,relativePath:(0,import_node_path9.join)(STIGMER_LOCAL_STATE_DIR2,INPUTS_SUBDIR,filename)}}return console.warn(`Attachment ${attachment.filename}: cloud storage download not yet implemented for cursor-runner`),null}var import_promises6,import_node_path9,STIGMER_LOCAL_STATE_DIR2,INPUTS_SUBDIR,init_attachment_resolver=__esm({"dist/activities/execute-cursor/attachment-resolver.js"(){"use strict";import_promises6=require("node:fs/promises"),import_node_path9=require("node:path");init_platform_dir();STIGMER_LOCAL_STATE_DIR2=".stigmer",INPUTS_SUBDIR="inputs"}});function buildEnhancedPrompt(options){let sections=[],modePrefix=formatInteractionModePrefix(options.interactionMode);modePrefix&&sections.push(modePrefix),options.instructions&&sections.push(formatInstructions(options.instructions)),options.skills.length>0&&sections.push(formatSkillsSection(options.skills)),options.subAgents.length>0&&sections.push(formatSubAgentsSection(options.subAgents));let safeDirs=sanitizeWorkspaceDirs(options.workspaceDirs);return safeDirs.length>0&&sections.push(formatExplorationGuidance()),safeDirs.length>1&&sections.push(formatWorkspaceContext(safeDirs)),options.attachmentPaths.length>0&&sections.push(formatInputFiles(options.attachmentPaths)),options.workspaceFileRefs.length>0&&sections.push(formatReferencedFiles(options.workspaceFileRefs)),options.instructions||sections.push(formatResponseRules()),sections.push(formatToolApprovalProtocol()),sections.push(`<user_request>
148
148
  ${options.userMessage}
@@ -2068,7 +2068,7 @@ Your task: {description}`,BUILTIN_DESCRIPTIONS=new Map([["explore","Read-only co
2068
2068
  `}});function jsonSchemaToZod(schema2){let type3=schema2.type;if(type3==="object"){let properties=schema2.properties,required3=new Set(schema2.required??[]);if(!properties)return external_exports.object({}).passthrough();let shape={};for(let[key,propSchema]of Object.entries(properties)){let fieldType=jsonSchemaToZod(propSchema);required3.has(key)||(fieldType=fieldType.nullable()),shape[key]=fieldType}return external_exports.object(shape).passthrough()}if(type3==="array"){let items=schema2.items;return external_exports.array(items?jsonSchemaToZod(items):external_exports.unknown())}if(type3==="string"){let enumValues=schema2.enum;return enumValues&&enumValues.length>0?external_exports.enum(enumValues):external_exports.string()}return type3==="number"||type3==="integer"?external_exports.number():type3==="boolean"?external_exports.boolean():type3==="null"?external_exports.null():external_exports.unknown()}var init_json_schema_to_zod=__esm({"dist/shared/json-schema-to-zod.js"(){"use strict";init_zod5()}});async function performSetup(deps){let{config:config4,client:client2,executionId,threadId}=deps,mcpConnection=null;try{await reportSetupProgress(client2,executionId,"Fetching execution\u2026");let execution=await client2.getExecution(executionId);console.log(`[setup] Execution fetched: agent_id=${execution.spec?.agentId}`),await reportSetupProgress(client2,executionId,"Resolving agent\u2026");let sessionId=execution.spec.sessionId;if(!sessionId)throw new Error(`Session ID is required for execution ${executionId}. Execution must have a valid session_id.`);let session=await client2.getSession(sessionId),agentInstance=await client2.getAgentInstance(session.spec.agentInstanceId),agent=await client2.getAgent(agentInstance.spec.agentId),instructions=agent.spec.instructions||"You are a helpful AI assistant.";console.log(`[setup] Chain resolved: session=${sessionId}, agent=${agent.metadata.name}`);let modelName=execution.spec.executionConfig?.modelName||await getDefaultModel(),checkpointer=await createCheckpointer({type:config4.checkpointerType,proxyEndpoint:config4.checkpointerProxyEndpoint??void 0,authToken:config4.stigmerToken??void 0});await reportSetupProgress(client2,executionId,"Resolving environment\u2026");let envResult=await resolveEnvironment(client2,executionId),artifactStorageConfig=loadArtifactStorageConfig(config4),artifactStorage=createArtifactStorage(artifactStorageConfig);await reportSetupProgress(client2,executionId,"Initializing workspace\u2026");let{workspaceBackend,provisionResults}=await provisionWorkspace(config4,session,envResult.mergedEnvVars,sessionId),mcpServerUsages=[...agent.spec.mcpServerUsages||[],...session.spec.mcpServerUsages||[]],resolvedMcpServers=null;if(mcpServerUsages.length>0){await reportSetupProgress(client2,executionId,"Connecting tools\u2026"),resolvedMcpServers=await resolveMcpServers2(client2,mcpServerUsages,envResult.mergedEnvVars);let sessionOrg=session.metadata?.org??"";resolvedMcpServers={resolvedServers:await backfillMcpServersIfNeeded(client2,resolvedMcpServers.resolvedServers,mcpServerUsages,envResult.mergedEnvVars,sessionOrg,void 0,envResult.secretKeys)},mcpConnection=await connectMcpServers(resolvedMcpServers.resolvedServers,{isCloudMode:config4.cloudModeEnabled})}let skillRefs=mergeSkillRefs2(agent.spec.skillRefs||[],session.spec.skillRefs||[]),skillsPromptSection="";if(skillRefs.length>0){await reportSetupProgress(client2,executionId,"Loading skills\u2026");let skills=await fetchSkillsByRefs(client2,skillRefs);if(skills.length>0){let artifacts=await fetchSkillArtifacts(client2,skills),{paths:skillPaths}=await writeSkills(skills,workspaceBackend,artifacts),userMessage2=execution.spec.message||"",skillNames=skills.map(s=>s.spec?.name||s.metadata?.slug||"unknown"),skillDescriptions=skills.map(s=>s.spec?.description||"");if(skills.length>=8){let filterResult=filterSkills(userMessage2,skillNames,skillDescriptions);if(filterResult.excludedNames.length>0){let includedSkills=filterResult.includedIndices.map(i2=>skills[i2]);console.log(`[setup] Skill relevance filter: ${includedSkills.length} included, ${filterResult.excludedNames.length} excluded: ${filterResult.excludedNames.join(", ")}`),skillsPromptSection=generatePromptSection(includedSkills,skillPaths)+generateAlsoAvailableSection(filterResult.excludedNames)}else skillsPromptSection=generatePromptSection(skills,skillPaths)}else skillsPromptSection=generatePromptSection(skills,skillPaths);console.log(`[setup] Skills loaded: ${skills.length} total, prompt section ${skillsPromptSection.length} chars`)}}let attachments=execution.spec.attachments||[],injectedFiles=await injectAttachments({backend:workspaceBackend,attachments,storage:artifactStorage,isLocalMode:config4.mode==="local"}),systemPrompt=buildEnhancedSystemPrompt({instructions,provisionResults,containerRoot:workspaceBackend.rootDir,skillsPromptSection,workspaceFileRefs:execution.spec.workspaceFileRefs||[],workspaceRoot:workspaceBackend.rootDir,injectedFiles}),model=constructModel(modelName,config4,executionId);await ensureLoaded2();let pricing=getModelPricing(modelName),execConfig=execution.spec.executionConfig,toolServerMap=new Map;if(mcpConnection)for(let[serverName,serverTools]of Object.entries(mcpConnection.serverToolMap))for(let t of serverTools)toolServerMap.set(t.name,serverName);let autoApproveAll=(execution.spec.autoApproveAll??!1)||hasApproveAllDecision(execution),agentOverrides=agent.spec.mcpServerUsages?.flatMap(u=>u.toolApprovalOverrides??[])??[],approvalPolicies=mergeApprovalPolicies2(resolvedMcpServers?.resolvedServers??[],agentOverrides,autoApproveAll),maxCostUsd=execConfig?.maxCostUsd??0,{middleware,gracefulStop,costCap:costCapMiddleware}=buildMiddlewareStack({loopDetection:{historySize:20,consecutiveThreshold:7,totalThreshold:20},executionBudget:{recursionLimit:execConfig?.maxToolRounds?execConfig.maxToolRounds*6:6e3,warningPct:80},toolTruncation:{maxChars:execConfig?.maxToolResultChars||3e4},costCap:maxCostUsd>0?{maxCostUsd,inputPricePerMillion:pricing.inputPricePerMillion,outputPricePerMillion:pricing.outputPricePerMillion,cacheReadPricePerMillion:pricing.cacheReadPricePerMillion,warningPct:80}:null,otelSpans:{toolServerMap},approvalGate:autoApproveAll?null:{policies:approvalPolicies,autoApproveAll,toolServerMap}}),tools3=[...mcpConnection?.tools??[],createThinkTool()],subAgentProtos=agent.spec.subAgents||[],compiledSubagents;if(subAgentProtos.length>0||workspaceBackend.rootDir){await reportSetupProgress(client2,executionId,"Configuring sub-agents\u2026");let parentMcpServerToolMap=new Map;if(mcpConnection)for(let[serverName,serverTools]of Object.entries(mcpConnection.serverToolMap))parentMcpServerToolMap.set(serverName,serverTools);compiledSubagents=await transformAndCompileSubagents({subAgents:subAgentProtos,parentMcpTools:mcpConnection?.tools??[],parentMcpServerToolMap,parentMcpUsages:mcpServerUsages,skillClient:client2,workspaceBackend,approvalPolicies,autoApproveAll,parentModelName:modelName,parentHasNativeThinking:_modelHasNativeThinking(modelName),costCap:costCapMiddleware??void 0,modelFactory:m=>constructModel(m,config4,executionId)})}await reportSetupProgress(client2,executionId,"Creating agent\u2026");let outputSchema=execution.spec.executionConfig?.structuredOutputSchema,responseFormat;outputSchema&&(responseFormat=jsonSchemaToZod(outputSchema));let isPlanMode=execConfig?.interactionMode===InteractionMode.PLAN,planModePermissions=[{operations:["write"],paths:["/**"],mode:"deny"}],agentGraph=await createDeepAgent({model,checkpointer,backend:new FilesystemBackend({rootDir:workspaceBackend.rootDir}),systemPrompt,tools:tools3,middleware,subagents:compiledSubagents??void 0,...responseFormat?{responseFormat}:{},...isPlanMode?{permissions:planModePermissions}:{}}),userMessage=execution.spec.message;outputSchema&&(userMessage+=`
2069
2069
 
2070
2070
  ---
2071
- IMPORTANT: When your analysis is complete, provide your findings as structured output matching the required schema. The system will capture your structured response automatically.`);let langgraphInput={messages:[{role:"user",content:userMessage}]},langgraphConfig={configurable:{thread_id:threadId}},streamVersion=process.env.LANGGRAPH_STREAM_EVENTS_VERSION==="v2"?"v2":"v3";return console.log(`[setup] Complete: model=${modelName}, tools=${tools3.length}, middleware=${middleware.length}, thread_id=${threadId}, streamVersion=${streamVersion}`),{agentGraph,langgraphConfig,langgraphInput,execution,agent,session,workspaceBackend,mcpConnection,mergedEnvVars:envResult.mergedEnvVars,secretKeys:envResult.secretKeys,modelName,gracefulStop,artifactStorage,provisionResults,approvalPolicies,toolServerMap,autoApproveAll,hasStructuredOutput:!!outputSchema,streamVersion}}catch(err){if(mcpConnection)try{await mcpConnection.client.close()}catch{}throw err}}function constructModel(modelName,config4,executionId){let provider=inferProvider2(modelName),apiModelId=stripProviderPrefix(modelName),baseUrl=config4.proxyEndpoint?resolveProxyBaseUrl(config4.proxyEndpoint,provider):void 0,headers=config4.proxyEndpoint&&config4.stigmerToken?buildProxyHeaders(config4.stigmerToken,{executionId}):void 0;switch(provider){case"anthropic":return buildAnthropicModel(apiModelId,baseUrl,headers,config4);case"openai":return buildOpenAIModel(apiModelId,baseUrl,headers,config4)}}function buildAnthropicModel(model,baseUrl,headers,config4){let apiKey=config4.proxyEndpoint?config4.stigmerToken??"proxy-managed":process.env.ANTHROPIC_API_KEY??"",requestTimeoutMs=parseInt(process.env.STIGMER_LLM_REQUEST_TIMEOUT_MS??"0")||void 0;return new ChatAnthropic({model,apiKey,temperature:0,...requestTimeoutMs?{maxRetries:0,timeout:requestTimeoutMs}:{},...baseUrl||headers?{clientOptions:{...baseUrl?{baseURL:baseUrl}:{},...headers?{defaultHeaders:headers}:{}}}:{}})}function buildOpenAIModel(model,baseUrl,headers,config4){let apiKey=config4.proxyEndpoint?config4.stigmerToken??"proxy-managed":process.env.OPENAI_API_KEY??"",requestTimeoutMs=parseInt(process.env.STIGMER_LLM_REQUEST_TIMEOUT_MS??"0")||void 0;return new ChatOpenAI({model,apiKey,temperature:0,...requestTimeoutMs?{maxRetries:0,timeout:requestTimeoutMs}:{},...baseUrl||headers?{configuration:{...baseUrl?{baseURL:baseUrl}:{},...headers?{defaultHeaders:headers}:{}}}:{}})}async function provisionWorkspace(config4,session,mergedEnvVars,sessionId){let platformDir=await ensurePlatformDir(sessionId),workspaceBackend=new LocalWorkspaceBackend(config4.workspaceRootDir,platformDir),workspaceEntries=session.spec.workspaceEntries||[];if(workspaceEntries.length===0)return{workspaceBackend,provisionResults:[]};let provisionResults=await new WorkspaceProvisioner().provisionAll(workspaceEntries.map(entry=>({name:entry.name,source:entry.source})),workspaceBackend,mergedEnvVars,config4.mode==="local",config4.mode!=="local");return provisionResults.length===1&&provisionResults[0].rootDir!==workspaceBackend.rootDir?{workspaceBackend:new LocalWorkspaceBackend(provisionResults[0].rootDir,platformDir),provisionResults}:{workspaceBackend,provisionResults}}function _modelHasNativeThinking(modelId){let lower=modelId.toLowerCase();return lower.includes("haiku")||lower.includes("gpt-4o-mini")?!1:!!(lower.includes("claude")&&(lower.includes("sonnet")||lower.includes("opus"))||lower.includes("o1")||lower.includes("o3")||lower.includes("o4"))}var init_setup=__esm({"dist/activities/execute-deep-agent/setup.js"(){"use strict";init_dist8();init_enum_pb();init_dist9();init_dist10();init_factory();init_mcp_manager();init_mcp_resolver2();init_connect_backfill();init_provisioner();init_local_backend();init_platform_dir();init_status2();init_environment();init_prompt_builder2();init_middleware4();init_model_pricing2();init_model_registry();init_artifact_storage();init_approval_policy2();init_llm_proxy();init_skill_writer();init_skill_relevance();init_attachment_injector();init_subagent_transformer();init_json_schema_to_zod()}});var ExecutionState,init_execution_state=__esm({"dist/activities/execute-deep-agent/execution-state.js"(){"use strict";ExecutionState=class{proto;toolCalls=new Map;messagesByRun=new Map;currentAiMessage=new Map;lastLlmRunId=new Map;toolStartTimes=new Map;constructor(proto){this.proto=proto}resetEphemeralState(){this.messagesByRun.clear(),this.currentAiMessage.clear(),this.lastLlmRunId.clear(),this.toolStartTimes.clear()}rebuildToolCallIndex(){this.toolCalls.clear();for(let message of this.proto.messages)for(let tc of message.toolCalls)tc.id&&this.toolCalls.set(tc.id,tc)}}}});function toBigInt(value){return typeof value=="bigint"?value:typeof value=="number"&&Number.isFinite(value)?BigInt(Math.floor(value)):0n}function serializeToolContent(content){if(typeof content=="string")return content;if(Array.isArray(content))return JSON.stringify(content)}function extractToolResult(data){let output=data.output;if(typeof output=="string")return output;if(typeof output=="object"&&output!==null){let fromContent=serializeToolContent(output.content);if(fromContent!==void 0)return fromContent}try{return JSON.stringify(output??data)}catch{return"[serialization error]"}}function extractToolResultV3(output){if(typeof output=="string")return output;if(typeof output=="object"&&output!==null){let obj=output,kwargs=obj.kwargs;if(kwargs){let fromKwargs=serializeToolContent(kwargs.content);if(fromKwargs!==void 0)return fromKwargs}let fromContent=serializeToolContent(obj.content);if(fromContent!==void 0)return fromContent}try{return JSON.stringify(output)}catch{return"[serialization error]"}}function sanitizeArgsPreview(args){let sanitized={};for(let[key,value]of Object.entries(args))SENSITIVE_ARG_KEYS.has(key.toLowerCase())?sanitized[key]="[REDACTED]":sanitized[key]=value;try{let json5=JSON.stringify(sanitized);return json5.length>MAX_ARGS_PREVIEW_LENGTH?json5.slice(0,MAX_ARGS_PREVIEW_LENGTH)+"\u2026":json5}catch{return""}}var UsageAccumulator2,SENSITIVE_ARG_KEYS,MAX_ARGS_PREVIEW_LENGTH,init_status_builder_shared=__esm({"dist/activities/execute-deep-agent/status-builder-shared.js"(){"use strict";init_esm4();init_usage_pb();init_status2();UsageAccumulator2=class{inputTokens=0n;outputTokens=0n;cacheReadTokens=0n;cacheWriteTokens=0n;turnCount=0;lastObservedAt="";accumulate(meta3){this.inputTokens+=toBigInt(meta3.input_tokens),this.outputTokens+=toBigInt(meta3.output_tokens),this.cacheReadTokens+=toBigInt(meta3.cache_read_input_tokens),this.cacheWriteTokens+=toBigInt(meta3.cache_creation_input_tokens),this.turnCount++,this.lastObservedAt=utcTimestamp()}snapshot(){return{inputTokens:this.inputTokens,outputTokens:this.outputTokens,cacheReadTokens:this.cacheReadTokens,cacheWriteTokens:this.cacheWriteTokens,totalTokens:this.inputTokens+this.outputTokens+this.cacheReadTokens+this.cacheWriteTokens,turnCount:this.turnCount,observedAt:this.lastObservedAt}}toProto(){return create(StreamingUsageSummarySchema,this.snapshot())}};SENSITIVE_ARG_KEYS=new Set(["password","token","secret","api_key","apikey","credentials","auth","authorization"]),MAX_ARGS_PREVIEW_LENGTH=500}});var StatusBuilder,init_status_builder=__esm({"dist/activities/execute-deep-agent/status-builder.js"(){"use strict";init_esm4();init_message_pb();init_enum_pb();init_approval_policy2();init_tool_kind();init_execution_state();init_status2();init_status_builder_shared();StatusBuilder=class{executionId;state;_forceNextUpdate=!1;approvalProvider=null;usageAccumulator;handlers;constructor(executionId,initialStatus){this.executionId=executionId,this.state=new ExecutionState(initialStatus),initialStatus.phase=ExecutionPhase.EXECUTION_IN_PROGRESS,initialStatus.startedAt||(initialStatus.startedAt=utcTimestamp()),this.usageAccumulator=new UsageAccumulator2,this.handlers=new Map([["on_chat_model_stream",this.handleChatModelStream.bind(this)],["on_chat_model_end",this.handleChatModelEnd.bind(this)],["on_tool_start",this.handleToolStart.bind(this)],["on_tool_end",this.handleToolEnd.bind(this)]])}setApprovalProvider(provider){this.approvalProvider=provider}get currentStatus(){return this.state.proto}get forceNextUpdate(){return this._forceNextUpdate}clearForceFlag(){this._forceNextUpdate=!1}processEvent(event){let namespace=this.extractNamespace(event),handler=this.handlers.get(event.event);if(handler)try{handler(event,namespace)}catch(err){console.error(`[StatusBuilder] Event handler error: execution=${this.executionId} event=${event.event} run_id=${event.run_id}: ${err}`)}}addArtifact(artifact){let artifacts=this.state.proto.artifacts,idx=artifacts.findIndex(a=>a.sandboxPath===artifact.sandboxPath);if(idx>=0){artifacts[idx].contentHash!==artifact.contentHash&&(artifacts[idx]=artifact,this._forceNextUpdate=!0);return}artifacts.push(artifact),this._forceNextUpdate=!0}addWriteBack(wb){let backs=this.state.proto.workspaceWriteBacks,idx=backs.findIndex(b=>b.workspaceEntryName===wb.workspaceEntryName);idx>=0?backs[idx]=wb:backs.push(wb),this._forceNextUpdate=!0}handleChatModelStream(event,namespace){let chunk=event.data?.chunk;if(!chunk)return;let content=chunk.content;if(Array.isArray(content)){for(let block of content)if(typeof block=="object"&&block!==null){let b=block;b.type==="thinking"&&typeof b.thinking=="string"?this.appendThinkingContent(event.run_id,namespace,b.thinking):b.type==="text"&&typeof b.text=="string"&&this.appendTextContent(event.run_id,namespace,b.text)}}else typeof content=="string"&&content.length>0&&this.appendTextContent(event.run_id,namespace,content)}handleChatModelEnd(event,namespace){let output=event.data?.output,msg=this.state.messagesByRun.get(event.run_id);msg&&(msg.isStreaming=!1);let usageMeta=output?.usage_metadata??event.data?.usage_metadata;usageMeta&&(this.usageAccumulator.accumulate(usageMeta),this.syncUsageToProto())}handleToolStart(event,namespace){let parentMsg=this.state.currentAiMessage.get(namespace)??this.ensureAiMessageForToolCall(event.run_id,namespace);if(!parentMsg)return;let toolName=event.name??"unknown_tool",rawArgs=event.data?.input,args=rawArgs??{},approvalReq=this.checkApprovalRequirement(toolName,args),tc=create(ToolCallSchema,{id:event.run_id,name:toolName,status:approvalReq.requiresApproval?ToolCallStatus.TOOL_CALL_WAITING_APPROVAL:ToolCallStatus.TOOL_CALL_RUNNING,startedAt:utcTimestamp()});if(rawArgs&&(tc.args=rawArgs),approvalReq.serverSlug&&(tc.mcpServerSlug=approvalReq.serverSlug),tc.toolKind=classifyTool(tc.name,tc.mcpServerSlug),approvalReq.requiresApproval){tc.requiresApproval=!0,tc.approvalMessage=approvalReq.message,tc.approvalRequestedAt=utcTimestamp();let argsPreview=sanitizeArgsPreview(args);argsPreview&&(tc.argsPreview=argsPreview),this.state.proto.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL}parentMsg.toolCalls.push(tc),this.state.toolCalls.set(event.run_id,tc),this.state.toolStartTimes.set(event.run_id,performance.now()),this._forceNextUpdate=!0}checkApprovalRequirement(toolName,args){if(!this.approvalProvider)return{requiresApproval:!1,message:"",serverSlug:""};let serverSlug=this.approvalProvider.toolServerMap.get(toolName)??"";if(this.approvalProvider.autoApproveAll)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage2(policy.approvalMessage,toolName,args),serverSlug}:{requiresApproval:!1,message:"",serverSlug}}return{requiresApproval:!1,message:"",serverSlug:""}}handleToolEnd(event,_namespace){let tc=this.state.toolCalls.get(event.run_id);if(!tc)return;let errorMsg=event.data?.output?.error;errorMsg?(tc.status=ToolCallStatus.TOOL_CALL_FAILED,tc.error=errorMsg):(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.result=extractToolResult(event.data)),tc.completedAt=utcTimestamp(),tc.isStreaming=!1,this.state.toolStartTimes.delete(event.run_id),this._forceNextUpdate=!0}appendTextContent(runId,namespace,text){let msg=this.ensureAiMessage(runId,namespace,MessageType.MESSAGE_AI);msg.content+=text,msg.isStreaming=!0}appendThinkingContent(runId,namespace,text){let thinkingKey=`thinking:${namespace}`,existingMsg=this.state.messagesByRun.get(thinkingKey);if(existingMsg&&existingMsg.type===MessageType.MESSAGE_THINKING){existingMsg.content+=text,existingMsg.isStreaming=!0;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:text,timestamp:utcTimestamp(),isStreaming:!0});this.state.proto.messages.push(msg),this.state.messagesByRun.set(thinkingKey,msg)}ensureAiMessage(runId,namespace,type3){let existingByRun=this.state.messagesByRun.get(runId);if(existingByRun)return existingByRun;let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId&&lastRunId!==runId){let existingMsg=this.state.currentAiMessage.get(namespace);existingMsg&&(existingMsg.isStreaming=!1)}let msg=create(AgentMessageSchema,{type:type3,content:"",timestamp:utcTimestamp(),isStreaming:!0});return this.state.proto.messages.push(msg),this.state.messagesByRun.set(runId,msg),this.state.currentAiMessage.set(namespace,msg),this.state.lastLlmRunId.set(namespace,runId),msg}ensureAiMessageForToolCall(_toolRunId,namespace){let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId){let existing=this.state.messagesByRun.get(lastRunId);if(existing)return this.state.currentAiMessage.set(namespace,existing),existing}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});return this.state.proto.messages.push(msg),this.state.currentAiMessage.set(namespace,msg),msg}extractNamespace(event){let meta3=event.metadata;if(!meta3)return"";let ns3=meta3.langgraph_checkpoint_ns??meta3.checkpoint_ns??"";return typeof ns3=="string"?ns3:""}syncUsageToProto(){this.state.proto.streamingUsage=this.usageAccumulator.toProto()}}}});function handlePause(writer2,eventsProcessed,pendingPublishPromises,pendingWritebackPromises){let status=writer2.currentStatus;return status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue from this checkpoint.",timestamp:utcTimestamp()})),{eventsProcessed,terminalStatus:slimStatus(status),pendingPublishPromises,pendingWritebackPromises}}function handleStop(writer2,eventsProcessed,pendingPublishPromises,pendingWritebackPromises){let status=writer2.currentStatus;return status.phase=ExecutionPhase.EXECUTION_COMPLETED,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution stopped by the platform.",timestamp:utcTimestamp()})),{eventsProcessed,terminalStatus:slimStatus(status),pendingPublishPromises,pendingWritebackPromises}}function handleRecursionLimit(writer2,eventsProcessed,pendingPublishPromises,pendingWritebackPromises){let status=writer2.currentStatus;return status.phase=ExecutionPhase.EXECUTION_TERMINATED,status.completedAt=utcTimestamp(),status.error=`Agent reached the tool-call limit after processing ${eventsProcessed} events. Send another message to continue.`,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"The agent reached the tool-call limit for this message. Work completed so far has been saved. Send another message to continue where the agent left off.",timestamp:utcTimestamp()})),{eventsProcessed,terminalStatus:slimStatus(status),pendingPublishPromises,pendingWritebackPromises}}function isGraphRecursionError(err){return err instanceof Error?err.constructor.name==="GraphRecursionError"||err.message.includes("GraphRecursionError")||err.message.includes("Recursion limit"):!1}var init_streaming_terminal=__esm({"dist/activities/execute-deep-agent/streaming-terminal.js"(){"use strict";init_esm4();init_message_pb();init_enum_pb();init_status2()}});function loadStreamingConfig(){let minIntervalMs=parsePositiveInt(process.env.STREAMING_MIN_INTERVAL_MS,DEFAULT_CONFIG.minIntervalMs,"STREAMING_MIN_INTERVAL_MS"),maxIntervalMs=parsePositiveInt(process.env.STREAMING_MAX_INTERVAL_MS,DEFAULT_CONFIG.maxIntervalMs,"STREAMING_MAX_INTERVAL_MS"),burstThreshold=parsePositiveInt(process.env.STREAMING_BURST_THRESHOLD,DEFAULT_CONFIG.burstThreshold,"STREAMING_BURST_THRESHOLD");return maxIntervalMs<minIntervalMs&&(console.warn(`STREAMING_MAX_INTERVAL_MS (${maxIntervalMs}) < STREAMING_MIN_INTERVAL_MS (${minIntervalMs}). Setting max to min value.`),maxIntervalMs=minIntervalMs),{minIntervalMs,maxIntervalMs,burstThreshold}}function parsePositiveInt(raw,fallback,envName){if(!raw)return fallback;let parsed=Number(raw);return!Number.isFinite(parsed)||parsed<=0||!Number.isInteger(parsed)?(console.warn(`Invalid ${envName}='${raw}'. Using default: ${fallback}`),fallback):parsed}var UpdateReason,DEFAULT_CONFIG,StreamingUpdateScheduler,init_streaming_scheduler=__esm({"dist/activities/execute-deep-agent/streaming-scheduler.js"(){"use strict";(function(UpdateReason2){UpdateReason2.TIME_THRESHOLD="time_threshold",UpdateReason2.BURST_PROTECTION="burst_protection",UpdateReason2.KEEPALIVE="keepalive",UpdateReason2.FIRST_UPDATE="first_update",UpdateReason2.NONE="none"})(UpdateReason||(UpdateReason={}));DEFAULT_CONFIG={minIntervalMs:500,maxIntervalMs:5e3,burstThreshold:50};StreamingUpdateScheduler=class{config;lastUpdateTime;lastUpdateEvents=0;lastReason=UpdateReason.NONE;firstCheck=!0;constructor(config4,nowMs){this.config=config4??DEFAULT_CONFIG,this.lastUpdateTime=nowMs??performance.now()}shouldSendUpdate(eventsProcessed,nowMs){let timeSinceLastMs=(nowMs??performance.now())-this.lastUpdateTime,eventsSinceLast=eventsProcessed-this.lastUpdateEvents;return this.firstCheck&&eventsSinceLast>=1?(this.lastReason=UpdateReason.FIRST_UPDATE,!0):timeSinceLastMs>=this.config.minIntervalMs&&eventsSinceLast>=1?(this.lastReason=UpdateReason.TIME_THRESHOLD,!0):eventsSinceLast>=this.config.burstThreshold?(this.lastReason=UpdateReason.BURST_PROTECTION,!0):timeSinceLastMs>=this.config.maxIntervalMs?(this.lastReason=UpdateReason.KEEPALIVE,!0):(this.lastReason=UpdateReason.NONE,!1)}markUpdateSent(eventsProcessed,nowMs){this.lastUpdateTime=nowMs??performance.now(),this.lastUpdateEvents=eventsProcessed,this.firstCheck=!1}get updateReason(){return this.lastReason}timeSinceLastUpdateMs(nowMs){return(nowMs??performance.now())-this.lastUpdateTime}eventsSinceLastUpdate(eventsProcessed){return eventsProcessed-this.lastUpdateEvents}}}});function createV2EventRecorder(executionId,recordDir){if(recordDir)return new FileV2EventRecorder(executionId,recordDir)}function safeClone2(obj){try{return JSON.parse(JSON.stringify(obj,bigintReplacer))}catch{return{_serializationError:!0,keys:Object.keys(obj)}}}function bigintReplacer(_key,value){return typeof value=="bigint"?value.toString():value}var import_promises13,import_node_path18,FileV2EventRecorder,init_event_recorder=__esm({"dist/activities/execute-deep-agent/event-recorder.js"(){"use strict";import_promises13=require("node:fs/promises"),import_node_path18=require("node:path");FileV2EventRecorder=class{executionId;outputDir;events=[];constructor(executionId,outputDir){this.executionId=executionId,this.outputDir=outputDir}record(event,seq2){this.events.push({seq:seq2,timestamp:new Date().toISOString(),event:event.event,name:event.name,run_id:event.run_id,data:safeClone2(event.data),metadata:event.metadata?safeClone2(event.metadata):void 0})}async flush(){if(this.events.length===0)return;await(0,import_promises13.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path18.join)(this.outputDir,`${this.executionId}.v2-events.json`),payload={executionId:this.executionId,recordedAt:new Date().toISOString(),eventCount:this.events.length,events:this.events};await(0,import_promises13.writeFile)(filePath,JSON.stringify(payload,bigintReplacer,2))}}}});function createV3EventRecorder(executionId,recordDir){if(recordDir)return new FileV3EventRecorder(executionId,recordDir)}function safeClone3(obj){try{return JSON.parse(JSON.stringify(obj,bigintReplacer2))}catch{return obj&&typeof obj=="object"?{_serializationError:!0,keys:Object.keys(obj)}:{_serializationError:!0}}}function bigintReplacer2(_key,value){return typeof value=="bigint"?value.toString():value}var import_promises14,import_node_path19,FileV3EventRecorder,init_v3_event_recorder=__esm({"dist/activities/execute-deep-agent/v3-event-recorder.js"(){"use strict";import_promises14=require("node:fs/promises"),import_node_path19=require("node:path");FileV3EventRecorder=class{executionId;outputDir;events=[];constructor(executionId,outputDir){this.executionId=executionId,this.outputDir=outputDir}record(event,seq2){this.events.push({seq:seq2,capturedAt:new Date().toISOString(),type:event.type,method:event.method,namespace:event.params.namespace,timestamp:event.params.timestamp,node:event.params.node,data:safeClone3(event.params.data)})}async flush(){if(this.events.length===0)return;await(0,import_promises14.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path19.join)(this.outputDir,`${this.executionId}.v3-events.json`),payload={executionId:this.executionId,recordedAt:new Date().toISOString(),eventCount:this.events.length,events:this.events};await(0,import_promises14.writeFile)(filePath,JSON.stringify(payload,bigintReplacer2,2))}}}});function formatNamespace(ns3){return ns3.length===0?"":ns3.join("|")}function namespaceDepth(namespace){if(!namespace)return 0;let count=1;for(let i2=0;i2<namespace.length;i2++)namespace[i2]==="|"&&count++;return count}var init_v3_events=__esm({"dist/activities/execute-deep-agent/v3-events.js"(){"use strict"}});function normalize3(event){switch(event.method){case"messages":return normalizeMessage(event);case"tools":return normalizeTool(event);case"lifecycle":return normalizeLifecycle(event);default:return[]}}function normalizeMessage(event){let data=event.params.data;if(!data)return[];let eventType=readEventType(data),base={seq:event.seq,namespace:formatNamespace(event.params.namespace),node:event.params.node},runId=data.run_id??"";switch(eventType){case"message-start":return[{kind:"message_start",...base,runId,messageId:data.id}];case"content-block-delta":return normalizeContentBlockDelta(event,data,base,runId);case"message-finish":return[{kind:"message_finish",...base,runId,usage:normalizeUsagePayload(data.usage),reason:data.reason}];case"usage":return[{kind:"usage",...base,runId,usage:normalizeUsagePayload(data.usage)}];case"provider":return[{kind:"provider",...base,provider:data.provider??"",model:extractModel(data)}];case"content-block-start":case"content-block-finish":return[];default:return logUnknown("messages",eventType),[]}}function normalizeContentBlockDelta(event,data,base,runId){let delta=data.delta;if(!delta)return[];let deltaType=delta.type;if(deltaType==="text-delta"){let text=delta.text??"";return text?[{kind:"text_delta",...base,runId,text}]:[]}if(deltaType==="reasoning-delta"){let text=delta.reasoning??"";return text?[{kind:"reasoning_delta",...base,runId,text}]:[]}if(deltaType==="block-delta"){let fields=delta.fields;if(!fields)return[];if(fields.type==="tool_call_chunk"){let callId=fields.id??"",argsChunk=fields.args??"";return!argsChunk&&!callId?[]:[{kind:"tool_call_arg_delta",...base,callId,argsChunk}]}}return[]}function normalizeTool(event){let data=event.params.data;if(!data)return[];let eventType=readEventType(data),base={seq:event.seq,namespace:formatNamespace(event.params.namespace),node:event.params.node};switch(eventType){case"tool-started":{let callId=readToolCallId(data),name2=readToolName(data),input=parseToolInput(data.input);return[{kind:"tool_started",...base,callId,name:name2,input}]}case"tool-finished":{let callId=readToolCallId(data);return[{kind:"tool_finished",...base,callId,output:data.output}]}case"tool-error":{let callId=readToolCallId(data),message=data.message??data.error??"";return[{kind:"tool_error",...base,callId,message}]}case"tool-output-delta":{let callId=readToolCallId(data),delta=data.delta??"";return[{kind:"tool_output_delta",...base,callId,delta:String(delta)}]}default:return logUnknown("tools",eventType),[]}}function normalizeLifecycle(event){let data=event.params.data;return data?[{kind:"lifecycle",seq:event.seq,namespace:formatNamespace(event.params.namespace),node:event.params.node,event:readEventType(data),graphName:data.graph_name??data.graphName}]:[]}function readEventType(data){return data.event??data.type??""}function readToolCallId(data){return data.tool_call_id??data.toolCallId??""}function readToolName(data){return data.tool_name??data.toolName??data.name??"unknown_tool"}function parseToolInput(raw){if(raw==null)return{};if(typeof raw=="object"&&!Array.isArray(raw))return raw;if(typeof raw=="string")try{return JSON.parse(raw)}catch{return{}}return{}}function normalizeUsagePayload(raw){if(!raw)return;let details=raw.input_token_details;return{input_tokens:raw.input_tokens,output_tokens:raw.output_tokens,total_tokens:raw.total_tokens,input_token_details:details?{cache_creation:details.cache_creation,cache_read:details.cache_read}:void 0}}function extractModel(data){return data.payload?.model}function logUnknown(method,eventType){let key=`${method}:${eventType}`;loggedUnknowns.has(key)||(loggedUnknowns.add(key),console.debug(`[V3Normalizer] Unknown event: method=${method} event=${eventType}`))}var loggedUnknowns,init_v3_protocol_normalizer=__esm({"dist/activities/execute-deep-agent/v3-protocol-normalizer.js"(){"use strict";init_v3_events();loggedUnknowns=new Set}});function extractFirstSegment(namespace){let pipeIdx=namespace.indexOf("|");return pipeIdx===-1?namespace:namespace.slice(0,pipeIdx)}function stripFirstSegment(namespace){let pipeIdx=namespace.indexOf("|");return pipeIdx===-1?"":namespace.slice(pipeIdx+1)}function safeString2(obj,key){let val=obj[key];return typeof val=="string"?val:""}var SubAgentTracker,init_subagent_tracker=__esm({"dist/activities/execute-deep-agent/subagent-tracker.js"(){"use strict";init_esm4();init_subagent_pb();init_message_pb();init_enum_pb();init_status2();init_tool_kind();init_status_builder_shared();SubAgentTracker=class{executions=[];stateByCallId=new Map;stateByPrefix=new Map;onTaskToolStarted(callId,args,routingPrefix){if(this.stateByCallId.has(callId))return;let name2=safeString2(args,"subagent_type")||"task",description2=safeString2(args,"description")||"",proto=create(SubAgentExecutionSchema,{id:callId,name:name2,subject:description2,input:description2,status:SubAgentStatus.SUB_AGENT_IN_PROGRESS,startedAt:utcTimestamp()}),state={proto,callId,namespacePrefix:routingPrefix,messagesByRun:new Map,currentAiMessage:new Map,lastLlmRunId:new Map,toolCalls:new Map,toolArgBuffers:new Map};this.executions.push(proto),this.stateByCallId.set(callId,state),this.stateByPrefix.set(routingPrefix,state)}onTaskToolFinished(callId,output){let state=this.stateByCallId.get(callId);state&&(state.proto.status=SubAgentStatus.SUB_AGENT_COMPLETED,state.proto.completedAt=utcTimestamp(),state.proto.output=extractToolResultV3(output),this.finalizeStreamingMessages(state))}onTaskToolError(callId,errorMessage){let state=this.stateByCallId.get(callId);state&&(state.proto.status=SubAgentStatus.SUB_AGENT_FAILED,state.proto.completedAt=utcTimestamp(),state.proto.error=errorMessage,this.finalizeStreamingMessages(state))}cancelAll(){for(let state of this.stateByCallId.values())state.proto.status===SubAgentStatus.SUB_AGENT_IN_PROGRESS&&(state.proto.status=SubAgentStatus.SUB_AGENT_CANCELLED,state.proto.completedAt=utcTimestamp(),state.proto.error="Cancelled: parent execution was cancelled",this.finalizeStreamingMessages(state))}isSubAgentNamespace(namespace){if(!namespace||!namespace.includes("|"))return!1;let firstSegment=extractFirstSegment(namespace);return this.stateByPrefix.has(firstSegment)}routeEvent(event){let firstSegment=extractFirstSegment(event.namespace),state=this.stateByPrefix.get(firstSegment);if(!state)return;let localNs=this.resolveAgentNamespace(stripFirstSegment(event.namespace));switch(event.kind){case"message_start":this.handleMessageStart(state,event.runId,localNs);break;case"text_delta":this.handleTextDelta(state,event.runId,localNs,event.text);break;case"reasoning_delta":this.handleReasoningDelta(state,event.runId,localNs,event.text);break;case"tool_call_arg_delta":this.handleToolCallArgDelta(state,event.callId,event.argsChunk);break;case"message_finish":this.handleMessageFinish(state,event.runId,event.usage);break;case"tool_started":this.handleToolStarted(state,event.callId,event.name,event.input,localNs);break;case"tool_finished":this.handleToolFinished(state,event.callId,event.output);break;case"tool_error":this.handleToolError(state,event.callId,event.message);break;case"tool_output_delta":this.handleToolOutputDelta(state,event.callId,event.delta);break;case"usage":case"lifecycle":case"provider":break}}getExecutions(){return this.executions}hasExecutions(){return this.executions.length>0}handleMessageStart(state,runId,localNs){let lastRunId=state.lastLlmRunId.get(localNs);if(lastRunId&&lastRunId!==runId){let existingMsg=state.currentAiMessage.get(localNs);existingMsg&&(existingMsg.isStreaming=!1)}state.lastLlmRunId.set(localNs,runId)}handleTextDelta(state,runId,localNs,text){let msg=this.ensureAiMessage(state,runId,localNs,MessageType.MESSAGE_AI);msg.content+=text,msg.isStreaming=!0}handleReasoningDelta(state,runId,localNs,text){let thinkingKey=`thinking:${localNs}`,existing=state.messagesByRun.get(thinkingKey);if(existing&&existing.type===MessageType.MESSAGE_THINKING){existing.content+=text,existing.isStreaming=!0;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:text,timestamp:utcTimestamp(),isStreaming:!0});state.proto.messages.push(msg),state.messagesByRun.set(thinkingKey,msg)}handleMessageFinish(state,runId,usage){let msg=state.messagesByRun.get(runId);msg&&(msg.isStreaming=!1)}handleToolStarted(state,callId,name2,input,localNs){let agentNs=this.resolveAgentNamespace(localNs),parentMsg=state.currentAiMessage.get(agentNs)??this.ensureAiMessageForToolCall(state,agentNs);if(!parentMsg)return;let tc=create(ToolCallSchema,{id:callId,name:name2,status:ToolCallStatus.TOOL_CALL_RUNNING,startedAt:utcTimestamp(),toolKind:classifyTool(name2)});Object.keys(input).length>0&&(tc.args=input),parentMsg.toolCalls.push(tc),state.toolCalls.set(callId,tc)}handleToolFinished(state,callId,output){let tc=state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.result=extractToolResultV3(output),tc.completedAt=utcTimestamp(),tc.isStreaming=!1,state.toolArgBuffers.delete(callId))}handleToolError(state,callId,message){let tc=state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_FAILED,tc.error=message,tc.completedAt=utcTimestamp(),tc.isStreaming=!1,state.toolArgBuffers.delete(callId))}handleToolCallArgDelta(state,callId,argsChunk){let tc=state.toolCalls.get(callId);if(!tc)return;let buffer=(state.toolArgBuffers.get(callId)??"")+argsChunk;state.toolArgBuffers.set(callId,buffer);try{tc.args=JSON.parse(buffer)}catch{}}handleToolOutputDelta(state,callId,delta){let tc=state.toolCalls.get(callId);tc&&(tc.result=(tc.result??"")+delta)}ensureAiMessage(state,runId,localNs,type3){let existing=state.messagesByRun.get(runId);if(existing)return existing;let lastRunId=state.lastLlmRunId.get(localNs);if(lastRunId&&lastRunId!==runId){let prev=state.currentAiMessage.get(localNs);prev&&(prev.isStreaming=!1)}let msg=create(AgentMessageSchema,{type:type3,content:"",timestamp:utcTimestamp(),isStreaming:!0});return state.proto.messages.push(msg),state.messagesByRun.set(runId,msg),state.currentAiMessage.set(localNs,msg),state.lastLlmRunId.set(localNs,runId),msg}ensureAiMessageForToolCall(state,localNs){let lastRunId=state.lastLlmRunId.get(localNs);if(lastRunId){let existing=state.messagesByRun.get(lastRunId);if(existing)return state.currentAiMessage.set(localNs,existing),existing}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});return state.proto.messages.push(msg),state.currentAiMessage.set(localNs,msg),msg}resolveAgentNamespace(ns3){return ns3?ns3.split("|").filter(p=>!p.startsWith("tools:")&&!p.startsWith("model_request")).join("|"):""}finalizeStreamingMessages(state){for(let msg of state.currentAiMessage.values())msg.isStreaming=!1}}}});var V3StatusBuilder,init_v3_status_builder=__esm({"dist/activities/execute-deep-agent/v3-status-builder.js"(){"use strict";init_esm4();init_message_pb();init_enum_pb();init_approval_policy2();init_tool_kind();init_execution_state();init_status2();init_v3_events();init_status_builder_shared();init_subagent_tracker();V3StatusBuilder=class{executionId;state;_forceNextUpdate=!1;approvalProvider=null;usageAccumulator;subAgentTracker;toolArgBuffers=new Map;constructor(executionId,initialStatus){this.executionId=executionId,this.state=new ExecutionState(initialStatus),initialStatus.phase=ExecutionPhase.EXECUTION_IN_PROGRESS,initialStatus.startedAt||(initialStatus.startedAt=utcTimestamp()),this.usageAccumulator=new UsageAccumulator2,this.subAgentTracker=new SubAgentTracker}setApprovalProvider(provider){this.approvalProvider=provider}get currentStatus(){return this.state.proto}get forceNextUpdate(){return this._forceNextUpdate}clearForceFlag(){this._forceNextUpdate=!1}processEvent(event){try{if(event.kind==="tool_started"&&event.name==="task"&&namespaceDepth(event.namespace)<=1){let routingPrefix=event.namespace||`tools:${event.callId}`;this.subAgentTracker.onTaskToolStarted(event.callId,event.input,routingPrefix),this.handleToolStarted(event.callId,event.name,event.input,event.namespace),this._forceNextUpdate=!0;return}if(event.kind==="tool_finished"&&this.isTrackedTaskTool(event.callId)){this.subAgentTracker.onTaskToolFinished(event.callId,event.output),this.handleToolFinished(event.callId,event.output),this._forceNextUpdate=!0;return}if(event.kind==="tool_error"&&this.isTrackedTaskTool(event.callId)){this.subAgentTracker.onTaskToolError(event.callId,event.message),this.handleToolError(event.callId,event.message),this._forceNextUpdate=!0;return}if(this.subAgentTracker.isSubAgentNamespace(event.namespace)){this.subAgentTracker.routeEvent(event);return}switch(event.kind){case"message_start":this.handleMessageStart(event.runId,event.namespace);break;case"text_delta":this.appendTextContent(event.runId,event.namespace,event.text);break;case"reasoning_delta":this.appendThinkingContent(event.runId,event.namespace,event.text);break;case"tool_call_arg_delta":this.handleToolCallArgDelta(event.callId,event.argsChunk);break;case"message_finish":this.handleMessageFinish(event.runId,event.namespace,event.usage);break;case"tool_started":this.handleToolStarted(event.callId,event.name,event.input,event.namespace);break;case"tool_finished":this.handleToolFinished(event.callId,event.output);break;case"tool_error":this.handleToolError(event.callId,event.message);break;case"tool_output_delta":this.handleToolOutputDelta(event.callId,event.delta);break;case"usage":case"lifecycle":case"provider":break}}catch(err){console.error(`[V3StatusBuilder] Event handler error: execution=${this.executionId} kind=${event.kind} seq=${event.seq}: ${err}`)}}addArtifact(artifact){let artifacts=this.state.proto.artifacts,idx=artifacts.findIndex(a=>a.sandboxPath===artifact.sandboxPath);if(idx>=0){artifacts[idx].contentHash!==artifact.contentHash&&(artifacts[idx]=artifact,this._forceNextUpdate=!0);return}artifacts.push(artifact),this._forceNextUpdate=!0}addWriteBack(wb){let backs=this.state.proto.workspaceWriteBacks,idx=backs.findIndex(b=>b.workspaceEntryName===wb.workspaceEntryName);idx>=0?backs[idx]=wb:backs.push(wb),this._forceNextUpdate=!0}handleMessageStart(runId,namespace){let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId&&lastRunId!==runId){let existingMsg=this.state.currentAiMessage.get(namespace);existingMsg&&(existingMsg.isStreaming=!1)}this.state.lastLlmRunId.set(namespace,runId)}handleMessageFinish(runId,_namespace,usage){let msg=this.state.messagesByRun.get(runId);msg&&(msg.isStreaming=!1),usage&&this.accumulateV3Usage(usage)}appendTextContent(runId,namespace,text){let msg=this.ensureAiMessage(runId,namespace,MessageType.MESSAGE_AI);msg.content+=text,msg.isStreaming=!0}appendThinkingContent(runId,namespace,text){let thinkingKey=`thinking:${namespace}`,existingMsg=this.state.messagesByRun.get(thinkingKey);if(existingMsg&&existingMsg.type===MessageType.MESSAGE_THINKING){existingMsg.content+=text,existingMsg.isStreaming=!0;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:text,timestamp:utcTimestamp(),isStreaming:!0});this.state.proto.messages.push(msg),this.state.messagesByRun.set(thinkingKey,msg)}handleToolStarted(callId,name2,input,namespace){let agentNs=this.resolveAgentNamespace(namespace),parentMsg=this.state.currentAiMessage.get(agentNs)??this.ensureAiMessageForToolCall(agentNs);if(!parentMsg)return;let approvalReq=this.checkApprovalRequirement(name2,input),tc=create(ToolCallSchema,{id:callId,name:name2,status:approvalReq.requiresApproval?ToolCallStatus.TOOL_CALL_WAITING_APPROVAL:ToolCallStatus.TOOL_CALL_RUNNING,startedAt:utcTimestamp()});if(Object.keys(input).length>0&&(tc.args=input),approvalReq.serverSlug&&(tc.mcpServerSlug=approvalReq.serverSlug),tc.toolKind=classifyTool(tc.name,tc.mcpServerSlug),approvalReq.requiresApproval){tc.requiresApproval=!0,tc.approvalMessage=approvalReq.message,tc.approvalRequestedAt=utcTimestamp();let argsPreview=sanitizeArgsPreview(input);argsPreview&&(tc.argsPreview=argsPreview),this.state.proto.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL}parentMsg.toolCalls.push(tc),this.state.toolCalls.set(callId,tc),this.state.toolStartTimes.set(callId,performance.now()),this._forceNextUpdate=!0}handleToolFinished(callId,output){let tc=this.state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.result=extractToolResultV3(output),tc.completedAt=utcTimestamp(),tc.isStreaming=!1,this.state.toolStartTimes.delete(callId),this.toolArgBuffers.delete(callId),this._forceNextUpdate=!0)}handleToolError(callId,message){let tc=this.state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_FAILED,tc.error=message,tc.completedAt=utcTimestamp(),tc.isStreaming=!1,this.state.toolStartTimes.delete(callId),this.toolArgBuffers.delete(callId),this._forceNextUpdate=!0)}handleToolCallArgDelta(callId,argsChunk){let tc=this.state.toolCalls.get(callId);if(!tc)return;let buffer=(this.toolArgBuffers.get(callId)??"")+argsChunk;this.toolArgBuffers.set(callId,buffer);try{tc.args=JSON.parse(buffer)}catch{}}handleToolOutputDelta(callId,delta){let tc=this.state.toolCalls.get(callId);tc&&(tc.result=(tc.result??"")+delta)}resolveAgentNamespace(ns3){return ns3?ns3.split("|").filter(p=>!p.startsWith("tools:")).join("|"):""}checkApprovalRequirement(toolName,args){if(!this.approvalProvider)return{requiresApproval:!1,message:"",serverSlug:""};let serverSlug=this.approvalProvider.toolServerMap.get(toolName)??"";if(this.approvalProvider.autoApproveAll)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage2(policy.approvalMessage,toolName,args),serverSlug}:{requiresApproval:!1,message:"",serverSlug}}return{requiresApproval:!1,message:"",serverSlug:""}}ensureAiMessage(runId,namespace,type3){let existingByRun=this.state.messagesByRun.get(runId);if(existingByRun)return existingByRun;let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId&&lastRunId!==runId){let existingMsg=this.state.currentAiMessage.get(namespace);existingMsg&&(existingMsg.isStreaming=!1)}let msg=create(AgentMessageSchema,{type:type3,content:"",timestamp:utcTimestamp(),isStreaming:!0});return this.state.proto.messages.push(msg),this.state.messagesByRun.set(runId,msg),this.state.currentAiMessage.set(namespace,msg),this.state.lastLlmRunId.set(namespace,runId),msg}ensureAiMessageForToolCall(namespace){let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId){let existing=this.state.messagesByRun.get(lastRunId);if(existing)return this.state.currentAiMessage.set(namespace,existing),existing}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});return this.state.proto.messages.push(msg),this.state.currentAiMessage.set(namespace,msg),msg}accumulateV3Usage(usage){let meta3={input_tokens:usage.input_tokens,output_tokens:usage.output_tokens};usage.input_token_details&&(meta3.cache_read_input_tokens=usage.input_token_details.cache_read,meta3.cache_creation_input_tokens=usage.input_token_details.cache_creation),this.usageAccumulator.accumulate(meta3),this.state.proto.streamingUsage=this.usageAccumulator.toProto()}isTrackedTaskTool(callId){return this.state.toolCalls.get(callId)?.name==="task"}syncSubAgentExecutions(){this.subAgentTracker.hasExecutions()&&(this.state.proto.subAgentExecutions=this.subAgentTracker.getExecutions())}cancelSubAgents(){this.subAgentTracker.cancelAll(),this.syncSubAgentExecutions()}}}});function extractFilePath(input){return typeof input.path=="string"?input.path:typeof input.file_path=="string"?input.file_path:typeof input.filePath=="string"?input.filePath:typeof input.filename=="string"?input.filename:typeof input.file=="string"?input.file:null}var FILE_MODIFYING_TOOLS,StreamingSideEffects,init_streaming_side_effects=__esm({"dist/activities/execute-deep-agent/streaming-side-effects.js"(){"use strict";FILE_MODIFYING_TOOLS=new Set(["write_file","edit_file","create_file","write","edit","create","str_replace_editor"]),StreamingSideEffects=class{inputCache=new Map;inlinePublisher;writebackCoordinator;pendingPublishPromises=[];pendingWritebackPromises=[];constructor(opts){this.inlinePublisher=opts.inlinePublisher,this.writebackCoordinator=opts.writebackCoordinator}onProtocolEvent(event){if(event.method!=="tools"||!this.inlinePublisher&&!this.writebackCoordinator)return;let data=event.params.data;if(!data)return;let eventType=data.event??data.type,callId=data.tool_call_id??data.toolCallId;if(callId){if(eventType==="tool-started"){let toolName=data.tool_name??data.toolName??data.name??"",rawInput=data.input,input={};if(typeof rawInput=="string")try{input=JSON.parse(rawInput)}catch{}else rawInput&&typeof rawInput=="object"&&!Array.isArray(rawInput)&&(input=rawInput);this.inputCache.set(callId,{toolName,input});return}if(eventType==="tool-finished"){let cached3=this.inputCache.get(callId);if(this.inputCache.delete(callId),!cached3||!FILE_MODIFYING_TOOLS.has(cached3.toolName))return;let filePath=extractFilePath(cached3.input);if(!filePath)return;this.inlinePublisher&&this.pendingPublishPromises.push(this.inlinePublisher.publish(filePath)),this.writebackCoordinator&&this.pendingWritebackPromises.push(this.writebackCoordinator.onFileModified(filePath))}}}}}});async function streamExecutionV3(deps){let{agentGraph,langgraphInput,langgraphConfig,executionId,client:client2,initialStatus,streamingConfig,retryOptions,offload,stallTimeoutMs=DEFAULT_STALL_TIMEOUT_MS,heartbeatFn,isCancelledFn,gracefulStop,inlinePublisher,writebackCoordinator,approvalProvider}=deps,statusBuilder=new V3StatusBuilder(executionId,initialStatus);approvalProvider&&statusBuilder.setApprovalProvider(approvalProvider);let scheduler=new StreamingUpdateScheduler(streamingConfig),recorder=createV3EventRecorder(executionId,process.env.V3_EVENT_RECORD_DIR),abortController=new AbortController,sideEffects=new StreamingSideEffects({inlinePublisher,writebackCoordinator});sendHeartbeat(heartbeatFn,executionId,0,statusBuilder);let run=await agentGraph.streamEvents(langgraphInput,{...langgraphConfig,version:"v3",signal:abortController.signal}),eventsProcessed=0,lastActivityAt2=performance.now(),heartbeatTimer=setInterval(()=>{sendHeartbeat(heartbeatFn,executionId,eventsProcessed,statusBuilder)},HEARTBEAT_INTERVAL_MS);try{for await(let event of run){if(isCancelledFn?.())return abortController.abort("Cancelled by platform"),statusBuilder.cancelSubAgents(),handlePause(statusBuilder,eventsProcessed,sideEffects.pendingPublishPromises,sideEffects.pendingWritebackPromises);lastActivityAt2=performance.now(),recorder?.record(event,eventsProcessed);for(let normalized of normalize3(event))statusBuilder.processEvent(normalized);if(sideEffects.onProtocolEvent(event),eventsProcessed++,statusBuilder.forceNextUpdate||scheduler.shouldSendUpdate(eventsProcessed)){statusBuilder.forceNextUpdate&&statusBuilder.clearForceFlag(),statusBuilder.syncSubAgentExecutions();let signal=await persistStatus(client2,executionId,statusBuilder.currentStatus,{offload,retry:retryOptions});if(scheduler.markUpdateSent(eventsProcessed),signal===ExecutionControlSignal.STOP)if(console.warn(`[streaming-v3] STOP signal received for execution ${executionId}`),gracefulStop)gracefulStop.activate("Platform STOP signal");else return handleStop(statusBuilder,eventsProcessed,sideEffects.pendingPublishPromises,sideEffects.pendingWritebackPromises)}checkStallTimeout(lastActivityAt2,stallTimeoutMs,executionId)}}catch(err){if(isGraphRecursionError(err))return await recorder?.flush(),handleRecursionLimit(statusBuilder,eventsProcessed,sideEffects.pendingPublishPromises,sideEffects.pendingWritebackPromises);throw err}finally{clearInterval(heartbeatTimer)}if(await recorder?.flush(),eventsProcessed===0)throw new Error("Stream completed without processing any events. This may indicate a configuration error or v3 API incompatibility.");if(statusBuilder.syncSubAgentExecutions(),initialStatus.phase===ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL)return console.log(`[streaming-v3] execution=${executionId} stream ended with WAITING_FOR_APPROVAL. Not setting COMPLETED. pending_approvals computed server-side.`),{eventsProcessed,terminalStatus:slimStatus(initialStatus),pendingPublishPromises:sideEffects.pendingPublishPromises,pendingWritebackPromises:sideEffects.pendingWritebackPromises};console.log(`[streaming-v3] execution=${executionId} stream finished \u2014 processed ${eventsProcessed} events`);let runOutput=await extractRunOutput(run,executionId);return{eventsProcessed,runOutput,pendingPublishPromises:sideEffects.pendingPublishPromises,pendingWritebackPromises:sideEffects.pendingWritebackPromises}}async function extractRunOutput(run,executionId){try{let finalState=await Promise.race([run.output,timeoutPromise(RUN_OUTPUT_TIMEOUT_MS)]);if(finalState===TIMEOUT_SENTINEL){console.warn(`[streaming-v3] execution=${executionId} \u2014 run.output did not resolve within ${RUN_OUTPUT_TIMEOUT_MS}ms. Proceeding without final state.`);return}let output=finalState;return console.log(`[streaming-v3] execution=${executionId} \u2014 run.output resolved. Keys: [${Object.keys(output??{}).join(", ")}]. hasStructuredResponse=${output?.structuredResponse!==void 0}`),output}catch(err){console.warn(`[streaming-v3] execution=${executionId} \u2014 run.output rejected: ${err}`);return}}function timeoutPromise(ms){return new Promise(resolve5=>setTimeout(()=>resolve5(TIMEOUT_SENTINEL),ms))}function sendHeartbeat(fn,executionId,eventsProcessed,sb){if(fn)try{fn({executionId,eventsProcessed,messages:sb.currentStatus.messages.length,phase:sb.currentStatus.phase})}catch{}}function checkStallTimeout(lastActivityAt2,stallTimeoutMs,executionId){let elapsed2=performance.now()-lastActivityAt2;if(elapsed2>stallTimeoutMs)throw new StallTimeoutError2(`Agent stream stalled: no events received for ${Math.round(elapsed2/1e3)}s for execution ${executionId}`)}var DEFAULT_STALL_TIMEOUT_MS,HEARTBEAT_INTERVAL_MS,RUN_OUTPUT_TIMEOUT_MS,TIMEOUT_SENTINEL,init_streaming_v3=__esm({"dist/activities/execute-deep-agent/streaming-v3.js"(){"use strict";init_streaming5();init_enum_pb();init_v3_event_recorder();init_v3_protocol_normalizer();init_v3_status_builder();init_streaming_scheduler();init_status2();init_streaming_side_effects();init_streaming_terminal();DEFAULT_STALL_TIMEOUT_MS=12e4,HEARTBEAT_INTERVAL_MS=2e3,RUN_OUTPUT_TIMEOUT_MS=3e4;TIMEOUT_SENTINEL=Symbol("timeout")}});async function streamExecution(deps){return deps.streamVersion==="v3"?streamExecutionV3(deps):streamExecutionV2(deps)}async function streamExecutionV2(deps){let{agentGraph,langgraphInput,langgraphConfig,executionId,client:client2,initialStatus,streamingConfig,retryOptions,offload,stallTimeoutMs=DEFAULT_STALL_TIMEOUT_MS2,heartbeatFn,isCancelledFn,gracefulStop,inlinePublisher,writebackCoordinator,approvalProvider}=deps,statusBuilder=new StatusBuilder(executionId,initialStatus);approvalProvider&&statusBuilder.setApprovalProvider(approvalProvider);let scheduler=new StreamingUpdateScheduler(streamingConfig),recorder=createV2EventRecorder(executionId,process.env.V2_EVENT_RECORD_DIR),eventsProcessed=0,lastEventTime=performance.now(),lastHeartbeatTime=performance.now(),heartbeatIntervalMs=2e3,pendingPublishPromises=[],pendingWritebackPromises=[];try{let stream=agentGraph.streamEvents(langgraphInput,langgraphConfig,{version:"v2"});for await(let event of stream){if(isCancelledFn?.())return handlePause(statusBuilder,eventsProcessed,pendingPublishPromises,pendingWritebackPromises);if(lastEventTime=performance.now(),recorder?.record(event,eventsProcessed),statusBuilder.processEvent(event),eventsProcessed++,event.event==="on_tool_end"&&(inlinePublisher||writebackCoordinator)){let filePath=extractFilePathFromToolEnd(event);filePath&&(inlinePublisher&&pendingPublishPromises.push(inlinePublisher.publish(filePath)),writebackCoordinator&&pendingWritebackPromises.push(writebackCoordinator.onFileModified(filePath)))}let now=performance.now();if(heartbeatFn&&now-lastHeartbeatTime>=heartbeatIntervalMs&&(sendHeartbeat2(heartbeatFn,executionId,eventsProcessed,statusBuilder),lastHeartbeatTime=now),statusBuilder.forceNextUpdate||scheduler.shouldSendUpdate(eventsProcessed)){statusBuilder.forceNextUpdate&&statusBuilder.clearForceFlag();let signal=await persistStatus(client2,executionId,statusBuilder.currentStatus,{offload,retry:retryOptions});if(scheduler.markUpdateSent(eventsProcessed),signal===ExecutionControlSignal.STOP)if(console.warn(`[streaming] STOP signal received for execution ${executionId}`),gracefulStop)gracefulStop.activate("Platform STOP signal");else return handleStop(statusBuilder,eventsProcessed,pendingPublishPromises,pendingWritebackPromises)}checkStallTimeout2(lastEventTime,stallTimeoutMs,executionId)}}catch(err){if(isGraphRecursionError(err))return handleRecursionLimit(statusBuilder,eventsProcessed,pendingPublishPromises,pendingWritebackPromises);throw err}if(await recorder?.flush(),eventsProcessed===0)throw new Error("Stream completed without processing any events. This may indicate a configuration error.");return initialStatus.phase===ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL?(console.log(`[streaming] execution=${executionId} stream ended with WAITING_FOR_APPROVAL. Not setting COMPLETED. pending_approvals computed server-side.`),{eventsProcessed,terminalStatus:slimStatus(initialStatus),pendingPublishPromises,pendingWritebackPromises}):(console.log(`[streaming] execution=${executionId} stream finished \u2014 processed ${eventsProcessed} events`),{eventsProcessed,pendingPublishPromises,pendingWritebackPromises})}function sendHeartbeat2(fn,executionId,eventsProcessed,sb){try{fn({executionId,eventsProcessed,messages:sb.currentStatus.messages.length,phase:sb.currentStatus.phase})}catch(err){console.warn(`[streaming] Heartbeat failed for ${executionId}:`,err)}}function checkStallTimeout2(lastEventTime,stallTimeoutMs,executionId){let elapsed2=performance.now()-lastEventTime;if(elapsed2>stallTimeoutMs)throw new StallTimeoutError2(`Agent stream stalled: no events received for ${Math.round(elapsed2/1e3)}s for execution ${executionId}`)}function extractFilePathFromToolEnd(event){let toolName=event.name??"";if(!FILE_MODIFYING_TOOLS2.has(toolName))return null;let input=event.data?.input;return input?typeof input.path=="string"?input.path:typeof input.file_path=="string"?input.file_path:typeof input.filename=="string"?input.filename:typeof input.file=="string"?input.file:null:null}var DEFAULT_STALL_TIMEOUT_MS2,FILE_MODIFYING_TOOLS2,StallTimeoutError2,init_streaming5=__esm({"dist/activities/execute-deep-agent/streaming.js"(){"use strict";init_enum_pb();init_status_builder();init_streaming_terminal();init_streaming_scheduler();init_status2();init_event_recorder();init_streaming_v3();DEFAULT_STALL_TIMEOUT_MS2=12e4;FILE_MODIFYING_TOOLS2=new Set(["write_file","edit_file","create_file","write","edit","create","str_replace_editor"]);StallTimeoutError2=class extends Error{constructor(message){super(message),this.name="StallTimeoutError"}}}});function normalizePath(path6){return path6.replace(/^\/+/,"")}function sha2563(content){return(0,import_node_crypto8.createHash)("sha256").update(content).digest("hex")}function guessContentType(filename){let ext=filename.slice(filename.lastIndexOf(".")).toLowerCase();return CONTENT_TYPE_MAP[ext]??"application/octet-stream"}var import_node_crypto8,import_node_path20,InlinePublisher,CONTENT_TYPE_MAP,init_inline_publisher=__esm({"dist/activities/execute-deep-agent/inline-publisher.js"(){"use strict";import_node_crypto8=require("node:crypto"),import_node_path20=require("node:path");init_esm4();init_artifact_pb();init_enum_pb();init_status2();InlinePublisher=class{workspaceBackend;artifactStorage;statusWriter;executionId;published=new Map;constructor(opts){this.workspaceBackend=opts.workspaceBackend,this.artifactStorage=opts.artifactStorage,this.statusWriter=opts.statusWriter,this.executionId=opts.executionId}get publishedPaths(){return new Set(this.published.keys())}async publish(path6){try{let sandboxPath=normalizePath(path6),content=await this.workspaceBackend.readFile(sandboxPath),contentBuffer=Buffer.from(content,"utf-8"),contentHash=sha2563(contentBuffer);if(this.published.get(sandboxPath)===contentHash)return;let fileName=(0,import_node_path20.basename)(sandboxPath),storageKey=`artifacts/${this.executionId}/${fileName}`;await this.artifactStorage.upload(storageKey,contentBuffer,guessContentType(fileName));let downloadUrl=await this.artifactStorage.getDownloadUrl(storageKey),artifact=create(ExecutionArtifactSchema,{name:fileName,sandboxPath,kind:ExecutionArtifactKind.FILE,sizeBytes:BigInt(contentBuffer.length),storageKey,downloadUrl,createdAt:utcTimestamp(),contentHash});this.statusWriter.addArtifact(artifact),this.published.set(sandboxPath,contentHash),console.log(`[InlinePublisher] execution=${this.executionId} \u2014 published '${sandboxPath}' (${contentBuffer.length} bytes, hash=${contentHash.slice(0,12)})`)}catch(err){console.warn(`[InlinePublisher] execution=${this.executionId} \u2014 failed to publish '${path6}' (non-fatal): ${err}`)}}};CONTENT_TYPE_MAP={".txt":"text/plain",".md":"text/markdown",".json":"application/json",".js":"application/javascript",".ts":"application/typescript",".py":"text/x-python",".html":"text/html",".css":"text/css",".xml":"text/xml",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".pdf":"application/pdf",".zip":"application/zip",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml"}}});function parseGithubRepo(repoUrl){let httpsMatch=repoUrl.match(/github\.com[/:]([^/]+)\/([^/.]+?)(?:\.git)?$/);if(httpsMatch)return{owner:httpsMatch[1],repo:httpsMatch[2]};throw new Error(`Cannot parse GitHub owner/repo from URL: ${repoUrl}`)}function extractGithubToken(repoUrl){let match=repoUrl.match(/https?:\/\/([^@]+)@github\.com/);if(match)return match[1];let envToken=process.env.GITHUB_TOKEN;if(envToken)return envToken;throw new Error("Cannot extract GitHub token from repo URL and GITHUB_TOKEN is not set")}var WRITE_BACK_ENABLED_MODES,WriteBackCoordinator,init_writeback_coordinator=__esm({"dist/activities/execute-deep-agent/writeback-coordinator.js"(){"use strict";init_esm4();init_writeback_pb();init_writeback_pb();init_enum_pb4();init_types6();WRITE_BACK_ENABLED_MODES=new Set([GitWriteBackMode.GIT_WRITE_BACK_MODE_UNSPECIFIED,GitWriteBackMode.GIT_WRITE_BACK_BRANCH_AND_PR]),WriteBackCoordinator=class{statusWriter;executionId;workspaceBackend;shortId;branchName;eligible=new Map;state=new Map;locks=new Map;constructor(opts){this.statusWriter=opts.statusWriter,this.executionId=opts.executionId,this.workspaceBackend=opts.workspaceBackend,this.shortId=opts.executionId.slice(0,8),this.branchName=`stigmer/${this.shortId}`,this.initEligibleEntries(opts.provisionResults,opts.workspaceEntries)}get hasEligibleEntries(){return this.eligible.size>0}async onFileModified(path6){try{let entryName=this.resolveEntry(path6);if(!entryName)return;await this.withLock(entryName,()=>this.incrementalWriteBack(entryName))}catch(err){console.warn(`[WriteBack] execution=${this.executionId} \u2014 onFileModified error for '${path6}': ${err}`)}}async finalize(){for(let entryName of this.eligible.keys())try{await this.withLock(entryName,()=>this.incrementalWriteBack(entryName))}catch(err){console.warn(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 finalize error: ${err}`)}}initEligibleEntries(provisionResults,workspaceEntries){let modeMap=new Map;for(let entry of workspaceEntries){let source=entry.source;source?.source.case==="gitRepo"&&modeMap.set(entry.name,source.source.value.writeBackMode)}for(let pr of provisionResults){if(pr.sourceType!==SourceType.GIT_REPO||!pr.gitMetadata||!pr.gitMetadata.gitCredentialsConfigured)continue;let mode=modeMap.get(pr.entryName)??GitWriteBackMode.GIT_WRITE_BACK_MODE_UNSPECIFIED;WRITE_BACK_ENABLED_MODES.has(mode)&&(this.eligible.set(pr.entryName,{provisionResult:pr,baseBranch:pr.gitMetadata.branch,rootDir:pr.rootDir,entryName:pr.entryName}),this.state.set(pr.entryName,{branchCreated:!1,prCreated:!1,prUrl:"",prNumber:0,commitCount:0,lastCommitSha:"",githubToken:"",githubOwner:"",githubRepo:""}))}this.eligible.size>0&&console.log(`[WriteBack] execution=${this.executionId} \u2014 coordinator initialized with ${this.eligible.size} eligible workspace(s): ${[...this.eligible.keys()].join(", ")}`)}resolveEntry(path6){if(this.eligible.size===0)return null;if(this.eligible.size===1)return this.eligible.keys().next().value;let normalized=path6.replace(/^\/+/,"");for(let entryName of this.eligible.keys())if(normalized.startsWith(entryName+"/")||normalized===entryName)return entryName;return null}async incrementalWriteBack(entryName){let entry=this.eligible.get(entryName),entryState=this.state.get(entryName),rootDir=entry.rootDir,exec2=async cmd=>this.workspaceBackend.execute(`cd ${rootDir} && ${cmd}`),mutationStarted=!1;try{if(!await this.hasChanges(exec2))return;mutationStarted=!0,entryState.branchCreated||await this.createBranch(entryName,entryState,exec2);let commitMsg=`agent changes (${entryState.commitCount+1})`;await this.commitAndPush(entryName,entryState,exec2,commitMsg),entryState.prCreated||await this.createPr(entryName,entryState,entry,exec2),await this.updateStatus(entryName,entryState,entry,exec2)}catch(err){if(console.warn(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 incremental error: ${err}`),!mutationStarted)return;let wb=create(WorkspaceWriteBackSchema,{workspaceEntryName:entryName,baseBranch:entry.baseBranch,branchName:entryState.branchCreated?this.branchName:"",phase:WorkspaceWriteBackPhase.WORKSPACE_WRITE_BACK_FAILED,error:String(err)});entryState.prCreated&&(wb.pullRequestUrl=entryState.prUrl,wb.pullRequestNumber=entryState.prNumber),this.statusWriter.addWriteBack(wb)}}async hasChanges(exec2){let diff=await exec2("git diff --stat").catch(()=>""),staged=await exec2("git diff --cached --stat").catch(()=>"");return diff.trim()||staged.trim()?!0:(await exec2("git ls-files --others --exclude-standard").catch(()=>"")).trim().length>0}async createBranch(entryName,entryState,exec2){await exec2(`git checkout -b ${this.branchName}`),entryState.branchCreated=!0,console.log(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 created branch ${this.branchName}`)}async commitAndPush(entryName,entryState,exec2,commitMsg){await exec2("git add -A"),await exec2(`git commit -m "${commitMsg}"`),entryState.commitCount++;let shaOutput=await exec2("git rev-parse HEAD");entryState.lastCommitSha=shaOutput.trim(),entryState.commitCount===1?await exec2(`git push -u origin ${this.branchName}`):await exec2("git push"),console.log(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 commit #${entryState.commitCount} pushed (sha=${entryState.lastCommitSha.slice(0,12)})`)}async createPr(entryName,entryState,entry,_exec){let meta3=entry.provisionResult.gitMetadata,{owner,repo}=parseGithubRepo(meta3.repoUrl);entryState.githubToken||(entryState.githubToken=extractGithubToken(meta3.repoUrl),entryState.githubOwner=owner,entryState.githubRepo=repo);let prTitle=`Agent changes (${this.shortId})`,prBody=`Automated pull request from Stigmer agent execution.
2071
+ IMPORTANT: When your analysis is complete, provide your findings as structured output matching the required schema. The system will capture your structured response automatically.`);let langgraphInput={messages:[{role:"user",content:userMessage}]},langgraphConfig={configurable:{thread_id:threadId}},streamVersion=process.env.LANGGRAPH_STREAM_EVENTS_VERSION==="v2"?"v2":"v3";return console.log(`[setup] Complete: model=${modelName}, tools=${tools3.length}, middleware=${middleware.length}, thread_id=${threadId}, streamVersion=${streamVersion}`),{agentGraph,langgraphConfig,langgraphInput,execution,agent,session,workspaceBackend,mcpConnection,mergedEnvVars:envResult.mergedEnvVars,secretKeys:envResult.secretKeys,modelName,gracefulStop,artifactStorage,provisionResults,approvalPolicies,toolServerMap,autoApproveAll,hasStructuredOutput:!!outputSchema,streamVersion}}catch(err){if(mcpConnection)try{await mcpConnection.client.close()}catch{}throw err}}function constructModel(modelName,config4,executionId){let provider=inferProvider2(modelName),apiModelId=stripProviderPrefix(modelName),baseUrl=config4.proxyEndpoint?resolveProxyBaseUrl(config4.proxyEndpoint,provider):void 0,headers=config4.proxyEndpoint&&config4.stigmerToken?buildProxyHeaders(config4.stigmerToken,{executionId}):void 0;switch(provider){case"anthropic":return buildAnthropicModel(apiModelId,baseUrl,headers,config4);case"openai":return buildOpenAIModel(apiModelId,baseUrl,headers,config4)}}function buildAnthropicModel(model,baseUrl,headers,config4){let apiKey=config4.proxyEndpoint?config4.stigmerToken??"proxy-managed":process.env.ANTHROPIC_API_KEY??"",requestTimeoutMs=parseInt(process.env.STIGMER_LLM_REQUEST_TIMEOUT_MS??"0")||void 0;return new ChatAnthropic({model,apiKey,temperature:0,...requestTimeoutMs?{maxRetries:0,timeout:requestTimeoutMs}:{},...baseUrl||headers?{clientOptions:{...baseUrl?{baseURL:baseUrl}:{},...headers?{defaultHeaders:headers}:{}}}:{}})}function buildOpenAIModel(model,baseUrl,headers,config4){let apiKey=config4.proxyEndpoint?config4.stigmerToken??"proxy-managed":process.env.OPENAI_API_KEY??"",requestTimeoutMs=parseInt(process.env.STIGMER_LLM_REQUEST_TIMEOUT_MS??"0")||void 0;return new ChatOpenAI({model,apiKey,temperature:0,...requestTimeoutMs?{maxRetries:0,timeout:requestTimeoutMs}:{},...baseUrl||headers?{configuration:{...baseUrl?{baseURL:baseUrl}:{},...headers?{defaultHeaders:headers}:{}}}:{}})}async function provisionWorkspace(config4,session,mergedEnvVars,sessionId){let platformDir=await ensurePlatformDir(sessionId),workspaceBackend=new LocalWorkspaceBackend(config4.workspaceRootDir,platformDir),workspaceEntries=session.spec.workspaceEntries||[];if(workspaceEntries.length===0)return{workspaceBackend,provisionResults:[]};let provisionResults=await new WorkspaceProvisioner().provisionAll(workspaceEntries.map(entry=>({name:entry.name,source:entry.source})),workspaceBackend,mergedEnvVars,config4.mode==="local",config4.mode!=="local");return provisionResults.length===1&&provisionResults[0].rootDir!==workspaceBackend.rootDir?{workspaceBackend:new LocalWorkspaceBackend(provisionResults[0].rootDir,platformDir),provisionResults}:{workspaceBackend,provisionResults}}function _modelHasNativeThinking(modelId){let lower=modelId.toLowerCase();return lower.includes("haiku")||lower.includes("gpt-4o-mini")?!1:!!(lower.includes("claude")&&(lower.includes("sonnet")||lower.includes("opus"))||lower.includes("o1")||lower.includes("o3")||lower.includes("o4"))}var init_setup=__esm({"dist/activities/execute-deep-agent/setup.js"(){"use strict";init_dist8();init_enum_pb();init_dist9();init_dist10();init_factory();init_mcp_manager();init_mcp_resolver2();init_connect_backfill();init_provisioner();init_local_backend();init_platform_dir();init_status2();init_environment();init_prompt_builder2();init_middleware4();init_model_pricing2();init_model_registry();init_artifact_storage();init_approval_policy2();init_llm_proxy();init_skill_writer();init_skill_relevance();init_attachment_injector();init_subagent_transformer();init_json_schema_to_zod()}});var ExecutionState,init_execution_state=__esm({"dist/activities/execute-deep-agent/execution-state.js"(){"use strict";ExecutionState=class{proto;toolCalls=new Map;messagesByRun=new Map;currentAiMessage=new Map;lastLlmRunId=new Map;toolStartTimes=new Map;constructor(proto){this.proto=proto}resetEphemeralState(){this.messagesByRun.clear(),this.currentAiMessage.clear(),this.lastLlmRunId.clear(),this.toolStartTimes.clear()}rebuildToolCallIndex(){this.toolCalls.clear();for(let message of this.proto.messages)for(let tc of message.toolCalls)tc.id&&this.toolCalls.set(tc.id,tc)}}}});function toBigInt(value){return typeof value=="bigint"?value:typeof value=="number"&&Number.isFinite(value)?BigInt(Math.floor(value)):0n}function serializeToolContent(content){if(typeof content=="string")return content;if(Array.isArray(content))return JSON.stringify(content)}function extractToolResult(data){let output=data.output;if(typeof output=="string")return output;if(typeof output=="object"&&output!==null){let fromContent=serializeToolContent(output.content);if(fromContent!==void 0)return fromContent}try{return JSON.stringify(output??data)}catch{return"[serialization error]"}}function extractToolResultV3(output){if(typeof output=="string")return output;if(typeof output=="object"&&output!==null){let obj=output,kwargs=obj.kwargs;if(kwargs){let fromKwargs=serializeToolContent(kwargs.content);if(fromKwargs!==void 0)return fromKwargs}let fromContent=serializeToolContent(obj.content);if(fromContent!==void 0)return fromContent}try{return JSON.stringify(output)}catch{return"[serialization error]"}}function sanitizeArgsPreview(args){let sanitized={};for(let[key,value]of Object.entries(args))SENSITIVE_ARG_KEYS.has(key.toLowerCase())?sanitized[key]="[REDACTED]":sanitized[key]=value;try{let json5=JSON.stringify(sanitized);return json5.length>MAX_ARGS_PREVIEW_LENGTH?json5.slice(0,MAX_ARGS_PREVIEW_LENGTH)+"\u2026":json5}catch{return""}}var UsageAccumulator2,SENSITIVE_ARG_KEYS,MAX_ARGS_PREVIEW_LENGTH,init_status_builder_shared=__esm({"dist/activities/execute-deep-agent/status-builder-shared.js"(){"use strict";init_esm4();init_usage_pb();init_status2();UsageAccumulator2=class{inputTokens=0n;outputTokens=0n;cacheReadTokens=0n;cacheWriteTokens=0n;turnCount=0;lastObservedAt="";accumulate(meta3){this.inputTokens+=toBigInt(meta3.input_tokens),this.outputTokens+=toBigInt(meta3.output_tokens),this.cacheReadTokens+=toBigInt(meta3.cache_read_input_tokens),this.cacheWriteTokens+=toBigInt(meta3.cache_creation_input_tokens),this.turnCount++,this.lastObservedAt=utcTimestamp()}snapshot(){return{inputTokens:this.inputTokens,outputTokens:this.outputTokens,cacheReadTokens:this.cacheReadTokens,cacheWriteTokens:this.cacheWriteTokens,totalTokens:this.inputTokens+this.outputTokens+this.cacheReadTokens+this.cacheWriteTokens,turnCount:this.turnCount,observedAt:this.lastObservedAt}}toProto(){return create(StreamingUsageSummarySchema,this.snapshot())}};SENSITIVE_ARG_KEYS=new Set(["password","token","secret","api_key","apikey","credentials","auth","authorization"]),MAX_ARGS_PREVIEW_LENGTH=500}});var StatusBuilder,init_status_builder=__esm({"dist/activities/execute-deep-agent/status-builder.js"(){"use strict";init_esm4();init_message_pb();init_enum_pb();init_approval_policy2();init_tool_kind();init_execution_state();init_status2();init_status_builder_shared();StatusBuilder=class{executionId;state;_forceNextUpdate=!1;approvalProvider=null;usageAccumulator;handlers;constructor(executionId,initialStatus){this.executionId=executionId,this.state=new ExecutionState(initialStatus),initialStatus.phase=ExecutionPhase.EXECUTION_IN_PROGRESS,initialStatus.startedAt||(initialStatus.startedAt=utcTimestamp()),this.usageAccumulator=new UsageAccumulator2,this.handlers=new Map([["on_chat_model_stream",this.handleChatModelStream.bind(this)],["on_chat_model_end",this.handleChatModelEnd.bind(this)],["on_tool_start",this.handleToolStart.bind(this)],["on_tool_end",this.handleToolEnd.bind(this)]])}setApprovalProvider(provider){this.approvalProvider=provider}get currentStatus(){return this.state.proto}get forceNextUpdate(){return this._forceNextUpdate}clearForceFlag(){this._forceNextUpdate=!1}processEvent(event){let namespace=this.extractNamespace(event),handler=this.handlers.get(event.event);if(handler)try{handler(event,namespace)}catch(err){console.error(`[StatusBuilder] Event handler error: execution=${this.executionId} event=${event.event} run_id=${event.run_id}: ${err}`)}}addArtifact(artifact){let artifacts=this.state.proto.artifacts,idx=artifacts.findIndex(a=>a.sandboxPath===artifact.sandboxPath);if(idx>=0){artifacts[idx].contentHash!==artifact.contentHash&&(artifacts[idx]=artifact,this._forceNextUpdate=!0);return}artifacts.push(artifact),this._forceNextUpdate=!0}addWriteBack(wb){let backs=this.state.proto.workspaceWriteBacks,idx=backs.findIndex(b=>b.workspaceEntryName===wb.workspaceEntryName);idx>=0?backs[idx]=wb:backs.push(wb),this._forceNextUpdate=!0}handleChatModelStream(event,namespace){let chunk=event.data?.chunk;if(!chunk)return;let content=chunk.content;if(Array.isArray(content)){for(let block of content)if(typeof block=="object"&&block!==null){let b=block;b.type==="thinking"&&typeof b.thinking=="string"?this.appendThinkingContent(event.run_id,namespace,b.thinking):b.type==="text"&&typeof b.text=="string"&&this.appendTextContent(event.run_id,namespace,b.text)}}else typeof content=="string"&&content.length>0&&this.appendTextContent(event.run_id,namespace,content)}handleChatModelEnd(event,namespace){let output=event.data?.output,msg=this.state.messagesByRun.get(event.run_id);msg&&(msg.isStreaming=!1);let usageMeta=output?.usage_metadata??event.data?.usage_metadata;usageMeta&&(this.usageAccumulator.accumulate(usageMeta),this.syncUsageToProto())}handleToolStart(event,namespace){let parentMsg=this.state.currentAiMessage.get(namespace)??this.ensureAiMessageForToolCall(event.run_id,namespace);if(!parentMsg)return;let toolName=event.name??"unknown_tool",rawArgs=event.data?.input,args=rawArgs??{},approvalReq=this.checkApprovalRequirement(toolName,args),tc=create(ToolCallSchema,{id:event.run_id,name:toolName,status:approvalReq.requiresApproval?ToolCallStatus.TOOL_CALL_WAITING_APPROVAL:ToolCallStatus.TOOL_CALL_RUNNING,startedAt:utcTimestamp()});if(rawArgs&&(tc.args=rawArgs),approvalReq.serverSlug&&(tc.mcpServerSlug=approvalReq.serverSlug),tc.toolKind=classifyTool(tc.name,tc.mcpServerSlug),approvalReq.requiresApproval){tc.requiresApproval=!0,tc.approvalMessage=approvalReq.message,tc.approvalRequestedAt=utcTimestamp();let argsPreview=sanitizeArgsPreview(args);argsPreview&&(tc.argsPreview=argsPreview),this.state.proto.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL}parentMsg.toolCalls.push(tc),this.state.toolCalls.set(event.run_id,tc),this.state.toolStartTimes.set(event.run_id,performance.now()),this._forceNextUpdate=!0}checkApprovalRequirement(toolName,args){if(!this.approvalProvider)return{requiresApproval:!1,message:"",serverSlug:""};let serverSlug=this.approvalProvider.toolServerMap.get(toolName)??"";if(this.approvalProvider.autoApproveAll)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage2(policy.approvalMessage,toolName,args),serverSlug}:{requiresApproval:!1,message:"",serverSlug}}return{requiresApproval:!1,message:"",serverSlug:""}}handleToolEnd(event,_namespace){let tc=this.state.toolCalls.get(event.run_id);if(!tc)return;let errorMsg=event.data?.output?.error;errorMsg?(tc.status=ToolCallStatus.TOOL_CALL_FAILED,tc.error=errorMsg):(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.result=extractToolResult(event.data)),tc.completedAt=utcTimestamp(),tc.isStreaming=!1,this.state.toolStartTimes.delete(event.run_id),this._forceNextUpdate=!0}appendTextContent(runId,namespace,text){let msg=this.ensureAiMessage(runId,namespace,MessageType.MESSAGE_AI);msg.content+=text,msg.isStreaming=!0}appendThinkingContent(runId,namespace,text){let thinkingKey=`thinking:${namespace}`,existingMsg=this.state.messagesByRun.get(thinkingKey);if(existingMsg&&existingMsg.type===MessageType.MESSAGE_THINKING){existingMsg.content+=text,existingMsg.isStreaming=!0;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:text,timestamp:utcTimestamp(),isStreaming:!0});this.state.proto.messages.push(msg),this.state.messagesByRun.set(thinkingKey,msg)}ensureAiMessage(runId,namespace,type3){let existingByRun=this.state.messagesByRun.get(runId);if(existingByRun)return existingByRun;let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId&&lastRunId!==runId){let existingMsg=this.state.currentAiMessage.get(namespace);existingMsg&&(existingMsg.isStreaming=!1)}let msg=create(AgentMessageSchema,{type:type3,content:"",timestamp:utcTimestamp(),isStreaming:!0});return this.state.proto.messages.push(msg),this.state.messagesByRun.set(runId,msg),this.state.currentAiMessage.set(namespace,msg),this.state.lastLlmRunId.set(namespace,runId),msg}ensureAiMessageForToolCall(_toolRunId,namespace){let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId){let existing=this.state.messagesByRun.get(lastRunId);if(existing)return this.state.currentAiMessage.set(namespace,existing),existing}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});return this.state.proto.messages.push(msg),this.state.currentAiMessage.set(namespace,msg),msg}extractNamespace(event){let meta3=event.metadata;if(!meta3)return"";let ns3=meta3.langgraph_checkpoint_ns??meta3.checkpoint_ns??"";return typeof ns3=="string"?ns3:""}syncUsageToProto(){this.state.proto.streamingUsage=this.usageAccumulator.toProto()}}}});function handlePause(writer2,eventsProcessed,pendingPublishPromises,pendingWritebackPromises){let status=writer2.currentStatus;return status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue from this checkpoint.",timestamp:utcTimestamp()})),{eventsProcessed,terminalStatus:slimStatus(status),pendingPublishPromises,pendingWritebackPromises}}function handleStop(writer2,eventsProcessed,pendingPublishPromises,pendingWritebackPromises){let status=writer2.currentStatus;return status.phase=ExecutionPhase.EXECUTION_COMPLETED,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution stopped by the platform.",timestamp:utcTimestamp()})),{eventsProcessed,terminalStatus:slimStatus(status),pendingPublishPromises,pendingWritebackPromises}}function handleRecursionLimit(writer2,eventsProcessed,pendingPublishPromises,pendingWritebackPromises){let status=writer2.currentStatus;return status.phase=ExecutionPhase.EXECUTION_TERMINATED,status.completedAt=utcTimestamp(),status.error=`Agent reached the tool-call limit after processing ${eventsProcessed} events. Send another message to continue.`,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"The agent reached the tool-call limit for this message. Work completed so far has been saved. Send another message to continue where the agent left off.",timestamp:utcTimestamp()})),{eventsProcessed,terminalStatus:slimStatus(status),pendingPublishPromises,pendingWritebackPromises}}function isGraphRecursionError(err){return err instanceof Error?err.constructor.name==="GraphRecursionError"||err.message.includes("GraphRecursionError")||err.message.includes("Recursion limit"):!1}var init_streaming_terminal=__esm({"dist/activities/execute-deep-agent/streaming-terminal.js"(){"use strict";init_esm4();init_message_pb();init_enum_pb();init_status2()}});function createV2EventRecorder(executionId,recordDir){if(recordDir)return new FileV2EventRecorder(executionId,recordDir)}function safeClone2(obj){try{return JSON.parse(JSON.stringify(obj,bigintReplacer))}catch{return{_serializationError:!0,keys:Object.keys(obj)}}}function bigintReplacer(_key,value){return typeof value=="bigint"?value.toString():value}var import_promises13,import_node_path18,FileV2EventRecorder,init_event_recorder=__esm({"dist/activities/execute-deep-agent/event-recorder.js"(){"use strict";import_promises13=require("node:fs/promises"),import_node_path18=require("node:path");FileV2EventRecorder=class{executionId;outputDir;events=[];constructor(executionId,outputDir){this.executionId=executionId,this.outputDir=outputDir}record(event,seq2){this.events.push({seq:seq2,timestamp:new Date().toISOString(),event:event.event,name:event.name,run_id:event.run_id,data:safeClone2(event.data),metadata:event.metadata?safeClone2(event.metadata):void 0})}async flush(){if(this.events.length===0)return;await(0,import_promises13.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path18.join)(this.outputDir,`${this.executionId}.v2-events.json`),payload={executionId:this.executionId,recordedAt:new Date().toISOString(),eventCount:this.events.length,events:this.events};await(0,import_promises13.writeFile)(filePath,JSON.stringify(payload,bigintReplacer,2))}}}});function createV3EventRecorder(executionId,recordDir){if(recordDir)return new FileV3EventRecorder(executionId,recordDir)}function safeClone3(obj){try{return JSON.parse(JSON.stringify(obj,bigintReplacer2))}catch{return obj&&typeof obj=="object"?{_serializationError:!0,keys:Object.keys(obj)}:{_serializationError:!0}}}function bigintReplacer2(_key,value){return typeof value=="bigint"?value.toString():value}var import_promises14,import_node_path19,FileV3EventRecorder,init_v3_event_recorder=__esm({"dist/activities/execute-deep-agent/v3-event-recorder.js"(){"use strict";import_promises14=require("node:fs/promises"),import_node_path19=require("node:path");FileV3EventRecorder=class{executionId;outputDir;events=[];constructor(executionId,outputDir){this.executionId=executionId,this.outputDir=outputDir}record(event,seq2){this.events.push({seq:seq2,capturedAt:new Date().toISOString(),type:event.type,method:event.method,namespace:event.params.namespace,timestamp:event.params.timestamp,node:event.params.node,data:safeClone3(event.params.data)})}async flush(){if(this.events.length===0)return;await(0,import_promises14.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path19.join)(this.outputDir,`${this.executionId}.v3-events.json`),payload={executionId:this.executionId,recordedAt:new Date().toISOString(),eventCount:this.events.length,events:this.events};await(0,import_promises14.writeFile)(filePath,JSON.stringify(payload,bigintReplacer2,2))}}}});function formatNamespace(ns3){return ns3.length===0?"":ns3.join("|")}function namespaceDepth(namespace){if(!namespace)return 0;let count=1;for(let i2=0;i2<namespace.length;i2++)namespace[i2]==="|"&&count++;return count}var init_v3_events=__esm({"dist/activities/execute-deep-agent/v3-events.js"(){"use strict"}});function normalize3(event){switch(event.method){case"messages":return normalizeMessage(event);case"tools":return normalizeTool(event);case"lifecycle":return normalizeLifecycle(event);default:return[]}}function normalizeMessage(event){let data=event.params.data;if(!data)return[];let eventType=readEventType(data),base={seq:event.seq,namespace:formatNamespace(event.params.namespace),node:event.params.node},runId=data.run_id??"";switch(eventType){case"message-start":return[{kind:"message_start",...base,runId,messageId:data.id}];case"content-block-delta":return normalizeContentBlockDelta(event,data,base,runId);case"message-finish":return[{kind:"message_finish",...base,runId,usage:normalizeUsagePayload(data.usage),reason:data.reason}];case"usage":return[{kind:"usage",...base,runId,usage:normalizeUsagePayload(data.usage)}];case"provider":return[{kind:"provider",...base,provider:data.provider??"",model:extractModel(data)}];case"content-block-start":case"content-block-finish":return[];default:return logUnknown("messages",eventType),[]}}function normalizeContentBlockDelta(event,data,base,runId){let delta=data.delta;if(!delta)return[];let deltaType=delta.type;if(deltaType==="text-delta"){let text=delta.text??"";return text?[{kind:"text_delta",...base,runId,text}]:[]}if(deltaType==="reasoning-delta"){let text=delta.reasoning??"";return text?[{kind:"reasoning_delta",...base,runId,text}]:[]}if(deltaType==="block-delta"){let fields=delta.fields;if(!fields)return[];if(fields.type==="tool_call_chunk"){let callId=fields.id??"",argsChunk=fields.args??"";return!argsChunk&&!callId?[]:[{kind:"tool_call_arg_delta",...base,callId,argsChunk}]}}return[]}function normalizeTool(event){let data=event.params.data;if(!data)return[];let eventType=readEventType(data),base={seq:event.seq,namespace:formatNamespace(event.params.namespace),node:event.params.node};switch(eventType){case"tool-started":{let callId=readToolCallId(data),name2=readToolName(data),input=parseToolInput(data.input);return[{kind:"tool_started",...base,callId,name:name2,input}]}case"tool-finished":{let callId=readToolCallId(data);return[{kind:"tool_finished",...base,callId,output:data.output}]}case"tool-error":{let callId=readToolCallId(data),message=data.message??data.error??"";return[{kind:"tool_error",...base,callId,message}]}case"tool-output-delta":{let callId=readToolCallId(data),delta=data.delta??"";return[{kind:"tool_output_delta",...base,callId,delta:String(delta)}]}default:return logUnknown("tools",eventType),[]}}function normalizeLifecycle(event){let data=event.params.data;return data?[{kind:"lifecycle",seq:event.seq,namespace:formatNamespace(event.params.namespace),node:event.params.node,event:readEventType(data),graphName:data.graph_name??data.graphName}]:[]}function readEventType(data){return data.event??data.type??""}function readToolCallId(data){return data.tool_call_id??data.toolCallId??""}function readToolName(data){return data.tool_name??data.toolName??data.name??"unknown_tool"}function parseToolInput(raw){if(raw==null)return{};if(typeof raw=="object"&&!Array.isArray(raw))return raw;if(typeof raw=="string")try{return JSON.parse(raw)}catch{return{}}return{}}function normalizeUsagePayload(raw){if(!raw)return;let details=raw.input_token_details;return{input_tokens:raw.input_tokens,output_tokens:raw.output_tokens,total_tokens:raw.total_tokens,input_token_details:details?{cache_creation:details.cache_creation,cache_read:details.cache_read}:void 0}}function extractModel(data){return data.payload?.model}function logUnknown(method,eventType){let key=`${method}:${eventType}`;loggedUnknowns.has(key)||(loggedUnknowns.add(key),console.debug(`[V3Normalizer] Unknown event: method=${method} event=${eventType}`))}var loggedUnknowns,init_v3_protocol_normalizer=__esm({"dist/activities/execute-deep-agent/v3-protocol-normalizer.js"(){"use strict";init_v3_events();loggedUnknowns=new Set}});function extractFirstSegment(namespace){let pipeIdx=namespace.indexOf("|");return pipeIdx===-1?namespace:namespace.slice(0,pipeIdx)}function stripFirstSegment(namespace){let pipeIdx=namespace.indexOf("|");return pipeIdx===-1?"":namespace.slice(pipeIdx+1)}function safeString2(obj,key){let val=obj[key];return typeof val=="string"?val:""}var SubAgentTracker,init_subagent_tracker=__esm({"dist/activities/execute-deep-agent/subagent-tracker.js"(){"use strict";init_esm4();init_subagent_pb();init_message_pb();init_enum_pb();init_status2();init_tool_kind();init_status_builder_shared();SubAgentTracker=class{executions=[];stateByCallId=new Map;stateByPrefix=new Map;onTaskToolStarted(callId,args,routingPrefix){if(this.stateByCallId.has(callId))return;let name2=safeString2(args,"subagent_type")||"task",description2=safeString2(args,"description")||"",proto=create(SubAgentExecutionSchema,{id:callId,name:name2,subject:description2,input:description2,status:SubAgentStatus.SUB_AGENT_IN_PROGRESS,startedAt:utcTimestamp()}),state={proto,callId,namespacePrefix:routingPrefix,messagesByRun:new Map,currentAiMessage:new Map,lastLlmRunId:new Map,toolCalls:new Map,toolArgBuffers:new Map};this.executions.push(proto),this.stateByCallId.set(callId,state),this.stateByPrefix.set(routingPrefix,state)}onTaskToolFinished(callId,output){let state=this.stateByCallId.get(callId);state&&(state.proto.status=SubAgentStatus.SUB_AGENT_COMPLETED,state.proto.completedAt=utcTimestamp(),state.proto.output=extractToolResultV3(output),this.finalizeStreamingMessages(state))}onTaskToolError(callId,errorMessage){let state=this.stateByCallId.get(callId);state&&(state.proto.status=SubAgentStatus.SUB_AGENT_FAILED,state.proto.completedAt=utcTimestamp(),state.proto.error=errorMessage,this.finalizeStreamingMessages(state))}cancelAll(){for(let state of this.stateByCallId.values())state.proto.status===SubAgentStatus.SUB_AGENT_IN_PROGRESS&&(state.proto.status=SubAgentStatus.SUB_AGENT_CANCELLED,state.proto.completedAt=utcTimestamp(),state.proto.error="Cancelled: parent execution was cancelled",this.finalizeStreamingMessages(state))}isSubAgentNamespace(namespace){if(!namespace||!namespace.includes("|"))return!1;let firstSegment=extractFirstSegment(namespace);return this.stateByPrefix.has(firstSegment)}routeEvent(event){let firstSegment=extractFirstSegment(event.namespace),state=this.stateByPrefix.get(firstSegment);if(!state)return;let localNs=this.resolveAgentNamespace(stripFirstSegment(event.namespace));switch(event.kind){case"message_start":this.handleMessageStart(state,event.runId,localNs);break;case"text_delta":this.handleTextDelta(state,event.runId,localNs,event.text);break;case"reasoning_delta":this.handleReasoningDelta(state,event.runId,localNs,event.text);break;case"tool_call_arg_delta":this.handleToolCallArgDelta(state,event.callId,event.argsChunk);break;case"message_finish":this.handleMessageFinish(state,event.runId,event.usage);break;case"tool_started":this.handleToolStarted(state,event.callId,event.name,event.input,localNs);break;case"tool_finished":this.handleToolFinished(state,event.callId,event.output);break;case"tool_error":this.handleToolError(state,event.callId,event.message);break;case"tool_output_delta":this.handleToolOutputDelta(state,event.callId,event.delta);break;case"usage":case"lifecycle":case"provider":break}}getExecutions(){return this.executions}hasExecutions(){return this.executions.length>0}handleMessageStart(state,runId,localNs){let lastRunId=state.lastLlmRunId.get(localNs);if(lastRunId&&lastRunId!==runId){let existingMsg=state.currentAiMessage.get(localNs);existingMsg&&(existingMsg.isStreaming=!1)}state.lastLlmRunId.set(localNs,runId)}handleTextDelta(state,runId,localNs,text){let msg=this.ensureAiMessage(state,runId,localNs,MessageType.MESSAGE_AI);msg.content+=text,msg.isStreaming=!0}handleReasoningDelta(state,runId,localNs,text){let thinkingKey=`thinking:${localNs}`,existing=state.messagesByRun.get(thinkingKey);if(existing&&existing.type===MessageType.MESSAGE_THINKING){existing.content+=text,existing.isStreaming=!0;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:text,timestamp:utcTimestamp(),isStreaming:!0});state.proto.messages.push(msg),state.messagesByRun.set(thinkingKey,msg)}handleMessageFinish(state,runId,usage){let msg=state.messagesByRun.get(runId);msg&&(msg.isStreaming=!1)}handleToolStarted(state,callId,name2,input,localNs){let agentNs=this.resolveAgentNamespace(localNs),parentMsg=state.currentAiMessage.get(agentNs)??this.ensureAiMessageForToolCall(state,agentNs);if(!parentMsg)return;let tc=create(ToolCallSchema,{id:callId,name:name2,status:ToolCallStatus.TOOL_CALL_RUNNING,startedAt:utcTimestamp(),toolKind:classifyTool(name2)});Object.keys(input).length>0&&(tc.args=input),parentMsg.toolCalls.push(tc),state.toolCalls.set(callId,tc)}handleToolFinished(state,callId,output){let tc=state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.result=extractToolResultV3(output),tc.completedAt=utcTimestamp(),tc.isStreaming=!1,state.toolArgBuffers.delete(callId))}handleToolError(state,callId,message){let tc=state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_FAILED,tc.error=message,tc.completedAt=utcTimestamp(),tc.isStreaming=!1,state.toolArgBuffers.delete(callId))}handleToolCallArgDelta(state,callId,argsChunk){let tc=state.toolCalls.get(callId);if(!tc)return;let buffer=(state.toolArgBuffers.get(callId)??"")+argsChunk;state.toolArgBuffers.set(callId,buffer);try{tc.args=JSON.parse(buffer)}catch{}}handleToolOutputDelta(state,callId,delta){let tc=state.toolCalls.get(callId);tc&&(tc.result=(tc.result??"")+delta)}ensureAiMessage(state,runId,localNs,type3){let existing=state.messagesByRun.get(runId);if(existing)return existing;let lastRunId=state.lastLlmRunId.get(localNs);if(lastRunId&&lastRunId!==runId){let prev=state.currentAiMessage.get(localNs);prev&&(prev.isStreaming=!1)}let msg=create(AgentMessageSchema,{type:type3,content:"",timestamp:utcTimestamp(),isStreaming:!0});return state.proto.messages.push(msg),state.messagesByRun.set(runId,msg),state.currentAiMessage.set(localNs,msg),state.lastLlmRunId.set(localNs,runId),msg}ensureAiMessageForToolCall(state,localNs){let lastRunId=state.lastLlmRunId.get(localNs);if(lastRunId){let existing=state.messagesByRun.get(lastRunId);if(existing)return state.currentAiMessage.set(localNs,existing),existing}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});return state.proto.messages.push(msg),state.currentAiMessage.set(localNs,msg),msg}resolveAgentNamespace(ns3){return ns3?ns3.split("|").filter(p=>!p.startsWith("tools:")&&!p.startsWith("model_request")).join("|"):""}finalizeStreamingMessages(state){for(let msg of state.currentAiMessage.values())msg.isStreaming=!1}}}});var V3StatusBuilder,init_v3_status_builder=__esm({"dist/activities/execute-deep-agent/v3-status-builder.js"(){"use strict";init_esm4();init_message_pb();init_enum_pb();init_approval_policy2();init_tool_kind();init_execution_state();init_status2();init_v3_events();init_status_builder_shared();init_subagent_tracker();V3StatusBuilder=class{executionId;state;_forceNextUpdate=!1;approvalProvider=null;usageAccumulator;subAgentTracker;toolArgBuffers=new Map;constructor(executionId,initialStatus){this.executionId=executionId,this.state=new ExecutionState(initialStatus),initialStatus.phase=ExecutionPhase.EXECUTION_IN_PROGRESS,initialStatus.startedAt||(initialStatus.startedAt=utcTimestamp()),this.usageAccumulator=new UsageAccumulator2,this.subAgentTracker=new SubAgentTracker}setApprovalProvider(provider){this.approvalProvider=provider}get currentStatus(){return this.state.proto}get forceNextUpdate(){return this._forceNextUpdate}clearForceFlag(){this._forceNextUpdate=!1}processEvent(event){try{if(event.kind==="tool_started"&&event.name==="task"&&namespaceDepth(event.namespace)<=1){let routingPrefix=event.namespace||`tools:${event.callId}`;this.subAgentTracker.onTaskToolStarted(event.callId,event.input,routingPrefix),this.handleToolStarted(event.callId,event.name,event.input,event.namespace),this._forceNextUpdate=!0;return}if(event.kind==="tool_finished"&&this.isTrackedTaskTool(event.callId)){this.subAgentTracker.onTaskToolFinished(event.callId,event.output),this.handleToolFinished(event.callId,event.output),this._forceNextUpdate=!0;return}if(event.kind==="tool_error"&&this.isTrackedTaskTool(event.callId)){this.subAgentTracker.onTaskToolError(event.callId,event.message),this.handleToolError(event.callId,event.message),this._forceNextUpdate=!0;return}if(this.subAgentTracker.isSubAgentNamespace(event.namespace)){this.subAgentTracker.routeEvent(event);return}switch(event.kind){case"message_start":this.handleMessageStart(event.runId,event.namespace);break;case"text_delta":this.appendTextContent(event.runId,event.namespace,event.text);break;case"reasoning_delta":this.appendThinkingContent(event.runId,event.namespace,event.text);break;case"tool_call_arg_delta":this.handleToolCallArgDelta(event.callId,event.argsChunk);break;case"message_finish":this.handleMessageFinish(event.runId,event.namespace,event.usage);break;case"tool_started":this.handleToolStarted(event.callId,event.name,event.input,event.namespace);break;case"tool_finished":this.handleToolFinished(event.callId,event.output);break;case"tool_error":this.handleToolError(event.callId,event.message);break;case"tool_output_delta":this.handleToolOutputDelta(event.callId,event.delta);break;case"usage":case"lifecycle":case"provider":break}}catch(err){console.error(`[V3StatusBuilder] Event handler error: execution=${this.executionId} kind=${event.kind} seq=${event.seq}: ${err}`)}}addArtifact(artifact){let artifacts=this.state.proto.artifacts,idx=artifacts.findIndex(a=>a.sandboxPath===artifact.sandboxPath);if(idx>=0){artifacts[idx].contentHash!==artifact.contentHash&&(artifacts[idx]=artifact,this._forceNextUpdate=!0);return}artifacts.push(artifact),this._forceNextUpdate=!0}addWriteBack(wb){let backs=this.state.proto.workspaceWriteBacks,idx=backs.findIndex(b=>b.workspaceEntryName===wb.workspaceEntryName);idx>=0?backs[idx]=wb:backs.push(wb),this._forceNextUpdate=!0}handleMessageStart(runId,namespace){let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId&&lastRunId!==runId){let existingMsg=this.state.currentAiMessage.get(namespace);existingMsg&&(existingMsg.isStreaming=!1)}this.state.lastLlmRunId.set(namespace,runId)}handleMessageFinish(runId,_namespace,usage){let msg=this.state.messagesByRun.get(runId);msg&&(msg.isStreaming=!1),usage&&this.accumulateV3Usage(usage)}appendTextContent(runId,namespace,text){let msg=this.ensureAiMessage(runId,namespace,MessageType.MESSAGE_AI);msg.content+=text,msg.isStreaming=!0}appendThinkingContent(runId,namespace,text){let thinkingKey=`thinking:${namespace}`,existingMsg=this.state.messagesByRun.get(thinkingKey);if(existingMsg&&existingMsg.type===MessageType.MESSAGE_THINKING){existingMsg.content+=text,existingMsg.isStreaming=!0;return}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_THINKING,content:text,timestamp:utcTimestamp(),isStreaming:!0});this.state.proto.messages.push(msg),this.state.messagesByRun.set(thinkingKey,msg)}handleToolStarted(callId,name2,input,namespace){let agentNs=this.resolveAgentNamespace(namespace),parentMsg=this.state.currentAiMessage.get(agentNs)??this.ensureAiMessageForToolCall(agentNs);if(!parentMsg)return;let approvalReq=this.checkApprovalRequirement(name2,input),tc=create(ToolCallSchema,{id:callId,name:name2,status:approvalReq.requiresApproval?ToolCallStatus.TOOL_CALL_WAITING_APPROVAL:ToolCallStatus.TOOL_CALL_RUNNING,startedAt:utcTimestamp()});if(Object.keys(input).length>0&&(tc.args=input),approvalReq.serverSlug&&(tc.mcpServerSlug=approvalReq.serverSlug),tc.toolKind=classifyTool(tc.name,tc.mcpServerSlug),approvalReq.requiresApproval){tc.requiresApproval=!0,tc.approvalMessage=approvalReq.message,tc.approvalRequestedAt=utcTimestamp();let argsPreview=sanitizeArgsPreview(input);argsPreview&&(tc.argsPreview=argsPreview),this.state.proto.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL}parentMsg.toolCalls.push(tc),this.state.toolCalls.set(callId,tc),this.state.toolStartTimes.set(callId,performance.now()),this._forceNextUpdate=!0}handleToolFinished(callId,output){let tc=this.state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_COMPLETED,tc.result=extractToolResultV3(output),tc.completedAt=utcTimestamp(),tc.isStreaming=!1,this.state.toolStartTimes.delete(callId),this.toolArgBuffers.delete(callId),this._forceNextUpdate=!0)}handleToolError(callId,message){let tc=this.state.toolCalls.get(callId);tc&&(tc.status=ToolCallStatus.TOOL_CALL_FAILED,tc.error=message,tc.completedAt=utcTimestamp(),tc.isStreaming=!1,this.state.toolStartTimes.delete(callId),this.toolArgBuffers.delete(callId),this._forceNextUpdate=!0)}handleToolCallArgDelta(callId,argsChunk){let tc=this.state.toolCalls.get(callId);if(!tc)return;let buffer=(this.toolArgBuffers.get(callId)??"")+argsChunk;this.toolArgBuffers.set(callId,buffer);try{tc.args=JSON.parse(buffer)}catch{}}handleToolOutputDelta(callId,delta){let tc=this.state.toolCalls.get(callId);tc&&(tc.result=(tc.result??"")+delta)}resolveAgentNamespace(ns3){return ns3?ns3.split("|").filter(p=>!p.startsWith("tools:")).join("|"):""}checkApprovalRequirement(toolName,args){if(!this.approvalProvider)return{requiresApproval:!1,message:"",serverSlug:""};let serverSlug=this.approvalProvider.toolServerMap.get(toolName)??"";if(this.approvalProvider.autoApproveAll)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage2(policy.approvalMessage,toolName,args),serverSlug}:{requiresApproval:!1,message:"",serverSlug}}return{requiresApproval:!1,message:"",serverSlug:""}}ensureAiMessage(runId,namespace,type3){let existingByRun=this.state.messagesByRun.get(runId);if(existingByRun)return existingByRun;let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId&&lastRunId!==runId){let existingMsg=this.state.currentAiMessage.get(namespace);existingMsg&&(existingMsg.isStreaming=!1)}let msg=create(AgentMessageSchema,{type:type3,content:"",timestamp:utcTimestamp(),isStreaming:!0});return this.state.proto.messages.push(msg),this.state.messagesByRun.set(runId,msg),this.state.currentAiMessage.set(namespace,msg),this.state.lastLlmRunId.set(namespace,runId),msg}ensureAiMessageForToolCall(namespace){let lastRunId=this.state.lastLlmRunId.get(namespace);if(lastRunId){let existing=this.state.messagesByRun.get(lastRunId);if(existing)return this.state.currentAiMessage.set(namespace,existing),existing}let msg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});return this.state.proto.messages.push(msg),this.state.currentAiMessage.set(namespace,msg),msg}accumulateV3Usage(usage){let meta3={input_tokens:usage.input_tokens,output_tokens:usage.output_tokens};usage.input_token_details&&(meta3.cache_read_input_tokens=usage.input_token_details.cache_read,meta3.cache_creation_input_tokens=usage.input_token_details.cache_creation),this.usageAccumulator.accumulate(meta3),this.state.proto.streamingUsage=this.usageAccumulator.toProto()}isTrackedTaskTool(callId){return this.state.toolCalls.get(callId)?.name==="task"}syncSubAgentExecutions(){this.subAgentTracker.hasExecutions()&&(this.state.proto.subAgentExecutions=this.subAgentTracker.getExecutions())}cancelSubAgents(){this.subAgentTracker.cancelAll(),this.syncSubAgentExecutions()}}}});function extractFilePath(input){return typeof input.path=="string"?input.path:typeof input.file_path=="string"?input.file_path:typeof input.filePath=="string"?input.filePath:typeof input.filename=="string"?input.filename:typeof input.file=="string"?input.file:null}var FILE_MODIFYING_TOOLS,StreamingSideEffects,init_streaming_side_effects=__esm({"dist/activities/execute-deep-agent/streaming-side-effects.js"(){"use strict";FILE_MODIFYING_TOOLS=new Set(["write_file","edit_file","create_file","write","edit","create","str_replace_editor"]),StreamingSideEffects=class{inputCache=new Map;inlinePublisher;writebackCoordinator;pendingPublishPromises=[];pendingWritebackPromises=[];constructor(opts){this.inlinePublisher=opts.inlinePublisher,this.writebackCoordinator=opts.writebackCoordinator}onProtocolEvent(event){if(event.method!=="tools"||!this.inlinePublisher&&!this.writebackCoordinator)return;let data=event.params.data;if(!data)return;let eventType=data.event??data.type,callId=data.tool_call_id??data.toolCallId;if(callId){if(eventType==="tool-started"){let toolName=data.tool_name??data.toolName??data.name??"",rawInput=data.input,input={};if(typeof rawInput=="string")try{input=JSON.parse(rawInput)}catch{}else rawInput&&typeof rawInput=="object"&&!Array.isArray(rawInput)&&(input=rawInput);this.inputCache.set(callId,{toolName,input});return}if(eventType==="tool-finished"){let cached3=this.inputCache.get(callId);if(this.inputCache.delete(callId),!cached3||!FILE_MODIFYING_TOOLS.has(cached3.toolName))return;let filePath=extractFilePath(cached3.input);if(!filePath)return;this.inlinePublisher&&this.pendingPublishPromises.push(this.inlinePublisher.publish(filePath)),this.writebackCoordinator&&this.pendingWritebackPromises.push(this.writebackCoordinator.onFileModified(filePath))}}}}}});async function streamExecutionV3(deps){let{agentGraph,langgraphInput,langgraphConfig,executionId,client:client2,initialStatus,streamingConfig,retryOptions,offload,stallTimeoutMs=DEFAULT_STALL_TIMEOUT_MS,heartbeatFn,isCancelledFn,gracefulStop,inlinePublisher,writebackCoordinator,approvalProvider}=deps,statusBuilder=new V3StatusBuilder(executionId,initialStatus);approvalProvider&&statusBuilder.setApprovalProvider(approvalProvider);let scheduler=new StreamingUpdateScheduler(streamingConfig),recorder=createV3EventRecorder(executionId,process.env.V3_EVENT_RECORD_DIR),abortController=new AbortController,sideEffects=new StreamingSideEffects({inlinePublisher,writebackCoordinator});sendHeartbeat(heartbeatFn,executionId,0,statusBuilder);let run=await agentGraph.streamEvents(langgraphInput,{...langgraphConfig,version:"v3",signal:abortController.signal}),eventsProcessed=0,lastActivityAt2=performance.now(),heartbeatTimer=setInterval(()=>{sendHeartbeat(heartbeatFn,executionId,eventsProcessed,statusBuilder)},HEARTBEAT_INTERVAL_MS);try{for await(let event of run){if(isCancelledFn?.())return abortController.abort("Cancelled by platform"),statusBuilder.cancelSubAgents(),handlePause(statusBuilder,eventsProcessed,sideEffects.pendingPublishPromises,sideEffects.pendingWritebackPromises);lastActivityAt2=performance.now(),recorder?.record(event,eventsProcessed);for(let normalized of normalize3(event))statusBuilder.processEvent(normalized);if(sideEffects.onProtocolEvent(event),eventsProcessed++,statusBuilder.forceNextUpdate||scheduler.shouldSendUpdate(eventsProcessed)){statusBuilder.forceNextUpdate&&statusBuilder.clearForceFlag(),statusBuilder.syncSubAgentExecutions();let signal=await persistStatus(client2,executionId,statusBuilder.currentStatus,{offload,retry:retryOptions});if(scheduler.markUpdateSent(eventsProcessed),signal===ExecutionControlSignal.STOP)if(console.warn(`[streaming-v3] STOP signal received for execution ${executionId}`),gracefulStop)gracefulStop.activate("Platform STOP signal");else return handleStop(statusBuilder,eventsProcessed,sideEffects.pendingPublishPromises,sideEffects.pendingWritebackPromises)}checkStallTimeout(lastActivityAt2,stallTimeoutMs,executionId)}}catch(err){if(isGraphRecursionError(err))return await recorder?.flush(),handleRecursionLimit(statusBuilder,eventsProcessed,sideEffects.pendingPublishPromises,sideEffects.pendingWritebackPromises);throw err}finally{clearInterval(heartbeatTimer)}if(await recorder?.flush(),eventsProcessed===0)throw new Error("Stream completed without processing any events. This may indicate a configuration error or v3 API incompatibility.");if(statusBuilder.syncSubAgentExecutions(),initialStatus.phase===ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL)return console.log(`[streaming-v3] execution=${executionId} stream ended with WAITING_FOR_APPROVAL. Not setting COMPLETED. pending_approvals computed server-side.`),{eventsProcessed,terminalStatus:slimStatus(initialStatus),pendingPublishPromises:sideEffects.pendingPublishPromises,pendingWritebackPromises:sideEffects.pendingWritebackPromises};console.log(`[streaming-v3] execution=${executionId} stream finished \u2014 processed ${eventsProcessed} events`);let runOutput=await extractRunOutput(run,executionId);return{eventsProcessed,runOutput,pendingPublishPromises:sideEffects.pendingPublishPromises,pendingWritebackPromises:sideEffects.pendingWritebackPromises}}async function extractRunOutput(run,executionId){try{let finalState=await Promise.race([run.output,timeoutPromise(RUN_OUTPUT_TIMEOUT_MS)]);if(finalState===TIMEOUT_SENTINEL){console.warn(`[streaming-v3] execution=${executionId} \u2014 run.output did not resolve within ${RUN_OUTPUT_TIMEOUT_MS}ms. Proceeding without final state.`);return}let output=finalState;return console.log(`[streaming-v3] execution=${executionId} \u2014 run.output resolved. Keys: [${Object.keys(output??{}).join(", ")}]. hasStructuredResponse=${output?.structuredResponse!==void 0}`),output}catch(err){console.warn(`[streaming-v3] execution=${executionId} \u2014 run.output rejected: ${err}`);return}}function timeoutPromise(ms){return new Promise(resolve5=>setTimeout(()=>resolve5(TIMEOUT_SENTINEL),ms))}function sendHeartbeat(fn,executionId,eventsProcessed,sb){if(fn)try{fn({executionId,eventsProcessed,messages:sb.currentStatus.messages.length,phase:sb.currentStatus.phase})}catch{}}function checkStallTimeout(lastActivityAt2,stallTimeoutMs,executionId){let elapsed2=performance.now()-lastActivityAt2;if(elapsed2>stallTimeoutMs)throw new StallTimeoutError2(`Agent stream stalled: no events received for ${Math.round(elapsed2/1e3)}s for execution ${executionId}`)}var DEFAULT_STALL_TIMEOUT_MS,HEARTBEAT_INTERVAL_MS,RUN_OUTPUT_TIMEOUT_MS,TIMEOUT_SENTINEL,init_streaming_v3=__esm({"dist/activities/execute-deep-agent/streaming-v3.js"(){"use strict";init_streaming5();init_enum_pb();init_v3_event_recorder();init_v3_protocol_normalizer();init_v3_status_builder();init_streaming_scheduler();init_status2();init_streaming_side_effects();init_streaming_terminal();DEFAULT_STALL_TIMEOUT_MS=12e4,HEARTBEAT_INTERVAL_MS=2e3,RUN_OUTPUT_TIMEOUT_MS=3e4;TIMEOUT_SENTINEL=Symbol("timeout")}});async function streamExecution(deps){return deps.streamVersion==="v3"?streamExecutionV3(deps):streamExecutionV2(deps)}async function streamExecutionV2(deps){let{agentGraph,langgraphInput,langgraphConfig,executionId,client:client2,initialStatus,streamingConfig,retryOptions,offload,stallTimeoutMs=DEFAULT_STALL_TIMEOUT_MS2,heartbeatFn,isCancelledFn,gracefulStop,inlinePublisher,writebackCoordinator,approvalProvider}=deps,statusBuilder=new StatusBuilder(executionId,initialStatus);approvalProvider&&statusBuilder.setApprovalProvider(approvalProvider);let scheduler=new StreamingUpdateScheduler(streamingConfig),recorder=createV2EventRecorder(executionId,process.env.V2_EVENT_RECORD_DIR),eventsProcessed=0,lastEventTime=performance.now(),lastHeartbeatTime=performance.now(),heartbeatIntervalMs=2e3,pendingPublishPromises=[],pendingWritebackPromises=[];try{let stream=agentGraph.streamEvents(langgraphInput,langgraphConfig,{version:"v2"});for await(let event of stream){if(isCancelledFn?.())return handlePause(statusBuilder,eventsProcessed,pendingPublishPromises,pendingWritebackPromises);if(lastEventTime=performance.now(),recorder?.record(event,eventsProcessed),statusBuilder.processEvent(event),eventsProcessed++,event.event==="on_tool_end"&&(inlinePublisher||writebackCoordinator)){let filePath=extractFilePathFromToolEnd(event);filePath&&(inlinePublisher&&pendingPublishPromises.push(inlinePublisher.publish(filePath)),writebackCoordinator&&pendingWritebackPromises.push(writebackCoordinator.onFileModified(filePath)))}let now=performance.now();if(heartbeatFn&&now-lastHeartbeatTime>=heartbeatIntervalMs&&(sendHeartbeat2(heartbeatFn,executionId,eventsProcessed,statusBuilder),lastHeartbeatTime=now),statusBuilder.forceNextUpdate||scheduler.shouldSendUpdate(eventsProcessed)){statusBuilder.forceNextUpdate&&statusBuilder.clearForceFlag();let signal=await persistStatus(client2,executionId,statusBuilder.currentStatus,{offload,retry:retryOptions});if(scheduler.markUpdateSent(eventsProcessed),signal===ExecutionControlSignal.STOP)if(console.warn(`[streaming] STOP signal received for execution ${executionId}`),gracefulStop)gracefulStop.activate("Platform STOP signal");else return handleStop(statusBuilder,eventsProcessed,pendingPublishPromises,pendingWritebackPromises)}checkStallTimeout2(lastEventTime,stallTimeoutMs,executionId)}}catch(err){if(isGraphRecursionError(err))return handleRecursionLimit(statusBuilder,eventsProcessed,pendingPublishPromises,pendingWritebackPromises);throw err}if(await recorder?.flush(),eventsProcessed===0)throw new Error("Stream completed without processing any events. This may indicate a configuration error.");return initialStatus.phase===ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL?(console.log(`[streaming] execution=${executionId} stream ended with WAITING_FOR_APPROVAL. Not setting COMPLETED. pending_approvals computed server-side.`),{eventsProcessed,terminalStatus:slimStatus(initialStatus),pendingPublishPromises,pendingWritebackPromises}):(console.log(`[streaming] execution=${executionId} stream finished \u2014 processed ${eventsProcessed} events`),{eventsProcessed,pendingPublishPromises,pendingWritebackPromises})}function sendHeartbeat2(fn,executionId,eventsProcessed,sb){try{fn({executionId,eventsProcessed,messages:sb.currentStatus.messages.length,phase:sb.currentStatus.phase})}catch(err){console.warn(`[streaming] Heartbeat failed for ${executionId}:`,err)}}function checkStallTimeout2(lastEventTime,stallTimeoutMs,executionId){let elapsed2=performance.now()-lastEventTime;if(elapsed2>stallTimeoutMs)throw new StallTimeoutError2(`Agent stream stalled: no events received for ${Math.round(elapsed2/1e3)}s for execution ${executionId}`)}function extractFilePathFromToolEnd(event){let toolName=event.name??"";if(!FILE_MODIFYING_TOOLS2.has(toolName))return null;let input=event.data?.input;return input?typeof input.path=="string"?input.path:typeof input.file_path=="string"?input.file_path:typeof input.filename=="string"?input.filename:typeof input.file=="string"?input.file:null:null}var DEFAULT_STALL_TIMEOUT_MS2,FILE_MODIFYING_TOOLS2,StallTimeoutError2,init_streaming5=__esm({"dist/activities/execute-deep-agent/streaming.js"(){"use strict";init_enum_pb();init_status_builder();init_streaming_terminal();init_streaming_scheduler();init_status2();init_event_recorder();init_streaming_v3();DEFAULT_STALL_TIMEOUT_MS2=12e4;FILE_MODIFYING_TOOLS2=new Set(["write_file","edit_file","create_file","write","edit","create","str_replace_editor"]);StallTimeoutError2=class extends Error{constructor(message){super(message),this.name="StallTimeoutError"}}}});function normalizePath(path6){return path6.replace(/^\/+/,"")}function sha2563(content){return(0,import_node_crypto8.createHash)("sha256").update(content).digest("hex")}function guessContentType(filename){let ext=filename.slice(filename.lastIndexOf(".")).toLowerCase();return CONTENT_TYPE_MAP[ext]??"application/octet-stream"}var import_node_crypto8,import_node_path20,InlinePublisher,CONTENT_TYPE_MAP,init_inline_publisher=__esm({"dist/activities/execute-deep-agent/inline-publisher.js"(){"use strict";import_node_crypto8=require("node:crypto"),import_node_path20=require("node:path");init_esm4();init_artifact_pb();init_enum_pb();init_status2();InlinePublisher=class{workspaceBackend;artifactStorage;statusWriter;executionId;published=new Map;constructor(opts){this.workspaceBackend=opts.workspaceBackend,this.artifactStorage=opts.artifactStorage,this.statusWriter=opts.statusWriter,this.executionId=opts.executionId}get publishedPaths(){return new Set(this.published.keys())}async publish(path6){try{let sandboxPath=normalizePath(path6),content=await this.workspaceBackend.readFile(sandboxPath),contentBuffer=Buffer.from(content,"utf-8"),contentHash=sha2563(contentBuffer);if(this.published.get(sandboxPath)===contentHash)return;let fileName=(0,import_node_path20.basename)(sandboxPath),storageKey=`artifacts/${this.executionId}/${fileName}`;await this.artifactStorage.upload(storageKey,contentBuffer,guessContentType(fileName));let downloadUrl=await this.artifactStorage.getDownloadUrl(storageKey),artifact=create(ExecutionArtifactSchema,{name:fileName,sandboxPath,kind:ExecutionArtifactKind.FILE,sizeBytes:BigInt(contentBuffer.length),storageKey,downloadUrl,createdAt:utcTimestamp(),contentHash});this.statusWriter.addArtifact(artifact),this.published.set(sandboxPath,contentHash),console.log(`[InlinePublisher] execution=${this.executionId} \u2014 published '${sandboxPath}' (${contentBuffer.length} bytes, hash=${contentHash.slice(0,12)})`)}catch(err){console.warn(`[InlinePublisher] execution=${this.executionId} \u2014 failed to publish '${path6}' (non-fatal): ${err}`)}}};CONTENT_TYPE_MAP={".txt":"text/plain",".md":"text/markdown",".json":"application/json",".js":"application/javascript",".ts":"application/typescript",".py":"text/x-python",".html":"text/html",".css":"text/css",".xml":"text/xml",".yaml":"text/yaml",".yml":"text/yaml",".csv":"text/csv",".pdf":"application/pdf",".zip":"application/zip",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml"}}});function parseGithubRepo(repoUrl){let httpsMatch=repoUrl.match(/github\.com[/:]([^/]+)\/([^/.]+?)(?:\.git)?$/);if(httpsMatch)return{owner:httpsMatch[1],repo:httpsMatch[2]};throw new Error(`Cannot parse GitHub owner/repo from URL: ${repoUrl}`)}function extractGithubToken(repoUrl){let match=repoUrl.match(/https?:\/\/([^@]+)@github\.com/);if(match)return match[1];let envToken=process.env.GITHUB_TOKEN;if(envToken)return envToken;throw new Error("Cannot extract GitHub token from repo URL and GITHUB_TOKEN is not set")}var WRITE_BACK_ENABLED_MODES,WriteBackCoordinator,init_writeback_coordinator=__esm({"dist/activities/execute-deep-agent/writeback-coordinator.js"(){"use strict";init_esm4();init_writeback_pb();init_writeback_pb();init_enum_pb4();init_types6();WRITE_BACK_ENABLED_MODES=new Set([GitWriteBackMode.GIT_WRITE_BACK_MODE_UNSPECIFIED,GitWriteBackMode.GIT_WRITE_BACK_BRANCH_AND_PR]),WriteBackCoordinator=class{statusWriter;executionId;workspaceBackend;shortId;branchName;eligible=new Map;state=new Map;locks=new Map;constructor(opts){this.statusWriter=opts.statusWriter,this.executionId=opts.executionId,this.workspaceBackend=opts.workspaceBackend,this.shortId=opts.executionId.slice(0,8),this.branchName=`stigmer/${this.shortId}`,this.initEligibleEntries(opts.provisionResults,opts.workspaceEntries)}get hasEligibleEntries(){return this.eligible.size>0}async onFileModified(path6){try{let entryName=this.resolveEntry(path6);if(!entryName)return;await this.withLock(entryName,()=>this.incrementalWriteBack(entryName))}catch(err){console.warn(`[WriteBack] execution=${this.executionId} \u2014 onFileModified error for '${path6}': ${err}`)}}async finalize(){for(let entryName of this.eligible.keys())try{await this.withLock(entryName,()=>this.incrementalWriteBack(entryName))}catch(err){console.warn(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 finalize error: ${err}`)}}initEligibleEntries(provisionResults,workspaceEntries){let modeMap=new Map;for(let entry of workspaceEntries){let source=entry.source;source?.source.case==="gitRepo"&&modeMap.set(entry.name,source.source.value.writeBackMode)}for(let pr of provisionResults){if(pr.sourceType!==SourceType.GIT_REPO||!pr.gitMetadata||!pr.gitMetadata.gitCredentialsConfigured)continue;let mode=modeMap.get(pr.entryName)??GitWriteBackMode.GIT_WRITE_BACK_MODE_UNSPECIFIED;WRITE_BACK_ENABLED_MODES.has(mode)&&(this.eligible.set(pr.entryName,{provisionResult:pr,baseBranch:pr.gitMetadata.branch,rootDir:pr.rootDir,entryName:pr.entryName}),this.state.set(pr.entryName,{branchCreated:!1,prCreated:!1,prUrl:"",prNumber:0,commitCount:0,lastCommitSha:"",githubToken:"",githubOwner:"",githubRepo:""}))}this.eligible.size>0&&console.log(`[WriteBack] execution=${this.executionId} \u2014 coordinator initialized with ${this.eligible.size} eligible workspace(s): ${[...this.eligible.keys()].join(", ")}`)}resolveEntry(path6){if(this.eligible.size===0)return null;if(this.eligible.size===1)return this.eligible.keys().next().value;let normalized=path6.replace(/^\/+/,"");for(let entryName of this.eligible.keys())if(normalized.startsWith(entryName+"/")||normalized===entryName)return entryName;return null}async incrementalWriteBack(entryName){let entry=this.eligible.get(entryName),entryState=this.state.get(entryName),rootDir=entry.rootDir,exec2=async cmd=>this.workspaceBackend.execute(`cd ${rootDir} && ${cmd}`),mutationStarted=!1;try{if(!await this.hasChanges(exec2))return;mutationStarted=!0,entryState.branchCreated||await this.createBranch(entryName,entryState,exec2);let commitMsg=`agent changes (${entryState.commitCount+1})`;await this.commitAndPush(entryName,entryState,exec2,commitMsg),entryState.prCreated||await this.createPr(entryName,entryState,entry,exec2),await this.updateStatus(entryName,entryState,entry,exec2)}catch(err){if(console.warn(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 incremental error: ${err}`),!mutationStarted)return;let wb=create(WorkspaceWriteBackSchema,{workspaceEntryName:entryName,baseBranch:entry.baseBranch,branchName:entryState.branchCreated?this.branchName:"",phase:WorkspaceWriteBackPhase.WORKSPACE_WRITE_BACK_FAILED,error:String(err)});entryState.prCreated&&(wb.pullRequestUrl=entryState.prUrl,wb.pullRequestNumber=entryState.prNumber),this.statusWriter.addWriteBack(wb)}}async hasChanges(exec2){let diff=await exec2("git diff --stat").catch(()=>""),staged=await exec2("git diff --cached --stat").catch(()=>"");return diff.trim()||staged.trim()?!0:(await exec2("git ls-files --others --exclude-standard").catch(()=>"")).trim().length>0}async createBranch(entryName,entryState,exec2){await exec2(`git checkout -b ${this.branchName}`),entryState.branchCreated=!0,console.log(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 created branch ${this.branchName}`)}async commitAndPush(entryName,entryState,exec2,commitMsg){await exec2("git add -A"),await exec2(`git commit -m "${commitMsg}"`),entryState.commitCount++;let shaOutput=await exec2("git rev-parse HEAD");entryState.lastCommitSha=shaOutput.trim(),entryState.commitCount===1?await exec2(`git push -u origin ${this.branchName}`):await exec2("git push"),console.log(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 commit #${entryState.commitCount} pushed (sha=${entryState.lastCommitSha.slice(0,12)})`)}async createPr(entryName,entryState,entry,_exec){let meta3=entry.provisionResult.gitMetadata,{owner,repo}=parseGithubRepo(meta3.repoUrl);entryState.githubToken||(entryState.githubToken=extractGithubToken(meta3.repoUrl),entryState.githubOwner=owner,entryState.githubRepo=repo);let prTitle=`Agent changes (${this.shortId})`,prBody=`Automated pull request from Stigmer agent execution.
2072
2072
 
2073
2073
  **Execution:** \`${this.executionId}\`
2074
2074
  **Workspace:** \`${entryName}\`
@@ -2191,7 +2191,7 @@ CRITICAL OUTPUT REQUIREMENT:
2191
2191
  Your final response MUST be a single valid JSON object (no markdown, no commentary, no code fences) that matches this schema:
2192
2192
  ${schemaStr}
2193
2193
 
2194
- Respond with ONLY the JSON object. Nothing else.`}let promptChars=effectivePrompt.length,promptEstimatedTokens=Math.ceil(promptChars/4);console.log(`ExecuteCursor prompt built: execution=${executionId}, chars=${promptChars}, estimatedTokens=${promptEstimatedTokens}, resolution=${resolution.reason}, mode=${resolution.mode}`),await ensureLoaded();let usageAccumulator=new UsageAccumulator(validatedModel),{startCursorTurnSpan:startCursorTurnSpan2}=await Promise.resolve().then(()=>(init_otel(),otel_exports)),turnSpan=await startCursorTurnSpan2({model:validatedModel,mode:agentMode,sessionId:sessionId??""});status.phase=ExecutionPhase.EXECUTION_IN_PROGRESS;let deltaEnricher=new DeltaEnricher,todoTracker=new TodoTracker(status.todos),eventRecorder=createCursorEventRecorder(executionId),platformStopSignaled=!1,firstTurnAttributionLogged=!1,streamErrorMessage,alreadyRetriedWithFreshAgent=!1,lastToolName,taskQueue=import_activity14.Context.current().info.taskQueue,shutdownSignal=getShutdownSignalForQueue(taskQueue);periodicHeartbeat=startHeartbeat(3e4,()=>({phase:"cursor_streaming",execution:executionId}),{shutdownSignal});try{(0,import_node_events.setMaxListeners)(25,import_activity14.Context.current().cancellationSignal)}catch{}let run=await resolution.agent.send(effectivePrompt,{onDelta:({update})=>{if(stallWatchdog?.recordActivity(),update.type==="turn-ended"&&update.usage&&(usageAccumulator.addTurn(update.usage),!firstTurnAttributionLogged)){firstTurnAttributionLogged=!0;let sdkInputTokens=update.usage.inputTokens??0,cursorOverhead=Math.max(0,sdkInputTokens-promptEstimatedTokens);console.log(`ExecuteCursor context attribution (first turn): execution=${executionId}, sdkInputTokens=${sdkInputTokens}, stigmerPreamble=${promptEstimatedTokens}, cursorOverhead=${cursorOverhead} (estimated)`)}deltaEnricher.processDelta(update);try{(0,import_activity14.heartbeat)()}catch(hbErr){if(hbErr instanceof import_activity14.CancelledFailure){pauseDetected=!0;return}throw hbErr}}});stallWatchdog=startStallWatchdog(config4.cursorStreamStallTimeoutMs,idleMs=>{stallDetected=!0,stallError=new StallTimeoutError(idleMs,lastToolName?`last tool: ${lastToolName}`:void 0),console.warn(`ExecuteCursor stall detected: execution=${executionId}, idleMs=${idleMs}, lastTool=${lastToolName??"none"}`),run.supports?.("cancel")&&run.cancel().catch(cancelErr=>{console.warn(`ExecuteCursor run.cancel() after stall failed (non-fatal): execution=${executionId}, error=${cancelErr instanceof Error?cancelErr.message:cancelErr}`)})});let accumulator=new MessageAccumulator(status.messages,{mergedPolicies}),eventCount=0;try{for await(let event of run.stream()){if(pauseDetected||import_activity14.Context.current().cancellationSignal.aborted){pauseDetected=!0;break}if(stallDetected)break;if(stallWatchdog.recordActivity(),event.type==="tool_call"&&typeof event.name=="string"&&(lastToolName=event.name),eventRecorder?.record(event,eventCount),accumulator.processEvent(event),todoTracker.processEvent(event),event.type==="tool_call"&&event.name==="task"&&accumulator.trackSubAgentExecution(event),deltaEnricher.applyEnrichments(status.messages),eventCount++,event.type==="status"){console.log(`ExecuteCursor stream status: execution=${executionId}, status=${JSON.stringify(event)}`);let statusEvent=event;statusEvent.status==="ERROR"&&statusEvent.message&&(streamErrorMessage=statusEvent.message)}let shouldPersist=eventCount%20===0||deltaEnricher.isDirty||todoTracker.isDirty||accumulator.subAgentDirty;if(usageAccumulator.hasTurns&&(status.streamingUsage=create(StreamingUsageSummarySchema,usageAccumulator.snapshot())),shouldPersist){status.subAgentExecutions=accumulator.subAgentExecutions;let signal=await persist(status);deltaEnricher.markPersisted(),todoTracker.markPersisted(),accumulator.markSubAgentPersisted(),(0,import_activity14.heartbeat)(),signal===ExecutionControlSignal.STOP&&(platformStopSignaled=!0,console.warn(`ExecuteCursor platform stop signal received: execution=${executionId}`))}if(platformStopSignaled){console.log(`ExecuteCursor stopping stream due to platform stop signal: execution=${executionId}`);break}}}catch(streamErr){if(!stallDetected)throw streamErr;console.warn(`ExecuteCursor stream ended via stall cancel: execution=${executionId}`)}periodicHeartbeat.stop(),stallWatchdog.stop();let isShutdown=periodicHeartbeat.workerShutdown||(shutdownSignal?.aborted??!1);isShutdown?pauseDetected=!1:periodicHeartbeat.cancelled&&(pauseDetected=!0),workerShutdownDetected=isShutdown,accumulator.finalize(),deltaEnricher.finalize(status.messages),(pauseDetected||workerShutdownDetected||stallDetected||import_activity14.Context.current().cancellationSignal.aborted)&&accumulator.cancelInProgressSubAgents(),status.subAgentExecutions=accumulator.subAgentExecutions,await eventRecorder?.flush(),usageAccumulator.hasTurns&&(status.streamingUsage=create(StreamingUsageSummarySchema,usageAccumulator.snapshot())),console.log(`ExecuteCursor stream ended: execution=${executionId}, events=${eventCount}, messages=${status.messages.length}, subAgents=${status.subAgentExecutions.length}`),await persist(status),(0,import_activity14.heartbeat)();let usageSnapshot=usageAccumulator.snapshot();turnSpan.setTokens(Number(usageSnapshot.inputTokens),Number(usageSnapshot.outputTokens)),turnSpan.end();try{let{recordTurnMetrics:recordTurnMetrics2}=await Promise.resolve().then(()=>(init_otel(),otel_exports)),turnDurationMs=Date.now()-(status.startedAt?new Date(status.startedAt).getTime():Date.now());await recordTurnMetrics2({durationMs:turnDurationMs,inputTokens:Number(usageSnapshot.inputTokens),outputTokens:Number(usageSnapshot.outputTokens),model:validatedModel,mode:agentMode})}catch{}if(stallDetected){let err=stallError??new StallTimeoutError(config4.cursorStreamStallTimeoutMs);return status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatStallFailure(err),status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Execution failed: the agent made no progress for too long and was stopped (${err.message}). You can retry or resume.`,timestamp:utcTimestamp()})),await persist(status),console.warn(`ExecuteCursor stalled: execution=${executionId}, events=${eventCount}, error=${status.error}`),slimStatus(status)}if(workerShutdownDetected)throw status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: runner worker was shut down. Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the runner worker was shut down while the agent was still running. You can retry or resume.",timestamp:utcTimestamp()})),await persist(status),console.log(`ExecuteCursor interrupted (worker shutdown): execution=${executionId}, events=${eventCount}`),new import_activity14.CancelledFailure("Activity cancelled (worker shutdown, not user pause)");if(pauseDetected)throw status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue.",timestamp:utcTimestamp()})),await persist(status),console.log(`ExecuteCursor paused: execution=${executionId}, events=${eventCount}`),new import_activity14.CancelledFailure("Activity paused by orchestrator");if(import_activity14.Context.current().cancellationSignal.aborted)throw status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: agent was unresponsive (heartbeat timeout). Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the agent was unresponsive for too long. You can retry or resume.",timestamp:utcTimestamp()})),await persist(status),console.log(`ExecuteCursor interrupted (infrastructure cancel): execution=${executionId}, events=${eventCount}`),new import_activity14.CancelledFailure("Activity cancelled (heartbeat timeout, not user pause)");if(platformStopSignaled){status.phase=ExecutionPhase.EXECUTION_COMPLETED,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution stopped by the platform.",timestamp:utcTimestamp()})),await persist(status);try{resolution.agent.close()}catch{}return console.log(`ExecuteCursor completed (platform stop): execution=${executionId}`),slimStatus(status)}let deniedLedger=await readDenialLedger(hitlDir??""),deniedToolCalls=reconcileDeniedToolCalls(status.messages,deniedLedger,mergedPolicies);if(deniedToolCalls.length>0)return status.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL,await persist(status),console.log(`ExecuteCursor returning WAITING_FOR_APPROVAL: ${deniedToolCalls.length} tools pending`),slimStatus(status);let result=await run.wait(),sdkResolvedModel=result.model?.id||void 0;switch(console.log(`ExecuteCursor run.wait() result: execution=${executionId}, result=${JSON.stringify(result)}`),sdkResolvedModel&&sdkResolvedModel!==validatedModel&&console.log(`ExecuteCursor model divergence: execution=${executionId}, requested=${validatedModel}, sdkResolved=${sdkResolvedModel}`),status.completedAt=utcTimestamp(),result.status){case"finished":status.phase=ExecutionPhase.EXECUTION_COMPLETED;break;case"error":{let resultAny=result,sdkError=result.result??resultAny.error??resultAny.message??resultAny.reason,sdkErrorStr=sdkError?String(sdkError):void 0,conversationErrorText=await introspectConversation(run,executionId),capturedRejection=getCapturedRejection(executionId);capturedRejection&&clearCapturedRejection(executionId);let classified=synthesizeError({sdkResultFields:sdkErrorStr,streamErrorMessage,capturedRejection,conversationErrorText,isResumedHandle:resolution.reason==="resumed_successfully",fallbackContext:{model:validatedModel,mode:agentMode,agentId:resolution.agentId},durationMs:result.durationMs,messageCount:status.messages.length});if(console.error(`ExecuteCursor agent error: execution=${executionId}, classified=${JSON.stringify(classified)}, rawResult=${JSON.stringify(result)}`),shouldRetryWithFreshAgent(classified)&&resolution.reason==="resumed_successfully"&&!alreadyRetriedWithFreshAgent){alreadyRetriedWithFreshAgent=!0,console.warn(`ExecuteCursor poisoned-handle recovery: execution=${executionId}, disposing agent ${resolution.agentId} and creating fresh agent`);try{resolution.agent.close()}catch{}let freshAgent=agentMode==="cloud"?await createCloudAgent(createOptions):await createAgent(createOptions),freshPrompt=buildPrompt({resolution:{...resolution,agent:freshAgent,agentId:freshAgent.agentId,isNew:!0,resumed:!1,reason:"created_after_resume_failure",resumeFailureDetail:`poisoned-handle recovery: ${classified.message}`},approvalDecisions,instructions:blueprint.instructions,userMessage:spec.message,skills:skillMetadata,subAgents:blueprint.subAgents,workspaceDirs:blueprint.workspaceDirs,workspaceFileRefs:spec.workspaceFileRefs??[],attachmentPaths,pendingApprovals:adjudicatedApprovals,interactionMode});console.log(`ExecuteCursor retry with fresh agent: execution=${executionId}, newAgentId=${freshAgent.agentId}`);try{blueprint.sessionSpec.harnessStateId=freshAgent.agentId,blueprint.session.metadata&&(blueprint.session.metadata.slug=""),await client2.updateSession(blueprint.session)}catch(updateErr){console.warn("Failed to update session with fresh agentId (non-fatal):",updateErr)}let retryWatchdog,retryRun=await freshAgent.send(freshPrompt,{onDelta:({update})=>{retryWatchdog?.recordActivity(),update.type==="turn-ended"&&update.usage&&usageAccumulator.addTurn(update.usage),deltaEnricher.processDelta(update);try{(0,import_activity14.heartbeat)()}catch{}}});retryWatchdog=startStallWatchdog(config4.cursorStreamStallTimeoutMs,idleMs=>{console.warn(`ExecuteCursor retry stall detected: execution=${executionId}, idleMs=${idleMs}`),retryRun.supports?.("cancel")&&retryRun.cancel().catch(()=>{})}),streamErrorMessage=void 0;try{for await(let retryEvent of retryRun.stream()){if(import_activity14.Context.current().cancellationSignal.aborted)break;if(retryWatchdog.recordActivity(),accumulator.processEvent(retryEvent),retryEvent.type==="status"){let retryStatusEvent=retryEvent;retryStatusEvent.status==="ERROR"&&retryStatusEvent.message&&(streamErrorMessage=retryStatusEvent.message)}(0,import_activity14.heartbeat)()}}finally{retryWatchdog.stop()}let retryResult=await retryRun.wait();if(console.log(`ExecuteCursor retry run.wait(): execution=${executionId}, retryResult=${JSON.stringify(retryResult)}`),retryResult.status==="finished"){status.phase=ExecutionPhase.EXECUTION_COMPLETED,console.log(`ExecuteCursor poisoned-handle recovery SUCCEEDED: execution=${executionId}`);break}if(retryResult.status==="cancelled"){status.phase=ExecutionPhase.EXECUTION_CANCELLED;break}let retryRejection=getCapturedRejection(executionId);retryRejection&&clearCapturedRejection(executionId);let retryConversationErrorText=await introspectConversation(retryRun,executionId),retryClassified=synthesizeError({sdkResultFields:retryResult.result?String(retryResult.result):void 0,streamErrorMessage,capturedRejection:retryRejection,conversationErrorText:retryConversationErrorText,isResumedHandle:!1,fallbackContext:{model:validatedModel,mode:agentMode,agentId:freshAgent.agentId}});status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatClassifiedError(retryClassified),console.error(`ExecuteCursor poisoned-handle recovery FAILED: execution=${executionId}, retryError=${status.error}`);break}if(classified.category==="network"&&classified.retryable&&resolution.reason!=="resumed_successfully"&&!alreadyRetriedWithFreshAgent){alreadyRetriedWithFreshAgent=!0,console.warn(`ExecuteCursor transport-timeout recovery: execution=${executionId}, resetting proxy sessions and retrying with fresh agent`);try{resolution.agent.close()}catch{}closeProxySessions();let freshAgent=agentMode==="cloud"?await createCloudAgent(createOptions):await createAgent(createOptions);try{blueprint.sessionSpec.harnessStateId=freshAgent.agentId,blueprint.session.metadata&&(blueprint.session.metadata.slug=""),await client2.updateSession(blueprint.session)}catch(updateErr){console.warn("Failed to update session with fresh agentId (non-fatal):",updateErr)}let retryWatchdog,retryRun=await freshAgent.send(effectivePrompt,{onDelta:({update})=>{retryWatchdog?.recordActivity(),update.type==="turn-ended"&&update.usage&&usageAccumulator.addTurn(update.usage),deltaEnricher.processDelta(update);try{(0,import_activity14.heartbeat)()}catch{}}});retryWatchdog=startStallWatchdog(config4.cursorStreamStallTimeoutMs,idleMs=>{console.warn(`ExecuteCursor retry stall detected: execution=${executionId}, idleMs=${idleMs}`),retryRun.supports?.("cancel")&&retryRun.cancel().catch(()=>{})}),streamErrorMessage=void 0;try{for await(let retryEvent of retryRun.stream()){if(import_activity14.Context.current().cancellationSignal.aborted)break;if(retryWatchdog.recordActivity(),accumulator.processEvent(retryEvent),retryEvent.type==="status"){let retryStatusEvent=retryEvent;retryStatusEvent.status==="ERROR"&&retryStatusEvent.message&&(streamErrorMessage=retryStatusEvent.message)}(0,import_activity14.heartbeat)()}}finally{retryWatchdog.stop()}if((await retryRun.wait()).status==="finished"){status.phase=ExecutionPhase.EXECUTION_COMPLETED,resolution={...resolution,agent:freshAgent,agentId:freshAgent.agentId,isNew:!0};break}status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=`Transport recovery failed: ${formatClassifiedError(classified)}`;break}status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatClassifiedError(classified);break}case"cancelled":status.phase=ExecutionPhase.EXECUTION_CANCELLED;break;default:status.phase=ExecutionPhase.EXECUTION_COMPLETED}let structuredOutput,finalText;if(status.phase===ExecutionPhase.EXECUTION_COMPLETED){if(finalText=[...status.messages].reverse().find(m=>m.type===MessageType.MESSAGE_AI)?.content,structuredOutputSchema&&finalText){let{extractJsonFromText:extractJsonFromText2}=await Promise.resolve().then(()=>(init_extract_json(),extract_json_exports));if(structuredOutput=extractJsonFromText2(finalText),structuredOutput!==void 0&&console.log(`ExecuteCursor structured output extracted (text): execution=${executionId}, finalTextLength=${finalText.length}`),structuredOutput===void 0){console.log(`ExecuteCursor text extraction failed, trying LLM extraction: execution=${executionId}, finalTextLength=${finalText.length}`);try{structuredOutput=await extractStructuredOutput(finalText,structuredOutputSchema,config4,requestedModel),structuredOutput!==void 0&&console.log(`ExecuteCursor structured output extracted (LLM): execution=${executionId}`)}catch(extractErr){let errMsg=extractErr instanceof Error?extractErr.message:String(extractErr);console.error(`ExecuteCursor structured output extraction FAILED: execution=${executionId}, requestedModel=${requestedModel}, finalTextLength=${finalText.length}, error=${errMsg}`)}}}if(structuredOutput!==void 0&&(status.structuredOutput=structuredOutput),interactionMode===InteractionMode.PLAN&&finalText&&artifactStorage)try{await publishPlanArtifact({status,executionId,planText:finalText,artifactStorage})}catch(err){console.warn(`ExecuteCursor plan artifact publish skipped (non-fatal): execution=${executionId}, error=${err}`)}}await persist(status),console.log(`ExecuteCursor completed: execution=${executionId}, phase=${ExecutionPhase[status.phase]}, hasStructuredOutput=${structuredOutput!==void 0}`+(status.error?`, error=${status.error}`:""));try{resolution.agent.close()}catch{}let slim=slimStatus(status);return finalText!==void 0&&(slim.final_text=finalText),structuredOutput!==void 0&&(slim.structured=structuredOutput),slim}catch(err){if(periodicHeartbeat?.stop(),err instanceof import_activity14.CancelledFailure)throw workerShutdownDetected?(console.log(`ExecuteCursor cancelled (worker shutdown) for execution ${executionId}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: runner worker was shut down. Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the runner worker was shut down while the agent was still running. You can retry or resume.",timestamp:utcTimestamp()}))):pauseDetected?(console.log(`ExecuteCursor cancelled (pause) for execution ${executionId}`),status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue.",timestamp:utcTimestamp()}))):(console.log(`ExecuteCursor cancelled (infrastructure) for execution ${executionId}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: agent was unresponsive (heartbeat timeout). Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the agent was unresponsive for too long. You can retry or resume.",timestamp:utcTimestamp()}))),cancelInProgressSubAgentProtos(status.subAgentExecutions),await persist(status).catch(()=>{}),err;if(pauseDetected){let errDetail=err instanceof Error?err.message:String(err);throw console.log(`ExecuteCursor error during pause (treating as pause): execution=${executionId}, error=${errDetail}`),status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue.",timestamp:utcTimestamp()})),cancelInProgressSubAgentProtos(status.subAgentExecutions),await persist(status).catch(()=>{}),new import_activity14.CancelledFailure("Activity paused by orchestrator (error during pause)")}if(import_activity14.Context.current().cancellationSignal.aborted){let errDetail=err instanceof Error?err.message:String(err);throw console.log(`ExecuteCursor error during infrastructure cancel: execution=${executionId}, error=${errDetail}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=`Execution interrupted: ${errDetail}`,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the agent was unresponsive for too long. You can retry or resume.",timestamp:utcTimestamp()})),cancelInProgressSubAgentProtos(status.subAgentExecutions),await persist(status).catch(()=>{}),new import_activity14.CancelledFailure("Activity cancelled (infrastructure, not user pause)")}let{CursorSdkError}=await import("@cursor/sdk");if(err instanceof CursorSdkError){let sdkErrorJson=err.toJSON();console.error(`ExecuteCursor SDK error: execution=${executionId}, sdkError=${JSON.stringify(sdkErrorJson)}`);let classified=synthesizeError({sdkError:{code:err.code,status:err.status,message:err.message},sdkResultFields:void 0,streamErrorMessage:void 0,capturedRejection:getCapturedRejection(executionId),isResumedHandle:!1,fallbackContext:errorContext});clearCapturedRejection(executionId),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatClassifiedError(classified),status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Internal system error occurred. Please contact support if this issue persists.",timestamp:utcTimestamp()}),create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Error details: ${status.error}`,timestamp:utcTimestamp()}));try{await persist(status)}catch(persistErr){console.error("Failed to persist error status (best-effort):",persistErr)}return slimStatus(status)}let errMsg=err instanceof Error?err.message:String(err),errType=err instanceof Error?err.constructor.name:"Unknown";console.error(`ExecuteCursor failed: execution=${executionId}, [${errType}] ${errMsg}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=`Execution failed: [${errType}] ${errMsg}`,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Internal system error occurred. Please contact support if this issue persists.",timestamp:utcTimestamp()}),create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Error details: [${errType}] ${errMsg}`,timestamp:utcTimestamp()}));try{await persist(status)}catch(persistErr){console.error("Failed to persist error status (best-effort):",persistErr)}return slimStatus(status)}finally{if(stallWatchdog?.stop(),hitlCleanup)try{await hitlCleanup()}catch(cleanupErr){console.warn(`ExecuteCursor HITL gate teardown failed (non-fatal): execution=${executionId}, error=${cleanupErr instanceof Error?cleanupErr.message:cleanupErr}`)}}}async function extractStructuredOutput(agentResponse,schema2,config4,primaryModel){let{ChatOpenAI:ChatOpenAI3}=await Promise.resolve().then(()=>(init_dist10(),dist_exports3)),{ChatAnthropic:ChatAnthropic2}=await Promise.resolve().then(()=>(init_dist9(),dist_exports2)),{inferProvider:inferProvider3,resolveProxyBaseUrl:resolveProxyBaseUrl2,buildProxyHeaders:buildProxyHeaders2}=await Promise.resolve().then(()=>(init_llm_proxy(),llm_proxy_exports)),{getEconomyModel:getEconomyModel2}=await Promise.resolve().then(()=>(init_model_registry(),model_registry_exports)),extractionModel=await getEconomyModel2(primaryModel),provider=inferProvider3(extractionModel),proxyEndpoint=config4.proxyEndpoint??config4.stigmerBackendEndpoint,baseUrl=resolveProxyBaseUrl2(proxyEndpoint,provider),headers=config4.stigmerToken?buildProxyHeaders2(config4.stigmerToken,{}):{},apiKey=provider==="openai"?config4.stigmerToken??process.env.OPENAI_API_KEY??"proxy-managed":config4.stigmerToken??process.env.ANTHROPIC_API_KEY??"proxy-managed",llm=provider==="openai"?new ChatOpenAI3({model:extractionModel,apiKey,temperature:0,maxTokens:4096,configuration:{baseURL:baseUrl,defaultHeaders:headers}}):new ChatAnthropic2({model:extractionModel,apiKey,temperature:0,maxTokens:4096,clientOptions:{baseURL:baseUrl,defaultHeaders:headers}}),zodSchema=jsonSchemaToZod(schema2);return await llm.withStructuredOutput(zodSchema).invoke([{role:"system",content:"Extract the structured data from the agent's response. Return only the data that matches the schema."},{role:"user",content:agentResponse}])??null}function buildPrompt(input){let{resolution,approvalDecisions,instructions,userMessage,skills,subAgents,workspaceDirs,workspaceFileRefs,attachmentPaths,interactionMode}=input;return approvalDecisions!==void 0&&approvalDecisions.size>0?buildReinvocationPrompt(input.pendingApprovals,approvalDecisions):resolution.reason==="resumed_successfully"?userMessage:buildEnhancedPrompt({instructions,userMessage,skills,subAgents,workspaceDirs,workspaceFileRefs,attachmentPaths,interactionMode})}async function introspectConversation(run,executionId){try{if(!run.supports("conversation")){console.log(`ExecuteCursor conversation introspection unsupported: execution=${executionId}, reason=${run.unsupportedReason("conversation")??"n/a"}`);return}let turns=await run.conversation(),raw=JSON.stringify(turns),bounded=raw.length>8e3?`${raw.slice(0,8e3)}\u2026(truncated ${raw.length} chars)`:raw;return console.error(`ExecuteCursor conversation introspection: execution=${executionId}, turns=${turns.length}, raw=${bounded}`),extractConversationErrorText(turns)}catch(introspectErr){console.warn(`ExecuteCursor conversation introspection failed (non-fatal): execution=${executionId}, error=${introspectErr instanceof Error?introspectErr.message:String(introspectErr)}`);return}}function extractConversationErrorText(turns){if(!turns||turns.length===0)return;let collected=[],visit=(node,depth)=>{if(node==null||depth>6||typeof node!="object")return;if(Array.isArray(node)){for(let item of node)visit(item,depth+1);return}let obj=node;obj.status==="error"&&obj.error!=null&&collected.push(typeof obj.error=="string"?obj.error:JSON.stringify(obj.error));for(let[key,value]of Object.entries(obj))(key==="text"||key==="message"||key==="reason")&&typeof value=="string"&&value.trim().length>0?collected.push(value.trim()):typeof value=="object"&&value!=null&&visit(value,depth+1)};if(visit(turns[turns.length-1],0),collected.length===0)return;let joined=[...new Set(collected)].join(" | ");return joined.length>600?`${joined.slice(0,600)}\u2026`:joined}var import_activity14,import_node_events,init_execute_cursor=__esm({"dist/activities/execute-cursor/index.js"(){"use strict";import_activity14=__toESM(require_lib4(),1);init_esm4();init_api_pb3();init_message_pb();init_enum_pb();init_stigmer_client();init_session_lifecycle();init_enum_pb4();init_cursor_mode();init_message_translator();init_status2();init_stall_watchdog();init_artifact_storage();init_plan_artifact();init_delta_enricher();init_todo_tracker();init_cursor_event_recorder();init_mcp_resolver();init_approval_policy();init_approval_policy2();init_connect_backfill2();init_env_resolver();init_blueprint_resolver();init_subagent_config();init_skill_resolver();init_attachment_resolver();init_prompt_builder();init_workspace_setup();init_platform_dir();init_approval_state();init_workspace_provision();init_fetch_interceptor();init_http2_interceptor();init_model_pricing();init_usage_accumulator();init_usage_pb();init_idle_watchdog();init_rejection_capture();init_error_classifier();init_session_lifecycle();import_node_events=require("node:events");init_heartbeat();init_runner_manager();init_json_schema_to_zod()}});var import_node_crypto15=require("node:crypto"),import_node_fs9=require("node:fs"),import_node_path24=require("node:path"),import_node_readline=require("node:readline");init_config();init_otel();var import_node_fs8=require("node:fs"),import_node_path23=require("node:path"),import_node_os5=require("node:os");init_config();init_bootstrap();async function createStigmerRunner(options){validateOptions(options);let baseConfig=mapOptionsToConfig(options),{installFetchInterceptor:installFetchInterceptor2,getExecutionContext:getExecutionContext2}=await Promise.resolve().then(()=>(init_fetch_interceptor(),fetch_interceptor_exports));installFetchInterceptor2({proxyEndpoint:baseConfig.proxyEndpoint??void 0,stigmerToken:baseConfig.stigmerToken??void 0});let{installHttp2Interceptor:installHttp2Interceptor2,assertHttp2ConnectPatched:assertHttp2ConnectPatched2}=await Promise.resolve().then(()=>(init_http2_interceptor(),http2_interceptor_exports));installHttp2Interceptor2({proxyEndpoint:baseConfig.proxyEndpoint??void 0,stigmerToken:baseConfig.stigmerToken??void 0}),await assertHttp2ConnectPatched2();let coordinates=await resolveRunnerBootstrap({explicitAddress:options.temporalAddress,explicitNamespace:options.temporalNamespace,token:options.stigmerToken,stigmerEndpoint:baseConfig.stigmerBackendEndpoint}),config4={...baseConfig,temporalAddress:coordinates.temporalAddress,temporalNamespace:coordinates.temporalNamespace},{setExecutionContextRef:setExecutionContextRef2}=await Promise.resolve().then(()=>(init_rejection_capture(),rejection_capture_exports));setExecutionContextRef2(getExecutionContext2());let activities=await createAllActivities2(config4);console.log(`[runner] Registered activities: ${Object.keys(activities).join(", ")}`),console.log(`[runner] Task queue: ${config4.taskQueue} | Mode: ${config4.mode} | Max concurrency: ${config4.maxConcurrentActivities}`);let payloadCodec=await createPayloadCodec2(config4),{startWorker:startWorker2}=await Promise.resolve().then(()=>(init_worker(),worker_exports)),worker=await startWorker2({config:config4,activities,payloadCodec});return{async start(){console.log("Worker ready, polling for tasks..."),await worker.run(),console.log("Worker stopped")},shutdown(){worker.shutdown()}}}function validateOptions(options){if(!options.taskQueue)throw new Error("StigmerRunnerOptions.taskQueue is required \u2014 specify the Temporal task queue to poll");if(!options.stigmerEndpoint)throw new Error("StigmerRunnerOptions.stigmerEndpoint is required \u2014 specify the Stigmer server endpoint (e.g. 'http://localhost:7234')")}function mapOptionsToConfig(options){let proxyActive=!!options.proxyEndpoint,mode=options.executionMode??(proxyActive?"cloud":"local");return{taskQueue:options.taskQueue,temporalAddress:options.temporalAddress??"",temporalNamespace:options.temporalNamespace??"default",stigmerBackendEndpoint:normalizeEndpoint3(options.stigmerEndpoint),stigmerToken:options.stigmerToken??null,cursorApiKey:proxyActive?options.cursorApiKey??"proxy-managed":options.cursorApiKey??"",workspaceRootDir:options.workspaceRootDir??resolveDefaultWorkspaceDir2(),mode,proxyEndpoint:options.proxyEndpoint??null,maxConcurrentActivities:options.maxConcurrentActivities??5,idleTimeoutSeconds:null,cloudModeEnabled:options.cloudModeEnabled??!1,checkpointerType:options.checkpointerType??(proxyActive?"http":"memory"),checkpointerProxyEndpoint:options.checkpointerProxyEndpoint??options.proxyEndpoint??null,primaryModel:options.primaryModel??"gpt-4.1",cursorStreamStallTimeoutMs:options.cursorStreamStallTimeoutMs??DEFAULT_CURSOR_STREAM_STALL_TIMEOUT_MS}}async function createAllActivities2(config4){let[{createCursorActivities:createCursorActivities2},{createDeepAgentActivities:createDeepAgentActivities2},{createEnsureThreadActivities:createEnsureThreadActivities2},{createClassifyToolApprovalsActivities:createClassifyToolApprovalsActivities2},{createDiscoverMcpServerActivities:createDiscoverMcpServerActivities2},{createEvaluateExpressionsActivities:createEvaluateExpressionsActivities2},{createCallHttpActivities:createCallHttpActivities2},{createCallGrpcActivities:createCallGrpcActivities2},{createCallFunctionActivities:createCallFunctionActivities2},{createCallLlmActivities:createCallLlmActivities2},{createCallAgentActivities:createCallAgentActivities2},{createCallAgentStatusActivities:createCallAgentStatusActivities2},{createRunCommandActivities:createRunCommandActivities2},{createHydrateWorkflowActivities:createHydrateWorkflowActivities2},{createWorkflowEventActivities:createWorkflowEventActivities2},{createPromoteTaskOutputActivities:createPromoteTaskOutputActivities2}]=await Promise.all([Promise.resolve().then(()=>(init_execute_cursor(),execute_cursor_exports)),Promise.resolve().then(()=>(init_execute_deep_agent(),execute_deep_agent_exports)),Promise.resolve().then(()=>(init_ensure_thread(),ensure_thread_exports)),Promise.resolve().then(()=>(init_classify_tool_approvals(),classify_tool_approvals_exports)),Promise.resolve().then(()=>(init_discover_mcp_server(),discover_mcp_server_exports)),Promise.resolve().then(()=>(init_evaluate_expressions(),evaluate_expressions_exports)),Promise.resolve().then(()=>(init_call_http(),call_http_exports)),Promise.resolve().then(()=>(init_call_grpc(),call_grpc_exports)),Promise.resolve().then(()=>(init_call_function(),call_function_exports)),Promise.resolve().then(()=>(init_call_llm(),call_llm_exports)),Promise.resolve().then(()=>(init_call_agent(),call_agent_exports)),Promise.resolve().then(()=>(init_call_agent_status(),call_agent_status_exports)),Promise.resolve().then(()=>(init_run_command(),run_command_exports)),Promise.resolve().then(()=>(init_hydrate_workflow_execution(),hydrate_workflow_execution_exports)),Promise.resolve().then(()=>(init_workflow_event_activities(),workflow_event_activities_exports)),Promise.resolve().then(()=>(init_promote_task_output(),promote_task_output_exports))]);return{...createCursorActivities2(config4),...createDeepAgentActivities2(config4),...createEnsureThreadActivities2(),...createClassifyToolApprovalsActivities2(config4),...createDiscoverMcpServerActivities2(config4),...createEvaluateExpressionsActivities2(),...createCallHttpActivities2(),...createCallGrpcActivities2(),...createCallFunctionActivities2(),...createCallLlmActivities2(),...createCallAgentActivities2(),...createCallAgentStatusActivities2(),...createRunCommandActivities2(),...createHydrateWorkflowActivities2(config4),...createWorkflowEventActivities2(),...createPromoteTaskOutputActivities2()}}async function createPayloadCodec2(config4){let{loadClaimcheckConfig:loadClaimcheckConfig2,ClaimcheckPayloadCodec:ClaimcheckPayloadCodec2}=await Promise.resolve().then(()=>(init_claimcheck(),claimcheck_exports)),claimcheckConfig=loadClaimcheckConfig2();if(!claimcheckConfig.enabled)return;let{loadArtifactStorageConfig:loadArtifactStorageConfig2,createArtifactStorage:createArtifactStorage2}=await Promise.resolve().then(()=>(init_artifact_storage(),artifact_storage_exports)),storageConfig=loadArtifactStorageConfig2(config4),storage=createArtifactStorage2(storageConfig);return console.log(`[runner] Claimcheck enabled (threshold=${claimcheckConfig.thresholdBytes}B, compression=${claimcheckConfig.compressionEnabled}, storage=${storageConfig.type})`),new ClaimcheckPayloadCodec2(storage,claimcheckConfig)}function resolveDefaultWorkspaceDir2(){try{let dir=(0,import_node_path23.join)((0,import_node_os5.homedir)(),".stigmer","workspaces","runner");return(0,import_node_fs8.mkdirSync)(dir,{recursive:!0}),dir}catch{let dir=(0,import_node_path23.join)((0,import_node_os5.tmpdir)(),"stigmer-runner-workspace");return(0,import_node_fs8.mkdirSync)(dir,{recursive:!0}),dir}}function normalizeEndpoint3(endpoint){return endpoint.startsWith("http://")||endpoint.startsWith("https://")?endpoint:endpoint.endsWith(":443")?`https://${endpoint}`:`http://${endpoint}`}init_runner_manager();function buildReadyMessage(){return{type:"ready",protocolVersion:1}}init_rejection_capture();var BROKEN_PIPE_CODES=new Set(["EPIPE","ERR_STREAM_DESTROYED","ERR_STREAM_WRITE_AFTER_END"]);function isBrokenPipeError(err){let code=err?.code;return typeof code=="string"&&BROKEN_PIPE_CODES.has(code)}function guardStream(stream,onUnexpectedError){let detached=!1;return stream.on("error",err=>{let wasAttached=!detached;detached=!0,wasAttached&&!isBrokenPipeError(err)&&onUnexpectedError?.(err)}),chunk=>{if(detached)return!1;try{return stream.write(chunk)}catch{return detached=!0,!1}}}var installed=null;function installProcessPipeGuards(){if(installed)return installed;let writeStderr2=guardStream(process.stderr);return installed={writeStdout:guardStream(process.stdout,err=>{writeStderr2(`[pipe-safety] stdout (IPC) channel error, detaching: ${err.stack??err}
2194
+ Respond with ONLY the JSON object. Nothing else.`}let promptChars=effectivePrompt.length,promptEstimatedTokens=Math.ceil(promptChars/4);console.log(`ExecuteCursor prompt built: execution=${executionId}, chars=${promptChars}, estimatedTokens=${promptEstimatedTokens}, resolution=${resolution.reason}, mode=${resolution.mode}`),await ensureLoaded();let usageAccumulator=new UsageAccumulator(validatedModel),{startCursorTurnSpan:startCursorTurnSpan2}=await Promise.resolve().then(()=>(init_otel(),otel_exports)),turnSpan=await startCursorTurnSpan2({model:validatedModel,mode:agentMode,sessionId:sessionId??""});status.phase=ExecutionPhase.EXECUTION_IN_PROGRESS;let deltaEnricher=new DeltaEnricher,todoTracker=new TodoTracker(status.todos),eventRecorder=createCursorEventRecorder(executionId),platformStopSignaled=!1,firstTurnAttributionLogged=!1,streamErrorMessage,alreadyRetriedWithFreshAgent=!1,lastToolName,taskQueue=import_activity14.Context.current().info.taskQueue,shutdownSignal=getShutdownSignalForQueue(taskQueue);periodicHeartbeat=startHeartbeat(3e4,()=>({phase:"cursor_streaming",execution:executionId}),{shutdownSignal});try{(0,import_node_events.setMaxListeners)(25,import_activity14.Context.current().cancellationSignal)}catch{}let run=await resolution.agent.send(effectivePrompt,{onDelta:({update})=>{if(stallWatchdog?.recordActivity(),update.type==="turn-ended"&&update.usage&&(usageAccumulator.addTurn(update.usage),!firstTurnAttributionLogged)){firstTurnAttributionLogged=!0;let sdkInputTokens=update.usage.inputTokens??0,cursorOverhead=Math.max(0,sdkInputTokens-promptEstimatedTokens);console.log(`ExecuteCursor context attribution (first turn): execution=${executionId}, sdkInputTokens=${sdkInputTokens}, stigmerPreamble=${promptEstimatedTokens}, cursorOverhead=${cursorOverhead} (estimated)`)}deltaEnricher.processDelta(update);try{(0,import_activity14.heartbeat)()}catch(hbErr){if(hbErr instanceof import_activity14.CancelledFailure){pauseDetected=!0;return}throw hbErr}}});stallWatchdog=startStallWatchdog(config4.cursorStreamStallTimeoutMs,idleMs=>{stallDetected=!0,stallError=new StallTimeoutError(idleMs,lastToolName?`last tool: ${lastToolName}`:void 0),console.warn(`ExecuteCursor stall detected: execution=${executionId}, idleMs=${idleMs}, lastTool=${lastToolName??"none"}`),run.supports?.("cancel")&&run.cancel().catch(cancelErr=>{console.warn(`ExecuteCursor run.cancel() after stall failed (non-fatal): execution=${executionId}, error=${cancelErr instanceof Error?cancelErr.message:cancelErr}`)})});let accumulator=new MessageAccumulator(status.messages,{mergedPolicies}),scheduler=new StreamingUpdateScheduler(loadStreamingConfig()),eventCount=0;try{for await(let event of run.stream()){if(pauseDetected||import_activity14.Context.current().cancellationSignal.aborted){pauseDetected=!0;break}if(stallDetected)break;if(stallWatchdog.recordActivity(),event.type==="tool_call"&&typeof event.name=="string"&&(lastToolName=event.name),eventRecorder?.record(event,eventCount),accumulator.processEvent(event),todoTracker.processEvent(event),event.type==="tool_call"&&event.name==="task"&&accumulator.trackSubAgentExecution(event),deltaEnricher.applyEnrichments(status.messages),eventCount++,event.type==="status"){console.log(`ExecuteCursor stream status: execution=${executionId}, status=${JSON.stringify(event)}`);let statusEvent=event;statusEvent.status==="ERROR"&&statusEvent.message&&(streamErrorMessage=statusEvent.message)}let shouldPersist=shouldPersistStreamingStatus({deltaEnricherDirty:deltaEnricher.isDirty,todosDirty:todoTracker.isDirty,contentDirty:accumulator.isDirty},scheduler,eventCount);if(usageAccumulator.hasTurns&&(status.streamingUsage=create(StreamingUsageSummarySchema,usageAccumulator.snapshot())),shouldPersist){status.subAgentExecutions=accumulator.subAgentExecutions;let signal=await persist(status);deltaEnricher.markPersisted(),todoTracker.markPersisted(),accumulator.markPersisted(),scheduler.markUpdateSent(eventCount),(0,import_activity14.heartbeat)(),signal===ExecutionControlSignal.STOP&&(platformStopSignaled=!0,console.warn(`ExecuteCursor platform stop signal received: execution=${executionId}`))}if(platformStopSignaled){console.log(`ExecuteCursor stopping stream due to platform stop signal: execution=${executionId}`);break}}}catch(streamErr){if(!stallDetected)throw streamErr;console.warn(`ExecuteCursor stream ended via stall cancel: execution=${executionId}`)}periodicHeartbeat.stop(),stallWatchdog.stop();let isShutdown=periodicHeartbeat.workerShutdown||(shutdownSignal?.aborted??!1);isShutdown?pauseDetected=!1:periodicHeartbeat.cancelled&&(pauseDetected=!0),workerShutdownDetected=isShutdown,accumulator.finalize(),deltaEnricher.finalize(status.messages),(pauseDetected||workerShutdownDetected||stallDetected||import_activity14.Context.current().cancellationSignal.aborted)&&accumulator.cancelInProgressSubAgents(),status.subAgentExecutions=accumulator.subAgentExecutions,await eventRecorder?.flush(),usageAccumulator.hasTurns&&(status.streamingUsage=create(StreamingUsageSummarySchema,usageAccumulator.snapshot())),console.log(`ExecuteCursor stream ended: execution=${executionId}, events=${eventCount}, messages=${status.messages.length}, subAgents=${status.subAgentExecutions.length}`),await persist(status),(0,import_activity14.heartbeat)();let usageSnapshot=usageAccumulator.snapshot();turnSpan.setTokens(Number(usageSnapshot.inputTokens),Number(usageSnapshot.outputTokens)),turnSpan.end();try{let{recordTurnMetrics:recordTurnMetrics2}=await Promise.resolve().then(()=>(init_otel(),otel_exports)),turnDurationMs=Date.now()-(status.startedAt?new Date(status.startedAt).getTime():Date.now());await recordTurnMetrics2({durationMs:turnDurationMs,inputTokens:Number(usageSnapshot.inputTokens),outputTokens:Number(usageSnapshot.outputTokens),model:validatedModel,mode:agentMode})}catch{}if(stallDetected){let err=stallError??new StallTimeoutError(config4.cursorStreamStallTimeoutMs);return status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatStallFailure(err),status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Execution failed: the agent made no progress for too long and was stopped (${err.message}). You can retry or resume.`,timestamp:utcTimestamp()})),await persist(status),console.warn(`ExecuteCursor stalled: execution=${executionId}, events=${eventCount}, error=${status.error}`),slimStatus(status)}if(workerShutdownDetected)throw status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: runner worker was shut down. Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the runner worker was shut down while the agent was still running. You can retry or resume.",timestamp:utcTimestamp()})),await persist(status),console.log(`ExecuteCursor interrupted (worker shutdown): execution=${executionId}, events=${eventCount}`),new import_activity14.CancelledFailure("Activity cancelled (worker shutdown, not user pause)");if(pauseDetected)throw status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue.",timestamp:utcTimestamp()})),await persist(status),console.log(`ExecuteCursor paused: execution=${executionId}, events=${eventCount}`),new import_activity14.CancelledFailure("Activity paused by orchestrator");if(import_activity14.Context.current().cancellationSignal.aborted)throw status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: agent was unresponsive (heartbeat timeout). Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the agent was unresponsive for too long. You can retry or resume.",timestamp:utcTimestamp()})),await persist(status),console.log(`ExecuteCursor interrupted (infrastructure cancel): execution=${executionId}, events=${eventCount}`),new import_activity14.CancelledFailure("Activity cancelled (heartbeat timeout, not user pause)");if(platformStopSignaled){status.phase=ExecutionPhase.EXECUTION_COMPLETED,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution stopped by the platform.",timestamp:utcTimestamp()})),await persist(status);try{resolution.agent.close()}catch{}return console.log(`ExecuteCursor completed (platform stop): execution=${executionId}`),slimStatus(status)}let deniedLedger=await readDenialLedger(hitlDir??""),deniedToolCalls=reconcileDeniedToolCalls(status.messages,deniedLedger,mergedPolicies);if(deniedToolCalls.length>0)return status.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL,await persist(status),console.log(`ExecuteCursor returning WAITING_FOR_APPROVAL: ${deniedToolCalls.length} tools pending`),slimStatus(status);let result=await run.wait(),sdkResolvedModel=result.model?.id||void 0;switch(console.log(`ExecuteCursor run.wait() result: execution=${executionId}, result=${JSON.stringify(result)}`),sdkResolvedModel&&sdkResolvedModel!==validatedModel&&console.log(`ExecuteCursor model divergence: execution=${executionId}, requested=${validatedModel}, sdkResolved=${sdkResolvedModel}`),status.completedAt=utcTimestamp(),result.status){case"finished":status.phase=ExecutionPhase.EXECUTION_COMPLETED;break;case"error":{let resultAny=result,sdkError=result.result??resultAny.error??resultAny.message??resultAny.reason,sdkErrorStr=sdkError?String(sdkError):void 0,conversationErrorText=await introspectConversation(run,executionId),capturedRejection=getCapturedRejection(executionId);capturedRejection&&clearCapturedRejection(executionId);let classified=synthesizeError({sdkResultFields:sdkErrorStr,streamErrorMessage,capturedRejection,conversationErrorText,isResumedHandle:resolution.reason==="resumed_successfully",fallbackContext:{model:validatedModel,mode:agentMode,agentId:resolution.agentId},durationMs:result.durationMs,messageCount:status.messages.length});if(console.error(`ExecuteCursor agent error: execution=${executionId}, classified=${JSON.stringify(classified)}, rawResult=${JSON.stringify(result)}`),shouldRetryWithFreshAgent(classified)&&resolution.reason==="resumed_successfully"&&!alreadyRetriedWithFreshAgent){alreadyRetriedWithFreshAgent=!0,console.warn(`ExecuteCursor poisoned-handle recovery: execution=${executionId}, disposing agent ${resolution.agentId} and creating fresh agent`);try{resolution.agent.close()}catch{}let freshAgent=agentMode==="cloud"?await createCloudAgent(createOptions):await createAgent(createOptions),freshPrompt=buildPrompt({resolution:{...resolution,agent:freshAgent,agentId:freshAgent.agentId,isNew:!0,resumed:!1,reason:"created_after_resume_failure",resumeFailureDetail:`poisoned-handle recovery: ${classified.message}`},approvalDecisions,instructions:blueprint.instructions,userMessage:spec.message,skills:skillMetadata,subAgents:blueprint.subAgents,workspaceDirs:blueprint.workspaceDirs,workspaceFileRefs:spec.workspaceFileRefs??[],attachmentPaths,pendingApprovals:adjudicatedApprovals,interactionMode});console.log(`ExecuteCursor retry with fresh agent: execution=${executionId}, newAgentId=${freshAgent.agentId}`);try{blueprint.sessionSpec.harnessStateId=freshAgent.agentId,blueprint.session.metadata&&(blueprint.session.metadata.slug=""),await client2.updateSession(blueprint.session)}catch(updateErr){console.warn("Failed to update session with fresh agentId (non-fatal):",updateErr)}let retryWatchdog,retryRun=await freshAgent.send(freshPrompt,{onDelta:({update})=>{retryWatchdog?.recordActivity(),update.type==="turn-ended"&&update.usage&&usageAccumulator.addTurn(update.usage),deltaEnricher.processDelta(update);try{(0,import_activity14.heartbeat)()}catch{}}});retryWatchdog=startStallWatchdog(config4.cursorStreamStallTimeoutMs,idleMs=>{console.warn(`ExecuteCursor retry stall detected: execution=${executionId}, idleMs=${idleMs}`),retryRun.supports?.("cancel")&&retryRun.cancel().catch(()=>{})}),streamErrorMessage=void 0;try{for await(let retryEvent of retryRun.stream()){if(import_activity14.Context.current().cancellationSignal.aborted)break;if(retryWatchdog.recordActivity(),accumulator.processEvent(retryEvent),retryEvent.type==="status"){let retryStatusEvent=retryEvent;retryStatusEvent.status==="ERROR"&&retryStatusEvent.message&&(streamErrorMessage=retryStatusEvent.message)}(0,import_activity14.heartbeat)()}}finally{retryWatchdog.stop()}let retryResult=await retryRun.wait();if(console.log(`ExecuteCursor retry run.wait(): execution=${executionId}, retryResult=${JSON.stringify(retryResult)}`),retryResult.status==="finished"){status.phase=ExecutionPhase.EXECUTION_COMPLETED,console.log(`ExecuteCursor poisoned-handle recovery SUCCEEDED: execution=${executionId}`);break}if(retryResult.status==="cancelled"){status.phase=ExecutionPhase.EXECUTION_CANCELLED;break}let retryRejection=getCapturedRejection(executionId);retryRejection&&clearCapturedRejection(executionId);let retryConversationErrorText=await introspectConversation(retryRun,executionId),retryClassified=synthesizeError({sdkResultFields:retryResult.result?String(retryResult.result):void 0,streamErrorMessage,capturedRejection:retryRejection,conversationErrorText:retryConversationErrorText,isResumedHandle:!1,fallbackContext:{model:validatedModel,mode:agentMode,agentId:freshAgent.agentId}});status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatClassifiedError(retryClassified),console.error(`ExecuteCursor poisoned-handle recovery FAILED: execution=${executionId}, retryError=${status.error}`);break}if(classified.category==="network"&&classified.retryable&&resolution.reason!=="resumed_successfully"&&!alreadyRetriedWithFreshAgent){alreadyRetriedWithFreshAgent=!0,console.warn(`ExecuteCursor transport-timeout recovery: execution=${executionId}, resetting proxy sessions and retrying with fresh agent`);try{resolution.agent.close()}catch{}closeProxySessions();let freshAgent=agentMode==="cloud"?await createCloudAgent(createOptions):await createAgent(createOptions);try{blueprint.sessionSpec.harnessStateId=freshAgent.agentId,blueprint.session.metadata&&(blueprint.session.metadata.slug=""),await client2.updateSession(blueprint.session)}catch(updateErr){console.warn("Failed to update session with fresh agentId (non-fatal):",updateErr)}let retryWatchdog,retryRun=await freshAgent.send(effectivePrompt,{onDelta:({update})=>{retryWatchdog?.recordActivity(),update.type==="turn-ended"&&update.usage&&usageAccumulator.addTurn(update.usage),deltaEnricher.processDelta(update);try{(0,import_activity14.heartbeat)()}catch{}}});retryWatchdog=startStallWatchdog(config4.cursorStreamStallTimeoutMs,idleMs=>{console.warn(`ExecuteCursor retry stall detected: execution=${executionId}, idleMs=${idleMs}`),retryRun.supports?.("cancel")&&retryRun.cancel().catch(()=>{})}),streamErrorMessage=void 0;try{for await(let retryEvent of retryRun.stream()){if(import_activity14.Context.current().cancellationSignal.aborted)break;if(retryWatchdog.recordActivity(),accumulator.processEvent(retryEvent),retryEvent.type==="status"){let retryStatusEvent=retryEvent;retryStatusEvent.status==="ERROR"&&retryStatusEvent.message&&(streamErrorMessage=retryStatusEvent.message)}(0,import_activity14.heartbeat)()}}finally{retryWatchdog.stop()}if((await retryRun.wait()).status==="finished"){status.phase=ExecutionPhase.EXECUTION_COMPLETED,resolution={...resolution,agent:freshAgent,agentId:freshAgent.agentId,isNew:!0};break}status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=`Transport recovery failed: ${formatClassifiedError(classified)}`;break}status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatClassifiedError(classified);break}case"cancelled":status.phase=ExecutionPhase.EXECUTION_CANCELLED;break;default:status.phase=ExecutionPhase.EXECUTION_COMPLETED}let structuredOutput,finalText;if(status.phase===ExecutionPhase.EXECUTION_COMPLETED){if(finalText=[...status.messages].reverse().find(m=>m.type===MessageType.MESSAGE_AI)?.content,structuredOutputSchema&&finalText){let{extractJsonFromText:extractJsonFromText2}=await Promise.resolve().then(()=>(init_extract_json(),extract_json_exports));if(structuredOutput=extractJsonFromText2(finalText),structuredOutput!==void 0&&console.log(`ExecuteCursor structured output extracted (text): execution=${executionId}, finalTextLength=${finalText.length}`),structuredOutput===void 0){console.log(`ExecuteCursor text extraction failed, trying LLM extraction: execution=${executionId}, finalTextLength=${finalText.length}`);try{structuredOutput=await extractStructuredOutput(finalText,structuredOutputSchema,config4,requestedModel),structuredOutput!==void 0&&console.log(`ExecuteCursor structured output extracted (LLM): execution=${executionId}`)}catch(extractErr){let errMsg=extractErr instanceof Error?extractErr.message:String(extractErr);console.error(`ExecuteCursor structured output extraction FAILED: execution=${executionId}, requestedModel=${requestedModel}, finalTextLength=${finalText.length}, error=${errMsg}`)}}}if(structuredOutput!==void 0&&(status.structuredOutput=structuredOutput),interactionMode===InteractionMode.PLAN&&finalText&&artifactStorage)try{await publishPlanArtifact({status,executionId,planText:finalText,artifactStorage})}catch(err){console.warn(`ExecuteCursor plan artifact publish skipped (non-fatal): execution=${executionId}, error=${err}`)}}await persist(status),console.log(`ExecuteCursor completed: execution=${executionId}, phase=${ExecutionPhase[status.phase]}, hasStructuredOutput=${structuredOutput!==void 0}`+(status.error?`, error=${status.error}`:""));try{resolution.agent.close()}catch{}let slim=slimStatus(status);return finalText!==void 0&&(slim.final_text=finalText),structuredOutput!==void 0&&(slim.structured=structuredOutput),slim}catch(err){if(periodicHeartbeat?.stop(),err instanceof import_activity14.CancelledFailure)throw workerShutdownDetected?(console.log(`ExecuteCursor cancelled (worker shutdown) for execution ${executionId}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: runner worker was shut down. Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the runner worker was shut down while the agent was still running. You can retry or resume.",timestamp:utcTimestamp()}))):pauseDetected?(console.log(`ExecuteCursor cancelled (pause) for execution ${executionId}`),status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue.",timestamp:utcTimestamp()}))):(console.log(`ExecuteCursor cancelled (infrastructure) for execution ${executionId}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error="Execution interrupted: agent was unresponsive (heartbeat timeout). Retry or resume.",status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the agent was unresponsive for too long. You can retry or resume.",timestamp:utcTimestamp()}))),cancelInProgressSubAgentProtos(status.subAgentExecutions),await persist(status).catch(()=>{}),err;if(pauseDetected){let errDetail=err instanceof Error?err.message:String(err);throw console.log(`ExecuteCursor error during pause (treating as pause): execution=${executionId}, error=${errDetail}`),status.phase=ExecutionPhase.EXECUTION_PAUSED,status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution paused by user. Use resume to continue.",timestamp:utcTimestamp()})),cancelInProgressSubAgentProtos(status.subAgentExecutions),await persist(status).catch(()=>{}),new import_activity14.CancelledFailure("Activity paused by orchestrator (error during pause)")}if(import_activity14.Context.current().cancellationSignal.aborted){let errDetail=err instanceof Error?err.message:String(err);throw console.log(`ExecuteCursor error during infrastructure cancel: execution=${executionId}, error=${errDetail}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=`Execution interrupted: ${errDetail}`,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Execution interrupted: the agent was unresponsive for too long. You can retry or resume.",timestamp:utcTimestamp()})),cancelInProgressSubAgentProtos(status.subAgentExecutions),await persist(status).catch(()=>{}),new import_activity14.CancelledFailure("Activity cancelled (infrastructure, not user pause)")}let{CursorSdkError}=await import("@cursor/sdk");if(err instanceof CursorSdkError){let sdkErrorJson=err.toJSON();console.error(`ExecuteCursor SDK error: execution=${executionId}, sdkError=${JSON.stringify(sdkErrorJson)}`);let classified=synthesizeError({sdkError:{code:err.code,status:err.status,message:err.message},sdkResultFields:void 0,streamErrorMessage:void 0,capturedRejection:getCapturedRejection(executionId),isResumedHandle:!1,fallbackContext:errorContext});clearCapturedRejection(executionId),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=formatClassifiedError(classified),status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Internal system error occurred. Please contact support if this issue persists.",timestamp:utcTimestamp()}),create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Error details: ${status.error}`,timestamp:utcTimestamp()}));try{await persist(status)}catch(persistErr){console.error("Failed to persist error status (best-effort):",persistErr)}return slimStatus(status)}let errMsg=err instanceof Error?err.message:String(err),errType=err instanceof Error?err.constructor.name:"Unknown";console.error(`ExecuteCursor failed: execution=${executionId}, [${errType}] ${errMsg}`),status.phase=ExecutionPhase.EXECUTION_FAILED,status.error=`Execution failed: [${errType}] ${errMsg}`,status.completedAt=utcTimestamp(),status.messages.push(create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:"Internal system error occurred. Please contact support if this issue persists.",timestamp:utcTimestamp()}),create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Error details: [${errType}] ${errMsg}`,timestamp:utcTimestamp()}));try{await persist(status)}catch(persistErr){console.error("Failed to persist error status (best-effort):",persistErr)}return slimStatus(status)}finally{if(stallWatchdog?.stop(),hitlCleanup)try{await hitlCleanup()}catch(cleanupErr){console.warn(`ExecuteCursor HITL gate teardown failed (non-fatal): execution=${executionId}, error=${cleanupErr instanceof Error?cleanupErr.message:cleanupErr}`)}}}async function extractStructuredOutput(agentResponse,schema2,config4,primaryModel){let{ChatOpenAI:ChatOpenAI3}=await Promise.resolve().then(()=>(init_dist10(),dist_exports3)),{ChatAnthropic:ChatAnthropic2}=await Promise.resolve().then(()=>(init_dist9(),dist_exports2)),{inferProvider:inferProvider3,resolveProxyBaseUrl:resolveProxyBaseUrl2,buildProxyHeaders:buildProxyHeaders2}=await Promise.resolve().then(()=>(init_llm_proxy(),llm_proxy_exports)),{getEconomyModel:getEconomyModel2}=await Promise.resolve().then(()=>(init_model_registry(),model_registry_exports)),extractionModel=await getEconomyModel2(primaryModel),provider=inferProvider3(extractionModel),proxyEndpoint=config4.proxyEndpoint??config4.stigmerBackendEndpoint,baseUrl=resolveProxyBaseUrl2(proxyEndpoint,provider),headers=config4.stigmerToken?buildProxyHeaders2(config4.stigmerToken,{}):{},apiKey=provider==="openai"?config4.stigmerToken??process.env.OPENAI_API_KEY??"proxy-managed":config4.stigmerToken??process.env.ANTHROPIC_API_KEY??"proxy-managed",llm=provider==="openai"?new ChatOpenAI3({model:extractionModel,apiKey,temperature:0,maxTokens:4096,configuration:{baseURL:baseUrl,defaultHeaders:headers}}):new ChatAnthropic2({model:extractionModel,apiKey,temperature:0,maxTokens:4096,clientOptions:{baseURL:baseUrl,defaultHeaders:headers}}),zodSchema=jsonSchemaToZod(schema2);return await llm.withStructuredOutput(zodSchema).invoke([{role:"system",content:"Extract the structured data from the agent's response. Return only the data that matches the schema."},{role:"user",content:agentResponse}])??null}function buildPrompt(input){let{resolution,approvalDecisions,instructions,userMessage,skills,subAgents,workspaceDirs,workspaceFileRefs,attachmentPaths,interactionMode}=input;return approvalDecisions!==void 0&&approvalDecisions.size>0?buildReinvocationPrompt(input.pendingApprovals,approvalDecisions):resolution.reason==="resumed_successfully"?userMessage:buildEnhancedPrompt({instructions,userMessage,skills,subAgents,workspaceDirs,workspaceFileRefs,attachmentPaths,interactionMode})}async function introspectConversation(run,executionId){try{if(!run.supports("conversation")){console.log(`ExecuteCursor conversation introspection unsupported: execution=${executionId}, reason=${run.unsupportedReason("conversation")??"n/a"}`);return}let turns=await run.conversation(),raw=JSON.stringify(turns),bounded=raw.length>8e3?`${raw.slice(0,8e3)}\u2026(truncated ${raw.length} chars)`:raw;return console.error(`ExecuteCursor conversation introspection: execution=${executionId}, turns=${turns.length}, raw=${bounded}`),extractConversationErrorText(turns)}catch(introspectErr){console.warn(`ExecuteCursor conversation introspection failed (non-fatal): execution=${executionId}, error=${introspectErr instanceof Error?introspectErr.message:String(introspectErr)}`);return}}function extractConversationErrorText(turns){if(!turns||turns.length===0)return;let collected=[],visit=(node,depth)=>{if(node==null||depth>6||typeof node!="object")return;if(Array.isArray(node)){for(let item of node)visit(item,depth+1);return}let obj=node;obj.status==="error"&&obj.error!=null&&collected.push(typeof obj.error=="string"?obj.error:JSON.stringify(obj.error));for(let[key,value]of Object.entries(obj))(key==="text"||key==="message"||key==="reason")&&typeof value=="string"&&value.trim().length>0?collected.push(value.trim()):typeof value=="object"&&value!=null&&visit(value,depth+1)};if(visit(turns[turns.length-1],0),collected.length===0)return;let joined=[...new Set(collected)].join(" | ");return joined.length>600?`${joined.slice(0,600)}\u2026`:joined}var import_activity14,import_node_events,init_execute_cursor=__esm({"dist/activities/execute-cursor/index.js"(){"use strict";import_activity14=__toESM(require_lib4(),1);init_esm4();init_api_pb3();init_message_pb();init_enum_pb();init_stigmer_client();init_session_lifecycle();init_enum_pb4();init_cursor_mode();init_message_translator();init_status2();init_stall_watchdog();init_artifact_storage();init_plan_artifact();init_delta_enricher();init_todo_tracker();init_persist_decision();init_streaming_scheduler();init_cursor_event_recorder();init_mcp_resolver();init_approval_policy();init_approval_policy2();init_connect_backfill2();init_env_resolver();init_blueprint_resolver();init_subagent_config();init_skill_resolver();init_attachment_resolver();init_prompt_builder();init_workspace_setup();init_platform_dir();init_approval_state();init_workspace_provision();init_fetch_interceptor();init_http2_interceptor();init_model_pricing();init_usage_accumulator();init_usage_pb();init_idle_watchdog();init_rejection_capture();init_error_classifier();init_session_lifecycle();import_node_events=require("node:events");init_heartbeat();init_runner_manager();init_json_schema_to_zod()}});var import_node_crypto15=require("node:crypto"),import_node_fs9=require("node:fs"),import_node_path24=require("node:path"),import_node_readline=require("node:readline");init_config();init_otel();var import_node_fs8=require("node:fs"),import_node_path23=require("node:path"),import_node_os5=require("node:os");init_config();init_bootstrap();async function createStigmerRunner(options){validateOptions(options);let baseConfig=mapOptionsToConfig(options),{installFetchInterceptor:installFetchInterceptor2,getExecutionContext:getExecutionContext2}=await Promise.resolve().then(()=>(init_fetch_interceptor(),fetch_interceptor_exports));installFetchInterceptor2({proxyEndpoint:baseConfig.proxyEndpoint??void 0,stigmerToken:baseConfig.stigmerToken??void 0});let{installHttp2Interceptor:installHttp2Interceptor2,assertHttp2ConnectPatched:assertHttp2ConnectPatched2}=await Promise.resolve().then(()=>(init_http2_interceptor(),http2_interceptor_exports));installHttp2Interceptor2({proxyEndpoint:baseConfig.proxyEndpoint??void 0,stigmerToken:baseConfig.stigmerToken??void 0}),await assertHttp2ConnectPatched2();let coordinates=await resolveRunnerBootstrap({explicitAddress:options.temporalAddress,explicitNamespace:options.temporalNamespace,token:options.stigmerToken,stigmerEndpoint:baseConfig.stigmerBackendEndpoint}),config4={...baseConfig,temporalAddress:coordinates.temporalAddress,temporalNamespace:coordinates.temporalNamespace},{setExecutionContextRef:setExecutionContextRef2}=await Promise.resolve().then(()=>(init_rejection_capture(),rejection_capture_exports));setExecutionContextRef2(getExecutionContext2());let activities=await createAllActivities2(config4);console.log(`[runner] Registered activities: ${Object.keys(activities).join(", ")}`),console.log(`[runner] Task queue: ${config4.taskQueue} | Mode: ${config4.mode} | Max concurrency: ${config4.maxConcurrentActivities}`);let payloadCodec=await createPayloadCodec2(config4),{startWorker:startWorker2}=await Promise.resolve().then(()=>(init_worker(),worker_exports)),worker=await startWorker2({config:config4,activities,payloadCodec});return{async start(){console.log("Worker ready, polling for tasks..."),await worker.run(),console.log("Worker stopped")},shutdown(){worker.shutdown()}}}function validateOptions(options){if(!options.taskQueue)throw new Error("StigmerRunnerOptions.taskQueue is required \u2014 specify the Temporal task queue to poll");if(!options.stigmerEndpoint)throw new Error("StigmerRunnerOptions.stigmerEndpoint is required \u2014 specify the Stigmer server endpoint (e.g. 'http://localhost:7234')")}function mapOptionsToConfig(options){let proxyActive=!!options.proxyEndpoint,mode=options.executionMode??(proxyActive?"cloud":"local");return{taskQueue:options.taskQueue,temporalAddress:options.temporalAddress??"",temporalNamespace:options.temporalNamespace??"default",stigmerBackendEndpoint:normalizeEndpoint3(options.stigmerEndpoint),stigmerToken:options.stigmerToken??null,cursorApiKey:proxyActive?options.cursorApiKey??"proxy-managed":options.cursorApiKey??"",workspaceRootDir:options.workspaceRootDir??resolveDefaultWorkspaceDir2(),mode,proxyEndpoint:options.proxyEndpoint??null,maxConcurrentActivities:options.maxConcurrentActivities??5,idleTimeoutSeconds:null,cloudModeEnabled:options.cloudModeEnabled??!1,checkpointerType:options.checkpointerType??(proxyActive?"http":"memory"),checkpointerProxyEndpoint:options.checkpointerProxyEndpoint??options.proxyEndpoint??null,primaryModel:options.primaryModel??"gpt-4.1",cursorStreamStallTimeoutMs:options.cursorStreamStallTimeoutMs??DEFAULT_CURSOR_STREAM_STALL_TIMEOUT_MS}}async function createAllActivities2(config4){let[{createCursorActivities:createCursorActivities2},{createDeepAgentActivities:createDeepAgentActivities2},{createEnsureThreadActivities:createEnsureThreadActivities2},{createClassifyToolApprovalsActivities:createClassifyToolApprovalsActivities2},{createDiscoverMcpServerActivities:createDiscoverMcpServerActivities2},{createEvaluateExpressionsActivities:createEvaluateExpressionsActivities2},{createCallHttpActivities:createCallHttpActivities2},{createCallGrpcActivities:createCallGrpcActivities2},{createCallFunctionActivities:createCallFunctionActivities2},{createCallLlmActivities:createCallLlmActivities2},{createCallAgentActivities:createCallAgentActivities2},{createCallAgentStatusActivities:createCallAgentStatusActivities2},{createRunCommandActivities:createRunCommandActivities2},{createHydrateWorkflowActivities:createHydrateWorkflowActivities2},{createWorkflowEventActivities:createWorkflowEventActivities2},{createPromoteTaskOutputActivities:createPromoteTaskOutputActivities2}]=await Promise.all([Promise.resolve().then(()=>(init_execute_cursor(),execute_cursor_exports)),Promise.resolve().then(()=>(init_execute_deep_agent(),execute_deep_agent_exports)),Promise.resolve().then(()=>(init_ensure_thread(),ensure_thread_exports)),Promise.resolve().then(()=>(init_classify_tool_approvals(),classify_tool_approvals_exports)),Promise.resolve().then(()=>(init_discover_mcp_server(),discover_mcp_server_exports)),Promise.resolve().then(()=>(init_evaluate_expressions(),evaluate_expressions_exports)),Promise.resolve().then(()=>(init_call_http(),call_http_exports)),Promise.resolve().then(()=>(init_call_grpc(),call_grpc_exports)),Promise.resolve().then(()=>(init_call_function(),call_function_exports)),Promise.resolve().then(()=>(init_call_llm(),call_llm_exports)),Promise.resolve().then(()=>(init_call_agent(),call_agent_exports)),Promise.resolve().then(()=>(init_call_agent_status(),call_agent_status_exports)),Promise.resolve().then(()=>(init_run_command(),run_command_exports)),Promise.resolve().then(()=>(init_hydrate_workflow_execution(),hydrate_workflow_execution_exports)),Promise.resolve().then(()=>(init_workflow_event_activities(),workflow_event_activities_exports)),Promise.resolve().then(()=>(init_promote_task_output(),promote_task_output_exports))]);return{...createCursorActivities2(config4),...createDeepAgentActivities2(config4),...createEnsureThreadActivities2(),...createClassifyToolApprovalsActivities2(config4),...createDiscoverMcpServerActivities2(config4),...createEvaluateExpressionsActivities2(),...createCallHttpActivities2(),...createCallGrpcActivities2(),...createCallFunctionActivities2(),...createCallLlmActivities2(),...createCallAgentActivities2(),...createCallAgentStatusActivities2(),...createRunCommandActivities2(),...createHydrateWorkflowActivities2(config4),...createWorkflowEventActivities2(),...createPromoteTaskOutputActivities2()}}async function createPayloadCodec2(config4){let{loadClaimcheckConfig:loadClaimcheckConfig2,ClaimcheckPayloadCodec:ClaimcheckPayloadCodec2}=await Promise.resolve().then(()=>(init_claimcheck(),claimcheck_exports)),claimcheckConfig=loadClaimcheckConfig2();if(!claimcheckConfig.enabled)return;let{loadArtifactStorageConfig:loadArtifactStorageConfig2,createArtifactStorage:createArtifactStorage2}=await Promise.resolve().then(()=>(init_artifact_storage(),artifact_storage_exports)),storageConfig=loadArtifactStorageConfig2(config4),storage=createArtifactStorage2(storageConfig);return console.log(`[runner] Claimcheck enabled (threshold=${claimcheckConfig.thresholdBytes}B, compression=${claimcheckConfig.compressionEnabled}, storage=${storageConfig.type})`),new ClaimcheckPayloadCodec2(storage,claimcheckConfig)}function resolveDefaultWorkspaceDir2(){try{let dir=(0,import_node_path23.join)((0,import_node_os5.homedir)(),".stigmer","workspaces","runner");return(0,import_node_fs8.mkdirSync)(dir,{recursive:!0}),dir}catch{let dir=(0,import_node_path23.join)((0,import_node_os5.tmpdir)(),"stigmer-runner-workspace");return(0,import_node_fs8.mkdirSync)(dir,{recursive:!0}),dir}}function normalizeEndpoint3(endpoint){return endpoint.startsWith("http://")||endpoint.startsWith("https://")?endpoint:endpoint.endsWith(":443")?`https://${endpoint}`:`http://${endpoint}`}init_runner_manager();function buildReadyMessage(){return{type:"ready",protocolVersion:1}}init_rejection_capture();var BROKEN_PIPE_CODES=new Set(["EPIPE","ERR_STREAM_DESTROYED","ERR_STREAM_WRITE_AFTER_END"]);function isBrokenPipeError(err){let code=err?.code;return typeof code=="string"&&BROKEN_PIPE_CODES.has(code)}function guardStream(stream,onUnexpectedError){let detached=!1;return stream.on("error",err=>{let wasAttached=!detached;detached=!0,wasAttached&&!isBrokenPipeError(err)&&onUnexpectedError?.(err)}),chunk=>{if(detached)return!1;try{return stream.write(chunk)}catch{return detached=!0,!1}}}var installed=null;function installProcessPipeGuards(){if(installed)return installed;let writeStderr2=guardStream(process.stderr);return installed={writeStdout:guardStream(process.stdout,err=>{writeStderr2(`[pipe-safety] stdout (IPC) channel error, detaching: ${err.stack??err}
2195
2195
  `)}),writeStderr:writeStderr2},installed}function reportFatal(write,label,err){try{let detail=err instanceof Error?err.stack??err.message:String(err);write(`${label} ${detail}
2196
2196
  `)}catch{}}var{writeStdout,writeStderr}=installProcessPipeGuards();process.on("unhandledRejection",reason=>{handleUnhandledRejection(reason)});process.on("uncaughtException",err=>{reportFatal(writeStderr,"Uncaught exception in runner:",err)});function sendIpc(msg){writeStdout(JSON.stringify(msg)+`
2197
2197
  `)}async function runManagerMode(config4){let originalLog=console.log;console.log=(...args)=>{writeStderr(args.map(String).join(" ")+`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stigmer/runner-slim",
3
- "version": "3.0.8",
3
+ "version": "3.0.9-dev.20260615150714",
4
4
  "description": "Self-contained Stigmer runner build for embedding in desktop apps — the bundle-friendly @stigmer/runner",
5
5
  "license": "Apache-2.0",
6
6
  "engines": {
@@ -16,11 +16,11 @@
16
16
  "jq-wasm": "^1.1.0-jq-1.8.1"
17
17
  },
18
18
  "optionalDependencies": {
19
- "@stigmer/runner-slim-darwin-arm64": "3.0.8",
20
- "@stigmer/runner-slim-darwin-x64": "3.0.8",
21
- "@stigmer/runner-slim-linux-x64": "3.0.8",
22
- "@stigmer/runner-slim-linux-arm64": "3.0.8",
23
- "@stigmer/runner-slim-win32-x64": "3.0.8"
19
+ "@stigmer/runner-slim-darwin-arm64": "3.0.9-dev.20260615150714",
20
+ "@stigmer/runner-slim-darwin-x64": "3.0.9-dev.20260615150714",
21
+ "@stigmer/runner-slim-linux-x64": "3.0.9-dev.20260615150714",
22
+ "@stigmer/runner-slim-linux-arm64": "3.0.9-dev.20260615150714",
23
+ "@stigmer/runner-slim-win32-x64": "3.0.9-dev.20260615150714"
24
24
  },
25
25
  "keywords": [
26
26
  "stigmer",