openclaw-code-agent 4.7.10 β 4.7.12
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/README.md +1 -1
- package/dist/index.js +16 -16
- package/npm-shrinkwrap.json +14 -13
- package/openclaw.plugin.json +1 -1
- package/package.json +8 -7
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as Zo,A as de,Aa as qt,B as br,C as Rr,D as Ar,E as Rt,F as At,G as It,H as Tt,I as zo,J as Ho,K as C,L as D,M as z,N as Qo,O as xt,P as Yo,Pa as Vt,Q as Ir,R as L,S as Ct,T as Je,U as Mt,V as Jo,W as Xo,X as Ee,Y as oe,Z as Xe,_ as _t,a as Te,aa as H,b as xe,ba as Tr,c as wr,ca as xr,d as qo,da as Ze,e as Ce,ea as et,f as ue,fa as B,g as Z,ga as Dt,h as le,ha as ei,i as Ye,ia as tt,j as Vo,ja as ie,k as _,ka as Ne,l as Uo,la as ti,m as Y,ma as $t,n as Me,na as nt,o as Pt,oa as Et,p as ce,pa as Nt,q as _e,qa as Oe,r as wt,ra as Ot,s as bt,sa as ni,t as Go,ta as Wt,u as De,ua as Ft,v as $e,va as ri,w as jo,wa as Lt,x as p,xa as Bt,y as k,ya as Kt,z as $,za as Se}from"./chunks/chunk.js";import{readdirSync as hf,statSync as yf,rmSync as Sf}from"fs";import{execFileSync as kf}from"child_process";import{join as Bo}from"path";var oi={name:"openclaw-code-agent",version:"4.7.10",type:"module",packageManager:"pnpm@11.15.1",main:"dist/index.js",scripts:{"audit:prod":"pnpm audit --prod",build:"esbuild index.ts --bundle --splitting --platform=node --target=node22 --format=esm --outdir=dist --entry-names=index --chunk-names=chunks/[name] --minify --charset=utf8 --pure:console.log --pure:console.warn --pure:console.info --pure:console.debug --external:@anthropic-ai/claude-agent-sdk --external:openclaw/plugin-sdk/plugin-entry","generate:npm-shrinkwrap":"node scripts/generate-npm-shrinkwrap.mjs","check-static-guardrails":"node scripts/check-static-guardrails.mjs && node scripts/check-npm-shrinkwrap.mjs","check-plugin-security":"node scripts/check-plugin-security.mjs",test:"node scripts/run-tests.mjs","test:integ:crabbox":"node scripts/run-tests.mjs tests/oca-codex-crabbox-integ.test.ts tests/oca-plugin-workflows-integ.test.ts tests/oca-codex-telegram-proof.test.ts tests/oca-codex-proof-app-server.test.ts tests/oca-codex-proof-workflow.test.ts","test:serial":"node scripts/run-tests.mjs","test:file":"node scripts/run-tests.mjs","smoke:backend":"node scripts/run-tests.mjs tests/codex-harness.test.ts tests/plan-mode-e2e.test.ts tests/session-restore-service.test.ts","smoke:backend-parity":"node scripts/run-tests.mjs tests/backend-contract-smoke.test.ts tests/codex-harness.test.ts tests/harness-registry.test.ts","smoke:codex-worktrees":"node scripts/run-tests.mjs tests/codex-harness.test.ts tests/session-bootstrap.test.ts tests/session-restore-service.test.ts","smoke:codex-live":"OPENCLAW_RUN_LIVE_CODEX_SMOKE=1 node scripts/run-tests.mjs tests/live-codex-app-server-smoke.test.ts","proof:codex-doctor":"node --import tsx scripts/e2e/oca-codex-telegram-proof.ts doctor","proof:codex-local":"node --import tsx scripts/e2e/oca-codex-telegram-proof.ts local-smoke","proof:codex-telegram":"node scripts/e2e/run-oca-codex-telegram-proof.mjs","smoke:codex-release":"OPENCLAW_RUN_LIVE_CODEX_RELEASE_SMOKE=1 node scripts/run-tests.mjs tests/live-codex-app-server-smoke.test.ts","smoke:opencode-live":"OPENCLAW_RUN_LIVE_OPENCODE_SMOKE=1 node scripts/run-tests.mjs tests/live-opencode-server-smoke.test.ts",typecheck:"tsc -p tsconfig.typecheck.json --noEmit","validate:release-metadata":"node scripts/validate-release-metadata.mjs","verify:npm-consumer":"node scripts/verify-npm-consumer-install.mjs",verify:"pnpm check-static-guardrails && pnpm typecheck && pnpm build && pnpm test"},openclaw:{extensions:["./dist/index.js"],install:{npmSpec:"openclaw-code-agent",defaultChoice:"npm",minHostVersion:">=2026.8.2"},compat:{pluginApi:">=2026.8.1",minGatewayVersion:"2026.8.1"},build:{openclawVersion:"2026.8.2",pluginSdkVersion:"2026.8.2"}},files:["dist/","skills/","openclaw.plugin.json","npm-shrinkwrap.json","README.md","LICENSE"],dependencies:{"@anthropic-ai/claude-agent-sdk":"0.3.251","@anthropic-ai/sdk":"0.122.0","@hono/node-server":"2.1.1","@modelcontextprotocol/sdk":"1.30.0","express-rate-limit":"8.7.0","fast-uri":"3.1.5",hono:"4.12.34","ip-address":"10.5.0",zod:"4.5.4"},devDependencies:{"@types/node":"^26.0.1",esbuild:"^0.28.1",nanoid:"^6.0.0",openclaw:"2026.8.2",tsx:"^4.21.0",typescript:"^7.0.2"},keywords:["openclaw","plugin","claude","claude-code","opencode","coding-agent","codex","ai","anthropic","agent","code-generation","automation","cli","background-process","developer-tools"],repository:{type:"git",url:"git+https://github.com/goldmar/openclaw-code-agent.git"},homepage:"https://github.com/goldmar/openclaw-code-agent#readme",bugs:{url:"https://github.com/goldmar/openclaw-code-agent/issues"},license:"MIT",author:"Mark Goldenstein",publishConfig:{access:"public",provenance:!0},description:"An OpenClaw plugin that orchestrates coding agent sessions as managed background processes. Launch, monitor, and control coding agents (Claude Code, Codex, experimental OpenCode, and more) directly from your AI gateway.",peerDependencies:{openclaw:">=2026.8.1"}};import{execFile as xl}from"node:child_process";import{mkdirSync as Cl,readFileSync as Ml,renameSync as _l,writeFileSync as Dl}from"node:fs";import{dirname as $l,join as El}from"node:path";import{promisify as Nl}from"node:util";import*as pi from"child_process";import{createHash as fl}from"crypto";var W="code-agent";var gl=new Set(["1","true","yes","on"]);function Mr(){let n=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(n&&gl.has(n))}function K(n){if(!(typeof n!="string"||n.length===0))return fl("sha256").update(n).digest("hex").slice(0,12)}function ii(n){return typeof n.callbackData=="string"?n.callbackData:typeof n.value=="string"?n.value:void 0}function E(n){let e=(n??[]).filter(r=>Array.isArray(r)&&r.length>0),t=e.flat();return{buttonRows:e.length||void 0,buttonCount:t.length||void 0,buttonLabels:t.length>0?t.map(r=>typeof r.label=="string"?r.label:void 0):void 0,callbackByteLengths:t.length>0?t.map(r=>{let o=ii(r);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:t.length>0?t.map(r=>K(ii(r))):void 0,buttonStyles:t.length>0?t.map(r=>typeof r.style=="string"?r.style:void 0):void 0}}function pe(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function ai(n){let e=pe(n),t=Array.isArray(e?.blocks)?e.blocks:void 0;if(t)return t.map(r=>pe(r)?.type).filter(r=>typeof r=="string"&&r.length>0)}function li(n){let e=pe(n),t=Array.isArray(e?.blocks)?e.blocks:void 0;if(!t)return;let r=t.map(o=>{let i=pe(o);return i?.type!=="buttons"||!Array.isArray(i.buttons)?[]:i.buttons}).filter(o=>o.length>0);return r.length>0?r:void 0}function _r(n){let e=li(n);return{presentationBlockTypes:ai(n),...E(e)}}function Dr(n){let e=pe(n),t=e?.interactive,r=pe(e?.channelData),o=pe(r?.telegram),i=Array.isArray(o?.buttons)?o.buttons:void 0;return{renderedPayloadKeys:e?Object.keys(e).sort():void 0,interactiveBlockTypes:ai(t),...si("interactive",E(li(t))),...si("telegramChannelData",E(i)),hasPresentation:!!e?.presentation,hasInteractive:!!t,hasTelegramChannelDataButtons:!!i?.some(s=>s.length>0)}}function di(n){let e=pe(n);return e?{sendResultKeys:Object.keys(e).sort(),messageId:Cr(e.messageId),chatId:Cr(e.chatId),telegramThreadId:Cr(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof n}}function Cr(n){return typeof n=="string"||typeof n=="number"?n:void 0}function si(n,e){let t={};for(let[r,o]of Object.entries(e))o!==void 0&&(t[`${n}${r.charAt(0).toUpperCase()}${r.slice(1)}`]=o);return t}function M(n,e){if(!Mr())return;let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));`${JSON.stringify({event:n,callbackNamespace:W,...t})}`}var ui=5e3,mi=64,hl={primary:"primary",success:"success",positive:"success",danger:"danger",destructive:"danger",negative:"danger"},yl={execFile:pi.execFile},me=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},We=class{constructor(e=yl.execFile){this.execFile=e}execFile;async send(e,t,r){M("direct_send_started",{...J(e),messageTextLength:t.length,...E(r)});try{await this.sendViaRuntime(e,t,r),M("direct_send_succeeded",{...J(e),deliveryPath:"runtime",...E(r)});return}catch(o){if(!(o instanceof me))throw M("direct_send_failed",{...J(e),deliveryPath:"runtime",...E(r),error:$r(o)}),o;M("direct_send_runtime_capability_missing",{...J(e),deliveryPath:"runtime",...E(r),reason:o.message}),await this.sendViaBoundedCliFallback(e,t,r,o.message),M("direct_send_succeeded",{...J(e),deliveryPath:"cli-fallback",...E(r)})}}async sendViaRuntime(e,t,r){let o=xe(),i=qo(),s=o?.channel?.outbound?.loadAdapter;if(!o)throw new me("OpenClaw plugin runtime is unavailable for direct notification delivery");if(i==null)throw new me("OpenClaw runtime config snapshot is unavailable for direct notification delivery");if(!o.channel)throw new me(`OpenClaw plugin runtime channel surface is unavailable for direct notification delivery (runtimeVersion=${Er(o)})`);if(!o.channel.outbound)throw new me(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${Er(o)})`);if(!s)throw new me(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${Er(o)})`);let a=await s(e.channel);if(!a)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let l=jt(r);if(M("runtime_adapter_loaded",{...J(e),adapterHasRenderPresentation:typeof a.renderPresentation=="function",adapterHasSendPayload:typeof a.sendPayload=="function",adapterHasSendText:typeof a.sendText=="function",...E(r),...l?_r(l):{}}),l){await this.sendPresentation(a,i,e,t,l);return}if(!a.sendText)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" cannot send text`);await a.sendText({cfg:i,to:e.target,text:t,accountId:e.accountId,threadId:e.threadId})}async sendPresentation(e,t,r,o,i){let s=kl(i),a={text:o,presentation:i,interactive:s};M("presentation_render_started",{...J(r),messageTextLength:o.length,adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",..._r(i)});let l={cfg:t,to:r.target,text:o,payload:a,accountId:r.accountId,threadId:r.threadId},d=e.renderPresentation?await e.renderPresentation({payload:a,presentation:i,ctx:l}):a,u=Pl(d,s,r.channel);if(M("presentation_render_completed",{...J(r),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Dr(u)}),!u||typeof u!="object"||!e.sendPayload)throw new Error(`OpenClaw outbound adapter for channel "${r.channel}" cannot preserve interactive presentation`);let f=await e.sendPayload({...l,payload:u});M("presentation_send_payload_completed",{...J(r),...Dr(u),...di(f)})}sendViaBoundedCliFallback(e,t,r,o){return new Promise((i,s)=>{let a=Sl(e,t,r);M("direct_send_cli_fallback_started",{...J(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:t.length,...E(r)}),this.execFile("openclaw",a,{timeout:ui,killSignal:"SIGKILL"},(l,d,u)=>{if(!l){M("direct_send_cli_fallback_completed",{...J(e),deliveryPath:"cli-fallback",...E(r)}),i();return}let f=u?.trim()?` | stderr: ${u.trim()}`:"";M("direct_send_cli_fallback_failed",{...J(e),deliveryPath:"cli-fallback",...E(r),error:$r(l),stderrLength:u?.length}),s(new Error(`${o}; bounded openclaw message send fallback failed within ${ui}ms timeout: ${$r(l)}${f}`))})})}};function J(n){return{channel:n.channel,target:n.target,accountId:n.accountId,threadId:n.threadId,sessionKey:n.sessionKey}}function Sl(n,e,t){let r=jt(t),o=["message","send","--channel",n.channel,"--target",n.target,"--message",e];return n.accountId&&o.push("--account",n.accountId),n.threadId&&o.push("--thread-id",n.threadId),r&&o.push("--presentation",JSON.stringify(r)),o}function $r(n){return n instanceof Error?n.message:String(n)}function Er(n){if(!n||typeof n!="object")return"unknown";let e=n.version;return typeof e=="string"&&e.trim()?e:"unknown"}function jt(n){let e=(n??[]).filter(t=>Array.isArray(t)&&t.length>0).map(t=>({type:"buttons",buttons:t.map(r=>({label:r.label,value:Tl(r.callbackData),...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function kl(n){let e=n.blocks.filter(t=>t.type==="buttons"&&t.buttons.length>0).map(t=>({type:"buttons",buttons:t.buttons.map(r=>({label:r.label,value:r.value,...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function vl(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n.interactive;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.blocks;return Array.isArray(t)&&t.some(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let o=r;return o.type==="buttons"&&Array.isArray(o.buttons)&&o.buttons.length>0})}function Pl(n,e,t){if(!e)return n;let r=vl(n)?n:wl(n,e);return t!=="telegram"?r:bl(r,e)}function wl(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:{...n,interactive:e}}function bl(n,e){if(!n||typeof n!="object"||Array.isArray(n))return n;let t=n,r=Fe(t.channelData),o=Fe(r?.telegram),i=Al(o?.buttons);if(i)return{...t,channelData:{...r??{},telegram:{...o??{},buttons:i}}};let s=Rl(e);return s?{...t,channelData:{...r??{},telegram:{...o??{},buttons:s}}}:n}function Rl(n){let e=n.blocks.filter(t=>t.type==="buttons"&&t.buttons.length>0).map(t=>t.buttons.filter(r=>typeof r.value=="string"&&r.value.trim().length>0&&Buffer.byteLength(r.value,"utf8")<=mi).map(r=>({text:r.label,callback_data:r.value,...fi(r.style)}))).filter(t=>t.length>0);return e.length>0?e:void 0}function Al(n){if(!Array.isArray(n))return;let e=n.map(t=>Array.isArray(t)?t.map(r=>{if(!r||typeof r!="object"||Array.isArray(r))return;let{style:o,...i}=r;if(!(typeof i.text!="string"||i.text.trim().length===0)&&!(i.callback_data!==void 0&&(typeof i.callback_data!="string"||i.callback_data.trim().length===0||Buffer.byteLength(i.callback_data,"utf8")>mi))&&Il(i))return{...i,...fi(o)}}).filter(r=>!!r):[]).filter(t=>t.length>0);return e.length>0?e:void 0}function Il(n){return Gt(n.callback_data)||Gt(n.url)||Ut(n.web_app)||Ut(n.webApp)||Ut(n.login_url)||Ut(n.loginUrl)||typeof n.switch_inline_query=="string"||typeof n.switch_inline_query_current_chat=="string"||Fe(n.switch_inline_query_chosen_chat)!==void 0||Fe(n.callback_game)!==void 0||n.pay===!0||ci(n.copy_text)||ci(n.copyText)}function Gt(n){return typeof n=="string"&&n.trim().length>0}function Ut(n){let e=Fe(n);return Gt(e?.url)}function ci(n){let e=Fe(n);return Gt(e?.text)}function fi(n){if(typeof n!="string")return{};let e=n.trim().toLowerCase(),t=hl[e];return t?{style:t}:{}}function Fe(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Tl(n){return n.startsWith(`${W}:`)?n:`${W}:${n}`}var Ol=Nl(xl),rt="openclaw-code-agent",Wl=`https://registry.npmjs.org/${encodeURIComponent(rt)}/latest`,Fl="openclaw-code-agent-auto-update.json",Si=1440*60*1e3,Ll=7*Si,Bl=1e4,Le="plugin:auto-update";function fe(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function Nr(n){return n instanceof Error?n.message:String(n)}function te(n){return n?.trim().replace(/^v/i,"")||void 0}function ee(n,e){let t=n[e];return typeof t=="string"&&t.trim()?t.trim():void 0}function gi(n){let e=n?.trim().replace(/^npm:/,"");if(!e)return;if(e.startsWith("@")){let r=e.indexOf("@",1);return r===-1?e:e.slice(0,r)}let t=e.indexOf("@");return t===-1?e:e.slice(0,t)}function Or(n){let e=`${n.stdout}
|
|
1
|
+
import{$ as Zo,A as de,Aa as qt,B as br,C as Rr,D as Ar,E as Rt,F as At,G as It,H as Tt,I as zo,J as Ho,K as C,L as D,M as z,N as Qo,O as xt,P as Yo,Pa as Vt,Q as Ir,R as L,S as Ct,T as Je,U as Mt,V as Jo,W as Xo,X as Ee,Y as oe,Z as Xe,_ as _t,a as Te,aa as H,b as xe,ba as Tr,c as wr,ca as xr,d as qo,da as Ze,e as Ce,ea as et,f as ue,fa as B,g as Z,ga as Dt,h as le,ha as ei,i as Ye,ia as tt,j as Vo,ja as ie,k as _,ka as Ne,l as Uo,la as ti,m as Y,ma as $t,n as Me,na as nt,o as Pt,oa as Et,p as ce,pa as Nt,q as _e,qa as Oe,r as wt,ra as Ot,s as bt,sa as ni,t as Go,ta as Wt,u as De,ua as Ft,v as $e,va as ri,w as jo,wa as Lt,x as p,xa as Bt,y as k,ya as Kt,z as $,za as Se}from"./chunks/chunk.js";import{readdirSync as hf,statSync as yf,rmSync as Sf}from"fs";import{execFileSync as kf}from"child_process";import{join as Bo}from"path";var oi={name:"openclaw-code-agent",version:"4.7.12",type:"module",packageManager:"pnpm@11.15.1",main:"dist/index.js",scripts:{"audit:prod":"pnpm audit --prod",build:"esbuild index.ts --bundle --splitting --platform=node --target=node22 --format=esm --outdir=dist --entry-names=index --chunk-names=chunks/[name] --minify --charset=utf8 --pure:console.log --pure:console.warn --pure:console.info --pure:console.debug --external:@anthropic-ai/claude-agent-sdk --external:openclaw/plugin-sdk/plugin-entry","generate:npm-shrinkwrap":"node scripts/generate-npm-shrinkwrap.mjs","check-static-guardrails":"node scripts/check-static-guardrails.mjs && node scripts/check-npm-shrinkwrap.mjs","check-plugin-security":"node scripts/check-plugin-security.mjs",test:"node scripts/run-tests.mjs","test:integ:crabbox":"node scripts/run-tests.mjs tests/oca-codex-crabbox-integ.test.ts tests/oca-plugin-workflows-integ.test.ts tests/oca-codex-telegram-proof.test.ts tests/oca-codex-proof-app-server.test.ts tests/oca-codex-proof-workflow.test.ts","test:serial":"node scripts/run-tests.mjs","test:file":"node scripts/run-tests.mjs","smoke:backend":"node scripts/run-tests.mjs tests/codex-harness.test.ts tests/plan-mode-e2e.test.ts tests/session-restore-service.test.ts","smoke:backend-parity":"node scripts/run-tests.mjs tests/backend-contract-smoke.test.ts tests/codex-harness.test.ts tests/harness-registry.test.ts","smoke:codex-worktrees":"node scripts/run-tests.mjs tests/codex-harness.test.ts tests/session-bootstrap.test.ts tests/session-restore-service.test.ts","smoke:codex-live":"OPENCLAW_RUN_LIVE_CODEX_SMOKE=1 node scripts/run-tests.mjs tests/live-codex-app-server-smoke.test.ts","proof:codex-doctor":"node --import tsx scripts/e2e/oca-codex-telegram-proof.ts doctor","proof:codex-local":"node --import tsx scripts/e2e/oca-codex-telegram-proof.ts local-smoke","proof:codex-telegram":"node scripts/e2e/run-oca-codex-telegram-proof.mjs","smoke:codex-release":"OPENCLAW_RUN_LIVE_CODEX_RELEASE_SMOKE=1 node scripts/run-tests.mjs tests/live-codex-app-server-smoke.test.ts","smoke:opencode-live":"OPENCLAW_RUN_LIVE_OPENCODE_SMOKE=1 node scripts/run-tests.mjs tests/live-opencode-server-smoke.test.ts",typecheck:"tsc -p tsconfig.typecheck.json --noEmit","validate:release-metadata":"node scripts/validate-release-metadata.mjs","verify:npm-consumer":"node scripts/verify-npm-consumer-install.mjs",verify:"pnpm check-static-guardrails && pnpm typecheck && pnpm build && pnpm test"},openclaw:{extensions:["./dist/index.js"],install:{npmSpec:"openclaw-code-agent",defaultChoice:"npm",minHostVersion:">=2026.9.1"},compat:{pluginApi:">=2026.8.1",minGatewayVersion:"2026.8.1"},build:{openclawVersion:"2026.9.1",pluginSdkVersion:"2026.9.1"}},files:["dist/","skills/","openclaw.plugin.json","npm-shrinkwrap.json","README.md","LICENSE"],dependencies:{"@anthropic-ai/claude-agent-sdk":"0.3.251","@anthropic-ai/sdk":"0.122.0","@hono/node-server":"2.1.1","@modelcontextprotocol/sdk":"1.30.0","express-rate-limit":"8.7.0","fast-uri":"3.1.6",hono:"4.12.34","ip-address":"10.7.0",qs:"6.16.0",zod:"4.5.4"},devDependencies:{"@types/node":"^26.0.1",esbuild:"^0.28.1",nanoid:"^6.0.0",openclaw:"2026.9.1",tsx:"^4.21.0",typescript:"^7.0.2"},keywords:["openclaw","plugin","claude","claude-code","opencode","coding-agent","codex","ai","anthropic","agent","code-generation","automation","cli","background-process","developer-tools"],repository:{type:"git",url:"git+https://github.com/goldmar/openclaw-code-agent.git"},homepage:"https://github.com/goldmar/openclaw-code-agent#readme",bugs:{url:"https://github.com/goldmar/openclaw-code-agent/issues"},license:"MIT",author:"Mark Goldenstein",publishConfig:{access:"public",provenance:!0},description:"An OpenClaw plugin that orchestrates coding agent sessions as managed background processes. Launch, monitor, and control coding agents (Claude Code, Codex, experimental OpenCode, and more) directly from your AI gateway.",peerDependencies:{openclaw:">=2026.8.1"}};import{execFile as xl}from"node:child_process";import{mkdirSync as Cl,readFileSync as Ml,renameSync as _l,writeFileSync as Dl}from"node:fs";import{dirname as $l,join as El}from"node:path";import{promisify as Nl}from"node:util";import*as pi from"child_process";import{createHash as fl}from"crypto";var W="code-agent";var gl=new Set(["1","true","yes","on"]);function Mr(){let n=process.env.OPENCLAW_CODE_AGENT_BUTTON_DIAGNOSTICS?.trim().toLowerCase();return!!(n&&gl.has(n))}function K(n){if(!(typeof n!="string"||n.length===0))return fl("sha256").update(n).digest("hex").slice(0,12)}function ii(n){return typeof n.callbackData=="string"?n.callbackData:typeof n.value=="string"?n.value:void 0}function E(n){let e=(n??[]).filter(r=>Array.isArray(r)&&r.length>0),t=e.flat();return{buttonRows:e.length||void 0,buttonCount:t.length||void 0,buttonLabels:t.length>0?t.map(r=>typeof r.label=="string"?r.label:void 0):void 0,callbackByteLengths:t.length>0?t.map(r=>{let o=ii(r);return o?Buffer.byteLength(o,"utf8"):void 0}):void 0,callbackHashes:t.length>0?t.map(r=>K(ii(r))):void 0,buttonStyles:t.length>0?t.map(r=>typeof r.style=="string"?r.style:void 0):void 0}}function pe(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function ai(n){let e=pe(n),t=Array.isArray(e?.blocks)?e.blocks:void 0;if(t)return t.map(r=>pe(r)?.type).filter(r=>typeof r=="string"&&r.length>0)}function li(n){let e=pe(n),t=Array.isArray(e?.blocks)?e.blocks:void 0;if(!t)return;let r=t.map(o=>{let i=pe(o);return i?.type!=="buttons"||!Array.isArray(i.buttons)?[]:i.buttons}).filter(o=>o.length>0);return r.length>0?r:void 0}function _r(n){let e=li(n);return{presentationBlockTypes:ai(n),...E(e)}}function Dr(n){let e=pe(n),t=e?.interactive,r=pe(e?.channelData),o=pe(r?.telegram),i=Array.isArray(o?.buttons)?o.buttons:void 0;return{renderedPayloadKeys:e?Object.keys(e).sort():void 0,interactiveBlockTypes:ai(t),...si("interactive",E(li(t))),...si("telegramChannelData",E(i)),hasPresentation:!!e?.presentation,hasInteractive:!!t,hasTelegramChannelDataButtons:!!i?.some(s=>s.length>0)}}function di(n){let e=pe(n);return e?{sendResultKeys:Object.keys(e).sort(),messageId:Cr(e.messageId),chatId:Cr(e.chatId),telegramThreadId:Cr(e.messageThreadId??e.threadId),channel:typeof e.channel=="string"?e.channel:void 0}:{sendResultType:typeof n}}function Cr(n){return typeof n=="string"||typeof n=="number"?n:void 0}function si(n,e){let t={};for(let[r,o]of Object.entries(e))o!==void 0&&(t[`${n}${r.charAt(0).toUpperCase()}${r.slice(1)}`]=o);return t}function M(n,e){if(!Mr())return;let t=Object.fromEntries(Object.entries(e).filter(([,r])=>r!==void 0));`${JSON.stringify({event:n,callbackNamespace:W,...t})}`}var ui=5e3,mi=64,hl={primary:"primary",success:"success",positive:"success",danger:"danger",destructive:"danger",negative:"danger"},yl={execFile:pi.execFile},me=class extends Error{constructor(e){super(e),this.name="MissingRuntimeDirectNotificationCapabilityError"}},We=class{constructor(e=yl.execFile){this.execFile=e}execFile;async send(e,t,r){M("direct_send_started",{...J(e),messageTextLength:t.length,...E(r)});try{await this.sendViaRuntime(e,t,r),M("direct_send_succeeded",{...J(e),deliveryPath:"runtime",...E(r)});return}catch(o){if(!(o instanceof me))throw M("direct_send_failed",{...J(e),deliveryPath:"runtime",...E(r),error:$r(o)}),o;M("direct_send_runtime_capability_missing",{...J(e),deliveryPath:"runtime",...E(r),reason:o.message}),await this.sendViaBoundedCliFallback(e,t,r,o.message),M("direct_send_succeeded",{...J(e),deliveryPath:"cli-fallback",...E(r)})}}async sendViaRuntime(e,t,r){let o=xe(),i=qo(),s=o?.channel?.outbound?.loadAdapter;if(!o)throw new me("OpenClaw plugin runtime is unavailable for direct notification delivery");if(i==null)throw new me("OpenClaw runtime config snapshot is unavailable for direct notification delivery");if(!o.channel)throw new me(`OpenClaw plugin runtime channel surface is unavailable for direct notification delivery (runtimeVersion=${Er(o)})`);if(!o.channel.outbound)throw new me(`OpenClaw plugin runtime channel outbound surface is unavailable for direct notification delivery (runtimeVersion=${Er(o)})`);if(!s)throw new me(`OpenClaw plugin runtime channel outbound loadAdapter is unavailable for direct notification delivery (runtimeVersion=${Er(o)})`);let a=await s(e.channel);if(!a)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" is unavailable`);let l=jt(r);if(M("runtime_adapter_loaded",{...J(e),adapterHasRenderPresentation:typeof a.renderPresentation=="function",adapterHasSendPayload:typeof a.sendPayload=="function",adapterHasSendText:typeof a.sendText=="function",...E(r),...l?_r(l):{}}),l){await this.sendPresentation(a,i,e,t,l);return}if(!a.sendText)throw new Error(`OpenClaw outbound adapter for channel "${e.channel}" cannot send text`);await a.sendText({cfg:i,to:e.target,text:t,accountId:e.accountId,threadId:e.threadId})}async sendPresentation(e,t,r,o,i){let s=kl(i),a={text:o,presentation:i,interactive:s};M("presentation_render_started",{...J(r),messageTextLength:o.length,adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",..._r(i)});let l={cfg:t,to:r.target,text:o,payload:a,accountId:r.accountId,threadId:r.threadId},d=e.renderPresentation?await e.renderPresentation({payload:a,presentation:i,ctx:l}):a,u=Pl(d,s,r.channel);if(M("presentation_render_completed",{...J(r),adapterHasRenderPresentation:typeof e.renderPresentation=="function",adapterHasSendPayload:typeof e.sendPayload=="function",...Dr(u)}),!u||typeof u!="object"||!e.sendPayload)throw new Error(`OpenClaw outbound adapter for channel "${r.channel}" cannot preserve interactive presentation`);let f=await e.sendPayload({...l,payload:u});M("presentation_send_payload_completed",{...J(r),...Dr(u),...di(f)})}sendViaBoundedCliFallback(e,t,r,o){return new Promise((i,s)=>{let a=Sl(e,t,r);M("direct_send_cli_fallback_started",{...J(e),deliveryPath:"cli-fallback",reason:o,messageTextLength:t.length,...E(r)}),this.execFile("openclaw",a,{timeout:ui,killSignal:"SIGKILL"},(l,d,u)=>{if(!l){M("direct_send_cli_fallback_completed",{...J(e),deliveryPath:"cli-fallback",...E(r)}),i();return}let f=u?.trim()?` | stderr: ${u.trim()}`:"";M("direct_send_cli_fallback_failed",{...J(e),deliveryPath:"cli-fallback",...E(r),error:$r(l),stderrLength:u?.length}),s(new Error(`${o}; bounded openclaw message send fallback failed within ${ui}ms timeout: ${$r(l)}${f}`))})})}};function J(n){return{channel:n.channel,target:n.target,accountId:n.accountId,threadId:n.threadId,sessionKey:n.sessionKey}}function Sl(n,e,t){let r=jt(t),o=["message","send","--channel",n.channel,"--target",n.target,"--message",e];return n.accountId&&o.push("--account",n.accountId),n.threadId&&o.push("--thread-id",n.threadId),r&&o.push("--presentation",JSON.stringify(r)),o}function $r(n){return n instanceof Error?n.message:String(n)}function Er(n){if(!n||typeof n!="object")return"unknown";let e=n.version;return typeof e=="string"&&e.trim()?e:"unknown"}function jt(n){let e=(n??[]).filter(t=>Array.isArray(t)&&t.length>0).map(t=>({type:"buttons",buttons:t.map(r=>({label:r.label,value:Tl(r.callbackData),...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function kl(n){let e=n.blocks.filter(t=>t.type==="buttons"&&t.buttons.length>0).map(t=>({type:"buttons",buttons:t.buttons.map(r=>({label:r.label,value:r.value,...r.style?{style:r.style}:{}}))}));return e.length>0?{blocks:e}:void 0}function vl(n){if(!n||typeof n!="object"||Array.isArray(n))return!1;let e=n.interactive;if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.blocks;return Array.isArray(t)&&t.some(r=>{if(!r||typeof r!="object"||Array.isArray(r))return!1;let o=r;return o.type==="buttons"&&Array.isArray(o.buttons)&&o.buttons.length>0})}function Pl(n,e,t){if(!e)return n;let r=vl(n)?n:wl(n,e);return t!=="telegram"?r:bl(r,e)}function wl(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:{...n,interactive:e}}function bl(n,e){if(!n||typeof n!="object"||Array.isArray(n))return n;let t=n,r=Fe(t.channelData),o=Fe(r?.telegram),i=Al(o?.buttons);if(i)return{...t,channelData:{...r??{},telegram:{...o??{},buttons:i}}};let s=Rl(e);return s?{...t,channelData:{...r??{},telegram:{...o??{},buttons:s}}}:n}function Rl(n){let e=n.blocks.filter(t=>t.type==="buttons"&&t.buttons.length>0).map(t=>t.buttons.filter(r=>typeof r.value=="string"&&r.value.trim().length>0&&Buffer.byteLength(r.value,"utf8")<=mi).map(r=>({text:r.label,callback_data:r.value,...fi(r.style)}))).filter(t=>t.length>0);return e.length>0?e:void 0}function Al(n){if(!Array.isArray(n))return;let e=n.map(t=>Array.isArray(t)?t.map(r=>{if(!r||typeof r!="object"||Array.isArray(r))return;let{style:o,...i}=r;if(!(typeof i.text!="string"||i.text.trim().length===0)&&!(i.callback_data!==void 0&&(typeof i.callback_data!="string"||i.callback_data.trim().length===0||Buffer.byteLength(i.callback_data,"utf8")>mi))&&Il(i))return{...i,...fi(o)}}).filter(r=>!!r):[]).filter(t=>t.length>0);return e.length>0?e:void 0}function Il(n){return Gt(n.callback_data)||Gt(n.url)||Ut(n.web_app)||Ut(n.webApp)||Ut(n.login_url)||Ut(n.loginUrl)||typeof n.switch_inline_query=="string"||typeof n.switch_inline_query_current_chat=="string"||Fe(n.switch_inline_query_chosen_chat)!==void 0||Fe(n.callback_game)!==void 0||n.pay===!0||ci(n.copy_text)||ci(n.copyText)}function Gt(n){return typeof n=="string"&&n.trim().length>0}function Ut(n){let e=Fe(n);return Gt(e?.url)}function ci(n){let e=Fe(n);return Gt(e?.text)}function fi(n){if(typeof n!="string")return{};let e=n.trim().toLowerCase(),t=hl[e];return t?{style:t}:{}}function Fe(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Tl(n){return n.startsWith(`${W}:`)?n:`${W}:${n}`}var Ol=Nl(xl),rt="openclaw-code-agent",Wl=`https://registry.npmjs.org/${encodeURIComponent(rt)}/latest`,Fl="openclaw-code-agent-auto-update.json",Si=1440*60*1e3,Ll=7*Si,Bl=1e4,Le="plugin:auto-update";function fe(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}function Nr(n){return n instanceof Error?n.message:String(n)}function te(n){return n?.trim().replace(/^v/i,"")||void 0}function ee(n,e){let t=n[e];return typeof t=="string"&&t.trim()?t.trim():void 0}function gi(n){let e=n?.trim().replace(/^npm:/,"");if(!e)return;if(e.startsWith("@")){let r=e.indexOf("@",1);return r===-1?e:e.slice(0,r)}let t=e.indexOf("@");return t===-1?e:e.slice(0,t)}function Or(n){let e=`${n.stdout}
|
|
2
2
|
${n.stderr}`;if(/No install record/i.test(e))throw new Error("OpenClaw reported no managed install record for OpenClaw Code Agent.");let t;try{t=JSON.parse(n.stdout)}catch{throw new Error("OpenClaw returned invalid JSON while inspecting the OpenClaw Code Agent install.")}if(!fe(t)||!fe(t.plugin)||!fe(t.install))throw new Error("OpenClaw inspection did not include the OpenClaw Code Agent plugin and managed install record.");let r=ee(t.plugin,"id"),o=te(ee(t.plugin,"version"));if(r!==rt||!o)throw new Error("OpenClaw inspection returned an unexpected OpenClaw Code Agent plugin identity or version.");let i=ee(t.install,"source"),s=te(ee(t.install,"version")),a=te(ee(t.install,"resolvedVersion"));if(i==="npm"){let l=ee(t.install,"resolvedName")??gi(ee(t.install,"spec"))??gi(ee(t.install,"resolvedSpec"));if(!l)throw new Error("The OpenClaw Code Agent npm install record does not identify its package.");return{pluginVersion:o,install:{source:i,packageName:l,recordedVersion:s,resolvedVersion:a}}}if(i==="clawhub"){let l=ee(t.install,"clawhubPackage");if(!l)throw new Error("The OpenClaw Code Agent ClawHub install record does not identify its package.");return{pluginVersion:o,install:{source:i,packageName:l,recordedVersion:s,resolvedVersion:a}}}throw new Error(`OpenClaw Code Agent self-update does not support managed install source ${i??"unknown"}.`)}function Kl(n,e){return["plugins","install",n.source==="npm"?`${n.packageName}@${e}`:`clawhub:${n.packageName}@${e}`,"--force"]}function ql(n,e,t){if(e.install.source!==n.install.source||e.install.packageName!==n.install.packageName)throw new Error("OpenClaw Code Agent update verification found that the managed install source or package changed.");if(e.pluginVersion!==t)throw new Error(`OpenClaw Code Agent update verification found installed plugin version ${e.pluginVersion}, expected ${t}.`);let r=[e.install.recordedVersion,e.install.resolvedVersion].filter(o=>!!o);if(r.length===0||r.some(o=>o!==t))throw new Error(`OpenClaw Code Agent update verification found managed install version ${r.join("/")||"unknown"}, expected ${t}.`)}function Wr(n){let t=te(n)?.match(/^((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))\.((?:0|[1-9]\d*))$/);if(!t?.[1]||!t[2]||!t[3])return;let r=[Number(t[1]),Number(t[2]),Number(t[3])];return r.every(Number.isSafeInteger)?r:void 0}function Vl(n,e){let t=Wr(n),r=Wr(e);if(!t||!r)return!1;for(let o=0;o<3;o+=1){if(t[o]>r[o])return!0;if(t[o]<r[o])return!1}return!1}function Ul(n){if(!fe(n))return{};let e={};for(let t of["lastCheckedAt","latestVersion","promptedVersion","lastPromptedAt","dismissedVersion","lastDismissedAt","updateInstalledVersion","restartPromptedVersion","lastError"]){let r=n[t];typeof r=="string"&&r.trim()&&(e[t]=r)}return e}function hi(n){if(!(!n?.provider||!n.target||n.provider==="system"||n.target==="system"))return{channel:n.provider,target:n.target,accountId:n.accountId,threadId:n.threadId,sessionKey:n.sessionKey}}function yi(){if(_.fallbackChannel)return ue(_.fallbackChannel)}async function Gl(){let{fetchNpmReleaseMetadata:n}=await import("./chunks/npm-release-client.js"),e=await n(Wl,Bl),t=fe(e)&&typeof e.version=="string"?te(e.version):void 0;return t?{version:t}:void 0}async function jl(n,e){let t=await n("openclaw",["plugins","search",e,"--limit","100","--json"]),r;try{r=JSON.parse(t.stdout)}catch{throw new Error("OpenClaw returned invalid JSON while checking ClawHub for OpenClaw Code Agent updates.")}let o=fe(r)&&Array.isArray(r.results)?r.results:[];for(let i of o){if(!fe(i)||!fe(i.package)||ee(i.package,"name")!==e)continue;let s=te(ee(i.package,"latestVersion"));return s?{version:s}:void 0}}async function zl(n){let e=Or(await n("openclaw",["plugins","inspect",rt,"--json"]));return e.install.source==="npm"?Gl():jl(n,e.install.packageName)}async function Hl(n,e){let t=await Ol(n,e,{timeout:12e4,maxBuffer:1048576});return{stdout:t.stdout?.toString()??"",stderr:t.stderr?.toString()??""}}var zt=class{constructor(e){this.options=e;this.statePath=El(e.stateDir,Fl),this.notifier=e.notifier??new We,this.runCommand=e.runCommand??Hl,this.fetchLatestRelease=e.fetchLatestRelease??(()=>zl(this.runCommand)),this.now=e.now??Date.now}options;statePath;notifier;fetchLatestRelease;runCommand;now;checkInFlight;maybeCheckForUpdate(e={}){this.checkInFlight||(this.checkInFlight=this.checkForUpdate(e).catch(t=>{`${Nr(t)}`}).finally(()=>{this.checkInFlight=void 0}))}async waitForIdle(){await this.checkInFlight}async installConfirmed(e,t){let r=te(e);if(!r||!Wr(r))return"Could not determine which stable OpenClaw Code Agent version to update to.";let o=Or(await this.runCommand("openclaw",["plugins","inspect",rt,"--json"])),i=await this.runCommand("openclaw",Kl(o.install,r));if(/No install record/i.test(`${i.stdout}
|
|
3
3
|
${i.stderr}`))throw new Error("OpenClaw reported no managed install record while updating OpenClaw Code Agent.");let s=Or(await this.runCommand("openclaw",["plugins","inspect",rt,"--json"]));ql(o,s,r);let a=this.readState();this.writeState({...a,updateInstalledVersion:r});let l=hi(t?.route??yi());if(l)try{return await this.sendRestartPrompt(l,r),`OpenClaw Code Agent ${r} installation was verified. Restart confirmation was sent.`}catch(d){`${r}${Nr(d)}`}return[`OpenClaw Code Agent ${r} installation was verified.`,"Restart the Gateway explicitly to load it: openclaw gateway restart"].join(`
|
|
4
4
|
`)}async restartConfirmed(e){let t=te(e);return await this.runCommand("openclaw",["gateway","restart"]),t?`Gateway restart requested for OpenClaw Code Agent ${t}.`:"Gateway restart requested."}dismiss(e){return this.postpone(e,"Dismissed")}remindLater(e){return this.postpone(e,"Will remind later about")}postpone(e,t){let r=te(e),o=this.readState();return this.writeState({...o,...r?{dismissedVersion:r,lastDismissedAt:new Date(this.now()).toISOString()}:{}}),r?`${t} OpenClaw Code Agent ${r} update reminder.`:`${t} OpenClaw Code Agent update reminder.`}async checkForUpdate(e){let t=this.readState(),r=t.lastCheckedAt?Date.parse(t.lastCheckedAt):Number.NaN;if(Number.isFinite(r)&&this.now()-r<Si){await this.promptFromState(t,e);return}let o=new Date(this.now()).toISOString(),i={...t,lastCheckedAt:o};delete i.lastError,this.writeState(i);try{let s=await this.fetchLatestRelease(),a=te(s?.version),l={...this.readState(),latestVersion:a};delete l.lastError,this.writeState(l),await this.promptFromState(l,e)}catch(s){throw this.writeState({...this.readState(),lastError:Nr(s)}),s}}async promptFromState(e,t){let r=te(e.latestVersion);if(!Vl(r,this.options.currentVersion)||!this.shouldPromptForVersion(e,r))return;let o=hi(t.route??yi());o&&(await this.sendUpdatePrompt(o,r),this.writeState({...this.readState(),latestVersion:r,promptedVersion:r,lastPromptedAt:new Date(this.now()).toISOString()}))}async sendUpdatePrompt(e,t){await this.notifier.send(e,[`OpenClaw Code Agent update available: ${this.options.currentVersion} -> ${t}.`,"","Update now will reinstall the exact approved version from OpenClaw Code Agent's recorded npm or ClawHub source, then verify it.","If the update succeeds, OpenClaw Code Agent will ask separately before restarting the Gateway."].join(`
|
|
@@ -11,13 +11,13 @@ ${i.stderr}`))throw new Error("OpenClaw reported no managed install record while
|
|
|
11
11
|
`):"";return{kind:"blocked",text:["Resume-first protection blocked a fresh launch.","",F,V,["If you intentionally want a brand-new independent session here, call:"," agent_launch(prompt='<new task>', force_new_session=true)"].join(`
|
|
12
12
|
`)].filter(Boolean).join(`
|
|
13
13
|
|
|
14
|
-
`)}}}let c=n.resume_session_id,h=c?t.resolve?.(c):void 0,v=c?t.getPersistedSession?.(c):void 0;if(c){let T=t.resolveBackendConversationId?.(c)??t.resolveHarnessSessionId?.(c);if(!T)return{kind:"error",text:`Error: Could not resolve resume_session_id "${c}" to a session ID. Use agent_sessions to list available sessions.`};c=T}let{resumeSessionId:
|
|
14
|
+
`)}}}let c=n.resume_session_id,h=c?t.resolve?.(c):void 0,v=c?t.getPersistedSession?.(c):void 0;if(c){let T=t.resolveBackendConversationId?.(c)??t.resolveHarnessSessionId?.(c);if(!T)return{kind:"error",text:`Error: Could not resolve resume_session_id "${c}" to a session ID. Use agent_sessions to list available sessions.`};c=T}let{resumeSessionId:b,clearedPersistedCodexResume:A}=Be({requestedResumeSessionId:c,activeSession:h?{harnessSessionId:h.backendConversationId??h.harnessSessionId}:void 0,persistedSession:v?{harness:v.harness,backendRef:v.backendRef}:void 0}),I=n.permission_mode??_.permissionMode,R=n.plan_approval??_.planApproval,m=Jt({ctx:e,route:De(e,g,S),recoveredRouteSource:v,operation:"coding session"});if(m.kind==="error")return m;let w=m.route;return{kind:"resolved",workdir:r,harness:o,resolvedModel:u,permissionMode:I,planApproval:R,originChannel:m.recovered?w.accountId?`${w.provider}|${w.accountId}|${w.target}`:`${w.provider}|${w.target}`:g,originThreadId:m.recovered?w.threadId:y,originSessionKey:m.recovered?w.sessionKey:S,route:w,resumeSessionId:b,resolvedResumeId:c,clearedPersistedCodexResume:A,reasoningEffort:ce(o),fastMode:_e(o)}}function ge(n){let e=n.harness?.trim(),t=n.model?.trim();return e&&t?`${e} | ${t}`:e?`${e} | default`:t}function se(n){if(!Number.isFinite(n))return"0s";let e=Math.floor(n/1e3),t=Math.floor(e/60),r=e%60;return t>0?`${t}m${r}s`:`${r}s`}var od=new Set(["a","an","the","is","are","was","were","be","been","being","have","has","had","do","does","did","will","would","could","should","may","might","shall","can","need","must","i","me","my","we","our","you","your","it","its","he","she","to","of","in","for","on","with","at","by","from","as","into","through","about","that","this","these","those","and","or","but","if","then","so","not","no","please","just","also","very","all","some","any","each","make","write","create","build","implement","add","update"]);function Ri(n){let t=n.toLowerCase().replace(/[^a-z0-9\s-]/g," ").split(/\s+/).filter(r=>r.length>1&&!od.has(r)).slice(0,3);return t.length===0?"session":t.join("-")}var bi={starting:"π‘",running:"π’",completed:"β
",failed:"β",killed:"β",awaiting_plan_decision:"π",awaiting_user_input:"β",awaiting_worktree_decision:"πΏ",suspended:"βΈοΈ",terminal:"π"};function id(n){let e=n.worktreeLifecycle?.state??n.worktreeState;return n.worktreeMerged||e==="merged"?"[merged β]":e==="released"?"[released]":n.worktreePrUrl?`[PR: ${n.worktreePrUrl}]`:e==="pr_open"?"[PR open]":e==="dismissed"?"[dismissed]":e==="no_change"?"[no change]":"[not merged]"}function Ai(n){let e=bi[n.phase]??bi[n.status]??"β",t=se(n.duration),r=n.multiTurn?"multi-turn":"single",o=n.prompt.length>80?n.prompt.slice(0,80)+"...":n.prompt,i=n.costUsd>0?` | $${n.costUsd.toFixed(2)}`:"",s=[`${e} ${n.name} [${n.id}] (${t}${i}) β ${r}`,` π ${n.workdir}`,` π "${o}"`];if(n.worktreePath&&n.worktreeBranch&&s.push(` πΏ Worktree: ${n.worktreeBranch} ${id(n)}`),n.phase!==n.status&&s.push(` βοΈ Phase: ${n.phase}`),n.lifecycle&&n.lifecycle!==n.phase&&s.push(` π Lifecycle: ${n.lifecycle}`),(n.requestedPermissionMode||n.currentPermissionMode||n.approvalExecutionState)&&s.push(` π Approval: ${n.approvalExecutionState??"unknown"} (requested=${n.requestedPermissionMode??"unknown"}, effective=${n.currentPermissionMode??"unknown"})`),n.resumable&&s.push(" β©οΈ Resumable: yes"),n.recovered&&n.runtimeRecovery){let l=n.runtimeRecovery?.reason?` (${n.runtimeRecovery.reason})`:"";s.push(` β»οΈ Recovered: persisted metadata only; no live process to kill${l}`),s.push(` π©Ί Recovery: raw=${n.runtimeRecovery.rawStatus??"unknown"}/${n.runtimeRecovery.rawLifecycle??"unknown"}/${n.runtimeRecovery.rawRuntimeState??"unknown"} β normalized=${n.runtimeRecovery.normalizedStatus}/${n.runtimeRecovery.normalizedLifecycle??"unknown"}/${n.runtimeRecovery.normalizedRuntimeState??"unknown"}`)}else n.recovered&&s.push(" πΎ Persisted: no live runtime process in this Gateway");n.harness?s.push(` π§° Harness | model: ${ge({harness:n.harness,model:n.model})}`):n.model&&s.push(` π§° Harness | model: ${n.model}`);let a=C(n);return a&&s.push(` π Backend ID: ${a}`),n.resumeSessionId&&s.push(` β©οΈ Resumed from: ${n.resumeSessionId}${n.forkSession?" (forked)":""}`),s.join(`
|
|
15
15
|
`)}function Zt(n,e){let t=n.sessionsWithDuration>0?n.totalDurationMs/n.sessionsWithDuration:0,{completed:r,failed:o,killed:i}=n.sessionsByStatus,s=["π OpenClaw Code Agent Stats","","π Sessions",` Launched: ${n.totalLaunched}`,` Running: ${e}`,` Completed: ${r}`,` Failed: ${o}`,` Killed: ${i}`,"",`β±οΈ Average duration: ${t>0?se(t):"n/a"}`,`π΅ Estimated API cost: $${n.totalCostUsd.toFixed(2)}`];if(n.mostExpensive){let a=n.mostExpensive;s.push("","π Notable session",` ${a.name} [${a.id}]`,` π΅ $${a.costUsd.toFixed(2)}`,` π "${a.prompt}"`)}return s.join(`
|
|
16
16
|
`)}function G(n,e){return e<=0?"":n.length<=e?n:e<=3?".".repeat(e):n.slice(0,e-3)+"..."}function Ii(n,e){let t=n.split(`
|
|
17
17
|
`),r=[],o=0;for(let i=t.length-1;i>=0;i--){let s=t[i].length+(r.length>0?1:0);if(o+s>e&&r.length>0)break;r.unshift(t[i]),o+=s}return r.join(`
|
|
18
18
|
`)}function Ti(n,e){let t=n.split(`
|
|
19
19
|
`),r=[],o=0;for(let i=0;i<t.length;i++){let s=t[i].length+(r.length>0?1:0);if(o+s>e&&r.length>0)break;r.push(t[i]),o+=s}return r.join(`
|
|
20
|
-
`)}var sd="openclaw-code-agent",ad=160,en={create(){},progress(){},finalize(){}};function tn(n,e){let t=e instanceof Error?e.message:String(e);`${n}${t}`}function Lr(n,e){if(e.applied===!1){let t=e.code?` (${e.code})`:"";`${n}${t}`}}function ld(n){let e=n.prompt.trim().replace(/\s+/g," ");return G(e||n.name,ad)}function xi(n){if(n.status==="starting"||n.lifecycle==="starting")return"Starting";if(n.lifecycle==="active")return"Running";if(n.lifecycle==="awaiting_plan_decision")return"Waiting for plan approval";if(n.lifecycle==="awaiting_user_input")return"Waiting for input";if(n.lifecycle==="awaiting_worktree_decision")return"Waiting for worktree decision";if(n.lifecycle==="suspended")return"Suspended after idle timeout"}function Ci(n){if(n.status==="completed")return"succeeded";if(n.status==="failed")return"failed";if(n.status==="killed")return n.killReason==="idle-timeout"||n.killReason==="startup-timeout"?"timed_out":"cancelled"}function nn(n,e){return n==="completed"?"Completed":n==="failed"?"Failed":e==="idle-timeout"?"Timed out after idle timeout":e==="startup-timeout"?"Timed out during startup":e==="shutdown"?"Cancelled during shutdown":e==="user"?"Cancelled by user":"Cancelled"}function dd(n){return rn(n.lifecycle)}function rn(n){return n==="awaiting_plan_decision"||n==="awaiting_user_input"||n==="awaiting_worktree_decision"||n==="suspended"}function ud(n){if(n.pendingPlanApproval||n.pendingWorktreeDecisionSince)return!0;if(n.runtimeRecovery?.reason==="persisted-running-without-runtime"){let e=n.runtimeRecovery.rawLifecycle;return e==="suspended"?n.runtimeRecovery.rawResumable===!0||n.resumable===!0:rn(e)}return n.lifecycle==="suspended"?n.resumable===!0:rn(n.lifecycle)}function cd(n){if(n.runtimeRecovery?.reason==="persisted-running-without-runtime"){let e=n.runtimeRecovery.rawLifecycle;if(rn(e))return e}return n.lifecycle}function Fr(n,e,t){return{phase:e,integration:"phase-1-managed-task-flow",sessionId:n.id,sessionName:n.name,sessionStatus:n.status,sessionLifecycle:n.lifecycle,summary:t}}function pd(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.createManaged=="function"&&typeof e.resume=="function"&&typeof e.setWaiting=="function"&&typeof e.finish=="function"&&typeof e.fail=="function"}function on(n,e){if(e.applied)return e.flow;let t=e.current;return t?.flowId&&typeof t.revision=="number"?t:n}var Br=class{constructor(e){this.taskFlow=e}taskFlow;flow;finalized=!1;lastProgressKey;create(e){if(this.flow||this.finalized)return;let t="Starting",r=Date.now();try{this.flow=this.taskFlow.createManaged({controllerId:sd,goal:ld(e),status:"running",notifyPolicy:"silent",currentStep:t,stateJson:Fr(e,"created",t),createdAt:e.startedAt,updatedAt:r}),e.taskFlowMirror=this.flow,this.lastProgressKey=this.progressKey(e,t)}catch(o){tn("create",o)}}progress(e){if(!this.flow||this.finalized)return;let t=xi(e);if(!t)return;let r=this.progressKey(e,t);if(r!==this.lastProgressKey)try{let o=Fr(e,"progress",t),i=Date.now(),s=dd(e)?this.taskFlow.setWaiting({flowId:this.flow.flowId,expectedRevision:this.flow.revision,currentStep:t,stateJson:o,waitJson:{reason:t,sessionId:e.id},blockedSummary:t,updatedAt:i}):this.taskFlow.resume({flowId:this.flow.flowId,expectedRevision:this.flow.revision,status:"running",currentStep:t,stateJson:o,updatedAt:i});this.flow=on(this.flow,s),this.flow&&(e.taskFlowMirror=this.flow),this.lastProgressKey=r}catch(o){tn("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let t=Ci(e);if(!t)return;let r=t==="succeeded"?"Completed":t==="failed"?"Failed":nn(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...Fr(e,"terminal",r),terminalStatus:t,terminalSummary:nn(e.status,e.killReason),...e.status==="failed"&&e.error?{error:e.error}:{}},s=t==="succeeded"?this.taskFlow.finish({flowId:this.flow.flowId,expectedRevision:this.flow.revision,stateJson:i,updatedAt:o,endedAt:o}):this.taskFlow.fail({flowId:this.flow.flowId,expectedRevision:this.flow.revision,stateJson:i,blockedSummary:nn(e.status,e.killReason),updatedAt:o,endedAt:o});Lr("finalize",s),this.flow=on(this.flow,s),this.flow&&(e.taskFlowMirror=this.flow),this.finalized=!0}catch(o){tn("finalize",o)}}progressKey(e,t){return`${e.status}:${e.lifecycle}:${t}`}};function md(n){return n==="succeeded"||n==="failed"||n==="cancelled"||n==="lost"}function fd(n){if(!n?.trim())return;let e=wr()?.fromToolContext;if(typeof e!="function")return;let t=e({sessionKey:n});if(!t||typeof t!="object")return;let r=t;if(!(typeof r.setWaiting!="function"||typeof r.finish!="function"||typeof r.fail!="function"))return{setWaiting:r.setWaiting,finish:r.finish,fail:r.fail}}function gd(n){return n.originSessionKey??n.route?.sessionKey}function hd(n){return n.runtimeRecovery?.reason==="persisted-running-without-runtime"?"Lost after OpenClaw Code Agent restart without live process":nn(n.status,n.killReason??"unknown")}function Mi(n){let e=n.taskFlowMirror?{...n.taskFlowMirror}:void 0;if(!e||md(e.status))return;let t=fd(gd(n));if(!t)return;let r=Date.now();if(ud(n)){let d=xi({status:n.status,lifecycle:cd(n)??"suspended"})??"Waiting",u=t.setWaiting({flowId:e.flowId,expectedRevision:e.revision,currentStep:d,stateJson:{phase:"progress",integration:"phase-1-managed-task-flow",sessionId:n.sessionId,sessionName:n.name,sessionStatus:n.status,sessionLifecycle:n.lifecycle,summary:d,reconciled:!0},waitJson:{reason:d,sessionId:n.sessionId},blockedSummary:d,updatedAt:r});return Lr("reconcile-waiting",u),on(e,u)}let o=Ci({status:n.status,killReason:n.killReason??"unknown"})??"failed",i=hd(n),s=n.completedAt??r,a={phase:"terminal",integration:"phase-1-managed-task-flow",sessionId:n.sessionId,sessionName:n.name,sessionStatus:n.status,sessionLifecycle:n.lifecycle,summary:i,terminalStatus:n.runtimeRecovery?.reason==="persisted-running-without-runtime"?"lost":o,terminalSummary:i,reconciled:!0,runtimeRecovery:n.runtimeRecovery},l=o==="succeeded"?t.finish({flowId:e.flowId,expectedRevision:e.revision,stateJson:a,updatedAt:s,endedAt:s}):t.fail({flowId:e.flowId,expectedRevision:e.revision,stateJson:a,blockedSummary:i,updatedAt:s,endedAt:s});return Lr("reconcile-terminal",l),on(e,l)}function sn(n){if(!n.sessionKey?.trim())return en;try{let e=wr()?.fromToolContext;if(typeof e!="function")return en;let t=e(n);return pd(t)?new Br(t):en}catch(e){return tn("resolve",e),en}}function yd(...n){let e;for(let t of n)t!=null&&(e=e==null?t:Math.max(e,t));return e}function Kr(n){if(n.actionablePlanDecisionVersion!=null)return n.actionablePlanDecisionVersion;let e=yd(n.approvalPromptRequiredVersion,n.approvalPromptVersion);return e??n.canonicalPlanPromptVersion??n.planDecisionVersion}function qr(n,e){return n.kind==="plan-approve"&&n.planDecisionVersion!=null&&e.approvalState==="approved"&&!e.pendingPlanApproval&&e.planDecisionVersion===n.planDecisionVersion+1}function _i(n,e){return n.worktreePath&&e&&!e.worktreePath?{...n,worktreePath:void 0,worktreeBranch:void 0,worktreeState:e.worktreeState,worktreeDisposition:e.worktreeDisposition,worktreeLifecycle:e.worktreeLifecycle,pendingWorktreeDecisionSince:e.pendingWorktreeDecisionSince,lastWorktreeReminderAt:e.lastWorktreeReminderAt,worktreeDecisionSnoozedUntil:e.worktreeDecisionSnoozedUntil,worktreeMerged:e.worktreeMerged,worktreeMergedAt:e.worktreeMergedAt,worktreeDismissedAt:e.worktreeDismissedAt,worktreeRemoteOutcome:e.worktreeRemoteOutcome}:n}function an(n,e){let t=Kr(n);if(!n.pendingPlanApproval)return{permissionMode:e,approvalApplied:!1,patch:{}};let r={planApprovalContext:n.planApprovalContext,canonicalPlanPromptVersion:n.canonicalPlanPromptVersion,approvalPromptRequiredVersion:n.approvalPromptRequiredVersion,approvalPromptVersion:n.approvalPromptVersion,approvalPromptStatus:n.approvalPromptStatus,approvalPromptTransport:n.approvalPromptTransport,approvalPromptMessageKind:n.approvalPromptMessageKind,approvalPromptLastAttemptAt:n.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:n.approvalPromptDeliveredAt,approvalPromptFailedAt:n.approvalPromptFailedAt};return e==="bypassPermissions"&&n.actionablePlanDecisionVersion!=null&&n.actionablePlanDecisionVersion>0&&t===n.actionablePlanDecisionVersion&&n.approvalState!=="rejected"?{permissionMode:"bypassPermissions",approvalApplied:!0,decisionVersion:t,patch:{...r,pendingPlanApproval:!1,approvalState:"approved",approvalExecutionState:"awaiting_plan_output",planModeApproved:!0,planDecisionVersion:t+1,actionablePlanDecisionVersion:void 0}}:{permissionMode:"plan",approvalApplied:!1,decisionVersion:t,patch:{...r,pendingPlanApproval:!0,approvalState:n.approvalState??"pending",planDecisionVersion:t??n.planDecisionVersion,actionablePlanDecisionVersion:n.actionablePlanDecisionVersion}}}function Sd(n){return n instanceof Error?n.message:String(n)}function Di(n,e){return n?("id"in n?n.id:n.sessionId)??e??"unknown-session":e??"unknown-session"}function kd(n){return!n||typeof n!="object"?!1:typeof n.prompt=="string"}function vd(n){return!!n&&typeof n=="object"&&typeof n.formatLaunchResult=="function"}function Pd(n){return!!n&&typeof n=="object"&&typeof n.checkRepoPolicyForLaunch=="function"&&typeof n.requestRepoPolicyForLaunch=="function"}function $i(n){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn β they stay open for follow-up messages via agent_respond. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:p.Object({prompt:p.String({description:"The task prompt to execute"}),name:p.Optional(p.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:p.Optional(p.String({description:"Working directory (defaults to cwd)"})),model:p.Optional(p.String({description:"Model name to use"})),system_prompt:p.Optional(p.String({description:"Additional system prompt"})),allowed_tools:p.Optional(p.Array(p.String(),{description:"List of allowed tools"})),resume_session_id:p.Optional(p.String({description:"Session reference to continue or fork from. Prefer the plugin session ID shown by agent_launch or agent_sessions; persisted backend conversation IDs also resolve when available."})),fork_session:p.Optional(p.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:p.Optional(p.Boolean({description:"Bypass resume-first protection and start a brand-new linked session even when a resumable or active linked session already exists."})),permission_mode:p.Optional(p.Union([p.Literal("default"),p.Literal("plan"),p.Literal("bypassPermissions")],{description:"Permission mode: 'default' (plugin-managed interactive execution), 'plan' (present the plan first and block implementation until approval), 'bypassPermissions' (fully autonomous execution). Defaults to plugin config ('plan' by default)."})),plan_approval:p.Optional(p.Union([p.Literal("ask"),p.Literal("delegate"),p.Literal("approve")],{description:"Plan approval policy for this session: 'ask' (send a decision-grade plan brief to the user with Approve/Revise/Reject buttons), 'delegate' (orchestrator must review the full plan, then either approve directly or escalate back to the user with the same decision brief and buttons), 'approve' (auto-approve after verification). Overrides the plugin-level planApproval setting."})),harness:p.Optional(p.String({description:"Agent harness to use ('claude-code', 'codex', or experimental 'opencode'). Defaults to the plugin defaultHarness."})),worktree_strategy:p.Optional(p.Union([p.Literal("off"),p.Literal("manual"),p.Literal("ask"),p.Literal("delegate"),p.Literal("auto-merge"),p.Literal("auto-pr")],{description:"Worktree strategy: 'off' (no worktree), 'manual' (create worktree but no auto merge-back), 'ask' (prompt user with Merge/Open PR/Later/Discard buttons), 'delegate' (orchestrator decides), 'auto-merge' (merge automatically), 'auto-pr' (open/update a PR automatically). Defaults to the plugin config when unset."})),worktree_base_branch:p.Optional(p.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:p.Optional(p.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex' for fork-to-upstream workflow). If not set, auto-detected from 'upstream' remote or defaults to 'origin'."}))}),async execute(e,t){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!kd(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};t.agentId&&`${t.agentId}${n.agentId}`;try{let r=Xt(t,n,k);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:l,originChannel:d,originThreadId:u,originSessionKey:f,route:g,resumeSessionId:S,resolvedResumeId:y,clearedPersistedCodexResume:c,reasoningEffort:h,fastMode:v}=r,R=t.resume_session_id?k.resolve(t.resume_session_id)??k.getPersistedSession(t.resume_session_id):void 0,A=!t.fork_session&&R?ke(R):void 0;if(A?.kind==="direct")return{content:[{type:"text",text:`Session ${R.name} [${Di(R,t.resume_session_id)}] is already running. Use agent_respond(session='${t.resume_session_id}', message='<next instruction>') instead of agent_launch(resume_session_id=...).`}]};if(A?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${R.name} [${Di(R,t.resume_session_id)}] (${A.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let I=R&&"resumedFromSessionName"in R?R.resumedFromSessionName:void 0,b=A?.kind==="resume"&&!t.fork_session?I??R?.name:void 0,m=b&&!t.name?b:t.name,w=t.worktree_strategy??_.defaultWorktreeStrategy??"off",T=t.fork_session?void 0:A?.kind==="resume"||A?.kind==="relaunch"?A.stableSessionId:void 0,F=A?.kind==="resume"&&!t.fork_session&&R?an(R,a):{permissionMode:a,approvalApplied:!1,patch:{}};if(w!=="off"&&Pd(k)&&k.checkRepoPolicyForLaunch(o,t.worktree_strategy).ok===!1)return{content:[{type:"text",text:k.requestRepoPolicyForLaunch({route:g,prompt:t.prompt,workdir:o,name:m,model:s,reasoningEffort:h,fastMode:v,systemPrompt:t.system_prompt,allowedTools:t.allowed_tools,resumeSessionId:A?.kind==="resume"?A.resumeSessionId:S,resumedFromSessionName:b,resumeWorktreeFrom:T??t.resume_session_id??y,sessionIdOverride:T,clearedPersistedCodexResume:c,forkSession:S?t.fork_session:!1,forceNewSession:t.force_new_session,permissionMode:a,planApproval:l,harness:i,worktreeStrategy:t.worktree_strategy,worktreeBaseBranch:t.worktree_base_branch,worktreePrTargetRepo:t.worktree_pr_target_repo,originAgentId:n.agentId||void 0})}]};let V=k.spawn({prompt:t.prompt,sessionIdOverride:T,name:m,workdir:o,model:s,reasoningEffort:h,fastMode:v,systemPrompt:t.system_prompt,allowedTools:t.allowed_tools,resumeSessionId:A?.kind==="resume"?A.resumeSessionId:S,resumedFromSessionName:b,resumeWorktreeFrom:T??t.resume_session_id??y,forkSession:S?t.fork_session:!1,multiTurn:!0,permissionMode:F.permissionMode,planApproval:l,codexApprovalPolicy:i==="codex"?"never":void 0,...F.patch,originChannel:d,originThreadId:u,originAgentId:n.agentId||void 0,originSessionKey:f,route:g,harness:i,taskLifecycle:sn(n),worktreeStrategy:t.worktree_strategy,worktreeBaseBranch:t.worktree_base_branch,worktreePrTargetRepo:t.worktree_pr_target_repo});return{content:[{type:"text",text:vd(k)?k.formatLaunchResult({prompt:t.prompt,workdir:o,harness:i,permissionMode:F.permissionMode,planApproval:l,forceNewSession:t.force_new_session,resumeSessionId:t.resume_session_id,resumeSessionName:b,forkSession:t.fork_session,clearedPersistedCodexResume:c},V):Ht({prompt:t.prompt,workdir:o,harness:i,permissionMode:F.permissionMode,planApproval:l,resumeSessionId:t.resume_session_id,resumeSessionName:b,forkSession:t.fork_session,forceNewSession:t.force_new_session,clearedPersistedCodexResume:c},{id:V.id,name:V.name,model:V.model,reasoningEffort:V.reasoningEffort??ce(i),fastMode:V.fastMode??v,worktreeStrategy:V.worktreeStrategy??t.worktree_strategy??_.defaultWorktreeStrategy??"off",repoIntegrationPolicy:V.repoIntegrationPolicy,repoProvider:V.repoProvider,worktreePath:V.worktreePath,originalWorkdir:V.originalWorkdir})}]}}catch(r){let o=Sd(r),i=o.includes("Max sessions")?"":`
|
|
20
|
+
`)}var sd="openclaw-code-agent",ad=160,en={create(){},progress(){},finalize(){}};function tn(n,e){let t=e instanceof Error?e.message:String(e);`${n}${t}`}function Lr(n,e){if(e.applied===!1){let t=e.code?` (${e.code})`:"";`${n}${t}`}}function ld(n){let e=n.prompt.trim().replace(/\s+/g," ");return G(e||n.name,ad)}function xi(n){if(n.status==="starting"||n.lifecycle==="starting")return"Starting";if(n.lifecycle==="active")return"Running";if(n.lifecycle==="awaiting_plan_decision")return"Waiting for plan approval";if(n.lifecycle==="awaiting_user_input")return"Waiting for input";if(n.lifecycle==="awaiting_worktree_decision")return"Waiting for worktree decision";if(n.lifecycle==="suspended")return"Suspended after idle timeout"}function Ci(n){if(n.status==="completed")return"succeeded";if(n.status==="failed")return"failed";if(n.status==="killed")return n.killReason==="idle-timeout"||n.killReason==="startup-timeout"?"timed_out":"cancelled"}function nn(n,e){return n==="completed"?"Completed":n==="failed"?"Failed":e==="idle-timeout"?"Timed out after idle timeout":e==="startup-timeout"?"Timed out during startup":e==="shutdown"?"Cancelled during shutdown":e==="user"?"Cancelled by user":"Cancelled"}function dd(n){return rn(n.lifecycle)}function rn(n){return n==="awaiting_plan_decision"||n==="awaiting_user_input"||n==="awaiting_worktree_decision"||n==="suspended"}function ud(n){if(n.pendingPlanApproval||n.pendingWorktreeDecisionSince)return!0;if(n.runtimeRecovery?.reason==="persisted-running-without-runtime"){let e=n.runtimeRecovery.rawLifecycle;return e==="suspended"?n.runtimeRecovery.rawResumable===!0||n.resumable===!0:rn(e)}return n.lifecycle==="suspended"?n.resumable===!0:rn(n.lifecycle)}function cd(n){if(n.runtimeRecovery?.reason==="persisted-running-without-runtime"){let e=n.runtimeRecovery.rawLifecycle;if(rn(e))return e}return n.lifecycle}function Fr(n,e,t){return{phase:e,integration:"phase-1-managed-task-flow",sessionId:n.id,sessionName:n.name,sessionStatus:n.status,sessionLifecycle:n.lifecycle,summary:t}}function pd(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.createManaged=="function"&&typeof e.resume=="function"&&typeof e.setWaiting=="function"&&typeof e.finish=="function"&&typeof e.fail=="function"}function on(n,e){if(e.applied)return e.flow;let t=e.current;return t?.flowId&&typeof t.revision=="number"?t:n}var Br=class{constructor(e){this.taskFlow=e}taskFlow;flow;finalized=!1;lastProgressKey;create(e){if(this.flow||this.finalized)return;let t="Starting",r=Date.now();try{this.flow=this.taskFlow.createManaged({controllerId:sd,goal:ld(e),status:"running",notifyPolicy:"silent",currentStep:t,stateJson:Fr(e,"created",t),createdAt:e.startedAt,updatedAt:r}),e.taskFlowMirror=this.flow,this.lastProgressKey=this.progressKey(e,t)}catch(o){tn("create",o)}}progress(e){if(!this.flow||this.finalized)return;let t=xi(e);if(!t)return;let r=this.progressKey(e,t);if(r!==this.lastProgressKey)try{let o=Fr(e,"progress",t),i=Date.now(),s=dd(e)?this.taskFlow.setWaiting({flowId:this.flow.flowId,expectedRevision:this.flow.revision,currentStep:t,stateJson:o,waitJson:{reason:t,sessionId:e.id},blockedSummary:t,updatedAt:i}):this.taskFlow.resume({flowId:this.flow.flowId,expectedRevision:this.flow.revision,status:"running",currentStep:t,stateJson:o,updatedAt:i});this.flow=on(this.flow,s),this.flow&&(e.taskFlowMirror=this.flow),this.lastProgressKey=r}catch(o){tn("progress",o)}}finalize(e){if(!this.flow||this.finalized)return;let t=Ci(e);if(!t)return;let r=t==="succeeded"?"Completed":t==="failed"?"Failed":nn(e.status,e.killReason);try{let o=e.completedAt??Date.now(),i={...Fr(e,"terminal",r),terminalStatus:t,terminalSummary:nn(e.status,e.killReason),...e.status==="failed"&&e.error?{error:e.error}:{}},s=t==="succeeded"?this.taskFlow.finish({flowId:this.flow.flowId,expectedRevision:this.flow.revision,stateJson:i,updatedAt:o,endedAt:o}):this.taskFlow.fail({flowId:this.flow.flowId,expectedRevision:this.flow.revision,stateJson:i,blockedSummary:nn(e.status,e.killReason),updatedAt:o,endedAt:o});Lr("finalize",s),this.flow=on(this.flow,s),this.flow&&(e.taskFlowMirror=this.flow),this.finalized=!0}catch(o){tn("finalize",o)}}progressKey(e,t){return`${e.status}:${e.lifecycle}:${t}`}};function md(n){return n==="succeeded"||n==="failed"||n==="cancelled"||n==="lost"}function fd(n){if(!n?.trim())return;let e=wr()?.fromToolContext;if(typeof e!="function")return;let t=e({sessionKey:n});if(!t||typeof t!="object")return;let r=t;if(!(typeof r.setWaiting!="function"||typeof r.finish!="function"||typeof r.fail!="function"))return{setWaiting:r.setWaiting,finish:r.finish,fail:r.fail}}function gd(n){return n.originSessionKey??n.route?.sessionKey}function hd(n){return n.runtimeRecovery?.reason==="persisted-running-without-runtime"?"Lost after OpenClaw Code Agent restart without live process":nn(n.status,n.killReason??"unknown")}function Mi(n){let e=n.taskFlowMirror?{...n.taskFlowMirror}:void 0;if(!e||md(e.status))return;let t=fd(gd(n));if(!t)return;let r=Date.now();if(ud(n)){let d=xi({status:n.status,lifecycle:cd(n)??"suspended"})??"Waiting",u=t.setWaiting({flowId:e.flowId,expectedRevision:e.revision,currentStep:d,stateJson:{phase:"progress",integration:"phase-1-managed-task-flow",sessionId:n.sessionId,sessionName:n.name,sessionStatus:n.status,sessionLifecycle:n.lifecycle,summary:d,reconciled:!0},waitJson:{reason:d,sessionId:n.sessionId},blockedSummary:d,updatedAt:r});return Lr("reconcile-waiting",u),on(e,u)}let o=Ci({status:n.status,killReason:n.killReason??"unknown"})??"failed",i=hd(n),s=n.completedAt??r,a={phase:"terminal",integration:"phase-1-managed-task-flow",sessionId:n.sessionId,sessionName:n.name,sessionStatus:n.status,sessionLifecycle:n.lifecycle,summary:i,terminalStatus:n.runtimeRecovery?.reason==="persisted-running-without-runtime"?"lost":o,terminalSummary:i,reconciled:!0,runtimeRecovery:n.runtimeRecovery},l=o==="succeeded"?t.finish({flowId:e.flowId,expectedRevision:e.revision,stateJson:a,updatedAt:s,endedAt:s}):t.fail({flowId:e.flowId,expectedRevision:e.revision,stateJson:a,blockedSummary:i,updatedAt:s,endedAt:s});return Lr("reconcile-terminal",l),on(e,l)}function sn(n){if(!n.sessionKey?.trim())return en;try{let e=wr()?.fromToolContext;if(typeof e!="function")return en;let t=e(n);return pd(t)?new Br(t):en}catch(e){return tn("resolve",e),en}}function yd(...n){let e;for(let t of n)t!=null&&(e=e==null?t:Math.max(e,t));return e}function Kr(n){if(n.actionablePlanDecisionVersion!=null)return n.actionablePlanDecisionVersion;let e=yd(n.approvalPromptRequiredVersion,n.approvalPromptVersion);return e??n.canonicalPlanPromptVersion??n.planDecisionVersion}function qr(n,e){return n.kind==="plan-approve"&&n.planDecisionVersion!=null&&e.approvalState==="approved"&&!e.pendingPlanApproval&&e.planDecisionVersion===n.planDecisionVersion+1}function _i(n,e){return n.worktreePath&&e&&!e.worktreePath?{...n,worktreePath:void 0,worktreeBranch:void 0,worktreeState:e.worktreeState,worktreeDisposition:e.worktreeDisposition,worktreeLifecycle:e.worktreeLifecycle,pendingWorktreeDecisionSince:e.pendingWorktreeDecisionSince,lastWorktreeReminderAt:e.lastWorktreeReminderAt,worktreeDecisionSnoozedUntil:e.worktreeDecisionSnoozedUntil,worktreeMerged:e.worktreeMerged,worktreeMergedAt:e.worktreeMergedAt,worktreeDismissedAt:e.worktreeDismissedAt,worktreeRemoteOutcome:e.worktreeRemoteOutcome}:n}function an(n,e){let t=Kr(n);if(!n.pendingPlanApproval)return{permissionMode:e,approvalApplied:!1,patch:{}};let r={planApprovalContext:n.planApprovalContext,canonicalPlanPromptVersion:n.canonicalPlanPromptVersion,approvalPromptRequiredVersion:n.approvalPromptRequiredVersion,approvalPromptVersion:n.approvalPromptVersion,approvalPromptStatus:n.approvalPromptStatus,approvalPromptTransport:n.approvalPromptTransport,approvalPromptMessageKind:n.approvalPromptMessageKind,approvalPromptLastAttemptAt:n.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:n.approvalPromptDeliveredAt,approvalPromptFailedAt:n.approvalPromptFailedAt};return e==="bypassPermissions"&&n.actionablePlanDecisionVersion!=null&&n.actionablePlanDecisionVersion>0&&t===n.actionablePlanDecisionVersion&&n.approvalState!=="rejected"?{permissionMode:"bypassPermissions",approvalApplied:!0,decisionVersion:t,patch:{...r,pendingPlanApproval:!1,approvalState:"approved",approvalExecutionState:"awaiting_plan_output",planModeApproved:!0,planDecisionVersion:t+1,actionablePlanDecisionVersion:void 0}}:{permissionMode:"plan",approvalApplied:!1,decisionVersion:t,patch:{...r,pendingPlanApproval:!0,approvalState:n.approvalState??"pending",planDecisionVersion:t??n.planDecisionVersion,actionablePlanDecisionVersion:n.actionablePlanDecisionVersion}}}function Sd(n){return n instanceof Error?n.message:String(n)}function Di(n,e){return n?("id"in n?n.id:n.sessionId)??e??"unknown-session":e??"unknown-session"}function kd(n){return!n||typeof n!="object"?!1:typeof n.prompt=="string"}function vd(n){return!!n&&typeof n=="object"&&typeof n.formatLaunchResult=="function"}function Pd(n){return!!n&&typeof n=="object"&&typeof n.checkRepoPolicyForLaunch=="function"&&typeof n.requestRepoPolicyForLaunch=="function"}function $i(n){return{name:"agent_launch",description:"Launch a coding agent session in background to execute a development task. Sessions are multi-turn β they stay open for follow-up messages via agent_respond. Supports resuming previous sessions. Returns a session ID and name for tracking.",parameters:p.Object({prompt:p.String({description:"The task prompt to execute"}),name:p.Optional(p.String({description:"Short human-readable name for the session (kebab-case, e.g. 'fix-auth'). Auto-generated from prompt if omitted."})),workdir:p.Optional(p.String({description:"Working directory (defaults to cwd)"})),model:p.Optional(p.String({description:"Model name to use"})),system_prompt:p.Optional(p.String({description:"Additional system prompt"})),allowed_tools:p.Optional(p.Array(p.String(),{description:"List of allowed tools"})),resume_session_id:p.Optional(p.String({description:"Session reference to continue or fork from. Prefer the plugin session ID shown by agent_launch or agent_sessions; persisted backend conversation IDs also resolve when available."})),fork_session:p.Optional(p.Boolean({description:"When resuming, fork to a new session instead of continuing the existing one. Use with resume_session_id."})),force_new_session:p.Optional(p.Boolean({description:"Bypass resume-first protection and start a brand-new linked session even when a resumable or active linked session already exists."})),permission_mode:p.Optional(p.Union([p.Literal("default"),p.Literal("plan"),p.Literal("bypassPermissions")],{description:"Permission mode: 'default' (plugin-managed interactive execution), 'plan' (present the plan first and block implementation until approval), 'bypassPermissions' (fully autonomous execution). Defaults to plugin config ('plan' by default)."})),plan_approval:p.Optional(p.Union([p.Literal("ask"),p.Literal("delegate"),p.Literal("approve")],{description:"Plan approval policy for this session: 'ask' (send a decision-grade plan brief to the user with Approve/Revise/Reject buttons), 'delegate' (orchestrator must review the full plan, then either approve directly or escalate back to the user with the same decision brief and buttons), 'approve' (auto-approve after verification). Overrides the plugin-level planApproval setting."})),harness:p.Optional(p.String({description:"Agent harness to use ('claude-code', 'codex', or experimental 'opencode'). Defaults to the plugin defaultHarness."})),worktree_strategy:p.Optional(p.Union([p.Literal("off"),p.Literal("manual"),p.Literal("ask"),p.Literal("delegate"),p.Literal("auto-merge"),p.Literal("auto-pr")],{description:"Worktree strategy: 'off' (no worktree), 'manual' (create worktree but no auto merge-back), 'ask' (prompt user with Merge/Open PR/Later/Discard buttons), 'delegate' (orchestrator decides), 'auto-merge' (merge automatically), 'auto-pr' (open/update a PR automatically). Defaults to the plugin config when unset."})),worktree_base_branch:p.Optional(p.String({description:"Base branch for worktree merge/PR operations (default: auto-detected or 'main')"})),worktree_pr_target_repo:p.Optional(p.String({description:"Target repository for cross-repo PRs (e.g. 'openai/codex' for fork-to-upstream workflow). If not set, auto-detected from 'upstream' remote or defaults to 'origin'."}))}),async execute(e,t){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!kd(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { prompt }."}]};t.agentId&&`${t.agentId}${n.agentId}`;try{let r=Xt(t,n,k);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};let{workdir:o,harness:i,resolvedModel:s,permissionMode:a,planApproval:l,originChannel:d,originThreadId:u,originSessionKey:f,route:g,resumeSessionId:S,resolvedResumeId:y,clearedPersistedCodexResume:c,reasoningEffort:h,fastMode:v}=r,b=t.resume_session_id?k.resolve(t.resume_session_id)??k.getPersistedSession(t.resume_session_id):void 0,A=!t.fork_session&&b?ke(b):void 0;if(A?.kind==="direct")return{content:[{type:"text",text:`Session ${b.name} [${Di(b,t.resume_session_id)}] is already running. Use agent_respond(session='${t.resume_session_id}', message='<next instruction>') instead of agent_launch(resume_session_id=...).`}]};if(A?.kind==="unavailable")return{content:[{type:"text",text:`Resume unavailable for session ${b.name} [${Di(b,t.resume_session_id)}] (${A.reason}). Use agent_launch(prompt='<new task>') for a fresh session or set fork_session=true to fork from prior context.`}]};let I=b&&"resumedFromSessionName"in b?b.resumedFromSessionName:void 0,R=A?.kind==="resume"&&!t.fork_session?I??b?.name:void 0,m=R&&!t.name?R:t.name,w=t.worktree_strategy??_.defaultWorktreeStrategy??"off",T=t.fork_session?void 0:A?.kind==="resume"||A?.kind==="relaunch"?A.stableSessionId:void 0,F=A?.kind==="resume"&&!t.fork_session&&b?an(b,a):{permissionMode:a,approvalApplied:!1,patch:{}};if(w!=="off"&&Pd(k)&&k.checkRepoPolicyForLaunch(o,t.worktree_strategy).ok===!1)return{content:[{type:"text",text:k.requestRepoPolicyForLaunch({route:g,prompt:t.prompt,workdir:o,name:m,model:s,reasoningEffort:h,fastMode:v,systemPrompt:t.system_prompt,allowedTools:t.allowed_tools,resumeSessionId:A?.kind==="resume"?A.resumeSessionId:S,resumedFromSessionName:R,resumeWorktreeFrom:T??t.resume_session_id??y,sessionIdOverride:T,clearedPersistedCodexResume:c,forkSession:S?t.fork_session:!1,forceNewSession:t.force_new_session,permissionMode:a,planApproval:l,harness:i,worktreeStrategy:t.worktree_strategy,worktreeBaseBranch:t.worktree_base_branch,worktreePrTargetRepo:t.worktree_pr_target_repo,originAgentId:n.agentId||void 0})}]};let V=k.spawn({prompt:t.prompt,sessionIdOverride:T,name:m,workdir:o,model:s,reasoningEffort:h,fastMode:v,systemPrompt:t.system_prompt,allowedTools:t.allowed_tools,resumeSessionId:A?.kind==="resume"?A.resumeSessionId:S,resumedFromSessionName:R,resumeWorktreeFrom:T??t.resume_session_id??y,forkSession:S?t.fork_session:!1,multiTurn:!0,permissionMode:F.permissionMode,planApproval:l,codexApprovalPolicy:i==="codex"?"never":void 0,...F.patch,originChannel:d,originThreadId:u,originAgentId:n.agentId||void 0,originSessionKey:f,route:g,harness:i,taskLifecycle:sn(n),worktreeStrategy:t.worktree_strategy,worktreeBaseBranch:t.worktree_base_branch,worktreePrTargetRepo:t.worktree_pr_target_repo});return{content:[{type:"text",text:vd(k)?k.formatLaunchResult({prompt:t.prompt,workdir:o,harness:i,permissionMode:F.permissionMode,planApproval:l,forceNewSession:t.force_new_session,resumeSessionId:t.resume_session_id,resumeSessionName:R,forkSession:t.fork_session,clearedPersistedCodexResume:c},V):Ht({prompt:t.prompt,workdir:o,harness:i,permissionMode:F.permissionMode,planApproval:l,resumeSessionId:t.resume_session_id,resumeSessionName:R,forkSession:t.fork_session,forceNewSession:t.force_new_session,clearedPersistedCodexResume:c},{id:V.id,name:V.name,model:V.model,reasoningEffort:V.reasoningEffort??ce(i),fastMode:V.fastMode??v,worktreeStrategy:V.worktreeStrategy??t.worktree_strategy??_.defaultWorktreeStrategy??"off",repoIntegrationPolicy:V.repoIntegrationPolicy,repoProvider:V.repoProvider,worktreePath:V.worktreePath,originalWorkdir:V.originalWorkdir})}]}}catch(r){let o=Sd(r),i=o.includes("Max sessions")?"":`
|
|
21
21
|
|
|
22
22
|
Use agent_sessions to see active sessions and their status.`;return{content:[{type:"text",text:`Error launching session: ${o}${i}`}]}}}}}import{existsSync as jr,readFileSync as Gi}from"fs";import{EventEmitter as $d}from"events";var Ei="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var Wi=65536;function Vr(n){let e=0;for(;e<n.length;){let t=Math.min(e+Wi,n.length);crypto.getRandomValues(n.subarray(e,t)),e=t}}function Ni(n){if(n|=0,n<0)throw new RangeError("Wrong ID size");let e=Buffer.allocUnsafe(n);return Vr(e),e}function Oi(n,e,t){let r=256-256%n.length;if(r===256){let i=n.length-1;return(s=e)=>{if(!s)return"";let a="";for(;;){let l=t(s),d=s;for(;d--;)if(a+=n[l[d]&i],a.length>=s)return a}}}let o=Math.ceil(1.6*256*e/r);return(i=e)=>{if(!i)return"";let s="";for(;;){let a=t(o),l=o;for(;l--;)if(a[l]<r&&(s+=n[a[l]%n.length],s.length>=i))return s}}}var wd=Wi/2;function bd(n,e=21){if(typeof n!="string"||!n||n.length>256)return Oi(n,e,Ni);for(let l=0;l<n.length;l++)if(n.charCodeAt(l)>255)return Oi(n,e,Ni);let t=Uint8Array.from(n,l=>l.charCodeAt(0)),r=n.length,o=(2<<31-Math.clz32(r-1|1))-1,i="",s=0,a=0;return(l=e)=>{if(l|=0,l<0)throw new RangeError("Wrong ID size");if(l===0)return"";if(s+l>i.length){let d=Math.max(a,l);a=Math.min(d*16,wd);let u=Buffer.allocUnsafe(d);if(o===r-1){Vr(u);for(let f=0;f<d;f++)u[f]=t[u[f]&o]}else{let f=Buffer.allocUnsafe(Math.ceil(1.6*(o+1)*d/r)),g=0;for(;g<d;){Vr(f);for(let S=0;S<f.length;S++){let y=f[S]&o;if(y<r&&(u[g++]=t[y],g===d))break}}}i=u.toString("latin1"),s=0}return s+=l,i.substring(s-l,s)}}var ln=bd(Ei);var Fi={starting:["running","failed","killed"],running:["completed","failed","killed"],completed:[],failed:[],killed:[]};function O(n,e){return Object.hasOwn(n,e)}var Li=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]);function Rd(n){return n.requestedPermissionMode!=="plan"?"not_plan_gated":n.pendingPlanApproval?"awaiting_approval":n.planModeApproved?n.status==="starting"||n.status!=="running"&&n.approvalExecutionState==="awaiting_plan_output"?"awaiting_plan_output":"approved_then_implemented":n.currentPermissionMode!=="plan"?"implemented_without_required_approval":"awaiting_plan_output"}function U(n){return{...n,approvalExecutionState:Rd(n)}}function Ur(n,e){switch(e.type){case"initialize":return U({...n,worktreeState:e.hasWorktree&&n.worktreeState==="none"?"provisioned":n.worktreeState,lifecycle:n.status==="starting"?"starting":n.lifecycle,runtimeState:n.status==="starting"?"live":n.runtimeState});case"status.transition":return e.status==="starting"?U({...n,status:e.status,lifecycle:"starting",runtimeState:"live"}):e.status==="running"?U({...n,status:e.status,lifecycle:n.lifecycle==="starting"||n.lifecycle==="suspended"?"active":n.lifecycle,runtimeState:"live"}):U({...n,status:e.status,runtimeState:"stopped",lifecycle:n.lifecycle==="suspended"?"suspended":"terminal"});case"permission.mode_changed":return U({...n,currentPermissionMode:e.currentPermissionMode});case"turn.started":return U({...n,lifecycle:"active",runtimeState:"live"});case"input.requested":return U({...n,lifecycle:n.pendingPlanApproval?"awaiting_plan_decision":"awaiting_user_input"});case"plan.requested":if(n.planModeApproved)return n;{let t=n.pendingPlanApproval&&n.approvalState==="pending"&&n.planApprovalContext===e.context,r=n.pendingPlanApproval&&n.approvalState==="changes_requested"&&n.planApprovalContext===e.context&&n.planDecisionVersion>0,o=!n.pendingPlanApproval&&n.approvalState==="changes_requested"&&n.planApprovalContext===e.context&&n.planDecisionVersion>0,i=t||r||o?n.planDecisionVersion:n.planDecisionVersion+1;return U({...n,pendingPlanApproval:!0,planApprovalContext:e.context,approvalState:"pending",planDecisionVersion:i,actionablePlanDecisionVersion:i,canonicalPlanPromptVersion:t?n.canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:t?n.approvalPromptRequiredVersion:void 0,approvalPromptVersion:t?n.approvalPromptVersion:void 0,approvalPromptStatus:t?n.approvalPromptStatus:"not_sent",approvalPromptTransport:t?n.approvalPromptTransport:"none",approvalPromptMessageKind:t?n.approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:t?n.approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:t?n.approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:t?n.approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"})}case"plan.cleared":return U({...n,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,approvalState:n.approvalState==="pending"?"not_required":n.approvalState});case"plan.approved":return U({...n,pendingPlanApproval:!1,planApprovalContext:void 0,actionablePlanDecisionVersion:void 0,planModeApproved:!0,approvalState:"approved",planDecisionVersion:n.planDecisionVersion+1,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",lifecycle:n.status==="running"?"active":n.lifecycle});case"plan.changes_requested":return U({...n,pendingPlanApproval:!0,approvalState:"changes_requested",planDecisionVersion:n.planDecisionVersion+1,actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0,lifecycle:"awaiting_plan_decision"});case"terminal.entered":return U({...n,lifecycle:e.suspended?"suspended":"terminal",runtimeState:"stopped"});case"worktree.decision_requested":return U({...n,lifecycle:"awaiting_worktree_decision",worktreeState:"pending_decision"});case"worktree.state_set":return U({...n,worktreeState:e.worktreeState,lifecycle:e.worktreeState==="pending_decision"?"awaiting_worktree_decision":Li.has(e.worktreeState)?"terminal":n.lifecycle});case"delivery.state_set":return U({...n,deliveryState:e.deliveryState})}}function Bi(n,e){let t={...n,...O(e,"lifecycle")?{lifecycle:e.lifecycle}:{},...O(e,"approvalState")?{approvalState:e.approvalState}:{},...O(e,"approvalExecutionState")?{approvalExecutionState:e.approvalExecutionState}:{},...O(e,"worktreeState")?{worktreeState:e.worktreeState}:{},...O(e,"runtimeState")?{runtimeState:e.runtimeState}:{},...O(e,"deliveryState")?{deliveryState:e.deliveryState}:{},...O(e,"requestedPermissionMode")?{requestedPermissionMode:e.requestedPermissionMode}:{},...O(e,"currentPermissionMode")?{currentPermissionMode:e.currentPermissionMode}:{},...O(e,"pendingPlanApproval")?{pendingPlanApproval:e.pendingPlanApproval}:{},...O(e,"planApprovalContext")?{planApprovalContext:e.planApprovalContext}:{},...O(e,"planDecisionVersion")?{planDecisionVersion:e.planDecisionVersion}:{},...O(e,"actionablePlanDecisionVersion")?{actionablePlanDecisionVersion:e.actionablePlanDecisionVersion}:{},...O(e,"canonicalPlanPromptVersion")?{canonicalPlanPromptVersion:e.canonicalPlanPromptVersion}:{},...O(e,"approvalPromptRequiredVersion")?{approvalPromptRequiredVersion:e.approvalPromptRequiredVersion}:{},...O(e,"approvalPromptVersion")?{approvalPromptVersion:e.approvalPromptVersion}:{},...O(e,"approvalPromptStatus")?{approvalPromptStatus:e.approvalPromptStatus}:{},...O(e,"approvalPromptTransport")?{approvalPromptTransport:e.approvalPromptTransport}:{},...O(e,"approvalPromptMessageKind")?{approvalPromptMessageKind:e.approvalPromptMessageKind}:{},...O(e,"approvalPromptLastAttemptAt")?{approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt}:{},...O(e,"approvalPromptDeliveredAt")?{approvalPromptDeliveredAt:e.approvalPromptDeliveredAt}:{},...O(e,"approvalPromptFailedAt")?{approvalPromptFailedAt:e.approvalPromptFailedAt}:{},...O(e,"planModeApproved")?{planModeApproved:e.planModeApproved}:{}};return e.approvalState==="changes_requested"&&e.pendingPlanApproval===void 0&&(t={...t,pendingPlanApproval:!1}),t.pendingPlanApproval?t={...t,approvalState:"pending",actionablePlanDecisionVersion:t.actionablePlanDecisionVersion??t.planDecisionVersion,lifecycle:"awaiting_plan_decision"}:t.approvalState==="changes_requested"&&(t={...t,actionablePlanDecisionVersion:void 0,lifecycle:"awaiting_user_input"}),O(e,"pendingWorktreeDecisionSince")&&e.pendingWorktreeDecisionSince!==void 0||t.worktreeState==="pending_decision"?t=Ur(t,{type:"worktree.decision_requested"}):Li.has(t.worktreeState)&&(t={...t,lifecycle:"terminal"}),U(t)}var dn=class{queue=[];resolve=null;done=!1;hasPending(){return this.queue.length>0}push(e){this.queue.push(e),this.resolve&&(this.resolve(),this.resolve=null)}end(){this.done=!0,this.resolve&&(this.resolve(),this.resolve=null)}async*[Symbol.asyncIterator](){for(;;){for(;this.queue.length>0;)yield this.queue.shift();if(this.done)return;await new Promise(e=>{this.resolve=e})}}};import{createHash as Ad}from"crypto";import{appendFileSync as Id}from"fs";import{tmpdir as Td}from"os";import{join as xd}from"path";var Ki=2e3,Cd=/^[A-Za-z0-9_.-]+$/;function Md(n){return Cd.test(n)?n:`hashed+${Ad("sha256").update(n,"utf8").digest("hex")}`}function ve(n){return xd(Td(),`openclaw-agent-${Md(n)}.txt`)}function _d(n,e){if(!e)return;let t=e.split(`
|
|
23
23
|
`),[r="",...o]=t;n.length===0?n.push(r):n[n.length-1]+=r;for(let i of o)n.push(i)}function qi(n,e,t){_d(n,t),n.length>Ki&&n.splice(0,n.length-Ki);try{Id(ve(e),t,"utf-8")}catch{}return n}var un=class{timers=new Map;get size(){return this.timers.size}set(e,t,r){this.clear(e);let o=setTimeout(()=>{this.timers.get(e)===o&&this.timers.delete(e),r()},t);o.unref?.(),this.timers.set(e,o)}clear(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var cn=class{constructor(e){this.deps=e}deps;waitingForInputFired=!1;lastTurnHadQuestion=!1;turnInProgress=!0;currentTurnText="";currentTurnPlanArtifact;pendingInputNotificationIdentity;beginUserTurn(){this.waitingForInputFired=!1,this.turnInProgress=!0,this.currentTurnText="",this.currentTurnPlanArtifact=void 0,this.lastTurnHadQuestion=!1}noteTextDelta(e,t){this.waitingForInputFired=!1,t||(this.lastTurnHadQuestion=!1),this.deps.appendOutput(e),this.currentTurnText+=this.currentTurnText?`
|
|
@@ -51,7 +51,7 @@ ${d}`}}catch{}return l}function hn(n,e="all",t,r={}){let o=n.listPersistedSessio
|
|
|
51
51
|
|
|
52
52
|
`)}function Xd(n,e){let t=new Map;for(let r of e){if(!Vd(r.status))continue;let o=r.completedAt??Date.now(),i=r.createdAt??o,s=zr(r),a=r.sessionId??`persisted:${s??r.harnessSessionId}`;t.set(a,{id:r.sessionId??s??r.harnessSessionId,name:r.name||r.sessionId||s||r.harnessSessionId,status:r.status,startedAt:r.createdAt??0,completedAt:r.completedAt,duration:Math.max(0,o-i),prompt:r.prompt??"",workdir:r.workdir??"(unknown)",costUsd:r.costUsd??0,multiTurn:!0,phase:r.lifecycle??r.status,lifecycle:r.lifecycle,resumable:r.resumable,harness:r.harness,model:r.model,backendRef:r.backendRef,harnessSessionId:r.harnessSessionId,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState,originChannel:r.originChannel,originThreadId:r.originThreadId,worktreePath:r.worktreePath,worktreeBranch:r.worktreeBranch,worktreeStrategy:r.worktreeStrategy,worktreeState:r.worktreeState,worktreeLifecycle:r.worktreeLifecycle,worktreeMerged:r.worktreeMerged,worktreeMergedAt:r.worktreeMergedAt,worktreePrUrl:r.worktreePrUrl,recovered:!0,runtimeRecovery:r.runtimeRecovery})}for(let r of n){let o=t.get(r.id);t.set(r.id,{id:r.id,name:r.name,status:r.status,startedAt:r.startedAt,completedAt:r.completedAt,duration:r.duration,prompt:r.prompt,workdir:r.originalWorkdir??r.workdir,costUsd:r.costUsd,multiTurn:r.multiTurn,phase:r.phase,lifecycle:r.lifecycle,resumable:r.isExplicitlyResumable,harness:r.harnessName,model:r.model,backendRef:r.backendRef,harnessSessionId:r.harnessSessionId,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,approvalExecutionState:r.approvalExecutionState,originChannel:r.originChannel,originThreadId:r.originThreadId,worktreePath:r.worktreePath,worktreeBranch:r.worktreeBranch,worktreeStrategy:r.worktreeStrategy,worktreeState:Gd(r.worktreeState,o?.worktreeState),worktreeLifecycle:jd(r.worktreeLifecycle,o?.worktreeLifecycle),worktreeMerged:r.worktreeMerged??o?.worktreeMerged,worktreeMergedAt:r.worktreeMergedAt??o?.worktreeMergedAt,worktreePrUrl:r.worktreePrUrl??o?.worktreePrUrl,recovered:!1})}return[...t.values()].sort((r,o)=>(o.startedAt??0)-(r.startedAt??0))}function Zd(n){if(!n||typeof n!="object")return"all";let e=n.status;switch(e){case"running":case"completed":case"failed":case"killed":case"all":return e;default:return"all"}}function Hi(n){return{name:"agent_sessions",description:"List coding agent sessions with their status and progress. By default, shows the 5 most recent sessions; set `full` to show all sessions from the last 24 hours.",parameters:p.Object({status:p.Optional(p.Union([p.Literal("all"),p.Literal("running"),p.Literal("completed"),p.Literal("failed"),p.Literal("killed")],{description:'Filter by status (default "all")'})),full:p.Optional(p.Boolean({description:"Show all sessions from the last 24h instead of just the most recent 5"}))}),async execute(e,t){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};let r=Zd(t),o=n?.workspaceDir?$e(n.workspaceDir):void 0,i=!!(t&&typeof t=="object"&&t.full===!0);return{content:[{type:"text",text:hn(k,r,o,{full:i})}]}}}}function yn(n,e,t){let r=n.resolve(e);if(!r){let o=n.getPersistedSession(e);if(!o)return`Error: Session "${e}" not found.`;if(o.status==="killed"&&o.lifecycle==="suspended"){let i=t==="completed";if(n.updatePersistedSession(e,{status:i?"completed":"killed",lifecycle:"terminal",runtimeState:"stopped",resumable:!1,killReason:i?"done":"user"}))return i?`Recovered session ${o.name} [${o.sessionId??o.harnessSessionId}] marked as completed. No live process was running.`:`Recovered session ${o.name} [${o.sessionId??o.harnessSessionId}] dismissed. No live process was running.`}return`Session ${o.name} [${o.sessionId??o.harnessSessionId}] is a persisted ${o.status} record with no live process to kill.`}return r.status==="completed"||r.status==="failed"||r.status==="killed"?`Session ${r.name} [${r.id}] is already ${r.status}. No action needed.`:t==="completed"?(r.complete(),`Session ${r.name} [${r.id}] marked as completed.`):(n.kill(r.id),`Session ${r.name} [${r.id}] has been terminated.`)}function eu(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.session!="string"?!1:e.reason===void 0?!0:e.reason==="completed"||e.reason==="killed"}function Qi(n){return{name:"agent_kill",description:"Terminate or complete a running coding agent session by name or ID. Use reason='completed' to mark a session as successfully completed instead of killed.",parameters:p.Object({session:p.String({description:"Session name or ID to terminate"}),reason:p.Optional(p.Union([p.Literal("completed"),p.Literal("killed")],{description:"Reason for closing the session. 'completed' marks it as successfully done (sends β
notification). 'killed' (default) terminates it."}))}),async execute(e,t){return k?eu(t)?{content:[{type:"text",text:yn(k,t.session,t.reason)}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, reason? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}function tu(n){return!n||typeof n!="object"?!1:typeof n.session=="string"}function Sn(n){return{name:"agent_output",description:"Show recent output from a coding agent session (by name or ID).",parameters:p.Object({session:p.String({description:"Session name or ID to get output from"}),lines:p.Optional(p.Number({description:"Number of recent lines to show (default 50)"})),full:p.Optional(p.Boolean({description:"Show all available output"}))}),async execute(e,t){return k?tu(t)?{content:[{type:"text",text:gn(k,t.session,{full:t.full,lines:t.lines})}]}:{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, lines?, full? }."}]}:{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]}}}}var nu=10;function Qr(n){return n instanceof Error?n.message:String(n)}function Pe(n){return D(n)??n.harnessSessionId??"unknown-session"}function ru(n){if(!(!n.worktreeStrategy||n.worktreeStrategy==="off"))return Yt(n)??D(n)??C(n)}function Yi(n){return n.status!=="running"&&!!n.pendingPlanApproval&&!!C(n)}function ou(n){let e=n.trim().toLowerCase().replace(/[.!?]+$/g,"").trim();if(e==="approve"||e==="approved")return"approve";if(e==="revise"||e==="request changes"||e==="changes requested")return"revise";if(e==="reject"||e==="rejected")return"reject"}function st(n,e,t){let r=e==="completed"?`This session is closed by default. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Pe(n)}', fork_session=true, prompt='<new task>').`:e==="legacy_non_resumable"?`Persisted historical backend state is intentionally non-resumable here. Launch fresh, or fork with agent_launch(resume_session_id='${Pe(n)}', fork_session=true, prompt='<new task>').`:e==="missing_backend_state"?`No resumable backend state is available. Launch a fresh session, or fork from prior context with agent_launch(resume_session_id='${Pe(n)}', fork_session=true, prompt='<new task>').`:`Use agent_respond(session='${Pe(n)}', message='<next instruction>') to continue the running session.`,o=t?` ${t}`:"";return{text:`Resume unavailable for session ${n.name} [${Pe(n)}] (${e}).${o} ${r}`,isError:!0}}async function Ji(n,e,t){try{let r={prompt:e.prompt,sessionIdOverride:Yt(e),workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,worktreeStrategy:e.worktreeStrategy,multiTurn:!0,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,permissionMode:e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,harness:"harnessName"in e?e.harnessName:e.harness},o=await n.spawnAndAwaitRunning(r,{notifyLaunch:!1});return n.notifySession(o,`βΆοΈ [${o.name}] Relaunched fresh`,"notification",`agent-respond-relaunched:${o.id}:${o.startedAt}`),{text:`Session ${e.name} was relaunched fresh β it was killed during startup before the harness initialized. New session: ${o.name} [${o.id}].`}}catch(r){return{text:`Error relaunching session ${e.name} [${Pe(e)}]: ${Qr(r)}`,isError:!0}}}var iu=`[SYSTEM: The user has approved your plan. Exit plan mode immediately and implement the changes with full permissions. Do not ask for further confirmation.]
|
|
53
53
|
|
|
54
|
-
`;function Xi(n){let e=n?.replace(/\s+/g," ").trim();if(e)return G(e,240)}function Hr(n){if(n.approvalState==="changes_requested"&&!kn(n))return`Plan changes were already requested for session ${n.name}. Wait for the revised plan before approving.`;if(n.approvalState==="rejected")return`Plan for session ${n.name} was already rejected.`}function kn(n){return n.pendingPlanApproval?(n.approvalState==="changes_requested"?n.actionablePlanDecisionVersion:n.actionablePlanDecisionVersion??n.planDecisionVersion)>0:!1}function su(n){return Hr(n)?!1:kn(n)||n.currentPermissionMode==="plan"}function au(n,e){let t=n.updatePersistedSession;if(typeof t!="function")return;let r=e.controlStateSnapshot();t.call(n,e.id,{lifecycle:r.lifecycle,approvalState:r.approvalState,approvalExecutionState:r.approvalExecutionState,runtimeState:r.runtimeState,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,actionablePlanDecisionVersion:r.actionablePlanDecisionVersion,planModeApproved:r.planModeApproved,approvalRationale:e.approvalRationale})}function lu(n){return(n.planDecisionVersion??0)+1}function Zi(n,e){let t={approvalState:e,lifecycle:e==="rejected"?"terminal":"awaiting_user_input",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:lu(n),actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0};return e==="rejected"&&(t.runtimeState="stopped"),t}function es(n,e){let t=n;typeof t.applyControlPatch=="function"&&t.applyControlPatch(e),Object.assign(n,e)}function Yr(n,e){let t=n.resolve(e),r=t?void 0:n.getPersistedSession(e),o=t??r,i=o?.name??e;if(n.clearPlanDecisionTokens?.(e),!o)return{text:`Plan rejected for [${i}].`,isError:!1};let s=Zi(o,"rejected");return t?(es(t,s),n.updatePersistedSession?.(e,s),n.kill(t.id,"user"),{text:`Plan rejected for [${t.name}]. Session stopped.`}):(n.updatePersistedSession?.(e,s),{text:`Plan rejected for [${i}]. Session remains stopped.`})}function Jr(n,e){let t=n.resolve(e),r=t?void 0:n.getPersistedSession(e),o=t??r,i=o?.name??e;if(n.clearPlanDecisionTokens?.(e),o){let s=Zi(o,"changes_requested");t&&es(t,s),n.updatePersistedSession?.(e,s)}return{text:`Type your revision feedback for [${i}] and I'll forward it to the agent.`}}async function du(n,e,t,r={}){let o=ke(e);if(!(o.kind==="resume"||Yi(e)))return;let s=!!(r.approve&&su(e)),a=s?Xi(r.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?Ji(n,e,t):st(e,o.reason);let l={prompt:s?iu+t:t,sessionIdOverride:o.stableSessionId,workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,resumeSessionId:o.resumeSessionId,resumeWorktreeFrom:ru(e),worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,multiTurn:!0,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,permissionMode:s?"bypassPermissions":e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,pendingPlanApproval:s?!1:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:s?(e.actionablePlanDecisionVersion??e.planDecisionVersion)+1:e.planDecisionVersion,actionablePlanDecisionVersion:s?void 0:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,...s?{approvalState:"approved",approvalExecutionState:"awaiting_plan_output",approvalRationale:a,planModeApproved:!0}:{},harness:"harnessName"in e?e.harnessName:e.harness},d=await n.spawnAndAwaitRunning(l,{notifyLaunch:!1});return s?(n.notifySession(d,`π [${d.name}] Plan approved (resumed)`,"plan-approved",`agent-respond-plan-approved-resumed:${d.id}:${d.startedAt}:${o.resumeSessionId}:v${e.planDecisionVersion??"unknown"}`),{text:`Plan approved for session ${d.name} [${d.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(n.notifyResumedLaunch(d),{text:`Resume started for session ${d.name} [${d.id}]. Use agent_output to see the response.`})}catch(l){return st(e,"missing_backend_state",`Backend resume failed: ${Qr(l)}`)}}async function Q(n,e){let t=n.resolve(e.session),r=t?void 0:n.getPersistedSession(e.session);if(!t&&!r)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=t??r,i=o.status==="running"?{kind:"direct"}:ke(o),s=!e.approve&&o.lifecycle==="awaiting_plan_decision"&&o.pendingPlanApproval&&e.userInitiated?ou(e.message):void 0;if(s==="approve")return Q(n,{...e,message:"Approved. Go ahead.",approve:!0});if(s==="revise")return Jr(n,t?.id??r?.sessionId??e.session);if(s==="reject")return Yr(n,t?.id??r?.sessionId??e.session);if(e.approve){let l=Hr(o);if(l)return{text:l,isError:!0}}if(i.kind==="resume"||Yi(o)){let l=await du(n,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(l)return l}else{if(i.kind==="relaunch")return Ji(n,o,e.message);if(i.kind==="unavailable")return st(o,i.reason)}if(!t)return ot(r)?st(r,"completed"):{text:`Error: Session ${r.name} [${Pe(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(t.status!=="running")return ot(t)?st(t,"completed"):{text:`Error: Session ${t.name} [${t.id}] is not running (status: ${t.status}). Cannot send a message to a non-running session.`,isError:!0};let a=_.maxAutoResponds??nu;if(e.userInitiated)t.resetAutoRespond();else if(t.autoRespondCount>=a)return{text:`β οΈ Auto-respond limit reached (${t.autoRespondCount}/${a}). Ask the user to provide the answer for session ${t.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(e.approve){let h=Hr(t);if(h)return{text:h,isError:!0}}let l=t.pendingInputState?.activeQuestionIndex,d=t.pendingInputState?.questions?.length;if(!e.approve&&t.pendingInputState?.allowsFreeText&&await t.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let
|
|
54
|
+
`;function Xi(n){let e=n?.replace(/\s+/g," ").trim();if(e)return G(e,240)}function Hr(n){if(n.approvalState==="changes_requested"&&!kn(n))return`Plan changes were already requested for session ${n.name}. Wait for the revised plan before approving.`;if(n.approvalState==="rejected")return`Plan for session ${n.name} was already rejected.`}function kn(n){return n.pendingPlanApproval?(n.approvalState==="changes_requested"?n.actionablePlanDecisionVersion:n.actionablePlanDecisionVersion??n.planDecisionVersion)>0:!1}function su(n){return Hr(n)?!1:kn(n)||n.currentPermissionMode==="plan"}function au(n,e){let t=n.updatePersistedSession;if(typeof t!="function")return;let r=e.controlStateSnapshot();t.call(n,e.id,{lifecycle:r.lifecycle,approvalState:r.approvalState,approvalExecutionState:r.approvalExecutionState,runtimeState:r.runtimeState,requestedPermissionMode:r.requestedPermissionMode,currentPermissionMode:r.currentPermissionMode,pendingPlanApproval:r.pendingPlanApproval,planApprovalContext:r.planApprovalContext,planDecisionVersion:r.planDecisionVersion,actionablePlanDecisionVersion:r.actionablePlanDecisionVersion,planModeApproved:r.planModeApproved,approvalRationale:e.approvalRationale})}function lu(n){return(n.planDecisionVersion??0)+1}function Zi(n,e){let t={approvalState:e,lifecycle:e==="rejected"?"terminal":"awaiting_user_input",pendingPlanApproval:!1,planApprovalContext:void 0,planDecisionVersion:lu(n),actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0};return e==="rejected"&&(t.runtimeState="stopped"),t}function es(n,e){let t=n;typeof t.applyControlPatch=="function"&&t.applyControlPatch(e),Object.assign(n,e)}function Yr(n,e){let t=n.resolve(e),r=t?void 0:n.getPersistedSession(e),o=t??r,i=o?.name??e;if(n.clearPlanDecisionTokens?.(e),!o)return{text:`Plan rejected for [${i}].`,isError:!1};let s=Zi(o,"rejected");return t?(es(t,s),n.updatePersistedSession?.(e,s),n.kill(t.id,"user"),{text:`Plan rejected for [${t.name}]. Session stopped.`}):(n.updatePersistedSession?.(e,s),{text:`Plan rejected for [${i}]. Session remains stopped.`})}function Jr(n,e){let t=n.resolve(e),r=t?void 0:n.getPersistedSession(e),o=t??r,i=o?.name??e;if(n.clearPlanDecisionTokens?.(e),o){let s=Zi(o,"changes_requested");t&&es(t,s),n.updatePersistedSession?.(e,s)}return{text:`Type your revision feedback for [${i}] and I'll forward it to the agent.`}}async function du(n,e,t,r={}){let o=ke(e);if(!(o.kind==="resume"||Yi(e)))return;let s=!!(r.approve&&su(e)),a=s?Xi(r.approvalRationale):void 0;try{if(o.kind!=="resume")return o.kind==="relaunch"?Ji(n,e,t):st(e,o.reason);let l={prompt:s?iu+t:t,sessionIdOverride:o.stableSessionId,workdir:e.workdir,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,resumeSessionId:o.resumeSessionId,resumeWorktreeFrom:ru(e),worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,multiTurn:!0,originChannel:e.originChannel,originThreadId:e.originThreadId,originAgentId:e.originAgentId,originSessionKey:e.originSessionKey,route:e.route,permissionMode:s?"bypassPermissions":e.currentPermissionMode,requestedPermissionMode:e.requestedPermissionMode??e.currentPermissionMode,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy,pendingPlanApproval:s?!1:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:s?(e.actionablePlanDecisionVersion??e.planDecisionVersion)+1:e.planDecisionVersion,actionablePlanDecisionVersion:s?void 0:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,...s?{approvalState:"approved",approvalExecutionState:"awaiting_plan_output",approvalRationale:a,planModeApproved:!0}:{},harness:"harnessName"in e?e.harnessName:e.harness},d=await n.spawnAndAwaitRunning(l,{notifyLaunch:!1});return s?(n.notifySession(d,`π [${d.name}] Plan approved (resumed)`,"plan-approved",`agent-respond-plan-approved-resumed:${d.id}:${d.startedAt}:${o.resumeSessionId}:v${e.planDecisionVersion??"unknown"}`),{text:`Plan approved for session ${d.name} [${d.id}]. Session resumed in bypassPermissions mode. Use agent_output to see the response.`}):(n.notifyResumedLaunch(d),{text:`Resume started for session ${d.name} [${d.id}]. Use agent_output to see the response.`})}catch(l){return st(e,"missing_backend_state",`Backend resume failed: ${Qr(l)}`)}}async function Q(n,e){let t=n.resolve(e.session),r=t?void 0:n.getPersistedSession(e.session);if(!t&&!r)return{text:`Error: Session "${e.session}" not found.`,isError:!0};let o=t??r,i=o.status==="running"?{kind:"direct"}:ke(o),s=!e.approve&&o.lifecycle==="awaiting_plan_decision"&&o.pendingPlanApproval&&e.userInitiated?ou(e.message):void 0;if(s==="approve")return Q(n,{...e,message:"Approved. Go ahead.",approve:!0});if(s==="revise")return Jr(n,t?.id??r?.sessionId??e.session);if(s==="reject")return Yr(n,t?.id??r?.sessionId??e.session);if(e.approve){let l=Hr(o);if(l)return{text:l,isError:!0}}if(i.kind==="resume"||Yi(o)){let l=await du(n,o,e.message,{approve:e.approve,approvalRationale:e.approvalRationale});if(l)return l}else{if(i.kind==="relaunch")return Ji(n,o,e.message);if(i.kind==="unavailable")return st(o,i.reason)}if(!t)return ot(r)?st(r,"completed"):{text:`Error: Session ${r.name} [${Pe(r)}] is not running (status: ${r.status}). Cannot send a message to a non-running session.`,isError:!0};if(t.status!=="running")return ot(t)?st(t,"completed"):{text:`Error: Session ${t.name} [${t.id}] is not running (status: ${t.status}). Cannot send a message to a non-running session.`,isError:!0};let a=_.maxAutoResponds??nu;if(e.userInitiated)t.resetAutoRespond();else if(t.autoRespondCount>=a)return{text:`β οΈ Auto-respond limit reached (${t.autoRespondCount}/${a}). Ask the user to provide the answer for session ${t.name}. Then call agent_respond with their answer and set userInitiated: true to reset the counter.`};try{if(e.approve){let h=Hr(t);if(h)return{text:h,isError:!0}}let l=t.pendingInputState?.activeQuestionIndex,d=t.pendingInputState?.questions?.length;if(!e.approve&&t.pendingInputState?.allowsFreeText&&await t.submitPendingInputText?.(e.message)===!0){if(e.userInitiated){let b=G(e.message,100);n.notifySession(t,`βͺοΈ [${t.name}] "${b}"`,"agent-respond")}e.userInitiated||t.incrementAutoRespond();let h=G(e.message,80),v=l!=null&&d!=null&&l+1<d;return{text:[v?`Pending input question answered for session ${t.name} [${t.id}]; more input is required.`:`Pending input request submitted for session ${t.name} [${t.id}].`,` Message: "${h}"`,v?"The next question is being delivered to the user.":"Use agent_output to see the response."].join(`
|
|
55
55
|
`)}}let f=!1;e.interrupt&&(f=await t.interrupt());let g=!!(e.approve&&kn(t)),S=g?Xi(e.approvalRationale):void 0,y="";if(e.approve&&kn(t)?(t.switchPermissionMode("bypassPermissions"),t.approvalRationale=S):e.approve&&t.currentPermissionMode==="default"?t.switchPermissionMode("bypassPermissions"):e.approve&&t.currentPermissionMode==="bypassPermissions"?y=`
|
|
56
56
|
βΉοΈ approve=true was set but session is already in bypassPermissions mode.`:e.approve?y=`
|
|
57
57
|
β οΈ approve=true was set but session has no pending plan approval.`:(t.pendingPlanApproval||t.approvalState==="changes_requested")&&(y=`
|
|
@@ -65,12 +65,12 @@ ${d}`}}catch{}return l}function hn(n,e="all",t,r={}){let o=n.listPersistedSessio
|
|
|
65
65
|
`)}]}:l.kind==="ambiguous"?{content:[{type:"text",text:[dt(a),"",`Repo policy saved, but ${l.count} pending launches match this policy. Run the intended launch again to avoid starting the wrong session.`].join(`
|
|
66
66
|
`)}]}:{content:[{type:"text",text:dt(a)}]}}let i=k.resolveRepoPolicy(o);if(!i.identity)return{content:[{type:"text",text:`No git repository found for ${o}.`}]};let s=i.record;return s?{content:[{type:"text",text:dt(s)}]}:{content:[{type:"text",text:["Repo policy: unknown",`Repo: ${i.identity.repoRoot}`,`Provider: ${i.provider}${i.prAvailable?"":" (PR automation unavailable)"}`,...i.identity.remoteUrl?[`Remote: ${i.identity.remoteUrl}`]:[]].join(`
|
|
67
67
|
`)}]}}}}import{existsSync as Pn}from"fs";function Ru(n){return!n||typeof n!="object"?!1:typeof n.session=="string"}function Au(n){return n.mergeResult.stashPopConflict?[`Pre-merge stash pop conflicted; run git stash show ${n.mergeResult.stashRef??"stash@{0}"} in ${n.repoDir} to review stashed changes.`]:n.mergeResult.stashed?[`Pre-existing changes on ${n.baseBranch} were auto-stashed and restored.`]:[]}function Iu(n){return n.deleteBranchRequested?n.branchDeleted&&n.worktreeCleanedUp&&!n.worktreeAlreadyAbsent?{detailLine:"Branch and worktree cleaned up.",summaryFragment:" Branch and worktree cleaned up."}:n.branchDeleted&&n.worktreeAlreadyAbsent?{detailLine:"Branch deleted; worktree was already absent.",summaryFragment:" Branch deleted; worktree was already absent."}:n.branchDeleted?{detailLine:"Branch deleted; worktree cleanup failed.",summaryFragment:" Branch deleted; worktree cleanup failed."}:n.worktreeAlreadyAbsent?{detailLine:"Worktree was already absent; branch deletion failed.",summaryFragment:" Worktree was already absent; branch deletion failed."}:n.worktreeCleanedUp?{detailLine:"Worktree cleaned up; branch deletion failed.",summaryFragment:" Worktree cleaned up; branch deletion failed."}:{detailLine:"Branch deletion and worktree cleanup failed.",summaryFragment:" Branch deletion and worktree cleanup failed."}:n.worktreeCleanedUp&&!n.worktreeAlreadyAbsent?{detailLine:"Worktree cleaned up; branch deletion was not requested.",summaryFragment:" Worktree cleaned up; branch kept."}:n.worktreeAlreadyAbsent?{detailLine:"Worktree was already absent; branch deletion was not requested.",summaryFragment:" Worktree was already absent; branch kept."}:{detailLine:"Worktree cleanup failed; branch deletion was not requested.",summaryFragment:" Worktree cleanup failed; branch kept."}}function wn(n){return{name:"agent_merge",description:"Merge a worktree branch back to the base branch. Resolves session (active or persisted), gets worktree path, and performs the merge. On conflict, spawns a conflict-resolver session using the configured default harness.",parameters:p.Object({session:p.String({description:"Session name or ID to merge"}),base_branch:p.Optional(p.String({description:"Base branch to merge into (default: main)"})),strategy:p.Optional(p.Union([p.Literal("merge"),p.Literal("squash")],{description:"Merge strategy: 'merge' (default, fast-forward if possible; merge commit if branches have diverged) or 'squash' (squashes all commits into one)"})),push:p.Optional(p.Boolean({description:"Push the base branch after successful merge (default: false)"})),delete_branch:p.Optional(p.Boolean({description:"Delete the worktree branch after successful merge (default: true)"}))}),async execute(e,t){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Ru(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session, base_branch?, strategy?, push?, delete_branch? }."}]};let r=Ft(k,t.session),o=r.activeSession,i=r.persistedSession;if(!o&&!i)return{content:[{type:"text",text:`Error: Session "${t.session}" not found.`}]};let{worktreePath:s,originalWorkdir:a,branchName:l}=r;if(!s||!a)return{content:[{type:"text",text:`Error: Session "${t.session}" does not have a worktree.`}]};if(!l)return{content:[{type:"text",text:`Error: Cannot determine branch name for worktree at ${s}. The worktree may have been removed and no persisted branch name is available.`}]};Pn(s)||`${s}${a}`;let d=a;if(!Pn(a))return{content:[{type:"text",text:`Error: originalWorkdir "${a}" does not exist.`}]};let u=t.base_branch??Ee(d),f=u,g=t.strategy??"merge",S=t.push===!0,y=t.delete_branch!==!1,c=k.resolveRepoPolicy(d);if(c?.policy==="pr-required")return{content:[{type:"text",text:`β Merge blocked: repo policy requires a pull request for ${c.identity?.repoRoot??d}. Use agent_pr if PR automation is available.`}]};if(i?.worktreeLifecycle?.state==="merged"||i?.worktreeMerged)return{content:[{type:"text",text:`βΉοΈ Session "${t.session}" is already merged.`}]};if((Pn(s)?Xe(d,l,f):void 0)===0&&et(s))return{content:[{type:"text",text:[`β Merge blocked: session "${t.session}" has uncommitted worktree changes but branch ${l} has no commits ahead of ${f}.`,`Worktree: ${s}`,"Resume or inspect the session, then commit real task changes or clean temporary files before retrying agent_merge."].join(`
|
|
68
|
-
`)}]};let v={content:[{type:"text",text:"β Merge did not run (internal error)"}]};return await k.enqueueMerge(d,async()=>{let
|
|
68
|
+
`)}]};let v={content:[{type:"text",text:"β Merge did not run (internal error)"}]};return await k.enqueueMerge(d,async()=>{let b=k.getPersistedSession(t.session);if(b?.worktreeLifecycle?.state==="merged"||b?.worktreeMerged){v={content:[{type:"text",text:`βΉοΈ Session "${t.session}" was already merged while waiting in queue.`}]};return}let A=Ne(d,l,u),I=$t(d,l,f,g,s),R=tt(I);if(I.success){let m=Au({mergeResult:I,repoDir:d,baseBranch:f});if(S&&!ti(d,f)){let Ie=`β οΈ Merged ${l} β ${f} locally, but failed to push ${f}`;k.notifyWorktreeOutcome(r.notificationTarget,Ie,{detailLines:[`Branch ${l} was merged into ${f} in the local repository.`,`Pushing ${f} failed; remote state may not include the merge.`,"Cleanup was skipped so the branch/worktree remains available for follow-up.",...m,...R]}),v={content:[{type:"text",text:ie(Ie,I)}]};return}let w=!1,T=!1,F=!Pn(s);T=F?!0:B(d,s),Dt(d),y&&(w=H(d,l));let V=Iu({deleteBranchRequested:y,branchDeleted:w,worktreeCleanedUp:T,worktreeAlreadyAbsent:F});if(b){let Ie=new Date().toISOString();for(let pl of ri({...r,persistedSession:b}))k.updatePersistedSession(pl,{...Wt({worktreeBaseBranch:u,worktreePrTargetRepo:b.worktreePrTargetRepo,worktreePushRemote:b.worktreePushRemote},{mergedAt:Ie,updatedAt:Ie,resolvedAt:Ie,resolutionSource:"agent_merge"}),worktreeDisposition:"merged"})}let Ko=Nt({kind:"merge",branch:l,base:u,filesChanged:A?.filesChanged,insertions:A?.insertions,deletions:A?.deletions});k.notifyWorktreeOutcome(r.notificationTarget,Ko,{detailLines:[I.fastForward?"Merge type: fast-forward.":"Merge type: merge commit.",S?`Pushed ${f}.`:`Did not push ${f}; push was not requested.`,V.detailLine,...m,...R]});let Qe=`β
${I.fastForward?"β‘ Fast-forward":"π Merge commit"}: ${l} β ${f}.${S?" Pushed.":""}${V.summaryFragment}`;I.stashPopConflict?Qe+=`
|
|
69
69
|
β οΈ Pre-merge stash pop conflicted β run \`git stash show ${I.stashRef??"stash@{0}"}\` in ${d} to review stashed changes.`:I.stashed&&(Qe+=`
|
|
70
70
|
(Pre-existing changes on ${f} were auto-stashed and restored.)`),Qe=ie(Qe,I),v={content:[{type:"text",text:Qe}]}}else if(I.rebaseConflict)v={content:[{type:"text",text:ie(`β οΈ Rebase conflicts β manual resolution required:
|
|
71
71
|
|
|
72
72
|
${I.error}`,I)}]};else if(I.conflictFiles&&I.conflictFiles.length>0){let m=["Resolve merge conflicts in the following files and commit the resolution:","",...I.conflictFiles.map(w=>`- ${w}`),"",`After resolving, commit with message: "Resolve merge conflicts from ${l}"`].join(`
|
|
73
|
-
`);try{let w=k.spawn({prompt:m,workdir:d,name:`${t.session}-conflict-resolver`,harness:Y(),permissionMode:"bypassPermissions",multiTurn:!0,route:o?.route??i?.route,originChannel:o?.originChannel??i?.originChannel,originThreadId:o?.originThreadId??i?.originThreadId,originAgentId:o?.originAgentId??i?.originAgentId,originSessionKey:o?.originSessionKey??i?.originSessionKey});v={content:[{type:"text",text:ie(`β οΈ Merge conflicts in ${I.conflictFiles.length} file(s) β spawned conflict resolver session: ${w.name}`,I)}]}}catch(w){v={content:[{type:"text",text:ie(`β Merge conflicts detected, but failed to spawn resolver: ${w instanceof Error?w.message:String(w)}`,I)}]}}}else{let m=I.dirtyError?`β Merge blocked: ${I.error}`:`β Merge failed: ${I.error??"unknown error"}`;v={content:[{type:"text",text:ie(m,I)}]}}}),v}}}function Tu(n){return!!n&&typeof n=="object"}function ms(n){return{name:"agent_worktree_cleanup",description:"Manage worktree cleanup with lifecycle-aware safety rules. Use preview_safe to list what Clean all safe would remove, clean_safe to execute it, or preview_all to see both safe and retained sandboxes with kept reasons.",parameters:p.Object({workdir:p.Optional(p.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:p.Optional(p.String({description:"Override base branch for lifecycle resolution"})),mode:p.Optional(p.Union([p.Literal("preview_safe"),p.Literal("clean_safe"),p.Literal("preview_all")],{description:"Cleanup mode. preview_safe shows what Clean all safe would remove, clean_safe performs that cleanup, preview_all shows both safe and retained worktrees. Defaults to preview_safe when dry_run=true, otherwise clean_safe."})),skip_session_check:p.Optional(p.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:p.Optional(p.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:p.Optional(p.Boolean({description:"Show what would be cleaned without deleting anything."})),session:p.Optional(p.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:p.Optional(p.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,t){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Tu(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let r=t.session,o=t.mode??(t.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",s=o==="preview_all"||o==="clean_safe";if(r&&t.dismiss_session===!0)return{content:[{type:"text",text:await k.dismissWorktree(r)}]};let a=Bt(k);if(r&&(a=a.filter(S=>Kt(S,r)),a.length===0)){let S=Ft(k,r);if(!S.persistedSession&&!S.activeSession)return{content:[{type:"text",text:`Error: Session "${r}" not found.`}]}}if(t.workdir&&(a=a.filter(S=>S.workdir===t.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let l=[],d=[],u=[],f=[];for(let S of a){let{persistedSession:y,activeSession:c,resolvedLifecycle:h}=Lt(k,S,{baseBranch:t.base_branch});if(!h.cleanupSafe){if(s){let v=h.reasons.length>0?h.reasons.map(qt).join(", "):Se(h.derivedState);d.push(`${S.name} [kept: ${v}]`)}continue}if(l.push(`${S.name} (${Se(h.derivedState)})`),!i)try{let v=S.workdir;if(!((y??c)&&L(y??c))&&S.worktreePath&&B(v,S.worktreePath,{destructive:!1}),S.worktreeBranch&&H(v,S.worktreeBranch),y){let A=h.derivedState==="merged"||h.derivedState==="released"?h.derivedState:h.lifecycle.state,I=new Date().toISOString(),
|
|
73
|
+
`);try{let w=k.spawn({prompt:m,workdir:d,name:`${t.session}-conflict-resolver`,harness:Y(),permissionMode:"bypassPermissions",multiTurn:!0,route:o?.route??i?.route,originChannel:o?.originChannel??i?.originChannel,originThreadId:o?.originThreadId??i?.originThreadId,originAgentId:o?.originAgentId??i?.originAgentId,originSessionKey:o?.originSessionKey??i?.originSessionKey});v={content:[{type:"text",text:ie(`β οΈ Merge conflicts in ${I.conflictFiles.length} file(s) β spawned conflict resolver session: ${w.name}`,I)}]}}catch(w){v={content:[{type:"text",text:ie(`β Merge conflicts detected, but failed to spawn resolver: ${w instanceof Error?w.message:String(w)}`,I)}]}}}else{let m=I.dirtyError?`β Merge blocked: ${I.error}`:`β Merge failed: ${I.error??"unknown error"}`;v={content:[{type:"text",text:ie(m,I)}]}}}),v}}}function Tu(n){return!!n&&typeof n=="object"}function ms(n){return{name:"agent_worktree_cleanup",description:"Manage worktree cleanup with lifecycle-aware safety rules. Use preview_safe to list what Clean all safe would remove, clean_safe to execute it, or preview_all to see both safe and retained sandboxes with kept reasons.",parameters:p.Object({workdir:p.Optional(p.String({description:"Restrict cleanup to sessions rooted in this repository"})),base_branch:p.Optional(p.String({description:"Override base branch for lifecycle resolution"})),mode:p.Optional(p.Union([p.Literal("preview_safe"),p.Literal("clean_safe"),p.Literal("preview_all")],{description:"Cleanup mode. preview_safe shows what Clean all safe would remove, clean_safe performs that cleanup, preview_all shows both safe and retained worktrees. Defaults to preview_safe when dry_run=true, otherwise clean_safe."})),skip_session_check:p.Optional(p.Boolean({description:"Deprecated. Safe cleanup never removes live sessions."})),force:p.Optional(p.Boolean({description:"Deprecated alias for skip_session_check."})),dry_run:p.Optional(p.Boolean({description:"Show what would be cleaned without deleting anything."})),session:p.Optional(p.String({description:"Session name or ID to clean or dismiss."})),dismiss_session:p.Optional(p.Boolean({description:"When true and session is provided, permanently dismiss the worktree."}))}),async execute(e,t){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!Tu(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { workdir?, base_branch?, mode?, dry_run?, session?, dismiss_session? }."}]};let r=t.session,o=t.mode??(t.dry_run===!0?"preview_safe":"clean_safe"),i=o!=="clean_safe",s=o==="preview_all"||o==="clean_safe";if(r&&t.dismiss_session===!0)return{content:[{type:"text",text:await k.dismissWorktree(r)}]};let a=Bt(k);if(r&&(a=a.filter(S=>Kt(S,r)),a.length===0)){let S=Ft(k,r);if(!S.persistedSession&&!S.activeSession)return{content:[{type:"text",text:`Error: Session "${r}" not found.`}]}}if(t.workdir&&(a=a.filter(S=>S.workdir===t.workdir)),a.length===0)return{content:[{type:"text",text:"No managed worktrees matched the requested scope."}]};let l=[],d=[],u=[],f=[];for(let S of a){let{persistedSession:y,activeSession:c,resolvedLifecycle:h}=Lt(k,S,{baseBranch:t.base_branch});if(!h.cleanupSafe){if(s){let v=h.reasons.length>0?h.reasons.map(qt).join(", "):Se(h.derivedState);d.push(`${S.name} [kept: ${v}]`)}continue}if(l.push(`${S.name} (${Se(h.derivedState)})`),!i)try{let v=S.workdir;if(!((y??c)&&L(y??c))&&S.worktreePath&&B(v,S.worktreePath,{destructive:!1}),S.worktreeBranch&&H(v,S.worktreeBranch),y){let A=h.derivedState==="merged"||h.derivedState==="released"?h.derivedState:h.lifecycle.state,I=new Date().toISOString(),R=A==="merged"?y.worktreeMergedAt:A==="dismissed"?y.worktreeDismissedAt:void 0;k.updatePersistedSession(S.id,{worktreePath:void 0,worktreeBranch:void 0,lifecycle:"terminal",worktreeState:"none",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0,worktreeMerged:A==="merged"?!0:y.worktreeMerged,worktreeMergedAt:A==="merged"?y.worktreeMergedAt??I:y.worktreeMergedAt,worktreeLifecycle:{...y.worktreeLifecycle??h.lifecycle,state:A,updatedAt:I,resolvedAt:y.worktreeLifecycle?.resolvedAt??R??I,resolutionSource:y.worktreeLifecycle?.resolutionSource??"maintenance",baseBranch:t.base_branch??h.lifecycle.baseBranch??y.worktreeBaseBranch,targetRepo:y.worktreePrTargetRepo,pushRemote:y.worktreePushRemote,notes:h.reasons}})}u.push(`${S.name} (${Se(h.derivedState)})`)}catch(v){f.push(`${S.name}: ${v instanceof Error?v.message:String(v)}`)}}let g=[o==="clean_safe"?"Clean all safe:":o==="preview_all"?"Worktree lifecycle review:":"Clean all safe preview:"];return g.push(` SAFE ${i?"NOW":"FOUND"} (${l.length}): ${l.join(", ")||"(none)"}`),s&&g.push(` KEPT (${d.length}): ${d.join(", ")||"(none)"}`),i||(g.push(` CLEANED (${u.length}): ${u.join(", ")||"(none)"}`),g.push(` FAILURES (${f.length}): ${f.join(", ")||"(none)"}`)),{content:[{type:"text",text:g.join(`
|
|
74
74
|
`)}]}}}}function xu(n){if(n==null)return!0;if(Array.isArray(n)||typeof n!="object")return!1;let e=n.session;return e===void 0||typeof e=="string"}function fs(n){return{name:"agent_worktree_status",description:"Show lifecycle-first worktree status for coding agent sessions. Displays product-facing lifecycle state, released handling, cleanup safety, and retained reasons.",parameters:p.Object({session:p.Optional(p.String({description:"Session name or ID to show status for (optional, shows all if omitted)"}))}),async execute(e,t){if(!k)return{content:[{type:"text",text:"Error: SessionManager not initialized. The code-agent service must be running."}]};if(!xu(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { session? }."}]};let r=t&&typeof t=="object"?t.session:void 0,o=Bt(k);if(r&&(o=o.filter(s=>Kt(s,r)),o.length===0))return{content:[{type:"text",text:`Error: Session "${r}" not found or has no worktree.`}]};if(o.length===0)return{content:[{type:"text",text:"No sessions with worktrees found."}]};let i=[];for(let s of o){let{persistedSession:a,resolvedLifecycle:l}=Lt(k,s),d=l.cleanupSafe?"safe now":l.preserve?"preserve":"blocked";i.push(`Session: ${s.name} [${s.id}]`),i.push(` Branch: ${s.worktreeBranch??"(unknown)"} β ${l.lifecycle.baseBranch??a?.worktreeBaseBranch??"main"}`),i.push(` Repo: ${s.workdir}`),i.push(` Lifecycle:${Se(l.lifecycle.state)}`),l.derivedState!==l.lifecycle.state&&i.push(` Derived: ${Se(l.derivedState)}`),i.push(` Cleanup: ${d}`),l.evidence.prUrl&&i.push(` PR: ${l.evidence.prUrl} (${l.evidence.prState??"unknown"})`),(l.evidence.branchAheadCount!=null||l.evidence.baseAheadCount!=null)&&i.push(` Ahead: ${l.evidence.branchAheadCount??0} ahead / ${l.evidence.baseAheadCount??0} behind`),i.push(` Reasons: ${l.reasons.length>0?l.reasons.map(qt).join(", "):"none"}`),i.push("")}return{content:[{type:"text",text:i.join(`
|
|
75
75
|
`).trim()}]}}}}import{existsSync as Cu}from"fs";function Mu(n=[]){return n.map((e,t)=>({label:`check-${t+1}`,command:e.trim()})).filter(e=>e.command.length>0)}function bn(n,e){let t=n.goal.trim();if(!t)return{kind:"error",text:"Error: goal must not be empty."};let r=n.workdir||e.workspaceDir||_.defaultWorkdir||process.cwd();if(!Cu(r))return{kind:"error",text:`Error: Working directory does not exist: ${r}`};let o=Mu(n.verifierCommands),i=n.goalMode??(o.length>0?"verifier":"ralph");if(i==="verifier"&&o.length===0)return{kind:"error",text:"Error: verifier mode requires at least one non-empty verifier command."};let s=n.harness??Y(),a=n.model??Me(s),l=Rt(s,a),d=Pt(s);if(!l&&(s!=="opencode"||d&&d.length>0))return{kind:"error",text:`Error: No default model configured for harness "${s}". Set plugins.entries["openclaw-code-agent"].config.harnesses.${s}.defaultModel or pass model explicitly.`};if(l&&!It(s,l))return{kind:"error",text:`Error: Model "${a}" is not supported for harness "${s}". Use a bare Codex model id such as "gpt-5.6-sol".`};if(l&&!At(s,l,d))return{kind:"error",text:`Error: Model "${a}" is not allowed. Permitted models: ${d?.join(", ")}`};let u=Tt(s,l,d),f=e.sessionKey||void 0,g=wt(e),S=bt(e,g||$e(r)),y=De(e,S,f),c=Jt({ctx:e,route:y,operation:"goal task"});if(c.kind==="error")return c;let h=c.route;return{kind:"resolved",goal:t,name:n.name,workdir:r,model:u,reasoningEffort:ce(s),fastMode:_e(s),systemPrompt:n.systemPrompt,allowedTools:n.allowedTools,maxIterations:n.maxIterations,permissionMode:n.permissionMode??"bypassPermissions",harness:s,loopMode:i,completionPromise:n.completionPromise,originChannel:S,originThreadId:y?.threadId,originAgentId:e.agentId||void 0,originSessionKey:f,route:h,verifierCommands:o}}function Rn(n,e){return["Goal task launched.",` Name: ${n.name}`,` ID: ${n.id}`,` Dir: ${n.workdir}`,` Session: ${n.sessionName} [${n.sessionId}]`,` Harness: ${e.harness}`,` Model: ${e.model??"default"}`,...e.fastMode?[" Fast mode: enabled"]:[],` Loop mode: ${n.loopMode}`,` Max controller iterations: ${n.maxIterations}`,` Goal: "${e.goal.length>100?`${e.goal.slice(0,100)}...`:e.goal}"`,...n.loopMode==="ralph"?[` Completion promise: ${n.completionPromise}`]:[" Verifiers:",...e.verifierCommands.map(r=>` - ${r.command}`)],"","Controller iteration progress advances only when the goal controller starts another agent turn; internal agent review passes are reported in the completion summary.","","Use /agent_goal_status to follow progress or /agent_goal_stop to terminate the task in chat."].join(`
|
|
76
76
|
`)}function _u(n){return!n||typeof n!="object"?!1:typeof n.goal=="string"}function gs(n){return{name:"agent_goal_launch",description:"Launch an explicit goal loop. Use this only when the user specifically asks for a goal task, Ralph-style autonomous loop, iterative loop, autonomous repair loop, or keep-going-until-checks-pass workflow. This is not the default session path.",parameters:p.Object({goal:p.String({description:"End goal for the autonomous task"}),verifier_commands:p.Optional(p.Array(p.String({description:"Shell command that must pass for the goal to be considered complete"}),{minItems:1,description:"Verifier commands run after each coding turn"})),name:p.Optional(p.String({description:"Short task name (kebab-case preferred)"})),workdir:p.Optional(p.String({description:"Working directory (defaults to cwd / configured workspace)"})),model:p.Optional(p.String({description:"Model name to use"})),system_prompt:p.Optional(p.String({description:"Additional system prompt"})),allowed_tools:p.Optional(p.Array(p.String(),{description:"Allowed tools for the underlying agent session"})),max_iterations:p.Optional(p.Number({description:"Maximum verifier-driven repair iterations",minimum:1})),goal_mode:p.Optional(p.Union([p.Literal("ralph"),p.Literal("verifier")],{description:"Loop strategy. 'ralph' repeats until a completion promise appears. 'verifier' repeats until verifier commands pass. Defaults to 'ralph' when no verifiers are provided, otherwise 'verifier'."})),completion_promise:p.Optional(p.String({description:"Exact completion promise for Ralph-mode loops. Defaults to 'DONE'."})),permission_mode:p.Optional(p.Union([p.Literal("default"),p.Literal("plan"),p.Literal("bypassPermissions")],{description:"Permission mode for the underlying agent session. Defaults to bypassPermissions for autonomous goal loops."})),harness:p.Optional(p.String({description:"Agent harness to use ('claude-code', 'codex', or experimental 'opencode')."}))}),async execute(e,t){if(!$)return{content:[{type:"text",text:"Error: GoalController not initialized. The code-agent service must be running."}]};if(!_u(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected at least { goal }."}]};let r=bn({goal:t.goal,verifierCommands:t.verifier_commands,name:t.name,workdir:t.workdir,model:t.model,systemPrompt:t.system_prompt,allowedTools:t.allowed_tools,maxIterations:t.max_iterations,permissionMode:t.permission_mode,harness:t.harness,goalMode:t.goal_mode,completionPromise:t.completion_promise},n);if(r.kind!=="resolved")return{content:[{type:"text",text:r.text}]};try{let o=await $.launchTask({goal:r.goal,name:r.name,workdir:r.workdir,model:r.model,reasoningEffort:r.reasoningEffort,fastMode:r.fastMode,systemPrompt:r.systemPrompt,allowedTools:r.allowedTools,maxIterations:r.maxIterations,permissionMode:r.permissionMode,loopMode:r.loopMode,completionPromise:r.completionPromise,originChannel:r.originChannel,originThreadId:r.originThreadId,originAgentId:r.originAgentId,originSessionKey:r.originSessionKey,route:r.route,harness:r.harness,verifierCommands:r.verifierCommands});return{content:[{type:"text",text:Rn(o,r)}]}}catch(o){return{content:[{type:"text",text:`Error launching goal task: ${o instanceof Error?o.message:String(o)}`}]}}}}}function io(n,e){return n.split(`
|
|
@@ -82,7 +82,7 @@ ${I.error}`,I)}]};else if(I.conflictFiles&&I.conflictFiles.length>0){let m=["Res
|
|
|
82
82
|
`)}function Tn(n,e){return n?n.action==="already_terminal"?`Task is already ${n.task.status}.`:`Task "${n.task.name}" (${n.task.id}) stopped.`:`Error: Goal task "${e}" not found.`}function xn(n,e){switch(n.action){case"updated":return`Task "${n.task.name}" (${n.task.id}) goal updated.`;case"not_found":return`Error: Goal task "${e}" not found.`;case"invalid_goal":return"Error: replacement goal must not be empty.";case"not_editable":return n.task.status!=="waiting_for_user"?`Task is already ${n.task.status}.`:`Error: Goal task "${n.task.name}" is ${n.task.status} and cannot be edited.`}}function ys(n){return{name:"agent_goal_status",description:"Show status for explicit goal tasks managed by the goal controller. Use this to inspect one goal task or list all goal tasks.",parameters:p.Object({task:p.Optional(p.String({description:"Task name or ID. Omit to list all tasks."}))}),async execute(e,t){if(!$)return{content:[{type:"text",text:X}]};let r=t&&typeof t=="object"&&typeof t.task=="string"?t.task:void 0;return{content:[{type:"text",text:In($,o=>k?.resolve(o),r)}]}}}}function Nu(n){return!!n&&typeof n=="object"&&typeof n.task=="string"}function Ss(n){return{name:"agent_goal_stop",description:"Stop an explicit goal task and kill its underlying agent session.",parameters:p.Object({task:p.String({description:"Goal task name or ID"})}),async execute(e,t){if(!$)return{content:[{type:"text",text:X}]};if(!Nu(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task }."}]};let r=$.stopTask(t.task);return{content:[{type:"text",text:Tn(r,t.task)}]}}}}function Ou(n){if(!n||typeof n!="object")return!1;let e=n;return typeof e.task=="string"&&typeof e.goal=="string"}function ks(n){return{name:"agent_goal_edit",description:"Edit the goal text for an active goal task without stopping or relaunching its session.",parameters:p.Object({task:p.String({description:"Goal task name or ID"}),goal:p.String({description:"Replacement goal text"})}),async execute(e,t){if(!$)return{content:[{type:"text",text:X}]};if(!Ou(t))return{content:[{type:"text",text:"Error: Invalid parameters. Expected { task, goal }."}]};let r=$.editTask(t.task,t.goal);return{content:[{type:"text",text:xn(r,t.task)}]}}}}var lo=new Set,vs="β οΈ Could not submit that answer. The question prompt is still active; try again or reply with the answer.",ut=new Map;function Wu(n){return`${n.sessionId}:${n.pendingInputRequestId??n.id}`}function Fu(n){return!!(n&&n.status!=="running"&&ke(n).kind==="resume")}function Lu(n){return n.label?.trim()?["[SYSTEM: The gateway restarted while a user question was pending. Treat the user's selection below as the answer to that interrupted question and continue without asking it again.]","",n.pendingInputQuestionId?`Question ID: ${n.pendingInputQuestionId}`:"Question: the interrupted pending question",`Selected answer: ${n.label.trim()}`].join(`
|
|
83
83
|
`):void 0}async function Rs(n){try{await n}catch(e){let t=e instanceof Error?e.message:String(e);`${t}`}}async function Ps(n,e,t){if(!n)return t();for(;;){let o=ut.get(n)?.operation;if(!o)break;await Rs(o)}let r=Promise.resolve().then(t);ut.set(n,{operation:r,tokenId:e});try{return await r}finally{ut.get(n)?.operation===r&&ut.delete(n)}}function Bu(n){let e=n.trim().replace(new RegExp(`^${W}:`),"");return e||null}function Ku(n){return n.trim().startsWith(`${W}:`)}async function Cn(n,e=!1){if(n.channel==="telegram")try{return(await N(n,{alreadyAcknowledged:e,forceTelegramMarkupEdit:!0})).textDelivered}catch(r){let o=r instanceof Error?r.message:String(r);return`${o}`,!1}let t=n.respond;if(typeof t.clearComponents=="function")try{return await t.clearComponents(),!1}catch(r){if(be(r))return!1;let o=r instanceof Error?r.message:String(r);`${o}`}if(typeof t.clearButtons=="function")try{await t.clearButtons()}catch(r){let o=r instanceof Error?r.message:String(r);`${o}`}else!e&&typeof t.acknowledge=="function"&&await t.acknowledge();return!1}async function ne(n,e=!1){await N(n,{alreadyAcknowledged:e,forceTelegramMarkupEdit:n.channel==="telegram"})}function Dn(n){if(n&&typeof n=="object"&&"content"in n&&Array.isArray(n.content)){let e=n.content[0];return typeof e?.text=="string"?e.text:"(done)"}return"(done)"}function ws(n){if(n&&typeof n=="object"&&"meta"in n){let e=n.meta;if(typeof e?.success=="boolean")return e.success}return po(Dn(n))}function po(n){return!/^\s*(?:Error\b:?|β|β οΈ)/.test(n)}function $n(n){return n==="plan-approve"||n==="plan-request-changes"||n==="plan-reject"}function qu(n){if($n(n.kind))return`${n.sessionId}:v${n.planDecisionVersion??"unknown"}`}function Vu(n){return n?n.approvalState==="approved"||!n.pendingPlanApproval:!1}function uo(n,e){if(!$n(n.kind))return;if(!e)return"This plan decision is stale because the session is no longer available.";let t=Kr(e);if(n.planDecisionVersion!=null&&t!=null&&n.planDecisionVersion!==t)return"This plan decision is stale because a newer plan review state already exists.";if(!e.pendingPlanApproval)return"This plan is no longer awaiting approval.";if(n.kind==="plan-approve"&&e.approvalState==="changes_requested"&&!e.pendingPlanApproval)return"Changes were already requested for this plan. Wait for the revised plan before approving.";if(n.kind==="plan-request-changes"&&e.approvalState==="changes_requested")return"Changes were already requested for this plan. Send your feedback to the agent instead."}function As(n,...e){return e.find(t=>typeof t=="string"&&n(t))}function Mn(...n){return As(e=>e.trim().length>0,...n)}function bs(...n){return As(Ku,...n)}function Uu(n){let e="callback"in n?bs(n.callback?.data,n.callback?.callback_data,n.callback?.callbackData):void 0;if(e)return e;let t="interaction"in n?n.interaction:void 0,r=bs(t?.data,t?.callback_data,t?.callbackData);if(r)return r;let o="callback"in n?Mn(n.callback?.payload):void 0;if(o)return o;let i=Mn(t?.payload);return i||(("callback"in n?Mn(n.callback?.data,n.callback?.callback_data,n.callback?.callbackData):void 0)??Mn(t?.data,t?.callback_data,t?.callbackData)??"")}function ct(n,e=new Set){if(n==null)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return String(n);if(n instanceof Error)return[n.name,n.message,ct(n.cause,e)].filter(Boolean).join(" ");if(typeof n!="object")return String(n);if(e.has(n))return"";e.add(n);let t=n;return[t.message,t.description,t.error,t.error_description,ct(t.cause,e),ct(t.response,e),ct(t.payload,e)].filter(Boolean).join(" ")}function be(n){return/message is not modified/i.test(ct(n))}function Gu(n){let e=n instanceof Error?n.message:String(n);return/empty message/i.test(e)}async function we(n){if(typeof n.clearButtons=="function")try{await n.clearButtons()}catch(e){if(be(e))return;throw e}}async function N(n,e={}){let t=n.respond,{alreadyAcknowledged:r=!1,forceTelegramMarkupEdit:o=!1,text:i}=e;if(n.channel==="telegram"){if(typeof i=="string"&&typeof t.editMessage=="function")try{return await t.editMessage({text:i,buttons:[]}),await we(t),{textDelivered:!0}}catch(a){if(be(a))return await we(t),{textDelivered:!0};let l=a instanceof Error?a.message:String(a);`${l}`}if(o&&typeof t.editButtons=="function")try{return await t.editButtons({buttons:[]}),await we(t),{textDelivered:!1}}catch(a){if(be(a))return await we(t),{textDelivered:!1};let l=a instanceof Error?a.message:String(a);`${l}`}let s="callback"in n&&typeof n.callback?.messageText=="string"?n.callback.messageText:void 0;if(o&&typeof s=="string"&&typeof t.editMessage=="function")try{return await t.editMessage({text:s,buttons:[]}),await we(t),{textDelivered:!1}}catch(a){if(be(a))return await we(t),{textDelivered:!1};let l=a instanceof Error?a.message:String(a);`${l}`}return await we(t),{textDelivered:!1}}if(typeof t.clearComponents=="function")try{return await t.clearComponents(typeof i=="string"?{text:i}:void 0),{textDelivered:typeof i=="string"}}catch(s){if(be(s))return{textDelivered:typeof i=="string"};if(Gu(s)){if(typeof i!="string"&&r)return{textDelivered:!1};if(typeof i!="string"&&typeof t.acknowledge=="function")return await t.acknowledge(),{textDelivered:!1};typeof i!="string"&&t.acknowledge}else{if(typeof i!="string")throw s;{let a=s instanceof Error?s.message:String(s);`${a}`}}}if(typeof i=="string"&&typeof t.editMessage=="function"){try{await t.editMessage({text:i})}catch(s){if(be(s))return typeof t.clearButtons=="function"&&await t.clearButtons(),{textDelivered:!0};let a=s instanceof Error?s.message:String(s);return`${a}`,typeof t.clearButtons=="function"&&await t.clearButtons(),{textDelivered:!1}}return typeof t.clearButtons=="function"&&await t.clearButtons(),{textDelivered:!0}}return typeof t.clearButtons=="function"&&await t.clearButtons(),{textDelivered:!1}}async function ju(n){let e=n.respond;if(typeof e.acknowledge!="function")return!1;try{return await e.acknowledge(),!0}catch(t){let r=t instanceof Error?t.message:String(t);return`${r}`,!1}}async function x(n,e){if(n.channel==="telegram"){await n.respond.reply({text:e});return}await n.respond.reply({text:e,ephemeral:!0})}var zu="β οΈ This action is stale or has already been used.";async function qe(n,e){try{await e()}catch(t){let r=t instanceof Error?t.message:String(t);`${r}`}try{await x(n,zu)}catch(t){let r=t instanceof Error?t.message:String(t);`${r}`}}async function _n(n,e){try{await N(n,{alreadyAcknowledged:e,forceTelegramMarkupEdit:!0})}catch(t){let r=t instanceof Error?t.message:String(t);`${r}`}}var co=["plan-approve","plan-request-changes","plan-reject"];function Hu(n){switch(n){case"plan-approve":return"Approve";case"plan-request-changes":return"Revise";case"plan-reject":return"Reject";default:return"Continue"}}function Qu(n){switch(n){case"plan-approve":return"primary";case"plan-reject":return"danger";default:return"secondary"}}function Yu(n,e){let t=n,o=(typeof t?.listActiveActionTokens=="function"?co.flatMap(a=>t.listActiveActionTokens?.(a)??[]):[e]).filter(a=>$n(a.kind)&&a.sessionId===e.sessionId&&(e.planDecisionVersion==null||a.planDecisionVersion==null||a.planDecisionVersion===e.planDecisionVersion)).sort((a,l)=>co.indexOf(a.kind)-co.indexOf(l.kind)),i=new Set,s=o.filter(a=>i.has(a.kind)?!1:(i.add(a.kind),!0)).map(a=>({label:typeof a.label=="string"&&a.label.trim()?a.label:Hu(a.kind),callbackData:`${W}:${a.id}`,style:Qu(a.kind)}));return s.length>0?[s]:void 0}async function Ju(n,e,t,r){if(n.channel!=="telegram"){await x(n,e);return}let o=Yu(t,r);await n.respond.reply({text:o?`${e}
|
|
84
84
|
|
|
85
|
-
Approval is still pending. Try again below.`:e,...o?{buttons:o}:{}})}function Is(n="telegram",e={}){let t=e.makeAgentMergeTool??wn,r=e.makeAgentPrTool??Vt;return M("callback_handler_registered",{channel:n,namespace:W}),{channel:n,namespace:W,handler:async o=>{let i=await ju(o);if(!o.auth.isAuthorizedSender)return await x(o,"β Unauthorized."),{handled:!0};let s=Uu(o),a=Bu(s);if(M("callback_received",{channel:o.channel,namespace:W,payloadByteLength:Buffer.byteLength(s,"utf8"),tokenHash:K(a),isAuthorizedSender:o.auth.isAuthorizedSender}),!a)return await x(o,"β οΈ Unrecognized callback payload."),{handled:!0};if(!k)return await x(o,"β οΈ Code agent service not running."),{handled:!0};let l=k.getActionToken(a);if(M("callback_token_lookup_completed",{channel:o.channel,namespace:W,tokenHash:K(a),tokenFound:!!l,actionKind:l?.kind,sessionId:l?.sessionId,planDecisionVersion:l?.planDecisionVersion}),!l)return await qe(o,()=>N(o,{alreadyAcknowledged:i})),{handled:!0};if(l.kind==="question-answer"&&l.consumedAt!=null)return await N(o,{alreadyAcknowledged:i}),await x(o,"β οΈ That question button is no longer active. Use the latest question prompt."),{handled:!0};let d=l.sessionId,u=k.resolve?.(d)??k.getPersistedSession?.(d),f=u?.name??d;if(u&&qr(l,u))return k.consumePlanDecisionTokens?.(d,l.planDecisionVersion),await ne(o,i),await x(o,`β
Plan v${l.planDecisionVersion} was already approved; resume is in progress or running.`),{handled:!0};let g=uo(l,u);if(M("callback_plan_validation_completed",{channel:o.channel,namespace:W,tokenHash:K(a),actionKind:l.kind,sessionId:d,sessionName:f,planDecisionVersion:l.planDecisionVersion,valid:!g}),g)return $n(l.kind)?await ne(o,i):await N(o,{alreadyAcknowledged:i}),await x(o,`β οΈ ${g}`),{handled:!0};if(l.kind==="question-answer"){if(l.optionIndex==null)return await N(o,{alreadyAcknowledged:i}),await x(o,"β οΈ Invalid question-answer action."),{handled:!0};let c=Wu(l);if(lo.has(c))return await x(o,"β οΈ That answer is already being submitted. If the question remains active, try again."),{handled:!0};lo.add(c);let h=!1,v=!1;try{if(h=await k.resolvePendingInputOption(d,l.optionIndex,{requestId:l.pendingInputRequestId,questionId:l.pendingInputQuestionId}),!h&&!(k.canSubmitPendingInputOption?.(d)??!1)){let b=k.getPersistedSession?.(d),m=Lu(l);m&&Fu(b)&&(h=!(await Q(k,{session:d,message:m,userInitiated:!0})).isError,v=h)}}catch(b){let m=b instanceof Error?b.message:String(b);return`${m}`,await x(o,vs),{handled:!0}}finally{lo.delete(c)}if(!h)return await x(o,vs),{handled:!0};let A=(l.pendingInputRequestId?k.consumeQuestionAnswerTokens(d,l.pendingInputRequestId,l.pendingInputQuestionId):[]).find(b=>b.id===a)??k.consumeActionToken(a);if(M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!A,actionKind:A?.kind,sessionId:A?.sessionId,planDecisionVersion:A?.planDecisionVersion}),!A){await N(o,{alreadyAcknowledged:i});let b=!v&&(k.pendingInputSubmissionRequiresMore?.(d)??!1);return await x(o,v?"β
Answer forwarded to the resumed session.":b?"β
Question step answered; more input is required.":"β
Pending input request submitted."),{handled:!0}}await N(o,{alreadyAcknowledged:i});let I=!v&&(k.pendingInputSubmissionRequiresMore?.(d)??!1);return await x(o,v?"β
Answer forwarded to the resumed session.":I?"β
Question step answered; more input is required.":"β
Pending input request submitted."),{handled:!0}}let S=qu(l);if(S)for(;;){let c=ut.get(S);if(!c)break;if(c.tokenId===a)return await ne(o,i),await x(o,"β οΈ This plan decision is already being processed."),{handled:!0};await Rs(c.operation);let h=k.getActionToken(a);if(!h)return await qe(o,()=>ne(o,i)),{handled:!0};if(d=h.sessionId,u=k.resolve?.(d)??k.getPersistedSession?.(d),f=u?.name??d,u&&qr(h,u))return k.consumePlanDecisionTokens?.(d,h.planDecisionVersion),await ne(o,i),await x(o,`β
Plan v${h.planDecisionVersion} was already approved; resume is in progress or running.`),{handled:!0};if(g=uo(h,u),M("callback_plan_validation_completed",{channel:o.channel,namespace:W,tokenHash:K(a),actionKind:h.kind,sessionId:d,sessionName:f,planDecisionVersion:h.planDecisionVersion,valid:!g,afterPlanDecisionLock:!0}),g)return await ne(o,i),await x(o,`β οΈ ${g}`),{handled:!0};l=h}if(l.kind==="plan-approve"){let c=l,h=!1,v=async(I=!1)=>{h||!I&&o.channel!=="telegram"||(await ne(o,i),h=!0)},R=await Ps(S,a,async()=>(await v(),Q(k,{session:c.sessionId,message:"Approved. Go ahead.",approve:!0,userInitiated:!0})));if(R.isError){let I=k.resolve?.(c.sessionId)??k.getPersistedSession?.(c.sessionId),b=Vu(I);if(b){let m=k.consumeActionToken(a);M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!m,actionKind:m?.kind,sessionId:m?.sessionId??c.sessionId,planDecisionVersion:m?.planDecisionVersion,approvalAppliedAfterError:!0}),await v(!0)}return b?await x(o,`β οΈ ${R.text}`):await Ju(o,`β οΈ ${R.text}`,k,c),{handled:!0}}let A=k.consumeActionToken(a);return M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!A,actionKind:A?.kind,sessionId:A?.sessionId??c.sessionId,planDecisionVersion:A?.planDecisionVersion}),A?(await v(!0),{handled:!0}):(await qe(o,()=>v(!0)),{handled:!0})}if(l.kind==="plan-reject"||l.kind==="plan-request-changes")return await Ps(S,a,async()=>{let c=k.getActionToken(a);if(!c)return await qe(o,()=>ne(o,i)),{handled:!0};d=c.sessionId,u=k.resolve?.(d)??k.getPersistedSession?.(d),f=u?.name??d;let h=uo(c,u);if(M("callback_plan_validation_completed",{channel:o.channel,namespace:W,tokenHash:K(a),actionKind:c.kind,sessionId:d,sessionName:f,planDecisionVersion:c.planDecisionVersion,valid:!h,afterPlanDecisionLock:!0}),h)return await ne(o,i),await x(o,`β οΈ ${h}`),{handled:!0};let v=k.consumeActionToken(a);if(M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!v,actionKind:v?.kind,sessionId:v?.sessionId,planDecisionVersion:v?.planDecisionVersion}),!v)return await qe(o,()=>ne(o,i)),{handled:!0};if(await ne(o,i),v.kind==="plan-reject"){let R=Yr(k,d);await x(o,`β ${R.text}`)}else{let R=Jr(k,d);await x(o,`βοΈ ${R.text}`)}return{handled:!0}});let y=k.consumeActionToken(a);if(M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!y,actionKind:y?.kind,sessionId:y?.sessionId,planDecisionVersion:y?.planDecisionVersion}),!y)return await qe(o,()=>N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:l.kind==="plan-offer-start"||l.kind==="plan-offer-dismiss"})),{handled:!0};switch(y.kind){case"plugin-update-install":{if(await _n(o,i),M("callback_update_action_started",{channel:o.channel,tokenHash:K(a),actionKind:y.kind,approvedVersion:y.pluginUpdateVersion}),!de){M("callback_update_action_failed",{channel:o.channel,tokenHash:K(a),reason:"service_unavailable"}),await x(o,"β οΈ OpenClaw Code Agent update service is not running.");break}let c;try{c=await de.installConfirmed(y.pluginUpdateVersion,{route:y.route})}catch(h){M("callback_update_action_failed",{channel:o.channel,tokenHash:K(a),reason:"install_failed"}),await x(o,`β οΈ OpenClaw Code Agent update failed: ${h instanceof Error?h.message:String(h)}`);break}M("callback_update_action_completed",{channel:o.channel,tokenHash:K(a),approvedVersion:y.pluginUpdateVersion});try{await x(o,`β
${c}`)}catch(h){M("callback_update_confirmation_failed",{channel:o.channel,tokenHash:K(a),reason:"reply_failed"}),`${h instanceof Error?h.message:String(h)}`}break}case"plugin-update-restart":{if(await _n(o,i),!de){await x(o,"β οΈ OpenClaw Code Agent update service is not running.");break}try{let c=await de.restartConfirmed(y.pluginUpdateVersion);await x(o,`βΆοΈ ${c}`)}catch(c){await x(o,`β οΈ Gateway restart failed: ${c instanceof Error?c.message:String(c)}`)}break}case"plugin-update-dismiss":{await _n(o,i);let c=de?de.dismiss(y.pluginUpdateVersion):"Dismissed OpenClaw Code Agent update reminder.";await x(o,`β
${c}`);break}case"plugin-update-remind-later":{await _n(o,i);let c=de?de.remindLater(y.pluginUpdateVersion):"Will remind later about OpenClaw Code Agent update reminder.";await x(o,`β
${c}`);break}case"worktree-merge":{let c=await t().execute("callback",{session:d}),h=Dn(c);if(ws(c)){await Cn(o,i);break}await x(o,h);break}case"worktree-decide-later":{let c=k.snoozeWorktreeDecision(d,{notifyUser:!1});if(po(c)){let v=`βοΈ Snoozed 24h for [${f}]`;await Cn(o,i),await x(o,v)}else await x(o,c);break}case"worktree-dismiss":{let c=await k.dismissWorktree(d),h=po(c);h&&await Cn(o,i),await x(o,h?"β
Discarded":c);break}case"worktree-create-pr":case"worktree-update-pr":{let c=await r().execute("callback",{session:d}),h=Dn(c);if(ws(c)){await Cn(o,i);break}await x(o,h);break}case"worktree-view-pr":{await N(o,{alreadyAcknowledged:i});let c=k.getPersistedSession?.(d),h=l.targetUrl??c?.worktreePrUrl;await x(o,h?`PR: ${h}`:"β οΈ PR URL is no longer available.");break}case"plan-offer-start":{if(!y.launchPrompt||!y.launchWorkdir){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β οΈ This action is missing the plan launch context.");break}let c;try{c=k.launchPlanOffer({route:y.route,prompt:y.launchPrompt,workdir:y.launchWorkdir,name:y.launchName,worktreeStrategy:y.launchWorktreeStrategy})}catch(h){let v=h instanceof Error?h.message:String(h);await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ Failed to start planning session: ${v}`);break}await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`βΆοΈ Planning session started: ${c.name} [${c.id}]`);break}case"plan-offer-dismiss":{await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β
Dismissed.");break}case"repo-policy-set":{if(!y.repoPolicy||!y.repoPolicyWorkdir){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β οΈ This action is missing the repo policy context.");break}if(!y.launchPrompt||!y.launchWorkdir){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β οΈ This action is missing the launch context.");break}if(typeof k.resolveRepoPolicy=="function"){let v=k.resolveRepoPolicy(y.repoPolicyWorkdir);if(v.identity){let R=Ke(y.repoPolicy,v.prAvailable);if(R){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ ${R}`);break}}}let c=k.setRepoPolicy(y.repoPolicyWorkdir,y.repoPolicy);if(!c){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ Could not resolve a git repository for ${y.repoPolicyWorkdir}.`);break}k.clearRepoPolicyChoiceTokens(y.sessionId);let h;try{h=k.launchAfterRepoPolicyChoice({route:y.route,prompt:y.launchPrompt,workdir:y.launchWorkdir,name:y.launchName,model:y.launchModel,reasoningEffort:y.launchReasoningEffort,fastMode:y.launchFastMode,systemPrompt:y.launchSystemPrompt,allowedTools:y.launchAllowedTools,resumeSessionId:y.launchResumeSessionId,resumedFromSessionName:y.launchResumedFromSessionName,resumeWorktreeFrom:y.launchResumeWorktreeFrom,sessionIdOverride:y.launchSessionIdOverride,clearedPersistedCodexResume:y.launchClearedPersistedCodexResume,forkSession:y.launchForkSession,forceNewSession:y.launchForceNewSession,permissionMode:y.launchPermissionMode,planApproval:y.launchPlanApproval,harness:y.launchHarness,worktreeStrategy:y.launchWorktreeStrategy,worktreeBaseBranch:y.launchWorktreeBaseBranch,worktreePrTargetRepo:y.launchWorktreePrTargetRepo,originAgentId:y.launchOriginAgentId}).text}catch(v){let R=v instanceof Error?v.message:String(v);await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ Repo policy saved, but launch failed: ${R}`);break}await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,[`β
Repo policy saved: ${ls(c.policy).title}.`,"",h].join(`
|
|
85
|
+
Approval is still pending. Try again below.`:e,...o?{buttons:o}:{}})}function Is(n="telegram",e={}){let t=e.makeAgentMergeTool??wn,r=e.makeAgentPrTool??Vt;return M("callback_handler_registered",{channel:n,namespace:W}),{channel:n,namespace:W,handler:async o=>{let i=await ju(o);if(!o.auth.isAuthorizedSender)return await x(o,"β Unauthorized."),{handled:!0};let s=Uu(o),a=Bu(s);if(M("callback_received",{channel:o.channel,namespace:W,payloadByteLength:Buffer.byteLength(s,"utf8"),tokenHash:K(a),isAuthorizedSender:o.auth.isAuthorizedSender}),!a)return await x(o,"β οΈ Unrecognized callback payload."),{handled:!0};if(!k)return await x(o,"β οΈ Code agent service not running."),{handled:!0};let l=k.getActionToken(a);if(M("callback_token_lookup_completed",{channel:o.channel,namespace:W,tokenHash:K(a),tokenFound:!!l,actionKind:l?.kind,sessionId:l?.sessionId,planDecisionVersion:l?.planDecisionVersion}),!l)return await qe(o,()=>N(o,{alreadyAcknowledged:i})),{handled:!0};if(l.kind==="question-answer"&&l.consumedAt!=null)return await N(o,{alreadyAcknowledged:i}),await x(o,"β οΈ That question button is no longer active. Use the latest question prompt."),{handled:!0};let d=l.sessionId,u=k.resolve?.(d)??k.getPersistedSession?.(d),f=u?.name??d;if(u&&qr(l,u))return k.consumePlanDecisionTokens?.(d,l.planDecisionVersion),await ne(o,i),await x(o,`β
Plan v${l.planDecisionVersion} was already approved; resume is in progress or running.`),{handled:!0};let g=uo(l,u);if(M("callback_plan_validation_completed",{channel:o.channel,namespace:W,tokenHash:K(a),actionKind:l.kind,sessionId:d,sessionName:f,planDecisionVersion:l.planDecisionVersion,valid:!g}),g)return $n(l.kind)?await ne(o,i):await N(o,{alreadyAcknowledged:i}),await x(o,`β οΈ ${g}`),{handled:!0};if(l.kind==="question-answer"){if(l.optionIndex==null)return await N(o,{alreadyAcknowledged:i}),await x(o,"β οΈ Invalid question-answer action."),{handled:!0};let c=Wu(l);if(lo.has(c))return await x(o,"β οΈ That answer is already being submitted. If the question remains active, try again."),{handled:!0};lo.add(c);let h=!1,v=!1;try{if(h=await k.resolvePendingInputOption(d,l.optionIndex,{requestId:l.pendingInputRequestId,questionId:l.pendingInputQuestionId}),!h&&!(k.canSubmitPendingInputOption?.(d)??!1)){let R=k.getPersistedSession?.(d),m=Lu(l);m&&Fu(R)&&(h=!(await Q(k,{session:d,message:m,userInitiated:!0})).isError,v=h)}}catch(R){let m=R instanceof Error?R.message:String(R);return`${m}`,await x(o,vs),{handled:!0}}finally{lo.delete(c)}if(!h)return await x(o,vs),{handled:!0};let A=(l.pendingInputRequestId?k.consumeQuestionAnswerTokens(d,l.pendingInputRequestId,l.pendingInputQuestionId):[]).find(R=>R.id===a)??k.consumeActionToken(a);if(M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!A,actionKind:A?.kind,sessionId:A?.sessionId,planDecisionVersion:A?.planDecisionVersion}),!A){await N(o,{alreadyAcknowledged:i});let R=!v&&(k.pendingInputSubmissionRequiresMore?.(d)??!1);return await x(o,v?"β
Answer forwarded to the resumed session.":R?"β
Question step answered; more input is required.":"β
Pending input request submitted."),{handled:!0}}await N(o,{alreadyAcknowledged:i});let I=!v&&(k.pendingInputSubmissionRequiresMore?.(d)??!1);return await x(o,v?"β
Answer forwarded to the resumed session.":I?"β
Question step answered; more input is required.":"β
Pending input request submitted."),{handled:!0}}let S=qu(l);if(S)for(;;){let c=ut.get(S);if(!c)break;if(c.tokenId===a)return await ne(o,i),await x(o,"β οΈ This plan decision is already being processed."),{handled:!0};await Rs(c.operation);let h=k.getActionToken(a);if(!h)return await qe(o,()=>ne(o,i)),{handled:!0};if(d=h.sessionId,u=k.resolve?.(d)??k.getPersistedSession?.(d),f=u?.name??d,u&&qr(h,u))return k.consumePlanDecisionTokens?.(d,h.planDecisionVersion),await ne(o,i),await x(o,`β
Plan v${h.planDecisionVersion} was already approved; resume is in progress or running.`),{handled:!0};if(g=uo(h,u),M("callback_plan_validation_completed",{channel:o.channel,namespace:W,tokenHash:K(a),actionKind:h.kind,sessionId:d,sessionName:f,planDecisionVersion:h.planDecisionVersion,valid:!g,afterPlanDecisionLock:!0}),g)return await ne(o,i),await x(o,`β οΈ ${g}`),{handled:!0};l=h}if(l.kind==="plan-approve"){let c=l,h=!1,v=async(I=!1)=>{h||!I&&o.channel!=="telegram"||(await ne(o,i),h=!0)},b=await Ps(S,a,async()=>(await v(),Q(k,{session:c.sessionId,message:"Approved. Go ahead.",approve:!0,userInitiated:!0})));if(b.isError){let I=k.resolve?.(c.sessionId)??k.getPersistedSession?.(c.sessionId),R=Vu(I);if(R){let m=k.consumeActionToken(a);M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!m,actionKind:m?.kind,sessionId:m?.sessionId??c.sessionId,planDecisionVersion:m?.planDecisionVersion,approvalAppliedAfterError:!0}),await v(!0)}return R?await x(o,`β οΈ ${b.text}`):await Ju(o,`β οΈ ${b.text}`,k,c),{handled:!0}}let A=k.consumeActionToken(a);return M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!A,actionKind:A?.kind,sessionId:A?.sessionId??c.sessionId,planDecisionVersion:A?.planDecisionVersion}),A?(await v(!0),{handled:!0}):(await qe(o,()=>v(!0)),{handled:!0})}if(l.kind==="plan-reject"||l.kind==="plan-request-changes")return await Ps(S,a,async()=>{let c=k.getActionToken(a);if(!c)return await qe(o,()=>ne(o,i)),{handled:!0};d=c.sessionId,u=k.resolve?.(d)??k.getPersistedSession?.(d),f=u?.name??d;let h=uo(c,u);if(M("callback_plan_validation_completed",{channel:o.channel,namespace:W,tokenHash:K(a),actionKind:c.kind,sessionId:d,sessionName:f,planDecisionVersion:c.planDecisionVersion,valid:!h,afterPlanDecisionLock:!0}),h)return await ne(o,i),await x(o,`β οΈ ${h}`),{handled:!0};let v=k.consumeActionToken(a);if(M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!v,actionKind:v?.kind,sessionId:v?.sessionId,planDecisionVersion:v?.planDecisionVersion}),!v)return await qe(o,()=>ne(o,i)),{handled:!0};if(await ne(o,i),v.kind==="plan-reject"){let b=Yr(k,d);await x(o,`β ${b.text}`)}else{let b=Jr(k,d);await x(o,`βοΈ ${b.text}`)}return{handled:!0}});let y=k.consumeActionToken(a);if(M("callback_token_consume_completed",{channel:o.channel,namespace:W,tokenHash:K(a),consumed:!!y,actionKind:y?.kind,sessionId:y?.sessionId,planDecisionVersion:y?.planDecisionVersion}),!y)return await qe(o,()=>N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:l.kind==="plan-offer-start"||l.kind==="plan-offer-dismiss"})),{handled:!0};switch(y.kind){case"plugin-update-install":{if(await _n(o,i),M("callback_update_action_started",{channel:o.channel,tokenHash:K(a),actionKind:y.kind,approvedVersion:y.pluginUpdateVersion}),!de){M("callback_update_action_failed",{channel:o.channel,tokenHash:K(a),reason:"service_unavailable"}),await x(o,"β οΈ OpenClaw Code Agent update service is not running.");break}let c;try{c=await de.installConfirmed(y.pluginUpdateVersion,{route:y.route})}catch(h){M("callback_update_action_failed",{channel:o.channel,tokenHash:K(a),reason:"install_failed"}),await x(o,`β οΈ OpenClaw Code Agent update failed: ${h instanceof Error?h.message:String(h)}`);break}M("callback_update_action_completed",{channel:o.channel,tokenHash:K(a),approvedVersion:y.pluginUpdateVersion});try{await x(o,`β
${c}`)}catch(h){M("callback_update_confirmation_failed",{channel:o.channel,tokenHash:K(a),reason:"reply_failed"}),`${h instanceof Error?h.message:String(h)}`}break}case"plugin-update-restart":{if(await _n(o,i),!de){await x(o,"β οΈ OpenClaw Code Agent update service is not running.");break}try{let c=await de.restartConfirmed(y.pluginUpdateVersion);await x(o,`βΆοΈ ${c}`)}catch(c){await x(o,`β οΈ Gateway restart failed: ${c instanceof Error?c.message:String(c)}`)}break}case"plugin-update-dismiss":{await _n(o,i);let c=de?de.dismiss(y.pluginUpdateVersion):"Dismissed OpenClaw Code Agent update reminder.";await x(o,`β
${c}`);break}case"plugin-update-remind-later":{await _n(o,i);let c=de?de.remindLater(y.pluginUpdateVersion):"Will remind later about OpenClaw Code Agent update reminder.";await x(o,`β
${c}`);break}case"worktree-merge":{let c=await t().execute("callback",{session:d}),h=Dn(c);if(ws(c)){await Cn(o,i);break}await x(o,h);break}case"worktree-decide-later":{let c=k.snoozeWorktreeDecision(d,{notifyUser:!1});if(po(c)){let v=`βοΈ Snoozed 24h for [${f}]`;await Cn(o,i),await x(o,v)}else await x(o,c);break}case"worktree-dismiss":{let c=await k.dismissWorktree(d),h=po(c);h&&await Cn(o,i),await x(o,h?"β
Discarded":c);break}case"worktree-create-pr":case"worktree-update-pr":{let c=await r().execute("callback",{session:d}),h=Dn(c);if(ws(c)){await Cn(o,i);break}await x(o,h);break}case"worktree-view-pr":{await N(o,{alreadyAcknowledged:i});let c=k.getPersistedSession?.(d),h=l.targetUrl??c?.worktreePrUrl;await x(o,h?`PR: ${h}`:"β οΈ PR URL is no longer available.");break}case"plan-offer-start":{if(!y.launchPrompt||!y.launchWorkdir){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β οΈ This action is missing the plan launch context.");break}let c;try{c=k.launchPlanOffer({route:y.route,prompt:y.launchPrompt,workdir:y.launchWorkdir,name:y.launchName,worktreeStrategy:y.launchWorktreeStrategy})}catch(h){let v=h instanceof Error?h.message:String(h);await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ Failed to start planning session: ${v}`);break}await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`βΆοΈ Planning session started: ${c.name} [${c.id}]`);break}case"plan-offer-dismiss":{await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β
Dismissed.");break}case"repo-policy-set":{if(!y.repoPolicy||!y.repoPolicyWorkdir){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β οΈ This action is missing the repo policy context.");break}if(!y.launchPrompt||!y.launchWorkdir){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,"β οΈ This action is missing the launch context.");break}if(typeof k.resolveRepoPolicy=="function"){let v=k.resolveRepoPolicy(y.repoPolicyWorkdir);if(v.identity){let b=Ke(y.repoPolicy,v.prAvailable);if(b){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ ${b}`);break}}}let c=k.setRepoPolicy(y.repoPolicyWorkdir,y.repoPolicy);if(!c){await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ Could not resolve a git repository for ${y.repoPolicyWorkdir}.`);break}k.clearRepoPolicyChoiceTokens(y.sessionId);let h;try{h=k.launchAfterRepoPolicyChoice({route:y.route,prompt:y.launchPrompt,workdir:y.launchWorkdir,name:y.launchName,model:y.launchModel,reasoningEffort:y.launchReasoningEffort,fastMode:y.launchFastMode,systemPrompt:y.launchSystemPrompt,allowedTools:y.launchAllowedTools,resumeSessionId:y.launchResumeSessionId,resumedFromSessionName:y.launchResumedFromSessionName,resumeWorktreeFrom:y.launchResumeWorktreeFrom,sessionIdOverride:y.launchSessionIdOverride,clearedPersistedCodexResume:y.launchClearedPersistedCodexResume,forkSession:y.launchForkSession,forceNewSession:y.launchForceNewSession,permissionMode:y.launchPermissionMode,planApproval:y.launchPlanApproval,harness:y.launchHarness,worktreeStrategy:y.launchWorktreeStrategy,worktreeBaseBranch:y.launchWorktreeBaseBranch,worktreePrTargetRepo:y.launchWorktreePrTargetRepo,originAgentId:y.launchOriginAgentId}).text}catch(v){let b=v instanceof Error?v.message:String(v);await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,`β οΈ Repo policy saved, but launch failed: ${b}`);break}await N(o,{alreadyAcknowledged:i,forceTelegramMarkupEdit:!0}),await x(o,[`β
Repo policy saved: ${ls(c.policy).title}.`,"",h].join(`
|
|
86
86
|
`));break}case"session-restart":case"session-resume":{await N(o,{alreadyAcknowledged:i});let c=await Q(k,{session:d,message:"Continue where you left off.",userInitiated:!0});await x(o,c.isError?`β οΈ ${c.text}`:`βΆοΈ ${c.text}`);break}case"view-output":{await N(o,{alreadyAcknowledged:i});let c=await Sn().execute("callback",{session:d,lines:50});await x(o,Dn(c));break}default:{await N(o,{alreadyAcknowledged:i}),await x(o,"β οΈ Unknown callback action.");break}}return{handled:!0}}}}function Ve(n){return Ts(n).map(e=>e.value)}function Ts(n){return Array.from(n.matchAll(/"[^"]*"|'[^']*'|\S+/g),e=>{let t=e[0],r=e.index??0;return{value:Xu(t),raw:t,start:r,end:r+t.length}})}function Re(n){let[e]=Ts(n);if(e)return{value:e.value,rest:n.slice(e.end).trimStart()}}function Xu(n){return n.length>1&&(n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'"))?n.slice(1,-1):n}function Zu(n){return n instanceof Error?n.message:String(n)}function ec(n){let e=Ve(n),t,r=e;return e[0]==="--name"&&e[1]&&(t=e[1],r=e.slice(2)),{name:t,prompt:r.join(" ").trim()}}function xs(n){n.registerCommand({name:"agent",description:"Launch a coding agent session. Usage: /agent [--name <name>] <prompt>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=(e.args??"").trim();if(!t)return{text:"Usage: /agent [--name <name>] <prompt>"};let{name:r,prompt:o}=ec(t);if(!o)return{text:"Usage: /agent [--name <name>] <prompt>"};try{let i=Xt({prompt:o,name:r},e,k);if(i.kind!=="resolved")return{text:i.text};let s=k.spawn({prompt:o,name:r,workdir:i.workdir,model:i.resolvedModel,reasoningEffort:i.reasoningEffort,fastMode:i.fastMode,codexApprovalPolicy:i.harness==="codex"?"never":void 0,originChannel:i.originChannel,originThreadId:i.originThreadId,originAgentId:e.agentId||void 0,originSessionKey:i.originSessionKey,route:i.route,harness:i.harness,permissionMode:i.permissionMode,planApproval:i.planApproval,taskLifecycle:sn(e)});return{text:k.formatLaunchResult({prompt:o,workdir:i.workdir,harness:i.harness,permissionMode:i.permissionMode??_.permissionMode,planApproval:i.planApproval},s)}}catch(i){let s=Zu(i),a=s.includes("Max sessions")?"":`
|
|
87
87
|
|
|
88
88
|
Use /agent_sessions to see active sessions.`;return{text:`Error launching session: ${s}${a}`}}}})}function Cs(n){n.registerCommand({name:"agent_sessions",description:"List coding agent sessions. Usage: /agent_sessions [--full]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=(e.args??"").split(/\s+/).includes("--full");return{text:hn(k,"all",void 0,{full:t})}}})}function Ms(n){n.registerCommand({name:"agent_kill",description:"Kill a coding agent session by name or ID",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=e.args?.trim();return t?{text:yn(k,t,"killed")}:{text:"Usage: /agent_kill <name-or-id>"}}})}function _s(n){n.registerCommand({name:"agent_respond",description:"Send a follow-up message to a running coding agent session. Usage: /agent_respond <id-or-name> <message>",acceptsArgs:!0,requireAuth:!0,handler:async e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=(e.args??"").trim();if(!t)return{text:`Usage: /agent_respond <id-or-name> <message>
|
|
@@ -92,7 +92,7 @@ Use /agent_sessions to see active sessions.`;return{text:`Error launching sessio
|
|
|
92
92
|
`)};if(d.kind==="ambiguous")return{text:[l,"",`Repo policy saved, but ${d.count} pending launches match this policy. Run the intended launch again to avoid starting the wrong session.`].join(`
|
|
93
93
|
`)}}catch(d){let u=d instanceof Error?d.message:String(d);return{text:[l,"",`Repo policy saved, but the deferred launch failed: ${u}`,"The pending launch context was kept so you can retry the same /agent_policy command or run the intended launch again."].join(`
|
|
94
94
|
`)}}return{text:l}}let i=k.resolveRepoPolicy(o);if(!i.identity)return{text:`No git repository found for ${o}.`};let s=at(i.prAvailable).map(a=>a.policy).join(", ");return{text:[`Repo policy: ${i.policy??"unknown"}`,`Repo: ${i.identity.repoRoot}`,`Provider: ${i.provider}${i.prAvailable?"":" (PR automation unavailable)"}`,...i.identity.remoteUrl?[`Remote: ${i.identity.remoteUrl}`]:[],"",`Set with /agent_policy ${s}.`].join(`
|
|
95
|
-
`)}}})}var nc=50;function Es(n){n.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=(e.args??"").trim();if(!t)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=Ve(t),o="",i=!1,s=nc;for(let l=0;l<r.length;l++)if(r[l]==="--full")i=!0;else if(r[l]==="--lines"&&l+1<r.length){let d=parseInt(r[l+1],10);!isNaN(d)&&d>0&&(s=d),l++}else o||(o=r[l]);return o?{text:gn(k,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}var Ns="Usage: /agent_goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>";function Os(n){n.registerCommand({name:"agent_goal",description:"Launch an explicit goal task (Ralph-style completion loop or verifier-driven loop)",acceptsArgs:!0,requireAuth:!0,handler:async e=>{if(!$)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let t=(e.args??"").trim();if(!t)return{text:Ns};let r=Ve(t),o,i,s,a,l="bypassPermissions",d,u,f,g=[],S=[];for(let h=0;h<r.length;h++){let v=r[h];if(v==="--name"&&h+1<r.length)o=r[++h];else if(v==="--workdir"&&h+1<r.length)i=r[++h];else if(v==="--model"&&h+1<r.length)s=r[++h];else if(v==="--max-iterations"&&h+1<r.length){let
|
|
95
|
+
`)}}})}var nc=50;function Es(n){n.registerCommand({name:"agent_output",description:"Show recent output from a coding agent session. Usage: /agent_output <id-or-name> [--full] [--lines N]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!k)return{text:"Error: SessionManager not initialized. The code-agent service must be running."};let t=(e.args??"").trim();if(!t)return{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"};let r=Ve(t),o="",i=!1,s=nc;for(let l=0;l<r.length;l++)if(r[l]==="--full")i=!0;else if(r[l]==="--lines"&&l+1<r.length){let d=parseInt(r[l+1],10);!isNaN(d)&&d>0&&(s=d),l++}else o||(o=r[l]);return o?{text:gn(k,o,{full:i,lines:s})}:{text:"Usage: /agent_output <id-or-name> [--full] [--lines N]"}}})}var Ns="Usage: /agent_goal [--name <name>] [--workdir <dir>] [--model <model>] [--harness <name>] [--mode <ralph|verifier>] [--completion-promise <text>] [--max-iterations N] [--verify <cmd> ...] <goal>";function Os(n){n.registerCommand({name:"agent_goal",description:"Launch an explicit goal task (Ralph-style completion loop or verifier-driven loop)",acceptsArgs:!0,requireAuth:!0,handler:async e=>{if(!$)return{text:"Error: GoalController not initialized. The code-agent service must be running."};let t=(e.args??"").trim();if(!t)return{text:Ns};let r=Ve(t),o,i,s,a,l="bypassPermissions",d,u,f,g=[],S=[];for(let h=0;h<r.length;h++){let v=r[h];if(v==="--name"&&h+1<r.length)o=r[++h];else if(v==="--workdir"&&h+1<r.length)i=r[++h];else if(v==="--model"&&h+1<r.length)s=r[++h];else if(v==="--max-iterations"&&h+1<r.length){let b=parseInt(r[++h],10);!Number.isNaN(b)&&b>0&&(a=b)}else if(v==="--permission-mode"&&h+1<r.length){let b=r[++h];if(b==="default"||b==="plan"||b==="bypassPermissions")l=b;else return{text:`Error: Invalid permission mode "${b}".`}}else if(v==="--harness"&&h+1<r.length)d=r[++h];else if(v==="--mode"&&h+1<r.length){let b=r[++h];if(b==="ralph"||b==="verifier")u=b;else return{text:`Error: Invalid goal mode "${b}". Use ralph or verifier.`}}else if(v==="--completion-promise"&&h+1<r.length)f=r[++h];else if(v==="--verify"&&h+1<r.length){let b=r[++h].trim();if(!b)return{text:"Error: --verify commands must not be empty."};g.push(b)}else S.push(v)}let y=S.join(" ").trim();if(!y)return{text:Ns};let c=bn({goal:y,verifierCommands:g,name:o,workdir:i,model:s,maxIterations:a,permissionMode:l,harness:d,goalMode:u,completionPromise:f},e);if(c.kind!=="resolved")return{text:c.text};try{let h=await $.launchTask({goal:c.goal,name:c.name,workdir:c.workdir,model:c.model,reasoningEffort:c.reasoningEffort,fastMode:c.fastMode,maxIterations:c.maxIterations,permissionMode:c.permissionMode,harness:c.harness,loopMode:c.loopMode,completionPromise:c.completionPromise,originChannel:c.originChannel,originThreadId:c.originThreadId,originAgentId:c.originAgentId,originSessionKey:c.originSessionKey,route:c.route,verifierCommands:c.verifierCommands});return{text:Rn(h,c)}}catch(h){return{text:`Error launching goal task: ${h instanceof Error?h.message:String(h)}`}}}})}function Ws(n){n.registerCommand({name:"agent_goal_status",description:"Show one goal task or list all explicit goal tasks. Usage: /agent_goal_status [<task-id-or-name>]",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!$)return{text:X};let t=(e.args??"").trim();return{text:In($,r=>k?.resolve(r),t)}}})}function Fs(n){n.registerCommand({name:"agent_goal_stop",description:"Stop a goal task. Usage: /agent_goal_stop <task-id-or-name>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!$)return{text:X};let t=(e.args??"").trim();if(!t)return{text:"Usage: /agent_goal_stop <task-id-or-name>"};let r=$.stopTask(t);return{text:Tn(r,t)}}})}var Ls="Usage: /agent_goal_edit <task-id-or-name> <replacement-goal>";function Bs(n){n.registerCommand({name:"agent_goal_edit",description:"Edit a running goal task. Usage: /agent_goal_edit <task-id-or-name> <replacement-goal>",acceptsArgs:!0,requireAuth:!0,handler:e=>{if(!$)return{text:X};let t=(e.args??"").trim();if(!t)return{text:Ls};let r=Re(t),o=r?.value.trim(),i=r?.rest.trim();if(!o||!i)return{text:Ls};let s=$.editTask(o,i);return{text:xn(s,o)}}})}import{execFile as hc}from"child_process";import{createHash as ta}from"crypto";import{existsSync as pt,mkdirSync as rc,readFileSync as oc,renameSync as Vs,writeFileSync as ic}from"fs";import{homedir as sc}from"os";import{dirname as ac,join as Us}from"path";var lc=new Set(["running","waiting_for_session","waiting_for_user","succeeded","failed","stopped"]);function dc(n){let e=n.OPENCLAW_HOME?.trim();return e||Us(sc(),".openclaw")}function uc(n){let e=n.OPENCLAW_CODE_AGENT_GOAL_TASKS_PATH?.trim();return e||Us(dc(n),"code-agent-goal-tasks.json")}function Gs(n){return n instanceof Error?n.message:String(n)}function js(n){return!!n&&typeof n=="object"&&!Array.isArray(n)}var cc=100;function Ks(n,e,t){let r=t==null?"":`-${t}`;return`${n}.invalid-${e}${r}.json`}function pc(n){if(!pt(n))return;let e=Date.now(),t=Ks(n,e);if(!pt(t))return t;for(let r=1;r<=cc;r+=1){let o=Ks(n,e,r);if(!pt(o))return o}}function qs(n,e){try{let t=pc(n);return t?(Vs(n,t),`${e}${t}`,!0):(pt(n),!1)}catch(t){return`${Gs(t)}`,!1}}function mc(n){if(!js(n))return;let e=n;if(!(typeof e.provider!="string"||typeof e.target!="string"))return{provider:e.provider,target:e.target,accountId:typeof e.accountId=="string"?e.accountId:void 0,threadId:typeof e.threadId=="string"?e.threadId:void 0,sessionKey:typeof e.sessionKey=="string"?e.sessionKey:void 0}}function fc(n){if(!js(n))return;let e=n;if(typeof e.id!="string"||typeof e.name!="string"||typeof e.goal!="string"||typeof e.workdir!="string"||typeof e.status!="string"||!lc.has(e.status))return;let t=e.status,r=t==="running"||t==="waiting_for_session"?"waiting_for_session":t;return{id:e.id,name:e.name,goal:e.goal,workdir:e.workdir,status:r,createdAt:typeof e.createdAt=="number"?e.createdAt:Date.now(),updatedAt:typeof e.updatedAt=="number"?e.updatedAt:Date.now(),iteration:typeof e.iteration=="number"?e.iteration:0,maxIterations:typeof e.maxIterations=="number"?e.maxIterations:8,sessionId:typeof e.sessionId=="string"?e.sessionId:void 0,sessionName:typeof e.sessionName=="string"?e.sessionName:void 0,harnessSessionId:typeof e.harnessSessionId=="string"?e.harnessSessionId:void 0,model:typeof e.model=="string"?e.model:void 0,reasoningEffort:typeof e.reasoningEffort=="string"?e.reasoningEffort:void 0,fastMode:e.fastMode===!0?!0:void 0,systemPrompt:typeof e.systemPrompt=="string"?e.systemPrompt:void 0,allowedTools:Array.isArray(e.allowedTools)?e.allowedTools.filter(o=>typeof o=="string"):void 0,originChannel:typeof e.originChannel=="string"?e.originChannel:void 0,originThreadId:typeof e.originThreadId=="string"||typeof e.originThreadId=="number"?e.originThreadId:void 0,originAgentId:typeof e.originAgentId=="string"?e.originAgentId:void 0,originSessionKey:typeof e.originSessionKey=="string"?e.originSessionKey:void 0,route:mc(e.route),harness:typeof e.harness=="string"?e.harness:void 0,permissionMode:typeof e.permissionMode=="string"?e.permissionMode:void 0,loopMode:e.loopMode==="ralph"?"ralph":"verifier",completionPromise:typeof e.completionPromise=="string"?e.completionPromise:void 0,verifierCommands:Array.isArray(e.verifierCommands)?e.verifierCommands.filter(o=>!!o&&typeof o=="object"&&typeof o.label=="string"&&typeof o.command=="string"):[],lastVerifierSummary:typeof e.lastVerifierSummary=="string"?e.lastVerifierSummary:void 0,lastVerifierFingerprint:typeof e.lastVerifierFingerprint=="string"?e.lastVerifierFingerprint:void 0,repeatedFailureCount:typeof e.repeatedFailureCount=="number"?e.repeatedFailureCount:0,waitingForUserReason:typeof e.waitingForUserReason=="string"?e.waitingForUserReason:void 0,failureReason:typeof e.failureReason=="string"?e.failureReason:void 0}}function gc(n){if(!Array.isArray(n))return;let e=[];for(let t of n){let r=fc(t);if(!r)return;e.push(r)}return e}var En=class{path;tasks=new Map;constructor(e=process.env){this.path=uc(e),this.load()}load(){try{if(!pt(this.path))return;let e=oc(this.path,"utf8"),t=JSON.parse(e),r=gc(t);if(!r){qs(this.path,"invalid")&&this.save();return}this.tasks.clear();for(let o of r)this.tasks.set(o.id,o);this.save()}catch(e){if(e.code==="ENOENT")return;qs(this.path,"corrupt or unreadable")&&this.save()}}save(){try{rc(ac(this.path),{recursive:!0});let e=`${this.path}.tmp`;ic(e,JSON.stringify([...this.tasks.values()],null,2),"utf8"),Vs(e,this.path)}catch(e){`${this.path}${Gs(e)}`}}upsert(e){this.tasks.set(e.id,e),this.save()}get(e){let t=this.tasks.get(e);return t||[...this.tasks.values()].find(r=>r.name===e)}list(){return[...this.tasks.values()].sort((e,t)=>t.createdAt-e.createdAt)}};var yc=8,na=600*1e3,Sc=4e3,mo=1200,kc="DONE",vc=["BASH_ENV","ENV"];function Pc(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"goal-task"}function Ue(n,e){return n.length<=e?n:`${n.slice(0,e-3)}...`}function he(n,e=20){let t=n.split(/\r?\n/).map(r=>r.trimEnd()).filter(r=>r.trim().length>0);return t.length<=e?t.join(`
|
|
96
96
|
`):t.slice(-e).join(`
|
|
97
97
|
`)}function wc(n){let e=(n??"").split(/\r?\n/).map(t=>t.trim()).filter(t=>t.length>0).filter(t=>!/^Iteration summary:$/i.test(t)).map(t=>t.replace(/^[-*]\s+/,""));return e.length>0?e.join(`
|
|
98
98
|
`):void 0}function zs(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hs(n){let e=n?.trim();return e&&e.length>0?e:kc}function bc(n){return n.route??ue(n.originChannel,n.originThreadId,n.originSessionKey)}function fo(n){return n.map((e,t)=>({label:e.label.trim()||`check-${t+1}`,command:e.command.trim(),timeoutMs:e.timeoutMs??na})).filter(e=>e.command.length>0)}function Rc(n){return n.loopMode==="verifier"}function Ac(n){return fo(n.verifierCommands).length>0}function Qs(n){return Rc(n)&&!Ac(n)}function Nn(){return"Verifier-mode goal tasks require at least one verifier command."}function Ys(n){let e=n.steps.filter(t=>!t.ok).map(t=>`${t.label}:${t.exitCode}:${he(t.output,12)}`).join(`
|
|
@@ -137,7 +137,7 @@ ${e.failureReason}`,"goal-task-stopped")}async handleRunningSession(e,t){if(t.pe
|
|
|
137
137
|
`));return}e.iteration+=1;let S=Mc(e,g),y=An({output:s,verifierSummary:g.summary,completionPromise:a,completionDetected:!0});try{let c=await this.resumeTaskSession(e,S,t);this.setTaskRunningWithSession(e,c),this.notifyIterationStatus(e,`π [${e.name}] Completion claimed but verifiers still failed`,void 0,y),this.scheduleTaskEvaluation(e.id,"ralph-verifier-resume",c.id)}catch(c){this.markTaskFailed(e,`Failed to resume the Ralph goal task after verifier failure: ${Ae(c)}`)}return}let d=Ic(s);if(e.lastVerifierFingerprint===d?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=d,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Completion promise "${a}" was not emitted before hitting the iteration budget (${e.maxIterations}).`,"Latest output:",he(s,20)||"(no output)"].join(`
|
|
138
138
|
`));return}e.iteration+=1;let u=Cc(e,s),f=An({output:s,completionPromise:a,completionDetected:!1});try{let g=await this.resumeTaskSession(e,u,t);this.setTaskRunningWithSession(e,g),this.notifyIterationStatus(e,`π [${e.name}] Continued`,void 0,f),this.scheduleTaskEvaluation(e.id,"ralph-continue",g.id)}catch(g){this.markTaskFailed(e,`Failed to continue the Ralph goal task: ${Ae(g)}`)}return}let r=await this.runVerifiers(e);if(e.lastVerifierSummary=r.summary,e.updatedAt=Date.now(),r.status==="pass"){this.markTaskSucceeded(e,r.summary);return}if(e.lastVerifierFingerprint===r.fingerprint?e.repeatedFailureCount+=1:e.repeatedFailureCount=1,e.lastVerifierFingerprint=r.fingerprint,e.iteration+1>=e.maxIterations){this.markTaskFailed(e,[`Verifier did not pass before hitting the iteration budget (${e.maxIterations}).`,r.summary].join(`
|
|
139
139
|
`));return}e.iteration+=1;let o=xc(e,r),i=An({verifierSummary:r.summary});try{let s=await this.resumeTaskSession(e,o,t);this.setTaskRunningWithSession(e,s),this.notifyIterationStatus(e,`π [${e.name}] Repair iteration started after verifier failure`,void 0,i),this.scheduleTaskEvaluation(e.id,"repair-resume",s.id)}catch(s){this.markTaskFailed(e,`Failed to resume the goal task: ${Ae(s)}`)}}async evaluateTask(e,t,r){this.restorePromise&&await this.restorePromise;let o=this.store.get(e);o&&await this.reconcileTask(o,t,r)}async reconcileTask(e,t="manual",r){if(!(e.status==="succeeded"||e.status==="failed"||e.status==="stopped")){if(this.inFlight.has(e.id)){this.dirtyEvaluations.add(e.id),!this.dirtyEvaluationSessionIds.get(e.id)&&r?this.dirtyEvaluationSessionIds.set(e.id,r):this.dirtyEvaluationSessionIds.has(e.id)||this.dirtyEvaluationSessionIds.set(e.id,r);return}this.inFlight.add(e.id);try{if(r&&e.sessionId&&e.sessionId!==r){let i=this.sessionManager.resolve(r);if(i&&(i.status==="completed"||i.status==="failed"||i.status==="killed"))return}let o=r?this.sessionManager.resolve(r)??(e.sessionId?this.sessionManager.resolve(e.sessionId):void 0):e.sessionId?this.sessionManager.resolve(e.sessionId):void 0;if(e.status==="waiting_for_user"){this.markTaskFailed(e,"Goal task was waiting for user input and cannot continue autonomously");return}if(Qs(e)){this.markTaskFailed(e,Nn());return}if(!o){this.markTaskFailed(e,"Underlying session could not be found.");return}if(e.sessionName=o.name,e.harnessSessionId=o.harnessSessionId,e.route=o.route??e.route,e.updatedAt=Date.now(),this.store.upsert(e),o.status==="starting"||o.status==="running"){await this.handleRunningSession(e,o);return}await this.handleTerminalSession(e,o)}finally{if(this.inFlight.delete(e.id),this.dirtyEvaluations.has(e.id)){this.dirtyEvaluations.delete(e.id);let o=this.dirtyEvaluationSessionIds.get(e.id);this.dirtyEvaluationSessionIds.delete(e.id),this.scheduleTaskEvaluation(e.id,`${t}:dirty`,o)}}}}};import{createHash as dl}from"crypto";import{existsSync as Nc,realpathSync as Oc}from"fs";import{resolve as Wc}from"path";function ra(n){if(!n)return;let e=Wc(n);try{if(Nc(e))return Oc.native(e)}catch{}return e}function Wn(n,e){return!n||!e?!1:ra(n)===ra(e)}import{existsSync as Fc}from"fs";function Lc(n){if(!(!n.provider||!n.target))return n.accountId?`${n.provider}|${n.accountId}|${n.target}`:`${n.provider}|${n.target}`}function Bc(n){return Ce(Z({route:n.route,originChannel:n.originChannel,originThreadId:n.originThreadId,originSessionKey:n.originSessionKey}))}function Kc(n,e){if(Bc(n))return;let t=[n.resumeSessionId,n.resumeWorktreeFrom].filter(r=>!!r?.trim());for(let r of t){let o=e(r);if(!o)continue;let i=Z({route:o.route,originChannel:o.originChannel,originThreadId:o.originThreadId,originSessionKey:o.originSessionKey});if(Ce(i)){n.route={...i},n.originChannel=o.originChannel??Lc(i),n.originThreadId=o.originThreadId??i.threadId,n.originSessionKey=o.originSessionKey??i.sessionKey,n.originAgentId??=o.originAgentId;return}}}function oa(n){return n instanceof Error?n.message:String(n)}function qc(n){let e=n.worktreeStrategy??_.defaultWorktreeStrategy;return!!e&&e!=="off"&&Yo(xt({harnessName:n.harness??Y(),backendRef:n.backendRef}))}function Vc(n,e,t,r){let o=["","You are working in a git worktree.",`Worktree path: ${t}`,`Branch: ${r}`,"",`IMPORTANT: ALL file edits must be made within this worktree at ${t}.`,`Do NOT edit files directly in ${e} (the original workspace).`,`If your task references files by absolute path under ${e}, rewrite those`,"paths relative to your current working directory. For example:",` "${e}/src/file.py" β use relative path "src/file.py"`,"","Before finishing, run `git status --short` in this worktree.","If you made actual task changes, commit all of them to this branch before finishing.","Use `git add` and `git commit`. If no repository changes are needed, leave the worktree clean before finishing.","Do NOT run `git checkout`, `git switch`, or `git reset --hard` as these will detach or corrupt the worktree HEAD.","","When making changes, please note:","- Do NOT commit planning documents, investigation notes, or analysis artifacts to this branch","- Only commit actual code, configuration, tests, and documentation changes that were explicitly requested as part of the task"].join(`
|
|
140
|
-
`);return(n??"")+o}function Uc(n,e){let t=n.resumeWorktreeFrom??n.resumeSessionId;if(!t)return{};let r=e(t);if(!r)return{};let o=!!r.harness||!!r.backendRef,i=(()=>{if(r.workdir&&r.workdir!==r.worktreePath)return r.workdir;if(r.worktreePath){let a=Ct(r.worktreePath);return r.workdir&&a&&Wn(r.workdir,a)?r.workdir:a??r.workdir}return r.workdir})();if(n.worktreeStrategy||(r.worktreeLifecycle?.state==="pr_open"||r.worktreePrUrl?n.worktreeStrategy="auto-pr":r.worktreeStrategy&&(n.worktreeStrategy=r.worktreeStrategy)),!n.planApproval&&r.planApproval&&(n.planApproval=r.planApproval),!r.worktreePath){let a=o&&Ir(xt({persistedHarness:r.harness,backendRef:r.backendRef}));return{originalWorkdir:i,canCreateManagedWorktreeForResumeWithoutPersistedPath:a}}if(!r.worktreeBranch)throw new Error(`Cannot resume session "${t}": persisted worktree metadata is missing worktreeBranch.`);let s=Ir(xt({persistedHarness:r.harness,backendRef:r.backendRef}))&&!!r.backendRef?.worktreePath;if(Fc(r.worktreePath))return`${r.worktreePath}`,{actualWorkdir:r.worktreePath,originalWorkdir:i??r.worktreePath,worktreePath:r.worktreePath,worktreeBranchName:r.worktreeBranch,worktreeParentBranch:r.worktreeParentBranch};if(!i)return`${r.worktreePath}`,{clearedResumeSessionId:!!n.resumeSessionId,clearedResumeWorktreeFrom:!!n.resumeWorktreeFrom};if(s)return`${r.worktreePath}`,{actualWorkdir:i,originalWorkdir:i,worktreeBranchName:r.worktreeBranch,worktreeParentBranch:r.worktreeParentBranch,clearedResumeWorktreeFrom:!!n.resumeWorktreeFrom,restoredMissingNativeBackendWorktree:!0};try{Dt(i);let a=xr(i,r.worktreeBranch.replace(/^agent\//,""),{allowExistingBranch:!0});return`${r.worktreeBranch}${a}`,{actualWorkdir:a,originalWorkdir:i,worktreePath:a,worktreeBranchName:r.worktreeBranch,worktreeParentBranch:r.worktreeParentBranch}}catch(a){return`${oa(a)}`,{actualWorkdir:i,originalWorkdir:i,clearedResumeSessionId:!!n.resumeSessionId,clearedResumeWorktreeFrom:!!n.resumeWorktreeFrom,failedResumeWorktreeRestore:!0}}}function ia(n,e,t){Kc(n,t);let{actualWorkdir:r,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,worktreeParentBranch:a,clearedResumeSessionId:l,clearedResumeWorktreeFrom:d,restoredMissingNativeBackendWorktree:u,canCreateManagedWorktreeForResumeWithoutPersistedPath:f,failedResumeWorktreeRestore:g}=Uc(n,t);l&&(n.resumeSessionId=void 0),d&&(n.resumeWorktreeFrom=void 0),r??=n.workdir,o??=n.workdir;let S=!!(n.resumeSessionId??n.resumeWorktreeFrom),y=n.worktreeStrategy??_.defaultWorktreeStrategy;y&&(n.worktreeStrategy=y),!S&&y&&y!=="off"&&Mt(o)&&(a??=oe(o));let c=qc(n),v=(!S||!!f)&&!u&&!i&&y&&y!=="off"&&!c;if(g&&y&&y!=="off")throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" was requested, but no isolated worktree was prepared. Launch with worktree_strategy "off" only when running in the base checkout is intentional.`);if(c&&!Mt(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" requires a git worktree, but "${o}" is not a git repository.`);if(v&&Mt(o)){if(!Jo(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=xr(o,e),r=i,s=oe(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);`${i}`}catch(R){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${oa(R)}`)}}else if(v)throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" requires a git worktree, but "${o}" is not a git repository.`);if(S&&i&&(r=i),y&&y!=="off"&&!i)throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" was requested, but no isolated worktree was prepared. Launch with worktree_strategy "off" only when running in the base checkout is intentional.`);return{actualWorkdir:r,originalWorkdir:o,effectiveSystemPrompt:i&&s?Vc(n.systemPrompt,o,i,s):n.systemPrompt,worktreePath:i,worktreeBranchName:s,worktreeParentBranch:a,clearedResumeSessionId:l,clearedResumeWorktreeFrom:d,restoredMissingNativeBackendWorktree:u,failedResumeWorktreeRestore:g}}var Fn=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,t){return ia(e,t,this.getPersistedSession)}hydrateSpawnedSession(e,t,r){r.worktreeStrategy&&r.worktreeStrategy!=="off"&&(e.originalWorkdir=t.originalWorkdir),e.worktreeParentBranch=t.worktreeParentBranch,t.worktreePath&&(e.worktreePath=t.worktreePath,e.worktreeBranch=t.worktreeBranchName,e.worktreeState="provisioned"),r.worktreePrTargetRepo&&(e.worktreePrTargetRepo=r.worktreePrTargetRepo)}};var Ln=class{constructor(e){this.deps=e}deps;applySessionPatch(e,t){let r=this.normalizeCompletionWakePatch(t),o=this.deps.store.getPersistedSession(e);o&&(Object.assign(o,r),this.deps.store.assertPersistedEntry(o));let i=this.findActiveSessionForRef(e,o);return i&&this.applyPatchToActiveSession(i,r),!o&&!i?!1:(o&&this.deps.store.saveIndex(),!0)}normalizeCompletionWakePatch(e){return"completionWakeSucceededAt"in e&&e.completionWakeSucceededAt||"completionWakeSkippedAt"in e&&e.completionWakeSkippedAt?{...e,completionWakeSummaryRequired:void 0}:e}matchesExistingSession(e,t){if(!t)return!1;let r=C(e),o=C(t);return!!(t.sessionId&&e.id===t.sessionId||o&&o===r||t?.harnessSessionId&&e.harnessSessionId===t.harnessSessionId||t?.name&&e.name===t.name)}findActiveSessionForRef(e,t){let r=this.deps.resolveSession(e);if(r)return r;for(let o of this.deps.sessions.values())if(D(o)===e||C(o)===e||o.harnessSessionId===e||this.matchesExistingSession(o,t))return o}applyPatchToActiveSession(e,t){this.applyControlStatePatch(e,t),this.applySessionMetadataPatch(e,t),this.applyWorktreeMetadataPatch(e,t)}applyControlStatePatch(e,t){let r={};if(this.copyControlPatchField(r,t,"lifecycle"),this.copyControlPatchField(r,t,"approvalState"),this.copyControlPatchField(r,t,"approvalExecutionState"),this.copyControlPatchField(r,t,"worktreeState"),this.copyControlPatchField(r,t,"runtimeState"),this.copyControlPatchField(r,t,"deliveryState"),this.copyControlPatchField(r,t,"requestedPermissionMode"),this.copyControlPatchField(r,t,"currentPermissionMode"),this.copyControlPatchField(r,t,"pendingPlanApproval"),this.copyControlPatchField(r,t,"planApprovalContext"),this.copyControlPatchField(r,t,"planDecisionVersion"),this.copyControlPatchField(r,t,"actionablePlanDecisionVersion"),this.copyControlPatchField(r,t,"canonicalPlanPromptVersion"),this.copyControlPatchField(r,t,"approvalPromptRequiredVersion"),this.copyControlPatchField(r,t,"approvalPromptVersion"),this.copyControlPatchField(r,t,"approvalPromptStatus"),this.copyControlPatchField(r,t,"approvalPromptTransport"),this.copyControlPatchField(r,t,"approvalPromptMessageKind"),this.copyControlPatchField(r,t,"approvalPromptLastAttemptAt"),this.copyControlPatchField(r,t,"approvalPromptDeliveredAt"),this.copyControlPatchField(r,t,"approvalPromptFailedAt"),this.copyControlPatchField(r,t,"planModeApproved"),this.copyControlPatchField(r,t,"pendingWorktreeDecisionSince"),typeof e.applyControlPatch=="function"){e.applyControlPatch(r);return}this.assignIfPresent(e,"lifecycle",t,"lifecycle"),this.assignIfPresent(e,"approvalState",t,"approvalState"),this.assignIfPresent(e,"approvalExecutionState",t,"approvalExecutionState"),this.assignIfPresent(e,"worktreeState",t,"worktreeState"),this.assignIfPresent(e,"runtimeState",t,"runtimeState"),this.assignIfPresent(e,"deliveryState",t,"deliveryState"),this.assignIfPresent(e,"requestedPermissionMode",t,"requestedPermissionMode"),this.assignIfPresent(e,"currentPermissionMode",t,"currentPermissionMode"),this.assignIfPresent(e,"pendingPlanApproval",t,"pendingPlanApproval"),this.assignIfPresent(e,"planApprovalContext",t,"planApprovalContext"),this.assignIfPresent(e,"planDecisionVersion",t,"planDecisionVersion"),this.assignIfPresent(e,"actionablePlanDecisionVersion",t,"actionablePlanDecisionVersion"),this.assignIfPresent(e,"canonicalPlanPromptVersion",t,"canonicalPlanPromptVersion"),this.assignIfPresent(e,"approvalPromptRequiredVersion",t,"approvalPromptRequiredVersion"),this.assignIfPresent(e,"approvalPromptVersion",t,"approvalPromptVersion"),this.assignIfPresent(e,"approvalPromptStatus",t,"approvalPromptStatus"),this.assignIfPresent(e,"approvalPromptTransport",t,"approvalPromptTransport"),this.assignIfPresent(e,"approvalPromptMessageKind",t,"approvalPromptMessageKind"),this.assignIfPresent(e,"approvalPromptLastAttemptAt",t,"approvalPromptLastAttemptAt"),this.assignIfPresent(e,"approvalPromptDeliveredAt",t,"approvalPromptDeliveredAt"),this.assignIfPresent(e,"approvalPromptFailedAt",t,"approvalPromptFailedAt"),this.setControlFieldIfPresent(e,"planModeApproved",t)}applySessionMetadataPatch(e,t){this.assignIfDefined(e,"approvalRationale",t.approvalRationale),this.assignIfDefined(e,"taskFlowMirror",t.taskFlowMirror)}applyWorktreeMetadataPatch(e,t){this.assignIfDefined(e,"worktreePath",t.worktreePath),this.assignIfDefined(e,"worktreeBranch",t.worktreeBranch),this.assignIfDefined(e,"worktreePrUrl",t.worktreePrUrl),this.assignIfDefined(e,"worktreePrNumber",t.worktreePrNumber),this.assignIfDefined(e,"worktreeMerged",t.worktreeMerged),this.assignIfDefined(e,"worktreeMergedAt",t.worktreeMergedAt),this.assignIfDefined(e,"worktreeDisposition",t.worktreeDisposition),this.assignIfDefined(e,"worktreePrTargetRepo",t.worktreePrTargetRepo),this.assignIfDefined(e,"worktreePushRemote",t.worktreePushRemote),this.assignIfDefined(e,"worktreeLifecycle",t.worktreeLifecycle),"autoMergeParentSessionId"in t&&(e.autoMergeParentSessionId=t.autoMergeParentSessionId),"autoMergeConflictResolutionAttemptCount"in t&&(e.autoMergeConflictResolutionAttemptCount=t.autoMergeConflictResolutionAttemptCount),"autoMergeResolverSessionId"in t&&(e.autoMergeResolverSessionId=t.autoMergeResolverSessionId)}assignIfDefined(e,t,r){r!==void 0&&(e[t]=r)}assignIfPresent(e,t,r,o){Object.hasOwn(r,o)&&(e[t]=r[o])}copyControlPatchField(e,t,r){Object.hasOwn(t,r)&&(e[r]=t[r])}setControlFieldIfPresent(e,t,r){Object.hasOwn(r,t)&&e.setControlField?.(t,r[t])}};var Gc=new Set(["starting","running"]),Bn=class{constructor(e,t){this.sessions=e;this.store=t}sessions;store;resolveActive(e){let t=this.sessions.get(e);return t||(this.findPreferredMatch(e,r=>r.name===e)??this.findPreferredMatch(e,r=>C(r)===e)??this.findPreferredMatch(e,r=>r.harnessSessionId===e))}getPersistedSession(e){return this.store.getPersistedSession(e)}resolveBackendConversationId(e){let t=this.resolveActive(e);return this.store.resolveBackendConversationId(e,t?C(t)??t.harnessSessionId:void 0)}findPreferredMatch(e,t){let r,o;for(let i of this.sessions.values())t(i,e)&&((!o||i.startedAt>o.startedAt)&&(o=i),Gc.has(i.status)&&(!r||i.startedAt>r.startedAt)&&(r=i));return r??o}};import{existsSync as jc}from"fs";var sa=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]),Kn=class{constructor(e){this.deps=e}deps;async plan(e){let t=D(e)??e.harnessSessionId;if(this.deps.isAlreadyMerged(t))return`${e.name}`,{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};let r=sa.has(e.worktreeState)?e.worktreeState:e.worktreeLifecycle?.state&&sa.has(e.worktreeLifecycle.state)?e.worktreeLifecycle.state:void 0;if(r&&!(r==="pr_open"&&e.worktreeStrategy==="auto-pr"))return`${e.name}${e.worktreeLifecycle?.state??e.worktreeState}`,{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};if(e.status!=="completed")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};if(!this.deps.shouldRunWorktreeStrategy(e))return`${e.name}${e.phase}`,{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let o=e.worktreeStrategy;if(!o||o==="off"||o==="manual")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let i=e.worktreePath,s=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,i),a=e.worktreeBranch;if(!s)return{kind:"notify",label:"worktree-missing-repo-dir",message:`β οΈ [${e.name}] Cannot determine the original repo for worktree ${i}. Manual inspection is required.`};if(!a)return{kind:"notify",label:"worktree-no-branch-name",message:`β οΈ [${e.name}] Cannot determine branch name for worktree ${i}. The worktree may have been removed or is in detached HEAD state. Manual cleanup may be needed.`};let l=L(e);if(l&&!jc(i))return{kind:"no-change",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l};let d=e.worktreeBaseBranch??Ee(s),u=this.deps.getWorktreeCompletionState(s,i,a,d);if(u==="no-change")return{kind:"no-change",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l};if(u==="merged")return{kind:"merged",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l};if(u==="released")return{kind:"released",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l,reasons:["merge_noop_content_already_on_base"]};if(u==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`β οΈ [${e.name}] Auto-merge: branch '${a}' has no commits ahead of '${d}', but '${d}' has new commits β commits likely landed outside the worktree branch. Verify that commits were not made directly to '${d}' instead of the worktree branch. Worktree: ${i}`};if(u==="dirty-uncommitted")return{kind:"dirty-uncommitted",worktreePath:i,branchName:a,baseBranch:d};let f=Ne(s,a,d);if(!f)return`${a}`,{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let g=e.repoIntegrationPolicy?void 0:this.deps.resolveRepoPolicy?.(s),S=e.repoIntegrationPolicy??g?.policy,y=e.repoIntegrationPolicy?this.deps.isPrAvailable(s):g?.prAvailable??this.deps.isPrAvailable(s),c=cs({requestedStrategy:o,policy:S,prAvailable:y,existingOpenPr:!1});return c.strategy?{kind:"decision",strategy:c.strategy,policy:S,policyReason:c.reason,policyBlocked:c.blocked,allowedActions:c.allowedActions,repoDir:s,worktreePath:i,branchName:a,baseBranch:d,diffSummary:f,sessionRef:t??void 0}:{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}}}};function ye(n){let e=[];typeof n.costUsd=="number"&&Number.isFinite(n.costUsd)&&e.push(`$${n.costUsd.toFixed(2)}`);let t=zc(n);t!==void 0&&e.push(se(t));let r=ge({harness:n.harnessName??n.harness,model:n.model});return r&&e.push(...r.split(" | ")),e.length>0?` | ${e.join(" | ")}`:""}function zc(n){if(typeof n.duration=="number"&&Number.isFinite(n.duration)&&n.duration>=0)return n.duration;if(typeof n.createdAt=="number"&&Number.isFinite(n.createdAt)&&typeof n.completedAt=="number"&&Number.isFinite(n.completedAt)&&n.completedAt>=n.createdAt)return n.completedAt-n.createdAt}function Hc(n){if(n.requestedPermissionMode==="plan"){if(n.approvalExecutionState==="approved_then_implemented"){if(n.planApproval==="ask"&&n.approvalPromptStatus==="delivered"&&n.approvalPromptMessageKind==="canonical_buttons"&&n.approvalPromptDeliveredAt)return"Approval interpretation: canonical Approve/Revise/Reject buttons were delivered, and implementation after approval was expected.";if(n.approvalState==="approved")return"Approval interpretation: explicit plan approval was recorded before implementation, so leaving plan-only mode was expected."}if(n.approvalExecutionState==="implemented_without_required_approval")return"Approval interpretation: implementation left plan-only mode without a recorded approval."}}function Qc(){return/https?:\/\/github\.com\/[^\s)]+\/[^\s)]+\/pull\/(\d+)(?=[\s).,;:]|$)/gi}function Yc(){return/https?:\/\/\S+/gi}function qn(n){let e=Hc(n);return[`Requested permission mode: ${n.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${n.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${n.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function go(n){switch(n){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}function Jc(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function Xc(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToWorktreeTerminalOutcomes:!0}}function Zc(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToGoalTaskCompletions:!0}}function ho(n){let{sessionId:e,canonicalStatusDetail:t,canonicalStatusDelivered:r=!0,hasOriginRouteBlock:o=!1}=n,i=o?["7. Before sending that follow-up, honor the Session origin route block above. If originRoute differs from the current chat, do NOT use a plain final assistant reply; use a routed send path that preserves provider/target/threadId."]:[],s=o?8:7,a=o?9:8;return["[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${e}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW β do not wait for user input.",`3. ${t??(r?"The plugin already sent the canonical completion status to the user.":"The plugin did not confirm delivery of the canonical completion status to the user.")}`,"4. Treat the completed session output as source material, not visible delivery. A meaningful final summary inside agent_output is not enough to skip, because the user may only have seen the plugin's terse status line.","5. If the visible result is only the plugin's terse status line, use the full output to send the user one short factual completion summary for this completed session. Do this even when agent_output already contains a good final summary.","6. This requirement applies to ordinary terminal/manual completions too, not just delegated worktree decisions.",...i,`${s}. That follow-up belongs to you alone; keep it brief, concrete, and grounded in reliable result data. Send at most one orchestrator-owned human summary for this terminal/worktree outcome.`,...r?[`${a}. Do NOT repeat the plugin's status line, and do NOT rely on the plugin to summarize the completed work for you.`]:[`${a}. Because canonical status delivery was not confirmed, account for that gap yourself when you follow up; do NOT assume the plugin already reached the user.`],`${a+1}. Send a normal concise final response after any routed follow-up is visibly sent. Do not use marker text, do not answer NO_REPLY, and do not ask the user whether they want the summary.`]}function ep(n){let{contract:e,canonicalStatusDelivered:t}=n;return["Completion diagnostics:",`- Canonical completion status delivered to user: ${t?"yes":"no"}`,`- Plugin requested short factual follow-up summary: ${e.requiresShortFactualSummary?"yes":"no"}`,`- Contract applies to ordinary terminal/manual completions: ${e.appliesToOrdinaryTerminalCompletions?"yes":"no"}`]}function yo(n){let{session:e,originThreadLine:t,preview:r}=n,o=!!t.trim(),i=Jc(),s=a=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,...o?[t]:[],...qn(e),"","Output preview:",r,"",...ep({contract:i,canonicalStatusDelivered:a}),"",...ho({sessionId:e.id,canonicalStatusDelivered:a,hasOriginRouteBlock:o})].join(`
|
|
140
|
+
`);return(n??"")+o}function Uc(n,e){let t=n.resumeWorktreeFrom??n.resumeSessionId;if(!t)return{};let r=e(t);if(!r)return{};let o=!!r.harness||!!r.backendRef,i=(()=>{if(r.workdir&&r.workdir!==r.worktreePath)return r.workdir;if(r.worktreePath){let a=Ct(r.worktreePath);return r.workdir&&a&&Wn(r.workdir,a)?r.workdir:a??r.workdir}return r.workdir})();if(n.worktreeStrategy||(r.worktreeLifecycle?.state==="pr_open"||r.worktreePrUrl?n.worktreeStrategy="auto-pr":r.worktreeStrategy&&(n.worktreeStrategy=r.worktreeStrategy)),!n.planApproval&&r.planApproval&&(n.planApproval=r.planApproval),!r.worktreePath){let a=o&&Ir(xt({persistedHarness:r.harness,backendRef:r.backendRef}));return{originalWorkdir:i,canCreateManagedWorktreeForResumeWithoutPersistedPath:a}}if(!r.worktreeBranch)throw new Error(`Cannot resume session "${t}": persisted worktree metadata is missing worktreeBranch.`);let s=Ir(xt({persistedHarness:r.harness,backendRef:r.backendRef}))&&!!r.backendRef?.worktreePath;if(Fc(r.worktreePath))return`${r.worktreePath}`,{actualWorkdir:r.worktreePath,originalWorkdir:i??r.worktreePath,worktreePath:r.worktreePath,worktreeBranchName:r.worktreeBranch,worktreeParentBranch:r.worktreeParentBranch};if(!i)return`${r.worktreePath}`,{clearedResumeSessionId:!!n.resumeSessionId,clearedResumeWorktreeFrom:!!n.resumeWorktreeFrom};if(s)return`${r.worktreePath}`,{actualWorkdir:i,originalWorkdir:i,worktreeBranchName:r.worktreeBranch,worktreeParentBranch:r.worktreeParentBranch,clearedResumeWorktreeFrom:!!n.resumeWorktreeFrom,restoredMissingNativeBackendWorktree:!0};try{Dt(i);let a=xr(i,r.worktreeBranch.replace(/^agent\//,""),{allowExistingBranch:!0});return`${r.worktreeBranch}${a}`,{actualWorkdir:a,originalWorkdir:i,worktreePath:a,worktreeBranchName:r.worktreeBranch,worktreeParentBranch:r.worktreeParentBranch}}catch(a){return`${oa(a)}`,{actualWorkdir:i,originalWorkdir:i,clearedResumeSessionId:!!n.resumeSessionId,clearedResumeWorktreeFrom:!!n.resumeWorktreeFrom,failedResumeWorktreeRestore:!0}}}function ia(n,e,t){Kc(n,t);let{actualWorkdir:r,originalWorkdir:o,worktreePath:i,worktreeBranchName:s,worktreeParentBranch:a,clearedResumeSessionId:l,clearedResumeWorktreeFrom:d,restoredMissingNativeBackendWorktree:u,canCreateManagedWorktreeForResumeWithoutPersistedPath:f,failedResumeWorktreeRestore:g}=Uc(n,t);l&&(n.resumeSessionId=void 0),d&&(n.resumeWorktreeFrom=void 0),r??=n.workdir,o??=n.workdir;let S=!!(n.resumeSessionId??n.resumeWorktreeFrom),y=n.worktreeStrategy??_.defaultWorktreeStrategy;y&&(n.worktreeStrategy=y),!S&&y&&y!=="off"&&Mt(o)&&(a??=oe(o));let c=qc(n),v=(!S||!!f)&&!u&&!i&&y&&y!=="off"&&!c;if(g&&y&&y!=="off")throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" was requested, but no isolated worktree was prepared. Launch with worktree_strategy "off" only when running in the base checkout is intentional.`);if(c&&!Mt(o))throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" requires a git worktree, but "${o}" is not a git repository.`);if(v&&Mt(o)){if(!Jo(o))throw new Error(`Cannot launch session "${e}": insufficient space for worktree creation.`);try{if(i=xr(o,e),r=i,s=oe(i),!s)throw new Error(`created worktree at ${i} but failed to resolve branch name`);`${i}`}catch(b){throw new Error(`Cannot launch session "${e}": worktree creation failed: ${oa(b)}`)}}else if(v)throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" requires a git worktree, but "${o}" is not a git repository.`);if(S&&i&&(r=i),y&&y!=="off"&&!i)throw new Error(`Cannot launch session "${e}": worktree strategy "${y}" was requested, but no isolated worktree was prepared. Launch with worktree_strategy "off" only when running in the base checkout is intentional.`);return{actualWorkdir:r,originalWorkdir:o,effectiveSystemPrompt:i&&s?Vc(n.systemPrompt,o,i,s):n.systemPrompt,worktreePath:i,worktreeBranchName:s,worktreeParentBranch:a,clearedResumeSessionId:l,clearedResumeWorktreeFrom:d,restoredMissingNativeBackendWorktree:u,failedResumeWorktreeRestore:g}}var Fn=class{constructor(e){this.getPersistedSession=e}getPersistedSession;prepareSpawn(e,t){return ia(e,t,this.getPersistedSession)}hydrateSpawnedSession(e,t,r){r.worktreeStrategy&&r.worktreeStrategy!=="off"&&(e.originalWorkdir=t.originalWorkdir),e.worktreeParentBranch=t.worktreeParentBranch,t.worktreePath&&(e.worktreePath=t.worktreePath,e.worktreeBranch=t.worktreeBranchName,e.worktreeState="provisioned"),r.worktreePrTargetRepo&&(e.worktreePrTargetRepo=r.worktreePrTargetRepo)}};var Ln=class{constructor(e){this.deps=e}deps;applySessionPatch(e,t){let r=this.normalizeCompletionWakePatch(t),o=this.deps.store.getPersistedSession(e);o&&(Object.assign(o,r),this.deps.store.assertPersistedEntry(o));let i=this.findActiveSessionForRef(e,o);return i&&this.applyPatchToActiveSession(i,r),!o&&!i?!1:(o&&this.deps.store.saveIndex(),!0)}normalizeCompletionWakePatch(e){return"completionWakeSucceededAt"in e&&e.completionWakeSucceededAt||"completionWakeSkippedAt"in e&&e.completionWakeSkippedAt?{...e,completionWakeSummaryRequired:void 0}:e}matchesExistingSession(e,t){if(!t)return!1;let r=C(e),o=C(t);return!!(t.sessionId&&e.id===t.sessionId||o&&o===r||t?.harnessSessionId&&e.harnessSessionId===t.harnessSessionId||t?.name&&e.name===t.name)}findActiveSessionForRef(e,t){let r=this.deps.resolveSession(e);if(r)return r;for(let o of this.deps.sessions.values())if(D(o)===e||C(o)===e||o.harnessSessionId===e||this.matchesExistingSession(o,t))return o}applyPatchToActiveSession(e,t){this.applyControlStatePatch(e,t),this.applySessionMetadataPatch(e,t),this.applyWorktreeMetadataPatch(e,t)}applyControlStatePatch(e,t){let r={};if(this.copyControlPatchField(r,t,"lifecycle"),this.copyControlPatchField(r,t,"approvalState"),this.copyControlPatchField(r,t,"approvalExecutionState"),this.copyControlPatchField(r,t,"worktreeState"),this.copyControlPatchField(r,t,"runtimeState"),this.copyControlPatchField(r,t,"deliveryState"),this.copyControlPatchField(r,t,"requestedPermissionMode"),this.copyControlPatchField(r,t,"currentPermissionMode"),this.copyControlPatchField(r,t,"pendingPlanApproval"),this.copyControlPatchField(r,t,"planApprovalContext"),this.copyControlPatchField(r,t,"planDecisionVersion"),this.copyControlPatchField(r,t,"actionablePlanDecisionVersion"),this.copyControlPatchField(r,t,"canonicalPlanPromptVersion"),this.copyControlPatchField(r,t,"approvalPromptRequiredVersion"),this.copyControlPatchField(r,t,"approvalPromptVersion"),this.copyControlPatchField(r,t,"approvalPromptStatus"),this.copyControlPatchField(r,t,"approvalPromptTransport"),this.copyControlPatchField(r,t,"approvalPromptMessageKind"),this.copyControlPatchField(r,t,"approvalPromptLastAttemptAt"),this.copyControlPatchField(r,t,"approvalPromptDeliveredAt"),this.copyControlPatchField(r,t,"approvalPromptFailedAt"),this.copyControlPatchField(r,t,"planModeApproved"),this.copyControlPatchField(r,t,"pendingWorktreeDecisionSince"),typeof e.applyControlPatch=="function"){e.applyControlPatch(r);return}this.assignIfPresent(e,"lifecycle",t,"lifecycle"),this.assignIfPresent(e,"approvalState",t,"approvalState"),this.assignIfPresent(e,"approvalExecutionState",t,"approvalExecutionState"),this.assignIfPresent(e,"worktreeState",t,"worktreeState"),this.assignIfPresent(e,"runtimeState",t,"runtimeState"),this.assignIfPresent(e,"deliveryState",t,"deliveryState"),this.assignIfPresent(e,"requestedPermissionMode",t,"requestedPermissionMode"),this.assignIfPresent(e,"currentPermissionMode",t,"currentPermissionMode"),this.assignIfPresent(e,"pendingPlanApproval",t,"pendingPlanApproval"),this.assignIfPresent(e,"planApprovalContext",t,"planApprovalContext"),this.assignIfPresent(e,"planDecisionVersion",t,"planDecisionVersion"),this.assignIfPresent(e,"actionablePlanDecisionVersion",t,"actionablePlanDecisionVersion"),this.assignIfPresent(e,"canonicalPlanPromptVersion",t,"canonicalPlanPromptVersion"),this.assignIfPresent(e,"approvalPromptRequiredVersion",t,"approvalPromptRequiredVersion"),this.assignIfPresent(e,"approvalPromptVersion",t,"approvalPromptVersion"),this.assignIfPresent(e,"approvalPromptStatus",t,"approvalPromptStatus"),this.assignIfPresent(e,"approvalPromptTransport",t,"approvalPromptTransport"),this.assignIfPresent(e,"approvalPromptMessageKind",t,"approvalPromptMessageKind"),this.assignIfPresent(e,"approvalPromptLastAttemptAt",t,"approvalPromptLastAttemptAt"),this.assignIfPresent(e,"approvalPromptDeliveredAt",t,"approvalPromptDeliveredAt"),this.assignIfPresent(e,"approvalPromptFailedAt",t,"approvalPromptFailedAt"),this.setControlFieldIfPresent(e,"planModeApproved",t)}applySessionMetadataPatch(e,t){this.assignIfDefined(e,"approvalRationale",t.approvalRationale),this.assignIfDefined(e,"taskFlowMirror",t.taskFlowMirror)}applyWorktreeMetadataPatch(e,t){this.assignIfDefined(e,"worktreePath",t.worktreePath),this.assignIfDefined(e,"worktreeBranch",t.worktreeBranch),this.assignIfDefined(e,"worktreePrUrl",t.worktreePrUrl),this.assignIfDefined(e,"worktreePrNumber",t.worktreePrNumber),this.assignIfDefined(e,"worktreeMerged",t.worktreeMerged),this.assignIfDefined(e,"worktreeMergedAt",t.worktreeMergedAt),this.assignIfDefined(e,"worktreeDisposition",t.worktreeDisposition),this.assignIfDefined(e,"worktreePrTargetRepo",t.worktreePrTargetRepo),this.assignIfDefined(e,"worktreePushRemote",t.worktreePushRemote),this.assignIfDefined(e,"worktreeLifecycle",t.worktreeLifecycle),"autoMergeParentSessionId"in t&&(e.autoMergeParentSessionId=t.autoMergeParentSessionId),"autoMergeConflictResolutionAttemptCount"in t&&(e.autoMergeConflictResolutionAttemptCount=t.autoMergeConflictResolutionAttemptCount),"autoMergeResolverSessionId"in t&&(e.autoMergeResolverSessionId=t.autoMergeResolverSessionId)}assignIfDefined(e,t,r){r!==void 0&&(e[t]=r)}assignIfPresent(e,t,r,o){Object.hasOwn(r,o)&&(e[t]=r[o])}copyControlPatchField(e,t,r){Object.hasOwn(t,r)&&(e[r]=t[r])}setControlFieldIfPresent(e,t,r){Object.hasOwn(r,t)&&e.setControlField?.(t,r[t])}};var Gc=new Set(["starting","running"]),Bn=class{constructor(e,t){this.sessions=e;this.store=t}sessions;store;resolveActive(e){let t=this.sessions.get(e);return t||(this.findPreferredMatch(e,r=>r.name===e)??this.findPreferredMatch(e,r=>C(r)===e)??this.findPreferredMatch(e,r=>r.harnessSessionId===e))}getPersistedSession(e){return this.store.getPersistedSession(e)}resolveBackendConversationId(e){let t=this.resolveActive(e);return this.store.resolveBackendConversationId(e,t?C(t)??t.harnessSessionId:void 0)}findPreferredMatch(e,t){let r,o;for(let i of this.sessions.values())t(i,e)&&((!o||i.startedAt>o.startedAt)&&(o=i),Gc.has(i.status)&&(!r||i.startedAt>r.startedAt)&&(r=i));return r??o}};import{existsSync as jc}from"fs";var sa=new Set(["merged","released","pr_open","dismissed","cleanup_failed"]),Kn=class{constructor(e){this.deps=e}deps;async plan(e){let t=D(e)??e.harnessSessionId;if(this.deps.isAlreadyMerged(t))return`${e.name}`,{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};let r=sa.has(e.worktreeState)?e.worktreeState:e.worktreeLifecycle?.state&&sa.has(e.worktreeLifecycle.state)?e.worktreeLifecycle.state:void 0;if(r&&!(r==="pr_open"&&e.worktreeStrategy==="auto-pr"))return`${e.name}${e.worktreeLifecycle?.state??e.worktreeState}`,{kind:"skip",result:{notificationSent:!0,worktreeRemoved:!1}};if(e.status!=="completed")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};if(!this.deps.shouldRunWorktreeStrategy(e))return`${e.name}${e.phase}`,{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let o=e.worktreeStrategy;if(!o||o==="off"||o==="manual")return{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let i=e.worktreePath,s=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,i),a=e.worktreeBranch;if(!s)return{kind:"notify",label:"worktree-missing-repo-dir",message:`β οΈ [${e.name}] Cannot determine the original repo for worktree ${i}. Manual inspection is required.`};if(!a)return{kind:"notify",label:"worktree-no-branch-name",message:`β οΈ [${e.name}] Cannot determine branch name for worktree ${i}. The worktree may have been removed or is in detached HEAD state. Manual cleanup may be needed.`};let l=L(e);if(l&&!jc(i))return{kind:"no-change",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l};let d=e.worktreeBaseBranch??Ee(s),u=this.deps.getWorktreeCompletionState(s,i,a,d);if(u==="no-change")return{kind:"no-change",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l};if(u==="merged")return{kind:"merged",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l};if(u==="released")return{kind:"released",repoDir:s,worktreePath:i,branchName:a,nativeBackendWorktree:l,reasons:["merge_noop_content_already_on_base"]};if(u==="base-advanced")return{kind:"notify",label:"worktree-no-commits-ahead",message:`β οΈ [${e.name}] Auto-merge: branch '${a}' has no commits ahead of '${d}', but '${d}' has new commits β commits likely landed outside the worktree branch. Verify that commits were not made directly to '${d}' instead of the worktree branch. Worktree: ${i}`};if(u==="dirty-uncommitted")return{kind:"dirty-uncommitted",worktreePath:i,branchName:a,baseBranch:d};let f=Ne(s,a,d);if(!f)return`${a}`,{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}};let g=e.repoIntegrationPolicy?void 0:this.deps.resolveRepoPolicy?.(s),S=e.repoIntegrationPolicy??g?.policy,y=e.repoIntegrationPolicy?this.deps.isPrAvailable(s):g?.prAvailable??this.deps.isPrAvailable(s),c=cs({requestedStrategy:o,policy:S,prAvailable:y,existingOpenPr:!1});return c.strategy?{kind:"decision",strategy:c.strategy,policy:S,policyReason:c.reason,policyBlocked:c.blocked,allowedActions:c.allowedActions,repoDir:s,worktreePath:i,branchName:a,baseBranch:d,diffSummary:f,sessionRef:t??void 0}:{kind:"skip",result:{notificationSent:!1,worktreeRemoved:!1}}}};function ye(n){let e=[];typeof n.costUsd=="number"&&Number.isFinite(n.costUsd)&&e.push(`$${n.costUsd.toFixed(2)}`);let t=zc(n);t!==void 0&&e.push(se(t));let r=ge({harness:n.harnessName??n.harness,model:n.model});return r&&e.push(...r.split(" | ")),e.length>0?` | ${e.join(" | ")}`:""}function zc(n){if(typeof n.duration=="number"&&Number.isFinite(n.duration)&&n.duration>=0)return n.duration;if(typeof n.createdAt=="number"&&Number.isFinite(n.createdAt)&&typeof n.completedAt=="number"&&Number.isFinite(n.completedAt)&&n.completedAt>=n.createdAt)return n.completedAt-n.createdAt}function Hc(n){if(n.requestedPermissionMode==="plan"){if(n.approvalExecutionState==="approved_then_implemented"){if(n.planApproval==="ask"&&n.approvalPromptStatus==="delivered"&&n.approvalPromptMessageKind==="canonical_buttons"&&n.approvalPromptDeliveredAt)return"Approval interpretation: canonical Approve/Revise/Reject buttons were delivered, and implementation after approval was expected.";if(n.approvalState==="approved")return"Approval interpretation: explicit plan approval was recorded before implementation, so leaving plan-only mode was expected."}if(n.approvalExecutionState==="implemented_without_required_approval")return"Approval interpretation: implementation left plan-only mode without a recorded approval."}}function Qc(){return/https?:\/\/github\.com\/[^\s)]+\/[^\s)]+\/pull\/(\d+)(?=[\s).,;:]|$)/gi}function Yc(){return/https?:\/\/\S+/gi}function qn(n){let e=Hc(n);return[`Requested permission mode: ${n.requestedPermissionMode??"unknown"}`,`Effective permission mode: ${n.currentPermissionMode??"unknown"}`,`Deterministic approval/execution state: ${n.approvalExecutionState??"unknown"}`,...e?[e]:[]]}function go(n){switch(n){case"user":return"Stopped by user";case"shutdown":return"Stopped by shutdown";case"startup-timeout":return"Stopped by startup timeout";case"unknown":case void 0:return"Stopped unexpectedly";default:return"Stopped"}}function Jc(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToOrdinaryTerminalCompletions:!0}}function Xc(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToWorktreeTerminalOutcomes:!0}}function Zc(){return{requiresShortFactualSummary:!0,owner:"agent",appliesToGoalTaskCompletions:!0}}function ho(n){let{sessionId:e,canonicalStatusDetail:t,canonicalStatusDelivered:r=!0,hasOriginRouteBlock:o=!1}=n,i=o?["7. Before sending that follow-up, honor the Session origin route block above. If originRoute differs from the current chat, do NOT use a plain final assistant reply; use a routed send path that preserves provider/target/threadId."]:[],s=o?8:7,a=o?9:8;return["[ACTION REQUIRED] Follow your autonomy rules for session completion:",`1. Use agent_output(session='${e}', full=true) to read the full result.`,"2. If this is part of a multi-phase pipeline, launch the next phase NOW β do not wait for user input.",`3. ${t??(r?"The plugin already sent the canonical completion status to the user.":"The plugin did not confirm delivery of the canonical completion status to the user.")}`,"4. Treat the completed session output as source material, not visible delivery. A meaningful final summary inside agent_output is not enough to skip, because the user may only have seen the plugin's terse status line.","5. If the visible result is only the plugin's terse status line, use the full output to send the user one short factual completion summary for this completed session. Do this even when agent_output already contains a good final summary.","6. This requirement applies to ordinary terminal/manual completions too, not just delegated worktree decisions.",...i,`${s}. That follow-up belongs to you alone; keep it brief, concrete, and grounded in reliable result data. Send at most one orchestrator-owned human summary for this terminal/worktree outcome.`,...r?[`${a}. Do NOT repeat the plugin's status line, and do NOT rely on the plugin to summarize the completed work for you.`]:[`${a}. Because canonical status delivery was not confirmed, account for that gap yourself when you follow up; do NOT assume the plugin already reached the user.`],`${a+1}. Send a normal concise final response after any routed follow-up is visibly sent. Do not use marker text, do not answer NO_REPLY, and do not ask the user whether they want the summary.`]}function ep(n){let{contract:e,canonicalStatusDelivered:t}=n;return["Completion diagnostics:",`- Canonical completion status delivered to user: ${t?"yes":"no"}`,`- Plugin requested short factual follow-up summary: ${e.requiresShortFactualSummary?"yes":"no"}`,`- Contract applies to ordinary terminal/manual completions: ${e.appliesToOrdinaryTerminalCompletions?"yes":"no"}`]}function yo(n){let{session:e,originThreadLine:t,preview:r}=n,o=!!t.trim(),i=Jc(),s=a=>["Coding agent session completed.",`Name: ${e.name} | ID: ${e.id}`,`Status: ${e.status}`,...o?[t]:[],...qn(e),"","Output preview:",r,"",...ep({contract:i,canonicalStatusDelivered:a}),"",...ho({sessionId:e.id,canonicalStatusDelivered:a,hasOriginRouteBlock:o})].join(`
|
|
141
141
|
`);return{userMessage:`β
[${e.name}] Completed${ye(e)}`,wakeMessageOnNotifySuccess:s(!0),wakeMessageOnNotifyFailed:s(!1),followupContract:i}}function Ge(n){let e=Xc(),t=!!n.originThreadLine.trim(),r=(n.detailLines??[]).map(i=>aa(i).trim()).filter(i=>i.length>0),o=aa(n.outcomeLine);return["Worktree follow-through outcome recorded.",`Name: ${n.sessionName??"unknown"} | ID: ${n.sessionId}`,...t?[n.originThreadLine]:[],"","Canonical outcome status:",o,...r.length>0?["","Outcome details:",...r.map(i=>`- ${i}`)]:[],"","Completion diagnostics:",`- Canonical worktree status delivered to user: ${n.canonicalStatusDelivered?"yes":"no"}`,`- Plugin requested short factual follow-up summary: ${e.requiresShortFactualSummary?"yes":"no"}`,`- Contract applies to worktree terminal outcomes: ${e.appliesToWorktreeTerminalOutcomes?"yes":"no"}`,"","[ACTION REQUIRED] Follow your autonomy rules for worktree follow-through:",`1. Use agent_output(session='${n.sessionId}', full=true) to read the full result if output is available.`,"2. Treat the completed session output as source material, not visible delivery. A meaningful final summary inside agent_output is not enough to skip, because the user may only have seen the plugin's terse status line.","3. Use the full output plus the canonical outcome facts above to send the user one short factual outcome summary. Do this even when agent_output already contains a good final summary.","4. If full output is unavailable or not meaningful, say only what is proven by the merge/PR facts above; do not invent task details.","5. Mention blockers such as push failure when present; do not describe a local-only merge as pushed.","6. Do not include raw PR URLs in the follow-up summary. The plugin already posted the PR link in the canonical status; refer to PRs by number, repo, and branch instead.",...t?["7. Before sending that follow-up, honor the Session origin route block above. If originRoute differs from the current chat, do NOT use a plain final assistant reply; use a routed send path that preserves provider/target/threadId."]:[],`${t?8:7}. Do NOT repeat only the plugin status line; keep the follow-up brief, concrete, and non-duplicative. Send at most one human-visible summary for this terminal/worktree outcome, counting summaries already sent by the foreground assistant turn or routed message tools.`,`${t?9:8}. Send a normal concise final response after any routed follow-up is visibly sent. Do not use marker text, do not answer NO_REPLY, and do not ask the user whether they want the summary.`].join(`
|
|
142
142
|
`)}function So(n){let e=Zc(),t=!!n.originThreadLine.trim();return["Goal task succeeded.",`Task: ${n.taskName}`,`Name: ${n.sessionName??n.taskName} | ID: ${n.sessionId}`,...t?[n.originThreadLine]:[],"","Canonical goal status:",n.summary,"","Completion diagnostics:",`- Canonical goal success status delivered to user: ${n.canonicalStatusDelivered?"yes":"no"}`,`- Plugin requested short factual follow-up summary: ${e.requiresShortFactualSummary?"yes":"no"}`,`- Contract applies to goal task completions: ${e.appliesToGoalTaskCompletions?"yes":"no"}`,"","[ACTION REQUIRED] Follow your autonomy rules for goal task completion:",`1. Use agent_output(session='${n.sessionId}', full=true) to read the full result if output is available.`,"2. Treat the completed session output as source material, not visible delivery. A meaningful final summary inside agent_output is not enough to skip, because the user may only have seen the plugin's terse goal status line.","3. Send the user one short factual completion summary grounded in the full output plus the canonical goal status above. Do this even when agent_output already contains a good final summary.","4. If full output is unavailable or not meaningful, say only what is proven by the goal status above; do not invent task details.",...t?["5. Before sending that follow-up, honor the Session origin route block above. If originRoute differs from the current chat, do NOT use a plain final assistant reply; use a routed send path that preserves provider/target/threadId."]:[],`${t?6:5}. Do NOT repeat only the plugin status line; keep the follow-up brief, concrete, and non-duplicative. Send at most one human-visible summary for this goal success outcome, counting summaries already sent by the foreground assistant turn or routed message tools.`,`${t?7:6}. Send a normal concise final response after any routed follow-up is visibly sent. Do not use marker text, do not answer NO_REPLY, and do not ask the user whether they want the summary.`].join(`
|
|
143
143
|
`)}function aa(n){return n.replace(Qc(),"PR #$1").replace(Yc(),"[link omitted]")}function ko(n){let{session:e,originThreadLine:t,errorSummary:r,preview:o,worktreeAutoCleaned:i,failedButtons:s}=n,a=o.trim()?["","Output preview:",o]:[],l=i?["","Note: Worktree and branch were auto-removed (zero cost, startup failure)."]:[];return{userMessage:[`β [${e.name}] Failed${ye(e)}`,` β οΈ ${r}`].join(`
|
|
@@ -174,10 +174,10 @@ ${i?"Choose Approve, Revise, or Reject below.":"Approval is still pending for th
|
|
|
174
174
|
${e}`}function up(n,e){return e!=null&&n.approvalPromptRequiredVersion===e&&(n.approvalPromptStatus==="delivered"||n.approvalPromptStatus==="fallback_delivered")}function Sa(n){let{session:e,summary:t}=n,r=e.actionablePlanDecisionVersion??e.planDecisionVersion;return[`π [${e.name}] Plan v${r??"?"} needs your decision.`,"","Interactive Approve / Revise / Reject buttons could not be delivered, so reply here instead:",'- Reply "approve" to approve and start implementation','- Reply "reject" to reject and stop the session',"- Any other reply will be sent back as revision feedback","","Decision context:","",t].join(`
|
|
175
175
|
`)}function gt(n){let e=ga(Sa(n));return e.map((t,r)=>({text:e.length===1?t:`${t}
|
|
176
176
|
|
|
177
|
-
${r===e.length-1?"End of decision context.":"Continued in next message."}`,requiredForSequenceSuccess:!0}))}function xo(n){let{session:e,preview:t,questionText:r,questionContextSummary:o,planArtifact:i,originThreadLine:s,planApprovalMode:a,planApprovalButtons:l,questionButtons:d}=n,u=e.pendingPlanApproval,f=e.actionablePlanDecisionVersion??e.planDecisionVersion,g=up(e,f),S=a??"delegate",y=u&&S==="ask"&&!g?ft({sessionName:e.name,actionableVersion:f,preview:t,artifact:i,hasButtons:!!l}):void 0,c=u?y?.reviewSummary??To({preview:t,artifact:i}):void 0,h=u?y&&y.userMessages.length===1?y.userMessages[0]:void 0:dp({sessionName:e.name,questionText:r??t,contextSummary:o,hasButtons:!!d}),v=u&&y&&y.userMessages.length>1?y.userMessages.map((A,I,
|
|
177
|
+
${r===e.length-1?"End of decision context.":"Continued in next message."}`,requiredForSequenceSuccess:!0}))}function xo(n){let{session:e,preview:t,questionText:r,questionContextSummary:o,planArtifact:i,originThreadLine:s,planApprovalMode:a,planApprovalButtons:l,questionButtons:d}=n,u=e.pendingPlanApproval,f=e.actionablePlanDecisionVersion??e.planDecisionVersion,g=up(e,f),S=a??"delegate",y=u&&S==="ask"&&!g?ft({sessionName:e.name,actionableVersion:f,preview:t,artifact:i,hasButtons:!!l}):void 0,c=u?y?.reviewSummary??To({preview:t,artifact:i}):void 0,h=u?y&&y.userMessages.length===1?y.userMessages[0]:void 0:dp({sessionName:e.name,questionText:r??t,contextSummary:o,hasButtons:!!d}),v=u&&y&&y.userMessages.length>1?y.userMessages.map((A,I,R)=>({text:A,buttons:I===R.length-1?l:void 0,requiredForSequenceSuccess:!0})):void 0;if(u){let A=S,I="Permission mode: plan β will switch to bypassPermissions on approval";return A==="delegate"?{label:"plan-approval",userMessage:h,userMessages:v,planReviewSummary:c,wakeMessage:["[DELEGATED PLAN APPROVAL] Coding agent session has finished its plan and is requesting approval to implement.",`Name: ${e.name} | ID: ${e.id} | Plan v${f??"?"}`,s,I,"","β οΈ YOU MUST COMPLETE THESE STEPS IN ORDER. Do NOT skip any step.","","βββ STEP 1 (MANDATORY): Read the full plan βββ",`Call agent_output(session='${e.id}', full=true) to read the FULL plan output.`,"The preview below is truncated β you MUST read the full output before making any decision.","","Preview (truncated):",t,"","βββ STEP 2 (MANDATORY): Review privately βββ","You are the delegated decision-maker. Review the plan yourself before involving the user.","If you approve directly, you own the user-facing explanation of what was approved and why.","Keep it short and user-facing: one sentence is usually enough.","","βββ STEP 3 (ONLY AFTER steps 1 and 2): Decide βββ","Choose ONE:","","APPROVE the plan directly if ALL of the following are true:","- You have read the FULL plan (not just the preview)","- The plan scope matches the original task request","- The changes are low-risk (no destructive operations, no credential handling, no production deployments)","- The plan is clear and well-scoped (no ambiguous requirements or open design questions)","- No architectural decisions that the user should weigh in on","- The working directory and codebase are correct","","ESCALATE to the user and WAIT if ANY of the following are true:","- The plan involves destructive operations (deleting files, dropping tables, force-pushing)","- The plan involves credentials, secrets, or production environments","- The plan requires architectural decisions not covered by the original task","- The scope has expanded beyond the original request","- The requirements are ambiguous or the plan makes assumptions the user should confirm","- You are unsure β when in doubt, always escalate","",`If approving: call agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true, approval_rationale='<brief reason>').`,"That rationale should say why approval was safe: for example scope match, low risk, or no meaningful ambiguity.","After approving directly, send the user a short plain-text follow-up explaining what was approved and why.","The plugin's thumbs-up line is only the minimal approval acknowledgment, not the explanation.",`If escalating: call agent_request_plan_approval(session='${e.id}', summary='...') exactly once so the plugin posts the single canonical Approve / Revise / Reject prompt.`,"That summary must concisely explain why this was escalated, plus changed files/components, risk level and why, scope match/expansion, and any concerns or assumptions.","After the canonical prompt exists, WAIT for the user's button click or explicit response and do NOT send a second plain-text recap.",`To request changes without user escalation: call agent_respond(session='${e.id}', message='<your feedback>') and do NOT set approve=true. The agent will revise the plan.`].join(`
|
|
178
178
|
`)}:A==="ask"?{label:"plan-approval",userMessage:h,userMessages:v,planReviewSummary:c,wakeMessage:["[USER APPROVAL REQUESTED] Coding agent session has finished its plan. The user has been notified via Telegram and must approve directly.",`Name: ${e.name} | ID: ${e.id} | Plan v${f??"?"}`,s,I,"","DO NOT approve this plan yourself. Wait for the user's explicit approval or rejection.","Once the user responds, forward their decision:",` To approve: agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`,` To request changes: agent_respond(session='${e.id}', message='<user feedback>')`,"","Preview (truncated):",t].join(`
|
|
179
179
|
`),buttons:v?void 0:l}:{label:"plan-approval",userMessage:h,planReviewSummary:c,wakeMessage:["[AUTO-APPROVE] Session has a plan ready. Approve it now:",`agent_respond(session='${e.id}', message='Approved. Go ahead.', approve=true)`].join(`
|
|
180
|
-
`)}}let
|
|
180
|
+
`)}}let b=e.multiTurn?"Multi-turn session":"Session";return{label:"waiting",userMessage:h,wakeMessage:[`[SYSTEM INSTRUCTION: Follow your auto-respond rules strictly. If this is a permission request or "should I continue?" β auto-respond. For ALL other questions β forward the agent's EXACT question to the user. Do NOT add your own analysis, commentary, or interpretation. Do NOT "nudge" or "poke" the session.]`,"",`${b} is waiting for a genuine user reply.`,`Name: ${e.name} | ID: ${e.id}`,s,"","Last output:",t,"",`Use agent_respond(session='${e.id}', message='...') to send a reply, or agent_output(session='${e.id}', full: true) to see full context before deciding.`].join(`
|
|
181
181
|
`),buttons:d}}var Vn=3,Co=180,cp=4e3,ka=32;function va(){let n=xe(),e=kp(n);if(e)return{async generateWorktreeDecisionSummary(t){if(typeof e.generateWorktreeDecisionSummary=="function")return await e.generateWorktreeDecisionSummary(t);if(typeof e.summarizeWorktreeDecision=="function")return await e.summarizeWorktreeDecision(t);let r=vp(t);if(typeof e.generateObject=="function")return await e.generateObject({task:"openclaw-code-agent.worktree-decision-summary",prompt:r,input:t});if(typeof e.generateText=="function")return await e.generateText({task:"openclaw-code-agent.worktree-decision-summary",prompt:r});if(typeof e.complete=="function")return await e.complete({prompt:r})}}}function pp(n,e){let t=Pp(e);if(t.length>0)return t;let r=mp(n);if(r.length>0)return r;let o=[],i=n.changedFiles.slice(0,3).map(a=>`\`${a}\``);if(i.length>0){let a=n.changedFiles.length-i.length;o.push(a>0?`Touches ${i.join(", ")} and ${a} more file${a===1?"":"s"}`:`Touches ${i.join(", ")}`)}let s=[...new Set(n.commitMessages.map(a=>a.message.trim()).filter(Boolean))].slice(0,2);return s.length>0&&o.push(`Recent work: ${s.join("; ")}`),o}function mp(n){let e=new Set,t=n.commitMessages.length===1?n.changedFiles:[];return n.commitMessages.map(r=>fp(r.message,t)).filter(r=>!!r).filter(r=>{let o=r.toLowerCase();return e.has(o)?!1:(e.add(o),!0)}).slice(0,Vn)}function fp(n,e){let t=gp(n);if(!t)return;let r=e.length===1?` in \`${e[0]}\``:e.length>1&&e.length<=3?` across ${e.map(o=>`\`${o}\``).join(", ")}`:"";return Mo(`${t}${r}.`,Co)}function gp(n){let e=Un(Gn(n)).replace(/^(?:feat|fix|docs|style|refactor|perf|test|tests|build|ci|chore|revert)(?:\([^)]+\))?!?:\s*/i,"").replace(/\.$/,"").trim();if(!e||_o(e))return;let t=e.match(/^([a-z]+)\b(.*)$/i);if(!t)return e;let r=t[1].toLowerCase(),o=t[2]??"",s=new Map([["add","Adds"],["address","Addresses"],["block","Blocks"],["change","Changes"],["clarify","Clarifies"],["clean","Cleans"],["cover","Covers"],["create","Creates"],["deduplicate","Deduplicates"],["delete","Deletes"],["disable","Disables"],["document","Documents"],["enable","Enables"],["extract","Extracts"],["fix","Fixes"],["guard","Guards"],["harden","Hardens"],["implement","Implements"],["improve","Improves"],["init","Initializes"],["initialize","Initializes"],["migrate","Migrates"],["move","Moves"],["normalize","Normalizes"],["preserve","Preserves"],["prevent","Prevents"],["refactor","Refactors"],["remove","Removes"],["rename","Renames"],["restore","Restores"],["simplify","Simplifies"],["tighten","Tightens"],["update","Updates"],["use","Uses"],["wire","Wires"],["wrap","Wraps"]]).get(r);return s?`${s}${o}`:`${r[0].toUpperCase()}${r.slice(1)}${o}`}async function Pa(n){let e=hp(n),t=pp(n.diffSummary??{changedFiles:e.changedFiles,commitMessages:e.commitSubjects.map(r=>({message:r}))},n.outputPreview);if(!n.provider)return{source:"fallback",lines:t,evidence:e,error:"LLM summary provider unavailable."};try{let r=await n.provider.generateWorktreeDecisionSummary(e),o=yp(r);return o.length>0?{source:"llm",lines:o,evidence:e}:{source:"fallback",lines:t,evidence:e,error:"LLM-generated worktree summary failed schema validation."}}catch(r){let o=r instanceof Error?r.message:String(r);return`${o}`,{source:"fallback",lines:t,evidence:e,error:"LLM summary provider failed."}}}function hp(n){let e=n.diffSummary;return{sessionName:n.sessionName,objective:Rp(n.prompt),stats:e?{commits:e.commits,filesChanged:e.filesChanged,insertions:e.insertions,deletions:e.deletions}:void 0,changedFiles:e?.changedFiles??[],commitSubjects:e?.commitMessages.map(t=>Un(t.message)).filter(Boolean).slice(0,8)??[],outputPreview:Mo(Gn(n.outputPreview??""),cp)}}function yp(n){let e=Sp(n),t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.summary)?e.summary:void 0;if(!t||t.length===0||t.length>Vn)return[];let r=t.map(o=>typeof o=="string"?Un(o):"").filter(Boolean);return r.length!==t.length?[]:r.some(o=>o.length>Co)?[]:r.some(_o)?[]:r}function Sp(n){if(typeof n!="string")return n;let e=n.trim();if(e)try{return JSON.parse(e)}catch{return{summary:e.split(`
|
|
182
182
|
`).map(t=>t.replace(/^[-*β’]\s+/,"").trim()).filter(Boolean).slice(0,Vn)}}}function kp(n){return[n?.worktreeDecisionSummary,n?.llm,n?.ai,n?.model,n?.models].find(t=>!!(t&&typeof t=="object"&&(typeof t.generateWorktreeDecisionSummary=="function"||typeof t.summarizeWorktreeDecision=="function"||typeof t.generateObject=="function"||typeof t.generateText=="function"||typeof t.complete=="function")))}function vp(n){return["Summarize the completed OpenClaw Code Agent work for a worktree decision notification.",'Return only JSON with shape {"summary":["..."]}.',"Write 1-3 concise, user-facing bullets that help a human choose Merge, Open PR, Later, or Discard.","Do not mention that you are summarizing. Do not invent changes not supported by the evidence.","","Evidence:",JSON.stringify(n,null,2)].join(`
|
|
183
183
|
`)}function Pp(n){let e=new Set;return Gn(n??"").replace(/\r\n/g,`
|
|
@@ -192,10 +192,10 @@ ${r===e.length-1?"End of decision context.":"Continued in next message."}`,requi
|
|
|
192
192
|
(Pre-existing changes on ${i} were auto-stashed and restored.)`),f=ie(f,a);let g=tt(a),S=[a.fastForward?"Merge type: fast-forward.":"Merge type: merge commit.",`Auto-merge landed ${o} into ${i}.`,"Local worktree branch cleanup was requested.",...a.stashPopConflict?[`Pre-merge stash pop conflicted; run git stash show ${a.stashRef??"stash@{0}"} in ${t} to review stashed changes.`]:[],...!a.stashPopConflict&&a.stashed?[`Pre-existing changes on ${i} were auto-stashed and restored.`]:[],...g];return this.deps.dispatchSessionNotification(e,{label:"worktree-merge-success",idempotencyKey:`worktree-merge-success:${e.id}:${o}:${i}:${re(e)}`,userMessage:f,notifyUser:"always",completionSummary:{required:!0,producer:"worktree",outcomeKey:`worktree-merge:${e.id}:${o}:${i}:${re(e)}`},completionWakeSummaryRequired:!0,completionWakeOutcomeKey:`worktree-merge:${e.id}:${o}:${i}:${re(e)}`,deferConditionalWakeUntilNextTick:!0,wakeMessageOnNotifySuccess:Ge({sessionId:e.id,sessionName:e.name,outcomeLine:u,originThreadLine:this.deps.originThreadLine(e),detailLines:S,canonicalStatusDelivered:!0}),wakeMessageOnNotifyFailed:Ge({sessionId:e.id,sessionName:e.name,outcomeLine:u,originThreadLine:this.deps.originThreadLine(e),detailLines:S,canonicalStatusDelivered:!1})}),d}async handleInitialAutoMergeConflict(e,t,r,o,i,s,a,l){let d=l?tt(l):[],u=e.autoMergeConflictResolutionAttemptCount??0;if(u>=1){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_exhausted"],clearResolverSessionId:!0}),this.notifyAutoMergeConflictEscalation(e,o,s.pr?`The rebased branch still conflicts with \`${i}\`. Open a PR or resolve manually in ${r}.`:`The rebased branch still conflicts with \`${i}\`. Resolve manually in ${r}.`,s,d);return}let f=this.buildConflictResolverPrompt({session:e,repoDir:t,worktreePath:r,branchName:o,baseBranch:i,mergeError:a});try{let g=await this.deps.spawnConflictResolver({session:e,repoDir:t,worktreePath:r,branchName:o,baseBranch:i,prompt:f});this.markAutoMergeConflictResolving(e,g.id,u+1),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-resolving",idempotencyKey:`worktree-merge-conflict-resolving:${e.id}:${o}:${g.id}`,userMessage:[`β οΈ [${e.name}] Auto-merge hit a rebase conflict. Started resolver session ${g.name} and will retry automatically if it succeeds.`,...d.map(S=>`β οΈ ${S}`)].join(`
|
|
193
193
|
`)})}catch(g){this.markPendingDecision(e,{notes:["auto_merge_conflict_resolver_spawn_failed"]}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-conflict-spawn-failed",idempotencyKey:`worktree-merge-conflict-spawn-failed:${e.id}:${o}:${re(e)}`,userMessage:[`β [${e.name}] Auto-merge hit a rebase conflict and failed to start the resolver: ${g instanceof Error?g.message:String(g)}`,...d.map(S=>`β οΈ ${S}`)].join(`
|
|
194
194
|
`),buttons:this.getPolicyAwareWorktreeDecisionButtons(e.id,s,{},[[this.deps.makeOpenPrButton(e.id)]])})}}handleAutoMergeRetryFailure(e,t,r,o,i){this.markPendingDecision(e,{notes:["auto_merge_conflict_retry_failed"],clearResolverSessionId:!0}),this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",idempotencyKey:`worktree-merge-error:${e.id}:${t}:${re(e)}`,userMessage:[o,"","Auto-merge retry did not complete after conflict resolution.",`Branch \`${t}\` was preserved for manual follow-up in ${r}.`].join(`
|
|
195
|
-
`),buttons:this.getPolicyAwareWorktreeDecisionButtons(e.id,i,{},[[this.deps.makeOpenPrButton(e.id)]])})}async handleAutoMergeStrategy(e,t,r,o,i,s,a=D(e)??e.harnessSessionId,l={merge:!0,pr:!0}){if(this.deps.isAlreadyMerged(a)||e.autoMergeResolverSessionId)return!1;let d=!1;return await this.deps.enqueueMerge(t,async()=>{if(this.deps.isAlreadyMerged(a))return;let u=this.deps.mergeBranch(t,o,i,"merge",r);if(u.success){d=this.handleAutoMergeSuccess(e,t,r,o,i,s,u);return}if(u.rebaseConflict){await this.handleInitialAutoMergeConflict(e,t,r,o,i,l,u.error,u);return}let f=ie(u.dirtyError?`β [${e.name}] Merge blocked: ${u.error}`:`β [${e.name}] Merge failed: ${u.error??"unknown error"}`,u);if(e.worktreeState==="merge_conflict_resolving"||e.worktreeLifecycle?.state==="merge_conflict_resolving"){this.handleAutoMergeRetryFailure(e,o,r,f,l);return}this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",idempotencyKey:`worktree-merge-error:${e.id}:${o}:${re(e)}`,userMessage:f})},()=>{this.deps.dispatchSessionNotification(e,{label:"worktree-merge-queued",idempotencyKey:`worktree-merge-queued:${e.id}:${o}:${re(e)}`,userMessage:`π [${e.name}] Merge queued β another merge for this repo is in progress. Will notify when complete.`})}),d}async handleAutoPrStrategy(e,t,r,o,i,s={merge:!0,pr:!0}){let a=this.releaseIfRepresentedByTargetPrBranch(e,t,r,o,i);if(a)return a;if(this.updatePersistedSessionFor(e,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),!(await this.deps.runAutoPr(e,i)).success){let d=this.releaseIfRepresentedByTargetPrBranch(e,t,r,o,i);if(d)return d;this.markPendingDecision(e),this.deps.dispatchSessionNotification(e,{label:"worktree-auto-pr-failed",idempotencyKey:`worktree-auto-pr-failed:${e.id}:${i}:${re(e)}`,userMessage:`β οΈ [${e.name}] Auto-PR did not complete. The worktree is preserved for an explicit merge or PR decision.`,buttons:this.getPolicyAwareWorktreeDecisionButtons(e.id,s)})}return{notificationSent:!0,worktreeRemoved:!1}}getPrStatusForUrl(e,t,r){return this.deps.getPrStatusForUrl?.(e,t,r)??Et(e,t,r)}releaseIfRepresentedByTargetPrBranch(e,t,r,o,i){if(Ze(r).length>0)return;let s=this.resolveExistingTargetPr(e,t,o,i),a=s?.headRefName;if(!a||a===o||a===i)return;let l=this.deps.fetchRemoteBranch?this.deps.fetchRemoteBranch(t,a):Xo(t,a);if(!l||!!!((s?.state==="open"||s?.state==="merged")&&s?.baseRefName===i&&_t(t,o,l)))return;let u=L(e)?!0:B(t,r);return u?(e.worktreePath=void 0,e.worktreePrUrl=s.url,e.worktreePrNumber=s.number,e.worktreePrTargetRepo=Tr(t,e.worktreePrTargetRepo),this.updatePersistedSessionFor(e,{worktreePath:void 0,worktreePrUrl:s.url,worktreePrNumber:s.number,worktreePrTargetRepo:e.worktreePrTargetRepo,worktreeRemoteOutcome:"pr-updated"}),H(t,o),this.markReleased(e,[`released_by_branch:${a}`]),{notificationSent:!1,worktreeRemoved:u}):(this.markPendingDecision(e,{notes:[`represented_by_branch:${a}`,"represented_worktree_cleanup_failed"]}),{notificationSent:!1,worktreeRemoved:!1})}};import{existsSync as dm,statSync as um,writeFileSync as cm}from"fs";import{randomUUID as Ap}from"crypto";function wa(n){return n==="plan-approve"||n==="plan-request-changes"||n==="plan-reject"}var zn=class{constructor(e,t){this.onChange=e;this.retentionMs=t}onChange;retentionMs;tokens=new Map;afterChange;replaceAll(e){this.tokens.clear();for(let t of e)this.tokens.set(t.id,t)}clear(){this.tokens.clear(),this.notifyChanged()}listForPersistence(){return[...this.tokens.values()]}createActionToken(e,t,r={}){let o={id:Ap(),sessionId:e,kind:t,createdAt:Date.now(),...r};return this.tokens.set(o.id,o),this.notifyChanged(),o}getActionToken(e){let t=this.tokens.get(e);if(t){if(t.expiresAt!=null&&t.expiresAt<=Date.now()){this.tokens.delete(e),this.notifyChanged();return}return t}}listActiveActionTokens(e){let t=[];for(let r of[...this.tokens.keys()]){let o=this.getActionToken(r);!o||o.consumedAt!=null||e&&o.kind!==e||t.push(o)}return t}consumeActionToken(e){let t=this.getActionToken(e);if(!(!t||t.consumedAt!=null))return t.consumedAt=Date.now(),this.notifyChanged(),t}consumeQuestionAnswerTokens(e,t,r){let o=[],i=Date.now();for(let s of this.tokens.values())s.sessionId!==e||s.kind!=="question-answer"||s.pendingInputRequestId!==t||r!=null&&s.pendingInputQuestionId!==r||s.consumedAt!=null||(s.consumedAt=i,o.push(s));return o.length>0&&this.notifyChanged(),o}consumePlanDecisionTokens(e,t){let r=[],o=Date.now();for(let i of this.tokens.values())i.sessionId!==e||!wa(i.kind)||i.planDecisionVersion!==t||i.consumedAt!=null||(i.consumedAt=o,r.push(i));return r.length>0&&this.notifyChanged(),r}deleteActionTokensForSession(e){let t=!1;for(let[r,o]of this.tokens)o.sessionId===e&&(this.tokens.delete(r),t=!0);t&&this.notifyChanged()}deleteActionTokensForSessionByKind(e,t){let r=!1;for(let[o,i]of this.tokens)i.sessionId===e&&i.kind===t&&(this.tokens.delete(o),r=!0);r&&this.notifyChanged()}deletePlanDecisionTokensForSession(e,t){let r=!1;for(let[o,i]of this.tokens)i.sessionId!==e||!wa(i.kind)||t!=null&&i.planDecisionVersion===t||(this.tokens.delete(o),r=!0);r&&this.notifyChanged()}purgeExpiredActionTokens(e=Date.now()){let t=!1;for(let[r,o]of this.tokens){let i=o.expiresAt!=null&&o.expiresAt<=e,s=o.consumedAt!=null&&e-o.consumedAt>=this.retentionMs;(i||s)&&(this.tokens.delete(r),t=!0)}return t&&this.notifyChanged(),t}nextExpiryAt(){let e;for(let t of this.tokens.values()){let r=[t.expiresAt,t.consumedAt!=null?t.consumedAt+this.retentionMs:void 0].filter(o=>o!=null&&Number.isFinite(o));for(let o of r)(e==null||o<e)&&(e=o)}return e}setAfterChangeListener(e){this.afterChange=e}notifyChanged(){this.onChange(),this.afterChange?.()}};var Hn=class{constructor(e){this.indexes=e}indexes;hasRecordedSession(e){return this.indexes.idIndex.has(e)}getLatestPersistedByName(e){let t,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let a of this.indexes.persisted.values()){if(a.name!==e){s++;continue}let l=a.createdAt??Number.NEGATIVE_INFINITY,d=a.completedAt??Number.NEGATIVE_INFINITY;(l>r||l===r&&d>o||l===r&&d===o&&s>i)&&(t=a,r=l,o=d,i=s),s++}return t}resolveBackendConversationId(e,t){if(t)return t;let r=this.indexes.idIndex.get(e);if(r){let s=this.indexes.persisted.get(r);return(s?C(s):void 0)??r}let o=this.getLatestPersistedByName(e);if(o)return C(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?C(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?C(s)??e:e}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return e}resolveHarnessSessionId(e,t){return this.resolveBackendConversationId(e,t)}getPersistedSession(e){let t=this.indexes.idIndex.get(e);if(t)return this.indexes.persisted.get(t);let r=this.getLatestPersistedByName(e);if(r)return r;let o=this.indexes.backendIdIndex.get(e);return o?this.indexes.persisted.get(o):this.indexes.persisted.get(e)}listPersistedSessions(){return[...this.indexes.persisted.values()].sort((e,t)=>(t.completedAt??0)-(e.completedAt??0))}};import{existsSync as $a,mkdirSync as Zp,readFileSync as em,readdirSync as tm,renameSync as Ea,statSync as Na,unlinkSync as Oa,writeFileSync as Wa}from"fs";import{tmpdir as nm}from"os";import{dirname as rm,join as Fa}from"path";import{homedir as Ip}from"node:os";import{join as Tp}from"node:path";function Qn(n){let e=n.OPENCLAW_HOME?.trim();if(e)return e;let t=n.HOME?.trim()||Ip();return Tp(t,".openclaw")}var Yn=7,xp=new Set(["running","completed","failed","killed"]),Cp=new Set(["queued","running","waiting","blocked","succeeded","failed","cancelled","lost"]);function ae(n){return!!n&&typeof n=="object"}function je(n,e=""){return typeof n=="string"&&n.trim().length>0?n:e}function P(n){return typeof n=="string"&&n.trim().length>0?n:void 0}function q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Mp(n){if(!ae(n))return;let e=P(n.flowId),t=q(n.revision);if(!e||t===void 0)return;let r=typeof n.status=="string"&&Cp.has(n.status)?n.status:void 0;return{flowId:e,revision:t,...r?{status:r}:{}}}function ba(n){return typeof n=="string"&&is.has(n)?n:void 0}function Do(n){return n==="default"||n==="plan"||n==="bypassPermissions"?n:void 0}function _p(n){return n==="never"||n==="on-request"?"never":void 0}function Ra(n){return n==="approve"||n==="ask"||n==="delegate"?n:void 0}function Dp(n){if(n==="plan-mode"||n==="codex-first-turn-plan"||n==="soft-plan")return"plan-mode"}function Aa(n){return typeof n=="string"&&vn.has(n)?n:void 0}function $o(n){return typeof n=="string"&&os.has(n)?n:void 0}function Ia(n){return n==="github"||n==="unsupported"?n:void 0}function $p(n){return n==="stored"||n==="seeded"||n==="unknown"?n:void 0}function Ep(n){return n==="user"||n==="idle-timeout"||n==="startup-timeout"||n==="shutdown"||n==="done"||n==="unknown"?n:void 0}function Ta(n){return n==="starting"||n==="active"||n==="awaiting_plan_decision"||n==="awaiting_user_input"||n==="awaiting_worktree_decision"||n==="suspended"||n==="terminal"?n:void 0}function Np(n){return n==="not_required"||n==="pending"||n==="approved"||n==="changes_requested"||n==="rejected"?n:void 0}function Op(n){return n==="none"||n==="provisioned"||n==="pending_decision"||n==="merge_conflict_resolving"||n==="merge_in_progress"||n==="pr_in_progress"||n==="merged"||n==="released"||n==="pr_open"||n==="dismissed"||n==="cleanup_failed"?n:void 0}function Wp(n){return n==="none"||n==="provisioned"||n==="pending_decision"||n==="merge_conflict_resolving"||n==="pr_open"||n==="merged"||n==="released"||n==="dismissed"||n==="no_change"||n==="cleanup_failed"?n:void 0}function xa(n){return n==="live"||n==="stopped"?n:void 0}function Fp(n){if(!ae(n)||n.reason!=="persisted-running-without-runtime")return;let e=P(n.recoveredAt);if(!e||!Number.isFinite(Date.parse(e)))return;let t=n.normalizedStatus==="killed"?"killed":void 0;if(t)return{reason:"persisted-running-without-runtime",recoveredAt:e,rawStatus:P(n.rawStatus),rawLifecycle:P(n.rawLifecycle),rawRuntimeState:P(n.rawRuntimeState),rawResumable:typeof n.rawResumable=="boolean"?n.rawResumable:void 0,rawCompletedAt:q(n.rawCompletedAt),rawOutputPath:P(n.rawOutputPath),normalizedStatus:t,normalizedLifecycle:Ta(n.normalizedLifecycle),normalizedRuntimeState:xa(n.normalizedRuntimeState)}}function Lp(n){return{reason:"persisted-running-without-runtime",recoveredAt:new Date().toISOString(),rawStatus:P(n.status),rawLifecycle:P(n.lifecycle),rawRuntimeState:P(n.runtimeState),rawResumable:typeof n.resumable=="boolean"?n.resumable:void 0,rawCompletedAt:q(n.completedAt),rawOutputPath:P(n.outputPath),normalizedStatus:"killed",normalizedLifecycle:"suspended",normalizedRuntimeState:"stopped"}}function Bp(n){return n==="not_sent"||n==="sending"||n==="delivered"||n==="fallback_delivered"||n==="failed"?n:void 0}function Kp(n){return n==="direct-telegram"?"direct-message":n==="none"||n==="direct-message"||n==="wake-only"?n:void 0}function qp(n){return n==="none"||n==="canonical_buttons"||n==="explicit_fallback_text"?n:void 0}function Vp(n){return n==="idle"||n==="notifying"||n==="wake_pending"||n==="failed"?n:void 0}function Up(n){return n==="in_flight"||n==="delivered"?n:void 0}function Gp(n){if(!Array.isArray(n))return;let e=n.map(t=>{if(!ae(t))return;let r=P(t.key),o=Up(t.status),i=P(t.recordedAt);if(!(!r||!o||!i||!Number.isFinite(Date.parse(i))))return{key:r,status:o,recordedAt:i,label:P(t.label)}}).filter(t=>!!t);return e.length>0?e.slice(-64):void 0}function jp(n){if(!Array.isArray(n))return;let e=n.map(t=>{if(!ae(t))return;let r=P(t.key),o=P(t.recordedAt);if(!r||!o||!Number.isFinite(Date.parse(o)))return;let i=Array.isArray(t.linkedKeys)?[...new Set(t.linkedKeys.map(P).filter(s=>!!(s&&s!==r)))]:void 0;return{key:r,linkedKeys:i&&i.length>0?i:void 0,recordedAt:o,label:P(t.label),skipReason:P(t.skipReason)}}).filter(t=>!!t);return e.length>0?e.slice(-1024):void 0}function zp(n){return n==="awaiting_plan_output"||n==="awaiting_approval"||n==="approved_then_implemented"||n==="implemented_without_required_approval"||n==="not_plan_gated"?n:void 0}function Hp(n){return n==="plan-approve"||n==="plan-request-changes"||n==="plan-reject"||n==="plan-offer-start"||n==="plan-offer-dismiss"||n==="repo-policy-set"||n==="worktree-merge"||n==="worktree-create-pr"||n==="worktree-update-pr"||n==="worktree-view-pr"||n==="worktree-decide-later"||n==="worktree-dismiss"||n==="session-resume"||n==="session-restart"||n==="view-output"||n==="question-answer"?n:void 0}function Ca(n){if(!ae(n))return;let e=P(n.provider),t=P(n.accountId),r=P(n.target),o=P(n.threadId),i=P(n.sessionKey);if(!(!e||!r))return{provider:e,accountId:t,target:r,threadId:o,sessionKey:i}}function Qp(n,e,t){if(ae(n)){let r=P(n.kind),o=P(n.conversationId);if(o&&(r==="claude-code"||r==="codex-app-server"||r==="opencode-server"))return{kind:r,conversationId:o,runId:P(n.runId),worktreeId:P(n.worktreeId),worktreePath:P(n.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:t}}function Yp(n){if(!ae(n))return;let e=Wp(n.state),t=P(n.updatedAt);if(!e||!t)return;let r=P(n.resolutionSource);return{state:e,updatedAt:t,resolvedAt:P(n.resolvedAt),resolutionSource:r==="agent_merge"||r==="agent_pr"||r==="strategy_no_change"||r==="lifecycle_resolver"||r==="dismiss"||r==="maintenance"?r:void 0,baseBranch:P(n.baseBranch),targetRepo:P(n.targetRepo),pushRemote:P(n.pushRemote),notes:Array.isArray(n.notes)?n.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function Jp(n){let e=new Date(0).toISOString(),t=P(n.worktreeMergedAt)??P(n.worktreeDismissedAt)??P(n.pendingWorktreeDecisionSince)??e;if(n.worktreeMerged===!0||n.worktreeDisposition==="merged")return{state:"merged",updatedAt:t,resolvedAt:P(n.worktreeMergedAt)??t,resolutionSource:"agent_merge",baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:t,resolvedAt:P(n.worktreeDismissedAt)??t,resolutionSource:"dismiss",baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:t,resolvedAt:t,resolutionSource:"strategy_no_change",baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeDisposition==="pr-opened"||n.worktreeState==="pr_open")return{state:"pr_open",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.pendingWorktreeDecisionSince||n.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(P(n.worktreePath)||P(n.worktreeBranch))return{state:"provisioned",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)}}function Xp(n){if(typeof n=="string"&&xp.has(n))return n==="running"?"killed":n}function Ma(n){if(!ae(n))return;let e=je(n.harnessSessionId);if(!e)return;let t=Xp(n.status);if(!t)return;let r=n.status==="running",o=P(n.worktreePath),i=P(n.worktreeBranch),s=P(n.originChannel),a=typeof n.originThreadId=="string"||typeof n.originThreadId=="number"?n.originThreadId:void 0,l=P(n.originSessionKey),d=Ca(n.route);if(!d)return;let u=Z({route:d,originChannel:s,originThreadId:a,originSessionKey:l});if(!u||o&&!i)return;let f=P(n.harness),g=Qp(n.backendRef,f,e),S=Yp(n.worktreeLifecycle)??Jp(n),y=P(n.completionWakeSucceededAt),c=P(n.completionWakeSkippedAt),h=n.completionWakeSummaryRequired===!0&&!c?!0:void 0;return{sessionId:P(n.sessionId),harnessSessionId:e,backendRef:g,name:je(n.name,e),prompt:je(n.prompt),workdir:je(n.workdir,"(unknown)"),model:P(n.model),reasoningEffort:ba(n.reasoningEffort),fastMode:n.fastMode===!0?!0:void 0,createdAt:q(n.createdAt),completedAt:q(n.completedAt),status:t,lifecycle:r?"suspended":Ta(n.lifecycle),approvalState:Np(n.approvalState),worktreeState:Op(n.worktreeState),runtimeState:r?"stopped":xa(n.runtimeState),runtimeRecovery:r?Lp(n):Fp(n.runtimeRecovery),taskFlowMirror:Mp(n.taskFlowMirror),deliveryState:Vp(n.deliveryState),notificationDedupe:Gp(n.notificationDedupe),completionSummaryDedupe:jp(n.completionSummaryDedupe),completionWakeIssuedAt:P(n.completionWakeIssuedAt),completionWakeSucceededAt:y,completionWakeFailedAt:P(n.completionWakeFailedAt),completionWakeSkippedAt:c,completionWakeSkipReason:P(n.completionWakeSkipReason),completionWakeSummaryRequired:h,killReason:Ep(n.killReason),costUsd:typeof n.costUsd=="number"&&Number.isFinite(n.costUsd)?n.costUsd:0,originAgentId:P(n.originAgentId),originChannel:s,originThreadId:a,originSessionKey:l,route:u,outputPath:P(n.outputPath),harness:f,resumedFromSessionName:P(n.resumedFromSessionName),goalTaskId:P(n.goalTaskId),requestedPermissionMode:Do(n.requestedPermissionMode),currentPermissionMode:Do(n.currentPermissionMode),approvalExecutionState:zp(n.approvalExecutionState),approvalRationale:P(n.approvalRationale),planModeApproved:n.planModeApproved===!0,pendingPlanApproval:n.pendingPlanApproval===!0,planApprovalContext:Dp(n.planApprovalContext),planDecisionVersion:q(n.planDecisionVersion),actionablePlanDecisionVersion:q(n.actionablePlanDecisionVersion),canonicalPlanPromptVersion:q(n.canonicalPlanPromptVersion),approvalPromptRequiredVersion:q(n.approvalPromptRequiredVersion),approvalPromptVersion:q(n.approvalPromptVersion),approvalPromptStatus:Bp(n.approvalPromptStatus),approvalPromptTransport:Kp(n.approvalPromptTransport),approvalPromptMessageKind:qp(n.approvalPromptMessageKind),approvalPromptLastAttemptAt:P(n.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:P(n.approvalPromptDeliveredAt),approvalPromptFailedAt:P(n.approvalPromptFailedAt),planApproval:Ra(n.planApproval),codexApprovalPolicy:_p(n.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:Aa(n.worktreeStrategy),repoIntegrationPolicy:$o(n.repoIntegrationPolicy),repoIntegrationPolicySource:$p(n.repoIntegrationPolicySource),repoProvider:Ia(n.repoProvider),worktreeMerged:typeof n.worktreeMerged=="boolean"?n.worktreeMerged:void 0,worktreeMergedAt:P(n.worktreeMergedAt),worktreePrUrl:P(n.worktreePrUrl),worktreePrNumber:q(n.worktreePrNumber),pendingWorktreeDecisionSince:P(n.pendingWorktreeDecisionSince),lastWorktreeReminderAt:P(n.lastWorktreeReminderAt),worktreeBaseBranch:P(n.worktreeBaseBranch),worktreeParentBranch:P(n.worktreeParentBranch),worktreePrTargetRepo:P(n.worktreePrTargetRepo),autoMergeParentSessionId:P(n.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:q(n.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:P(n.autoMergeResolverSessionId),worktreePushRemote:P(n.worktreePushRemote),worktreeDecisionSnoozedUntil:P(n.worktreeDecisionSnoozedUntil),worktreeDisposition:n.worktreeDisposition==="active"||n.worktreeDisposition==="pr-opened"||n.worktreeDisposition==="merged"||n.worktreeDisposition==="dismissed"||n.worktreeDisposition==="no-change-cleaned"?n.worktreeDisposition:void 0,worktreeRemoteOutcome:n.worktreeRemoteOutcome==="pr-opened"||n.worktreeRemoteOutcome==="pr-updated"?n.worktreeRemoteOutcome:void 0,worktreeDismissedAt:P(n.worktreeDismissedAt),worktreeLifecycle:S,resumable:r?!0:n.resumable===!0}}function _a(n){if(!ae(n))return;let e=P(n.key),t=P(n.repoRoot),r=$o(n.policy),o=Ia(n.provider)??"unsupported",i=P(n.createdAt),s=P(n.updatedAt),a=n.source==="seeded"?"seeded":"stored";if(!(!e||!t||!r||!i||!s)&&!(!Number.isFinite(Date.parse(i))||!Number.isFinite(Date.parse(s))))return{key:e,policy:r,repoRoot:t,remoteUrl:P(n.remoteUrl),provider:o,createdAt:i,updatedAt:s,source:a}}function Da(n){if(!ae(n))return;let e=Hp(n.kind),t=je(n.id),r=je(n.sessionId),o=q(n.createdAt);if(!(!t||!r||!e||o==null))return{id:t,sessionId:r,kind:e,createdAt:o,planDecisionVersion:q(n.planDecisionVersion),expiresAt:q(n.expiresAt),consumedAt:q(n.consumedAt),optionIndex:q(n.optionIndex),pendingInputRequestId:P(n.pendingInputRequestId),pendingInputQuestionId:P(n.pendingInputQuestionId),label:P(n.label),targetUrl:P(n.targetUrl),route:Ca(n.route),launchName:P(n.launchName),launchPrompt:P(n.launchPrompt),launchWorkdir:P(n.launchWorkdir),launchModel:P(n.launchModel),launchReasoningEffort:ba(n.launchReasoningEffort),launchFastMode:n.launchFastMode===!0?!0:void 0,launchSystemPrompt:P(n.launchSystemPrompt),launchAllowedTools:Array.isArray(n.launchAllowedTools)?n.launchAllowedTools.filter(i=>typeof i=="string"):void 0,launchResumeSessionId:P(n.launchResumeSessionId),launchResumedFromSessionName:P(n.launchResumedFromSessionName),launchResumeWorktreeFrom:P(n.launchResumeWorktreeFrom),launchSessionIdOverride:P(n.launchSessionIdOverride),launchClearedPersistedCodexResume:n.launchClearedPersistedCodexResume===!0?!0:void 0,launchForkSession:typeof n.launchForkSession=="boolean"?n.launchForkSession:void 0,launchForceNewSession:typeof n.launchForceNewSession=="boolean"?n.launchForceNewSession:void 0,launchPermissionMode:Do(n.launchPermissionMode),launchPlanApproval:Ra(n.launchPlanApproval),launchHarness:P(n.launchHarness),launchWorktreeStrategy:Aa(n.launchWorktreeStrategy),launchWorktreeBaseBranch:P(n.launchWorktreeBaseBranch),launchWorktreePrTargetRepo:P(n.launchWorktreePrTargetRepo),launchOriginAgentId:P(n.launchOriginAgentId),repoPolicy:$o(n.repoPolicy),repoPolicyWorkdir:P(n.repoPolicyWorkdir)}}function Jn(n){if(!n.backendRef?.kind||!n.backendRef.conversationId)throw new Error(`Persisted session ${n.harnessSessionId} is missing required backend ref metadata.`);if(!n.route?.provider||!n.route.target)throw new Error(`Persisted session ${n.harnessSessionId} is missing required route metadata.`);if(n.worktreePath&&!n.worktreeBranch)throw new Error(`Persisted session ${n.harnessSessionId} is missing required worktreeBranch metadata.`)}function ht(n){return!!n&&typeof n=="object"}function Eo(n){return n instanceof Error?n.message:String(n)}function om(n,e){JSON.stringify({component:"SessionStore",event:n,at:new Date().toISOString(),...e})}function im(n){return ht(n)?{backendRefKind:typeof n.kind=="string"?n.kind:void 0,hasBackendConversationId:typeof n.conversationId=="string"&&n.conversationId.length>0,hasBackendRunId:typeof n.runId=="string"&&n.runId.length>0,hasBackendWorktreeId:typeof n.worktreeId=="string"&&n.worktreeId.length>0,hasBackendWorktreePath:typeof n.worktreePath=="string"&&n.worktreePath.length>0}:{}}function La(n,e,t=Date.now()){let r=`${n}.${e}-${t}`;for(let o=0;o<100;o+=1){let i=o===0?"":`-${o}`,s=`${r}${i}.json`;if(!$a(s))return s}}function No(){let n=nm();return tm(n).filter(e=>e.startsWith("openclaw-agent-")&&e.endsWith(".txt")).map(e=>Fa(n,e))}function Ba(n){let e=n.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||Fa(Qn(n),"code-agent-sessions.json")}function Ka(n,e,t,r=[]){try{Zp(rm(n),{recursive:!0});let o=n+".tmp";Wa(o,JSON.stringify({schemaVersion:Yn,sessions:e,actionTokens:t,repoPolicies:r},null,2),"utf-8"),Ea(o,n)}catch(o){`${Eo(o)}`}}function sm(n,e){try{if(!$a(n))return!1;let t=La(n,"legacy");return t?(Ea(n,t),`${e}${t}`,!0):!1}catch(t){return`${Eo(t)}`,!1}}var am={archiveLegacySessionIndex:sm};function lm(n,e){try{if(e.length===0)return;let t=La(n,"codex-sdk-legacy");if(!t)return;Wa(t,JSON.stringify(e,null,2),"utf-8"),`${e.length}${t}`}catch(t){`${Eo(t)}`}}function qa(n,e,t=[]){try{let r=new Set(t);for(let o of No())if(!r.has(o))try{let i=Na(o).mtimeMs;n-i>e&&Oa(o)}catch{}}catch{}}function Va(n,e,t=[]){try{let r=new Set(t),o;for(let i of No())if(!r.has(i))try{let s=Na(i).mtimeMs+e;if(s<=n)return n;o=o==null?s:Math.min(o,s)}catch{}return o}catch{return}}function Ua(n){try{let e=new Set(n);for(let t of No())if(!e.has(t))try{Oa(t)}catch{}}catch{}}function Ga(n){let{indexPath:e,clearAll:t,indexPersistedEntry:r,setActionToken:o,setRepoPolicy:i,purgeExpiredActionTokens:s,saveIndex:a}=n,l=d=>am.archiveLegacySessionIndex(e,d)?(t(),!0):!1;try{let d=em(e,"utf-8"),u=JSON.parse(d);if(Array.isArray(u)){if(!l("legacy array store"))return;a();return}if(!ht(u)||u.schemaVersion!==Yn&&u.schemaVersion!==6&&u.schemaVersion!==4){if(!l(`schema mismatch (expected v${Yn})`))return;a();return}let f=(b,m)=>{if(!Object.prototype.hasOwnProperty.call(u,b))return[];let w=u[b];if(Array.isArray(w))return w;l(m)&&a()},g=f("sessions","invalid sessions collection");if(g===void 0)return;let S=[],y=[],c=!1;for(let b of g){if(ht(b)&&b.harness==="codex"){let w=ht(b.backendRef)?b.backendRef:void 0;if((typeof w?.kind=="string"?w.kind:void 0)!=="codex-app-server"){S.push(b);continue}}let m=Ma(b);if(!m){if(!l("invalid v4 session entry"))return;a();return}ht(b)&&b.status==="running"&&(c=!0,om("session.recovered_from_running_persisted_row",{sessionId:typeof b.sessionId=="string"?b.sessionId:void 0,hasHarnessSessionId:typeof b.harnessSessionId=="string"&&b.harnessSessionId.length>0,...im(b.backendRef),rawStatus:b.status,rawLifecycle:b.lifecycle,rawRuntimeState:b.runtimeState,normalizedStatus:m.status,normalizedLifecycle:m.lifecycle,normalizedRuntimeState:m.runtimeState,reason:m.runtimeRecovery?.reason})),y.push(m)}S.length>0&&lm(e,S);let h=f("actionTokens","invalid action token collection");if(h===void 0)return;let v=[];for(let b of h){let m=Da(b);if(!m){if(!l("invalid v4 action token"))return;a();return}v.push(m)}let R=f("repoPolicies","invalid repo policy collection");if(R===void 0)return;let A=[],I=!1;for(let b of R){let m=_a(b);if(!m){I=!0;continue}A.push(m)}for(let b of y)r(b);for(let b of v)o(b);for(let b of A)i(b);(S.length>0||c)&&a(),I&&a(),s()}catch(d){if(d.code==="ENOENT"||!l("corrupt or unreadable"))return;a()}}var pm=new Set(["completed","failed","killed"]),Oo=1440*60*1e3;function mm(n){return n instanceof Error?n.message:String(n)}var fm={statSync:um};function gm(n){try{return fm.statSync(n).isDirectory()}catch(e){let t=e.code;return t!=="ENOENT"&&t!=="ENOTDIR"}}var Xn=class{persisted=new Map;repoPolicies=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(e={}){let t=e.env??process.env;this.indexPath=e.indexPath??Ba(t),this.actionTokenStore=new zn(()=>this.saveIndex(),Oo),this.actionTokens=this.actionTokenStore.tokens,this.queries=new Hn({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),t.OPENCLAW_DEBUG_SESSION_STORE==="1"&&`${this.indexPath}`,this.loadIndex()}loadIndex(){Ga({indexPath:this.indexPath,clearAll:()=>{this.persisted.clear(),this.repoPolicies.clear(),this.idIndex.clear(),this.nameIndex.clear(),this.backendIdIndex.clear(),this.actionTokenStore.clear()},indexPersistedEntry:e=>this.indexPersistedEntry(e),setActionToken:e=>{this.actionTokens.set(e.id,e)},setRepoPolicy:e=>{this.repoPolicies.set(e.key,e)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){Ka(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence(),[...this.repoPolicies.values()])}assertPersistedEntry(e){Jn(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){let t=Qo(e),r=t==="codex"?"codex-app-server":t==="opencode"?"opencode-server":"claude-code";return e.backendRef??{kind:e.backendKind??r,conversationId:e.harnessSessionId}}getSessionApprovalSnapshot(e){if(typeof e.approvalSnapshot=="function")return e.approvalSnapshot();let t=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1};return{requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:t.planModeApproved,pendingPlanApproval:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy}}getSessionRoutingSnapshot(e){return typeof e.routingSnapshot=="function"?e.routingSnapshot():{route:e.route,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey}}getSessionWorktreeSnapshot(e){return typeof e.worktreeSnapshot=="function"?e.worktreeSnapshot():{worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,repoIntegrationPolicy:e.repoIntegrationPolicy,repoIntegrationPolicySource:e.repoIntegrationPolicySource,repoProvider:e.repoProvider,worktreeBaseBranch:e.worktreeBaseBranch,worktreeParentBranch:e.worktreeParentBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle}}indexPersistedEntry(e){let t=this.getEntryStorageKey(e);if(e.sessionId){let o=this.idIndex.get(e.sessionId);if(o&&o!==t){let i=this.persisted.get(o);i&&this.removePersistedIndexes(i)}}this.persisted.set(t,e),e.sessionId&&this.idIndex.set(e.sessionId,t),e.name&&this.nameIndex.set(e.name,t);let r=C(e);r&&this.backendIdIndex.set(r,t)}removePersistedIndexes(e){let t=this.getEntryStorageKey(e);this.persisted.delete(t);for(let[r,o]of this.idIndex)o===t&&this.idIndex.delete(r);for(let[r,o]of this.nameIndex)o===t&&this.nameIndex.delete(r);for(let[r,o]of this.backendIdIndex)o===t&&this.backendIdIndex.delete(r)}markRunning(e){if(!e.harnessSessionId)return;let t=this.getSessionApprovalSnapshot(e),r=this.getSessionRoutingSnapshot(e),o=this.getSessionWorktreeSnapshot(e),i=Z({route:r.route,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey});if(!i)throw new Error(`Cannot persist running session ${e.id}: canonical lifecycle route is missing.`);let s={sessionId:e.id,harnessSessionId:e.harnessSessionId,backendRef:this.buildPersistedBackendRef(e),name:e.name,prompt:e.prompt,workdir:e.originalWorkdir??e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,createdAt:e.startedAt,status:"running",lifecycle:e.lifecycle,approvalState:e.approvalState,worktreeState:e.worktreeState,runtimeState:e.runtimeState,taskFlowMirror:e.taskFlowMirror,deliveryState:e.deliveryState,notificationDedupe:this.getExistingNotificationDedupe(e),completionSummaryDedupe:this.getExistingCompletionSummaryDedupe(e),costUsd:0,originAgentId:r.originAgentId,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey,route:i,outputPath:ve(e.id),harness:e.harnessName,resumedFromSessionName:e.resumedFromSessionName,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,approvalRationale:t.approvalRationale,planModeApproved:t.planModeApproved,pendingPlanApproval:t.pendingPlanApproval,planApprovalContext:t.planApprovalContext,planDecisionVersion:t.planDecisionVersion,actionablePlanDecisionVersion:t.actionablePlanDecisionVersion,canonicalPlanPromptVersion:t.canonicalPlanPromptVersion,approvalPromptRequiredVersion:t.approvalPromptRequiredVersion,approvalPromptVersion:t.approvalPromptVersion,approvalPromptStatus:t.approvalPromptStatus,approvalPromptTransport:t.approvalPromptTransport,approvalPromptMessageKind:t.approvalPromptMessageKind,approvalPromptLastAttemptAt:t.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:t.approvalPromptDeliveredAt,approvalPromptFailedAt:t.approvalPromptFailedAt,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,repoIntegrationPolicy:o.repoIntegrationPolicy,repoIntegrationPolicySource:o.repoIntegrationPolicySource,repoProvider:o.repoProvider,worktreeBaseBranch:o.worktreeBaseBranch,worktreeParentBranch:o.worktreeParentBranch,worktreePrTargetRepo:o.worktreePrTargetRepo,autoMergeParentSessionId:o.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:o.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:o.autoMergeResolverSessionId,worktreeLifecycle:o.worktreeLifecycle,resumable:e.isExplicitlyResumable};Jn(s),this.indexPersistedEntry(s),this.saveIndex()}hasRecordedSession(e){return this.queries.hasRecordedSession(e)}persistTerminal(e){if(!e.harnessSessionId)return;let t=this.getSessionApprovalSnapshot(e),r=this.getSessionRoutingSnapshot(e),o=this.getSessionWorktreeSnapshot(e),i=Z({route:r.route,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey});if(!i)throw new Error(`Cannot persist terminal session ${e.id}: canonical lifecycle route is missing.`);let s;try{let l=ve(e.id);if(dm(l))s=l;else{let d=e.getOutput().join(`
|
|
195
|
+
`),buttons:this.getPolicyAwareWorktreeDecisionButtons(e.id,i,{},[[this.deps.makeOpenPrButton(e.id)]])})}async handleAutoMergeStrategy(e,t,r,o,i,s,a=D(e)??e.harnessSessionId,l={merge:!0,pr:!0}){if(this.deps.isAlreadyMerged(a)||e.autoMergeResolverSessionId)return!1;let d=!1;return await this.deps.enqueueMerge(t,async()=>{if(this.deps.isAlreadyMerged(a))return;let u=this.deps.mergeBranch(t,o,i,"merge",r);if(u.success){d=this.handleAutoMergeSuccess(e,t,r,o,i,s,u);return}if(u.rebaseConflict){await this.handleInitialAutoMergeConflict(e,t,r,o,i,l,u.error,u);return}let f=ie(u.dirtyError?`β [${e.name}] Merge blocked: ${u.error}`:`β [${e.name}] Merge failed: ${u.error??"unknown error"}`,u);if(e.worktreeState==="merge_conflict_resolving"||e.worktreeLifecycle?.state==="merge_conflict_resolving"){this.handleAutoMergeRetryFailure(e,o,r,f,l);return}this.deps.dispatchSessionNotification(e,{label:"worktree-merge-error",idempotencyKey:`worktree-merge-error:${e.id}:${o}:${re(e)}`,userMessage:f})},()=>{this.deps.dispatchSessionNotification(e,{label:"worktree-merge-queued",idempotencyKey:`worktree-merge-queued:${e.id}:${o}:${re(e)}`,userMessage:`π [${e.name}] Merge queued β another merge for this repo is in progress. Will notify when complete.`})}),d}async handleAutoPrStrategy(e,t,r,o,i,s={merge:!0,pr:!0}){let a=this.releaseIfRepresentedByTargetPrBranch(e,t,r,o,i);if(a)return a;if(this.updatePersistedSessionFor(e,{lifecycle:"terminal",worktreeState:"pr_in_progress"}),!(await this.deps.runAutoPr(e,i)).success){let d=this.releaseIfRepresentedByTargetPrBranch(e,t,r,o,i);if(d)return d;this.markPendingDecision(e),this.deps.dispatchSessionNotification(e,{label:"worktree-auto-pr-failed",idempotencyKey:`worktree-auto-pr-failed:${e.id}:${i}:${re(e)}`,userMessage:`β οΈ [${e.name}] Auto-PR did not complete. The worktree is preserved for an explicit merge or PR decision.`,buttons:this.getPolicyAwareWorktreeDecisionButtons(e.id,s)})}return{notificationSent:!0,worktreeRemoved:!1}}getPrStatusForUrl(e,t,r){return this.deps.getPrStatusForUrl?.(e,t,r)??Et(e,t,r)}releaseIfRepresentedByTargetPrBranch(e,t,r,o,i){if(Ze(r).length>0)return;let s=this.resolveExistingTargetPr(e,t,o,i),a=s?.headRefName;if(!a||a===o||a===i)return;let l=this.deps.fetchRemoteBranch?this.deps.fetchRemoteBranch(t,a):Xo(t,a);if(!l||!!!((s?.state==="open"||s?.state==="merged")&&s?.baseRefName===i&&_t(t,o,l)))return;let u=L(e)?!0:B(t,r);return u?(e.worktreePath=void 0,e.worktreePrUrl=s.url,e.worktreePrNumber=s.number,e.worktreePrTargetRepo=Tr(t,e.worktreePrTargetRepo),this.updatePersistedSessionFor(e,{worktreePath:void 0,worktreePrUrl:s.url,worktreePrNumber:s.number,worktreePrTargetRepo:e.worktreePrTargetRepo,worktreeRemoteOutcome:"pr-updated"}),H(t,o),this.markReleased(e,[`released_by_branch:${a}`]),{notificationSent:!1,worktreeRemoved:u}):(this.markPendingDecision(e,{notes:[`represented_by_branch:${a}`,"represented_worktree_cleanup_failed"]}),{notificationSent:!1,worktreeRemoved:!1})}};import{existsSync as dm,statSync as um,writeFileSync as cm}from"fs";import{randomUUID as Ap}from"crypto";function wa(n){return n==="plan-approve"||n==="plan-request-changes"||n==="plan-reject"}var zn=class{constructor(e,t){this.onChange=e;this.retentionMs=t}onChange;retentionMs;tokens=new Map;afterChange;replaceAll(e){this.tokens.clear();for(let t of e)this.tokens.set(t.id,t)}clear(){this.tokens.clear(),this.notifyChanged()}listForPersistence(){return[...this.tokens.values()]}createActionToken(e,t,r={}){let o={id:Ap(),sessionId:e,kind:t,createdAt:Date.now(),...r};return this.tokens.set(o.id,o),this.notifyChanged(),o}getActionToken(e){let t=this.tokens.get(e);if(t){if(t.expiresAt!=null&&t.expiresAt<=Date.now()){this.tokens.delete(e),this.notifyChanged();return}return t}}listActiveActionTokens(e){let t=[];for(let r of[...this.tokens.keys()]){let o=this.getActionToken(r);!o||o.consumedAt!=null||e&&o.kind!==e||t.push(o)}return t}consumeActionToken(e){let t=this.getActionToken(e);if(!(!t||t.consumedAt!=null))return t.consumedAt=Date.now(),this.notifyChanged(),t}consumeQuestionAnswerTokens(e,t,r){let o=[],i=Date.now();for(let s of this.tokens.values())s.sessionId!==e||s.kind!=="question-answer"||s.pendingInputRequestId!==t||r!=null&&s.pendingInputQuestionId!==r||s.consumedAt!=null||(s.consumedAt=i,o.push(s));return o.length>0&&this.notifyChanged(),o}consumePlanDecisionTokens(e,t){let r=[],o=Date.now();for(let i of this.tokens.values())i.sessionId!==e||!wa(i.kind)||i.planDecisionVersion!==t||i.consumedAt!=null||(i.consumedAt=o,r.push(i));return r.length>0&&this.notifyChanged(),r}deleteActionTokensForSession(e){let t=!1;for(let[r,o]of this.tokens)o.sessionId===e&&(this.tokens.delete(r),t=!0);t&&this.notifyChanged()}deleteActionTokensForSessionByKind(e,t){let r=!1;for(let[o,i]of this.tokens)i.sessionId===e&&i.kind===t&&(this.tokens.delete(o),r=!0);r&&this.notifyChanged()}deletePlanDecisionTokensForSession(e,t){let r=!1;for(let[o,i]of this.tokens)i.sessionId!==e||!wa(i.kind)||t!=null&&i.planDecisionVersion===t||(this.tokens.delete(o),r=!0);r&&this.notifyChanged()}purgeExpiredActionTokens(e=Date.now()){let t=!1;for(let[r,o]of this.tokens){let i=o.expiresAt!=null&&o.expiresAt<=e,s=o.consumedAt!=null&&e-o.consumedAt>=this.retentionMs;(i||s)&&(this.tokens.delete(r),t=!0)}return t&&this.notifyChanged(),t}nextExpiryAt(){let e;for(let t of this.tokens.values()){let r=[t.expiresAt,t.consumedAt!=null?t.consumedAt+this.retentionMs:void 0].filter(o=>o!=null&&Number.isFinite(o));for(let o of r)(e==null||o<e)&&(e=o)}return e}setAfterChangeListener(e){this.afterChange=e}notifyChanged(){this.onChange(),this.afterChange?.()}};var Hn=class{constructor(e){this.indexes=e}indexes;hasRecordedSession(e){return this.indexes.idIndex.has(e)}getLatestPersistedByName(e){let t,r=Number.NEGATIVE_INFINITY,o=Number.NEGATIVE_INFINITY,i=Number.NEGATIVE_INFINITY,s=0;for(let a of this.indexes.persisted.values()){if(a.name!==e){s++;continue}let l=a.createdAt??Number.NEGATIVE_INFINITY,d=a.completedAt??Number.NEGATIVE_INFINITY;(l>r||l===r&&d>o||l===r&&d===o&&s>i)&&(t=a,r=l,o=d,i=s),s++}return t}resolveBackendConversationId(e,t){if(t)return t;let r=this.indexes.idIndex.get(e);if(r){let s=this.indexes.persisted.get(r);return(s?C(s):void 0)??r}let o=this.getLatestPersistedByName(e);if(o)return C(o)??o.harnessSessionId;let i=this.indexes.backendIdIndex.get(e);if(i){let s=this.indexes.persisted.get(i);return(s?C(s):void 0)??i}if(this.indexes.persisted.has(e)){let s=this.indexes.persisted.get(e);return s?C(s)??e:e}if(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e))return e}resolveHarnessSessionId(e,t){return this.resolveBackendConversationId(e,t)}getPersistedSession(e){let t=this.indexes.idIndex.get(e);if(t)return this.indexes.persisted.get(t);let r=this.getLatestPersistedByName(e);if(r)return r;let o=this.indexes.backendIdIndex.get(e);return o?this.indexes.persisted.get(o):this.indexes.persisted.get(e)}listPersistedSessions(){return[...this.indexes.persisted.values()].sort((e,t)=>(t.completedAt??0)-(e.completedAt??0))}};import{existsSync as $a,mkdirSync as Zp,readFileSync as em,readdirSync as tm,renameSync as Ea,statSync as Na,unlinkSync as Oa,writeFileSync as Wa}from"fs";import{tmpdir as nm}from"os";import{dirname as rm,join as Fa}from"path";import{homedir as Ip}from"node:os";import{join as Tp}from"node:path";function Qn(n){let e=n.OPENCLAW_HOME?.trim();if(e)return e;let t=n.HOME?.trim()||Ip();return Tp(t,".openclaw")}var Yn=7,xp=new Set(["running","completed","failed","killed"]),Cp=new Set(["queued","running","waiting","blocked","succeeded","failed","cancelled","lost"]);function ae(n){return!!n&&typeof n=="object"}function je(n,e=""){return typeof n=="string"&&n.trim().length>0?n:e}function P(n){return typeof n=="string"&&n.trim().length>0?n:void 0}function q(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Mp(n){if(!ae(n))return;let e=P(n.flowId),t=q(n.revision);if(!e||t===void 0)return;let r=typeof n.status=="string"&&Cp.has(n.status)?n.status:void 0;return{flowId:e,revision:t,...r?{status:r}:{}}}function ba(n){return typeof n=="string"&&is.has(n)?n:void 0}function Do(n){return n==="default"||n==="plan"||n==="bypassPermissions"?n:void 0}function _p(n){return n==="never"||n==="on-request"?"never":void 0}function Ra(n){return n==="approve"||n==="ask"||n==="delegate"?n:void 0}function Dp(n){if(n==="plan-mode"||n==="codex-first-turn-plan"||n==="soft-plan")return"plan-mode"}function Aa(n){return typeof n=="string"&&vn.has(n)?n:void 0}function $o(n){return typeof n=="string"&&os.has(n)?n:void 0}function Ia(n){return n==="github"||n==="unsupported"?n:void 0}function $p(n){return n==="stored"||n==="seeded"||n==="unknown"?n:void 0}function Ep(n){return n==="user"||n==="idle-timeout"||n==="startup-timeout"||n==="shutdown"||n==="done"||n==="unknown"?n:void 0}function Ta(n){return n==="starting"||n==="active"||n==="awaiting_plan_decision"||n==="awaiting_user_input"||n==="awaiting_worktree_decision"||n==="suspended"||n==="terminal"?n:void 0}function Np(n){return n==="not_required"||n==="pending"||n==="approved"||n==="changes_requested"||n==="rejected"?n:void 0}function Op(n){return n==="none"||n==="provisioned"||n==="pending_decision"||n==="merge_conflict_resolving"||n==="merge_in_progress"||n==="pr_in_progress"||n==="merged"||n==="released"||n==="pr_open"||n==="dismissed"||n==="cleanup_failed"?n:void 0}function Wp(n){return n==="none"||n==="provisioned"||n==="pending_decision"||n==="merge_conflict_resolving"||n==="pr_open"||n==="merged"||n==="released"||n==="dismissed"||n==="no_change"||n==="cleanup_failed"?n:void 0}function xa(n){return n==="live"||n==="stopped"?n:void 0}function Fp(n){if(!ae(n)||n.reason!=="persisted-running-without-runtime")return;let e=P(n.recoveredAt);if(!e||!Number.isFinite(Date.parse(e)))return;let t=n.normalizedStatus==="killed"?"killed":void 0;if(t)return{reason:"persisted-running-without-runtime",recoveredAt:e,rawStatus:P(n.rawStatus),rawLifecycle:P(n.rawLifecycle),rawRuntimeState:P(n.rawRuntimeState),rawResumable:typeof n.rawResumable=="boolean"?n.rawResumable:void 0,rawCompletedAt:q(n.rawCompletedAt),rawOutputPath:P(n.rawOutputPath),normalizedStatus:t,normalizedLifecycle:Ta(n.normalizedLifecycle),normalizedRuntimeState:xa(n.normalizedRuntimeState)}}function Lp(n){return{reason:"persisted-running-without-runtime",recoveredAt:new Date().toISOString(),rawStatus:P(n.status),rawLifecycle:P(n.lifecycle),rawRuntimeState:P(n.runtimeState),rawResumable:typeof n.resumable=="boolean"?n.resumable:void 0,rawCompletedAt:q(n.completedAt),rawOutputPath:P(n.outputPath),normalizedStatus:"killed",normalizedLifecycle:"suspended",normalizedRuntimeState:"stopped"}}function Bp(n){return n==="not_sent"||n==="sending"||n==="delivered"||n==="fallback_delivered"||n==="failed"?n:void 0}function Kp(n){return n==="direct-telegram"?"direct-message":n==="none"||n==="direct-message"||n==="wake-only"?n:void 0}function qp(n){return n==="none"||n==="canonical_buttons"||n==="explicit_fallback_text"?n:void 0}function Vp(n){return n==="idle"||n==="notifying"||n==="wake_pending"||n==="failed"?n:void 0}function Up(n){return n==="in_flight"||n==="delivered"?n:void 0}function Gp(n){if(!Array.isArray(n))return;let e=n.map(t=>{if(!ae(t))return;let r=P(t.key),o=Up(t.status),i=P(t.recordedAt);if(!(!r||!o||!i||!Number.isFinite(Date.parse(i))))return{key:r,status:o,recordedAt:i,label:P(t.label)}}).filter(t=>!!t);return e.length>0?e.slice(-64):void 0}function jp(n){if(!Array.isArray(n))return;let e=n.map(t=>{if(!ae(t))return;let r=P(t.key),o=P(t.recordedAt);if(!r||!o||!Number.isFinite(Date.parse(o)))return;let i=Array.isArray(t.linkedKeys)?[...new Set(t.linkedKeys.map(P).filter(s=>!!(s&&s!==r)))]:void 0;return{key:r,linkedKeys:i&&i.length>0?i:void 0,recordedAt:o,label:P(t.label),skipReason:P(t.skipReason)}}).filter(t=>!!t);return e.length>0?e.slice(-1024):void 0}function zp(n){return n==="awaiting_plan_output"||n==="awaiting_approval"||n==="approved_then_implemented"||n==="implemented_without_required_approval"||n==="not_plan_gated"?n:void 0}function Hp(n){return n==="plan-approve"||n==="plan-request-changes"||n==="plan-reject"||n==="plan-offer-start"||n==="plan-offer-dismiss"||n==="repo-policy-set"||n==="worktree-merge"||n==="worktree-create-pr"||n==="worktree-update-pr"||n==="worktree-view-pr"||n==="worktree-decide-later"||n==="worktree-dismiss"||n==="session-resume"||n==="session-restart"||n==="view-output"||n==="question-answer"?n:void 0}function Ca(n){if(!ae(n))return;let e=P(n.provider),t=P(n.accountId),r=P(n.target),o=P(n.threadId),i=P(n.sessionKey);if(!(!e||!r))return{provider:e,accountId:t,target:r,threadId:o,sessionKey:i}}function Qp(n,e,t){if(ae(n)){let r=P(n.kind),o=P(n.conversationId);if(o&&(r==="claude-code"||r==="codex-app-server"||r==="opencode-server"))return{kind:r,conversationId:o,runId:P(n.runId),worktreeId:P(n.worktreeId),worktreePath:P(n.worktreePath)}}if(e==="claude-code")return{kind:"claude-code",conversationId:t}}function Yp(n){if(!ae(n))return;let e=Wp(n.state),t=P(n.updatedAt);if(!e||!t)return;let r=P(n.resolutionSource);return{state:e,updatedAt:t,resolvedAt:P(n.resolvedAt),resolutionSource:r==="agent_merge"||r==="agent_pr"||r==="strategy_no_change"||r==="lifecycle_resolver"||r==="dismiss"||r==="maintenance"?r:void 0,baseBranch:P(n.baseBranch),targetRepo:P(n.targetRepo),pushRemote:P(n.pushRemote),notes:Array.isArray(n.notes)?n.notes.filter(o=>typeof o=="string"&&o.length>0):void 0}}function Jp(n){let e=new Date(0).toISOString(),t=P(n.worktreeMergedAt)??P(n.worktreeDismissedAt)??P(n.pendingWorktreeDecisionSince)??e;if(n.worktreeMerged===!0||n.worktreeDisposition==="merged")return{state:"merged",updatedAt:t,resolvedAt:P(n.worktreeMergedAt)??t,resolutionSource:"agent_merge",baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeDisposition==="dismissed")return{state:"dismissed",updatedAt:t,resolvedAt:P(n.worktreeDismissedAt)??t,resolutionSource:"dismiss",baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeDisposition==="no-change-cleaned")return{state:"no_change",updatedAt:t,resolvedAt:t,resolutionSource:"strategy_no_change",baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeDisposition==="pr-opened"||n.worktreeState==="pr_open")return{state:"pr_open",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.pendingWorktreeDecisionSince||n.worktreeState==="pending_decision")return{state:"pending_decision",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(n.worktreeState==="merge_conflict_resolving")return{state:"merge_conflict_resolving",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)};if(P(n.worktreePath)||P(n.worktreeBranch))return{state:"provisioned",updatedAt:t,baseBranch:P(n.worktreeBaseBranch),targetRepo:P(n.worktreePrTargetRepo),pushRemote:P(n.worktreePushRemote)}}function Xp(n){if(typeof n=="string"&&xp.has(n))return n==="running"?"killed":n}function Ma(n){if(!ae(n))return;let e=je(n.harnessSessionId);if(!e)return;let t=Xp(n.status);if(!t)return;let r=n.status==="running",o=P(n.worktreePath),i=P(n.worktreeBranch),s=P(n.originChannel),a=typeof n.originThreadId=="string"||typeof n.originThreadId=="number"?n.originThreadId:void 0,l=P(n.originSessionKey),d=Ca(n.route);if(!d)return;let u=Z({route:d,originChannel:s,originThreadId:a,originSessionKey:l});if(!u||o&&!i)return;let f=P(n.harness),g=Qp(n.backendRef,f,e),S=Yp(n.worktreeLifecycle)??Jp(n),y=P(n.completionWakeSucceededAt),c=P(n.completionWakeSkippedAt),h=n.completionWakeSummaryRequired===!0&&!c?!0:void 0;return{sessionId:P(n.sessionId),harnessSessionId:e,backendRef:g,name:je(n.name,e),prompt:je(n.prompt),workdir:je(n.workdir,"(unknown)"),model:P(n.model),reasoningEffort:ba(n.reasoningEffort),fastMode:n.fastMode===!0?!0:void 0,createdAt:q(n.createdAt),completedAt:q(n.completedAt),status:t,lifecycle:r?"suspended":Ta(n.lifecycle),approvalState:Np(n.approvalState),worktreeState:Op(n.worktreeState),runtimeState:r?"stopped":xa(n.runtimeState),runtimeRecovery:r?Lp(n):Fp(n.runtimeRecovery),taskFlowMirror:Mp(n.taskFlowMirror),deliveryState:Vp(n.deliveryState),notificationDedupe:Gp(n.notificationDedupe),completionSummaryDedupe:jp(n.completionSummaryDedupe),completionWakeIssuedAt:P(n.completionWakeIssuedAt),completionWakeSucceededAt:y,completionWakeFailedAt:P(n.completionWakeFailedAt),completionWakeSkippedAt:c,completionWakeSkipReason:P(n.completionWakeSkipReason),completionWakeSummaryRequired:h,killReason:Ep(n.killReason),costUsd:typeof n.costUsd=="number"&&Number.isFinite(n.costUsd)?n.costUsd:0,originAgentId:P(n.originAgentId),originChannel:s,originThreadId:a,originSessionKey:l,route:u,outputPath:P(n.outputPath),harness:f,resumedFromSessionName:P(n.resumedFromSessionName),goalTaskId:P(n.goalTaskId),requestedPermissionMode:Do(n.requestedPermissionMode),currentPermissionMode:Do(n.currentPermissionMode),approvalExecutionState:zp(n.approvalExecutionState),approvalRationale:P(n.approvalRationale),planModeApproved:n.planModeApproved===!0,pendingPlanApproval:n.pendingPlanApproval===!0,planApprovalContext:Dp(n.planApprovalContext),planDecisionVersion:q(n.planDecisionVersion),actionablePlanDecisionVersion:q(n.actionablePlanDecisionVersion),canonicalPlanPromptVersion:q(n.canonicalPlanPromptVersion),approvalPromptRequiredVersion:q(n.approvalPromptRequiredVersion),approvalPromptVersion:q(n.approvalPromptVersion),approvalPromptStatus:Bp(n.approvalPromptStatus),approvalPromptTransport:Kp(n.approvalPromptTransport),approvalPromptMessageKind:qp(n.approvalPromptMessageKind),approvalPromptLastAttemptAt:P(n.approvalPromptLastAttemptAt),approvalPromptDeliveredAt:P(n.approvalPromptDeliveredAt),approvalPromptFailedAt:P(n.approvalPromptFailedAt),planApproval:Ra(n.planApproval),codexApprovalPolicy:_p(n.codexApprovalPolicy),worktreePath:o,worktreeBranch:i,worktreeStrategy:Aa(n.worktreeStrategy),repoIntegrationPolicy:$o(n.repoIntegrationPolicy),repoIntegrationPolicySource:$p(n.repoIntegrationPolicySource),repoProvider:Ia(n.repoProvider),worktreeMerged:typeof n.worktreeMerged=="boolean"?n.worktreeMerged:void 0,worktreeMergedAt:P(n.worktreeMergedAt),worktreePrUrl:P(n.worktreePrUrl),worktreePrNumber:q(n.worktreePrNumber),pendingWorktreeDecisionSince:P(n.pendingWorktreeDecisionSince),lastWorktreeReminderAt:P(n.lastWorktreeReminderAt),worktreeBaseBranch:P(n.worktreeBaseBranch),worktreeParentBranch:P(n.worktreeParentBranch),worktreePrTargetRepo:P(n.worktreePrTargetRepo),autoMergeParentSessionId:P(n.autoMergeParentSessionId),autoMergeConflictResolutionAttemptCount:q(n.autoMergeConflictResolutionAttemptCount),autoMergeResolverSessionId:P(n.autoMergeResolverSessionId),worktreePushRemote:P(n.worktreePushRemote),worktreeDecisionSnoozedUntil:P(n.worktreeDecisionSnoozedUntil),worktreeDisposition:n.worktreeDisposition==="active"||n.worktreeDisposition==="pr-opened"||n.worktreeDisposition==="merged"||n.worktreeDisposition==="dismissed"||n.worktreeDisposition==="no-change-cleaned"?n.worktreeDisposition:void 0,worktreeRemoteOutcome:n.worktreeRemoteOutcome==="pr-opened"||n.worktreeRemoteOutcome==="pr-updated"?n.worktreeRemoteOutcome:void 0,worktreeDismissedAt:P(n.worktreeDismissedAt),worktreeLifecycle:S,resumable:r?!0:n.resumable===!0}}function _a(n){if(!ae(n))return;let e=P(n.key),t=P(n.repoRoot),r=$o(n.policy),o=Ia(n.provider)??"unsupported",i=P(n.createdAt),s=P(n.updatedAt),a=n.source==="seeded"?"seeded":"stored";if(!(!e||!t||!r||!i||!s)&&!(!Number.isFinite(Date.parse(i))||!Number.isFinite(Date.parse(s))))return{key:e,policy:r,repoRoot:t,remoteUrl:P(n.remoteUrl),provider:o,createdAt:i,updatedAt:s,source:a}}function Da(n){if(!ae(n))return;let e=Hp(n.kind),t=je(n.id),r=je(n.sessionId),o=q(n.createdAt);if(!(!t||!r||!e||o==null))return{id:t,sessionId:r,kind:e,createdAt:o,planDecisionVersion:q(n.planDecisionVersion),expiresAt:q(n.expiresAt),consumedAt:q(n.consumedAt),optionIndex:q(n.optionIndex),pendingInputRequestId:P(n.pendingInputRequestId),pendingInputQuestionId:P(n.pendingInputQuestionId),label:P(n.label),targetUrl:P(n.targetUrl),route:Ca(n.route),launchName:P(n.launchName),launchPrompt:P(n.launchPrompt),launchWorkdir:P(n.launchWorkdir),launchModel:P(n.launchModel),launchReasoningEffort:ba(n.launchReasoningEffort),launchFastMode:n.launchFastMode===!0?!0:void 0,launchSystemPrompt:P(n.launchSystemPrompt),launchAllowedTools:Array.isArray(n.launchAllowedTools)?n.launchAllowedTools.filter(i=>typeof i=="string"):void 0,launchResumeSessionId:P(n.launchResumeSessionId),launchResumedFromSessionName:P(n.launchResumedFromSessionName),launchResumeWorktreeFrom:P(n.launchResumeWorktreeFrom),launchSessionIdOverride:P(n.launchSessionIdOverride),launchClearedPersistedCodexResume:n.launchClearedPersistedCodexResume===!0?!0:void 0,launchForkSession:typeof n.launchForkSession=="boolean"?n.launchForkSession:void 0,launchForceNewSession:typeof n.launchForceNewSession=="boolean"?n.launchForceNewSession:void 0,launchPermissionMode:Do(n.launchPermissionMode),launchPlanApproval:Ra(n.launchPlanApproval),launchHarness:P(n.launchHarness),launchWorktreeStrategy:Aa(n.launchWorktreeStrategy),launchWorktreeBaseBranch:P(n.launchWorktreeBaseBranch),launchWorktreePrTargetRepo:P(n.launchWorktreePrTargetRepo),launchOriginAgentId:P(n.launchOriginAgentId),repoPolicy:$o(n.repoPolicy),repoPolicyWorkdir:P(n.repoPolicyWorkdir)}}function Jn(n){if(!n.backendRef?.kind||!n.backendRef.conversationId)throw new Error(`Persisted session ${n.harnessSessionId} is missing required backend ref metadata.`);if(!n.route?.provider||!n.route.target)throw new Error(`Persisted session ${n.harnessSessionId} is missing required route metadata.`);if(n.worktreePath&&!n.worktreeBranch)throw new Error(`Persisted session ${n.harnessSessionId} is missing required worktreeBranch metadata.`)}function ht(n){return!!n&&typeof n=="object"}function Eo(n){return n instanceof Error?n.message:String(n)}function om(n,e){JSON.stringify({component:"SessionStore",event:n,at:new Date().toISOString(),...e})}function im(n){return ht(n)?{backendRefKind:typeof n.kind=="string"?n.kind:void 0,hasBackendConversationId:typeof n.conversationId=="string"&&n.conversationId.length>0,hasBackendRunId:typeof n.runId=="string"&&n.runId.length>0,hasBackendWorktreeId:typeof n.worktreeId=="string"&&n.worktreeId.length>0,hasBackendWorktreePath:typeof n.worktreePath=="string"&&n.worktreePath.length>0}:{}}function La(n,e,t=Date.now()){let r=`${n}.${e}-${t}`;for(let o=0;o<100;o+=1){let i=o===0?"":`-${o}`,s=`${r}${i}.json`;if(!$a(s))return s}}function No(){let n=nm();return tm(n).filter(e=>e.startsWith("openclaw-agent-")&&e.endsWith(".txt")).map(e=>Fa(n,e))}function Ba(n){let e=n.OPENCLAW_CODE_AGENT_SESSIONS_PATH?.trim();return e||Fa(Qn(n),"code-agent-sessions.json")}function Ka(n,e,t,r=[]){try{Zp(rm(n),{recursive:!0});let o=n+".tmp";Wa(o,JSON.stringify({schemaVersion:Yn,sessions:e,actionTokens:t,repoPolicies:r},null,2),"utf-8"),Ea(o,n)}catch(o){`${Eo(o)}`}}function sm(n,e){try{if(!$a(n))return!1;let t=La(n,"legacy");return t?(Ea(n,t),`${e}${t}`,!0):!1}catch(t){return`${Eo(t)}`,!1}}var am={archiveLegacySessionIndex:sm};function lm(n,e){try{if(e.length===0)return;let t=La(n,"codex-sdk-legacy");if(!t)return;Wa(t,JSON.stringify(e,null,2),"utf-8"),`${e.length}${t}`}catch(t){`${Eo(t)}`}}function qa(n,e,t=[]){try{let r=new Set(t);for(let o of No())if(!r.has(o))try{let i=Na(o).mtimeMs;n-i>e&&Oa(o)}catch{}}catch{}}function Va(n,e,t=[]){try{let r=new Set(t),o;for(let i of No())if(!r.has(i))try{let s=Na(i).mtimeMs+e;if(s<=n)return n;o=o==null?s:Math.min(o,s)}catch{}return o}catch{return}}function Ua(n){try{let e=new Set(n);for(let t of No())if(!e.has(t))try{Oa(t)}catch{}}catch{}}function Ga(n){let{indexPath:e,clearAll:t,indexPersistedEntry:r,setActionToken:o,setRepoPolicy:i,purgeExpiredActionTokens:s,saveIndex:a}=n,l=d=>am.archiveLegacySessionIndex(e,d)?(t(),!0):!1;try{let d=em(e,"utf-8"),u=JSON.parse(d);if(Array.isArray(u)){if(!l("legacy array store"))return;a();return}if(!ht(u)||u.schemaVersion!==Yn&&u.schemaVersion!==6&&u.schemaVersion!==4){if(!l(`schema mismatch (expected v${Yn})`))return;a();return}let f=(R,m)=>{if(!Object.prototype.hasOwnProperty.call(u,R))return[];let w=u[R];if(Array.isArray(w))return w;l(m)&&a()},g=f("sessions","invalid sessions collection");if(g===void 0)return;let S=[],y=[],c=!1;for(let R of g){if(ht(R)&&R.harness==="codex"){let w=ht(R.backendRef)?R.backendRef:void 0;if((typeof w?.kind=="string"?w.kind:void 0)!=="codex-app-server"){S.push(R);continue}}let m=Ma(R);if(!m){if(!l("invalid v4 session entry"))return;a();return}ht(R)&&R.status==="running"&&(c=!0,om("session.recovered_from_running_persisted_row",{sessionId:typeof R.sessionId=="string"?R.sessionId:void 0,hasHarnessSessionId:typeof R.harnessSessionId=="string"&&R.harnessSessionId.length>0,...im(R.backendRef),rawStatus:R.status,rawLifecycle:R.lifecycle,rawRuntimeState:R.runtimeState,normalizedStatus:m.status,normalizedLifecycle:m.lifecycle,normalizedRuntimeState:m.runtimeState,reason:m.runtimeRecovery?.reason})),y.push(m)}S.length>0&&lm(e,S);let h=f("actionTokens","invalid action token collection");if(h===void 0)return;let v=[];for(let R of h){let m=Da(R);if(!m){if(!l("invalid v4 action token"))return;a();return}v.push(m)}let b=f("repoPolicies","invalid repo policy collection");if(b===void 0)return;let A=[],I=!1;for(let R of b){let m=_a(R);if(!m){I=!0;continue}A.push(m)}for(let R of y)r(R);for(let R of v)o(R);for(let R of A)i(R);(S.length>0||c)&&a(),I&&a(),s()}catch(d){if(d.code==="ENOENT"||!l("corrupt or unreadable"))return;a()}}var pm=new Set(["completed","failed","killed"]),Oo=1440*60*1e3;function mm(n){return n instanceof Error?n.message:String(n)}var fm={statSync:um};function gm(n){try{return fm.statSync(n).isDirectory()}catch(e){let t=e.code;return t!=="ENOENT"&&t!=="ENOTDIR"}}var Xn=class{persisted=new Map;repoPolicies=new Map;idIndex=new Map;nameIndex=new Map;backendIdIndex=new Map;actionTokens;actionTokenStore;indexPath;queries;constructor(e={}){let t=e.env??process.env;this.indexPath=e.indexPath??Ba(t),this.actionTokenStore=new zn(()=>this.saveIndex(),Oo),this.actionTokens=this.actionTokenStore.tokens,this.queries=new Hn({persisted:this.persisted,idIndex:this.idIndex,nameIndex:this.nameIndex,backendIdIndex:this.backendIdIndex}),t.OPENCLAW_DEBUG_SESSION_STORE==="1"&&`${this.indexPath}`,this.loadIndex()}loadIndex(){Ga({indexPath:this.indexPath,clearAll:()=>{this.persisted.clear(),this.repoPolicies.clear(),this.idIndex.clear(),this.nameIndex.clear(),this.backendIdIndex.clear(),this.actionTokenStore.clear()},indexPersistedEntry:e=>this.indexPersistedEntry(e),setActionToken:e=>{this.actionTokens.set(e.id,e)},setRepoPolicy:e=>{this.repoPolicies.set(e.key,e)},purgeExpiredActionTokens:()=>this.actionTokenStore.purgeExpiredActionTokens(),saveIndex:()=>this.saveIndex()})}saveIndex(){Ka(this.indexPath,[...this.persisted.values()],this.actionTokenStore.listForPersistence(),[...this.repoPolicies.values()])}assertPersistedEntry(e){Jn(e)}getEntryStorageKey(e){return e.harnessSessionId}buildPersistedBackendRef(e){let t=Qo(e),r=t==="codex"?"codex-app-server":t==="opencode"?"opencode-server":"claude-code";return e.backendRef??{kind:e.backendKind??r,conversationId:e.harnessSessionId}}getSessionApprovalSnapshot(e){if(typeof e.approvalSnapshot=="function")return e.approvalSnapshot();let t=typeof e.controlStateSnapshot=="function"?e.controlStateSnapshot():{planModeApproved:!1};return{requestedPermissionMode:e.requestedPermissionMode,currentPermissionMode:e.currentPermissionMode,approvalExecutionState:e.approvalExecutionState,approvalRationale:e.approvalRationale,planModeApproved:t.planModeApproved,pendingPlanApproval:e.pendingPlanApproval,planApprovalContext:e.planApprovalContext,planDecisionVersion:e.planDecisionVersion,actionablePlanDecisionVersion:e.actionablePlanDecisionVersion,canonicalPlanPromptVersion:e.canonicalPlanPromptVersion,approvalPromptRequiredVersion:e.approvalPromptRequiredVersion,approvalPromptVersion:e.approvalPromptVersion,approvalPromptStatus:e.approvalPromptStatus,approvalPromptTransport:e.approvalPromptTransport,approvalPromptMessageKind:e.approvalPromptMessageKind,approvalPromptLastAttemptAt:e.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:e.approvalPromptDeliveredAt,approvalPromptFailedAt:e.approvalPromptFailedAt,planApproval:e.planApproval,codexApprovalPolicy:e.codexApprovalPolicy}}getSessionRoutingSnapshot(e){return typeof e.routingSnapshot=="function"?e.routingSnapshot():{route:e.route,originAgentId:e.originAgentId,originChannel:e.originChannel,originThreadId:e.originThreadId,originSessionKey:e.originSessionKey}}getSessionWorktreeSnapshot(e){return typeof e.worktreeSnapshot=="function"?e.worktreeSnapshot():{worktreePath:e.worktreePath,worktreeBranch:e.worktreeBranch,worktreeStrategy:e.worktreeStrategy,repoIntegrationPolicy:e.repoIntegrationPolicy,repoIntegrationPolicySource:e.repoIntegrationPolicySource,repoProvider:e.repoProvider,worktreeBaseBranch:e.worktreeBaseBranch,worktreeParentBranch:e.worktreeParentBranch,worktreePrTargetRepo:e.worktreePrTargetRepo,autoMergeParentSessionId:e.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:e.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:e.autoMergeResolverSessionId,worktreeLifecycle:e.worktreeLifecycle}}indexPersistedEntry(e){let t=this.getEntryStorageKey(e);if(e.sessionId){let o=this.idIndex.get(e.sessionId);if(o&&o!==t){let i=this.persisted.get(o);i&&this.removePersistedIndexes(i)}}this.persisted.set(t,e),e.sessionId&&this.idIndex.set(e.sessionId,t),e.name&&this.nameIndex.set(e.name,t);let r=C(e);r&&this.backendIdIndex.set(r,t)}removePersistedIndexes(e){let t=this.getEntryStorageKey(e);this.persisted.delete(t);for(let[r,o]of this.idIndex)o===t&&this.idIndex.delete(r);for(let[r,o]of this.nameIndex)o===t&&this.nameIndex.delete(r);for(let[r,o]of this.backendIdIndex)o===t&&this.backendIdIndex.delete(r)}markRunning(e){if(!e.harnessSessionId)return;let t=this.getSessionApprovalSnapshot(e),r=this.getSessionRoutingSnapshot(e),o=this.getSessionWorktreeSnapshot(e),i=Z({route:r.route,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey});if(!i)throw new Error(`Cannot persist running session ${e.id}: canonical lifecycle route is missing.`);let s={sessionId:e.id,harnessSessionId:e.harnessSessionId,backendRef:this.buildPersistedBackendRef(e),name:e.name,prompt:e.prompt,workdir:e.originalWorkdir??e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,createdAt:e.startedAt,status:"running",lifecycle:e.lifecycle,approvalState:e.approvalState,worktreeState:e.worktreeState,runtimeState:e.runtimeState,taskFlowMirror:e.taskFlowMirror,deliveryState:e.deliveryState,notificationDedupe:this.getExistingNotificationDedupe(e),completionSummaryDedupe:this.getExistingCompletionSummaryDedupe(e),costUsd:0,originAgentId:r.originAgentId,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey,route:i,outputPath:ve(e.id),harness:e.harnessName,resumedFromSessionName:e.resumedFromSessionName,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,approvalRationale:t.approvalRationale,planModeApproved:t.planModeApproved,pendingPlanApproval:t.pendingPlanApproval,planApprovalContext:t.planApprovalContext,planDecisionVersion:t.planDecisionVersion,actionablePlanDecisionVersion:t.actionablePlanDecisionVersion,canonicalPlanPromptVersion:t.canonicalPlanPromptVersion,approvalPromptRequiredVersion:t.approvalPromptRequiredVersion,approvalPromptVersion:t.approvalPromptVersion,approvalPromptStatus:t.approvalPromptStatus,approvalPromptTransport:t.approvalPromptTransport,approvalPromptMessageKind:t.approvalPromptMessageKind,approvalPromptLastAttemptAt:t.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:t.approvalPromptDeliveredAt,approvalPromptFailedAt:t.approvalPromptFailedAt,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,repoIntegrationPolicy:o.repoIntegrationPolicy,repoIntegrationPolicySource:o.repoIntegrationPolicySource,repoProvider:o.repoProvider,worktreeBaseBranch:o.worktreeBaseBranch,worktreeParentBranch:o.worktreeParentBranch,worktreePrTargetRepo:o.worktreePrTargetRepo,autoMergeParentSessionId:o.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:o.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:o.autoMergeResolverSessionId,worktreeLifecycle:o.worktreeLifecycle,resumable:e.isExplicitlyResumable};Jn(s),this.indexPersistedEntry(s),this.saveIndex()}hasRecordedSession(e){return this.queries.hasRecordedSession(e)}persistTerminal(e){if(!e.harnessSessionId)return;let t=this.getSessionApprovalSnapshot(e),r=this.getSessionRoutingSnapshot(e),o=this.getSessionWorktreeSnapshot(e),i=Z({route:r.route,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey});if(!i)throw new Error(`Cannot persist terminal session ${e.id}: canonical lifecycle route is missing.`);let s;try{let l=ve(e.id);if(dm(l))s=l;else{let d=e.getOutput().join(`
|
|
196
196
|
`);d.length>0&&(cm(l,d,"utf-8"),s=l)}}catch(l){`${e.id}${mm(l)}`}let a={sessionId:e.id,harnessSessionId:e.harnessSessionId,backendRef:this.buildPersistedBackendRef(e),name:e.name,prompt:e.prompt,workdir:e.originalWorkdir??e.workdir,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,createdAt:e.startedAt,completedAt:e.completedAt,status:e.status,lifecycle:e.lifecycle,approvalState:e.approvalState,worktreeState:e.worktreeState,runtimeState:e.runtimeState,taskFlowMirror:e.taskFlowMirror,deliveryState:e.deliveryState,notificationDedupe:this.getExistingNotificationDedupe(e),completionSummaryDedupe:this.getExistingCompletionSummaryDedupe(e),killReason:e.killReason,costUsd:e.costUsd,originAgentId:r.originAgentId,originChannel:r.originChannel,originThreadId:r.originThreadId,originSessionKey:r.originSessionKey,route:i,outputPath:s,harness:e.harnessName,resumedFromSessionName:e.resumedFromSessionName,goalTaskId:e.goalTaskId,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,approvalRationale:t.approvalRationale,planModeApproved:t.planModeApproved,pendingPlanApproval:t.pendingPlanApproval,planApprovalContext:t.planApprovalContext,planDecisionVersion:t.planDecisionVersion,actionablePlanDecisionVersion:t.actionablePlanDecisionVersion,canonicalPlanPromptVersion:t.canonicalPlanPromptVersion,approvalPromptRequiredVersion:t.approvalPromptRequiredVersion,approvalPromptVersion:t.approvalPromptVersion,approvalPromptStatus:t.approvalPromptStatus,approvalPromptTransport:t.approvalPromptTransport,approvalPromptMessageKind:t.approvalPromptMessageKind,approvalPromptLastAttemptAt:t.approvalPromptLastAttemptAt,approvalPromptDeliveredAt:t.approvalPromptDeliveredAt,approvalPromptFailedAt:t.approvalPromptFailedAt,planApproval:t.planApproval,codexApprovalPolicy:t.codexApprovalPolicy,worktreePath:o.worktreePath,worktreeBranch:o.worktreeBranch,worktreeStrategy:o.worktreeStrategy,worktreeBaseBranch:o.worktreeBaseBranch,worktreeParentBranch:o.worktreeParentBranch,worktreePrTargetRepo:o.worktreePrTargetRepo,autoMergeParentSessionId:o.autoMergeParentSessionId,autoMergeConflictResolutionAttemptCount:o.autoMergeConflictResolutionAttemptCount,autoMergeResolverSessionId:o.autoMergeResolverSessionId,worktreeLifecycle:o.worktreeLifecycle,resumable:e.isExplicitlyResumable};Jn(a),this.indexPersistedEntry(a),this.saveIndex()}getExistingNotificationDedupe(e){return this.getPersistedSession(e.id)?.notificationDedupe??(e.harnessSessionId?this.getPersistedSession(e.harnessSessionId)?.notificationDedupe:void 0)??(C(e)?this.getPersistedSession(C(e))?.notificationDedupe:void 0)}getExistingCompletionSummaryDedupe(e){return this.getPersistedSession(e.id)?.completionSummaryDedupe??(e.harnessSessionId?this.getPersistedSession(e.harnessSessionId)?.completionSummaryDedupe:void 0)??(C(e)?this.getPersistedSession(C(e))?.completionSummaryDedupe:void 0)}getLatestPersistedByName(e){return this.queries.getLatestPersistedByName(e)}resolveBackendConversationId(e,t){return this.queries.resolveBackendConversationId(e,t)}resolveHarnessSessionId(e,t){return this.queries.resolveHarnessSessionId(e,t)}getPersistedSession(e){return this.queries.getPersistedSession(e)}replacePersistedSession(e){let t=e.sessionId?this.getPersistedSession(e.sessionId):void 0;t&&this.removePersistedIndexes(t),this.indexPersistedEntry(e),this.saveIndex()}listPersistedSessions(){return this.queries.listPersistedSessions()}getRepoPolicy(e){return this.repoPolicies.get(e)}listRepoPolicies(){return[...this.repoPolicies.values()].sort((e,t)=>e.repoRoot.localeCompare(t.repoRoot)||e.key.localeCompare(t.key))}setRepoPolicy(e){let t=this.repoPolicies.get(e.key),r={...e,createdAt:t?.createdAt??e.createdAt,updatedAt:new Date().toISOString(),source:"stored"};return this.repoPolicies.set(r.key,r),this.saveIndex(),r}updateRepoPolicy(e,t){let r=this.repoPolicies.get(e);if(r)return this.setRepoPolicy({...r,policy:t})}resetRepoPolicy(e){let t=this.repoPolicies.delete(e);return t&&this.saveIndex(),t}removeRepoPolicies(e){let t=[];for(let r of e){let o=this.repoPolicies.get(r);o&&(this.repoPolicies.delete(r),t.push(o))}return t.length>0&&this.saveIndex(),t.sort((r,o)=>r.repoRoot.localeCompare(o.repoRoot)||r.key.localeCompare(o.key))}cleanupRepoPolicies(){let e=[];for(let[t,r]of this.repoPolicies)gm(r.repoRoot)||(this.repoPolicies.delete(t),e.push(r));return e.length>0&&this.saveIndex(),e.sort((t,r)=>t.repoRoot.localeCompare(r.repoRoot)||t.key.localeCompare(r.key))}cleanupTmpOutputFiles(e){this.actionTokenStore.purgeExpiredActionTokens(e),qa(e,Oo,this.getReferencedOutputPaths())}getNextTmpOutputCleanupAt(e){return Va(e,Oo,this.getReferencedOutputPaths())}evictOldestPersisted(e){let t=this.listPersistedSessions();if(t.length<=e)return[];let r=t.slice(e);for(let o of r)this.removePersistedIndexes(o);return this.saveIndex(),r}shouldGcActiveSession(e,t,r){return!e.completedAt||!pm.has(e.status)?!1:t-e.completedAt>r}getActionToken(e){return this.actionTokenStore.getActionToken(e)}consumeActionToken(e){return this.actionTokenStore.consumeActionToken(e)}deleteActionTokensForSession(e){this.actionTokenStore.deleteActionTokensForSession(e)}purgeExpiredActionTokens(e=Date.now()){return this.actionTokenStore.purgeExpiredActionTokens(e)}getNextActionTokenExpiry(){return this.actionTokenStore.nextExpiryAt()}onActionTokensChanged(e){this.actionTokenStore.setAfterChangeListener(e)}hasOutputPathReference(e){for(let t of this.persisted.values())if(t.outputPath===e)return!0;return!1}getReferencedOutputPaths(){return[...new Set([...this.persisted.values()].map(e=>e.outputPath).filter(e=>typeof e=="string"&&e.length>0))]}cleanupOrphanOutputFiles(){Ua(this.getReferencedOutputPaths())}};var hm=new Set(["completed","failed","killed"]),Zn=class{metrics={totalCostUsd:0,costPerDay:new Map,sessionsByStatus:{completed:0,failed:0,killed:0},totalLaunched:0,totalDurationMs:0,sessionsWithDuration:0,mostExpensive:null};incrementLaunched(){this.metrics.totalLaunched++}recordSession(e){let t=e.costUsd??0,r=e.status;this.metrics.totalCostUsd+=t;let o=new Date(e.completedAt??e.startedAt).toISOString().slice(0,10);if(this.metrics.costPerDay.set(o,(this.metrics.costPerDay.get(o)??0)+t),hm.has(r)&&this.metrics.sessionsByStatus[r]++,e.completedAt){let i=e.completedAt-e.startedAt;this.metrics.totalDurationMs+=i,this.metrics.sessionsWithDuration++}(!this.metrics.mostExpensive||t>this.metrics.mostExpensive.costUsd)&&(this.metrics.mostExpensive={id:e.id,name:e.name,costUsd:t,prompt:G(e.prompt,80)})}getMetrics(){return{totalCostUsd:this.metrics.totalCostUsd,costPerDay:new Map(this.metrics.costPerDay),sessionsByStatus:{...this.metrics.sessionsByStatus},totalLaunched:this.metrics.totalLaunched,totalDurationMs:this.metrics.totalDurationMs,sessionsWithDuration:this.metrics.sessionsWithDuration,mostExpensive:this.metrics.mostExpensive?{...this.metrics.mostExpensive}:null}}};import*as ja from"child_process";var ze=class{tails=new Map;enqueue(e,t,r){let o=this.tails.get(e);o!==void 0&&r?.();let s=(o?.catch(()=>{})??Promise.resolve()).then(()=>t()),a=s.catch(()=>{});return this.tails.set(e,a),a.finally(()=>{this.tails.get(e)===a&&this.tails.delete(e)}),s}clear(){this.tails.clear()}};var Wo=3e4,ym=2e3,Sm=2e4,j=4;function yt(n){return n instanceof Error?n.message:String(n)}function km(){return new Error(`Dispatch timed out after ${Wo}ms`)}function vm(n){if(!(n instanceof Error))return!1;let e=n;return e.killed===!0&&e.signal==="SIGKILL"}var Pm={execFile:ja.execFile},er=class{pendingRetryTimers=new Map;orderedDispatches=new ze;disposed=!1;clearPendingRetries(){for(let e of this.pendingRetryTimers.values())for(let t of e)clearTimeout(t.timer),t.onCleared?.();this.pendingRetryTimers.clear()}clearRetryTimersForSession(e){let t=this.pendingRetryTimers.get(e);if(t){for(let r of t)clearTimeout(r.timer),r.onCleared?.();this.pendingRetryTimers.delete(e)}}dispose(){this.disposed=!0,this.clearPendingRetries(),this.orderedDispatches.clear()}execute(e,t,r=1){if(!this.disposed){if(r===1&&t.orderingKey){this.enqueueOrderedDispatch(t.orderingKey,o=>this.executeNow(e,t,o,r));return}this.executeNow(e,t,void 0,r)}}executePromise(e,t,r=1){if(!this.disposed){if(r===1&&t.orderingKey){this.enqueueOrderedDispatch(t.orderingKey,o=>this.executePromiseNow(e,t,o,r));return}this.executePromiseNow(e,t,void 0,r)}}executeNow(e,t,r,o=1){if(this.disposed||t.shouldContinue?.()===!1){r?.();return}let i=Date.now();o===1&&t.onStarted?.(),this.log("info","dispatch_started",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j}),Pm.execFile("openclaw",e,{timeout:Wo,killSignal:"SIGKILL"},(s,a,l)=>{if(this.disposed){r?.();return}let d=Date.now()-i;if(!s){let y=t.successValidator?.(a??"");if(y?.outcome==="failure"){this.log("error","dispatch_success_validation_failed",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:d,error:y.reason,terminal:!0}),t.onFinalFailure?.(),r?.();return}if(y?.outcome==="skipped"){this.log("info","dispatch_skipped",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:d,reason:y.reason}),t.shouldContinue?.()!==!1&&t.onSkipped?.(y.reason),r?.();return}this.log("info","dispatch_succeeded",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:d}),t.shouldContinue?.()!==!1&&t.onSuccess?.(),r?.();return}let u=l?.trim()?` | stderr: ${l.trim()}`:"";if(t.shouldContinue?.()===!1){r?.();return}if(t.target==="message.send"&&vm(s)){this.log("error","dispatch_failed",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:d,error:`${yt(s)}${u}`,terminal:!0,ambiguousResult:!0}),t.onAmbiguousResult?.(),r?.();return}if(o>=j||t.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:d,error:`${yt(s)}${u}`,terminal:!0}),t.onFinalFailure?.(),r?.();return}let g=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:d,retryDelayMs:g,error:`${yt(s)}${u}`});let S={timer:setTimeout(()=>{let y=this.pendingRetryTimers.get(t.sessionId);if(y&&(y.delete(S),y.size===0&&this.pendingRetryTimers.delete(t.sessionId)),t.shouldContinue?.()===!1){r?.();return}this.executeNow(e,t,r,o+1)},g),onCleared:r};S.timer.unref?.(),this.pendingRetryTimers.has(t.sessionId)||this.pendingRetryTimers.set(t.sessionId,new Set),this.pendingRetryTimers.get(t.sessionId).add(S)})}executePromiseNow(e,t,r,o=1){if(this.disposed||t.shouldContinue?.()===!1){r?.();return}let i=Date.now();o===1&&t.onStarted?.(),this.log("info","dispatch_started",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j}),this.executePromiseWithTimeout(e).then(()=>{if(this.disposed){r?.();return}let s=Date.now()-i;this.log("info","dispatch_succeeded",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:s}),t.shouldContinue?.()!==!1&&t.onSuccess?.(),r?.()}).catch(s=>{if(this.disposed){r?.();return}let a=Date.now()-i;if(t.shouldContinue?.()===!1){r?.();return}if(o>=j||t.terminalOnFailure===!0){this.log("error","dispatch_failed",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:a,error:yt(s),terminal:!0,...t.terminalOnFailure===!0&&o<j?{terminalReason:"non_retryable"}:{}}),t.onFinalFailure?.(),r?.();return}let l=this.retryDelayMs(o);this.log("error","dispatch_retry_scheduled",{label:t.label,sessionId:t.sessionId,target:t.target,phase:t.phase,messageKind:t.messageKind,route:t.routeSummary,...t.dispatchContext,attempt:o,maxAttempts:j,elapsedMs:a,retryDelayMs:l,error:yt(s)});let d={timer:setTimeout(()=>{let u=this.pendingRetryTimers.get(t.sessionId);if(u&&(u.delete(d),u.size===0&&this.pendingRetryTimers.delete(t.sessionId)),t.shouldContinue?.()===!1){r?.();return}this.executePromiseNow(e,t,r,o+1)},l),onCleared:r};d.timer.unref?.(),this.pendingRetryTimers.has(t.sessionId)||this.pendingRetryTimers.set(t.sessionId,new Set),this.pendingRetryTimers.get(t.sessionId).add(d)})}executePromiseWithTimeout(e){return new Promise((t,r)=>{let o=!1,i=setTimeout(()=>{o||(o=!0,r(km()))},Wo);i.unref?.(),Promise.resolve().then(e).then(()=>{o||(o=!0,clearTimeout(i),t())}).catch(s=>{o||(o=!0,clearTimeout(i),r(s))})})}retryDelayMs(e){let t=Math.max(0,e-1),r=ym*2**t;return Math.min(r,Sm)}enqueueOrderedDispatch(e,t){this.orderedDispatches.enqueue(e,async()=>{this.disposed||await new Promise(r=>{let o=!1;t(()=>{o||(o=!0,r())})})})}log(e,t,r){let o=`[WakeDispatcher] ${JSON.stringify({event:t,...r})}`;if(e==="error"){console.error(o);return}}};var tr=class{resolve(e){let t=le(e);if(!(!t?.provider||!t.target))return{channel:t.provider,target:t.target,accountId:t.accountId,threadId:t.threadId,sessionKey:t.sessionKey}}summary(e){if(!e)return"system";let t=e.accountId?`|${e.accountId}`:"",r=e.threadId?`#${e.threadId}`:"";return`${e.channel}${t}|${e.target}${r}`}};import{randomUUID as wm}from"crypto";var nr=class{constructor(e={}){}buildChatSendArgs(e,t,r,o=wm()){return["gateway","call","chat.send","--expect-final","--timeout","30000","--params",JSON.stringify({sessionKey:e,message:t,deliver:r,idempotencyKey:o})]}buildDirectNotificationArgs(e,t,r){let o=jt(r),i=["message","send","--channel",e.channel,"--target",e.target,"--message",t];return e.accountId&&i.push("--account",e.accountId),e.threadId&&i.push("--thread-id",e.threadId),o&&i.push("--presentation",JSON.stringify(o)),i}buildSystemEventArgs(e){return["system","event","--text",e,"--mode","now"]}};function bm(n){let e=Rm(n).trim();return e?/^NO_REPLY$/i.test(e)?{outcome:"failure",reason:"completion follow-up wake ended with NO_REPLY"}:{outcome:"success"}:{outcome:"failure",reason:"completion follow-up wake produced no final response"}}function Rm(n){let e=n.trim();if(!e)return"";try{return Fo(JSON.parse(e)).trim()}catch{return e}}function Fo(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.map(r=>Fo(r)).filter(Boolean).join(`
|
|
197
197
|
`);if(!n||typeof n!="object")return"";let e=n,t=["final","finalResponse","final_response","assistantFinal","assistant_final","response","text","content"];for(let r of t){let o=e[r];if(typeof o=="string"&&o.trim())return o}for(let r of["result","message","data"]){let o=Fo(e[r]);if(o.trim())return o}return""}var rr=class{routes=new tr;transport;directNotifications;executor=new er;constructor(e={}){this.transport=e.transport??new nr(e.transportOptions),this.directNotifications=e.directNotifications===void 0?new We:e.directNotifications}clearPendingRetries(){this.executor.clearPendingRetries()}clearRetryTimersForSession(e){this.executor.clearRetryTimersForSession(e)}dispose(){this.executor.dispose()}buildDispatchContext(e){let t=e.buttons??[],r=t.flat();return{transportRoute:e.routeSummary,transportChannel:e.route?.channel??"system",transportTarget:e.route?.target??"system",transportAccountId:e.route?.accountId,transportThreadId:e.route?.threadId,transportSessionKey:e.route?.sessionKey,messageTextLength:e.text.length,buttonsPresent:r.length>0,buttonRows:t.length||void 0,buttonCount:r.length||void 0,buttonLabels:r.length>0?r.map(o=>o.label):void 0,maxCallbackDataLength:r.length>0?Math.max(...r.map(o=>o.callbackData.length)):void 0}}sendWake(e,t,r,o,i,s,a,l,d,u){let f=this.routes.resolve(e),g=a;if(g?.()===!1)return;let S=f?.sessionKey?.trim();if(!S){this.executor.execute(this.transport.buildSystemEventArgs(t),{label:`${r}-system`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:t}),onSuccess:s,onSkipped:d,onFinalFailure:i,successValidator:l,shouldContinue:g});return}this.executor.execute(this.transport.buildChatSendArgs(S,t,!0,u),{label:r,sessionId:e.id,target:"chat.send",phase:o,routeSummary:`session:${S}`,messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:`session:${S}`,route:f,text:t}),onSuccess:s,onSkipped:d,successValidator:l,shouldContinue:g,onFinalFailure:()=>{g?.()!==!1&&this.executor.execute(this.transport.buildSystemEventArgs(t),{label:`${r}-fallback`,sessionId:e.id,target:"system.event",phase:o,routeSummary:"system",messageKind:"wake",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:t}),onSuccess:s,onSkipped:d,onFinalFailure:i,successValidator:l,shouldContinue:g})}})}sendUserNotification(e,t,r,o,i,s,a=!1,l){if(l?.()===!1)return;let d=!!o?.some(y=>Array.isArray(y)&&y.length>0),u=this.routes.resolve(e);M("wake_notify_selected",{sessionId:e.id,sessionName:e.name,label:r,messageTextLength:t.length,requireDirectDelivery:a,hasDirectNotificationTransport:!!this.directNotifications,routeSummary:u?this.routes.summary(u):"system",channel:u?.channel,target:u?.target,accountId:u?.accountId,threadId:u?.threadId,sessionKey:u?.sessionKey,...E(o)});let f=u?`notify:${u.channel}|${u.accountId??""}|${u.target}|${u.threadId??""}`:`notify:system:${e.id}`;if(!u){if(M("wake_notify_no_direct_route",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:d,...E(o)}),a){`${r}${e.id}`,i?.();return}if(d){`${r}${e.id}`,i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(t),{label:`${r}-notify-system`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:t,buttons:o}),orderingKey:f,onSuccess:s,onFinalFailure:i,shouldContinue:l});return}let g=()=>{if(M("wake_notify_direct_failed",{sessionId:e.id,sessionName:e.name,label:r,requireDirectDelivery:a,hasInteractiveButtons:d,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...E(o)}),a){`${r}${e.id}`,i?.();return}if(d){`${r}${e.id}`,i?.();return}this.executor.execute(this.transport.buildSystemEventArgs(t),{label:`${r}-notify-fallback`,sessionId:e.id,target:"system.event",phase:"notify",routeSummary:"system",messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:"system",text:t}),orderingKey:f,onSuccess:s,onFinalFailure:i,shouldContinue:l})},S={label:`${r}-notify`,sessionId:e.id,target:"message.send",phase:"notify",routeSummary:this.routes.summary(u),messageKind:"notify",dispatchContext:this.buildDispatchContext({routeSummary:this.routes.summary(u),route:u,text:t,buttons:o}),orderingKey:f,onSuccess:s,onAmbiguousResult:g,onFinalFailure:g,terminalOnFailure:this.directNotifications?!0:void 0,shouldContinue:l};if(this.directNotifications){M("wake_notify_dispatching_direct_runtime",{sessionId:e.id,sessionName:e.name,label:r,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...E(o)}),this.executor.executePromise(()=>this.directNotifications.send(u,t,o),S);return}M("wake_notify_dispatching_cli_message_send",{sessionId:e.id,sessionName:e.name,label:r,channel:u.channel,target:u.target,accountId:u.accountId,threadId:u.threadId,sessionKey:u.sessionKey,...E(o)}),this.executor.execute(this.transport.buildDirectNotificationArgs(u,t,o),S)}sendUserNotificationSequence(e,t,r,o,i,s=!1,a){let l=t.map(u=>({text:u.text.trim(),buttons:u.buttons,requiredForSequenceSuccess:u.requiredForSequenceSuccess})).filter(u=>u.text.length>0);if(l.length===0){o?.();return}M("wake_notify_sequence_started",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:l.length,buttonChunkIndexes:l.map((u,f)=>u.buttons?.some(g=>Array.isArray(g)&&g.length>0)?f+1:void 0).filter(u=>typeof u=="number"),requireDirectDelivery:s});let d=u=>{if(a?.()===!1)return;let f=l[u];if(!f){M("wake_notify_sequence_succeeded",{sessionId:e.id,sessionName:e.name,label:r,chunkCount:l.length}),i?.();return}let g=u===0||f.requiredForSequenceSuccess===!0,S=g?o:i;M("wake_notify_sequence_chunk_selected",{sessionId:e.id,sessionName:e.name,label:r,chunkIndex:u+1,chunkCount:l.length,messageTextLength:f.text.length,failureHandler:g?"sequence-failed":"partial-success",...E(f.buttons)}),this.sendUserNotification(e,f.text,`${r}-part-${u+1}`,f.buttons,S,()=>d(u+1),s,a)};d(0)}dispatchSessionNotification(e,t){let r=t.hooks,o=t.wakeMessageOnNotifySuccess!=null||t.wakeMessageOnNotifyFailed!=null,i=t.notifyUser??(t.wakeMessage?"on-wake-fallback":"always"),s=(t.userMessages?.length?t.userMessages:t.userMessage?.trim()?[{text:t.userMessage.trim(),buttons:t.buttons}]:[]).map(u=>({text:u.text.trim(),buttons:u.buttons,requiredForSequenceSuccess:u.requiredForSequenceSuccess})).filter(u=>u.text.length>0),a=t.wakeMessage?.trim(),l=t.shouldDispatch,d=t.completionWakeSummaryRequired===!0?bm:void 0;if(o){let u=t.wakeMessageOnNotifySuccess?.trim(),f=t.wakeMessageOnNotifyFailed?.trim(),g=h=>{h&&l?.()!==!1&&(r?.onWakeStarted?.(),this.sendWake(e,h,`${t.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l,d,r?.onWakeSkipped,t.idempotencyKey))},S=h=>{if(h){if(t.deferConditionalWakeUntilNextTick===!0||t.deferConditionalWakeMs!==void 0){let v=Math.max(0,Math.floor(t.deferConditionalWakeMs??0));setTimeout(()=>g(h),v).unref?.();return}g(h)}},y=()=>{l?.()!==!1&&(r?.onNotifySucceeded?.(),u&&S(u))},c=f?()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),t.onUserNotifyFailed?.(),S(f))}:()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),t.onUserNotifyFailed?.())};if(s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,t.label,c,y,t.requireDirectUserNotification===!0,l)}else c();return}if(i==="always"&&s.length>0){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,t.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),t.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},t.requireDirectUserNotification===!0,l)}if(a&&l?.()!==!1){if(r?.onWakeStarted?.(),i==="on-wake-fallback"&&s.length>0&&!this.routes.resolve(e)?.sessionKey){if(l?.()===!1)return;r?.onNotifyStarted?.(),this.sendUserNotificationSequence(e,s,t.label,()=>{l?.()!==!1&&(r?.onNotifyFailed?.(),t.onUserNotifyFailed?.())},()=>{l?.()!==!1&&r?.onNotifySucceeded?.()},!1,l)}this.sendWake(e,a,`${t.label}-wake`,"wake",r?.onWakeFailed,r?.onWakeSucceeded,l,d,r?.onWakeSkipped,t.idempotencyKey)}}};var za=36,Ha=2,Qa="...";function Am(n){let e=Array.from(n);return e.length<=za?n:`${e.slice(0,za-Qa.length).join("")}${Qa}`}var or=class{constructor(e,t){this.actionTokens=e;this.isGitHubCliAvailable=t}actionTokens;isGitHubCliAvailable;createActionToken(e,t,r={}){return this.actionTokens.createActionToken(e,t,{expiresAt:Date.now()+10080*60*1e3,...r})}consumeActionToken(e){return this.actionTokens.consumeActionToken(e)}consumeQuestionAnswerTokens(e,t,r){return this.actionTokens.consumeQuestionAnswerTokens(e,t,r)}consumePlanDecisionTokens(e,t){return this.actionTokens.consumePlanDecisionTokens(e,t)}getActionToken(e){return this.actionTokens.getActionToken(e)}listActiveActionTokens(e){return this.actionTokens.listActiveActionTokens(e)}clearRepoPolicyChoiceTokens(e){this.actionTokens.deleteActionTokensForSessionByKind(e,"repo-policy-set")}clearPlanDecisionTokens(e,t){this.actionTokens.deletePlanDecisionTokensForSession(e,t)}makeActionButton(e,t,r,o={}){let i=this.createActionToken(e,t,{label:r,...o});return{label:r,callbackData:i.id,style:this.resolveButtonStyle(t)}}resolveButtonStyle(e){switch(e){case"plan-approve":case"worktree-create-pr":case"worktree-update-pr":case"plan-offer-start":case"repo-policy-set":return"primary";case"worktree-merge":case"session-resume":case"session-restart":case"plugin-update-install":case"plugin-update-restart":return"success";case"plugin-update-remind-later":return"secondary";case"plan-reject":case"worktree-dismiss":case"plugin-update-dismiss":return"danger";default:return"secondary"}}getWorktreeDecisionButtons(e,t,r={merge:!0,pr:!0}){if(!t)return[];let o=[],i=[];if(r.merge&&i.push(this.makeActionButton(e,"worktree-merge","Merge")),r.pr&&this.isGitHubCliAvailable())t.worktreePrUrl?(i.push(this.makeActionButton(e,"worktree-view-pr","View PR",{targetUrl:t.worktreePrUrl})),i.length>0&&o.push(i),o.push([this.makeActionButton(e,"worktree-update-pr","Sync PR"),this.makeActionButton(e,"worktree-decide-later","Later")])):(i.push(this.makeActionButton(e,"worktree-create-pr","Open PR")),i.length>0&&o.push(i),o.push([this.makeActionButton(e,"worktree-decide-later","Later"),this.makeActionButton(e,"worktree-dismiss","Discard")]));else return o.push([...i,this.makeActionButton(e,"worktree-decide-later","Later")]),o.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),o;return t.worktreePrUrl&&o.push([this.makeActionButton(e,"worktree-dismiss","Discard")]),o}getPlanApprovalButtons(e,t){let r=t?.actionablePlanDecisionVersion??t?.planDecisionVersion;this.clearPlanDecisionTokens(e,r);let o=[[this.makeActionButton(e,"plan-approve","Approve",{planDecisionVersion:r}),this.makeActionButton(e,"plan-request-changes","Revise",{planDecisionVersion:r}),this.makeActionButton(e,"plan-reject","Reject",{planDecisionVersion:r})]];return M("plan_approval_buttons_created",{sessionId:e,planDecisionVersion:r,...E(o)}),o}getResumeButtons(e,t){let r=[];return t.isExplicitlyResumable&&r.push(this.makeActionButton(e,"session-resume","Resume")),r.push(this.makeActionButton(e,"view-output","View output")),[r]}getQuestionButtons(e,t,r={}){if(t.length===0)return;let o=t.map((s,a)=>{let l=this.createActionToken(e,"question-answer",{label:s.label,optionIndex:a,pendingInputRequestId:r.requestId,pendingInputQuestionId:r.questionId});return{label:Am(s.label),callbackData:l.id,style:this.resolveButtonStyle("question-answer")}}),i=[];for(let s=0;s<o.length;s+=Ha)i.push(o.slice(s,s+Ha));return i}getPlanOfferButtons(e){let{offerId:t,route:r,planName:o,planPrompt:i,planWorkdir:s,planWorktreeStrategy:a}=e,l=[[this.makeActionButton(t,"plan-offer-start","Start Plan",{route:r,launchName:o,launchPrompt:i,launchWorkdir:s,launchWorktreeStrategy:a}),this.makeActionButton(t,"plan-offer-dismiss","Dismiss",{route:r})]];return M("plan_offer_buttons_created",{offerId:t,planName:o,channel:r.provider,target:r.target,accountId:r.accountId,threadId:r.threadId,sessionKey:r.sessionKey,planPromptLength:i.length,planWorkdirLength:s.length,planWorktreeStrategy:a,...E(l)}),l}getRepoPolicyChoiceButtons(e){let t=at(e.prAvailable??!0),r=Array.from({length:Math.ceil(t.length/2)},(o,i)=>t.slice(i*2,i*2+2)).map(o=>o.map(i=>this.makeActionButton(e.choiceId,"repo-policy-set",i.label,{route:e.route,repoPolicy:i.policy,repoPolicyWorkdir:e.repoRoot,launchName:e.launchName,launchPrompt:e.launchPrompt,launchWorkdir:e.launchWorkdir,launchModel:e.launchModel,launchReasoningEffort:e.launchReasoningEffort,launchFastMode:e.launchFastMode,launchSystemPrompt:e.launchSystemPrompt,launchAllowedTools:e.launchAllowedTools,launchResumeSessionId:e.launchResumeSessionId,launchResumedFromSessionName:e.launchResumedFromSessionName,launchResumeWorktreeFrom:e.launchResumeWorktreeFrom,launchSessionIdOverride:e.launchSessionIdOverride,launchClearedPersistedCodexResume:e.launchClearedPersistedCodexResume,launchForkSession:e.launchForkSession,launchForceNewSession:e.launchForceNewSession,launchPermissionMode:e.launchPermissionMode,launchPlanApproval:e.launchPlanApproval,launchHarness:e.launchHarness,launchWorktreeStrategy:e.launchWorktreeStrategy,launchWorktreeBaseBranch:e.launchWorktreeBaseBranch,launchWorktreePrTargetRepo:e.launchWorktreePrTargetRepo,launchOriginAgentId:e.launchOriginAgentId})));return M("repo_policy_choice_buttons_created",{choiceId:e.choiceId,repoRoot:e.repoRoot,channel:e.route.provider,target:e.route.target,accountId:e.route.accountId,threadId:e.route.threadId,sessionKey:e.route.sessionKey,labels:t.map(o=>o.label),...E(r)}),r}};import{createHash as Cm}from"crypto";var Im="duplicate notification already delivered or in flight",ir=class{maxRecords;inFlightTtlMs;now;inFlight=new Set;delivered=new Set;constructor(e={}){this.maxRecords=Math.max(1,Math.floor(e.maxRecords??64)),this.inFlightTtlMs=Math.max(1,Math.floor(e.inFlightTtlMs??6e5)),this.now=e.now??(()=>new Date)}claim(e,t,r){if(!e)return{allowed:!0};let o=this.now(),i=this.prune(t??[],o),s=i.find(a=>a.key===e);return this.delivered.has(e)||this.inFlight.has(e)||s?.status==="delivered"||s?.status==="in_flight"&&this.isFreshInFlight(s,o)?{allowed:!1,records:i,reason:Im}:(this.inFlight.add(e),this.delivered.delete(e),{allowed:!0,records:this.upsert(i,{key:e,status:"in_flight",recordedAt:o.toISOString(),label:r})})}deliveredRecords(e,t,r){if(!e)return;let o=this.now();return this.inFlight.delete(e),this.delivered.add(e),this.upsert(this.prune(t??[],o),{key:e,status:"delivered",recordedAt:o.toISOString(),label:r})}releasedRecords(e,t){if(!e)return;let r=this.now();return this.inFlight.delete(e),this.prune(t??[],r).filter(o=>!(o.key===e&&o.status==="in_flight"))}prune(e,t){let r=e.filter(o=>o.status==="delivered"?!0:this.isFreshInFlight(o,t));return r.slice(Math.max(0,r.length-this.maxRecords))}isFreshInFlight(e,t){let r=Date.parse(e.recordedAt);return Number.isFinite(r)?t.getTime()-r<this.inFlightTtlMs:!1}upsert(e,t){let o=[...e.filter(i=>i.key!==t.key),t];return o.slice(Math.max(0,o.length-this.maxRecords))}};import{createHash as Tm}from"crypto";var xm=1024,St="duplicate completion follow-up wake already handled",sr="prior human-visible summary already delivered",ar=class{inFlight=new Set;completed=new Map;claimKeysByPrimary=new Map;maxCompletedKeys;constructor(e={}){this.maxCompletedKeys=Math.max(1,Math.floor(e.maxCompletedKeys??xm))}decide(e,t,r){if(t?.required!==!0)return{required:!1,allowed:!1,explicit:!1};let o=this.buildKeySet(e,t);if(!o)return{required:!0,allowed:!0,explicit:!1};let i=this.normalizeRecords(r),s=this.buildPersistedKeyMap(i),a=o.decisionKeys.find(u=>this.inFlight.has(u)||!!this.getCompletedRecord(u)||s.has(u)),l=a?this.getCompletedRecord(a):void 0,d=a?s.get(a):void 0;return a?{required:!0,allowed:!1,explicit:o.explicit,dedupeKey:o.primary,skipReason:l?.skipReason??d?.skipReason??St}:(this.registerClaim(o.primary,o.claimKeys),{required:!0,allowed:!0,key:o.primary,explicit:o.explicit})}recordVisibleDelivery(e,t,r,o){if(t.required!==!0)return{required:!1,allowed:!1,explicit:!1};let i=this.buildKeySet(e,t);if(!i)return{required:!0,allowed:!0,explicit:!1};let s=this.normalizeRecords(r),a=this.buildPersistedKeyMap(s),l=i.decisionKeys.find(g=>!!this.getCompletedRecord(g)||a.has(g)),d=l?this.getCompletedRecord(l):void 0,u=l?a.get(l):void 0;if(d||u)return{required:!0,allowed:!1,explicit:i.explicit,dedupeKey:i.primary,skipReason:d?.skipReason??u?.skipReason};this.finishKeys(i.primary,i.claimKeys,!0,sr);let f=this.deliveredRecords(i.claimKeys,s,o,sr);return{required:!0,allowed:!0,key:i.primary,explicit:i.explicit,records:f}}finish(e,t,r=St){if(!e)return;let o=this.claimKeysByPrimary.get(e)??[e];this.finishKeys(e,o,t,r)}completionRecordsAfterDelivery(e,t,r,o=St){if(!e)return;let i=this.claimKeysByPrimary.get(e)??[e];return this.deliveredRecords(i,t,r,o)}registerClaim(e,t){for(let r of t)this.inFlight.add(r);for(this.claimKeysByPrimary.delete(e),this.claimKeysByPrimary.set(e,t);this.claimKeysByPrimary.size>this.maxCompletedKeys;){let r=this.claimKeysByPrimary.keys().next().value;if(r===void 0)break;let o=this.claimKeysByPrimary.get(r)??[r];for(let i of o)this.inFlight.delete(i);this.claimKeysByPrimary.delete(r)}}finishKeys(e,t,r,o=St){for(let i of t)this.inFlight.delete(i);if(this.claimKeysByPrimary.delete(e),!!r){for(let i of t)this.completed.get(i)?.skipReason===sr&&o!==sr||(this.completed.delete(i),this.completed.set(i,{skipReason:o,linkedKeys:t.filter(a=>a!==i)}));for(;this.completed.size>this.maxCompletedKeys;){let i=this.completed.keys().next().value;if(i===void 0)break;this.completed.delete(i)}}}buildKeySet(e,t){let r=this.getDeliveryRef(e);if(!r)return;let o=this.normalizeOutcomeKey(e,t.outcomeKey?.trim());if(o){let a=`${this.buildVisibleScope(r,e)}:outcome:${this.digest(o)}`,l=this.isGoalLike(e,t,o),d=this.buildSessionAliasKeys(r,e,"visible-summary"),u=this.buildSessionAliasKeys(r,e,"goal-summary"),f=this.isTerminalLike(t,o),g=o.startsWith("worktree-pr:")?this.normalizeWorktreePrOutcome(t.outcomeKey?.trim()):void 0,S=g?.aliases.map(y=>`${this.buildVisibleScope(r,e)}:outcome:${this.digest(y)}`)??[];return{primary:a,explicit:!0,claimKeys:[...d,...l?u:[],...S,a],decisionKeys:[a,...g?.blocksAliases?S:[],...l||f?d:[],...u]}}let i=t.fallbackFingerprint?.trim();if(!i)return;let s=`${r}:${t.producer}:${this.digest(i)}`;return{primary:s,explicit:!1,claimKeys:[s],decisionKeys:[s]}}isGoalLike(e,t,r){return!!e.goalTaskId?.trim()||t.producer==="goal"||/^goal:/i.test(r)}isTerminalLike(e,t){return e.producer==="terminal"||/^terminal:/i.test(t)}normalizeOutcomeKey(e,t){let r=e.goalTaskId?.trim();if(r)return`goal:${r}`;let o=this.normalizeWorktreePrOutcome(t);return o?o.primary:t}normalizeWorktreePrOutcome(e){if(!e)return;let t=e.split(":");if(t[0]!=="worktree-pr"||t.length<5)return;let r=t[1]?.trim().toLowerCase();if(!r||!/^(?:draft-)?(?:opened|updated)$/.test(r))return;let o=t[2]?.trim()||"default-repo",i=t[3]?.trim();if(!i)return;let s=this.normalizePrIdentity(i),a=t[4]?.trim();if(!s||!a)return;let l=["worktree-pr",o.toLowerCase(),s,a].join(":"),d=`${l}:created`;if(r.endsWith("updated")){let u=t.slice(5).join(":").trim();return{primary:u?`${l}:updated:${u}`:`${l}:updated`,aliases:[d,l],blocksAliases:!1}}return{primary:d,aliases:[l],blocksAliases:!0}}normalizePrIdentity(e){let t=e.match(/#?(\d+)$/);if(t?.[1])return`#${t[1]}`;let r=e.match(/\/pull\/(\d+)(?:\b|\/|$)/);if(r?.[1])return`#${r[1]}`;let o=e.trim();return o||void 0}buildVisibleScope(e,t){let r=le(t);return r?`route:${this.digest(JSON.stringify({provider:r.provider,accountId:r.accountId,target:r.target,threadId:r.threadId}))}`:e}buildSessionAliasKeys(e,t,r){let o=this.buildVisibleScope(e,t),i="startedAt"in t?t.startedAt:t.createdAt,s=Number.isFinite(i)?`${o}:cycle:${this.digest(String(i))}`:o,a=["id"in t?t.id:void 0,"sessionId"in t?t.sessionId:void 0,t.name,C(t),t.harnessSessionId,e].map(l=>l?.trim()).filter(l=>!!l);return[...new Set(a)].map(l=>`${s}:session:${this.digest(l)}:${r}`)}getDeliveryRef(e){return D(e)??C(e)??""}digest(e){return Tm("sha256").update(e).digest("hex").slice(0,16)}normalizeRecords(e){return e?.length?e.filter(t=>t.key.trim()&&Number.isFinite(Date.parse(t.recordedAt))).slice(-this.maxCompletedKeys):[]}buildPersistedKeyMap(e){let t=new Map;for(let r of e){t.set(r.key,r);for(let o of r.linkedKeys??[])o.trim()&&t.set(o,r)}return t}getCompletedRecord(e){let t=this.completed.get(e);if(t)return t;for(let r of this.completed.values())if(r.linkedKeys?.includes(e))return r}deliveredRecords(e,t,r,o=St){let i=new Date().toISOString(),s=this.normalizeRecords(t),a=new Set(e),d=[...s.filter(u=>!a.has(u.key)&&!(u.linkedKeys??[]).some(f=>a.has(f))),...e.map(u=>{let f=e.filter(g=>g!==u);return{key:u,linkedKeys:f.length>0?f:void 0,recordedAt:i,label:r,skipReason:o}})];return d.slice(Math.max(0,d.length-this.maxCompletedKeys))}};var Mm=2e3,_m=new Set(["1","true","yes","on"]);function Dm(){let n=process.env.OPENCLAW_CODE_AGENT_NOTIFICATION_DIAGNOSTICS?.trim().toLowerCase();return!!(n&&_m.has(n))||Mr()}function $m(n){Dm()&&process.stderr.write(`[SessionNotification] ${JSON.stringify(n)}
|
|
198
|
-
`)}function Em(n){let e=n?.trim().split(":")??[];if(e[0]!=="worktree-pr")return;let t=e[1]?.toLowerCase();if(t==="updated"||t==="draft-updated")return"pr-updated";if(t==="opened"||t==="draft-opened")return"pr-opened"}var lr=class{constructor(e,t,r={}){this.wakeDispatcher=e;this.applyPersistedPatch=t;this.completionSummaries=new ar({maxCompletedKeys:r.maxCompletedCompletionWakeKeys}),this.notificationDedupe=new ir({maxRecords:r.maxNotificationDedupeRecords}),this.getPersistedSession=r.getPersistedSession}wakeDispatcher;applyPersistedPatch;completionSummaries;notificationDedupe;getPersistedSession;dispatch(e,t){let r=this.getDeliveryRef(e),o=this.getPersistedSession?.(r),i=this.buildNotificationDedupeKey(e,t),s=this.notificationDedupe.claim(i,o?.notificationDedupe,t.label);if(s.records&&this.applyNotificationDedupePatch(r,s.records),!s.allowed){this.logNotificationDecision({session:e,request:t,deliveryRef:r,dedupeKey:i,decision:"skip",reason:s.reason??"duplicate notification skipped",deliveryPath:"notify"}),t.hooks?.onDuplicateSkipped?.(s.reason??"duplicate notification skipped");return}let a=this.buildCompletionSummaryFact(t),l=t.completionSummaryOwner==="foreground"&&a?.required===!0,d=l?this.completionSummaries.recordVisibleDelivery(e,a,o?.completionSummaryDedupe,t.label):this.completionSummaries.decide(e,a,o?.completionSummaryDedupe);d.records&&this.applyCompletionSummaryDedupePatch(r,d.records);let u=l?this.withoutCompletionWake(t):t;if(d.required&&!d.allowed)if(this.logNotificationDecision({session:e,request:t,deliveryRef:r,dedupeKey:d.dedupeKey??d.key,outcomeKey:a?.outcomeKey,decision:l?"skip":d.explicit?"send_without_followup":"skip",reason:d.skipReason??"completion follow-up wake suppressed",deliveryPath:l?"foreground-summary":"wake",followupKind:a?.producer}),t.hooks?.onWakeSkipped?.(d.skipReason??"completion follow-up wake suppressed"),l){this.releaseNotificationDedupe(r,i);return}else if(d.explicit)u=this.withoutCompletionWake(t);else{this.releaseNotificationDedupe(r,i);return}a?.required===!0&&this.logNotificationDecision({session:e,request:u,deliveryRef:r,dedupeKey:d.dedupeKey??d.key,outcomeKey:a.outcomeKey,decision:l?"record_visible":u.completionWakeSummaryRequired===!0?"send_with_followup":"send_without_followup",reason:l?"foreground summary owns completion follow-up":void 0,deliveryPath:l?"foreground-summary":"wake",followupKind:a.producer});let f=this.buildCompletionWakePatch(u),g=!!(u.wakeMessage?.trim()||u.wakeMessageOnNotifySuccess?.trim()),S=!!(u.wakeMessage?.trim()||u.wakeMessageOnNotifyFailed?.trim()),y=u.failureWakeConfirmsNotificationDelivery!==!1,c=!1,h=!1,v=!1,
|
|
198
|
+
`)}function Em(n){let e=n?.trim().split(":")??[];if(e[0]!=="worktree-pr")return;let t=e[1]?.toLowerCase();if(t==="updated"||t==="draft-updated")return"pr-updated";if(t==="opened"||t==="draft-opened")return"pr-opened"}var lr=class{constructor(e,t,r={}){this.wakeDispatcher=e;this.applyPersistedPatch=t;this.completionSummaries=new ar({maxCompletedKeys:r.maxCompletedCompletionWakeKeys}),this.notificationDedupe=new ir({maxRecords:r.maxNotificationDedupeRecords}),this.getPersistedSession=r.getPersistedSession}wakeDispatcher;applyPersistedPatch;completionSummaries;notificationDedupe;getPersistedSession;dispatch(e,t){let r=this.getDeliveryRef(e),o=this.getPersistedSession?.(r),i=this.buildNotificationDedupeKey(e,t),s=this.notificationDedupe.claim(i,o?.notificationDedupe,t.label);if(s.records&&this.applyNotificationDedupePatch(r,s.records),!s.allowed){this.logNotificationDecision({session:e,request:t,deliveryRef:r,dedupeKey:i,decision:"skip",reason:s.reason??"duplicate notification skipped",deliveryPath:"notify"}),t.hooks?.onDuplicateSkipped?.(s.reason??"duplicate notification skipped");return}let a=this.buildCompletionSummaryFact(t),l=t.completionSummaryOwner==="foreground"&&a?.required===!0,d=l?this.completionSummaries.recordVisibleDelivery(e,a,o?.completionSummaryDedupe,t.label):this.completionSummaries.decide(e,a,o?.completionSummaryDedupe);d.records&&this.applyCompletionSummaryDedupePatch(r,d.records);let u=l?this.withoutCompletionWake(t):t;if(d.required&&!d.allowed)if(this.logNotificationDecision({session:e,request:t,deliveryRef:r,dedupeKey:d.dedupeKey??d.key,outcomeKey:a?.outcomeKey,decision:l?"skip":d.explicit?"send_without_followup":"skip",reason:d.skipReason??"completion follow-up wake suppressed",deliveryPath:l?"foreground-summary":"wake",followupKind:a?.producer}),t.hooks?.onWakeSkipped?.(d.skipReason??"completion follow-up wake suppressed"),l){this.releaseNotificationDedupe(r,i);return}else if(d.explicit)u=this.withoutCompletionWake(t);else{this.releaseNotificationDedupe(r,i);return}a?.required===!0&&this.logNotificationDecision({session:e,request:u,deliveryRef:r,dedupeKey:d.dedupeKey??d.key,outcomeKey:a.outcomeKey,decision:l?"record_visible":u.completionWakeSummaryRequired===!0?"send_with_followup":"send_without_followup",reason:l?"foreground summary owns completion follow-up":void 0,deliveryPath:l?"foreground-summary":"wake",followupKind:a.producer});let f=this.buildCompletionWakePatch(u),g=!!(u.wakeMessage?.trim()||u.wakeMessageOnNotifySuccess?.trim()),S=!!(u.wakeMessage?.trim()||u.wakeMessageOnNotifyFailed?.trim()),y=u.failureWakeConfirmsNotificationDelivery!==!1,c=!1,h=!1,v=!1,b=()=>{v||(v=!0,c||(this.releaseNotificationDedupe(r,i),c=!0),this.completionSummaries.finish(d.key,!1))},A=u.shouldDispatch?()=>{let R=u.shouldDispatch?.()!==!1;return R||b(),R}:void 0,I={onNotifyStarted:()=>{this.applyDeliveryState(r,"notifying"),u.hooks?.onNotifyStarted?.()},onNotifySucceeded:()=>{c=!0,this.markNotificationDedupeDelivered(r,i,u.label),this.applyNotifyDeliveryState(r,g?"wake_pending":"idle",g?f:void 0),g||this.completionSummaries.finish(d.key,!1),u.hooks?.onNotifySucceeded?.()},onNotifyFailed:()=>{h=!0,this.applyNotifyDeliveryState(r,S?"wake_pending":"failed",S?f:void 0),S||(this.completionSummaries.finish(d.key,!1),this.releaseNotificationDedupe(r,i),c=!0),u.hooks?.onNotifyFailed?.()},onWakeStarted:()=>{this.applyPersistedPatchWithCompletionWake(r,"wake_pending",f,{completionWakeIssuedAt:new Date().toISOString(),completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),u.hooks?.onWakeStarted?.()},onWakeSucceeded:()=>{c=!0,h&&!y?this.releaseNotificationDedupe(r,i):this.markNotificationDedupeDelivered(r,i,u.label),this.markCompletionSummaryDelivered(r,d.key,u.label),this.applyPersistedPatchWithCompletionWake(r,"idle",this.buildCompletionWakeSucceededPatch(f),{completionWakeSucceededAt:new Date().toISOString(),completionWakeFailedAt:void 0,completionWakeSkippedAt:void 0,completionWakeSkipReason:void 0}),this.completionSummaries.finish(d.key,!0),u.hooks?.onWakeSucceeded?.()},onWakeSkipped:R=>{if(v){u.hooks?.onWakeSkipped?.(R);return}c=!0,h&&!y?this.releaseNotificationDedupe(r,i):this.markNotificationDedupeDelivered(r,i,u.label),this.markCompletionSummaryDelivered(r,d.key,u.label,R),this.applyPersistedPatchWithCompletionWake(r,"idle",this.buildCompletionWakeSucceededPatch(f),{completionWakeSucceededAt:void 0,completionWakeFailedAt:void 0,completionWakeSkippedAt:new Date().toISOString(),completionWakeSkipReason:R}),this.completionSummaries.finish(d.key,!0),u.hooks?.onWakeSkipped?.(R)},onWakeFailed:()=>{this.applyPersistedPatchWithCompletionWake(r,"failed",f,{completionWakeFailedAt:new Date().toISOString()}),this.completionSummaries.finish(d.key,!1),this.releaseNotificationDedupe(r,i),c=!0,u.hooks?.onWakeFailed?.()}};this.wakeDispatcher.dispatchSessionNotification(e,{...u,idempotencyKey:i??u.idempotencyKey,shouldDispatch:A,hooks:I})}notifyWorktreeOutcome(e,t,r={}){let o=this.getDeliveryRef(e),i=Em(r.completionWakeOutcomeKey);o&&i&&this.applyPersistedPatch(o,{worktreeRemoteOutcome:i});let s=Nm(t,e),a=f=>Ge({sessionId:o,sessionName:e.name,outcomeLine:s,originThreadLine:Ye(e),detailLines:r.detailLines,canonicalStatusDelivered:f}),l=r.summaryWakeRequired??!0,d={required:l,producer:"worktree-pr",outcomeKey:r.completionWakeOutcomeKey??`terminal:${o}`},u=r.completionSummaryOwner!=="foreground";if(l&&!u){let f=this.getDeliveryRef(e),g=this.completionSummaries.recordVisibleDelivery(e,d,f?this.getPersistedSession?.(f)?.completionSummaryDedupe:void 0,"worktree-outcome");g.records&&this.applyCompletionSummaryDedupePatch(f,g.records)}this.dispatch(e,{label:"worktree-outcome",userMessage:s,notifyUser:"always",requireDirectUserNotification:!0,completionSummary:{...d,required:l&&u},completionWakeSummaryRequired:l&&u,completionWakeOutcomeKey:r.completionWakeOutcomeKey??`terminal:${o}`,idempotencyKey:`worktree-outcome:${r.completionWakeOutcomeKey??t}`,deferConditionalWakeUntilNextTick:!0,deferConditionalWakeMs:Mm,wakeMessageOnNotifySuccess:l&&u?a(!0):void 0,wakeMessageOnNotifyFailed:l&&u?a(!1):void 0})}dispose(){this.wakeDispatcher.dispose()}getDeliveryRef(e){return D(e)??C(e)??""}applyDeliveryState(e,t){!e||!t||this.applyPersistedPatch(e,{deliveryState:t})}applyNotifyDeliveryState(e,t,r){!e||!t||this.applyPersistedPatch(e,r?{deliveryState:t,...r}:{deliveryState:t})}applyPersistedPatchWithCompletionWake(e,t,r,o){!e||!t||this.applyPersistedPatch(e,r?{deliveryState:t,...r,...o}:{deliveryState:t})}buildCompletionWakePatch(e){if(e.completionWakeSummaryRequired===!0)return{completionWakeSummaryRequired:!0}}buildCompletionWakeSucceededPatch(e){if(e)return{completionWakeSummaryRequired:void 0}}withoutCompletionWake(e){return{...e,completionSummary:e.completionSummary?{...e.completionSummary,required:!1}:void 0,wakeMessage:void 0,wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:void 0,completionWakeSummaryRequired:!1}}buildCompletionSummaryFact(e){if(e.completionSummary)return e.completionSummary;if(e.completionWakeSummaryRequired!==!0)return;let t=[e.wakeMessage,e.wakeMessageOnNotifySuccess,e.wakeMessageOnNotifyFailed].map(r=>r?.trim()).filter(r=>!!r);return{required:!0,producer:"legacy",outcomeKey:e.completionWakeOutcomeKey,fallbackFingerprint:t.length>0?`${e.label}
|
|
199
199
|
${t.join(`
|
|
200
200
|
---completion-wake---
|
|
201
201
|
`)}`:void 0}}buildNotificationDedupeKey(e,t){let r=t.idempotencyKey?.trim();if(!r)return;let o=this.getDeliveryRef(e);if(!o)return;let i=le(e),s=i?{provider:i.provider,accountId:i.accountId,target:i.target,threadId:i.threadId}:{deliveryRef:o};return`notification:${this.digest(JSON.stringify({scope:s,semanticKey:r}))}`}markNotificationDedupeDelivered(e,t,r){let o=this.notificationDedupe.deliveredRecords(t,e?this.getPersistedSession?.(e)?.notificationDedupe:void 0,r);o&&this.applyNotificationDedupePatch(e,o)}releaseNotificationDedupe(e,t){let r=this.notificationDedupe.releasedRecords(t,e?this.getPersistedSession?.(e)?.notificationDedupe:void 0);r&&this.applyNotificationDedupePatch(e,r)}applyNotificationDedupePatch(e,t){this.getPersistedSession&&e&&this.applyPersistedPatch(e,{notificationDedupe:t})}markCompletionSummaryDelivered(e,t,r,o){let i=this.completionSummaries.completionRecordsAfterDelivery(t,e?this.getPersistedSession?.(e)?.completionSummaryDedupe:void 0,r,o);i&&this.applyCompletionSummaryDedupePatch(e,i)}applyCompletionSummaryDedupePatch(e,t){this.getPersistedSession&&e&&this.applyPersistedPatch(e,{completionSummaryDedupe:t})}logNotificationDecision(e){let t=le(e.session);$m({event:"oca_notification_decision",sessionId:"id"in e.session?e.session.id:e.session.sessionId,sessionName:e.session.name,harnessSessionId:e.session.harnessSessionId,originRoute:t?{provider:t.provider,accountId:t.accountId,target:t.target,threadId:t.threadId,sessionKey:t.sessionKey}:void 0,outcomeType:e.outcomeKey?.split(":").slice(0,2).join(":")??e.request.label,notificationKind:e.request.label,followupKind:e.followupKind,dedupeKey:e.dedupeKey,deliveryPath:e.deliveryPath,decision:e.decision,reason:e.reason,completionWakeSummaryRequired:e.request.completionWakeSummaryRequired,deliveryRef:e.deliveryRef})}digest(e){return Cm("sha256").update(e).digest("hex").slice(0,16)}};function Nm(n,e){let t=ye(e);return t?`${n}${t}`:n}import{existsSync as Om}from"fs";var dr=class{getCompletionState(e,t,r,o){if(oe(t)!==r)return"has-commits";let i=Xe(e,r,o);if(i===void 0)return"has-commits";if(i===0){let s=Xe(e,o,r);return s===void 0?"has-commits":s>0?_t(e,r,o)?"merged":"base-advanced":et(t)?"dirty-uncommitted":"no-change"}return et(t)?"dirty-uncommitted":Zo(e,r,o)?"released":"has-commits"}isResolvedWorktreeEligibleForCleanup(e,t,r){if(!e.worktreePath||!e.workdir||!Om(e.worktreePath)||e.pendingWorktreeDecisionSince||e.worktreeState==="pending_decision"||e.pendingPlanApproval||e.resumable||e.worktreeBranch&&oe(e.worktreePath)!==e.worktreeBranch)return!1;let o=e.worktreeMergedAt??e.worktreeDismissedAt??e.completedAt??e.createdAt,i=typeof o=="string"?new Date(o).getTime():Number(o??0);return!!i&&t-i>=r}};import{randomUUID as Wm}from"node:crypto";function Fm(n){let e=n.pendingInputState,t=e?.activeQuestionIndex??0;return e?.questions?.[t]?.id??(e?.activeQuestionIndex!=null?`q${e.activeQuestionIndex}`:void 0)}var ur=class{constructor(e,t,r,o){this.pendingQuestions=e;this.dispatchSessionNotification=t;this.clearWaitingTimestamp=r;this.getQuestionButtons=o}pendingQuestions;dispatchSessionNotification;clearWaitingTimestamp;getQuestionButtons;async handleAskUserQuestion(e,t){let i=t?.questions??[];if(i.length===0)throw new Error("AskUserQuestion: no questions in input");let s=i[0],a=s.options??[],l=`β [${e.name}] ${s.question}`,d=Fm(e),u=e.pendingInputState?.requestId??`legacy:${Wm()}`,f=this.getQuestionButtons(e.id,a,{requestId:u,questionId:d}),g=[`[ASK USER QUESTION] Session "${e.name}" has a question requiring user input.`,"",`Question: ${s.question}`,...a.length>0?["Options:",...a.map((S,y)=>` ${y+1}. ${S.label}`)]:[],"",`Send the question to the user and call agent_respond(session="${e.id}", message="<answer>") with their answer.`].join(`
|
|
@@ -209,16 +209,16 @@ ${t.join(`
|
|
|
209
209
|
`)}function tf(n){return n.options.map(e=>({label:e.label,description:e.description?.trim()??""})).filter(e=>e.description&&e.description.length<=Zm)}function el(n){let e=n?.activeQuestionIndex??0;return n?.questions?.[e]?.id??(n?.activeQuestionIndex!=null?`q${n.activeQuestionIndex}`:void 0)}function nf(n,e,t){let r=n.pendingInputState;return!!(r&&r.requestId===e&&el(r)===t)}function rf(n){return[n.startedAt??"unknown-started-at",n.result?.session_id??"unknown-backend-session",n.result?.num_turns??0].join(":")}function Za(n){return[n.status,n.startedAt??"unknown-started-at",n.result?.session_id??"unknown-backend-session",n.result?.num_turns??0,n.killReason??"unknown"].join(":")}var fr=class{constructor(e){this.deps=e}deps;dispatchPlanApprovalFallback(e,t,r){let o=new Date().toISOString();this.deps.dispatchSessionNotification(e,{label:"plan-approval-fallback",idempotencyKey:`plan-approval:${e.id}:v${t??"unknown"}:fallback`,userMessages:gt({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>vt(e,t),hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:t,approvalPromptVersion:t,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:t,approvalPromptVersion:t,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:t,approvalPromptVersion:t,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:He(e,t,!0),wakeMessageOnNotifyFailed:pr({session:e,planDecisionVersion:t,originThreadLine:this.deps.originThreadLine(e)}),failureWakeConfirmsNotificationDelivery:!1})}logCompletionWakeDiagnostic(e){JSON.stringify({event:e.event,sessionId:e.session.id,sessionName:e.session.name,canonicalStatusDelivered:e.canonicalStatusDelivered,requestedShortFactualSummary:e.followupSummaryRequired,completionKind:"terminal"})}shouldRequestCompletionFollowup(e){return e.originSessionKey?.trim()?.startsWith("agent:main:cron:")?!1:!!le(e)}async handleTurnEnd(e,t){if(e.status!=="running"){`${e.id}${e.status}`;return}if(!e.goalTaskId){if(t||e.pendingPlanApproval){await this.emitWaitingForInput(e);return}if(e.worktreeStrategy==="ask"||e.worktreeStrategy==="delegate"){`${e.id}${e.worktreeStrategy}`;return}this.deps.shouldEmitTurnCompleteWake(e)&&this.emitTurnComplete(e)}}async handleSessionTerminal(e){if(this.deps.persistSession(e),this.deps.clearWaitingTimestamp(e.id),e.goalTaskId){this.deps.clearRetryTimersForSession(e.id);return}if(e.pendingPlanApproval){e.killReason==="idle-timeout"&&e.pendingPlanApproval?this.emitIdleTimeoutPlanApproval(e):await this.emitWaitingForInput(e),this.deps.clearRetryTimersForSession(e.id);return}let t={notificationSent:!1,worktreeRemoved:!1};e.worktreePath&&e.originalWorkdir&&(t=await this.deps.handleWorktreeStrategy(e));let r=!1;if(e.worktreePath&&e.originalWorkdir&&e.status==="failed"&&e.costUsd===0&&e.duration<3e4){let a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),l=e.worktreeBranch,d=L(e);`${e.name}${e.costUsd.toFixed(2)}${e.duration}`;let u=!1;if(a&&!d&&(u=B(a,e.worktreePath)),a&&l&&!d&&u&&H(a,l),u){for(let f of z(e))this.deps.updatePersistedSession(f,{worktreePath:void 0,worktreeBranch:void 0});r=!0}}let o=e.worktreeStrategy&&e.worktreeStrategy!=="off"&&e.worktreeStrategy!=="manual";if(!r&&e.worktreePath&&e.originalWorkdir){let a=this.deps.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath),l=L(e);t.worktreeRemoved?`${e.name}`:o?`${e.name}${e.worktreeStrategy}`:a&&!l&&B(a,e.worktreePath)}if(t.notificationSent){`${e.id}`;return}if(e.killReason==="done"){if(this.deps.hasTurnCompleteWakeMarker(e.id)||!this.deps.shouldEmitTerminalWake(e))return;this.emitCompleted(e);return}if(e.status==="completed"){if(!this.deps.shouldEmitTerminalWake(e))return;this.emitCompleted(e);return}if(e.status==="failed"){if(!this.deps.shouldEmitTerminalWake(e))return;let a=e.error||e.result?.is_error&&e.result.result||e.result?.result||this.deps.extractLastOutputLine(e)||`Session failed with no error details (session=${e.id}, subtype=${e.result?.subtype??"none"}, turns=${e.result?.num_turns??0})`;this.emitFailed(e,G(a,200),r);return}let i=`$${(e.costUsd??0).toFixed(2)}`,s=e.duration;if(e.killReason==="idle-timeout"){if(e.pendingPlanApproval){this.emitIdleTimeoutPlanApproval(e),this.deps.clearRetryTimersForSession(e.id);return}this.deps.dispatchSessionNotification(e,{label:"suspended",idempotencyKey:`suspended:${e.id}:${e.killReason??"idle-timeout"}:${e.completedAt??"unknown"}`,userMessage:`π€ [${e.name}] Suspended after idle timeout | ${i} | ${se(s)}`,notifyUser:"always",buttons:this.deps.getResumeButtons(e.id,e)}),this.deps.clearRetryTimersForSession(e.id);return}this.deps.notifySession(e,`β [${e.name}] ${go(e.killReason)} | ${i} | ${se(s)}`),this.deps.clearRetryTimersForSession(e.id)}emitIdleTimeoutPlanApproval(e){let t=this.deps.resolvePlanApprovalMode(e),r=e.actionablePlanDecisionVersion??e.planDecisionVersion,o=kt(e,r);if(t==="delegate"){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",idempotencyKey:`plan-approval-timeout:${e.id}:v${r??"unknown"}:delegate`,wakeMessage:["[DELEGATED PLAN APPROVAL REMINDER] Plan review is still pending after the session hit idle timeout.",`Name: ${e.name} | ID: ${e.id}`,this.deps.originThreadLine(e),"The agent already produced a plan and is waiting for a delegated decision.","Review privately first. Approve directly with agent_respond(..., approve=true, approval_rationale='...') if the plan is clearly within scope and low risk.","Escalate only if needed via agent_request_plan_approval(summary='...').","If you approve directly, follow up with a short user-facing explanation; the plugin's thumbs-up line is only the minimal approval acknowledgment.","If a canonical approval prompt was already posted for this plan version, do not restate it in plain text."].join(`
|
|
210
210
|
`),notifyUser:"never"});return}if(t==="ask"&&o){this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",idempotencyKey:`plan-approval-timeout:${e.id}:v${r??"unknown"}:already-delivered`,notifyUser:"never",wakeMessage:["[PLAN APPROVAL REMINDER] The user already has an actionable plan review prompt for this plan version.",`Name: ${e.name} | ID: ${e.id} | Plan v${r??"?"}`,this.deps.originThreadLine(e),"Do NOT post another approval summary unless canonical delivery is known to be missing."].join(`
|
|
211
211
|
`)});return}this.deps.dispatchSessionNotification(e,{label:"plan-approval-timeout",idempotencyKey:`plan-approval-timeout:${e.id}:v${r??"unknown"}:user-prompt`,userMessage:[`π [${e.name}] Plan v${r??"?"} still awaiting approval after idle timeout | $${(e.costUsd??0).toFixed(2)} | ${se(e.duration)}`,"","The agent already produced a plan and is waiting for your decision.","Approve resumes the session and starts implementation.","Revise resumes it in plan mode so it can update the plan first.","Reject keeps the session stopped."].join(`
|
|
212
|
-
`),notifyUser:"always",buttons:t==="ask"&&!o?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:r}):void 0})}async emitWaitingForInput(e){let t=e.pendingInputState?.questions,r=t?.[e.pendingInputState?.activeQuestionIndex??0],o=e.pendingInputState?.requestId,i=el(e.pendingInputState),s=o?[o,i].filter(Boolean).join(":"):void 0,a=s?`pending-input:${s}`:void 0;if(!this.deps.debounceWaitingEvent(e.id,a))return;let l=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0,d=e.actionablePlanDecisionVersion??e.planDecisionVersion,u=e.pendingPlanApproval&&l==="ask"&&kt(e,d),f=e.pendingInputState?.promptText?.trim()||void 0,g=e.pendingPlanApproval?void 0:this.deps.getOutputPreview(e),S=!e.pendingPlanApproval&&f?f:!e.pendingPlanApproval&&g!==void 0?g:this.deps.getOutputPreview(e,e.pendingPlanApproval&&l!=="delegate"?Number.POSITIVE_INFINITY:void 0),y=e.pendingInputState?.options.map(w=>({label:w}))??[],c=!t||t.length===0?y:r&&r.options.length>0&&r.options.length<=6&&!r.options.some(w=>w.isOther)&&!r.multiSelect?r.options:t.length===1&&r&&r.options.length===0?y:[],h=e.pendingPlanApproval&&l==="ask"&&!u?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:d}):!e.pendingPlanApproval&&c.length?this.deps.getQuestionButtons(e.id,c,{requestId:e.pendingInputState?.requestId,questionId:r?.id}):void 0,v=Lo(e,d),R=r?tf(r):[],A=r?ef({question:r,index:e.pendingInputState?.activeQuestionIndex??0,total:t?.length??1,optionDescriptions:R}):f,I=!e.pendingPlanApproval&&this.deps.questionContextSummaryProvider?await Xa({sessionName:e.name,question:A??S,context:g,provider:this.deps.questionContextSummaryProvider}):void 0,b=xo({session:e,preview:S,questionText:e.pendingPlanApproval?void 0:A,questionContextPreview:g,questionContextSummary:I,planArtifact:v,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:l,planApprovalButtons:h,questionButtons:e.pendingPlanApproval?void 0:h}),m=b.planReviewSummary??S;if(b.label==="plan-approval"&&l==="ask"&&u){this.deps.dispatchSessionNotification(e,{label:b.label,idempotencyKey:`plan-approval:${e.id}:v${d??"unknown"}:canonical`,userMessage:b.userMessage,userMessages:b.userMessages,notifyUser:"never",buttons:b.buttons,wakeMessage:b.wakeMessage});return}if(b.label==="plan-approval"&&l==="ask"){this.deps.dispatchSessionNotification(e,{label:b.label,idempotencyKey:`plan-approval:${e.id}:v${d??"unknown"}:canonical`,userMessage:b.userMessage,userMessages:b.userMessages,notifyUser:"always",buttons:b.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:d,approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},shouldDispatch:()=>vt(e,d),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,d,m),wakeMessageOnNotifySuccess:He(e,d)});return}if(b.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:b.label,idempotencyKey:`plan-approval:${e.id}:v${d??"unknown"}:wake-only`,userMessage:b.userMessage,wakeMessage:b.wakeMessage,notifyUser:"never",buttons:b.buttons});return}this.deps.dispatchSessionNotification(e,{label:b.label,idempotencyKey:`waiting:${e.id}:${s??`${b.label}:${b.userMessage}`}`,userMessage:b.userMessage,notifyUser:"always",buttons:b.buttons,shouldDispatch:o?()=>nf(e,o,i):void 0,wakeMessageOnNotifyFailed:b.wakeMessage})}emitTurnComplete(e){`${e.id}${e.result?.num_turns??0}${e.worktreeStrategy??"none"}`;let t=vo({session:e,originThreadLine:this.deps.originThreadLine(e),preview:this.deps.getOutputPreview(e)});this.deps.dispatchSessionNotification(e,{label:"turn-complete",idempotencyKey:`turn-complete:${e.id}:${rf(e)}`,userMessage:t.userMessage,wakeMessage:t.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{`${e.id}`,this.deps.shouldEmitTerminalWake(e)&&this.emitCompleted(e)}})}emitCompleted(e){let t=this.deps.getOutputPreview(e),r=this.shouldRequestCompletionFollowup(e),o=yo({session:e,originThreadLine:this.deps.originThreadLine(e),preview:t}),i=Za(e),s=`terminal:${e.id}:${i}`,a;this.deps.dispatchSessionNotification(e,{label:"completed",idempotencyKey:`terminal-completed:${e.id}:${i}`,userMessage:o.userMessage,notifyUser:"always",completionSummary:{required:r,producer:"terminal",outcomeKey:s},completionWakeSummaryRequired:r,completionWakeOutcomeKey:s,requireDirectUserNotification:!0,wakeMessageOnNotifySuccess:r?o.wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:r?o.wakeMessageOnNotifyFailed:void 0,hooks:{onNotifySucceeded:()=>{a=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:a,followupSummaryRequired:r})},onNotifyFailed:()=>{a=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:a,followupSummaryRequired:r})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:a,followupSummaryRequired:r})}}})}emitFailed(e,t,r){let o=ko({session:e,originThreadLine:this.deps.originThreadLine(e),errorSummary:t,preview:this.deps.getOutputPreview(e),worktreeAutoCleaned:r,failedButtons:this.deps.getResumeButtons(e.id,e)});this.deps.dispatchSessionNotification(e,{label:"failed",idempotencyKey:`terminal-failed:${e.id}:${Za(e)}:${t}`,userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};import{existsSync as of}from"fs";var gr=class{constructor(e){this.deps=e}deps;async dismissWorktree(e){let t=this.deps.getPersistedSession(e),r=this.deps.resolveActiveSession(e),o=r??t;if(!o)return`Error: Session "${e}" not found.`;let i=r?.worktreePath??t?.worktreePath,s=this.deps.resolveWorktreeRepoDir(r?.originalWorkdir??t?.workdir,i),a=r?.worktreeBranch??t?.worktreeBranch,l=r?.name??t?.name??e;if(!s)return`Error: No workdir found for session "${e}".`;let d=L(o);!d&&i&&of(i)&&B(s,i,{destructive:!0}),a&&H(s,a);for(let f of z(r??t))this.deps.updatePersistedSession(f,{worktreeDisposition:"dismissed",worktreeDismissedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,worktreeState:"dismissed",lifecycle:"terminal",worktreePath:void 0,worktreeBranch:void 0,worktreeLifecycle:{state:"dismissed",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"dismiss",baseBranch:t?.worktreeLifecycle?.baseBranch,targetRepo:t?.worktreePrTargetRepo,pushRemote:t?.worktreePushRemote}});let u=d?`ποΈ [${l}] Branch \`${a??"unknown"}\` dismissed. Native backend worktree released for backend cleanup.`:`ποΈ [${l}] Branch \`${a??"unknown"}\` dismissed and permanently deleted.`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:D(r??t??{id:e})??e,sessionId:t?.sessionId,harnessSessionId:r?.harnessSessionId??t?.harnessSessionId,backendRef:r?.backendRef??t?.backendRef,route:r?.route??t?.route}),{label:"worktree-dismissed",idempotencyKey:`worktree-dismissed:${D(r??t??{id:e})??e}:${a??"unknown"}`,userMessage:u,notifyUser:"always"}),u}snoozeWorktreeDecision(e,t={}){let r=this.deps.getPersistedSession(e);if(!r)return`Error: Session "${e}" not found.`;let o=Date.now(),i=new Date(o+1440*60*1e3).toISOString();for(let l of z(r))this.deps.updatePersistedSession(l,{worktreeDecisionSnoozedUntil:i,lastWorktreeReminderAt:new Date(o).toISOString()});let a=`βοΈ Reminder snoozed 24h for \`${r.worktreeBranch??"unknown"}\` (session: ${r.name})`;return t.notifyUser!==!1&&this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:D(r)??C(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",idempotencyKey:`worktree-snoozed:${D(r)??C(r)??r.harnessSessionId}:${i}`,userMessage:a,notifyUser:"always"}),a}};var tl=new Set(["starting","running"]);function nl(n,e){JSON.stringify({component:"SessionRuntimeRegistry",event:n,at:new Date().toISOString(),...e})}function rl(n){return{sessionId:n.id,name:n.name,status:n.status,lifecycle:n.lifecycle,runtimeState:n.runtimeState,harness:n.harnessName,hasHarnessSessionId:!!n.harnessSessionId,backendRefKind:n.backendRef?.kind,hasBackendConversationId:!!n.backendRef?.conversationId,hasBackendRunId:!!n.backendRef?.runId,hasBackendWorktreeId:!!n.backendRef?.worktreeId,hasBackendWorktreePath:!!n.backendRef?.worktreePath}}var hr=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>tl.has(e.status)).length}uniqueName(e){let t=new Set([...this.sessions.values()].filter(o=>tl.has(o.status)).map(o=>o.name));if(!t.has(e))return e;let r=2;for(;t.has(`${e}-${r}`);)r+=1;return`${e}-${r}`}add(e,t="spawn"){nl("runtime.add",{reason:t,...rl(e),activeCountBefore:this.activeSessionCount()}),this.sessions.set(e.id,e)}remove(e,t="unknown"){let r=this.sessions.get(e);nl("runtime.remove",{reason:t,sessionId:e,existed:!!r,...r?rl(r):{},activeCountBefore:this.activeSessionCount()}),this.sessions.delete(e)}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()]}};var yr=class{constructor(e){this.deps=e}deps;initializeSession(e,t,r,o={}){if(this.deps.hydrateSpawnedSession(e,t,r),r.taskLifecycle?.create(e),e.on("statusChange",(i,s)=>{s==="running"?(e.harnessSessionId&&this.deps.markRunning(e),r.taskLifecycle?.progress(e)):(s==="completed"||s==="failed"||s==="killed")&&(r.taskLifecycle?.finalize(e),this.deps.handleTerminal(e).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${e.id}:`,a)}))}),e.on("lifecycleChange",(i,s)=>{r.taskLifecycle?.progress(e)}),e.on("turnEnd",(i,s)=>{this.deps.handleTurnEnd(e,s).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTurnEnd threw for session ${e.id}:`,a)})}),o.startAfter?o.startAfter.then(()=>e.start()).catch(i=>{console.error(`[SessionRuntimeBootstrap] deferred start threw for session ${e.id}:`,i)}):e.start(),o.notifyLaunch!==!1){let i=this.buildLaunchNotification(e);this.deps.notifySession(e,i.text,i.label,i.idempotencyKey)}return e}buildLaunchNotification(e){let t=this.deps.formatLaunchWorkdirLabel(e),r=ge({harness:e.harnessName,model:e.model})??"default";return e.resumeSessionId?{text:Qt({sessionName:e.name,resumedFromSessionName:e.resumedFromSessionName,workdirLabel:t,harnessLabel:r}),label:"resumed-launch",idempotencyKey:`resumed-launch:${e.id}:${e.startedAt}:${e.resumeSessionId}`}:{text:`π [${e.name}] Launched | ${t} | ${r}`,label:"launch"}}};var Sr=class{buildNoChangeNotification(e){let{session:t,nativeBackendWorktree:r,cleanupSucceeded:o,worktreePath:i,worktreeBranch:s,preview:a,originThreadLine:l,preservedSummary:d,remoteOutcome:u}=e,f=d?"preserved":o?"cleaned":"cleanup-failed",g=[s?.trim()||"unknown-branch",i.trim()||"unknown-worktree",t.startedAt].join(":"),S=d??(o?r?"native backend worktree released for backend cleanup":"worktree cleaned up":`cleanup failed; worktree still exists at ${i}`),y=ye({costUsd:t.costUsd,duration:typeof t.completedAt=="number"?t.completedAt-t.startedAt:void 0,harnessName:t.harnessName,model:t.model}),c=u==="pr-updated"?"PR updated; no local worktree changes remained to merge":u==="pr-opened"?"PR opened; no local worktree changes remained to merge":"Session completed with no worktree changes to merge",h=u==="pr-updated"?`PR updated; no local worktree changes remained to merge β ${S}`:u==="pr-opened"?`PR opened; no local worktree changes remained to merge β ${S}`:void 0,v=u==="pr-updated"?"PR updated; no local worktree changes remained to merge":u==="pr-opened"?"PR opened; no local worktree changes remained to merge":"Session completed with no worktree changes to merge",R=u==="pr-updated"?"Coding agent session updated a PR; no local worktree changes remained to merge.":u==="pr-opened"?"Coding agent session opened a PR; no local worktree changes remained to merge.":void 0;return{label:d?"worktree-no-changes-preserved":o?"worktree-no-changes":"worktree-no-changes-cleanup-failed",idempotencyKey:`worktree-no-change:${t.id}:${f}:${g}`,userMessage:d?`βΉοΈ [${t.name}] ${c} β ${d}${y}`:o?r?`βΉοΈ [${t.name}] ${c} β native backend worktree released for backend cleanup${y}`:`βΉοΈ [${t.name}] ${c} β worktree cleaned up${y}`:`β οΈ [${t.name}] ${v}, but worktree cleanup failed. Worktree still exists at ${i}${y}`,wakeMessage:bo({sessionName:t.name,sessionId:t.id,headline:R,cleanupSummary:h??S,preview:a,originThreadLine:l,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,approvalState:t.approvalState,planApproval:t.planApproval,approvalPromptStatus:t.approvalPromptStatus,approvalPromptMessageKind:t.approvalPromptMessageKind,approvalPromptDeliveredAt:t.approvalPromptDeliveredAt}),notifyUser:"always"}}buildAskNotification(e){let{session:t,branchName:r,baseBranch:o,diffSummary:i,buttons:s,summaryLines:a=[],policyReason:l}=e,d=i.commitMessages.slice(0,5).map(g=>`β’ ${g.hash} ${g.message} (${g.author})`),u=i.commits>5?`...and ${i.commits-5} more`:"",f=t.worktreePrTargetRepo?`Branch: \`${r}\` β \`${o}\` | PR target: ${t.worktreePrTargetRepo}`:`Branch: \`${r}\` β \`${o}\``;return{label:"worktree-merge-ask",idempotencyKey:["worktree-decision",t.id,r,o,i.commits,i.commitMessages.map(g=>g.hash).join(",")].join(":"),userMessage:[`π Worktree decision required for session \`${t.name}\``,"",f,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(g=>`- ${g}`),""]:[],...l?[`Policy: ${l}`,""]:[],"Recent commits:",...d,...u?[u]:[],"",`β οΈ Discard will permanently delete branch \`${r}\` and all local changes. This cannot be undone.`].join(`
|
|
212
|
+
`),notifyUser:"always",buttons:t==="ask"&&!o?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:r}):void 0})}async emitWaitingForInput(e){let t=e.pendingInputState?.questions,r=t?.[e.pendingInputState?.activeQuestionIndex??0],o=e.pendingInputState?.requestId,i=el(e.pendingInputState),s=o?[o,i].filter(Boolean).join(":"):void 0,a=s?`pending-input:${s}`:void 0;if(!this.deps.debounceWaitingEvent(e.id,a))return;let l=e.pendingPlanApproval?this.deps.resolvePlanApprovalMode(e):void 0,d=e.actionablePlanDecisionVersion??e.planDecisionVersion,u=e.pendingPlanApproval&&l==="ask"&&kt(e,d),f=e.pendingInputState?.promptText?.trim()||void 0,g=e.pendingPlanApproval?void 0:this.deps.getOutputPreview(e),S=!e.pendingPlanApproval&&f?f:!e.pendingPlanApproval&&g!==void 0?g:this.deps.getOutputPreview(e,e.pendingPlanApproval&&l!=="delegate"?Number.POSITIVE_INFINITY:void 0),y=e.pendingInputState?.options.map(w=>({label:w}))??[],c=!t||t.length===0?y:r&&r.options.length>0&&r.options.length<=6&&!r.options.some(w=>w.isOther)&&!r.multiSelect?r.options:t.length===1&&r&&r.options.length===0?y:[],h=e.pendingPlanApproval&&l==="ask"&&!u?this.deps.getPlanApprovalButtons(e.id,{...e,planDecisionVersion:d}):!e.pendingPlanApproval&&c.length?this.deps.getQuestionButtons(e.id,c,{requestId:e.pendingInputState?.requestId,questionId:r?.id}):void 0,v=Lo(e,d),b=r?tf(r):[],A=r?ef({question:r,index:e.pendingInputState?.activeQuestionIndex??0,total:t?.length??1,optionDescriptions:b}):f,I=!e.pendingPlanApproval&&this.deps.questionContextSummaryProvider?await Xa({sessionName:e.name,question:A??S,context:g,provider:this.deps.questionContextSummaryProvider}):void 0,R=xo({session:e,preview:S,questionText:e.pendingPlanApproval?void 0:A,questionContextPreview:g,questionContextSummary:I,planArtifact:v,originThreadLine:this.deps.originThreadLine(e),planApprovalMode:l,planApprovalButtons:h,questionButtons:e.pendingPlanApproval?void 0:h}),m=R.planReviewSummary??S;if(R.label==="plan-approval"&&l==="ask"&&u){this.deps.dispatchSessionNotification(e,{label:R.label,idempotencyKey:`plan-approval:${e.id}:v${d??"unknown"}:canonical`,userMessage:R.userMessage,userMessages:R.userMessages,notifyUser:"never",buttons:R.buttons,wakeMessage:R.wakeMessage});return}if(R.label==="plan-approval"&&l==="ask"){this.deps.dispatchSessionNotification(e,{label:R.label,idempotencyKey:`plan-approval:${e.id}:v${d??"unknown"}:canonical`,userMessage:R.userMessage,userMessages:R.userMessages,notifyUser:"always",buttons:R.buttons,hooks:{onNotifyStarted:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.deps.updatePersistedSession(e.id,{canonicalPlanPromptVersion:d,approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.deps.updatePersistedSession(e.id,{approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},shouldDispatch:()=>vt(e,d),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(e,d,m),wakeMessageOnNotifySuccess:He(e,d)});return}if(R.label==="plan-approval"){this.deps.dispatchSessionNotification(e,{label:R.label,idempotencyKey:`plan-approval:${e.id}:v${d??"unknown"}:wake-only`,userMessage:R.userMessage,wakeMessage:R.wakeMessage,notifyUser:"never",buttons:R.buttons});return}this.deps.dispatchSessionNotification(e,{label:R.label,idempotencyKey:`waiting:${e.id}:${s??`${R.label}:${R.userMessage}`}`,userMessage:R.userMessage,notifyUser:"always",buttons:R.buttons,shouldDispatch:o?()=>nf(e,o,i):void 0,wakeMessageOnNotifyFailed:R.wakeMessage})}emitTurnComplete(e){`${e.id}${e.result?.num_turns??0}${e.worktreeStrategy??"none"}`;let t=vo({session:e,originThreadLine:this.deps.originThreadLine(e),preview:this.deps.getOutputPreview(e)});this.deps.dispatchSessionNotification(e,{label:"turn-complete",idempotencyKey:`turn-complete:${e.id}:${rf(e)}`,userMessage:t.userMessage,wakeMessage:t.wakeMessage,notifyUser:"always",onUserNotifyFailed:()=>{`${e.id}`,this.deps.shouldEmitTerminalWake(e)&&this.emitCompleted(e)}})}emitCompleted(e){let t=this.deps.getOutputPreview(e),r=this.shouldRequestCompletionFollowup(e),o=yo({session:e,originThreadLine:this.deps.originThreadLine(e),preview:t}),i=Za(e),s=`terminal:${e.id}:${i}`,a;this.deps.dispatchSessionNotification(e,{label:"completed",idempotencyKey:`terminal-completed:${e.id}:${i}`,userMessage:o.userMessage,notifyUser:"always",completionSummary:{required:r,producer:"terminal",outcomeKey:s},completionWakeSummaryRequired:r,completionWakeOutcomeKey:s,requireDirectUserNotification:!0,wakeMessageOnNotifySuccess:r?o.wakeMessageOnNotifySuccess:void 0,wakeMessageOnNotifyFailed:r?o.wakeMessageOnNotifyFailed:void 0,hooks:{onNotifySucceeded:()=>{a=!0,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_succeeded",canonicalStatusDelivered:a,followupSummaryRequired:r})},onNotifyFailed:()=>{a=!1,this.logCompletionWakeDiagnostic({session:e,event:"completion_notify_failed",canonicalStatusDelivered:a,followupSummaryRequired:r})},onWakeSucceeded:()=>{this.logCompletionWakeDiagnostic({session:e,event:"completion_wake_succeeded",canonicalStatusDelivered:a,followupSummaryRequired:r})}}})}emitFailed(e,t,r){let o=ko({session:e,originThreadLine:this.deps.originThreadLine(e),errorSummary:t,preview:this.deps.getOutputPreview(e),worktreeAutoCleaned:r,failedButtons:this.deps.getResumeButtons(e.id,e)});this.deps.dispatchSessionNotification(e,{label:"failed",idempotencyKey:`terminal-failed:${e.id}:${Za(e)}:${t}`,userMessage:o.userMessage,wakeMessage:o.wakeMessage,notifyUser:"always",buttons:o.buttons})}};import{existsSync as of}from"fs";var gr=class{constructor(e){this.deps=e}deps;async dismissWorktree(e){let t=this.deps.getPersistedSession(e),r=this.deps.resolveActiveSession(e),o=r??t;if(!o)return`Error: Session "${e}" not found.`;let i=r?.worktreePath??t?.worktreePath,s=this.deps.resolveWorktreeRepoDir(r?.originalWorkdir??t?.workdir,i),a=r?.worktreeBranch??t?.worktreeBranch,l=r?.name??t?.name??e;if(!s)return`Error: No workdir found for session "${e}".`;let d=L(o);!d&&i&&of(i)&&B(s,i,{destructive:!0}),a&&H(s,a);for(let f of z(r??t))this.deps.updatePersistedSession(f,{worktreeDisposition:"dismissed",worktreeDismissedAt:new Date().toISOString(),pendingWorktreeDecisionSince:void 0,worktreeState:"dismissed",lifecycle:"terminal",worktreePath:void 0,worktreeBranch:void 0,worktreeLifecycle:{state:"dismissed",updatedAt:new Date().toISOString(),resolvedAt:new Date().toISOString(),resolutionSource:"dismiss",baseBranch:t?.worktreeLifecycle?.baseBranch,targetRepo:t?.worktreePrTargetRepo,pushRemote:t?.worktreePushRemote}});let u=d?`ποΈ [${l}] Branch \`${a??"unknown"}\` dismissed. Native backend worktree released for backend cleanup.`:`ποΈ [${l}] Branch \`${a??"unknown"}\` dismissed and permanently deleted.`;return this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:D(r??t??{id:e})??e,sessionId:t?.sessionId,harnessSessionId:r?.harnessSessionId??t?.harnessSessionId,backendRef:r?.backendRef??t?.backendRef,route:r?.route??t?.route}),{label:"worktree-dismissed",idempotencyKey:`worktree-dismissed:${D(r??t??{id:e})??e}:${a??"unknown"}`,userMessage:u,notifyUser:"always"}),u}snoozeWorktreeDecision(e,t={}){let r=this.deps.getPersistedSession(e);if(!r)return`Error: Session "${e}" not found.`;let o=Date.now(),i=new Date(o+1440*60*1e3).toISOString();for(let l of z(r))this.deps.updatePersistedSession(l,{worktreeDecisionSnoozedUntil:i,lastWorktreeReminderAt:new Date(o).toISOString()});let a=`βοΈ Reminder snoozed 24h for \`${r.worktreeBranch??"unknown"}\` (session: ${r.name})`;return t.notifyUser!==!1&&this.deps.dispatchNotification(this.deps.buildRoutingProxy({id:D(r)??C(r)??r.harnessSessionId,sessionId:r.sessionId,harnessSessionId:r.harnessSessionId,backendRef:r.backendRef,route:r.route}),{label:"worktree-snoozed",idempotencyKey:`worktree-snoozed:${D(r)??C(r)??r.harnessSessionId}:${i}`,userMessage:a,notifyUser:"always"}),a}};var tl=new Set(["starting","running"]);function nl(n,e){JSON.stringify({component:"SessionRuntimeRegistry",event:n,at:new Date().toISOString(),...e})}function rl(n){return{sessionId:n.id,name:n.name,status:n.status,lifecycle:n.lifecycle,runtimeState:n.runtimeState,harness:n.harnessName,hasHarnessSessionId:!!n.harnessSessionId,backendRefKind:n.backendRef?.kind,hasBackendConversationId:!!n.backendRef?.conversationId,hasBackendRunId:!!n.backendRef?.runId,hasBackendWorktreeId:!!n.backendRef?.worktreeId,hasBackendWorktreePath:!!n.backendRef?.worktreePath}}var hr=class{sessions=new Map;activeSessionCount(){return[...this.sessions.values()].filter(e=>tl.has(e.status)).length}uniqueName(e){let t=new Set([...this.sessions.values()].filter(o=>tl.has(o.status)).map(o=>o.name));if(!t.has(e))return e;let r=2;for(;t.has(`${e}-${r}`);)r+=1;return`${e}-${r}`}add(e,t="spawn"){nl("runtime.add",{reason:t,...rl(e),activeCountBefore:this.activeSessionCount()}),this.sessions.set(e.id,e)}remove(e,t="unknown"){let r=this.sessions.get(e);nl("runtime.remove",{reason:t,sessionId:e,existed:!!r,...r?rl(r):{},activeCountBefore:this.activeSessionCount()}),this.sessions.delete(e)}get(e){return this.sessions.get(e)}list(){return[...this.sessions.values()]}};var yr=class{constructor(e){this.deps=e}deps;initializeSession(e,t,r,o={}){if(this.deps.hydrateSpawnedSession(e,t,r),r.taskLifecycle?.create(e),e.on("statusChange",(i,s)=>{s==="running"?(e.harnessSessionId&&this.deps.markRunning(e),r.taskLifecycle?.progress(e)):(s==="completed"||s==="failed"||s==="killed")&&(r.taskLifecycle?.finalize(e),this.deps.handleTerminal(e).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTerminal threw for session ${e.id}:`,a)}))}),e.on("lifecycleChange",(i,s)=>{r.taskLifecycle?.progress(e)}),e.on("turnEnd",(i,s)=>{this.deps.handleTurnEnd(e,s).catch(a=>{console.error(`[SessionRuntimeBootstrap] handleTurnEnd threw for session ${e.id}:`,a)})}),o.startAfter?o.startAfter.then(()=>e.start()).catch(i=>{console.error(`[SessionRuntimeBootstrap] deferred start threw for session ${e.id}:`,i)}):e.start(),o.notifyLaunch!==!1){let i=this.buildLaunchNotification(e);this.deps.notifySession(e,i.text,i.label,i.idempotencyKey)}return e}buildLaunchNotification(e){let t=this.deps.formatLaunchWorkdirLabel(e),r=ge({harness:e.harnessName,model:e.model})??"default";return e.resumeSessionId?{text:Qt({sessionName:e.name,resumedFromSessionName:e.resumedFromSessionName,workdirLabel:t,harnessLabel:r}),label:"resumed-launch",idempotencyKey:`resumed-launch:${e.id}:${e.startedAt}:${e.resumeSessionId}`}:{text:`π [${e.name}] Launched | ${t} | ${r}`,label:"launch"}}};var Sr=class{buildNoChangeNotification(e){let{session:t,nativeBackendWorktree:r,cleanupSucceeded:o,worktreePath:i,worktreeBranch:s,preview:a,originThreadLine:l,preservedSummary:d,remoteOutcome:u}=e,f=d?"preserved":o?"cleaned":"cleanup-failed",g=[s?.trim()||"unknown-branch",i.trim()||"unknown-worktree",t.startedAt].join(":"),S=d??(o?r?"native backend worktree released for backend cleanup":"worktree cleaned up":`cleanup failed; worktree still exists at ${i}`),y=ye({costUsd:t.costUsd,duration:typeof t.completedAt=="number"?t.completedAt-t.startedAt:void 0,harnessName:t.harnessName,model:t.model}),c=u==="pr-updated"?"PR updated; no local worktree changes remained to merge":u==="pr-opened"?"PR opened; no local worktree changes remained to merge":"Session completed with no worktree changes to merge",h=u==="pr-updated"?`PR updated; no local worktree changes remained to merge β ${S}`:u==="pr-opened"?`PR opened; no local worktree changes remained to merge β ${S}`:void 0,v=u==="pr-updated"?"PR updated; no local worktree changes remained to merge":u==="pr-opened"?"PR opened; no local worktree changes remained to merge":"Session completed with no worktree changes to merge",b=u==="pr-updated"?"Coding agent session updated a PR; no local worktree changes remained to merge.":u==="pr-opened"?"Coding agent session opened a PR; no local worktree changes remained to merge.":void 0;return{label:d?"worktree-no-changes-preserved":o?"worktree-no-changes":"worktree-no-changes-cleanup-failed",idempotencyKey:`worktree-no-change:${t.id}:${f}:${g}`,userMessage:d?`βΉοΈ [${t.name}] ${c} β ${d}${y}`:o?r?`βΉοΈ [${t.name}] ${c} β native backend worktree released for backend cleanup${y}`:`βΉοΈ [${t.name}] ${c} β worktree cleaned up${y}`:`β οΈ [${t.name}] ${v}, but worktree cleanup failed. Worktree still exists at ${i}${y}`,wakeMessage:bo({sessionName:t.name,sessionId:t.id,headline:b,cleanupSummary:h??S,preview:a,originThreadLine:l,requestedPermissionMode:t.requestedPermissionMode,currentPermissionMode:t.currentPermissionMode,approvalExecutionState:t.approvalExecutionState,approvalState:t.approvalState,planApproval:t.planApproval,approvalPromptStatus:t.approvalPromptStatus,approvalPromptMessageKind:t.approvalPromptMessageKind,approvalPromptDeliveredAt:t.approvalPromptDeliveredAt}),notifyUser:"always"}}buildAskNotification(e){let{session:t,branchName:r,baseBranch:o,diffSummary:i,buttons:s,summaryLines:a=[],policyReason:l}=e,d=i.commitMessages.slice(0,5).map(g=>`β’ ${g.hash} ${g.message} (${g.author})`),u=i.commits>5?`...and ${i.commits-5} more`:"",f=t.worktreePrTargetRepo?`Branch: \`${r}\` β \`${o}\` | PR target: ${t.worktreePrTargetRepo}`:`Branch: \`${r}\` β \`${o}\``;return{label:"worktree-merge-ask",idempotencyKey:["worktree-decision",t.id,r,o,i.commits,i.commitMessages.map(g=>g.hash).join(",")].join(":"),userMessage:[`π Worktree decision required for session \`${t.name}\``,"",f,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`,"",...a.length>0?["Summary:",...a.map(g=>`- ${g}`),""]:[],...l?[`Policy: ${l}`,""]:[],"Recent commits:",...d,...u?[u]:[],"",`β οΈ Discard will permanently delete branch \`${r}\` and all local changes. This cannot be undone.`].join(`
|
|
213
213
|
`),notifyUser:"always",buttons:s,wakeMessageOnNotifySuccess:["Worktree decision buttons delivered to the user.",`Session: ${t.name} | ID: ${t.id}`,f,"Wait for their button callback β do NOT act on this worktree yourself."].join(`
|
|
214
214
|
`),wakeMessageOnNotifyFailed:[`π Worktree decision required for session \`${t.name}\``,"",f,`Commits: ${i.commits} | Files: ${i.filesChanged} | +${i.insertions} / -${i.deletions}`].join(`
|
|
215
215
|
`)}}buildDelegateNotification(e){let{session:t,branchName:r,baseBranch:o,diffSummary:i,policyReason:s,allowedActions:a,originThreadLine:l}=e,d=i.commitMessages.slice(0,5).map(g=>`β’ ${g.hash} ${g.message} (${g.author})`),u=i.commits>5?`...and ${i.commits-5} more`:void 0,f=t.prompt?t.prompt.slice(0,500):"(no prompt)";return{label:"worktree-delegate",idempotencyKey:["worktree-delegate",t.id,r,o,i.commits,i.commitMessages.map(g=>g.hash).join(",")].join(":"),wakeMessage:Po({sessionName:t.name,sessionId:t.id,branchName:r,baseBranch:o,promptSnippet:f,commitLines:d,moreNote:u,originThreadLine:l,diffSummary:i,allowedActions:a,policyReason:s}),notifyUser:"never"}}};function ol(n,e=1e3){let t=!Number.isFinite(e),r=typeof n.getOutput=="function"?n.getOutput():[],o=t?r.join(`
|
|
216
216
|
`):sf(n);return t?o:o.length>e?il(n)?Ii(o,e):Ti(o,e):o}function sf(n){let e=typeof n.getOutput=="function"?n.getOutput():[],t=e.join(`
|
|
217
217
|
`).trim();return t?il(n)?af(t)??t:e.slice(-20).join(`
|
|
218
218
|
`):""}function il(n){if(n.status==="completed"||n.killReason==="done")return!0;let e=n;return e.approvalState==="approved"||e.planModeApproved===!0||(e.planDecisionVersion??0)>0}function af(n){let t=n.split(/\n\s*\n+/).map(r=>r.trim()).filter(r=>/[A-Za-z0-9]/.test(r)).at(-1);if(t)return t.length>=120||t.includes(`
|
|
219
|
-
`)?t:void 0}import{unlinkSync as lf}from"fs";var kr=class n{timers=new Map;disposed=!1;static MAX_DELAY_MS=2147483647;schedule(e,t,r){if(this.disposed||(this.cancel(e),!Number.isFinite(t)))return;let o=Math.max(0,t-Date.now()),i=setTimeout(()=>{if(this.timers.delete(e),!this.disposed){if(t-Date.now()>0){this.schedule(e,t,r);return}r()}},Math.min(o,n.MAX_DELAY_MS));i.unref?.(),this.timers.set(e,i)}cancel(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}cancelPrefix(e){for(let t of this.timers.keys())t.startsWith(e)&&this.cancel(t)}dispose(){this.disposed=!0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var sl=10080*60*1e3,df=300*1e3,al="tmp-output:cleanup",uf=60*1e3;function cf(n){return n instanceof Error?n.message:String(n)}var vr=class{constructor(e){this.deps=e}deps;scheduler=new kr;lastTmpOutputCleanupAttemptAt;schedule(e,t,r){this.scheduler.schedule(e,t,r)}cancel(e){this.scheduler.cancel(e)}cancelPrefix(e){this.scheduler.cancelPrefix(e)}bootstrapMaintenanceSchedules(){let e=Date.now();this.runTmpOutputCleanup(e);for(let t of this.deps.store.listPersistedSessions())this.syncPersistedSessionMaintenance(t);this.syncActionTokenExpiryDeadline(),this.deps.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let t=this.runtimeGcKey(e.id);this.schedule(t,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let r=this.deps.sessions.get(e.id);if(!r||!r.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.deps.store.shouldGcActiveSession(r,Date.now(),o)){this.syncRuntimeGcDeadline(r);return}this.deps.removeRuntimeSession(e.id,"runtime-gc"),this.deps.persistSession(r,{scheduleRuntimeGc:!1}),this.deps.clearRuntimeSessionState(e.id)})}cancelRuntimeGc(e){this.cancel(this.runtimeGcKey(e))}cancelPersistedMaintenance(e){let t=this.persistedMaintenanceRef(e);t&&this.cancelPrefix(`persisted:${t}:`)}syncPersistedSessionMaintenance(e){let t=this.persistedMaintenanceRef(e);if(!t)return;this.cancel(this.persistedMaintenanceKey(t,"worktree-reminder"));let r=this.deps.reminders.getNextReminderAt(e);r!=null?this.schedulePersistedWorktreeReminder(t,r):this.deps.reminders.clearResolvedReminderState(e),this.cancel(this.persistedMaintenanceKey(t,"worktree-retention"));let o=Oe(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),i=this.resolvedAtIso(e),s=this.isLegacyResolvedWorktree(e);if((o.cleanupSafe||s)&&typeof i=="string"){let a=new Date(i).getTime();Number.isFinite(a)&&this.schedule(this.persistedMaintenanceKey(t,"worktree-retention"),a+sl,()=>{let l=this.deps.store.getPersistedSession(t);l&&this.reconcileResolvedWorktreeRetention(l,Date.now())})}}reconcileResolvedWorktreeRetention(e,t){let r=Oe(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=this.resolvedAtIso(e),i=o?new Date(o).getTime():0,s=this.legacyResolvedWorktreeState(e);if(!(!r.cleanupSafe&&!s||!o||!Number.isFinite(i)||t-i<sl))try{if(!e.worktreePath&&!L(e))return;let a=this.deps.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let l=L(e)?!1:B(a,e.worktreePath);if(!L(e)&&!l)return;for(let d of z(e))this.deps.updatePersistedSession(d,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0,worktreeLifecycle:{...e.worktreeLifecycle??r.lifecycle,state:r.cleanupSafe?r.derivedState:s??r.derivedState,updatedAt:new Date(t).toISOString(),resolvedAt:e.worktreeLifecycle?.resolvedAt??o,resolutionSource:e.worktreeLifecycle?.resolutionSource??"maintenance",notes:r.reasons}})}catch(a){`${e.worktreePath}${cf(a)}`}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.cancel(e);let t=this.deps.store.getNextActionTokenExpiry();t!=null&&this.schedule(e,t,()=>{this.deps.store.purgeExpiredActionTokens(Date.now())||this.syncActionTokenExpiryDeadline()})}syncTmpOutputCleanupDeadline(e=Date.now()){this.cancel(al);let t=this.deps.store.getNextTmpOutputCleanupAt(e);if(t==null){this.lastTmpOutputCleanupAttemptAt=void 0;return}t>e&&(this.lastTmpOutputCleanupAttemptAt=void 0),this.schedule(al,this.getTmpOutputCleanupScheduleAt(t,e),()=>{let r=Date.now();this.runTmpOutputCleanup(r),this.syncTmpOutputCleanupDeadline(r)})}enforcePersistedRetention(){let e=this.deps.store.evictOldestPersisted(this.deps.getMaxPersistedSessions());for(let t of e)this.cancelPersistedMaintenance(t),t.sessionId&&this.cancelRuntimeGc(t.sessionId),this.cleanupOutputPathIfUnreferenced(t.outputPath)}dispose(){this.scheduler.dispose()}persistedMaintenanceRef(e){return e.sessionId??C(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,t){return`persisted:${e}:${t}`}runtimeGcMaxAgeMs(){return(_.sessionGcAgeMinutes??1440)*6e4}runTmpOutputCleanup(e){this.lastTmpOutputCleanupAttemptAt=e,this.deps.store.cleanupTmpOutputFiles(e)}getTmpOutputCleanupScheduleAt(e,t){if(e>t||this.lastTmpOutputCleanupAttemptAt==null)return e;let r=this.lastTmpOutputCleanupAttemptAt+uf;return r>t?r:e}schedulePersistedWorktreeReminder(e,t){let r=this.persistedMaintenanceKey(e,"worktree-reminder");this.schedule(r,t,()=>{let o=this.deps.store.getPersistedSession(e);if(!o||this.deps.reminders.sendReminderIfDue(o,Date.now()))return;let s=this.deps.reminders.getNextReminderAt(o);s!=null&&this.schedulePersistedWorktreeReminder(e,Math.max(s,Date.now()+df))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{lf(e)}catch{}}resolvedAtIso(e){return e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0)}isLegacyResolvedWorktree(e){return this.legacyResolvedWorktreeState(e)!=null}legacyResolvedWorktreeState(e){if(e.worktreeMerged===!0||e.worktreeDisposition==="merged"||e.worktreeState==="merged")return"merged";if(e.worktreeDisposition==="dismissed"||e.worktreeState==="dismissed")return"dismissed";if(e.worktreeDisposition==="no-change-cleaned")return"no_change"}};var ll=new Set(["completed","failed","killed"]),pf=new Set(["starting","running"]),mf=5e3;function ff(n,e){return dl("sha256").update(JSON.stringify({route:n.route?{provider:n.route.provider,target:n.route.target,accountId:n.route.accountId,threadId:n.route.threadId,sessionKey:n.route.sessionKey}:void 0,prompt:n.prompt,workdir:n.workdir,name:n.name,model:n.model,reasoningEffort:n.reasoningEffort,fastMode:n.fastMode,systemPrompt:n.systemPrompt,allowedTools:n.allowedTools?[...n.allowedTools].sort():n.allowedTools,resumeSessionId:n.resumeSessionId,resumedFromSessionName:n.resumedFromSessionName,resumeWorktreeFrom:n.resumeWorktreeFrom,sessionIdOverride:n.sessionIdOverride,clearedPersistedCodexResume:n.clearedPersistedCodexResume,forkSession:n.forkSession,forceNewSession:n.forceNewSession,permissionMode:n.permissionMode,planApproval:n.planApproval,harness:n.harness,worktreeStrategy:n.worktreeStrategy,effectiveWorktreeStrategy:e,worktreeBaseBranch:n.worktreeBaseBranch,worktreePrTargetRepo:n.worktreePrTargetRepo,originAgentId:n.originAgentId})).digest("hex").slice(0,16)}function gf(n){return dl("sha256").update(JSON.stringify({route:n.route?{provider:n.route.provider,target:n.route.target,accountId:n.route.accountId,threadId:n.route.threadId,sessionKey:n.route.sessionKey}:void 0,prompt:n.launchPrompt,workdir:n.launchWorkdir,name:n.launchName,model:n.launchModel,reasoningEffort:n.launchReasoningEffort,fastMode:n.launchFastMode,systemPrompt:n.launchSystemPrompt,allowedTools:n.launchAllowedTools?[...n.launchAllowedTools].sort():n.launchAllowedTools,resumeSessionId:n.launchResumeSessionId,resumedFromSessionName:n.launchResumedFromSessionName,resumeWorktreeFrom:n.launchResumeWorktreeFrom,sessionIdOverride:n.launchSessionIdOverride,clearedPersistedCodexResume:n.launchClearedPersistedCodexResume,forkSession:n.launchForkSession,forceNewSession:n.launchForceNewSession,permissionMode:n.launchPermissionMode,planApproval:n.launchPlanApproval,harness:n.launchHarness,worktreeStrategy:n.launchWorktreeStrategy,worktreeBaseBranch:n.launchWorktreeBaseBranch,worktreePrTargetRepo:n.launchWorktreePrTargetRepo,originAgentId:n.launchOriginAgentId})).digest("hex").slice(0,16)}var Pr=class n{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new ze;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;maintenance;pendingPlanResumeClaims=new Map;constructor(e=20,t=50,r={}){this.maxSessions=e,this.maxPersistedSessions=t;let o=n.createServiceBundle(this,r);this.registry=o.registry,this.sessions=o.sessions,this.store=o.store,this.metrics=o.metrics,this.wakeDispatcher=o.wakeDispatcher,this.interactions=o.interactions,this.notifications=o.notifications,this.worktrees=o.worktrees,this.questions=o.questions,this.lifecycle=o.lifecycle,this.restore=o.restore,this.stateSync=o.stateSync,this.references=o.references,this.worktreeStrategy=o.worktreeStrategy,this.worktreeDecisions=o.worktreeDecisions,this.runtimeBootstrap=o.runtimeBootstrap,this.worktreeMessages=o.worktreeMessages,this.maintenance=o.maintenance,this.reconcilePersistedTaskFlowMirrors()}static createServiceBundle(e,t){let r=new hr,o=r.sessions,i=new Xn(t.store),s=new Zn,a=new rr,l=new or(i.actionTokenStore,Je),d=new Bn(o,i),u=new Ln({store:i,sessions:o,resolveSession:m=>d.resolveActive(m)}),f=new lr(a,(m,w)=>u.applySessionPatch(m,w),{getPersistedSession:m=>i.getPersistedSession(m)}),g=new dr,S=new Fn(m=>i.getPersistedSession(m)),y=new Sr,c=new jn({shouldRunWorktreeStrategy:m=>e.shouldRunWorktreeStrategy(m),isAlreadyMerged:m=>e.isAlreadyMerged(m),resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),getWorktreeCompletionState:(m,w,T,F)=>e.getWorktreeCompletionState(m,w,T,F),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),getPersistedSession:m=>i.getPersistedSession(m),dispatchSessionNotification:(m,w)=>e.dispatchSessionNotification(m,w),getOutputPreview:(m,w)=>e.getOutputPreview(m,w),originThreadLine:m=>e.originThreadLine(m),getWorktreeDecisionButtons:m=>e.getWorktreeDecisionButtons(m),getPolicyAwareWorktreeDecisionButtons:(m,w,T)=>e.getWorktreeDecisionButtons(m,w,T),makeOpenPrButton:m=>e.makeActionButton(m,"worktree-create-pr","Open PR"),isPrAvailable:m=>e.resolveRepoPolicy(m).prAvailable,hasOpenPrForBranch:(m,w,T)=>{let F=nt(m,w,T);return F.exists&&F.state==="open"},getPrStatusForBranch:(m,w,T)=>nt(m,w,T),getPrStatusForUrl:(m,w,T)=>Et(m,w,T),resolveRepoPolicy:m=>e.resolveRepoPolicy(m),worktreeSummaryProvider:t.worktreeSummaryProvider,worktreeMessages:y,enqueueMerge:(m,w,T)=>e.enqueueMerge(m,w,T),mergeBranch:$t,spawnConflictResolver:async({session:m,worktreePath:w,prompt:T})=>e.spawn({prompt:T,workdir:w,name:`${m.name}-conflict-resolver`,harness:m.harnessName||Y(),model:m.model,reasoningEffort:m.reasoningEffort,fastMode:m.fastMode,permissionMode:"bypassPermissions",multiTurn:!0,worktreeStrategy:"off",autoMergeParentSessionId:m.id,route:m.route,originChannel:m.originChannel,originThreadId:m.originThreadId,originAgentId:m.originAgentId,originSessionKey:m.originSessionKey},{notifyLaunch:!1}),runAutoPr:async(m,w)=>{let{makeAgentPrTool:T}=await import("./chunks/agent-pr.js");return{success:(await T().execute("auto-pr",{session:m.id,base_branch:w}))?.meta?.success===!0}}}),h=new ur(e.pendingAskUserQuestions,(m,w)=>e.dispatchSessionNotification(m,w),m=>{e.clearWaitingTimestampsForSession(m)},(m,w,T)=>l.getQuestionButtons(m,w,T)),v=new cr(m=>e.buildRoutingProxy(m),(m,w)=>f.dispatch(m,w),(m,w)=>e.updatePersistedSession(m,w),(m,w)=>e.getPolicyAwareWorktreeDecisionButtons(m,{},void 0,w)),R=new vr({store:i,sessions:o,reminders:v,removeRuntimeSession:(m,w)=>r.remove(m,w),persistSession:(m,w)=>e.persistSession(m,w),clearRuntimeSessionState:m=>{e.clearWaitingTimestampsForSession(m),e.lastTurnCompleteMarkers.delete(m),e.lastTerminalWakeMarkers.delete(m)},resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),getMaxPersistedSessions:()=>e.maxPersistedSessions});i.onActionTokensChanged(()=>e.syncActionTokenExpiryDeadline());let A=new fr({persistSession:m=>e.persistSession(m),clearWaitingTimestamp:m=>{e.clearWaitingTimestampsForSession(m)},handleWorktreeStrategy:m=>e.handleWorktreeStrategy(m),resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),dispatchSessionNotification:(m,w)=>e.dispatchSessionNotification(m,w),notifySession:(m,w,T,F)=>e.notifySession(m,w,T,F),clearRetryTimersForSession:m=>a.clearRetryTimersForSession(m),hasTurnCompleteWakeMarker:m=>e.lastTurnCompleteMarkers.has(m),shouldEmitTurnCompleteWake:m=>e.shouldEmitTurnCompleteWake(m),shouldEmitTerminalWake:m=>e.shouldEmitTerminalWake(m),resolvePlanApprovalMode:m=>e.resolvePlanApprovalMode(m),getPlanApprovalButtons:(m,w)=>l.getPlanApprovalButtons(m,w),getResumeButtons:(m,w)=>l.getResumeButtons(m,w),getQuestionButtons:(m,w,T)=>l.getQuestionButtons(m,w,T),extractLastOutputLine:m=>e.extractLastOutputLine(m),getOutputPreview:(m,w)=>e.getOutputPreview(m,w),originThreadLine:m=>e.originThreadLine(m),debounceWaitingEvent:(m,w)=>e.debounceWaitingEvent(m,w),isAlreadyMerged:m=>e.isAlreadyMerged(m),questionContextSummaryProvider:t.questionContextSummaryProvider??Ja()}),I=new gr({getPersistedSession:m=>i.getPersistedSession(m),resolveActiveSession:m=>d.resolveActive(m),resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),dispatchNotification:(m,w)=>f.dispatch(m,w),buildRoutingProxy:m=>e.buildRoutingProxy(m)}),b=new yr({hydrateSpawnedSession:(m,w,T)=>{S.hydrateSpawnedSession(m,w,T)},markRunning:m=>{i.markRunning(m),m.approvalState==="approved"&&m.planDecisionVersion>0&&l.consumePlanDecisionTokens(m.id,m.planDecisionVersion-1),e.pendingPlanResumeClaims.delete(m.id),e.onPersistedSessionChanged(i.getPersistedSession(m.id))},handleTerminal:async m=>{let w=e.pendingPlanResumeClaims.get(m.id);try{await e.onSessionTerminal(m)}finally{if(w){let T=_i(w,i.getPersistedSession(m.id));i.replacePersistedSession(T),e.pendingPlanResumeClaims.delete(m.id),e.onPersistedSessionChanged(T)}}},handleTurnEnd:(m,w)=>A.handleTurnEnd(m,w),formatLaunchWorkdirLabel:m=>e.formatLaunchWorkdirLabel(m),notifySession:(m,w,T,F)=>e.notifySession(m,w,T,F)});return{registry:r,sessions:o,store:i,metrics:s,wakeDispatcher:a,interactions:l,notifications:f,worktrees:g,questions:h,lifecycle:A,restore:S,stateSync:u,references:d,worktreeStrategy:c,worktreeDecisions:I,runtimeBootstrap:b,worktreeMessages:y,maintenance:R}}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(e){return this.registry.uniqueName(e)}syncRuntimeGcDeadline(e){this.maintenance.syncRuntimeGcDeadline(e)}onPersistedSessionChanged(e){e&&(this.syncPersistedSessionMaintenance(e),this.enforcePersistedRetention())}syncPersistedSessionMaintenance(e){this.maintenance.syncPersistedSessionMaintenance(e)}syncActionTokenExpiryDeadline(){this.maintenance.syncActionTokenExpiryDeadline()}syncTmpOutputCleanupDeadline(e=Date.now()){this.maintenance.syncTmpOutputCleanupDeadline(e)}enforcePersistedRetention(){this.maintenance.enforcePersistedRetention()}bootstrapMaintenanceSchedules(){this.maintenance.bootstrapMaintenanceSchedules()}disposeMaintenance(){this.maintenance.dispose()}spawn(e,t={}){if(this.registry.activeSessionCount()>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o,i,s=h=>{i=i?Promise.all([i,h]).then(()=>{}):h};if(e.resumeSessionId&&!e.forkSession){let h=this.registry.list().filter(R=>R.backendKind==="codex-app-server"&&(R.harnessSessionId===e.resumeSessionId||R.backendRef?.conversationId===e.resumeSessionId||!R.harnessSessionId&&!R.backendRef?.conversationId&&R.resumeSessionId===e.resumeSessionId)),v=h.find(R=>R.status==="starting"||R.status==="running");if(v)throw new Error(`Cannot resume backend thread ${e.resumeSessionId}: session ${v.id} still owns its active writer.`);for(let R of h)typeof R.waitForTeardown=="function"&&s(R.waitForTeardown())}if(e.sessionIdOverride){let h=this.getPersistedSession(e.sessionIdOverride);if(e.resumeSessionId&&h?.pendingPlanApproval){let R=an(h,e.permissionMode??_.permissionMode);e={...e,permissionMode:R.permissionMode,...R.patch},R.approvalApplied&&(o=h)}let v=this.registry.get(e.sessionIdOverride);if(v?.status==="starting"||v?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${v.status}.`);v&&(typeof v.waitForTeardown=="function"&&s(v.waitForTeardown()),this.registry.remove(v.id,"session-id-override-replacement")),this.clearWaitingTimestampsForSession(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancelRuntimeGc(e.sessionIdOverride)}let a=e.name||Ri(e.prompt),l=this.uniqueName(a);l!==a&&`${a}${l}`;let d=this.checkRepoPolicyForLaunch(e.workdir,e.worktreeStrategy);if(!d.ok){let h=d;throw new Error(h.text)}e.repoIntegrationPolicy=d.resolution.policy,e.repoIntegrationPolicySource=d.resolution.source==="none"?void 0:d.resolution.source,e.repoProvider=d.resolution.provider;let u=this.restore.prepareSpawn(e,l);if(!e.route?.provider||!e.route.target)throw new Error(`Cannot launch session "${l}": missing explicit route metadata.`);let f=e.harness??"claude-code",g=this,S,y=f==="claude-code"&&!e.canUseTool?async(h,v)=>{if(!S)throw new Error("canUseTool called before session ID was set");return g.handleAskUserQuestion(S,v)}:e.canUseTool,c=new mn({...e,workdir:u.actualWorkdir,systemPrompt:u.effectiveSystemPrompt,canUseTool:y},l);S=c.id,o&&this.pendingPlanResumeClaims.set(c.id,o),this.registry.add(c),this.metrics.incrementLaunched();try{return this.runtimeBootstrap.initializeSession(c,u,e,{...t,startAfter:i})}catch(h){throw this.pendingPlanResumeClaims.delete(c.id),h}}async spawnAndAwaitRunning(e,t={}){let r=this.spawn(e,t);return await this.waitForRunningSession(r),r}async waitForRunningSession(e){if(e.status==="running")return;if(ll.has(e.status))throw new Error(this.describeLaunchFailure(e));let t=e.on?.bind(e),r=e.off?.bind(e)??e.removeListener?.bind(e);if(!t||!r)throw new Error(`Session ${e.name} [${e.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(l,d)=>{if(d==="running"){a(),o();return}ll.has(d)&&(a(),i(new Error(this.describeLaunchFailure(e))))},a=()=>{r("statusChange",s)};t("statusChange",s)})}describeLaunchFailure(e){let t=e.killReason?` (reason: ${e.killReason})`:"",r=e.error||e.result?.result||`status=${e.status}${t}`;return`Session ${e.name} [${e.id}] failed to start: ${r}`}formatLaunchResult(e,t){return Ht({prompt:e.prompt,workdir:e.workdir,harness:e.harness,permissionMode:e.permissionMode??_.permissionMode,planApproval:e.planApproval,resumeSessionId:e.resumeSessionId,resumeSessionName:e.resumeSessionName,forkSession:e.forkSession,forceNewSession:e.forceNewSession,clearedPersistedCodexResume:e.clearedPersistedCodexResume},t)}shouldRunWorktreeStrategy(e){let t=e.lifecycle;return!(t==="starting"||t==="awaiting_plan_decision"||t==="awaiting_user_input"||e.pendingPlanApproval)}resolveRepoPolicy(e){let t=lt(e);if(!t)return{source:"none",provider:"unsupported",prAvailable:!1};let r=this.store.getRepoPolicy(t.key);if(r)return{identity:t,policy:r.policy,source:"stored",provider:t.provider,prAvailable:t.provider==="github"&&Je(),record:r};let o=us(t);if(o){let i=no(t,o,"seeded");return{identity:t,policy:o,source:"seeded",provider:t.provider,prAvailable:ro({provider:t.provider}),record:i}}return{identity:t,source:"unknown",provider:t.provider,prAvailable:ro({provider:t.provider})}}checkRepoPolicyForLaunch(e,t){let r=t??_.defaultWorktreeStrategy??"off",o=this.resolveRepoPolicy(e);return r==="off"?{ok:!0,resolution:o}:o.source==="none"?{ok:!0,resolution:o}:o.source==="unknown"&&o.identity?{ok:!1,text:oo(o.identity,r,o.prAvailable)}:{ok:!0,resolution:o}}getRepoPolicyRecordForWorkdir(e){return this.resolveRepoPolicy(e).record}listRepoPolicies(){return this.store.listRepoPolicies()}cleanupRepoPolicies(){let e=[...this.store.cleanupRepoPolicies()],t=[];for(let r of this.store.listRepoPolicies()){let o=lt(r.repoRoot);!o||o.key===r.key||t.push(r.key)}return e.push(...this.store.removeRepoPolicies(t)),e.sort((r,o)=>r.repoRoot.localeCompare(o.repoRoot)||r.key.localeCompare(o.key))}setRepoPolicy(e,t){let r=lt(e);if(r)return this.store.setRepoPolicy(no(r,t,"stored"))}resetRepoPolicy(e){let t=lt(e);return t?this.store.resetRepoPolicy(t.key):!1}requestRepoPolicyForLaunch(e){let t=e.worktreeStrategy??_.defaultWorktreeStrategy??"off",r=this.resolveRepoPolicy(e.workdir);if(!r.identity)return`Error: ${e.workdir} is not a git repository.`;let o=oo(r.identity,t,r.prAvailable);if(!e.route?.provider||!e.route.target)return o;let i=`repo-policy:${r.identity.key}`,s=this.interactions.getRepoPolicyChoiceButtons({choiceId:i,route:e.route,repoRoot:r.identity.repoRoot,launchPrompt:e.prompt,launchWorkdir:e.workdir,launchName:e.name,launchModel:e.model,launchReasoningEffort:e.reasoningEffort,launchFastMode:e.fastMode,launchSystemPrompt:e.systemPrompt,launchAllowedTools:e.allowedTools,launchResumeSessionId:e.resumeSessionId,launchResumedFromSessionName:e.resumedFromSessionName,launchResumeWorktreeFrom:e.resumeWorktreeFrom,launchSessionIdOverride:e.sessionIdOverride,launchClearedPersistedCodexResume:e.clearedPersistedCodexResume,launchForkSession:e.forkSession,launchForceNewSession:e.forceNewSession,launchPermissionMode:e.permissionMode,launchPlanApproval:e.planApproval,launchHarness:e.harness,launchWorktreeStrategy:t,launchWorktreeBaseBranch:e.worktreeBaseBranch,launchWorktreePrTargetRepo:e.worktreePrTargetRepo,launchOriginAgentId:e.originAgentId,prAvailable:r.prAvailable}),a=ff(e,t);return this.notifications.dispatch(this.buildRoutingProxy({id:i,name:"repo-policy",route:e.route}),{label:"repo-policy-choice",idempotencyKey:`repo-policy-choice:${r.identity.key}:${t}:${a}`,userMessage:[o,"","After you choose a policy, OpenClaw Code Agent will continue this launch automatically."].join(`
|
|
219
|
+
`)?t:void 0}import{unlinkSync as lf}from"fs";var kr=class n{timers=new Map;disposed=!1;static MAX_DELAY_MS=2147483647;schedule(e,t,r){if(this.disposed||(this.cancel(e),!Number.isFinite(t)))return;let o=Math.max(0,t-Date.now()),i=setTimeout(()=>{if(this.timers.delete(e),!this.disposed){if(t-Date.now()>0){this.schedule(e,t,r);return}r()}},Math.min(o,n.MAX_DELAY_MS));i.unref?.(),this.timers.set(e,i)}cancel(e){let t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}cancelPrefix(e){for(let t of this.timers.keys())t.startsWith(e)&&this.cancel(t)}dispose(){this.disposed=!0;for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var sl=10080*60*1e3,df=300*1e3,al="tmp-output:cleanup",uf=60*1e3;function cf(n){return n instanceof Error?n.message:String(n)}var vr=class{constructor(e){this.deps=e}deps;scheduler=new kr;lastTmpOutputCleanupAttemptAt;schedule(e,t,r){this.scheduler.schedule(e,t,r)}cancel(e){this.scheduler.cancel(e)}cancelPrefix(e){this.scheduler.cancelPrefix(e)}bootstrapMaintenanceSchedules(){let e=Date.now();this.runTmpOutputCleanup(e);for(let t of this.deps.store.listPersistedSessions())this.syncPersistedSessionMaintenance(t);this.syncActionTokenExpiryDeadline(),this.deps.store.cleanupOrphanOutputFiles(),this.syncTmpOutputCleanupDeadline(e)}syncRuntimeGcDeadline(e){if(!e.completedAt)return;let t=this.runtimeGcKey(e.id);this.schedule(t,e.completedAt+this.runtimeGcMaxAgeMs(),()=>{let r=this.deps.sessions.get(e.id);if(!r||!r.completedAt)return;let o=this.runtimeGcMaxAgeMs();if(!this.deps.store.shouldGcActiveSession(r,Date.now(),o)){this.syncRuntimeGcDeadline(r);return}this.deps.removeRuntimeSession(e.id,"runtime-gc"),this.deps.persistSession(r,{scheduleRuntimeGc:!1}),this.deps.clearRuntimeSessionState(e.id)})}cancelRuntimeGc(e){this.cancel(this.runtimeGcKey(e))}cancelPersistedMaintenance(e){let t=this.persistedMaintenanceRef(e);t&&this.cancelPrefix(`persisted:${t}:`)}syncPersistedSessionMaintenance(e){let t=this.persistedMaintenanceRef(e);if(!t)return;this.cancel(this.persistedMaintenanceKey(t,"worktree-reminder"));let r=this.deps.reminders.getNextReminderAt(e);r!=null?this.schedulePersistedWorktreeReminder(t,r):this.deps.reminders.clearResolvedReminderState(e),this.cancel(this.persistedMaintenanceKey(t,"worktree-retention"));let o=Oe(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),i=this.resolvedAtIso(e),s=this.isLegacyResolvedWorktree(e);if((o.cleanupSafe||s)&&typeof i=="string"){let a=new Date(i).getTime();Number.isFinite(a)&&this.schedule(this.persistedMaintenanceKey(t,"worktree-retention"),a+sl,()=>{let l=this.deps.store.getPersistedSession(t);l&&this.reconcileResolvedWorktreeRetention(l,Date.now())})}}reconcileResolvedWorktreeRetention(e,t){let r=Oe(e,{activeSession:!1,includePrSync:e.worktreeLifecycle?.state==="pr_open"||!!e.worktreePrUrl}),o=this.resolvedAtIso(e),i=o?new Date(o).getTime():0,s=this.legacyResolvedWorktreeState(e);if(!(!r.cleanupSafe&&!s||!o||!Number.isFinite(i)||t-i<sl))try{if(!e.worktreePath&&!L(e))return;let a=this.deps.resolveWorktreeRepoDir(e.workdir,e.worktreePath);if(!a)return;let l=L(e)?!1:B(a,e.worktreePath);if(!L(e)&&!l)return;for(let d of z(e))this.deps.updatePersistedSession(d,{worktreePath:void 0,worktreeBranch:void 0,worktreeState:"none",pendingWorktreeDecisionSince:void 0,lastWorktreeReminderAt:void 0,worktreeDecisionSnoozedUntil:void 0,worktreeLifecycle:{...e.worktreeLifecycle??r.lifecycle,state:r.cleanupSafe?r.derivedState:s??r.derivedState,updatedAt:new Date(t).toISOString(),resolvedAt:e.worktreeLifecycle?.resolvedAt??o,resolutionSource:e.worktreeLifecycle?.resolutionSource??"maintenance",notes:r.reasons}})}catch(a){`${e.worktreePath}${cf(a)}`}}syncActionTokenExpiryDeadline(){let e="tokens:expiry";this.cancel(e);let t=this.deps.store.getNextActionTokenExpiry();t!=null&&this.schedule(e,t,()=>{this.deps.store.purgeExpiredActionTokens(Date.now())||this.syncActionTokenExpiryDeadline()})}syncTmpOutputCleanupDeadline(e=Date.now()){this.cancel(al);let t=this.deps.store.getNextTmpOutputCleanupAt(e);if(t==null){this.lastTmpOutputCleanupAttemptAt=void 0;return}t>e&&(this.lastTmpOutputCleanupAttemptAt=void 0),this.schedule(al,this.getTmpOutputCleanupScheduleAt(t,e),()=>{let r=Date.now();this.runTmpOutputCleanup(r),this.syncTmpOutputCleanupDeadline(r)})}enforcePersistedRetention(){let e=this.deps.store.evictOldestPersisted(this.deps.getMaxPersistedSessions());for(let t of e)this.cancelPersistedMaintenance(t),t.sessionId&&this.cancelRuntimeGc(t.sessionId),this.cleanupOutputPathIfUnreferenced(t.outputPath)}dispose(){this.scheduler.dispose()}persistedMaintenanceRef(e){return e.sessionId??C(e)??e.harnessSessionId}runtimeGcKey(e){return`runtime-gc:${e}`}persistedMaintenanceKey(e,t){return`persisted:${e}:${t}`}runtimeGcMaxAgeMs(){return(_.sessionGcAgeMinutes??1440)*6e4}runTmpOutputCleanup(e){this.lastTmpOutputCleanupAttemptAt=e,this.deps.store.cleanupTmpOutputFiles(e)}getTmpOutputCleanupScheduleAt(e,t){if(e>t||this.lastTmpOutputCleanupAttemptAt==null)return e;let r=this.lastTmpOutputCleanupAttemptAt+uf;return r>t?r:e}schedulePersistedWorktreeReminder(e,t){let r=this.persistedMaintenanceKey(e,"worktree-reminder");this.schedule(r,t,()=>{let o=this.deps.store.getPersistedSession(e);if(!o||this.deps.reminders.sendReminderIfDue(o,Date.now()))return;let s=this.deps.reminders.getNextReminderAt(o);s!=null&&this.schedulePersistedWorktreeReminder(e,Math.max(s,Date.now()+df))})}cleanupOutputPathIfUnreferenced(e){if(!(!e||this.deps.store.hasOutputPathReference(e)))try{lf(e)}catch{}}resolvedAtIso(e){return e.worktreeLifecycle?.resolvedAt??e.worktreeMergedAt??e.worktreeDismissedAt??(e.completedAt?new Date(e.completedAt).toISOString():void 0)}isLegacyResolvedWorktree(e){return this.legacyResolvedWorktreeState(e)!=null}legacyResolvedWorktreeState(e){if(e.worktreeMerged===!0||e.worktreeDisposition==="merged"||e.worktreeState==="merged")return"merged";if(e.worktreeDisposition==="dismissed"||e.worktreeState==="dismissed")return"dismissed";if(e.worktreeDisposition==="no-change-cleaned")return"no_change"}};var ll=new Set(["completed","failed","killed"]),pf=new Set(["starting","running"]),mf=5e3;function ff(n,e){return dl("sha256").update(JSON.stringify({route:n.route?{provider:n.route.provider,target:n.route.target,accountId:n.route.accountId,threadId:n.route.threadId,sessionKey:n.route.sessionKey}:void 0,prompt:n.prompt,workdir:n.workdir,name:n.name,model:n.model,reasoningEffort:n.reasoningEffort,fastMode:n.fastMode,systemPrompt:n.systemPrompt,allowedTools:n.allowedTools?[...n.allowedTools].sort():n.allowedTools,resumeSessionId:n.resumeSessionId,resumedFromSessionName:n.resumedFromSessionName,resumeWorktreeFrom:n.resumeWorktreeFrom,sessionIdOverride:n.sessionIdOverride,clearedPersistedCodexResume:n.clearedPersistedCodexResume,forkSession:n.forkSession,forceNewSession:n.forceNewSession,permissionMode:n.permissionMode,planApproval:n.planApproval,harness:n.harness,worktreeStrategy:n.worktreeStrategy,effectiveWorktreeStrategy:e,worktreeBaseBranch:n.worktreeBaseBranch,worktreePrTargetRepo:n.worktreePrTargetRepo,originAgentId:n.originAgentId})).digest("hex").slice(0,16)}function gf(n){return dl("sha256").update(JSON.stringify({route:n.route?{provider:n.route.provider,target:n.route.target,accountId:n.route.accountId,threadId:n.route.threadId,sessionKey:n.route.sessionKey}:void 0,prompt:n.launchPrompt,workdir:n.launchWorkdir,name:n.launchName,model:n.launchModel,reasoningEffort:n.launchReasoningEffort,fastMode:n.launchFastMode,systemPrompt:n.launchSystemPrompt,allowedTools:n.launchAllowedTools?[...n.launchAllowedTools].sort():n.launchAllowedTools,resumeSessionId:n.launchResumeSessionId,resumedFromSessionName:n.launchResumedFromSessionName,resumeWorktreeFrom:n.launchResumeWorktreeFrom,sessionIdOverride:n.launchSessionIdOverride,clearedPersistedCodexResume:n.launchClearedPersistedCodexResume,forkSession:n.launchForkSession,forceNewSession:n.launchForceNewSession,permissionMode:n.launchPermissionMode,planApproval:n.launchPlanApproval,harness:n.launchHarness,worktreeStrategy:n.launchWorktreeStrategy,worktreeBaseBranch:n.launchWorktreeBaseBranch,worktreePrTargetRepo:n.launchWorktreePrTargetRepo,originAgentId:n.launchOriginAgentId})).digest("hex").slice(0,16)}var Pr=class n{registry;sessions;maxSessions;maxPersistedSessions;lastWaitingEventTimestamps=new Map;lastTurnCompleteMarkers=new Map;lastTerminalWakeMarkers=new Map;mergeQueue=new ze;pendingAskUserQuestions=new Map;store;metrics;wakeDispatcher;interactions;notifications;worktrees;questions;lifecycle;restore;stateSync;references;worktreeStrategy;worktreeDecisions;runtimeBootstrap;worktreeMessages;maintenance;pendingPlanResumeClaims=new Map;constructor(e=20,t=50,r={}){this.maxSessions=e,this.maxPersistedSessions=t;let o=n.createServiceBundle(this,r);this.registry=o.registry,this.sessions=o.sessions,this.store=o.store,this.metrics=o.metrics,this.wakeDispatcher=o.wakeDispatcher,this.interactions=o.interactions,this.notifications=o.notifications,this.worktrees=o.worktrees,this.questions=o.questions,this.lifecycle=o.lifecycle,this.restore=o.restore,this.stateSync=o.stateSync,this.references=o.references,this.worktreeStrategy=o.worktreeStrategy,this.worktreeDecisions=o.worktreeDecisions,this.runtimeBootstrap=o.runtimeBootstrap,this.worktreeMessages=o.worktreeMessages,this.maintenance=o.maintenance,this.reconcilePersistedTaskFlowMirrors()}static createServiceBundle(e,t){let r=new hr,o=r.sessions,i=new Xn(t.store),s=new Zn,a=new rr,l=new or(i.actionTokenStore,Je),d=new Bn(o,i),u=new Ln({store:i,sessions:o,resolveSession:m=>d.resolveActive(m)}),f=new lr(a,(m,w)=>u.applySessionPatch(m,w),{getPersistedSession:m=>i.getPersistedSession(m)}),g=new dr,S=new Fn(m=>i.getPersistedSession(m)),y=new Sr,c=new jn({shouldRunWorktreeStrategy:m=>e.shouldRunWorktreeStrategy(m),isAlreadyMerged:m=>e.isAlreadyMerged(m),resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),getWorktreeCompletionState:(m,w,T,F)=>e.getWorktreeCompletionState(m,w,T,F),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),getPersistedSession:m=>i.getPersistedSession(m),dispatchSessionNotification:(m,w)=>e.dispatchSessionNotification(m,w),getOutputPreview:(m,w)=>e.getOutputPreview(m,w),originThreadLine:m=>e.originThreadLine(m),getWorktreeDecisionButtons:m=>e.getWorktreeDecisionButtons(m),getPolicyAwareWorktreeDecisionButtons:(m,w,T)=>e.getWorktreeDecisionButtons(m,w,T),makeOpenPrButton:m=>e.makeActionButton(m,"worktree-create-pr","Open PR"),isPrAvailable:m=>e.resolveRepoPolicy(m).prAvailable,hasOpenPrForBranch:(m,w,T)=>{let F=nt(m,w,T);return F.exists&&F.state==="open"},getPrStatusForBranch:(m,w,T)=>nt(m,w,T),getPrStatusForUrl:(m,w,T)=>Et(m,w,T),resolveRepoPolicy:m=>e.resolveRepoPolicy(m),worktreeSummaryProvider:t.worktreeSummaryProvider,worktreeMessages:y,enqueueMerge:(m,w,T)=>e.enqueueMerge(m,w,T),mergeBranch:$t,spawnConflictResolver:async({session:m,worktreePath:w,prompt:T})=>e.spawn({prompt:T,workdir:w,name:`${m.name}-conflict-resolver`,harness:m.harnessName||Y(),model:m.model,reasoningEffort:m.reasoningEffort,fastMode:m.fastMode,permissionMode:"bypassPermissions",multiTurn:!0,worktreeStrategy:"off",autoMergeParentSessionId:m.id,route:m.route,originChannel:m.originChannel,originThreadId:m.originThreadId,originAgentId:m.originAgentId,originSessionKey:m.originSessionKey},{notifyLaunch:!1}),runAutoPr:async(m,w)=>{let{makeAgentPrTool:T}=await import("./chunks/agent-pr.js");return{success:(await T().execute("auto-pr",{session:m.id,base_branch:w}))?.meta?.success===!0}}}),h=new ur(e.pendingAskUserQuestions,(m,w)=>e.dispatchSessionNotification(m,w),m=>{e.clearWaitingTimestampsForSession(m)},(m,w,T)=>l.getQuestionButtons(m,w,T)),v=new cr(m=>e.buildRoutingProxy(m),(m,w)=>f.dispatch(m,w),(m,w)=>e.updatePersistedSession(m,w),(m,w)=>e.getPolicyAwareWorktreeDecisionButtons(m,{},void 0,w)),b=new vr({store:i,sessions:o,reminders:v,removeRuntimeSession:(m,w)=>r.remove(m,w),persistSession:(m,w)=>e.persistSession(m,w),clearRuntimeSessionState:m=>{e.clearWaitingTimestampsForSession(m),e.lastTurnCompleteMarkers.delete(m),e.lastTerminalWakeMarkers.delete(m)},resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),getMaxPersistedSessions:()=>e.maxPersistedSessions});i.onActionTokensChanged(()=>e.syncActionTokenExpiryDeadline());let A=new fr({persistSession:m=>e.persistSession(m),clearWaitingTimestamp:m=>{e.clearWaitingTimestampsForSession(m)},handleWorktreeStrategy:m=>e.handleWorktreeStrategy(m),resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),dispatchSessionNotification:(m,w)=>e.dispatchSessionNotification(m,w),notifySession:(m,w,T,F)=>e.notifySession(m,w,T,F),clearRetryTimersForSession:m=>a.clearRetryTimersForSession(m),hasTurnCompleteWakeMarker:m=>e.lastTurnCompleteMarkers.has(m),shouldEmitTurnCompleteWake:m=>e.shouldEmitTurnCompleteWake(m),shouldEmitTerminalWake:m=>e.shouldEmitTerminalWake(m),resolvePlanApprovalMode:m=>e.resolvePlanApprovalMode(m),getPlanApprovalButtons:(m,w)=>l.getPlanApprovalButtons(m,w),getResumeButtons:(m,w)=>l.getResumeButtons(m,w),getQuestionButtons:(m,w,T)=>l.getQuestionButtons(m,w,T),extractLastOutputLine:m=>e.extractLastOutputLine(m),getOutputPreview:(m,w)=>e.getOutputPreview(m,w),originThreadLine:m=>e.originThreadLine(m),debounceWaitingEvent:(m,w)=>e.debounceWaitingEvent(m,w),isAlreadyMerged:m=>e.isAlreadyMerged(m),questionContextSummaryProvider:t.questionContextSummaryProvider??Ja()}),I=new gr({getPersistedSession:m=>i.getPersistedSession(m),resolveActiveSession:m=>d.resolveActive(m),resolveWorktreeRepoDir:(m,w)=>e.resolveWorktreeRepoDir(m,w),updatePersistedSession:(m,w)=>e.updatePersistedSession(m,w),dispatchNotification:(m,w)=>f.dispatch(m,w),buildRoutingProxy:m=>e.buildRoutingProxy(m)}),R=new yr({hydrateSpawnedSession:(m,w,T)=>{S.hydrateSpawnedSession(m,w,T)},markRunning:m=>{i.markRunning(m),m.approvalState==="approved"&&m.planDecisionVersion>0&&l.consumePlanDecisionTokens(m.id,m.planDecisionVersion-1),e.pendingPlanResumeClaims.delete(m.id),e.onPersistedSessionChanged(i.getPersistedSession(m.id))},handleTerminal:async m=>{let w=e.pendingPlanResumeClaims.get(m.id);try{await e.onSessionTerminal(m)}finally{if(w){let T=_i(w,i.getPersistedSession(m.id));i.replacePersistedSession(T),e.pendingPlanResumeClaims.delete(m.id),e.onPersistedSessionChanged(T)}}},handleTurnEnd:(m,w)=>A.handleTurnEnd(m,w),formatLaunchWorkdirLabel:m=>e.formatLaunchWorkdirLabel(m),notifySession:(m,w,T,F)=>e.notifySession(m,w,T,F)});return{registry:r,sessions:o,store:i,metrics:s,wakeDispatcher:a,interactions:l,notifications:f,worktrees:g,questions:h,lifecycle:A,restore:S,stateSync:u,references:d,worktreeStrategy:c,worktreeDecisions:I,runtimeBootstrap:R,worktreeMessages:y,maintenance:b}}get persisted(){return this.store.persisted}get idIndex(){return this.store.idIndex}get nameIndex(){return this.store.nameIndex}uniqueName(e){return this.registry.uniqueName(e)}syncRuntimeGcDeadline(e){this.maintenance.syncRuntimeGcDeadline(e)}onPersistedSessionChanged(e){e&&(this.syncPersistedSessionMaintenance(e),this.enforcePersistedRetention())}syncPersistedSessionMaintenance(e){this.maintenance.syncPersistedSessionMaintenance(e)}syncActionTokenExpiryDeadline(){this.maintenance.syncActionTokenExpiryDeadline()}syncTmpOutputCleanupDeadline(e=Date.now()){this.maintenance.syncTmpOutputCleanupDeadline(e)}enforcePersistedRetention(){this.maintenance.enforcePersistedRetention()}bootstrapMaintenanceSchedules(){this.maintenance.bootstrapMaintenanceSchedules()}disposeMaintenance(){this.maintenance.dispose()}spawn(e,t={}){if(this.registry.activeSessionCount()>=this.maxSessions)throw new Error(`Max sessions reached (${this.maxSessions}). Use agent_sessions to list active sessions and agent_kill to end one.`);let o,i,s=h=>{i=i?Promise.all([i,h]).then(()=>{}):h};if(e.resumeSessionId&&!e.forkSession){let h=this.registry.list().filter(b=>b.backendKind==="codex-app-server"&&(b.harnessSessionId===e.resumeSessionId||b.backendRef?.conversationId===e.resumeSessionId||!b.harnessSessionId&&!b.backendRef?.conversationId&&b.resumeSessionId===e.resumeSessionId)),v=h.find(b=>b.status==="starting"||b.status==="running");if(v)throw new Error(`Cannot resume backend thread ${e.resumeSessionId}: session ${v.id} still owns its active writer.`);for(let b of h)typeof b.waitForTeardown=="function"&&s(b.waitForTeardown())}if(e.sessionIdOverride){let h=this.getPersistedSession(e.sessionIdOverride);if(e.resumeSessionId&&h?.pendingPlanApproval){let b=an(h,e.permissionMode??_.permissionMode);e={...e,permissionMode:b.permissionMode,...b.patch},b.approvalApplied&&(o=h)}let v=this.registry.get(e.sessionIdOverride);if(v?.status==="starting"||v?.status==="running")throw new Error(`Cannot reuse session ID ${e.sessionIdOverride}: that session is still ${v.status}.`);v&&(typeof v.waitForTeardown=="function"&&s(v.waitForTeardown()),this.registry.remove(v.id,"session-id-override-replacement")),this.clearWaitingTimestampsForSession(e.sessionIdOverride),this.lastTurnCompleteMarkers.delete(e.sessionIdOverride),this.lastTerminalWakeMarkers.delete(e.sessionIdOverride),this.maintenance.cancelRuntimeGc(e.sessionIdOverride)}let a=e.name||Ri(e.prompt),l=this.uniqueName(a);l!==a&&`${a}${l}`;let d=this.checkRepoPolicyForLaunch(e.workdir,e.worktreeStrategy);if(!d.ok){let h=d;throw new Error(h.text)}e.repoIntegrationPolicy=d.resolution.policy,e.repoIntegrationPolicySource=d.resolution.source==="none"?void 0:d.resolution.source,e.repoProvider=d.resolution.provider;let u=this.restore.prepareSpawn(e,l);if(!e.route?.provider||!e.route.target)throw new Error(`Cannot launch session "${l}": missing explicit route metadata.`);let f=e.harness??"claude-code",g=this,S,y=f==="claude-code"&&!e.canUseTool?async(h,v)=>{if(!S)throw new Error("canUseTool called before session ID was set");return g.handleAskUserQuestion(S,v)}:e.canUseTool,c=new mn({...e,workdir:u.actualWorkdir,systemPrompt:u.effectiveSystemPrompt,canUseTool:y},l);S=c.id,o&&this.pendingPlanResumeClaims.set(c.id,o),this.registry.add(c),this.metrics.incrementLaunched();try{return this.runtimeBootstrap.initializeSession(c,u,e,{...t,startAfter:i})}catch(h){throw this.pendingPlanResumeClaims.delete(c.id),h}}async spawnAndAwaitRunning(e,t={}){let r=this.spawn(e,t);return await this.waitForRunningSession(r),r}async waitForRunningSession(e){if(e.status==="running")return;if(ll.has(e.status))throw new Error(this.describeLaunchFailure(e));let t=e.on?.bind(e),r=e.off?.bind(e)??e.removeListener?.bind(e);if(!t||!r)throw new Error(`Session ${e.name} [${e.id}] did not expose lifecycle events during startup.`);await new Promise((o,i)=>{let s=(l,d)=>{if(d==="running"){a(),o();return}ll.has(d)&&(a(),i(new Error(this.describeLaunchFailure(e))))},a=()=>{r("statusChange",s)};t("statusChange",s)})}describeLaunchFailure(e){let t=e.killReason?` (reason: ${e.killReason})`:"",r=e.error||e.result?.result||`status=${e.status}${t}`;return`Session ${e.name} [${e.id}] failed to start: ${r}`}formatLaunchResult(e,t){return Ht({prompt:e.prompt,workdir:e.workdir,harness:e.harness,permissionMode:e.permissionMode??_.permissionMode,planApproval:e.planApproval,resumeSessionId:e.resumeSessionId,resumeSessionName:e.resumeSessionName,forkSession:e.forkSession,forceNewSession:e.forceNewSession,clearedPersistedCodexResume:e.clearedPersistedCodexResume},t)}shouldRunWorktreeStrategy(e){let t=e.lifecycle;return!(t==="starting"||t==="awaiting_plan_decision"||t==="awaiting_user_input"||e.pendingPlanApproval)}resolveRepoPolicy(e){let t=lt(e);if(!t)return{source:"none",provider:"unsupported",prAvailable:!1};let r=this.store.getRepoPolicy(t.key);if(r)return{identity:t,policy:r.policy,source:"stored",provider:t.provider,prAvailable:t.provider==="github"&&Je(),record:r};let o=us(t);if(o){let i=no(t,o,"seeded");return{identity:t,policy:o,source:"seeded",provider:t.provider,prAvailable:ro({provider:t.provider}),record:i}}return{identity:t,source:"unknown",provider:t.provider,prAvailable:ro({provider:t.provider})}}checkRepoPolicyForLaunch(e,t){let r=t??_.defaultWorktreeStrategy??"off",o=this.resolveRepoPolicy(e);return r==="off"?{ok:!0,resolution:o}:o.source==="none"?{ok:!0,resolution:o}:o.source==="unknown"&&o.identity?{ok:!1,text:oo(o.identity,r,o.prAvailable)}:{ok:!0,resolution:o}}getRepoPolicyRecordForWorkdir(e){return this.resolveRepoPolicy(e).record}listRepoPolicies(){return this.store.listRepoPolicies()}cleanupRepoPolicies(){let e=[...this.store.cleanupRepoPolicies()],t=[];for(let r of this.store.listRepoPolicies()){let o=lt(r.repoRoot);!o||o.key===r.key||t.push(r.key)}return e.push(...this.store.removeRepoPolicies(t)),e.sort((r,o)=>r.repoRoot.localeCompare(o.repoRoot)||r.key.localeCompare(o.key))}setRepoPolicy(e,t){let r=lt(e);if(r)return this.store.setRepoPolicy(no(r,t,"stored"))}resetRepoPolicy(e){let t=lt(e);return t?this.store.resetRepoPolicy(t.key):!1}requestRepoPolicyForLaunch(e){let t=e.worktreeStrategy??_.defaultWorktreeStrategy??"off",r=this.resolveRepoPolicy(e.workdir);if(!r.identity)return`Error: ${e.workdir} is not a git repository.`;let o=oo(r.identity,t,r.prAvailable);if(!e.route?.provider||!e.route.target)return o;let i=`repo-policy:${r.identity.key}`,s=this.interactions.getRepoPolicyChoiceButtons({choiceId:i,route:e.route,repoRoot:r.identity.repoRoot,launchPrompt:e.prompt,launchWorkdir:e.workdir,launchName:e.name,launchModel:e.model,launchReasoningEffort:e.reasoningEffort,launchFastMode:e.fastMode,launchSystemPrompt:e.systemPrompt,launchAllowedTools:e.allowedTools,launchResumeSessionId:e.resumeSessionId,launchResumedFromSessionName:e.resumedFromSessionName,launchResumeWorktreeFrom:e.resumeWorktreeFrom,launchSessionIdOverride:e.sessionIdOverride,launchClearedPersistedCodexResume:e.clearedPersistedCodexResume,launchForkSession:e.forkSession,launchForceNewSession:e.forceNewSession,launchPermissionMode:e.permissionMode,launchPlanApproval:e.planApproval,launchHarness:e.harness,launchWorktreeStrategy:t,launchWorktreeBaseBranch:e.worktreeBaseBranch,launchWorktreePrTargetRepo:e.worktreePrTargetRepo,launchOriginAgentId:e.originAgentId,prAvailable:r.prAvailable}),a=ff(e,t);return this.notifications.dispatch(this.buildRoutingProxy({id:i,name:"repo-policy",route:e.route}),{label:"repo-policy-choice",idempotencyKey:`repo-policy-choice:${r.identity.key}:${t}:${a}`,userMessage:[o,"","After you choose a policy, OpenClaw Code Agent will continue this launch automatically."].join(`
|
|
220
220
|
`),notifyUser:"always",requireDirectUserNotification:!0,buttons:s,wakeMessageOnNotifySuccess:["Repo policy choice buttons delivered to the user.",`Repo: ${r.identity.repoRoot}`,"Wait for their policy choice; do not set the policy or relaunch separately."].join(`
|
|
221
221
|
`),wakeMessageOnNotifyFailed:o}),[`Repo policy choice prompt sent for ${r.identity.repoRoot}.`,r.prAvailable?"Wait for the user's Require PR, Merge or PR, No PR, or Manual response.":"Wait for the user's No PR or Manual response.","Do not send a separate plain-text policy question."].join(" ")}launchAfterRepoPolicyChoice(e){let t=e.route;if(!t?.provider||!t.target)throw new Error("missing route metadata for stored launch");let r=e.harness??Y(),o=e.permissionMode??_.permissionMode,i=e.planApproval??_.planApproval,s=this.spawn({prompt:e.prompt,workdir:e.workdir,sessionIdOverride:e.sessionIdOverride,name:e.name,model:e.model,reasoningEffort:e.reasoningEffort,fastMode:e.fastMode,systemPrompt:e.systemPrompt,allowedTools:e.allowedTools,resumeSessionId:e.resumeSessionId,resumedFromSessionName:e.resumedFromSessionName,resumeWorktreeFrom:e.resumeWorktreeFrom,forkSession:e.resumeSessionId?e.forkSession:!1,multiTurn:!0,permissionMode:o,planApproval:i,codexApprovalPolicy:r==="codex"?"never":void 0,originChannel:this.originChannelFromRoute(t),originThreadId:t.threadId,originAgentId:e.originAgentId,originSessionKey:t.sessionKey,route:t,harness:r,worktreeStrategy:e.worktreeStrategy,worktreeBaseBranch:e.worktreeBaseBranch,worktreePrTargetRepo:e.worktreePrTargetRepo});return{session:s,text:this.formatLaunchResult({prompt:e.prompt,workdir:e.workdir,harness:r,permissionMode:o,planApproval:i,forceNewSession:e.forceNewSession,resumeSessionId:e.resumeSessionId,resumeSessionName:e.resumedFromSessionName,forkSession:e.forkSession,clearedPersistedCodexResume:e.clearedPersistedCodexResume},s)}}continueLaunchAfterManualRepoPolicy(e,t){let r=this.resolveRepoPolicy(e);if(!r.identity)return{kind:"none"};let o=this.interactions.listActiveActionTokens("repo-policy-set").filter(u=>u.repoPolicyWorkdir===r.identity?.repoRoot),i=()=>{for(let u of new Set(o.map(f=>f.sessionId)))this.clearRepoPolicyChoiceTokens(u)},s=o.filter(u=>u.repoPolicy===t&&!!u.launchPrompt&&!!u.launchWorkdir&&!!u.route?.provider&&!!u.route?.target);if(s.length===0)return i(),{kind:"none"};let a=new Map;for(let u of s){let f=gf(u);a.has(f)||a.set(f,u)}if(a.size>1)return i(),{kind:"ambiguous",count:a.size};let l=[...a.values()][0];if(!l.launchPrompt||!l.launchWorkdir)return{kind:"none"};let d=this.launchAfterRepoPolicyChoice({route:l.route,prompt:l.launchPrompt,workdir:l.launchWorkdir,name:l.launchName,model:l.launchModel,reasoningEffort:l.launchReasoningEffort,fastMode:l.launchFastMode,systemPrompt:l.launchSystemPrompt,allowedTools:l.launchAllowedTools,resumeSessionId:l.launchResumeSessionId,resumedFromSessionName:l.launchResumedFromSessionName,resumeWorktreeFrom:l.launchResumeWorktreeFrom,sessionIdOverride:l.launchSessionIdOverride,clearedPersistedCodexResume:l.launchClearedPersistedCodexResume,forkSession:l.launchForkSession,forceNewSession:l.launchForceNewSession,permissionMode:l.launchPermissionMode,planApproval:l.launchPlanApproval,harness:l.launchHarness,worktreeStrategy:l.launchWorktreeStrategy,worktreeBaseBranch:l.launchWorktreeBaseBranch,worktreePrTargetRepo:l.launchWorktreePrTargetRepo,originAgentId:l.launchOriginAgentId});return this.consumeActionToken(l.id),this.clearRepoPolicyChoiceTokens(l.sessionId),{kind:"launched",...d}}makeActionButton(e,t,r,o={}){return this.interactions.makeActionButton(e,t,r,o)}makePluginActionButton(e,t,r,o={}){return this.makeActionButton(e,t,r,o)}consumeActionToken(e){return this.interactions.consumeActionToken(e)}getActionToken(e){return this.interactions.getActionToken(e)}clearRepoPolicyChoiceTokens(e){this.interactions.clearRepoPolicyChoiceTokens(e)}clearPlanDecisionTokens(e,t){this.interactions.clearPlanDecisionTokens(e,t)}isCurrentPendingPlanDecision(e,t){let r=this.resolve(e)??this.getPersistedSession(e);return vt(r,t)}dispatchPlanApprovalFallback(e,t,r){let o=new Date().toISOString();this.notifications.dispatch(e,{label:"plan-approval-fallback",idempotencyKey:`plan-approval:${e.id}:v${t??"unknown"}:fallback`,userMessages:gt({session:e,summary:r}),notifyUser:"always",shouldDispatch:()=>this.isCurrentPendingPlanDecision(e.id,t),hooks:{onNotifyStarted:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:t,approvalPromptVersion:t,approvalPromptStatus:"sending",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o})},onNotifySucceeded:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:t,approvalPromptVersion:t,approvalPromptStatus:"fallback_delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(e.id,{approvalPromptRequiredVersion:t,approvalPromptVersion:t,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"explicit_fallback_text",approvalPromptLastAttemptAt:o,approvalPromptFailedAt:new Date().toISOString()})}},wakeMessageOnNotifySuccess:He(e,t,!0),wakeMessageOnNotifyFailed:pr({session:e,planDecisionVersion:t}),failureWakeConfirmsNotificationDelivery:!1})}getWorktreeDecisionButtons(e,t={},r={merge:!0,pr:!0}){let o=this.resolve(e)??this.getPersistedSession(e);if(!(!o||o.worktreeStrategy==="delegate"&&t.allowDelegate!==!0))return this.interactions.getWorktreeDecisionButtons(e,o,r)}getPolicyAwareWorktreeDecisionButtons(e,t={},r,o){let i=r??this.resolve(e),s=o??this.getPersistedSession(e),a=this.resolveWorktreeRepoDir(i?.originalWorkdir??s?.workdir,i?.worktreePath??s?.worktreePath),l=a?this.resolveRepoPolicy(a):void 0,d=i?.repoIntegrationPolicy??s?.repoIntegrationPolicy,u=d??l?.policy,f=l?.prAvailable??!!(d&&d!=="never-pr"&&d!=="manual"),g=u?to({policy:u,prAvailable:f}):{merge:!0,pr:!0};return this.getWorktreeDecisionButtons(e,t,g)}getWorktreeCompletionState(e,t,r,o){return this.worktrees.getCompletionState(e,t,r,o)}notifyWorktreeOutcome(e,t,r){this.notifications.notifyWorktreeOutcome(e,t,r)}requestPlanApprovalFromUser(e,t){let r=t.trim();if(!r)return"Error: summary must not be empty.";let o=Io(r),i=this.resolve(e),s=i?void 0:this.getPersistedSession(e),a=i??s;if(!a)return`Error: Session "${e}" not found.`;if(!a.pendingPlanApproval)return`Error: Session "${e}" is not awaiting plan approval.`;let l=D(i??s??{id:e})??e;if(this.resolvePlanApprovalMode(a)!=="delegate")return`Error: Session "${e}" already uses direct user plan approval. Do not send a duplicate approval prompt.`;let d=a.actionablePlanDecisionVersion??a.planDecisionVersion;if(kt(a,d))return[`An actionable plan review prompt already exists for session ${a.name} [${l}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ");if(a.deliveryState==="notifying")return[`A plan approval prompt is already being delivered for session ${a.name} [${l}].`,"Wait for delivery to finish before retrying."].join(" ");let u=this.interactions.getPlanApprovalButtons(l,{...a,planDecisionVersion:d}),f=i?Lo(i,d):void 0,g=ft({sessionName:a.name,actionableVersion:d,preview:i?.getOutput().join(`
|
|
222
222
|
`)??"",artifact:f,escalationRationale:o,hasButtons:!0,heading:"needs your decision"}),S=g.userMessages.map((y,c,h)=>({text:y,buttons:c===h.length-1?u:void 0,requiredForSequenceSuccess:!0}));return this.notifications.dispatch(this.buildRoutingProxy({id:l,name:a.name,sessionId:s?.sessionId,harnessSessionId:i?.harnessSessionId??s?.harnessSessionId,backendRef:i?.backendRef??s?.backendRef,route:i?.route??s?.route}),{label:"plan-approval",idempotencyKey:`plan-approval:${l}:v${d??"unknown"}:canonical`,userMessage:S.length===1?S[0]?.text:void 0,userMessages:S.length>1?S:void 0,notifyUser:"always",buttons:S.length===1?u:void 0,hooks:{onNotifyStarted:()=>{this.updatePersistedSession(l,{approvalPromptRequiredVersion:d,approvalPromptStatus:"sending",approvalPromptVersion:d,approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptLastAttemptAt:new Date().toISOString()})},onNotifySucceeded:()=>{this.updatePersistedSession(l,{canonicalPlanPromptVersion:d,approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"delivered",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptDeliveredAt:new Date().toISOString(),approvalPromptFailedAt:void 0})},onNotifyFailed:()=>{this.updatePersistedSession(l,{approvalPromptRequiredVersion:d,approvalPromptVersion:d,approvalPromptStatus:"failed",approvalPromptTransport:"direct-message",approvalPromptMessageKind:"canonical_buttons",approvalPromptFailedAt:new Date().toISOString()})}},shouldDispatch:()=>this.isCurrentPendingPlanDecision(l,d),onUserNotifyFailed:()=>this.dispatchPlanApprovalFallback(this.buildRoutingProxy({id:l,name:a.name,sessionId:s?.sessionId,harnessSessionId:i?.harnessSessionId??s?.harnessSessionId,backendRef:i?.backendRef??s?.backendRef,route:i?.route??s?.route}),d,g.reviewSummary),wakeMessageOnNotifySuccess:He({id:l,name:a.name},d)}),[`Canonical plan approval prompt sent for session ${a.name} [${l}].`,"Wait for the user's Approve, Revise, or Reject response.","Do not send a separate plain-text approval message."].join(" ")}requestWorktreeDecisionFromUser(e,t){let r=t.trim();if(!r)return"Error: summary must not be empty.";let o=this.resolve(e),i=this.getPersistedSession(e),s=o??i;if(!s)return`Error: Session "${e}" not found.`;if(s.worktreeStrategy!=="delegate")return`Error: Session "${e}" already uses direct user worktree decisions. Do not send a duplicate decision prompt.`;if(!(!!("pendingWorktreeDecisionSince"in s?s.pendingWorktreeDecisionSince:void 0)||s.worktreeState==="pending_decision"||s.worktreeLifecycle?.state==="pending_decision"))return`Error: Session "${e}" is not awaiting a delegated worktree decision.`;let d=D(o??i??{id:e})??e,u=o?.worktreePath??i?.worktreePath,f=o?.worktreeBranch??i?.worktreeBranch,g=this.resolveWorktreeRepoDir(o?.originalWorkdir??i?.workdir,u);if(!u)return`Error: Session "${e}" has no managed worktree path.`;if(!f)return`Error: Session "${e}" has no managed worktree branch.`;if(!g)return`Error: Session "${e}" has no resolvable repository root for worktree ${u}.`;let S=o?.worktreeBaseBranch??i?.worktreeBaseBranch??Ee(g),y=Ne(g,f,S);if(!y)return`Error: Could not compute worktree diff summary for session "${e}".`;let c=this.getPolicyAwareWorktreeDecisionButtons(d,{allowDelegate:!0},o,i);if(!c||c.length===0)return`Error: Could not create worktree decision buttons for session "${e}".`;let h=r.split(/\r?\n/).map(v=>v.replace(/^[-*]\s+/,"").trim()).filter(v=>v.length>0);return this.notifications.dispatch(this.buildRoutingProxy({id:d,name:s.name,sessionId:i?.sessionId,harnessSessionId:o?.harnessSessionId??i?.harnessSessionId,backendRef:o?.backendRef??i?.backendRef,route:o?.route??i?.route}),this.worktreeMessages.buildAskNotification({session:{id:d,name:s.name,worktreePrTargetRepo:o?.worktreePrTargetRepo??i?.worktreePrTargetRepo},branchName:f,baseBranch:S,diffSummary:y,summaryLines:h,buttons:c})),[`Canonical worktree decision prompt sent for session ${s.name} [${d}].`,"Wait for the user's Merge, Open PR, Later, or Discard response.","Do not send a separate plain-text worktree decision message."].join(" ")}buildRoutingProxy(e){return{id:D(e)??C(e)??e.harnessSessionId??"unknown-session",name:e.name,harnessSessionId:e.harnessSessionId,backendRef:e.backendRef?{...e.backendRef}:void 0,route:e.route}}resolveWorktreeRepoDir(e,t){return e&&(!t||!Wn(e,t))||!t?e:Ct(t)??e}formatLaunchWorkdirLabel(e){if(!e.worktreePath)return e.workdir;let t=this.resolveWorktreeRepoDir(e.originalWorkdir,e.worktreePath);return!t||t===e.worktreePath?e.worktreePath:`${e.worktreePath} (worktree of ${t})`}async dismissWorktree(e){return this.worktreeDecisions.dismissWorktree(e)}snoozeWorktreeDecision(e,t){return this.worktreeDecisions.snoozeWorktreeDecision(e,t)}async handleWorktreeStrategy(e){return this.worktreeStrategy.handleWorktreeStrategy(e)}async onSessionTerminal(e){if(e.autoMergeParentSessionId){await this.handleAutoMergeResolverTerminal(e);return}return this.lifecycle.handleSessionTerminal(e)}async handleAutoMergeResolverTerminal(e){this.persistSession(e),this.clearWaitingTimestampsForSession(e.id),this.wakeDispatcher.clearRetryTimersForSession(e.id);let t=e.autoMergeParentSessionId;if(!t)return;let r=this.resolve(t),o=this.getPersistedSession(t),i=r??(o?this.buildRoutingProxy({id:o.sessionId,name:o.name,sessionId:o.sessionId,harnessSessionId:o.harnessSessionId,backendRef:o.backendRef,route:o.route}):void 0);if(!i){`${e.id}${t}`;return}if(e.status==="completed"&&r){this.updatePersistedSession(t,{autoMergeResolverSessionId:void 0}),await this.handleWorktreeStrategy(r);return}let s=r?.worktreeBranch??o?.worktreeBranch??"unknown",a=r?.worktreePath??o?.worktreePath??"(unknown worktree)",l=r?.worktreeBaseBranch??o?.worktreeBaseBranch,d=r?.worktreePrTargetRepo??o?.worktreePrTargetRepo,u=r?.worktreePushRemote??o?.worktreePushRemote;this.updatePersistedSession(t,Ot({worktreeBaseBranch:l,worktreePrTargetRepo:d,worktreePushRemote:u},{clearResolverSessionId:!0,notes:[e.status==="completed"?"auto_merge_conflict_resolver_completed_without_retry_target":"auto_merge_conflict_resolver_failed"]})),this.dispatchSessionNotification(i,{label:"worktree-merge-conflict-resolver-failed",idempotencyKey:`worktree-merge-conflict-resolver-failed:${t}:${e.id}`,userMessage:[`β οΈ [${i.name}] Auto-merge conflict resolution did not complete successfully.`,`Branch \`${s}\` was preserved for manual follow-up in ${a}.`,e.status==="completed"?"The resolver finished, but the original session could not be resumed for the merge retry.":`Resolver session ${e.name} ended with status=${e.status}.`].join(`
|
|
223
223
|
`),buttons:this.getPolicyAwareWorktreeDecisionButtons(t,{allowDelegate:!0},r,o)})}persistSession(e,t={}){let r=t.scheduleRuntimeGc??!0;this.store.hasRecordedSession(e.id)||this.metrics.recordSession(e),this.store.persistTerminal(e),r&&this.syncRuntimeGcDeadline(e),this.onPersistedSessionChanged(this.store.getPersistedSession(e.id)),this.syncTmpOutputCleanupDeadline()}reconcilePersistedTaskFlowMirrors(){let e=!1;for(let t of this.store.listPersistedSessions()){let r=Mi(t);r&&(t.taskFlowMirror=r,e=!0)}e&&this.store.saveIndex()}getMetrics(){return this.metrics.getMetrics()}notifySession(e,t,r="notification",o){this.dispatchSessionNotification(e,{label:r,idempotencyKey:r==="agent-respond"?void 0:o??`notify:${e.id}:${r}:${t}`,userMessage:t,notifyUser:"always"})}notifyResumedLaunch(e){if(!e.resumeSessionId)return;let t=this.formatLaunchWorkdirLabel(e),r=ge({harness:e.harnessName,model:e.model})??"default";this.notifySession(e,Qt({sessionName:e.name,resumedFromSessionName:e.resumedFromSessionName,workdirLabel:t,harnessLabel:r}),"resumed-launch",`resumed-launch:${e.id}:${e.startedAt}:${e.resumeSessionId}`)}sendPlanOffer(e){let t=this.interactions.getPlanOfferButtons({offerId:e.offerId,route:e.route,planName:e.planName,planPrompt:e.planPrompt,planWorkdir:e.planWorkdir,planWorktreeStrategy:e.planWorktreeStrategy});this.dispatchSessionNotification(this.buildRoutingProxy({id:e.offerId,route:e.route}),{label:"plan-offer",idempotencyKey:`plan-offer:${e.offerId}`,userMessage:e.text,notifyUser:"always",buttons:t})}emitGoalTaskUpdate(e,t,r="goal-task"){let o=e.sessionId??e.id,i=this.buildRoutingProxy({id:o,name:e.sessionName??e.name,route:e.route});i.originChannel=e.originChannel,i.originThreadId=e.originThreadId,i.originSessionKey=e.originSessionKey;let s=r==="goal-task-succeeded",a=[`β
[${e.name}] Goal task succeeded`,e.sessionId?`Session: ${e.sessionName??e.name} [${e.sessionId}]`:void 0].filter(d=>!!d).join(`
|
|
224
|
-
`),l=d=>So({sessionId:o,sessionName:e.sessionName,taskName:e.name,summary:t,originThreadLine:Ye(i),canonicalStatusDelivered:d});this.dispatchSessionNotification(i,{label:r,idempotencyKey:`goal:${e.id}:${r}:${s?"success":t}`,userMessage:s?a:t,notifyUser:"always",completionSummary:s?{required:!0,producer:"goal",outcomeKey:`goal:${e.id}`}:void 0,completionWakeSummaryRequired:s,completionWakeOutcomeKey:s?`goal:${e.id}`:void 0,wakeMessageOnNotifySuccess:s?l(!0):void 0,wakeMessageOnNotifyFailed:s?l(!1):void 0})}launchPlanOffer(e){let t=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:Y(),permissionMode:"plan",planApproval:"ask",worktreeStrategy:e.worktreeStrategy??"off",multiTurn:!0,route:t,originChannel:this.originChannelFromRoute(t),originThreadId:t.threadId,originSessionKey:t.sessionKey})}dispatchSessionNotification(e,t){this.notifications.dispatch(e,t)}originChannelFromRoute(e){return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}debounceWaitingEvent(e,t){let r=Date.now(),o=t?`${e}:${t}`:e,i=this.lastWaitingEventTimestamps.get(o);return i&&r-i<mf?!1:(this.lastWaitingEventTimestamps.set(o,r),!0)}clearWaitingTimestampsForSession(e){this.lastWaitingEventTimestamps.delete(e);let t=`${e}:`;for(let r of this.lastWaitingEventTimestamps.keys())r.startsWith(t)&&this.lastWaitingEventTimestamps.delete(r)}originThreadLine(e){return Ye(e)}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,t=1e3){return ol(e,t)}resolvePlanApprovalMode(e){return e.planApproval??_.planApproval??"delegate"}shouldEmitTurnCompleteWake(e){let t=`${e.startedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}`;return this.lastTurnCompleteMarkers.get(e.id)===t?(`${e.id}${t}`,!1):(this.lastTurnCompleteMarkers.set(e.id,t),!0)}shouldEmitTerminalWake(e){let t=`${e.status}|${e.startedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.killReason}`;return this.lastTerminalWakeMarkers.get(e.id)===t?!1:(this.lastTerminalWakeMarkers.set(e.id,t),!0)}resolve(e){return this.references.resolveActive(e)}get(e){return this.registry.get(e)}list(e){let t=this.registry.list();return e&&e!=="all"&&(t=t.filter(r=>r.status===e)),t.sort((r,o)=>o.startedAt-r.startedAt)}kill(e,t){let r=this.registry.get(e);if(!r)return!1;if(r.pendingPlanApproval){this.clearPlanDecisionTokens(r.id);let o={lifecycle:"terminal",runtimeState:"stopped",pendingPlanApproval:!1,planApprovalContext:void 0,approvalState:r.approvalState==="pending"?"rejected":r.approvalState,planDecisionVersion:(r.planDecisionVersion??0)+1,actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0};r.applyControlPatch(o),Object.assign(r,o),this.updatePersistedSession(r.id,o)}return r.kill(t??"user"),!0}killAll(e="user"){for(let t of this.sessions.values())pf.has(t.status)&&this.kill(t.id,e)}resolveBackendConversationId(e){return this.references.resolveBackendConversationId(e)}resolveHarnessSessionId(e){return this.resolveBackendConversationId(e)}getPersistedSession(e){return this.references.getPersistedSession(e)}isAlreadyMerged(e){if(!e)return!1;let t=this.store.getPersistedSession(e);return t?.worktreeMerged===!0||t?.worktreeLifecycle?.state==="merged"||t?.worktreeLifecycle?.state==="released"}async enqueueMerge(e,t,r){return this.mergeQueue.enqueue(e,t,r)}updatePersistedSession(e,t){let r=this.stateSync.applySessionPatch(e,t);return r&&this.onPersistedSessionChanged(this.store.getPersistedSession(e)),r}listPersistedSessions(){return this.store.listPersistedSessions()}async handleAskUserQuestion(e,t){let r=this.sessions.get(e);if(!r)throw new Error(`Session "${e}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(r,t)}resolveAskUserQuestion(e,t,r={}){return this.questions.resolveAskUserQuestion(e,t,r)}async resolvePendingInputOption(e,t,r={}){let o=this.sessions.get(e);return o?.canSubmitPendingInputOption?.()?await o.submitPendingInputOption(t,r)?(this.clearWaitingTimestampsForSession(e),!0):!1:this.questions.resolveAskUserQuestion(e,t,r)}canSubmitPendingInputOption(e){return this.sessions.get(e)?.canSubmitPendingInputOption?.()===!0}pendingInputSubmissionRequiresMore(e){return this.sessions.get(e)?.pendingInputSubmissionRequiresMore()===!0}consumeQuestionAnswerTokens(e,t,r){return this.interactions.consumeQuestionAnswerTokens(e,t,r)}consumePlanDecisionTokens(e,t){return this.interactions.consumePlanDecisionTokens(e,t)}dispose(){this.disposeMaintenance(),this.questions.dispose(),this.notifications.dispose()}};import{definePluginEntry as ul}from"openclaw/plugin-sdk/plugin-entry";function vf(n){let e=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,t=e*60*60*1e3,r=Date.now()-t,o=new Set(n.listPersistedSessions().map(l=>l.worktreePath).filter(l=>typeof l=="string"&&l.length>0)),i=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??_.worktreeDir;if(s)i.add(s);else for(let l of n.listPersistedSessions())
|
|
224
|
+
`),l=d=>So({sessionId:o,sessionName:e.sessionName,taskName:e.name,summary:t,originThreadLine:Ye(i),canonicalStatusDelivered:d});this.dispatchSessionNotification(i,{label:r,idempotencyKey:`goal:${e.id}:${r}:${s?"success":t}`,userMessage:s?a:t,notifyUser:"always",completionSummary:s?{required:!0,producer:"goal",outcomeKey:`goal:${e.id}`}:void 0,completionWakeSummaryRequired:s,completionWakeOutcomeKey:s?`goal:${e.id}`:void 0,wakeMessageOnNotifySuccess:s?l(!0):void 0,wakeMessageOnNotifyFailed:s?l(!1):void 0})}launchPlanOffer(e){let t=e.route??{provider:"system",target:"system"};return this.spawn({prompt:e.prompt,workdir:e.workdir,name:e.name,harness:Y(),permissionMode:"plan",planApproval:"ask",worktreeStrategy:e.worktreeStrategy??"off",multiTurn:!0,route:t,originChannel:this.originChannelFromRoute(t),originThreadId:t.threadId,originSessionKey:t.sessionKey})}dispatchSessionNotification(e,t){this.notifications.dispatch(e,t)}originChannelFromRoute(e){return e.accountId?`${e.provider}|${e.accountId}|${e.target}`:`${e.provider}|${e.target}`}debounceWaitingEvent(e,t){let r=Date.now(),o=t?`${e}:${t}`:e,i=this.lastWaitingEventTimestamps.get(o);return i&&r-i<mf?!1:(this.lastWaitingEventTimestamps.set(o,r),!0)}clearWaitingTimestampsForSession(e){this.lastWaitingEventTimestamps.delete(e);let t=`${e}:`;for(let r of this.lastWaitingEventTimestamps.keys())r.startsWith(t)&&this.lastWaitingEventTimestamps.delete(r)}originThreadLine(e){return Ye(e)}extractLastOutputLine(e){return e.getOutput(3).filter(o=>o.trim()).pop()?.trim()||void 0}getOutputPreview(e,t=1e3){return ol(e,t)}resolvePlanApprovalMode(e){return e.planApproval??_.planApproval??"delegate"}shouldEmitTurnCompleteWake(e){let t=`${e.startedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}`;return this.lastTurnCompleteMarkers.get(e.id)===t?(`${e.id}${t}`,!1):(this.lastTurnCompleteMarkers.set(e.id,t),!0)}shouldEmitTerminalWake(e){let t=`${e.status}|${e.startedAt??0}|${e.result?.session_id??""}|${e.result?.num_turns??0}|${e.killReason}`;return this.lastTerminalWakeMarkers.get(e.id)===t?!1:(this.lastTerminalWakeMarkers.set(e.id,t),!0)}resolve(e){return this.references.resolveActive(e)}get(e){return this.registry.get(e)}list(e){let t=this.registry.list();return e&&e!=="all"&&(t=t.filter(r=>r.status===e)),t.sort((r,o)=>o.startedAt-r.startedAt)}kill(e,t){let r=this.registry.get(e);if(!r)return!1;if(r.pendingPlanApproval){this.clearPlanDecisionTokens(r.id);let o={lifecycle:"terminal",runtimeState:"stopped",pendingPlanApproval:!1,planApprovalContext:void 0,approvalState:r.approvalState==="pending"?"rejected":r.approvalState,planDecisionVersion:(r.planDecisionVersion??0)+1,actionablePlanDecisionVersion:void 0,canonicalPlanPromptVersion:void 0,approvalPromptRequiredVersion:void 0,approvalPromptVersion:void 0,approvalPromptStatus:"not_sent",approvalPromptTransport:"none",approvalPromptMessageKind:"none",approvalPromptLastAttemptAt:void 0,approvalPromptDeliveredAt:void 0,approvalPromptFailedAt:void 0};r.applyControlPatch(o),Object.assign(r,o),this.updatePersistedSession(r.id,o)}return r.kill(t??"user"),!0}killAll(e="user"){for(let t of this.sessions.values())pf.has(t.status)&&this.kill(t.id,e)}resolveBackendConversationId(e){return this.references.resolveBackendConversationId(e)}resolveHarnessSessionId(e){return this.resolveBackendConversationId(e)}getPersistedSession(e){return this.references.getPersistedSession(e)}isAlreadyMerged(e){if(!e)return!1;let t=this.store.getPersistedSession(e);return t?.worktreeMerged===!0||t?.worktreeLifecycle?.state==="merged"||t?.worktreeLifecycle?.state==="released"}async enqueueMerge(e,t,r){return this.mergeQueue.enqueue(e,t,r)}updatePersistedSession(e,t){let r=this.stateSync.applySessionPatch(e,t);return r&&this.onPersistedSessionChanged(this.store.getPersistedSession(e)),r}listPersistedSessions(){return this.store.listPersistedSessions()}async handleAskUserQuestion(e,t){let r=this.sessions.get(e);if(!r)throw new Error(`Session "${e}" not found for AskUserQuestion intercept`);return this.questions.handleAskUserQuestion(r,t)}resolveAskUserQuestion(e,t,r={}){return this.questions.resolveAskUserQuestion(e,t,r)}async resolvePendingInputOption(e,t,r={}){let o=this.sessions.get(e);return o?.canSubmitPendingInputOption?.()?await o.submitPendingInputOption(t,r)?(this.clearWaitingTimestampsForSession(e),!0):!1:this.questions.resolveAskUserQuestion(e,t,r)}canSubmitPendingInputOption(e){return this.sessions.get(e)?.canSubmitPendingInputOption?.()===!0}pendingInputSubmissionRequiresMore(e){return this.sessions.get(e)?.pendingInputSubmissionRequiresMore()===!0}consumeQuestionAnswerTokens(e,t,r){return this.interactions.consumeQuestionAnswerTokens(e,t,r)}consumePlanDecisionTokens(e,t){return this.interactions.consumePlanDecisionTokens(e,t)}dispose(){this.disposeMaintenance(),this.questions.dispose(),this.notifications.dispose()}};import{definePluginEntry as ul}from"openclaw/plugin-sdk/plugin-entry";function vf(n){return[...new Set(n.map(e=>e.workdir).filter(e=>typeof e=="string"&&e.length>0))]}function Pf(n){let e=parseInt(process.env.OPENCLAW_WORKTREE_CLEANUP_AGE_HOURS??"168",10)||168,t=e*60*60*1e3,r=Date.now()-t,o=new Set(n.listPersistedSessions().map(l=>l.worktreePath).filter(l=>typeof l=="string"&&l.length>0)),i=new Set,s=process.env.OPENCLAW_WORKTREE_DIR??_.worktreeDir;if(s)i.add(s);else for(let l of vf(n.listPersistedSessions()))try{let d=kf("git",["rev-parse","--show-toplevel"],{cwd:l,timeout:5e3,encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim();d&&i.add(Bo(d,".worktrees"))}catch{}if(i.size===0)return;let a=0;for(let l of i)try{let d=hf(l);for(let u of d){if(!u.startsWith("openclaw-worktree-"))continue;let f=Bo(l,u);try{let g=yf(f);if(!g.isDirectory()||g.mtimeMs>r||o.has(f))continue;Sf(f,{recursive:!0,force:!0}),a++}catch(g){`${f}${g instanceof Error?g.message:String(g)}`}}}catch{}a>0&&`${a}${e}`}function wf(n){if(!n||typeof n!="object")return;let e=n,t=e.channel?.trim().toLowerCase();if(!t)return;let r=t==="telegram"?e.callback?.chatId??e.parentConversationId??e.conversationId:e.parentConversationId??e.conversationId??e.callback?.chatId;if(r)return ue(e.accountId?`${t}|${e.accountId}|${r}`:`${t}|${r}`,e.threadId,e.sessionKey)}function bf(n){let e=null,t=null,r=null,o=!1,i=!1,s=n.registerTool;Te(n.runtime);let a=()=>Bo(Qn(process.env),"plugin-state","openclaw-code-agent"),l=c=>{let h=c.deliveryContext;return h?.channel&&h.to?ue(h.accountId?`${h.channel}|${h.accountId}|${h.to}`:`${h.channel}|${h.to}`,h.threadId,c.sessionKey):ue(c.messageChannel,void 0,c.sessionKey)},d=c=>{r?.maybeCheckForUpdate({route:c})},u=c=>{if(o){c&&!i&&(Te(n.runtime,c.config),i=!0);return}let h=n.pluginConfig??{};Uo(h),c?(Te(n.runtime,c.config),i=!0):(Te(n.runtime),i=!1),e=new Pr(_.maxSessions,_.maxPersistedSessions,{worktreeSummaryProvider:va()}),t=new On(e),r=new zt({stateDir:c?.stateDir??a(),currentVersion:n.version??oi.version??"0.0.0",actionButtonFactory:(v,b,A,I)=>e.makePluginActionButton(v,b,A,I)}),br(e),Rr(t),Ar(r),t.start(),Pf(e),e.bootstrapMaintenanceSchedules(),o=!0,d()},f=()=>{t&&t.stop(),e&&e.killAll("shutdown"),e&&e.dispose(),t=null,e=null,r=null,o=!1,i=!1,Te(void 0),Rr(null),br(null),Ar(null)},g=(c,h)=>{s(v=>{let b=c(v);return{...b,execute(A,I){return u(),d(l(v)),b.execute(A,I)}}},h)},S={...n,registerCommand(c){n.registerCommand({...c,handler:h=>(u(),d(l(h)),c.handler(h))})}},y=c=>{let h=Is(c);n.registerInteractiveHandler({...h,handler:async v=>(u(),d(wf(v)),h.handler(v))})};g(c=>$i(c),{optional:!1,name:"agent_launch"}),g(c=>Hi(c),{optional:!1,name:"agent_sessions"}),g(c=>Qi(c),{optional:!1,name:"agent_kill"}),g(c=>Sn(c),{optional:!1,name:"agent_output"}),g(c=>ts(c),{optional:!1,name:"agent_respond"}),g(c=>ns(c),{optional:!1,name:"agent_request_plan_approval"}),g(c=>rs(c),{optional:!1,name:"agent_request_worktree_decision"}),g(c=>ss(c),{optional:!1,name:"agent_send_plan_offer"}),g(c=>as(c),{optional:!1,name:"agent_stats"}),g(c=>ps(c),{optional:!1,name:"agent_repo_policy"}),g(c=>wn(c),{optional:!1,name:"agent_merge"}),g(c=>Vt(c),{optional:!1,name:"agent_pr"}),g(c=>ms(c),{optional:!1,name:"agent_worktree_cleanup"}),g(c=>fs(c),{optional:!1,name:"agent_worktree_status"}),g(c=>gs(c),{optional:!1,name:"agent_goal_launch"}),g(c=>ys(c),{optional:!1,name:"agent_goal_status"}),g(c=>Ss(c),{optional:!1,name:"agent_goal_stop"}),g(c=>ks(c),{optional:!1,name:"agent_goal_edit"}),y("telegram"),y("discord"),xs(S),Cs(S),Ms(S),_s(S),Ds(S),$s(S),Es(S),Os(S),Ws(S),Fs(S),Bs(S),n.registerService({id:"openclaw-code-agent",start:u,stop:f})}var mb=ul({id:"openclaw-code-agent",name:"Code Agent",description:"Multi-session coding-agent orchestration from OpenClaw chat",register:bf});export{mb as default,bf as register,wf as routeFromInteractiveContext,vf as uniquePersistedWorkdirs};
|