@stigmer/runner-slim 3.1.4 → 3.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/main.js +3 -3
- package/package.json +6 -6
package/main.js
CHANGED
|
@@ -160,7 +160,7 @@ ${path6}`}function findUnmatchedStreamCallByNormalizedSalient(messages,matchedCa
|
|
|
160
160
|
`);if(first<0)return;let key=decoded.slice(0,first),rest=decoded.slice(first+1),second=rest.indexOf(`
|
|
161
161
|
`);return second<0?{key,salient:rest,digest:""}:{key,salient:rest.slice(0,second),digest:rest.slice(second+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,digest,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),approvalContentDigest:digest});if(salient&&(tc.argsPreview=JSON.stringify({path:salient})),tc.approvalMessage=salient?`Tool requires approval: ${displayName} (${salient})`:resolveDeniedApprovalMessage(displayName,"",{},mergedPolicies),mergedPolicies){let source=resolveApprovalProvenance(displayName,"",mergedPolicies,NO_LEASED_CATEGORIES,!1);tc.approvalPolicySource=toProtoPolicySource(source),source&&(tc.policyEngineVersion=POLICY_ENGINE_VERSION)}return 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,NO_LEASED_CATEGORIES,SUBAGENT_TOOL_RESULT_FAILURE_KEYS,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_policy2();init_approval_policy();init_approval_state();init_status2();init_tool_row();init_tool_kind();init_file_change();init_file_tools();init_secret_paths();init_args_preview();SUPPRESSED_TOOL_NAMES=new Set(["TodoWrite","updateTodos"]);NO_LEASED_CATEGORIES=new Set;SUBAGENT_TOOL_RESULT_FAILURE_KEYS=new Set(["error","permissionDenied","rejected"]);MessageAccumulator=class{messages;activeAiByRunId=new Map;activeThinkingByRunId=new Map;_subAgentExecutions=[];subAgentMap=new Map;mergedPolicies;provenance;workspaceRoot;toolCallIndex=new Map;_dirty=!1;constructor(messages,options){this.messages=messages,this.mergedPolicies=options?.mergedPolicies,this.provenance=options?.provenance,this.workspaceRoot=options?.workspaceRoot,this.rebuildToolCallIndex();for(let sub of options?.seededSubAgents??[])this._subAgentExecutions.push(sub),sub.id&&this.subAgentMap.set(sub.id,sub)}rebuildToolCallIndex(){this.toolCallIndex.clear();for(let message of this.messages)for(let tc of message.toolCalls)tc.id&&this.toolCallIndex.set(tc.id,tc)}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){this.mergeToolCallEvent(existing,event);return}let tc=buildToolCallProto(event,this.mergedPolicies,this.provenance),seeded=this.findResumableSeededToolCall(tc);if(seeded){this.toolCallIndex.set(event.call_id,seeded),this.mergeToolCallEvent(seeded,event);return}this.findOrCreateLastAiMessage().toolCalls.push(tc),this.toolCallIndex.set(event.call_id,tc),this._dirty=!0}findResumableSeededToolCall(candidate){let wanted=toolCallIdentityToken(candidate);for(let tc of this.toolCallIndex.values())if(tc.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL&&toolCallIdentityToken(tc)===wanted)return tc}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,resolveUsableArtifactStorage:()=>resolveUsableArtifactStorage});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)}async function isLocalPathWritable(basePath){let probePath=(0,import_node_path7.join)(basePath,`.write-probe-${process.pid}-${Date.now()}`);try{return await(0,import_promises3.mkdir)(basePath,{recursive:!0}),await(0,import_promises3.writeFile)(probePath,""),await(0,import_promises3.rm)(probePath,{force:!0}),!0}catch{return!1}}async function resolveUsableArtifactStorage(cfg,ctx){let storage;try{storage=createArtifactStorage(cfg)}catch(err){console.warn(`[artifact-storage] unavailable \u2014 file capture degrades to the deny-gate and tool-output offload is disabled: execution=${ctx.executionId}, type=${cfg.type}, error=${err}`);return}if(cfg.type==="local"&&!await isLocalPathWritable(cfg.localPath)){console.warn(`[artifact-storage] local path not writable \u2014 file capture degrades to the deny-gate and tool-output offload is disabled: execution=${ctx.executionId}, path=${cfg.localPath}`);return}return storage}var import_promises3,import_node_path7,LocalArtifactStorage,ProxyArtifactStorage,init_artifact_storage=__esm({"dist/shared/artifact-storage.js"(){"use strict";import_promises3=require("node:fs/promises"),import_node_path7=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_path7.join)(this.basePath,key);return await(0,import_promises3.mkdir)((0,import_node_path7.dirname)(filePath),{recursive:!0}),await(0,import_promises3.writeFile)(filePath,content),key}async getDownloadUrl(key){return`${this.serveUrlBase}/${key}`}async download(key){try{return await(0,import_promises3.readFile)((0,import_node_path7.join)(this.basePath,key))}catch(err){let reason=err instanceof Error?err.message:String(err);throw new Error(`Artifact not found for key '${key}': ${reason}`)}}async exists(key){try{return await(0,import_promises3.access)((0,import_node_path7.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 download(key){let url3=await this.getDownloadUrl(key),resp=await fetch(url3);if(!resp.ok)throw new Error(`Artifact download failed (HTTP ${resp.status}) for key '${key}': `+await resp.text());return Buffer.from(await resp.arrayBuffer())}async exists(key){let url3;try{url3=await this.getDownloadUrl(key)}catch{return!1}let resp=await fetch(url3,{headers:{Range:"bytes=0-0"}});if(await resp.arrayBuffer().catch(()=>{}),resp.status===404)return!1;if(resp.status===200||resp.status===206||resp.status===416)return!0;throw new Error(`Artifact existence check failed (HTTP ${resp.status}) for key '${key}'`)}}}});function isPlanArtifactName(name2){return name2===PLAN_ARTIFACT_NAME||name2.endsWith(PLAN_ARTIFACT_SUFFIX)}function extractPlanTitle(planText){let trimmed=planText.trim(),body=trimmed,tagged2=ENCLOSING_MARKDOWN_FENCE_RE.exec(trimmed);if(tagged2)body=tagged2[2];else{let bare=ENCLOSING_BARE_FENCE_RE.exec(trimmed);bare&&(body=bare[2])}let h1=LEADING_H1_RE.exec(body.trim());return h1?h1[1]:void 0}function stripPlanLabel(title){return title.replace(/^plan\s*[:\u2013\u2014-]\s*/i,"")}function slugifyPlanTitle(title){return title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,MAX_PLAN_SLUG_LENGTH).replace(/-+$/g,"")}function planArtifactName(planText){let id=(0,import_node_crypto7.createHash)("sha256").update(planText,"utf-8").digest("hex").slice(0,PLAN_ID_LENGTH),title=extractPlanTitle(planText),slug=title?slugifyPlanTitle(stripPlanLabel(title)):"";return slug.length>0?`${slug}_${id}${PLAN_ARTIFACT_SUFFIX}`:`${id}${PLAN_ARTIFACT_SUFFIX}`}function planArtifactSandboxPath(name2){return`.stigmer/plans/${name2}`}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_crypto7.createHash)("sha256").update(content).digest("hex"),name2=planArtifactName(planText),storageKey=`artifacts/${executionId}/${name2}`;await artifactStorage.upload(storageKey,content,"text/markdown");let artifact=create(ExecutionArtifactSchema,{name:name2,sandboxPath:planArtifactSandboxPath(name2),kind:ExecutionArtifactKind.FILE,sizeBytes:BigInt(content.length),storageKey,createdAt:utcTimestamp(),contentHash}),existingIdx=status.artifacts.findIndex(a=>isPlanArtifactName(a.name));existingIdx>=0?status.artifacts[existingIdx]=artifact:status.artifacts.push(artifact),console.log(`[plan-artifact] execution=${executionId} \u2014 published ${name2} (${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_crypto7,PLAN_ARTIFACT_NAME,PLAN_ARTIFACT_SUFFIX,MAX_PLAN_SLUG_LENGTH,PLAN_ID_LENGTH,ENCLOSING_MARKDOWN_FENCE_RE,ENCLOSING_BARE_FENCE_RE,LEADING_H1_RE,init_plan_artifact=__esm({"dist/shared/plan-artifact.js"(){"use strict";import_node_crypto7=require("node:crypto");init_esm4();init_artifact_pb();init_enum_pb();init_status2();PLAN_ARTIFACT_NAME="plan.md",PLAN_ARTIFACT_SUFFIX=".plan.md",MAX_PLAN_SLUG_LENGTH=60,PLAN_ID_LENGTH=8;ENCLOSING_MARKDOWN_FENCE_RE=/^(`{3,})[ \t]*(?:markdown|md)[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/i,ENCLOSING_BARE_FENCE_RE=/^(`{3,})[ \t]*\r?\n([\s\S]*?)\r?\n\1[ \t]*$/,LEADING_H1_RE=/^#[ \t]+(.+?)[ \t]*(?:\r?\n+|$)/}});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}}}});function applyTodoUpdate(target,rawTodos,opts){let{merge:merge4}=opts,now=opts.now??utcTimestamp();if(!Array.isArray(rawTodos)||rawTodos.length===0)return merge4?!1:(clearMap(target),!0);merge4||clearMap(target);for(let i2=0;i2<rawTodos.length;i2++){let raw=coerceRawTodo(rawTodos[i2]),id=raw.id||`todo-${i2}`,statusStr=(raw.status??"pending").toLowerCase(),status=STATUS_MAP[statusStr]??TodoStatus.TODO_PENDING,existing=merge4?target[id]:void 0;target[id]=create(TodoItemSchema,{id,content:raw.content??"",status,createdAt:existing?.createdAt||raw.created_at||now,updatedAt:now})}return!0}function coerceRawTodo(value){return typeof value=="object"&&value!==null?value:{}}function clearMap(target){for(let key of Object.keys(target))delete target[key]}var STATUS_MAP,init_todos=__esm({"dist/shared/todos.js"(){"use strict";init_esm4();init_todo_pb();init_enum_pb();init_status2();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}}});var TODO_TOOL_NAMES,TodoTracker,init_todo_tracker=__esm({"dist/activities/execute-cursor/todo-tracker.js"(){"use strict";init_todos();TODO_TOOL_NAMES=new Set(["TodoWrite","updateTodos"]),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;applyTodoUpdate(this.todos,args.todos,{merge:args.merge===!0})&&(this._isDirty=!0),Array.isArray(args.todos)&&args.todos.length>0&&console.log(`TodoTracker: processed ${args.todos.length} todo(s) from ${event.name} (merge=${args.merge===!0})`)}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}}}});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_promises4,import_node_path8,FileCursorEventRecorder,init_cursor_event_recorder=__esm({"dist/activities/execute-cursor/cursor-event-recorder.js"(){"use strict";import_promises4=require("node:fs/promises"),import_node_path8=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_promises4.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path8.join)(this.outputDir,`${this.executionId}.cursor-events.jsonl`);await(0,import_promises4.writeFile)(filePath,this.lines.join(`
|
|
162
162
|
`)+`
|
|
163
|
-
`),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 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 git2=entry.source.source.value;repos.push({url:git2.url,startingRef:git2.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_path9.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_path9,RUNNER_INTERNAL_MARKERS,init_blueprint_resolver=__esm({"dist/activities/execute-cursor/blueprint-resolver.js"(){"use strict";import_node_path9=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 getStigmerHome(){return process.env.HOME||process.env.USERPROFILE||(0,import_node_os3.homedir)()}function getSessionDir(sessionId){return(0,import_node_path10.join)(getStigmerHome(),".stigmer","sessions",sessionId)}function getHitlGateDir(workspaceRoot){let key=(0,import_node_crypto8.createHash)("sha256").update(workspaceRoot).digest("hex").slice(0,16);return(0,import_node_path10.join)(getStigmerHome(),".stigmer","hitl-gate",key)}async function ensureHitlGateDir(workspaceRoot){let dir=getHitlGateDir(workspaceRoot);return await(0,import_promises5.mkdir)(dir,{recursive:!0}),dir}function getPlatformDir(sessionId){return(0,import_node_path10.join)(getSessionDir(sessionId),"platform")}async function ensurePlatformDir(sessionId){let dir=getPlatformDir(sessionId);return await(0,import_promises5.mkdir)(dir,{recursive:!0}),dir}function getHitlDir(sessionId){return(0,import_node_path10.join)(getSessionDir(sessionId),"hitl")}async function ensureHitlDir(sessionId){let dir=getHitlDir(sessionId);return await(0,import_promises5.mkdir)(dir,{recursive:!0}),dir}var import_node_path10,import_promises5,import_node_os3,import_node_crypto8,init_platform_dir=__esm({"dist/shared/workspace/platform-dir.js"(){"use strict";import_node_path10=require("node:path"),import_promises5=require("node:fs/promises"),import_node_os3=require("node:os"),import_node_crypto8=require("node:crypto")}});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 basename7=name2.includes("/")?name2.slice(name2.lastIndexOf("/")+1):name2;return excludeSet.has(basename7)}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((resolve7,reject)=>{let inflate=(0,import_node_zlib.createInflateRaw)(),chunks=[];inflate.on("data",chunk=>chunks.push(chunk)),inflate.on("end",()=>resolve7(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 ensureStigmerSymlink(workspaceDir,platformDir){let linkPath=(0,import_node_path11.join)(workspaceDir,STIGMER_LOCAL_STATE_DIR);try{if(await(0,import_promises6.readlink)(linkPath)===platformDir)return;await(0,import_promises6.unlink)(linkPath)}catch(err){if(err.code!=="ENOENT")if(err.code==="EINVAL")await(0,import_promises6.rm)(linkPath,{recursive:!0,force:!0});else throw err}await(0,import_promises6.symlink)(platformDir,linkPath,"dir")}async function removeStigmerSymlink(workspaceDir){let linkPath=(0,import_node_path11.join)(workspaceDir,STIGMER_LOCAL_STATE_DIR);try{(await(0,import_promises6.lstat)(linkPath)).isSymbolicLink()&&await(0,import_promises6.unlink)(linkPath)}catch(err){err?.code!=="ENOENT"&&console.warn(`removeStigmerSymlink: failed to remove ${linkPath} (non-fatal): ${err instanceof Error?err.message:err}`)}}var import_promises6,import_node_path11,STIGMER_LOCAL_STATE_DIR,init_stigmer_link=__esm({"dist/activities/execute-cursor/stigmer-link.js"(){"use strict";import_promises6=require("node:fs/promises"),import_node_path11=require("node:path"),STIGMER_LOCAL_STATE_DIR=".stigmer"}});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_path12.join)(platformDir,SKILLS_SUBDIR);await(0,import_promises7.mkdir)(skillsDir,{recursive:!0}),await ensureStigmerSymlink(options.primaryWorkspaceDir,platformDir),console.log(`[resolveSkills] symlink created: ${(0,import_node_path12.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_path12.join)(skillsDir,name2);await(0,import_promises7.mkdir)(skillDir,{recursive:!0});let skillMdPath=(0,import_node_path12.join)(skillDir,"SKILL.md");if(await(0,import_promises7.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_path12.join)(skillDir,entry.path);await(0,import_promises7.mkdir)((0,import_node_path12.dirname)(filePath),{recursive:!0}),await(0,import_promises7.writeFile)(filePath,entry.content,"utf-8")}}let relativePath=(0,import_node_path12.join)(STIGMER_LOCAL_STATE_DIR,SKILLS_SUBDIR,name2,"SKILL.md");return{name:name2,description:spec.description||`Skill: ${name2}`,path:relativePath}}var import_promises7,import_node_path12,SKILLS_SUBDIR,init_skill_resolver=__esm({"dist/activities/execute-cursor/skill-resolver.js"(){"use strict";import_promises7=require("node:fs/promises"),import_node_path12=require("node:path");init_platform_dir();init_zip_extract();init_stigmer_link();SKILLS_SUBDIR="skills"}});async function resolveAttachments(attachments,options){if(attachments.length===0)return[];let platformDir=getPlatformDir(options.sessionId),inputsDir=(0,import_node_path13.join)(platformDir,INPUTS_SUBDIR);await(0,import_promises8.mkdir)(inputsDir,{recursive:!0}),await ensureStigmerSymlink(options.primaryWorkspaceDir,platformDir);let results=[];for(let attachment of attachments)results.push(await resolveAttachment(attachment,inputsDir,options));return console.log(`[attachment-resolver] resolved ${results.length} attachment(s): `+results.map(r=>r.relativePath).join(", ")),results}async function resolveAttachment(attachment,inputsDir,options){if(options.mode==="local"&&attachment.localPath){let filename2=attachment.filename||(0,import_node_path13.basename)(attachment.localPath);try{await(0,import_promises8.copyFile)(attachment.localPath,(0,import_node_path13.join)(inputsDir,filename2))}catch(err){throw new AttachmentResolutionError(attachment.filename,`failed to copy local file '${attachment.localPath}': ${err instanceof Error?err.message:String(err)}`)}return{filename:filename2,relativePath:(0,import_node_path13.join)(STIGMER_LOCAL_STATE_DIR,INPUTS_SUBDIR,filename2)}}if(!attachment.storageKey)throw new AttachmentResolutionError(attachment.filename,"missing storageKey \u2014 cannot download attachment from storage");if(!options.storage)throw new AttachmentResolutionError(attachment.filename,`artifact storage is unavailable, so this attachment (key: ${attachment.storageKey}) cannot be downloaded`);let filename=attachment.filename||(0,import_node_path13.basename)(attachment.storageKey),content;try{content=await options.storage.download(attachment.storageKey)}catch(err){throw new AttachmentResolutionError(attachment.filename,`failed to download from storage (key: ${attachment.storageKey}): ${err instanceof Error?err.message:String(err)}`)}return await(0,import_promises8.writeFile)((0,import_node_path13.join)(inputsDir,filename),content),{filename,relativePath:(0,import_node_path13.join)(STIGMER_LOCAL_STATE_DIR,INPUTS_SUBDIR,filename)}}var import_promises8,import_node_path13,INPUTS_SUBDIR,AttachmentResolutionError,init_attachment_resolver=__esm({"dist/activities/execute-cursor/attachment-resolver.js"(){"use strict";import_promises8=require("node:fs/promises"),import_node_path13=require("node:path");init_platform_dir();init_stigmer_link();INPUTS_SUBDIR="inputs",AttachmentResolutionError=class extends Error{attachmentFilename;reason;constructor(attachmentFilename,reason){super(`Attachment '${attachmentFilename}': ${reason}`),this.name="AttachmentResolutionError",this.attachmentFilename=attachmentFilename,this.reason=reason}}}});var PLAN_MODE_DIRECTIVE,init_plan_mode_prompt=__esm({"dist/shared/plan-mode-prompt.js"(){"use strict";PLAN_MODE_DIRECTIVE=["IMPORTANT: You are in Plan mode \u2014 a read-only analysis turn whose deliverable is an implementation plan.","","Constraints:","- Do NOT create, edit, or delete any files.","- Do NOT run commands that modify the filesystem or any external state.","- Only read, search, and analyze.","","Deliverable \u2014 your FINAL message IS the plan. It is published verbatim as a plan document that the user reviews and builds from, so:","- Write it as a complete, well-structured markdown document: start with a single `#` title and organize the work under `##` section headings. Use lists and tables where they aid scanning.",'- Give the `#` title a concise, descriptive name for the work itself; do NOT prefix it with "Plan:" (this document is already a plan \u2014 the prefix is redundant and leaks into the plan\'s filename).',"- Reference concrete file paths and describe the specific changes planned for each.","- Do NOT wrap the document in a code fence.","- When quoting content that itself contains fenced code blocks (e.g. a proposed file section with a code sample inside), open the outer fence with MORE backticks than any inner fence (four or more) \u2014 a same-length inner closer would terminate the outer fence early and corrupt the rendered document.","- Fenced ```mermaid blocks at the top level of the document render as diagrams in the plan viewer. When a diagram helps communicate the design (architecture, flows), include it directly in the plan body \u2014 not only inside quoted file content, where it stays unrendered source.",`- Do NOT end with conversational closers ("Let me know...", "Shall I proceed?") \u2014 the next step is the user's Build action, and trailing chat would be published as part of the document.`].join(`
|
|
163
|
+
`),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 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 git2=entry.source.source.value;repos.push({url:git2.url,startingRef:git2.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_path9.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_path9,RUNNER_INTERNAL_MARKERS,init_blueprint_resolver=__esm({"dist/activities/execute-cursor/blueprint-resolver.js"(){"use strict";import_node_path9=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 getStigmerHome(){return process.env.HOME||process.env.USERPROFILE||(0,import_node_os3.homedir)()}function getSessionDir(sessionId){return(0,import_node_path10.join)(getStigmerHome(),".stigmer","sessions",sessionId)}function getHitlGateDir(workspaceRoot){let key=(0,import_node_crypto8.createHash)("sha256").update(workspaceRoot).digest("hex").slice(0,16);return(0,import_node_path10.join)(getStigmerHome(),".stigmer","hitl-gate",key)}async function ensureHitlGateDir(workspaceRoot){let dir=getHitlGateDir(workspaceRoot);return await(0,import_promises5.mkdir)(dir,{recursive:!0}),dir}function getPlatformDir(sessionId){return(0,import_node_path10.join)(getSessionDir(sessionId),"platform")}async function ensurePlatformDir(sessionId){let dir=getPlatformDir(sessionId);return await(0,import_promises5.mkdir)(dir,{recursive:!0}),dir}function getHitlDir(sessionId){return(0,import_node_path10.join)(getSessionDir(sessionId),"hitl")}async function ensureHitlDir(sessionId){let dir=getHitlDir(sessionId);return await(0,import_promises5.mkdir)(dir,{recursive:!0}),dir}var import_node_path10,import_promises5,import_node_os3,import_node_crypto8,init_platform_dir=__esm({"dist/shared/workspace/platform-dir.js"(){"use strict";import_node_path10=require("node:path"),import_promises5=require("node:fs/promises"),import_node_os3=require("node:os"),import_node_crypto8=require("node:crypto")}});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 basename7=name2.includes("/")?name2.slice(name2.lastIndexOf("/")+1):name2;return excludeSet.has(basename7)}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((resolve7,reject)=>{let inflate=(0,import_node_zlib.createInflateRaw)(),chunks=[];inflate.on("data",chunk=>chunks.push(chunk)),inflate.on("end",()=>resolve7(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 ensureStigmerSymlink(workspaceDir,platformDir){let linkPath=(0,import_node_path11.join)(workspaceDir,STIGMER_LOCAL_STATE_DIR);try{if(await(0,import_promises6.readlink)(linkPath)===platformDir)return;await(0,import_promises6.unlink)(linkPath)}catch(err){if(err.code!=="ENOENT")if(err.code==="EINVAL")await(0,import_promises6.rm)(linkPath,{recursive:!0,force:!0});else throw err}await(0,import_promises6.symlink)(platformDir,linkPath,"dir")}async function removeStigmerSymlink(workspaceDir){let linkPath=(0,import_node_path11.join)(workspaceDir,STIGMER_LOCAL_STATE_DIR);try{(await(0,import_promises6.lstat)(linkPath)).isSymbolicLink()&&await(0,import_promises6.unlink)(linkPath)}catch(err){err?.code!=="ENOENT"&&console.warn(`removeStigmerSymlink: failed to remove ${linkPath} (non-fatal): ${err instanceof Error?err.message:err}`)}}var import_promises6,import_node_path11,STIGMER_LOCAL_STATE_DIR,init_stigmer_link=__esm({"dist/shared/workspace/stigmer-link.js"(){"use strict";import_promises6=require("node:fs/promises"),import_node_path11=require("node:path"),STIGMER_LOCAL_STATE_DIR=".stigmer"}});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_path12.join)(platformDir,SKILLS_SUBDIR);await(0,import_promises7.mkdir)(skillsDir,{recursive:!0}),await ensureStigmerSymlink(options.primaryWorkspaceDir,platformDir),console.log(`[resolveSkills] symlink created: ${(0,import_node_path12.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_path12.join)(skillsDir,name2);await(0,import_promises7.mkdir)(skillDir,{recursive:!0});let skillMdPath=(0,import_node_path12.join)(skillDir,"SKILL.md");if(await(0,import_promises7.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_path12.join)(skillDir,entry.path);await(0,import_promises7.mkdir)((0,import_node_path12.dirname)(filePath),{recursive:!0}),await(0,import_promises7.writeFile)(filePath,entry.content,"utf-8")}}let relativePath=(0,import_node_path12.join)(STIGMER_LOCAL_STATE_DIR,SKILLS_SUBDIR,name2,"SKILL.md");return{name:name2,description:spec.description||`Skill: ${name2}`,path:relativePath}}var import_promises7,import_node_path12,SKILLS_SUBDIR,init_skill_resolver=__esm({"dist/activities/execute-cursor/skill-resolver.js"(){"use strict";import_promises7=require("node:fs/promises"),import_node_path12=require("node:path");init_platform_dir();init_zip_extract();init_stigmer_link();SKILLS_SUBDIR="skills"}});async function resolveAttachments(attachments,options){if(attachments.length===0)return[];let platformDir=getPlatformDir(options.sessionId),inputsDir=(0,import_node_path13.join)(platformDir,INPUTS_SUBDIR);await(0,import_promises8.mkdir)(inputsDir,{recursive:!0}),await ensureStigmerSymlink(options.primaryWorkspaceDir,platformDir);let results=[];for(let attachment of attachments)results.push(await resolveAttachment(attachment,inputsDir,options));return console.log(`[attachment-resolver] resolved ${results.length} attachment(s): `+results.map(r=>r.relativePath).join(", ")),results}async function resolveAttachment(attachment,inputsDir,options){if(options.mode==="local"&&attachment.localPath){let filename2=attachment.filename||(0,import_node_path13.basename)(attachment.localPath);try{await(0,import_promises8.copyFile)(attachment.localPath,(0,import_node_path13.join)(inputsDir,filename2))}catch(err){throw new AttachmentResolutionError(attachment.filename,`failed to copy local file '${attachment.localPath}': ${err instanceof Error?err.message:String(err)}`)}return{filename:filename2,relativePath:(0,import_node_path13.join)(STIGMER_LOCAL_STATE_DIR,INPUTS_SUBDIR,filename2)}}if(!attachment.storageKey)throw new AttachmentResolutionError(attachment.filename,"missing storageKey \u2014 cannot download attachment from storage");if(!options.storage)throw new AttachmentResolutionError(attachment.filename,`artifact storage is unavailable, so this attachment (key: ${attachment.storageKey}) cannot be downloaded`);let filename=attachment.filename||(0,import_node_path13.basename)(attachment.storageKey),content;try{content=await options.storage.download(attachment.storageKey)}catch(err){throw new AttachmentResolutionError(attachment.filename,`failed to download from storage (key: ${attachment.storageKey}): ${err instanceof Error?err.message:String(err)}`)}return await(0,import_promises8.writeFile)((0,import_node_path13.join)(inputsDir,filename),content),{filename,relativePath:(0,import_node_path13.join)(STIGMER_LOCAL_STATE_DIR,INPUTS_SUBDIR,filename)}}var import_promises8,import_node_path13,INPUTS_SUBDIR,AttachmentResolutionError,init_attachment_resolver=__esm({"dist/activities/execute-cursor/attachment-resolver.js"(){"use strict";import_promises8=require("node:fs/promises"),import_node_path13=require("node:path");init_platform_dir();init_stigmer_link();INPUTS_SUBDIR="inputs",AttachmentResolutionError=class extends Error{attachmentFilename;reason;constructor(attachmentFilename,reason){super(`Attachment '${attachmentFilename}': ${reason}`),this.name="AttachmentResolutionError",this.attachmentFilename=attachmentFilename,this.reason=reason}}}});var PLAN_MODE_DIRECTIVE,init_plan_mode_prompt=__esm({"dist/shared/plan-mode-prompt.js"(){"use strict";PLAN_MODE_DIRECTIVE=["IMPORTANT: You are in Plan mode \u2014 a read-only analysis turn whose deliverable is an implementation plan.","","Constraints:","- Do NOT create, edit, or delete any files.","- Do NOT run commands that modify the filesystem or any external state.","- Only read, search, and analyze.","","Deliverable \u2014 your FINAL message IS the plan. It is published verbatim as a plan document that the user reviews and builds from, so:","- Write it as a complete, well-structured markdown document: start with a single `#` title and organize the work under `##` section headings. Use lists and tables where they aid scanning.",'- Give the `#` title a concise, descriptive name for the work itself; do NOT prefix it with "Plan:" (this document is already a plan \u2014 the prefix is redundant and leaks into the plan\'s filename).',"- Reference concrete file paths and describe the specific changes planned for each.","- Do NOT wrap the document in a code fence.","- When quoting content that itself contains fenced code blocks (e.g. a proposed file section with a code sample inside), open the outer fence with MORE backticks than any inner fence (four or more) \u2014 a same-length inner closer would terminate the outer fence early and corrupt the rendered document.","- Fenced ```mermaid blocks at the top level of the document render as diagrams in the plan viewer. When a diagram helps communicate the design (architecture, flows), include it directly in the plan body \u2014 not only inside quoted file content, where it stays unrendered source.",`- Do NOT end with conversational closers ("Let me know...", "Shall I proceed?") \u2014 the next step is the user's Build action, and trailing chat would be published as part of the document.`].join(`
|
|
164
164
|
`)}});function findApprovedPlanPath(attachmentPaths){return attachmentPaths.find(p=>{let name2=p.split("/").pop();return name2!==void 0&&isPlanArtifactName(name2)})}function buildImplementPlanDirective(planPath){return planPath?["IMPORTANT: This turn implements a plan the user has reviewed and APPROVED.","",`The approved plan document is attached at \`${planPath}\`. Read it FIRST, then implement it step by step.`,"","That document is the authoritative version of the plan \u2014 the user may have edited it after it was proposed, so where it differs from the conversation above, follow the document.","",TRACK_PROGRESS_INSTRUCTION].join(`
|
|
165
165
|
`):["IMPORTANT: This turn implements a plan the user has reviewed and APPROVED.","","Implement the plan proposed in the conversation above, step by step.","",TRACK_PROGRESS_INSTRUCTION].join(`
|
|
166
166
|
`)}var TRACK_PROGRESS_INSTRUCTION,init_implement_plan_prompt=__esm({"dist/shared/implement-plan-prompt.js"(){"use strict";init_plan_artifact();TRACK_PROGRESS_INSTRUCTION=["Track your progress with your to-do list so the user can follow the build:","- Before you start, break the plan into a concrete, ordered to-do list \u2014 roughly one item per implementation step.","- As you work, keep it current: mark each item in progress when you begin it and completed when it is done."].join(`
|
|
@@ -2284,11 +2284,11 @@ Your task: {description}`,BUILTIN_DESCRIPTIONS=new Map([["explore","Read-only co
|
|
|
2284
2284
|
`}});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_zod4()}});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),artifactStorage=await resolveUsableArtifactStorage(loadArtifactStorageConfig(config4),{executionId});await reportSetupProgress(client2,executionId,"Initializing workspace\u2026");let{workspaceBackend,provisionResults}=await provisionWorkspace(config4,session,envResult.mergedEnvVars,sessionId),gitWorkspace=await isGitWorkTree(workspaceBackend.rootDir),captureMode=deriveCaptureMode(workspaceBackend.rootDir,gitWorkspace,!!artifactStorage),isCapturablePath=gitWorkspace?rawPath=>isPathCapturable(workspaceBackend.rootDir,resolveWorkspacePath(rawPath,workspaceBackend.rootDir,!0).path):_rawPath=>Promise.resolve(!1),casObserver=new CasCaptureObserver({rootDir:workspaceBackend.rootDir,isIgnored:gitWorkspace?async relPath=>!await isPathCapturable(workspaceBackend.rootDir,relPath):async()=>!0}),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,interactionMode:execution.spec.executionConfig?.interactionMode,buildFromPlan:execution.spec.executionConfig?.buildFromPlan}),requestTimeoutMs=parseInt(process.env.STIGMER_LLM_REQUEST_TIMEOUT_MS??"0")||void 0,{model}=await buildChatModel({modelName,proxyEndpoint:config4.proxyEndpoint??void 0,stigmerToken:config4.stigmerToken??void 0,headerScope:{executionId},timeoutMs:requestTimeoutMs});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 leases=deriveActiveLeases(execution),globalBypass=leases.global,agentOverrides=agent.spec.mcpServerUsages?.flatMap(u=>u.toolApprovalOverrides??[])??[],approvalPolicies=mergeApprovalPolicies(resolvedMcpServers?.resolvedServers??[],agentOverrides,leases),approvalGateConfig=globalBypass?null:{policies:approvalPolicies,leasedCategories:leases.categories,toolServerMap,fingerprintKey:deriveExecutionFingerprintKey(getRunnerHitlMasterSecret(),executionId),executionId,fileCaptureMode:captureMode,isCapturablePath,captureIgnored:captureMode&&!!artifactStorage,recordBlockedSecret:rawPath=>casObserver.recordBlockedSecret(rawPath)},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:approvalGateConfig}),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,approvalGate:approvalGateConfig,casObserver,parentModelName:modelName,parentHasNativeThinking:_modelHasNativeThinking(modelName),costCap:costCapMiddleware??void 0,modelFactory:async m=>(await buildChatModel({modelName:m,proxyEndpoint:config4.proxyEndpoint??void 0,stigmerToken:config4.stigmerToken??void 0,headerScope:{executionId}})).model})}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"}],fileBackend=new CasCaptureFilesystemBackend({rootDir:workspaceBackend.rootDir},{observer:casObserver}),agentGraph=await createDeepAgent({model,checkpointer,backend:fileBackend,systemPrompt,tools:tools3,middleware,subagents:compiledSubagents??void 0,...responseFormat?{responseFormat}:{},...isPlanMode?{permissions:planModePermissions}:{}}),userMessage=execution.spec.message;outputSchema&&(userMessage+=`
|
|
2285
2285
|
|
|
2286
2286
|
---
|
|
2287
|
-
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,leasedCategories:leases.categories,globalBypass,hasStructuredOutput:!!outputSchema,streamVersion,casObserver,captureMode,gitWorkspace}}catch(err){if(mcpConnection)try{await mcpConnection.client.close()}catch{}throw err}}async function provisionWorkspace(config4,session,mergedEnvVars,sessionId){let platformDir=await ensurePlatformDir(sessionId),workspaceEntries=session.spec.workspaceEntries||[];if(workspaceEntries.length===0){let sessionRoot=await resolveSessionWorkspaceRoot(config4.workspaceRootDir,workspaceEntries,sessionId);return{workspaceBackend:new LocalWorkspaceBackend(sessionRoot,platformDir),provisionResults:[]}}let workspaceBackend=new LocalWorkspaceBackend(config4.workspaceRootDir,platformDir),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_factory();init_mcp_manager();init_mcp_resolver2();init_connect_backfill();init_provisioner();init_local_backend();init_cas_capture_backend();init_cas_capture_observer();init_git_substrate();init_capture();init_file_change();init_platform_dir();init_session_root();init_status2();init_environment();init_prompt_builder2();init_middleware4();init_approval_fingerprint();init_fingerprint_secret();init_model_pricing2();init_model_registry();init_model_client();init_artifact_storage();init_approval_policy();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 stampApprovalProvenance(tc,provider){if(!provider)return;let serverSlug=tc.mcpServerSlug||provider.toolServerMap.get(tc.name)||"",source=resolveApprovalProvenance(tc.name,serverSlug,provider.policies,provider.leasedCategories??NO_LEASED_CATEGORIES2,provider.globalBypass);tc.approvalPolicySource=toProtoPolicySource(source),source&&(tc.policyEngineVersion=POLICY_ENGINE_VERSION)}var UsageAccumulator2,NO_LEASED_CATEGORIES2,init_status_builder_shared=__esm({"dist/activities/execute-deep-agent/status-builder-shared.js"(){"use strict";init_esm4();init_usage_pb();init_status2();init_approval_policy();init_args_preview();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())}};NO_LEASED_CATEGORIES2=new Set}});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_policy();init_tool_kind();init_todos();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.messages.length>0&&this.state.rebuildToolCallIndex(),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 toolName=event.name??"unknown_tool",seeded=this.findResumableSeededToolCall(toolName);if(seeded){seeded.status=ToolCallStatus.TOOL_CALL_RUNNING,this.state.toolCalls.set(event.run_id,seeded),this.state.toolStartTimes.set(event.run_id,performance.now()),this._forceNextUpdate=!0;return}let parentMsg=this.state.currentAiMessage.get(namespace)??this.ensureAiMessageForToolCall(event.run_id,namespace);if(!parentMsg)return;let 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),stampApprovalProvenance(tc,this.approvalProvider),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}findResumableSeededToolCall(toolName){for(let tc of this.state.toolCalls.values())if(tc.name===toolName&&tc.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL)return tc}checkApprovalRequirement(toolName,args){if(!this.approvalProvider)return{requiresApproval:!1,message:"",serverSlug:""};let serverSlug=this.approvalProvider.toolServerMap.get(toolName)??"";if(this.approvalProvider.globalBypass)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage(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.toolKind===ToolKind.TODO&&applyTodoUpdate(this.state.proto.todos,tc.args?.todos,{merge:!1})),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_promises22,import_node_path29,FileV2EventRecorder,init_event_recorder=__esm({"dist/activities/execute-deep-agent/event-recorder.js"(){"use strict";import_promises22=require("node:fs/promises"),import_node_path29=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_promises22.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path29.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_promises22.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_promises23,import_node_path30,FileV3EventRecorder,init_v3_event_recorder=__esm({"dist/activities/execute-deep-agent/v3-event-recorder.js"(){"use strict";import_promises23=require("node:fs/promises"),import_node_path30=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_promises23.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path30.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_promises23.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_policy();init_tool_kind();init_todos();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.messages.length>0&&this.state.rebuildToolCallIndex(),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 existing=this.state.toolCalls.get(callId);if(existing){existing.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL&&(existing.status=ToolCallStatus.TOOL_CALL_RUNNING),Object.keys(input).length>0&&!existing.args&&(existing.args=input),this.state.toolStartTimes.set(callId,performance.now()),this._forceNextUpdate=!0;return}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),stampApprovalProvenance(tc,this.approvalProvider),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),tc.toolKind===ToolKind.TODO&&applyTodoUpdate(this.state.proto.todos,tc.args?.todos,{merge:!1}),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.globalBypass)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage(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()}}}});var StreamingSideEffects,init_streaming_side_effects=__esm({"dist/activities/execute-deep-agent/streaming-side-effects.js"(){"use strict";init_file_tools();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 cached4=this.inputCache.get(callId);if(this.inputCache.delete(callId),!cached4||!isFileModifyingTool(cached4.toolName))return;let filePath=extractFilePath(cached4.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 statusToPersist=statusBuilder.currentStatus;await deps.beforePersist?.(statusToPersist);let signal=await persistStatus(client2,executionId,statusToPersist,{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(resolve7=>setTimeout(()=>resolve7(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 statusToPersist=statusBuilder.currentStatus;await deps.beforePersist?.(statusToPersist);let signal=await persistStatus(client2,executionId,statusToPersist,{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(!isFileModifyingTool(toolName))return null;let input=event.data?.input;return input?extractFilePath(input):null}var DEFAULT_STALL_TIMEOUT_MS2,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();init_file_tools();DEFAULT_STALL_TIMEOUT_MS2=12e4;StallTimeoutError2=class extends Error{constructor(message){super(message),this.name="StallTimeoutError"}}}});function normalizePath(path6){return path6.replace(/^\/+/,"")}function sha2563(content){return(0,import_node_crypto15.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_crypto15,import_node_path31,InlinePublisher,CONTENT_TYPE_MAP,init_inline_publisher=__esm({"dist/activities/execute-deep-agent/inline-publisher.js"(){"use strict";import_node_crypto15=require("node:crypto"),import_node_path31=require("node:path");init_esm4();init_artifact_pb();init_enum_pb();init_status2();init_secret_paths();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){if(this.artifactStorage)try{let sandboxPath=normalizePath(path6);if(isSecretLikePath(sandboxPath)){console.log(`[InlinePublisher] execution=${this.executionId} \u2014 withheld '${sandboxPath}' (secret-like; never published to artifact storage)`);return}let 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_path31.basename)(sandboxPath),storageKey=`artifacts/${this.executionId}/${fileName}`;await this.artifactStorage.upload(storageKey,contentBuffer,guessContentType(fileName));let artifact=create(ExecutionArtifactSchema,{name:fileName,sandboxPath,kind:ExecutionArtifactKind.FILE,sizeBytes:BigInt(contentBuffer.length),storageKey,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.
|
|
2287
|
+
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,leasedCategories:leases.categories,globalBypass,hasStructuredOutput:!!outputSchema,streamVersion,casObserver,captureMode,gitWorkspace}}catch(err){if(mcpConnection)try{await mcpConnection.client.close()}catch{}throw err}}async function provisionWorkspace(config4,session,mergedEnvVars,sessionId){let platformDir=await ensurePlatformDir(sessionId),workspaceEntries=session.spec.workspaceEntries||[];if(workspaceEntries.length===0){let sessionRoot=await resolveSessionWorkspaceRoot(config4.workspaceRootDir,workspaceEntries,sessionId);return{workspaceBackend:new LocalWorkspaceBackend(sessionRoot,platformDir),provisionResults:[]}}let workspaceBackend=new LocalWorkspaceBackend(config4.workspaceRootDir,platformDir),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_factory();init_mcp_manager();init_mcp_resolver2();init_connect_backfill();init_provisioner();init_local_backend();init_cas_capture_backend();init_cas_capture_observer();init_git_substrate();init_capture();init_file_change();init_platform_dir();init_session_root();init_status2();init_environment();init_prompt_builder2();init_middleware4();init_approval_fingerprint();init_fingerprint_secret();init_model_pricing2();init_model_registry();init_model_client();init_artifact_storage();init_approval_policy();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 stampApprovalProvenance(tc,provider){if(!provider)return;let serverSlug=tc.mcpServerSlug||provider.toolServerMap.get(tc.name)||"",source=resolveApprovalProvenance(tc.name,serverSlug,provider.policies,provider.leasedCategories??NO_LEASED_CATEGORIES2,provider.globalBypass);tc.approvalPolicySource=toProtoPolicySource(source),source&&(tc.policyEngineVersion=POLICY_ENGINE_VERSION)}var UsageAccumulator2,NO_LEASED_CATEGORIES2,init_status_builder_shared=__esm({"dist/activities/execute-deep-agent/status-builder-shared.js"(){"use strict";init_esm4();init_usage_pb();init_status2();init_approval_policy();init_args_preview();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())}};NO_LEASED_CATEGORIES2=new Set}});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_policy();init_tool_kind();init_todos();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.messages.length>0&&this.state.rebuildToolCallIndex(),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 toolName=event.name??"unknown_tool",seeded=this.findResumableSeededToolCall(toolName);if(seeded){seeded.status=ToolCallStatus.TOOL_CALL_RUNNING,this.state.toolCalls.set(event.run_id,seeded),this.state.toolStartTimes.set(event.run_id,performance.now()),this._forceNextUpdate=!0;return}let parentMsg=this.state.currentAiMessage.get(namespace)??this.ensureAiMessageForToolCall(event.run_id,namespace);if(!parentMsg)return;let 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),stampApprovalProvenance(tc,this.approvalProvider),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}findResumableSeededToolCall(toolName){for(let tc of this.state.toolCalls.values())if(tc.name===toolName&&tc.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL)return tc}checkApprovalRequirement(toolName,args){if(!this.approvalProvider)return{requiresApproval:!1,message:"",serverSlug:""};let serverSlug=this.approvalProvider.toolServerMap.get(toolName)??"";if(this.approvalProvider.globalBypass)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage(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.toolKind===ToolKind.TODO&&applyTodoUpdate(this.state.proto.todos,tc.args?.todos,{merge:!1})),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_promises22,import_node_path29,FileV2EventRecorder,init_event_recorder=__esm({"dist/activities/execute-deep-agent/event-recorder.js"(){"use strict";import_promises22=require("node:fs/promises"),import_node_path29=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_promises22.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path29.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_promises22.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_promises23,import_node_path30,FileV3EventRecorder,init_v3_event_recorder=__esm({"dist/activities/execute-deep-agent/v3-event-recorder.js"(){"use strict";import_promises23=require("node:fs/promises"),import_node_path30=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_promises23.mkdir)(this.outputDir,{recursive:!0});let filePath=(0,import_node_path30.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_promises23.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_policy();init_tool_kind();init_todos();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.messages.length>0&&this.state.rebuildToolCallIndex(),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 existing=this.state.toolCalls.get(callId);if(existing){existing.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL&&(existing.status=ToolCallStatus.TOOL_CALL_RUNNING),Object.keys(input).length>0&&!existing.args&&(existing.args=input),this.state.toolStartTimes.set(callId,performance.now()),this._forceNextUpdate=!0;return}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),stampApprovalProvenance(tc,this.approvalProvider),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),tc.toolKind===ToolKind.TODO&&applyTodoUpdate(this.state.proto.todos,tc.args?.todos,{merge:!1}),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.globalBypass)return{requiresApproval:!1,message:"",serverSlug};if(serverSlug){let key=`${serverSlug}/${toolName}`,policy=this.approvalProvider.policies.get(key);return policy?.requiresApproval?{requiresApproval:!0,message:resolveApprovalMessage(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()}}}});var StreamingSideEffects,init_streaming_side_effects=__esm({"dist/activities/execute-deep-agent/streaming-side-effects.js"(){"use strict";init_file_tools();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 cached4=this.inputCache.get(callId);if(this.inputCache.delete(callId),!cached4||!isFileModifyingTool(cached4.toolName))return;let filePath=extractFilePath(cached4.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 statusToPersist=statusBuilder.currentStatus;await deps.beforePersist?.(statusToPersist);let signal=await persistStatus(client2,executionId,statusToPersist,{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(resolve7=>setTimeout(()=>resolve7(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 statusToPersist=statusBuilder.currentStatus;await deps.beforePersist?.(statusToPersist);let signal=await persistStatus(client2,executionId,statusToPersist,{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(!isFileModifyingTool(toolName))return null;let input=event.data?.input;return input?extractFilePath(input):null}var DEFAULT_STALL_TIMEOUT_MS2,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();init_file_tools();DEFAULT_STALL_TIMEOUT_MS2=12e4;StallTimeoutError2=class extends Error{constructor(message){super(message),this.name="StallTimeoutError"}}}});function normalizePath(path6){return path6.replace(/^\/+/,"")}function sha2563(content){return(0,import_node_crypto15.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_crypto15,import_node_path31,InlinePublisher,CONTENT_TYPE_MAP,init_inline_publisher=__esm({"dist/activities/execute-deep-agent/inline-publisher.js"(){"use strict";import_node_crypto15=require("node:crypto"),import_node_path31=require("node:path");init_esm4();init_artifact_pb();init_enum_pb();init_status2();init_secret_paths();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){if(this.artifactStorage)try{let sandboxPath=normalizePath(path6);if(isSecretLikePath(sandboxPath)){console.log(`[InlinePublisher] execution=${this.executionId} \u2014 withheld '${sandboxPath}' (secret-like; never published to artifact storage)`);return}let 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_path31.basename)(sandboxPath),storageKey=`artifacts/${this.executionId}/${fileName}`;await this.artifactStorage.upload(storageKey,contentBuffer,guessContentType(fileName));let artifact=create(ExecutionArtifactSchema,{name:fileName,sandboxPath,kind:ExecutionArtifactKind.FILE,sizeBytes:BigInt(contentBuffer.length),storageKey,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 gitCommitAsAgent(commitMsg){return`git ${AGENT_GIT_IDENTITY_FLAGS} commit -m "${commitMsg}"`}var AGENT_GIT_AUTHOR_NAME,AGENT_GIT_AUTHOR_EMAIL,AGENT_GIT_IDENTITY_FLAGS,init_git_identity=__esm({"dist/shared/workspace/git-identity.js"(){"use strict";AGENT_GIT_AUTHOR_NAME="Stigmer Agent",AGENT_GIT_AUTHOR_EMAIL="noreply@stigmer.ai",AGENT_GIT_IDENTITY_FLAGS=`-c user.name='${AGENT_GIT_AUTHOR_NAME}' -c user.email='${AGENT_GIT_AUTHOR_EMAIL}'`}});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();init_git_identity();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(gitCommitAsAgent(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.
|
|
2288
2288
|
|
|
2289
2289
|
**Execution:** \`${this.executionId}\`
|
|
2290
2290
|
**Workspace:** \`${entryName}\`
|
|
2291
|
-
`,resp=await fetch(`https://api.github.com/repos/${entryState.githubOwner}/${entryState.githubRepo}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${entryState.githubToken}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:prTitle,body:prBody,head:this.branchName,base:entry.baseBranch})});if(!resp.ok){let body=await resp.text();throw new Error(`GitHub API error (HTTP ${resp.status}): ${body}`)}let data=await resp.json();entryState.prCreated=!0,entryState.prUrl=data.html_url??"",entryState.prNumber=data.number??0,console.log(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 PR #${entryState.prNumber} created: ${entryState.prUrl}`)}async updateStatus(entryName,entryState,entry,exec2){let summaryOutput=await exec2(`git diff --stat ${entry.baseBranch}...HEAD`).catch(()=>""),phase=entryState.prCreated?WorkspaceWriteBackPhase.WORKSPACE_WRITE_BACK_PR_CREATED:WorkspaceWriteBackPhase.WORKSPACE_WRITE_BACK_PUSHED,wb=create(WorkspaceWriteBackSchema,{workspaceEntryName:entryName,branchName:this.branchName,baseBranch:entry.baseBranch,commitSha:entryState.lastCommitSha,pullRequestUrl:entryState.prUrl,pullRequestNumber:entryState.prNumber,diffSummary:summaryOutput.trim(),phase});this.statusWriter.addWriteBack(wb)}async withLock(entryName,fn){let next=(this.locks.get(entryName)??Promise.resolve()).then(fn,fn);this.locks.set(entryName,next),await next}}}});async function autoPublishWrittenFiles(status,inlinePublisher){let alreadyPublished=inlinePublisher.publishedPaths,pathsToPublish=[];for(let message of status.messages)for(let tc of message.toolCalls){if(!FILE_MODIFYING_TOOLS2.has(tc.name))continue;let filePath=extractFilePath2(tc.args);if(!filePath)continue;let normalized=filePath.replace(/^\/+/,"");alreadyPublished.has(normalized)||pathsToPublish.includes(normalized)||pathsToPublish.push(normalized)}let count=0;for(let path6 of pathsToPublish)try{await inlinePublisher.publish(path6),count++}catch{}return count>0&&console.log(`[autoPublish] Published ${count} additional artifact(s) via safety net`),count}function extractFilePath2(args){return args?typeof args.path=="string"?args.path:typeof args.file_path=="string"?args.file_path:typeof args.filename=="string"?args.filename:typeof args.file=="string"?args.file:null:null}var FILE_MODIFYING_TOOLS2,init_auto_publish=__esm({"dist/activities/execute-deep-agent/auto-publish.js"(){"use strict";FILE_MODIFYING_TOOLS2=new Set(["write_file","edit_file","create_file","write","edit","create","str_replace_editor"])}});async function processPostStream(opts){let{status,inlinePublisher,writebackCoordinator,pendingPublishPromises,pendingWritebackPromises,executionId}=opts;if(status.phase===ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL||status.phase===ExecutionPhase.EXECUTION_PAUSED){let phaseName=status.phase===ExecutionPhase.EXECUTION_PAUSED?"PAUSED":"WAITING_FOR_APPROVAL";(pendingPublishPromises.length>0||pendingWritebackPromises.length>0)&&(await Promise.allSettled([...pendingPublishPromises,...pendingWritebackPromises]),console.log(`[postStream] execution=${executionId} \u2014 drained pending promises (phase is ${phaseName})`));return}if(pendingPublishPromises.length>0)try{await Promise.allSettled(pendingPublishPromises),console.log(`[postStream] execution=${executionId} \u2014 drained ${pendingPublishPromises.length} pending publish task(s)`)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 error draining publish tasks: ${err}`)}if(pendingWritebackPromises.length>0)try{await Promise.allSettled(pendingWritebackPromises),console.log(`[postStream] execution=${executionId} \u2014 drained ${pendingWritebackPromises.length} pending writeback task(s)`)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 error draining writeback tasks: ${err}`)}try{await autoPublishWrittenFiles(status,inlinePublisher)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 auto-publish safety net error: ${err}`)}if(writebackCoordinator)try{await writebackCoordinator.finalize(),console.log(`[postStream] execution=${executionId} \u2014 writeback finalize complete`)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 writeback finalize error: ${err}`)}}var init_post_stream=__esm({"dist/activities/execute-deep-agent/post-stream.js"(){"use strict";init_enum_pb();init_auto_publish()}});function resolveResumeInput(execution,graphState,userMessage){let pendingInterrupts=extractPendingInterrupts(graphState);if(pendingInterrupts.length===0)return{graphInput:{messages:[{role:"user",content:userMessage}]},isResumeFromApproval:!1,hasRejection:!1,rejectionReason:""};let decisions=extractApprovalDecisions(execution);if(decisions.size===0)return{graphInput:{messages:[{role:"user",content:userMessage}]},isResumeFromApproval:!1,hasRejection:!1,rejectionReason:""};let resumeDict={},hasRejection=!1,rejectionReason="";for(let intr of pendingInterrupts){let toolCallId=intr.toolCallId,decision=decisions.get(toolCallId);if(!decision)continue;let actionStr=ACTION_MAP.get(decision.action);actionStr&&(resumeDict[intr.interruptId]={action:actionStr,...decision.comment?{comment:decision.comment}:{}},decision.action===ApprovalAction.REJECT&&(hasRejection=!0,rejectionReason=decision.comment||"Rejected by user"))}return Object.keys(resumeDict).length===0?{graphInput:{messages:[{role:"user",content:userMessage}]},isResumeFromApproval:!1,hasRejection:!1,rejectionReason:""}:(console.log(`[hitl] Building resume for ${Object.keys(resumeDict).length} interrupt(s), rejection=${hasRejection}`),{graphInput:new Command({resume:resumeDict}),isResumeFromApproval:!0,hasRejection,rejectionReason})}function extractPendingInterrupts(state){let result=[];for(let task2 of state.tasks)if(task2.interrupts)for(let intr of task2.interrupts){if(intr.resumeValue!==void 0)continue;let value=intr.value;if(typeof value=="object"&&value!==null){let toolCallId=value.tool_call_id;typeof toolCallId=="string"&&toolCallId&&result.push({interruptId:intr.id??task2.id,toolCallId})}}return result}function extractApprovalDecisions(execution){let decisions=new Map,status=execution.status;if(!status)return decisions;for(let message of status.messages)for(let tc of message.toolCalls)tc.approvalAction!==ApprovalAction.UNSPECIFIED&&tc.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL&&decisions.set(tc.id,{action:tc.approvalAction,comment:""});return decisions}var ACTION_MAP,init_hitl2=__esm({"dist/activities/execute-deep-agent/hitl.js"(){"use strict";init_dist4();init_enum_pb();ACTION_MAP=new Map([[ApprovalAction.APPROVE,"approve"],[ApprovalAction.APPROVE_ALL,"approve"],[ApprovalAction.SKIP,"skip"],[ApprovalAction.REJECT,"reject"]])}});function findAiMessageToolCallArgs(messages,toolCallId){for(let msg of messages){if(!msg||typeof msg!="object")continue;let toolCalls=msg.tool_calls;if(Array.isArray(toolCalls))for(let tc of toolCalls){if(!tc||typeof tc!="object")continue;let entry=tc;if(entry.id===toolCallId)return entry.args&&typeof entry.args=="object"&&!Array.isArray(entry.args)?entry.args:{}}}}function captureApprovalArtifacts(opts){let args=findAiMessageToolCallArgs(opts.messages,opts.toolCallId);return!args||Object.keys(args).length===0?{}:{argsPreview:sanitizeArgsPreview(args)||void 0}}var init_approval_file_change=__esm({"dist/activities/execute-deep-agent/approval-file-change.js"(){"use strict";init_status_builder_shared()}});function stampFlowedFileEditRows2(messages,changeSetId,skipToolCallIds){for(let msg of messages)for(let tc of msg.toolCalls){if(tc.fileChangeSetId||skipToolCallIds?.has(tc.id)||isToolCallRowHidden(tc))continue;let category=toolApprovalCategory(tc.name);category!=="write"&&category!=="delete"||stampFileEditRow(tc,changeSetId)}}function stampFlowedSubAgentFileEditRows(subAgents,changeSetId,priorToolCallIds){for(let sa of subAgents)stampFlowedFileEditRows2(sa.messages,changeSetId,priorToolCallIds)}var init_stamp_flowed_rows=__esm({"dist/activities/execute-deep-agent/stamp-flowed-rows.js"(){"use strict";init_tool_kind();init_tool_row()}});function deriveTurnCommandProvenance2(inputs){let{status,priorSettledToolCallIds,priorSubAgentToolCallIds,globalBypass}=inputs;for(let id of collectSubAgentToolCallIds(status.subAgentExecutions))if(!priorSubAgentToolCallIds.has(id))return;let messages=status.messages,turnToolCalls=messages.flatMap(m=>m.toolCalls).filter(tc=>!priorSettledToolCallIds.has(tc.id));return qualifyTurnCommandProvenance({turnToolCalls,messages,isExecutedCommand:tc=>tc.status===ToolCallStatus.TOOL_CALL_COMPLETED,resolveDirectConsent:tc=>tc.approvalAction===ApprovalAction.APPROVE||tc.approvalAction===ApprovalAction.APPROVE_ALL?tc.id:void 0,globalBypass})}var init_command_provenance3=__esm({"dist/activities/execute-deep-agent/command-provenance.js"(){"use strict";init_enum_pb();init_command_provenance();init_tool_row()}});var extract_json_exports={};__export(extract_json_exports,{extractJsonFromText:()=>extractJsonFromText});function extractJsonFromText(text){if(!text)return;let trimmed=text.trim(),direct=tryParse(trimmed);if(direct!==void 0)return direct;let fenced=extractFromCodeFences(trimmed);if(fenced!==void 0)return fenced;let braced=extractLastJsonObject(trimmed);if(braced!==void 0)return braced}function extractFromCodeFences(text){let fences=[],match;for(;(match=CODE_FENCE_RE.exec(text))!==null;)fences.push(match[1]);CODE_FENCE_RE.lastIndex=0;for(let i2=fences.length-1;i2>=0;i2--){let content=fences[i2].trim();if(!content.startsWith("{")&&!content.startsWith("["))continue;let result=tryParse(content);if(result!==void 0)return result}}function extractLastJsonObject(text){let lastClose=text.lastIndexOf("}");if(lastClose===-1)return;let depth=0,inString=!1,escaped=!1;for(let i2=lastClose;i2>=0;i2--){let ch=text[i2];if(inString){if(escaped){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}ch==='"'&&(inString=!1);continue}if(ch==='"'){inString=!0;continue}if(ch==="}")depth++;else if(ch==="{"&&(depth--,depth===0)){let candidate=text.slice(i2,lastClose+1);return tryParse(candidate)}}}function tryParse(candidate){try{return JSON.parse(candidate)}catch{}let repaired=stripTrailingCommas(candidate);if(repaired!==candidate)try{return JSON.parse(repaired)}catch{}}function stripTrailingCommas(json5){return json5.replace(/,\s*([}\]])/g,"$1")}var CODE_FENCE_RE,init_extract_json=__esm({"dist/shared/extract-json.js"(){"use strict";CODE_FENCE_RE=/```(?:json|JSON)?\s*\n([\s\S]*?)```/g}});var execute_deep_agent_exports={};__export(execute_deep_agent_exports,{createDeepAgentActivities:()=>createDeepAgentActivities});function createDeepAgentActivities(config4){let client2=new StigmerClient({endpoint:config4.stigmerBackendEndpoint,token:config4.stigmerToken,tokenRef:config4.stigmerTokenRef}),streamingConfig=loadStreamingConfig();return{ExecuteDeepAgent:async(arg0,arg1)=>{let{executionId,threadId,turnSeq}=normalizeActivityInput(arg0,arg1);activityStarted();let setup=null,releaseWorkspaceLock;try{console.log(`[ExecuteDeepAgent] Started for execution ${executionId}`),setup=await performSetup({config:config4,client:client2,executionId,threadId});let statusOffload=setup.artifactStorage?{artifactStorage:setup.artifactStorage,executionId}:void 0,graphState=await setup.agentGraph.getState(setup.langgraphConfig),initialStatus=shouldSeedFromPersistedTranscript(setup.execution)?seedStatusFromExecution(setup.execution):create(AgentExecutionStatusSchema,{}),statusBuilder=new StatusBuilder(executionId,initialStatus);statusBuilder.setApprovalProvider({policies:setup.approvalPolicies,toolServerMap:setup.toolServerMap,leasedCategories:setup.leasedCategories,globalBypass:setup.globalBypass});let resume=resolveResumeInput(setup.execution,graphState,setup.execution.spec.message);if(resume.hasRejection){let failedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_FAILED,error:`Execution rejected: ${resume.rejectionReason}`,completedAt:utcTimestamp(),messages:[create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Execution rejected by user: ${resume.rejectionReason}`,timestamp:utcTimestamp()})]});return await persistStatus(client2,executionId,failedStatus,{offload:statusOffload}),slimStatus(failedStatus)}let effectiveInput=resume.isResumeFromApproval?resume.graphInput:setup.langgraphInput,inlinePublisher=new InlinePublisher({workspaceBackend:setup.workspaceBackend,artifactStorage:setup.artifactStorage,statusWriter:statusBuilder,executionId}),workspaceEntries=setup.session.spec?.workspaceEntries??[],writebackCoordinator=setup.provisionResults.length>0?new WriteBackCoordinator({statusWriter:statusBuilder,executionId,provisionResults:setup.provisionResults,workspaceEntries,workspaceBackend:setup.workspaceBackend}):null,gitRoot=setup.workspaceBackend.rootDir,changeSetId=`${executionId}:${turnSeq}`;try{releaseWorkspaceLock=await acquireWorkspaceLock(gitRoot,{onWaiting:()=>reportSetupProgress(client2,executionId,"Waiting for workspace \u2014 in use by another session"),heartbeat:()=>import_activity3.Context.current().heartbeat(),signal:import_activity3.Context.current().cancellationSignal,timeoutMs:config4.workspaceLockTimeoutMs})}catch(lockErr){if(lockErr instanceof WorkspaceLockCancelledError)throw new import_activity3.CancelledFailure("Activity cancelled while waiting for the workspace lock");if(lockErr instanceof WorkspaceLockTimeoutError){let failedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_FAILED,error:lockErr.message,completedAt:utcTimestamp(),messages:[create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Execution failed: ${lockErr.message}`,timestamp:utcTimestamp()})]});return await persistStatus(client2,executionId,failedStatus,{offload:statusOffload}),slimStatus(failedStatus)}throw lockErr}if(setup.captureMode){let decidedSets=(setup.execution.status?.fileChangeSets??[]).filter(cs=>cs.status===FileChangeSetStatus.DECIDED),reconciledAny=!1,reconcileFailed=!1,reconcileFailureDetail="",casReadBlob=setup.artifactStorage?casBlobReader(setup.artifactStorage):void 0;for(let changeSet of decidedSets){let capResult=await applyCaptureDecisions({status:initialStatus,gitRoot,executionId,changeSet,harnessId:DEEP_AGENT_HARNESS_ID,storage:setup.artifactStorage,readBlob:casReadBlob,gitWorkspace:setup.gitWorkspace});capResult.isCaptureTurn&&(reconciledAny=!0,capResult.failed&&(reconcileFailed=!0,reconcileFailureDetail=capResult.failureDetail??"file review reconcile failed"))}if(reconciledAny){if(reconcileFailed)return initialStatus.phase=ExecutionPhase.EXECUTION_FAILED,initialStatus.error=`File review reconcile failed: ${reconcileFailureDetail}`,initialStatus.completedAt=utcTimestamp(),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),slimStatus(initialStatus);if(!hasPendingToolApprovals(setup.execution)){initialStatus.phase=ExecutionPhase.EXECUTION_COMPLETED,initialStatus.completedAt=utcTimestamp(),writebackCoordinator&&await processCaptureWriteback(writebackCoordinator,executionId),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload});let slim2=slimStatus(initialStatus),lastAi=[...initialStatus.messages].reverse().find(m=>m.type===MessageType.MESSAGE_AI);return lastAi?.content&&(slim2.final_text=lastAi.content),initialStatus.structuredOutput!==void 0&&(slim2.structured=initialStatus.structuredOutput),slim2}}}let captureBaselineTree="",priorSubAgentToolCallIds=collectSubAgentToolCallIds(initialStatus.subAgentExecutions),priorSettledToolCallIds=collectSettledToolCallIds(initialStatus.messages);setup.captureMode&&(captureBaselineTree=await captureBaselineToLedger({status:initialStatus,gitRoot,executionId,changeSetId,harnessId:DEEP_AGENT_HARNESS_ID,gitWorkspace:setup.gitWorkspace}));let progressState=newProgressCaptureState(),casObserver=setup.casObserver,readObserverTouched=()=>({before:new Map(casObserver.before),blockedSecretPaths:new Set(casObserver.blockedSecretPaths)}),progressSubstrate=setup.captureMode?setup.gitWorkspace?captureBaselineTree?createHybridProgressSubstrate(createGitProgressSubstrate({workspaceRoot:gitRoot,executionId,baselineTree:captureBaselineTree}),createCasProgressSubstrate({workspaceRoot:gitRoot,read:readObserverTouched})):void 0:createCasProgressSubstrate({workspaceRoot:gitRoot,read:readObserverTouched}):void 0,cancellationSignal=import_activity3.Context.current().cancellationSignal,result=await streamExecution({agentGraph:setup.agentGraph,langgraphInput:effectiveInput,langgraphConfig:setup.langgraphConfig,executionId,client:client2,initialStatus,streamingConfig,offload:statusOffload,gracefulStop:setup.gracefulStop,inlinePublisher,writebackCoordinator:setup.captureMode?void 0:writebackCoordinator??void 0,heartbeatFn:details=>import_activity3.Context.current().heartbeat(details),isCancelledFn:()=>cancellationSignal.aborted,approvalProvider:{policies:setup.approvalPolicies,toolServerMap:setup.toolServerMap,leasedCategories:setup.leasedCategories,globalBypass:setup.globalBypass},streamVersion:setup.streamVersion,beforePersist:async status=>{progressSubstrate&&await captureFileChangeProgress({status,changeSetId,substrate:progressSubstrate,state:progressState})}});await processPostStream({status:initialStatus,inlinePublisher,writebackCoordinator:setup.captureMode?null:writebackCoordinator,pendingPublishPromises:result.pendingPublishPromises,pendingWritebackPromises:result.pendingWritebackPromises,executionId}),withholdSecretContentFromMessages(initialStatus.messages,initialStatus.subAgentExecutions);let fileReviewPending=!1,abnormalTerminal=!!result.terminalStatus&&initialStatus.phase!==ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL;if(setup.captureMode&&!abnormalTerminal){let casCaptureClass=setup.gitWorkspace?FileCaptureClass.GIT_IGNORED_CAPTURED:FileCaptureClass.NON_GIT_CAS,{casCaptures,unreviewablePaths}=await buildCasTurnCaptures2(setup.casObserver,gitRoot,casCaptureClass),commandProvenance=deriveTurnCommandProvenance2({status:initialStatus,priorSettledToolCallIds,priorSubAgentToolCallIds,globalBypass:setup.globalBypass});commandProvenance&&console.log(`[ExecuteDeepAgent] capture: turn qualifies for approved-command auto-keep (consent rows: ${commandProvenance.consentToolCallIds.join(",")||"(auto_approve_all)"}); attaching provenance to candidate (execution=${executionId})`),await captureCandidateToLedger({status:initialStatus,gitRoot,executionId,changeSetId,baselineTree:captureBaselineTree,harnessId:DEEP_AGENT_HARNESS_ID,casCaptures,storage:setup.artifactStorage,unreviewablePaths,unreviewableCaptureClass:casCaptureClass,gitWorkspace:setup.gitWorkspace,commandProvenance}),fileReviewPending=hasCandidateCaptured(initialStatus,changeSetId),fileReviewPending&&(stampFlowedFileEditRows2(initialStatus.messages,changeSetId),stampFlowedSubAgentFileEditRows(initialStatus.subAgentExecutions,changeSetId,priorSubAgentToolCallIds))}if(result.terminalStatus){if(initialStatus.phase===ExecutionPhase.EXECUTION_PAUSED)throw await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),console.log(`[ExecuteDeepAgent] Paused for execution ${executionId}: events=${result.eventsProcessed}`),new import_activity3.CancelledFailure("Activity paused by orchestrator");return setup.captureMode&&!abnormalTerminal?(await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),slimStatus(initialStatus)):result.terminalStatus}if(!setup.globalBypass){let postStreamGraphState=await setup.agentGraph.getState(setup.langgraphConfig),graphMessages=postStreamGraphState.values.messages,aiMessages=Array.isArray(graphMessages)?graphMessages:[],pendingInterrupts=detectPendingInterrupts(postStreamGraphState);if(pendingInterrupts.length>0){console.log(`[ExecuteDeepAgent] Detected ${pendingInterrupts.length} pending interrupt(s) for execution ${executionId} \u2014 setting WAITING_FOR_APPROVAL`),initialStatus.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL;let aiMsg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});for(let intr of pendingInterrupts){let toolCall=create(ToolCallSchema,{id:intr.toolCallId,name:intr.toolName,status:ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,requiresApproval:!0,approvalMessage:intr.message,approvalRequestedAt:utcTimestamp(),mcpServerSlug:intr.mcpServerSlug,startedAt:utcTimestamp(),toolKind:classifyTool(intr.toolName,intr.mcpServerSlug),approvalPolicySource:toProtoPolicySource(intr.policySource),policyEngineVersion:intr.policySource?POLICY_ENGINE_VERSION:""}),{argsPreview}=captureApprovalArtifacts({toolCallId:intr.toolCallId,messages:aiMessages});argsPreview&&(toolCall.argsPreview=argsPreview),aiMsg.toolCalls.push(toolCall)}return initialStatus.messages.push(aiMsg),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),slimStatus(initialStatus)}}let completeNow=!fileReviewPending;initialStatus.phase=completeNow?ExecutionPhase.EXECUTION_COMPLETED:ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL,completeNow&&(initialStatus.completedAt=utcTimestamp());let structuredOutput,finalText,lastAiMsg=[...initialStatus.messages].reverse().find(m=>m.type===MessageType.MESSAGE_AI);if(lastAiMsg&&(finalText=lastAiMsg.content),setup.hasStructuredOutput){let sr=result.runOutput?.structuredResponse;if(sr!=null&&typeof sr=="object"&&!Array.isArray(sr)?structuredOutput=sr:sr!==void 0&&console.warn(`[ExecuteDeepAgent] structuredResponse is not a plain object for execution ${executionId}: type=${typeof sr}`),structuredOutput===void 0&&finalText){let{extractJsonFromText:extractJsonFromText2}=await Promise.resolve().then(()=>(init_extract_json(),extract_json_exports)),extracted=extractJsonFromText2(finalText);extracted!=null&&typeof extracted=="object"&&!Array.isArray(extracted)&&(structuredOutput=extracted,console.log(`[ExecuteDeepAgent] structured output extracted from final text for execution ${executionId}: finalTextLength=${finalText.length}`))}structuredOutput!==void 0&&(initialStatus.structuredOutput=structuredOutput)}if(setup.execution.spec?.executionConfig?.interactionMode===InteractionMode.PLAN&&finalText&&setup.artifactStorage&&await publishPlanArtifact({status:initialStatus,executionId,planText:finalText,artifactStorage:setup.artifactStorage}),setup.captureMode&&completeNow&&writebackCoordinator&&await processCaptureWriteback(writebackCoordinator,executionId),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),console.log(`[ExecuteDeepAgent] ${completeNow?"Completed":"Awaiting file review for"} execution ${executionId}: events=${result.eventsProcessed}, messages=${initialStatus.messages.length}, artifacts=${initialStatus.artifacts.length}, writebacks=${initialStatus.workspaceWriteBacks.length}, hasStructuredOutput=${structuredOutput!==void 0}`),!completeNow)return slimStatus(initialStatus);let slim=slimStatus(initialStatus);return finalText!==void 0&&(slim.final_text=finalText),structuredOutput!==void 0&&(slim.structured=structuredOutput),slim}catch(err){if(err instanceof import_activity3.CancelledFailure){console.log(`[ExecuteDeepAgent] Cancelled (pause) for execution ${executionId}`);let pausedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_PAUSED});throw await persistStatus(client2,executionId,pausedStatus).catch(()=>{}),err}if(import_activity3.Context.current().cancellationSignal.aborted){console.log(`[ExecuteDeepAgent] Error during cancellation for ${executionId}, treating as pause: ${err}`);let pausedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_PAUSED});throw await persistStatus(client2,executionId,pausedStatus).catch(()=>{}),new import_activity3.CancelledFailure("Activity paused by orchestrator (error during cancellation)")}let errorMessage=err instanceof Error?err.message:String(err),errorType=err instanceof Error?err.constructor.name:"UnknownError";console.error(`[ExecuteDeepAgent] Failed for execution ${executionId}: [${errorType}] ${errorMessage}`);let failedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_FAILED,error:`Execution failed: [${errorType}] ${errorMessage}`,completedAt:utcTimestamp(),messages:[create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Error: [${errorType}] ${errorMessage}`,timestamp:utcTimestamp()})]});return await persistStatus(client2,executionId,failedStatus),slimStatus(failedStatus)}finally{await cleanup(setup),await releaseWorkspaceLock?.(),activityFinished()}}}}function detectPendingInterrupts(graphState){return graphState.tasks?.flatMap(task2=>(task2.interrupts??[]).filter(intr=>intr.resumeValue===void 0).map(intr=>{let val=intr.value;return{toolCallId:val?.tool_call_id??"",toolName:val?.tool_name??"",mcpServerSlug:val?.mcp_server_slug??"",message:val?.message??"",policySource:val?.policy_source||void 0}}))??[]}function hasPendingToolApprovals(execution){let status=execution.status;if(!status)return!1;let anyWaiting=msgs=>msgs.some(m=>m.toolCalls.some(tc=>tc.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL));return anyWaiting(status.messages)?!0:status.subAgentExecutions.some(sa=>anyWaiting(sa.messages))}async function buildCasTurnCaptures2(observer,workspaceRoot,captureClass){let{capturablePaths,unreviewablePaths}=partitionIgnoredPathsBySecret(observer.before.keys(),observer.blockedSecretPaths),casCaptures=[];for(let relPath of capturablePaths){let after=await readFileOrNull3((0,import_node_path32.join)(workspaceRoot,relPath));casCaptures.push({path:relPath,before:observer.before.get(relPath)??null,after,captureClass})}return{casCaptures,unreviewablePaths:[...unreviewablePaths]}}async function readFileOrNull3(absolutePath){try{return await(0,import_promises24.readFile)(absolutePath)}catch{return null}}async function processCaptureWriteback(writebackCoordinator,executionId){await writebackCoordinator.finalize(),console.log(`[ExecuteDeepAgent] capture writeback finalized for execution ${executionId}`)}function shouldSeedFromPersistedTranscript(execution){return(execution.status?.messages.length??0)>0}function seedStatusFromExecution(execution){let seeded=clone(AgentExecutionStatusSchema,execution.status);return seeded.completedAt="",seeded.error="",seeded}async function cleanup(setup){if(setup&&setup.mcpConnection)try{await setup.mcpConnection.client.close()}catch(err){console.warn("[ExecuteDeepAgent] MCP connection cleanup failed:",err)}}var import_promises24,import_node_path32,import_activity3,DEEP_AGENT_HARNESS_ID,init_execute_deep_agent=__esm({"dist/activities/execute-deep-agent/index.js"(){"use strict";import_promises24=require("node:fs/promises"),import_node_path32=require("node:path"),import_activity3=__toESM(require_lib4(),1);init_esm4();init_api_pb3();init_message_pb();init_enum_pb();init_idle_watchdog();init_activity_input();init_status2();init_workspace_lock();init_plan_artifact();init_tool_kind();init_approval_policy();init_stigmer_client();init_setup();init_streaming5();init_streaming_scheduler();init_status_builder();init_inline_publisher();init_writeback_coordinator();init_post_stream();init_hitl2();init_approval_file_change();init_capture();init_progress();init_cas_progress();init_events();init_cas_substrate();init_secret_paths();init_tool_row();init_stamp_flowed_rows();init_command_provenance3();DEEP_AGENT_HARNESS_ID="deep-agent"}});var ensure_thread_exports={};__export(ensure_thread_exports,{createEnsureThreadActivities:()=>createEnsureThreadActivities});function createEnsureThreadActivities(){return{EnsureThread:async(sessionId,agentId)=>{activityStarted();try{if(sessionId){let threadId2=`thread-${sessionId}`;return console.log(`[EnsureThread] Session-based thread: ${threadId2}`),threadId2}let threadId=`ephemeral-${agentId}-${(0,import_node_crypto16.randomUUID)().replace(/-/g,"").slice(0,8)}`;return console.log(`[EnsureThread] Ephemeral thread: ${threadId}`),threadId}finally{activityFinished()}}}}var import_node_crypto16,init_ensure_thread=__esm({"dist/activities/ensure-thread.js"(){"use strict";import_node_crypto16=require("node:crypto");init_idle_watchdog()}});var classify_tool_approvals_exports={};__export(classify_tool_approvals_exports,{buildToolsPayload:()=>buildToolsPayload,classifyTools:()=>classifyTools,createClassifyToolApprovalsActivities:()=>createClassifyToolApprovalsActivities,fallbackApprovals:()=>fallbackApprovals,reconcileBatchClassifications:()=>reconcileBatchClassifications});async function classifyTools(input,options){let{tools:tools3,serverName,serverDescription,mcpServerId}=input;if(tools3.length===0)return[];let model=await getSummarizationModel(options.primaryModel),batches=[];for(let i2=0;i2<tools3.length;i2+=BATCH_SIZE)batches.push(tools3.slice(i2,i2+BATCH_SIZE));console.log(`[ClassifyToolApprovals] Classifying ${tools3.length} tools for '${serverName}' using model '${model}' (${batches.length} batch(es) of up to ${BATCH_SIZE})`);let allApprovals=[];for(let batchIdx=0;batchIdx<batches.length;batchIdx++){let batch=batches[batchIdx];try{let batchResult=await classifyBatch({batch,serverName,serverDescription,model,proxyEndpoint:options.proxyEndpoint,stigmerToken:options.stigmerToken,mcpServerId:mcpServerId??null,batchIdx,totalBatches:batches.length}),{reconciled,failedClosedCount}=reconcileBatchClassifications(batch,batchResult);failedClosedCount>0&&console.warn(`[ClassifyToolApprovals] Batch ${batchIdx+1}/${batches.length} for '${serverName}': ${failedClosedCount} tool(s) missing from classifier output \u2014 failing closed (requires_approval=true)`),allApprovals.push(...reconciled)}catch(err){console.error(`[ClassifyToolApprovals] Batch ${batchIdx+1}/${batches.length} failed for '${serverName}' (${batch.length} tools) \u2014 falling back to requires_approval=true`,err),allApprovals.push(...fallbackApprovals(batch))}}let approved=allApprovals.filter(a=>a.requires_approval);return console.log(`[ClassifyToolApprovals] Classification complete for '${serverName}': ${approved.length}/${allApprovals.length} tools require approval`),approved}async function classifyBatch(params){let{batch,serverName,serverDescription,model,proxyEndpoint,stigmerToken,mcpServerId,batchIdx,totalBatches}=params,maxTokens=Math.max(MIN_MAX_TOKENS,batch.length*MAX_TOKENS_PER_TOOL),{model:llm}=await buildChatModel({modelName:model,proxyEndpoint,stigmerToken:stigmerToken??void 0,headerScope:{mcpServerId:mcpServerId??void 0},maxTokens}),structuredLlm=llm.withStructuredOutput(ClassifyToolApprovalsOutputSchema),toolsPayload=buildToolsPayload(batch),userPrompt=`MCP Server: ${serverName}
|
|
2291
|
+
`,resp=await fetch(`https://api.github.com/repos/${entryState.githubOwner}/${entryState.githubRepo}/pulls`,{method:"POST",headers:{Authorization:`Bearer ${entryState.githubToken}`,Accept:"application/vnd.github+json","Content-Type":"application/json"},body:JSON.stringify({title:prTitle,body:prBody,head:this.branchName,base:entry.baseBranch})});if(!resp.ok){let body=await resp.text();throw new Error(`GitHub API error (HTTP ${resp.status}): ${body}`)}let data=await resp.json();entryState.prCreated=!0,entryState.prUrl=data.html_url??"",entryState.prNumber=data.number??0,console.log(`[WriteBack] execution=${this.executionId} entry=${entryName} \u2014 PR #${entryState.prNumber} created: ${entryState.prUrl}`)}async updateStatus(entryName,entryState,entry,exec2){let summaryOutput=await exec2(`git diff --stat ${entry.baseBranch}...HEAD`).catch(()=>""),phase=entryState.prCreated?WorkspaceWriteBackPhase.WORKSPACE_WRITE_BACK_PR_CREATED:WorkspaceWriteBackPhase.WORKSPACE_WRITE_BACK_PUSHED,wb=create(WorkspaceWriteBackSchema,{workspaceEntryName:entryName,branchName:this.branchName,baseBranch:entry.baseBranch,commitSha:entryState.lastCommitSha,pullRequestUrl:entryState.prUrl,pullRequestNumber:entryState.prNumber,diffSummary:summaryOutput.trim(),phase});this.statusWriter.addWriteBack(wb)}async withLock(entryName,fn){let next=(this.locks.get(entryName)??Promise.resolve()).then(fn,fn);this.locks.set(entryName,next),await next}}}});async function autoPublishWrittenFiles(status,inlinePublisher){let alreadyPublished=inlinePublisher.publishedPaths,pathsToPublish=[];for(let message of status.messages)for(let tc of message.toolCalls){if(!FILE_MODIFYING_TOOLS2.has(tc.name))continue;let filePath=extractFilePath2(tc.args);if(!filePath)continue;let normalized=filePath.replace(/^\/+/,"");alreadyPublished.has(normalized)||pathsToPublish.includes(normalized)||pathsToPublish.push(normalized)}let count=0;for(let path6 of pathsToPublish)try{await inlinePublisher.publish(path6),count++}catch{}return count>0&&console.log(`[autoPublish] Published ${count} additional artifact(s) via safety net`),count}function extractFilePath2(args){return args?typeof args.path=="string"?args.path:typeof args.file_path=="string"?args.file_path:typeof args.filename=="string"?args.filename:typeof args.file=="string"?args.file:null:null}var FILE_MODIFYING_TOOLS2,init_auto_publish=__esm({"dist/activities/execute-deep-agent/auto-publish.js"(){"use strict";FILE_MODIFYING_TOOLS2=new Set(["write_file","edit_file","create_file","write","edit","create","str_replace_editor"])}});async function processPostStream(opts){let{status,inlinePublisher,writebackCoordinator,pendingPublishPromises,pendingWritebackPromises,executionId}=opts;if(status.phase===ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL||status.phase===ExecutionPhase.EXECUTION_PAUSED){let phaseName=status.phase===ExecutionPhase.EXECUTION_PAUSED?"PAUSED":"WAITING_FOR_APPROVAL";(pendingPublishPromises.length>0||pendingWritebackPromises.length>0)&&(await Promise.allSettled([...pendingPublishPromises,...pendingWritebackPromises]),console.log(`[postStream] execution=${executionId} \u2014 drained pending promises (phase is ${phaseName})`));return}if(pendingPublishPromises.length>0)try{await Promise.allSettled(pendingPublishPromises),console.log(`[postStream] execution=${executionId} \u2014 drained ${pendingPublishPromises.length} pending publish task(s)`)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 error draining publish tasks: ${err}`)}if(pendingWritebackPromises.length>0)try{await Promise.allSettled(pendingWritebackPromises),console.log(`[postStream] execution=${executionId} \u2014 drained ${pendingWritebackPromises.length} pending writeback task(s)`)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 error draining writeback tasks: ${err}`)}try{await autoPublishWrittenFiles(status,inlinePublisher)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 auto-publish safety net error: ${err}`)}if(writebackCoordinator)try{await writebackCoordinator.finalize(),console.log(`[postStream] execution=${executionId} \u2014 writeback finalize complete`)}catch(err){console.warn(`[postStream] execution=${executionId} \u2014 writeback finalize error: ${err}`)}}var init_post_stream=__esm({"dist/activities/execute-deep-agent/post-stream.js"(){"use strict";init_enum_pb();init_auto_publish()}});function resolveResumeInput(execution,graphState,userMessage){let pendingInterrupts=extractPendingInterrupts(graphState);if(pendingInterrupts.length===0)return{graphInput:{messages:[{role:"user",content:userMessage}]},isResumeFromApproval:!1,hasRejection:!1,rejectionReason:""};let decisions=extractApprovalDecisions(execution);if(decisions.size===0)return{graphInput:{messages:[{role:"user",content:userMessage}]},isResumeFromApproval:!1,hasRejection:!1,rejectionReason:""};let resumeDict={},hasRejection=!1,rejectionReason="";for(let intr of pendingInterrupts){let toolCallId=intr.toolCallId,decision=decisions.get(toolCallId);if(!decision)continue;let actionStr=ACTION_MAP.get(decision.action);actionStr&&(resumeDict[intr.interruptId]={action:actionStr,...decision.comment?{comment:decision.comment}:{}},decision.action===ApprovalAction.REJECT&&(hasRejection=!0,rejectionReason=decision.comment||"Rejected by user"))}return Object.keys(resumeDict).length===0?{graphInput:{messages:[{role:"user",content:userMessage}]},isResumeFromApproval:!1,hasRejection:!1,rejectionReason:""}:(console.log(`[hitl] Building resume for ${Object.keys(resumeDict).length} interrupt(s), rejection=${hasRejection}`),{graphInput:new Command({resume:resumeDict}),isResumeFromApproval:!0,hasRejection,rejectionReason})}function extractPendingInterrupts(state){let result=[];for(let task2 of state.tasks)if(task2.interrupts)for(let intr of task2.interrupts){if(intr.resumeValue!==void 0)continue;let value=intr.value;if(typeof value=="object"&&value!==null){let toolCallId=value.tool_call_id;typeof toolCallId=="string"&&toolCallId&&result.push({interruptId:intr.id??task2.id,toolCallId})}}return result}function extractApprovalDecisions(execution){let decisions=new Map,status=execution.status;if(!status)return decisions;for(let message of status.messages)for(let tc of message.toolCalls)tc.approvalAction!==ApprovalAction.UNSPECIFIED&&tc.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL&&decisions.set(tc.id,{action:tc.approvalAction,comment:""});return decisions}var ACTION_MAP,init_hitl2=__esm({"dist/activities/execute-deep-agent/hitl.js"(){"use strict";init_dist4();init_enum_pb();ACTION_MAP=new Map([[ApprovalAction.APPROVE,"approve"],[ApprovalAction.APPROVE_ALL,"approve"],[ApprovalAction.SKIP,"skip"],[ApprovalAction.REJECT,"reject"]])}});function findAiMessageToolCallArgs(messages,toolCallId){for(let msg of messages){if(!msg||typeof msg!="object")continue;let toolCalls=msg.tool_calls;if(Array.isArray(toolCalls))for(let tc of toolCalls){if(!tc||typeof tc!="object")continue;let entry=tc;if(entry.id===toolCallId)return entry.args&&typeof entry.args=="object"&&!Array.isArray(entry.args)?entry.args:{}}}}function captureApprovalArtifacts(opts){let args=findAiMessageToolCallArgs(opts.messages,opts.toolCallId);return!args||Object.keys(args).length===0?{}:{argsPreview:sanitizeArgsPreview(args)||void 0}}var init_approval_file_change=__esm({"dist/activities/execute-deep-agent/approval-file-change.js"(){"use strict";init_status_builder_shared()}});function stampFlowedFileEditRows2(messages,changeSetId,skipToolCallIds){for(let msg of messages)for(let tc of msg.toolCalls){if(tc.fileChangeSetId||skipToolCallIds?.has(tc.id)||isToolCallRowHidden(tc))continue;let category=toolApprovalCategory(tc.name);category!=="write"&&category!=="delete"||stampFileEditRow(tc,changeSetId)}}function stampFlowedSubAgentFileEditRows(subAgents,changeSetId,priorToolCallIds){for(let sa of subAgents)stampFlowedFileEditRows2(sa.messages,changeSetId,priorToolCallIds)}var init_stamp_flowed_rows=__esm({"dist/activities/execute-deep-agent/stamp-flowed-rows.js"(){"use strict";init_tool_kind();init_tool_row()}});function deriveTurnCommandProvenance2(inputs){let{status,priorSettledToolCallIds,priorSubAgentToolCallIds,globalBypass}=inputs;for(let id of collectSubAgentToolCallIds(status.subAgentExecutions))if(!priorSubAgentToolCallIds.has(id))return;let messages=status.messages,turnToolCalls=messages.flatMap(m=>m.toolCalls).filter(tc=>!priorSettledToolCallIds.has(tc.id));return qualifyTurnCommandProvenance({turnToolCalls,messages,isExecutedCommand:tc=>tc.status===ToolCallStatus.TOOL_CALL_COMPLETED,resolveDirectConsent:tc=>tc.approvalAction===ApprovalAction.APPROVE||tc.approvalAction===ApprovalAction.APPROVE_ALL?tc.id:void 0,globalBypass})}var init_command_provenance3=__esm({"dist/activities/execute-deep-agent/command-provenance.js"(){"use strict";init_enum_pb();init_command_provenance();init_tool_row()}});var extract_json_exports={};__export(extract_json_exports,{extractJsonFromText:()=>extractJsonFromText});function extractJsonFromText(text){if(!text)return;let trimmed=text.trim(),direct=tryParse(trimmed);if(direct!==void 0)return direct;let fenced=extractFromCodeFences(trimmed);if(fenced!==void 0)return fenced;let braced=extractLastJsonObject(trimmed);if(braced!==void 0)return braced}function extractFromCodeFences(text){let fences=[],match;for(;(match=CODE_FENCE_RE.exec(text))!==null;)fences.push(match[1]);CODE_FENCE_RE.lastIndex=0;for(let i2=fences.length-1;i2>=0;i2--){let content=fences[i2].trim();if(!content.startsWith("{")&&!content.startsWith("["))continue;let result=tryParse(content);if(result!==void 0)return result}}function extractLastJsonObject(text){let lastClose=text.lastIndexOf("}");if(lastClose===-1)return;let depth=0,inString=!1,escaped=!1;for(let i2=lastClose;i2>=0;i2--){let ch=text[i2];if(inString){if(escaped){escaped=!1;continue}if(ch==="\\"){escaped=!0;continue}ch==='"'&&(inString=!1);continue}if(ch==='"'){inString=!0;continue}if(ch==="}")depth++;else if(ch==="{"&&(depth--,depth===0)){let candidate=text.slice(i2,lastClose+1);return tryParse(candidate)}}}function tryParse(candidate){try{return JSON.parse(candidate)}catch{}let repaired=stripTrailingCommas(candidate);if(repaired!==candidate)try{return JSON.parse(repaired)}catch{}}function stripTrailingCommas(json5){return json5.replace(/,\s*([}\]])/g,"$1")}var CODE_FENCE_RE,init_extract_json=__esm({"dist/shared/extract-json.js"(){"use strict";CODE_FENCE_RE=/```(?:json|JSON)?\s*\n([\s\S]*?)```/g}});var execute_deep_agent_exports={};__export(execute_deep_agent_exports,{createDeepAgentActivities:()=>createDeepAgentActivities});function createDeepAgentActivities(config4){let client2=new StigmerClient({endpoint:config4.stigmerBackendEndpoint,token:config4.stigmerToken,tokenRef:config4.stigmerTokenRef}),streamingConfig=loadStreamingConfig();return{ExecuteDeepAgent:async(arg0,arg1)=>{let{executionId,threadId,turnSeq}=normalizeActivityInput(arg0,arg1);activityStarted();let setup=null,releaseWorkspaceLock;try{console.log(`[ExecuteDeepAgent] Started for execution ${executionId}`),setup=await performSetup({config:config4,client:client2,executionId,threadId});let statusOffload=setup.artifactStorage?{artifactStorage:setup.artifactStorage,executionId}:void 0,graphState=await setup.agentGraph.getState(setup.langgraphConfig),initialStatus=shouldSeedFromPersistedTranscript(setup.execution)?seedStatusFromExecution(setup.execution):create(AgentExecutionStatusSchema,{}),statusBuilder=new StatusBuilder(executionId,initialStatus);statusBuilder.setApprovalProvider({policies:setup.approvalPolicies,toolServerMap:setup.toolServerMap,leasedCategories:setup.leasedCategories,globalBypass:setup.globalBypass});let resume=resolveResumeInput(setup.execution,graphState,setup.execution.spec.message);if(resume.hasRejection){let failedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_FAILED,error:`Execution rejected: ${resume.rejectionReason}`,completedAt:utcTimestamp(),messages:[create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Execution rejected by user: ${resume.rejectionReason}`,timestamp:utcTimestamp()})]});return await persistStatus(client2,executionId,failedStatus,{offload:statusOffload}),slimStatus(failedStatus)}let effectiveInput=resume.isResumeFromApproval?resume.graphInput:setup.langgraphInput,inlinePublisher=new InlinePublisher({workspaceBackend:setup.workspaceBackend,artifactStorage:setup.artifactStorage,statusWriter:statusBuilder,executionId}),workspaceEntries=setup.session.spec?.workspaceEntries??[],writebackCoordinator=setup.provisionResults.length>0?new WriteBackCoordinator({statusWriter:statusBuilder,executionId,provisionResults:setup.provisionResults,workspaceEntries,workspaceBackend:setup.workspaceBackend}):null,gitRoot=setup.workspaceBackend.rootDir,changeSetId=`${executionId}:${turnSeq}`;try{releaseWorkspaceLock=await acquireWorkspaceLock(gitRoot,{onWaiting:()=>reportSetupProgress(client2,executionId,"Waiting for workspace \u2014 in use by another session"),heartbeat:()=>import_activity3.Context.current().heartbeat(),signal:import_activity3.Context.current().cancellationSignal,timeoutMs:config4.workspaceLockTimeoutMs})}catch(lockErr){if(lockErr instanceof WorkspaceLockCancelledError)throw new import_activity3.CancelledFailure("Activity cancelled while waiting for the workspace lock");if(lockErr instanceof WorkspaceLockTimeoutError){let failedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_FAILED,error:lockErr.message,completedAt:utcTimestamp(),messages:[create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Execution failed: ${lockErr.message}`,timestamp:utcTimestamp()})]});return await persistStatus(client2,executionId,failedStatus,{offload:statusOffload}),slimStatus(failedStatus)}throw lockErr}if(setup.workspaceBackend.platformDir&&await ensureStigmerSymlink(gitRoot,setup.workspaceBackend.platformDir),setup.captureMode){let decidedSets=(setup.execution.status?.fileChangeSets??[]).filter(cs=>cs.status===FileChangeSetStatus.DECIDED),reconciledAny=!1,reconcileFailed=!1,reconcileFailureDetail="",casReadBlob=setup.artifactStorage?casBlobReader(setup.artifactStorage):void 0;for(let changeSet of decidedSets){let capResult=await applyCaptureDecisions({status:initialStatus,gitRoot,executionId,changeSet,harnessId:DEEP_AGENT_HARNESS_ID,storage:setup.artifactStorage,readBlob:casReadBlob,gitWorkspace:setup.gitWorkspace});capResult.isCaptureTurn&&(reconciledAny=!0,capResult.failed&&(reconcileFailed=!0,reconcileFailureDetail=capResult.failureDetail??"file review reconcile failed"))}if(reconciledAny){if(reconcileFailed)return initialStatus.phase=ExecutionPhase.EXECUTION_FAILED,initialStatus.error=`File review reconcile failed: ${reconcileFailureDetail}`,initialStatus.completedAt=utcTimestamp(),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),slimStatus(initialStatus);if(!hasPendingToolApprovals(setup.execution)){initialStatus.phase=ExecutionPhase.EXECUTION_COMPLETED,initialStatus.completedAt=utcTimestamp(),writebackCoordinator&&await processCaptureWriteback(writebackCoordinator,executionId),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload});let slim2=slimStatus(initialStatus),lastAi=[...initialStatus.messages].reverse().find(m=>m.type===MessageType.MESSAGE_AI);return lastAi?.content&&(slim2.final_text=lastAi.content),initialStatus.structuredOutput!==void 0&&(slim2.structured=initialStatus.structuredOutput),slim2}}}let captureBaselineTree="",priorSubAgentToolCallIds=collectSubAgentToolCallIds(initialStatus.subAgentExecutions),priorSettledToolCallIds=collectSettledToolCallIds(initialStatus.messages);setup.captureMode&&(captureBaselineTree=await captureBaselineToLedger({status:initialStatus,gitRoot,executionId,changeSetId,harnessId:DEEP_AGENT_HARNESS_ID,gitWorkspace:setup.gitWorkspace}));let progressState=newProgressCaptureState(),casObserver=setup.casObserver,readObserverTouched=()=>({before:new Map(casObserver.before),blockedSecretPaths:new Set(casObserver.blockedSecretPaths)}),progressSubstrate=setup.captureMode?setup.gitWorkspace?captureBaselineTree?createHybridProgressSubstrate(createGitProgressSubstrate({workspaceRoot:gitRoot,executionId,baselineTree:captureBaselineTree}),createCasProgressSubstrate({workspaceRoot:gitRoot,read:readObserverTouched})):void 0:createCasProgressSubstrate({workspaceRoot:gitRoot,read:readObserverTouched}):void 0,cancellationSignal=import_activity3.Context.current().cancellationSignal,result=await streamExecution({agentGraph:setup.agentGraph,langgraphInput:effectiveInput,langgraphConfig:setup.langgraphConfig,executionId,client:client2,initialStatus,streamingConfig,offload:statusOffload,gracefulStop:setup.gracefulStop,inlinePublisher,writebackCoordinator:setup.captureMode?void 0:writebackCoordinator??void 0,heartbeatFn:details=>import_activity3.Context.current().heartbeat(details),isCancelledFn:()=>cancellationSignal.aborted,approvalProvider:{policies:setup.approvalPolicies,toolServerMap:setup.toolServerMap,leasedCategories:setup.leasedCategories,globalBypass:setup.globalBypass},streamVersion:setup.streamVersion,beforePersist:async status=>{progressSubstrate&&await captureFileChangeProgress({status,changeSetId,substrate:progressSubstrate,state:progressState})}});await processPostStream({status:initialStatus,inlinePublisher,writebackCoordinator:setup.captureMode?null:writebackCoordinator,pendingPublishPromises:result.pendingPublishPromises,pendingWritebackPromises:result.pendingWritebackPromises,executionId}),withholdSecretContentFromMessages(initialStatus.messages,initialStatus.subAgentExecutions);let fileReviewPending=!1,abnormalTerminal=!!result.terminalStatus&&initialStatus.phase!==ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL;if(setup.captureMode&&!abnormalTerminal){let casCaptureClass=setup.gitWorkspace?FileCaptureClass.GIT_IGNORED_CAPTURED:FileCaptureClass.NON_GIT_CAS,{casCaptures,unreviewablePaths}=await buildCasTurnCaptures2(setup.casObserver,gitRoot,casCaptureClass),commandProvenance=deriveTurnCommandProvenance2({status:initialStatus,priorSettledToolCallIds,priorSubAgentToolCallIds,globalBypass:setup.globalBypass});commandProvenance&&console.log(`[ExecuteDeepAgent] capture: turn qualifies for approved-command auto-keep (consent rows: ${commandProvenance.consentToolCallIds.join(",")||"(auto_approve_all)"}); attaching provenance to candidate (execution=${executionId})`),await captureCandidateToLedger({status:initialStatus,gitRoot,executionId,changeSetId,baselineTree:captureBaselineTree,harnessId:DEEP_AGENT_HARNESS_ID,casCaptures,storage:setup.artifactStorage,unreviewablePaths,unreviewableCaptureClass:casCaptureClass,gitWorkspace:setup.gitWorkspace,commandProvenance}),fileReviewPending=hasCandidateCaptured(initialStatus,changeSetId),fileReviewPending&&(stampFlowedFileEditRows2(initialStatus.messages,changeSetId),stampFlowedSubAgentFileEditRows(initialStatus.subAgentExecutions,changeSetId,priorSubAgentToolCallIds))}if(result.terminalStatus){if(initialStatus.phase===ExecutionPhase.EXECUTION_PAUSED)throw await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),console.log(`[ExecuteDeepAgent] Paused for execution ${executionId}: events=${result.eventsProcessed}`),new import_activity3.CancelledFailure("Activity paused by orchestrator");return setup.captureMode&&!abnormalTerminal?(await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),slimStatus(initialStatus)):result.terminalStatus}if(!setup.globalBypass){let postStreamGraphState=await setup.agentGraph.getState(setup.langgraphConfig),graphMessages=postStreamGraphState.values.messages,aiMessages=Array.isArray(graphMessages)?graphMessages:[],pendingInterrupts=detectPendingInterrupts(postStreamGraphState);if(pendingInterrupts.length>0){console.log(`[ExecuteDeepAgent] Detected ${pendingInterrupts.length} pending interrupt(s) for execution ${executionId} \u2014 setting WAITING_FOR_APPROVAL`),initialStatus.phase=ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL;let aiMsg=create(AgentMessageSchema,{type:MessageType.MESSAGE_AI,content:"",timestamp:utcTimestamp(),isStreaming:!1});for(let intr of pendingInterrupts){let toolCall=create(ToolCallSchema,{id:intr.toolCallId,name:intr.toolName,status:ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,requiresApproval:!0,approvalMessage:intr.message,approvalRequestedAt:utcTimestamp(),mcpServerSlug:intr.mcpServerSlug,startedAt:utcTimestamp(),toolKind:classifyTool(intr.toolName,intr.mcpServerSlug),approvalPolicySource:toProtoPolicySource(intr.policySource),policyEngineVersion:intr.policySource?POLICY_ENGINE_VERSION:""}),{argsPreview}=captureApprovalArtifacts({toolCallId:intr.toolCallId,messages:aiMessages});argsPreview&&(toolCall.argsPreview=argsPreview),aiMsg.toolCalls.push(toolCall)}return initialStatus.messages.push(aiMsg),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),slimStatus(initialStatus)}}let completeNow=!fileReviewPending;initialStatus.phase=completeNow?ExecutionPhase.EXECUTION_COMPLETED:ExecutionPhase.EXECUTION_WAITING_FOR_APPROVAL,completeNow&&(initialStatus.completedAt=utcTimestamp());let structuredOutput,finalText,lastAiMsg=[...initialStatus.messages].reverse().find(m=>m.type===MessageType.MESSAGE_AI);if(lastAiMsg&&(finalText=lastAiMsg.content),setup.hasStructuredOutput){let sr=result.runOutput?.structuredResponse;if(sr!=null&&typeof sr=="object"&&!Array.isArray(sr)?structuredOutput=sr:sr!==void 0&&console.warn(`[ExecuteDeepAgent] structuredResponse is not a plain object for execution ${executionId}: type=${typeof sr}`),structuredOutput===void 0&&finalText){let{extractJsonFromText:extractJsonFromText2}=await Promise.resolve().then(()=>(init_extract_json(),extract_json_exports)),extracted=extractJsonFromText2(finalText);extracted!=null&&typeof extracted=="object"&&!Array.isArray(extracted)&&(structuredOutput=extracted,console.log(`[ExecuteDeepAgent] structured output extracted from final text for execution ${executionId}: finalTextLength=${finalText.length}`))}structuredOutput!==void 0&&(initialStatus.structuredOutput=structuredOutput)}if(setup.execution.spec?.executionConfig?.interactionMode===InteractionMode.PLAN&&finalText&&setup.artifactStorage&&await publishPlanArtifact({status:initialStatus,executionId,planText:finalText,artifactStorage:setup.artifactStorage}),setup.captureMode&&completeNow&&writebackCoordinator&&await processCaptureWriteback(writebackCoordinator,executionId),await persistStatus(client2,executionId,initialStatus,{offload:statusOffload}),console.log(`[ExecuteDeepAgent] ${completeNow?"Completed":"Awaiting file review for"} execution ${executionId}: events=${result.eventsProcessed}, messages=${initialStatus.messages.length}, artifacts=${initialStatus.artifacts.length}, writebacks=${initialStatus.workspaceWriteBacks.length}, hasStructuredOutput=${structuredOutput!==void 0}`),!completeNow)return slimStatus(initialStatus);let slim=slimStatus(initialStatus);return finalText!==void 0&&(slim.final_text=finalText),structuredOutput!==void 0&&(slim.structured=structuredOutput),slim}catch(err){if(err instanceof import_activity3.CancelledFailure){console.log(`[ExecuteDeepAgent] Cancelled (pause) for execution ${executionId}`);let pausedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_PAUSED});throw await persistStatus(client2,executionId,pausedStatus).catch(()=>{}),err}if(import_activity3.Context.current().cancellationSignal.aborted){console.log(`[ExecuteDeepAgent] Error during cancellation for ${executionId}, treating as pause: ${err}`);let pausedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_PAUSED});throw await persistStatus(client2,executionId,pausedStatus).catch(()=>{}),new import_activity3.CancelledFailure("Activity paused by orchestrator (error during cancellation)")}let errorMessage=err instanceof Error?err.message:String(err),errorType=err instanceof Error?err.constructor.name:"UnknownError";console.error(`[ExecuteDeepAgent] Failed for execution ${executionId}: [${errorType}] ${errorMessage}`);let failedStatus=create(AgentExecutionStatusSchema,{phase:ExecutionPhase.EXECUTION_FAILED,error:`Execution failed: [${errorType}] ${errorMessage}`,completedAt:utcTimestamp(),messages:[create(AgentMessageSchema,{type:MessageType.MESSAGE_SYSTEM,content:`Error: [${errorType}] ${errorMessage}`,timestamp:utcTimestamp()})]});return await persistStatus(client2,executionId,failedStatus),slimStatus(failedStatus)}finally{await cleanup(setup),await releaseWorkspaceLock?.(),activityFinished()}}}}function detectPendingInterrupts(graphState){return graphState.tasks?.flatMap(task2=>(task2.interrupts??[]).filter(intr=>intr.resumeValue===void 0).map(intr=>{let val=intr.value;return{toolCallId:val?.tool_call_id??"",toolName:val?.tool_name??"",mcpServerSlug:val?.mcp_server_slug??"",message:val?.message??"",policySource:val?.policy_source||void 0}}))??[]}function hasPendingToolApprovals(execution){let status=execution.status;if(!status)return!1;let anyWaiting=msgs=>msgs.some(m=>m.toolCalls.some(tc=>tc.status===ToolCallStatus.TOOL_CALL_WAITING_APPROVAL));return anyWaiting(status.messages)?!0:status.subAgentExecutions.some(sa=>anyWaiting(sa.messages))}async function buildCasTurnCaptures2(observer,workspaceRoot,captureClass){let{capturablePaths,unreviewablePaths}=partitionIgnoredPathsBySecret(observer.before.keys(),observer.blockedSecretPaths),casCaptures=[];for(let relPath of capturablePaths){let after=await readFileOrNull3((0,import_node_path32.join)(workspaceRoot,relPath));casCaptures.push({path:relPath,before:observer.before.get(relPath)??null,after,captureClass})}return{casCaptures,unreviewablePaths:[...unreviewablePaths]}}async function readFileOrNull3(absolutePath){try{return await(0,import_promises24.readFile)(absolutePath)}catch{return null}}async function processCaptureWriteback(writebackCoordinator,executionId){await writebackCoordinator.finalize(),console.log(`[ExecuteDeepAgent] capture writeback finalized for execution ${executionId}`)}function shouldSeedFromPersistedTranscript(execution){return(execution.status?.messages.length??0)>0}function seedStatusFromExecution(execution){let seeded=clone(AgentExecutionStatusSchema,execution.status);return seeded.completedAt="",seeded.error="",seeded}async function cleanup(setup){if(setup){if(setup.mcpConnection)try{await setup.mcpConnection.client.close()}catch(err){console.warn("[ExecuteDeepAgent] MCP connection cleanup failed:",err)}await removeStigmerSymlink(setup.workspaceBackend.rootDir)}}var import_promises24,import_node_path32,import_activity3,DEEP_AGENT_HARNESS_ID,init_execute_deep_agent=__esm({"dist/activities/execute-deep-agent/index.js"(){"use strict";import_promises24=require("node:fs/promises"),import_node_path32=require("node:path"),import_activity3=__toESM(require_lib4(),1);init_esm4();init_api_pb3();init_message_pb();init_enum_pb();init_idle_watchdog();init_activity_input();init_status2();init_workspace_lock();init_stigmer_link();init_plan_artifact();init_tool_kind();init_approval_policy();init_stigmer_client();init_setup();init_streaming5();init_streaming_scheduler();init_status_builder();init_inline_publisher();init_writeback_coordinator();init_post_stream();init_hitl2();init_approval_file_change();init_capture();init_progress();init_cas_progress();init_events();init_cas_substrate();init_secret_paths();init_tool_row();init_stamp_flowed_rows();init_command_provenance3();DEEP_AGENT_HARNESS_ID="deep-agent"}});var ensure_thread_exports={};__export(ensure_thread_exports,{createEnsureThreadActivities:()=>createEnsureThreadActivities});function createEnsureThreadActivities(){return{EnsureThread:async(sessionId,agentId)=>{activityStarted();try{if(sessionId){let threadId2=`thread-${sessionId}`;return console.log(`[EnsureThread] Session-based thread: ${threadId2}`),threadId2}let threadId=`ephemeral-${agentId}-${(0,import_node_crypto16.randomUUID)().replace(/-/g,"").slice(0,8)}`;return console.log(`[EnsureThread] Ephemeral thread: ${threadId}`),threadId}finally{activityFinished()}}}}var import_node_crypto16,init_ensure_thread=__esm({"dist/activities/ensure-thread.js"(){"use strict";import_node_crypto16=require("node:crypto");init_idle_watchdog()}});var classify_tool_approvals_exports={};__export(classify_tool_approvals_exports,{buildToolsPayload:()=>buildToolsPayload,classifyTools:()=>classifyTools,createClassifyToolApprovalsActivities:()=>createClassifyToolApprovalsActivities,fallbackApprovals:()=>fallbackApprovals,reconcileBatchClassifications:()=>reconcileBatchClassifications});async function classifyTools(input,options){let{tools:tools3,serverName,serverDescription,mcpServerId}=input;if(tools3.length===0)return[];let model=await getSummarizationModel(options.primaryModel),batches=[];for(let i2=0;i2<tools3.length;i2+=BATCH_SIZE)batches.push(tools3.slice(i2,i2+BATCH_SIZE));console.log(`[ClassifyToolApprovals] Classifying ${tools3.length} tools for '${serverName}' using model '${model}' (${batches.length} batch(es) of up to ${BATCH_SIZE})`);let allApprovals=[];for(let batchIdx=0;batchIdx<batches.length;batchIdx++){let batch=batches[batchIdx];try{let batchResult=await classifyBatch({batch,serverName,serverDescription,model,proxyEndpoint:options.proxyEndpoint,stigmerToken:options.stigmerToken,mcpServerId:mcpServerId??null,batchIdx,totalBatches:batches.length}),{reconciled,failedClosedCount}=reconcileBatchClassifications(batch,batchResult);failedClosedCount>0&&console.warn(`[ClassifyToolApprovals] Batch ${batchIdx+1}/${batches.length} for '${serverName}': ${failedClosedCount} tool(s) missing from classifier output \u2014 failing closed (requires_approval=true)`),allApprovals.push(...reconciled)}catch(err){console.error(`[ClassifyToolApprovals] Batch ${batchIdx+1}/${batches.length} failed for '${serverName}' (${batch.length} tools) \u2014 falling back to requires_approval=true`,err),allApprovals.push(...fallbackApprovals(batch))}}let approved=allApprovals.filter(a=>a.requires_approval);return console.log(`[ClassifyToolApprovals] Classification complete for '${serverName}': ${approved.length}/${allApprovals.length} tools require approval`),approved}async function classifyBatch(params){let{batch,serverName,serverDescription,model,proxyEndpoint,stigmerToken,mcpServerId,batchIdx,totalBatches}=params,maxTokens=Math.max(MIN_MAX_TOKENS,batch.length*MAX_TOKENS_PER_TOOL),{model:llm}=await buildChatModel({modelName:model,proxyEndpoint,stigmerToken:stigmerToken??void 0,headerScope:{mcpServerId:mcpServerId??void 0},maxTokens}),structuredLlm=llm.withStructuredOutput(ClassifyToolApprovalsOutputSchema),toolsPayload=buildToolsPayload(batch),userPrompt=`MCP Server: ${serverName}
|
|
2292
2292
|
Description: ${serverDescription||"No description provided"}
|
|
2293
2293
|
|
|
2294
2294
|
Tools to classify (${batch.length}):
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stigmer/runner-slim",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.5",
|
|
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.1.
|
|
20
|
-
"@stigmer/runner-slim-darwin-x64": "3.1.
|
|
21
|
-
"@stigmer/runner-slim-linux-x64": "3.1.
|
|
22
|
-
"@stigmer/runner-slim-linux-arm64": "3.1.
|
|
23
|
-
"@stigmer/runner-slim-win32-x64": "3.1.
|
|
19
|
+
"@stigmer/runner-slim-darwin-arm64": "3.1.5",
|
|
20
|
+
"@stigmer/runner-slim-darwin-x64": "3.1.5",
|
|
21
|
+
"@stigmer/runner-slim-linux-x64": "3.1.5",
|
|
22
|
+
"@stigmer/runner-slim-linux-arm64": "3.1.5",
|
|
23
|
+
"@stigmer/runner-slim-win32-x64": "3.1.5"
|
|
24
24
|
},
|
|
25
25
|
"keywords": [
|
|
26
26
|
"stigmer",
|